text:
package com.mesosphere.sdk.offer.evaluate.placement;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.mesosphere.sdk.specification.PodInstance;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.mesos.Protos.Offer;
import org.apache.mesos.Protos.TaskInfo;
import com.mesosphere.sdk.offer.evaluate.EvaluationOutcome;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * This rule ensures that the given Offer is colocated with (or never colocated with) the specified
 * task 'type', whose retrieval from the TaskInfo is defined by the developer's implementation of a
 * {@link TaskTypeConverter}.
 *
 * For example, this can be used to colocate 'data' nodes with 'index' nodes, or to ensure that the
 * two are never colocated.
 */
public class TaskTypeRule implements PlacementRule {

    /**
     * Returns a {@link PlacementRule} which enforces avoidance of tasks which have the provided
     * type. For example, this could be used to ensure that 'data' nodes are never colocated with
     * 'index' nodes, or that 'data' nodes are never colocated with other 'data' nodes
     * (self-avoidance). Note that this rule is unidirectional; mutual avoidance requires
     * creating separate colocate rules for each direction.
     *
     * Note that if the avoided task does not already exist in the cluster, this will just pick a
     * random node, as there will be nothing to avoid.
     */
    public static PlacementRule avoid(String typeToAvoid, TaskTypeConverter typeConverter) {
        return new TaskTypeRule(typeToAvoid, typeConverter, BehaviorType.AVOID);
    }

    /**
     * Calls {@link #avoid(String, TaskTypeConverter) with a {@link TaskTypeLabelConverter}.
     */
    public static PlacementRule avoid(String typeToAvoid) {
        return avoid(typeToAvoid, null);
    }

    /**
     * Returns a {@link PlacementRule} which enforces colocation with tasks which have the provided
     * type. For example, this could be used to ensure that 'data' nodes are always colocated with
     * 'index' nodes. Note that this rule is unidirectional; mutual colocation requires
     * creating separate colocate rules for each direction.
     *
     * Note that if the colocated task does not already exist in the cluster, this will just pick a
     * random node. This behavior is to support defining mutual colocation: A colocates with B, and
     * B colocates with A. In this case one of the two directions won't see anything to colocate
     * with.
     */
    public static PlacementRule colocateWith(String typeToColocateWith, TaskTypeConverter typeConverter) {
        return new TaskTypeRule(typeToColocateWith, typeConverter, BehaviorType.COLOCATE);
    }

    /**
     * Calls {@link #colocateWith(String, TaskTypeConverter) with a {@link TaskTypeLabelConverter}.
     */
    public static PlacementRule colocateWith(String typeToColocateWith) {
        return colocateWith(typeToColocateWith, null);
    }

    /**
     * The behavior to be used.
     */
    private enum BehaviorType {
        COLOCATE,
        AVOID
    }

    private final String typeToFind;
    private final TaskTypeConverter typeConverter;
    private final BehaviorType behaviorType;

    @JsonCreator
    private TaskTypeRule(
            @JsonProperty("type") String typeToFind,
            @JsonProperty("converter") TaskTypeConverter typeConverter,
            @JsonProperty("behavior") BehaviorType behaviorType) {
        this.typeToFind = typeToFind;
        if (typeConverter == null) { // null when unspecified in serialized data
            typeConverter = new TaskTypeLabelConverter();
        }
        this.typeConverter = typeConverter;
        this.behaviorType = behaviorType;
    }

    @Override
    public EvaluationOutcome filter(Offer offer, PodInstance podInstance, Collection<TaskInfo> tasks) {
        List<TaskInfo> matchingTasks = new ArrayList<>();
        for (TaskInfo task : tasks) {
            if (typeToFind.equals(typeConverter.getTaskType(task))) {
                matchingTasks.add(task);
            }
        }
        // Create a rule which will handle most of the validation. Logic is deferred to avoid
        // double-counting a task against a prior version of itself.
        switch (behaviorType) {
        case AVOID:
            if (matchingTasks.isEmpty()) {
                // nothing to avoid, but this is expected when avoiding nodes of the same type
                // (self-avoidance), or when the developer has configured bidirectional rules
                // (A avoids B + B avoids A)
                return EvaluationOutcome.pass(
                        this,
                        "No tasks of avoided type '%s' are currently running.",
                        typeToFind)
                        .build();
            } else {
                return filterAvoid(offer, podInstance, matchingTasks);
            }
        case COLOCATE:
            if (matchingTasks.isEmpty()) {
                // nothing to colocate with! fall back to allowing any location.
                // this is expected when the developer has configured bidirectional rules
                // (A colocates with B + B colocates with A)
                return EvaluationOutcome.pass(
                        this,
                        "No tasks of colocated type '%s' are currently running.",
                        typeToFind)
                        .build();
            } else {
                return filterColocate(offer, podInstance, matchingTasks);
            }
        default:
            throw new IllegalStateException("Unsupported behavior type: " + behaviorType);
        }
    }

    @Override
    public Collection<PlacementField> getPlacementFields() {
        // TaskTypeRules are not generated by the Marathon constraint language
        return Collections.emptyList();
    }

    /**
     * Implementation of task type avoidance. Considers the presence of tasks in the cluster to
     * determine whether the provided task can be launched against a given offer. This rule requires
     * that the offer be located on an agent which doesn't currently have an instance of the
     * specified task type.
     */
    private EvaluationOutcome filterAvoid(
            Offer offer,
            PodInstance podInstance,
            Collection<TaskInfo> tasksToAvoid) {

        for (TaskInfo taskToAvoid : tasksToAvoid) {
            if (PlacementUtils.areEquivalent(taskToAvoid, podInstance)) {
                // This is stale data for the same task that we're currently evaluating for
                // placement. Don't worry about avoiding it. This occurs when we're redeploying
                // a given task with a new configuration (old data not deleted yet).
                continue;
            }
            if (taskToAvoid.getSlaveId().equals(offer.getSlaveId())) {
                // The offer is for an agent which has a task to be avoided. Denied!
                return EvaluationOutcome.fail(
                        this,
                        "Found a task matching avoided type '%s' on this agent.", typeToFind)
                        .build();
            }
        }
        // The offer doesn't match any tasks to avoid. Approved!
        return EvaluationOutcome.pass(this, "No tasks of avoided type '%s' found on this agent.", typeToFind).build();
    }

    /**
     * Implementation of task type colocation. Considers the presence of tasks in the cluster to
     * determine whether the provided task can be launched against a given offer. This rule requires
     * that the offer be located on an agent which currently has an instance of the specified task
     * type.
     */
    private EvaluationOutcome filterColocate(
            Offer offer,
            PodInstance podInstance,
            Collection<TaskInfo> tasksToColocate) {

        for (TaskInfo taskToColocate : tasksToColocate) {
            if (PlacementUtils.areEquivalent(taskToColocate, podInstance)) {
                // This is stale data for the same task that we're currently evaluating for
                // placement. Don't worry about colocating with it. This occurs when we're
                // redeploying a given task with a new configuration (old data not deleted yet).
                continue;
            }
            if (taskToColocate.getSlaveId().equals(offer.getSlaveId())) {
                // The offer is for an agent which has a task to colocate with. Approved!
                return EvaluationOutcome.pass(
                        this,
                        "Found a task matching colocated type '%s' on this agent.",
                        typeToFind)
                        .build();
            }
        }
        // The offer doesn't match any tasks to colocate with. Denied!
        return EvaluationOutcome.fail(
                this,
                "Didn't find a task matching colocated type '%s' on this agent.", typeToFind)
                .build();
    }

    @JsonProperty("type")
    private String getType() {
        return typeToFind;
    }

    @JsonProperty("converter")
    private TaskTypeConverter getTypeConverter() {
        return typeConverter;
    }

    @JsonProperty("behavior")
    private BehaviorType getBehavior() {
        return behaviorType;
    }

    @Override
    public String toString() {
        return String.format("TaskTypeRule{type=%s, converter=%s, behavior=%s}",
            typeToFind, typeConverter, behaviorType);
    }

    @Override
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}


text:
MISTIFY_IFSTATE=/tmp/.ifstate
MISTIFY_CONFIG=/tmp/mistify-config
MISTIFY_MAC=/etc/sysconfig/ovsbridge
PROC_CMDLINE=/proc/cmdline
ETHER_DEVS=(`ls /sys/class/net | egrep -v '^lo$'`)

MISTIFY_KOPT_IP=""
MISTIFY_KOPT_GW=""
MISTIFY_KOPT_IFACE=""

# Parse the kernel boot arguments and look for any mistify.* arguments and
# pick out their values.
function parse_boot_args() {
    local cmdline=$(cat $PROC_CMDLINE)
    grep -q 'mistify.debug/test/not-for-prod' <<<$cmdline || return

    for kopt in $cmdline; do
        k=`echo $kopt | awk -F= '{print $1}'`
        v=`echo $kopt | awk -F= '{print $2}'`
        case $k in
            'mistify.debug/test/not-for-prod.ip')
                MISTIFY_KOPT_IP="$v"
                ;;
            'mistify.debug/test/not-for-prod.gw')
                MISTIFY_KOPT_GW="$v"
                ;;
            'mistify.debug/test/not-for-prod.iface')
                MISTIFY_KOPT_IFACE="$v"
                ;;
        esac
    done
}

# Act on any IP address being passed to us via kernel boot arguments.
# By default, configure the first enummerated interface on the system with it.
function configure_net_manual() {
    if [ -n "$MISTIFY_KOPT_IFACE" ]; then
        local iface="$MISTIFY_KOPT_IFACE"
    else
        local iface="${ETHER_DEVS[0]}"
    fi

    echo "Manually configuring $iface with $MISTIFY_KOPT_IP..."
    /sbin/ip link set $iface up
    /sbin/ip addr add $MISTIFY_KOPT_IP dev $iface
    echo "IFTYPE=MANUAL" >> $MISTIFY_IFSTATE
    echo "IFACE=$iface" >> $MISTIFY_IFSTATE
    echo "IP=$MISTIFY_KOPT_IP" >> $MISTIFY_IFSTATE

    if [ -n "$MISTIFY_KOPT_GW" ]; then
        echo "Manually adding $MISTIFY_KOPT_GW as default route"
        /sbin/ip route add default via $MISTIFY_KOPT_GW
        echo "GW=$MISTIFY_KOPT_GW" >> $MISTIFY_IFSTATE
    fi

    save_mac_for_bridge $iface
}

# Cycle through all known ethernet interfaces until we find one which
# responds to DHCP requests.
function configure_net_dhcp() {
    set -x
    echo "Probing for DHCP"
    /sbin/dhclient -v -e MISTIFY_IFSTATE=$MISTIFY_IFSTATE -1 ${ETHER_DEVS[*]} &&
        echo "IFTYPE=DHCP" >> $MISTIFY_IFSTATE
}

# Unconfigure and otherwise clean up any interfaces we may have configured
function unconfigure_net_iface() {
    if [ -f $MISTIFY_IFSTATE ]; then
        . $MISTIFY_IFSTATE
    else
        return 1
    fi

    if [ "$IFTYPE" != "DHCP" ]; then
        return
    fi

    echo "Releasing DHCP lease on $IFACE..."
    /sbin/dhclient -v -e MISTIFY_IFSTATE=$MISTIFY_IFSTATE -r ${ETHER_DEVS[*]}
    /sbin/ip addr del $IP dev $IFACE
    /sbin/ip link set $IFACE up

    save_mac_for_bridge $IFACE
}

function save_mac_for_bridge() {
    local mac=$(cat /sys/class/net/$1/address)
    ! grep -sq MACAddress $MISTIFY_MAC &&
        echo "MACAddress=$mac" >> $MISTIFY_MAC &&
        echo "Saving MAC address for bridge $mac"
}

