text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const path_1 = require("path");
const dev = Math.floor(Math.random() * 10000);
class VirtualStats {
    constructor(_path) {
        this._path = _path;
        this._ctime = new Date();
        this._mtime = new Date();
        this._atime = new Date();
        this._btime = new Date();
        this._dev = dev;
        this._ino = Math.floor(Math.random() * 100000);
        this._mode = parseInt('777', 8); // RWX for everyone.
        this._uid = process.env['UID'] || 0;
        this._gid = process.env['GID'] || 0;
    }
    isFile() { return false; }
    isDirectory() { return false; }
    isBlockDevice() { return false; }
    isCharacterDevice() { return false; }
    isSymbolicLink() { return false; }
    isFIFO() { return false; }
    isSocket() { return false; }
    get dev() { return this._dev; }
    get ino() { return this._ino; }
    get mode() { return this._mode; }
    get nlink() { return 1; } // Default to 1 hard link.
    get uid() { return this._uid; }
    get gid() { return this._gid; }
    get rdev() { return 0; }
    get size() { return 0; }
    get blksize() { return 512; }
    get blocks() { return Math.ceil(this.size / this.blksize); }
    get atime() { return this._atime; }
    get mtime() { return this._mtime; }
    get ctime() { return this._ctime; }
    get birthtime() { return this._btime; }
}
exports.VirtualStats = VirtualStats;
class VirtualDirStats extends VirtualStats {
    constructor(_fileName) {
        super(_fileName);
    }
    isDirectory() { return true; }
    get size() { return 1024; }
}
exports.VirtualDirStats = VirtualDirStats;
class VirtualFileStats extends VirtualStats {
    constructor(_fileName, _content) {
        super(_fileName);
        this._content = _content;
    }
    get content() { return this._content; }
    set content(v) {
        this._content = v;
        this._mtime = new Date();
        this._sourceFile = null;
    }
    setSourceFile(sourceFile) {
        this._sourceFile = sourceFile;
    }
    getSourceFile(languageVersion, setParentNodes) {
        if (!this._sourceFile) {
            this._sourceFile = ts.createSourceFile(this._path, this._content, languageVersion, setParentNodes);
        }
        return this._sourceFile;
    }
    isFile() { return true; }
    get size() { return this._content.length; }
}
exports.VirtualFileStats = VirtualFileStats;
class WebpackCompilerHost {
    constructor(_options, basePath) {
        this._options = _options;
        this._files = Object.create(null);
        this._directories = Object.create(null);
        this._changedFiles = Object.create(null);
        this._changedDirs = Object.create(null);
        this._cache = false;
        this._setParentNodes = true;
        this._delegate = ts.createCompilerHost(this._options, this._setParentNodes);
        this._basePath = this._normalizePath(basePath);
    }
    _normalizePath(path) {
        return path.replace(/\\/g, '/');
    }
    _resolve(path) {
        path = this._normalizePath(path);
        if (path[0] == '.') {
            return this._normalizePath(path_1.join(this.getCurrentDirectory(), path));
        }
        else if (path[0] == '/' || path.match(/^\w:\//)) {
            return path;
        }
        else {
            return this._normalizePath(path_1.join(this._basePath, path));
        }
    }
    _setFileContent(fileName, content) {
        this._files[fileName] = new VirtualFileStats(fileName, content);
        let p = path_1.dirname(fileName);
        while (p && !this._directories[p]) {
            this._directories[p] = new VirtualDirStats(p);
            this._changedDirs[p] = true;
            p = path_1.dirname(p);
        }
        this._changedFiles[fileName] = true;
    }
    get dirty() {
        return Object.keys(this._changedFiles).length > 0;
    }
    enableCaching() {
        this._cache = true;
    }
    resetChangedFileTracker() {
        this._changedFiles = Object.create(null);
        this._changedDirs = Object.create(null);
    }
    getChangedFilePaths() {
        return Object.keys(this._changedFiles);
    }
    invalidate(fileName) {
        fileName = this._resolve(fileName);
        if (fileName in this._files) {
            this._files[fileName] = null;
            this._changedFiles[fileName] = true;
        }
    }
    fileExists(fileName, delegate = true) {
        fileName = this._resolve(fileName);
        return this._files[fileName] != null || (delegate && this._delegate.fileExists(fileName));
    }
    readFile(fileName) {
        fileName = this._resolve(fileName);
        const stats = this._files[fileName];
        if (stats == null) {
            const result = this._delegate.readFile(fileName);
            if (result !== undefined && this._cache) {
                this._setFileContent(fileName, result);
                return result;
            }
            else {
                return result;
            }
        }
        return stats.content;
    }
    // Does not delegate, use with `fileExists/directoryExists()`.
    stat(path) {
        path = this._resolve(path);
        return this._files[path] || this._directories[path];
    }
    directoryExists(directoryName, delegate = true) {
        directoryName = this._resolve(directoryName);
        return (this._directories[directoryName] != null)
            || (delegate
                && this._delegate.directoryExists != undefined
                && this._delegate.directoryExists(directoryName));
    }
    getFiles(path) {
        path = this._resolve(path);
        return Object.keys(this._files)
            .filter(fileName => path_1.dirname(fileName) == path)
            .map(path => path_1.basename(path));
    }
    getDirectories(path) {
        path = this._resolve(path);
        const subdirs = Object.keys(this._directories)
            .filter(fileName => path_1.dirname(fileName) == path)
            .map(path => path_1.basename(path));
        let delegated;
        try {
            delegated = this._delegate.getDirectories(path);
        }
        catch (e) {
            delegated = [];
        }
        return delegated.concat(subdirs);
    }
    getSourceFile(fileName, languageVersion, _onError) {
        fileName = this._resolve(fileName);
        const stats = this._files[fileName];
        if (stats == null) {
            const content = this.readFile(fileName);
            if (!this._cache) {
                return ts.createSourceFile(fileName, content, languageVersion, this._setParentNodes);
            }
        }
        return this._files[fileName].getSourceFile(languageVersion, this._setParentNodes);
    }
    getCancellationToken() {
        return this._delegate.getCancellationToken();
    }
    getDefaultLibFileName(options) {
        return this._delegate.getDefaultLibFileName(options);
    }
    // This is due to typescript CompilerHost interface being weird on writeFile. This shuts down
    // typings in WebStorm.
    get writeFile() {
        return (fileName, data, _writeByteOrderMark, _onError, _sourceFiles) => {
            fileName = this._resolve(fileName);
            this._setFileContent(fileName, data);
        };
    }
    getCurrentDirectory() {
        return this._basePath !== null ? this._basePath : this._delegate.getCurrentDirectory();
    }
    getCanonicalFileName(fileName) {
        fileName = this._resolve(fileName);
        return this._delegate.getCanonicalFileName(fileName);
    }
    useCaseSensitiveFileNames() {
        return this._delegate.useCaseSensitiveFileNames();
    }
    getNewLine() {
        return this._delegate.getNewLine();
    }
}
exports.WebpackCompilerHost = WebpackCompilerHost;
//# sourceMappingURL=/users/hansl/sources/hansl/angular-cli/src/compiler_host.js.map


text:
package cn.chendihao;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

	private DevicePolicyManager policyManager;
	private ComponentName componentName;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //获取设备管理服务
        policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

        //AdminReceiver 继承自 DeviceAdminReceiver
        componentName = new ComponentName(this, AdminReceiver.class);

    	boolean active = policyManager.isAdminActive(componentName);

    	if(!active){//若无权限
            // 启动设备管理(隐式Intent) - 在AndroidManifest.xml中设定相应过滤器
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

            //权限列表
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);

            //描述(additional explanation)
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "------ 老杰锁屏 ------");

            startActivityForResult(intent, 0);

    		policyManager.lockNow();//并锁屏

    	}else{

            policyManager.lockNow();//直接锁屏
        }

    //  killMyself ,锁屏之后就立即kill掉我们的Activity,避免资源的浪费;
        android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
    protected void onResume() {//重写此方法用来在第一次激活设备管理器之后锁定屏幕
		super.onResume();

        if (policyManager.isAdminActive(componentName)) {
            policyManager.lockNow();
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //unregisterReceiver(mReceiver);
    }

}

redpajama_set_name: RedPajamaGithub


text:
"""
This script reads task data in iCalendar format and converts it to Gina
Trapani's todo.txt format (see http://todotxt.com/).

The task data can be exported from Remember The Milk or Apple's Reminders
app on OS X.
"""

import codecs
import re
import sys
import os

USAGE = """
Convert iCalendar task data to a todo.txt file.
See README.md for details.

Usage:
    {0} INPUT_ICS OUTPUT_TXT [APPENDIX]

Where:
    INPUT_ICS     : Pathname of the source iCalendar file.

    OUTPUT_TXT    : Pathname for the output todo.txt file.
                    The file must not exist.

    APPENDIX      : Text to append to each output line.

Examples:
    $ {0} Reminders.ics todo.txt.Reminders +ListName

    $ {0} iCalendar_Service.ics todo.txt.RTM
"""

