text:
This set of playbooks can be used to deploy an Ambari-managed Hadoop cluster, Metron services, or both using ansible
playbooks. These playbooks currently only target RHEL/CentOS 6.x operating
systems.

In addition, an Ambari Management Pack can be built which can be deployed in conjuction with RPMs detailed in this README.

## Prerequisites
The following tools are required to run these scripts:

- Maven - https://maven.apache.org/
- Git - https://git-scm.com/
- Ansible - http://www.ansible.com/ (version 2.0 or greater)

Currently Metron must be built from source.  Before running these scripts perform the following steps:

1. Clone the Metron git repository with `git clone git@github.com:apache/incubator-metron.git`
2. Navigate to `incubator-metron` and run `mvn clean package`

These scripts depend on two files for configuration:

- hosts - declares which Ansible roles will be run on which hosts
- group_vars/all - various configuration settings needed to install Metron

Examples can be found in the
`incubator-metron/metron-deployment/inventory/metron_example` directory and are a good starting point.  Copy this directory
into `incubator-metron/metron-deployment/inventory/` and rename it to your `project_name`.  More information about Ansible files and directory
structure can be found at http://docs.ansible.com/ansible/playbooks_best_practices.html.

## Ambari
The Ambari playbook will install a Hadoop cluster with all the services and configuration required by Metron.  This
section can be skipped if installing Metron on a pre-existing cluster.

Currently, this playbook supports building a local development cluster running on one node but options for other types
 of clusters will be added in the future.

### Setting up your inventory
Make sure to update the hosts file in `incubator-metron/metron-deployment/inventory/project_name/hosts` or provide an
alternate inventory file when you launch the playbooks, including the
ssh user(s) and ssh keyfile location(s). These playbooks expect two
host groups:

- ambari_master
- ambari_slaves

### Running the playbook
This playbook will install the Ambari server on the ambari_master, install the ambari agents on
the ambari_slaves, and create a cluster in Ambari with a blueprint for the required
Metron components.

Navigate to `incubator-metron/metron-deployment/playbooks` and run:
`ansible-playbook -i ../inventory/project_name ambari_install.yml`

## Metron
The Metron playbook will gather the necessary cluster settings from Ambari and install the Metron services.

### Setting up your inventory
Edit the hosts file at `incubator-metron/metron-deployment/inventory/project_name/hosts`.  Declare where which hosts the
Metron services will be installed on by updating these groups:

- enrichment - submits the topology code to Storm and requires a storm client
- search - host where Elasticsearch will be run
- web - host where the Metron UI and underlying services will run
- sensors - host where network data will be collected and published to Kafka

The Metron topologies depend on Kafka topics and HBase tables being created beforehand.  Declare a host that has Kafka and HBase clients installed by updating these groups:

- metron_kafka_topics
- metron_hbase_tables

If only installing Metron, these groups can be ignored:

- ambari_master
- ambari_slaves

### Configuring group variables
The Metron Ansible scripts depend on a set of variables.  These variables can be found in the file at
`incubator-metron/metron-deployment/inventory/project_name/group_vars/all`.  Edit the ambari* variables to match your Ambari
instance and update the java_home variable to match the java path on your hosts.

### Running the playbook
Navigate to `incubator-metron/metron-deployment/playbooks` and run:
`ansible-playbook -i ../inventory/project_name metron_install.yml`

## Vagrant
A VagrantFile is included and will install a working version of the entire Metron stack.  The following is required to
run this:

- Vagrant - https://www.vagrantup.com/
- Hostmanager plugin for vagrant - Run `vagrant plugin install vagrant-hostmanager` on the machine where Vagrant is
installed

Navigate to `incubator-metron/metron-deployment/vagrant/full-dev-platform` and run `vagrant up`.  This also provides a good
example of how to run a full end-to-end Metron install.

## Ambari Management Pack
An Ambari Management Pack can be built in order to make the Metron service available on top of an existing stack, rather than needing a direct stack update.

This will set up
- Metron Parsers
- Enrichment
- Indexing
- GeoIP database on MySQL
- Optional Elasticsearch
- Optional Kibana

### Prerequisites
- A cluster managed by Ambari 2.4
- Metron RPMs available on the cluster in the /localrepo directory.  See [RPM](#RPM) for further information.

### Building Management Pack
From `metron-deployment` run
```
mvn clean package
```

A tar.gz that can be used with Ambari can be found at `metron-deployment/packaging/ambari/metron-mpack/target/`

### Installing Management Pack
Before installing the mpack, update Storm's topology.classpath in Ambari to include '/etc/hbase/conf:/etc/hadoop/conf'. Restart Storm service.

Place the mpack's tar.gz onto the node running Ambari Server. From the command line on this node, run
```
ambari-server install-mpack --mpack=<mpack_location> --verbose
```

This will make the services available in Ambari in the same manner as any services in a stack, e.g. through Add Services or during cluster install.
The Indexing / Parsers/ Enrichment masters should be colocated with a Kafka Broker (to create topics) and HBase client (to create the enrichment and theatintel tables).
This colocation is currently not enforced by Ambari, and should be managed by either a Service or Stack advisor as an enhancement.

Several configuration parameters will need to be filled in, and should be pretty self explanatory (primarily a couple of Elasticsearch configs, and the Storm REST URL).  Examples are provided in the descriptions on Ambari.
Notably, the URL for the GeoIP database that is preloaded (and is prefilled by default) can be set to use a `file://` location

After installation, a custom action is available in Ambari (where stop / start services are) to install Elasticsearch templates.  Similar to this, a custom Kibana action to Load Template is available.

#### Offline installation
Currently there is only one point that would reach out to the internet during an install.  This is the URL for the GeoIP database information that is preloaded into MySQL.

The RPMs DO NOT reach out to the internet (because there is currently no hosting for them).  They look on the local filesystem in `/localrepo`.

### Current Limitations
There are a set of limitations that should be addressed based to improve the current state of the mpacks.

- MySQL install should be optional (and allow for using an existing instance).
- MySQL should not be installed on a node already running a MySQL instance (e.g. an Ambari Server using MySQL as its database).
- There is currently no hosting for RPMs remotely.  They will have to be built locally.
- Colocation of appropriate services should be enforced by Ambari.  See [#Installing Management Pack] for more details.
- Storm's topology.classpath is not updated with the Metron service install and needs to be updated separately.
- Several configuration parameters used when installing the Metron service could (and should) be grabbed from Ambari.  Install will require them to be manually entered.
- Need to handle upgrading Metron

## RPM
RPMs can be built to install the components in metron-platform. These RPMs are built in a Docker container and placed into `target`.

Components in the RPMs:
- metron-common
- metron-data-management
- metron-elasticsearch
- metron-enrichment
- metron-parsers
- metron-pcap
- metron-solr

### Prerequisites
- Docker.  The image detailed in: `metron-deployment/packaging/docker/rpm-docker/README.md` will automatically be built (or rebuilt if necessary).
- On Mac, Docker Toolbox's handling of ownership causes permissions issues in the Docker container.  Please use Docker for Mac instead.
- Artifacts for metron-platform have been produced.  E.g. `mvn clean package -DskipTests` in `metron-platform`

### Building RPMs
From `metron-deployment` run
```
mvn clean package -Pbuild-rpms
```

The output RPM files will land in `target/RPMS/noarch`.  They can be installed with the standard
```
rpm -i <package>
```

## TODO
- migrate existing MySQL/GeoLite playbook
- Support Ubuntu deployments


text:
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});

