text:
[![version](https://img.shields.io/pypi/v/nuke.svg)](https://pypi.python.org/pypi/nuke)
[![license](https://img.shields.io/pypi/l/nuke.svg)](https://pypi.python.org/pypi/nuke)
[![wheel](https://img.shields.io/pypi/wheel/nuke.svg)](https://pypi.python.org/pypi/nuke)
[![python](https://img.shields.io/pypi/pyversions/nuke.svg)](https://pypi.python.org/pypi/nuke)
[![Build Status](https://travis-ci.org/varunagrawal/nuke.svg?branch=master)](https://travis-ci.org/varunagrawal/nuke)
[![say-thanks](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/varunagrawal)

Command line tool for nuking a directory 💥.

## Installation

Installing `nuke` is intended to be super easy. The only dependency is a supported Python interpreter. You can get `nuke` via `pip`:

```shell
$ pip install nuke
```
`nuke` is supported for Python 3.6+.

## Usage

The most common usage of `nuke` is when you wish to recreate a build directory for a build program such as CMake.

To use `nuke`, you just call `nuke` from the command line and specify the directory you wish to nuke:

```shell
$ nuke path/to/directory
```

If you are already in the directory you wish to nuke, you don't need to exit the directory. Calling `nuke` without any arguments will nuke the current directory:

```shell
$ nuke  # same as "nuke ."
```

Since nuking is a dangerous operation and you don't want to inadvertently delete something important, `nuke` always asks you to confirm the nuking of a directory. If you wish to override this since you know what you are doing or you wish to use `nuke` in a shell script, you can pass in the `-y` flag:

```shell
$ nuke -y /path/to/dir/
```

You can also specify a `.nukeignore` file inside the directory to be nuked. This works similar to the `.gitignore` file. Every file that matches a pattern in the `.nukeignore` is ignored and spared from a gruesome fate of its eligible siblings.

For example:
```shell
*.py
```
will result in all `.py` files not being nuked.

Suppose you just want to see what files will be nuked without actually deleting them, you can then run `nuke -l /path/to/dir`, and this will print out the directory tree of all the files that will be nuked.


text:
<?php

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Compiler\ResolveNamedArgumentsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes;
use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy;
use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsVariadicsDummy;
use Symfony\Component\DependencyInjection\Tests\Fixtures\SimilarArgumentsDummy;
use Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1;

/**
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class ResolveNamedArgumentsPassTest extends TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();

        $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
        $definition->setArguments([
            2 => 'http://api.example.com',
            '$apiKey' => '123',
            0 => new Reference('foo'),
        ]);
        $definition->addMethodCall('setApiKey', ['$apiKey' => '123']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);

        $this->assertEquals([0 => new Reference('foo'), 1 => '123', 2 => 'http://api.example.com'], $definition->getArguments());
        $this->assertEquals([['setApiKey', ['123']]], $definition->getMethodCalls());
    }

    public function testWithFactory()
    {
        $container = new ContainerBuilder();

        $container->register('factory', NoConstructor::class);
        $definition = $container->register('foo', NoConstructor::class)
            ->setFactory([new Reference('factory'), 'create'])
            ->setArguments(['$apiKey' => '123']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);

        $this->assertSame([0 => '123'], $definition->getArguments());
    }

    public function testClassNull()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $container = new ContainerBuilder();

        $definition = $container->register(NamedArgumentsDummy::class);
        $definition->setArguments(['$apiKey' => '123']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);
    }

    public function testClassNotExist()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $container = new ContainerBuilder();

        $definition = $container->register(NotExist::class, NotExist::class);
        $definition->setArguments(['$apiKey' => '123']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);
    }

    public function testClassNoConstructor()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $container = new ContainerBuilder();

        $definition = $container->register(NoConstructor::class, NoConstructor::class);
        $definition->setArguments(['$apiKey' => '123']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);
    }

    public function testArgumentNotFound()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException');
        $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "__construct()" has no argument named "$notFound". Check your service definition.');
        $container = new ContainerBuilder();

        $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
        $definition->setArguments(['$notFound' => '123']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);
    }

    public function testCorrectMethodReportedInException()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException');
        $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1": method "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes::createTestDefinition1()" has no argument named "$notFound". Check your service definition.');
        $container = new ContainerBuilder();

        $container->register(FactoryDummyWithoutReturnTypes::class, FactoryDummyWithoutReturnTypes::class);

        $definition = $container->register(TestDefinition1::class, TestDefinition1::class);
        $definition->setFactory([FactoryDummyWithoutReturnTypes::class, 'createTestDefinition1']);
        $definition->setArguments(['$notFound' => '123']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);
    }

    public function testTypedArgument()
    {
        $container = new ContainerBuilder();

        $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
        $definition->setArguments(['$apiKey' => '123', CaseSensitiveClass::class => new Reference('foo')]);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);

        $this->assertEquals([new Reference('foo'), '123'], $definition->getArguments());
    }

    public function testTypedArgumentWithMissingDollar()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException');
        $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": did you forget to add the "$" prefix to argument "apiKey"?');
        $container = new ContainerBuilder();

        $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
        $definition->setArgument('apiKey', '123');

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);
    }

    public function testInterfaceTypedArgument()
    {
        $container = new ContainerBuilder();

        $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
        $definition->setArgument(ContainerInterface::class, $expected = new Reference('foo'));

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);

        $this->assertSame($expected, $definition->getArgument(3));
    }

    public function testResolvesMultipleArgumentsOfTheSameType()
    {
        $container = new ContainerBuilder();

        $definition = $container->register(SimilarArgumentsDummy::class, SimilarArgumentsDummy::class);
        $definition->setArguments([CaseSensitiveClass::class => new Reference('foo'), '$token' => 'qwerty']);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);

        $this->assertEquals([new Reference('foo'), 'qwerty', new Reference('foo')], $definition->getArguments());
    }

    public function testResolvePrioritizeNamedOverType()
    {
        $container = new ContainerBuilder();

        $definition = $container->register(SimilarArgumentsDummy::class, SimilarArgumentsDummy::class);
        $definition->setArguments([CaseSensitiveClass::class => new Reference('foo'), '$token' => 'qwerty', '$class1' => new Reference('bar')]);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);

        $this->assertEquals([new Reference('bar'), 'qwerty', new Reference('foo')], $definition->getArguments());
    }

    public function testVariadics()
    {
        $container = new ContainerBuilder();

        $definition = $container->register(NamedArgumentsVariadicsDummy::class, NamedArgumentsVariadicsDummy::class);
        $definition->setArguments([
            '$class' => new \stdClass(),
            '$variadics' => [
                new Reference('foo'),
                new Reference('bar'),
                new Reference('baz'),
            ],
        ]);

        $pass = new ResolveNamedArgumentsPass();
        $pass->process($container);

        $this->assertEquals(
            [
                0 => new \stdClass(),
                1 => new Reference('foo'),
                2 => new Reference('bar'),
                3 => new Reference('baz'),
            ],
            $definition->getArguments()
        );
    }
}

class NoConstructor
{
    public static function create($apiKey)
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading;
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Tang.Annotations;

namespace Org.Apache.REEF.Examples.Tasks.FailedTask
{
    public class FailedTask : ITask
    {
        [Inject]
        public FailedTask()
        {
        }

        public byte[] Call(byte[] memento)
        {
            Console.WriteLine("I am about to fail.");
            Thread.Sleep(2 * 1000);
            throw new ApplicationException("bite me.");
        }

        public void Dispose()
        {
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Initialize newt</title>

newt_grid_wrapped_window

newt_label_set_text

Newt Functions

PHP Manual

newt_init

(PECL newt >= 0.1)

newt_init — Initialize newt

Description

   int newt_init
    ( void
   )

   Initializes the newt interface. This function must be called before any other newt function.

Return Values

   Returns 1 on success, 0 on failure.

See Also

newt_finished() - Uninitializes newt interface

newt_grid_wrapped_window

newt_label_set_text

Newt Functions

PHP Manual


text:
extern "C"
{
#endif
typedef void (*glXBindTexImageEXTProc) (Display*, GLXDrawable, int, const int*);
typedef void (*glXReleaseTexImageEXTProc) (Display*, GLXDrawable, int);
typedef struct renderer_t renderer_t;
typedef struct kinect_t   kinect_t;

typedef struct riftwin_t
{
  Window            window;
  GLuint            texture;
  Pixmap            pixmap;
  GLXPixmap         glx_pixmap;
  int               glx_bound;
  int               width;
  int               height;
  int               dirty;
  int               mapped;
  int               focused;
  char             *name;
  vec3              pos;
  vec3              rot;
  float             r_width;
  float             r_height;

  struct riftwin_t *next;
} riftwin_t;

typedef struct riftfb_t
{
  GLXFBConfig       config;
  int               depth;
} riftfb_t;

typedef struct riftwm_t
{
  Display                   *dpy;
  int                        screen;
  Window                     root;
  Window                     overlay;
  GLXContext                 context;
  riftfb_t                  *fb_config;
  int                        fb_count;
  glXBindTexImageEXTProc     glXBindTexImageEXT;
  glXReleaseTexImageEXTProc  glXReleaseTexImageEXT;

  int                        screen_width;
  int                        screen_height;

  int                        vcursor_x;
  int                        vcursor_y;
  int                        vcursor_show;

  int                        key_up;
  int                        key_down;
  int                        key_left;
  int                        key_right;

  jmp_buf                    err_jmp;
  char                      *err_msg;

  int                        verbose;
  volatile int               running;
  riftwin_t                 *windows;
  int                        window_count;

  int                        has_rift;
  ohmd_context              *rift_ctx;
  ohmd_device               *rift_dev;
  renderer_t                *renderer;
  kinect_t                  *kinect;
  float                      head_pos[3];
} riftwm_t;

// -----------------------------------------------------------------------------
void riftwm_init(riftwm_t *);
void riftwm_run(riftwm_t *);
void riftwm_scan(riftwm_t *);
void riftwm_destroy(riftwm_t *);
void riftwm_restart(riftwm_t *);
void riftwm_error(riftwm_t *, const char *, ...);
void riftwin_update(riftwm_t *, riftwin_t *);

#ifdef __cplusplus
}
#endif

#endif


text:
package com.jf.djplayer.sortable;

import com.jf.djplayer.bean.Song;

import java.text.CollationKey;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/**
 * Created by JF on 2016/1/5.
 * 根据歌曲名字进行排序
 */
public class SortBySongName implements SongListSortable,Comparator<Song>{

    private Collator collator = Collator.getInstance(Locale.CHINA);

    @Override
    public void sort(List<Song> songInfoList) {

        Collections.sort(songInfoList,this);//调用自定义比较器"this"进行排序
//        Collections.sort(songInfoList,new Comparator<_SongInfo>() {
//            @Override
//            public int compare(_SongInfo lhs, _SongInfo rhs) {
//                return rhs.getSongName().compareTo(lhs.getSongName());
//            }
//        });
    }
//    因为需要对中文做排序所以使用自定义比较器
    @Override
    public int compare(Song lhs,Song rhs) {
            CollationKey key1 = collator
                    .getCollationKey(lhs.getSongName());
            CollationKey key2 = collator
                    .getCollationKey(rhs.getSongName());
            return key1.compareTo(key2);
        }
    }


text:
require "active_support"
require "minitest/autorun"
require "vcr"

require "orchestrate-api"
require "orchestrate-rails"

# Configure Orchestrate-Rails ------------------------------------------------

Orchestrate::Application::Connect.config File.join(File.dirname(__FILE__), "lib", "orch_config-demo.json")
Orchestrate::Rails::Schema.instance.load File.join(File.dirname(__FILE__), "db/schema_rails_test.rb")

# Configure VCR --------------------------------------------------------------

VCR.configure do |c|
  # c.allow_http_connections_when_no_cassette = true
  c.hook_into :webmock
  c.cassette_library_dir = File.join(File.dirname(__FILE__), "fixtures", "vcr_cassettes")
  default_cassette_options = { :record => :all }
end

# Test Helpers ---------------------------------------------------------------

def output_message(name, msg = nil)
  msg = "START TEST" if msg.blank?
  puts "\n======= #{msg}: #{name} ======="
end

# Shared Test Model ---------------------------------------------------------

module Test
  class TestModel < Orchestrate::Rails::Model
  end

  class TestEvent < Orchestrate::Rails::Event
  end
end


text:
package com.streamsets.datacollector.client.api;

import com.streamsets.datacollector.client.ApiClient;
import com.streamsets.datacollector.client.ApiException;
import com.streamsets.datacollector.client.util.TestUtil;
import com.streamsets.datacollector.http.WebServerTask;
import com.streamsets.datacollector.task.Task;
import com.streamsets.testing.NetworkUtils;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class TestSystemApi {
  private String baseURL;
  private String[] authenticationTypes = {"none", "basic", "form", "digest"};

  @Test
  public void testForDifferentAuthenticationTypes() {
    Task server = null;
    try {
      for(String authType: authenticationTypes) {
        int port = NetworkUtils.getRandomPort();
        server = TestUtil.startServer(port, authType);
        baseURL = "http://127.0.0.1:" + port;
        ApiClient apiClient = getApiClient(authType);

        SystemApi systemApi = new SystemApi(apiClient);

        testGetConfiguration(systemApi);
        testGetSDCDirectories(systemApi);
        testGetBuildInfo(systemApi);
        testGetUserInfo(systemApi);
        testGetServerTime(systemApi);
        testGetThreadsDump(systemApi);

        TestUtil.stopServer(server);

      }
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    } finally {
      if(server != null) {
        TestUtil.stopServer(server);
      }
    }
  }

  private ApiClient getApiClient(String authenticationType) {
    ApiClient apiClient = new ApiClient(authenticationType);
    apiClient.setBasePath(baseURL+ "/rest");
    apiClient.setUsername("admin");
    apiClient.setPassword("admin");
    return apiClient;
  }

  public void testGetConfiguration(SystemApi systemApi) throws ApiException  {
    Map<String, Object> configuration = systemApi.getConfiguration();
    Assert.assertNotNull(configuration);
    Assert.assertNotNull(configuration.get(WebServerTask.HTTP_PORT_KEY));
    Assert.assertNotNull(configuration.get(WebServerTask.AUTHENTICATION_KEY));
  }

  public void testGetSDCDirectories(SystemApi systemApi) throws ApiException  {
    Map<String, Object> sdcDirectories = systemApi.getSDCDirectories();
    Assert.assertNotNull(sdcDirectories);
    Assert.assertNotNull(sdcDirectories.get("runtimeDir"));
    Assert.assertNotNull(sdcDirectories.get("configDir"));
    Assert.assertNotNull(sdcDirectories.get("dataDir"));
    Assert.assertNotNull(sdcDirectories.get("logDir"));
    Assert.assertNotNull(sdcDirectories.get("resourcesDir"));
  }

  public void testGetBuildInfo(SystemApi systemApi) throws ApiException {
    Map<String, Object> buildInfo = systemApi.getBuildInfo();
    Assert.assertNotNull(buildInfo);
    Assert.assertNotNull(buildInfo.get("builtDate"));
    Assert.assertNotNull(buildInfo.get("builtBy"));
    Assert.assertNotNull(buildInfo.get("version"));
  }

  public void testGetUserInfo(SystemApi systemApi) throws ApiException  {
    Map<String, Object> userInfo = systemApi.getUserInfo();
    Assert.assertNotNull(userInfo);
    Assert.assertNotNull(userInfo.get("roles"));
    Assert.assertNotNull(userInfo.get("user"));
    Assert.assertEquals(userInfo.get("user"), "admin");
  }

  public void testGetServerTime(SystemApi systemApi) throws ApiException  {
    Map<String, Object> serverTime = systemApi.getServerTime();
    Assert.assertNotNull(serverTime);
    Assert.assertNotNull(serverTime.get("serverTime"));
  }

  public void testGetThreadsDump(SystemApi systemApi) throws ApiException  {
    List<Map<String, Object>> threadsDump = systemApi.getThreadsDump();
    Assert.assertNotNull(threadsDump);
    Assert.assertTrue(threadsDump.size() > 0);
  }

}


text:
set -e  # Exit on error.
set -x  # Make command execution verbose

export P4C_DEPS="bison \
             build-essential \
             cmake \
             curl \
             flex \
             g++ \
             git \
             lld \
             libboost-dev \
             libboost-graph-dev \
             libboost-iostreams1.71-dev \
             libfl-dev \
             libgc-dev \
             pkg-config \
             python3 \
             python3-pip \
             python3-setuptools \
             tcpdump"

export P4C_EBPF_DEPS="libpcap-dev \
             libelf-dev \
             zlib1g-dev \
             llvm \
             clang \
             iproute2 \
             iptables \
             net-tools"

export P4C_RUNTIME_DEPS="cpp \
                     libboost-graph1.71.0 \
                     libboost-iostreams1.71.0 \
                     libgc1c2 \
                     libgmp-dev \
                     python3"

# use scapy 2.4.5, which is the version on which ptf depends
export P4C_PIP_PACKAGES="ipaddr \
                          pyroute2 \
                          ply==3.8 \
                          scapy==2.4.5 \
                          clang-format>=15.0.4"

apt update
apt install -y --no-install-recommends \
  ${P4C_DEPS} \
  ${P4C_EBPF_DEPS} \
  ${P4C_RUNTIME_DEPS}

# TODO: Remove this rm -rf line once the ccache memcache config (https://github.com/p4lang/third-party/blob/main/Dockerfile#L72) is removed.
rm -rf /usr/local/etc/ccache.conf
/usr/local/bin/ccache --set-config cache_dir=/p4c/.ccache
/usr/local/bin/ccache --set-config max_size=1G

# we want to use Python as the default so change the symlinks
ln -sf /usr/bin/python3 /usr/bin/python
ln -sf /usr/bin/pip3 /usr/bin/pip

pip3 install wheel
pip3 install $P4C_PIP_PACKAGES

# Build libbpf for eBPF tests.
cd /p4c
backends/ebpf/build_libbpf
cd /p4c

# ! ------  BEGIN PTF_EBPF -----------------------------------------------
function install_ptf_ebpf_test_deps() (
  # Install linux-tools for specified kernels and for current one
  LINUX_TOOLS="linux-tools-`uname -r`"
  for version in $KERNEL_VERSIONS; do
    LINUX_TOOLS+=" linux-tools-$version-generic"
  done
  export P4C_PTF_PACKAGES="gcc-multilib \
                           python3-six \
                           libgmp-dev \
                           libjansson-dev"
  apt install -y --no-install-recommends ${P4C_PTF_PACKAGES}

  if apt-cache show ${LINUX_TOOLS}; then
    apt install -y --no-install-recommends ${LINUX_TOOLS}
  fi

  git clone --depth 1 --recursive --branch v0.2.0 https://github.com/NIKSS-vSwitch/nikss /tmp/nikss
  cd /tmp/nikss
  ./build_libbpf.sh
  mkdir build
  cd build
  cmake -DCMAKE_BUILD_TYPE=Release ..
  make "-j$(nproc)"
  make install

  # install bpftool
  git clone --recurse-submodules https://github.com/libbpf/bpftool.git /tmp/bpftool
  cd /tmp/bpftool/src
  make "-j$(nproc)"
  make install
)
# ! ------  END PTF_EBPF -----------------------------------------------

if [[ "${INSTALL_PTF_EBPF_DEPENDENCIES}" == "ON" ]] ; then
  install_ptf_ebpf_test_deps
fi

# ! ------  BEGIN VALIDATION -----------------------------------------------
function build_gauntlet() {
  # For add-apt-repository.
  apt install -y software-properties-common
  # Symlink the toz3 extension for the p4 compiler.
  mkdir -p /p4c/extensions
  git clone -b stable https://github.com/p4gauntlet/toz3 /p4c/extensions/toz3
  # The interpreter requires boost filesystem for file management.
  apt install -y libboost-filesystem-dev
  # Disable failures on crashes
  CMAKE_FLAGS+="-DVALIDATION_IGNORE_CRASHES=ON "
}

# These steps are necessary to validate the correct compilation of the P4C test
# suite programs. See also https://github.com/p4gauntlet/gauntlet.
if [ "$VALIDATION" == "ON" ]; then
  build_gauntlet
fi
# ! ------  END VALIDATION -----------------------------------------------

# ! ------  BEGIN P4TESTGEN -----------------------------------------------
function build_tools_deps() {
  # This is needed for P4Testgen.
  apt install -y libboost-filesystem-dev libboost-system-dev wget zip

  # Install a recent version of Z3
  Z3_VERSION="z3-4.8.14"
  Z3_DIST="${Z3_VERSION}-x64-glibc-2.31"

  cd /tmp
  wget https://github.com/Z3Prover/z3/releases/download/${Z3_VERSION}/${Z3_DIST}.zip
  unzip ${Z3_DIST}.zip
  cp -r ${Z3_DIST}/bin/libz3.* /usr/local/lib/
  cp -r ${Z3_DIST}/include/* /usr/local/include/
  cd /p4c
  rm -rf /tmp/${Z3_DIST}
}
# ! ------  END P4TESTGEN -----------------------------------------------

# Build the dependencies necessary for the P4Tools platform.
if [ "$ENABLE_TEST_TOOLS" == "ON" ]; then
  build_tools_deps
fi
# ! ------  END TOOLS -----------------------------------------------

# Build with Clang instead of GCC.
if [ "$COMPILE_WITH_CLANG" == "ON" ]; then
  export CC=clang
  export CXX=clang++
fi

# Strong optimization.
export CXXFLAGS="${CXXFLAGS} -O3"
# Toggle unified compilation.
CMAKE_FLAGS+="-DENABLE_UNIFIED_COMPILATION=${ENABLE_UNIFIED_COMPILATION} "
# Toggle static builds.
CMAKE_FLAGS+="-DBUILD_STATIC_RELEASE=${BUILD_STATIC_RELEASE} "
# Toggle the installation of the tools back end.
CMAKE_FLAGS+="-DENABLE_TEST_TOOLS=${ENABLE_TEST_TOOLS} "
# RELEASE should be default, but we want to make sure.
CMAKE_FLAGS+="-DCMAKE_BUILD_TYPE=RELEASE "
# Treat warnings as errors.
CMAKE_FLAGS+="-DENABLE_WERROR=${ENABLE_WERROR} "
# Enable sanitizers.
CMAKE_FLAGS+="-DENABLE_SANITIZERS=${ENABLE_SANITIZERS} "
# Enable auto var initialization with pattern.
CMAKE_FLAGS+="-DBUILD_AUTO_VAR_INIT_PATTERN=${BUILD_AUTO_VAR_INIT_PATTERN} "

# Run CMake in the build folder.
if [ -e build ]; then /bin/rm -rf build; fi
mkdir -p build
cd build
cmake ${CMAKE_FLAGS} ..

# If CMAKE_ONLY is active, only run CMake. Do not build.
if [ "$CMAKE_ONLY" == "OFF" ]; then
  make
  make install
  # Print ccache statistics after building
  /usr/local/bin/ccache -p -s
fi

if [[ "${IMAGE_TYPE}" == "build" ]] ; then
  apt purge -y ${P4C_DEPS} git
  apt autoremove --purge -y
  rm -rf /p4c /var/cache/apt/* /var/lib/apt/lists/*
  echo 'Build image ready'

elif [[ "${IMAGE_TYPE}" == "test" ]] ; then
  echo 'Test image ready'

fi


text:
//
//  TagService.java
//  blogwt
//
//  Created by William Shakour on July 15, 2015.
//  Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.server.service.tag;

import static com.willshex.blogwt.server.helper.PersistenceHelper.id;
import static com.willshex.blogwt.server.helper.PersistenceHelper.keyToId;
import static com.willshex.blogwt.server.service.persistence.PersistenceServiceProvider.provide;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Work;
import com.googlecode.objectify.cmd.LoadType;
import com.willshex.blogwt.server.helper.PersistenceHelper;
import com.willshex.blogwt.server.service.post.PostServiceProvider;
import com.willshex.blogwt.shared.api.Pager;
import com.willshex.blogwt.shared.api.SortDirectionType;
import com.willshex.blogwt.shared.api.datatype.Post;
import com.willshex.blogwt.shared.api.datatype.PostSortType;
import com.willshex.blogwt.shared.api.datatype.Tag;
import com.willshex.blogwt.shared.helper.DataTypeHelper;
import com.willshex.blogwt.shared.helper.PagerHelper;
import com.willshex.blogwt.shared.helper.PostHelper;

final class TagService implements ITagService {
	public String getName () {
		return NAME;
	}

	@Override
	public Tag getTag (Long id) {
		return id(load(), id);
	}

	private LoadType<Tag> load () {
		return provide().load().type(Tag.class);
	}

	@Override
	public Tag addTag (Tag tag) {
		if (tag.created == null) {
			tag.created = new Date();
		}

		tag.name = tag.name.toLowerCase();
		tag.slug = PostHelper.slugify(tag.name);

		if (tag.posts != null) {
			for (Post post : tag.posts) {
				if (tag.postKeys == null) {
					tag.postKeys = new ArrayList<Key<Post>>();
				}

				tag.postKeys.add(Key.create(post));
			}
		}

		Key<Tag> key = provide().save().entity(tag).now();
		tag.id = keyToId(key);

		return tag;
	}

	@Override
	public void deleteTag (Tag tag) {
		provide().delete().entity(tag).now();
	}

	/* (non-Javadoc)
	 *
	 * @see com.willshex.blogwt.server.service.tag.ITagService#getTags() */
	@Override
	public List<Tag> getTags () {
		return load().list();
	}

	/* (non-Javadoc)
	 *
	 * @see com.willshex.blogwt.server.service.tag.ITagService#generateTags() */
	@Override
	public void generateTags () {
		Map<String, Tag> tagLookup = new HashMap<String, Tag>();
		List<Post> posts;
		Tag tag;

		Pager pager = PagerHelper.createDefaultPager();

		do {
			posts = PostServiceProvider.provide().getPosts(Boolean.FALSE,
					Boolean.FALSE, pager.start, pager.count,
					PostSortType.PostSortTypePublished,
					SortDirectionType.SortDirectionTypeDescending);

			if (posts != null) {
				PagerHelper.moveForward(pager);

				for (Post post : posts) {
					if (post.tags != null) {
						for (String postTag : post.tags) {
							tag = tagLookup.get(postTag.toLowerCase());

							if (tag == null) {
								tag = new Tag().name(postTag.toLowerCase())
										.posts(new ArrayList<Post>());
								tagLookup.put(tag.name, tag);
							}

							tag.posts.add(post);
						}
					}
				}
			}
		} while (posts != null && posts.size() >= pager.count.intValue());

		if (tagLookup.size() > 0) {
			addTagBatch(tagLookup.values());
		}

	}

	/* (non-Javadoc)
	 *
	 * @see com.willshex.blogwt.server.service.tag.ITagService#addTagBatch(java.
	 * util.Collection) */
	@Override
	public void addTagBatch (Collection<Tag> tags) {
		for (Tag tag : tags) {
			if (tag.created == null) {
				tag.created = new Date();
			}

			tag.name = tag.name.toLowerCase();
			tag.slug = PostHelper.slugify(tag.name);

			if (tag.posts != null) {
				for (Post post : tag.posts) {
					if (tag.postKeys == null) {
						tag.postKeys = new ArrayList<Key<Post>>();
					}

					tag.postKeys.add(Key.create(post));
				}
			}
		}

		provide().save().entities(tags).now();
	}

	/* (non-Javadoc)
	 *
	 * @see com.willshex.blogwt.server.service.tag.ITagService#getSlugTag(java.
	 * lang.String) */
	@Override
	public Tag getSlugTag (String slug) {
		return PersistenceHelper.one(load().filter("slug", slug));
	}

	/* (non-Javadoc)
	 *
	 * @see com.willshex.blogwt.server.service.tag.ITagService#addTagPost(com.
	 * willshex .blogwt.shared.api.datatype.Tag,
	 * com.willshex.blogwt.shared.api.datatype.Post) */
	@Override
	public void addTagPost (final Tag tag, final Post post) {
		provide().transact(new Work<Void>() {

			@Override
			public Void run () {
				Tag latest = getTag(tag.id);

				if (latest.postKeys == null) {
					latest.postKeys = new ArrayList<Key<Post>>();
				}

				boolean found = false;
				for (Key<Post> key : latest.postKeys) {
					if (DataTypeHelper.<Post> same(key, post)) {
						found = true;
						break;
					}
				}

				if (!found) {
					latest.postKeys.add(Key.create(post));
				}

				provide().save().entity(latest).now();

				return null;
			}
		});
	}

	/* (non-Javadoc)
	 *
	 * @see com.willshex.blogwt.server.service.tag.ITagService#removeTagPost(com
	 * .willshex.blogwt.shared.api.datatype.Tag,
	 * com.willshex.blogwt.shared.api.datatype.Post) */
	@Override
	public void removeTagPost (final Tag tag, final Post post) {
		provide().transact(new Work<Void>() {

			@Override
			public Void run () {
				Tag latest = getTag(tag.id);

				if (latest.postKeys == null) {
					latest.postKeys = new ArrayList<Key<Post>>();
				}

				Key<Post> foundKey = null;
				for (Key<Post> key : latest.postKeys) {
					if (DataTypeHelper.<Post> same(key, post)) {
						foundKey = key;
						break;
					}
				}

				if (foundKey != null) {
					if (latest.postKeys.size() == 1) {
						deleteTag(latest);
					} else {
						latest.postKeys.remove(foundKey);
						provide().save().entity(latest).now();
					}
				}

				return null;
			}
		});
	}
}


text:
package ru.yandex.money.api.rights;

/**
 * Право на получение информации о состоянии счета
 * @author dvmelnikov
 */

public class AccountInfo extends AbstractPermission {
    public AccountInfo() {
        super("account-info");
    }
}


text:
use protocol::{self, mojang, packet};
use world;
use world::block;
use rand::{self, Rng};
use std::sync::{Arc, RwLock};
use std::sync::mpsc;
use std::thread;
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use types::hash::FNVHash;
use resources;
use render;
use settings::Stevenkey;
use ecs;
use entity;
use cgmath::{self, Point};
use types::Gamemode;
use shared::{Axis, Position};
use format;

mod sun;
pub mod plugin_messages;
pub mod target;

pub struct Server {
    username: String,
    uuid: protocol::UUID,
    conn: Option<protocol::Conn>,
    read_queue: Option<mpsc::Receiver<Result<packet::Packet, protocol::Error>>>,
    pub disconnect_reason: Option<format::Component>,
    just_disconnected: bool,

    pub world: world::World,
    pub entities: ecs::Manager,
    world_age: i64,
    world_time: f64,
    world_time_target: f64,
    tick_time: bool,

    resources: Arc<RwLock<resources::Manager>>,
    version: usize,

    // Entity accessors
    game_info: ecs::Key<entity::GameInfo>,
    player_movement: ecs::Key<entity::player::PlayerMovement>,
    gravity: ecs::Key<entity::Gravity>,
    position: ecs::Key<entity::Position>,
    target_position: ecs::Key<entity::TargetPosition>,
    velocity: ecs::Key<entity::Velocity>,
    gamemode: ecs::Key<Gamemode>,
    pub rotation: ecs::Key<entity::Rotation>,
    target_rotation: ecs::Key<entity::TargetRotation>,
    //

    pub player: Option<ecs::Entity>,
    entity_map: HashMap<i32, ecs::Entity, BuildHasherDefault<FNVHash>>,
    players: HashMap<protocol::UUID, PlayerInfo, BuildHasherDefault<FNVHash>>,

    tick_timer: f64,
    entity_tick_timer: f64,

    sun_model: Option<sun::SunModel>,
    target_info: target::Info,
}

pub struct PlayerInfo {
    name: String,
    uuid: protocol::UUID,
    skin_url: Option<String>,

    display_name: Option<format::Component>,
    ping: i32,
    gamemode: Gamemode,
}

macro_rules! handle_packet {
    ($s:ident $pck:ident {
        $($packet:ident => $func:ident,)*
    }) => (
        match $pck {
        $(
            protocol::packet::Packet::$packet(val) => $s.$func(val),
        )*
            _ => {},
        }
    )
}

impl Server {

    pub fn connect(resources: Arc<RwLock<resources::Manager>>, profile: mojang::Profile, address: &str) -> Result<Server, protocol::Error> {
        use openssl::crypto::pkey;
        use openssl::crypto::rand::rand_bytes;
        let mut conn = try!(protocol::Conn::new(address));

        let host = conn.host.clone();
        let port = conn.port;
        try!(conn.write_packet(protocol::packet::handshake::serverbound::Handshake {
             protocol_version: protocol::VarInt(protocol::SUPPORTED_PROTOCOL),
             host: host,
             port: port,
             next: protocol::VarInt(2),
         }));
        conn.state = protocol::State::Login;
        try!(conn.write_packet(protocol::packet::login::serverbound::LoginStart {
            username: profile.username.clone(),
        }));

        let packet;
        loop {
            match try!(conn.read_packet()) {
                protocol::packet::Packet::SetInitialCompression(val) => {
                    conn.set_compresssion(val.threshold.0);
                },
                protocol::packet::Packet::EncryptionRequest(val) => {
                    packet = val;
                    break;
                },
                protocol::packet::Packet::LoginSuccess(val) => {
                    warn!("Server is running in offline mode");
                    debug!("Login: {} {}", val.username, val.uuid);
                    let mut read = conn.clone();
                    let mut write = conn.clone();
                    read.state = protocol::State::Play;
                    write.state = protocol::State::Play;
                    let rx = Self::spawn_reader(read);
                    return Ok(Server::new(val.username, protocol::UUID::from_str(&val.uuid), resources, Some(write), Some(rx)));
                }
                protocol::packet::Packet::LoginDisconnect(val) => return Err(protocol::Error::Disconnect(val.reason)),
                val => return Err(protocol::Error::Err(format!("Wrong packet: {:?}", val))),
            };
        }

        let mut key = pkey::PKey::new();
        key.load_pub(&packet.public_key.data);
        let shared = rand_bytes(16);

        let shared_e = key.public_encrypt_with_padding(&shared, pkey::EncryptionPadding::PKCS1v15);
        let token_e = key.public_encrypt_with_padding(&packet.verify_token.data, pkey::EncryptionPadding::PKCS1v15);

        try!(profile.join_server(&packet.server_id, &shared, &packet.public_key.data));

        try!(conn.write_packet(protocol::packet::login::serverbound::EncryptionResponse {
            shared_secret: protocol::LenPrefixedBytes::new(shared_e),
            verify_token: protocol::LenPrefixedBytes::new(token_e),
        }));

        let mut read = conn.clone();
        let mut write = conn.clone();

        read.enable_encyption(&shared, true);
        write.enable_encyption(&shared, false);

        let username;
        let uuid;
        loop {
           match try!(read.read_packet()) {
               protocol::packet::Packet::SetInitialCompression(val) => {
                   read.set_compresssion(val.threshold.0);
                   write.set_compresssion(val.threshold.0);
               }
               protocol::packet::Packet::LoginSuccess(val) => {
                   debug!("Login: {} {}", val.username, val.uuid);
                   username = val.username;
                   uuid = val.uuid;
                   read.state = protocol::State::Play;
                   write.state = protocol::State::Play;
                   break;
               }
               protocol::packet::Packet::LoginDisconnect(val) => return Err(protocol::Error::Disconnect(val.reason)),
               val => return Err(protocol::Error::Err(format!("Wrong packet: {:?}", val))),
           }
        }

        let rx = Self::spawn_reader(read);

        Ok(Server::new(username, protocol::UUID::from_str(&uuid), resources, Some(write), Some(rx)))
    }

    fn spawn_reader(mut read: protocol::Conn) -> mpsc::Receiver<Result<packet::Packet, protocol::Error>> {
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            loop {
                let pck = read.read_packet();
                let was_error = pck.is_err();
                if let Err(_) = tx.send(pck) {
                    return;
                }
                if was_error {
                    return;
                }
            }
        });
        rx
    }

    pub fn dummy_server(resources: Arc<RwLock<resources::Manager>>) -> Server {
        let mut server = Server::new("dummy".to_owned(), protocol::UUID::default(), resources, None, None);
        let mut rng = rand::thread_rng();
        for x in -7*16 .. 7*16 {
            for z in -7*16 .. 7*16 {
                let h = 5 + (6.0 * (x as f64 / 16.0).cos() * (z as f64 / 16.0).sin()) as i32;
                for y in 0 .. h {
                    server.world.set_block(Position::new(x, y, z), block::Dirt{ snowy: false, variant: block::DirtVariant::Normal });
                }
                server.world.set_block(Position::new(x, h, z), block::Grass{ snowy: false });

                if x*x + z*z > 16*16 && rng.gen_weighted_bool(80) {
                    for i in 0 .. 5 {
                        server.world.set_block(Position::new(x, h + 1 + i, z), block::Log{ axis: Axis::Y, variant: block::TreeVariant::Oak });
                    }
                    for xx in -2 .. 3 {
                        for zz in -2 .. 3 {
                            if xx == 0 && z == 0 {
                                continue;
                            }
                            server.world.set_block(Position::new(x + xx, h + 3, z + zz), block::Leaves{ variant: block::TreeVariant::Oak, check_decay: false, decayable: false });
                            server.world.set_block(Position::new(x + xx, h + 4, z + zz), block::Leaves{ variant: block::TreeVariant::Oak, check_decay: false, decayable: false });
                            if xx.abs() <= 1 && zz.abs() <= 1 {
                                server.world.set_block(Position::new(x + xx, h + 5, z + zz), block::Leaves{ variant: block::TreeVariant::Oak, check_decay: false, decayable: false });
                            }
                            if xx * xx + zz * zz <= 1 {
                                server.world.set_block(Position::new(x + xx, h + 6, z + zz), block::Leaves{ variant: block::TreeVariant::Oak, check_decay: false, decayable: false });
                            }
                        }
                    }
                }
            }
        }
        server
    }

    fn new(
        username: String, uuid: protocol::UUID,
        resources: Arc<RwLock<resources::Manager>>,
        conn: Option<protocol::Conn>, read_queue: Option<mpsc::Receiver<Result<packet::Packet, protocol::Error>>>
    ) -> Server {
        let mut entities = ecs::Manager::new();
        entity::add_systems(&mut entities);

        let world_entity = entities.get_world();
        let game_info = entities.get_key();
        entities.add_component(world_entity, game_info, entity::GameInfo::new());

        let version = resources.read().unwrap().version();
        Server {
            username: username,
            uuid: uuid,
            conn: conn,
            read_queue: read_queue,
            disconnect_reason: None,
            just_disconnected: false,

            world: world::World::new(),
            world_age: 0,
            world_time: 0.0,
            world_time_target: 0.0,
            tick_time: true,

            version: version,
            resources: resources,

            // Entity accessors
            game_info: game_info,
            player_movement: entities.get_key(),
            gravity: entities.get_key(),
            position: entities.get_key(),
            target_position: entities.get_key(),
            velocity: entities.get_key(),
            gamemode: entities.get_key(),
            rotation: entities.get_key(),
            target_rotation: entities.get_key(),
            //

            entities: entities,
            player: None,
            entity_map: HashMap::with_hasher(BuildHasherDefault::default()),
            players: HashMap::with_hasher(BuildHasherDefault::default()),

            tick_timer: 0.0,
            entity_tick_timer: 0.0,
            sun_model: None,

            target_info: target::Info::new(),
        }
    }

    pub fn disconnect(&mut self, reason: Option<format::Component>) {
        self.conn = None;
        self.disconnect_reason = reason;
        if let Some(player) = self.player.take() {
            self.entities.remove_entity(player);
        }
        self.just_disconnected = true;
    }

    pub fn is_connected(&self) -> bool {
        self.conn.is_some()
    }

    pub fn tick(&mut self, renderer: &mut render::Renderer, delta: f64) {
        let version = self.resources.read().unwrap().version();
        if version != self.version {
            self.version = version;
            self.world.flag_dirty_all();
        }
        // TODO: Check if the world type actually needs a sun
        if self.sun_model.is_none() {
            self.sun_model = Some(sun::SunModel::new(renderer));
        }

        // Copy to camera
        if let Some(player) = self.player {
            let position = self.entities.get_component(player, self.position).unwrap();
            let rotation = self.entities.get_component(player, self.rotation).unwrap();
            renderer.camera.pos = cgmath::Point::from_vec(position.position + cgmath::Vector3::new(0.0, 1.62, 0.0));
            renderer.camera.yaw = rotation.yaw;
            renderer.camera.pitch = rotation.pitch;
        }
        self.entity_tick(renderer, delta);

        self.tick_timer += delta;
        while self.tick_timer >= 3.0 && self.is_connected() {
            self.minecraft_tick();
            self.tick_timer -= 3.0;
        }

        self.update_time(renderer, delta);

        if let Some(sun_model) = self.sun_model.as_mut() {
            sun_model.tick(renderer, self.world_time, self.world_age);
        }

        self.world.tick(&mut self.entities);

        if self.player.is_some() {
            if let Some((pos, bl, _, _)) = target::trace_ray(&self.world, 4.0, renderer.camera.pos.to_vec(), renderer.view_vector.cast(), target::test_block) {
                self.target_info.update(renderer, pos, bl);
            } else {
                self.target_info.clear(renderer);
            }
        } else {
            self.target_info.clear(renderer);
        }
    }

    fn entity_tick(&mut self, renderer: &mut render::Renderer, delta: f64) {
        let world_entity = self.entities.get_world();
        // Update the game's state for entities to read
        self.entities.get_component_mut(world_entity, self.game_info)
            .unwrap().delta = delta;

        // Packets modify entities so need to handled here
        if let Some(rx) = self.read_queue.take() {
            while let Ok(pck) = rx.try_recv() {
                match pck {
                    Ok(pck) => handle_packet!{
                        self pck {
                            JoinGame => on_game_join,
                            Respawn => on_respawn,
                            KeepAliveClientbound => on_keep_alive,
                            ChunkData => on_chunk_data,
                            ChunkUnload => on_chunk_unload,
                            BlockChange => on_block_change,
                            MultiBlockChange => on_multi_block_change,
                            TeleportPlayer => on_teleport,
                            TimeUpdate => on_time_update,
                            ChangeGameState => on_game_state_change,
                            UpdateBlockEntity => on_block_entity_update,
                            PlayerInfo => on_player_info,
                            Disconnect => on_disconnect,
                            // Entities
                            EntityDestroy => on_entity_destroy,
                            SpawnPlayer => on_player_spawn,
                            EntityTeleport => on_entity_teleport,
                            EntityMove => on_entity_move,
                            EntityLook => on_entity_look,
                            EntityLookAndMove => on_entity_look_and_move,
                        }
                    },
                    Err(err) => panic!("Err: {:?}", err),
                }
                // Disconnected
                if self.conn.is_none() {
                    break;
                }
            }

            if self.conn.is_some() {
                self.read_queue = Some(rx);
            }
        }

        if self.is_connected() || self.just_disconnected { // Allow an extra tick when disconnected to clean up
            self.just_disconnected = false;
            self.entity_tick_timer += delta;
            while self.entity_tick_timer >= 3.0 {
                self.entities.tick(&mut self.world, renderer);
                self.entity_tick_timer -= 3.0;
            }

            self.entities.render_tick(&mut self.world, renderer);
        }
    }

    pub fn remove(&mut self, renderer: &mut render::Renderer) {
        self.entities.remove_all_entities(&mut self.world, renderer);
        if let Some(mut sun_model) = self.sun_model.take() {
            sun_model.remove(renderer);
        }
        self.target_info.clear(renderer);
    }

    fn update_time(&mut self, renderer: &mut render::Renderer, delta: f64) {
        if self.tick_time {
            self.world_time_target += delta / 3.0;
            self.world_time_target = (24000.0 + self.world_time_target) % 24000.0;
            let mut diff = self.world_time_target - self.world_time;
            if diff < -12000.0 {
                diff += 24000.0
            } else if diff > 12000.0 {
                diff -= 24000.0
            }
            self.world_time += diff * (1.5 / 60.0) * delta;
            self.world_time = (24000.0 + self.world_time) % 24000.0;
        } else {
            self.world_time = self.world_time_target;
        }
        renderer.sky_offset = self.calculate_sky_offset();
    }

    fn calculate_sky_offset(&self) -> f32 {
        use std::f32::consts::PI;
        let mut offset = ((1.0 + self.world_time as f32) / 24000.0) - 0.25;
        if offset < 0.0 {
            offset += 1.0;
        } else if offset > 1.0 {
            offset -= 1.0;
        }

        let prev_offset = offset;
        offset = 1.0 - (((offset * PI).cos() + 1.0) / 2.0);
        offset = prev_offset + (offset - prev_offset) / 3.0;

        offset = 1.0 - ((offset * PI * 2.0).cos() * 2.0 + 0.2);
        if offset > 1.0 {
            offset = 1.0;
        } else if offset < 0.0 {
            offset = 0.0;
        }
        offset = 1.0 - offset;
        offset * 0.8 + 0.2
    }

    pub fn minecraft_tick(&mut self) {
        use std::f32::consts::PI;
        if let Some(player) = self.player {
            let movement = self.entities.get_component_mut(player, self.player_movement).unwrap();
            let on_ground = self.entities.get_component(player, self.gravity).map_or(false, |v| v.on_ground);
            let position = self.entities.get_component(player, self.target_position).unwrap();
            let rotation = self.entities.get_component(player, self.rotation).unwrap();

            // Force the server to know when touched the ground
            // otherwise if it happens between ticks the server
            // will think we are flying.
            let on_ground = if movement.did_touch_ground {
                movement.did_touch_ground = false;
                true
            } else {
                on_ground
            };

            // Sync our position to the server
            // Use the smaller packets when possible
            let packet = packet::play::serverbound::PlayerPositionLook {
                x: position.position.x,
                y: position.position.y,
                z: position.position.z,
                yaw: -(rotation.yaw as f32) * (180.0 / PI),
                pitch: (-rotation.pitch as f32) * (180.0 / PI) + 180.0,
                on_ground: on_ground,
            };
            self.write_packet(packet);
        }
    }

    pub fn key_press(&mut self, down: bool, key: Stevenkey) {
        if let Some(player) = self.player {
            if let Some(movement) = self.entities.get_component_mut(player, self.player_movement) {
                movement.pressed_keys.insert(key, down);
            }
        }
    }

    pub fn on_right_click(&mut self, renderer: &mut render::Renderer) {
        use shared::Direction;
        if self.player.is_some() {
            if let Some((pos, _, face, at)) = target::trace_ray(&self.world, 4.0, renderer.camera.pos.to_vec(), renderer.view_vector.cast(), target::test_block) {
                self.write_packet(packet::play::serverbound::PlayerBlockPlacement {
                    location: pos,
                    face: protocol::VarInt(match face {
                        Direction::Down => 0,
                        Direction::Up => 1,
                        Direction::North => 2,
                        Direction::South => 3,
                        Direction::West => 4,
                        Direction::East => 5,
                        _ => unreachable!(),
                    }),
                    hand: protocol::VarInt(0),
                    cursor_x: at.x as f32,
                    cursor_y: at.y as f32,
                    cursor_z: at.z as f32
                });
            }
        }
    }

    pub fn write_packet<T: protocol::PacketType>(&mut self, p: T) {
        let _ = self.conn.as_mut().unwrap().write_packet(p); // TODO handle errors
    }

    fn on_keep_alive(&mut self, keep_alive: packet::play::clientbound::KeepAliveClientbound) {
        self.write_packet(packet::play::serverbound::KeepAliveServerbound {
            id: keep_alive.id,
        });
    }

    fn on_game_join(&mut self, join: packet::play::clientbound::JoinGame) {
        let gamemode = Gamemode::from_int((join.gamemode & 0x7) as i32);
        let player = entity::player::create_local(&mut self.entities);
        if let Some(info) = self.players.get(&self.uuid) {
            let model = self.entities.get_component_mut_direct::<entity::player::PlayerModel>(player).unwrap();
            model.set_skin(info.skin_url.clone());
        }
        *self.entities.get_component_mut(player, self.gamemode).unwrap() = gamemode;
        // TODO: Temp
        self.entities.get_component_mut(player, self.player_movement).unwrap().flying = gamemode.can_fly();

        self.entity_map.insert(join.entity_id, player);
        self.player = Some(player);

        // Let the server know who we are
        self.write_packet(plugin_messages::Brand {
            brand: "Steven".into(),
        }.as_message());
    }

    fn on_respawn(&mut self, respawn: packet::play::clientbound::Respawn) {
        self.world = world::World::new();
        let gamemode = Gamemode::from_int((respawn.gamemode & 0x7) as i32);

        if let Some(player) = self.player {
            *self.entities.get_component_mut(player, self.gamemode).unwrap() = gamemode;
            // TODO: Temp
            self.entities.get_component_mut(player, self.player_movement).unwrap().flying = gamemode.can_fly();
        }
    }

    fn on_disconnect(&mut self, disconnect: packet::play::clientbound::Disconnect) {
        self.disconnect(Some(disconnect.reason));
    }

    fn on_time_update(&mut self, time_update: packet::play::clientbound::TimeUpdate) {
        self.world_age = time_update.time_of_day;
        self.world_time_target = (time_update.time_of_day % 24000) as f64;
        if self.world_time_target < 0.0 {
            self.world_time_target = -self.world_time_target;
            self.tick_time = false;
        } else {
            self.tick_time = true;
        }
    }

    fn on_game_state_change(&mut self, game_state: packet::play::clientbound::ChangeGameState) {
        if game_state.reason == 3 {
            if let Some(player) = self.player {
                let gamemode = Gamemode::from_int(game_state.value as i32);
                *self.entities.get_component_mut(player, self.gamemode).unwrap() = gamemode;
                // TODO: Temp
                self.entities.get_component_mut(player, self.player_movement).unwrap().flying = gamemode.can_fly();
            }
        }
    }

    fn on_entity_destroy(&mut self, entity_destroy: packet::play::clientbound::EntityDestroy) {
        for id in entity_destroy.entity_ids.data {
            if let Some(entity) = self.entity_map.remove(&id.0) {
                self.entities.remove_entity(entity);
            }
        }
    }

    fn on_entity_teleport(&mut self, entity_telport: packet::play::clientbound::EntityTeleport) {
        use std::f64::consts::PI;
        if let Some(entity) = self.entity_map.get(&entity_telport.entity_id.0) {
            let target_position = self.entities.get_component_mut(*entity, self.target_position).unwrap();
            let target_rotation = self.entities.get_component_mut(*entity, self.target_rotation).unwrap();
            target_position.position.x = entity_telport.x;
            target_position.position.y = entity_telport.y;
            target_position.position.z = entity_telport.z;
            target_rotation.yaw = -((entity_telport.yaw as f64) / 256.0) * PI * 2.0;
            target_rotation.pitch = -((entity_telport.pitch as f64) / 256.0) * PI * 2.0;
        }
    }

    fn on_entity_move(&mut self, m: packet::play::clientbound::EntityMove) {
        if let Some(entity) = self.entity_map.get(&m.entity_id.0) {
            let position = self.entities.get_component_mut(*entity, self.target_position).unwrap();
            position.position.x += m.delta_x as f64 / (32.0 * 128.0);
            position.position.y += m.delta_y as f64 / (32.0 * 128.0);
            position.position.z += m.delta_z as f64 / (32.0 * 128.0);
        }
    }

    fn on_entity_look(&mut self, look: packet::play::clientbound::EntityLook) {
        use std::f64::consts::PI;
        if let Some(entity) = self.entity_map.get(&look.entity_id.0) {
            let rotation = self.entities.get_component_mut(*entity, self.target_rotation).unwrap();
            rotation.yaw = -((look.yaw as f64) / 256.0) * PI * 2.0;
            rotation.pitch = -((look.pitch as f64) / 256.0) * PI * 2.0;
        }
    }

    fn on_entity_look_and_move(&mut self, lookmove: packet::play::clientbound::EntityLookAndMove) {
        use std::f64::consts::PI;
        if let Some(entity) = self.entity_map.get(&lookmove.entity_id.0) {
            let position = self.entities.get_component_mut(*entity, self.target_position).unwrap();
            let rotation = self.entities.get_component_mut(*entity, self.target_rotation).unwrap();
            position.position.x += lookmove.delta_x as f64 / (32.0 * 128.0);
            position.position.y += lookmove.delta_y as f64 / (32.0 * 128.0);
            position.position.z += lookmove.delta_z as f64 / (32.0 * 128.0);
            rotation.yaw = -((lookmove.yaw as f64) / 256.0) * PI * 2.0;
            rotation.pitch = -((lookmove.pitch as f64) / 256.0) * PI * 2.0;
        }
    }

    fn on_player_spawn(&mut self, spawn: packet::play::clientbound::SpawnPlayer) {
        use std::f64::consts::PI;
        if let Some(entity) = self.entity_map.remove(&spawn.entity_id.0) {
            self.entities.remove_entity(entity);
        }
        let entity = entity::player::create_remote(&mut self.entities, self.players.get(&spawn.uuid).map_or("MISSING", |v| &v.name));
        let position = self.entities.get_component_mut(entity, self.position).unwrap();
        let target_position = self.entities.get_component_mut(entity, self.target_position).unwrap();
        let rotation = self.entities.get_component_mut(entity, self.rotation).unwrap();
        let target_rotation = self.entities.get_component_mut(entity, self.target_rotation).unwrap();
        position.position.x = spawn.x;
        position.position.y = spawn.y;
        position.position.z = spawn.z;
        target_position.position.x = spawn.x;
        target_position.position.y = spawn.y;
        target_position.position.z = spawn.z;
        rotation.yaw = -((spawn.yaw as f64) / 256.0) * PI * 2.0;
        rotation.pitch = -((spawn.pitch as f64) / 256.0) * PI * 2.0;
        target_rotation.yaw = rotation.yaw;
        target_rotation.pitch = rotation.pitch;
        if let Some(info) = self.players.get(&spawn.uuid) {
            let model = self.entities.get_component_mut_direct::<entity::player::PlayerModel>(entity).unwrap();
            model.set_skin(info.skin_url.clone());
        }
        self.entity_map.insert(spawn.entity_id.0, entity);
    }

    fn on_teleport(&mut self, teleport: packet::play::clientbound::TeleportPlayer) {
        use std::f64::consts::PI;
        if let Some(player) = self.player {
            let position = self.entities.get_component_mut(player, self.target_position).unwrap();
            let rotation = self.entities.get_component_mut(player, self.rotation).unwrap();
            let velocity = self.entities.get_component_mut(player, self.velocity).unwrap();

            position.position.x = calculate_relative_teleport(TeleportFlag::RelX, teleport.flags, position.position.x, teleport.x);
            position.position.y = calculate_relative_teleport(TeleportFlag::RelY, teleport.flags, position.position.y, teleport.y);
            position.position.z = calculate_relative_teleport(TeleportFlag::RelZ, teleport.flags, position.position.z, teleport.z);
            rotation.yaw = calculate_relative_teleport(TeleportFlag::RelYaw, teleport.flags, rotation.yaw, -teleport.yaw as f64 * (PI / 180.0));

            rotation.pitch = -((calculate_relative_teleport(
                TeleportFlag::RelPitch,
                teleport.flags,
                (-rotation.pitch) * (180.0 / PI) + 180.0,
                teleport.pitch as f64
            ) - 180.0) * (PI / 180.0));

            if (teleport.flags & (TeleportFlag::RelX as u8)) == 0 {
                velocity.velocity.x = 0.0;
            }
            if (teleport.flags & (TeleportFlag::RelY as u8)) == 0 {
                velocity.velocity.y = 0.0;
            }
            if (teleport.flags & (TeleportFlag::RelZ as u8)) == 0 {
                velocity.velocity.z = 0.0;
            }

            self.write_packet(packet::play::serverbound::TeleportConfirm {
                teleport_id: teleport.teleport_id,
            });
        }
    }

    fn on_block_entity_update(&mut self, block_update: packet::play::clientbound::UpdateBlockEntity) {
        match block_update.nbt {
            None => {
                // NBT is null, so we need to remove the block entity
                self.world.add_block_entity_action(world::BlockEntityAction::Remove(
                    block_update.location,
                ));
            },
            Some(nbt) => {
                if block_update.action == 9 {
                    use format;
                    let line1 = format::Component::from_string(nbt.1.get("Text1").unwrap().as_string().unwrap());
                    let line2 = format::Component::from_string(nbt.1.get("Text2").unwrap().as_string().unwrap());
                    let line3 = format::Component::from_string(nbt.1.get("Text3").unwrap().as_string().unwrap());
                    let line4 = format::Component::from_string(nbt.1.get("Text4").unwrap().as_string().unwrap());
                    self.world.add_block_entity_action(world::BlockEntityAction::UpdateSignText(
                        block_update.location,
                        line1,
                        line2,
                        line3,
                        line4,
                    ));
                }
            }
        }
    }

    fn on_player_info(&mut self, player_info: packet::play::clientbound::PlayerInfo) {
        use protocol::packet::PlayerDetail::*;
        use rustc_serialize::base64::FromBase64;
        use serde_json;
        for detail in player_info.inner.players {
            match detail {
                Add { name, uuid, properties, display, gamemode, ping} => {
                    let info = self.players.entry(uuid.clone()).or_insert(PlayerInfo {
                        name: name.clone(),
                        uuid: uuid,
                        skin_url: None,

                        display_name: display.clone(),
                        ping: ping.0,
                        gamemode: Gamemode::from_int(gamemode.0),
                    });
                    // Re-set the props of the player in case of dodgy server implementations
                    info.name = name;
                    info.display_name = display;
                    info.ping = ping.0;
                    info.gamemode = Gamemode::from_int(gamemode.0);
                    for prop in properties {
                        if prop.name != "textures" {
                            continue;
                        }
                        // Ideally we would check the signature of the blob to
                        // verify it was from Mojang and not faked by the server
                        // but this requires the public key which is distributed
                        // authlib. We could download authlib on startup and extract
                        // the key but this seems like overkill compared to just
                        // whitelisting Mojang's texture servers instead.
                        let skin_blob = match prop.value.from_base64() {
                            Ok(val) => val,
                            Err(err) => {
                                error!("Failed to decode skin blob, {:?}", err);
                                continue;
                            },
                        };
                        let skin_blob: serde_json::Value = match serde_json::from_slice(&skin_blob) {
                            Ok(val) => val,
                            Err(err) => {
                                error!("Failed to parse skin blob, {:?}", err);
                                continue;
                            },
                        };
                        if let Some(skin_url) = skin_blob.lookup("textures.SKIN.url").and_then(|v| v.as_string()) {
                            info.skin_url = Some(skin_url.to_owned());
                        }
                    }

                    // Refresh our own skin when the server sends it to us.
                    // The join game packet can come before this packet meaning
                    // we may not have the skin in time for spawning ourselves.
                    // This isn't an issue for other players because this packet
                    // must come before the spawn player packet.
                    if info.uuid == self.uuid {
                        let model = self.entities.get_component_mut_direct::<entity::player::PlayerModel>(self.player.unwrap()).unwrap();
                        model.set_skin(info.skin_url.clone());
                    }
                },
                UpdateGamemode { uuid, gamemode } => {
                    if let Some(info) = self.players.get_mut(&uuid) {
                        info.gamemode = Gamemode::from_int(gamemode.0);
                    }
                },
                UpdateLatency { uuid, ping } => {
                    if let Some(info) = self.players.get_mut(&uuid) {
                        info.ping = ping.0;
                    }
                },
                UpdateDisplayName { uuid, display } => {
                    if let Some(info) = self.players.get_mut(&uuid) {
                        info.display_name = display;
                    }
                },
                Remove { uuid } => {
                    self.players.remove(&uuid);
                },
            }
        }
    }

    fn on_chunk_data(&mut self, chunk_data: packet::play::clientbound::ChunkData) {
        self.world.load_chunk(
            chunk_data.chunk_x,
            chunk_data.chunk_z,
            chunk_data.new,
            chunk_data.bitmask.0 as u16,
            chunk_data.data.data
        ).unwrap();
        for optional_block_entity in chunk_data.block_entities.data {
            if let Some(block_entity) = optional_block_entity {
                let x = block_entity.1.get("x").unwrap().as_int().unwrap();
                let y = block_entity.1.get("y").unwrap().as_int().unwrap();
                let z = block_entity.1.get("z").unwrap().as_int().unwrap();
                let tile_id = block_entity.1.get("id").unwrap().as_string().unwrap();
                let action;
                match tile_id {
                    // Fake a sign update
                    "Sign" => action = 9,
                    // Not something we care about, so break the loop
                    _ => continue,
                }
                self.on_block_entity_update(packet::play::clientbound::UpdateBlockEntity {
                    location: Position::new(x, y, z),
                    action: action,
                    nbt: Some(block_entity.clone()),
                });
            }
        }
    }

    fn on_chunk_unload(&mut self, chunk_unload: packet::play::clientbound::ChunkUnload) {
        self.world.unload_chunk(chunk_unload.x, chunk_unload.z, &mut self.entities);
    }

    fn on_block_change(&mut self, block_change: packet::play::clientbound::BlockChange) {
        self.world.set_block(
            block_change.location,
            block::Block::by_vanilla_id(block_change.block_id.0 as usize)
        );
    }

    fn on_multi_block_change(&mut self, block_change: packet::play::clientbound::MultiBlockChange) {
        let ox = block_change.chunk_x << 4;
        let oz = block_change.chunk_z << 4;
        for record in block_change.records.data {
            self.world.set_block(
                Position::new(
                    ox + (record.xz >> 4) as i32,
                    record.y as i32,
                    oz + (record.xz & 0xF) as i32
                ),
                block::Block::by_vanilla_id(record.block_id.0 as usize)
            );
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum TeleportFlag {
    RelX = 0b00001,
    RelY = 0b00010,
    RelZ = 0b00100,
    RelYaw = 0b01000,
    RelPitch = 0b10000,
}

fn calculate_relative_teleport(flag: TeleportFlag, flags: u8, base: f64, val: f64) -> f64 {
    if (flags & (flag as u8)) == 0 {
        val
    } else {
        base + val
    }
}


text:
require File.expand_path('../boot', __FILE__)

require 'rails/all'

# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)

module Balder
  class Application < Rails::Application

    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/
    config.autoload_paths += %W(#{config.root}/lib #{config.root}/app/middleware/)

    config.encoding = "utf-8"

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters += [:password, :password_confirmation]
  end
end


text:
Shipit::Engine.routes.draw do
  stack_id_format = %r{[^/]+/[^/]+/[^/]+}
  sha_format = /[\da-f]{6,40}/
  root to: 'stacks#index'

  mount Pubsubstub::StreamAction.new, at: "/events", as: :events

  # Robots
  get '/status/version' => 'status#version', as: :version

  resources :stacks, only: %i(new create index) do
    resource :webhooks, only: [] do
      post :push, :state
    end
  end

  resources :webhooks, only: [] do
    collection do
      post :membership
      get :membership
    end
  end

  # API
  namespace :api do
    root to: 'base#index'
    resources :stacks, only: %i(index create)
    scope '/stacks/*id', id: stack_id_format, as: :stack do
      get '/' => 'stacks#show'
    end

    scope '/stacks/*stack_id', stack_id: stack_id_format, as: :stack do
      get '/ccmenu' => 'ccmenu#show', as: :ccmenu
      resource :lock, only: %i(create update destroy)
      resources :tasks, only: %i(index show) do
        resource :output, only: :show
      end
      resources :deploys, only: %i(create)
      resources :commits, only: %i(index)
      resources :pull_requests, only: %i(index show update destroy)
      post '/task/:task_name' => 'tasks#trigger', as: :trigger_task
      resources :hooks, only: %i(index create show update destroy)
    end

    resources :hooks, only: %i(index create show update destroy)
  end

  scope '/ccmenu/*stack_id', stack_id: stack_id_format, as: :ccmenu_url do
    get '/' => 'ccmenu_url#fetch'
  end

  # Humans
  scope '/github/auth/github', as: :github_authentication, controller: :github_authentication do
    get '/', action: :request
    post :callback
    get :callback
    get :logout
  end

  scope '/*id', id: stack_id_format, as: :stack do
    get '/' => 'stacks#show'
    patch '/' => 'stacks#update'
    delete '/' => 'stacks#destroy'
    get :settings, controller: :stacks
    post :refresh, controller: :stacks
    get :refresh, controller: :stacks # For easier design, sorry :/
    post :sync_webhooks, controller: :stacks
    post :clear_git_cache, controller: :stacks
  end

  scope '/*stack_id', stack_id: stack_id_format, as: :stack do
    get '/commit/:sha/checks' => 'commit_checks#show', as: :commit_checks
    get '/commit/:sha/checks/tail' => 'commit_checks#tail', as: :tail_commit_checks, defaults: {format: :json}

    resources :rollbacks, only: %i(create)
    resources :commits, only: %i(update)
    resources :tasks, only: %i(show) do
      collection do
        get '' => 'tasks#index', as: :index
        get ':definition_id/new' => 'tasks#new', as: :new
        post ':definition_id' => 'tasks#create', as: ''
      end

      member do
        post :abort
        get :tail, defaults: {format: :json}
      end
    end

    resources :deploys, only: %i(show create) do
      get ':sha', sha: sha_format, on: :new, action: :new, as: ''
      member do
        get :rollback
        get :revert
      end
    end

    resources :pull_requests, only: %i(index destroy create)
  end
  get '/stacks/:id' => 'stacks#lookup'
end


text:
class CreateArticles < ActiveRecord::Migration[5.1]
  def change
    create_table :articles do |t|
      t.string :name
      t.text :excerpt
      t.text :body
      t.datetime :published_at
      t.references :user, foreign_key: true
      t.string :permalink
      t.boolean :anonymous

      t.timestamps
    end
  end
end


text:
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using SixLabors.ImageSharp.Web.Caching;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Extensions;

namespace Umbraco.Cms.Web.Common.DependencyInjection;

/// <summary>
///     Configures the ImageSharp physical file system cache options.
/// </summary>
/// <seealso cref="IConfigureOptions{PhysicalFileSystemCacheOptions}" />
public sealed class ConfigurePhysicalFileSystemCacheOptions : IConfigureOptions<PhysicalFileSystemCacheOptions>
{
    private readonly IHostEnvironment _hostEnvironment;
    private readonly ImagingSettings _imagingSettings;

    /// <summary>
    ///     Initializes a new instance of the <see cref="ConfigurePhysicalFileSystemCacheOptions" /> class.
    /// </summary>
    /// <param name="imagingSettings">The Umbraco imaging settings.</param>
    /// <param name="hostEnvironment">The host environment.</param>
    public ConfigurePhysicalFileSystemCacheOptions(
        IOptions<ImagingSettings> imagingSettings,
        IHostEnvironment hostEnvironment)
    {
        _imagingSettings = imagingSettings.Value;
        _hostEnvironment = hostEnvironment;
    }

    /// <inheritdoc />
    public void Configure(PhysicalFileSystemCacheOptions options)
    {
        options.CacheFolder = _hostEnvironment.MapPathContentRoot(_imagingSettings.Cache.CacheFolder);
        options.CacheFolderDepth = _imagingSettings.Cache.CacheFolderDepth;
    }
}


text:
describe("wu.every", () => {
  it("should return true when the predicate succeeds for all items", () => {
    assert.equal(true, wu.every(x => typeof x === "number", [1, 2, 3]));
  });

  it("should return false when the predicate fails for any item", () => {
    assert.equal(false, wu.every(x => typeof x === "number", [1, 2, "3"]));
  });
});


text:
[![Build Status](https://travis-ci.org/bandwidthcom/bandwidth-webrtc.svg?branch=master)](https://travis-ci.org/bandwidthcom/bandwidth-webrtc)
[![Coverage Status](https://coveralls.io/repos/bandwidthcom/bandwidth-webrtc/badge.svg)](https://coveralls.io/r/bandwidthcom/bandwidth-webrtc)

# This project has been Deprecated.

Please see [JSSIP](https://gist.github.com/avbel/f089355cb749254cda44afa8ace549b2) tutorial.

## Generating BWClient library
```javascript
npm install
grunt compile-assets
```
BWClient.js will be generated at "dist/BWClient.js"
Just include this at the top of your HTML page that will declare a global BWClient object.

```
<script src="BWClient.js"></script>
```

## Prerequisites

- Register for a Catapult (Bandwidth Application Platform) account [here](https://catapult.inetwork.com)
- Register a SIP domain
- Create an endpoint/user
- If you want to make calls to the PSTN (normal phones) you will need a server to handler events from Catapult
- Make phone calls

For a more in depth guide, view [this article](http://ap.bandwidth.com/docs/how-to-guides/use-endpoints-make-receive-calls-sip-clients)

##Quick Start
Full docs are [here](doc/)

CDN hosted library: [minified](https://code.bandwidth.com/bandwidth-0.9.4.min.js) [not-minified](https://code.bandwidth.com/bandwidth-0.9.4.js)

[JSFIDDLE Demo Client](https://jsfiddle.net/vLg9baqg/)

### Outbound Call
```javascript
var bwPhone = BWClient.createPhone({
    username: "user_123",
    domain: "prod.domain.com",
    password: "taco123",
    logLevel: "debug"//can be debug,log,warn,error (default=log)
});
var bwCall = bwPhone.call("222-333-4444");
bwCall.on("connected",function(){
    //the call has connected, and audio is playing
});
bwCall.on("ended",function(){
    //the call has ended
});
...
//play a DTMF tone
bwCall.sendDtmf("1");
bwCall.sendDtmf("#");

//mute call
bwCall.mute();

//unmute call
bwCall.unmute();

//to hangup the call
bwCall.hangup();
```
### Inbound Call
```javascript
var bwPhone = BWClient.createPhone({
    username : "user_123",
    domain   : "prod.domain.com",
    password : "taco123",
    logLevel : "debug"
});
bwPhone.on("incomingCall",function (bwCall) {
    //get into to determine if the call should be accepted/rejected
    var info = bwCall.getInfo();

    //user friendly remote identifier
    var remoteId = info.remoteId;

    //setup event handlers
    bwCall.on("connected",function () {
        ...
    });
    //to accept the call
    bwCall.accept();

    //to reject the call
    bwCall.reject();
});
```
## Supported Browsers
* Firefox
* Chrome
* Opera

# License: [MIT](LICENSE)


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: FleskPlugins::Captcha::Validations::ClassMethods</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />

          Module
          FleskPlugins::Captcha::Validations::ClassMethods

            In:

                lib/add_captcha_to_active_record.rb

Class methods to be used in your models.

Methods

      validates_captcha

Included Modules

        FleskPlugins::Captcha::Validations::InstanceMethods

Public Instance methods

          validates_captcha(options = {})

Validates a CAPTCHA challenge.

  class MySuperModel
    validates_captcha :message => "Nope, that wasn't it at all."
  end

This method adds two accessors to your model, <tt>captcha_id</tt> and
<tt>captcha_validation</tt>, and makes them accessible for mass-assignment.
They are virtual, so you don’t need them in your database table. You
will have to assign them values from your form in your controller, but if
you do something like <tt>tyra =
MySuperModel.new(params[:my_super_model])</tt> and you use the helpers in
Helpers::Captcha, this will happen automatically. Note that if you use
<tt>attr_accessible</tt>, you will have to place the <tt>validates_captcha</tt> after this to
have the attributes automatically assigned.

It takes the optional <tt>:on</tt> and <tt>:if</tt> parameters, that work
like in Rails’ built-in validations.

  class MySuperModel
    validates_captcha :on => :create, :if => Proc.new{|r| !r.has_user? }
  end

[Source]

    # File lib/add_captcha_to_active_record.rb, line 40
40:         def validates_captcha(options = {})
41:           options = {
42:             :message => CaptchaConfig.config['default_message'] || 'CAPTCHA validation did not match.'
43:           }.update(options)
44:
45:           include FleskPlugins::Captcha::Validations::InstanceMethods
46:
47:           class_eval {
48:             attr_accessor :captcha_id, :captcha_validation
49:             attr_accessible :captcha_id, :captcha_validation if accessible_attributes
50:
51:             after_create :delete_captcha
52:
53:             send(validation_method(options[:on] || :save)){|record|
54:               unless options[:if] && !evaluate_condition(options[:if], record)
55:                 record.send(:validate_captcha, options)
56:               end
57:             }
58:           }
59:         end

[Validate]


text:
<?php

namespace CotaPreco\Cielo\Serialization\Node;

use CotaPreco\Cielo\Serialization\VisitorInterface;

/**
 * @author Andrey K. Vital <andreykvital@gmail.com>
 */
abstract class AbstractNodeSerializationVisitor implements VisitorInterface
{
    /**
     * @var \DOMElement
     */
    protected $root;

    /**
     * @var \DOMDocument
     */
    protected $document;

    /**
     * @param \DOMElement $root
     */
    public function __construct(\DOMElement $root)
    {
        $this->root     = $root;
        $this->document = $root->ownerDocument;
    }
}


text:
'use strict';

/**
 * This module provides easy access to Bonita BPM REST APIs
 *
 * @author Philippe Ozil
 * @author Rodrigue Le Gall
 */
angular.module('ngBonita', [ 'ngResource' ]);


text:
import os
import numpy as np
from . import print_image
from . import plot_image

def output_mask(device, img, mask, filename, outdir=None, mask_only=False, debug=None):
    """Prints ori image and mask to directories.

    Inputs:
    device   = pipeline step counter
    img = original image, read in with plantcv function read_image
    mask  = binary mask image (single chanel)
    filename = vis image file name (output of plantcv read_image function)
    outdir = output directory
    debug    = None, print, or plot. Print = save to file, Plot = print to screen.

    Returns:
    device   = device number
    imgpath = path to image
    maskpath path to mask

    :param img: array
    :param mask: array
    :param filename: str
    :param outdir: str
    :param device: int
    :param debug: str
    :return device: int
    :return imgpath: str
    :return maskpath: str

    """

    device += 1
    analysis_images = []

    if outdir == None:
        directory = os.getcwd()
    else:
        directory = outdir

    if mask_only == False:
        path = os.path.join(str(directory), "ori-images")

        if os.path.exists(path) == True:
            imgpath = os.path.join(str(path), str(filename))
            print_image(img, imgpath)
            analysis_images.append(['IMAGE', 'ori-img', imgpath])

        else:
            os.mkdir(path)
            imgpath = os.path.join(str(path), str(filename))
            print_image(img, imgpath)
            analysis_images.append(['IMAGE', 'ori-img', imgpath])

        path1 = os.path.join(str(directory), "mask-images")

        if os. path.exists(path1) == True:
            maskpath = os.path.join(str(path1), str(filename))
            print_image(mask, maskpath)
            analysis_images.append(['IMAGE', 'mask', maskpath])
        else:
            os.mkdir(path1)
            maskpath = os.path.join(str(path1), str(filename))
            print_image(mask, maskpath)
            analysis_images.append(['IMAGE', 'mask', maskpath])

        if debug == 'print':
            print_image(img, (str(device) + '_ori-img.png'))
            print_image(mask, (str(device) + '_mask-img.png'))

        elif debug == 'plot':
            if len(np.shape(img)) == 3:
                plot_image(img)
                plot_image(mask, cmap='gray')
            else:
                plot_image(img, cmap='gray')
                plot_image(mask, cmap='gray')

        return device, imgpath, maskpath, analysis_images

    else:
        path1 = os.path.join(str(directory), "mask-images")

        if os.path.exists(path1) == True:
            maskpath = os.path.join(str(path1), str(filename))
            print_image(mask, maskpath)
            analysis_images.append(['IMAGE', 'mask', maskpath])
        else:
            os.mkdir(path1)
            maskpath = os.path.join(str(path1), str(filename))
            print_image(mask, maskpath)
            analysis_images.append(['IMAGE', 'mask', maskpath])

        if debug == 'print':
            print_image(mask, (str(device) + '_mask-img.png'))
        elif debug == 'plot':
                plot_image(mask, cmap='gray')

        return device, maskpath, analysis_images


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Ext.Direct Named Arguments</title>
    <link rel="stylesheet" type="text/css" href="shared/example.css" />

Ext.Direct Named Arguments

The js is not minified so it is readable. See named-arguments.js.


text:
from gos.configuration import Configuration
from gos.exceptions import GOSTaskException, GOSExecutableContainerException
from gos.executable_containers import ExecutableContainer
from gos.tasks import TaskLoader

class Manager(object):
    def __init__(self, config):
        self.configuration = config
        self.tasks_classes = {}
        self.tasks_instances = {}
        self.executable_containers_classes = {}
        self.executable_containers_instances = {}

    def initiate_tasks(self):
        """ Loads all tasks using `TaskLoader` from respective configuration option """
        self.tasks_classes = TaskLoader().load_tasks(
            paths=self.configuration[Configuration.ALGORITHM][Configuration.TASKS][Configuration.PATHS])

    def instantiate_tasks(self):
        """ All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent """
        self.tasks_instances = {}
        for task_name, task_class in self.tasks_classes.items():
            try:
                self.tasks_instances[task_name] = task_class()
            except Exception as ex:
                if not self.configuration[Configuration.ALGORITHM][Configuration.IOSF]:
                    raise GOSTaskException("An exception happened during the task instantiation."
                                           "{exception}".format(exception=ex))

    def initiate_executable_containers(self):
        for entry in self.configuration[Configuration.ALGORITHM]["executable_containers"]:
            if "reference" in entry:
                reference = entry["reference"]
                for ec_config in self.configuration[Configuration.ALGORITHM][reference]:
                    ec_config["group_reference_name"] = reference
                    result = ExecutableContainer.setup_from_config(manager=self, config=ec_config)
                    self.executable_containers_instances[result.name] = result
            elif "paths" in entry:
                paths = entry["paths"]
                for path in paths:
                    try:
                        for ec_instance in ExecutableContainer.setup_from_file(file_path=path):
                            self.executable_containers_instances[ec_instance.name] = ec_instance
                    except GOSExecutableContainerException:
                        continue
        if "pipeline" not in self.configuration[Configuration.ALGORITHM]["executable_containers"]:
            pipeline_config = self.configuration[Configuration.ALGORITHM]["pipeline"]
            if "name" not in pipeline_config:
                pipeline_config["name"] = "pipeline"
            self.executable_containers_instances["pipeline"] = ExecutableContainer.setup_from_config(manager=self,
                                                                                config=pipeline_config)

    def instantiate_executable_containers(self):
        for executable_container in self.executable_containers_instances.values():
            for entry_name in executable_container.entries_names:
                try:
                    entry = self.tasks_instances[entry_name]
                except KeyError:
                    entry = self.executable_containers_instances[entry_name]
                executable_container.entries.append(entry)

    def run(self):
        self.executable_containers_instances["pipeline"].run(manager=self)

    def get_task_instance(self, task_name):
        return self.tasks_instances[task_name]

    def get_executable_container_instance(self, ec_name):
        return self.executable_containers_instances[ec_name]


text:
/** @defgroup logging Server logging
 *  @ingroup yadifad
 *  @brief
 *
 *
 *
 * @{
 *
 *----------------------------------------------------------------------------*/

#define LOG_STATISTICS_C_

#include "log_statistics.h"

#define SHOW_REFERRAL 1

logger_handle* g_statistics_logger;

void
log_statistics_legend()
{
    logger_handle_msg(g_statistics_logger,
            MSG_INFO,
            "statistics legend: \n"
            "\n"
            "input: \n"
            "\n"
            "\tin : input count \n"
            "\tqr : query count \n"
            "\tni : notify count \n"
            "\tup : update count \n"

            "\tdr : dropped count \n"
            "\tst : total bytes sent (simple queries only) \n"
            "\tun : undefined opcode count \n"
#if SHOW_REFERRAL
            "\trf : referral count\n"
#endif

            "\tax : axfr query count \n"
            "\tix : ixfr query count \n"
            "\tov : (tcp) connection overflow \n"
            "\n"
            "output:\n"
            "\n"
            "\tOK : NOERROR answer count \n"
            "\tFR : FORMERR answer count \n"
            "\tSF : SERVFAIL answer count \n"
            "\tNE : NXDOMAIN answer count \n"
            "\tNI : NOTIMP answer count \n"
            "\tRE : REFUSED answer count \n"
            "\tXD : YXDOMAIN answer count \n"
            "\tXR : YXRRSET answer count \n"
            "\tNR : NXRRSET answer count \n"
            "\tNA : NOTAUTH answer count \n"
            "\tNZ : NOTZONE answer count \n"

            "\tBV : BADVERS answer count \n"
            "\tBS : BADSIG answer count \n"
            "\tBK : BADKEY answer count \n"
            "\tBT : BADTIME answer count \n"
            "\tBM : BADMODE answer count \n"
            "\tBN : BADNAME answer count \n"
            "\tBA : BADALG answer count \n"
            "\tTR : BADTRUNC answer count"
            );
}

void
log_statistics(server_statistics_t *server_statistics)
{
    logger_handle_msg(g_statistics_logger,
            MSG_INFO,
#if 0
            "loops=%llu (%llu/s) "
            "timeout=%llu "
            "sched=%llu "
#endif
             "udp (in=%llu qr=%llu ni=%llu up=%llu "
                  "dr=%llu st=%llu un=%llu "
#if SHOW_REFERRAL
                  "rf=%llu) "
#endif

             "tcp (in=%llu qr=%llu ni=%llu up=%llu "
                  "dr=%llu st=%llu un=%llu """
#if SHOW_REFERRAL
                  "rf=%llu "
#endif
                  "ax=%llu ix=%llu ov=%llu) "

            "udpa (OK=%llu FE=%llu SF=%llu NE=%llu "
                  "NI=%llu RE=%llu XD=%llu XR=%llu "
                  "NR=%llu NA=%llu NZ=%llu BV=%llu "
                  "BS=%llu BK=%llu BT=%llu BM=%llu "
                  "BN=%llu BA=%llu TR=%llu) "

            "tcpa (OK=%llu FE=%llu SF=%llu NE=%llu "
                  "NI=%llu RE=%llu XD=%llu XR=%llu "
                  "NR=%llu NA=%llu NZ=%llu BV=%llu "
                  "BS=%llu BK=%llu BT=%llu BM=%llu "
                  "BN=%llu BA=%llu TR=%llu)"
            ,
#if 0
            server_statistics->input_loop_count,
            1000LL * server_statistics->loop_rate_counter / server_statistics->loop_rate_elapsed,
            server_statistics->input_timeout_count,
            server_statistics->sched_queries_count,
#endif
            // udp

            server_statistics->udp_input_count,
            server_statistics->udp_queries_count,
            server_statistics->udp_notify_input_count,
            server_statistics->udp_updates_count,

            server_statistics->udp_dropped_count,
            server_statistics->udp_output_size_total,
            server_statistics->udp_undefined_count,
#if SHOW_REFERRAL
            server_statistics->udp_referrals_count,
#endif

            // tcp

            server_statistics->tcp_input_count,
            server_statistics->tcp_queries_count,
            server_statistics->tcp_notify_input_count,
            server_statistics->tcp_updates_count,

            server_statistics->tcp_dropped_count,
            server_statistics->tcp_output_size_total,
            server_statistics->tcp_undefined_count,
#if SHOW_REFERRAL
            server_statistics->tcp_referrals_count,
#endif

            server_statistics->tcp_axfr_count,
            server_statistics->tcp_ixfr_count,
            server_statistics->tcp_overflow_count,

            // udp fp

            server_statistics->udp_fp[RCODE_NOERROR],
            server_statistics->udp_fp[RCODE_FORMERR],
            server_statistics->udp_fp[RCODE_SERVFAIL],
            server_statistics->udp_fp[RCODE_NXDOMAIN],
            server_statistics->udp_fp[RCODE_NOTIMP],
            server_statistics->udp_fp[RCODE_REFUSED],
            server_statistics->udp_fp[RCODE_YXDOMAIN],
            server_statistics->udp_fp[RCODE_YXRRSET],
            server_statistics->udp_fp[RCODE_NXRRSET],
            server_statistics->udp_fp[RCODE_NOTAUTH],
            server_statistics->udp_fp[RCODE_NOTZONE],
            server_statistics->udp_fp[RCODE_BADVERS],
            server_statistics->udp_fp[RCODE_BADSIG],
            server_statistics->udp_fp[RCODE_BADKEY],
            server_statistics->udp_fp[RCODE_BADTIME],
            server_statistics->udp_fp[RCODE_BADMODE],
            server_statistics->udp_fp[RCODE_BADNAME],
            server_statistics->udp_fp[RCODE_BADALG],
            server_statistics->udp_fp[RCODE_BADTRUNC],

            // tcp fp

            server_statistics->tcp_fp[RCODE_NOERROR],
            server_statistics->tcp_fp[RCODE_FORMERR],
            server_statistics->tcp_fp[RCODE_SERVFAIL],
            server_statistics->tcp_fp[RCODE_NXDOMAIN],
            server_statistics->tcp_fp[RCODE_NOTIMP],
            server_statistics->tcp_fp[RCODE_REFUSED],
            server_statistics->tcp_fp[RCODE_YXDOMAIN],
            server_statistics->tcp_fp[RCODE_YXRRSET],
            server_statistics->tcp_fp[RCODE_NXRRSET],
            server_statistics->tcp_fp[RCODE_NOTAUTH],
            server_statistics->tcp_fp[RCODE_NOTZONE],
            server_statistics->tcp_fp[RCODE_BADVERS],
            server_statistics->tcp_fp[RCODE_BADSIG],
            server_statistics->tcp_fp[RCODE_BADKEY],
            server_statistics->tcp_fp[RCODE_BADTIME],
            server_statistics->tcp_fp[RCODE_BADMODE],
            server_statistics->tcp_fp[RCODE_BADNAME],
            server_statistics->tcp_fp[RCODE_BADALG],
            server_statistics->tcp_fp[RCODE_BADTRUNC]

            );
}

/*    ------------------------------------------------------------    */

/** @} */


text:
.class Landroid/widget/AutoCompleteTextView$DropDownItemClickListener;
.super Ljava/lang/Object;
.source "AutoCompleteTextView.java"

# interfaces
.implements Landroid/widget/AdapterView$OnItemClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/AutoCompleteTextView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "DropDownItemClickListener"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/AutoCompleteTextView;

# direct methods
.method private constructor <init>(Landroid/widget/AutoCompleteTextView;)V
    .locals 0

    iput-object p1, p0, Landroid/widget/AutoCompleteTextView$DropDownItemClickListener;->this$0:Landroid/widget/AutoCompleteTextView;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/widget/AutoCompleteTextView;Landroid/widget/AutoCompleteTextView$DropDownItemClickListener;)V
    .locals 0

    invoke-direct {p0, p1}, Landroid/widget/AutoCompleteTextView$DropDownItemClickListener;-><init>(Landroid/widget/AutoCompleteTextView;)V

    return-void
.end method

# virtual methods
.method public onItemClick(Landroid/widget/AdapterView;Landroid/view/View;IJ)V
    .locals 2

    iget-object v0, p0, Landroid/widget/AutoCompleteTextView$DropDownItemClickListener;->this$0:Landroid/widget/AutoCompleteTextView;

    invoke-static {v0, p2, p3, p4, p5}, Landroid/widget/AutoCompleteTextView;->-wrap1(Landroid/widget/AutoCompleteTextView;Landroid/view/View;IJ)V

    return-void
.end method


text:
#pragma once

#include "com/manager.hpp"
#include "query/query_list.hpp"
#include "util/partition.hpp"

namespace dpt {
namespace tree {

template <typename Alphabet,
          typename GlobalIndex,
          typename LocalIndex,
          template <typename, typename, typename> class PatriciaTrieStructure>
class patricia_trie {

  using manager = dpt::com::manager<Alphabet, GlobalIndex, LocalIndex>;
  using partition = dpt::util::partition<GlobalIndex, GlobalIndex, LocalIndex>;
  using q_list = dpt::query::query_list<Alphabet, GlobalIndex, LocalIndex>;

public:
  patricia_trie() { }

  template <template <typename, typename, typename> class Communication>
  void construct(partition&& local_sa, partition&& local_lcp,
    manager& manager, const GlobalIndex max_lcp) {
    local_sa_ = std::move(local_sa);
    trie_.template construct<Communication>(local_sa_, local_lcp, manager, max_lcp);
  }

  std::pair<std::array<GlobalIndex, 2>, std::array<GlobalIndex, 2>>
    global_sa_and_lcp() const {
    return trie_.global_sa_and_lcp();
  }

  template <template <typename, typename, typename> class Communication>
  inline auto existential_batched(q_list&& rec_queries, manager& manager)
    const {
    return trie_.template existential_batched<Communication>(
      std::move(rec_queries), manager, local_sa_);
  }

  template <template <typename, typename, typename> class Communication>
  inline auto counting_batched(q_list&& rec_queries, manager& manager) const {
    return trie_.template counting_batched<Communication>(
      std::move(rec_queries), manager, local_sa_);
  }

  template <template <typename, typename, typename> class Communication>
  inline auto enumeration_batched(q_list&& rec_queries, manager& manager) const {
    return trie_.template enumeration_batched<Communication>(
      std::move(rec_queries), manager, local_sa_);
  }

private:
  partition local_sa_;
  PatriciaTrieStructure<Alphabet, GlobalIndex, LocalIndex> trie_;

}; // class patricia_trie

} // namespace tree
} // namespace dpt

/******************************************************************************/


text:
<?php

namespace Acrobat\Bundle\RecaptchaBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * AcrobatRecaptchaBundle
 *
 * @author Jeroen Thora <jeroenthora@gmail.com>
 */
class AcrobatRecaptchaBundle extends Bundle
{
}