class ICSParser:
    """Quick and dirty iCalendar format parser."""

    def __init__(self, input_file):
        """Initialize a new parser object and parse the input file."""
        linebuf = None
        self.__node = {}
        self.__stack = []
        for line in input_file:
            line = line.rstrip('\r\n')
            if linebuf is None:
                linebuf = line
            else:
                if line[0] == ' ':
                    linebuf += line[1:]
                else:
                    self.__parse_line(linebuf)
                    linebuf = line
        if linebuf is not None:
            self.__parse_line(linebuf)

    def get_root(self):
        """Return the top-level VCALENDAR object."""
        return self.__node['VCALENDAR'][0]

    def __parse_line(self, line):
        """Parse an input line; update internal structures."""
        if line.startswith('BEGIN:'):
            self.__stack.append(self.__node)
            node_name = line[6:]
            new_node = {}
            if node_name in self.__node:
                self.__node[node_name].append(new_node)
            else:
                self.__node[node_name] = [new_node]
            self.__node = new_node
        elif line.startswith('END:'):
            self.__node = self.__stack.pop()
        else:
            key, val = tuple(line.split(':', 1))
            key = key.split(';', 1)[0]
            if key not in self.__node:
                self.__node[key] = val

def normalize_date(date):
    """Bring the date argument to a uniform format, which is YYYY-MM-DD."""
    # Remove the time portion.
    time_pos = date.find('T')
    if time_pos >= 0:
        date = date[:time_pos]
    # Insert dashes.
    if len(date) == 8:
        date = date[:4] + '-' + date[4:6] + '-' + date[6:]
    return date

def camel_case(words):
    """Convert a noun phrase to a CamelCase identifier."""
    result = ''
    for word in re.split(r'(?:\W|_)+', words):
        if word:
            if word[:1].islower():
                word = word.capitalize()
            result += word
    return result

def unescape(string):
    """Remove backslashes from the string."""
    return re.sub(r'\\(.)', r'\1', string)

def process_description(description):
    """Extract tags, location, and notes from the DESCRIPTION component."""
    result = ''
    sep = ' '
    next_sep = '; '
    for field in description.split(r'\n'):
        if field.startswith('Time estimate:') or \
                field.startswith('Updated:') or not field:
            continue
        elif field.startswith('Tags:'):
            tags = field[5:].strip()
            if tags != 'none':
                for tag in unescape(tags).split(','):
                    result += ' @' + camel_case(tag)
        elif field.startswith('Location:'):
            location = field[9:].strip()
            if location != 'none':
                result += ' @' + camel_case(location)
        elif re.match('^--+$', field):
            next_sep = ': '
        else:
            result += sep + unescape(field)
            sep = next_sep
            next_sep = '; '
    return result

def main(argv):
    """Convert input_file (iCalendar_Service.ics) to output_file (todo.txt)."""
    if len(argv) == 4:
        appendix = ' ' + argv[3]
    elif len(argv) == 3:
        appendix = ''
    else:
        print(USAGE.format(argv[0]), file=sys.stderr)
        return 1
    input_file_name = argv[1]
    output_file_name = argv[2]
    if os.path.exists(output_file_name):
        print("Error: '" + output_file_name + "' exists.", file=sys.stderr)
        return 1
    try:
        todos = ICSParser(codecs.open(input_file_name,
                          'r', 'utf-8')).get_root()['VTODO']
        output_file = codecs.open(output_file_name, 'w', 'utf-8')
        for todo in todos:
            output_line = ''
            if 'STATUS' in todo and todo['STATUS'] == 'COMPLETED':
                output_line = 'x '
            if 'PRIORITY' in todo:
                output_line += '(' + \
                    chr(((ord(todo['PRIORITY']) - 49) >> 2) + 65) + ') '
            dates = set()
            for field in 'DTSTAMP', 'DTSTART', 'LAST-MODIFIED', 'COMPLETED':
                if field in todo:
                    dates.add(normalize_date(todo[field]))
            for date in sorted(dates, reverse=True):
                output_line += date + ' '
            output_line += unescape(todo['SUMMARY'])
            if 'URL' in todo:
                output_line += ' ' + todo['URL']
            if 'DUE' in todo:
                output_line += ' due:' + normalize_date(todo['DUE'])
            if 'DESCRIPTION' in todo:
                output_line += process_description(todo['DESCRIPTION'])
            print(output_line + appendix, file=output_file)
    except IOError as err:
        print(err, file=sys.stderr)
        return 2
    print('Conversion completed. Please carefully review the contents of')
    print(output_file_name + ' before merging it into your existing todo.txt.')
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))


text:
package org.gradle.model.internal.core;

import org.gradle.api.Nullable;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;

public interface ModelAdapter {

    @Nullable
        // if the model can't be viewed as this type
    <T> ModelView<? extends T> asWritable(ModelBinding<T> reference, ModelRuleDescriptor sourceDescriptor, Inputs inputs, ModelRuleRegistrar modelRegistry);

    @Nullable
        // if the model can't be viewed as this type
    <T> ModelView<? extends T> asReadOnly(ModelType<T> type);

    // TODO some kind of description of the model item?

}


text:
<LINK REL="stylesheet" HREF="../static/styles.css">

<TITLE>FMOD_STUDIO_USER_PROPERTY_TYPE</TITLE>

Firelight Technologies FMOD Studio API

FMOD_STUDIO_USER_PROPERTY_TYPE

These definitions describe a user property's type.

Enumeration

typedef enum {
  FMOD_STUDIO_USER_PROPERTY_TYPE_INTEGER,
  FMOD_STUDIO_USER_PROPERTY_TYPE_BOOLEAN,
  FMOD_STUDIO_USER_PROPERTY_TYPE_FLOAT,
  FMOD_STUDIO_USER_PROPERTY_TYPE_STRING
} FMOD_STUDIO_USER_PROPERTY_TYPE;

Values

FMOD_STUDIO_USER_PROPERTY_TYPE_INTEGER

Integer property

FMOD_STUDIO_USER_PROPERTY_TYPE_BOOLEAN

Boolean property

FMOD_STUDIO_USER_PROPERTY_TYPE_FLOAT

Float property

FMOD_STUDIO_USER_PROPERTY_TYPE_STRING

String property

See Also

FMOD_STUDIO_USER_PROPERTY

Version 1.08.02 Built on Apr 14, 2016


text:
'use strict';

var Task = require('wheelie/lib/models/task');

function config(globals) {
  var source = globals.src + 'templates/**';

  return {
    watcher: source,
    src: source,
    dest: globals.dest + '/'
  };
}

function run(gulp, config) {
  return function() {
      return gulp.src(config.src)
        .pipe(gulp.dest(config.dest));
  };
}

module.exports = new Task('templates', [], run, config);


text:
import {h, cloneElement} from 'preact';
import HeaderPage from '../HeaderPage';

const style = {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
  background: '#242424'
}

function Top(props) {
  return (
    <div className="uk-view" style={{...style, height: props.layout.top}}>
      <HeaderPage {...props} />
    </div>
  )
}

export default Top;


text:
<?php
namespace vendor\GoogleIdentity;

Class GoogleIdentity_Message {
 private $msg = null;
 private $action = null;
 private $code = null;
 private $data = null;

 function __construct($action, $msg, $code = 0, $data = NULL) {
  $this->msg = $msg;
  $this->action = $action;
  $this->code = $code;
  $this->data = $data;
  return $this;
 }

 public function write() {
 	header('Cache-Control: no-cache, must-revalidate');
 	header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
 	header('Content-type: application/json');
 	echo $this->to_json();
 }

 public function to_json() {
  return json_encode(
    array('msg' => $this->msg, 'action' => $this->action,
      'code' => $this->code, 'data' => $this->data));
  return $this;
 }
}


text:
.ErrorPanel_topContainer {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 60%;
}

.ErrorPanel_top_row {
    align-self: flex-start;
}

.ErrorPanel_row {
    max-width: 90%;
}

.ErrorPanel_errorCell {
    border: 1px solid black;
    padding: 30px;
    border-radius: 10px;
}

.ErrorPanel_errorText {
    font-size: 12pt;
    height: 30px;
}

.ErrorPanel_errorIcon {
    height: 60px;
}

.ErrorPanel_bottom_row {
    align-self: flex-end;
}


text:
layout: data_model
title: DigitalSignaturesType
this_version: 1.0
---

  Heads up! These docs are for STIX 1.0, which is not the latest version (1.2). View the latest!

DigitalSignaturesTypeCybOX Common Schema

The DigitalSignaturesType is used for representing a list of digital signatures.

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" >STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" selected="selected">STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      Digital_Signature0..n

          DigitalSignatureInfoType

The Digital_Signature field is optional and captures a single digital signature for this Object.


text:
/*!
  \file		kernel/pit.h
  \brief	Programmable Interval Timer
*/

#ifndef _PIT_H_
#define _PIT_H_

#include <ace.h>
#include <kernel/interrupt.h>

/* Timer frequency is 100 Hz */
#define TIMER_FREQUENCY (100)

#define MILLISECONDS_TO_TICKS(ms)	((ms) / (1000/TIMER_FREQUENCY))
#define TICKS_TO_MILLISECONDS(ticks)	((ticks) * (1000/TIMER_FREQUENCY))

void InitPit(UINT32 frequency);
UINT32 ElapsedTicks();
void TimerSleep(UINT32 ticks);
void Delay(UINT32 ms);

ISR_RETURN_CODE _8254Handler(INTERRUPT_INFO_PTR interrupt_info, void * arg);
ISR_RETURN_CODE LapicTimerHandler(INTERRUPT_INFO_PTR interrupt_info, void * arg);

extern volatile UINT32 ElapsedSeconds;
extern volatile UINT32 timer_ticks;

#endif


text:
"""Defines TestPackageExecutable to help run stand-alone executables."""

import logging
import os
import posixpath
import sys
import tempfile

from devil.android import device_errors
from devil.utils import cmd_helper
from pylib import constants
from pylib import pexpect
from pylib.gtest import gtest_test_instance
from pylib.gtest.test_package import TestPackage

