text:
/* global page, Location, Page, Vitamin, Search, Prescription, Artist, User, Elem, View, Log, document, Utils */
(function() {

    var init = function(ctx, next) {
	var params = Utils.search(ctx.querystring);
	var query = params.q;

	if (!query) {
	    next();
	    return;
	}

	Search.query('count', {
	    q: query
	}, function(err, data) {
	    if (err) {
		Log.error(err);
		next();
		return;
	    }

	    data.query = query;
	    ctx.state.search = data;
	    ctx.save();
	    next();
	});
    };

    var read = function(ctx) {

	var offset = 0;

	var load = function() {

	    var params = Utils.search(ctx.querystring);
	    var query = params.q;

	    var r = document.getElementById('river');

	    if (!query) {

		View.scrollOff();
		delete r.dataset.loading;

		return;
	    }

	    var input = document.getElementById('search').firstChild;
	    input.value = query || '';

	    var l = r.querySelector('.list');

	    var subpath = ctx.params.subpath || 'top';

	    if (Utils.isUrl(query) && subpath === 'top') {
		Page.create(query, function(err, page) {
		    if (err) {
			Log.error(err);
			r.dataset.loadingError = true;
			return;
		    }

		    var frag = document.createDocumentFragment();
		    frag.appendChild(Page.render(page, { subscribe: true, meta: true }));

		    page.vitamins.forEach(function(v) {
			frag.appendChild(Vitamin.render(v));
		    });

		    l.appendChild(frag);

		    View.scrollOff();
		    delete r.dataset.loading;
		});
	    } else if (query) {
		Search.query(subpath, {
		    offset: offset,
		    q: query,
		    limit: subpath === 'top' ? 5 : 10
		}, function(err, data) {
		    if (err) {
			Log.error(err);
			r.dataset.loadingError = true;
			return;
		    }

		    var frag = document.createDocumentFragment();

		    if (data.length && subpath === 'top') {
			frag.appendChild(Elem.create({
			    className: 'h _d',
			    childs: [{
				tag: 'a',
				text: 'Top Results'
			    }]
			}));
		    }

		    var handler;

		    switch(subpath) {
		    case 'top':
			handler = function(i) {
			    if (typeof i.duration !== 'undefined') {
				frag.appendChild(Vitamin.render(i));
			    } else if (i.url) {
				frag.appendChild(Page.render(i, { subscribe: true, meta: true }));
			    } else if (i.description) {
				frag.appendChild(Prescription.render(i));
			    } else if (i.username) {
				frag.appendChild(User.render(i, { subscribe: true, bio: true }));
			    } else if (typeof i.artist_city !== 'undefined') {
				frag.appendChild(Artist.render(i));
			    }
			    frag.appendChild(Elem.create({className: 'i-divider'}));
			};
			break;
		    case 'artists':
			handler = function(i) {
			    frag.appendChild(Artist.render(i));
			};
			break;
		    case 'pages':
			handler = function(i) {
			    frag.appendChild(Page.render(i, { subscribe: true, meta: true }));
			};
			break;
		    case 'users':
			handler = function(i) {
			    frag.appendChild(User.render(i, { subscribe: true, bio: true }));
			};
			break;
		    case 'prescriptions':
			handler = function(i) {
			    frag.appendChild(Prescription.render(i));
			};
			break;
		    case 'vitamins':
			handler = function(i) {
			    frag.appendChild(Vitamin.render(i));
			};
			break;
		    }

		    data.forEach(handler);

		    if (data.length < 10 || subpath === 'top') View.scrollOff();
		    offset += data.length;

		    if (!data.length) l.setAttribute('empty', 'no results');

		    l.appendChild(frag);

		    delete r.dataset.loading;
		});
	    } else {
		delete r.dataset.loading;
	    }
	};

	View.render({
	    id: '/search.html',
	    data: ctx.state.search || {},
	    load: load
	});

	var form = document.getElementById('search');
	var input = form.firstChild;

	View.active('[href="/search"]');

	form.onsubmit = function() {

	    var search = input.value;

	    page('/search/top?q=' + encodeURIComponent(search));

	    return false;
	};

	input.focus();
    };

    page('/search/:subpath?', init, read);

})();

redpajama_set_name: RedPajamaGithub


text:
package format

import (
	"github.com/trivago/gollum/core"
	"testing"
)

func TestFormatters(t *testing.T) {
	formatters := core.TypeRegistry.GetRegistered("format.")

	if len(formatters) == 0 {
		t.Error("No formatters defined")
	}

	for _, name := range formatters {
		conf := core.NewPluginConfig("", name)
		_, err := core.NewPluginWithConfig(conf)
		if err != nil {
			t.Errorf("Failed to create formatter %s: %s", name, err.Error())
		}
	}
}


text:
import { Stream } from '@most/types';

export function delay<A>(dt: number, s: Stream<A>): Stream<A>;
export function delay<A>(dt: number): (s: Stream<A>) => Stream<A>;


text:
package com.ysu.zyw.tc.components.dubbox.support;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysu.zyw.tc.base.utils.TcSerializationUtils;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.ext.ContextResolver;

@Slf4j
public class TcDubboxJacksonObjectMapperProvider implements ContextResolver<ObjectMapper> {

    @Override
    public ObjectMapper getContext(Class<?> aClass) {
        log.info("start to use tc object mapper as resteasy jaxrs jackson object mapper provider");
        return TcSerializationUtils.OBJECT_MAPPER;
    }

}


text:
class ClParserReal : public ClParserObj {
 protected:
  friend class CRefPtr<ClParserReal>;
  friend class ClParserValue;

 protected:
  static ClParserRealPtr createReal(double real=0.0) {
    ClParserReal *preal = new ClParserReal(real);

    return ClParserRealPtr(preal);
  }

  static ClParserRealPtr createReal(const ClParserReal &real) {
    ClParserReal *preal = new ClParserReal(real);

    return ClParserRealPtr(preal);
  }

  static ClParserRealPtr createReal(ClParserRealPtr real) {
    ClParserReal *preal = new ClParserReal(real);

    return ClParserRealPtr(preal);
  }

  explicit ClParserReal(double real = 0.0) :
   ClParserObj(CL_PARSER_VALUE_TYPE_REAL), real_(real) {
  }

  ClParserReal(const ClParserReal &real) :
   ClParserObj(CL_PARSER_VALUE_TYPE_REAL), real_(real.real_) {
  }

  explicit ClParserReal(ClParserRealPtr real) :
   ClParserObj(CL_PARSER_VALUE_TYPE_REAL), real_(real->real_) {
  }

 ~ClParserReal() { }

  ClParserReal &operator=(const ClParserReal &real) {
    real_ = real.real_;

    return *this;
  }

  ClParserReal *dup() const override;

 public:
  static const ClParserReal &castObj(const ClParserObj &obj) {
    assert(obj.getBaseType() == CL_PARSER_VALUE_TYPE_REAL);

    return reinterpret_cast<const ClParserReal &>(obj);
  }

  void copy(const ClParserObj &obj) override;

  //--------

  double getValue() const { return real_; }

  const double *getValueP() const { return &real_; }

  void setValue(double real) { real_ = real; }

  bool isNanValue() const;

  long getInteger() const;

  bool toBool() const override;

  //------

  std::string asString() const override;

  void print() const override;
  void print(std::ostream &os) const override;

  void debugPrint() const override;

  //------

  int cmp(const ClParserObj &rhs) const override;

  //------

  // Inline Ops

  const ClParserObj &increment() override;
  const ClParserObj &decrement() override;

  //------

  // Unary Ops

  ClParserValuePtr unaryPlus () const override;
  ClParserValuePtr unaryMinus() const override;
  ClParserValuePtr bitNot    () const override;

  //------

  // Binary Ops

  ClParserValuePtr plus(const ClParserObj &obj) const override;
  ClParserValuePtr minus(const ClParserObj &obj) const override;
  ClParserValuePtr times(const ClParserObj &obj) const override;
  ClParserValuePtr divide(const ClParserObj &obj) const override;
  ClParserValuePtr modulus(const ClParserObj &obj) const override;
  ClParserValuePtr power(const ClParserObj &obj) const override;
  ClParserValuePtr approxEqual(const ClParserObj &obj) const override;
  ClParserValuePtr bitAnd(const ClParserObj &obj) const override;
  ClParserValuePtr bitOr(const ClParserObj &obj) const override;
  ClParserValuePtr bitXor(const ClParserObj &obj) const override;
  ClParserValuePtr bitLShift(const ClParserObj &obj) const override;
  ClParserValuePtr bitRShift(const ClParserObj &obj) const override;

  //------

  // Internal Fns

  ClParserValuePtr abs     () const override;
  ClParserValuePtr ceil    () const override;
  ClParserValuePtr floor   () const override;
  ClParserValuePtr sign    () const override;
  ClParserValuePtr sqr     () const override;
  ClParserValuePtr sqrt    () const override;
  ClParserValuePtr cos     () const override;
  ClParserValuePtr sin     () const override;
  ClParserValuePtr tan     () const override;
  ClParserValuePtr acos    () const override;
  ClParserValuePtr asin    () const override;
  ClParserValuePtr atan    () const override;
  ClParserValuePtr atan    (double real) const override;
  ClParserValuePtr exp     () const override;
  ClParserValuePtr log     () const override;
  ClParserValuePtr log10   () const override;
  ClParserValuePtr cosh    () const override;
  ClParserValuePtr sinh    () const override;
  ClParserValuePtr tanh    () const override;
  ClParserValuePtr norm    () const override;
  ClParserValuePtr invnorm () const override;
  ClParserValuePtr toChar  () const override;
  ClParserValuePtr toInt   () const override;
  ClParserValuePtr toReal  () const override;
  ClParserValuePtr toString() const override;
  ClParserValuePtr isNan   () const override;
  ClParserValuePtr toLower () const override;
  ClParserValuePtr toUpper () const override;
  ClParserValuePtr min     () const override;
  ClParserValuePtr max     () const override;
  ClParserValuePtr sum     () const override;

  ClParserValuePtr index (const ClParserObj &obj) const override;
  ClParserValuePtr rindex(const ClParserObj &obj) const override;

  ClParserValuePtr sort(ClParserSortDirection direction) const override;

  ClParserValuePtr doAssert() const override;

 private:
  long ival() const;

 private:
  double real_ { 0.0 };
};

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content">

    <ViewSwitcher
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/soft_q_view_switcher"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/soft_q_add_q"
                android:background="@android:drawable/ic_input_add"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/soft_q_selector"
                android:layout_centerInParent="true"
                android:spinnerMode="dropdown" />
        </RelativeLayout>

    </ViewSwitcher>

</RelativeLayout><!-- From: file:/home/otf/code/AssesorTron/app/src/main/res/layout/soft_q_control_block.xml -->


text:
package org.cirdles.topsoil.app.dataset;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.cirdles.topsoil.app.dataset.reader.RawDataReader;
import org.cirdles.topsoil.app.dataset.reader.TsvRawDataReader;
import org.cirdles.topsoil.app.dataset.writer.RawDataWriter;
import org.cirdles.topsoil.app.dataset.writer.TsvRawDataWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by johnzeringue on 9/3/15.
 */