function get_mistify_config() {
    if [ -f $MISTIFY_IFSTATE ]; then
        . $MISTIFY_IFSTATE
    else
        return 1
    fi

    if [[ -z $DNS ]]; then
        # not configured via dhcp
        return 1
    fi

    local resp=''
    for dns in ${DNS[*]}; do
        srv=$(dig +noall +answer +additional SRV ipxe.services.lochness.local @$dns) || continue
        resp="$srv"
        break
    done

    if [[ -z $resp ]]; then
        echo "could not resolv ipxe service"
        return 1
    fi

    local addr=$(echo $resp | awk '/\sA\s/ {print $NF}')
    local port=$(echo $resp | awk '/\sSRV\s/ {print $7}')
    local ip=${IP%%/*}
    curl http://$addr:$port/config/$ip > $MISTIFY_CONFIG

    if [ $? -ne 0 ]; then
        echo "FATAL: Could not get Mistify configuration for $ip!"
        return 1
    fi
}

## Network initialization main. Under 'start' we either manually configure a IP address
## on the first interface if we are given one in the kernel boot arguments.
## Otherwise we probe each interface for a DHCP response until we fine one that does.
case "$1" in
    'start')
        # Initialize our own interface state file
        cp /dev/null $MISTIFY_IFSTATE

        parse_boot_args

        if [ -n "$MISTIFY_KOPT_IP" ]; then
            configure_net_manual
        else
            configure_net_dhcp
            get_mistify_config
        fi
        ;;
    'stop')
        unconfigure_net_iface
        ;;
    *)
        echo "Usage: $0 {start|stop}"
        ;;
esac

# vim:set ts=4 sw=4 et:

redpajama_set_name: RedPajamaGithub


text:
createusers() (
    local adminusername=${INFLUXDB_ADMINUSERNAME:-admin}
    local adminpassword=${INFLUXDB_ADMINPASSWORD:-admin}
    local username=${INFLUXDB_USERNAME:-influx}
    local password=${INFLUXDB_PASSWORD:-influx}
    local database=${INFLUXDB_DEFAULT_DATABASE:-influx}

    local port=$(echo "$INFLUXDB_HTTP_BIND_ADDRESS" | grep -Eo '[0-9]+')

    sleep 1

    echo "Setting influxdb admin user"
    influx --port "$port" -execute "CREATE USER $adminusername WITH PASSWORD '$adminpassword' WITH ALL PRIVILEGES"

    echo "Creating default influxdb database"
    influx --port "$port" -username "$adminusername" -password "$adminpassword" -execute "CREATE DATABASE $database"

    echo "Creating default influxdb user"
    influx --port "$port" -username "$adminusername" -password "$adminpassword" -execute "CREATE USER $username WITH PASSWORD '$password'"
    influx --port "$port" -username "$adminusername" -password "$adminpassword" -execute "GRANT ALL on $database to $username"

)

# create users in background
echo "Kicking off user creation"
createusers &

# to connect:
# influx -username "$INFLUXDB_ADMINUSERNAME" -password "$INFLUXDB_ADMINPASSWORD"

echo "Starting influxdb"
influxd


text:
/*
* This file is automatically created from tigl.h on 2014-10-21.
* If you experience any bugs please contact the authors
*/

package de.dlr.sc.tigl;

import java.util.ArrayList;

public enum TiglLogLevel {
    TILOG_SILENT(0),
    TILOG_ERROR(1),
    TILOG_WARNING(2),
    TILOG_INFO(3),
    TILOG_DEBUG(4),
    TILOG_DEBUG1(5),
    TILOG_DEBUG2(6),
    TILOG_DEBUG3(7),
    TILOG_DEBUG4(8);

    private static ArrayList<TiglLogLevel> codes = new ArrayList<>();

    static {
        codes.add(TILOG_SILENT);
        codes.add(TILOG_ERROR);
        codes.add(TILOG_WARNING);
        codes.add(TILOG_INFO);
        codes.add(TILOG_DEBUG);
        codes.add(TILOG_DEBUG1);
        codes.add(TILOG_DEBUG2);
        codes.add(TILOG_DEBUG3);
        codes.add(TILOG_DEBUG4);
    }

    private final int code;

    private TiglLogLevel(final int value) {
         code = value;
    }

    public static TiglLogLevel getEnum(final int value) {
        return codes.get(Integer.valueOf(value));
    }

    public int getValue() {
        return code;
    }
};


text:
<!doctype html>

    <meta name="viewport" content="width=device-width" />
    <title>bespoke-camera demo</title>
    <link rel="stylesheet" type="text/css" href="style.css" />

bespoke-camera

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE114_Process_Control__w32_wchar_t_file_03.c
Label Definition File: CWE114_Process_Control__w32.label.xml
Template File: sources-sink-03.tmpl.c
*/
/*
 * @description
 * CWE: 114 Process Control
 * BadSource: file Read input from a file
 * GoodSource: Hard code the full pathname to the library
 * Sink:
 *    BadSink : Load a dynamic link library
 * Flow Variant: 03 Control flow: if(5==5) and if(5!=5)
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif

#include <windows.h>

#ifndef OMITBAD

void CWE114_Process_Control__w32_wchar_t_file_03_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(5==5)
    {
        {
            /* Read input from a file */
            size_t dataLen = wcslen(data);
            FILE * pFile;
            /* if there is room in data, attempt to read the input from a file */
            if (100-dataLen > 1)
            {
                pFile = fopen(FILENAME, "r");
                if (pFile != NULL)
                {
                    /* POTENTIAL FLAW: Read data from a file */
                    if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                    {
                        printLine("fgetws() failed");
                        /* Restore NUL terminator if fgetws fails */
                        data[dataLen] = L'\0';
                    }
                    fclose(pFile);
                }
            }
        }
    }
    {
        HMODULE hModule;
        /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to
         * replace his own file with the intended library */
        hModule = LoadLibraryW(data);
        if (hModule != NULL)
        {
            FreeLibrary(hModule);
            printLine("Library loaded and freed successfully");
        }
        else
        {
            printLine("Unable to load library");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B1() - use goodsource and badsink by changing the 5==5 to 5!=5 */
static void goodG2B1()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(5!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Specify the full pathname for the library */
        wcscpy(data, L"C:\\Windows\\System32\\winsrv.dll");
    }
    {
        HMODULE hModule;
        /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to
         * replace his own file with the intended library */
        hModule = LoadLibraryW(data);
        if (hModule != NULL)
        {
            FreeLibrary(hModule);
            printLine("Library loaded and freed successfully");
        }
        else
        {
            printLine("Unable to load library");
        }
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(5==5)
    {
        /* FIX: Specify the full pathname for the library */
        wcscpy(data, L"C:\\Windows\\System32\\winsrv.dll");
    }
    {
        HMODULE hModule;
        /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to
         * replace his own file with the intended library */
        hModule = LoadLibraryW(data);
        if (hModule != NULL)
        {
            FreeLibrary(hModule);
            printLine("Library loaded and freed successfully");
        }
        else
        {
            printLine("Unable to load library");
        }
    }
}

void CWE114_Process_Control__w32_wchar_t_file_03_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE114_Process_Control__w32_wchar_t_file_03_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE114_Process_Control__w32_wchar_t_file_03_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
from scipy import *
from scipy.io import read_array
from pylab import *

def main():

    # First example, read first and second column from ascii file. Skip first
    # line of header.
    # Note use of (1,-1) in lines to skip first line and then read to end of file
    # Note use of (0,) in columns to pick first column, since its a tuple need trailing comma
    x=read_array("test.txt",lines=(1,-1), columns=(0,))
    y=read_array("test.txt",lines=(1,-1), columns=(1,))

    #Second example, read the file into a single arry
    z=read_array("test.txt",lines=(1,-1), columns=(0,2))

    # Plot the data
    plot(x,y,'r--',z[:,0],z[:,1])
    show()

# The one and only main function
if __name__ == "__main__":
    main()


text:
package org.apache.ignite.internal.processors.query.calcite;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.query.QueryEngine;
import org.apache.ignite.internal.processors.query.calcite.util.Commons;
import org.apache.ignite.testframework.junits.WithSystemProperty;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static java.util.Collections.singletonList;

/** */
@WithSystemProperty(key = "calcite.debug", value = "true")
public class DateTimeTest extends GridCommonAbstractTest {
    /** */
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    /** */
    private static QueryEngine queryEngine;

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        Ignite grid = startGridsMultiThreaded(1);

        QueryEntity qryEnt = new QueryEntity();
        qryEnt.setKeyFieldName("ID");
        qryEnt.setKeyType(Integer.class.getName());
        qryEnt.setValueType(DateTimeEntry.class.getName());

        qryEnt.addQueryField("ID", Integer.class.getName(), null);
        qryEnt.addQueryField("JAVADATE", Date.class.getName(), null);
        qryEnt.addQueryField("SQLDATE", java.sql.Date.class.getName(), null);
        qryEnt.addQueryField("SQLTIME", Time.class.getName(), null);
        qryEnt.addQueryField("SQLTIMESTAMP", Timestamp.class.getName(), null);
        qryEnt.setTableName("datetimetable");

        final CacheConfiguration<Integer, DateTimeEntry> cfg = new CacheConfiguration<>(qryEnt.getTableName());

        cfg.setCacheMode(CacheMode.PARTITIONED)
            .setBackups(1)
            .setQueryEntities(singletonList(qryEnt))
            .setSqlSchema("PUBLIC");

        IgniteCache<Integer, DateTimeEntry> dateTimeCache = grid.createCache(cfg);

        dateTimeCache.put(1, new DateTimeEntry(1, javaDate("2020-10-01 12:00:00.000"),
            sqlDate("2020-10-01"), sqlTime("12:00:00"), sqlTimestamp("2020-10-01 12:00:00.000")));
        dateTimeCache.put(2, new DateTimeEntry(2, javaDate("2020-12-01 00:10:20.000"),
            sqlDate("2020-12-01"), sqlTime("00:10:20"), sqlTimestamp("2020-12-01 00:10:20.000")));
        dateTimeCache.put(3, new DateTimeEntry(3, javaDate("2020-10-20 13:15:00.000"),
            sqlDate("2020-10-20"), sqlTime("13:15:00"), sqlTimestamp("2020-10-20 13:15:00.000")));
        dateTimeCache.put(4, new DateTimeEntry(4, javaDate("2020-01-01 22:40:00.000"),
            sqlDate("2020-01-01"), sqlTime("22:40:00"), sqlTimestamp("2020-01-01 22:40:00.000")));

        queryEngine = Commons.lookupComponent(((IgniteEx)grid).context(), QueryEngine.class);

        awaitPartitionMapExchange();
    }

    /** */
    @Test
    public void testQuery1() throws Exception {
        checkQuery("SELECT SQLDATE FROM datetimetable where SQLTIME = '12:00:00'")
            .returns(sqlDate("2020-10-01"))
            .check();
    }

    /** */
    @Test
    public void testQuery2() throws Exception {
        checkQuery("SELECT SQLDATE FROM datetimetable where JAVADATE = ?")
            .withParams(javaDate("2020-12-01 00:10:20.000"))
            .returns(sqlDate("2020-12-01"))
            .check();
    }

    /** */
    @Test
    public void testQuery3() throws Exception {
        checkQuery("SELECT SQLDATE FROM datetimetable where JAVADATE = ?")
            .withParams(sqlTimestamp("2020-12-01 00:10:20.000"))
            .returns(sqlDate("2020-12-01"))
            .check();
    }

    /** */
    @Test
    public void testQuery4() throws Exception {
        checkQuery("SELECT MAX(SQLDATE) FROM datetimetable")
            .returns(sqlDate("2020-12-01"))
            .check();
    }

    /** */
    @Test
    public void testQuery5() throws Exception {
        checkQuery("SELECT MIN(SQLDATE) FROM datetimetable")
            .returns(sqlDate("2020-01-01"))
            .check();
    }

    /** */
    @Test
    public void testQuery6() throws Exception {
        checkQuery("SELECT JAVADATE FROM datetimetable WHERE SQLTIME = '13:15:00'")
            .returns(javaDate("2020-10-20 13:15:00.000"))
            .check();
    }

    /** */
    @Test
    public void testQuery7() throws Exception {
        checkQuery("SELECT t1.JAVADATE, t2.JAVADATE FROM datetimetable t1 " +
            "INNER JOIN " +
            "(SELECT JAVADATE, CAST(SQLTIMESTAMP AS TIME) AS CASTED_TIME FROM datetimetable) t2 " +
            "ON t1.SQLTIME = t2.CASTED_TIME " +
            "WHERE t2.JAVADATE = '2020-10-20 13:15:00.000'")
            .returns(javaDate("2020-10-20 13:15:00.000"), javaDate("2020-10-20 13:15:00.000"))
            .check();
    }

    /**
     * Test right date/time interpretation taking into account DST clock shift.
     */
    @Test
    public void testDstShift() throws Exception {
        TimeZone oldTz = TimeZone.getDefault();

        try {
            TimeZone.setDefault(TimeZone.getTimeZone("Europe/Moscow"));

            // Time zone change (EET->MSK) 1992-01-19 02:00:00 -> 1992-01-19 03:00:00
            checkQuery("select date '1992-01-19'").returns(sqlDate("1992-01-19")).check();
            checkQuery("select date '1992-01-18' + interval (1) days").returns(sqlDate("1992-01-19")).check();
            checkQuery("select date '1992-01-18' + interval (24) hours").returns(sqlDate("1992-01-19")).check();
            checkQuery("SELECT timestamp '1992-01-18 02:30:00' + interval (25) hours")
                .returns(sqlTimestamp("1992-01-19 03:30:00.000")).check();
            checkQuery("SELECT timestamp '1992-01-18 02:30:00' + interval (23) hours")
                .returns(sqlTimestamp("1992-01-19 01:30:00.000")).check();
            checkQuery("SELECT timestamp '1992-01-18 02:30:00' + interval (24) hours")
                .returns(sqlTimestamp("1992-01-19 02:30:00.000")).check();

            // DST started 1992-03-29 02:00:00 -> 1992-03-29 03:00:00
            checkQuery("select date '1992-03-29'").returns(sqlDate("1992-03-29")).check();
            checkQuery("select date '1992-03-28' + interval (1) days").returns(sqlDate("1992-03-29")).check();
            checkQuery("select date '1992-03-28' + interval (24) hours").returns(sqlDate("1992-03-29")).check();
            checkQuery("SELECT timestamp '1992-03-28 02:30:00' + interval (25) hours")
                .returns(sqlTimestamp("1992-03-29 03:30:00.000")).check();
            checkQuery("SELECT timestamp '1992-03-28 02:30:00' + interval (23) hours")
                .returns(sqlTimestamp("1992-03-29 01:30:00.000")).check();
            checkQuery("SELECT timestamp '1992-03-28 02:30:00' + interval (24) hours")
                .returns(sqlTimestamp("1992-03-29 02:30:00.000")).check();

            // DST ended 1992-09-27 03:00:00 -> 1992-09-27 02:00:00
            checkQuery("select date '1992-09-27'").returns(sqlDate("1992-09-27")).check();
            checkQuery("select date '1992-09-26' + interval (1) days").returns(sqlDate("1992-09-27")).check();
            checkQuery("select date '1992-09-26' + interval (24) hours").returns(sqlDate("1992-09-27")).check();
            checkQuery("SELECT timestamp '1992-09-26 02:30:00' + interval (25) hours")
                .returns(sqlTimestamp("1992-09-27 03:30:00.000")).check();
            checkQuery("SELECT timestamp '1992-09-26 02:30:00' + interval (23) hours")
                .returns(sqlTimestamp("1992-09-27 01:30:00.000")).check();
            checkQuery("SELECT timestamp '1992-09-26 02:30:00' + interval (24) hours")
                .returns(sqlTimestamp("1992-09-27 02:30:00.000")).check();

            TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));

            // DST ended 2021-11-07 02:00:00 -> 2021-11-07 01:00:00
            checkQuery("select date '2021-11-07'").returns(sqlDate("2021-11-07")).check();
            checkQuery("select date '2021-11-06' + interval (1) days").returns(sqlDate("2021-11-07")).check();
            checkQuery("select date '2021-11-06' + interval (24) hours").returns(sqlDate("2021-11-07")).check();
            checkQuery("SELECT timestamp '2021-11-06 01:30:00' + interval (25) hours")
                .returns(sqlTimestamp("2021-11-07 02:30:00.000")).check();
            // Check string representation here, since after timestamp calculation we have '2021-11-07T01:30:00.000-0800'
            // but Timestamp.valueOf method converts '2021-11-07 01:30:00' in 'America/Los_Angeles' time zone to
            // '2021-11-07T01:30:00.000-0700' (we pass through '2021-11-07 01:30:00' twice after DST ended).
            checkQuery("SELECT (timestamp '2021-11-06 02:30:00' + interval (23) hours)::varchar")
                .returns("2021-11-07 01:30:00").check();
            checkQuery("SELECT (timestamp '2021-11-06 01:30:00' + interval (24) hours)::varchar")
                .returns("2021-11-07 01:30:00").check();
        }
        finally {
            TimeZone.setDefault(oldTz);
        }
    }

    /** */
    public static class DateTimeEntry {
        /** */
        long id;

        /** */
        Date javaDate;

        /** */
        java.sql.Date sqlDate;

        /** */
        Time sqlTime;

        /** */
        Timestamp sqlTimestamp;

        /** */
        public DateTimeEntry(long id, Date javaDate, java.sql.Date sqlDate, Time sqlTime, Timestamp sqlTimestamp) {
            this.id = id;
            this.javaDate = javaDate;
            this.sqlDate = sqlDate;
            this.sqlTime = sqlTime;
            this.sqlTimestamp = sqlTimestamp;
        }
    }

    /** */
    private QueryChecker checkQuery(String qry) {
        return new QueryChecker(qry) {
            @Override protected QueryEngine getEngine() {
                return queryEngine;
            }
        };
    }

    /** */
    private Date javaDate(String str) throws Exception {
        return DATE_FORMAT.parse(str);
    }

    /** */
    private java.sql.Date sqlDate(String str) throws Exception {
        return java.sql.Date.valueOf(str);
    }

    /** */
    private Time sqlTime(String str) throws Exception {
        return Time.valueOf(str);
    }

    /** */
    private Timestamp sqlTimestamp(String str) throws Exception {
        return Timestamp.valueOf(str);
    }
}