function drawGraph_${deviceType}(from, to) {
    $("#y_axis").html("");
    $("#smoother").html("");
    $("#legend").html("");
    $("#chart").html("");
    $("#x_axis").html("");
    $("#slider").html("");

    var devices = $("#details").data("devices");

    var tzOffset = new Date().getTimezoneOffset() * 60;

    var chartWrapperElmId = "#div-chart";
    var graphWidth = $(chartWrapperElmId).width() - 50;
    var graphConfig = {
        element: document.getElementById("chart"),
        width: graphWidth,
        height: 400,
        strokeWidth: 2,
        renderer: 'line',
        interpolation: "linear",
        unstack: true,
        stack: false,
        xScale: d3.time.scale(),
        padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
        series: []
    };

    if (devices) {
        for (var i = 0; i < devices.length; i++) {
            graphConfig['series'].push(
                {
                    'color': palette.color(),
                    'data': [{
                        x: parseInt(new Date().getTime() / 1000),
                        y: 0
                    }],
                    'name': devices[i].name
                });
        }
    } else {
        graphConfig['series'].push(
            {
                'color': palette.color(),
                'data': [{
                    x: parseInt(new Date().getTime() / 1000),
                    y: 0
                }],
                'name': $("#details").data("devicename")
            });
    }

    var graph = new Rickshaw.Graph(graphConfig);

    graph.render();

    var xAxis = new Rickshaw.Graph.Axis.Time({
        graph: graph
    });

    xAxis.render();

    var yAxis = new Rickshaw.Graph.Axis.Y({
        graph: graph,
        orientation: 'left',
        element: document.getElementById("y_axis"),
        width: 40,
        height: 410
    });

    yAxis.render();

    var slider = new Rickshaw.Graph.RangeSlider.Preview({
        graph: graph,
        element: document.getElementById("slider")
    });

    var legend = new Rickshaw.Graph.Legend({
        graph: graph,
        element: document.getElementById('legend')
    });

    var hoverDetail = new Rickshaw.Graph.HoverDetail({
        graph: graph,
        formatter: function (series, x, y) {
            var date = '' +
                moment.unix((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '';
            var swatch = '';
            return swatch + series.name + ": " + parseInt(y) + '
' + date;
        }
    });

    var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
        graph: graph,
        legend: legend
    });

    var order = new Rickshaw.Graph.Behavior.Series.Order({
        graph: graph,
        legend: legend
    });

    var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
        graph: graph,
        legend: legend
    });

    var deviceIndex = 0;

    if (devices) {
        getData();
    } else {
        var backendApiUrl = $("#chart").data("backend-api-url") + "?from=" + from + "&to=" + to;
        var successCallback = function (data) {
            if (data) {
                drawLineGraph(JSON.parse(data));
            }
        };
        invokerUtil.get(backendApiUrl, successCallback, function (message) {
            console.log(message);
        });
    }

    function getData() {
        if (deviceIndex >= devices.length) {
            return;
        }
        var backendApiUrl = $("#chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
            + "?from=" + from + "&to=" + to;
        var successCallback = function (data) {
            if (data) {
                drawLineGraph(JSON.parse(data));
            }
            deviceIndex++;
            getData();
        };
        invokerUtil.get(backendApiUrl, successCallback, function (message) {
            console.log(message);
            deviceIndex++;
            getData();
        });
    }

    function drawLineGraph(data) {
        if (data.length === 0 || data.length === undefined) {
            return;
        }

        var chartData = [];
        for (var i = 0; i < data.length; i++) {
            chartData.push(
                {
                    x: parseInt(data[i].values.time) - tzOffset,
                    y: parseInt(data[i].values.${nameOfTheSensor})
                }
            );
        }

        graphConfig.series[deviceIndex].data = chartData;
        graph.update();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.palantir.atlasdb.timelock;

import com.palantir.timelock.config.PaxosInstallConfiguration.PaxosLeaderMode;
import java.util.List;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.immutables.value.Value;

@Value.Immutable
@Value.Enclosing
@Value.Style(attributeBuilderDetection = true)
public interface TemplateVariables {
    int PROXY_OFFSET = 100;

    @Nullable
    String getDataDirectory();

    @Nullable
    String getSqliteDataDirectory();

    List<Integer> getServerPorts();

    Integer getLocalServerPort();

    TimestampPaxos getClientPaxos();

    PaxosLeaderMode getLeaderMode();

    @Value.Default
    default Integer getLocalProxyPort() {
        return doProxyTransform(getLocalServerPort());
    }

    @Value.Derived
    default List<Integer> getServerProxyPorts() {
        return getServerPorts().stream()
                .map(TemplateVariables::doProxyTransform)
                .collect(Collectors.toList());
    }

    static int doProxyTransform(int port) {
        return port + PROXY_OFFSET;
    }

    @Value.Check
    default TemplateVariables putLocalServerPortAmongstAllServerPorts() {
        // It is guaranteed that the transform ensures that after this runs once, the local proxy port will be present
        // in the server proxy ports.
        if (getServerProxyPorts().contains(getLocalProxyPort())) {
            return this;
        }

        return ImmutableTemplateVariables.builder()
                .from(this)
                .addServerPorts(getLocalServerPort())
                .build();
    }

    @Value.Immutable
    interface TimestampPaxos {
        boolean isUseBatchPaxosTimestamp();

        @Value.Default
        default boolean isBatchSingleLeader() {
            return false;
        }
    }

    static Iterable<TemplateVariables> generateThreeNodeTimelockCluster(
            int startingPort, UnaryOperator<ImmutableTemplateVariables.Builder> customizer) {
        List<Integer> allPorts =
                IntStream.range(startingPort, startingPort + 3).boxed().collect(Collectors.toList());
        return IntStream.range(startingPort, startingPort + 3)
                .boxed()
                .map(port -> ImmutableTemplateVariables.builder()
                        .serverPorts(allPorts)
                        .localServerPort(port))
                .map(customizer)
                .map(ImmutableTemplateVariables.Builder::build)
                .collect(Collectors.toList());
    }
}


text:
package org.keycloak.testsuite.federation.storage;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.exportimport.ExportImportConfig;
import org.keycloak.exportimport.ExportImportManager;
import org.keycloak.exportimport.singlefile.SingleFileExportProviderFactory;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.ComponentRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.testsuite.AbstractAuthTest;
import org.keycloak.testsuite.admin.ApiUtil;

import org.keycloak.testsuite.client.KeycloakTestingClient;
import org.keycloak.testsuite.federation.UserMapStorageFactory;
import org.keycloak.testsuite.util.RealmBuilder;

import javax.ws.rs.NotFoundException;
import java.io.File;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import static org.junit.Assert.fail;
import static org.keycloak.storage.UserStorageProviderModel.IMPORT_ENABLED;

/**
 *
 * @author tkyjovsk
 */
public class ComponentExportImportTest extends AbstractAuthTest {

    private static final String REALM_NAME = "exported-component";

    private File exportFile;

    @Before
    public void setDirs() {
        exportFile = new File (new File(System.getProperty("auth.server.config.dir", "target")), "singleFile-full.json");
        log.infof("Export file: %s", exportFile);

        // Remove realm if exists
        testingClient.server().run(session -> {
            RealmModel realm = session.realms().getRealmByName(REALM_NAME);
            if (realm != null) {
                session.realms().removeRealm(realm.getId());
            }
        });
    }

    @Override
    public RealmResource testRealmResource() {
        return adminClient.realm(REALM_NAME);
    }

    static void clearExportImportProperties(KeycloakTestingClient testingClient) {
        testingClient.server().run(session -> {
            // Clear export/import properties after test
            Properties systemProps = System.getProperties();
            Set<String> propsToRemove = new HashSet<>();

            for (Object key : systemProps.keySet()) {
                if (key.toString().startsWith(ExportImportConfig.PREFIX)) {
                    propsToRemove.add(key.toString());
                }
            }

            for (String propToRemove : propsToRemove) {
                systemProps.remove(propToRemove);
            }
        });
    }

    protected String addComponent(ComponentRepresentation component) {
        return ApiUtil.getCreatedId(testRealmResource().components().add(component));
    }

    @Test
    public void testSingleFile() {
        clearExportImportProperties(testingClient);

        RealmRepresentation realmRep = RealmBuilder.create()
                .name(REALM_NAME)
                .build();
        adminClient.realms().create(realmRep);
        String realmId = testRealmResource().toRepresentation().getId();

        ComponentRepresentation parentComponent = new ComponentRepresentation();
        parentComponent.setParentId(realmId);
        parentComponent.setName("parent");
        parentComponent.setSubType("subtype");
        parentComponent.setProviderId(UserMapStorageFactory.PROVIDER_ID);
        parentComponent.setProviderType(UserStorageProvider.class.getName());
        parentComponent.setConfig(new MultivaluedHashMap<>());
        parentComponent.getConfig().putSingle("priority", Integer.toString(0));
        parentComponent.getConfig().putSingle("attr", "value");
        parentComponent.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(false));
        String parentComponentId = addComponent(parentComponent);

        ComponentRepresentation subcomponent = new ComponentRepresentation();
        subcomponent.setParentId(parentComponentId);
        subcomponent.setName("child");
        subcomponent.setSubType("subtype2");
        subcomponent.setProviderId(UserMapStorageFactory.PROVIDER_ID);
        subcomponent.setProviderType(UserStorageProvider.class.getName());
        subcomponent.setConfig(new MultivaluedHashMap<>());
        subcomponent.getConfig().putSingle("priority", Integer.toString(0));
        subcomponent.getConfig().putSingle("attr", "value2");
        subcomponent.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(false));
        String subcomponentId = addComponent(subcomponent);

        final String exportFilePath = exportFile.getAbsolutePath();

        // export
        testingClient.server().run(session -> {
            ExportImportConfig.setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
            ExportImportConfig.setFile(exportFilePath);
            ExportImportConfig.setRealmName(REALM_NAME);
            ExportImportConfig.setAction(ExportImportConfig.ACTION_EXPORT);
            new ExportImportManager(session).runExport();
        });

        testRealmResource().remove();

        try {
            testRealmResource().toRepresentation();
            Assert.fail("Realm wasn't expected to be found");
        } catch (NotFoundException nfe) {
            // Expected
        }

        // import
        testingClient.server().run(session -> {
            Assert.assertNull(session.realms().getRealmByName(REALM_NAME));
            ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);
            new ExportImportManager(session).runImport();
        });

        // Assert realm was imported
        Assert.assertNotNull(testRealmResource().toRepresentation());

        try {
            parentComponent = testRealmResource().components().component(parentComponentId).toRepresentation();
            subcomponent = testRealmResource().components().component(subcomponentId).toRepresentation();
        } catch (NotFoundException nfe) {
            fail("Components not found after import.");
        }

        Assert.assertEquals(parentComponent.getParentId(), realmId);
        Assert.assertEquals(parentComponent.getName(), "parent");
        Assert.assertEquals(parentComponent.getSubType(), "subtype");
        Assert.assertEquals(parentComponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID);
        Assert.assertEquals(parentComponent.getProviderType(), UserStorageProvider.class.getName());
        Assert.assertEquals(parentComponent.getConfig().getFirst("attr"), "value");

        Assert.assertEquals(subcomponent.getParentId(), parentComponent.getId());
        Assert.assertEquals(subcomponent.getName(), "child");
        Assert.assertEquals(subcomponent.getSubType(), "subtype2");
        Assert.assertEquals(subcomponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID);
        Assert.assertEquals(subcomponent.getProviderType(), UserStorageProvider.class.getName());
        Assert.assertEquals(subcomponent.getConfig().getFirst("attr"), "value2");

    }

}


text:
export function readCookie(name: string, cookieString?: string): string | undefined {
  cookieString = cookieString || document.cookie
  const match = cookieString.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'))
  if (match) {
    return decodeURIComponent(match[3])
  }
}


text:
<?php

namespace Faker\ORM\Doctrine;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;

class ColumnTypeGuesser
{
    protected $generator;

    public function __construct(\Faker\Generator $generator)
    {
        $this->generator = $generator;
    }

    public function guessFormat($fieldName, ClassMetadata $class)
    {
        $generator = $this->generator;
        $type = $class->getTypeOfField($fieldName);
        switch ($type) {
            case 'boolean':
                return function() use ($generator) { return $generator->boolean; };
            case 'decimal':
                $size = isset($class->fieldMappings[$fieldName]['precision']) ? $class->fieldMappings[$fieldName]['precision'] : 2;

                return function() use ($generator, $size) { return $generator->randomNumber($size + 2) / 100; };
            case 'smallint':
                return function() { return mt_rand(0,65535); };
            case 'integer':
                return function() { return mt_rand(0,intval('2147483647')); };
            case 'bigint':
                return function() { return mt_rand(0,intval('18446744073709551615')); };
            case 'float':
                return function() { return mt_rand(0,intval('4294967295'))/mt_rand(1,intval('4294967295')); };
            case 'string':
                $size = isset($class->fieldMappings[$fieldName]['length']) ? $class->fieldMappings[$fieldName]['length'] : 255;

                return function() use ($generator, $size) { return $generator->text($size); };
            case 'text':
                return function() use ($generator) { return $generator->text; };
            case 'datetime':
            case 'date':
                case 'time':
                return function() use ($generator) { return $generator->datetime; };
            default:
                // no smart way to guess what the user expects here
                return null;
        }
    }
}


text:
package org.kitesdk.data.spi;

import com.google.common.base.Objects;

public class Pair<K, V> {

  private final K first;
  private final V second;

  public static <T, U> Pair<T, U> of(T first, U second) {
    return new Pair<T, U>(first, second);
  }

  public Pair(K first, V second) {
    this.first = first;
    this.second = second;
  }

  public K first() {
    return first;
  }

  public V second() {
    return second;
  }

  public Object get(int index) {
    switch (index) {
      case 0:
        return first;
      case 1:
        return second;
      default:
        throw new ArrayIndexOutOfBoundsException();
    }
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(first, second);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Pair<?, ?> other = (Pair<?, ?>) obj;
    return (Objects.equal(first, other.first)
        && Objects.equal(second, other.second));
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .add("first", first)
        .add("second", second)
        .toString();
  }
}


