text:
layout: post
title: Writing Custom Optimization Passes
date: 2019-05-22 13:39
comments: true
tags: polysemy, plugin, optimization
---

I've been paying a lot of attention to performance in [`polysemy`][polysemy].
Getting it to be fast [has been really hard][costly]. It's clearly possible, but
for the longest time I was afraid I'd need to fork the compiler. And that didn't
seem like a thing that would attract a large-user base.

[polysemy]: https://github.com/isovector/polysemy/
[costly]: /blog/freer-yet-too-costly/

For example, `polysemy` benefits greatly from a [late specialization
pass][specialization], and would benefit further from aggressive inlining
*after* the late specialization pass. Unfortunately, [GHC doesn't do any
inlining passes after `-flate-specialise`][passes], so it feels like we're stuck
on this front.

[specialization]: /blog/specialization/
[passes]: https://github.com/ghc/ghc/blob/master/compiler/simplCore/SimplCore.hs#L320-L345

Thankfully, the eternally helpful [mpickering][mpickering] pointed me at the
[GHC plugin interface][plugins], which has support for directing the optimizer
to do things it wouldn't usually.

[mpickering]: https://mpickering.github.io/
[plugins]: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/extending_ghc.html#writing-compiler-plugins

Today, I want to talk about how I made the [`polysemy-plugin`][polyplug] run two
optimizations that greatly benefit code written with `polysemy`.

[polyplug]: https://github.com/isovector/polysemy/tree/master/polysemy-plugin

The gist of writing a GHC plugin is to import `ghc:Plugins`, and to create an
exported top-level bind `plugin :: Plugin`. Other code can use this plugin by
specifying the `-fplugin=` option to point at this module.

## Installing Core ToDos

`Plugin`s have a field called `installCoreToDos` with type `[CommandLineOption]
-> [CoreToDo] -> CoreM [CoreToDo]`. A `CoreToDo` is GHC's oddly-named concept of
a compiler pass over Core. This function receives the list of `CoreToDo`s it was
planning to do, and you can change that list if you want.

By default there's a big flowchart of `CoreToDo`s that the compiler will run
through in order to compile a module. The optimization level (`-O`) effects
which passes get run, as do many of the [individual optimization
flags][optflags].

[optflags]: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/using-optimisation.html#f-platform-independent-flags

By attaching our extra optimization passes to the end of this list, we can make
GHC optimize harder than it usually would. But because most code *won't* benefit
from this extra work, we guard the new optimization passes behind two
conditions. The user must be compiling with optimizations turned on, and the
module being compiled must import `Polysemy`.

Checking for the optimization level is simple enough, we can pull it out of the
`DynFlags` (GHC's datatype that stores all of the crazy flags you might have
set):

```haskell
  dflags <- getDynFlags
  case optLevel dflags of
    0 -> -- corresponds to -O0
    1 -> -- corresponds to -O
    2 -> -- corresponds to -O2
```

Checking, however, for presence of the `Polysemy` module is less
straightforward. Honestly I'm not sure what the "correct" solution to this
problem is, but I'm pretty happy with the disgusting hack I came up with.

The `CoreM` monad (which is what you're running in when you install `CoreToDo`s)
doesn't exactly have [stellar documentation][corem]. It has access to the
`HscEnv`, which in turn has a `hsc_mod_graph :: ModuleGraph` --- which sounds
like the sort of thing that might contain the modules currently in scope.
Unfortunately this is not so; `hsc_mod_graph` contains the modules defined in
the *package* being defined.

[corem]: https://www.stackage.org/haddock/lts-13.21/ghc-8.6.5/CoreMonad.html#t:CoreM

If we could get our hands on the `ModGuts` (GHC's representation of a Haskell
module), we could inspect its `mg_deps :: Dependencies` field, which would
surely have what we need. Unfortunately, I couldn't find any easy way to get
access to the `ModGuts` in a `CoreM` without jumping through several hoops.

But one thing caught my eye! There is an operation `getVisibleOrphanMods ::
CoreM ModuleSet`, which after some investigation, turns out to contain any
module in scope (directly or otherwise) that defines an orphan instance.

It's disgusting, but I made an internal module in `polysemy` that contains the
following definitions:

```haskell
module Polysemy.Internal.PluginLookup where

class PluginLookup t
data Plugin
```

and the corresponding orphan instance in the module I wanted to track in my
plugin:

```haskell
{-# OPTIONS_GHC -fno-warn-orphans #-}

import Polysemy.Internal.PluginLookup

instance PluginLookup Plugin
```

I know, I know. But because the module that defines these things is internal,
there's no way for anyone else to define instances of this thing. So at least
it's a safe use of orphans.

Sure enough, this little gem is enough to get my module noticed by
`getVisibleOrphanMods`, and so I can check for the presence of my module via:

```haskell
  mods <- moduleSetElts <$> getVisibleOrphanMods
  if any ((== mkModuleName "Polysemy.Internal") . moduleName) mods
     then ...
```

And voila, we're now ready to install our extra `CoreToDo`s. In this case, I
just cargo-culted a few from GHC's existing passes list. Namely I added a
`CoreDoSpecialising`, a `CoreDoStaticArgs`, yet another `CoreDoSpecialising`,
and a bevvy of simplification passes. The result might be overkill, but it's
sufficient to massage [this scary core][bad] into [this][good] --- and get
roughly a 1000x runtime performance improvement in the process.

[bad]: https://gist.github.com/isovector/e4832512ec9c73bff94432a7a58470f9#file-t16473-dump-simpl
[good]: https://gist.github.com/isovector/e4832512ec9c73bff94432a7a58470f9#gistcomment-2883147

## Inlining Recursive Calls

But this lack of optimization passes wasn't the only thing slowly `polysemy`
down. The library depends on several library- and user-written functions that
are complicated and necessarily self-recursive.

GHC is understandably hesitant to inline recursive functions --- the result
would diverge --- but as a side-effect, it seems to refuse to optimize big
recursive functions whatsoever. For my purposes, this meant that most of the
crucial machinery in the library was being completely ignored by GHC's best
optimization pass.

I accidentally stumbled upon a fix. To illustrate, let's pretend like the
`factorial` function is my complicated self-recursive function. The optimizer
would refuse to fire when the function was written like this:

```haskell
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)
{-# INLINE factorial #-}
```

But, a minor syntactic tweak was enough to trick the compiler into optimizing
it:

```haskell
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial' (n - 1)
{-# INLINE factorial #-}

factorial' :: Int -> Int
factorial' = factorial
{-# NOINLINE factorial' #-}
```

Now `factorial` is no longer self-recursive. It's mutually recursive, and for
some reason, the `NO/INLINE` pragmas are enough to keep GHC off our back. This
is an easy fix, but it's annoying boilerplate. And I *hate* annoying
boilerplate.

Early versions of `polysemy` shipped with a function `inlineRecursiveCalls :: Q
[Dec] -> Q [Dec]` which would use Template Haskell to transform our slow,
self-recursive `factorial` above into the fast, mutually-exclusive version
below. While this worked, it was unsatisfactory; TH splices don't play nicely
with haddock or with text editors.

But this isn't something that regular users should need to care about!
Optimization concerns should lie solely in the responsibility of library-writers
--- not in their users. It seemed like a good opportunity to write a custom
optimization pass, and like any curious boy, I took it.

We can use the `CoreDoPluginPass :: String -> (ModGuts -> CoreM ModGuts) ->
CoreToDo` constructor to inject our own `ModGuts` transformation as an
optimization pass. Recall that `ModGuts` is GHC's definition of a module. For
our purposes, we're interested in its `mg_binds` field, which contains all of
the value-level things in the module.

A `mg_binds` is a `[Bind CoreBndr]`, and a `Bind CoreBndr` is a pair of a name
and its corresponding expression definition. More specifically, the definition
for `Bind` is:

```haskell
data Bind b = NonRec b (Expr b)
            | Rec [(b, (Expr b))]
```

A non-recursive binding is something like `x = 5`, while a recursive binding is
anything that is self- or mutually-recursive.

So, if we want to transform self-recursive calls into mutually-recursive calls,
we first need to identify if a definition is self-recursive. Fortunately, the
incredible `syb` library comes in handy here, as it lets us write small queries
that get lifted over the entire datatype.

We can write `containsName` using [`everywhere`][everywhere], [`mkQ`][mkQ] and the [`Any`][Any] monoid to
determine if the `CoreBndr` name is used anywhere in the `CoreExpr`[^1].

[everywhere]: https://www.stackage.org/haddock/lts-13.22/syb-0.7/Data-Generics-Schemes.html#v:everywhere
[mkQ]: https://www.stackage.org/haddock/lts-13.22/syb-0.7/Data-Generics-Aliases.html#v:mkQ
[Any]: https://www.stackage.org/haddock/lts-13.22/base-4.12.0.0/Data-Monoid.html#t:Any
[^1]: GHC has a bad habit of using type synonyms. A `CoreExpr` is just a `Expr CoreBndr`.

```haskell
containsName :: CoreBndr -> CoreExpr -> Bool
containsName n =
    getAny .
      everything
        (<>)
        (mkQ (Any False) matches)
  where
    matches :: CoreExpr -> Any
    matches (Var n') | n == n' = Any True
    matches _ = Any False
```

If `containsName b e` is `True` for any `(b, e)` in the `mg_binds`, then that
function is self-recursive. As such, we'd like to generate a new `NOINLINE` bind
for it, and then replace the original self-call to be to this new bind.

Replacing a call is just as easy as finding the recursion:

```haskell
replace :: CoreBndr -> CoreBndr -> CoreExpr -> CoreExpr
replace n n' = everywhere $ mkT go
  where
    go :: CoreExpr -> CoreExpr
    go v@(Var nn)
      | nn == n   = Var n'
      | otherwise = v
    go x = x
```

But creating the new binding is rather more work; we need to construct a new
name for it, and then fiddle with its `IdInfo` in order to set the inlining
information we'd like.

```haskell
loopbreaker :: Uniq -> CoreBndr -> CoreExpr -> [(Var, CoreExpr)]
loopbreaker newUniq n e =
  let Just info = zapUsageInfo $ idInfo n
      info' = setInlinePragInfo info alwaysInlinePragma
      n' = mkLocalVar
             (idDetails n)
             (mkInternalName newUniq (occName n) noSrcSpan)
             (idType n)
         $ setInlinePragInfo vanillaIdInfo neverInlinePragma
   in [ (lazySetIdInfo n info', replace n n' e)
      , (n', Var n)
      ]
```

First we use `zapUsageInfo` to make GHC forget that this binding is
self-recursive[^2], and then use `setInlinePragInfo` to spiritually inject a
`{-# INLINE n #-}` pragma onto it. We then construct a new name (a nontrivial
affair; `loopbreaker` above is simplified in order to get the new `Uniq` to
ensure our variable is hygienic), and replace the self-recursive call with a
call to the new name. Finally, we need to spit out the two resulting binds.

[^2]: I'm not sure this part is necessary, but it doesn't seem to hurt.

There's a little machinery to call `loopbreaker` on the `mg_guts`, but it's
uninteresting and this post is already long enough. If you're interested, the
[full code is available on Github][inline]. In total, it's a little less than
100 lines long; pretty good for adding a completely new optimization pass!

[inline]: https://github.com/isovector/polysemy/blob/f84dc2577524e8ba25c35b9b7479c63edd220a6e/polysemy-plugin/src/Polysemy/Plugin/InlineRecursiveCalls.hs

That's enough about writing plugins for improving performance; in the next post
we'll discuss typechecker plugins, and how they can be used to extend GHC's
constraint-solving machinery. Stay tuned!


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\ProfilPusatLatihanJurulatihSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Profil Pusat Latihan Jurulatihs';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Profil Pusat Latihan Jurulatih', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'profil_pusat_latihan_jurulatih_id',
            'profil_pusat_latihan_id',
            'jurulaith',
            'session_id',
            'created_by',
            // 'updated_by',
            // 'created',
            // 'updated',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace phpDocumentor\Plugin\LegacyNamespaceConverter\Tests;

use Mockery as m;
use phpDocumentor\Descriptor\DescriptorAbstract;
use phpDocumentor\Descriptor\ProjectDescriptorBuilder;
use phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter;

/**
 * Tests the phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter class.
 */
class LegacyNamespaceFilterTest extends \PHPUnit_Framework_TestCase
{
    /** @var LegacyNamespaceFilter */
    private $filter;

    /** @var ProjectDescriptorBuilder|m\MockInterface $builder */
    protected $builderMock;

    /**
     * Initializes the fixture and mocks any dependencies.
     *
     * @return void
     */
    public function setUp()
    {
        $this->builderMock = m::mock('phpDocumentor\Descriptor\ProjectDescriptorBuilder');
        $this->filter      = new LegacyNamespaceFilter($this->builderMock);
    }

    /**
     * @covers phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter::filter
     */
    public function testConvertClassNameWithUnderscoreWillBeConvertedToNamespace()
    {
        $descriptor = $this->createDescriptorMock();
        $descriptor->shouldReceive('getName')->andReturn('LegacyNamespace_ClassName');
        $descriptor->shouldReceive('getNamespace')->andReturn('\\');

        $descriptor->shouldReceive('setName')->with('ClassName')->once();
        $descriptor->shouldReceive('setNamespace')->with('\LegacyNamespace')->once();

        $this->filter->filter($descriptor);

        $this->assertTrue(true);
    }

    /**
     * @covers phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter::filter
     */
    public function testMultiLevelLegacyNamespace()
    {
        $descriptor = $this->createDescriptorMock();
        $descriptor->shouldReceive('getName')->andReturn('LegacyNamespace_Sub_ClassName');
        $descriptor->shouldReceive('getNamespace')->andReturn('\\');

        $descriptor->shouldReceive('setName')->with('ClassName')->once();
        $descriptor->shouldReceive('setNamespace')->with('\LegacyNamespace\Sub')->once();

        $this->filter->filter($descriptor);

        $this->assertTrue(true);
    }

    /**
     * @covers phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter::filter
     */
    public function testMixedNamespacesCanBeUnified()
    {
        $descriptor = $this->createDescriptorMock();
        $descriptor->shouldReceive('getName')->andReturn('LegacyNamespace_ClassName');
        $descriptor->shouldReceive('getNamespace')->andReturn('\\NewNamespace');

        $descriptor->shouldReceive('setName')->with('ClassName')->once();
        $descriptor->shouldReceive('setNamespace')->with('\\NewNamespace\\LegacyNamespace')->once();

        $this->filter->filter($descriptor);

        $this->assertTrue(true);
    }

    /**
     * @covers phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter::filter
     */
    public function testClassNameWithNewNamespaceWillNotBeModified()
    {
        $descriptor = $this->createDescriptorMock();
        $descriptor->shouldReceive('getName')->andReturn('ClassName');
        $descriptor->shouldReceive('getNamespace')->andReturn('\\NewNamespace');

        $descriptor->shouldReceive('setName')->with('ClassName')->once();
        $descriptor->shouldReceive('setNamespace')->with('\\NewNamespace')->once();

        $this->filter->filter($descriptor);

        $this->assertTrue(true);
    }

    /**
     * @covers phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter::filter
     */
    public function testClassNameWithEmptyNamespace()
    {
        $descriptor = $this->createDescriptorMock();
        $descriptor->shouldReceive('getName')->andReturn('ClassName');
        $descriptor->shouldReceive('getNamespace')->andReturn('\\');

        $descriptor->shouldReceive('setName')->with('ClassName')->once();
        $descriptor->shouldReceive('setNamespace')->with('\\')->once();

        $this->filter->filter($descriptor);

        $this->assertTrue(true);
    }

    /**
     * @covers phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter::filter
     */
    public function testPrefixedNamespace()
    {
        $this->filter->setNamespacePrefix('Vendor');

        $descriptor = $this->createDescriptorMock();
        $descriptor->shouldReceive('getName')->andReturn('ClassName');
        $descriptor->shouldReceive('getNamespace')->andReturn('');

        $descriptor->shouldReceive('setName')->with('ClassName')->once();
        $descriptor->shouldReceive('setNamespace')->with('\\Vendor')->once();

        $this->filter->filter($descriptor);

        $this->assertTrue(true);
    }

    /**
     * @covers phpDocumentor\Plugin\LegacyNamespaceConverter\LegacyNamespaceFilter::filter
     */
    public function testPrefixedNamespaceWithNamespacedClassWillNotBeModified()
    {
        $this->filter->setNamespacePrefix('Vendor');

        $descriptor = $this->createDescriptorMock();
        $descriptor->shouldReceive('getName')->andReturn('ClassName');
        $descriptor->shouldReceive('getNamespace')->andReturn('\\');

        $descriptor->shouldReceive('setName')->with('ClassName')->once();
        $descriptor->shouldReceive('setNamespace')->with('\\')->once();

        $this->filter->filter($descriptor);

        $this->assertTrue(true);
    }

    /**
     * Creates a mocked Descriptor.
     *
     * @return m\MockInterface|DescriptorAbstract
     */
    private function createDescriptorMock()
    {
        return m::mock('phpDocumentor\Descriptor\DescriptorAbstract');
    }
}


text:
using Caliburn.Micro;
using MyHoard.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyHoard.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        public MainPageViewModel(INavigationService navigationService, CollectionService collectionService) : base(navigationService,collectionService)
        {

        }
    }
}


