text:
.. _NEP29:

==================================================================================
NEP 29 — Recommend Python and NumPy version support as a community policy standard
==================================================================================

:Author: Thomas A Caswell <tcaswell@gmail.com>, Andreas Mueller, Brian Granger, Madicken Munk, Ralf Gommers, Matt Haberland <mhaberla@calpoly.edu>, Matthias Bussonnier <bussonniermatthias@gmail.com>, Stefan van der Walt <stefanv@berkeley.edu>
:Status: Final
:Type: Informational
:Created: 2019-07-13
:Resolution: https://mail.python.org/pipermail/numpy-discussion/2019-October/080128.html

Abstract
--------

This NEP recommends that all projects across the Scientific
Python ecosystem adopt a common "time window-based" policy for
support of Python and NumPy versions. Standardizing a recommendation
for project support of minimum Python and NumPy versions will improve
downstream project planning.

This is an unusual NEP in that it offers recommendations for
community-wide policy and not for changes to NumPy itself.  Since a
common place for SPEEPs (Scientific Python Ecosystem Enhancement
Proposals) does not exist and given NumPy's central role in the
ecosystem, a NEP provides a visible place to document the proposed
policy.

This NEP is being put forward by maintainers of Matplotlib, scikit-learn,
IPython, Jupyter, yt, SciPy, NumPy, and scikit-image.

Detailed description
--------------------

For the purposes of this NEP we assume semantic versioning and define:

*major version*
   A release that changes the first number (e.g. X.0.0)

*minor version*
   A release that changes the second number (e.g 1.Y.0)

*patch version*
   A release that changes the third number (e.g. 1.1.Z)

When a project releases a new major or minor version, we recommend that
they support at least all minor versions of Python
introduced and released in the prior 42 months *from the
anticipated release date* with a minimum of 2 minor versions of
Python, and all minor versions of NumPy released in the prior 24
months *from the anticipated release date* with a minimum of 3
minor versions of NumPy.

Consider the following timeline::

       Jan 16      Jan 17      Jan 18      Jan 19      Jan 20
       |           |           |           |           |
  +++++|+++++++++++|+++++++++++|+++++++++++|+++++++++++|++++++++++++
   |              |                  |               |
   py 3.5.0       py 3.6.0           py 3.7.0        py 3.8.0
  |-----------------------------------------> Feb19
            |-----------------------------------------> Dec19
                      |-----------------------------------------> Nov20

It shows the 42 month support windows for Python.  A project with a
major or minor version release in February 2019 should support Python 3.5 and newer,
a project with a major or minor version released in December 2019 should
support Python 3.6 and newer, and a project with a major or minor version
release in November 2020 should support Python 3.7 and newer.

The current Python release cadence is 18 months so a 42 month window
ensures that there will always be at least two minor versions of Python
in the window.  The window is extended 6 months beyond the anticipated two-release
interval for Python to provide resilience against small fluctuations /
delays in its release schedule.

Because Python minor version support is based only on historical
release dates, a 42 month time window, and a planned project release
date, one can predict with high confidence when a project will be able
to drop any given minor version of Python.  This, in turn, could save
months of unnecessary maintenance burden.

If a project releases immediately after a minor version of Python
drops out of the support window, there will inevitably be some
mismatch in supported versions—but this situation should only last
until other projects in the ecosystem make releases.

Otherwise, once a project does a minor or major release, it is
guaranteed that there will be a stable release of all other projects
that, at the source level, support the same set of Python versions
supported by the new release.

If there is a Python 4 or a NumPy 2 this policy will have to be
reviewed in light of the community's and projects' best interests.

Support Table
~~~~~~~~~~~~~

============ ====== =====
Date         Python NumPy
------------ ------ -----
Jan 07, 2020 3.6+   1.15+
Jun 23, 2020 3.7+   1.15+
Jul 23, 2020 3.7+   1.16+
Jan 13, 2021 3.7+   1.17+
Jul 26, 2021 3.7+   1.18+
Dec 22, 2021 3.7+   1.19+
Dec 26, 2021 3.8+   1.19+
Jun 21, 2022 3.8+   1.20+
Jan 31, 2023 3.8+   1.21+
Apr 14, 2023 3.9+   1.21+
Jun 23, 2023 3.9+   1.22+
Jan 01, 2024 3.9+   1.23+
Apr 05, 2024 3.10+  1.23+
Apr 04, 2025 3.11+  1.23+
============ ====== =====

Drop Schedule
~~~~~~~~~~~~~

::

  On next release, drop support for Python 3.5 (initially released on Sep 13, 2015)
  On Jan 07, 2020 drop support for NumPy 1.14 (initially released on Jan 06, 2018)
  On Jun 23, 2020 drop support for Python 3.6 (initially released on Dec 23, 2016)
  On Jul 23, 2020 drop support for NumPy 1.15 (initially released on Jul 23, 2018)
  On Jan 13, 2021 drop support for NumPy 1.16 (initially released on Jan 13, 2019)
  On Jul 26, 2021 drop support for NumPy 1.17 (initially released on Jul 26, 2019)
  On Dec 22, 2021 drop support for NumPy 1.18 (initially released on Dec 22, 2019)
  On Dec 26, 2021 drop support for Python 3.7 (initially released on Jun 27, 2018)
  On Jun 21, 2022 drop support for NumPy 1.19 (initially released on Jun 20, 2020)
  On Jan 31, 2023 drop support for NumPy 1.20 (initially released on Jan 31, 2021)
  On Apr 14, 2023 drop support for Python 3.8 (initially released on Oct 14, 2019)
  On Jun 23, 2023 drop support for NumPy 1.21 (initially released on Jun 22, 2021)
  On Jan 01, 2024 drop support for NumPy 1.22 (initially released on Dec 31, 2021)
  On Apr 05, 2024 drop support for Python 3.9 (initially released on Oct 05, 2020)
  On Apr 04, 2025 drop support for Python 3.10 (initially released on Oct 04, 2021)

Implementation
--------------

We suggest that all projects adopt the following language into their
development guidelines:

   This project supports:

   - All minor versions of Python released 42 months prior to the
     project, and at minimum the two latest minor versions.
   - All minor versions of ``numpy`` released in the 24 months prior
     to the project, and at minimum the last three minor versions.

   In ``setup.py``, the ``python_requires`` variable should be set to
   the minimum supported version of Python.  All supported minor
   versions of Python should be in the test matrix and have binary
   artifacts built for the release.

   Minimum Python and NumPy version support should be adjusted upward
   on every major and minor release, but never on a patch release.

Backward compatibility
----------------------

No backward compatibility issues.

Alternatives
------------

Ad-Hoc version support
~~~~~~~~~~~~~~~~~~~~~~

A project could, on every release, evaluate whether to increase
the minimum version of Python supported.
As a major downside, an ad-hoc approach makes it hard for downstream users to predict what
the future minimum versions will be.  As there is no objective threshold
to when the minimum version should be dropped, it is easy for these
version support discussions to devolve into `bike shedding <https://en.wikipedia.org/wiki/Wikipedia:Avoid_Parkinson%27s_bicycle-shed_effect>`_ and acrimony.

All CPython supported versions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The CPython supported versions of Python are listed in the Python
Developers Guide and the Python PEPs. Supporting these is a very clear
and conservative approach.  However, it means that there exists a four
year lag between when a new features is introduced into the language
and when a project is able to use it.  Additionally, for projects with
compiled extensions this requires building many binary artifacts for
each release.

For the case of NumPy, many projects carry workarounds to bugs that
are fixed in subsequent versions of NumPy.  Being proactive about
increasing the minimum version of NumPy allows downstream
packages to carry fewer version-specific patches.

Default version on Linux distribution
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The policy could be to support the version of Python that ships by
default in the latest Ubuntu LTS or CentOS/RHEL release.  However, we
would still have to standardize across the community which
distribution to follow.

By following the versions supported by major Linux distributions, we
are giving up technical control of our projects to external
organizations that may have different motivations and concerns than we
do.

N minor versions of Python
~~~~~~~~~~~~~~~~~~~~~~~~~~

Given the current release cadence of the Python, the proposed time (42
months) is roughly equivalent to "the last two" Python minor versions.
However, if Python changes their release cadence substantially, any
rule based solely on the number of minor releases may need to be
changed to remain sensible.

A more fundamental problem with a policy based on number of Python
releases is that it is hard to predict when support for a given minor
version of Python will be dropped as that requires correctly
predicting the release schedule of Python for the next 3-4 years.  A
time-based rule, in contrast, only depends on past events
and the length of the support window.

Time window from the X.Y.1 Python release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is equivalent to a few month longer support window from the X.Y.0
release.  This is because X.Y.1 bug-fix release is typically a few
months after the X.Y.0 release, thus a N month window from X.Y.1 is
roughly equivalent to a N+3 month from X.Y.0.

The X.Y.0 release is naturally a special release.  If we were to
anchor the window on X.Y.1 we would then have the discussion of why
not X.Y.M?

Discussion
----------

References and Footnotes
------------------------

Code to generate support and drop schedule tables ::

  from datetime import datetime, timedelta

  data = """Jan 15, 2017: NumPy 1.12
  Sep 13, 2015: Python 3.5
  Dec 23, 2016: Python 3.6
  Jun 27, 2018: Python 3.7
  Jun 07, 2017: NumPy 1.13
  Jan 06, 2018: NumPy 1.14
  Jul 23, 2018: NumPy 1.15
  Jan 13, 2019: NumPy 1.16
  Jul 26, 2019: NumPy 1.17
  Oct 14, 2019: Python 3.8
  Dec 22, 2019: NumPy 1.18
  Jun 20, 2020: NumPy 1.19
  Oct 05, 2020: Python 3.9
  Jan 30, 2021: NumPy 1.20
  Jun 22, 2021: NumPy 1.21
  Oct 04, 2021: Python 3.10
  Dec 31, 2021: NumPy 1.22
  """

  releases = []

  plus42 = timedelta(days=int(365*3.5 + 1))
  plus24 = timedelta(days=int(365*2 + 1))

  for line in data.splitlines():
      date, project_version = line.split(':')
      project, version = project_version.strip().split(' ')
      release = datetime.strptime(date, '%b %d, %Y')
      if project.lower() == 'numpy':
          drop = release + plus24
      else:
          drop = release + plus42
      releases.append((drop, project, version, release))

  releases = sorted(releases, key=lambda x: x[0])

  py_major,py_minor = sorted([int(x) for x in r[2].split('.')] for r in releases if r[1] == 'Python')[-1]
  minpy = f"{py_major}.{py_minor+1}+"

  num_major,num_minor = sorted([int(x) for x in r[2].split('.')] for r in releases if r[1] == 'NumPy')[-1]
  minnum = f"{num_major}.{num_minor+1}+"

  toprint_drop_dates = ['']
  toprint_support_table = []
  for d, p, v, r in releases[::-1]:
      df = d.strftime('%b %d, %Y')
      toprint_drop_dates.append(
          f'On {df} drop support for {p} {v} '
          f'(initially released on {r.strftime("%b %d, %Y")})')
      toprint_support_table.append(f'{df} {minpy:<6} {minnum:<5}')
      if p.lower() == 'numpy':
          minnum = v+'+'
      else:
          minpy = v+'+'
  print("On next release, drop support for Python 3.5 (initially released on Sep 13, 2015)")
  for e in toprint_drop_dates[-4::-1]:
      print(e)

  print('============ ====== =====')
  print('Date         Python NumPy')
  print('------------ ------ -----')
  for e in toprint_support_table[-4::-1]:
      print(e)
  print('============ ====== =====')