class TestPackageExecutable(TestPackage):
  """A helper class for running stand-alone executables."""

  _TEST_RUNNER_RET_VAL_FILE = 'gtest_retval'

  def __init__(self, suite_name):
    """
    Args:
      suite_name: Name of the test suite (e.g. base_unittests).
    """
    TestPackage.__init__(self, suite_name)
    self.suite_path = os.path.join(constants.GetOutDirectory(), suite_name)
    self._symbols_dir = os.path.join(constants.GetOutDirectory(),
                                     'lib.target')

  #override
  def GetGTestReturnCode(self, device):
    ret = None
    ret_code = 1  # Assume failure if we can't find it
    ret_code_file = tempfile.NamedTemporaryFile()
    try:
      if not device.PullFile(
          constants.TEST_EXECUTABLE_DIR + '/' +
          TestPackageExecutable._TEST_RUNNER_RET_VAL_FILE,
          ret_code_file.name):
        logging.critical('Unable to pull gtest ret val file %s',
                         ret_code_file.name)
        raise ValueError
      ret_code = file(ret_code_file.name).read()
      ret = int(ret_code)
    except ValueError:
      logging.critical('Error reading gtest ret val file %s [%s]',
                       ret_code_file.name, ret_code)
      ret = 1
    return ret

  @staticmethod
  def _AddNativeCoverageExports(device):
    # export GCOV_PREFIX set the path for native coverage results
    # export GCOV_PREFIX_STRIP indicates how many initial directory
    #                          names to strip off the hardwired absolute paths.
    #                          This value is calculated in buildbot.sh and
    #                          depends on where the tree is built.
    # Ex: /usr/local/google/code/chrome will become
    #     /code/chrome if GCOV_PREFIX_STRIP=3
    try:
      depth = os.environ['NATIVE_COVERAGE_DEPTH_STRIP']
      export_string = ('export GCOV_PREFIX="%s/gcov"\n' %
                       device.GetExternalStoragePath())
      export_string += 'export GCOV_PREFIX_STRIP=%s\n' % depth
      return export_string
    except KeyError:
      logging.info('NATIVE_COVERAGE_DEPTH_STRIP is not defined: '
                   'No native coverage.')
      return ''
    except device_errors.CommandFailedError:
      logging.info('No external storage found: No native coverage.')
      return ''

  #override
  def ClearApplicationState(self, device):
    device.KillAll(self.suite_name, blocking=True, timeout=30, quiet=True)

  #override
  def CreateCommandLineFileOnDevice(self, device, test_filter, test_arguments):
    tool_wrapper = self.tool.GetTestWrapper()
    sh_script_file = tempfile.NamedTemporaryFile()
    # We need to capture the exit status from the script since adb shell won't
    # propagate to us.
    sh_script_file.write(
        'cd %s\n'
        '%s'
        '%s LD_LIBRARY_PATH=%s/%s_deps %s/%s --gtest_filter=%s %s\n'
        'echo $? > %s' %
        (constants.TEST_EXECUTABLE_DIR,
         self._AddNativeCoverageExports(device),
         tool_wrapper,
         constants.TEST_EXECUTABLE_DIR,
         self.suite_name,
         constants.TEST_EXECUTABLE_DIR,
         self.suite_name,
         test_filter, test_arguments,
         TestPackageExecutable._TEST_RUNNER_RET_VAL_FILE))
    sh_script_file.flush()
    cmd_helper.RunCmd(['chmod', '+x', sh_script_file.name])
    device.PushChangedFiles([(
        sh_script_file.name,
        constants.TEST_EXECUTABLE_DIR + '/chrome_test_runner.sh')])
    logging.info('Conents of the test runner script: ')
    for line in open(sh_script_file.name).readlines():
      logging.info('  ' + line.rstrip())

  #override
  def GetAllTests(self, device):
    lib_path = posixpath.join(
        constants.TEST_EXECUTABLE_DIR, '%s_deps' % self.suite_name)

    cmd = []
    if self.tool.GetTestWrapper():
      cmd.append(self.tool.GetTestWrapper())
    cmd.extend([
        posixpath.join(constants.TEST_EXECUTABLE_DIR, self.suite_name),
        '--gtest_list_tests'])

    output = device.RunShellCommand(
        cmd, check_return=True, env={'LD_LIBRARY_PATH': lib_path})
    return gtest_test_instance.ParseGTestListTests(output)

  #override
  def SpawnTestProcess(self, device):
    args = ['adb', '-s', str(device), 'shell', 'sh',
            constants.TEST_EXECUTABLE_DIR + '/chrome_test_runner.sh']
    logging.info(args)
    return pexpect.spawn(args[0], args[1:], logfile=sys.stdout)

  #override
  def Install(self, device):
    if self.tool.NeedsDebugInfo():
      target_name = self.suite_path
    else:
      target_name = self.suite_path + '_stripped'
      if not os.path.isfile(target_name):
        raise Exception('Did not find %s, build target %s' %
                        (target_name, self.suite_name + '_stripped'))

      target_mtime = os.stat(target_name).st_mtime
      source_mtime = os.stat(self.suite_path).st_mtime
      if target_mtime < source_mtime:
        raise Exception(
            'stripped binary (%s, timestamp %d) older than '
            'source binary (%s, timestamp %d), build target %s' %
            (target_name, target_mtime, self.suite_path, source_mtime,
             self.suite_name + '_stripped'))

    test_binary_path = constants.TEST_EXECUTABLE_DIR + '/' + self.suite_name
    device.PushChangedFiles([(target_name, test_binary_path)])
    deps_path = self.suite_path + '_deps'
    if os.path.isdir(deps_path):
      device.PushChangedFiles([(deps_path, test_binary_path + '_deps')])

  #override
  def PullAppFiles(self, device, files, directory):
    pass


text:
package org.infinispan.spring.provider;

import java.util.Properties;