text:
module.exports = function(sockets, logPath) {
    var watcher = require('../../watcher')(logPath);

    return function (socket) {
        sockets.push(socket);
        socket.emit('send:path', {
            path: logPath
        });
        socket.emit('send:i18n', {
            time: 'Время',
            module: 'Модуль',
            level: 'Уровень',
            message: 'Сообщение'
        });
        watcher.invoke();
    };
};


text:
package org.kuali.rice.krms.api.engine;

import java.util.Map;

/**
 * An Engine executes using the given {@link SelectionCriteria}, @{link Facts}, and {@link ExecutionOptions} returning {@link EngineResults}
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface Engine {

	/**
	 * Initiates execution of the rules engine.
	 *
	 * @param selectionCriteria informs the engine of the {@link SelectionCriteria} to use for selection of contexts and agendas
	 * @param facts the facts that the rule engine can use during execution
	 * @param executionOptions defines various {@link ExecutionOptions} that instruct the rules engine on how to perform it's execution
	 *
	 * @return {@link EngineResults} the results of engine execution
	 */
	EngineResults execute(SelectionCriteria selectionCriteria, Facts facts, ExecutionOptions executionOptions);

    /**
     * Initiates execution of the rules engine.
     *
     * @param selectionCriteria informs the engine of the {@link SelectionCriteria} to use for selection of contexts and agendas
     * @param facts the facts that the rule engine can use during execution.  Since this signature does not pass in
     * {@link Term}s, all terms are defined with only a name, and term parameters can not be specified.
     * @param executionOptions defines various {@link ExecutionOptions} that instruct the rules engine on how to perform it's execution
     *
     * @return the results of engine execution
     */
    EngineResults execute(SelectionCriteria selectionCriteria, Map<String, Object> facts, ExecutionOptions executionOptions);

}


text:
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Serialization;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands.Serialization;
using Unicorn.Data;
using ItemData = Rainbow.Storage.Sc.ItemData;

namespace Unicorn.UI.Commands
{
	public class UnicornLoadItemCommand : LoadItemCommand
	{
		private readonly SerializationHelper _helper;

		public UnicornLoadItemCommand() : this(new SerializationHelper())
		{

		}

		public UnicornLoadItemCommand(SerializationHelper helper)
		{
			_helper = helper;
		}

		protected override Item LoadItem(Item item, LoadOptions options)
		{
			Assert.ArgumentNotNull(item, "item");

			var itemData = new ItemData(item);

			var configuration = _helper.GetConfigurationForItem(itemData);

			if (configuration == null) return base.LoadItem(item, options);

			var sourceStore = configuration.Resolve<ISourceDataStore>();
			var targetStore = configuration.Resolve<ITargetDataStore>();

			var targetItem = targetStore.GetByPathAndId(itemData.Path, itemData.Id, itemData.DatabaseName);

			if (targetItem == null)
			{
				Log.Warn("Unicorn: Unable to load item because it was not serialized.", this);
				return base.LoadItem(item, options);
			}

			sourceStore.Save(targetItem);

			return Database.GetItem(item.Uri);
		}
	}
}


text:
#ifndef   __USBIOCTL_H__
#define   __USBIOCTL_H__

#include "usb100.h"

#ifndef FAR
#define FAR
#endif

DEFINE_GUID( GUID_CLASS_USBHUB, 0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, \
             0xa0, 0xc9, 0x06, 0xbe, 0xd8);

//f18a0e88-c30c-11d0-8815-00a0c906bed8

// BUGBUG we need a device type added to DEVIOCTL.H
#define FILE_DEVICE_USB         FILE_DEVICE_UNKNOWN

//
// USB IOCTLS
//

#define USB_IOCTL_INTERNAL_INDEX       0x0000
#define USB_IOCTL_INDEX                0x00ff

//
// USB Internal IOCtls
//

/* IOCTL_INTERNAL_USB_SUBMIT_URB

   This IOCTL is used by client drivers to submit URB (USB Request Blocks)

   Parameters.Others.Argument1 = pointer to URB

*/

#define IOCTL_INTERNAL_USB_SUBMIT_URB  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INTERNAL_INDEX,  \
                                                METHOD_NEITHER,  \
                                                FILE_ANY_ACCESS)

/* IOCTL_INTERNAL_USB_RESET_PORT
*/

#define IOCTL_INTERNAL_USB_RESET_PORT  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INTERNAL_INDEX+1, \
                                                METHOD_NEITHER,  \
                                                FILE_ANY_ACCESS)

/*  IOCTL_INTERNAL_USB_GET_ROOTHUB_PDO

    This IOCTL is used internally by the hub driver

    Parameters.Others.Argument1 = pointer to be filled in with RootHubPdo;
    Parameters.Others.Argument2 = pointer to be filled in with HcdDeviceObject;

*/

#define IOCTL_INTERNAL_USB_GET_ROOTHUB_PDO  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INTERNAL_INDEX+3, \
                                                METHOD_NEITHER,  \
                                                FILE_ANY_ACCESS)

/* IOCTL_INTERNAL_USB_GET_PORT_STATUS

    This IOCTL returns the current port status

    Parameters.Others.Argument1 = pointer to port status register (ULONG)

    status bits are:

    USBD_PORT_ENABLED

*/

#define  USBD_PORT_ENABLED      0x00000001
#define  USBD_PORT_CONNECTED    0x00000002

#define IOCTL_INTERNAL_USB_GET_PORT_STATUS  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INTERNAL_INDEX+4, \
                                                METHOD_NEITHER,  \
                                                FILE_ANY_ACCESS)