Copyright
---------

This document has been placed in the public domain.


text:
<?php

declare(strict_types=1);

namespace Sokil\IsoCodes\Databases;

use Sokil\IsoCodes\Database\Subdivisions;
use Sokil\IsoCodes\Database\SubdivisionsPartitioned;

class SubdivisionsBench
{
    public function databaseProvider(): array
    {
        $countries = \array_column(
            \json_decode(
                file_get_contents(__DIR__ . '/../databases/iso_3166-1.json'),
                true
            )['3166-1'],
            'alpha_2'
        );

        return [
            'non_partitioned' => [
                'database' => Subdivisions::class,
                'countries' => $countries,
            ],
            'partitioned' => [
                'database' => SubdivisionsPartitioned::class,
                'countries' => $countries,
            ],
        ];
    }

    /**
     * @ParamProviders({"databaseProvider"})
     * @Revs(100)
     * @Iterations(1)
     */
    public function benchIterator(array $params): void
    {
        /** @var Subdivisions|SubdivisionsPartitioned $database */
        $database = new $params['database']();

        $database->toArray();
    }

    /**
     * @ParamProviders({"databaseProvider"})
     * @Revs(100)
     * @Iterations(2)
     */
    public function benchGetByCodeSameCode(array $params): void
    {
        /** @var Subdivisions|SubdivisionsPartitioned $database */
        $database = new $params['database']();

        $database->getByCode('UA-43');
        $database->getByCode('UA-43');
        $database->getByCode('UA-43');
        $database->getByCode('UA-43');
        $database->getByCode('UA-43');
    }

    /**
     * @ParamProviders({"databaseProvider"})
     * @Revs(100)
     * @Iterations(2)
     */
    public function benchGetAllByCountryCodeSameAlpha2CountryCode(array $params): void
    {
        /** @var Subdivisions|SubdivisionsPartitioned $database */
        $database = new $params['database']();

        $database->getAllByCountryCode('UA');
        $database->getAllByCountryCode('UA');
        $database->getAllByCountryCode('UA');
        $database->getAllByCountryCode('UA');
        $database->getAllByCountryCode('UA');
    }