text:
export default function (characters?: string): string;
//# sourceMappingURL=remove_circumflexes.d.ts.map


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>reptile-services</artifactId>
        <groupId>com.poet</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>reptile-service-spring</artifactId>
    <packaging>jar</packaging>

    <name>reptile-service-spring</name>
    <url>http://maven.apache.org</url>

    <dependencies>

        <dependency>
            <groupId>com.poet</groupId>
            <artifactId>reptile-api-service</artifactId>
            <version>${parent.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>

    </dependencies>
</project>


text:
/*
 * default/pointer-push-button.js
 */

"use strict";

var Q = require('q'),
    Button = require('./../../button');

var PointerPushButton = function (options) {
    Button.prototype.constructor.call(this, options);
    this.delay = options.delay > 0 ? options.delay : 0;
    this.g = null;
    if(typeof options.g === 'function') this.g = options.g;
    this.promisef = null;
    this.boundaries = { minX : 0, maxX : 0, minY : 0, maxY : 0 };
    this.leftOrEnded = false;
    this.pointerId = null;
};

PointerPushButton.prototype = (function (proto) {
    function F() {};
    F.prototype = proto;
    return new F();
})(Button.prototype);

PointerPushButton.prototype.constructor = PointerPushButton;

PointerPushButton.prototype.setG = function (g) {
    if (typeof g !== 'function')
        throw new Error("Button setG method needs a g function as argument.");
    this.g = g;
    return this;
};

PointerPushButton.prototype._isDownPointerId = function (pointerId) {
    return this.pointerId === pointerId;
};

PointerPushButton.prototype._isInActiveZone = function (evt) {
    var x = evt.clientX,
        y = evt.clientY,
        b = this.boundaries;
    return x < b.maxX && x > b.minX && y < b.maxY && y > b.minY;
};

PointerPushButton.prototype._setPointerCapture = function (pointerId) {
    if (window.MSPointerEvent)
        this.el.msSetPointerCapture(pointerId);
    else
        this.el.setPointerCapture(pointerId);
};

PointerPushButton.prototype.bind = function () {
    Button.prototype.bind.call(this);
    if (window.MSPointerEvent) {
        this.el.addEventListener('MSPointerDown', this, false);
        this.el.addEventListener('MSPointerMove', this, false);
        this.el.addEventListener('MSPointerUp', this, false);
        this.el.addEventListener('MSPointerCancel', this, false);
    } else {
        this.el.addEventListener('pointerdown', this, false);
        this.el.addEventListener('pointermove', this, false);
        this.el.addEventListener('pointerup', this, false);
        this.el.addEventListener('pointercancel', this, false);
    }
    this.binded = true;
    return this;
};

PointerPushButton.prototype.unbind = function () {
    Button.prototype.unbind.call(this);
    if (window.MSPointerEvent) {
        this.el.removeEventListener('MSPointerDown', this, false);
        this.el.removeEventListener('MSPointerMove', this, false);
        this.el.removeEventListener('MSPointerUp', this, false);
        this.el.removeEventListener('MSPointerCancel', this, false);
    } else {
        this.el.removeEventListener('pointerdown', this, false);
        this.el.removeEventListener('pointermove', this, false);
        this.el.removeEventListener('pointerup', this, false);
        this.el.removeEventListener('pointercancel', this, false);
    }
    this.binded = false;
    return this;
};

PointerPushButton.prototype.handleEvent = function (evt) {
    switch (evt.type) {
        case 'MSPointerDown':
        case 'pointerdown':
            this.onPointerdown(evt);
            break;
        case 'MSPointerMove':
        case 'pointermove':
            this.onPointermove(evt);
            break;
        case 'MSPointerUp':
        case 'pointerup':
            this.onPointerup(evt);
            break;
        case 'MSPointerCancel':
        case 'pointercancel':
            this.onPointercancel(evt);
            break;
    }
};

PointerPushButton.prototype.onPointerdown = function (evt) {
    if(!this.active && (!this.monotouchable || !this.isLocked())) {
        if(this.monotouchable) this.lock();
        this.setActive(true);
        this.pointerId = evt.pointerId;
        this._setPointerCapture(evt.pointerId);
        var boundingRect = this.el.getBoundingClientRect();
        this.boundaries.minX = boundingRect.left;
        this.boundaries.maxX = boundingRect.left + boundingRect.width;
        this.boundaries.minY = boundingRect.top;
        this.boundaries.maxY = boundingRect.bottom;
        this.promisef = Q.delay(evt, this.delay).then(this.f);
    }
};

PointerPushButton.prototype.onPointermove = function (evt) {
    if (this.active && !this.leftOrEnded) {
        if (this._isDownPointerId(evt.pointerId)) {
            evt.preventDefault();
            if (!this._isInActiveZone(evt)) {
                this._removeCls();
                this.leftOrEnded = true;
                this.promisef
                        .then(evt)
                        .then(this.g)
                        .finally(this._done(evt))
                        .done();
            }
        }
    }
};

PointerPushButton.prototype._done = function (evt) {
    var btn = this;
    return function () {
        btn.onPointercancel(evt);
    };
};

PointerPushButton.prototype.onPointerup = function (evt) {
    if (this.active && !this.leftOrEnded) {
        if (this._isDownPointerId(evt.pointerId)) {
            this._removeCls();
            this.leftOrEnded = true;
            this.promisef
                    .then(evt)
                    .then(this.g)
                    .finally(this._done(evt))
                    .done();
        }
    }
};

PointerPushButton.prototype.onPointercancel = function (evt) {
    this.setActive(false);
    if(this.monotouchable) this.unlock();
    this.leftOrEnded = false;
};

module.exports = PointerPushButton;


text:
class TaxonFrameworkRelationship < ApplicationRecord
  alias_attribute :internal_taxa, :taxa

  attr_accessor :current_user

  belongs_to :user
  has_updater
  belongs_to :taxon_framework
  has_many :external_taxa, dependent: :destroy
  has_many :taxa, before_add: :check_if_covered, dependent: :nullify

  accepts_nested_attributes_for :external_taxa, allow_destroy: true
  accepts_nested_attributes_for :taxa

  before_save :set_relationship
  before_validation :mark_external_taxa_for_destruction

  validates :taxon_framework, presence: true
  validate :taxon_framework_has_source

  RELATIONSHIPS = [
    "match",
    "alternate_position",
    "one_to_one",
    "many_to_many",
    "many_to_one",
    "one_to_many",
    "not_external",
    "not_internal"
  ]

  INTERNAL_TAXON_JOINS = [
    "LEFT OUTER JOIN taxa t ON t.taxon_framework_relationship_id = taxon_framework_relationships.id"
  ]
  EXTERNAL_TAXON_JOINS = [
    "LEFT OUTER JOIN external_taxa et ON et.taxon_framework_relationship_id = taxon_framework_relationships.id"
  ]

  scope :relationships, lambda { |relationships| where( "taxon_framework_relationships.relationship IN (?)", relationships ) }
  scope :taxon_framework, lambda{ |taxon_framework| where("taxon_framework_relationships.taxon_framework_id = ?", taxon_framework ) }
  scope :by, lambda{ |user| where( user_id: user ) }
  scope :active, -> {
    joins( INTERNAL_TAXON_JOINS ).
    where( "t.is_active = true" )
  }
  scope :inactive, -> {
    joins( INTERNAL_TAXON_JOINS ).
    where( "t.is_active = false" )
  }
  scope :internal_rank, lambda { |rank|
    joins( INTERNAL_TAXON_JOINS ).
    where( "t.rank = ?", rank )
  }
  scope :external_rank, lambda { |rank|
    joins( EXTERNAL_TAXON_JOINS ).
    where( "et.rank = ?", rank )
  }
  scope :internal_taxon, lambda{ |taxon|
    joins( INTERNAL_TAXON_JOINS ).
    where( "t.id = ? OR t.ancestry LIKE (?) OR t.ancestry LIKE (?)", taxon.id, "%/#{ taxon.id }", "%/#{ taxon.id }/%")
  }
  scope :external_taxon, lambda{ |taxon_name|
    joins( EXTERNAL_TAXON_JOINS ).
    where( "lower(et.name) = ? OR lower(et.parent_name) = ?", taxon_name.downcase.strip, taxon_name.downcase.strip)
  }

  def mark_external_taxa_for_destruction
    external_taxa.each do |external_taxon|
      if external_taxon.name.blank?
        external_taxon.mark_for_destruction
      end
    end
  end

  def taxon_framework_has_source
    unless taxon_framework && taxon_framework.source_id.present?
      errors.add :taxon_framework_id, "taxon framework must have source"
    end
  end

  def taxa_covered_by_taxon_framework
    return false unless taxa.map{ |t| t.parent.id == taxon_framework.taxon_id || taxon.upstream_taxon_framework.id == taxon_framework.id }.all?
    true
  end

  def check_if_covered(taxon)
    unless taxon.id.nil? || taxon.rank.nil?
      raise if taxon.ancestry.nil?
      raise unless taxon.parent.id == taxon_framework.taxon_id || taxon.upstream_taxon_framework.id == taxon_framework.id
    end
    true
  end

  def set_relationship
    external_taxa_count = external_taxa.count
    taxa_count = taxa.count
    if external_taxa_count == 1 && taxa_count == 1
      if external_taxa.first.name == taxa.first.name &&
         external_taxa.first.rank == taxa.first.rank &&
         external_taxa.first.parent_name == taxa.first.parent.name &&
         external_taxa.first.parent_rank.downcase == taxa.first.parent.rank
        self.relationship = "match"
      elsif external_taxa.first.name == taxa.first.name &&
         external_taxa.first.rank == taxa.first.rank
        self.relationship = "alternate_position"
      else
        self.relationship = "one_to_one"
      end
    elsif external_taxa_count > 1 && taxa_count > 1
      self.relationship = "many_to_many"
    elsif external_taxa_count == 1 && taxa_count > 1
      self.relationship = "many_to_one"
    elsif external_taxa_count > 1 && taxa_count == 1
      self.relationship = "one_to_many"
    elsif external_taxa_count == 0 && taxa_count >= 1
      self.relationship = "not_external"
    elsif external_taxa_count >= 1 && taxa_count == 0
      self.relationship = "not_internal"
    else
      self.relationship = "error"
    end
    true
  end

  def as_json
    internal_taxa = self.internal_taxa.map{ |it|
        { name: it.name, rank: it.rank, parent_name: it.parent.name, parent_rank: it.parent.rank, url: it.id }
    }
    if it_root = ( internal_taxa.map{ |it| it[:parent_name] + "_" + it[:parent_rank] }.uniq - internal_taxa.map{ |it| it[:name] + "_" + it[:rank] }.uniq )[0]
      internal_taxa.unshift( { name: it_root.split( "_" )[0], rank: it_root.split( "_" )[1] } )
    else
      internal_taxa.unshift( { name: nil, rank: nil } )
    end
    external_taxa = self.external_taxa.map{ |et|
      { name: et.name, rank: et.rank, parent_name: et.parent_name, parent_rank: et.parent_rank, url: et.url }
    }
    if et_root = ( external_taxa.map{ |et| et[:parent_name] + "_" + et[:parent_rank] }.uniq - external_taxa.map{ |et| et[:name] + "_" + et[:rank] }.uniq)[0]
      external_taxa.unshift( { name:  et_root.split( "_" )[0], rank: et_root.split( "_" )[1] } )
    else
      external_taxa.unshift( { name: nil, rank: nil } )
    end
    if external_taxa.count == 1 && external_taxa[0][:name].nil? && external_taxa[0][:rank].nil?
      if it_root
        external_taxa[0] = { name: it_root.split( "_" )[0], rank: it_root.split( "_" )[1] }
      end
    end
    if internal_taxa.count == 1 && internal_taxa[0][:name].nil? && internal_taxa[0][:rank].nil?
      if et_root
        internal_taxa[0] = { name:  et_root.split( "_" )[0], rank: et_root.split( "_" )[1] }
      end
    end
    {
      internal_taxa: internal_taxa,
      external_taxa: external_taxa
    }
  end

end


text:
<?php
require '../../../lib/three_seventy_api.php';
require '../../config.php';
use ThreeSeventyApi\Client;

// Creates a new template for a content group. Note that you can only have one template per supported language type.
class AddContentTemplate {
    public function run() {
        // Load the config
        $config = getConfig();

        // Create Client object
        $client = new Client($config);

        // Create ContentTemplate factory
        $contentFactory = $client->getFactory("ContentTemplate");

        // Create Content object
        $content = $contentFactory->getNew(array( // Details of the new template's format.
            "LanguageId" => 0, // {int} The language this template is for. (0) English, (1) Spanish, (2) Simplified Chinese
            "ChannelTypeId" => 0, // {int} The type of channel this content can be sent to. (0) SMS, (1) MMS, (2) Email
            "EncodingTypeId" => 0, // {int} The format of the tempalte data. (0) Text, (1) Razor
            "Template" => '', // {string} The actual template
        ));

        // The content group which the template will be contained within.
        $content_id = 1;

        // Create Content repository object
        $contentRepo = $client->getRepo("Content");

        // Adding content via API
        $result = $contentRepo->addTemplate($content_id, $content);

        // Printing result
        print_r($result);
    }
}
$example = new AddContentTemplate();
$example->run();


text:
class ModuleDocFragment(object):

    # Standard files documentation fragment
    DOCUMENTATION = """
notes:
    - "Requires A10 Networks aXAPI 2.1"
options:
  host:
    description:
      - Hostname or IP of the A10 Networks device.
    required: true
    default: null
  username:
    description:
      - An account with administrator privileges.
    required: true
    aliases: ['user', 'admin']
    default: null
  password:
    description:
      - Password for the C(username) account.
    required: true
    aliases: ['pass', 'pwd']
    default: null
  write_config:
    description:
      - If C(yes), any changes will cause a write of the running configuration
        to non-volatile memory. This will save I(all) configuration changes,
        including those that may have been made manually or through other modules,
        so care should be taken when specifying C(yes).
    required: false
    version_added: 2.2
    default: "no"
    choices: ["yes", "no"]
  validate_certs:
    description:
      - If C(no), SSL certificates will not be validated. This should only be used
        on personally controlled devices using self-signed certificates.
    required: false
    version_added: 2.2
    default: 'yes'
    choices: ['yes', 'no']
"""


text:
import pytest
from mock import Mock
from mock import patch

from nuts.data.test_suite import TestSuite as TSuite
from nuts.service.runner import Runner
from nuts.service.salt_api_wrapper import SaltApi

@pytest.fixture
def example_testsuite():
    test_suite = TSuite('ExampleSuite')
    data = [
        {'name': 'testPingFromAToB',
         'command': 'connectivity',
         'devices': 'Server01',
         'parameter': ['8.8.8.8'],
         'operator': '=',
         'expected': 'True'
         },
        {'name': 'checkuser',
         'command': 'checkuser',
         'devices': 'Server01',
         'parameter': ['8.8.8.8'],
         'operator': '=',
         'expected': 'admin'
         },
        {'name': 'Count ospf neighbors',
         'command': 'countospfneighbors',
         'devices': 'Switch1',
         'parameter': [],
         'operator': '=',
         'expected': '3'
         },
        {'name': 'bandwidth test',
         'command': 'bandwidth',
         'devices': 'linux1',
         'parameter': ['10.10.10.10'],
         'operator': '<',
         'expected': '100000000',
         'setup': [
             {'command': 'cmd.run',
              'devices': 'linux2',
              'parameter': ['iperf3 -s -D -1']
              },
             {'command': 'network.ip_addrs',
              'devices': 'linux2',
              'save': 'ip'
              }
         ],
         'teardown': [
             {'command': 'cmd.run',
              'devices': 'linux2',
              'parameter': ['pkill iperf3']
              }
         ]
         }
    ]
    for d in data:
        test_suite.create_test(**d)
    return test_suite

@pytest.fixture
def mock_testsuite():
    mock = Mock(spec=TSuite)
    return mock

@pytest.fixture
def api_mock():
    mock = Mock(spec=SaltApi)
    mock.start_task.return_value = {
        'return': [{'cisco.csr.1000v': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'}}]}
    mock.start_task_async.return_value = {
        'return': [{'jid': '20170302070941729675', 'minions': ['cisco.csr.1000v']}]}
    mock.get_task_result.return_value = {
        'return': [{'cisco.csr.1000v': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'}}]}
    return mock

def test_run_all_sync(example_testsuite, api_mock):
    example_testsuite.test_cases_sync += example_testsuite.test_cases_async
    example_testsuite.test_cases_async = []
    with patch.object(Runner, '_start_test_sync') as run_method_mocked:
        Runner(example_testsuite, api_mock).run_all()
        api_mock.connect.assert_called()
        run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('testPingFromAToB'))
        run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('checkuser'))
        run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('Count ospf neighbors'))
        run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('bandwidth test'))

def test_run_all_async(example_testsuite, api_mock):
    example_testsuite.test_cases_async += example_testsuite.test_cases_sync
    example_testsuite.test_cases_sync = []
    with patch.object(Runner, '_start_test_async') as run_method_mocked:
        with patch.object(Runner, '_collect_result') as result_method_mocked:
            Runner(example_testsuite, api_mock).run_all()
            api_mock.connect.assert_called()
            run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('testPingFromAToB'))
            run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('checkuser'))
            run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('Count ospf neighbors'))
            run_method_mocked.assert_any_call(example_testsuite.get_test_by_name('bandwidth test'))
            result_method_mocked.assert_any_call(example_testsuite.get_test_by_name('testPingFromAToB'))
            result_method_mocked.assert_any_call(example_testsuite.get_test_by_name('checkuser'))
            result_method_mocked.assert_any_call(example_testsuite.get_test_by_name('Count ospf neighbors'))
            result_method_mocked.assert_any_call(example_testsuite.get_test_by_name('bandwidth test'))