text:
"""
The 'polyjit' experiment.

This experiment uses likwid to measure the performance of all binaries
when running with polyjit support enabled.
"""
import copy
import uuid
from abc import abstractmethod
from functools import partial
from os import path

from plumbum import local

from benchbuild.experiment import RuntimeExperiment
from benchbuild.experiments.compilestats import collect_compilestats
from benchbuild.utils.actions import (Any, Build, Clean, Configure, Download,
                                      Echo, MakeBuildDir, Prepare, RequireAll,
                                      Run)
from benchbuild.utils.cmd import rm, time  # pylint: disable=E0401

def run_raw(project, experiment, config, run_f, args, **kwargs):
    """
    Run the given binary wrapped with nothing.

    Args:
        project: The benchbuild.project.
        experiment: The benchbuild.experiment.
        config: The benchbuild.settings.config.
        run_f: The file we want to execute.
        args: List of arguments that should be passed to the wrapped binary.
        **kwargs: Dictionary with our keyword args. We support the following
            entries:

            project_name: The real name of our project. This might not
                be the same as the configured project name, if we got wrapped
                with ::benchbuild.project.wrap_dynamic
            has_stdin: Signals whether we should take care of stdin.
    """
    from benchbuild.utils.run import track_execution
    from benchbuild.utils.run import handle_stdin
    from benchbuild.settings import CFG

    CFG.update(config)
    project.name = kwargs.get("project_name", project.name)

    run_cmd = local[run_f]
    run_cmd = handle_stdin(run_cmd[args], kwargs)
    with track_execution(run_cmd, project, experiment) as run:
        run()

def run_with_papi(project, experiment, config, jobs, run_f, args, **kwargs):
    """
    Run the given file with PAPI support.

    This just runs the project as PAPI support should be compiled in
    already. If not, this won't do a lot.

    Args:
        project: The benchbuild.project.
        experiment: The benchbuild.experiment.
        config: The benchbuild.settings.config.
        jobs: Number of cores we should use for this exection.
        run_f: The file we want to execute.
        args: List of arguments that should be passed to the wrapped binary.
        **kwargs: Dictionary with our keyword args. We support the following
            entries:

            project_name: The real name of our project. This might not
                be the same as the configured project name, if we got wrapped
                with ::benchbuild.project.wrap_dynamic
            has_stdin: Signals whether we should take care of stdin.
    """
    from benchbuild.settings import CFG
    from benchbuild.utils.run import track_execution, handle_stdin
    from benchbuild.utils.db import persist_config

    CFG.update(config)
    project.name = kwargs.get("project_name", project.name)
    run_cmd = local[run_f]
    run_cmd = handle_stdin(run_cmd[args], kwargs)

    with local.env(POLLI_ENABLE_PAPI=1, OMP_NUM_THREADS=jobs):
        with track_execution(run_cmd, project, experiment) as run:
            run_info = run()

    persist_config(run_info.db_run, run_info.session,
                   {"cores": str(jobs)})

def run_with_likwid(project, experiment, config, jobs, run_f, args, **kwargs):
    """
    Run the given file wrapped by likwid.

    Args:
        project: The benchbuild.project.
        experiment: The benchbuild.experiment.
        config: The benchbuild.settings.config.
        jobs: Number of cores we should use for this exection.
        run_f: The file we want to execute.
        args: List of arguments that should be passed to the wrapped binary.
        **kwargs: Dictionary with our keyword args. We support the following
            entries:

            project_name: The real name of our project. This might not
                be the same as the configured project name, if we got wrapped
                with ::benchbuild.project.wrap_dynamic
            has_stdin: Signals whether we should take care of stdin.
    """
    from benchbuild.settings import CFG
    from benchbuild.utils.run import track_execution, handle_stdin
    from benchbuild.utils.db import persist_likwid, persist_config
    from benchbuild.likwid import get_likwid_perfctr

    CFG.update(config)
    project.name = kwargs.get("project_name", project.name)
    likwid_f = project.name + ".txt"

    for group in ["CLOCK"]:
        likwid_path = path.join(CFG["likwiddir"], "bin")
        likwid_perfctr = local[path.join(likwid_path, "likwid-perfctr")]
        run_cmd = \
            likwid_perfctr["-O", "-o", likwid_f, "-m",
                           "-C", "0-{0:d}".format(jobs),
                           "-g", group, run_f]
        run_cmd = handle_stdin(run_cmd[args], kwargs)

        with local.env(POLLI_ENABLE_LIKWID=1):
            with track_execution(run_cmd, project, experiment) as run:
                ri = run()

        likwid_measurement = get_likwid_perfctr(likwid_f)
        persist_likwid(run, ri.session, likwid_measurement)
        persist_config(run, ri.session, {
            "cores": str(jobs),
            "likwid.group": group
        })
        rm("-f", likwid_f)