    /**
     * @ParamProviders({"databaseProvider"})
     * @Revs(100)
     * @Iterations(2)
     */
    public function benchGetAllByCountryCodeDiffAlpha2CountryCode(array $params): void
    {
        /** @var Subdivisions|SubdivisionsPartitioned $database */
        $database = new $params['database']();

        foreach ($params['countries'] as $countryAlpha2) {
            $database->getAllByCountryCode($countryAlpha2);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 */
package jkind.xtext.jkind.impl;

import java.util.Collection;

import jkind.xtext.jkind.Equation;
import jkind.xtext.jkind.Expr;
import jkind.xtext.jkind.JkindPackage;
import jkind.xtext.jkind.Variable;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import org.eclipse.emf.ecore.util.EObjectResolvingEList;

/**
 *
 * An implementation of the model object 'Equation'.
 *
 *

 * The following features are implemented:
 *

 *
{@link jkind.xtext.jkind.impl.EquationImpl#getLhs Lhs}

 *
{@link jkind.xtext.jkind.impl.EquationImpl#getRhs Rhs}

 *

 *

 *
 * @generated
 */
public class EquationImpl extends MinimalEObjectImpl.Container implements Equation
{
  /**
   * The cached value of the '{@link #getLhs() Lhs}' reference list.
   *
   *
   * @see #getLhs()
   * @generated
   * @ordered
   */
  protected EList<Variable> lhs;

  /**
   * The cached value of the '{@link #getRhs() Rhs}' containment reference.
   *
   *
   * @see #getRhs()
   * @generated
   * @ordered
   */
  protected Expr rhs;

  /**
   *
   *
   * @generated
   */
  protected EquationImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return JkindPackage.Literals.EQUATION;
  }

  /**
   *
   *
   * @generated
   */
  public EList<Variable> getLhs()
  {
    if (lhs == null)
    {
      lhs = new EObjectResolvingEList<Variable>(Variable.class, this, JkindPackage.EQUATION__LHS);
    }
    return lhs;
  }

  /**
   *
   *
   * @generated
   */
  public Expr getRhs()
  {
    return rhs;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetRhs(Expr newRhs, NotificationChain msgs)
  {
    Expr oldRhs = rhs;
    rhs = newRhs;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, JkindPackage.EQUATION__RHS, oldRhs, newRhs);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setRhs(Expr newRhs)
  {
    if (newRhs != rhs)
    {
      NotificationChain msgs = null;
      if (rhs != null)
        msgs = ((InternalEObject)rhs).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - JkindPackage.EQUATION__RHS, null, msgs);
      if (newRhs != null)
        msgs = ((InternalEObject)newRhs).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - JkindPackage.EQUATION__RHS, null, msgs);
      msgs = basicSetRhs(newRhs, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, JkindPackage.EQUATION__RHS, newRhs, newRhs));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case JkindPackage.EQUATION__RHS:
        return basicSetRhs(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case JkindPackage.EQUATION__LHS:
        return getLhs();
      case JkindPackage.EQUATION__RHS:
        return getRhs();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @SuppressWarnings("unchecked")
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case JkindPackage.EQUATION__LHS:
        getLhs().clear();
        getLhs().addAll((Collection<? extends Variable>)newValue);
        return;
      case JkindPackage.EQUATION__RHS:
        setRhs((Expr)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case JkindPackage.EQUATION__LHS:
        getLhs().clear();
        return;
      case JkindPackage.EQUATION__RHS:
        setRhs((Expr)null);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case JkindPackage.EQUATION__LHS:
        return lhs != null && !lhs.isEmpty();
      case JkindPackage.EQUATION__RHS:
        return rhs != null;
    }
    return super.eIsSet(featureID);
  }

} //EquationImpl


text:
var AppDispatcher = require('../dispatcher/AppDispatcher');
var appConstants = require('../constants/AppConstants');

var SurveyActions = {
    saveItem: function(item){
        AppDispatcher.handleAction({
            actionType: appConstants.ADD_ITEM,
            data: item
        });
    },
    deleteItem: function(index){
        AppDispatcher.handleAction({
            actionType: appConstants.REMOVE_ITEM,
            data: index
        })
    }
};

module.exports = SurveyActions;


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Gabardine
{
    public class RewriteResult : OneStepTendril
    {
        readonly Address address;
        readonly RewriteRule rule;
        readonly Term rewrite;

        public RewriteResult(Address address, RewriteRule rule, Term rewrite)
        {
            this.address = address;
            this.rule = rule;
            this.rewrite = rewrite;
        }

        public RewriteRule Rule { get { return rule; } }

        public override Term Matched(Term root)
        {
            return address.Get(root);
        }

        public override Term Transform(Term root)
        {
            return address.Replace(root, rewrite);
        }
    }

    public class RewriteSystem : Transformer<RewriteResult>
    {
        readonly Dictionary<Term, Term> normalForms = new Dictionary<Term, Term>();
        readonly Dictionary<Operator, List<RewriteRule>> rules = new Dictionary<Operator, List<RewriteRule>>();

        public void AddRule(RewriteRule rule)
        {
            //RewriteRule rule = RewriteRuleFactory.Create(id, lhs, rhs, Enumerable.Empty<ConditionPattern>(), priority, isDefault);
            List<RewriteRule> list;
            if (!rules.TryGetValue(rule.Pattern.Op, out list)) {
                list = new List<RewriteRule>();
                rules.Add(rule.Pattern.Op, list);
            }
            list.Add(rule);
            list.Sort(RuleComparison);
        }

        public void AddRule(Term lhs, Term rhs)
        {
            AddRule(RewriteRuleFactory.Create(lhs, rhs, 0, true));
        }

        public void AddEquivalence(Term lhs, Term rhs)
        {
            AddRule(RewriteRuleFactory.Create(lhs, rhs, 0, false));
            AddRule(RewriteRuleFactory.Create(rhs, lhs, 0, false));
        }

        public IEnumerable<RewriteRule> Rules
        {
            get
            {
                foreach (var lst in rules.Values) {
                    foreach (var rule in lst) {
                        yield return rule;
                    }
                }
            }
        }

        public IEnumerable<RewriteRule> OrderedRules
        {
            get
            {
                return Rules.OrderBy(r => r.Id);
            }
        }

        int RuleComparison(RewriteRule a, RewriteRule b)
        {
            int p_delta = b.Priority - a.Priority;
            if (p_delta == 0) {
                return b.Id - a.Id;
            }
            return p_delta;
        }

        ///
        ///   Gets the list of rules which might match the term at <paramref name="node"/>,
        ///   in priority order.
        ///
        IEnumerable<RewriteRule> GetPossibleRules(WalkContext node, bool includeReversible)
        {
            if (rules.TryGetValue(node.Term.Op, out List<RewriteRule> list)) {
                if (!includeReversible) {
                    return list.Where(x => x.IsDefault);
                }
                return list;
            }
            return Enumerable.Empty<RewriteRule>();
        }

        ///
        ///   Gets all possible rewrites anchored at <paramref
        ///   name="node"/>, including reverse direction.
        ///
        IEnumerable<RewriteResult> RootRewrites(WalkContext node)
        {
            var seq = GetPossibleRules(node, true);
            foreach (var rule in seq) {
                if (rule.TryRewrite(node.Term, this, out Term rewrite)) {
                    yield return new RewriteResult(node.GetAddress(), rule, rewrite);
                }
            }
        }

        ///
        ///   Gets the highest priority rewrite of the term at <paramref name="node"/>,
        ///   only taking the default direction into consideration. If successful,
        ///   <paramref name="rule"/> is set to the matching rule, and the rewrite is
        ///   returned. Otherwise null.
        ///
        Term GetDirectRewrite(WalkContext node, out RewriteRule rule)
        {
            rule = null;
            var seq = GetPossibleRules(node, false);
            foreach (var r in seq) {
                if (r.TryRewrite(node.Term, this, out Term rewrite)) {
                    rule = r;
                    return rewrite;
                }
            }
            return null;
        }

        ///
        ///   Implements Transformer<RewriteResult> by returning all
        ///   possible rewrites, in either direction, of <paramref name="root"/>, at any
        ///   location.
        ///
        public IEnumerable<RewriteResult> FindTransformations(Term root)
        {
            var stack = new Stack<WalkContext>();
            Stack<Term> args = new Stack<Term>();
            stack.Push(new WalkContext(root));

            while (stack.Count > 0) {
                var head = stack.Pop();

                if (ReferenceEquals(head, null)) {
                    head = stack.Pop();
                    args.PopFIFO(head.Arity);
                    var rws = RootRewrites(head);
                    foreach (var rw in rws) {
                        yield return rw;
                    }
                    args.Push(head.Term);
                    continue;
                }

                stack.Push(head);
                stack.Push(null);
                for (int i = head.Arity - 1; i >= 0; --i) {
                    stack.Push(head.MoveToChild(i));
                }
            }

            yield break;
        }

        Term RewriteUnordered(WalkContext src)
        {
            WalkContext node = src;

            bool changed = true;
            while(changed) {
                Term[] args = new Term[node.Arity];
                for (int i = 0; i < args.Length; ++i) {
                    args[i] = RewriteUnordered(node.MoveToChild(i));
                }
                node = node.WithTerm(new Term(node.Term.Op, args));

                Term rw = GetDirectRewrite(node, out RewriteRule rule);
                if (object.ReferenceEquals(rw, null)) {
                    break;
                }

                bool failure = rw.Op == Special.FailWith;
                if (failure) {
                    var message = ConsUtils.UnconsMany(rw[0]).Select(x => x.ToString()).Aggregate((u, v) => u + v);
                    throw new Exception(message);
                }
                node = node.WithTerm(rw);

            }

            return node.Term;
        }

        ///
        ///   Repeatedly rewrites <paramref name="source"/> to termination (i.e., until no
        ///   more rules match anywhere).
        ///
#if false
        public Term RewriteUnordered(Term source, bool dump_rewrites = false)
        {
            return RewriteUnordered(new WalkContext(source));
        }

#else
        public Term RewriteUnordered(Term source, bool dump_rewrites = false)
        {
            if (!dump_rewrites) {
                return RewriteUnordered(source, null);
            }

            RewriteHistory history = new RewriteHistory();
            Term retval = RewriteUnordered(source, history);
            foreach (var step in history.Steps) {
                step.Print(Terminal.Stdout);
            }
            return retval;
        }

        public Term RewriteUnordered(Term source, RewriteHistory history)
        {
            var stack = new Stack<WalkContext>();
            var args = new Stack<Term>();
            var trace = new Stack<Term>();
            var start = new Stack<int>();

            bool dumpRewrites = !object.ReferenceEquals(history, null);

            stack.Push(new WalkContext(source));
            start.Push(0);
            while (stack.Count > 0) {

                var head = stack.Pop();

                // Children have been processed
                if (ReferenceEquals(head, null)) {

                    // Rebuild term in terms of fully-rewritten children
                    head = stack.Pop();
                    Operator op = head.Term.Op;
                    head = head.WithTerm(new Term(op, args.PopFIFO(op.Arity)));

                    // Can we rewrite this new version?
                    Term rewrite = GetDirectRewrite(head, out RewriteRule matched);
                    if (ReferenceEquals(rewrite, null)) {
                        // This subterm has terminated.
                        args.Push(head.Term);
                        int lim = start.Pop();
                        while (trace.Count > lim) {
                            normalForms.Add(trace.Pop(), head.Term);
                        }
                        continue;
                    }

                    bool failure = rewrite.Op == Special.FailWith;

                    if (dumpRewrites) {
                        history.AddStep(stack, args, head, rewrite, matched);
                    }

                    if (failure) {
                        var message = ConsUtils.UnconsMany(rewrite[0]).Select(x => x.ToString()).Aggregate((u, v) => u + v);
                        throw new Exception(message);
                    }

                    head = head.WithTerm(rewrite);

                    // Rewrite successful. Reschedule children.
                }

                // Has this term been processed? If so, push its terminal form to argument
                // stack. If not, process it.
                if (!dumpRewrites) {
                    if (normalForms.TryGetValue(head.Term, out Term nf)) {
                        args.Push(nf);
                        int lim = start.Pop();
                        while (trace.Count > lim) {
                            normalForms.Add(trace.Pop(), nf);
                        }
                        continue;
                    }
                }

                // Visit children with return marker
                stack.Push(head);
                stack.Push(null);
                for (int i = head.Arity - 1; i >= 0; --i) {
                    start.Push(trace.Count);
                    stack.Push(head.MoveToChild(i));
                }
            }

            Debug.Assert(args.Count == 1, "Only result should remain.");
            return args.Pop();
        }
#endif

    }
}


text:
#ifndef H_LUCYX_SEARCH_MOCKMATCHER
#define H_LUCYX_SEARCH_MOCKMATCHER 1

#ifdef __cplusplus
extern "C" {
#endif

#include "lucy_parcel.h"

/* Include the header for this class's parent.
 */

#include "Lucy/Search/Matcher.h"

/* Define the struct layout for instances of this class.
 */

#ifdef C_LUCY_MOCKMATCHER
extern uint32_t lucy_MockMatcher_IVARS_OFFSET;
typedef struct lucy_MockMatcherIVARS lucy_MockMatcherIVARS;
static CFISH_INLINE lucy_MockMatcherIVARS*
lucy_MockMatcher_IVARS(lucy_MockMatcher *self) {
   char *ptr = (char*)self + lucy_MockMatcher_IVARS_OFFSET;
   return (lucy_MockMatcherIVARS*)ptr;
}
#ifdef LUCY_USE_SHORT_NAMES
  #define MockMatcherIVARS lucy_MockMatcherIVARS
  #define MockMatcher_IVARS lucy_MockMatcher_IVARS
#endif

struct lucy_MockMatcherIVARS {
    size_t size;
    lucy_I32Array* doc_ids;
    cfish_Blob* scores;
    int32_t tick;
};

#endif /* C_LUCY_MOCKMATCHER */

/* Declare this class's inert variables.
 */

/* Declare both this class's inert functions and the C functions which
 * implement this class's dynamic methods.
 */

LUCY_VISIBLE lucy_MockMatcher*
lucy_MockMatcher_new(lucy_I32Array* doc_ids, cfish_Blob* scores);

LUCY_VISIBLE lucy_MockMatcher*
lucy_MockMatcher_init(lucy_MockMatcher* self, lucy_I32Array* doc_ids, cfish_Blob* scores);

void
LUCY_MockMatcher_Destroy_IMP(lucy_MockMatcher* self);

int32_t
LUCY_MockMatcher_Next_IMP(lucy_MockMatcher* self);

float
LUCY_MockMatcher_Score_IMP(lucy_MockMatcher* self);

int32_t
LUCY_MockMatcher_Get_Doc_ID_IMP(lucy_MockMatcher* self);

/* Define typedefs for each dynamic method, allowing us to cast generic
 * pointers to the appropriate function pointer type more cleanly.
 */

typedef void*
(*LUCY_MockMatcher_To_Host_t)(lucy_MockMatcher* self, void* vcache);

typedef cfish_Obj*
(*LUCY_MockMatcher_Clone_t)(lucy_MockMatcher* self);

typedef bool
(*LUCY_MockMatcher_Equals_t)(lucy_MockMatcher* self, cfish_Obj* other);

typedef int32_t
(*LUCY_MockMatcher_Compare_To_t)(lucy_MockMatcher* self, cfish_Obj* other);

typedef void
(*LUCY_MockMatcher_Destroy_t)(lucy_MockMatcher* self);

typedef cfish_String*
(*LUCY_MockMatcher_To_String_t)(lucy_MockMatcher* self);

typedef int32_t
(*LUCY_MockMatcher_Next_t)(lucy_MockMatcher* self);

typedef int32_t
(*LUCY_MockMatcher_Advance_t)(lucy_MockMatcher* self, int32_t target);

typedef int32_t
(*LUCY_MockMatcher_Get_Doc_ID_t)(lucy_MockMatcher* self);

typedef float
(*LUCY_MockMatcher_Score_t)(lucy_MockMatcher* self);

typedef void
(*LUCY_MockMatcher_Collect_t)(lucy_MockMatcher* self, lucy_Collector* collector, lucy_Matcher* deletions);

/* Define type-safe wrappers for inert functions of Obj.
 */

static CFISH_INLINE cfish_Class*
lucy_MockMatcher_get_class(lucy_MockMatcher *self) {
    return cfish_Obj_get_class((cfish_Obj*)self);
}

static CFISH_INLINE cfish_String*
lucy_MockMatcher_get_class_name(lucy_MockMatcher *self) {
    return cfish_Obj_get_class_name((cfish_Obj*)self);
}

static CFISH_INLINE bool
lucy_MockMatcher_is_a(lucy_MockMatcher *self, cfish_Class *ancestor) {
    return cfish_Obj_is_a((cfish_Obj*)self, ancestor);
}

/* Define the inline functions which implement this class's virtual methods.
 */

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_To_Host_OFFSET;
static CFISH_INLINE void*
LUCY_MockMatcher_To_Host(lucy_MockMatcher* self, void* vcache) {
    const LUCY_MockMatcher_To_Host_t method = (LUCY_MockMatcher_To_Host_t)cfish_obj_method(self, LUCY_MockMatcher_To_Host_OFFSET);
    return method(self, vcache);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Clone_OFFSET;
static CFISH_INLINE cfish_Obj*
LUCY_MockMatcher_Clone(lucy_MockMatcher* self) {
    const LUCY_MockMatcher_Clone_t method = (LUCY_MockMatcher_Clone_t)cfish_obj_method(self, LUCY_MockMatcher_Clone_OFFSET);
    return method(self);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Equals_OFFSET;
static CFISH_INLINE bool
LUCY_MockMatcher_Equals(lucy_MockMatcher* self, cfish_Obj* other) {
    const LUCY_MockMatcher_Equals_t method = (LUCY_MockMatcher_Equals_t)cfish_obj_method(self, LUCY_MockMatcher_Equals_OFFSET);
    return method(self, other);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Compare_To_OFFSET;
static CFISH_INLINE int32_t
LUCY_MockMatcher_Compare_To(lucy_MockMatcher* self, cfish_Obj* other) {
    const LUCY_MockMatcher_Compare_To_t method = (LUCY_MockMatcher_Compare_To_t)cfish_obj_method(self, LUCY_MockMatcher_Compare_To_OFFSET);
    return method(self, other);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Destroy_OFFSET;
static CFISH_INLINE void
LUCY_MockMatcher_Destroy(lucy_MockMatcher* self) {
    const LUCY_MockMatcher_Destroy_t method = (LUCY_MockMatcher_Destroy_t)cfish_obj_method(self, LUCY_MockMatcher_Destroy_OFFSET);
    method(self);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_To_String_OFFSET;
static CFISH_INLINE cfish_String*
LUCY_MockMatcher_To_String(lucy_MockMatcher* self) {
    const LUCY_MockMatcher_To_String_t method = (LUCY_MockMatcher_To_String_t)cfish_obj_method(self, LUCY_MockMatcher_To_String_OFFSET);
    return method(self);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Next_OFFSET;
static CFISH_INLINE int32_t
LUCY_MockMatcher_Next(lucy_MockMatcher* self) {
    const LUCY_MockMatcher_Next_t method = (LUCY_MockMatcher_Next_t)cfish_obj_method(self, LUCY_MockMatcher_Next_OFFSET);
    return method(self);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Advance_OFFSET;
static CFISH_INLINE int32_t
LUCY_MockMatcher_Advance(lucy_MockMatcher* self, int32_t target) {
    const LUCY_MockMatcher_Advance_t method = (LUCY_MockMatcher_Advance_t)cfish_obj_method(self, LUCY_MockMatcher_Advance_OFFSET);
    return method(self, target);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Get_Doc_ID_OFFSET;
static CFISH_INLINE int32_t
LUCY_MockMatcher_Get_Doc_ID(lucy_MockMatcher* self) {
    const LUCY_MockMatcher_Get_Doc_ID_t method = (LUCY_MockMatcher_Get_Doc_ID_t)cfish_obj_method(self, LUCY_MockMatcher_Get_Doc_ID_OFFSET);
    return method(self);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Score_OFFSET;
static CFISH_INLINE float
LUCY_MockMatcher_Score(lucy_MockMatcher* self) {
    const LUCY_MockMatcher_Score_t method = (LUCY_MockMatcher_Score_t)cfish_obj_method(self, LUCY_MockMatcher_Score_OFFSET);
    return method(self);
}

extern LUCY_VISIBLE uint32_t LUCY_MockMatcher_Collect_OFFSET;
static CFISH_INLINE void
LUCY_MockMatcher_Collect(lucy_MockMatcher* self, lucy_Collector* collector, lucy_Matcher* deletions) {
    const LUCY_MockMatcher_Collect_t method = (LUCY_MockMatcher_Collect_t)cfish_obj_method(self, LUCY_MockMatcher_Collect_OFFSET);
    method(self, collector, deletions);
}

/* Declare callbacks for wrapping host overrides.
 */

#ifdef CFISH_NO_DYNAMIC_OVERRIDES
#else
#endif

/* Define "short names" for this class's symbols.
 */

#ifdef LUCY_USE_SHORT_NAMES
  #define MockMatcher lucy_MockMatcher
  #define MOCKMATCHER LUCY_MOCKMATCHER
  #define MockMatcher_new lucy_MockMatcher_new
  #define MockMatcher_init lucy_MockMatcher_init
  #define MockMatcher_get_class lucy_MockMatcher_get_class
  #define MockMatcher_get_class_name lucy_MockMatcher_get_class_name
  #define MockMatcher_is_a lucy_MockMatcher_is_a
  #define MockMatcher_Destroy_IMP LUCY_MockMatcher_Destroy_IMP
  #define MockMatcher_Next_IMP LUCY_MockMatcher_Next_IMP
  #define MockMatcher_Score_IMP LUCY_MockMatcher_Score_IMP
  #define MockMatcher_Get_Doc_ID_IMP LUCY_MockMatcher_Get_Doc_ID_IMP
  #define MockMatcher_To_Host LUCY_MockMatcher_To_Host
  #define MockMatcher_To_Host_t LUCY_MockMatcher_To_Host_t
  #define MockMatcher_Clone LUCY_MockMatcher_Clone
  #define MockMatcher_Clone_t LUCY_MockMatcher_Clone_t
  #define MockMatcher_Equals LUCY_MockMatcher_Equals
  #define MockMatcher_Equals_t LUCY_MockMatcher_Equals_t
  #define MockMatcher_Compare_To LUCY_MockMatcher_Compare_To
  #define MockMatcher_Compare_To_t LUCY_MockMatcher_Compare_To_t
  #define MockMatcher_Destroy LUCY_MockMatcher_Destroy
  #define MockMatcher_Destroy_t LUCY_MockMatcher_Destroy_t
  #define MockMatcher_To_String LUCY_MockMatcher_To_String
  #define MockMatcher_To_String_t LUCY_MockMatcher_To_String_t
  #define MockMatcher_Next LUCY_MockMatcher_Next
  #define MockMatcher_Next_t LUCY_MockMatcher_Next_t
  #define MockMatcher_Advance LUCY_MockMatcher_Advance
  #define MockMatcher_Advance_t LUCY_MockMatcher_Advance_t
  #define MockMatcher_Get_Doc_ID LUCY_MockMatcher_Get_Doc_ID
  #define MockMatcher_Get_Doc_ID_t LUCY_MockMatcher_Get_Doc_ID_t
  #define MockMatcher_Score LUCY_MockMatcher_Score
  #define MockMatcher_Score_t LUCY_MockMatcher_Score_t
  #define MockMatcher_Collect LUCY_MockMatcher_Collect
  #define MockMatcher_Collect_t LUCY_MockMatcher_Collect_t
#endif /* LUCY_USE_SHORT_NAMES */

#ifdef __cplusplus
}
#endif

#endif /* H_LUCYX_SEARCH_MOCKMATCHER */


text:
create table todoitem (
	ITEM_ID		INTEGER		NOT NULL,
	Description	VARCHAR(255)	NOT NULL check(Description <> ''),
	PRIMARY KEY(ITEM_ID)
);

insert into todoitem values (1, 'Read a book');
insert into todoitem values (2, 'Listen to music');
insert into todoitem values (3, 'Clean the toilet');
insert into todoitem values (4, 'Organize office');
insert into todoitem values (5, 'Pay the bills');
insert into todoitem values (6, 'Drink coffee');
insert into todoitem values (7, 'Eat cake');
insert into todoitem values (8, 'Go to the gym');
insert into todoitem values (9, 'Rehearse music');
insert into todoitem values (10, 'Send a postcard');
insert into todoitem values (11, 'Refactor codebase');
insert into todoitem values (12, 'Watch TV');
insert into todoitem values (13, 'Walk around the park');
insert into todoitem values (14, 'Learn how to cook');
insert into todoitem values (15, 'Play a game');
insert into todoitem values (16, 'Attend a meeting');


text:
[GNU Stow](https://www.gnu.org/software/stow/) is effectively a symlink
package manager. You define a "package" consisting of a directory tree which
details *where* things should be installed on your system, and GNU Stow will
create symlinks from your system *into* the "package" directory.

For example, let's say we had the following scripts placed inside of
`"/stow/scripts/usr/local/bin"`:

```
/stow/scripts/usr/local/bin/run_update.sh
/stow/scripts/usr/local/bin/callback.sh
/stow/scripts/usr/local/bin/restart_server.sh
/stow/scripts/usr/local/bin/reload_server.sh
```

If we changed to `/stow` and then ran `stow scripts` it would create the
following symlinks:

```
/usr/local/bin/run_update.sh -> /stow/scripts/usr/local/bin/run_update.sh
/usr/local/bin/callback.sh -> /stow/scripts/usr/local/bin/callback.sh
/usr/local/bin/restart_server.sh -> /stow/scripts/usr/local/bin/restart_server.sh
/usr/local/bin/reload_server.sh -> /stow/scripts/usr/local/bin/reload_server.sh
```

These scripts can now be used as if they were installed on your system. Further,
changing the scripts inside of `/stow` will update the scripts system-wide
(because they are just symlinks).

Finally, uninstalling these scripts is as simple as unstowing them with the
command `stow -D scripts` run from inside the `/stow` directory.

As you can see, GNU Stow is a *powerful* yet *simple* tool.


text:
package com.rockhoppertech.music.midi.js;

import java.util.ArrayList;
import java.util.List;

import javax.sound.midi.Instrument;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.VoiceStatus;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Shoves data directly to a channel on a device. No real timing. Useful for GUI
 * things like keyboards or sliders.
 *
 *

MIDINote note = MIDINoteBuilder.create()
                .channel(0)
                .startBeat(1d)
                .pitch(Pitch.D5)
                .duration(5d)
                .program(MIDIGMPatch.BANJO.getProgram())
                .build();

MIDISender sender = new MIDISender();
sender.play(note);
sender.closeDevice();

 *
 *
 * @author Gene De Lisa
 *
 */

public class MIDISender {
    /**
     *
     */
    private final static Logger logger = LoggerFactory
            .getLogger(MIDISender.class);
    private int num;
    private Synthesizer synth;
    private int sendChannel = 0;
    private MidiChannel channel;
    private int sendVelocity = 100;
    private MidiDevice midiDevice;
    // private Receiver receiver;
    List<Receiver> receivers = new ArrayList<Receiver>();
    private long sleepValue = 1000;
    private int octave = 5;

    /**
     * Uses the JavaSound Synthesizer.
     */
    public MIDISender() {
        try {
            this.midiDevice = MidiSystem.getSynthesizer();
        } catch (MidiUnavailableException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * Plays on the specified MIDI device.
     *
     * @param midiDevice
     *            the device to play on.
     */
    public MIDISender(MidiDevice midiDevice) {
        this.midiDevice = midiDevice;
    }

    public void play(MIDINote note) {
        this.openDevice();
        this.sleepValue = (long) (note.getDuration() * 1000L);
        this.sendMessage(
                note.getMidiNumber(),
                note.getVelocity(),
                note.getProgram());
        // this.closeDevice();
    }

    public void sendMessage(final int num) {
        this.sendMessage(num, 0, sendVelocity);
    }

    public void sendNoteOn(final int midiPitchNumber, final int velocity) {
        if (!midiDevice.isOpen()) {
            this.openDevice();
        }
        if (this.channel != null) {
            logger.debug("using channel");
            this.channel.noteOn(midiPitchNumber, velocity);
        } else {
            logger.debug("not using channel");
        }
        if (this.receivers != null && this.receivers.isEmpty() == false) {
            ShortMessage sm = new ShortMessage();
            try {
                sm.setMessage(
                        ShortMessage.NOTE_ON,
                        sendChannel,
                        midiPitchNumber,
                        sendVelocity);
            } catch (InvalidMidiDataException e1) {
                e1.printStackTrace();
                logger.error(e1.getLocalizedMessage(), e1);
            }
            for (Receiver r : receivers) {
                logger.debug("sending to receiver {}", r);
                logger.debug("msg {}", MIDIUtils.toString(sm));
                r.send(sm, this.midiDevice.getMicrosecondPosition());
            }
        }
    }

    public void sendNoteOff(final int midiPitchNumber) {
        if (!midiDevice.isOpen()) {
            this.openDevice();
        }
        if (this.channel != null) {
            logger.debug("using channel");
            this.channel.noteOff(midiPitchNumber);
        } else {
            logger.debug("not using channel");
        }
        if (this.receivers != null && this.receivers.isEmpty() == false) {
            ShortMessage sm = new ShortMessage();
            try {
                sm.setMessage(
                        ShortMessage.NOTE_OFF,
                        sendChannel,
                        midiPitchNumber,
                        sendVelocity);
            } catch (InvalidMidiDataException e1) {
                e1.printStackTrace();
                logger.error(e1.getLocalizedMessage(), e1);
            }
            for (Receiver r : receivers) {
                logger.debug("sending to receiver {}", sm);
                r.send(sm, this.midiDevice.getMicrosecondPosition());
            }
        }
    }

    public void sendMessage(final int midiPitchNumber, final int velocity,
            final int program) {
        // Timer timer = new Timer();
        // timer.schedule(new TimerTask() {
        // @Override
        // public void run() {
        // channel.noteOn(num, 0);
        // }}, sleepValue);

        if (!midiDevice.isOpen()) {
            this.openDevice();
        }
        setProgram(program);

        logger.debug("sending midiPitchNumber {}", midiPitchNumber);

        // this.channel.programChange(program);
        if (this.channel != null) {
            logger.debug("using channel");
            this.channel.noteOn(midiPitchNumber, velocity);
            try {
                Thread.sleep(this.sleepValue);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.channel.noteOn(midiPitchNumber, 0);
        } else {
            logger.debug("not using channel");
        }

        if (this.receivers != null && this.receivers.isEmpty() == false) {
            logger.debug("using port");
            ShortMessage sm = new ShortMessage();
            // try {
            // sm.setMessage(ShortMessage.PROGRAM_CHANGE, sendChannel, 0,
            // program);
            // } catch (InvalidMidiDataException e1) {
            // e1.printStackTrace();
            // }
            // for (Receiver r : receivers) {
            // logger.debug("sending to receiver " + sm);
            // r.send(sm, this.midiDevice.getMicrosecondPosition());
            // }

            try {
                sm.setMessage(
                        ShortMessage.NOTE_ON,
                        sendChannel,
                        midiPitchNumber,
                        sendVelocity);
            } catch (InvalidMidiDataException e1) {
                e1.printStackTrace();
            }
            for (Receiver r : receivers) {
                logger.debug("sending to receiver " + sm);
                r.send(sm, this.midiDevice.getMicrosecondPosition());
            }
            // this.receiver.send(sm, this.midiDevice.getMicrosecondPosition());
            logger.debug(
                    "ms posiiton {}",
                    this.midiDevice.getMicrosecondPosition());

            try {
                Thread.sleep(this.sleepValue);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // turn it off
            try {
                sm.setMessage(
                        ShortMessage.NOTE_ON,
                        sendChannel,
                        midiPitchNumber,
                        0);
            } catch (InvalidMidiDataException e) {
                e.printStackTrace();
            }
            for (Receiver r : receivers) {
                r.send(sm, this.synth.getMicrosecondPosition());
            }
            // this.receiver.send(sm, this.synth.getMicrosecondPosition());
        } else {

            logger.debug("Not using port");

        }
    }

    public Instrument[] openDevice() {
        Instrument[] insts = new Instrument[1];
        if (this.midiDevice == null) {
            logger.debug("midi device is null! Using default synthesizer.");
            try {
                this.midiDevice = MidiSystem.getSynthesizer();
            } catch (MidiUnavailableException e) {
                e.printStackTrace();
                logger.error(e.getLocalizedMessage(), e);
                // an empty array
                return insts;
            }
        }
        if (midiDevice.isOpen()) {
            if (this.midiDevice instanceof Synthesizer) {
                this.synth = (Synthesizer) this.midiDevice;
                insts = synth.getAvailableInstruments();
                return insts;
            }
            // an empty array
            return insts;
        }

        try {
            this.midiDevice.open();

            if (this.midiDevice instanceof Synthesizer) {
                this.synth = (Synthesizer) this.midiDevice;
                channel = this.synth.getChannels()[this.sendChannel];

                insts = synth.getAvailableInstruments();
            } else {
                receivers.add(this.midiDevice.getReceiver());
                // this.receiver = this.midiDevice.getReceiver();
            }

        } catch (MidiUnavailableException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);

        }
        return insts;
    }

    public void closeDevice() {
        if (this.midiDevice == null) {
            return;
        }
        logger.debug("Closing device {}",
                this.midiDevice.getDeviceInfo().getName());
        if (this.midiDevice.isOpen() == false) {
            return;
        }
        this.midiDevice.close();
        if (this.receivers != null) {
            // this.receiver.close();
        }
        this.midiDevice = null;
        // this.receiver = null;
        this.channel = null;
    }

    /**
     * @param inst
     *            the instrument
     * @return the instrument
     */
    public Instrument setInstrument(Instrument inst) {
        if (inst == null) {
            logger.debug("inst is null");
            return null;
        }
        if (this.synth == null)
            this.openDevice();

        this.synth.loadInstrument(inst);
        channel = synth.getChannels()[sendChannel];
        channel.programChange(inst.getPatch().getBank(), inst.getPatch()
                .getProgram());

        int bank = inst.getPatch().getBank();
        logger.debug("bank: " + bank);
        int setbank = (channel.getController(0) * 128)
                + channel.getController(32);
        logger.debug("setbank: " + setbank);

        VoiceStatus[] vs = this.synth.getVoiceStatus();
        for (VoiceStatus v : vs) {
            logger.debug("vs bank" + v.bank);
            logger.debug("vs channel" + v.channel);
            logger.debug("vs program" + v.program);
        }
        return inst;

    }

    /**
     * Sends a program change message.
     *
     * @param num
     *            the program number
     */
    public void setProgram(int num) {
        logger.debug("sending pchange {}", num);
        /*
         * if(this.midiDevice == null) this.openDevice(); if(this.receiver ==
         * null) this.openDevice();
         */

        if (this.channel != null) {
            this.channel.programChange(num);
        }
        if (this.receivers != null) {
            ShortMessage sm = new ShortMessage();
            try {
                sm.setMessage(ShortMessage.PROGRAM_CHANGE, sendChannel, num, 0);
            } catch (InvalidMidiDataException e) {
                e.printStackTrace();
            }
            // this.receiver.send(sm, this.midiDevice.getMicrosecondPosition());
            for (Receiver r : receivers) {
                r.send(sm, this.midiDevice.getMicrosecondPosition());
            }
        }
    }

    /**
     * @param midiDevice
     *            the midiDevice to set
     */
    public void setMidiDevice(MidiDevice midiDevice) {
        this.midiDevice = midiDevice;
    }

    /**
     * @return the num
     */
    public int getNum() {
        return this.num;
    }

    /**
     * @param num
     *            the num to set
     */
    public void setNum(int num) {
        this.num = num;
    }

    /**
     * @return the octave
     */
    public int getOctave() {
        return this.octave;
    }

    /**
     * @param octave
     *            the octave to set
     */
    public void setOctave(int octave) {
        this.octave = octave;
    }

    /**
     * @return the sendChannel
     */
    public int getSendChannel() {
        return this.sendChannel;
    }

    /**
     * @param sendChannel
     *            the sendChannel to set
     */
    public void setSendChannel(int sendChannel) {
        this.sendChannel = sendChannel;
    }

    /**
     * @return the sendVelocity
     */
    public int getSendVelocity() {
        return this.sendVelocity;
    }

    /**
     * @param sendVelocity
     *            the sendVelocity to set
     */
    public void setSendVelocity(int sendVelocity) {
        this.sendVelocity = sendVelocity;
    }

    /**
     * @return the sleepValue
     */
    public long getSleepValue() {
        return this.sleepValue;
    }

    /**
     * @param sleepValue
     *            the sleepValue to set
     */
    public void setSleepValue(long sleepValue) {
        this.sleepValue = sleepValue;
    }

    /**
     * doesn't work.
     *
     * @param myReceiver
     *            a JavaSound Receiver
     */
    // TODO fix this
    public void addReceiver(Receiver myReceiver) {
        receivers.add(myReceiver);
        // try {
        // midiDevice.getTransmitter().setReceiver(myReceiver);
        // } catch (MidiUnavailableException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // midiDevice.getReceivers().add(myReceiver);

    }

    public void setInstrument(
            com.rockhoppertech.music.midi.js.Instrument newValue) {
        // TODO Auto-generated method stub

    }

}

/*
 * Controller 0 - Bank Select MSB is used in conjunction often with the Bank
 * Select LSB to select the bank for the next program change message. This means
 * the patch does not change until the program change is received (bank messages
 * alone are not enough). The combination of Bank MSB and LSB messages gives a
 * possible 16384 banks, each of 128 different sounds, giving over 2 million
 * possible sounds! In practice, most manufacturers only use a few different
 * banks, and you can usually ignore the LSB message.
 */
/*
 * channel = synth.getChannels()[sendChannel];
 * channel.programChange(inst.getPatch().getBank(), inst
 * .getPatch().getProgram());
 *
 * int bank = inst.getPatch().getBank(); logger.debug("bank: " + bank); int
 * setbank = (channel.getController(0) * 128) + channel.getController(32);
 * logger.debug("setbank: " + setbank);
 */

/*
 * ShortMessage sm = new ShortMessage(); try {
 *
 *
 * //the bank number to switch to (0 to 16383) int bank =
 * inst.getPatch().getBank(); logger.debug("bank: " + bank); int msb = bank &
 * 0xF0; int lsb = bank & 0x0F;
 *
 * msb = bank >>> 8; lsb = bank & 0xFF;
 *
 * msb = ((int) bank & 0x000000FF) / 128; lsb = ((int) bank & 0x000000FF) % 128;
 * logger.debug("msb: " + msb); logger.debug("lsb: " + lsb);
 *
 * // msb sm.setMessage(ShortMessage.CONTROL_CHANGE, sendChannel, 0, msb);
 * receiver.send(sm, synth.getMicrosecondPosition());
 *
 * // lsb sm.setMessage(ShortMessage.CONTROL_CHANGE, sendChannel, 0x20, lsb);
 * receiver.send(sm, synth.getMicrosecondPosition());
 *
 * sm.setMessage(ShortMessage.PROGRAM_CHANGE, sendChannel,
 * inst.getPatch().getProgram(), 0); receiver.send(sm,
 * synth.getMicrosecondPosition());
 *
 * } catch (InvalidMidiDataException ex) { ex.printStackTrace(); }
 */


text:
function matern32KernDisplay(kern, spacing)

% MATERN32KERNDISPLAY Display parameters of the MATERN32 kernel.
%
%	Description:
%
%	MATERN32KERNDISPLAY(KERN) displays the parameters of the matern
%	kernel with nu=3/2 kernel and the kernel type to the console.
%	 Arguments:
%	  KERN - the kernel to display.
%
%	MATERN32KERNDISPLAY(KERN, SPACING)
%	 Arguments:
%	  KERN - the kernel to display.
%	  SPACING - how many spaces to indent the display of the kernel by.
%
%
%	See also
%	MATERN32KERNPARAMINIT, MODELDISPLAY, KERNDISPLAY

%	Copyright (c) 2006 Neil D. Lawrence

if nargin > 1
  spacing = repmat(32, 1, spacing);
else
  spacing = [];
end
spacing = char(spacing);
fprintf(spacing);
fprintf('Matern, nu=3/2, length scale: %2.4f\n', ...
        kern.lengthScale);
fprintf(spacing);
fprintf('Matern, nu=3/2, variance: %2.4f\n', kern.variance)


text:
import React from 'react'
import Truncated from '../truncated'
import { mount } from 'enzyme'

describe('Truncated', () => {
  test('handles undefined values', () => {
    let component = mount(<Truncated />)
    expect(component.text()).toBe('')
  })

  test('handles numbers', () => {
    let component = mount(<Truncated text={1} />)
    expect(component.text()).toBe('1')
  })

  test('limits text', () => {
    let component = mount(<Truncated text="This will be truncated" limit={10} />)
    expect(component.text()).toBe('This will…')
  })

  test('does not add ellipsis to short text', () => {
    let component = mount(<Truncated text="Short" limit={20} />)
    expect(component.text()).toBe('Short')
  })
})


text:
package ant.codecontext.parser;

/**
  the non terminal IfThenElseStatementNoShortIf node.

  @author Kim, sung-hoon
 */
public class IfThenElseStatementNoShortIf extends TreeNode {
	/**
	  Constructor.
	  the node number : 69.

	  @param x the line number.
	  @param y the column number.
	 */
	public IfThenElseStatementNoShortIf(int x,int y) {
		super(x,y,NonTerminal.IFTHENELSESTATEMENTNOSHORTIF);
	}

	/**
	  It converts the subtree into the string.

	  @return the converted string.
	 */
	public String toString() {
	    StringBuffer buffer=new StringBuffer();
	    TreeNode node=getChild();

	    buffer.append("if (");
	    buffer.append(node.toString());
	    buffer.append(")");

	    node=getChild();
	    buffer.append(node.toString());

	    node=getChild();
	    buffer.append(" else "+node.toString());

	    return buffer.toString();
	}
}


text:
public class LRUCache {

    int capacity;
    Map<Integer, Item> map = new HashMap<Integer, Item>();
    Item head = null, tail = null;

    class Item {
        public int key;
        public int value;
        public Item prev;
        public Item next;

        public Item(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    public LRUCache(int capacity) {
        this.capacity = capacity;

    }

    public int get(int key) {
        if (map.containsKey(key)) {
            Item item = map.get(key);
            remove(item);
            setHead(item);
            return item.value;
        }
        return -1;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            Item item = map.get(key);
            item.value = value;
            remove(item);
            setHead(item);
        } else {
            Item item = new Item(key, value);
            if (map.size() >= capacity) {
                map.remove(tail.key);
                remove(tail);
                setHead(item);
            } else {
                setHead(item);
            }
            map.put(key, item);
        }
    }
    private void remove(Item item) {
        if (item.prev != null) {
            item.prev.next = item.next;
        } else {
            head = item.next;
        }
        if (item.next != null) {
            item.next.prev = item.prev;
        } else {
            tail = item.prev;
        }
    }

    private void setHead(Item item) {
        item.next = head;
        item.prev = null;

        if (head != null)
            head.prev = item;
        head = item;

        if (tail == null)
            tail = head;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */


text:
UBUNTU_VERSION=$(cat /etc/apt/sources.list | grep ^deb | grep ubuntu | grep main | head -n 1 | cut -d\  -f 3)
case $UBUNTU_VERSION in
	precise)
		UBUNTU1X=ubuntu12
		;;
	trusty)
		UBUNTU1X=ubuntu14
		;;
	xenial)
		UBUNTU1X=ubuntu16
		;;
esac

echo "deb http://www.math.uiuc.edu/Macaulay2/Repositories/Ubuntu $UBUNTU_VERSION main" > /etc/apt/sources.list.d/macaulay2.list
apt-key adv --keyserver hkp://keys.gnupg.net --recv-key CD9C0E09B0C780943A1AD85553F8BD99F40DCB31

# echo "deb ftp://jim.mathematik.uni-kl.de/repo/$UBUNTU1X $UBUNTU_VERSION main" > /etc/apt/sources.list.d/singular.list
# wget -q ftp://jim.mathematik.uni-kl.de/repo/extra/gpg -O - | apt-key add -

# apt-add-repository -y ppa:aims/sagemath

add-apt-repository ppa:mc3man/trusty-media

apt-get update
apt-get dist-upgrade
apt-get -y install vim make gcc g++ git gdb m4 unzip libboost-dev ffmpeg zlib1g-dev criu
#apt-get -y install macaulay2 valgrind
#apt-get -y install sagemath-upstream-binary

#mkswap -f /dev/sdb
#swapon /dev/sdb

su vagrant << EOF
test -e groebner || git clone https://github.com/pichtj/groebner.git
EOF


text:
<?php

/**
 * @see CHttpRequest
 * @author Kevin Walter <walkev13@gmail.com>
 * @version 1.0
 */
class UBaseHtml extends CHtml
{
    /**
     * Slugify a string
     *
     * @param $text Text to slugify
     * @return string
     */
    public static function slugify($text)
    {
        // replace non letter or digits by -
        $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

        // trim
        $text = trim($text, '-');

        // transliterate
        if (function_exists('iconv')) {
            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        }

        // lowercase
        $text = strtolower($text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        if (empty($text)) {
            return 'n-a';
        }

        return $text;
    }

    /**
     * Get i18n label from id
     *
     * @param string $id I18n ID
     * @param bool $flag Display flag
     * @param bool $text Display text
     * @return string HTML
     */
    public static function labelI18n($id, $flag = true, $text = true)
    {
        return ''.($flag ? 'baseUrl . '/unitkit/images/i18n/' . $id . '.png" alt="" /> ' : '') .($text ? UI18n::labelI18n($id) : ''). '';
    }

    /**
     * Reduce a string
     *
     * @param string $string string to be transform
     * @param int $length number of maximum displayed characters
     * @return string
     */
    public static function textReduce($string, $length)
    {
        $string = html_entity_decode($string, ENT_COMPAT, 'UTF-8');
        return (strlen($string) > $length) ? htmlentities(mb_substr($string, 0, $length, 'UTF-8'), ENT_COMPAT, 'UTF-8') . '...' : $string;
    }

    /**
     * List data of advanced combobox
     *
     * @param string $modelName name of model
     * @param mixed $select array(text => , id =>, compare => true)
     * @param string $search search value
     * @param mixed $criteria array of criteria
     * @param int $cache cache duration (in seconds)
     * @return mixed
     */
    public static function listDataAdvCombobox($modelName, $select, $search, $criteria = array(), $cache = 0)
    {
        $model = new $modelName();
        $dbCriteria = $model->getDbCriteria();
        if (! isset($select['compare']) || $select['compare'] === true)
            $dbCriteria->compare($select['text'], $search, true);

        $tmp = $model->cache($cache/* cache duration */)->findAll(array_merge(array(
            'select' => $select['text'] . ', ' . $select['id']
        ), $criteria));

        $data = array();
        foreach ($tmp as $d)
            $data[] = array(
                'text' => $d->$select['text'],
                'id' => $d->$select['id']
            );

        return $data;
    }

    /**
     * List data of comboBox
     *
     * @param string $modelName name of model
     * @param mixed $select array(0 => id, 1 => text)
     * @param mixed $criteria array of criteria
     * @param int $cache cache duration (in seconds)
     * @return array
     */
    public static function listDataComboBox($modelName, $select, $criteria = array(), $cache = 0)
    {
        // init model
        $model = new $modelName();
        // get all data
        $data = $model->cache($cache/* cache duration */)->findAll(array_merge(array(
            'select' => implode(',', $select)
        ), $criteria));

        $result = array();
        foreach (CHtml::listData($data, $select[0], $select[1]) as $k => $v) {
            $result[$k] = $v;
        }

        return $result;
    }

    /**
     * Generates a text area input for a model attribute.
     * If the attribute has input error, the input field's CSS class will
     * be appended with {@link errorCss}.
     *
     * @param CModel $model the data model
     * @param string $attribute the attribute
     * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
     *        attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
     * @return string the generated text area
     * @see clientChange
     */
    public static function activeTextArea($model, $attribute, $htmlOptions = array())
    {
        if (! isset($htmlOptions['maxlength'])) {
            foreach ($model->getValidators($attribute) as $validator) {
                if ($validator instanceof CStringValidator && $validator->max !== null) {
                    $htmlOptions['maxlength'] = $validator->max;
                    break;
                }
            }
        } elseif ($htmlOptions['maxlength'] === false)
            unset($htmlOptions['maxlength']);

        self::resolveNameID($model, $attribute, $htmlOptions);
        self::clientChange('change', $htmlOptions);
        if ($model->hasErrors($attribute))
            self::addErrorCss($htmlOptions);
        if (isset($htmlOptions['value'])) {
            $text = $htmlOptions['value'];
            unset($htmlOptions['value']);
        } else {
            $text = self::resolveValue($model, $attribute);
        }

        return self::tag('textarea', $htmlOptions, isset($htmlOptions['encode']) && ! $htmlOptions['encode'] ? $text : self::encode($text));
    }

    /**
     * Displays a summary of validation errors for one or several models.
     *
     * @param mixed $model the models whose input errors are to be displayed. This can be either
     *        a single model or an array of models.
     * @param string $header a piece of HTML code that appears in front of the errors
     * @param string $footer a piece of HTML code that appears at the end of the errors
     * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
     *        A special option named 'firstError' is recognized, which when set true, will
     *        make the error summary to show only the first error message of each attribute.
     *        If this is not set or is false, all error messages will be displayed.
     *        This option has been available since version 1.1.3.
     * @return string the error summary. Empty if no errors are found.
     * @see CModel::getErrors
     * @see errorSummaryCss
     */
    public static function errorSummary($model, $header = null, $footer = null, $htmlOptions = array())
    {
        if ($header == null) {
            $header = '
' . Yii::t('yii', 'Please fix the following input errors:') . '
';
        }

        $modelClean = $model;

        // clean model
        if (is_array($modelClean)) {
            foreach($modelClean as $k => $m) {
                if( is_array($m)) {
                    unset($modelClean[$k]);
                }
            }
        }

        return parent::errorSummary($modelClean, $header, $footer, $htmlOptions);
    }

    /**
     * Generates a hyperlink that can be clicked to cause sorting.
     *
     * @param CSort $sort the current CSort instance
     * @param string $attribute the attribute name
     * @param string $label the attribute label
     * @return string
     */
    public static function createBSortLink(CSort $sort, $attribute, $label = null)
    {
        $class['link'] = '';
        $class['icon'] = 'glyphicon-sort-by-alphabet';

        $directions = $sort->getDirections();
        if (isset($directions[$attribute])) {
            $class['link'] = 'current-sort';
            if ($directions[$attribute])
                $class['icon'] = 'glyphicon-sort-by-alphabet-alt';
            $directions[$attribute] = ! $directions[$attribute];
        } else
            $directions[$attribute] = false;

        if ($label === null)
            $label = $sort->resolveLabel($attribute);

        return 'createUrl(Yii::app()->getController(), array(
            $attribute => $directions[$attribute]
        )) . '">

			' . $label . '
		';
    }
}


text: Serves as a starting point for creating PDF documents and charts using .NET Core 2.0 and SkiaSharp


text:
"""Script for unittesting the extstorage module"""

import os

from ganeti import errors
from ganeti.storage import extstorage

import testutils

class FakeStatResult(object):
  def __init__(self, st_mode):
    self.st_mode = st_mode
    self.st_rdev = 0

class TestExtStorageDevice(testutils.GanetiTestCase):
  """Testing case for extstorage.ExtStorageDevice"""

  def setUp(self):
    """Set up test data"""
    testutils.GanetiTestCase.setUp(self)
    self.name = "testname"
    self.uuid = "testuuid"
    self.test_unique_id = ("testdriver", "testvolumename")

  @testutils.patch_object(extstorage.ExtStorageDevice, "Attach")
  @testutils.patch_object(extstorage, "_ExtStorageAction")
  def testCreate(self, action_mock, attach_mock):
    action_mock.return_value = None
    attach_mock.return_value = True

    expected = extstorage.ExtStorageDevice(self.test_unique_id, [], 123, {}, {},
                                     name=self.name, uuid=self.uuid)
    got = extstorage.ExtStorageDevice.Create(self.test_unique_id, [], 123,
                                             None, {}, False, {},
                                             name=self.name, uuid=self.uuid)

    self.assertEqual(got, expected)

  def testCreateFailure(self):
    self.assertRaises(errors.ProgrammerError,
                      extstorage.ExtStorageDevice.Create,
                      self.test_unique_id, [], 123, None, {},
                      True, {}, name=self.name, uuid=self.uuid)

  @testutils.patch_object(extstorage.ExtStorageDevice, "_ExtStorageAction")
  @testutils.patch_object(os, "stat")
  def testAttach(self, stat_mock, action_mock):
    """Test for extstorage.ExtStorageDevice.Attach()"""
    stat_mock.return_value = FakeStatResult(0x6000) # bitmask for S_ISBLK
    action_mock.return_value = "/dev/path\nURI"
    dev = extstorage.ExtStorageDevice.__new__(extstorage.ExtStorageDevice)
    dev.unique_id = self.test_unique_id
    dev.ext_params = {}
    dev.name = self.name
    dev.uuid = self.uuid

    self.assertEqual(dev.Attach(), True)

  @testutils.patch_object(extstorage.ExtStorageDevice, "_ExtStorageAction")
  def testAttachNoUserspaceURI(self, action_mock):
    """Test for extstorage.ExtStorageDevice.Attach() with no userspace URI"""
    action_mock.return_value = ""
    dev = extstorage.ExtStorageDevice.__new__(extstorage.ExtStorageDevice)
    dev.unique_id = self.test_unique_id
    dev.ext_params = {}
    dev.name = self.name
    dev.uuid = self.uuid

    self.assertEqual(dev.Attach(), False)

  @testutils.patch_object(extstorage.ExtStorageDevice, "_ExtStorageAction")
  def testAttachWithUserspaceURI(self, action_mock):
    """Test for extstorage.ExtStorageDevice.Attach() with userspace URI"""
    action_mock.return_value = "\nURI"
    dev = extstorage.ExtStorageDevice.__new__(extstorage.ExtStorageDevice)
    dev.unique_id = self.test_unique_id
    dev.ext_params = {}
    dev.name = self.name
    dev.uuid = self.uuid

    self.assertEqual(dev.Attach(), True)

  @testutils.patch_object(extstorage.ExtStorageDevice, "_ExtStorageAction")
  @testutils.patch_object(os, "stat")
  def testAttachFailureNotBlockdev(self, stat_mock, action_mock):
    """Test for extstorage.ExtStorageDevice.Attach() failure, not a blockdev"""
    stat_mock.return_value = FakeStatResult(0x0)
    action_mock.return_value = "/dev/path\nURI"
    dev = extstorage.ExtStorageDevice.__new__(extstorage.ExtStorageDevice)
    dev.unique_id = self.test_unique_id
    dev.ext_params = {}
    dev.name = self.name
    dev.uuid = self.uuid

    self.assertEqual(dev.Attach(), False)

  @testutils.patch_object(extstorage.ExtStorageDevice, "_ExtStorageAction")
  @testutils.patch_object(os, "stat")
  def testAttachFailureNoDevice(self, stat_mock, action_mock):
    """Test for extstorage.ExtStorageDevice.Attach() failure, no device found"""
    stat_mock.side_effect = OSError("No device found")
    action_mock.return_value = "/dev/path\nURI"
    dev = extstorage.ExtStorageDevice.__new__(extstorage.ExtStorageDevice)
    dev.unique_id = self.test_unique_id
    dev.ext_params = {}
    dev.name = self.name
    dev.uuid = self.uuid

    self.assertEqual(dev.Attach(), False)

if __name__ == "__main__":
  testutils.GanetiTestProgram()


text:
using Hotcakes.Commerce.Controls;

namespace Hotcakes.Modules.Core.Admin.Controls
{
    partial class HtmlModifierField : ModificationControl<string>
    {
        public override string ApplyChanges(string item)
        {
            if (HtmlDropDownList.SelectedIndex == (int) Modes.SetTo)
            {
                return HtmlEditor.Text;
            }
            if (HtmlDropDownList.SelectedIndex == (int) Modes.AppendTo)
            {
                return item + HtmlEditor.Text;
            }
            return item;
        }

        private enum Modes
        {
            SetTo = 0,
            AppendTo = 1
        }
    }
}


text:
- **класс** `Key` (`php\crypto\Key`)
- **пакет** `crypto`
- **исходники** `php/crypto/Key.php`

**Описание**

Class CryptoKey

---

#### Методы

- `->`[`__construct()`](#method-__construct) - _constructor._
- `->`[`getAlgorithm()`](#method-getalgorithm)
- `->`[`getFormat()`](#method-getformat)
- `->`[`getEncoded()`](#method-getencoded)

---
# Методы

### __construct()
```php
__construct(string $key, string $algorithm): void
```
constructor.

---

### getAlgorithm()
```php
getAlgorithm(): string
```

---

### getFormat()
```php
getFormat(): string
```

---

### getEncoded()
```php
getEncoded(): string
```


text:
"""
Container for fieldlines in three-dimensional magnetic skeleton
"""
import numpy as np
from scipy.interpolate import splev, splprep, interp1d
import astropy.units as u
from astropy.coordinates import SkyCoord
import asdf
import zarr

from synthesizAR import Loop
from synthesizAR.visualize import plot_fieldlines

__all__ = ['Skeleton']

class Skeleton(object):
    """
    Construct magnetic field skeleton fieldlines

    Parameters
    ----------
    loops : `list`
        List of `Loop` objects

    Examples
    --------
    >>> import synthesizAR
    >>> import astropy.units as u
    >>> loop = synthesizAR.Loop('loop', SkyCoord(x=[1,4]*u.Mm, y=[2,5]*u.Mm, z=[3,6]*u.Mm,frame='heliographic_stonyhurst', representation_type='cartesian'), [1e2,1e3] * u.G)
    >>> field = synthesizAR.Skeleton([loop,])
    """

    def __init__(self, loops):
        self.loops = loops

    @classmethod
    def from_coordinates(cls, coordinates, field_strengths=None, **kwargs):
        """
        Construct `Skeleton` from list of coordinates and field strengths

        Parameters
        ----------
        coordinates : `list`
            List of `~astropy.coordinates.SkyCoord` loop coordinates
        field_strengths : `list`
            List of `~astropy.units.Quantity` scalar magnetic field strength along the loop
        """
        loops = []
        if field_strengths is None:
            field_strengths = len(coordinates) * [None]
        for i, (coord, fs) in enumerate(zip(coordinates, field_strengths)):
            loops.append(Loop(f'loop{i:06d}', coord, field_strength=fs, **kwargs))
        return cls(loops)

    def __repr__(self):
        return f'''synthesizAR Skeleton Object
------------------------
Number of loops: {len(self.loops)}'''

    def to_asdf(self, filename):
        """
        Serialize this instance of `Skeleton` to an ASDF file
        """
        tree = {}
        for l in self.loops:
            tree[l.name] = {
                'field_strength': l.field_strength,
                'coordinate': l.coordinate,
                'cross_sectional_area': l.cross_sectional_area,
                'model_results_filename': l.model_results_filename,
            }
        with asdf.AsdfFile(tree) as asdf_file:
            asdf_file.write_to(filename)

    @classmethod
    def from_asdf(cls, filename):
        """
        Restore a `Skeleton` instance from an ASDF file

        Examples
        --------
        >>> import synthesizAR
        >>> restored_field = synthesizAR.Skeleton.from_asdf('/path/to/skeleton.asdf') # doctest: +SKIP
        """
        exclude_keys = ['asdf_library', 'history']
        loops = []
        with asdf.open(filename, mode='r', copy_arrays=True) as af:
            for k in af.keys():
                if k in exclude_keys:
                    continue
                model_results_filename = af.tree[k].get('model_results_filename', None)
                cross_sectional_area = af.tree[k].get('cross_sectional_area', None)
                loops.append(Loop(
                    k,
                    SkyCoord(af.tree[k]['coordinate']),
                    af.tree[k]['field_strength'],
                    cross_sectional_area=cross_sectional_area,
                    model_results_filename=model_results_filename,
                ))
        return cls(loops)

    @u.quantity_input
    def refine_loops(self, delta_s: u.cm):
        """
        Interpolate loop coordinates and field strengths to a specified spatial resolution
        and return a new `Skeleton` object.

        This can be important in order to ensure that an adequate number of points are used
        to represent each fieldline when binning intensities onto the instrument grid.
        """
        new_loops = []
        for l in self.loops:
            _l = self.refine_loop(l, delta_s)
            new_loops.append(_l)

        return Skeleton(new_loops)

    @staticmethod
    @u.quantity_input
    def refine_loop(loop, delta_s: u.cm):
        try:
            tck, _ = splprep(loop.coordinate.cartesian.xyz.value,
                             u=loop.field_aligned_coordinate_norm)
            new_s = np.arange(0, loop.length.to(u.Mm).value, delta_s.to(u.Mm).value) * u.Mm
            x, y, z = splev((new_s/loop.length).decompose(), tck)
        except (ValueError, TypeError) as e:
            raise Exception(f'Failed to refine {loop.name}') from e
        unit = loop.coordinate.cartesian.xyz.unit
        new_coord = SkyCoord(x=x*unit,
                             y=y*unit,
                             z=z*unit,
                             frame=loop.coordinate.frame,
                             representation_type=loop.coordinate.representation_type)
        f_B = interp1d(loop.field_aligned_coordinate.to(u.Mm), loop.field_strength)
        new_field_strength = f_B(new_s.to(u.Mm)) * loop.field_strength.unit
        f_A = interp1d(loop.field_aligned_coordinate.to(u.Mm), loop.cross_sectional_area)
        new_area = f_A(new_s.to(u.Mm)) * loop.cross_sectional_area.unit
        return Loop(loop.name,
                    new_coord,
                    field_strength=new_field_strength,
                    cross_sectional_area=new_area,
                    model_results_filename=loop.model_results_filename)

    @property
    def all_coordinates(self):
        """
        Coordinates for all loops in the skeleton.

        .. note:: This should be treated as a collection of points and NOT a
                  continuous structure.
        """
        return SkyCoord([l.coordinate for l in self.loops],
                        frame=self.loops[0].coordinate.frame,
                        representation_type=self.loops[0].coordinate.representation_type)

    @property
    def all_coordinates_centers(self):
        """
        Coordinates for all grid cell centers of all loops in the skeleton

        .. note:: This should be treated as a collection of points and NOT a
                  continuous structure.
        """
        return SkyCoord([l.coordinate_center for l in self.loops],
                        frame=self.loops[0].coordinate_center.frame,
                        representation_type=self.loops[0].coordinate_center.representation_type)

    def peek(self, **kwargs):
        """
        Plot loop coordinates on the solar disk.

        See Also
        --------
        synthesizAR.visualize.plot_fieldlines
        """
        plot_fieldlines(*[_.coordinate for _ in self.loops], **kwargs)

    def configure_loop_simulations(self, interface, **kwargs):
        """
        Configure hydrodynamic simulations for each loop object
        """
        for loop in self.loops:
            interface.configure_input(loop, **kwargs)

    @staticmethod
    def _load_loop_simulation(loop, root=None, interface=None):
        # Load in parameters from interface
        (time, electron_temperature, ion_temperature,
            density, velocity) = interface.load_results(loop)
        # If no Zarr file is passed, set the quantites as attributes on the loops
        if root is None:
            loop._time = time
            loop._electron_temperature = electron_temperature
            loop._ion_temperature = ion_temperature
            loop._density = density
            loop._velocity = velocity
            loop._simulation_type = interface.name
        else:
            # Write to file
            grp = root.create_group(loop.name)
            grp.attrs['simulation_type'] = interface.name
            # time
            dset_time = grp.create_dataset('time', data=time.value)
            dset_time.attrs['unit'] = time.unit.to_string()
            # NOTE: Set the chunk size such that accessing all entries for a given timestep
            # is the most efficient pattern.
            chunks = (None,) + loop.field_aligned_coordinate_center.shape
            # electron temperature
            dset_electron_temperature = grp.create_dataset(
                'electron_temperature', data=electron_temperature.value, chunks=chunks)
            dset_electron_temperature.attrs['unit'] = electron_temperature.unit.to_string()
            # ion temperature
            dset_ion_temperature = grp.create_dataset(
                'ion_temperature', data=ion_temperature.value, chunks=chunks)
            dset_ion_temperature.attrs['unit'] = ion_temperature.unit.to_string()
            # number density
            dset_density = grp.create_dataset('density', data=density.value, chunks=chunks)
            dset_density.attrs['unit'] = density.unit.to_string()
            # field-aligned velocity
            dset_velocity = grp.create_dataset('velocity', data=velocity.value, chunks=chunks)
            dset_velocity.attrs['unit'] = velocity.unit.to_string()
            dset_velocity.attrs['note'] = 'Velocity in the field-aligned direction'

    def load_loop_simulations(self, interface, filename=None, **kwargs):
        """
        Load in loop parameters from hydrodynamic results.
        """
        if filename is None:
            root = None
        else:
            root = zarr.open(store=filename, mode='w', **kwargs)
        for loop in self.loops:
            loop.model_results_filename = filename
        try:
            import distributed
            client = distributed.get_client()
        except (ImportError, ValueError):
            for l in self.loops:
                self._load_loop_simulation(l, root=root, interface=interface)
        else:
            status = client.map(
                self._load_loop_simulation,
                self.loops,
                root=root,
                interface=interface,
            )
            return status

    def load_ionization_fractions(self, emission_model, interface=None, **kwargs):
        """
        Load the ionization fractions for each ion in the emission model.

        Parameters
        ----------
        emission_model : `synthesizAR.atomic.EmissionModel`
        interface : optional
            A model interface. Only necessary if loading the ionization fractions
            from the model

        If the model interface provides a method for loading the population fraction
        from the model, use that to get the population fractions. Otherwise, compute
        the ion population fractions in equilibrium. This should be done after
        calling `load_loop_simulations`.
        """
        from fiasco import Element
        from synthesizAR.atomic import equilibrium_ionization

        root = zarr.open(store=self.loops[0].model_results_filename, mode='a', **kwargs)
        # Check if we can load from the model
        FROM_MODEL = False
        if interface is not None and hasattr(interface, 'load_ionization_fraction'):
            frac = interface.load_ionization_fraction(self.loops[0], emission_model[0])
            # Some models may optionally output the ionization fractions such that
            # they will have this method, but it may not return anything
            if frac is not None:
                FROM_MODEL = True
        # Get the unique elements from all of our ions
        element_names = list(set([ion.element_name for ion in emission_model]))
        for el_name in element_names:
            el = Element(el_name, emission_model.temperature)
            ions = [i for i in emission_model if i.element_name == el.element_name]
            for loop in self.loops:
                chunks = (None,) + loop.field_aligned_coordinate_center.shape
                if not FROM_MODEL:
                    frac_el = equilibrium_ionization(el, loop.electron_temperature)
                if 'ionization_fraction' in root[loop.name]:
                    grp = root[f'{loop.name}/ionization_fraction']
                else:
                    grp = root[loop.name].create_group('ionization_fraction')
                for ion in ions:
                    if FROM_MODEL:
                        frac = interface.load_ionization_fraction(loop, ion)
                        desc = f'{ion.ion_name} ionization fraction computed by {interface.name}'
                    else:
                        frac = frac_el[:, :, ion.charge_state]
                        desc = f'{ion.ion_name} ionization fraction in equilibrium.'
                    dset = grp.create_dataset(f'{ion.ion_name}', data=frac, chunks=chunks)
                    dset.attrs['unit'] = ''
                    dset.attrs['description'] = desc


text:
class HardwareSerial : public Stream
{
public:
	inline void begin(uint32_t baud, uint8_t txen_pin=255) {
		_begin(((F_CPU / 8) + (baud / 2)) / baud, txen_pin);
	}
	void _begin(uint16_t baud_count, uint8_t pin);
	void end(void);
	void transmitterEnable(uint8_t pin);
	virtual int available(void);
	virtual int peek(void);
	virtual int read(void);
	virtual void flush(void);
	void clear(void);
#if ARDUINO >= 100
	virtual size_t write(uint8_t);
#else
	virtual void write(uint8_t);
#endif
	using Print::write;
};

extern HardwareSerial Serial1;

#endif


text:
import { Store } from './store';
import { map, distinctUntilChanged, takeWhile } from 'rxjs/operators';
import { ServiceLocator } from '../helpers/service-locator';
import { DataStrategy } from '@ng-state/data-strategy';

export class Select {
    static execute(store: Store<any>, path: any) {
        let mapped$: any;

        const dataStrategy = ServiceLocator.injector.get(DataStrategy);

        if (typeof path === 'object') {
            mapped$ = store.pipe(
                map((state: any) => dataStrategy.getIn(state, path)),
                takeWhile((state: any) => state !== undefined),
                distinctUntilChanged()
            );
        }
        else {
            throw new TypeError(`Unexpected type ${typeof path} in select operator,`
                + ` expected 'object' or 'function'`);
        }

        return mapped$;
    }
}

export interface SelectSignature {
  <T = any>(path: any[]): Store<T>;
}