def test_run_setup_teardown_sync(api_mock):
    test_suite = TSuite('TestTestSuite')
    test_suite.create_test(name='test', command='testcmd', devices='sw01', parameter='', operator='=', expected=True,
                           setup=[{'command': 'test setup cmd'}], teardown=[{'command': 'test setup cmd'}])
    with patch.object(Runner, '_start_tasks') as start_task_method_mocked:
        Runner(test_suite, api_mock).run_all()
        start_task_method_mocked.assert_any_call(test_suite.test_cases_sync[0].setup_tasks)
        start_task_method_mocked.assert_any_call(test_suite.test_cases_sync[0].teardown_tasks)

def test_run_setup_teardown_async(api_mock):
    test_suite = TSuite('TestTestSuite')
    test_suite.create_test(name='test', command='testcmd', devices='sw01', parameter='', operator='=', expected=True,
                           setup=[{'command': 'test setup cmd'}], teardown=[{'command': 'test setup cmd'}], async=True)
    with patch.object(Runner, '_start_tasks') as start_task_method_mocked:
        Runner(test_suite, api_mock).run_all()
        start_task_method_mocked.assert_any_call(test_suite.test_cases_async[0].setup_tasks)
        start_task_method_mocked.assert_any_call(test_suite.test_cases_async[0].teardown_tasks)