import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.spring.AbstractRemoteCacheManagerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 *

 * A {@link org.springframework.beans.factory.FactoryBean FactoryBean} for creating an
 * {@link org.infinispan.spring.provider.SpringRemoteCacheManager
 * SpringRemoteCacheManager} instance.
 *

 * Configuration

 *

 * A SpringRemoteCacheManager is configured through a {@link java.util.Properties
 * Properties} object. For an exhaustive list of valid properties to be used see
 * RemoteCacheManager's {@link org.infinispan.client.hotrod.RemoteCacheManager
 * javadocs}. This FactoryBean provides means to either
 * {@link #setConfigurationProperties(Properties) inject} a user-defined Properties
 * instance or to
 * {@link #setConfigurationPropertiesFileLocation(org.springframework.core.io.Resource) set} the
 * location of a properties file to load those properties from. Note that it is illegal to
 * use both mechanisms simultaneously.
 *

 *

 * Alternatively or in combination with
 * {@link #setConfigurationPropertiesFileLocation(org.springframework.core.io.Resource) setting} the
 * location of a Properties file to load the configuration from, this
 * FactoryBean provides (typed) setters for all configuration settings. Settings thus
 * defined take precedence over those defined in the injected Properties instance. This
 * flexibility enables users to use e.g. a company-wide Properties file containing
 * default settings while simultaneously overriding select settings whenever special requirements
 * warrant this.

 * Note that it is illegal to use setters in conjunction with
 * {@link #setConfigurationProperties(Properties) injecting} a Properties instance.
 *

 *

 * In addition to creating a SpringRemoteCacheManager this FactoryBean
 * does also control that SpringRemoteCacheManager's lifecycle by shutting it down when
 * the enclosing Spring application context is closed. It is therefore advisable to always
 * use this FactoryBean when creating an SpringRemoteCacheManager.
 *

 *
 * @author Olaf Bergner
 *
 * @see org.infinispan.client.hotrod.RemoteCacheManager
 * @see #destroy()
 */
public class SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory
         implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean {

   private SpringRemoteCacheManager springRemoteCacheManager;

   // ------------------------------------------------------------------------
   // org.springframework.beans.factory.InitializingBean
   // ------------------------------------------------------------------------

   /**
    * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
    */
   @Override
   public void afterPropertiesSet() throws Exception {
      assertCorrectlyConfigured();
      this.logger.info("Creating new instance of RemoteCacheManager ...");
      final Properties configurationPropertiesToUse = configurationProperties();
      final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager(
               configurationPropertiesToUse, this.startAutomatically);
      this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager);
      this.logger.info("Finished creating new instance of RemoteCacheManager");
   }

   // ------------------------------------------------------------------------
   // org.springframework.beans.factory.FactoryBean
   // ------------------------------------------------------------------------

   /**
    * @see org.springframework.beans.factory.FactoryBean#getObject()
    */
   @Override
   public SpringRemoteCacheManager getObject() throws Exception {
      return this.springRemoteCacheManager;
   }

   /**
    * @see org.springframework.beans.factory.FactoryBean#getObjectType()
    */
   @Override
   public Class<? extends SpringRemoteCacheManager> getObjectType() {
      return this.springRemoteCacheManager != null ? this.springRemoteCacheManager.getClass()
               : SpringRemoteCacheManager.class;
   }

   /**
    * Always return true.
    *
    * @see org.springframework.beans.factory.FactoryBean#isSingleton()
    */
   @Override
   public boolean isSingleton() {
      return true;
   }

   // ------------------------------------------------------------------------
   // org.springframework.beans.factory.DisposableBean
   // ------------------------------------------------------------------------

   /**
    * {@link org.infinispan.client.hotrod.RemoteCacheManager#stop() stop} the
    * RemoteCacheManager created by this factory.
    *
    * @see org.springframework.beans.factory.DisposableBean#destroy()
    */
   @Override
   public void destroy() throws Exception {
      // Being paranoid
      if (this.springRemoteCacheManager != null) {
         this.springRemoteCacheManager.stop();
      }
   }
}


text:
using System;
using System.Linq;
using Conventional;
using Nimbus.Configuration.Settings;
using Nimbus.Extensions;
using NUnit.Framework;

namespace Nimbus.Tests.Unit.Conventions
{
    [TestFixture]
    [Category("Convention")]
    public class AllSettingsClasses
    {
        [Test]
        public void MustAdhereToConventions()
        {
            typeof(Setting<>).Assembly
                             .GetTypes()
                             .Where(t => t.IsClosedTypeOf(typeof(Setting<>)))
                             .MustConformTo(new MustBePublicConventionSpecification())
                             .AndMustConformTo(new MustBeInMatchingNamespaceConventionSpecification(ns => ns.Contains(".Configuration.")))
                             .AndMustConformTo(new MustBeInMatchingNamespaceConventionSpecification(ns => ns.EndsWith(".Settings")))
                             .WithFailureAssertion(message => throw new Exception(message));
        }
    }
}


text:
function setup() {
  createCanvas(innerWidth, innerHeight);
}

function draw() {
  ellipse(mouseX, mouseY, 80, 80);
}


text:
Passel Bundle > Entities > Faction
===================================
Faction entity.

Attributes
----------
- id :: Primary key
- name :: Name
- [Passel](passel.md) :: `Passel` entity
- [Faction](faction.md) :: `Faction` entity
- [Position](position.md) :: `Position` entity
- [Level](level.md) :: `Level` entity

Methods
-------
- getPassel
- getFaction
- getPosition
- getLevel
- setPassel
- setFaction
- setPosition
- setLevel


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

/*----------------------------------------------------------------
    Copyright (C) 2022 Senparc

    文件名:TenPayResult.cs
    文件功能描述:微信支付返回结果

    创建标识:Senparc - 20150211

    修改标识:Senparc - 20150303
    修改描述:整理接口
----------------------------------------------------------------*/

using Senparc.Weixin.Entities;

namespace Senparc.Weixin.TenPay.V2
{
    /// <summary>
    /// 订单查询
    /// </summary>
    public class OrderqueryResult : WxJsonResult
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public OrderInfo orderInfo { get; set; }

        public class OrderInfo
        {
            public string ret_code { get; set; }
            public string ret_msg { get; set; }
            public string input_charset { get; set; }
            public string trade_state { get; set; }
            public string trade_mode { get; set; }
            public string partner { get; set; }
            public string bank_type { get; set; }
            public string bank_billno { get; set; }
            public string total_fee { get; set; }
            public string fee_type { get; set; }
            public string transaction_id { get; set; }
            public string out_trade_no { get; set; }
            public string is_split { get; set; }
            public string is_refund { get; set; }
            public string attach { get; set; }
            public string time_end { get; set; }
            public string transport_fee { get; set; }
            public string product_fee { get; set; }
            public string discount { get; set; }
            public string rmb_total_fee { get; set; }
        }
    }
}


text:
Dumps anonymized database contents to a YAML file. This is useful if you want to develop Rails applications with near-live data from your server. Based on [yaml_db](https://github.com/ludicast/yaml_db).

(c) 2012 by Thomas Hollstegge

## Installation

Add this line to your application's Gemfile:

    gem 'yaml_db_anonymizer'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install yaml_db_anonymizer

## Usage

* Specify the database fields to anonymize, e.g. in
   `config/initializers/yaml_db_anonymizer.rb`:

```ruby
YamlDb::Anonymizer.define do
  table :users
    remove :encrypted_password
    replace :name, with: 'John Doe'
    replace :phone, with: ->(phone) { phone.to_s[0..-3] + '***' }
  end

  table :logs do
    truncate
  end
end
```

* Run `rake db:data:dump_anonymized` on your server. This creates an anonymized dump in `db/data.yml`

* Copy `db/data.yml` to your local machine

* Run `rake db:data:load` on your local machine.

## Todo

* Provide capistrano integration

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License

MIT License. Copyright 2012 by Thomas Hollstegge


text:
Migrating legacy JavaScripts
============================

Legacy code often contains JavaScripts that expect a full page load whenever the
user interacts with the page. When you configure Unpoly to handle all interaction,
there will not be additional page loads as the user clicks a link or submits a form.

This may cause some of the following issues:

1. The `window` will not emit another `DOMContentLoaded` event when you
   update the page body through Unpoly. This may cause your legacy JavaScript to not
   run when you expect it to.
2. Legacy JavaScript often enhances elements on the entire page
   instead of scoping its changes to a region of the DOM.
   When we're updating fragments we only want to enhance elements within the new fragment,
   and don't want to touch elements that we have already enhanced.
3. Legacy JavaScript may have [memory leaks](https://nolanlawson.com/2020/02/19/fixing-memory-leaks-in-web-applications/), e.g. by scheduling timers with `setInterval()`
   but never clearing these timers when they're no longer needed.
   When you're resetting the page with every click you may never
   notice the leaks. However, when all links are handled through Unpoly
   the JavaScript VM may persist for minutes or hours and those leaks
   are going to stack up.

The cleanest solution to these issues is to call all your JavaScript
from an [Unpoly compiler](/up.compiler).

### Migrating legacy scripts to a compiler

The legacy code below waits for the page to load, then selects all links with a
`.lightbox` class and calls `lightboxify()` for each of these links:

```js
document.addEventListener('DOMContentLoaded', function(event) {
  document.querySelectorAll('a.lightbox').forEach(function(element) {
    lightboxify(element)
  })
})
```

Since the code only runs after the initial page load, links contained in
a fragment update will not be lightboxified.

You can fix this by moving your code to a [compiler](/up.compiler):

```js
up.compiler('a.lightbox', function(element) {
  lightboxify(element)
})
```

When the page initially loads, Unpoly will call this compiler for every element
matching `a.lightbox`. When a fragment is updated later, Unpoly will call this compiler
for new matches within the new fragment.

### Running inline `<script>` tags

By default Unpoly does not execute `<script>` tags in an updated fragment to prevent
unwanted side effects.
This means that your `<script>` tag will only be executed during the initial page
load, but not when navigating to a new page via an `a[up-follow]` link.

It is recommended to move all your JavaScript from `<script>` tags into a compiler.
This ensures your code is called after both page loads and fragment updats.
A compiler also enables you to scope   the side effects of your code to the DOM
fragment that was updated.

If you cannot migrate your `<script>` tags to a compiler, you you can also configure
Unpoly to run `<script>` tags in updated fragments:

```js
up.fragment.config.runScripts = true
```

If you do this, mind that the `<body>` element is a default [main target](/up-main). If you are including your global application scripts
at the end of your `<body>` for performance reasons, swapping the `<body>` will re-execute these scripts.
In that case you must configure a different main target that does not include
your application scripts.

@page legacy-scripts


text:
// /*
//   SharpNative - C# to D Transpiler
//   (C) 2014 Irio Systems
// */

namespace SharpNative.Compiler
{
    public class TempWriter : OutputWriter
    {
        public TempWriter()
            : base("", "", false)
        {
        }

        public override string ToString()
        {
            return base.ToString();
        }
    }
}


text:
'use strict';

// MODULES //

var nanvariancech = require( '@stdlib/stats/base/nanvariancech' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );

// MAIN //

/**
* Computes the standard deviation of a strided array ignoring `NaN` values and using a one-pass trial mean algorithm.
*
* @param {PositiveInteger} N - number of indexed elements
* @param {number} correction - degrees of freedom adjustment
* @param {NumericArray} x - input array
* @param {integer} stride - stride length
* @returns {number} standard deviation
*
* @example
* var x = [ 1.0, -2.0, NaN, 2.0 ];
*
* var v = nanstdevch( x.length, 1, x, 1 );
* // returns ~2.0817
*/
function nanstdevch( N, correction, x, stride ) {
	return sqrt( nanvariancech( N, correction, x, stride ) );
}

// EXPORTS //

module.exports = nanstdevch;


text:
import {
  filterSplice,
} from '../../../src/utils/array';

describe('filterSplice', function() {
  let array;
  beforeEach(() => {
    array = [1, 2, 3, 4, 5];
  });

  it('should splice elements that filter true', () => {
    filterSplice(array, i => i > 2);
    expect(array).to.deep.equal([3, 4, 5]);
  });

  it('should return filtered elements', () => {
    const filtered = filterSplice(array, i => i > 2);
    expect(filtered).to.deep.equal([1, 2]);
  });

  it('handles no removals', () => {
    const filtered = filterSplice(array, () => true);
    expect(array).to.deep.equal([1, 2, 3, 4, 5]);
    expect(filtered).to.deep.equal([]);
  });

  it('handles consecutive removals', () => {
    const filtered = filterSplice(array, () => false);
    expect(array).to.deep.equal([]);
    expect(filtered).to.deep.equal([1, 2, 3, 4, 5]);
  });
});


text:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 注意, 如果需要在当前工程中开发静态库, 需要配置targets > build Phases > target Dependencies > Link Binary WithLibraries

    NSLog(@"%d", [BGATool sumWithNum1:1 andNum2:2]);

    self.logoImageView.image = [BGATool loadLogoImage];
}

@end


text:
<?php declare(strict_types=1);

namespace App\Repository;

use App\Entity\Seizoen;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class SeizoenRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Seizoen::class);
    }

    public function getCurrent(): ?Seizoen
    {
        return $this->createQueryBuilder('s')->where('s.current = 1')->getQuery()->getOneOrNullResult();
    }

    public function getArchived(): array
    {
        return $this->createQueryBuilder('s')
            ->where('s.closed = 1')
            ->orderBy('s.start', 'ASC')
            ->getQuery()->getResult();
    }
}