/* IOCTL_INTERNAL_USB_ENABLE_PORT

    This IOCTL will request the hub to re-enable a disabled port
*/

#define IOCTL_INTERNAL_USB_ENABLE_PORT      CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INTERNAL_INDEX+5, \
                                                METHOD_NEITHER,  \
                                                FILE_ANY_ACCESS)

/* IOCTL_INTERNAL_USB_GET_HUB_COUNT

    This IOCTL is used internally by the hub driver

    Parameters.Others.Argument1 = pointer to be count of hubs in chain;

*/
#define IOCTL_INTERNAL_USB_GET_HUB_COUNT      CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INTERNAL_INDEX+6, \
                                                METHOD_NEITHER,  \
                                                FILE_ANY_ACCESS)

/* IOCTL_INTERNAL_USB_CYCLE_PORT

    This will simulate a plug/unplug on the port
*/

#define IOCTL_INTERNAL_USB_CYCLE_PORT  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INTERNAL_INDEX+7, \
                                                METHOD_NEITHER,  \
                                                FILE_ANY_ACCESS)

//
// USB Public IOCtls
//

//
// this ioctl is for adding debug hooks to HCDs
//

#define IOCTL_USB_HCD_GET_STATS          CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

//
// These ioctls are used for USB diagnostic and test applications
//

#define IOCTL_USB_DIAGNOSTIC_MODE_ON   CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+1,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_USB_DIAGNOSTIC_MODE_OFF  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+2,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_USB_GET_ROOT_HUB_NAME  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+3,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

/*
    Utility IOCTLS supported by the hub device
*/

//
// These ioctls are supported by the hub driver for
// use by user mode USB utilities.
//

#define IOCTL_USB_GET_NODE_INFORMATION                  CTL_CODE(FILE_DEVICE_USB,  \
                                               USB_IOCTL_INDEX+3,  \
                                               METHOD_BUFFERED,  \
                                               FILE_ANY_ACCESS)

#define IOCTL_USB_GET_NODE_CONNECTION_INFORMATION       CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+4,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION   CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+5,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_USB_GET_NODE_CONNECTION_NAME     CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+6,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_USB_DIAG_IGNORE_HUBS_ON   CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+7,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_USB_DIAG_IGNORE_HUBS_OFF  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+8,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME  CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+9,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)

#define IOCTL_GET_HCD_DRIVERKEY_NAME CTL_CODE(FILE_DEVICE_USB,  \
                                                USB_IOCTL_INDEX+10,  \
                                                METHOD_BUFFERED,  \
                                                FILE_ANY_ACCESS)
//
// structures for user mode ioctls
//

#pragma pack (1)

typedef enum _USB_HUB_NODE {
    UsbHub,
    UsbMIParent
} USB_HUB_NODE;

typedef struct _USB_HUB_INFORMATION {
    //
    // copy of data from hub descriptor
    //
    USB_HUB_DESCRIPTOR HubDescriptor;

    BOOLEAN HubIsBusPowered;

} USB_HUB_INFORMATION, *PUSB_HUB_INFORMATION;

typedef struct _USB_MI_PARENT_INFORMATION {
    ULONG NumberOfInterfaces;
} USB_MI_PARENT_INFORMATION, *PUSB_MI_PARENT_INFORMATION;

typedef struct _USB_NODE_INFORMATION {
    USB_HUB_NODE NodeType;        // hub, mi parent
    union {
        USB_HUB_INFORMATION HubInformation;
        USB_MI_PARENT_INFORMATION MiParentInformation;
    } u;
} USB_NODE_INFORMATION, *PUSB_NODE_INFORMATION;

typedef struct _USB_PIPE_INFO {
    USB_ENDPOINT_DESCRIPTOR EndpointDescriptor;
} USB_PIPE_INFO, PUSB_PIPE_INFO;

//
// BUGBUG
// more status codes?
//

typedef enum _USB_CONNECTION_STATUS {
    NoDeviceConnected,
    DeviceConnected,

    // failure codes, these map to fail reasons
    DeviceFailedEnumeration,
    DeviceGeneralFailure,
    DeviceCausedOvercurrent,
    DeviceNotEnoughPower,
} USB_CONNECTION_STATUS, *PUSB_CONNECTION_STATUS;

typedef struct _USB_NODE_CONNECTION_INFORMATION {
    ULONG ConnectionIndex;
    // usb device descriptor returned by this device
    // during enumeration
    USB_DEVICE_DESCRIPTOR DeviceDescriptor;
    UCHAR CurrentConfigurationValue;
    BOOLEAN LowSpeed;

    BOOLEAN DeviceIsHub;

    USHORT DeviceAddress;

    ULONG NumberOfOpenPipes;

    USB_CONNECTION_STATUS ConnectionStatus;
    USB_PIPE_INFO PipeList[0];
} USB_NODE_CONNECTION_INFORMATION, *PUSB_NODE_CONNECTION_INFORMATION;

typedef struct _USB_NODE_CONNECTION_DRIVERKEY_NAME {
    ULONG ConnectionIndex;  // INPUT
    ULONG ActualLength;     // OUTPUT
    // unicode name for the devnode.
    WCHAR DriverKeyName[1];      // OUTPUT
} USB_NODE_CONNECTION_DRIVERKEY_NAME, *PUSB_NODE_CONNECTION_DRIVERKEY_NAME;

typedef struct _USB_NODE_CONNECTION_NAME {
    ULONG ConnectionIndex;  // INPUT
    ULONG ActualLength;     // OUTPUT
    // unicode symbolic name for this node if it is a hub or parent driver
    // null if this node is a device.
    WCHAR NodeName[1];      // OUTPUT
} USB_NODE_CONNECTION_NAME, *PUSB_NODE_CONNECTION_NAME;

typedef struct _USB_ROOT_HUB_NAME {
    ULONG ActualLength;     // OUTPUT
    // NULL terminated unicode symbolic name for the root hub
    WCHAR RootHubName[1];   // OUTPUT
} USB_ROOT_HUB_NAME, *PUSB_ROOT_HUB_NAME;

typedef struct _USB_HCD_DRIVERKEY_NAME {
    ULONG ActualLength;     // OUTPUT
    // NULL terminated unicode driverkeyname for hcd
    WCHAR DriverKeyName[1];   // OUTPUT
} USB_HCD_DRIVERKEY_NAME, *PUSB_HCD_DRIVERKEY_NAME;

typedef struct _USB_DESCRIPTOR_REQUEST {
    ULONG ConnectionIndex;
    struct {
        UCHAR bmRequest;
        UCHAR bRequest;
        USHORT wValue;
        USHORT wIndex;
        USHORT wLength;
    } SetupPacket;
    UCHAR Data[0];
} USB_DESCRIPTOR_REQUEST, *PUSB_DESCRIPTOR_REQUEST;

//
// Structure for returning HCD debug and statistic information to
// a user mode application.
//

typedef struct _HCD_STAT_COUNTERS {
    ULONG BytesTransferred;

    USHORT IsoMissedCount;
    USHORT DataOverrunErrorCount;

    USHORT CrcErrorCount;
    USHORT ScheduleOverrunCount;

    USHORT TimeoutErrorCount;
    USHORT InternalHcErrorCount;

    USHORT BufferOverrunErrorCount;
    USHORT SWErrorCount;

    USHORT StallPidCount;
    USHORT PortDisableCount;

} HCD_STAT_COUNTERS, *PHCD_STAT_COUNTERS;

typedef struct _HCD_STAT_INFORMATION {
    ULONG Reserved1;
    ULONG Reserved2;
    ULONG ResetCounters;
    LARGE_INTEGER TimeRead;
    //
    // stat registers
    //
    HCD_STAT_COUNTERS Counters;

} HCD_STAT_INFORMATION, *PHCD_STAT_INFORMATION;

#pragma pack()

#endif // __USBIOCTL_H__


text:
package emp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import oracle.sql.json.OracleJsonFactory;
import oracle.sql.json.OracleJsonObject;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;

/**
 * Performs a partial update using JSON_MERGEPATCH.
 *
 * <p>
 * Run first: {@link CreateTable}, {@link Insert}
 * </p>
 */
public class UpdateMerge {

    public static void main(String[] args) throws SQLException {
        OracleJsonFactory factory = new OracleJsonFactory();

        PoolDataSource pool = PoolDataSourceFactory.getPoolDataSource();
        pool.setURL(String.join("", args));
        pool.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");

        try (Connection con = pool.getConnection()) {

            PreparedStatement stmt = con.prepareStatement(
                "UPDATE emp e " +
                "SET e.data = JSON_MERGEPATCH(e.data, :1) " +
                "WHERE e.data.name.string() = :2");

            OracleJsonObject patch = factory.createObject();
            patch.put("job", "Architect");
            patch.put("salary", 60000);

            stmt.setObject(1, patch);
            stmt.setString(2, "Miller");

            stmt.execute();

            System.out.println("Miller's salary and title have been updated");
        }
    }

}


text:
@interface XLButtonBarView ()

@property UIView * selectedBar;
@property NSUInteger selectedOptionIndex;

@end

@implementation XLButtonBarView

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self initializeXLButtonBarView];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeXLButtonBarView];
    }
    return self;
}

-(void)initializeXLButtonBarView
{
    _selectedOptionIndex = 0;
    [self addSubview:self.selectedBar];
}

-(void)moveToIndex:(NSUInteger)index animated:(BOOL)animated swipeDirection:(XLPagerTabStripDirection)swipeDirection
{
    self.selectedOptionIndex = index;
    [self updateSelectedBarPositionWithAnimation:animated swipeDirection:swipeDirection];
}

-(void)updateSelectedBarPositionWithAnimation:(BOOL)animation swipeDirection:(XLPagerTabStripDirection)swipeDirection
{
    CGRect frame = self.selectedBar.frame;
    UICollectionViewCell * cell = [self.dataSource collectionView:self cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.selectedOptionIndex inSection:0]];
    if (cell){
        if (swipeDirection != XLPagerTabStripDirectionNone){
            if (swipeDirection == XLPagerTabStripDirectionLeft)
            {
                float xValue = MIN(self.contentSize.width - self.frame.size.width, cell.frame.origin.x <= 35 ? 0 : cell.frame.origin.x - 35);
                [self  setContentOffset:CGPointMake(xValue, 0) animated:animation];
            }
            else if (swipeDirection == XLPagerTabStripDirectionRight){
                float xValue = MAX(0, cell.frame.origin.x + cell.frame.size.width - self.frame.size.width + 35);
                [self  setContentOffset:CGPointMake(xValue, 0) animated:animation];
            }

        }
    }
    frame.size.width = cell.frame.size.width;
    frame.origin.x = cell.frame.origin.x;
    frame.origin.y = cell.frame.size.height - frame.size.height;
    if (animation){
        [UIView animateWithDuration:0.3 animations:^{
            [self.selectedBar setFrame:frame];
        }];
    }
    else{
        self.selectedBar.frame = frame;
    }
}

#pragma mark - Properties

-(UIView *)selectedBar
{
    if (_selectedBar) return _selectedBar;
    _selectedBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 5, self.frame.size.width, 5)];
    _selectedBar.layer.zPosition = 9999;
    _selectedBar.backgroundColor = [UIColor blackColor];
    return _selectedBar;
}

@end


text:
import unittest
from netcdf import netcdf as nc
from datetime import datetime
from models import JobDescription
import os
import glob