def test_return_setup(api_mock):
    test_suite = TSuite('TestTestSuite')
    test_suite.create_test(name='test', command='testcmd', devices='sw01', parameter='', operator='=', expected=True,
                           setup=[{'command': 'test setup cmd', 'devices': 'sw99', 'save': 'ip'}])
    with patch.object(Runner, '_get_task_result') as create_task_method_mocked:
        Runner(test_suite, api_mock).run_all()
        test_case = test_suite.test_cases_sync[0]
        saved_data = {'ip': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'}}
        create_task_method_mocked.assert_any_call(test_case, saved_data)

def test_start_task(example_testsuite, api_mock):
    runner = Runner(example_testsuite, api_mock)
    test_case = example_testsuite.get_test_by_name('testPingFromAToB')
    runner._start_test_async(test_case)
    api_mock.start_task_async.assert_called_with(
            runner.create_test_task(test_case.devices, test_case.command, test_case.parameter))
    assert test_case.job_id == u'20170302070941729675'

def test_collect_result(example_testsuite, api_mock):
    runner = Runner(example_testsuite, api_mock)
    test_case = example_testsuite.get_test_by_name('testPingFromAToB')
    test_case.job_id = u'20170302070941729675'
    runner._collect_result(test_case)
    api_mock.get_task_result.assert_called_with(taskid=u'20170302070941729675')
    assert test_case.get_actual_result() == {
        u'cisco.csr.1000v': {
            'resulttype': 'single',
            'result': '00:0C:29:EA:D1:68'
        }}

def test_run(example_testsuite, api_mock):
    runner = Runner(example_testsuite, api_mock)
    test_case = example_testsuite.get_test_by_name('testPingFromAToB')
    runner._start_test_sync(test_case)
    api_mock.start_task.assert_called_with(
            runner.create_test_task(test_case.devices, test_case.command, test_case.parameter))
    assert test_case.get_actual_result() == {
        u'cisco.csr.1000v': {
            'resulttype': 'single',
            'result': '00:0C:29:EA:D1:68'
        }}

def test_extract_return_multiple_devices():
    return_dict = {'return': [{'cisco.csr.1000v': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'},
                               'cisco.test': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'}}]}
    assert Runner._extract_return(return_dict) == {
        u'cisco.csr.1000v': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'},
        u'cisco.test': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'}
    }

def test_extract_return_empty_multiple_devices():
    return_dict = {u'return': [{u'cisco.csr.1000v': None,
                                u'cisco.test': None}]}
    assert Runner._extract_return(return_dict) == {
        u'cisco.csr.1000v': {'resulttype': 'single', 'result': None},
        u'cisco.test': {'resulttype': 'single', 'result': None}
    }

def test_extract_return():
    return_dict = {'return': [{'cisco.csr.1000v': {'resulttype': 'single', 'result': '00:0C:29:EA:D1:68'}}]}
    assert Runner._extract_return(return_dict) == {
        u'cisco.csr.1000v': {
            'resulttype': 'single',
            'result': '00:0C:29:EA:D1:68'
        }}

def test_extract_return_empty():
    return_dict = {u'return': [{u'cisco.csr.1000v': None}]}
    assert Runner._extract_return(return_dict) == {
        u'cisco.csr.1000v': {
            'resulttype': 'single',
            'result': None
        }}

def test_create_task(example_testsuite, api_mock):
    runner = Runner(example_testsuite, api_mock)
    test_case = example_testsuite.get_test_by_name('testPingFromAToB')
    task = runner.create_test_task(test_case.devices, test_case.command, test_case.parameter)
    assert 'targets' in task
    assert 'function' in task
    assert 'arguments' in task
    assert task['targets'] == 'Server01'
    assert task['function'] == 'nuts.connectivity'
    assert task['arguments'] == ['8.8.8.8']

def test_create_task_render():
    task = Runner.create_test_task(devices='sw01{{ id }}', command='test.{{cmd}}',
                                   parameter=['{{ par }}', 'test2 {{ par2 }}'],
                                   render_data={'id': 123, 'cmd': 'command', 'par': 'parameter', 'par2': 2})
    assert 'targets' in task
    assert 'function' in task
    assert 'arguments' in task
    assert task['targets'] == 'sw01123'
    assert task['function'] == 'test.command'
    assert task['arguments'] == ['parameter', 'test2 2']

def test_create_task_add_nuts():
    task = Runner.create_test_task(devices='sw01', command='test')

    assert 'function' in task
    assert task['function'] == 'nuts.test'


text:
#ifndef _SUNXI_DMA_H
#define _SUNXI_DMA_H

#if defined(CONFIG_MACH_SUN4I) || defined(CONFIG_MACH_SUN5I) || defined(CONFIG_MACH_SUN7I)
#include <asm/arch/dma_sun4i.h>
#else
#error "DMA definition not available for this architecture"
#endif

#endif /* _SUNXI_DMA_H */


text:
#ifndef BOOST_HANA_DETAIL_OPERATORS_ORDERABLE_HPP
#define BOOST_HANA_DETAIL_OPERATORS_ORDERABLE_HPP

#include <boost/hana/config.hpp>
#include <boost/hana/core/tag_of.hpp>
#include <boost/hana/fwd/greater.hpp>
#include <boost/hana/fwd/greater_equal.hpp>
#include <boost/hana/fwd/less.hpp>
#include <boost/hana/fwd/less_equal.hpp>

#include <type_traits>

BOOST_HANA_NAMESPACE_BEGIN namespace detail {
    template <typename Tag>
    struct orderable_operators {
        static constexpr bool value = false;
    };

    namespace operators {
        template <typename X, typename Y, typename = typename std::enable_if<
            detail::orderable_operators<typename hana::tag_of<X>::type>::value ||
            detail::orderable_operators<typename hana::tag_of<Y>::type>::value
        >::type>
        constexpr auto operator<(X&& x, Y&& y)
        { return hana::less(static_cast<X&&>(x), static_cast<Y&&>(y)); }

        template <typename X, typename Y, typename = typename std::enable_if<
            detail::orderable_operators<typename hana::tag_of<X>::type>::value ||
            detail::orderable_operators<typename hana::tag_of<Y>::type>::value
        >::type>
        constexpr auto operator>(X&& x, Y&& y)
        { return hana::greater(static_cast<X&&>(x), static_cast<Y&&>(y)); }

        template <typename X, typename Y, typename = typename std::enable_if<
            detail::orderable_operators<typename hana::tag_of<X>::type>::value ||
            detail::orderable_operators<typename hana::tag_of<Y>::type>::value
        >::type>
        constexpr auto operator<=(X&& x, Y&& y)
        { return hana::less_equal(static_cast<X&&>(x), static_cast<Y&&>(y)); }

        template <typename X, typename Y, typename = typename std::enable_if<
            detail::orderable_operators<typename hana::tag_of<X>::type>::value ||
            detail::orderable_operators<typename hana::tag_of<Y>::type>::value
        >::type>
        constexpr auto operator>=(X&& x, Y&& y)
        { return hana::greater_equal(static_cast<X&&>(x), static_cast<Y&&>(y)); }
    } // end namespace operators
} BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_DETAIL_OPERATORS_ORDERABLE_HPP


text:
<root>
    <properties>
        <name>LearningBot</name>
        <id>learningbot</id>
        <version>1.0</version>
        <description> </description>
        <isactive>True</isactive>
        <debugmode>True</debugmode>
    </properties>
</root>


text:
{include file="header.html"}

{$lang.goods}

{$lang.all_goods}{$lang.all_goods}

{$lang.closed}{$lang.closed}

    <form method="get">
      <input type="hidden" name="app" value="goods" />

      <input type="hidden" name="closed" value="1" />
       {$lang.goods_name}:
      <input class="queryInput" type="text" name="goods_name" value="{$smarty.get.goods_name|escape}" />
      {$lang.store_name}:
      <input class="queryInput" type="text" name="store_name" value="{$smarty.get.store_name|escape}" />
      {$lang.brand}:
      <input class="queryInput" type="text" name="brand" value="{$smarty.get.brand|escape}" />

          {$lang.gcategory}:

            <input type="hidden" name="cate_id" value="0" class="mls_id" />
            <select class="querySelect">
              <option>{$lang.select_pls}</option>
              {html_options options=$gcategories}
            </select>

          <input type="submit" class="formbtn" value="{$lang.query}" />

      {$lang.cancel_query}

    </form>

{include file=page.top.html}

      <input type="checkbox" class="checkall" />
	  {if $enable_radar}{$lang.enable_radar}	{/if}
      {$lang.goods_name}
      {$lang.store_name}
      {$lang.brand}
      {$lang.gcategory}
      {$lang.if_show}
      {$lang.close}
      {$lang.views}
      {$lang.handler}

      <input type="checkbox" class="checkitem" value="{$goods.goods_id}"/>
    {if $enable_radar}

    {/if}
      {$goods.goods_name|escape}
      {$goods.store_name|escape}
      {$goods.brand|escape}
      {$goods.cate_name|nl2br}

      {$goods.views|default:0}
      {$lang.view}

      {$lang.no_data}

      <input class="formbtn batchButton" type="button" value="{$lang.recommend}" name="id" uri="index.php?app=goods&act=recommend&ret_page={$page_info.curr_page}" />

      <input class="formbtn batchButton" type="button" value="{$lang.edit}" name="id" uri="index.php?app=goods&act=edit&ret_page={$page_info.curr_page}" />
      <input class="formbtn batchButton" type="button" value="{$lang.drop}" name="id" uri="index.php?app=goods&act=drop&ret_page={$page_info.curr_page}" presubmit="confirm('{$lang.drop_confirm}')" />

{include file=page.bottom.html}

{include file="footer.html"}{if $enable_radar}
<input type="hidden" id="radar_lincense_id" value="" />
<input type="hidden" id="radar_product_key" value="ecmall" />
<input type="hidden" id="radar_sign_key" value="" />

{/if}


text:
import("utils.ipa.package", {alias = "ipagen"})
import("lib.detect.find_tool")

-- main entry
function main (ipafile)

    -- check
    assert(os.exists(ipafile), "%s not found!", ipafile)

    -- find ideviceinstaller
    local ideviceinstaller = assert(find_tool("ideviceinstaller"), "ideviceinstaller not found!")

    -- is *.app directory? package it first
    local istmp = false
    if os.isdir(ipafile) then
        local appdir = ipafile
        ipafile = os.tmpfile() .. ".ipa"
        ipagen(appdir, ipafile)
        istmp = true
    end

    -- do install
    os.vrunv(ideviceinstaller.program, {"-i", ipafile})
    if istmp then
        os.tryrm(ipafile)
    end
end


text:
package mesos

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/inputs"
	jsonparser "github.com/influxdata/telegraf/plugins/parsers/json"
)

type Mesos struct {
	Timeout    int
	Masters    []string
	MasterCols []string `toml:"master_collections"`
}

var defaultMetrics = []string{
	"resources", "master", "system", "slaves", "frameworks",
	"tasks", "messages", "evqueue", "messages", "registrar",
}

var sampleConfig = `
  # Timeout, in ms.
  timeout = 100
  # A list of Mesos masters, default value is localhost:5050.
  masters = ["localhost:5050"]
  # Metrics groups to be collected, by default, all enabled.
  master_collections = [
    "resources",
    "master",
    "system",
    "slaves",
    "frameworks",
    "messages",
    "evqueue",
    "registrar",
  ]
`

// SampleConfig returns a sample configuration block
func (m *Mesos) SampleConfig() string {
	return sampleConfig
}

// Description just returns a short description of the Mesos plugin
func (m *Mesos) Description() string {
	return "Telegraf plugin for gathering metrics from N Mesos masters"
}

// Gather() metrics from given list of Mesos Masters
func (m *Mesos) Gather(acc telegraf.Accumulator) error {
	var wg sync.WaitGroup
	var errorChannel chan error

	if len(m.Masters) == 0 {
		m.Masters = []string{"localhost:5050"}
	}

	errorChannel = make(chan error, len(m.Masters)*2)

	for _, v := range m.Masters {
		wg.Add(1)
		go func(c string) {
			errorChannel <- m.gatherMetrics(c, acc)
			wg.Done()
			return
		}(v)
	}

	wg.Wait()
	close(errorChannel)
	errorStrings := []string{}

	// Gather all errors for returning them at once
	for err := range errorChannel {
		if err != nil {
			errorStrings = append(errorStrings, err.Error())
		}
	}

	if len(errorStrings) > 0 {
		return errors.New(strings.Join(errorStrings, "\n"))
	}
	return nil
}

// metricsDiff() returns set names for removal
func metricsDiff(w []string) []string {
	b := []string{}
	s := make(map[string]bool)

	if len(w) == 0 {
		return b
	}

	for _, v := range w {
		s[v] = true
	}

	for _, d := range defaultMetrics {
		if _, ok := s[d]; !ok {
			b = append(b, d)
		}
	}

	return b
}

// masterBlocks serves as kind of metrics registry groupping them in sets
func masterBlocks(g string) []string {
	var m map[string][]string

	m = make(map[string][]string)

	m["resources"] = []string{
		"master/cpus_percent",
		"master/cpus_used",
		"master/cpus_total",
		"master/cpus_revocable_percent",
		"master/cpus_revocable_total",
		"master/cpus_revocable_used",
		"master/disk_percent",
		"master/disk_used",
		"master/disk_total",
		"master/disk_revocable_percent",
		"master/disk_revocable_total",
		"master/disk_revocable_used",
		"master/mem_percent",
		"master/mem_used",
		"master/mem_total",
		"master/mem_revocable_percent",
		"master/mem_revocable_total",
		"master/mem_revocable_used",
	}

	m["master"] = []string{
		"master/elected",
		"master/uptime_secs",
	}

	m["system"] = []string{
		"system/cpus_total",
		"system/load_15min",
		"system/load_5min",
		"system/load_1min",
		"system/mem_free_bytes",
		"system/mem_total_bytes",
	}

	m["slaves"] = []string{
		"master/slave_registrations",
		"master/slave_removals",
		"master/slave_reregistrations",
		"master/slave_shutdowns_scheduled",
		"master/slave_shutdowns_canceled",
		"master/slave_shutdowns_completed",
		"master/slaves_active",
		"master/slaves_connected",
		"master/slaves_disconnected",
		"master/slaves_inactive",
	}

	m["frameworks"] = []string{
		"master/frameworks_active",
		"master/frameworks_connected",
		"master/frameworks_disconnected",
		"master/frameworks_inactive",
		"master/outstanding_offers",
	}

	m["tasks"] = []string{
		"master/tasks_error",
		"master/tasks_failed",
		"master/tasks_finished",
		"master/tasks_killed",
		"master/tasks_lost",
		"master/tasks_running",
		"master/tasks_staging",
		"master/tasks_starting",
	}

	m["messages"] = []string{
		"master/invalid_executor_to_framework_messages",
		"master/invalid_framework_to_executor_messages",
		"master/invalid_status_update_acknowledgements",
		"master/invalid_status_updates",
		"master/dropped_messages",
		"master/messages_authenticate",
		"master/messages_deactivate_framework",
		"master/messages_decline_offers",
		"master/messages_executor_to_framework",
		"master/messages_exited_executor",
		"master/messages_framework_to_executor",
		"master/messages_kill_task",
		"master/messages_launch_tasks",
		"master/messages_reconcile_tasks",
		"master/messages_register_framework",
		"master/messages_register_slave",
		"master/messages_reregister_framework",
		"master/messages_reregister_slave",
		"master/messages_resource_request",
		"master/messages_revive_offers",
		"master/messages_status_update",
		"master/messages_status_update_acknowledgement",
		"master/messages_unregister_framework",
		"master/messages_unregister_slave",
		"master/messages_update_slave",
		"master/recovery_slave_removals",
		"master/slave_removals/reason_registered",
		"master/slave_removals/reason_unhealthy",
		"master/slave_removals/reason_unregistered",
		"master/valid_framework_to_executor_messages",
		"master/valid_status_update_acknowledgements",
		"master/valid_status_updates",
		"master/task_lost/source_master/reason_invalid_offers",
		"master/task_lost/source_master/reason_slave_removed",
		"master/task_lost/source_slave/reason_executor_terminated",
		"master/valid_executor_to_framework_messages",
	}

	m["evqueue"] = []string{
		"master/event_queue_dispatches",
		"master/event_queue_http_requests",
		"master/event_queue_messages",
	}

	m["registrar"] = []string{
		"registrar/state_fetch_ms",
		"registrar/state_store_ms",
		"registrar/state_store_ms/max",
		"registrar/state_store_ms/min",
		"registrar/state_store_ms/p50",
		"registrar/state_store_ms/p90",
		"registrar/state_store_ms/p95",
		"registrar/state_store_ms/p99",
		"registrar/state_store_ms/p999",
		"registrar/state_store_ms/p9999",
	}

	ret, ok := m[g]

	if !ok {
		log.Println("[mesos] Unkown metrics group: ", g)
		return []string{}
	}

	return ret
}

// removeGroup(), remove unwanted sets
func (m *Mesos) removeGroup(j *map[string]interface{}) {
	var ok bool

	b := metricsDiff(m.MasterCols)

	for _, k := range b {
		for _, v := range masterBlocks(k) {
			if _, ok = (*j)[v]; ok {
				delete((*j), v)
			}
		}
	}
}

var tr = &http.Transport{
	ResponseHeaderTimeout: time.Duration(3 * time.Second),
}

var client = &http.Client{
	Transport: tr,
	Timeout:   time.Duration(4 * time.Second),
}

// This should not belong to the object
func (m *Mesos) gatherMetrics(a string, acc telegraf.Accumulator) error {
	var jsonOut map[string]interface{}

	host, _, err := net.SplitHostPort(a)
	if err != nil {
		host = a
		a = a + ":5050"
	}

	tags := map[string]string{
		"server": host,
	}

	if m.Timeout == 0 {
		log.Println("[mesos] Missing timeout value, setting default value (100ms)")
		m.Timeout = 100
	}

	ts := strconv.Itoa(m.Timeout) + "ms"

	resp, err := client.Get("http://" + a + "/metrics/snapshot?timeout=" + ts)

	if err != nil {
		return err
	}

	data, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return err
	}

	if err = json.Unmarshal([]byte(data), &jsonOut); err != nil {
		return errors.New("Error decoding JSON response")
	}

	m.removeGroup(&jsonOut)

	jf := jsonparser.JSONFlattener{}

	err = jf.FlattenJSON("", jsonOut)

	if err != nil {
		return err
	}

	acc.AddFields("mesos", jf.Fields, tags)

	return nil
}

func init() {
	inputs.Add("mesos", func() telegraf.Input {
		return &Mesos{}
	})
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Task13
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implement the ADT queue as dynamic linked list.
            //Use generics (LinkedQueue<T>)to allow storing different data types in the queue.

            LinkedQueue<int> queue = new LinkedQueue<int>();

            Console.WriteLine("Add 1,2,3 in the queue");
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);

            Console.WriteLine("Dequeue the values");
            Console.WriteLine(queue.Dequeue());
            Console.WriteLine(queue.Dequeue());
            Console.WriteLine(queue.Dequeue());
        }
    }
}