public class RawDataHandler extends BaseTypeHandler<RawData> {

    private static final Logger LOGGER
            = LoggerFactory.getLogger(RawDataHandler.class);

    private final RawDataReader rawDataReader;
    private final RawDataWriter rawDataWriter;

    public RawDataHandler() {
        rawDataReader = new TsvRawDataReader();
        rawDataWriter = new TsvRawDataWriter();
    }

    @Override
    public void setNonNullParameter(
            PreparedStatement preparedStatement,
            int index,
            RawData rawData,
            JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(index, rawDataWriter.write(rawData));
        } catch (IOException ex) {
            LOGGER.error(null, ex);
            throw new RuntimeException(ex);
        }
    }

    @Override
    public RawData getNullableResult(
            ResultSet resultSet,
            String columnName) throws SQLException {
        try {
            return rawDataReader.read(resultSet.getString(columnName));
        } catch (IOException ex) {
            LOGGER.error(null, ex);
            throw new RuntimeException(ex);
        }
    }

    @Override
    public RawData getNullableResult(
            ResultSet resultSet,
            int columnIndex) throws SQLException {
        try {
            return rawDataReader.read(resultSet.getString(columnIndex));
        } catch (IOException ex) {
            LOGGER.error(null, ex);
            throw new RuntimeException(ex);
        }
    }

    @Override
    public RawData getNullableResult(
            CallableStatement callableStatement,
            int columnIndex) throws SQLException {
        try {
            return rawDataReader.read(callableStatement.getString(columnIndex));
        } catch (IOException ex) {
            LOGGER.error(null, ex);
            throw new RuntimeException(ex);
        }
    }

}


text:
import sys
import os
import platform
import random
import shlex
import re

from chip.setup_payload import SetupPayload
from chip import exceptions

if platform.system() == 'Darwin':
    from chip.ChipCoreBluetoothMgr import CoreBluetoothManager as BleManager
elif sys.platform.startswith('linux'):
    from chip.ChipBluezMgr import BluezManager as BleManager

import logging
log = logging.getLogger(__name__)

class ParsingError(exceptions.ChipStackException):
    def __init__(self, msg=None):
        self.msg = "Parsing Error: " + msg

    def __str__(self):
        return self.msg

def get_device_details(device):
    """
    Get device details from logs
    :param device: serial device instance
    :return: device details dictionary or None
    """
    ret = device.wait_for_output("SetupQRCode")
    if ret == None or len(ret) < 2:
        return None

    qr_code = re.sub(
        r"[\[\]]", "", ret[-1].partition("SetupQRCode:")[2]).strip()
    try:
        device_details = dict(SetupPayload().ParseQrCode(
            "VP:vendorpayload%{}".format(qr_code)).attributes)
    except exceptions.ChipStackError as ex:
        log.error(ex.msg)
        return None

    return device_details

def ParseEncodedString(value):
    if value.find(":") < 0:
        raise ParsingError(
            "Value should be encoded in encoding:encodedvalue format")
    enc, encValue = value.split(":", 1)
    if enc == "str":
        return encValue.encode("utf-8") + b'\x00'
    elif enc == "hex":
        return bytes.fromhex(encValue)
    raise ParsingError("Only str and hex encoding is supported")

def ParseValueWithType(value, type):
    if type == 'int':
        return int(value)
    elif type == 'str':
        return value
    elif type == 'bytes':
        return ParseEncodedString(value)
    elif type == 'bool':
        return (value.upper() not in ['F', 'FALSE', '0'])
    else:
        raise ParsingError('Cannot recognize type: {}'.format(type))

def FormatZCLArguments(args, command):
    commandArgs = {}
    for kvPair in args:
        if kvPair.find("=") < 0:
            raise ParsingError("Argument should in key=value format")
        key, value = kvPair.split("=", 1)
        valueType = command.get(key, None)
        commandArgs[key] = ParseValueWithType(value, valueType)
    return commandArgs

def send_zcl_command(devCtrl, line):
    """
    Send ZCL message to device:
    <cluster> <command> <nodeid> <endpoint> <groupid> [key=value]...
    :param devCtrl: device controller instance
    :param line: command line
    :return: error code and command responde
    """
    res = None
    err = 0
    try:
        args = shlex.split(line)
        all_commands = devCtrl.ZCLCommandList()
        if len(args) < 5:
            raise exceptions.InvalidArgumentCount(5, len(args))

        if args[0] not in all_commands:
            raise exceptions.UnknownCluster(args[0])
        command = all_commands.get(args[0]).get(args[1], None)
        # When command takes no arguments, (not command) is True
        if command == None:
            raise exceptions.UnknownCommand(args[0], args[1])
        err, res = devCtrl.ZCLSend(args[0], args[1], int(
            args[2]), int(args[3]), int(args[4]), FormatZCLArguments(args[5:], command), blocking=True)
        if err != 0:
            log.error("Failed to send ZCL command [{}] {}.".format(err, res))
        elif res != None:
            log.info("Success, received command response:")
            log.info(res)
        else:
            log.info("Success, no command response.")
    except exceptions.ChipStackException as ex:
        log.error("An exception occurred during processing ZCL command:")
        log.error(str(ex))
        err = -1
    except Exception as ex:
        log.error("An exception occurred during processing input:")
        log.error(str(ex))
        err = -1

    return (err, res)

def scan_chip_ble_devices(devCtrl):
    """
    BLE scan CHIP device
    BLE scanning for 10 seconds and collect the results
    :param devCtrl: device controller instance
    :return: List of visible BLE devices
    """
    devices = []
    bleMgr = BleManager(devCtrl)
    bleMgr.scan("-t 10")

    for device in bleMgr.peripheral_list:
        devIdInfo = bleMgr.get_peripheral_devIdInfo(device)
        if devIdInfo:
            devInfo = devIdInfo.__dict__
            devInfo["name"] = device.Name
            devices.append(devInfo)

    return devices

def check_chip_ble_devices_advertising(devCtrl, name, deviceDetails=None):
    """
    Check if CHIP device advertise
    BLE scanning for 10 seconds and compare with device details
    :param devCtrl: device controller instance
    :param name: device advertising name
    :param name: device details
    :return: True if device advertise else False
    """
    ble_chip_device = scan_chip_ble_devices(devCtrl)
    if ble_chip_device == None or len(ble_chip_device) == 0:
        log.info("No BLE CHIP device found")
        return False

    chip_device_found = False

    for ble_device in ble_chip_device:
        if deviceDetails != None:
            if (ble_device["name"] == name and
                int(ble_device["discriminator"]) == int(deviceDetails["Discriminator"]) and
                int(ble_device["vendorId"]) == int(deviceDetails["VendorID"]) and
                    int(ble_device["productId"]) == int(deviceDetails["ProductID"])):
                chip_device_found = True
                break
        else:
            if (ble_device["name"] == name):
                chip_device_found = True
                break

    return chip_device_found

def connect_device_over_ble(devCtrl, discriminator, pinCode, nodeId=None):
    """
    Connect to Matter accessory device over BLE
    :param devCtrl: device controller instance
    :param discriminator: CHIP device discriminator
    :param pinCode: CHIP device pin code
    :param nodeId: default value of node ID
    :return: node ID is provisioning successful, otherwise None
    """
    if nodeId == None:
        nodeId = random.randint(1, 1000000)

    try:
        devCtrl.ConnectBLE(int(discriminator), int(pinCode), int(nodeId))
    except exceptions.ChipStackException as ex:
        log.error("Connect device over BLE failed: {}".format(str(ex)))
        return None

    return nodeId

def close_connection(devCtrl, nodeId):
    """
    Close the BLE connection
    :param devCtrl: device controller instance
    :return: true if successful, otherwise false
    """
    try:
        devCtrl.CloseSession(nodeId)
    except exceptions.ChipStackException as ex:
        log.error("Close session failed: {}".format(str(ex)))
        return False

    return True

def close_ble(devCtrl):
    """
    Close the BLE connection
    :param devCtrl: device controller instance
    :return: true if successful, otherwise false
    """
    try:
        devCtrl.CloseBLEConnection()
    except exceptions.ChipStackException as ex:
        log.error("Close BLE connection failed: {}".format(str(ex)))
        return False

    return True

def commissioning_wifi(devCtrl, ssid, password, nodeId):
    """
    Commissioning a Wi-Fi device
    :param devCtrl: device controller instance
    :param ssid: network ssid
    :param password: network password
    :param nodeId: value of node ID
    :return: error code
    """

    # Inject the credentials to the device
    err, res = send_zcl_command(
        devCtrl, "NetworkCommissioning AddOrUpdateWiFiNetwork {} 0 0 ssid=str:{} credentials=str:{} breadcrumb=0 timeoutMs=1000".format(nodeId, ssid, password))
    if err != 0 and res["Status"] != 0:
        log.error("Set Wi-Fi credentials failed [{}]".format(err))
        return err

    # Enable the Wi-Fi interface
    err, res = send_zcl_command(
        devCtrl, "NetworkCommissioning ConnectNetwork {} 0 0 networkID=str:{} breadcrumb=0 timeoutMs=1000".format(nodeId, ssid))
    if err != 0 and res["Status"] != 0:
        log.error("Enable Wi-Fi failed [{}]".format(err))
        return err

    return err

def resolve_device(devCtrl, nodeId):
    """
    Discover IP address and port of the device.
    :param devCtrl: device controller instance
    :param nodeId: value of node ID
    :return: device IP address and port if successful, otherwise None
    """
    ret = None
    try:
        devCtrl.ResolveNode(int(nodeId))
        ret = devCtrl.GetAddressAndPort(int(nodeId))
        if ret == None:
            log.error("Get address and port failed")
    except exceptions.ChipStackException as ex:
        log.error("Resolve node failed {}".format(str(ex)))

    return ret


text:
using namespace std;

#define MAX_SIZE 256
#define SAFE_DELETE(p) if (p) { delete p; p = NULL; }

const wchar_t *const DOWN = L"down";
const wchar_t *const UP = L"up";
const wchar_t *const LEFT = L"left";
const wchar_t *const RIGHT = L"right";

const wchar_t *const MOVE = L"move";
const wchar_t *const WALK = L"walk";

class AbstractNode
{
public:
     virtual wchar_t *Interpret() = 0;
};

class AndNode : public AbstractNode
{
public:
     AndNode(AbstractNode *left, AbstractNode *right) : m_pLeft(left), m_pRight(right){}

     wchar_t *Interpret()
     {
          wchar_t *pResult = new wchar_t[MAX_SIZE];
          memset(pResult, 0, MAX_SIZE * sizeof(wchar_t));

          wchar_t *pLeft = m_pLeft->Interpret();
          wchar_t *pRight = m_pRight->Interpret();
          wcscat_s(pResult, MAX_SIZE, pLeft);
          wcscat_s(pResult, MAX_SIZE, pRight);

          SAFE_DELETE(pLeft);
          SAFE_DELETE(m_pRight);

          return pResult;
     }

private:
     AbstractNode *m_pLeft;
     AbstractNode *m_pRight;
};