class TestHeliosat(unittest.TestCase):

    def setUp(self):
        os.system('rm -rf static.nc temporal_cache product')
        os.system('cp -rf data mock_data')
        self.files = glob.glob('mock_data/goes13.*.BAND_01.nc')
        self.tile_cut = {
            "xc": [20, 30],
            "yc": [10, 15]
        }

    def tearDown(self):
        os.system('rm -rf mock_data')

    def verify_output(self):
        with nc.loader('tests/products/estimated/*.nc', self.tile_cut) as old:
            with nc.loader('products/estimated/*.nc', self.tile_cut) as new:
                valid = nc.getvar(old, 'globalradiation')
                max_vaild = valid[:].max()
                # It allow a 1% of the maximum value as the maximum error
                # threshold.
                threshold = max_vaild * 0.01
                calculated = nc.getvar(new, 'globalradiation')
                gtz = lambda m: m[calculated[:] >= 0]
                diff = gtz(calculated[:] - valid[:])
                print 'thr: ', threshold
                print 'min: ', gtz(calculated[:]).min(), '(', gtz(valid[:]).min(), ')'
                print 'max: ', gtz(calculated[:]).max(), '(', gtz(valid[:]).max(), ')'
                self.assertTrue((diff < threshold).all())
                shape = valid.shape
        return shape

    def test_main(self):
        config = {
            'algorithm': 'heliosat',
            'data': 'mock_data/goes13.2015.*.BAND_01.nc',
            'temporal_cache': 'temporal_cache',
            'product': 'products/estimated',
            'tile_cut': self.tile_cut
        }
        job = JobDescription(**config)
        begin = datetime.now()
        job.run()
        end = datetime.now()
        shape = self.verify_output()
        elapsed = (end - begin).total_seconds()
        image_ratio = (30. * 14 * 2 / shape[0])
        scale_shapes = (2245. / shape[1]) * (3515. / shape[2]) * (image_ratio)
        estimated = elapsed * scale_shapes / 3600.
        print "Scaling total time to %.2f hours." % estimated
        print "Efficiency achieved: %.2f%%" % (3.5 / estimated * 100.)

if __name__ == '__main__':
    unittest.run()


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <item name="viewpager" type="id"/>
  <item name="viewpagertab" type="id"/>
  <item name="title" type="id"/>
  <item name="header" type="id"/>
  <item name="header_image" type="id"/>
  <item name="list" type="id"/>
  <item name="empty" type="id"/>
  <item name="empty_container" type="id"/>
  <item name="refresh" type="id"/>
  <item name="progress" type="id"/>
  <item name="grid" type="id"/>
  <item name="webview" type="id"/>
  <item name="toolbar" type="id"/>
  <item name="swiperefresh" type="id"/>
  <item name="dragview" type="id"/>
  <item name="panel" type="id"/>
  <item name="back" type="id"/>
  <item name="back_icon" type="id"/>
  <item name="content" type="id"/>
</resources>


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 */
class GroupMember extends ImpulseObject{

	private $group;

	private $user;

	private $privilege;

	////////////////////////////////////////////////////////////////////////
	// CONSTRUCTOR
	/**
	 */
	public function __construct($group, $user, $privilege, $dateCreated, $dateModified, $lastModifier) {
		parent::__construct($dateCreated, $dateModified, $lastModifier);

		$this->group = $group;
		$this->user = $user;
		$this->privilege = $privilege;
	}

	////////////////////////////////////////////////////////////////////////
	// GETTERS

	public function get_group()	     { return $this->group; }
	public function get_privilege()	{ return $this->privilege; }
	public function get_user()      { return $this->user; }

	////////////////////////////////////////////////////////////////////////
	// GETTERS

	public function set_group($new) {
		$this->CI->api->modify->groupMember($this->group, $this->user, 'group', $new);
		$this->group = $new;
	}

	public function set_privilege($new) {
		$this->CI->api->modify->groupMember($this->group, $this->user, 'privilege', $new);
		$this->privilege = $new;
	}

	public function set_user($new) {
		$this->CI->api->modify->groupMember($this->group, $this->user, 'user', $new);
		$this->user= $new;
	}

	////////////////////////////////////////////////////////////////////////
	// PUBLIC FUNCTIONS

}
/* End of file GroupMember.php */
/* Location: ./application/libraries/objects/GroupMember.php */


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/image.h"

#include <algorithm>

#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "third_party/skia/include/core/SkBitmap.h"

#if defined(OS_LINUX)
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <glib-object.h>
#include "ui/gfx/canvas_skia.h"
#include "ui/gfx/gtk_util.h"
#elif defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#include "skia/ext/skia_utils_mac.h"
#endif

namespace gfx {

namespace internal {

#if defined(OS_MACOSX)
// This is a wrapper around gfx::NSImageToSkBitmap() because this cross-platform
// file cannot include the [square brackets] of ObjC.
bool NSImageToSkBitmaps(NSImage* image, std::vector<const SkBitmap*>* bitmaps);
#endif

#if defined(OS_LINUX)
const SkBitmap* GdkPixbufToSkBitmap(GdkPixbuf* pixbuf) {
  gfx::CanvasSkia canvas(gdk_pixbuf_get_width(pixbuf),
                         gdk_pixbuf_get_height(pixbuf),
                         /*is_opaque=*/false);
  canvas.DrawGdkPixbuf(pixbuf, 0, 0);
  return new SkBitmap(canvas.ExtractBitmap());
}
#endif

class SkBitmapRep;
class GdkPixbufRep;
class NSImageRep;

// An ImageRep is the object that holds the backing memory for an Image. Each
// RepresentationType has an ImageRep subclass that is responsible for freeing
// the memory that the ImageRep holds. When an ImageRep is created, it expects
// to take ownership of the image, without having to retain it or increase its
// reference count.
class ImageRep {
 public:
  explicit ImageRep(Image::RepresentationType rep) : type_(rep) {}

  // Deletes the associated pixels of an ImageRep.
  virtual ~ImageRep() {}

  // Cast helpers ("fake RTTI").
  SkBitmapRep* AsSkBitmapRep() {
    CHECK_EQ(type_, Image::kSkBitmapRep);
    return reinterpret_cast<SkBitmapRep*>(this);
  }

#if defined(OS_LINUX)
  GdkPixbufRep* AsGdkPixbufRep() {
    CHECK_EQ(type_, Image::kGdkPixbufRep);
    return reinterpret_cast<GdkPixbufRep*>(this);
  }
#endif

#if defined(OS_MACOSX)
  NSImageRep* AsNSImageRep() {
    CHECK_EQ(type_, Image::kNSImageRep);
    return reinterpret_cast<NSImageRep*>(this);
  }
#endif

  Image::RepresentationType type() const { return type_; }

 private:
  Image::RepresentationType type_;
};

class SkBitmapRep : public ImageRep {
 public:
  explicit SkBitmapRep(const SkBitmap* bitmap)
      : ImageRep(Image::kSkBitmapRep) {
    CHECK(bitmap);
    bitmaps_.push_back(bitmap);
  }

  explicit SkBitmapRep(const std::vector<const SkBitmap*>& bitmaps)
      : ImageRep(Image::kSkBitmapRep),
        bitmaps_(bitmaps) {
    CHECK(!bitmaps_.empty());
  }

  virtual ~SkBitmapRep() {
    STLDeleteElements(&bitmaps_);
  }

  const SkBitmap* bitmap() const { return bitmaps_[0]; }

  const std::vector<const SkBitmap*>& bitmaps() const { return bitmaps_; }

 private:
  std::vector<const SkBitmap*> bitmaps_;

  DISALLOW_COPY_AND_ASSIGN(SkBitmapRep);
};

#if defined(OS_LINUX)
class GdkPixbufRep : public ImageRep {
 public:
  explicit GdkPixbufRep(GdkPixbuf* pixbuf)
      : ImageRep(Image::kGdkPixbufRep),
        pixbuf_(pixbuf) {
    CHECK(pixbuf);
  }

  virtual ~GdkPixbufRep() {
    if (pixbuf_) {
      g_object_unref(pixbuf_);
      pixbuf_ = NULL;
    }
  }

  GdkPixbuf* pixbuf() const { return pixbuf_; }

 private:
  GdkPixbuf* pixbuf_;

  DISALLOW_COPY_AND_ASSIGN(GdkPixbufRep);
};
#endif

#if defined(OS_MACOSX)
class NSImageRep : public ImageRep {
 public:
  explicit NSImageRep(NSImage* image)
      : ImageRep(Image::kNSImageRep),
        image_(image) {
    CHECK(image);
  }

  virtual ~NSImageRep() {
    base::mac::NSObjectRelease(image_);
    image_ = nil;
  }

  NSImage* image() const { return image_; }

 private:
  NSImage* image_;

  DISALLOW_COPY_AND_ASSIGN(NSImageRep);
};
#endif

// The Storage class acts similarly to the pixels in a SkBitmap: the Image
// class holds a refptr instance of Storage, which in turn holds all the
// ImageReps. This way, the Image can be cheaply copied.
class ImageStorage : public base::RefCounted<ImageStorage> {
 public:
  ImageStorage(gfx::Image::RepresentationType default_type)
      : default_representation_type_(default_type) {
  }

  gfx::Image::RepresentationType default_representation_type() {
    return default_representation_type_;
  }
  gfx::Image::RepresentationMap& representations() { return representations_; }

 private:
  ~ImageStorage() {
    for (gfx::Image::RepresentationMap::iterator it = representations_.begin();
         it != representations_.end();
         ++it) {
      delete it->second;
    }
    representations_.clear();
  }

  // The type of image that was passed to the constructor. This key will always
  // exist in the |representations_| map.
  gfx::Image::RepresentationType default_representation_type_;

  // All the representations of an Image. Size will always be at least one, with
  // more for any converted representations.
  gfx::Image::RepresentationMap representations_;