def run_with_time(project, experiment, config, jobs, run_f, args, **kwargs):
    """
    Run the given binary wrapped with time.

    Args:
        project: The benchbuild.project.
        experiment: The benchbuild.experiment.
        config: The benchbuild.settings.config.
        jobs: Number of cores we should use for this exection.
        run_f: The file we want to execute.
        args: List of arguments that should be passed to the wrapped binary.
        **kwargs: Dictionary with our keyword args. We support the following
            entries:

            project_name: The real name of our project. This might not
                be the same as the configured project name, if we got wrapped
                with ::benchbuild.project.wrap_dynamic
            has_stdin: Signals whether we should take care of stdin.
    """
    from benchbuild.utils.run import track_execution, fetch_time_output
    from benchbuild.settings import CFG
    from benchbuild.utils.db import persist_time, persist_config

    CFG.update(config)
    project.name = kwargs.get("project_name", project.name)
    timing_tag = "BB-JIT: "

    may_wrap = kwargs.get("may_wrap", True)

    run_cmd = local[run_f]
    run_cmd = run_cmd[args]
    if may_wrap:
        run_cmd = time["-f", timing_tag + "%U-%S-%e", run_cmd]

    with local.env(OMP_NUM_THREADS=str(jobs),
                   POLLI_LOG_FILE=CFG["slurm"]["extra_log"].value()):
        with track_execution(run_cmd, project, experiment) as run:
            ri = run()

        if may_wrap:
            timings = fetch_time_output(
                timing_tag, timing_tag + "{:g}-{:g}-{:g}",
                ri.stderr.split("\n"))
            if timings:
                persist_time(ri.db_run, ri.session, timings)
    persist_config(ri.db_run, ri.session, {"cores": str(jobs-1),
                                           "cores-config": str(jobs),
                                           "recompilation": "enabled"})
    return ri

def run_without_recompile(project, experiment, config, jobs, run_f,
                          args, **kwargs):
    """
    Run the given binary wrapped with time.

    Args:
        project: The benchbuild.project.
        experiment: The benchbuild.experiment.
        config: The benchbuild.settings.config.
        jobs: Number of cores we should use for this exection.
        run_f: The file we want to execute.
        args: List of arguments that should be passed to the wrapped binary.
        **kwargs: Dictionary with our keyword args. We support the following
            entries:

            project_name: The real name of our project. This might not
                be the same as the configured project name, if we got wrapped
                with ::benchbuild.project.wrap_dynamic
            has_stdin: Signals whether we should take care of stdin.
    """
    from benchbuild.utils.run import track_execution, fetch_time_output
    from benchbuild.settings import CFG
    from benchbuild.utils.db import persist_time, persist_config

    CFG.update(config)
    project.name = kwargs.get("project_name", project.name)
    timing_tag = "BB-JIT: "

    may_wrap = kwargs.get("may_wrap", True)

    run_cmd = local[run_f]
    run_cmd = run_cmd[args]
    if may_wrap:
        run_cmd = time["-f", timing_tag + "%U-%S-%e", run_cmd]

    with local.env(OMP_NUM_THREADS=str(jobs),
                   POLLI_LOG_FILE=CFG["slurm"]["extra_log"].value()):
        with track_execution(run_cmd, project, experiment) as run:
            ri = run()

        if may_wrap:
            timings = fetch_time_output(
                timing_tag, timing_tag + "{:g}-{:g}-{:g}",
                ri.stderr.split("\n"))
            if timings:
                persist_time(ri.db_run, ri.session, timings)
    persist_config(ri.db_run, ri.session, {"cores": str(jobs-1),
                                           "cores-config": str(jobs),
                                           "recompilation": "disabled"})
    return ri

def run_with_perf(project, experiment, config, jobs, run_f, args, **kwargs):
    """
    Run the given binary wrapped with time.

    Args:
        project: The benchbuild.project.
        experiment: The benchbuild.experiment.
        config: The benchbuild.settings.config.
        jobs: Number of cores we should use for this exection.
        run_f: The file we want to execute.
        args: List of arguments that should be passed to the wrapped binary.
        **kwargs: Dictionary with our keyword args. We support the following
            entries:

            project_name: The real name of our project. This might not
                be the same as the configured project name, if we got wrapped
                with ::benchbuild.project.wrap_dynamic
            has_stdin: Signals whether we should take care of stdin.
    """
    from benchbuild.settings import CFG
    from benchbuild.utils.run import track_execution, handle_stdin
    from benchbuild.utils.db import persist_perf, persist_config
    from benchbuild.utils.cmd import perf

    CFG.update(config)
    project.name = kwargs.get("project_name", project.name)
    run_cmd = local[run_f]
    run_cmd = handle_stdin(run_cmd[args], kwargs)
    run_cmd = perf["record", "-q", "-F", 6249, "-g", run_cmd]

    with local.env(OMP_NUM_THREADS=str(jobs)):
        with track_execution(run_cmd, project, experiment) as run:
            ri = run(retcode=None)

        fg_path = path.join(CFG["src_dir"], "extern/FlameGraph")
        if path.exists(fg_path):
            sc_perf = local[path.join(fg_path, "stackcollapse-perf.pl")]
            flamegraph = local[path.join(fg_path, "flamegraph.pl")]

            fold_cmd = ((perf["script"] | sc_perf) > run_f + ".folded")
            graph_cmd = (flamegraph[run_f + ".folded"] > run_f + ".svg")

            fold_cmd()
            graph_cmd()
            persist_perf(ri.db_run, ri.session, run_f + ".svg")
            persist_config(ri.db_run, ri.session, {"cores": str(jobs)})

class PolyJIT(RuntimeExperiment):
    """The polyjit experiment."""

    @classmethod
    def init_project(cls, project):
        """
        Execute the benchbuild experiment.

        We perform this experiment in 2 steps:
            1. with likwid disabled.
            2. with likwid enabled.

        Args:
            project: The project we initialize.

        Returns:
            The initialized project.
        """
        project.ldflags += ["-lpjit", "-lgomp"]
        project.cflags = ["-fno-omit-frame-pointer",
                          "-rdynamic",
                          "-Xclang", "-load", "-Xclang", "LLVMPolyJIT.so",
                          "-O3", "-mllvm", "-jitable",
                          "-mllvm", "-polli-allow-modref-calls",
                          "-mllvm", "-polli"]
        return project

    @abstractmethod
    def actions_for_project(self, p):
        pass

class PolyJITFull(PolyJIT):
    """
    An experiment that executes all projects with PolyJIT support.

    This is our default experiment for speedup measurements.
    """

    NAME = "pj"

    def actions_for_project(self, p):
        from benchbuild.settings import CFG

        p.cflags = ["-O3", "-fno-omit-frame-pointer"]

        actns = []
        rawp = copy.deepcopy(p)
        rawp.run_uuid = uuid.uuid4()
        rawp.runtime_extension = partial(run_with_time, rawp, self, CFG, 1)

        actns.append(RequireAll([
            Echo("========= START: RAW Baseline"),
            MakeBuildDir(rawp),
            Prepare(rawp),
            Download(rawp),
            Configure(rawp),
            Build(rawp),
            Run(rawp),
            Clean(rawp),
            Echo("========= END: RAW Baseline")
        ]))

        jitp = copy.deepcopy(p)
        jitp = PolyJIT.init_project(jitp)
        norecomp = copy.deepcopy(jitp)
        norecomp.cflags += ["-mllvm", "-no-recompilation"]

        for i in range(2, int(str(CFG["jobs"])) + 1):
            cp = copy.deepcopy(norecomp)
            cp.run_uuid = uuid.uuid4()
            cp.runtime_extension = partial(run_without_recompile,
                                           cp, self, CFG, i)

            actns.append(RequireAll([
                Echo("========= START: JIT No Recomp - Cores: {0}".format(i)),
                MakeBuildDir(cp),
                Prepare(cp),
                Download(cp),
                Configure(cp),
                Build(cp),
                Run(cp),
                Clean(cp),
                Echo("========= END: JIT No Recomp - Cores: {0}".format(i))
            ]))

        for i in range(2, int(str(CFG["jobs"])) + 1):
            cp = copy.deepcopy(jitp)
            cp.run_uuid = uuid.uuid4()
            cp.runtime_extension = partial(run_with_time, cp, self, CFG, i)

            actns.append(RequireAll([
                Echo("========= START: JIT - Cores: {0}".format(i)),
                MakeBuildDir(cp),
                Prepare(cp),
                Download(cp),
                Configure(cp),
                Build(cp),
                Run(cp),
                Clean(cp),
                Echo("========= END: JIT - Cores: {0}".format(i))
            ]))
        return [Any(actns)]

class PJITRaw(PolyJIT):
    """
    An experiment that executes all projects with PolyJIT support.

    This is our default experiment for speedup measurements.
    """

    NAME = "pj-raw"

    def actions_for_project(self, p):
        from benchbuild.settings import CFG

        p = PolyJIT.init_project(p)

        actns = []
        for i in range(2, int(str(CFG["jobs"])) + 1):
            cp = copy.deepcopy(p)
            cp.run_uuid = uuid.uuid4()
            cp.cflags += ["-mllvm", "-polly-num-threads={0}".format(i)]
            cp.runtime_extension = partial(run_with_time, cp, self, CFG, i)

            actns.extend([
                MakeBuildDir(cp),
                Echo("{0} core configuration. Configure & Compile".format(i)),
                Prepare(cp),
                Download(cp),
                Configure(cp),
                Build(cp),
                Echo("{0} core configuration. Run".format(i)),
                Run(cp),
                Clean(cp)
            ])
        return actns

class PJITperf(PolyJIT):
    """An experiment that uses linux perf tools to generate flamegraphs."""

    NAME = "pj-perf"

    def actions_for_project(self, p):
        from benchbuild.settings import CFG

        p = PolyJIT.init_project(p)

        actns = []
        for i in range(1, int(str(CFG["jobs"])) + 1):
            cp = copy.deepcopy(p)
            cp.run_uuid = uuid.uuid4()
            cp.runtime_extension = partial(run_with_perf, cp, self, CFG, i)

            actns.extend([
                MakeBuildDir(cp),
                Echo("perf: {0} core configuration. Configure & Compile"
                     .format(i)),
                Prepare(cp),
                Download(cp),
                Configure(cp),
                Build(cp),
                Echo("perf: {0} core configuration. Run".format(i)),
                Run(cp),
                Clean(cp)
            ])
        return actns

class PJITlikwid(PolyJIT):
    """
    An experiment that uses likwid's instrumentation API for profiling.

    This instruments all projects with likwid instrumentation API calls
    in key regions of the JIT.

    This allows for arbitrary profiling of PolyJIT's overhead and run-time
    """

    NAME = "pj-likwid"

    def actions_for_project(self, p):
        from benchbuild.settings import CFG

        p = PolyJIT.init_project(p)
        p.cflags = ["-DLIKWID_PERFMON"] + p.cflags

        actns = []
        for i in range(1, int(str(CFG["jobs"])) + 1):
            cp = copy.deepcopy(p)
            cp.run_uuid = uuid.uuid4()
            cp.runtime_extension = partial(run_with_likwid, cp, self, CFG, i)

            actns.append(RequireAll([
                MakeBuildDir(cp),
                Echo("likwid: {0} core configuration. Configure & Compile"
                     .format(i)),
                Prepare(cp),
                Download(cp),
                Configure(cp),
                Build(cp),
                Echo("likwid: {0} core configuration. Run".format(i)),
                Run(cp),
                Clean(cp)]))
        return actns