class SentenceNode : public AbstractNode
{
public:
     SentenceNode(AbstractNode *direction, AbstractNode *action, AbstractNode *distance) :
          m_pDirection(direction), m_pAction(action), m_pDistance(distance){}

     wchar_t *Interpret()
     {
          wchar_t *pResult = new wchar_t[MAX_SIZE];
          memset(pResult, 0, MAX_SIZE * sizeof(wchar_t));

          wchar_t *pDirection = m_pDirection->Interpret();
          wchar_t *pAction = m_pAction->Interpret();
          wchar_t *pDistance = m_pDistance->Interpret();
          wcscat_s(pResult, MAX_SIZE, pDirection);
          wcscat_s(pResult, MAX_SIZE, pAction);
          wcscat_s(pResult, MAX_SIZE, pDistance);

          SAFE_DELETE(pDirection);
          SAFE_DELETE(pAction);
          SAFE_DELETE(pDistance);

          return pResult;
     }

private:
     AbstractNode *m_pDirection;
     AbstractNode *m_pAction;
     AbstractNode *m_pDistance;
};

class DirectionNode : public AbstractNode
{
public:
     DirectionNode(wchar_t *direction) : m_pDirection(direction){}

     wchar_t *Interpret()
     {
          wchar_t *pResult = new wchar_t[MAX_SIZE];
          memset(pResult, 0, MAX_SIZE * sizeof(wchar_t));

          if (!_wcsicmp(m_pDirection, DOWN))
          {
               wcscat_s(pResult, MAX_SIZE, L"ÏòÏÂ");
          }
          else if (!_wcsicmp(m_pDirection, UP))
          {
               wcscat_s(pResult, MAX_SIZE, L"ÏòÉÏ");
          }
          else if (!_wcsicmp(m_pDirection, LEFT))
          {
               wcscat_s(pResult, MAX_SIZE, L"Ïò×ó");
          }
          else if (!_wcsicmp(m_pDirection, RIGHT))
          {
               wcscat_s(pResult, MAX_SIZE, L"ÏòÓÒ");
          }
          else
          {
               wcscat_s(pResult, MAX_SIZE, L"ÎÞЧָÁî");
          }

          SAFE_DELETE(m_pDirection);
          return pResult;
     }

private:
     wchar_t *m_pDirection;
};

class ActionNode : public AbstractNode
{
public:
     ActionNode(wchar_t *action) : m_pAction(action){}

     wchar_t *Interpret()
     {
          wchar_t *pResult = new wchar_t[MAX_SIZE];
          memset(pResult, 0, MAX_SIZE * sizeof(wchar_t));

          if (!_wcsicmp(m_pAction, MOVE))
          {
               wcscat_s(pResult, MAX_SIZE, L"Òƶ¯");
          }
          else if (!_wcsicmp(m_pAction, WALK))
          {
               wcscat_s(pResult, MAX_SIZE, L"×߶¯");
          }
          else
          {
               wcscat_s(pResult, MAX_SIZE, L"ÎÞЧָÁî");
          }

          SAFE_DELETE(m_pAction);
          return pResult;
     }

private:
     wchar_t *m_pAction;
};

class DistanceNode : public AbstractNode
{
public:
     DistanceNode(wchar_t *distance) : m_pDistance(distance){}

     wchar_t *Interpret()
     {
          wchar_t *pResult = new wchar_t[MAX_SIZE];
          memset(pResult, 0, MAX_SIZE * sizeof(wchar_t));

          wcscat_s(pResult, MAX_SIZE, m_pDistance);

          SAFE_DELETE(m_pDistance);
          return pResult;
     }

private:
     wchar_t *m_pDistance;
};

class InstructionHandler
{
public:
     InstructionHandler(wchar_t *instruction) : m_pInstruction(instruction), m_pTree(NULL){}

     void Handle();
     void Output();

private:
     void SplitInstruction(wchar_t **&instruction, int &size);

     wchar_t *m_pInstruction;
     AbstractNode *m_pTree;
};

void InstructionHandler::Handle()
{
     AbstractNode *pLeft = NULL;
     AbstractNode *pRight = NULL;
     AbstractNode *pDirection = NULL;
     AbstractNode *pAction = NULL;
     AbstractNode *pDistance = NULL;

     vector<AbstractNode *> node; // Store the instruction expression

     // Split the instruction by " "
     wchar_t **InstructionArray = NULL;
     int size;
     SplitInstruction(InstructionArray, size);
     for (int i = 0; i < size; ++i)
     {
          if (!_wcsicmp(InstructionArray[i], L"and")) // The instruction is composited by two expressions
          {
               wchar_t *pDirectionStr = InstructionArray[++i];
               pDirection = new DirectionNode(pDirectionStr);

               wchar_t *pActionStr = InstructionArray[++i];
               pAction = new ActionNode(pActionStr);

               wchar_t *pDistanceStr = InstructionArray[++i];
               pDistance = new DistanceNode(pDistanceStr);

               pRight = new SentenceNode(pDirection, pAction, pDistance);
               node.push_back(new AndNode(pLeft, pRight));
          }
          else
          {
               wchar_t *pDirectionStr = InstructionArray[i];
               pDirection = new DirectionNode(pDirectionStr);

               wchar_t *pActionStr = InstructionArray[++i];
               pAction = new ActionNode(pActionStr);

               wchar_t *pDistanceStr = InstructionArray[++i];
               pDistance = new DistanceNode(pDistanceStr);

               pLeft = new SentenceNode(pDirection, pAction, pDistance);
               node.push_back(pLeft);
          }
     }

     m_pTree = node[node.size() - 1];
}

void InstructionHandler::Output()
{
     wchar_t *pResult = m_pTree->Interpret();

     setlocale(LC_ALL,"");
     wprintf_s(L"%s\n", pResult);

     SAFE_DELETE(pResult);
}

void InstructionHandler::SplitInstruction(wchar_t **&instruction, int &size)
{
     instruction = new wchar_t*[10];
     memset(instruction, 0, 10 * sizeof( wchar_t*));

     for (int i = 0; i < 10; ++i)
     {
          instruction[i] = new wchar_t[10];
          memset(instruction[i], 0, 10 * sizeof(wchar_t));
     }

     size = 0;
     int n = 0;
     while (*m_pInstruction != L'\0')
     {
          if (*m_pInstruction == L' ')
          {
               size++;
               m_pInstruction++;
               n = 0;
               continue;
          }

          instruction[size][n++] = *m_pInstruction++;
     }
     size++;
}

int main()
{
     wchar_t *pInstructionStr = L"up move 5 and down walk 10";

     InstructionHandler *pInstructionHandler = new InstructionHandler(pInstructionStr);
     pInstructionHandler->Handle();
     pInstructionHandler->Output();

     SAFE_DELETE(pInstructionHandler);
}


text: GET_DIRECTORY_PROPERTY(LF_VALUE LISTFILE_STACK)


text:
micro
=====

Repository for Helferty's micro class


text:
#ifndef RTLD_MACHDEP_H
#define RTLD_MACHDEP_H	1

#include <sys/types.h>
#include <machine/atomic.h>

struct Struct_Obj_Entry;

/* Return the address of the .dynamic section in the dynamic linker. */
#define rtld_dynamic(obj) \
    ((const Elf_Dyn *)((obj)->relocbase + (Elf_Addr)&_DYNAMIC))

/* Fixup the jump slot at "where" to transfer control to "target". */
static inline Elf_Addr
reloc_jmpslot(Elf_Addr *where, Elf_Addr target,
	      const struct Struct_Obj_Entry *obj,
	      const struct Struct_Obj_Entry *refobj, const Elf_Rel *rel)
{
#ifdef dbg
    dbg("reloc_jmpslot: *%p = %p", (void *)(where),
	(void *)(target));
#endif
    (*(Elf_Addr *)(where) = (Elf_Addr)(target));
    return target;
}

#define make_function_pointer(def, defobj) \
	((defobj)->relocbase + (def)->st_value)

#define call_initfini_pointer(obj, target) \
	(((InitFunc)(target))())

#define call_init_pointer(obj, target) \
	(((InitArrFunc)(target))(main_argc, main_argv, environ))

#define round(size, align) \
	(((size) + (align) - 1) & ~((align) - 1))
#define calculate_first_tls_offset(size, align) \
	round(size, align)
#define calculate_tls_offset(prev_offset, prev_size, size, align) \
	round((prev_offset) + (size), align)
#define calculate_tls_end(off, size) 	(off)

typedef struct {
    unsigned long ti_module;
    unsigned long ti_offset;
} tls_index;

void *__tls_get_addr(tls_index *ti) __exported;

#define	RTLD_DEFAULT_STACK_PF_EXEC	PF_X
#define	RTLD_DEFAULT_STACK_EXEC		PROT_EXEC

#endif


text:
package ru.mirea.oop.practice.coursej.tg;

import com.google.common.io.ByteStreams;
import com.google.gson.annotations.SerializedName;
import com.squareup.okhttp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit.Call;
import ru.mirea.oop.practice.coursej.ServiceCreator;
import ru.mirea.oop.practice.coursej.tg.entities.*;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public final class BotClient {
    private static final Logger logger = LoggerFactory.getLogger(BotClient.class);
    public final String url;
    private final TgApi clientApi;
    private final OkHttpClient client;

    public BotClient(String token, OkHttpClient client) {
        this(token, client, "https://api.telegram.org/bot");
    }

    public BotClient(String token, OkHttpClient client, String serverUrl) {
        this.url = serverUrl + token + "/";
        this.client = client;
        this.clientApi = ServiceCreator.createService(client, TgApi.class, serverUrl + token + "/");
    }

    public User getMe() throws IOException {
        return get(clientApi.getMe());
    }

    public Update[] getUpdates() throws IOException {
        return getUpdates(null, null, null);
    }

    public Update[] getUpdates(Integer offset, Integer limit, Integer timeout) throws IOException {
        return get(clientApi.getUpdates(offset, limit, timeout));
    }

    public Message sendMessage(Integer id, String text, Reply reply) throws IOException {
        return get(clientApi.sendMessage(id, text, "Markdown", null, null, reply));
    }

    public Boolean sendChatAction(Integer id, ChatAction action) throws IOException {
        return get(clientApi.sendChatAction(id, action));
    }

    public Message sendSticker(Integer id, String name, InputStream stream) throws IOException {
        return send(client, id, url, "sendSticker", "sticker", name, stream, null);
    }

    public Message sendPhoto(Integer id, String caption, String name, InputStream stream) throws IOException {
        Map<String, String> fields = new HashMap<>();
        fields.put("caption", caption);
        return send(client, id, url, "sendPhoto", "photo", name, stream, fields);
    }

    public Message sendDocument(Integer id, java.io.File file) throws IOException {
        try (InputStream stream = new FileInputStream(file)) {
            return send(client, id, url, "sendDocument", "document", file.getName(), stream, null);
        }
    }

    private static Message send(OkHttpClient client,
                                Integer id,
                                String url,
                                String method,
                                String field,
                                String fieldName,
                                InputStream content,
                                Map<String, String> fields) throws IOException {
        MultipartBuilder builder = new MultipartBuilder();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ByteStreams.copy(content, output);
        builder.addFormDataPart(
                field,
                fieldName,
                RequestBody.create(MediaType.parse("application/octet-stream"), output.toByteArray()));
        builder.addFormDataPart("chat_id", String.valueOf(id));
        if (fields != null) {
            for (Map.Entry<String, String> f : fields.entrySet()) {
                builder.addFormDataPart(f.getKey(), f.getValue());
            }
        }
        builder.type(MultipartBuilder.FORM);
        RequestBody build = builder.build();
        Request request = new Request.Builder()
                .url(HttpUrl.parse(url).newBuilder().addPathSegment(method).build())
                .post(build)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            ResultMessage rm = ServiceCreator.gson.fromJson(response.body().charStream(), ResultMessage.class);
            if (rm != null)
                return rm.result;
        } else {
            String string = response.body().string();
            System.out.println(string);
        }
        return null;
    }

    private final class ResultMessage {
        @SerializedName("result")
        public Message result;
    }

    private static <E> E get(Call<Result<E>> result) throws IOException {
        return Result.call(result);
    }
}