  friend class base::RefCounted<ImageStorage>;
};

}  // namespace internal

Image::Image(const SkBitmap* bitmap)
    : storage_(new internal::ImageStorage(Image::kSkBitmapRep)) {
  internal::SkBitmapRep* rep = new internal::SkBitmapRep(bitmap);
  AddRepresentation(rep);
}

Image::Image(const std::vector<const SkBitmap*>& bitmaps)
    : storage_(new internal::ImageStorage(Image::kSkBitmapRep)) {
  internal::SkBitmapRep* rep = new internal::SkBitmapRep(bitmaps);
  AddRepresentation(rep);
}

#if defined(OS_LINUX)
Image::Image(GdkPixbuf* pixbuf)
    : storage_(new internal::ImageStorage(Image::kGdkPixbufRep)) {
  internal::GdkPixbufRep* rep = new internal::GdkPixbufRep(pixbuf);
  AddRepresentation(rep);
}
#endif

#if defined(OS_MACOSX)
Image::Image(NSImage* image)
    : storage_(new internal::ImageStorage(Image::kNSImageRep)) {
  internal::NSImageRep* rep = new internal::NSImageRep(image);
  AddRepresentation(rep);
}
#endif

Image::Image(const Image& other) : storage_(other.storage_) {
}

Image& Image::operator=(const Image& other) {
  storage_ = other.storage_;
  return *this;
}

Image::~Image() {
}

Image::operator const SkBitmap*() const {
  internal::ImageRep* rep = GetRepresentation(Image::kSkBitmapRep);
  return rep->AsSkBitmapRep()->bitmap();
}

Image::operator const SkBitmap&() const {
  return *(this->operator const SkBitmap*());
}

#if defined(OS_LINUX)
Image::operator GdkPixbuf*() const {
  internal::ImageRep* rep = GetRepresentation(Image::kGdkPixbufRep);
  return rep->AsGdkPixbufRep()->pixbuf();
}
#endif

#if defined(OS_MACOSX)
Image::operator NSImage*() const {
  internal::ImageRep* rep = GetRepresentation(Image::kNSImageRep);
  return rep->AsNSImageRep()->image();
}
#endif

bool Image::HasRepresentation(RepresentationType type) const {
  return storage_->representations().count(type) != 0;
}

size_t Image::RepresentationCount() const {
  return storage_->representations().size();
}

void Image::SwapRepresentations(gfx::Image* other) {
  storage_.swap(other->storage_);
}

internal::ImageRep* Image::DefaultRepresentation() const {
  RepresentationMap& representations = storage_->representations();
  RepresentationMap::iterator it =
      representations.find(storage_->default_representation_type());
  DCHECK(it != representations.end());
  return it->second;
}

internal::ImageRep* Image::GetRepresentation(
    RepresentationType rep_type) const {
  // If the requested rep is the default, return it.
  internal::ImageRep* default_rep = DefaultRepresentation();
  if (rep_type == storage_->default_representation_type())
    return default_rep;

  // Check to see if the representation already exists.
  RepresentationMap::iterator it = storage_->representations().find(rep_type);
  if (it != storage_->representations().end())
    return it->second;

  // At this point, the requested rep does not exist, so it must be converted
  // from the default rep.

  // Handle native-to-Skia conversion.
  if (rep_type == Image::kSkBitmapRep) {
    internal::SkBitmapRep* rep = NULL;
#if defined(OS_LINUX)
    if (storage_->default_representation_type() == Image::kGdkPixbufRep) {
      internal::GdkPixbufRep* pixbuf_rep = default_rep->AsGdkPixbufRep();
      rep = new internal::SkBitmapRep(
          internal::GdkPixbufToSkBitmap(pixbuf_rep->pixbuf()));
    }
#elif defined(OS_MACOSX)
    if (storage_->default_representation_type() == Image::kNSImageRep) {
      internal::NSImageRep* nsimage_rep = default_rep->AsNSImageRep();
      std::vector<const SkBitmap*> bitmaps;
      CHECK(internal::NSImageToSkBitmaps(nsimage_rep->image(), &bitmaps));
      rep = new internal::SkBitmapRep(bitmaps);
    }
#endif
    CHECK(rep);
    AddRepresentation(rep);
    return rep;
  }

  // Handle Skia-to-native conversions.
  if (default_rep->type() == Image::kSkBitmapRep) {
    internal::SkBitmapRep* skia_rep = default_rep->AsSkBitmapRep();
    internal::ImageRep* native_rep = NULL;
#if defined(OS_LINUX)
    if (rep_type == Image::kGdkPixbufRep) {
      GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(skia_rep->bitmap());
      native_rep = new internal::GdkPixbufRep(pixbuf);
    }
#elif defined(OS_MACOSX)
    if (rep_type == Image::kNSImageRep) {
      NSImage* image = gfx::SkBitmapsToNSImage(skia_rep->bitmaps());
      base::mac::NSObjectRetain(image);
      native_rep = new internal::NSImageRep(image);
    }
#endif
    CHECK(native_rep);
    AddRepresentation(native_rep);
    return native_rep;
  }

  // Something went seriously wrong...
  return NULL;
}

void Image::AddRepresentation(internal::ImageRep* rep) const {
  storage_->representations().insert(std::make_pair(rep->type(), rep));
}

size_t Image::GetNumberOfSkBitmaps() const  {
  return GetRepresentation(Image::kSkBitmapRep)->AsSkBitmapRep()->
      bitmaps().size();
}

const SkBitmap* Image::GetSkBitmapAtIndex(size_t index) const {
  return GetRepresentation(Image::kSkBitmapRep)->AsSkBitmapRep()->
      bitmaps()[index];
}

}  // namespace gfx


text:
package com.facebook.buck.apple;

import static com.facebook.buck.rules.TestCellBuilder.createCellRoots;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.cxx.FrameworkDependencies;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.SingleThreadedBuildRuleResolver;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.testutil.TargetGraphFactory;
import com.facebook.buck.util.types.Either;
import com.google.common.collect.ImmutableSortedSet;
import org.junit.Test;

public class AppleBundleDescriptionTest {

  private ProjectFilesystem filesystem = new FakeProjectFilesystem();

  @Test
  public void depsHaveFlavorsPropagated() {
    BuildTarget bundleTarget = BuildTargetFactory.newInstance("//bar:bundle#iphoneos-x86_64");

    BuildTarget unflavoredDep = BuildTargetFactory.newInstance("//bar:dep1");
    BuildTarget unflavoredDepAfterPropagation =
        BuildTargetFactory.newInstance("//bar:dep1#iphoneos-x86_64");

    BuildTarget flavoredDep =
        BuildTargetFactory.newInstance("//bar:dep2#iphoneos-x86_64,iphoneos-i386");

    BuildTarget flavoredDepNotInDomain = BuildTargetFactory.newInstance("//bar:dep3#otherflavor");
    BuildTarget flavoredDepNotInDomainAfterPropagation =
        BuildTargetFactory.newInstance("//bar:dep3#iphoneos-x86_64,otherflavor");

    BuildTarget watchDep = BuildTargetFactory.newInstance("//bar:watch#watch");
    BuildTarget watchDepAfterPropagation =
        BuildTargetFactory.newInstance("//bar:watch#watchos-armv7k");

    BuildTarget binary = BuildTargetFactory.newInstance("//bar:binary");

    AppleBundleDescription desc = FakeAppleRuleDescriptions.BUNDLE_DESCRIPTION;
    AppleBundleDescriptionArg constructorArg =
        AppleBundleDescriptionArg.builder()
            .setName("bundle")
            .setExtension(Either.ofLeft(AppleBundleExtension.BUNDLE))
            .setInfoPlist(FakeSourcePath.of("Info.plist"))
            .setBinary(binary)
            .setDeps(
                ImmutableSortedSet.of(
                    binary, unflavoredDep, flavoredDep, flavoredDepNotInDomain, watchDep))
            .build();

    // Now call the find deps methods and verify it returns the targets with flavors.
    ImmutableSortedSet.Builder<BuildTarget> implicitDeps = ImmutableSortedSet.naturalOrder();
    desc.findDepsForTargetFromConstructorArgs(
        bundleTarget,
        createCellRoots(filesystem),
        constructorArg,
        implicitDeps,
        ImmutableSortedSet.naturalOrder());

    assertEquals(
        ImmutableSortedSet.<BuildTarget>naturalOrder()
            .add(unflavoredDepAfterPropagation)
            .add(flavoredDep)
            .add(flavoredDepNotInDomainAfterPropagation)
            .add(watchDepAfterPropagation)
            .build(),
        implicitDeps.build());
  }

  @Test
  public void depsHaveStripAndDebugFlavorsPropagated() {
    BuildTarget bundleTargetWithStripFlavor =
        BuildTargetFactory.newInstance("//bar:bundle#iphoneos-x86_64,strip-all,dwarf-and-dsym");

    BuildTarget unflavoredDep = BuildTargetFactory.newInstance("//bar:dep1");
    BuildTarget unflavoredDepAfterPropagation =
        BuildTargetFactory.newInstance("//bar:dep1#iphoneos-x86_64,strip-all,dwarf-and-dsym");

    BuildTarget flavoredDep =
        BuildTargetFactory.newInstance("//bar:dep2#iphoneos-i386,strip-debug,dwarf");

    BuildTarget flavoredDepNotInDomain = BuildTargetFactory.newInstance("//bar:dep3#otherflavor");
    BuildTarget flavoredDepNotInDomainAfterPropagation =
        BuildTargetFactory.newInstance(
            "//bar:dep3#iphoneos-x86_64,strip-all,dwarf-and-dsym,otherflavor");

    BuildTarget stripFlavorOnly = BuildTargetFactory.newInstance("//bar:dep4#strip-debug");
    BuildTarget stripFlavorOnlyAfterPropagation =
        BuildTargetFactory.newInstance("//bar:dep4#iphoneos-x86_64,strip-debug,dwarf-and-dsym");

    BuildTarget debugFlavorOnly = BuildTargetFactory.newInstance("//bar:dep5#dwarf");
    BuildTarget debugFlavorOnlyAfterPropagation =
        BuildTargetFactory.newInstance("//bar:dep5#iphoneos-x86_64,strip-all,dwarf");

    BuildTarget binary = BuildTargetFactory.newInstance("//bar:binary");

    AppleBundleDescription desc = FakeAppleRuleDescriptions.BUNDLE_DESCRIPTION;
    AppleBundleDescriptionArg constructorArg =
        AppleBundleDescriptionArg.builder()
            .setName("bundle")
            .setExtension(Either.ofLeft(AppleBundleExtension.BUNDLE))
            .setInfoPlist(FakeSourcePath.of("Info.plist"))
            .setBinary(binary)
            .setDeps(
                ImmutableSortedSet.<BuildTarget>naturalOrder()
                    .add(binary)
                    .add(unflavoredDep)
                    .add(flavoredDep)
                    .add(flavoredDepNotInDomain)
                    .add(stripFlavorOnly)
                    .add(debugFlavorOnly)
                    .build())
            .build();

    // Now call the find deps methods and verify it returns the targets with flavors.
    ImmutableSortedSet.Builder<BuildTarget> implicitDeps = ImmutableSortedSet.naturalOrder();
    desc.findDepsForTargetFromConstructorArgs(
        bundleTargetWithStripFlavor,
        createCellRoots(filesystem),
        constructorArg,
        implicitDeps,
        ImmutableSortedSet.naturalOrder());

    assertEquals(
        ImmutableSortedSet.<BuildTarget>naturalOrder()
            .add(unflavoredDepAfterPropagation)
            .add(flavoredDep)
            .add(flavoredDepNotInDomainAfterPropagation)
            .add(stripFlavorOnlyAfterPropagation)
            .add(debugFlavorOnlyAfterPropagation)
            .build(),
        implicitDeps.build());
  }

  @Test
  public void metadataTraversalForFrameworkDependenciesAreTerminated() throws Exception {
    BuildTarget binaryTarget = BuildTargetFactory.newInstance("//:binary");
    TargetNode<?, ?> binaryNode = new AppleBinaryBuilder(binaryTarget).build();

    BuildTarget bundleTarget = BuildTargetFactory.newInstance("//:bundle");
    TargetNode<?, ?> bundleNode =
        new AppleBundleBuilder(bundleTarget)
            .setExtension(Either.ofLeft(AppleBundleExtension.BUNDLE))
            .setInfoPlist(FakeSourcePath.of("Info.plist"))
            .setBinary(binaryTarget)
            .build();

    BuildRuleResolver buildRuleResolver =
        new SingleThreadedBuildRuleResolver(
            TargetGraphFactory.newInstance(bundleNode, binaryNode),
            new DefaultTargetNodeToBuildRuleTransformer());
    assertTrue(
        "Although querying a binary's framework dependencies should not return empty...",
        buildRuleResolver
            .requireMetadata(
                binaryTarget.withFlavors(
                    FakeAppleRuleDescriptions.DEFAULT_MACOSX_X86_64_PLATFORM.getFlavor()),
                FrameworkDependencies.class)
            .isPresent());
    assertFalse(
        "Querying a bundle's framework dependencies should return empty.",
        buildRuleResolver.requireMetadata(bundleTarget, FrameworkDependencies.class).isPresent());
  }
}


text:
'use strict';

const winston = require('winston');
const Promise = require('bluebird');

const appConfig = require('src/config/appConfig');

var logger = new winston.Logger({
  level: appConfig.logLevel,
  colorize: true,
  transports: [
    new(winston.transports.Console)(),
    new(winston.transports.File)({
      filename: appConfig.logFilePath
    })
  ]
});

/** @module Logger */
/** @class */
class LoggerService {
  constructor() {}

  /**
   * Log a debug message
   * @param {string} msg - Message to log
   */
  debug(msg) {
    logger.debug(msg);
  }

  /**
   * Log an info message
   * @param {string} msg - Message to log
   */
  info(msg) {
    logger.info(msg);
  }

  /**
   * Log a warn message
   * @param {string} msg - Message to log
   */
  warn(msg) {
    logger.warn(msg);
  }

  /**
   * Log an error message
   * @param {string} msg - Message to log
   */
  error(msg) {
    logger.error(msg);
  }

  /**
   * List log messages
   * @param {object} [options] - hash of options for listing
   * @param {date} [options.fromDate]
   * @param {date} [options.toDate]
   * @param {number} [options.skip]
   * @param {number} [options.limit]
   */
  list(options) {
    options = options || {};

    var queryOptions = {};
    if (options.fromDate) queryOptions.from = options.fromDate;
    if (options.toDate) queryOptions.until = options.toDate;
    if (options.skip) queryOptions.start = options.skip;
    if (options.limit) queryOptions.limit = options.limit;

    return new Promise(function(resolve, reject) {
      logger.query(queryOptions, function(err, results) {
        if (err) return reject(err);

        return resolve(results);
      });
    });
  }
}