text:
package org.spongepowered.mod.mixin.core.api.event;

import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.mod.interfaces.IMixinEvent;

@Mixin(AbstractEvent.class)
public abstract class MixinAbstractEvent implements IMixinEvent {

    @Override
    public void syncDataToForge(Event spongeEvent) { }

    @Override
    public void syncDataToSponge(Event spongeEvent) { }

    @Override
    public Event createSpongeEvent() {
        return (Event) this;
    }

}


text:
package constant

const (
	// HeaderJWTClaim is the special header name used in virtual service for routing based on JWT claims.
	HeaderJWTClaim = "@request.auth.claims."
)


text:
This repo will include some of my sliders built by [http://lab.hakim.se/reveal-js/](http://lab.hakim.se/reveal-js/)

- [Data Visualization](http://chihsuan.github.io/slides/data_visualization/)

## LICENSE
MIT


text:
'use strict';

/* Application - App unit test */

describe('Controller: AppCtrl', function () {

    // load the controller's module
    beforeEach(module('app', 'appServices'));

    var AppCtrl,
        scope;

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope, titleService) {
        scope = $rootScope.$new();
        AppCtrl = $controller('AppCtrl', {
            $scope: scope
        });
    }));
});


text:
#ifndef CALL_FAKE_RTP_TRANSPORT_CONTROLLER_SEND_H_
#define CALL_FAKE_RTP_TRANSPORT_CONTROLLER_SEND_H_

#include BOSS_WEBRTC_U_call__rtp_transport_controller_send_interface_h //original-code:"call/rtp_transport_controller_send_interface.h"
#include BOSS_WEBRTC_U_common_types_h //original-code:"common_types.h"  // NOLINT(build/include)
#include "modules/congestion_controller/include/send_side_congestion_controller.h"
#include "modules/pacing/packet_router.h"

namespace webrtc {

class FakeRtpTransportControllerSend
    : public RtpTransportControllerSendInterface {
 public:
  explicit FakeRtpTransportControllerSend(
      PacketRouter* packet_router,
      PacedSender* paced_sender,
      SendSideCongestionController* send_side_cc)
      : packet_router_(packet_router),
        paced_sender_(paced_sender),
        send_side_cc_(send_side_cc) {
    RTC_DCHECK(send_side_cc);
  }

  PacketRouter* packet_router() override { return packet_router_; }

  SendSideCongestionController* send_side_cc() override {
    return send_side_cc_;
  }

  TransportFeedbackObserver* transport_feedback_observer() override {
    return send_side_cc_;
  }

  PacedSender* pacer() override { return paced_sender_; }

  RtpPacketSender* packet_sender() override { return paced_sender_; }

  const RtpKeepAliveConfig& keepalive_config() const override {
    return keepalive_;
  }

  void SetAllocatedSendBitrateLimits(int min_send_bitrate_bps,
                                     int max_padding_bitrate_bps) override {}

  void set_keepalive_config(const RtpKeepAliveConfig& keepalive_config) {
    keepalive_ = keepalive_config;
  }

 private:
  PacketRouter* packet_router_;
  PacedSender* paced_sender_;
  SendSideCongestionController* send_side_cc_;
  RtpKeepAliveConfig keepalive_;
};

}  // namespace webrtc

#endif  // CALL_FAKE_RTP_TRANSPORT_CONTROLLER_SEND_H_


text:
<!DOCTYPE html>
  <title>Form Thing</title>

    Name: <input type="text">

    Awake? <input type="checkbox">

    Best color: <select>
      <option>Red</option>
      <option>Orange</option>
      <option>Yellow</option>
      <option>Green</option>
      <option>Blue</option>
    </select>

    Worst color: <select multiple="">
      <option>Red</option>
      <option>Orange</option>
      <option>Yellow</option>
      <option>Green</option>
      <option>Blue</option>
    </select>

    Password: <input type="password">

  <form>
    A: <input type="radio" name="foo" value="a">
    B: <input type="radio" name="foo" value="b">
  </form>

  <form>
    A: <input type="radio" name="foo" value="a">
    B: <input type="radio" name="foo" value="b">
  </form>

  A: <input type="radio" name="foo" value="a">
  B: <input type="radio" name="foo" value="b">


text:
import {expectType} from 'tsd';
import lowercaseKeys from './index.js';

expectType<Record<string, boolean>>(lowercaseKeys({FOO: true, bAr: false})); // eslint-disable-line @typescript-eslint/naming-convention
expectType<Record<string, string | number>>(lowercaseKeys({foo: 'bar', baz: 1}));


text:
import * as configuration from "./configuration";
import * as formatters from "./formatters";
import { RuleFailure } from "./language/rule/rule";
import * as rules from "./rules";
import * as test from "./test";
import * as linter from "./tslint";
import * as utils from "./utils";
export * from "./language/rule/rule";
export * from "./enableDisableRules";
export * from "./formatterLoader";
export * from "./ruleLoader";
export * from "./language/utils";
export * from "./language/languageServiceHost";
export * from "./language/walker";
export * from "./language/formatter/formatter";
export declare var Configuration: typeof configuration;
export declare var Formatters: typeof formatters;
export declare var Linter: typeof linter;
export declare var Rules: typeof rules;
export declare var Test: typeof test;
export declare var Utils: typeof utils;
export interface LintResult {
    failureCount: number;
    failures: RuleFailure[];
    format: string | Function;
    output: string;
}
export interface ILinterOptionsRaw {
    configuration?: any;
    formatter?: string | Function;
    formattersDirectory?: string;
    rulesDirectory?: string | string[];
}
export interface ILinterOptions extends ILinterOptionsRaw {
    configuration: any;
    formatter: string | Function;
    rulesDirectory: string | string[];
}
export interface IMultiLinterOptions {
    formatter?: string | Function;
    formattersDirectory?: string;
    rulesDirectory?: string | string[];
}