text:
package org.apache.hadoop.hdds.scm;

import org.apache.hadoop.hdds.HddsUtils;
import org.apache.ratis.proto.RaftProtos;
import org.apache.ratis.retry.RetryPolicy;
import org.apache.ratis.thirdparty.com.google.protobuf
    .InvalidProtocolBufferException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdds.scm.client.HddsClientUtils;
import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ContainerCommandRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos
    .ContainerCommandResponseProto;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.ratis.RatisHelper;
import org.apache.ratis.client.RaftClient;
import org.apache.ratis.protocol.RaftClientReply;
import org.apache.ratis.rpc.RpcType;
import org.apache.ratis.rpc.SupportedRpcType;
import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

/**
 * An abstract implementation of {@link XceiverClientSpi} using Ratis.
 * The underlying RPC mechanism can be chosen via the constructor.
 */
public final class XceiverClientRatis extends XceiverClientSpi {
  static final Logger LOG = LoggerFactory.getLogger(XceiverClientRatis.class);

  public static XceiverClientRatis newXceiverClientRatis(
      org.apache.hadoop.hdds.scm.pipeline.Pipeline pipeline,
      Configuration ozoneConf) {
    final String rpcType = ozoneConf
        .get(ScmConfigKeys.DFS_CONTAINER_RATIS_RPC_TYPE_KEY,
            ScmConfigKeys.DFS_CONTAINER_RATIS_RPC_TYPE_DEFAULT);
    final int maxOutstandingRequests =
        HddsClientUtils.getMaxOutstandingRequests(ozoneConf);
    final RetryPolicy retryPolicy = RatisHelper.createRetryPolicy(ozoneConf);
    return new XceiverClientRatis(pipeline,
        SupportedRpcType.valueOfIgnoreCase(rpcType), maxOutstandingRequests,
        retryPolicy);
  }

  private final Pipeline pipeline;
  private final RpcType rpcType;
  private final AtomicReference<RaftClient> client = new AtomicReference<>();
  private final int maxOutstandingRequests;
  private final RetryPolicy retryPolicy;

  /**
   * Constructs a client.
   */
  private XceiverClientRatis(Pipeline pipeline, RpcType rpcType,
      int maxOutStandingChunks, RetryPolicy retryPolicy) {
    super();
    this.pipeline = pipeline;
    this.rpcType = rpcType;
    this.maxOutstandingRequests = maxOutStandingChunks;
    this.retryPolicy = retryPolicy;
  }

  /**
   * Returns Ratis as pipeline Type.
   *
   * @return - Ratis
   */
  @Override
  public HddsProtos.ReplicationType getPipelineType() {
    return HddsProtos.ReplicationType.RATIS;
  }

  @Override
  public Pipeline getPipeline() {
    return pipeline;
  }

  @Override
  public void connect() throws Exception {
    LOG.debug("Connecting to pipeline:{} datanode:{}", getPipeline().getId(),
        RatisHelper.toRaftPeerId(pipeline.getFirstNode()));
    // TODO : XceiverClient ratis should pass the config value of
    // maxOutstandingRequests so as to set the upper bound on max no of async
    // requests to be handled by raft client
    if (!client.compareAndSet(null,
        RatisHelper.newRaftClient(rpcType, getPipeline(), retryPolicy))) {
      throw new IllegalStateException("Client is already connected.");
    }
  }

  @Override
  public void close() {
    final RaftClient c = client.getAndSet(null);
    if (c != null) {
      closeRaftClient(c);
    }
  }

  private void closeRaftClient(RaftClient raftClient) {
    try {
      raftClient.close();
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }

  private RaftClient getClient() {
    return Objects.requireNonNull(client.get(), "client is null");
  }

  private CompletableFuture<RaftClientReply> sendRequestAsync(
      ContainerCommandRequestProto request) {
    boolean isReadOnlyRequest = HddsUtils.isReadOnly(request);
    ByteString byteString = request.toByteString();
    LOG.debug("sendCommandAsync {} {}", isReadOnlyRequest, request);
    return isReadOnlyRequest ? getClient().sendReadOnlyAsync(() -> byteString) :
        getClient().sendAsync(() -> byteString);
  }

  @Override
  public void watchForCommit(long index, long timeout)
      throws InterruptedException, ExecutionException, TimeoutException,
      IOException {
    LOG.debug("commit index : {} watch timeout : {}", index, timeout);
    // create a new RaftClient instance for watch request
    RaftClient raftClient =
        RatisHelper.newRaftClient(rpcType, getPipeline(), retryPolicy);
    CompletableFuture<RaftClientReply> replyFuture = raftClient
        .sendWatchAsync(index, RaftProtos.ReplicationLevel.ALL_COMMITTED);
    try {
      replyFuture.get(timeout, TimeUnit.MILLISECONDS);
    } catch (TimeoutException toe) {
      LOG.warn("3 way commit failed ", toe);

      closeRaftClient(raftClient);
      // generate a new raft client instance again so that next watch request
      // does not get blocked for the previous one

      // TODO : need to remove the code to create the new RaftClient instance
      // here once the watch request bypassing sliding window in Raft Client
      // gets fixed.
      raftClient =
          RatisHelper.newRaftClient(rpcType, getPipeline(), retryPolicy);
      raftClient
          .sendWatchAsync(index, RaftProtos.ReplicationLevel.MAJORITY_COMMITTED)
          .get(timeout, TimeUnit.MILLISECONDS);
      LOG.info("Could not commit " + index + " to all the nodes."
          + "Committed by majority.");
    } finally {
      closeRaftClient(raftClient);
    }
  }
  /**
   * Sends a given command to server gets a waitable future back.
   *
   * @param request Request
   * @return Response to the command
   */
  @Override
  public XceiverClientAsyncReply sendCommandAsync(
      ContainerCommandRequestProto request) {
    XceiverClientAsyncReply asyncReply = new XceiverClientAsyncReply(null);
    CompletableFuture<RaftClientReply> raftClientReply =
        sendRequestAsync(request);
    Collection<XceiverClientAsyncReply.CommitInfo> commitInfos =
        new ArrayList<>();
    CompletableFuture<ContainerCommandResponseProto> containerCommandResponse =
        raftClientReply.whenComplete((reply, e) -> LOG
            .debug("received reply {} for request: {} exception: {}", request,
                reply, e))
            .thenApply(reply -> {
              try {
                ContainerCommandResponseProto response =
                    ContainerCommandResponseProto
                        .parseFrom(reply.getMessage().getContent());
                reply.getCommitInfos().forEach(e -> {
                  XceiverClientAsyncReply.CommitInfo commitInfo =
                      new XceiverClientAsyncReply.CommitInfo(
                          e.getServer().getAddress(), e.getCommitIndex());
                  commitInfos.add(commitInfo);
                  asyncReply.setCommitInfos(commitInfos);
                  asyncReply.setLogIndex(reply.getLogIndex());
                });
                return response;
              } catch (InvalidProtocolBufferException e) {
                throw new CompletionException(e);
              }
            });
    asyncReply.setResponse(containerCommandResponse);
    return asyncReply;
  }

}


text:
package org.zstack.storage.primary.smp;

import org.zstack.header.storage.primary.PrimaryStorageInventory;

/**
 * Created by xing5 on 2016/3/27.
 */
public interface BackupStorageKvmFactory {
    String getBackupStorageType();

    BackupStorageKvmUploader createUploader(PrimaryStorageInventory ps, String bsUuid);

    BackupStorageKvmDownloader createDownloader(PrimaryStorageInventory ps, String bsUuid);
}


text:
package com.haulmont.cuba.gui.xml.layout.loaders;

import com.haulmont.cuba.gui.components.ColorPicker;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;

public class ColorPickerLoader extends AbstractFieldLoader<ColorPicker>{

    @Override
    public void createComponent() {
        resultComponent = factory.create(ColorPicker.NAME);
        loadId(resultComponent, element);
    }

    @Override
    public void loadComponent() {
        super.loadComponent();

        loadTabIndex(resultComponent, element);

        loadHSVVisibility(resultComponent, element);
        loadSwatchesVisibility(resultComponent, element);
        loadRGBVisibility(resultComponent, element);
        loadHistoryVisibility(resultComponent, element);
        loadDefaultCaptionEnabled(resultComponent, element);

        loadCancelButtonCaption(resultComponent, element);
        loadConfirmButtonCaption(resultComponent, element);

        loadLookupAllCaption(resultComponent, element);
        loadLookupBlueCaption(resultComponent, element);
        loadLookupGreenCaption(resultComponent, element);
        loadLookupRedCaption(resultComponent, element);
        loadButtonCaption(resultComponent, element);

        loadRedSliderCaption(resultComponent, element);
        loadGreenSliderCaption(resultComponent, element);
        loadBlueSliderCaption(resultComponent, element);
        loadHueSliderCaption(resultComponent, element);
        loadSaturationSliderCaption(resultComponent, element);
        loadValueSliderCaption(resultComponent, element);

        loadPopupCaption(resultComponent, element);
        loadSwatchesTabCaption(resultComponent, element);
        loadResponsive(resultComponent, element);

        loadBuffered(resultComponent, element);
    }