text:
<!DOCTYPE html>
<!--[if IE 8]> 				 <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->

<?php
if ( !isset($path) ) {
	$path = "./";
}

$sitename = 'hazelnut-dev';
$tagline = 'interweb design & development';
if ( isset($pagetitle) ) {
	// Subpages:
	$pagetitle = $pagetitle . ' · ' . $sitename;
	// • • ‹ ‹ · · – –
} else {
	// Homepage:
	$pagetitle = $sitename . ': ' . $tagline;
}
?>

<head>
	<meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />

  <!-- Google Meta Tag Boilerplate: http://support.google.com/webmasters/bin/answer.py?hl=en&answer=79812 -->
  <!-- Important for Google snippet -->
  <meta name="description" content="hazelnut-dev: making the internet more beautiful." />
  <meta name="author"        content="Corey H. Walsh" />
  <meta name="publisher"     content="Corey H. Walsh" />
  <meta name="copyright"     content="2013 Corey H. Walsh" />
  <!-- Enable Google Chrome Frame -->
  <!-- We can also use X-UA-Compatible to force IE to render as an older version of IE -->
  <meta http-equiv="X-UA-Compatible" content="chrome=1" />
  <meta charset="utf-8">
  <meta http-equiv="content-type"    content="text/html; charset=utf-8" />
  <!-- Ask search engines to not cache -->
<!--  <meta http-equiv="cache-control"   content="no-cache" />-->
  <meta name="language"      content="english" />
  <meta name="distribution"  content="global" />
  <!-- Robots tag, default is "index, follow".  Options: index, noindex, follow, nofollow -->
  <!-- "index" allows indexing.  "follow" allows following links to other pages on your site -->
  <!-- http://www.robotstxt.org/meta.html -->
<!--  <meta name="robots"        content="index, follow" />-->
  <meta name="revisit-after" content="2 days" />
<!--  <meta name="fb:app_id"     content="" />-->
  <!-- Canonical Link.  If you have deep links with mostly duplicated content, Google can penalize you for duplicate content. Provide a canonical link with stripped customizations (ie. &color=red). http://davidwalsh.name/canonical-link-rel -->
  <!-- <link rel="canonical" href="" /> -->

  <!-- Open Graph Boilerplate: http://ogp.me/ -->
  <!-- Four Required Properties: -->
  <meta property="og:title" content="<?php echo $pagetitle ?>"/>
  <meta property="og:type" content="website"/>
  <!-- Image when shared. Square, JPG/PNG, 50x50px minimum. -->
  <!-- <meta property="og:image" content="http://designemcee.com/apple-touch-icon-144x144-precomposed.png"/> -->
  <!-- Canonical Link -->
  <meta property="og:url" content="">
  <!-- Optional Properties: -->
  <!-- <meta property="og:site_name" content="<?php echo $sitename ?>"/> -->
  <!-- <meta property="og:description" content="" /> -->

  <title><?php echo $pagetitle ?></title>

  <link rel="stylesheet" href="<?php echo $path ?>css/normalize.css" />

  <link rel="stylesheet" href="<?php echo $path ?>css/app.css" />

  <link rel="shortcut icon" href="http://hazelnutdev.com/favicon.ico">

<!--  <script src="<?php echo $path ?>js/vendor/custom.modernizr.js"></script>-->
  	<!-- css transforms -->
	<script src="<?php echo $path ?>js/modernizr.custom.37575.js"></script>

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-42462015-1', 'hzldv.com');
  ga('send', 'pageview');

</script>

</head>
<body>

	<div id="container" class=
		<?php
			echo '"';
			if ( isset($page_class) ) {
				echo $page_class . ' ';
			}
			echo '"';
		?>

	>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>New Test</title>

New Test

	open
	/run/com.vaadin.tests.components.datefield.WidthRecalculationOnEnableStateChange?restartApplication

	click
	vaadin=runcomvaadintestscomponentsdatefieldWidthRecalculationOnEnableStateChange::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[1]/VButton[0]/domChild[0]/domChild[0]

	screenCapture

	disabled

	click
	vaadin=runcomvaadintestscomponentsdatefieldWidthRecalculationOnEnableStateChange::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[1]/VButton[0]/domChild[0]/domChild[0]

	screenCapture

	enabled

	click
	vaadin=runcomvaadintestscomponentsdatefieldWidthRecalculationOnEnableStateChange::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[2]/VButton[0]/domChild[0]/domChild[0]

	screenCapture

	readonly


text:
import { $$ } from "@morleydev/functional-pipe";
import { AppDrivers } from "@morleydev/pauper/app-drivers";
import { GameAction } from "./game-action";
import { GameState } from "./game-state";
import { createEntityComponentReducer } from "@morleydev/pauper/ecs/entity-component.reducer";

export function createReducer(drivers: AppDrivers): (state: GameState, action: GameAction) => GameState {
	const entityComponentReducer = createEntityComponentReducer(drivers.physics.events);
	const physicsReducer = drivers.physics.reducer((state, collisions) => state);
	const logicalReducer = (state: GameState, action: GameAction) => state;

	return (state: GameState, action: any) =>
		$$(state)
			.$(state => physicsReducer(state, action))
			.$(state => entityComponentReducer(state, action))
			.$$(state => logicalReducer(state, action));
}


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

<TITLE>
edu.unc.ils.mrc.hive.admin
</TITLE>

<META NAME="date" CONTENT="2010-07-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package edu.unc.ils.mrc.hive.admin

Class Summary

AdminVocabularies
This class create Sesame Store, Lucene Index and AlphaIndex
 for a SKOS/RDF file

TaggerTrainer
This class train the tagger from a SKOS/RDF file and some domain oriented
 documents which are used like trainning set for KEA algorithm

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
require 'weka/class_builder'

module Weka
  module Core
    module Converters
      include ClassBuilder

      build_classes :ArffLoader,
                    :ArffSaver,
                    :CSVLoader,
                    :CSVSaver,
                    :JSONLoader,
                    :JSONSaver,
                    :C45Loader,
                    :C45Saver,
                    include_concerns: false
    end
  end
end


text:
require('babel-register');
const program = require('commander');
const commands = require('./commands');
const blacklist = require('./helpers/blacklist');

program
  .version('0.4.0');

program
  .command('route [route]>')
  .description('Create a route and all its boilerplate code.')
  .option('-c, --component <component>', 'Specify a custom React component.')
  .option('-d, --delete', 'Delete an existing route.')
  .option('-l, --list', 'List all registered application routes, optionally providing a parent path to check child routes.')
  .action((route, options) => {
    // list all routes
    if (options.list) {
      commands.list(route);
      return;
    }

    // bail if route is blacklisted
    if (blacklist.test(route)) {
      return;
    }

    // delete route
    if (options.delete) {
      commands.remove(route);
      return;
    }

    // parse component option
    const component = typeof options.component === 'undefined'
      ? ''
      : options.component;

    // bail if route has any non-alpha characters and no named component
    if (!/^[a-zA-Z]*$/.test(route) && component === '') {
      console.log('Regex routes must have a named react component. Use --component=CustomName');
      return;
    }

    // perform route creation
    commands.create(route, component);
  });

program
  .command('user <action> <username> [password] [role]')
  .description('Manage user accounts.')
  .action((action, username, password, role) => {
    switch (action) {
      case 'create': {
        const works = false;
        if (works === false) {
          console.log('user methods not available: https://github.com/austingray/reaxpress/issues/8');
          return;
        }
        if (typeof password === 'undefined') {
          console.log('You must provide a password.');
          return;
        }
        commands.user.create(username, password, role, () => {
          process.exit(1);
        });
        break;
      }
      case 'delete': {
        console.log('Coming soon...');
        process.exit(1);
        break;
      }
      default: {
        console.log('Did not recognize the command.');
        process.exit(1);
        break;
      }
    }
  });

program
  .command('model <name>')
  .description('Generate a boilerplate model methods file and add it to the models registry')
  .action((name) => {
    commands.model(name);
  });

program.parse(process.argv);
process.exit(1);


text:
using Todo.Infrastructure.Events;
using System;
using Todo.Infrastructure.Events.Versioning;
using Todo.Domain.Model;

namespace Todo.Domain.Messages.Events
{
    #region ToDoList Events
    public class CreatedToDoListEvent : Event
    {
        public Guid ToDoListId { get; private set; }
        public string Title { get; private set; }
        public string Description { get; private set; }

        public CreatedToDoListEvent(Guid toDoListId, string title, string description)
        {
            ToDoListId = toDoListId;
            Title = title;
            Description = description;
        }
    }

    public class ChangedToDoListDescriptionEvent : Event
    {
        public Guid ToDoListId { get; private set; }
        public string Description { get; private set; }

        public ChangedToDoListDescriptionEvent(Guid toDoListId, string description)
        {
            ToDoListId = toDoListId;
            Description = description;
        }
    }
    #endregion

    #region ToDoItem Events
    [VersionedEvent("AddedNewToDoItemEvent", 0)]
    public class AddedNewToDoItemEvent_V0 : Event
    {
        public Guid ToDoListId { get; private set; }
        public Guid ToDoItemId { get; private set; }
        public DateTime CreationDate { get; private set; }
        public string Description { get; private set; }
        public DateTime? DueDate { get; private set; }
        public int Importance { get; private set; }

        public AddedNewToDoItemEvent_V0(Guid toDoListId, Guid toDoItemId, DateTime creationDate, string description, DateTime? dueDate, int importance)
        {
            ToDoListId = toDoListId;
            ToDoItemId = toDoItemId;
            CreationDate = creationDate;
            Description = description;
            DueDate = dueDate;
            Importance = importance;
        }
    }