module.exports = new LoggerService();


text:
std::string ok_a(bool failed = false) {
    std::ostringstream ok; ok << "" // Suppress a warning.
        #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
            << "a::static_inv" << std::endl
            << "a::inv" << std::endl // This can fail.
        #endif
    ;
    if(!failed) ok
        #ifndef BOOST_CONTRACT_NO_OLDS
            << "a::dtor::old" << std::endl
        #endif
        << "a::dtor::body" << std::endl
        #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS
            << "a::static_inv" << std::endl
        #endif
        #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
            << "a::dtor::post" << std::endl
        #endif
    ;
    return ok.str();
}

std::string ok_b(bool threw = false) {
    std::ostringstream ok; ok << "" // Suppress a warning.
        #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
            << "b::static_inv" << std::endl
        #endif
        #ifndef BOOST_CONTRACT_NO_OLDS
            << "b::dtor::old" << std::endl
        #endif
        << "b::dtor::body" << std::endl
        #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS
            << "b::static_inv" << std::endl
            // No b::inv here (not even when threw).
        #endif
        #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
            << (!threw ? "b::dtor::post\n" : "")
        #endif
    ;
    return ok.str();
}

enum checked { passed, failed, threw };

std::string ok_c(checked check = passed) {
    std::ostringstream ok; ok << "" // Suppress a warning.
        #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
            << "c::static_inv" << std::endl
            << "c::inv" << std::endl // This can fail.
        #endif
    ;
    if(check != failed) ok
        #ifndef BOOST_CONTRACT_NO_OLDS
            << "c::dtor::old" << std::endl
        #endif
        << "c::dtor::body" << std::endl
        #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS
            << "c::static_inv" << std::endl
            << (check == threw ? "c::inv\n" : "")
        #endif
        #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
            << (check == passed ? "c::dtor::post\n" : "")
        #endif
    ;
    return ok.str();
}

struct err {}; // Global decl so visible in MSVC10 lambdas.

int main() {
    std::ostringstream ok;

    a_entry_inv = true;
    b_entry_inv = true;
    c_entry_inv = true;
    {
        a aa;
        out.str("");
    }
    ok.str(""); ok // Test nothing failed.
        << ok_a()
        << ok_b()
        << ok_c()
    ;
    BOOST_TEST(out.eq(ok.str()));

    boost::contract::set_entry_invariant_failure([&ok] (boost::contract::from) {
        BOOST_TEST(out.eq(ok.str())); // Must check before dtor throws...
        throw err(); // for testing (as dtors should never throw anyways).
    });

    #ifdef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
        #define BOOST_CONTRACT_TEST_entry_inv 0
    #else
        #define BOOST_CONTRACT_TEST_entry_inv 1
    #endif

    a_entry_inv = false;
    b_entry_inv = true;
    c_entry_inv = true;
    try {
        {
            a aa;
            ok.str(""); ok
                // Test entry a::inv failed...
                << ok_a(BOOST_CONTRACT_TEST_entry_inv)
            ;
            out.str("");
        }
        #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
                BOOST_TEST(false);
            } catch(err const&) {
        #endif
        ok // ...then exec other dtors and check inv on throw (as dtor threw).
            << ok_b(BOOST_CONTRACT_TEST_entry_inv)
            << ok_c(BOOST_CONTRACT_TEST_entry_inv ? threw : passed)
        ;
        BOOST_TEST(out.eq(ok.str()));
    } catch(...) { BOOST_TEST(false); }

    a_entry_inv = true;
    b_entry_inv = false;
    c_entry_inv = true;
    {
        a aa;
        out.str("");
    }
    ok.str(""); ok
        << ok_a()
        << ok_b() // Test no entry b::inv so no failure here.
        << ok_c()
    ;
    BOOST_TEST(out.eq(ok.str()));

    a_entry_inv = true;
    b_entry_inv = true;
    c_entry_inv = false;
    try {
        {
            a aa;
            ok.str(""); ok
                << ok_a()
                << ok_b()
                // Test entry c::inv failed...
                << ok_c(BOOST_CONTRACT_TEST_entry_inv ? failed : passed)
            ;
            out.str("");
        }
        #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
                BOOST_TEST(false);
            } catch(err const&) {
        #endif
        // ...then exec other dtors and check inv on throw (as dtor threw).
        BOOST_TEST(out.eq(ok.str()));
    } catch(...) { BOOST_TEST(false); }

    boost::contract::set_entry_invariant_failure([] (boost::contract::from) {
        // Testing multiple failures so dtors must not throw multiple
        // exceptions, just ignore failure and continue test program...
    });

    a_entry_inv = false;
    b_entry_inv = false;
    c_entry_inv = false;
    {
        a aa;
        out.str("");
    }
    ok.str(""); ok
        // Test entry a::inv failed (as all did).
        << ok_a(BOOST_CONTRACT_TEST_entry_inv)
        #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
            << "a::dtor::body" << std::endl
        #endif

        << ok_b() // Test no entry b::inv so no failure here.

        // Test entry c::inv failed (as all did).
        << ok_c(BOOST_CONTRACT_TEST_entry_inv ? failed : passed)
        #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
            << "c::dtor::body" << std::endl
        #endif
    ;
    BOOST_TEST(out.eq(ok.str()));

    #undef BOOST_CONTRACT_TEST_entry_inv
    return boost::report_errors();
}


text:
class GetAudioDeviceParm : public PortSysExMessage {
  public:
	GetAudioDeviceParm(Device *device);

	virtual ~GetAudioDeviceParm();

	void createAnswer(Command m_Command, std::vector<unsigned char> *message,
					  Device *m_pDevice);

  protected:
	std::vector<unsigned char> *getMessageData();
};

#endif // GETAUDIODEVICEPARM_H


text:
package com.mercury.platform.ui.components.panel.grid;

import lombok.AllArgsConstructor;
import lombok.Data;

import javax.swing.*;

@Data
@AllArgsConstructor
public class ItemCell {
    private int x;
    private int y;
    private JPanel cell;
}


text:
//! \file fbxclonemanager.h
#ifndef _FBXSDK_UTILS_CLONE_MANAGER_H_
#define _FBXSDK_UTILS_CLONE_MANAGER_H_

#include <fbxsdk_def.h>

#include <core/fbxobject.h>
#include <core/fbxquery.h>

#include <fbxsdk_nsbegin.h>

/** The clone manager is a utility for cloning entire networks of FbxObject.
  * Options are available for specifying how the clones inherit the connections
  * of the original.
  *
  * Networks of FbxObject (inter-connected objects by OO, OP, PO or PP connections)
  * can be cloned. How the connections of clones are handled depends on mSrcPolicy and mExternalDstPolicy.
  *
  * To clone FbxObject instances and their dependents, put them into a CloneSet
  * and pass the CloneSet to this class:
  * \code
  * FbxCloneManager                  cloneManager;
  * FbxCloneManager::CloneSet        cloneSet;
  * FbxCloneManager::CloneSetElement defaultCloneOptions(FbxCloneManager::sConnectToClone,
  *                                                      FbxCloneManager::sConnectToOriginal,
  *                                                      FbxObject::eDeepClone);
  * cloneSet.Insert(someObject, defaultCloneOptions);
  * cloneManager.AddDependents(cloneSet, someObject, defaultCloneOptions);
  * cloneManager.Clone(cloneSet, scene)
  * \endcode
  *
  * \remark If cloning occurs on the same scene as the original objects, the system will contain duplicated names. Although this is acceptable in FBX,
  *         some applications may not behave correctly with duplicated names. It is the responsability of the caller to resolve any conflicts.
  *
  * \see FbxCloneManager::CloneSetElement
  * \see FbxCloneManager::CloneSet
  * \nosubgrouping
  */
class FBXSDK_DLL FbxCloneManager
{
public:

    //! Maximum depth to clone dependents.
    static const int sMaximumCloneDepth;

    /** Connect to objects that are connected to original object.
      * This is a flag to mSrcPolicy or mExternalDstPolicy.
      */
    static const int sConnectToOriginal;

    /** Connect to clones of objects that are connected to original object.
      * (only if those original objects are also in the clone set)
      * This is a flag to mSrcPolicy.
      */
    static const int sConnectToClone;

    /** This represents an element in FbxCloneManager::CloneSet to be cloned.
      * This class contains the option for specifying how connections are cloned and the
      * cloned object.
      * \see FbxCloneManager
      * \see FbxCloneManager::CloneSet
      */
    struct FBXSDK_DLL CloneSetElement
    {
    public:
        /** Constructor.
          * \param pSrcPolicy Specify how to handle source connections. Valid values are 0, sConnectToOriginal,
          *                   sConnectToClone or sConnectToOriginal|sConnectToClone.
          * \param pExternalDstPolicy Specify how to handle destination connections to objects NOT in
          *                           the clone set. Valid values are 0 or sConnectToOriginal.
          * \param pCloneType Specify the type of cloning. FbxObject::Clone uses the same parameter.
          */
        CloneSetElement( int pSrcPolicy = 0,
                         int pExternalDstPolicy = 0,
                         FbxObject::ECloneType pCloneType = FbxObject::eReferenceClone );

        //! the type of cloning to perform
        FbxObject::ECloneType mType;

        /** Policy on how to handle source connections on the original object. Valid values are 0
          * or any bitwise OR'd combination of sConnectToOriginal, and sConnectToClone.
          */
        int mSrcPolicy;

        /** policy on how to handle destination connections on the original object to
          * objects NOT in the clone set. (Destination connections to objects in the set
          * are handled by that object's source policy) Valid values are 0 or sConnectToOriginal.
          */
        int mExternalDstPolicy;

        /** This is a pointer to the newly created clone.
          * It is set after the call to FbxCloneManager::Clone()
          */
        FbxObject* mObjectClone;
    };

    /** \brief Functor to compare object pointers. This class is used internally in FbxCloneManager.
      */
    class FBXSDK_DLL ObjectCompare
    {
    public:
        /** Operator converting instance to int type.
          * \param pKeyA Left key to be compared.
          * \param pKeyB Right key to be compared.
          */
        inline int operator()(FbxObject* const& pKeyA, FbxObject* const& pKeyB) const
        {
            return (pKeyA < pKeyB) ? -1 : ((pKeyB < pKeyA) ? 1 : 0);
        }
    };

    /** The CloneSet is a collection of pointers to objects that will be cloned in Clone()
      * Attached to each object is a CloneSetElement. Its member variables dictate how
      * the corresponding object will be cloned, and how it will inherit connections
      * on the original object.
      */
    typedef FbxMap<FbxObject*,CloneSetElement,ObjectCompare> CloneSet;

    /** Constructor
      */
    FbxCloneManager();

    /** Destructor
      */
    virtual ~FbxCloneManager();