    protected void loadRedSliderCaption(ColorPicker component, Element element) {
        String redSliderCaption = element.attributeValue("redSliderCaption");
        if (StringUtils.isNotEmpty(redSliderCaption)) {
            component.setRedSliderCaption(loadResourceString(redSliderCaption));
        }
    }

    protected void loadGreenSliderCaption(ColorPicker component, Element element) {
        String greenSliderCaption = element.attributeValue("greenSliderCaption");
        if (StringUtils.isNotEmpty(greenSliderCaption)) {
            component.setGreenSliderCaption(loadResourceString(greenSliderCaption));
        }
    }

    protected void loadBlueSliderCaption(ColorPicker component, Element element) {
        String blueSliderCaption = element.attributeValue("blueSliderCaption");
        if (StringUtils.isNotEmpty(blueSliderCaption)) {
            component.setBlueSliderCaption(loadResourceString(blueSliderCaption));
        }
    }

    protected void loadHueSliderCaption(ColorPicker component, Element element) {
        String hueSliderCaption = element.attributeValue("hueSliderCaption");
        if (StringUtils.isNotEmpty(hueSliderCaption)) {
            component.setHueSliderCaption(loadResourceString(hueSliderCaption));
        }
    }

    protected void loadSaturationSliderCaption(ColorPicker component, Element element) {
        String saturationSliderCaption = element.attributeValue("saturationSliderCaption");
        if (StringUtils.isNotEmpty(saturationSliderCaption)) {
            component.setSaturationSliderCaption(loadResourceString(saturationSliderCaption));
        }
    }

    protected void loadValueSliderCaption(ColorPicker component, Element element) {
        String valueSliderCaption = element.attributeValue("valueSliderCaption");
        if (StringUtils.isNotEmpty(valueSliderCaption)) {
            component.setValueSliderCaption(loadResourceString(valueSliderCaption));
        }
    }

    protected void loadPopupCaption(ColorPicker component, Element element) {
        String popupCaption = element.attributeValue("popupCaption");
        if (StringUtils.isNotEmpty(popupCaption)) {
            component.setPopupCaption(loadResourceString(popupCaption));
        }
    }

    protected void loadConfirmButtonCaption(ColorPicker component, Element element) {
        String confirmButtonCaption = element.attributeValue("confirmButtonCaption");
        if (StringUtils.isNotEmpty(confirmButtonCaption)) {
            component.setConfirmButtonCaption(loadResourceString(confirmButtonCaption));
        }
    }

    protected void loadCancelButtonCaption(ColorPicker component, Element element) {
        String cancelButtonCaption = element.attributeValue("cancelButtonCaption");
        if (StringUtils.isNotEmpty(cancelButtonCaption)) {
            component.setCancelButtonCaption(loadResourceString(cancelButtonCaption));
        }
    }

    protected void loadSwatchesTabCaption(ColorPicker component, Element element) {
        String swatchesTabCaption = element.attributeValue("swatchesTabCaption");
        if (StringUtils.isNotEmpty(swatchesTabCaption)) {
            component.setSwatchesTabCaption(loadResourceString(swatchesTabCaption));
        }
    }

    protected void loadLookupAllCaption(ColorPicker component, Element element) {
        String lookupAllCaption = element.attributeValue("lookupAllCaption");
        if (StringUtils.isNotEmpty(lookupAllCaption)) {
            component.setLookupAllCaption(loadResourceString(lookupAllCaption));
        }
    }

    protected void loadLookupRedCaption(ColorPicker component, Element element) {
        String lookupRedCaption = element.attributeValue("lookupRedCaption");
        if (StringUtils.isNotEmpty(lookupRedCaption)) {
            component.setLookupRedCaption(loadResourceString(lookupRedCaption));
        }
    }

    protected void loadLookupGreenCaption(ColorPicker component, Element element) {
        String lookupGreenCaption = element.attributeValue("lookupGreenCaption");
        if (StringUtils.isNotEmpty(lookupGreenCaption)) {
            component.setLookupGreenCaption(loadResourceString(lookupGreenCaption));
        }
    }

    protected void loadLookupBlueCaption(ColorPicker component, Element element) {
        String lookupBlueCaption = element.attributeValue("lookupBlueCaption");
        if (StringUtils.isNotEmpty(lookupBlueCaption)) {
            component.setLookupBlueCaption(loadResourceString(lookupBlueCaption));
        }
    }

    protected void loadSwatchesVisibility(ColorPicker component, Element element) {
        String swatchesVisible = element.attributeValue("swatchesVisible");
        if (StringUtils.isNotEmpty(swatchesVisible)) {
            component.setSwatchesVisible(Boolean.parseBoolean(swatchesVisible));
        }
    }

    protected void loadRGBVisibility(ColorPicker component, Element element) {
        String rgbVisible = element.attributeValue("rgbVisible");
        if (StringUtils.isNotEmpty(rgbVisible)) {
            component.setRGBVisible(Boolean.parseBoolean(rgbVisible));
        }
    }

    protected void loadHSVVisibility(ColorPicker component, Element element) {
        String hsvVisible = element.attributeValue("hsvVisible");
        if (StringUtils.isNotEmpty(hsvVisible)) {
            component.setHSVVisible(Boolean.parseBoolean(hsvVisible));
        }
    }

    protected void loadHistoryVisibility(ColorPicker component, Element element) {
        String historyVisible = element.attributeValue("historyVisible");
        if (StringUtils.isNotEmpty(historyVisible)) {
            component.setHistoryVisible(Boolean.parseBoolean(historyVisible));
        }
    }

    protected void loadDefaultCaptionEnabled(ColorPicker component, Element element) {
        String defaultCaptionEnabled = element.attributeValue("defaultCaptionEnabled");
        if (StringUtils.isNotEmpty(defaultCaptionEnabled)) {
            component.setDefaultCaptionEnabled(Boolean.parseBoolean(defaultCaptionEnabled));
        }
    }

    protected void loadButtonCaption(ColorPicker component, Element element) {
        String buttonCaption = element.attributeValue("buttonCaption");
        if (StringUtils.isNotEmpty(buttonCaption)) {
            component.setButtonCaption(loadResourceString(buttonCaption));
        }
    }
}


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.5.9">
  <compounddef id="dir_cf67b188d77b2f5b9ae83c7091a6563f" kind="dir">
    <compoundname>/Users/keith/Projects/Source/RMUpload/documentation/RMUploadKit.sdk/Library/Frameworks/RMUploadKit.framework/</compoundname>
    <innerdir refid="dir_ed54f06b6481195d07963b2cbf730f78">/Users/keith/Projects/Source/RMUpload/documentation/RMUploadKit.sdk/Library/Frameworks/RMUploadKit.framework/Versions/</innerdir>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="/Users/keith/Projects/Source/RMUpload/documentation/RMUploadKit.sdk/Library/Frameworks/RMUploadKit.framework/"/>
  </compounddef>
</doxygen>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aposphaeria rubefaciens Bubák

### Remarks
null


text:
import { CommonModule } from '@angular/common';
import { TestBed } from '@angular/core/testing';
import { RouterModule } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { expect } from '@skyux-sdk/testing';
import { SkyIconModule } from '@skyux/indicators';
import { SkyAppLinkModule, SkyHrefModule } from '@skyux/router';
import { SkyThemeModule } from '@skyux/theme';

import { PageHeaderFixturesComponent } from './fixtures/page-header-fixtures.component';
import { SkyPageHeaderComponent } from './page-header.component';

describe('Page header component', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [PageHeaderFixturesComponent, SkyPageHeaderComponent],
      imports: [
        RouterModule,
        CommonModule,
        SkyAppLinkModule,
        SkyThemeModule,
        SkyIconModule,
        SkyHrefModule,
        RouterTestingModule.withRoutes([]),
      ],
    });
  });

  it('should create a page header', () => {
    const fixture = TestBed.createComponent(PageHeaderFixturesComponent);
    fixture.detectChanges();
    expect(fixture.nativeElement).toHaveText('Parent Link Page Title');
  });
});


text:
namespace chromeos {

class MockShillServiceClient : public ShillServiceClient {
 public:
  MockShillServiceClient();
  virtual ~MockShillServiceClient();