    [VersionedEvent("AddedNewToDoItemEvent", 1)]
    public class AddedNewToDoItemEvent : Event
    {
        public Guid ToDoListId { get; private set; }
        public Guid ToDoItemId { get; private set; }
        public DateTime CreationDate { get; private set; }
        public string Description { get; private set; }
        public DateTime? DueDate { get; private set; }
        public int Importance { get; private set; }
        public string AssignedTo { get; private set; }

        public AddedNewToDoItemEvent(Guid toDoListId, Guid toDoItemId, DateTime creationDate, string description, DateTime? dueDate, int importance, string assignedTo)
        {
            ToDoListId = toDoListId;
            ToDoItemId = toDoItemId;
            CreationDate = creationDate;
            Description = description;
            DueDate = dueDate;
            Importance = importance;
            AssignedTo = assignedTo;
        }
    }

    [VersionedEvent("MarkedToDoItemAsCompletedEvent", 0)]
    public class MarkedToDoItemAsCompletedEvent_V0 : Event
    {
        public DateTime ClosingDate { get; private set; }

        public MarkedToDoItemAsCompletedEvent_V0(Guid id, DateTime closingDate)
        {
            Id = id;
            ClosingDate = closingDate;
        }
    }

    [VersionedEvent("MarkedToDoItemAsCompletedEvent", 1)]
    public class MarkedToDoItemAsCompletedEvent : Event
    {
        public DateTime ClosingDate { get; private set; }
        public string AssignedTo { get; private set; }

        public MarkedToDoItemAsCompletedEvent(Guid id, DateTime closingDate, string assignedTo)
        {
            Id = id;
            ClosingDate = closingDate;
            AssignedTo = assignedTo;
        }
    }

    public class ReOpenedToDoItemEvent : Event
    {
        public ReOpenedToDoItemEvent(Guid id)
        {
            Id = id;
        }
    }

    public class ChangedToDoItemImportanceEvent : Event
    {
        public int Importance { get; private set; }

        public ChangedToDoItemImportanceEvent(Guid id, int importance)
        {
            Id = id;
            Importance = importance;
        }
    }

    public class ChangedToDoItemDescriptionEvent : Event
    {
        public string Description { get; private set; }

        public ChangedToDoItemDescriptionEvent(Guid id, string description)
        {
            Id = id;
            Description = description;
        }
    }

    public class ChangedToDoItemDueDateEvent : Event
    {
        public DateTime? DueDate { get; private set; }

        public ChangedToDoItemDueDateEvent(Guid id, DateTime? dueDate)
        {
            Id = id;
            DueDate = dueDate;
        }
    }
    #endregion

    #region Memento Propagation Events
    public class ToDoListMementoPropagatedEvent : Event
    {
        public ToDoListMemento Memento { get; private set; }

        public ToDoListMementoPropagatedEvent(ToDoListMemento memento)
        {
            Memento = memento;
        }
    }

    public class ToDoItemMementoPropagatedEvent : Event
    {
        public ToDoItemMemento Memento { get; private set; }

        public ToDoItemMementoPropagatedEvent(ToDoItemMemento memento)
        {
            Memento = memento;
        }
    }
    #endregion

}


text:
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Cyclist32: React.ForwardRefExoticComponent<
  CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Cyclist32;


text:
package org.kuali.kpme.pm.api.positionappointment;

import org.kuali.kpme.core.api.mo.KpmeEffectiveKeyedDataTransferObject;

/**
 *
PositionAppointmentContract interface

 *
 */
public interface PositionAppointmentContract extends KpmeEffectiveKeyedDataTransferObject {

    /**
     * The primary key for a PositionAppointment entry saved in the database
     *
     *

     * pmPositionAppointmentId for the PositionAppointment.
     *

     *
     * @return pmPositionAppointmentId for PositionAppointment
     */
	public String getPmPositionAppointmentId();

    /**
     * The short text name of the appointment type
     *
     *

     * positionAppointment for the PositionAppointment.
     *

     *
     * @return positionAppointment for PositionAppointment
     */
	public String getPositionAppointment();

    /**
     * The longer text description of the appointment type
     *
     *

     * description for the PositionAppointment.
     *

     *
     * @return description for PositionAppointment
     */
	public String getDescription();
}


text:
using UnityEngine;
using System.Collections;

public class ProteinController : MonoBehaviour {

	public float randomTime;
	public float speed;
	public string text;

	float currentTime=0;
	float left;
	float up;
	float ford;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

		currentTime += Time.deltaTime;

		if(currentTime > randomTime)
		{

			System.Random rand = new System.Random();
			int next = rand.Next (0,6);

			switch (next)
			{
				case 0: left=1;  up=0; ford=0;	break;
				case 1: left=-1; up=0; ford=0;	break;
				case 2: left=0;  up=1; ford=0;	break;
				case 3: left=0;  up=-1; ford=0;	break;
				case 4: left=0;  up=0; ford=1;	break;
				case 5: left=0;  up=0; ford=-1;	break;
			}

			currentTime = 0;
		}

		//this.transform.Translate(new Vector3(left * speed * Time.deltaTime, up *  speed * Time.deltaTime, ford * speed * Time.deltaTime));
		this.transform.Rotate(new Vector3(left, up, ford), speed * 10 * Time.deltaTime);
	}

}


text:
@interface MeasurementComparsionViewController : UIViewController <MFMailComposeViewControllerDelegate>

@property int index;
@property (strong, nonatomic) UIScrollView *measurementScrollView;
@property (nonatomic, strong) UIImageView *measurementImageView;
@property (nonatomic, strong) UIImage *measurementImage;
@property Measurement *moleMeasurement;

@end


text:
<?php

require_once('BaseTModels.class.php');

// t_leadingss テーブルクラス
class Class_Model_TLeadings extends BaseTModels
{
	const TABLE_NAME = 't_leadings';
	protected $_name   = Class_Model_TLeadings::TABLE_NAME;

	public static function fieldArray($prefix = '')
	{
		if ($prefix == '')
			$prefix = Class_Model_TLeadings::TABLE_NAME;

		return array(
			$prefix . '_id' => 'id',
			$prefix . '_t_reserve_id' => 't_reserve_id',
			$prefix . '_submitdate' => 'submitdate',
			$prefix . '_m_member_id_charge' => 'm_member_id_charge',

			$prefix . '_staff_no' => 'staff_no',
			$prefix . '_name_jp' => 'name_jp',

			$prefix . '_counsel' => 'counsel',
			$prefix . '_teaching' => 'teaching',
			$prefix . '_remark' => 'remark',
			$prefix . '_summary' => 'summary',
			$prefix . '_leading_comment' => 'leading_comment',

// 			$prefix . '_createdate' => 'createdate',
// 			$prefix . '_creator' => 'creator',
// 			$prefix . '_lastupdate' => 'lastupdate',
// 			$prefix . '_lastupdater' => 'lastupdater',

			$prefix . '_submit_flag' => 'submit_flag',
			$prefix . '_cancel_flag' => 'cancel_flag',
		);
	}

	private function setJoinField($select)
	{
		$select
				->joinLeft(
					array('reserves' => 't_reserves'),
					'leadings.t_reserve_id = reserves.id',
					Class_Model_TReserves::fieldArray()
				)

				->joinLeft(
					array('shifts' => 'm_shifts'),
					'shifts.id = reserves.m_shift_id',
					Class_Model_MShifts::fieldArray()
				)

				->joinLeft(
					array('dockinds' => 'm_dockinds'),
					'dockinds.id = shifts.m_dockind_id',
					Class_Model_MDockinds::fieldArray()
				)

				->joinLeft(
					array('places' => 'm_places'),
					'places.id = shifts.m_place_id',
					Class_Model_MPlaces::fieldArray()
				)

				->joinLeft(
					array('members' => 'm_members'),
					'leadings.m_member_id_charge = members.id',
					Class_Model_MMembers::fieldArray()
				)
		;

		return $select;
	}

	// 指定の予約者のオブジェクトですべて取得
	public function GetSelectFromMemberId($m_member_id, $limit=0, $order=array())
	{
		$select = $this->select()->setIntegrityCheck(false)
				->from(array('leadings' => $this->_name), '*')

				->where('reserves.m_member_id_reserver = ?', $m_member_id);

		if (count($order) > 0)
			$select->order($order);

		if ($limit > 0)
			$select->limit($limit, 0);

		return $this->setJoinField($select);
	}

	public function selectFromMemberId($m_member_id, $limit=0, $order=array())
	{
		$select = $this->GetSelectFromMemberId($m_member_id, $limit, $order);
		return $this->fetchAll($select);
	}

	// 指定の予約IDを持つオブジェクトですべて取得
	public function selectFromReserveId($t_reserve_id)
	{
		$select = $this->select();

		$select->setIntegrityCheck(false)
				->from(array('leadings' => $this->_name), '*')

				->where('leadings.t_reserve_id = ?', $t_reserve_id);

		return $this->fetchRow($this->setJoinField($select));
	}

	// 指定の予約IDを持つオブジェクトで指導コメント入力済みの行を取得
	public function selectInputCommentFromReserveId($t_reserve_id)
	{
		$select = $this->select();

		$select->setIntegrityCheck(false)
		->from(array('leadings' => $this->_name), '*')

		->where('leadings.t_reserve_id = ?', $t_reserve_id)
		->where('leadings.leading_comment != \'\'');

		return $this->fetchRow($this->setJoinField($select));
	}

	// 指定の予約IDと担当者IDを持つオブジェクトですべて取得
	public function selectFromReserveIdAndMemberId($t_reserve_id, $m_member_id_charge)
	{
		$select = $this->select();

		$select->setIntegrityCheck(false)
				->from(array('leadings' => $this->_name), '*')

				->where('leadings.t_reserve_id = ?', $t_reserve_id)
				->where('leadings.m_member_id_charge = ?', $m_member_id_charge)

				;

		return $this->fetchRow($this->setJoinField($select));
	}

	// 指定の担当者IDを持つオブジェクトですべて取得
	public function selectFromChargeId($m_member_id_charge)
	{
		$select = $this->select();

		$select->setIntegrityCheck(false)
		->from(array('leadings' => $this->_name), '*')

		->where('leadings.m_member_id_charge = ?', $m_member_id_charge)
		;

		return $this->fetchAll($this->setJoinField($select));
	}

	// 指定の担当者、予約日、連番で取得
	public function selectFromChargeIdAndReserve($m_member_id_charge, $reservationdate, $dayno)
	{
		$select = $this->select()->setIntegrityCheck(false)
				->from(
					array('leadings' => $this->_name), "*")

				->where('leadings.m_member_id_charge = ?', $m_member_id_charge)
				->where('shifts.dayno = ?', $dayno)
				->where('reserves.reservationdate = ?', $reservationdate)

				;

		return $this->fetchAll($this->setJoinField($select));
	}

	// 指定予約IDを持つオブジェクトをすべて削除
	public function deleteFromReserveId($t_reserve_id)
	{
		$where = $this->getAdapter()->quoteInto('t_reserve_id = ?' , $t_reserve_id);

		return $this->delete($where);
	}

}


text:
"""
The object graph is the core unit of microcosm-based applications.

Object graphs wire together independently defined `components` using a set
of factory functions and application configuration. Components are bound
to the graph lazily (or via `graph.use()`) and are cached for reuse.

"""
from __future__ import annotations