    /** This function simplifies the process of cloning one object and all its depedency graph by automatically preparing
      * the CloneSet and calling the Clone method using the code below.
      *
      * \code
      * FbxCloneManager                  cloneManager;
      * FbxCloneManager::CloneSet        cloneSet;
      * FbxCloneManager::CloneSetElement defaultCloneOptions(FbxCloneManager::sConnectToClone,
      *                                                      FbxCloneManager::sConnectToOriginal,
      *                                                      FbxObject::eDeepClone);
      * FbxObject* lReturnObj = (FbxObject*)pObject;
      *
      * cloneManager.AddDependents(cloneSet, pObject, defaultCloneOptions, FbxCriteria::ObjectType(FbxObject::ClassId));
      * cloneSet.Insert((FbxObject*)pObject, defaultCloneOptions);
      *
      * // collect all the FbxCharacters, if any (these are indirect dependencies not visible by the AddDependents recursion)
      * FbxArray<FbxObject*> lExtras;
      * FbxCloneManager::CloneSet::RecordType* lIterator = cloneSet.Minimum();
      * while( lIterator )
      * {
      *     FbxObject* lObj = lIterator->GetKey();
      *     cloneManager.LookForIndirectDependent(lObj, cloneSet, lExtras);
      *     lIterator = lIterator->Successor();
      * }
      *
      * // and add them to cloneSet
      * for (int i = 0, c = lExtras.GetCount(); i < c; i++)
      * {
      *     FbxObject* lObj = lExtras[i];
      *     cloneManager.AddDependents(cloneSet, lObj, defaultCloneOptions);
      *     cloneSet.Insert(lObj, defaultCloneOptions);
      * }
      *
      * // clone everything
      * if (cloneManager.Clone(cloneSet, pContainer))
      * {
      *     // get the clone of pObject
      *     CloneSet::RecordType* lIterator = cloneSet.Find((FbxObject* const)pObject);
      *     if( lIterator )
      *     {
      *         lReturnObj = lIterator->GetValue().mObjectClone;
      *     }
      * }
      * return lReturnObj;
      * \endcode
      *
      * \param pObject Object to clone.
      * \param pContainer This object (typically a scene or document) will contain the new clones.
      * \return The clone of \e pObject if all its depedency graph have been cloned successfully, NULL otherwise.
      * \remark It is advised not to use an FbxNode object for \e pContainer to group the cloned dependency graph.
      *         Some objects of the FBX SDK are not meant to be connected to FbxNode objects and if they are, the final scene
      *         will not comply to the FBX standard and its behavior cannot be guaranteed.
      * \remark If \e pContainer is left \c NULL the cloned objects only exists in the FbxSdkManager and need to be
      *         manually connected to the scene in order to be saved to disk.
      *
      * Example:
      * \code
      *     FbxObject* lObj2BCloned = ...
      *     FbxNode* myNewParent = FbxNode::Create(lNewScene, "Clone");
      *     lNewScene->GetRootNode()->AddChild(lN);
      *
      *     FbxCloneManager cloneManager;
      *     FbxNode *lClone = (FbxNode*)cloneManager.Clone(lObj2BCloned);
      *
      *     // make sure the cloned object is connected to the scene
      *     lClone->ConnectDstObject(lNewScene);
      * \endcode
      */
    static FbxObject* Clone(const FbxObject* pObject, FbxObject* pContainer = NULL);

    /** Clone all objects in the set using the given policies for duplication
      * of connections. Each CloneSetElement in the set will have its mObjectClone
      * pointer set to the newly created clone. The following code shows how to access the cloned objects:
      *
      * \code
      *     if (cloneManager.Clone(cloneSet, pContainer))
      *     {
      *         // access the clones
      *         FbxCloneManager::CloneSet::RecordType* lIterator = cloneSet.Minimum();
      *         while( lIterator )
      *         {
      *             FbxObject* lOriginalObject = lIterator->GetKey();
      *             FbxObject* lClonedObject   = lIterator->GetValue().mObjectClone;
      *             lIterator = lIterator->Successor();
      *         }
      *     }
      * \endcode
      *
      * \param pSet Set of objects to clone
      * \param pContainer This object (typically a scene or document) will contain the new clones
      * \return true if all objects were cloned, false otherwise.
      * \remark It is advised not to use an FbxNode object for \e pContainer to group the cloned dependency graph.
      *         Some objects of the FBX SDK are not meant to be connected to FbxNode objects and if they are, the final scene
      *         will not comply to the FBX standard and its behavior cannot be guaranteed.
      * \remark If \e pContainer is left \c NULL the cloned objects only exists in the FbxSdkManager and need to be
      *         manually connected to the scene in order to be saved to disk.
      */
    virtual bool Clone( CloneSet& pSet, FbxObject* pContainer = NULL ) const;

    /** Add all dependents of the given object to the CloneSet.
      * Dependents of items already in the set are ignored to prevent
      * infinite recursion on cyclic dependencies.
      * \param pSet The set to add items.
      * \param pObject Object to add dependents to
	  * \param pCloneOptions
      * \param pTypes Types of dependent objects to consider
      * \param pDepth Maximum recursive depth. Valid range is [0,sMaximumCloneDepth]
      *
      * The following example shows how to perform multiple calls to AddDependents() to collect several
      * subgraphs to be cloned:
      * \code
      *         FbxObject* lRoot = ...           // initialized with the root of the graph to be cloned
      *         FbxCharacter* lCharacter = ...   // points to the FbxCharacter driving the character defined by "lRoot" graph
      *
      *         FbxCloneManager                  cloneManager;
      *         FbxCloneManager::CloneSet        cloneSet;
      *
      *         cloneManager.AddDependents(cloneSet, lRoot);
      *         cloneSet.Insert(lRoot, defaultCloneOptions);
      *
      *         cloneManager.AddDependents(cloneSet, lCharacter);
      *         cloneSet.Insert(lCharacter, defaultCloneOptions);
      *
      * \endcode
      */
    virtual void AddDependents( CloneSet& pSet,
                        const FbxObject* pObject,
                        const CloneSetElement& pCloneOptions = CloneSetElement(),
                        FbxCriteria pTypes = FbxCriteria::ObjectType(FbxObject::ClassId),
                        int pDepth = sMaximumCloneDepth ) const;

/*****************************************************************************************************************************
** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! **
*****************************************************************************************************************************/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
    static FbxObject* Clone(const FbxObject* pObject, CloneSet* pSet, FbxObject* pContainer = NULL);

private:
    friend class FbxScene;

	bool CloneConnections( CloneSet::RecordType* pIterator, const CloneSet& pSet) const;
    bool CheckIfCloneOnSameScene(const FbxObject* pObject, FbxObject* pContainer) const;

    virtual void LookForIndirectDependent(const FbxObject* pObject, CloneSet& pSet, FbxArray<FbxObject*>& lIndirectDepend);
    virtual bool NeedToBeExcluded(FbxObject* lObj) const;

    bool      mCloneOnSameScene;

#endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/
};

#include <fbxsdk_nsend.h>

#define CloneSetCast(x)         ((FbxCloneManager::CloneSet*)(x))
#define CloneSetElementCast(x)  ((FbxCloneManager::CloneSetElement*)((x!=NULL)?&(x->GetValue()):NULL))

#endif /* _FBXSDK_UTILS_CLONE_MANAGER_H_ */


text:
import React from 'react';
import PropTypes from 'prop-types';
import MenuItem from 'material-ui/MenuItem';
import DashboardIcon from 'material-ui/svg-icons/action/dashboard';
import { Link } from 'react-router-dom';
import translate from '../../i18n/translate';

const DashboardMenuItem = ({ onTouchTap, translate }) => (
    <MenuItem
        containerElement={<Link to="/" />}
        primaryText={translate('aor.page.dashboard')}
        leftIcon={<DashboardIcon />}
        onTouchTap={onTouchTap}
    />
);

DashboardMenuItem.propTypes = {
    onTouchTap: PropTypes.func,
    translate: PropTypes.func.isRequired,
};

export default translate(DashboardMenuItem);


text:
package org.platanios.tensorflow.api.ops.rnn.cell

import org.platanios.tensorflow.api.core.Shape
import org.platanios.tensorflow.api.core.types.{IsNotQuantized, TF}
import org.platanios.tensorflow.api.implicits.helpers.OutputToShape
import org.platanios.tensorflow.api.ops.{NN, Op, Output}
import org.platanios.tensorflow.api.ops.basic.Basic
import org.platanios.tensorflow.api.ops.math.Math
import org.platanios.tensorflow.api.tensors.Tensor

/** The most basic RNN cell.
  *
  * It is defined as: `output = newState = activation(W * input + U * state + b)`.
  *
  * Input tensors must be two-dimensional.
  *
  * @group RNNCellOps
  * @param  kernel     Kernel matrix to use.
  * @param  bias       Bias vector to use.
  * @param  activation Activation function to use.
  * @param  name       Name scope for the created ops.
  *
  * @author Emmanouil Antonios Platanios
  */
class BasicRNNCell[T: TF : IsNotQuantized] protected (
    val kernel: Output[T],
    val bias: Output[T],
    val activation: Output[T] => Output[T],
    val name: String = "BasicRNNCell"
) extends RNNCell[Output[T], Output[T], Shape, Shape] {
  override def outputShape: Shape = {
    bias.shape
  }

  override def stateShape: Shape = {
    bias.shape
  }

  @throws[IllegalArgumentException]
  override def forward(input: Tuple[Output[T], Output[T]]): BasicTuple[T] = {
    Op.nameScope(name) {
      val output = input.output
      val state = input.state
      if (output.rank != 2)
        throw new IllegalArgumentException(s"Input must be rank-2 (provided rank-${output.rank}).")
      if (output.shape(1) == -1)
        throw new IllegalArgumentException(s"Last axis of input shape (${output.shape}) must be known.")
      val linear = NN.addBias(Math.matmul(
        Basic.concatenate(Seq(output, state), axis = Tensor.ones[Int](Shape()).toOutput),
        kernel
      ), bias)
      val newOutput = activation(linear)
      Tuple(newOutput, newOutput)
    }
  }
}

object BasicRNNCell {
  def apply[T: TF : IsNotQuantized](
      kernel: Output[T],
      bias: Output[T],
      activation: Output[T] => Output[T],
      name: String = "BasicRNNCell"
  ): BasicRNNCell[T] = {
    new BasicRNNCell(kernel, bias, activation, name)
  }
}


text:
from future import standard_library
standard_library.install_aliases()
import sst
import sst.actions

from urllib.parse import urlparse

sst.actions.set_base_url('http://localhost:%s/' % sst.DEVSERVER_PORT)
# haven't visited a url yet, so all assert_url* fail
sst.actions.fails(
    sst.actions.assert_url, 'http://localhost:%s/' % sst.DEVSERVER_PORT)
sst.actions.fails(
    sst.actions.assert_url_contains, 'localhost')
sst.actions.fails(
    sst.actions.assert_url_network_location, 'localhost')

# now visit a url and test assertions
sst.actions.go_to('%sbegin' % sst.actions.get_base_url())

sst.actions.assert_url('/begin')
sst.actions.assert_url('/begin/')
sst.actions.assert_url('begin/')
sst.actions.assert_url('http://localhost:%s/begin' % sst.DEVSERVER_PORT)
sst.actions.assert_url('http://localhost:%s/begin/' % sst.DEVSERVER_PORT)
sst.actions.assert_url(urlparse('http://wrongurl/begin').path)
sst.actions.fails(sst.actions.assert_url, 'http://wrongurl/begin')

sst.actions.assert_url_contains('http://localhost:%s/begin'
                                % sst.DEVSERVER_PORT)
sst.actions.assert_url_contains('localhost:%s' % sst.DEVSERVER_PORT)
sst.actions.assert_url_contains('.*/begin', regex=True)
sst.actions.assert_url_contains('http://.*/begin', regex=True)
sst.actions.assert_url_contains('.*//localhost', regex=True)
sst.actions.assert_url_contains('lo[C|c]a.*host', regex=True)
sst.actions.fails(sst.actions.assert_url_contains, 'foobar')
sst.actions.fails(sst.actions.assert_url_contains, 'foobar', regex=True)

sst.actions.assert_url_network_location('localhost:%s' % sst.DEVSERVER_PORT)
sst.actions.fails(sst.actions.assert_url_network_location, 'localhost')
sst.actions.fails(sst.actions.assert_url_network_location, '')

# visit url with query strings and fragments, then test assertions
sst.actions.go_to('/begin?query_string#fragment_id')

sst.actions.assert_url(
    'http://localhost:%s/begin?query_string#fragment_id' % sst.DEVSERVER_PORT)
sst.actions.assert_url('/begin?query_string#fragment_id')
sst.actions.fails(sst.actions.assert_url, '/begin')
sst.actions.fails(
    sst.actions.assert_url, 'http://localhost:%s/begin' % sst.DEVSERVER_PORT)