  MOCK_METHOD2(AddPropertyChangedObserver,
               void(const dbus::ObjectPath& service_path,
                    ShillPropertyChangedObserver* observer));
  MOCK_METHOD2(RemovePropertyChangedObserver,
               void(const dbus::ObjectPath& service_path,
                    ShillPropertyChangedObserver* observer));
  MOCK_METHOD2(GetProperties, void(const dbus::ObjectPath& service_path,
                                   const DictionaryValueCallback& callback));
  MOCK_METHOD5(SetProperty, void(const dbus::ObjectPath& service_path,
                                 const std::string& name,
                                 const base::Value& value,
                                 const base::Closure& callback,
                                 const ErrorCallback& error_callback));
  MOCK_METHOD4(SetProperties, void(const dbus::ObjectPath& service_path,
                                   const base::DictionaryValue& properties,
                                   const base::Closure& callback,
                                   const ErrorCallback& error_callback));
  MOCK_METHOD4(ClearProperty, void(const dbus::ObjectPath& service_path,
                                   const std::string& name,
                                   const base::Closure& callback,
                                   const ErrorCallback& error_callback));
  MOCK_METHOD4(ClearProperties, void(const dbus::ObjectPath& service_path,
                                     const std::vector<std::string>& names,
                                     const ListValueCallback& callback,
                                     const ErrorCallback& error_callback));
  MOCK_METHOD3(Connect, void(const dbus::ObjectPath& service_path,
                             const base::Closure& callback,
                             const ErrorCallback& error_callback));
  MOCK_METHOD3(Disconnect, void(const dbus::ObjectPath& service_path,
                                const base::Closure& callback,
                                const ErrorCallback& error_callback));
  MOCK_METHOD3(Remove, void(const dbus::ObjectPath& service_path,
                            const base::Closure& callback,
                            const ErrorCallback& error_callback));
  MOCK_METHOD4(ActivateCellularModem,
               void(const dbus::ObjectPath& service_path,
                    const std::string& carrier,
                    const base::Closure& callback,
                    const ErrorCallback& error_callback));
  MOCK_METHOD3(CompleteCellularActivation,
               void(const dbus::ObjectPath& service_path,
                    const base::Closure& callback,
                    const ErrorCallback& error_callback));
  MOCK_METHOD2(CallActivateCellularModemAndBlock,
               bool(const dbus::ObjectPath& service_path,
                    const std::string& carrier));
  MOCK_METHOD2(GetLoadableProfileEntries,
               void(const dbus::ObjectPath& service_path,
                    const DictionaryValueCallback& callback));
  MOCK_METHOD0(GetTestInterface, TestInterface*());
};

}  // namespace chromeos

#endif  // CHROMEOS_DBUS_MOCK_SHILL_SERVICE_CLIENT_H_


text:
Extend the Express response object to set the status code and return JSON

## Usage

`npm install --save express-json-status-codes`

```
var express = require('express'),
    statusCodes = require('express-json-status-codes');

// Add the new responses to the `express.response` prototype
var extendedExpress = statusCodes(express);

var app = extendedExpress();
...
app.get('/', function(req, res) {
  res.ok('What's up');
});
```

## Available API

From `http-status-codes`:

```
accepted 202
badGateway 502
badRequest 400
conflict 409
continue 100
created 201
expectationFailed 417
failedDependency 424
forbidden 403
gatewayTimeout 504
gone 410
httpVersionNotSupported 505
insufficientSpaceOnResource 419
insufficientStorage 507
internalServerError 500
lengthRequired 411
locked 423
methodFailure 420
methodNotAllowed 405
movedPermanently 301
movedTemporarily 302
multiStatus 207
multipleChoices 300
networkAuthenticationRequired 511
noContent 204
nonAuthoritativeInformation 203
notAcceptable 406
notFound 404
notImplemented 501
notModified 304
ok 200
partialContent 206
paymentRequired 402
preconditionFailed 412
preconditionRequired 428
processing 102
proxyAuthenticationRequired 407
requestHeaderFieldsTooLarge 431
requestTimeout 408
requestTooLong 413
requestUriTooLong 414
requestedRangeNotSatisfiable 416
resetContent 205
seeOther 303
serviceUnavailable 503
switchingProtocols 101
temporaryRedirect 307
tooManyRequests 429
unauthorized 401
unprocessableEntity 422
unsupportedMediaType 415
useProxy 305
```


text:
import express = require('express');
import minify = require('express-minify');
import uglifyJS = require('uglify-js');

var app = express();
app.use(minify());
app.use(minify({
    cache: false,
    cssmin: require('cssmin'),
    uglifyJS: require('uglify-js')
}));

app.get('/', function (req: express.Request, res: express.Response) {
    res._skip = true;
    res._no_minify = false;
    res._no_cache = true;
    res._uglifyMangle = false;

    var outputOptions: uglifyJS.BeautifierOptions = {
        beautify: true,
        comments: false
    };

    res._uglifyOutput = outputOptions;

    res._uglifyCompress = false;

    var compressionOptions: uglifyJS.CompressorOptions = {
        cascade: true
    };

    res._uglifyCompress = compressionOptions;
})


text:
Términos y Condiciones

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eleifend aliquet nisl, id pretium mi consectetur in. Integer ultricies tristique pretium. Duis est magna, aliquam in pellentesque nec, semper non tortor. Maecenas varius dapibus posuere. Fusce pharetra nisi sed tortor congue blandit. Suspendisse mi orci, convallis ac turpis id, vestibulum tristique metus. In pellentesque lectus odio, a consequat lectus varius vel. Nulla eleifend arcu vel malesuada lacinia.

                        Pellentesque faucibus vehicula porta. Pellentesque rutrum tincidunt aliquet. Vivamus volutpat aliquam nulla in suscipit. Morbi dignissim sed libero id euismod. Mauris justo nulla, dignissim sit amet augue ut, aliquet sollicitudin ligula. Nunc fermentum imperdiet nisi nec elementum. Phasellus egestas pellentesque justo, non sodales libero laoreet a. Pellentesque lobortis sodales neque lacinia molestie. Donec eros turpis, dignissim a elit eget, aliquet egestas odio. Maecenas est arcu, pretium non gravida et, accumsan eget diam. Cras placerat turpis ac elit pharetra dictum. Maecenas orci mauris, ornare sit amet felis ut, ultrices dictum purus.

                        Nullam sed ornare sapien, sit amet porttitor nulla. Duis et magna vel est tempus vehicula vitae sit amet enim. Sed vitae ligula congue, luctus mauris eu, scelerisque felis. Quisque aliquet ornare nunc in viverra. Nullam ornare molestie ligula in luctus. Suspendisse ac cursus elit. Donec vel enim sit amet lorem vulputate condimentum. Sed nec gravida elit. Morbi et orci sagittis lorem suscipit porta. Nam scelerisque, massa vel volutpat volutpat, dui leo consectetur urna, non posuere purus sem quis justo.

                        Integer eget bibendum erat, et tempor diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean ullamcorper ut ipsum vel egestas. Aenean ornare risus in lectus bibendum, sit amet euismod quam accumsan. Vestibulum nec ante in ipsum bibendum porta a ac est. Vestibulum cursus molestie ante, eu bibendum lectus tincidunt sit amet. Nullam adipiscing, tortor at porttitor venenatis, dolor felis sollicitudin elit, ut gravida nunc velit vitae mauris. Curabitur quis pulvinar arcu. Mauris nulla sem, feugiat at hendrerit sed, accumsan sit amet odio. Cras pharetra vehicula nunc eget bibendum. In iaculis diam eros, eu elementum ipsum tincidunt euismod.

                        Sed ornare quam in massa iaculis sagittis sit amet eu arcu. Nulla facilisi. Sed diam augue, hendrerit in adipiscing ac, congue sit amet tellus. Sed quis rhoncus ante. Curabitur a ligula hendrerit, volutpat nisi nec, vehicula nisi. Vestibulum vestibulum lorem ligula, non dignissim lacus consequat lobortis. Pellentesque sem purus, consequat et arcu ac, fermentum laoreet sapien. Praesent sed leo nec tellus ultrices auctor vestibulum a metus. Curabitur sed urna sit amet tortor fringilla ullamcorper sed sed velit.


text:
module SimpleForm
  module Inputs
    class DatePickerInput < Base
      def input(wrapper_options = nil)
        @builder.datetime_field(attribute_name, input_html_options)
      end

      private

      def input_html_options
        if options.key?(:input_html) && options[:input_html].key?(:value)
          value = options[:input_html][:value]
        elsif options.key? :value
          value = options[:value]
        elsif object.respond_to?(attribute_name)
          value = object.send(attribute_name)
        else
          value = ''
        end

        value = Time.zone.parse(value) if value.is_a?(String)
        value = value.strftime("%Y-%m-%d") if value.respond_to?(:strftime)

        result = { class: 'form-control text-center date datepicker', value: value.presence || '' }
        if options.key? :input_html
          result[:class] += ' ' + options[:input_html][:class] if options[:input_html][:class].present?
          result.merge(options[:input_html].except(:class, :value))
        else
          result
        end
      end
    end
  end
end


text:
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * ASM: a very small and fast Java bytecode manipulation framework
 * Copyright (c) 2000-2011 INRIA, France Telecom
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holders nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.redkale.asm;

/**
 * A dynamically extensible vector of bytes. This class is roughly equivalent to
 * a DataOutputStream on top of a ByteArrayOutputStream, but is more efficient.
 *
 * @author Eric Bruneton
 */
public class ByteVector {

    /**
     * The content of this vector.
     */
    byte[] data;

    /**
     * Actual number of bytes in this vector.
     */
    int length;

    /**
     * Constructs a new {@link ByteVector ByteVector} with a default initial
     * size.
     */
    public ByteVector() {
        data = new byte[64];
    }

    /**
     * Constructs a new {@link ByteVector ByteVector} with the given initial
     * size.
     *
     * @param initialSize
     *            the initial size of the byte vector to be constructed.
     */
    public ByteVector(final int initialSize) {
        data = new byte[initialSize];
    }

    /**
     * Puts a byte into this byte vector. The byte vector is automatically
     * enlarged if necessary.
     *
     * @param b
     *            a byte.
     * @return this byte vector.
     */
    public ByteVector putByte(final int b) {
        int length = this.length;
        if (length + 1 > data.length) {
            enlarge(1);
        }
        data[length++] = (byte) b;
        this.length = length;
        return this;
    }