from contextlib import contextmanager
from typing import (
    Any,
    Callable,
    Iterable,
    List,
    Optional,
    Tuple,
    Type,
)

from microcosm.caching import Cache, create_cache
from microcosm.config.api import configure
from microcosm.config.model import Configuration
from microcosm.constants import RESERVED
from microcosm.errors import CyclicGraphError, LockedGraphError
from microcosm.hooks import invoke_resolve_hook
from microcosm.loaders import load_from_environ
from microcosm.metadata import Metadata
from microcosm.profile import NoopProfiler
from microcosm.registry import Registry, _registry
from microcosm.typing import Component

Factory = Callable[['ObjectGraph'], Component]

class ObjectGraph:
    """
    An object graph contains all of the instantiated components for a microservice.

    Because components can reference each other a-cyclically, this collection of
    components forms a directed acyclic graph.

    """
    def __init__(self, metadata: Metadata, config, registry, profiler, cache, loader) -> None:
        self.metadata = metadata
        self.config = config
        self._locked = False
        self._registry = registry
        self._profiler = profiler
        self._cache = cache
        self.loader = loader

    def use(self, *keys: str) -> List[Component]:
        """
        Explicitly initialize a set of components by their binding keys.

        """
        return [
            getattr(self, key)
            for key in keys
        ]

    def assign(self, key: str, value: Component) -> Component:
        """
        Explicitly assign a graph binding to a value.

        In general, graph values should only be derived from registered factories
        and the graph should not be assigned to; however, there can be exceptions including
        testing and "virtual" bindings, so assign can be used when circumventing setattr.

        """
        self._cache[key] = value
        return value

    def lock(self) -> ObjectGraph:
        """
        Lock the graph so that new components cannot be created.

        """
        self._locked = True
        return self

    def unlock(self) -> ObjectGraph:
        """
        Unlock the graph so that new components can created.

        """
        self._locked = False
        return self

    def factory_for(self, key: str) -> Factory:
        return self._registry.resolve(key)

    def get(self, key: str) -> Component:
        return self._cache.get(key)

    def __getattr__(self, key: str) -> Component:
        """
        Access a component by its binding key.

        If the component is not present, it will be lazily created.

        :raises CyclicGraphError: if the factory function requires a cycle
        :raises LockedGraphError: if the graph is locked

        """
        try:
            component = self._cache[key]
            if component is RESERVED:
                raise CyclicGraphError(key)
            return component
        except KeyError:
            pass

        if self._locked:
            raise LockedGraphError(key)
        return self._resolve_key(key)

    def __setattr__(self, key: str, value: Component) -> None:
        if not key.startswith("_") and key not in ("metadata", "config", "loader"):
            raise Exception("Cannot setattr on ObjectGraph for key: {}".format(key))
        super(ObjectGraph, self).__setattr__(key, value)

    @contextmanager
    def _reserve(self, key: str) -> Any:
        """
        Reserve a component's binding temporarily.

        Protects against cycles.

        """
        self.assign(key, RESERVED)
        try:
            yield
        finally:
            del self._cache[key]

    def _resolve_key(self, key: str) -> Component:
        """
        Attempt to lazily create a component.

        :raises NotBoundError: if the component does not have a bound factory
        :raises CyclicGraphError: if the factory function requires a cycle
        :raises LockedGraphError: if the graph is locked
        """
        with self._reserve(key):
            factory = self.factory_for(key)
            with self._profiler(key):
                component = factory(self)
            invoke_resolve_hook(component)

        return self.assign(key, component)

    def items(self) -> Iterable[Tuple[str, Component]]:
        """
        Iterates over tuples of (key, component) for all bound components.
        """
        yield from self._cache.items()

    __getitem__ = __getattr__

def create_object_graph(
    name: str,
    debug: bool = False,
    testing: bool = False,
    import_name: Optional[str] = None,
    root_path: Optional[str] = None,
    loader: Callable[[Metadata], Configuration] = load_from_environ,
    registry: Registry = _registry,
    profiler: Any = None,
    cache: Optional[Type[Cache]] = None
) -> ObjectGraph:
    """
    Create a new object graph.

    :param name: the name of the microservice
    :param debug: is development debugging enabled?
    :param testing: is unit testing enabled?
    :param import_name: the import name to use for resource loading
    :param root_path: the root path for resource loading
    :param loader: the configuration loader to use
    :param registry: the registry to use (defaults to the global)
    :param profiler:
    :param cache:

    """
    metadata = Metadata(
        name=name,
        debug=debug,
        testing=testing,
        import_name=import_name,
        root_path=root_path,
    )

    defaults = registry.defaults
    config = configure(defaults, metadata, loader)

    if profiler is None:
        profiler = NoopProfiler()

    if cache is None or isinstance(cache, str):
        cache = create_cache(cache)

    return ObjectGraph(
        metadata=metadata,
        config=config,
        registry=registry,
        profiler=profiler,
        cache=cache,
        loader=loader,
    )

def get_component_name(graph: ObjectGraph, component: Component) -> str:
    """
    Given an object that is attached to the graph, it returns the object name.

    """
    return next(
        key
        for key, possible_component in graph.items()
        if possible_component == component
    )


text:
package com.pi.xerosync.util;

import net.oauth.client.OAuthClient;
import net.oauth.client.URLConnectionClient;
import net.oauth.http.HttpClient;

/**
 * @author jiakuanwang
 */
public class TimeoutOAuthClient extends OAuthClient {

  public TimeoutOAuthClient() {
    super(new URLConnectionClient());

    getHttpParameters().put(HttpClient.CONNECT_TIMEOUT, 120 * 1000); // 3 minutes
    getHttpParameters().put(HttpClient.READ_TIMEOUT, 120 * 1000); // 3 minutes
  }
}


text:
package util

final class Query(table: String) {
	private val query = Resource("query/" + table + ".sql")

	def apply(q: String) = query(q).get
}

object Query {
	def apply(table: String) = new Query(table)
}


text:
module op.toolbar {
    'use strict';

    angular.module('op.common', [
        /* Core */
        'ngMaterial',
        /* Third party */
        'LocalStorageModule',
        'ngFileUpload'
    ]);
}


text:
namespace Phonebook
{
    using System;
    using System.Text;

    public class PhonebookEntry
    {
        public PhonebookEntry(
            string firstName,
            string middleName,
            string lastName,
            string nickname,
            string town,
            string phoneNumber)
        {
            this.FirstName = firstName;
            this.MiddleName = middleName;
            this.LastName = lastName;
            this.Nickname = nickname;
            this.Town = town;
            this.PhoneNumber = phoneNumber;
        }

        public string FirstName { get; set; }

        public string MiddleName { get; set; }

        public string LastName { get; set; }

        public string Nickname { get; set; }

        public string Town { get; set; }

        public string PhoneNumber { get; set; }