text:
namespace FunctionHacker.Forms
{
    partial class FormSelectProcess
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            this.dataProcessList = new System.Windows.Forms.DataGridView();
            this.processName = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.processID = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.processText = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.processPrivilege = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.processPath = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.refreshTimer = new System.Windows.Forms.Timer(this.components);
            this.buttonRefresh = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataProcessList)).BeginInit();
            this.SuspendLayout();
            //
            // dataProcessList
            //
            this.dataProcessList.AllowUserToAddRows = false;
            this.dataProcessList.AllowUserToDeleteRows = false;
            this.dataProcessList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dataProcessList.BackgroundColor = System.Drawing.Color.White;
            this.dataProcessList.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.SingleHorizontal;
            this.dataProcessList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataProcessList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.processName,
            this.processID,
            this.processText,
            this.processPrivilege,
            this.processPath});
            this.dataProcessList.Location = new System.Drawing.Point(-1, 2);
            this.dataProcessList.MultiSelect = false;
            this.dataProcessList.Name = "dataProcessList";
            this.dataProcessList.ReadOnly = true;
            this.dataProcessList.RowHeadersVisible = false;
            this.dataProcessList.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.False;
            this.dataProcessList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dataProcessList.Size = new System.Drawing.Size(822, 442);
            this.dataProcessList.TabIndex = 3;
            this.dataProcessList.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataProcessListCellDoubleClick1);
            this.dataProcessList.CellContentDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataProcessListCellContentDoubleClick);
            this.dataProcessList.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataProcessListCellContentClick);
            //
            // processName
            //
            this.processName.HeaderText = "Process";
            this.processName.Name = "processName";
            this.processName.ReadOnly = true;
            //
            // processID
            //
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            this.processID.DefaultCellStyle = dataGridViewCellStyle2;
            this.processID.HeaderText = "PID";
            this.processID.Name = "processID";
            this.processID.ReadOnly = true;
            this.processID.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            //
            // processText
            //
            this.processText.HeaderText = "Window Text";
            this.processText.Name = "processText";
            this.processText.ReadOnly = true;
            //
            // processPrivilege
            //
            this.processPrivilege.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
            this.processPrivilege.HeaderText = "Privilege";
            this.processPrivilege.Name = "processPrivilege";
            this.processPrivilege.ReadOnly = true;
            this.processPrivilege.Width = 72;
            //
            // processPath
            //
            this.processPath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.processPath.HeaderText = "Path";
            this.processPath.Name = "processPath";
            this.processPath.ReadOnly = true;
            //
            // refreshTimer
            //
            this.refreshTimer.Interval = 1000;
            this.refreshTimer.Tick += new System.EventHandler(this.RefreshTimerTick);
            //
            // buttonRefresh
            //
            this.buttonRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonRefresh.Location = new System.Drawing.Point(734, 450);
            this.buttonRefresh.Name = "buttonRefresh";
            this.buttonRefresh.Size = new System.Drawing.Size(87, 23);
            this.buttonRefresh.TabIndex = 4;
            this.buttonRefresh.Text = "Refresh";
            this.buttonRefresh.UseVisualStyleBackColor = true;
            this.buttonRefresh.Click += new System.EventHandler(this.buttonRefresh_Click);
            //
            // FormSelectProcess
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(821, 478);
            this.Controls.Add(this.buttonRefresh);
            this.Controls.Add(this.dataProcessList);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
            this.Name = "FormSelectProcess";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Select Process to Analyse";
            this.Load += new System.EventHandler(this.FormSelectProcessLoad);
            ((System.ComponentModel.ISupportInitialize)(this.dataProcessList)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dataProcessList;
        private System.Windows.Forms.Timer refreshTimer;
        private System.Windows.Forms.Button buttonRefresh;
        private System.Windows.Forms.DataGridViewTextBoxColumn processName;
        private System.Windows.Forms.DataGridViewTextBoxColumn processID;
        private System.Windows.Forms.DataGridViewTextBoxColumn processText;
        private System.Windows.Forms.DataGridViewTextBoxColumn processPrivilege;
        private System.Windows.Forms.DataGridViewTextBoxColumn processPath;
    }
}


text:
package at.tugraz.sss.adapter.rest.v3.system;

//@Path("/system")
//@Api(value = "/system")
public class SSRESTSystem{

  //TODO reimplement
//  @GET
//  @Consumes(MediaType.APPLICATION_JSON)
//  @Produces(MediaType.APPLICATION_JSON)
//  @Path    ("/version")
//  @ApiOperation(
//    value = "retrieve the version of the sss instance",
//    response = SSSystemVersionGetRet.class)
//  public Response systemVersionGet(
//    @Context
//      final HttpHeaders headers){
//
//    final ObjectMapper          sssJSONResponseMapper    = new ObjectMapper();
//    final SSSystemVersionGetPar par;
//    final SSRESTObject          restObj;
//    final SSSystemVersionGetRet ret;
//    final JsonNode              sssJSONResponseRootNode;
//
//    try{
//
//      par = new SSSystemVersionGetPar();
//
//      restObj = new SSRESTObject(par);
//
//    }catch(Exception error){
//      return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
//    }
//
//    try{
//      try{
//
//        restObj.sssCon =
//          new SSSocketCon(
//            conf.sss.host,
//            conf.sss.port);
//
//      }catch(Exception error){
//
//        restObj.response =
//          Response.status(500).entity(
//            getJSONStrForError(
//              SSErrE.sssConnectionFailed)).build();
//
//        return restObj.response;
//      }
//
//      try{
//        ret                        = new SSSystemVersionGetRet         (SSRestMainV2.conf.sss.version);
//        restObj.sssResponseMessage = restObj.sssCon.prepRetFullToClient(ret, ret.op);
//      }catch(Exception error){
//
//        restObj.response =
//          Response.status(500).entity(
//            getJSONStrForError(
//              SSErrE.sssReadFailed)).build();
//
//        return restObj.response;
//      }
//
//      try{
//
//        sssJSONResponseRootNode = sssJSONResponseMapper.readTree(restObj.sssResponseMessage);
//
//        restObj.response =
//          Response.status(200).entity(
//            SSJSONU.jsonStr(sssJSONResponseRootNode.get(restObj.par.op.toString()))).build();
//
//      }catch(Exception error){
//
//        restObj.response =
//          Response.status(500).entity(
//            getJSONStrForError(
//              SSErrE.sssResponseParsingFailed)).build();
//      }
//
//      return restObj.response;
//
//    }catch(Exception error){
//
//      restObj.response =
//        Response.status(500).entity(
//          getJSONStrForError(
//            SSErrE.restAdapterInternalError)).build();
//
//      return restObj.response;
//
//    }finally{
//
//      try{
//        if(restObj.sssCon != null){
//          restObj.sssCon.closeCon();
//        }
//      }catch(Exception error){
//        SSLogU.warn("socket connection not closed correctly");
//      }
//    }
//  }
}


text:
package com.miguelangelboti.books.mobile.main.presenter;

import com.miguelangelboti.books.mobile.base.presenter.Presenter;
import com.miguelangelboti.books.mobile.main.view.BookDetailView;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Interface definition for a books search presenter.
 * @author Miguel Ángel Botija.
 */
public interface BookDetailPresenter extends Presenter {

    void setView(@Nonnull BookDetailView view);

    void setBookId(@Nullable String bookId);

    void onFavoriteButtonClick(@Nonnull String bookId, boolean isChecked);
}


text:
import { SpriteSheet } from '../spritesheet'
import { Logger } from '../logger'

export class Entity {
    public id: number;
    public x: number;
    public y: number;
    public isVisible: boolean = true;
    public imageName: string = "";
    public textureIDX: number;

    private _SpriteSheet: SpriteSheet = SpriteSheet.getInstance();

    constructor(paramx: number, paramy: number, img: string, textID: number) {
        this.x = paramx;
        this.y = paramy;
        this.imageName = img;
        this.textureIDX = textID;

    }

    public Update(delta: number): void {

    }

    public Draw(delta: number, ctx: CanvasRenderingContext2D): void {
        if (!this.isVisible || this.imageName === "")
            return;

        try{
                ctx.save();
                ctx.translate(this.x, this.y);
                this._SpriteSheet.Draw(0,0,this.textureIDX,this.imageName,ctx);
                ctx.restore();
        }
        catch(e) {
            Logger.getInstance().error("Error drawing [" + this.imageName +"] :" + e.message , this.imageName);
        }
    }
}


text:
package routers

import (
	"github.com/mengxiangjian13/myapp/controllers"
	"github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})
}


text:
layout: post
title: Job posts in Assam Gramin Vikas Bank last date 25th June-2015
date: 2015-06-16 19:44
comments: true
tags: agriculture assam bank CA ICWA Finance engineer gramin IT law north-east office-assistant officer online
archive: true
---

Assam Gramin Vikash Bank invites applications from Indian citizens, for the post of Officer in Middle Management  Grade  (Scale  II),  Officer  in  Junior  Management  (Scale  I)  Cadre  and  Office  Assistant  (Multipurpose)  from  Indian citizens  who  have been  declared  qualified at  the  Online  CWE  for  RRBs  conducted  by  IBPS during September/ October 2014.  :
{:align="justify"}

- Officer Scale-II (IT) : 02 posts, Pay Scale : Rs. 19400 - 28100
- Officer Scale-II (CA) : 03 posts, Pay Scale : Rs. 19400 - 28100
- Officer Scale-II (Law) : 01 post, Pay Scale : Rs. 19400 - 28100
- Officer Scale-II (Treasury Manager) : 01 post, Pay Scale : Rs. 19400 - 28100
- Officer Scale-II (Agriculture Officer) : 02 posts, Pay Scale : Rs. 19400 - 28100
- Officer JMG Scale-I : 46 posts, Pay Scale : Rs. 14500 - 25700
- Office-Assistant (Multipurpose) : 45 posts, Pay Scale : Rs. 7200 - 19300

**How to Apply** : Apply Online at Assam Gramin Vikas Bank Website from 11/06/2015 to 25/06/2015.

Please visit <http://www.agvbank.co.in/recruitment.php> for detailed information and apply online.


text:
var helpText =
  "Render a Vega specification to PNG.\n\n" +
  "Usage:\n" +
  "  vg2png vega_json_file [output_png_file]\n" +
  "  If output_png_file is not provided, writes to stdout.\n\n" +
  "To load data, you may need to set a base directory:\n" +
  "  For web retrieval, use `-b http://host/data/`. \n" +
  "  For files, use `-b file:///dir/data/` (absolute) or `-b data/` (relative).";

// import required libraries
var path = require("path");
var fs = require("fs");
var vg = require("../index");

// arguments
var args = require("optimist")
  .usage(helpText)
  .demand(1)
  .string('b').alias('b', 'base')
  .describe('b', 'Base directory for data loading.')
  .argv;

// set baseURL if provided on command line
var base = "file://" + process.cwd() + path.sep;
if (args.b) {
  // if no protocol, assume files, relative to current dir
  base = /^[A-Za-z]+\:\/\//.test(args.b) ? args.b + path.sep
    : "file://" + process.cwd() + path.sep + args.b + path.sep;
}
vg.config.baseURL = base;

// input / output files
var specFile = args._[0],
    outputFile = args._[1] || null;

// load spec, render to png
fs.readFile(specFile, "utf8", function(err, text) {
  if (err) throw err;
  var spec = JSON.parse(text);
  convert(spec);
});

// ---

function writePNG(canvas, file) {
  var out = file ? fs.createWriteStream(file) : process.stdout;
  var stream = canvas.createPNGStream();
  stream.on("data", function(chunk) { out.write(chunk); });
}

function convert(spec) {
  vg.headless.convert(spec, "canvas", function(err, data) {
    if (err) throw err;
    writePNG(data.canvas, outputFile);
  });
}


text:
../bin/optimise_rotations_tex_m \
    -num_threads 1 \
    -use_local_parameterization \
    -input preload_mat_all.txt \
    -gps gps_mat_all.txt \
    -robustify \
    -display \
    -num_lines 5000


text:
#ifndef _MGL_BENCHWAVEFRONT_MGL_
#define _MGL_BENCHWAVEFRONT_MGL_

#include <chrono>
#include <iostream>
#include <min/wavefront.h>