    /**
     * Puts two bytes into this byte vector. The byte vector is automatically
     * enlarged if necessary.
     *
     * @param b1
     *            a byte.
     * @param b2
     *            another byte.
     * @return this byte vector.
     */
    ByteVector put11(final int b1, final int b2) {
        int length = this.length;
        if (length + 2 > data.length) {
            enlarge(2);
        }
        byte[] data = this.data;
        data[length++] = (byte) b1;
        data[length++] = (byte) b2;
        this.length = length;
        return this;
    }

    /**
     * Puts a short into this byte vector. The byte vector is automatically
     * enlarged if necessary.
     *
     * @param s
     *            a short.
     * @return this byte vector.
     */
    public ByteVector putShort(final int s) {
        int length = this.length;
        if (length + 2 > data.length) {
            enlarge(2);
        }
        byte[] data = this.data;
        data[length++] = (byte) (s >>> 8);
        data[length++] = (byte) s;
        this.length = length;
        return this;
    }

    /**
     * Puts a byte and a short into this byte vector. The byte vector is
     * automatically enlarged if necessary.
     *
     * @param b
     *            a byte.
     * @param s
     *            a short.
     * @return this byte vector.
     */
    ByteVector put12(final int b, final int s) {
        int length = this.length;
        if (length + 3 > data.length) {
            enlarge(3);
        }
        byte[] data = this.data;
        data[length++] = (byte) b;
        data[length++] = (byte) (s >>> 8);
        data[length++] = (byte) s;
        this.length = length;
        return this;
    }

    /**
     * Puts an int into this byte vector. The byte vector is automatically
     * enlarged if necessary.
     *
     * @param i
     *            an int.
     * @return this byte vector.
     */
    public ByteVector putInt(final int i) {
        int length = this.length;
        if (length + 4 > data.length) {
            enlarge(4);
        }
        byte[] data = this.data;
        data[length++] = (byte) (i >>> 24);
        data[length++] = (byte) (i >>> 16);
        data[length++] = (byte) (i >>> 8);
        data[length++] = (byte) i;
        this.length = length;
        return this;
    }

    /**
     * Puts a long into this byte vector. The byte vector is automatically
     * enlarged if necessary.
     *
     * @param l
     *            a long.
     * @return this byte vector.
     */
    public ByteVector putLong(final long l) {
        int length = this.length;
        if (length + 8 > data.length) {
            enlarge(8);
        }
        byte[] data = this.data;
        int i = (int) (l >>> 32);
        data[length++] = (byte) (i >>> 24);
        data[length++] = (byte) (i >>> 16);
        data[length++] = (byte) (i >>> 8);
        data[length++] = (byte) i;
        i = (int) l;
        data[length++] = (byte) (i >>> 24);
        data[length++] = (byte) (i >>> 16);
        data[length++] = (byte) (i >>> 8);
        data[length++] = (byte) i;
        this.length = length;
        return this;
    }

    /**
     * Puts an UTF8 string into this byte vector. The byte vector is
     * automatically enlarged if necessary.
     *
     * @param s
     *            a String whose UTF8 encoded length must be less than 65536.
     * @return this byte vector.
     */
    public ByteVector putUTF8(final String s) {
        int charLength = s.length();
        if (charLength > 65535) {
            throw new IllegalArgumentException();
        }
        int len = length;
        if (len + 2 + charLength > data.length) {
            enlarge(2 + charLength);
        }
        byte[] data = this.data;
        // optimistic algorithm: instead of computing the byte length and then
        // serializing the string (which requires two loops), we assume the byte
        // length is equal to char length (which is the most frequent case), and
        // we start serializing the string right away. During the serialization,
        // if we find that this assumption is wrong, we continue with the
        // general method.
        data[len++] = (byte) (charLength >>> 8);
        data[len++] = (byte) charLength;
        for (int i = 0; i < charLength; ++i) {
            char c = s.charAt(i);
            if (c >= '\001' && c <= '\177') {
                data[len++] = (byte) c;
            } else {
                length = len;
                return encodeUTF8(s, i, 65535);
            }
        }
        length = len;
        return this;
    }

    /**
     * Puts an UTF8 string into this byte vector. The byte vector is
     * automatically enlarged if necessary. The string length is encoded in two
     * bytes before the encoded characters, if there is space for that (i.e. if
     * this.length - i - 2 >= 0).
     *
     * @param s
     *            the String to encode.
     * @param i
     *            the index of the first character to encode. The previous
     *            characters are supposed to have already been encoded, using
     *            only one byte per character.
     * @param maxByteLength
     *            the maximum byte length of the encoded string, including the
     *            already encoded characters.
     * @return this byte vector.
     */
    ByteVector encodeUTF8(final String s, int i, int maxByteLength) {
        int charLength = s.length();
        int byteLength = i;
        char c;
        for (int j = i; j < charLength; ++j) {
            c = s.charAt(j);
            if (c >= '\001' && c <= '\177') {
                byteLength++;
            } else if (c > '\u07FF') {
                byteLength += 3;
            } else {
                byteLength += 2;
            }
        }
        if (byteLength > maxByteLength) {
            throw new IllegalArgumentException();
        }
        int start = length - i - 2;
        if (start >= 0) {
          data[start] = (byte) (byteLength >>> 8);
          data[start + 1] = (byte) byteLength;
        }
        if (length + byteLength - i > data.length) {
            enlarge(byteLength - i);
        }
        int len = length;
        for (int j = i; j < charLength; ++j) {
            c = s.charAt(j);
            if (c >= '\001' && c <= '\177') {
                data[len++] = (byte) c;
            } else if (c > '\u07FF') {
                data[len++] = (byte) (0xE0 | c >> 12 & 0xF);
                data[len++] = (byte) (0x80 | c >> 6 & 0x3F);
                data[len++] = (byte) (0x80 | c & 0x3F);
            } else {
                data[len++] = (byte) (0xC0 | c >> 6 & 0x1F);
                data[len++] = (byte) (0x80 | c & 0x3F);
            }
        }
        length = len;
        return this;
    }

    /**
     * Puts an array of bytes into this byte vector. The byte vector is
     * automatically enlarged if necessary.
     *
     * @param b
     *            an array of bytes. May be null to put len
     *            null bytes into this byte vector.
     * @param off
     *            index of the fist byte of b that must be copied.
     * @param len
     *            number of bytes of b that must be copied.
     * @return this byte vector.
     */
    public ByteVector putByteArray(final byte[] b, final int off, final int len) {
        if (length + len > data.length) {
            enlarge(len);
        }
        if (b != null) {
            System.arraycopy(b, off, data, length, len);
        }
        length += len;
        return this;
    }

    /**
     * Enlarge this byte vector so that it can receive n more bytes.
     *
     * @param size
     *            number of additional bytes that this byte vector should be
     *            able to receive.
     */
    private void enlarge(final int size) {
        int length1 = 2 * data.length;
        int length2 = length + size;
        byte[] newData = new byte[length1 > length2 ? length1 : length2];
        System.arraycopy(data, 0, newData, 0, length);
        data = newData;
    }
}


text:
package org.hisrc.camel.component.gcm.tests;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.hisrc.camel.component.gcm.GcmConstants;
import org.junit.Test;

public class GcmEndpointTest extends CamelTestSupport {

	private static final String TEST_GCM_PROPERTIES = "/test.gcm.properties";

	private Properties loadProperties(final String source) throws IOException {
		final Properties properties = new Properties();
		try {
			properties.load(getClass().getResourceAsStream(source));
		} catch (Exception e) {
			throw new IOException(e);
		}
		return properties;
	}

	@Test
	public void sendsComplexMessageWithSpecifiedToHeader() throws Exception {
		MockEndpoint mock = getMockEndpoint("mock:result");
		mock.expectedMinimumMessageCount(1);
		final Map<String, String> body = new HashMap<String, String>();
		body.put("facilityEquipmentnumber", "10213788");
		body.put("stationName", "Arnstadt Hbf");
		body.put("facilityDescription", "Aufzug zu Bstg 2/3");
		body.put("facilityState", "INACTIVE");
		final Map<String, Object> headers = new HashMap<String, Object>();
		headers.put(GcmConstants.TO, "/topics/foo");
		sendBody("direct:foo", body, headers);
		assertMockEndpointsSatisfied();
	}

	@Test
	public void sendsComplexMessageWithoutSpecifiedToHeader() throws Exception {
		MockEndpoint mock = getMockEndpoint("mock:result");
		mock.expectedMinimumMessageCount(1);
		final Map<String, String> body = new HashMap<String, String>();
		body.put("facilityEquipmentnumber", "10213788");
		body.put("stationName", "Arnstadt Hbf");
		body.put("facilityDescription", "Aufzug zu Bstg 2/3");
		body.put("facilityState", "INACTIVE");
		sendBody("direct:foo", body);
		assertMockEndpointsSatisfied();
	}

	@Test
	public void sendsSimpleMessage() throws Exception {
		MockEndpoint mock = getMockEndpoint("mock:result");
		mock.expectedMinimumMessageCount(1);
		sendBody("direct:foo", "doo");
		assertMockEndpointsSatisfied();
	}

	@Override
	protected RouteBuilder createRouteBuilder() throws Exception {
		final String apiKey = loadProperties(TEST_GCM_PROPERTIES).getProperty("gcm.apiKey");
		return new RouteBuilder() {
			public void configure() {
				from("direct:foo").to("gcm:/topics/bar?apiKey=" + apiKey).to("mock:result");
			}
		};
	}
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request.parser;

import com.yahoo.javacc.FastCharStream;

/**
 * @author Simon Thoresen Hult
 */
public class GroupingParserInput extends FastCharStream implements CharStream {

    public GroupingParserInput(String input) {
        super(input);
    }
}