class PJITRegression(PolyJIT):
    """
    This experiment will generate a series of regression tests.

    This can be used every time a new revision is produced for PolyJIT, as
    it will automatically collect any new SCoPs detected, using the JIT.

    The collection of the tests itself is intgrated into the JIT, so this
    experiment looks a lot like a RAW experiment, except we don't run
    anything.
    """

    NAME = "pj-collect"

    def actions_for_project(self, p):
        from benchbuild.settings import CFG
        from benchbuild.utils.run import track_execution

        def _track_compilestats(project, experiment, config, clang,
                                **kwargs):
            """Compile the project and track the compilestats."""
            from benchbuild.settings import CFG
            from benchbuild.utils.run import handle_stdin

            CFG.update(config)
            clang = handle_stdin(clang["-mllvm", "-polli-collect-modules"],
                                 kwargs)
            with track_execution(clang, project, experiment) as run:
                run()

        p = PolyJIT.init_project(p)
        p.cflags = ["-DLIKWID_PERFMON"] + p.cflags
        p.compiler_extension = partial(_track_compilestats, p, self, CFG)

        actns = [
            MakeBuildDir(p),
            Echo("{}: Configure...".format(self.name)),
            Prepare(p),
            Download(p),
            Configure(p),
            Echo("{}: Building...".format(self.name)),
            Build(p),
            Clean(p)
        ]
        return actns

class Compilestats(PolyJIT):
    """Gather compilestats, with enabled JIT."""

    NAME = "pj-cs"

    def actions_for_project(self, p):
        from benchbuild.settings import CFG

        p = PolyJIT.init_project(p)
        p.compiler_extension = partial(collect_compilestats, p, self, CFG)

        actns = [
            MakeBuildDir(p),
            Echo("{}: Configure...".format(self.name)),
            Prepare(p),
            Download(p),
            Configure(p),
            Echo("{}: Building...".format(self.name)),
            Build(p),
            Clean(p)
        ]
        return actns

class PJITpapi(PolyJIT):
    """
    Experiment that uses PolyJIT's instrumentation facilities.

    This uses PolyJIT to instrument all projects with libPAPI based
    region measurements. In the end the region measurements are
    aggregated and metrics like the dynamic SCoP coverage are extracted.

    This uses the same set of flags as all other PolyJIT based experiments.
    """

    NAME = "pj-papi"

    def actions(self):
        """Do the postprocessing, after all projects are done."""
        actions = super(PJITpapi, self).actions()
        from benchbuild.utils.actions import Step

        class Analyze(Step):
            NAME = "ANALYZE"
            DESCRIPTION = "Analyze the experiment after completion."

        def run_pprof_analyze():
            from benchbuild.settings import CFG
            from benchbuild.utils.cmd import pprof_analyze

            with local.env(BB_EXPERIMENT_ID=str(CFG["experiment_id"]),
                           BB_EXPERIMENT=self.name,
                           BB_USE_DATABASE=1,
                           BB_USE_FILE=0,
                           BB_USE_CSV=0):
                pprof_analyze()

        actions.append(
            Analyze(self, run_pprof_analyze)
        )

        return actions

    def actions_for_project(self, p):
        from benchbuild.settings import CFG

        p = PolyJIT.init_project(p)
        p.cflags = ["-mllvm", "-instrument"] + p.cflags
        p.ldflags = p.ldflags + ["-lbenchbuild"]

        actns = []
        for i in range(1, int(str(CFG["jobs"])) + 1):
            cp = copy.deepcopy(p)
            cp.compiler_extension = partial(collect_compilestats, cp, self,
                                            CFG)
            cp.runtime_extension = partial(run_with_papi, p, self, CFG, i)
            actns.extend([
                MakeBuildDir(cp),
                Echo("{}: Configure...".format(self.name)),
                Prepare(cp),
                Download(cp),
                Configure(cp),
                Echo("{}: Building...".format(self.name)),
                Build(cp),
                Clean(cp)
            ])

        return actns


text: Implementation of OSGi service code should go here for the interface in package jumpmicro


text:
The maze API is very simple - only one function is provided to set wall values.
Note that you have to be careful to always set both sides of a wall to the same
value, otherwise the maze will fail validation.

```c++
// Logging functions
void debug(const std::string& str);
void info(const std::string& str);
void warn(const std::string& str);
void error(const std::string& str);

// Misc functions
double getRandom(); // Returns a random number in [0.0, 1.0)
void quit(); // Forces the simulator to exit

// Sets the wall
void setWall(int x, int y, char direction, bool wallExists);
```


text:
package ortc

type onMessageChannel struct {
	Sender  *OrtcClient
	Channel string
	Message string
}

type channelSubscription struct {
	isSubscribing        bool
	isSubscribed         bool
	subscribeOnReconnect bool
	onMessage            chan onMessageChannel
}

func newChannelSubscription(subscribeOnReconnected bool) *channelSubscription {
	chanSub := new(channelSubscription)
	chanSub.subscribeOnReconnect = subscribeOnReconnected
	chanSub.onMessage = make(chan onMessageChannel)
	chanSub.isSubscribed = false
	chanSub.isSubscribing = false
	return chanSub
}

func (c *channelSubscription) subscribing() bool {
	return c.isSubscribing
}

func (c *channelSubscription) subscribed() bool {
	return c.isSubscribed
}

func (c *channelSubscription) subscribeOnReconnected() bool {
	return c.subscribeOnReconnect
}


text:
import { isElementInViewport } from '../utils';

export function* scrollToElement(element: HTMLElement) {
  if (element && !isElementInViewport(element)) {
    yield element.scrollIntoView({ block: 'start', behavior: 'smooth' });
  }
}


text:
namespace web_app {

ManifestUpdateManager::ManifestUpdateManager() = default;

ManifestUpdateManager::~ManifestUpdateManager() = default;

void ManifestUpdateManager::SetSubsystems(
    AppRegistrar* registrar,
    AppIconManager* icon_manager,
    WebAppUiManager* ui_manager,
    InstallManager* install_manager,
    SystemWebAppManager* system_web_app_manager) {
  registrar_ = registrar;
  icon_manager_ = icon_manager;
  ui_manager_ = ui_manager;
  install_manager_ = install_manager;
  system_web_app_manager_ = system_web_app_manager;
}

void ManifestUpdateManager::Start() {
  registrar_observer_.Add(registrar_);
}

void ManifestUpdateManager::Shutdown() {
  registrar_observer_.RemoveAll();
}

void ManifestUpdateManager::MaybeUpdate(const GURL& url,
                                        const AppId& app_id,
                                        content::WebContents* web_contents) {
  if (!base::FeatureList::IsEnabled(features::kDesktopPWAsLocalUpdating))
    return;

  if (app_id.empty() || !registrar_->IsLocallyInstalled(app_id)) {
    NotifyResult(url, ManifestUpdateResult::kNoAppInScope);
    return;
  }

  if (system_web_app_manager_->IsSystemWebApp(app_id)) {
    NotifyResult(url, ManifestUpdateResult::kAppIsSystemWebApp);
    return;
  }

  if (registrar_->IsPlaceholderApp(app_id)) {
    NotifyResult(url, ManifestUpdateResult::kAppIsPlaceholder);
    return;
  }

  if (base::Contains(tasks_, app_id))
    return;

  if (!MaybeConsumeUpdateCheck(url.GetOrigin(), app_id)) {
    NotifyResult(url, ManifestUpdateResult::kThrottled);
    return;
  }

  tasks_.insert_or_assign(
      app_id, std::make_unique<ManifestUpdateTask>(
                  url, app_id, web_contents,
                  base::Bind(&ManifestUpdateManager::OnUpdateStopped,
                             base::Unretained(this)),
                  hang_update_checks_for_testing_, *registrar_, *icon_manager_,
                  ui_manager_, install_manager_));
}

// AppRegistrarObserver:
void ManifestUpdateManager::OnWebAppUninstalled(const AppId& app_id) {
  auto it = tasks_.find(app_id);
  if (it != tasks_.end()) {
    NotifyResult(it->second->url(), ManifestUpdateResult::kAppUninstalled);
    tasks_.erase(it);
  }
  DCHECK(!tasks_.contains(app_id));
  last_update_check_.erase(app_id);
}

bool ManifestUpdateManager::MaybeConsumeUpdateCheck(const GURL& origin,
                                                    const AppId& app_id) {
  base::Optional<base::Time> last_check_time =
      GetLastUpdateCheckTime(origin, app_id);
  if (!last_check_time)
    return false;

  base::Time now = time_override_for_testing_.value_or(base::Time::Now());
  // Throttling updates to at most once per day is consistent with Android.
  // See |UPDATE_INTERVAL| in WebappDataStorage.java.
  constexpr base::TimeDelta kDelayBetweenChecks = base::TimeDelta::FromDays(1);
  if (now < *last_check_time + kDelayBetweenChecks)
    return false;

  SetLastUpdateCheckTime(origin, app_id, now);
  return true;
}

base::Optional<base::Time> ManifestUpdateManager::GetLastUpdateCheckTime(
    const GURL& origin,
    const AppId& app_id) const {
  auto it = last_update_check_.find(app_id);
  return it != last_update_check_.end() ? it->second : base::Time();
}

void ManifestUpdateManager::SetLastUpdateCheckTime(const GURL& origin,
                                                   const AppId& app_id,
                                                   base::Time time) {
  last_update_check_[app_id] = time;
}

void ManifestUpdateManager::OnUpdateStopped(const ManifestUpdateTask& task,
                                            ManifestUpdateResult result) {
  DCHECK_EQ(&task, tasks_[task.app_id()].get());
  NotifyResult(task.url(), result);
  tasks_.erase(task.app_id());
}

void ManifestUpdateManager::SetResultCallbackForTesting(
    ResultCallback callback) {
  DCHECK(result_callback_for_testing_.is_null());
  result_callback_for_testing_ = std::move(callback);
}

void ManifestUpdateManager::NotifyResult(const GURL& url,
                                         ManifestUpdateResult result) {
  // Don't log kNoAppInScope because it will be far too noisy (most page loads
  // will hit it).
  if (result != ManifestUpdateResult::kNoAppInScope) {
    UMA_HISTOGRAM_ENUMERATION("Webapp.Update.ManifestUpdateResult", result);
  }
  if (result_callback_for_testing_)
    std::move(result_callback_for_testing_).Run(url, result);
}

}  // namespace web_app


text:
<?php

/* ascio.whois 1.0	David Saez Padros <david@ols.es> */

if (!defined('__ASCIO_HANDLER__'))
	define('__ASCIO_HANDLER__', 1);

require_once('whois.parser.php');

class ascio_handler
	{

	function parse($data_str, $query)
		{

		$items = array(
                'owner' => 'Registrant:',
                'admin' => 'Administrative ',
                'tech' => 'Technical ',
                'domain.name' => 'Domain name:',
                'domain.nserver.' => 'Domain servers in listed order:',
                'domain.created' => 'Record created:',
                'domain.expires' => 'Record expires:',
                'domain.changed' => 'Record last updated:'
		            );

		return easy_parser($data_str, $items, 'ymd',false,false,true);
		}
	}
?>