double bench_wavefront()
{
    // Running wavefront test
    std::cout << std::endl
              << "wavefront: Opening a very large model: blender_suzanne.obj" << std::endl;

    // Start the time clock
    const auto start = std::chrono::high_resolution_clock::now();

    // load blender-suzanne model
    min::wavefront<float, uint32_t> wave("data/models/blender_suzanne.obj");
    min::mesh<float, uint32_t> &suzanne = wave.get_meshes()[0];
    suzanne.scale_uv(10.0);
    suzanne.calculate_tangents();

    // Calculate the difference between start and end
    const auto dtime = std::chrono::high_resolution_clock::now() - start;

    // Print the execution time
    const double out = std::chrono::duration<double, std::milli>(dtime).count();
    std::cout << "wavefront: OBJ mesh loaded in: " << out << " ms" << std::endl;

    // Calculate cost of calculation (milliseconds)
    return out;
}
#endif


text:
/* snakeUi - Snake Format user interface controls that are shared
 * between more than one CGI. */

/* Copyright (C) 2014 The Regents of the University of California
 * See README in this or parent directory for licensing information. */

#include "common.h"
#include "cheapcgi.h"
#include "errCatch.h"
#include "hCommon.h"
#include "hui.h"
#include "jsHelper.h"
#include "snakeUi.h"

static void showSnpWidthCfg(struct cart *cart, struct trackDb *tdb,
				char *name, boolean parentLevel)
{
unsigned showSnpWidth = cartOrTdbInt(cart, tdb,
    SNAKE_SHOW_SNP_WIDTH, SNAKE_DEFAULT_SHOW_SNP_WIDTH);

printf("Maximum window size in which to show mismatches: \n");

char varName[1024];
safef(varName, sizeof(varName), "%s." SNAKE_SHOW_SNP_WIDTH, name);
cgiMakeIntVar(varName, showSnpWidth, 10);
puts("
");
}

static char *colorByOptionLabels[] =
    {
    SNAKE_COLOR_BY_STRAND_LABEL,
    SNAKE_COLOR_BY_CHROM_LABEL,
    SNAKE_COLOR_BY_NONE_LABEL,
    };

static char *colorByOptionValues[] =
    {
    SNAKE_COLOR_BY_STRAND_VALUE,
    SNAKE_COLOR_BY_CHROM_VALUE,
    SNAKE_COLOR_BY_NONE_VALUE,
    };

static void colorByCfg(struct cart *cart, struct trackDb *tdb,
				char *name, boolean parentLevel)
{
char *colorBy = cartOrTdbString(cart, tdb,
    SNAKE_COLOR_BY, SNAKE_DEFAULT_COLOR_BY);

printf("Block coloring method:\n");

char varName[1024];
safef(varName, sizeof(varName), "%s." SNAKE_COLOR_BY, name);
cgiMakeDropListFull(varName, colorByOptionLabels,
			colorByOptionValues,
			ArraySize(colorByOptionLabels),
			colorBy, NULL, NULL);
puts("
");
}

void snakeCfgUi(struct cart *cart, struct trackDb *tdb, char *name, char *title, boolean boxed)
{
boolean parentLevel = isNameAtParentLevel(tdb, name);

showSnpWidthCfg(cart, tdb, name, parentLevel);
colorByCfg(cart, tdb, name, parentLevel);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Digital Clock Examples</string>
    <string name="app_name_fullscreen">Digital Clock Fullscreen</string>
</resources>


text:
#ifndef __PL2301_H__
#define __PL2301_H__

#include <sys/types.h>
#include <unistd.h>
#include <libusb-1.0/libusb.h>

#define PROLIFIC_VENDOR_ID          0x067b
#define PL2301_DEVICE_ID            0x0000
#define PL2302_DEVICE_ID            0x0001
#define BELKIN_VENDOR_ID            0x050d
#define BELKIN_VISTA_DEVICE_ID      0x258a

#define PEER_E    0x01 /* bit0 - Peer Exists */
#define TX_REQ    0x02 /* bit1 - Transfer Request */
#define TX_C      0x04 /* bit2 - Transfer Complete */
#define RESET_I   0x08 /* bit3 - Reset Input Pipe */
#define RESET_O   0x10 /* bit4 - Reset Ouput Pipe */
#define TX_RDY    0x20 /* bit5 - Transmit Request Acknowledge */
#define RESERVED  0x40 /* bit6 - Transmit Complete Acknowledge */
#define S_EN      0x80 /* bit7 - Suspend Enable */

/* clear a feature in quicklink features */
#define CLEAR_QLF(hnd, feature) while(libusb_control_transfer(hnd, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_CLEAR_FEATURE, feature, 0, 0, 0, 10000) < 0);

/* set a feature in quicklink features */
#define SET_QLF(hnd, feature) while(libusb_control_transfer(hnd, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_SET_FEATURE, feature, 0, 0, 0, 10000) < 0);

/* check status of a feature in quicklink features */
unsigned char CHECK_QLF(libusb_device_handle *hnd, int feature);

#endif


text:
/**
 * DocuSign REST API
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2.1
 * Contact: devcenter@docusign.com
 *
 * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead.
 *
 */

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['ApiClient'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('../ApiClient'));
  } else {
    // Browser globals (root is window)
    if (!root.Docusign) {
      root.Docusign = {};
    }
    root.Docusign.ProofServiceViewLink = factory(root.Docusign.ApiClient);
  }
}(this, function(ApiClient) {
  'use strict';

  /**
   * The ProofServiceViewLink model module.
   * @module model/ProofServiceViewLink
   */

  /**
   * Constructs a new ProofServiceViewLink.
   * @alias module:model/ProofServiceViewLink
   * @class
   */
  var exports = function() {
    var _this = this;

  };

  /**
   * Constructs a ProofServiceViewLink from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/ProofServiceViewLink} obj Optional instance to populate.
   * @return {module:model/ProofServiceViewLink} The populated ProofServiceViewLink instance.
   */
  exports.constructFromObject = function(data, obj) {
    if (data) {
      obj = obj || new exports();

      if (data.hasOwnProperty('ViewLink')) {
        obj['ViewLink'] = ApiClient.convertToType(data['ViewLink'], 'String');
      }
    }
    return obj;
  }

  /**
   *
   * @member {String} ViewLink
   */
  exports.prototype['ViewLink'] = undefined;

  return exports;
}));


text:
<?php

require_once __DIR__.'/../Base.php';

use Kanboard\Formatter\TaskFilterGanttFormatter;
use Kanboard\Model\Project;
use Kanboard\Model\TaskCreation;
use Kanboard\Core\DateParser;

class TaskFilterGanttFormatterTest extends Base
{
    public function testFormat()
    {
        $dp = new DateParser($this->container);
        $p = new Project($this->container);
        $tc = new TaskCreation($this->container);
        $tf = new TaskFilterGanttFormatter($this->container);

        $this->assertEquals(1, $p->create(array('name' => 'test')));
        $this->assertNotFalse($tc->create(array('project_id' => 1, 'title' => 'task1')));

        $this->assertNotEmpty($tf->search('status:open')->format());
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Roslyn.VisualStudio.Test.Utilities.Input
{
    [Flags]
    public enum ShiftState : byte
    {
        Shift = 1,
        Ctrl = 1 << 1,
        Alt = 1 << 2,
        Hankaku = 1 << 3,
        Reserved1 = 1 << 4,
        Reserved2 = 1 << 5
    }
}


text:
package com.manniwood.mmpt.test.beans;

public class BooleanArrayBean {

    private Boolean[] booleanArray;
    private String name;

    public BooleanArrayBean() {
        // null constructor keeps mybatis happy
    }

    public Boolean[] getBooleanArray() {
        return booleanArray;
    }

    public void setBooleanArray(Boolean[] booleanArray) {
        this.booleanArray = booleanArray;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
@implementation ZBJournal

-init
{
    @autoreleasepool
    {
        self = [super init];
        return self;
    }
}

-(NSMutableDictionary *)toJSON
{
    NSMutableDictionary *journalJSON = [[NSMutableDictionary alloc] init];
    if(_date)
    {
        [journalJSON setValue:_date forKey:@"journal_date"];
    }
    if(_referenceNumber)
    {
        [journalJSON setValue:_referenceNumber forKey:@"reference_number"];
    }
    if(_notes)
    {
        [journalJSON setValue:_notes forKey:@"notes"];
    }
    if(_lineItems != nil && [_lineItems count] > 0)
    {
        NSMutableArray *lineItemArray = [[NSMutableArray alloc] init];
        for(ZBItem *item in _lineItems)
        {
            [lineItemArray addObject:[item toJournalJSON]];
        }
        [journalJSON setValue:lineItemArray forKey:@"line_items"];
    }

    return journalJSON;
}

@end


text:
<?php

namespace Orm;

class Observer_UpdatedAt extends Observer
{
	/**
	 * @var  bool  set true to use mySQL timestamp instead of UNIX timestamp
	 */
	public static $mysql_timestamp = false;

	/**
	 * @var  string  property to set the timestamp on
	 */
	public static $property = 'updated_at';

	protected $_mysql_timestamp;
	protected $_property;

	public function __construct($class)
	{
		$props = $class::observers(get_class($this));
		$this->_mysql_timestamp  = isset($props['mysql_timestamp']) ? $props['mysql_timestamp'] : static::$mysql_timestamp;
		$this->_property         = isset($props['property']) ? $props['property'] : static::$property;
	}

	public function before_save(Model $obj)
	{
		if ($obj->is_new() or $obj->is_changed())
		{
			$obj->{$this->_property} = $this->_mysql_timestamp ? \Date::time()->format('mysql') : \Date::time()->get_timestamp();
		}
	}
}


text:
This test verifies that the correct sequence of keyboard events is generated for a keypress for certain special keys. To test manually, press keys and compare results to other browsers.

<input type="text"></input>


text:
package org.apache.camel.component.salesforce;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.salesforce.api.dto.PlatformEvent;
import org.assertj.core.api.Assertions;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.entry;

@Tag("standalone")
public class PlatformEventsConsumerIntegrationTest extends AbstractSalesforceTestBase {

    @Test
    public void shouldConsumePlatformEvents() throws InterruptedException, ExecutionException {
        final ExecutorService parallel = Executors.newSingleThreadExecutor();

        final Future<PlatformEvent> futurePlatformEvent
                = parallel.submit(
                        () -> consumer.receiveBody("salesforce:subscribe:event/TestEvent__e?replayId=-1", PlatformEvent.class));

        // it takes some time for the subscriber to subscribe, so we'll try to
        // send repeated platform events and wait until the first one is
        // received
        Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
            template.sendBody("direct:sendPlatformEvent", "{\"Test_Field__c\": \"data\"}");

            Assertions.assertThat(futurePlatformEvent.isDone()).isTrue();
        });

        final PlatformEvent platformEvent = futurePlatformEvent.get();
        Assertions.assertThat(platformEvent).isNotNull();
        Assertions.assertThat(platformEvent.getEventData()).containsOnly(entry("Test_Field__c", "data"));
    }

    @Override
    protected RouteBuilder doCreateRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:sendPlatformEvent").to("salesforce:createSObject?sObjectName=TestEvent__e");
            }
        };
    }
}


text:
<?php

namespace Palicao\Bundle\RsvpBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PalicaoRsvpBundle extends Bundle
{
}