        public static PhonebookEntry Parse(string entry)
        {
            string[] splitted =
                entry.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            string[] names =
                splitted[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            int providedNames = names.Length;

            string firstName = names[0].Trim();

            string middleName = null;
            if (providedNames > 1)
            {
                middleName = names[1].Trim();
            }

            string lastName = null;
            if (providedNames > 2)
            {
                lastName = names[2].Trim();
            }

            string nickname = null;
            if (providedNames > 3)
            {
                nickname = names[3].Trim();
            }

            PhonebookEntry phonebookEntry =
                new PhonebookEntry(firstName, middleName, lastName, nickname, splitted[1].Trim(), splitted[2].Trim());
            return phonebookEntry;
        }

        public override string ToString()
        {
            StringBuilder output = new StringBuilder();
            output.AppendFormat("[First name: {0}; ", this.FirstName);

            if (this.MiddleName != null)
            {
                output.AppendFormat("Middle name: {0}; ", this.MiddleName);
            }

            if (this.LastName != null)
            {
                output.AppendFormat("Last name: {0}; ", this.LastName);
            }

            if (this.Nickname != null)
            {
                output.AppendFormat("Nickname: {0}; ", this.Nickname);
            }

            output.AppendFormat("Town: {0}; ", this.Town);

            output.AppendFormat("Phone number: {0}]", this.PhoneNumber);

            return output.ToString();
        }
    }
}


text:
using Newtonsoft.Json;

namespace HaloOnline.Server.Core.Http.Model.Messaging
{
    public class SendServiceMessageResult
    {
        [JsonProperty("SendServiceMessageResult")]
        public ServiceResult<bool> Result { get; set; }
    }
}


text:
function Controller() {
    function loadinfoview() {
        $.contactView.removeAllChildren();
        $.contactView.add(Alloy.createController("information").getView());
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "contact";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.contact = Ti.UI.createView({
        id: "contact"
    });
    $.__views.contact && $.addTopLevelView($.__views.contact);
    $.__views.contactView = Ti.UI.createView({
        id: "contactView"
    });
    $.__views.contact.add($.__views.contactView);
    $.__views.backButton = Ti.UI.createButton({
        left: "2%",
        top: "2%",
        width: "30px",
        height: "30px",
        backgroundImage: "/images/back.png",
        id: "backButton"
    });
    $.__views.contactView.add($.__views.backButton);
    loadinfoview ? $.__views.backButton.addEventListener("click", loadinfoview) : __defers["$.__views.backButton!click!loadinfoview"] = true;
    $.__views.__alloyId17 = Ti.UI.createLabel({
        font: {
            fontSize: "15sp"
        },
        text: "This is the contact information view.",
        id: "__alloyId17"
    });
    $.__views.contactView.add($.__views.__alloyId17);
    exports.destroy = function() {};
    _.extend($, $.__views);
    __defers["$.__views.backButton!click!loadinfoview"] && $.__views.backButton.addEventListener("click", loadinfoview);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
var assert = require('assert')
  , Stream = require('stream')
  , fs = require('fs')
  , mongo = require('mongodb')
  , Grid = require('../')
  , crypto = require('crypto')
  , checksum = require('checksum')
  , tmpDir = __dirname + '/tmp/'
  , fixturesDir = __dirname + '/fixtures/'
  , imgReadPath = fixturesDir + 'mongo.png'
  , txtReadPath =fixturesDir + 'text.txt'
  , emptyReadPath = fixturesDir + 'emptydoc.txt'
  , largeBlobPath = tmpDir + '1mbBlob'
  , server
  , db

describe('test', function(){
  var id;
  before(function (done) {
    server = new mongo.Server('localhost', 27017);
    db = new mongo.Db('gridstream_test', server, {w:1});
    if (!fs.existsSync(tmpDir)) {
      fs.mkdirSync(tmpDir);
    }
    fs.writeFile(largeBlobPath, crypto.randomBytes(1024*1024), function (err) {
      if (err) {
        done(err);
      }
      db.open(done)
    });
  });

  describe('Grid', function () {
    it('should be a function', function () {
      assert('function' == typeof Grid);
    });
    it('should create instances without the new keyword', function () {
      var x = Grid(2,3);
      assert(x instanceof Grid);
    });
    it('should store the arguments', function () {
      var x = new Grid(4, 5);
      assert.equal(x.db, 4);
      assert.equal(x.mongo, 5);
    });
    it('should require mongo argument', function(){
      assert.throws(function () {
        new Grid(3)
      }, /missing mongo argument/);
    })
    it('should require db argument', function(){
      assert.throws(function () {
        new Grid(null, 3)
      }, /missing db argument/);
    })
    describe('files', function(){
      it('returns a collection', function(){
        var g = new Grid(db, mongo);
        assert(g.files instanceof mongo.Collection);
      })
    })
    describe('collection()', function(){
      it('changes the files collection', function(){
        var g = new Grid(db, mongo);
        assert.equal('function', typeof g.collection);
        assert(g.collection() instanceof mongo.Collection);
        assert.equal(g.collection(), g.files);
        var old = g.collection();
        g.collection('changed');
        assert(g.collection() instanceof mongo.Collection);
        assert.ok(g.collection() == g.files);
        assert.ok(g.collection() != old);
        assert.equal(g.collection(), g.files);
        assert.equal(g.collection().collectionName, 'changed.files');
      })
    })
  });

  describe('createWriteStream', function(){
    it('should be a function', function () {
      var x = Grid(1, mongo);
      assert('function' == typeof x.createWriteStream);
    });
  })

  describe('GridWriteStream', function(){
    var g
      , ws

    before(function(){
      Grid.mongo = mongo;
      g = Grid(db);
      ws = g.createWriteStream({ filename: 'logo.png' });
    });

    it('should be an instance of Stream', function(){
      assert(ws instanceof Stream);
    })
    it('should be an instance of Stream.Writable', function(){
      assert(ws instanceof Stream.Writable);
    })
    it('should should be writable', function(){
      assert(ws.writable);
    });
    it('should store the grid', function(){
      assert(ws._grid == g)
    });
    it('should have an id', function(){
      assert(ws.id)
    })
    it('id should be an ObjectId', function(){
      assert(ws.id instanceof mongo.ObjectID);
    });
    it('should have a name', function(){
      assert(ws.name == 'logo.png')
    })
    describe('options', function(){
      it('should have one key', function(){
        assert(Object.keys(ws.options).length === 1);
      });
      it('should have filename option', function(){
        assert(ws.options.filename === 'logo.png');
      });
    })
    it('mode should default to w', function(){
      assert(ws.mode == 'w');
    })
    describe('store', function(){
      it('should be an instance of mongo.GridStore', function(){
        assert(ws._store instanceof mongo.GridStore)
      })
    })
    describe('#methods', function(){
      describe('write', function(){
        it('should be a function', function(){
          assert('function' == typeof ws.write)
        })
      })
      describe('end', function(){
        it('should be a function', function(){
          assert('function' == typeof ws.end)
        })
      })
      describe('destroy', function(){
        it('should be a function', function(){
          assert('function' == typeof ws.destroy)
        })
      })
    });
    it('should provide piping from a readableStream into GridFS', function(done){
      var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 });
      var ws = g.createWriteStream({ filename: 'logo.png'});

      // used in readable stream test
      id = ws.id;

      var progress = 0;
      var finished = false;
      var opened = false;
      var closed = false;
      var file;

      ws.on('progress', function (size) {
        progress = size;
      });

      ws.on('open', function () {
        opened = true;
      });

      ws.on('close', function (file_) {
        closed = true;
        file = file_;
      });

      ws.on('finish', function () {
        assert(opened);
        assert(progress > 0);
        assert(closed);
        assert(file.filename === 'logo.png');
        assert(file._id === id);
        assert(file.length === fs.readFileSync(imgReadPath).length);
        done();
      });

      var pipe = readStream.pipe(ws);
    });
    it('should provide Error and File object on WriteStream close event', function(done){
      var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 });
      var ws = g.createWriteStream({
        mode: 'w',
        filename: 'closeEvent.png',
        content_type: "image/png"
      });
      // used in readable stream test
      id = ws.id;

      var progress = 0;

      ws.on('progress', function (size) {
        progress = size;
      });

      ws.on('close', function (file) {
        assert(file.filename === 'closeEvent.png')
        assert(file.contentType === 'image/png')
        assert(progress > 0);
        done();
      });
      var pipe = readStream.pipe(ws);
    });

    //W+ not supported in new mongodb v2 gridstore driver
    it.skip('should pipe more data to an existing GridFS file', function(done){
      function pipe (id, cb) {
        if (!cb) cb = id, id = null;
        var readStream = fs.createReadStream(txtReadPath);
        var ws = g.createWriteStream({
          _id: id,
          mode: 'w+' });
        ws.on('close', function () {
          cb(ws.id);
        });
        readStream.pipe(ws);
      }

      pipe(function (id) {
        pipe(id, function (id) {
          // read the file out. it should consist of two copies of original
          mongo.GridStore.read(db, id, function (err, txt) {
            if (err) return done(err);
            assert.equal(txt.length, fs.readFileSync(txtReadPath).length*2);
            done();
          });
        });
      })
    });

    it('should be able to store a 12-letter file name', function() {
      var ws = g.createWriteStream({ filename: '12345678.png' });
      assert.equal(ws.name,'12345678.png');
    });

    it("shouldn't clobber filename when rewriting to an existing file by id", function(done){
      var ws = g.createWriteStream({
        mode: 'w',
        filename: 'filename.txt',
        content_type: 'text/plain'
      });
      var rewrite_id = ws.id;
      ws.write("Some text\n");
      ws.end();

      ws.on('close', function () {
        // Rewrite the same file by _id
        var ws2 = g.createWriteStream({
          _id: rewrite_id,
          mode: 'w'
        });
        ws2.write("Some more text\n");
        ws2.end();

        ws2.on('close', function () {
          g.exist({ _id: rewrite_id }, function (err, result) {
            if (err) return done(err);
            assert.ok(result);
            g.exist({ filename: "filename.txt" }, function (err, result) {
              if (err) return done(err);
              assert.ok(result);
              done();
            });
          });
        });
      });
    });

    it('should be able to store an empty file', function(done){
      var readStream = fs.createReadStream(emptyReadPath);
      var ws = g.createWriteStream({
        mode: 'w',
        filename: 'closeEvent.txt',
        content_type: "text/plain"
      });

      ws.on('close', function (file) {
        assert(file.filename === 'closeEvent.txt')
        assert(file.contentType === 'text/plain')
        done();
      });
      var pipe = readStream.pipe(ws);
    });

    it('should create files with an _id of arbitrary type', function(done){
      var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 });
      var ws = g.createWriteStream({ _id: 'an_arbitrary_id', filename: 'file.img'});

      ws.on('close', function (file) {
        assert(file._id === 'an_arbitrary_id');
        done();
      });

      var pipe = readStream.pipe(ws);
    });

    it('should emit finish after the file exists', function(done){
      var readStream = fs.createReadStream(imgReadPath);
      var ws = g.createWriteStream({ filename: 'logo.png'});

      ws.on('finish', function () {
        var rs = g.createReadStream({_id: id});
        var file = fixturesDir + 'byid.png';
        var writeStream = fs.createWriteStream(file);

        rs.on('error', function (err) {
          // should not happen
          assert(false);
        });

        writeStream.on('finish', function () {
          var buf1 = fs.readFileSync(imgReadPath);
          var buf2 = fs.readFileSync(file);

          assert(buf1.length === buf2.length);

          for (var i = 0, len = buf1.length; i < len; ++i) {
            assert(buf1[i] == buf2[i]);
          }

          fs.unlinkSync(file);
          done();
        });

        rs.pipe(writeStream);
      });

      var pipe = readStream.pipe(ws);
    });

    it('should emit one error on destroy()', function(done){
      var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 });
      var ws = g.createWriteStream({ filename: 'logo.png'});

      var error = new Error('test error from destroy');
      var errorCounter = 0;

      ws.on('error', function (err) {
        errorCounter += 1;
        assert(errorCounter === 1);
        assert(err === error);
        done();
      });

      ws.on('progress', function (progress) {
        ws.destroy(error);
        ws.destroy(); // test multiple destroy call
      });