text:
Redis is the first supported storage backend for hyrax. Check the
[redis](http://redis.io) site for more information on the server itself. It's
the backend that's most conducive to hyrax, since hyrax was made with it in
mind.

Currently only a single redis node is usable, redis cluster will be supported in
the future (once it's actually released for production) and will be another
backend type.

## Configuration

When using Redis, the `storage-info` parameter for hyrax should take the form:

```
<host/ip>:<port>
```

With the default being:

```
localhost:6379
```

## Commands

The following commands are supported for being passed back to redis. Hyrax's
`key` field is passed back as the first argument to redis commands. For example,
a `SET FOO BAR` would look like:

```json
{"cmd":"SET","key":"FOO","args":["BAR"],"secret":"<hmac-sha1>"}
```

(Commands marked with `*` will require a `secret` field because they modify
state)

**Keys:**

* exists
* expire *
* expireat *
* persist *
* pexpire *
* pexpireat *
* pttl
* ttl
* type

**Strings:**

* append *
* bitcount
* decr *
* decrby *
* get
* getbit
* getrange
* getset *
* incr *
* incrby *
* incrbyfloat *
* psetex *
* set *
* setbit *
* setex *
* setnx *
* setrange *
* strlen

**Hashes:**

* hdel *
* hexists
* hget
* hgetall
* hincrby *
* hincrbyfloat *
* hkeys
* hlen
* hmget
* hset *
* hsetnx *
* hvals

**Lists:**

* lindex
* linsert *
* llen
* lpop *
* lpush *
* lpushx *
* lrange
* lrem *
* lset *
* ltrim *
* rpop *
* rpush *
* rpushx *

**Sets:**

* sadd *
* scard
* sismember
* smembers
* spop *
* srandmember
* srem *

**Sorted Sets:**

* zadd *
* zcard
* zcount
* zincrby *
* zrange
* zrangebyscore
* zrank
* zrem *
* zremrangebyrank *
* zremrangebyscore *
* zrevrange
* zrevrangebyscore
* zrevrank
* zscore


text:
#ifndef WebCompositionUnderline_h
#define WebCompositionUnderline_h

#include "../platform/WebColor.h"

namespace blink {

// Class WebCompositionUnderline is intended to be used with WebWidget's
// setComposition() method.
struct WebCompositionUnderline {
  WebCompositionUnderline()
      : startOffset(0),
        endOffset(0),
        color(0),
        thick(false),
        backgroundColor(0) {}

  WebCompositionUnderline(unsigned s,
                          unsigned e,
                          WebColor c,
                          bool t,
                          WebColor bc)
      : startOffset(s), endOffset(e), color(c), thick(t), backgroundColor(bc) {}

  bool operator<(const WebCompositionUnderline& other) const {
    return startOffset != other.startOffset ? startOffset < other.startOffset
                                            : endOffset < other.endOffset;
  }

  // Need to update IPC_STRUCT_TRAITS_BEGIN(blink::WebCompositionUnderline)
  // if members change.
  unsigned startOffset;
  unsigned endOffset;
  WebColor color;
  bool thick;
  WebColor backgroundColor;
};

}  // namespace blink

#endif


text:
Here is the list of the TLA+ language features that are currently supported by Apalache, following the [Summary of TLA+][cheat].

## Language

### Module-Level constructs

Construct  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
``EXTENDS module`` | ✔ | - | As soon as SANY imports the module. Some standard modules are not supported yet
``CONSTANTS C1, C2`` | ✔ | -  | Either define a ``ConstInit`` operator to initialize the constants, or declare operators instead of constants, e.g., C1 == 111
``VARIABLES x, y, z`` | ✔ | - |
``ASSUME P`` | ✔ / ✖ | - | Parsed, but not propagated to the solver
``F(x1, ..., x_n) == exp`` | ✔ / ✖ | - | Every application of `F` is replaced with its body. Recursive operators need [unrolling annotations](./manual.md#91-recursive-operators).
``f[x ∈ S] == exp`` | ✔ / ✖ | - | Only recursive functions that return integers or Booleans are supported.
``INSTANCE M WITH ...`` | ✔ / ✖ | - | No special treatment for ``~>``, ``\cdot``, ``ENABLED``
``N(x1, ..., x_n) == INSTANCE M WITH...`` | ✔ / ✖ | - | Parameterized instances are not supported yet, LOCAL operator definitions inside instances may fail to work
``THEOREM P`` | ✔ / ✖ | - | Parsed but not used
``LOCAL def`` | ✔ | - | Handled by SANY

### The constant operators

#### Logic

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`/\`, `\/`, `~`, `=>`, `<=>` | ✔ | - |
``TRUE``, ``FALSE``, ``BOOLEAN`` | ✔ | - |
``\A x \in S: p``, ``\E x \in S : p`` |  ✔ | - |
``CHOOSE x \in S : p`` |  ✔/✖ | - | Similar to TLC, we implement a non-deterministic choice. We will add a deterministic version in the future.
``CHOOSE x : x \notin S`` |  ✖ | ? | That is a commonly used idiom
``\A x : p, \E x : p`` |  ✖ | **NEVER** | Use the versions above
``CHOOSE x : p`` |  ✖ | **NEVER** | Use the version above

#### Sets

**Note:** only finite sets are supported. Additionally, existential
quantification over `Int` and `Nat` is supported, as soon as it can be
replaced with a constant.

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`=`, `/=`, `\in`, `\notin`, `\intersect`, `\union`, `\subseteq`, `\`  | ✔ | - |
`{e_1, ..., e_n}` | ✔ | - | Empty sets ``{}`` require [type annotations](types-and-annotations.md)
`{x \in S : p}` | ✔ | - |
`{e : x \in S}` | ✔ | - |
`SUBSET S` | ✔ | - | Sometimes, the powersets are expanded
`UNION S` |  ✔ | - | Provided that S is expanded

#### Functions

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`f[e]` | ✔ | - |
`DOMAIN f` | ✔ | - |
`[ x \in S ↦ e]` | ✔ / ✖ | - |
`[ S -> T ]` | ✔ | - | Sometimes, the functions sets are expanded
`[ f EXCEPT ![e1] = e2 ]` | ✔ | - |

#### Records

*Use [type annotations](types-and-annotations.md) to help the model checker in finding the right types.*
Note that our type system distinguishes records from general functions.

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`e.h` | ✔ | - |
`r[e]` | ✔/✖ | - | Provided that e is a constant expression.
`[ h1 ↦ e1, ..., h_n ↦ e_n]` | ✔ | - |
`[ h1 : S1, ..., h_n : S_n]` | ✔ | - |
`[ r EXCEPT !.h = e]` | ✔ | - |

#### Tuples

*Use [type annotations](types-and-annotations.md) to help the model checker in finding the right types.*
Note that our type system distinguishes tuples from general functions.

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`e[i]` | ✔ / ✖ | - | Provided that ``i`` is a constant expression
`<< e1, ..., e_n >>` | ✔ | - | By default, a tuple is constructed. Use a [type annotation](types-and-annotations.md) to construct a sequence of proper type.
`S1 \X ... \X S_n` | ✔ | - |
`[ t EXCEPT ![i] = e]` | ✔/✖ | - | Provided that ``i`` is a constant expression

#### Strings and numbers

Construct  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`"c1...c_n"` | ✔ | - | A string is always mapped to a unique uninterpreted constant
`STRING` | ✖ | - | It is an infinite set. We cannot handle infinite sets.
`d1...d_n` | ✔ | - | As long as the SMT solver (Z3) accepts that large number
`d1...d_n.d_n+1...d_m` | ✖ | - | Technical issue. We will implemented upon a user request.

#### Miscellaneous Constructs

Construct  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`IF p THEN e1 ELSE e2` | ✔ | - | Provided that both e1 and e2 have the same type
`CASE p1 -> e1 [] ... [] p_n -> e_n [] OTHER -> e` | ✔ | - | See the comment above
`CASE p1 -> e1 [] ... [] p_n -> e_n` | ✖ | - | Introduce the default arm with `OTHER`.
``LET d1 == e1 ... d_n == e_n IN e`` | ✔ / ✖ | `0.7-dev-calls` | All applications of `d1`, ..., `d_n` are replaced with the expressions `e1`, ... `e_n` respectively. LET-definitions without arguments are kept in place.
multi-line `/\` and `\/` | ✔ | - |

### The Action Operators

Construct  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
``e'`` | ✔ / ✖ | - | Provided that e is a variable
``[A]_e`` | ✖ | - | It does not matter for safety
``< A >_e`` | ✖ | - |
``ENABLED A`` | ✖ | - |
``UNCHANGED <<e_1, ..., e_k>>`` | ✔ | - |	Always replaced with ``e_1' = e_1 /\ ... /\ e_k' = e_k``
``A ∙ B`` | ✖ | - |

### The Temporal Operators

The model checker assumes that the specification has the form `Init /\
[][Next]_e`. Given an invariant candidate `Inv`, the tool checks, whether
`Inv` is violated by an execution whose length is bounded by the given
argument.

Except the standard form `Init /\ [][Next]_e`, no temporal operators are supported.

## Standard modules

### Integers and Naturals

For the moment, the model checker does not differentiate between integers and naturals. They are all translated as integers in SMT.

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
`+`, `-`, `*`, `<=`, `>=`, `<`, `>` | ✔ | - | These operators are translated into integer arithmetic of the SMT solver. Linear integer arithmetic is preferred.
`\div`, `%` | ✔ | - | Integer division and modulo
`a^b` | ✔ / ✖ | - | Provided a and b are constant expressions
`a..b` | ✔ / ✖ | - | Sometimes, `a..b` needs a constant upper bound on the range.  When Apalache complains, use `{x \in A..B : a <= x /\ x <= b}`, provided that `A` and `B` are constant expressions.
`Int`, `Nat` | ✔ / ✖ | - | Supported in `\E x \in Nat: p` and `\E x \in Int: p`, if the expression is not located under `\A` and `~`. We also support assignments like `f' \in [S -> Int]` and tests `f \in [S -> Nat]`
`/` | ✖ | - | Real division, not supported

### Sequences

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
``<<...>>``, ``Head``, ``Tail``, ``Len``, ``SubSeq``, `Append`, `\o`, `f[e]` | ✔ | - | The sequence constructor ``<<...>>`` needs a [type annotation](types-and-annotations.md).
``EXCEPT`` | ✖ | `0.9` | this operator do not seem to be often used
``Seq(S)`` | ✖ | - | We need an upper bound on the length of the sequences.
``SelectSeq`` | ✖ | - | will not be supported in the near future

### FiniteSets

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
``IsFinite`` | ✔ | - | Always returns true, as all the supported sets are finite
``Cardinality`` | ✔ | - | Try to avoid it, as Cardinality(S) produces ``O(n^2)`` constraints in SMT for cardinality `n`

### TLC

Operator  | Supported? | Milestone | Comment
------------------------|:------------------:|:---------------:|--------------
``f @@ a :> b`` | ✔ | - | Extends the function relation with the pair ``<<a, b>>``

### Reals

Not supported, not a priority

[cheat]: https://lamport.azurewebsites.net/tla/summary.pdf


text:
package edu.utah.ece.async.sboldesigner.sbol.editor.dialog;

import java.awt.Component;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
import javax.xml.namespace.QName;

import org.sbolstandard.core2.Annotation;
import org.sbolstandard.core2.ComponentDefinition;
import org.sbolstandard.core2.SBOLValidationException;

import edu.utah.ece.async.sboldesigner.swing.FormBuilder;

/**
 *
 * @author Evren Sirin
 */
public class AnnotationEditDialog extends InputDialog<Annotation> {
	private JTextField namespace;
	private JTextField prefix;
	private JTextField name;
	private JTextComponent value;
	private JCheckBox uri = new JCheckBox();
	private Annotation oldAnnotation = null;
	private ComponentDefinition cd = null;

	/**
	 * Prepopulates fields with oldAnnotation if oldAnnotation isn't null
	 */
	public AnnotationEditDialog(Component parent, Annotation oldAnnotation, ComponentDefinition cd) {
		super(JOptionPane.getFrameForComponent(parent), "AnnotationEditor");
		this.oldAnnotation = oldAnnotation;
		this.cd = cd;
	}

	@Override
	protected void initFormPanel(FormBuilder builder) {
		String oldNamespace = "";
		String oldPrefix = "";
		String oldName = "";
		String oldValue = "";

		if (oldAnnotation != null) {
			oldNamespace = oldAnnotation.getQName().getNamespaceURI();
			oldPrefix = oldAnnotation.getQName().getPrefix();
			oldName = oldAnnotation.getQName().getLocalPart();
			oldValue = getValue(oldAnnotation);
			uri.setSelected(oldAnnotation.isURIValue());
		}

		namespace = builder.addTextField("Namespace", oldNamespace);
		prefix = builder.addTextField("Prefix", oldPrefix);
		name = builder.addTextField("Name", oldName);
		value = builder.addTextField("Value", oldValue);
		builder.add("Is clickable URI?", uri);
	}

	private String getValue(Annotation ann) {
		if (ann.getBooleanValue() != null) {
			return ann.getBooleanValue().toString();
		} else if (ann.getDoubleValue() != null) {
			return ann.getDoubleValue().toString();
		} else if (ann.getIntegerValue() != null) {
			return ann.getIntegerValue().toString();
		} else if (ann.getStringValue() != null) {
			return ann.getStringValue();
		} else if (ann.getURIValue() != null) {
			return ann.getURIValue().toString();
		} else {
			return "No value found";
		}
	}

	@Override
	protected void initFinished() {
		setSelectAllowed(true);
	}

	@Override
	protected Annotation getSelection() {
		try {
			if (uri.isSelected()) {
				return cd.createAnnotation(new QName(namespace.getText(), name.getText(), prefix.getText()),
						new URI(value.getText()));
			} else {
				return cd.createAnnotation(new QName(namespace.getText(), name.getText(), prefix.getText()),
						value.getText());
			}
		} catch (SBOLValidationException | URISyntaxException e) {
			MessageDialog.showMessage(null, "Oops", Arrays.asList(e.getMessage().split("\"|,")));
			return null;
		}
	}
}


text:
namespace hackerrank {
namespace bmgandre {
namespace algorithms {
namespace implementation {

class apple_and_orange
{
public:
	static void solve();
};

} // namespace implementation
} // namespace algorithms
} // namespace bmgandre
} // namespace hackerrank


text:
using Claw.Documents;
using Claw.Validation;
using System;
using System.Diagnostics;
using System.Globalization;

namespace Claw.Controllers.Assignments
{
    /// <summary>
    /// Represents an assignment to a mouse axis.
    /// </summary>
    public class MouseAxisAssignment : Assignment
    {
        private const string ENVELOPE_ATTRIBUTE = "envelope";

        private const string SENSITIVITY_ENVELOPE = "sensitivity";

        #region Validation

        private static readonly string[] REQUIRED_ATTRIBUTES = {
            ENVELOPE_ATTRIBUTE,
        };
        private static readonly string[] OPTIONAL_ATTRIBUTES = { };
        private static readonly string[] REQUIRED_CHILD_NODES = { };
        private static readonly string[] OPTIONAL_CHILD_NODES = { };

        internal override string[] RequiredAttributes
        {
            get { return REQUIRED_ATTRIBUTES; }
        }

        internal override string[] OptionalAttributes
        {
            get { return OPTIONAL_ATTRIBUTES; }
        }

        internal override string[] RequiredChildNodes
        {
            get { return REQUIRED_CHILD_NODES; }
        }

        internal override string[] OptionalChildNodes
        {
            get { return OPTIONAL_CHILD_NODES; }
        }

		internal override bool CheckNodes
		{
			get { return false; }
		}

        #endregion

        private MouseAxisEnvelope envelope;

        private int value;

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Profile files need lowercase strings.")]
        protected override string NodeName
        {
            get { return MousePointerAssignment.MOUSE_AXIS_CHILD_NODE.ToLowerInvariant(); }
        }

        /// <summary>
        /// Creates a new MouseAxisAssignment.
        /// </summary>
        /// <param name="validator">The validator to use for validation.</param>
        /// <param name="node">The "mouseaxis" node.</param>
        internal MouseAxisAssignment(NodeValidator validator, Node node)
            : base(validator, node)
        {
            string envelopeName = null;
            if (node.Attributes.ContainsKey(ENVELOPE_ATTRIBUTE))
            {
                envelopeName = node.Attributes[ENVELOPE_ATTRIBUTE].ToUpperInvariant();
                envelope = MouseAxisEnvelopeHelper.TryParse(envelopeName);
            }

            if (!string.IsNullOrEmpty(envelopeName))
            {
                foreach (var child in node.Children)
                {
                    if (child.Name.ToUpperInvariant() == envelopeName)
                    {
                        value = int.Parse(child.Tag, CultureInfo.InvariantCulture);
                    }
                }
            }
        }

        internal override void FillNode(Node node)
        {
            if (envelope == MouseAxisEnvelope.Sensitivity)
            {
                node.Attributes.Add(ENVELOPE_ATTRIBUTE, SENSITIVITY_ENVELOPE);
                Node envelopeNode = new Node(SENSITIVITY_ENVELOPE);
                envelopeNode.Tag = value.ToString(CultureInfo.InvariantCulture);
                node.Children.AddLast(envelopeNode);
            }
        }
    }
}


text:
describe('Base', function() {
  var Base = requireFromSrc('effervescent/base');
  var base = null;

  beforeEach(function() {
    Test = Base.extend({});
  });

  it('can be extended from an extension', function() {
    var TestAgain = Test.extend({
      ok: 'Yep'
    });

    var instance = new TestAgain();
    expect(instance.ok).to.be.equal('Yep');
  });
});


text:
namespace {

// App ID of default pinned apps.
const char* kDefaultPinnedApps[] = {
  extension_misc::kGmailAppId,
  extension_misc::kGoogleSearchAppId,
  extension_misc::kGoogleDocAppId,
  extension_misc::kYoutubeAppId,
};

base::ListValue* CreateDefaultPinnedAppsList() {
  scoped_ptr<base::ListValue> apps(new base::ListValue);
  for (size_t i = 0; i < arraysize(kDefaultPinnedApps); ++i)
    apps->Append(ash::CreateAppDict(kDefaultPinnedApps[i]));

  return apps.release();
}

}  // namespace

namespace ash {

const char kPinnedAppsPrefAppIDPath[] = "id";

const char kShelfAutoHideBehaviorAlways[] = "Always";
const char kShelfAutoHideBehaviorNever[] = "Never";

extern const char kShelfAlignmentBottom[] = "Bottom";
extern const char kShelfAlignmentLeft[] = "Left";
extern const char kShelfAlignmentRight[] = "Right";
extern const char kShelfAlignmentTop[] = "Top";

void RegisterChromeLauncherUserPrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  // TODO: If we want to support multiple profiles this will likely need to be
  // pushed to local state and we'll need to track profile per item.
  registry->RegisterIntegerPref(
      prefs::kShelfChromeIconIndex,
      0,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterListPref(prefs::kPinnedLauncherApps,
                             CreateDefaultPinnedAppsList(),
                             user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterStringPref(prefs::kShelfAutoHideBehavior,
                               kShelfAutoHideBehaviorNever,
                               user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterStringPref(
      prefs::kShelfAutoHideBehaviorLocal,
      std::string(),
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterStringPref(prefs::kShelfAlignment,
                               kShelfAlignmentBottom,
                               user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterStringPref(
      prefs::kShelfAlignmentLocal,
      std::string(),
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterDictionaryPref(
      prefs::kShelfPreferences,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterIntegerPref(
      prefs::kLogoutDialogDurationMs,
      20000,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterBooleanPref(
      prefs::kShowLogoutButtonInTray,
      false,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}

base::DictionaryValue* CreateAppDict(const std::string& app_id) {
  scoped_ptr<base::DictionaryValue> app_value(new base::DictionaryValue);
  app_value->SetString(kPinnedAppsPrefAppIDPath, app_id);
  return app_value.release();
}

}  // namespace ash


text:
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Diagnostics;

namespace Dashboard.Azure.TestRuns
{
    /// <summary>
    /// Information about a test run.
    /// </summary>
    public sealed class TestRunEntity : TableEntity
    {
        public string MachineName { get; set; }
        public string EnlistmentRoot { get; set; }
        public DateTime RunDate { get; set; }
        public string CacheType { get; set; }
        public long ElapsedSeconds { get; set; }
        public bool Succeeded { get; set; }
        public bool IsJenkins { get; set; }
        public bool Is32Bit { get; set; }
        public int AssemblyCount { get; set; }
        public int CacheCount { get; set; }
        public int ChunkCount { get; set; }
        public string JenkinsUrl { get; set; }
        public bool HasErrors { get; set; }

        public TimeSpan Elapsed => TimeSpan.FromSeconds(ElapsedSeconds);

        public TestRunEntity()
        {

        }

        public TestRunEntity(DateTime runDate, BuildSource buildSource)
        {
            PartitionKey = GetPartitionKey(runDate);
            RowKey = GetRowKey(RunDate, buildSource);
            MachineName = buildSource.MachineName;
            EnlistmentRoot = buildSource.EnlistmentRoot;
            RunDate = runDate;
        }

        public static string GetPartitionKey(DateTime runDate)
        {
            Debug.Assert(runDate.Kind == DateTimeKind.Utc);
            var date = runDate.Date;
            return date.ToString("yyyy-MM-dd");
        }

        public static string GetRowKey(DateTime runDate, BuildSource buildSource)
        {
            var machineName = AzureUtil.NormalizeKey(buildSource.MachineName, '-');
            return $"{machineName}-{(long)runDate.Ticks}";
        }

        public EntityKey CreateEntityKey(DateTime runDate, BuildSource buildSource)
        {
            return new EntityKey(
                GetPartitionKey(runDate),
                GetRowKey(runDate, buildSource));
        }
    }
}


text:
package gavilan.irc;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.SECONDS;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CronImpl implements Cron {

private final Logger log;
private final Features features;

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

private Optional<ScheduledFuture<?>> cron = Optional.empty();

private final List<Procedure> recurs = new ArrayList<>();

@Autowired
public CronImpl(Logger log, Features features) {
  this.log = log;
  this.features = features;
  init();
}

private void init() {
  add(() -> log.info("tick"));
}

  @Override
  public void startCron() {
  log.info("Start cron");
  if (!cron.isPresent()) {
    cron = Optional.ofNullable(scheduler.scheduleAtFixedRate(() -> {
      recurs.forEach(Procedure::apply);
    }, 1, 60, SECONDS));
  }
}

  @Override
  public void stopCron() {
  log.info("Stop cron");
  cron.ifPresent(c -> c.cancel(true));
  cron = Optional.empty();
}

@PreDestroy
public void destroy() {
  scheduler.shutdown();
}

  @Override
  public void add(Procedure f) {
  recurs.add(f);
}

  @Override
  public void updateCron() {
  if (features.hasFeature("cron")) {
    startCron();
  }
  else {
    stopCron();
  }
}

}


text:
"""
    ORCID Member

    No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)  # noqa: E501

    OpenAPI spec version: Latest

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six
from orcid_api_v3.models.created_date_v30_rc2 import CreatedDateV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.last_modified_date_v30_rc2 import LastModifiedDateV30Rc2  # noqa: F401,E501
from orcid_api_v3.models.source_v30_rc2 import SourceV30Rc2  # noqa: F401,E501

class OtherNameV30Rc2(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """
    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'created_date': 'CreatedDateV30Rc2',
        'last_modified_date': 'LastModifiedDateV30Rc2',
        'source': 'SourceV30Rc2',
        'content': 'str',
        'visibility': 'str',
        'path': 'str',
        'put_code': 'int',
        'display_index': 'int'
    }

    attribute_map = {
        'created_date': 'created-date',
        'last_modified_date': 'last-modified-date',
        'source': 'source',
        'content': 'content',
        'visibility': 'visibility',
        'path': 'path',
        'put_code': 'put-code',
        'display_index': 'display-index'
    }

    def __init__(self, created_date=None, last_modified_date=None, source=None, content=None, visibility=None, path=None, put_code=None, display_index=None):  # noqa: E501
        """OtherNameV30Rc2 - a model defined in Swagger"""  # noqa: E501
        self._created_date = None
        self._last_modified_date = None
        self._source = None
        self._content = None
        self._visibility = None
        self._path = None
        self._put_code = None
        self._display_index = None
        self.discriminator = None
        if created_date is not None:
            self.created_date = created_date
        if last_modified_date is not None:
            self.last_modified_date = last_modified_date
        if source is not None:
            self.source = source
        if content is not None:
            self.content = content
        if visibility is not None:
            self.visibility = visibility
        if path is not None:
            self.path = path
        if put_code is not None:
            self.put_code = put_code
        if display_index is not None:
            self.display_index = display_index

    @property
    def created_date(self):
        """Gets the created_date of this OtherNameV30Rc2.  # noqa: E501

        :return: The created_date of this OtherNameV30Rc2.  # noqa: E501
        :rtype: CreatedDateV30Rc2
        """
        return self._created_date

    @created_date.setter
    def created_date(self, created_date):
        """Sets the created_date of this OtherNameV30Rc2.

        :param created_date: The created_date of this OtherNameV30Rc2.  # noqa: E501
        :type: CreatedDateV30Rc2
        """

        self._created_date = created_date

    @property
    def last_modified_date(self):
        """Gets the last_modified_date of this OtherNameV30Rc2.  # noqa: E501

        :return: The last_modified_date of this OtherNameV30Rc2.  # noqa: E501
        :rtype: LastModifiedDateV30Rc2
        """
        return self._last_modified_date

    @last_modified_date.setter
    def last_modified_date(self, last_modified_date):
        """Sets the last_modified_date of this OtherNameV30Rc2.

        :param last_modified_date: The last_modified_date of this OtherNameV30Rc2.  # noqa: E501
        :type: LastModifiedDateV30Rc2
        """

        self._last_modified_date = last_modified_date

    @property
    def source(self):
        """Gets the source of this OtherNameV30Rc2.  # noqa: E501

        :return: The source of this OtherNameV30Rc2.  # noqa: E501
        :rtype: SourceV30Rc2
        """
        return self._source

    @source.setter
    def source(self, source):
        """Sets the source of this OtherNameV30Rc2.

        :param source: The source of this OtherNameV30Rc2.  # noqa: E501
        :type: SourceV30Rc2
        """

        self._source = source

    @property
    def content(self):
        """Gets the content of this OtherNameV30Rc2.  # noqa: E501

        :return: The content of this OtherNameV30Rc2.  # noqa: E501
        :rtype: str
        """
        return self._content

    @content.setter
    def content(self, content):
        """Sets the content of this OtherNameV30Rc2.

        :param content: The content of this OtherNameV30Rc2.  # noqa: E501
        :type: str
        """

        self._content = content

    @property
    def visibility(self):
        """Gets the visibility of this OtherNameV30Rc2.  # noqa: E501

        :return: The visibility of this OtherNameV30Rc2.  # noqa: E501
        :rtype: str
        """
        return self._visibility

    @visibility.setter
    def visibility(self, visibility):
        """Sets the visibility of this OtherNameV30Rc2.

        :param visibility: The visibility of this OtherNameV30Rc2.  # noqa: E501
        :type: str
        """
        allowed_values = ["LIMITED", "REGISTERED_ONLY", "PUBLIC", "PRIVATE"]  # noqa: E501
        if visibility not in allowed_values:
            raise ValueError(
                "Invalid value for `visibility` ({0}), must be one of {1}"  # noqa: E501
                .format(visibility, allowed_values)
            )

        self._visibility = visibility

    @property
    def path(self):
        """Gets the path of this OtherNameV30Rc2.  # noqa: E501

        :return: The path of this OtherNameV30Rc2.  # noqa: E501
        :rtype: str
        """
        return self._path

    @path.setter
    def path(self, path):
        """Sets the path of this OtherNameV30Rc2.

        :param path: The path of this OtherNameV30Rc2.  # noqa: E501
        :type: str
        """

        self._path = path

    @property
    def put_code(self):
        """Gets the put_code of this OtherNameV30Rc2.  # noqa: E501

        :return: The put_code of this OtherNameV30Rc2.  # noqa: E501
        :rtype: int
        """
        return self._put_code

    @put_code.setter
    def put_code(self, put_code):
        """Sets the put_code of this OtherNameV30Rc2.

        :param put_code: The put_code of this OtherNameV30Rc2.  # noqa: E501
        :type: int
        """

        self._put_code = put_code

    @property
    def display_index(self):
        """Gets the display_index of this OtherNameV30Rc2.  # noqa: E501

        :return: The display_index of this OtherNameV30Rc2.  # noqa: E501
        :rtype: int
        """
        return self._display_index

    @display_index.setter
    def display_index(self, display_index):
        """Sets the display_index of this OtherNameV30Rc2.

        :param display_index: The display_index of this OtherNameV30Rc2.  # noqa: E501
        :type: int
        """

        self._display_index = display_index

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(OtherNameV30Rc2, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, OtherNameV30Rc2):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


text:
package DataProviders.JBDCDataProvider;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.Test;

import java.sql.*;

/**
 * Created by sunny_IT on 2/10/2017.
 */
public class TestSample {

    @Test(enabled = true, dataProvider = "jdbcDataProvider", dataProviderClass = JDBCDataProvider.class)
    @JDBCDataSource(connectionURL = "jdbc:h2:~/test", user="sa", statementQuery ="Select * from USER" )
    public void testJDBCProviderSimple(int id, String name) {
        System.out.println("Hello, " + id + ": " + name);
    }

    @Test(enabled = true, dataProvider = "jdbcLazyDataProvider", dataProviderClass = JDBCLazyDataProvider.class)
    @JDBCDataSource(connectionURL = "jdbc:h2:~/test", user="sa", statementQuery ="Select * from USER" )
    public void testJDBCProviderLazy(int id, String name) {
        System.out.println("Hello, " + id + ": " + name);
    }

    @BeforeClass
    public void setup() throws ClassNotFoundException, SQLException {

        //just for DEMO

        Class.forName("org.h2.Driver");
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DriverManager.getConnection("jdbc:h2:~/test;IFEXISTS=TRUE", "sa", "");
            statement = connection.createStatement();
            statement.execute("DROP TABLE IF EXISTS USER;");
            statement.execute("CREATE TABLE USER(ID INT PRIMARY KEY, NAME VARCHAR(255));");

            statement.execute("INSERT INTO USER VALUES(1,'borya')");
            statement.execute("INSERT INTO USER VALUES(2,'petya')");
            statement.execute("INSERT INTO USER VALUES(3,'vasya')");
            ResultSet rs = statement.executeQuery("select * from user");
        }catch(SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (statement != null)
                try { statement.close(); }
                catch (SQLException ignore) { }
            if (connection != null)
                try { connection.close(); }
                catch (SQLException ignore) { }
        }

    }

}


text:
from random import randint

addictions = [ "midget hookers playing football",
"touching yourself while eating sardines",
"cutting your hands off and surgically reattaching them to your butt",
"golden potato salad",
"dick salad",
"screaming I AM A SILVER SKELETOR",
"being a brony",
"mastering the art of shaving your own butthole",
"teaching mayonnaise how to love",
"grand piano sexual chocolate",
"ALCOHOL!  Collect your death on the way out",
"weird foot fetish porn (again)",
"bigger blacker dicks",
"coming up with sexual versions of children songs",
"calling white people ma nigga"
  ]

print "Your new addiction is.... "+ addictions[randint(0, len(addictions)-1)] + "!"
print "Congratulations!"


text:
import os
import unittest
import random
from test import support
thread = support.import_module('thread')
import time
import sys
import weakref

from test import lock_tests

NUMTASKS = 10
NUMTRIPS = 3

_print_mutex = thread.allocate_lock()

def verbose_print(arg):
    """Helper function for printing out debugging output."""
    if support.verbose:
        with _print_mutex:
            print arg

class BasicThreadTest(unittest.TestCase):

    def setUp(self):
        self.done_mutex = thread.allocate_lock()
        self.done_mutex.acquire()
        self.running_mutex = thread.allocate_lock()
        self.random_mutex = thread.allocate_lock()
        self.created = 0
        self.running = 0
        self.next_ident = 0

        key = support.threading_setup()
        self.addCleanup(support.threading_cleanup, *key)

class ThreadRunningTests(BasicThreadTest):

    def newtask(self):
        with self.running_mutex:
            self.next_ident += 1
            verbose_print("creating task %s" % self.next_ident)
            thread.start_new_thread(self.task, (self.next_ident,))
            self.created += 1
            self.running += 1

    def task(self, ident):
        with self.random_mutex:
            delay = random.random() / 10000.0
        verbose_print("task %s will run for %sus" % (ident, round(delay*1e6)))
        time.sleep(delay)
        verbose_print("task %s done" % ident)
        with self.running_mutex:
            self.running -= 1
            if self.created == NUMTASKS and self.running == 0:
                self.done_mutex.release()

    def test_starting_threads(self):
        with support.wait_threads_exit():
            # Basic test for thread creation.
            for i in range(NUMTASKS):
                self.newtask()
            verbose_print("waiting for tasks to complete...")
            self.done_mutex.acquire()
            verbose_print("all tasks done")

    def test_stack_size(self):
        # Various stack size tests.
        self.assertEqual(thread.stack_size(), 0, "initial stack size is not 0")

        thread.stack_size(0)
        self.assertEqual(thread.stack_size(), 0, "stack_size not reset to default")

    @unittest.skipIf(os.name not in ("nt", "os2", "posix"), 'test meant for nt, os2, and posix')
    def test_nt_and_posix_stack_size(self):
        try:
            thread.stack_size(4096)
        except ValueError:
            verbose_print("caught expected ValueError setting "
                            "stack_size(4096)")
        except thread.error:
            self.skipTest("platform does not support changing thread stack "
                          "size")

        fail_msg = "stack_size(%d) failed - should succeed"
        for tss in (262144, 0x100000, 0):
            thread.stack_size(tss)
            self.assertEqual(thread.stack_size(), tss, fail_msg % tss)
            verbose_print("successfully set stack_size(%d)" % tss)

        for tss in (262144, 0x100000):
            verbose_print("trying stack_size = (%d)" % tss)
            self.next_ident = 0
            self.created = 0
            with support.wait_threads_exit():
                for i in range(NUMTASKS):
                    self.newtask()

                verbose_print("waiting for all tasks to complete")
                self.done_mutex.acquire()
                verbose_print("all tasks done")

        thread.stack_size(0)

    def test__count(self):
        # Test the _count() function.
        orig = thread._count()
        mut = thread.allocate_lock()
        mut.acquire()
        started = []

        def task():
            started.append(None)
            mut.acquire()
            mut.release()

        with support.wait_threads_exit():
            thread.start_new_thread(task, ())
            while not started:
                time.sleep(0.01)
            self.assertEqual(thread._count(), orig + 1)
            # Allow the task to finish.
            mut.release()
            # The only reliable way to be sure that the thread ended from the
            # interpreter's point of view is to wait for the function object to be
            # destroyed.
            done = []
            wr = weakref.ref(task, lambda _: done.append(None))
            del task
            while not done:
                time.sleep(0.01)
            self.assertEqual(thread._count(), orig)

    def test_save_exception_state_on_error(self):
        # See issue #14474
        def task():
            started.release()
            raise SyntaxError
        def mywrite(self, *args):
            try:
                raise ValueError
            except ValueError:
                pass
            real_write(self, *args)
        c = thread._count()
        started = thread.allocate_lock()
        with support.captured_output("stderr") as stderr:
            real_write = stderr.write
            stderr.write = mywrite
            started.acquire()
            with support.wait_threads_exit():
                thread.start_new_thread(task, ())
                started.acquire()
        self.assertIn("Traceback", stderr.getvalue())

class Barrier:
    def __init__(self, num_threads):
        self.num_threads = num_threads
        self.waiting = 0
        self.checkin_mutex  = thread.allocate_lock()
        self.checkout_mutex = thread.allocate_lock()
        self.checkout_mutex.acquire()

    def enter(self):
        self.checkin_mutex.acquire()
        self.waiting = self.waiting + 1
        if self.waiting == self.num_threads:
            self.waiting = self.num_threads - 1
            self.checkout_mutex.release()
            return
        self.checkin_mutex.release()

        self.checkout_mutex.acquire()
        self.waiting = self.waiting - 1
        if self.waiting == 0:
            self.checkin_mutex.release()
            return
        self.checkout_mutex.release()

class BarrierTest(BasicThreadTest):

    def test_barrier(self):
        with support.wait_threads_exit():
            self.bar = Barrier(NUMTASKS)
            self.running = NUMTASKS
            for i in range(NUMTASKS):
                thread.start_new_thread(self.task2, (i,))
            verbose_print("waiting for tasks to end")
            self.done_mutex.acquire()
            verbose_print("tasks done")

    def task2(self, ident):
        for i in range(NUMTRIPS):
            if ident == 0:
                # give it a good chance to enter the next
                # barrier before the others are all out
                # of the current one
                delay = 0
            else:
                with self.random_mutex:
                    delay = random.random() / 10000.0
            verbose_print("task %s will run for %sus" %
                          (ident, round(delay * 1e6)))
            time.sleep(delay)
            verbose_print("task %s entering %s" % (ident, i))
            self.bar.enter()
            verbose_print("task %s leaving barrier" % ident)
        with self.running_mutex:
            self.running -= 1
            # Must release mutex before releasing done, else the main thread can
            # exit and set mutex to None as part of global teardown; then
            # mutex.release() raises AttributeError.
            finished = self.running == 0
        if finished:
            self.done_mutex.release()

class LockTests(lock_tests.LockTests):
    locktype = thread.allocate_lock

class TestForkInThread(unittest.TestCase):
    def setUp(self):
        self.read_fd, self.write_fd = os.pipe()

    @unittest.skipIf(sys.platform.startswith('win'),
                     "This test is only appropriate for POSIX-like systems.")
    @support.reap_threads
    def test_forkinthread(self):
        non_local = {'status': None}
        def thread1():
            try:
                pid = os.fork() # fork in a thread
            except RuntimeError:
                sys.exit(0) # exit the child

            if pid == 0: # child
                os.close(self.read_fd)
                os.write(self.write_fd, "OK")
                # Exiting the thread normally in the child process can leave
                # any additional threads (such as the one started by
                # importing _tkinter) still running, and this can prevent
                # the half-zombie child process from being cleaned up. See
                # Issue #26456.
                os._exit(0)
            else: # parent
                os.close(self.write_fd)
                pid, status = os.waitpid(pid, 0)
                non_local['status'] = status

        with support.wait_threads_exit():
            thread.start_new_thread(thread1, ())
            self.assertEqual(os.read(self.read_fd, 2), "OK",
                             "Unable to fork() in thread")
        self.assertEqual(non_local['status'], 0)

    def tearDown(self):
        try:
            os.close(self.read_fd)
        except OSError:
            pass

        try:
            os.close(self.write_fd)
        except OSError:
            pass

def test_main():
    support.run_unittest(ThreadRunningTests, BarrierTest, LockTests,
                              TestForkInThread)

if __name__ == "__main__":
    test_main()


text:
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Tools;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Mapping\AssociationMetadata;
use Doctrine\ORM\Mapping\ToOneAssociationMetadata;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\UnitOfWork;
use ProxyManager\Proxy\GhostObjectInterface;
use function count;
use function fclose;
use function fopen;
use function fwrite;
use function gettype;
use function is_object;
use function spl_object_id;

/**
 * Use this logger to dump the identity map during the onFlush event. This is useful for debugging
 * weird UnitOfWork behavior with complex operations.
 */
class DebugUnitOfWorkListener
{
    /** @var string */
    private $file;

    /** @var string */
    private $context;

    /**
     * Pass a stream and context information for the debugging session.
     *
     * The stream can be php://output to print to the screen.
     *
     * @param string $file
     * @param string $context
     */
    public function __construct($file = 'php://output', $context = '')
    {
        $this->file    = $file;
        $this->context = $context;
    }

    public function onFlush(OnFlushEventArgs $args)
    {
        $this->dumpIdentityMap($args->getEntityManager());
    }

    /**
     * Dumps the contents of the identity map into a stream.
     */
    public function dumpIdentityMap(EntityManagerInterface $em)
    {
        $uow         = $em->getUnitOfWork();
        $identityMap = $uow->getIdentityMap();

        $fh = fopen($this->file, 'xb+');

        if (count($identityMap) === 0) {
            fwrite($fh, 'Flush Operation [' . $this->context . "] - Empty identity map.\n");

            return;
        }

        fwrite($fh, 'Flush Operation [' . $this->context . "] - Dumping identity map:\n");

        foreach ($identityMap as $className => $map) {
            fwrite($fh, 'Class: ' . $className . "\n");

            foreach ($map as $entity) {
                fwrite($fh, ' Entity: ' . $this->getIdString($entity, $uow) . ' ' . spl_object_id($entity) . "\n");
                fwrite($fh, "  Associations:\n");

                $cm = $em->getClassMetadata($className);

                foreach ($cm->getDeclaredPropertiesIterator() as $field => $association) {
                    if (! ($association instanceof AssociationMetadata)) {
                        continue;
                    }

                    fwrite($fh, '   ' . $field . ' ');

                    $value = $association->getValue($entity);

                    if ($value === null) {
                        fwrite($fh, " NULL\n");

                        continue;
                    }

                    if ($association instanceof ToOneAssociationMetadata) {
                        if ($value instanceof GhostObjectInterface && ! $value->isProxyInitialized()) {
                            fwrite($fh, '[PROXY] ');
                        }

                        fwrite($fh, $this->getIdString($value, $uow) . ' ' . spl_object_id($value) . "\n");
                    } else {
                        $initialized = ! ($value instanceof PersistentCollection) || $value->isInitialized();

                        if ($initialized) {
                            fwrite($fh, '[INITIALIZED] ' . $this->getType($value) . ' ' . count($value) . " elements\n");

                            foreach ($value as $obj) {
                                fwrite($fh, '    ' . $this->getIdString($obj, $uow) . ' ' . spl_object_id($obj) . "\n");
                            }
                        } else {
                            fwrite($fh, '[PROXY] ' . $this->getType($value) . " unknown element size\n");

                            foreach ($value->unwrap() as $obj) {
                                fwrite($fh, '    ' . $this->getIdString($obj, $uow) . ' ' . spl_object_id($obj) . "\n");
                            }
                        }
                    }
                }
            }
        }

        fclose($fh);
    }

    /**
     * @param mixed $var
     *
     * @return string
     */
    private function getType($var)
    {
        if (is_object($var)) {
            $refl = new \ReflectionObject($var);

            return $refl->getShortName();
        }

        return gettype($var);
    }

    /**
     * @param object $entity
     *
     * @return string
     */
    private function getIdString($entity, UnitOfWork $uow)
    {
        if ($uow->isInIdentityMap($entity)) {
            $ids      = $uow->getEntityIdentifier($entity);
            $idstring = '';

            foreach ($ids as $k => $v) {
                $idstring .= $k . '=' . $v;
            }
        } else {
            $idstring = 'NEWOBJECT ';
        }

        $state = $uow->getEntityState($entity);

        if ($state === UnitOfWork::STATE_NEW) {
            $idstring .= ' [NEW]';
        } elseif ($state === UnitOfWork::STATE_REMOVED) {
            $idstring .= ' [REMOVED]';
        } elseif ($state === UnitOfWork::STATE_MANAGED) {
            $idstring .= ' [MANAGED]';
        } elseif ($state === UnitOfWork::STATE_DETACHED) {
            $idstring .= ' [DETACHED]';
        }

        return $idstring;
    }
}


text:
using Microsoft.Practices.Unity;
using System.Web.Http;
using Unity.WebApi;
using System.Threading;
using TickingViewSvc_Net.Services;

namespace TickingViewSvc_Net
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
			var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            var cts = new CancellationTokenSource();
            var viewEngine = new ViewEngine(cts.Token); // viewEngine;

            container.RegisterInstance(typeof(IViewEngine), viewEngine);

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }
}


text:
package com.nidkil.utils

class Timer {

  private var startTime = 0L
  private var stopTime = 0L

  def start() = startTime = System.currentTimeMillis

  def stop() = stopTime = System.currentTimeMillis

  def execTime(msecs : Boolean = true) : String = {
    val diff = stopTime - startTime
    if(msecs) s"$diff msecs"
    else "%s,%s secs".format(diff / 1000, (diff % 1000).toString().padTo(4, "0").mkString)
  }

}