      var pipe = readStream.pipe(ws);
    });

    it('should emit error on destroy() on nextTick', function(done){
      var ws = g.createWriteStream({ filename: 'logo.png'});

      ws.destroy(new Error('early destroy'));

      ws.on('error', function (err) {
        done();
      });
    });

    it('should emit close if open is emitted on destroy()', function(done){
      var ws = g.createWriteStream({ filename: 'logo.png'});

      var opened = false;
      var error = false;
      ws.on('open', function () {
        opened = true;
      });
      ws.on('close', function () {
        assert(opened);
        assert(error);
        done();
      });

      ws.destroy();

      ws.on('error', function (err) {
        error = true;
      });
    });

  });

  describe('createReadStream', function(){
    it('should be a function', function () {
      var x = Grid(1);
      assert('function' == typeof x.createReadStream);
    });
  });

  describe('GridReadStream', function(){
    var g
      , rs

    before(function(){
      g = Grid(db);
      rs = g.createReadStream({
        filename: 'logo.png'
      });
    });

    it('should create an instance of Stream', function(){
      assert(rs instanceof Stream);
    });
    it('should should be readable', function(){
      assert(rs.readable);
    });
    it('should store the grid', function(){
      assert(rs._grid == g)
    });
    it('should have a name', function(){
      assert(rs.name == 'logo.png')
    })
    it('should not have an id', function(){
      assert.equal(rs.id, null)
    })
    describe('options', function(){
      it('should have no defaults', function(){
        // NOTE: filename is required to avoid a throw here, because you can't create a valid
        // read stream for a non-existing file.
        assert(Object.keys(g.createReadStream({filename: 'logo.png'}).options).length === 1);
      });
    })
    it('mode should default to r', function(){
      assert(rs.mode == 'r');
      assert(rs._store.mode == 'r');
    })

    describe('store', function(){
      it('should be an instance of mongo.GridStore', function(){
        assert(rs._store instanceof mongo.GridStore)
      })
    })
    describe('#methods', function(){
      describe('setEncoding', function(){
        it('should be a function', function(){
          assert('function' == typeof rs.setEncoding)
          // TODO test actual encodings
        })
      })
      describe('pause', function(){
        it('should be a function', function(){
          assert('function' == typeof rs.pause)
        })
      })
      describe('destroy', function(){
        it('should be a function', function(){
          assert('function' == typeof rs.destroy)
        })
      })
      describe('resume', function(){
        it('should be a function', function(){
          assert('function' == typeof rs.resume)
        })
      })
      describe('pipe', function(){
        it('should be a function', function(){
          assert('function' == typeof rs.pipe)
        })
      })
    });
    it('should provide piping to a writable stream by name', function(done){
      var file = fixturesDir + 'byname.png';
      var rs = g.createReadStream({
        filename: 'logo.png'
      });
      var writeStream = fs.createWriteStream(file);

      var opened = false;
      var ended = false;

      rs.on('open', function () {
        opened = true;
      });

      rs.on('error', function (err) {
        throw err;
      });

      rs.on('end', function () {
        ended = true;
      });

      writeStream.on('close', function () {
        // check they are identical
        var buf1 = fs.readFileSync(imgReadPath);
        var buf2 = fs.readFileSync(file);

        assert(buf1.length === buf2.length);

        for (var i = 0, len = buf1.length; i < len; ++i) {
          assert(buf1[i] == buf2[i]);
        }

        assert(opened);
        assert(ended);

        fs.unlinkSync(file);
        done();
      });

      rs.pipe(writeStream);
    });

    it('should provide piping to a writable stream by id', function(done){
      var file = fixturesDir + 'byid.png';
      var rs = g.createReadStream({
        _id: id
      });
      var writeStream = fs.createWriteStream(file);
      assert(rs.id instanceof mongo.ObjectID);
      assert(rs.id == String(id))

      var opened = false;
      var ended = false;

      rs.on('open', function () {
        opened = true;
      });

      rs.on('error', function (err) {
        throw err;
      });

      rs.on('end', function () {
        ended = true;
      });

      writeStream.on('close', function () {
        //check they are identical
        assert(opened);
        assert(ended);

        var buf1 = fs.readFileSync(imgReadPath);
        var buf2 = fs.readFileSync(file);

        assert(buf1.length === buf2.length);

        for (var i = 0, len = buf1.length; i < len; ++i) {
          assert(buf1[i] == buf2[i]);
        }

        fs.unlinkSync(file);
        done();
      });

      rs.pipe(writeStream);
    });

    it('should provide piping to a writable stream with a range by id', function(done){
      var file = fixturesDir + 'byid.png';
      var rs = g.createReadStream({
        _id: id,
        range: {
          startPos: 1000,
          endPos: 10000
        }
      });
      var writeStream = fs.createWriteStream(file);
      assert(rs.id instanceof mongo.ObjectID);
      assert(rs.id == String(id))

      var opened = false;
      var ended = false;

      rs.on('open', function () {
        opened = true;
      });

      rs.on('error', function (err) {
        throw err;
      });

      rs.on('end', function () {
        ended = true;
      });

      writeStream.on('close', function () {
        //check they are identical
        assert(opened);
        assert(ended);

        var buf1 = fs.readFileSync(imgReadPath);
        var buf2 = fs.readFileSync(file);

        assert(buf2.length === rs.options.range.endPos - rs.options.range.startPos + 1);

        for (var i = 0, len = buf2.length; i < len; ++i) {
          assert(buf1[i + rs.options.range.startPos] == buf2[i]);
        }

        fs.unlinkSync(file);
        done();
      });

      rs.pipe(writeStream);
    });

    it('should read files with an _id of arbitrary type', function(done){
      var rs = g.createReadStream({ _id: 'an_arbitrary_id'});

      rs.on('open', function () {
        assert(rs.id === 'an_arbitrary_id');
        done();
      });

    });

    it('should allow checking for existence of files', function(done){
      g.exist({ _id: id }, function (err, result) {
        if (err) return done(err);
        assert.ok(result);
        done();
      });
    });

    it('should allow checking for non existence of files', function(done){
      g.exist({ filename: 'does-not-exists.1234' }, function (err, result) {
        if (err) return done(err);
        assert.ok(!result);
        done();
      });
    });

    // See #51
    it('should allow checking for existence of files in an alternate root collection', function(done){
      var alternateFileOptions = {filename: 'alternateLogo.png', root: 'alternate' };
      var readStream = g.createReadStream({filename: 'logo.png'});
      var writeStream = g.createWriteStream(alternateFileOptions);
      readStream.pipe(writeStream);
      writeStream.on('close', function () {
        g.exist(alternateFileOptions, function (err, result) {
          if (err) return done(err);
          assert.ok(result);
          done();
        });
      });
    });

    it('should get a specific file', function(done){
      g.findOne({ _id: id }, function(err, result) {
        if (err) return done(err);
        assert.ok(result);
        done();
      });
    })

    it('should allow removing files', function(done){
      g.remove({ _id: id }, function (err) {
        if (err) return done(err);
        g.files.findOne({ _id: id }, function (err, doc) {
          if (err) return done(err);
          assert.ok(!doc);
          done();
        })
      });
    })

    it('should be possible to pause a stream after constructing it', function (done) {
      var rs = g.createReadStream({ filename: 'logo.png' });
      rs.pause();
      setTimeout(function () {
        rs.resume();
      }, 1000);

      rs.on('data', function (data) {
        rs.destroy();
        done();
      });
    });

    //issue #46
    it('should be able handle multiple streams with multiple chunks', function (done) {
      var doneCounter = 0;
      var totalCounter = 100;
      var checksums = [];

      this.timeout(10000);
      function doTest (i) {
        var copyFileName = tmpDir + 'logo' + i + '.png';
        var readStream = g.createReadStream({filename: '1mbBlob'});
        var writeStream = fs.createWriteStream(copyFileName);
        readStream.pipe(writeStream);
        writeStream.on('close', function () {
          checksum.file(copyFileName, function (err, sum) {
            checksums.push(sum);
            fs.unlinkSync(copyFileName);
            if (++doneCounter == totalCounter) {
              assert(checksums.filter(function (value, index, self) {
                return self.indexOf(value) === index;
              }).length === 1);
              done();
            }
          });
        });
      }

      var writeStream = g.createWriteStream({filename: '1mbBlob'});
      fs.createReadStream(largeBlobPath).pipe(writeStream);
      writeStream.on('close', function() {
        for (var i = totalCounter; i-- > 0;) {
          doTest(i);
        }
      });
    });

    it('should be able to set the encoding of a readstream', function (done) {
      var rs = g.createReadStream({ filename: 'logo.png' });
      rs.setEncoding('utf8');

      rs.on('data', function (data) {
        assert.equal(typeof data, 'string');
        rs.destroy();
        done();
      });
    });

    it('should be able to pause/resume after a chunk is sent to be able to throttle the stream', function (done) {
      var rs = g.createReadStream({ filename: '1mbBlob' });
      var numChuksSent = 0

      // Pause stream after one chunk has been sent
      rs.on('data', function (data) {
        numChuksSent += 1;
        rs.pause();
      });

      // Only one chunk should have been sent because it was paused after that. 1mbBlob contains 5 with default gridstream chunk size
      setTimeout(function () {
        assert.equal( numChuksSent, 1 );
        rs.resume();
      }, 500);

      // Now there should be 2
      setTimeout(function () {
        assert.equal( numChuksSent, 2 );
        done()
      }, 1000);

    });
  });

  after(function (done) {
    fs.unlink(largeBlobPath, function (err) {
      if (err) {
        done(err);
      }
      fs.rmdir(tmpDir, function () {
        db.dropDatabase(function () {
          db.close(true, done);
        });
      });
    });
  });
});


text:
package com.navercorp.pinpoint.common.server.bo.codec.stat;

import com.navercorp.pinpoint.common.server.bo.stat.CpuLoadBo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * @author HyunGil Jeong
 */
@Component
public class CpuLoadEncoder extends AgentStatEncoder<CpuLoadBo> {

    private CpuLoadEncoder(@Qualifier("cpuLoadCodecV2") AgentStatCodec<CpuLoadBo> cpuLoadCodec) {
        super(cpuLoadCodec);
    }
}


text:
namespace Sample.WPFClient.Controls.WeakEventing
{
    /// <summary>
    /// Provides a non-generic base class for the WeakEventListener implementation.
    /// The main reason is to get easier reading code in the WeakEventSourceBase implementation.
    /// </summary>
    public abstract class WeakEventListenerBase
    {
        public abstract void Detach();
    }
}


text:
KJSenchaExample
===============

Example application for using [KJSencha](https://github.com/KablauJoustra/KJSencha)
with [Zend Framework 2](http://framework.zend.com/)
and [Sencha Ext JS](http://www.sencha.com/products/extjs/)

## Introduction

KJSencha is a Zend Framework 2 module which provides functionality to help you
build apps with Zend Framework 2 and the [Sencha Ext JS](http://www.sencha.com/products/extjs/) framework

## Requirements

KJSenchaExample is based on the Zend Framework 2

## Installation

You can install this module via [composer](https://getcomposer.org/) by running the following
command in your application's root directory:

```sh
$ ./composer.phar create-project kablau-joustra/kj-sencha-example
```

You can also install this module without composer, assuming you meet all the dependencies
specified in [`composer.json`](https://github.com/KablauJoustra/KJSenchaExample/blob/master/composer.json)


text:
getType()}}&entity_id={{ $entity->id }}"
     option:dropdown-search:local-search-selector=".entity-list-item"
>

@icon('chevron-right')

            @icon('search')
            <input refs="dropdown-search@searchInput"
                   aria-label="{{ trans('common.search') }}"
                   autocomplete="off"
                   placeholder="{{ trans('common.search') }}"
                   type="text">

            @include('common.loading-icon')


text:
package com.codepath.instagram.fragments;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.codepath.instagram.R;
import com.codepath.instagram.adapters.InstagramPostsAdapter;
import com.codepath.instagram.core.MainApplication;
import com.codepath.instagram.helpers.SimpleVerticalSpacerItemDecoration;
import com.codepath.instagram.helpers.Utils;
import com.codepath.instagram.models.InstagramPost;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

/**
 * Created by dleroy on 11/1/15.
 */
public class PostsFragment extends Fragment {
    private ArrayList<InstagramPost> posts;
    private RecyclerView rvPosts;
    private InstagramPostsAdapter adapter;
    private Context context;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_post, container, false);
        context = container.getContext();

        rvPosts = (RecyclerView) view.findViewById(R.id.rvPosts);

        posts = new ArrayList<InstagramPost>();

        RecyclerView.ItemDecoration itemDecoration = new SimpleVerticalSpacerItemDecoration(24);
        rvPosts.addItemDecoration(itemDecoration);
        adapter = new InstagramPostsAdapter(posts);
        rvPosts.setAdapter(adapter);
        rvPosts.setLayoutManager(new LinearLayoutManager(context));

        if (!isNetworkAvailable()) {
            showNetworkFailureAlert();
        } else {
            MainApplication.getRestClient().getOwnFeed(new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    posts.clear();
                    posts.addAll((ArrayList<InstagramPost>) Utils.decodePostsFromJsonResponse(response));
                    adapter.notifyDataSetChanged();
                    super.onSuccess(statusCode, headers, response);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    showNetworkFailureAlert();
                    super.onFailure(statusCode, headers, responseString, throwable);
                }
            });
        }

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void showNetworkFailureAlert() {
        new AlertDialog.Builder(context)
                .setTitle("Network Error")
                .setMessage("A network error has occurred")
                .setNeutralButton("Okay", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // continue with delete
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    private Boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }

    public static PostsFragment newInstance() {
        PostsFragment fragment = new PostsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

}


text:
using ThriftSharp;

namespace PocketCampus.Camipro.Models
{
    [ThriftStruct( "SendMailResult" )]
    public sealed class MailRequestResult
    {
        [ThriftField( 2, true, "iStatus" )]
        public ResponseStatus Status { get; set; }
    }
}