text:
<?php

namespace SensioLabs\Deptrac\DependencyResult;

use SensioLabs\AstRunner\AstMap\AstInheritInterface;

class InheritDependency implements DependencyInterface
{
    private $classA;

    /** @var Dependency */
    private $classB;

    /** @var AstInheritInterface */
    private $path;

    /** @var Dependency */
    private $originalDependency;

    /**
     * @param $classA
     * @param AstInheritInterface $path
     */
    public function __construct($classA, $classB, DependencyInterface $originalDependency, AstInheritInterface $path)
    {
        $this->classA = $classA;
        $this->classB = $classB;
        $this->originalDependency = $originalDependency;
        $this->path = $path;
    }

    public function getClassA()
    {
        return $this->classA;
    }

    public function getClassALine()
    {
        return '';
    }

    public function getClassB()
    {
        return $this->classB;
    }

    /**
     * @return AstInheritInterface
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @return Dependency
     */
    public function getOriginalDependency()
    {
        return $this->originalDependency;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  NSObject+BSKUtils.h
//  BSKToolsBoxDemo
//
//  Created by 刘万林 on 2017/7/17.
//  Copyright © 2017年 BlueSky335. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSObject (BSKUtils)
/*判断是否是NSNULL类*/
-(BOOL)bsk_isNullObject;
@end


text:
import clipNumber from 'helper/number/clip_number';
import coerceToString from 'helper/string/coerce_to_string';
import isNil from 'helper/object/is_nil';
import toInteger from 'helper/number/to_integer';
import toString from 'helper/string/to_string';

/**
 * Checks whether `subject` starts with `start`.
 *
 * @function startsWith
 * @static
 * @since 1.0.0
 * @memberOf Query
 * @param {string} [subject=''] The string to verify.
 * @param {string} start The starting string.
 * @param {number} [position=0] The position to start searching.
 * @return {boolean} Returns `true` if `subject` starts with `start` or `false` otherwise.
 * @example
 * v.startsWith('say hello to my little friend', 'say hello');
 * // => true
 *
 * v.startsWith('tony', 'on', 1);
 * // => true
 *
 * v.startsWith('the world is yours', 'world');
 * // => false
 */
export default function startsWith(subject, start, position) {
  const subjectString = coerceToString(subject);
  const startString = toString(start);
  if (startString === null) {
    return false;
  }
  if (startString === '') {
    return true;
  }
  position = isNil(position) ? 0 : clipNumber(toInteger(position), 0, subjectString.length);
  return subjectString.substr(position, startString.length) === startString;
}


text:
package com.amazonaws.services.dynamodbv2.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Represents a request to perform a PutItem operation.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Put implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * A map of attribute name to attribute values, representing the primary key of the item to be written by
     * PutItem. All of the table's primary key attributes must be specified, and their data types must
     * match those of the table's key schema. If any attributes are present in the item that are part of an index key
     * schema for the table, their types must match the index key schema.
     *

     */
    private java.util.Map<String, AttributeValue> item;
    /**
     *

     * Name of the table in which to write the item.
     *

     */
    private String tableName;
    /**
     *

     * A condition that must be satisfied in order for a conditional update to succeed.
     *

     */
    private String conditionExpression;
    /**
     *

     * One or more substitution tokens for attribute names in an expression.
     *

     */
    private java.util.Map<String, String> expressionAttributeNames;
    /**
     *

     * One or more values that can be substituted in an expression.
     *

     */
    private java.util.Map<String, AttributeValue> expressionAttributeValues;
    /**
     *

     * Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put condition
     * fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and ALL_OLD.
     *

     */
    private String returnValuesOnConditionCheckFailure;

    /**
     *

     * A map of attribute name to attribute values, representing the primary key of the item to be written by
     * PutItem. All of the table's primary key attributes must be specified, and their data types must
     * match those of the table's key schema. If any attributes are present in the item that are part of an index key
     * schema for the table, their types must match the index key schema.
     *

     *
     * @return A map of attribute name to attribute values, representing the primary key of the item to be written by
     *         PutItem. All of the table's primary key attributes must be specified, and their data types
     *         must match those of the table's key schema. If any attributes are present in the item that are part of an
     *         index key schema for the table, their types must match the index key schema.
     */

    public java.util.Map<String, AttributeValue> getItem() {
        return item;
    }

    /**
     *

     * A map of attribute name to attribute values, representing the primary key of the item to be written by
     * PutItem. All of the table's primary key attributes must be specified, and their data types must
     * match those of the table's key schema. If any attributes are present in the item that are part of an index key
     * schema for the table, their types must match the index key schema.
     *

     *
     * @param item
     *        A map of attribute name to attribute values, representing the primary key of the item to be written by
     *        PutItem. All of the table's primary key attributes must be specified, and their data types
     *        must match those of the table's key schema. If any attributes are present in the item that are part of an
     *        index key schema for the table, their types must match the index key schema.
     */

    public void setItem(java.util.Map<String, AttributeValue> item) {
        this.item = item;
    }

    /**
     *

     * A map of attribute name to attribute values, representing the primary key of the item to be written by
     * PutItem. All of the table's primary key attributes must be specified, and their data types must
     * match those of the table's key schema. If any attributes are present in the item that are part of an index key
     * schema for the table, their types must match the index key schema.
     *

     *
     * @param item
     *        A map of attribute name to attribute values, representing the primary key of the item to be written by
     *        PutItem. All of the table's primary key attributes must be specified, and their data types
     *        must match those of the table's key schema. If any attributes are present in the item that are part of an
     *        index key schema for the table, their types must match the index key schema.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put withItem(java.util.Map<String, AttributeValue> item) {
        setItem(item);
        return this;
    }

    /**
     * Add a single Item entry
     *
     * @see Put#withItem
     * @returns a reference to this object so that method calls can be chained together.
     */

    public Put addItemEntry(String key, AttributeValue value) {
        if (null == this.item) {
            this.item = new java.util.HashMap<String, AttributeValue>();
        }
        if (this.item.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.item.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into Item.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put clearItemEntries() {
        this.item = null;
        return this;
    }

    /**
     *

     * Name of the table in which to write the item.
     *

     *
     * @param tableName
     *        Name of the table in which to write the item.
     */

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    /**
     *

     * Name of the table in which to write the item.
     *

     *
     * @return Name of the table in which to write the item.
     */

    public String getTableName() {
        return this.tableName;
    }

    /**
     *

     * Name of the table in which to write the item.
     *

     *
     * @param tableName
     *        Name of the table in which to write the item.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put withTableName(String tableName) {
        setTableName(tableName);
        return this;
    }

    /**
     *

     * A condition that must be satisfied in order for a conditional update to succeed.
     *

     *
     * @param conditionExpression
     *        A condition that must be satisfied in order for a conditional update to succeed.
     */

    public void setConditionExpression(String conditionExpression) {
        this.conditionExpression = conditionExpression;
    }

    /**
     *

     * A condition that must be satisfied in order for a conditional update to succeed.
     *

     *
     * @return A condition that must be satisfied in order for a conditional update to succeed.
     */

    public String getConditionExpression() {
        return this.conditionExpression;
    }

    /**
     *

     * A condition that must be satisfied in order for a conditional update to succeed.
     *

     *
     * @param conditionExpression
     *        A condition that must be satisfied in order for a conditional update to succeed.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put withConditionExpression(String conditionExpression) {
        setConditionExpression(conditionExpression);
        return this;
    }

    /**
     *

     * One or more substitution tokens for attribute names in an expression.
     *

     *
     * @return One or more substitution tokens for attribute names in an expression.
     */

    public java.util.Map<String, String> getExpressionAttributeNames() {
        return expressionAttributeNames;
    }

    /**
     *

     * One or more substitution tokens for attribute names in an expression.
     *

     *
     * @param expressionAttributeNames
     *        One or more substitution tokens for attribute names in an expression.
     */

    public void setExpressionAttributeNames(java.util.Map<String, String> expressionAttributeNames) {
        this.expressionAttributeNames = expressionAttributeNames;
    }

    /**
     *

     * One or more substitution tokens for attribute names in an expression.
     *

     *
     * @param expressionAttributeNames
     *        One or more substitution tokens for attribute names in an expression.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put withExpressionAttributeNames(java.util.Map<String, String> expressionAttributeNames) {
        setExpressionAttributeNames(expressionAttributeNames);
        return this;
    }

    /**
     * Add a single ExpressionAttributeNames entry
     *
     * @see Put#withExpressionAttributeNames
     * @returns a reference to this object so that method calls can be chained together.
     */

    public Put addExpressionAttributeNamesEntry(String key, String value) {
        if (null == this.expressionAttributeNames) {
            this.expressionAttributeNames = new java.util.HashMap<String, String>();
        }
        if (this.expressionAttributeNames.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.expressionAttributeNames.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into ExpressionAttributeNames.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put clearExpressionAttributeNamesEntries() {
        this.expressionAttributeNames = null;
        return this;
    }

    /**
     *

     * One or more values that can be substituted in an expression.
     *

     *
     * @return One or more values that can be substituted in an expression.
     */

    public java.util.Map<String, AttributeValue> getExpressionAttributeValues() {
        return expressionAttributeValues;
    }

    /**
     *

     * One or more values that can be substituted in an expression.
     *

     *
     * @param expressionAttributeValues
     *        One or more values that can be substituted in an expression.
     */

    public void setExpressionAttributeValues(java.util.Map<String, AttributeValue> expressionAttributeValues) {
        this.expressionAttributeValues = expressionAttributeValues;
    }

    /**
     *

     * One or more values that can be substituted in an expression.
     *

     *
     * @param expressionAttributeValues
     *        One or more values that can be substituted in an expression.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put withExpressionAttributeValues(java.util.Map<String, AttributeValue> expressionAttributeValues) {
        setExpressionAttributeValues(expressionAttributeValues);
        return this;
    }

    /**
     * Add a single ExpressionAttributeValues entry
     *
     * @see Put#withExpressionAttributeValues
     * @returns a reference to this object so that method calls can be chained together.
     */

    public Put addExpressionAttributeValuesEntry(String key, AttributeValue value) {
        if (null == this.expressionAttributeValues) {
            this.expressionAttributeValues = new java.util.HashMap<String, AttributeValue>();
        }
        if (this.expressionAttributeValues.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.expressionAttributeValues.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into ExpressionAttributeValues.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Put clearExpressionAttributeValuesEntries() {
        this.expressionAttributeValues = null;
        return this;
    }

    /**
     *

     * Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put condition
     * fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and ALL_OLD.
     *

     *
     * @param returnValuesOnConditionCheckFailure
     *        Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put
     *        condition fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and
     *        ALL_OLD.
     * @see ReturnValuesOnConditionCheckFailure
     */

    public void setReturnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) {
        this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure;
    }

    /**
     *

     * Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put condition
     * fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and ALL_OLD.
     *

     *
     * @return Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put
     *         condition fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and
     *         ALL_OLD.
     * @see ReturnValuesOnConditionCheckFailure
     */

    public String getReturnValuesOnConditionCheckFailure() {
        return this.returnValuesOnConditionCheckFailure;
    }

    /**
     *

     * Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put condition
     * fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and ALL_OLD.
     *

     *
     * @param returnValuesOnConditionCheckFailure
     *        Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put
     *        condition fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and
     *        ALL_OLD.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ReturnValuesOnConditionCheckFailure
     */

    public Put withReturnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) {
        setReturnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailure);
        return this;
    }

    /**
     *

     * Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put condition
     * fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and ALL_OLD.
     *

     *
     * @param returnValuesOnConditionCheckFailure
     *        Use ReturnValuesOnConditionCheckFailure to get the item attributes if the Put
     *        condition fails. For ReturnValuesOnConditionCheckFailure, the valid values are: NONE and
     *        ALL_OLD.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ReturnValuesOnConditionCheckFailure
     */

    public Put withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) {
        this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getItem() != null)
            sb.append("Item: ").append(getItem()).append(",");
        if (getTableName() != null)
            sb.append("TableName: ").append(getTableName()).append(",");
        if (getConditionExpression() != null)
            sb.append("ConditionExpression: ").append(getConditionExpression()).append(",");
        if (getExpressionAttributeNames() != null)
            sb.append("ExpressionAttributeNames: ").append(getExpressionAttributeNames()).append(",");
        if (getExpressionAttributeValues() != null)
            sb.append("ExpressionAttributeValues: ").append(getExpressionAttributeValues()).append(",");
        if (getReturnValuesOnConditionCheckFailure() != null)
            sb.append("ReturnValuesOnConditionCheckFailure: ").append(getReturnValuesOnConditionCheckFailure());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof Put == false)
            return false;
        Put other = (Put) obj;
        if (other.getItem() == null ^ this.getItem() == null)
            return false;
        if (other.getItem() != null && other.getItem().equals(this.getItem()) == false)
            return false;
        if (other.getTableName() == null ^ this.getTableName() == null)
            return false;
        if (other.getTableName() != null && other.getTableName().equals(this.getTableName()) == false)
            return false;
        if (other.getConditionExpression() == null ^ this.getConditionExpression() == null)
            return false;
        if (other.getConditionExpression() != null && other.getConditionExpression().equals(this.getConditionExpression()) == false)
            return false;
        if (other.getExpressionAttributeNames() == null ^ this.getExpressionAttributeNames() == null)
            return false;
        if (other.getExpressionAttributeNames() != null && other.getExpressionAttributeNames().equals(this.getExpressionAttributeNames()) == false)
            return false;
        if (other.getExpressionAttributeValues() == null ^ this.getExpressionAttributeValues() == null)
            return false;
        if (other.getExpressionAttributeValues() != null && other.getExpressionAttributeValues().equals(this.getExpressionAttributeValues()) == false)
            return false;
        if (other.getReturnValuesOnConditionCheckFailure() == null ^ this.getReturnValuesOnConditionCheckFailure() == null)
            return false;
        if (other.getReturnValuesOnConditionCheckFailure() != null
                && other.getReturnValuesOnConditionCheckFailure().equals(this.getReturnValuesOnConditionCheckFailure()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getItem() == null) ? 0 : getItem().hashCode());
        hashCode = prime * hashCode + ((getTableName() == null) ? 0 : getTableName().hashCode());
        hashCode = prime * hashCode + ((getConditionExpression() == null) ? 0 : getConditionExpression().hashCode());
        hashCode = prime * hashCode + ((getExpressionAttributeNames() == null) ? 0 : getExpressionAttributeNames().hashCode());
        hashCode = prime * hashCode + ((getExpressionAttributeValues() == null) ? 0 : getExpressionAttributeValues().hashCode());
        hashCode = prime * hashCode + ((getReturnValuesOnConditionCheckFailure() == null) ? 0 : getReturnValuesOnConditionCheckFailure().hashCode());
        return hashCode;
    }

    @Override
    public Put clone() {
        try {
            return (Put) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.dynamodbv2.model.transform.PutMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class reply extends Model
{
    //
    protected $table = 'reply';
    protected $primaryKey = 'id';
    public $timestamps=false;
    protected $guarded=[];
}


text:
"""
Copyright (C) 2021 Erin Morelli.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see [https://www.gnu.org/licenses/].
"""

import os
from stat import S_IRUSR

import click
from cryptography.fernet import Fernet

from sqlalchemy.orm import sessionmaker
from sqlalchemy import MetaData, create_engine
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.ext.automap import automap_base

from .books import BooksContent
from .content import DownpourContent

class DownpourDownloader:
    """Core utilities and setup actions."""
    user_path = os.path.expanduser('~')
    # Manager configuration files storage location
    config_env_var = 'DP_DOWNLOAD_CONFIG_PATH'
    config_default = os.path.join(user_path, '.config', 'downpour-downloader')
    config_path = os.environ.get(config_env_var, None) or config_default
    # File to store password encryption key
    __key_file = os.path.join(config_path, '.secret_key')
    # URI for the local sqlite database file
    db_uri = f'sqlite:///{config_path}/content.db'
    # CLI context settings
    context_settings = {
        'help_option_names': ['-h', '--help']
    }
    #  List of all content type classes
    _types = [DownpourContent, BooksContent]

    def __init__(self):
        """Setup the sqlite database."""
        self._setup()
        # Encryption/decryption cipher handler
        self.__cipher = self.__get_cipher()
        # Setup the engine for the sqlite database
        self._engine = create_engine(self.db_uri)
        # Configure the SQLAlchemy metadata
        self._metadata = MetaData()
        self._metadata.bind = self._engine
        self._load_db()
        # Configure the auto-mapping base model
        self._base = automap_base(metadata=self._metadata)
        self._base.prepare()
        # Setup a session generator for database connections
        self._session = sessionmaker(bind=self._engine)

    def _setup(self):
        """Make sure files and folders exist."""
        if not os.path.isdir(self.config_path):
            os.makedirs(self.config_path)
        # Create a key file if one does not exist
        if not os.path.isfile(self.__key_file):
            with open(self.__key_file, 'wb') as f:
                f.write(Fernet.generate_key())
            # Make the file read-only
            os.chmod(self.__key_file, S_IRUSR)

    def __get_cipher(self):
        """Create a cipher manager from the stored key."""
        return Fernet(open(self.__key_file, 'rb').read())

    def encode(self, data):
        """Encode data with the cipher manager."""
        return self.__cipher.encrypt(data.encode('utf-8'))

    def decode(self, data):
        """Decode data with the cipher manager."""
        return self.__cipher.decrypt(data)

    def _load_db(self):
        """Dynamically loads database table schemas."""
        for type_ in self._types:
            try:
                type_.table(self._metadata)
            except InvalidRequestError:
                pass
        # Reflect metadata so auto-mapping works
        self._metadata.reflect(self._engine)
        # Make sure the tables exist
        self._metadata.create_all()

    def get_session(self):
        """Create a new database session using the session maker."""
        return self._session()

    @property
    def models(self):
        """Object containing auto-mapped database model classes."""
        return self._base.classes

    @staticmethod
    def success(msg):
        """Print success message in green text."""
        click.secho(msg, fg='green')

    @staticmethod
    def info(msg):
        """Print info message in blue text."""
        click.secho(msg, fg='blue')

    @staticmethod
    def warning(msg):
        """Print warning message in yellow text."""
        click.secho(msg, fg='yellow')

    @staticmethod
    def error(msg):
        """Print error message in red text."""
        click.secho(f'[ERROR] {msg}', fg='red')

    @property
    def cli(self):
        """Base command group to load subcommands into."""
        @click.group(context_settings=self.context_settings)
        def fn():
            """Manage Patreon exclusive content."""
        # Dynamically load commands from content type classes
        for type_ in self._types:
            fn.add_command(type_(self).cli, type_.command)
        return fn


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

namespace EmptyKeys.UserInterface.Designer
{
    public class RoutedEvents : UIElement
    {
        /// <summary>
        /// The visible event
        /// </summary>
        public static readonly RoutedEvent VisibleEvent;

        /// <summary>
        /// The hidden event
        /// </summary>
        public static readonly RoutedEvent HiddenEvent;

        /// <summary>
        /// The collapsed event
        /// </summary>
        public static readonly RoutedEvent CollapsedEvent;

        static RoutedEvents()
        {
            VisibleEvent = EventManager.RegisterRoutedEvent("Visible", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(RoutedEvents));
            HiddenEvent = EventManager.RegisterRoutedEvent("Hidden", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(RoutedEvents));
            CollapsedEvent = EventManager.RegisterRoutedEvent("Collapsed", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(RoutedEvents));
        }
    }
}


text:
local Util = require "lib.util"

--AUTORELOAD--
--watches ~/.hammerspoon directory for changes to .lua and reloads configs
AutoReload = {
	watcher = nil
};

function AutoReload:reloadConfig(files)
	print("reload")
	local doReload = false
	for _,file in pairs(files) do
		if file:sub(-4) == ".lua" then
			doReload = true
		end
	end

	if doReload then
		hs.reload()
	end
end

function AutoReload:init()
  self.watcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", function(paths)
		AutoReload:reloadConfig(paths)
	end):start()
  Util.toast("Hammerspoon","Config Reloaded.");
end

return AutoReload


text:
using namespace coral;
using namespace coral::rsync;
using namespace coral::thread;

//----------------------------------------------------------------------------
SegmenterThread::SegmenterThread( JobAgentPairQueue& queue )
: IThread("SegmenterThread")
, job_queue_( queue )
{
}

//----------------------------------------------------------------------------
SegmenterThread::~SegmenterThread()
{
}

//----------------------------------------------------------------------------
void SegmenterThread::run(const bool& shutdown )
{
   while ( shutdown == false )
   {
      JobAgentPair job_agent_pair;

      if ( job_queue_.pop( job_agent_pair ) )
      {
         JobAgent* agent_ptr = job_agent_pair.first;
         RsyncJob* job_ptr = job_agent_pair.second;

         if ( agent_ptr && job_ptr )
         {
            std::ifstream input_file;

            bool segment_success = job_ptr->fileSystem().open(
               job_ptr->descriptor().getDestination().path(),
               input_file
            );

            if ( segment_success )
            {
               segment_success = Segmenter::processFullStride(
                  input_file,
                  job_ptr->segments(),
                  job_ptr->descriptor().getSegmentSize(),
                  job_ptr->report().destination.segmentation
               );

               if ( segment_success == false )
               {
                  log::error("SegmenterThread: %s failed\n",
                             job_ptr->descriptor().getDestination().path().string().c_str());
               }

               input_file.close();
            }
            else
            {
               log::debug("SegmenterThread: Failed to open %s\n.",
                          job_ptr->descriptor().getDestination().path().string().c_str());
            }

            job_ptr->signalSegmentationDone();
         }
      }
   }

   log::debug("SegmenterThread: Shutting down\n");
}


text:
package aggregator

import (
	"fmt"
	"log"
	"sort"
	"strings"
	"time"

	"opentsp.org/cmd/collect-statse/statse"

	"opentsp.org/internal/tsdb"
)

type snapshotJob struct {
	Time   time.Time
	Store  *store
	Output []*tsdb.Point
}

func (job *snapshotJob) do() {
	byCluster := make(map[key]*entry)

	// Emit byhost stats.
	job.Store.Do(func(key key, host *entry) {
		// Update the synthetic cluster entry using the host entry.
		clusterKey := key
		clusterKey.Host = ""
		cluster := byCluster[clusterKey]
		if cluster == nil {
			cluster = newEntry()
			byCluster[clusterKey] = cluster
		}
		cluster.CountError += host.CountError
		cluster.CountOkay += host.CountOkay
		for key, values := range host.Buffer {
			for _, v := range values {
				cluster.Buffer[key].Append(v)
			}
		}

		// Process the host entry.
		for _, stat := range calc(host) {
			job.emitf(stat.Value, "%s.byhost.%s %s host=%s",
				key.Metric, stat.Name, key.Tags, key.Host)
			for i := range host.Buffer {
				host.Buffer[i].Reset()
			}
		}
	})

	// Emit bycluster stats.
	for key, cluster := range byCluster {
		for _, stat := range calc(cluster) {
			job.emitf(stat.Value, "%s.%s %s host=NA", key.Metric,
				stat.Name, key.Tags)
		}
	}
}

// emitf emits a data point.
func (job *snapshotJob) emitf(value interface{}, format string, arg ...interface{}) {
	series := fmt.Sprintf(format, arg...)
	id := strings.Fields(strings.Replace(series, "=", " ", -1))
	point, err := tsdb.NewPoint(job.Time, value, id[0], id[1:]...)
	if err != nil {
		log.Printf("aggregator: %v", err)
		return
	}
	job.Output = append(job.Output, point)
}

// calc calculates stats based on the provided entry.
func calc(entry *entry) []stat {
	s := make([]stat, 0, 2+statse.MaxKeys*5)
	s = append(s, stat{"count error=false", entry.CountOkay})
	s = append(s, stat{"count error=true", entry.CountError})
	for i, values := range entry.Buffer {
		if values == nil { // Never updated.
			continue
		}
		if len(values) == 0 { // Updated but not in this cycle.
			// Put in dummy zero value.
			values = []float32{0}
		}
		sort.Sort(ascending(values))
		statseKey := statse.Key(i).String()
		s = append(s, stat{statseKey + ".min", min(values...)})
		s = append(s, stat{statseKey + ".avg", avg(values...)})
		s = append(s, stat{statseKey + ".p95", p95(values...)})
		s = append(s, stat{statseKey + ".p99", p99(values...)})
		s = append(s, stat{statseKey + ".max", max(values...)})
	}
	return s
}

func min(a ...float32) float32 { return a[0] }
func avg(a ...float32) float32 { return sum(a...) / float32(len(a)) }
func p95(a ...float32) float32 { return a[95*len(a)/100] }
func p99(a ...float32) float32 { return a[99*len(a)/100] }
func max(a ...float32) float32 { return a[len(a)-1] }

func sum(a ...float32) float32 {
	var sum float32
	for i := range a {
		sum += a[i]
	}
	return sum
}

// stat represents a statistic based on a buffer.
type stat struct {
	Name  string
	Value interface{}
}

type ascending []float32

func (a ascending) Len() int           { return len(a) }
func (a ascending) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ascending) Less(i, j int) bool { return a[i] < a[j] }


text:
package com.malalaoshi.android.network.result;

import com.malalaoshi.android.core.base.BaseResult;
import com.malalaoshi.android.entity.Tag;

/**
 * tag 返回结果
 */
public class TagListResult extends BaseResult<Tag> {
}


text:
module.exports = (app, io) => {
	const handyUtils = require('handyutils');
	const randomize = require('randomatic');
	const redis = require('promise-redis')();
	const connectOpts = {
		host: process.env.DB_HOST,
		port: process.env.DB_PORT,
		password: process.env.DB_PASS
	};
	const client = redis.createClient(connectOpts);
	const statusControl = redis.createClient(connectOpts);
	// reference of the API, could be an environmental variable
	const API_IDENTIFIER = randomize('aA0',10);
	/*
	LIST ITEMS
	*/
	app.get('/listItems', (req, res) => {
		// get the elements in the shopping-list array
		client.lrange('shopping-list', 0, -1)
		.then(
			answer => {
				console.log(' answer at /listItems', answer);
				res.send({
					'shoppingList': answer,
					'status': 'OK'
				});
			},
			err => {
				console.log(' err at /listItems', err);
				res.send({
					'status': 'FAIL'
				});
			}
		);
	});
	// log when api subscribes to a channela and how many subscribers it has
	statusControl.on("subscribe", function (channel, count) {
		console.log(`-*- channel: ${channel}, count: ${count}`);
	});
	// here is where the api gets to know whether it will modify the db or just send the
	// modification to the view layer
	statusControl.on("message", function (channel, message) {
			console.log(`-*- sub channel: ${channel}`);
			console.log(`message: `, message);
			// here we have a conditional to check if the API that published a change is the current one.
			// if so, then that API gets to add or remove item from db.
			// else, the current API will only send the data to the view layer.

			//get a reference of the parsed message obj
			let parsedMessage = JSON.parse(message);
			console.log('parsedMessage: ', parsedMessage);
			if (parsedMessage.createdBy === API_IDENTIFIER) {
				console.log('it is created by this api!');
				if (parsedMessage.text && parsedMessage.action != 'remove') {
					// push the item into the db
					client.lpush('shopping-list', message)
					.then(
						answer => {
							handyUtils.debug('answer at lpush', answer);
						},
						err => {
					handyUtils.debug('err at lpush', err);
						}
					);
					// send it to the view layer so that it can be updated there.
					io.of('/shoppingList/').emit('event', message);
				} else if (parsedMessage.action === 'remove') {
					// reference for the object to remove
					let listItemObj = {};
					listItemObj.text = parsedMessage.text;
					listItemObj.itemId = parsedMessage.itemId;
					listItemObj.createdBy = parsedMessage.createdBy;
					let stringlistItemObj= JSON.stringify(listItemObj);
					handyUtils.debug('item to remove',stringlistItemObj);
					handyUtils.debug('item to remove typeof', typeof stringlistItemObj);
					client.lrem('shopping-list', 0, stringlistItemObj)
					.then(
						answer => {
							handyUtils.debug('answer at lrem', answer);
						},
						err => {
					handyUtils.debug('err at lrem', err);
						}
					);
				}
				// if the action is remove but it was not created by this API, simply send it to the view layer
			} else if(parsedMessage.action === 'remove' && parsedMessage.createdBy === API_IDENTIFIER) {
				io.of('/shoppingList/').emit('event', message);
			} else {
				// if it is not created by this API and it is not a remove, simply send the data to the view layer
				io.of('/shoppingList/').emit('event', message);
			}
	});

	io.of('/shoppingList/')
	.on('connection', (socket) => {
		handyUtils.debug('connection to shopping list feed has been established', '***');

		socket.on('event', (data) => {
			handyUtils.debug('event data:', data);
			// stringify before it is published
			let dataForStatusControl = {};
			// check if a remove event is incoming
			// if so, add the action and the itemId and createdBy field
			// otherwise generate an itemId and createdBy fields for it
			if (data.action ) {
				dataForStatusControl.action = data.action;
				dataForStatusControl.itemId = data.itemId;
				dataForStatusControl.createdBy = data.createdBy;
			} else{
				dataForStatusControl.itemId = randomize('0', 10);
				dataForStatusControl.createdBy = API_IDENTIFIER;
			}
			dataForStatusControl.text = data.text;
			// make the object into a string to publish
			let stringdataForStatusControl= JSON.stringify(dataForStatusControl);
			client.publish("shopping_list", stringdataForStatusControl)
			.then(
				answer => {
					handyUtils.debug('answer at publish', answer);
				},
				err => {
			handyUtils.debug('err at publish', err);
				}
			);
		});
	});
	// subscribe the StatusControl connection to he shopping list channel
	statusControl.subscribe("shopping_list");
};


text:
package com.jakduk.api.restcontroller.vo.search;

import java.util.List;

/**
 * @author Jang, Pyohwan
 * @since 2016. 12. 2.
 */

public class SearchArticleResult {
	private Long took; // 찾기에 걸린 시간(ms)
	private Long totalCount; // 매칭되는 아이템 수
	private List<ArticleSource> articles; // 매칭되는 게시물 목록

	public Long getTook() {
		return took;
	}

	public void setTook(Long took) {
		this.took = took;
	}

	public Long getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(Long totalCount) {
		this.totalCount = totalCount;
	}

	public List<ArticleSource> getArticles() {
		return articles;
	}

	public void setArticles(List<ArticleSource> articles) {
		this.articles = articles;
	}
}


text:
package org.hisp.dhis.android.app.views.dashboard.navigation.event;

import org.hisp.dhis.android.app.views.dashboard.TeiDashboardPresenter;
import org.hisp.dhis.client.sdk.core.event.EventInteractor;
import org.hisp.dhis.client.sdk.core.organisationunit.OrganisationUnitInteractor;
import org.hisp.dhis.client.sdk.core.program.ProgramInteractor;
import org.hisp.dhis.client.sdk.models.common.State;
import org.hisp.dhis.client.sdk.models.event.Event;
import org.hisp.dhis.client.sdk.models.event.EventStatus;
import org.hisp.dhis.client.sdk.models.organisationunit.OrganisationUnit;
import org.hisp.dhis.client.sdk.models.program.Program;
import org.hisp.dhis.client.sdk.models.program.ProgramStage;
import org.hisp.dhis.client.sdk.models.trackedentity.TrackedEntityDataValue;
import org.hisp.dhis.client.sdk.ui.adapters.expandable.ReportEntityChildViewHolder;
import org.hisp.dhis.client.sdk.ui.bindings.views.View;
import org.hisp.dhis.client.sdk.ui.models.ExpansionPanel;
import org.hisp.dhis.client.sdk.ui.models.Form;
import org.hisp.dhis.client.sdk.ui.models.ReportEntity;
import org.hisp.dhis.client.sdk.ui.models.ReportEntityFilter;
import org.hisp.dhis.client.sdk.utils.LocaleUtils;
import org.hisp.dhis.client.sdk.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class TeiProgramStagePresenterImpl implements TeiProgramStagePresenter {
    private static final String DATE_FORMAT = "yyyy-MM-dd h:mm";
    private final TeiDashboardPresenter teiDashboardPresenter;
    private TeiProgramStageView teiProgramStageView;
    private CompositeSubscription subscription;
    private final ProgramInteractor programInteractor;
    private final EventInteractor eventInteractor;
    private final OrganisationUnitInteractor organisationUnitInteractor;

    public TeiProgramStagePresenterImpl(TeiDashboardPresenter teiDashboardPresenter,
                                        ProgramInteractor programInteractor,
                                        EventInteractor eventInteractor, OrganisationUnitInteractor organisationUnitInteractor) {
        this.teiDashboardPresenter = teiDashboardPresenter;
        this.programInteractor = programInteractor;
        this.eventInteractor = eventInteractor;
        this.organisationUnitInteractor = organisationUnitInteractor;
    }

    @Override
    public void drawProgramStages(String enrollmentUid, String programUid) {
        this.generateDummyProgramStages(enrollmentUid, programUid);
    }

    @Override
    public void showEventForm(final String eventUid) {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
            subscription = null;
        }

        subscription = new CompositeSubscription();

        // TODO: remove this. send eventUid only and let FormSectionPresenter build form from Event/Program
        subscription.add(getEvent(eventUid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Event>() {
                    @Override
                    public void call(final Event event) {
                        subscription.add(getProgram(event.program())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<Program>() {
                            @Override
                            public void call(Program program) {

                                Form.Builder formBuilder = new Form.Builder()
                                        .setDataModelUid(eventUid)
                                        .setProgramUid(event.program())
                                        .setProgramStageUid(event.programStage());

                                for (ProgramStage programStage : program.programStages()) {
                                    if (programStage.uid().equals(event.programStage())) {
                                        formBuilder.setTitle(programStage.displayName());
                                        break;
                                    }
                                }
                                teiDashboardPresenter.showForm(formBuilder.build());
                            }
                        }));
                    }
                }));
    }

    @Override
    public void attachView(View view) {
        teiProgramStageView = (TeiProgramStageView) view;
    }

    @Override
    public void detachView() {
        teiProgramStageView = null;
    }

    private void generateDummyProgramStages(final String enrollmentUid, final String programUid) {

        //TODO: find the view holder for ReportEntities and update the icon according to the status.
        //TODO: Fix the "123"'s and so on to be the actual uid's and display the event name from the hashMap instead.

        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
            subscription = null;
        }

        subscription = new CompositeSubscription();
        subscription.add(Observable.zip(getProgram(programUid), getEventsForEnrollment(enrollmentUid), new Func2<Program, List<Event>, List<ExpansionPanel>>() {
            @Override
            public List<ExpansionPanel> call(Program program, List<Event> events) {
                List<ExpansionPanel> expansionPanels = new ArrayList<>();
                if (program != null && program.programStages() != null && !program.programStages().isEmpty()) {
                    for (ProgramStage programStage : program.programStages()) {
                        if (programStage != null) {
                            ExpansionPanel.Type type = ExpansionPanel.Type.ACTION_ADD;
                            if (programStage.repeatable() != null && programStage.repeatable()) {
                                type = ExpansionPanel.Type.ACTION_EDIT;
                            }
                            ExpansionPanel current = new ExpansionPanel(programStage.uid(), programStage.displayName(), type);
                            List<Event> eventsForStage = eventInteractor.store().queryEventsForEnrollmentAndProgramStage(enrollmentUid, programStage.uid());
                            current.setChildren(eventsToReportEntityList(programStage, eventsForStage));
                            expansionPanels.add(current);
                        }
                    }
                }
                return expansionPanels;
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Action1<List<ExpansionPanel>>() {
                    @Override
                    public void call(List<ExpansionPanel> expansionPanelList) {
                        if (teiProgramStageView != null) {
                            teiProgramStageView.drawProgramStages(expansionPanelList);
                        }
                    }
                }));

    }

    /**
     * Returns a list of ReportEntities that corresponds to Event's in that program stage.
     *
     * @param programStage
     * @param events
     * @return
     */
    private List<ReportEntity> eventsToReportEntityList(ProgramStage programStage, List<Event> events) {
        List<ReportEntity> reportEntities = new ArrayList<>();
        if (events == null || events.isEmpty()) { // preventing additional work
            return reportEntities;
        }
        Collections.sort(events, Event.DESCENDING_EVENT_DATE_COMPARATOR); // sort events by eventDate

        // retrieve state map for given events
        // it is done synchronously
        //TODO: use the new sdk when out, get states from the sdk :
        //Map<Long, State> stateMap = eventInteractor.map(events).toBlocking().first();

        for (Event event : events) {
            if (programStage.uid().equals(event.programStage())) { //if event in prog stage:
                // syncStatus of event
                ReportEntity.Status syncStatus;
                // get state of event
                State state = event.state();

                switch (state) {
                    case SYNCED: {
                        syncStatus = ReportEntity.Status.SENT;
                        break;
                    }
                    case TO_POST: {
                        syncStatus = ReportEntity.Status.TO_POST;
                        break;
                    }
                    case TO_UPDATE: {
                        syncStatus = ReportEntity.Status.TO_UPDATE;
                        break;
                    }
                    case ERROR: {
                        syncStatus = ReportEntity.Status.ERROR;
                        break;
                    }
                    case TO_DELETE: {
                        continue; // If event is to delete, skip this event.

                    }
                    default: {
                        throw new IllegalArgumentException(
                                "Unsupported event state: " + state);
                    }
                }

                EventStatus eventStatus = event.status();
                Date dateToShow;
                switch (eventStatus) {
                    case ACTIVE:
                        dateToShow = event.eventDate();
                        break;
                    case COMPLETED:
                        dateToShow = event.eventDate();
                        break;
                    case SCHEDULE:
                        dateToShow = event.dueDate();
                        break;
                    case SKIPPED:
                        dateToShow = event.eventDate();
                        break;

                    default:
                        throw new IllegalArgumentException("Unknown event status");
                }

                Map<String, String> dataElementToValueMap = new HashMap<>();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, LocaleUtils.getLocale());

                OrganisationUnit organisationUnit = organisationUnitInteractor.store().queryByUid(event.organisationUnit());
                String organisationUnitName;
                if(organisationUnit != null) {
                    organisationUnitName = organisationUnit.displayName();
                } else {
                    organisationUnitName = "";
                }

                dataElementToValueMap.put(ReportEntityFilter.DATE_KEY, sdf.format(dateToShow));
                dataElementToValueMap.put(ReportEntityFilter.STATUS_KEY, event.status().toString());
                dataElementToValueMap.put(ReportEntityChildViewHolder.SUB_LABEL, organisationUnitName);
                dataElementToValueMap.put(ReportEntityChildViewHolder.TEXT_LABEL, sdf.format(dateToShow));

                reportEntities.add(new ReportEntity(event.uid(), syncStatus, dataElementToValueMap));
            }
        }
        return reportEntities;
    }

    private Map<String, String> mapDataElementToValue(List<TrackedEntityDataValue> dataValues) {
        Map<String, String> dataElementToValueMap = new HashMap<>();
        if (dataValues != null && !dataValues.isEmpty()) {
            for (TrackedEntityDataValue dataValue : dataValues) {
                String value = !StringUtils.isEmpty(dataValue.value()) ? dataValue.value() : "";
                dataElementToValueMap.put(dataValue.dataElement(), value);
            }
        }
        return dataElementToValueMap;
    }

    private Observable<List<Event>> getEventsForEnrollment(final String enrollmentUid) {
        return Observable.just(eventInteractor.store().queryEventsForEnrollment(enrollmentUid));
    }

    private Observable<Event> getEvent(final String eventUid) {
        return Observable.just(eventInteractor.store().query(eventUid));
    }

    private Observable<Program> getProgram(final String programUid) {
        return Observable.just(programInteractor.store().queryByUid(programUid));
    }
}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org)

## Unreleased
### Added
 - basic readme with explanations about this project
 - electron as a baseline for development
 - Angular2 support for the frontend


text:
<?php
namespace hylook\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 * @ORM\Entity
 *
 */

class Emisor{
	/**
	 * @ORM\Id
	 * @ORM\Column(type="integer")
	 * @ORM\GeneratedValue
	 */
	private $id;
	/**
	 *
	 * @ORM\Column(type="string", length=200)
	 */
	protected $nombre;
	/**
	 *
	 * @ORM\Column(type="string", length=200)
	 */
	protected $descripcion;
	/**
	 *
	 * @ORM\ManyToOne(targetEntity="hylook\MainBundle\Entity\Usuarios")
	 */
	protected $usuario;

/*
	public function __construct($nombre, $descripcion, Usuarios $usuario){

		$this -> nombre = $nombre;
		$this -> descripcion = $descripcion;
		$this -> usuario = $usuario;

	}
	*/
	public function getId(){
		return $this->id;
	}

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return Emisor
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return Emisor
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set usuario
     *
     * @param \hylook\MainBundle\Entity\Usuarios $usuario
     * @return Emisor
     */
    public function setUsuario(\hylook\MainBundle\Entity\Usuarios $usuario = null)
    {
        $this->usuario = $usuario;

        return $this;
    }

    /**
     * Get usuario
     *
     * @return \hylook\MainBundle\Entity\Usuarios
     */
    public function getUsuario()
    {
        return $this->usuario;
    }

    public function __toString()
    {
    	return $this->getNombre();
    }
}


text:
package org.estatio.integtests.agreement;

import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.estatio.dom.agreement.AgreementRoleCommunicationChannels;
import org.estatio.dom.communicationchannel.CommunicationChannel;
import org.estatio.dom.communicationchannel.CommunicationChannelType;
import org.estatio.dom.communicationchannel.CommunicationChannels;
import org.estatio.dom.party.Parties;
import org.estatio.dom.party.Party;
import org.estatio.fixture.EstatioBaseLineFixture;
import org.estatio.fixture.lease._LeaseForOxfTopModel001Gb;
import org.estatio.integtests.EstatioIntegrationTest;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class AgreementRoleCommunicationChannelsTest extends EstatioIntegrationTest {

    public static class FindByCommunicationChannel extends AgreementRoleCommunicationChannelsTest {

        @Before
        public void setupData() {
            runFixtureScript(new FixtureScript() {
                @Override
                protected void execute(ExecutionContext executionContext) {
                    executionContext.executeChild(this, new EstatioBaseLineFixture());

                    executionContext.executeChild(this, new _LeaseForOxfTopModel001Gb());
                }
            });
        }

        @Inject
        CommunicationChannels communicationChannels;

        @Inject
        AgreementRoleCommunicationChannels agreementRoleCommunicationChannels;

        @Inject
        Parties parties;

        CommunicationChannel communicationChannel;

        Party party;

        @Before
        public void setUp() throws Exception {
            party = parties.findPartyByReference(_LeaseForOxfTopModel001Gb.PARTY_REF_TENANT);
            communicationChannel = communicationChannels.findByOwnerAndType(party, CommunicationChannelType.POSTAL_ADDRESS).first();
        }

        @Test
        public void happyCase() throws Exception {
            assertThat(agreementRoleCommunicationChannels.findByCommunicationChannel(communicationChannel).get(0).getCommunicationChannel(), is(communicationChannel));
        }
    }

}


text:
package com.opengamma.analytics.financial.interestrate.future.provider;

import com.opengamma.analytics.financial.interestrate.future.calculator.FuturesPriceBlackBondFuturesCalculator;
import com.opengamma.analytics.financial.interestrate.future.calculator.FuturesPriceBlackSensitivityBlackBondFuturesCalculator;
import com.opengamma.analytics.financial.interestrate.future.calculator.FuturesPriceCurveSensitivityBlackBondFuturesCalculator;
import com.opengamma.analytics.financial.interestrate.future.derivative.FuturesSecurity;
import com.opengamma.analytics.financial.interestrate.sensitivity.PresentValueBlackBondFuturesCubeSensitivity;
import com.opengamma.analytics.financial.provider.description.interestrate.BlackBondFuturesProviderInterface;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MulticurveSensitivity;

/**
 * Interface to generic futures security pricing method for multi-curve, issuer and Black on bond futures parameter provider.
 */
public class FuturesSecurityBlackBondFuturesMethod extends FuturesSecurityMethod {

  /** The futures price calculator **/
  private static final FuturesPriceBlackBondFuturesCalculator FPC = FuturesPriceBlackBondFuturesCalculator.getInstance();
  /** The futures price curve sensitivity calculator **/
  private static final FuturesPriceCurveSensitivityBlackBondFuturesCalculator FPCSC = FuturesPriceCurveSensitivityBlackBondFuturesCalculator.getInstance();
  /** The futures price Black sensitivity sensitivity calculator **/
  private static final FuturesPriceBlackSensitivityBlackBondFuturesCalculator FPBSC = FuturesPriceBlackSensitivityBlackBondFuturesCalculator.getInstance();

  /**
   * Computes the quoted price of a futures from a multicurve provider.
   * @param futures The futures security.
   * @param multicurve The multicurve provider.
   * @return The price.
   */
  public double price(final FuturesSecurity futures, final BlackBondFuturesProviderInterface multicurve) {
    return futures.accept(FPC, multicurve);
  }

  /**
   * Computes the quoted price curve sensitivity of a futures from a multicurve provider.
   * @param futures The futures security.
   * @param multicurve The multicurve provider.
   * @return The price curve sensitivity.
   */
  public MulticurveSensitivity priceCurveSensitivity(final FuturesSecurity futures, final BlackBondFuturesProviderInterface multicurve) {
    return futures.accept(FPCSC, multicurve);
  }

  /**
   * Computes the price sensitivity to the Black implied volatility (point sensitivity) from the curve and volatility provider.
   * @param futures The futures security.
   * @param multicurve The multicurve provider.
   * @return The price Black sensitivity.
   */
  public PresentValueBlackBondFuturesCubeSensitivity priceBlackSensitivity(final FuturesSecurity futures, final BlackBondFuturesProviderInterface multicurve) {
    return futures.accept(FPBSC, multicurve);
  }

}


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

<title>BlockingInputStream (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.poi.util

Class BlockingInputStream

java.lang.Object

java.io.InputStream

org.apache.poi.util.BlockingInputStream

All Implemented Interfaces:

java.io.Closeable, java.lang.AutoCloseable

public class BlockingInputStream
extends java.io.InputStream

Implementation of a BlockingInputStream to provide data to
 RawDataBlock that expects data in 512 byte chunks.  Useful to read
 data from slow (ie, non FileInputStream) sources, for example when
 reading an OLE2 Document over a network.

 Possible extentions: add a timeout. Curently a call to read(byte[]) on this
    class is blocking, so use at your own peril if your underlying stream blocks.

Author:

Jens Gerhard, aviks - documentation cleanups.

Field Summary

Fields

Modifier and Type
Field and Description

protected java.io.InputStream
is

Constructor Summary

Constructors

Constructor and Description

BlockingInputStream(java.io.InputStream is)

Method Summary

Methods

Modifier and Type
Method and Description

int
available()

void
close()

void
mark(int readLimit)

boolean
markSupported()

int
read()

int
read(byte[] bf)

We had to revert to byte per byte reading to keep
 with slow network connections on one hand, without
 missing the end-of-file.

int
read(byte[] bf,
    int s,
    int l)

void
reset()

long
skip(long n)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

is

protected java.io.InputStream is

Constructor Detail

BlockingInputStream

public BlockingInputStream(java.io.InputStream is)

Method Detail

available

public int available()
              throws java.io.IOException

Overrides:

available in class java.io.InputStream

Throws:

java.io.IOException

close

public void close()
           throws java.io.IOException

Specified by:

close in interface java.io.Closeable

Specified by:

close in interface java.lang.AutoCloseable

Overrides:

close in class java.io.InputStream

Throws:

java.io.IOException

mark

public void mark(int readLimit)

Overrides:

mark in class java.io.InputStream

markSupported

public boolean markSupported()

Overrides:

markSupported in class java.io.InputStream

read

public int read()
         throws java.io.IOException

Specified by:

read in class java.io.InputStream

Throws:

java.io.IOException

read

public int read(byte[] bf)
         throws java.io.IOException

We had to revert to byte per byte reading to keep
 with slow network connections on one hand, without
 missing the end-of-file.
 This is the only method that does its own thing in this class
    everything else is delegated to aggregated stream.
 THIS IS A BLOCKING BLOCK READ!!!

Overrides:

read in class java.io.InputStream

Throws:

java.io.IOException

read

public int read(byte[] bf,
       int s,
       int l)
         throws java.io.IOException

Overrides:

read in class java.io.InputStream

Throws:

java.io.IOException

reset

public void reset()
           throws java.io.IOException

Overrides:

reset in class java.io.InputStream

Throws:

java.io.IOException

skip

public long skip(long n)
          throws java.io.IOException

Overrides:

skip in class java.io.InputStream

Throws:

java.io.IOException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
package org.agorava.linkedin.model;

import java.io.Serializable;
import java.util.List;

/**
 * Model class representing a list of comments
 *
 * @author Robert Drysdale
 * @author Antoine Sabot-Durand
 */
public class Comments implements Serializable {

    private static final long serialVersionUID = 1L;

    private final List<Comment> comments;

    public Comments(List<Comment> comments) {
        this.comments = comments;
    }

    public List<Comment> getComments() {
        return comments;
    }

}


text:
import {
  map,
  reduce,
  filter,
  zip,
  pipe,
  isNil,
  assoc,
  has,
  is,
  mapObjIndexed,
  flatten,
  equals,
} from 'ramda';

import { rejectNil, contentByKey, onlyObjects, isArray } from './functional';

import EntityWrapper from '../EntityWrapper';

export function diffComponents(oldContent, newContent) {
  const newHashMap = contentByKey(newContent);
  const oldHashMap = contentByKey(oldContent);

  const added = [];
  const updated = [];
  const removed = [];

  for (let i = 0; i < newContent.length; i++) {
    const c = newContent[i];

    if (!Object.prototype.hasOwnProperty.call(oldHashMap, c.key)) {
      added.push(c);
    }
  }

  for (let i = 0; i < oldContent.length; i++) {
    const c = oldContent[i];

    if (Object.prototype.hasOwnProperty.call(newHashMap, c.key)) {
      updated.push([c, newHashMap[c.key]]);
    }

    if (!Object.prototype.hasOwnProperty.call(newHashMap, c.key)) {
      removed.push(c);
    }
  }

  return {
    added,
    updated,
    removed,
  };
}

export function mountChild(childEntity) {
  childEntity.entityInstance.mount(
    childEntity.props,
    childEntity.children,
    childEntity.context
  );
  return childEntity;
}

export const updateChild = ([oldChild, newChild]) => {
  const newProps = isNil(newChild.props) ? {} : newChild.props;
  const newChildren = isArray(newChild.children)
    ? flatten(newChild.children)
    : [];
  const newContext = isNil(newChild.context) ? {} : newChild.context;

  oldChild.entityInstance.updateParams(newProps, newChildren, newContext);
  oldChild.entityInstance.update();

  return oldChild;
};

export function prepareChildContentForMounting({
  entityClass,
  props,
  children,
  context,
}) {
  return {
    entityClass,
    props,
    key: props.key,
    children,
    entityInstance: new EntityWrapper(entityClass),
    entityClassName: entityClass.name,
    context,
  };
}

export const mountChildren = pipe(
  rejectNil,
  map(prepareChildContentForMounting),
  map(mountChild)
);

export function updateChildren(childrenToUpdate) {
  const updatedChildren = [];

  for (let i = 0; i < childrenToUpdate.length; i++) {
    updatedChildren.push(updateChild(childrenToUpdate[i]));
  }

  return updatedChildren;
}

export function removeChild({ entityInstance }) {
  entityInstance.remove();
}

export function removeChildren(childrenToRemove) {
  for (let i = 0; i < childrenToRemove.length; i++) {
    removeChild(childrenToRemove[i]);
  }
  return;
}

export function generateChildEntities(oldContent, newContent) {
  const { added, updated, removed } = diffComponents(oldContent, newContent);

  removed.length > 0 && removeChildren(removed);
  const addedEntities = mountChildren(added);
  const updatedEntities = updateChildren(updated);

  return addedEntities.concat(updatedEntities);
}

export const getRenderContent = (entity, params) => {
  if (!has('render', entity)) return [];
  const content = entity.render(params);
  if (isNil(content)) return [];

  const contentArray = isArray(content)
    ? content
    : has('key', content) ? [content] : [];

  return onlyObjects(contentArray);
};

export const callMethodInSystems = (methodName, systemParams) => {
  let { systems } = systemParams.props;
  let newParams = Object.assign({}, systemParams);

  for (let i = 0; i < systems.length; i++) {
    let system = systems[i];
    let systemResult;

    /*
      Accept a function as well as an object for systems.
      If passed a function, then call it on create and update.
    */

    if (
      system instanceof Function &&
      (methodName === 'create' || methodName === 'update')
    ) {
      systemResult = system(newParams);
    } else if (system[methodName] instanceof Function) {
      systemResult = system[methodName](newParams);
    }

    if (typeof systemResult === 'object') {
      newParams = Object.assign({}, newParams, {
        state: Object.assign({}, newParams.state, systemResult),
      });
    }
  }

  return newParams;
};


text:
use std::{error, result};
use std::fmt::Debug;

mod channel;
mod null;
mod register;

pub use state_machine::channel::ChannelStateMachine;
pub use state_machine::null::NullStateMachine;
pub use state_machine::register::RegisterStateMachine;

/// This trait is meant to be implemented such that the commands issued to it via `apply()` will
/// be reflected in your consuming application. Commands sent via `apply()` have been committed
/// in the cluser. Unlike `store`, your application should consume data produced by this and
/// accept it as truth.
pub trait StateMachine: Debug + Send + 'static {

    type Error: Debug + error::Error + Send + 'static;

    /// Applies a command to the state machine.
    fn apply(&mut self, command: &[u8]) -> result::Result<(), Self::Error>;

    /// Take a snapshot of the state machine.
    fn snapshot(&self) -> result::Result<Vec<u8>, Self::Error>;

    /// Restore a snapshot of the state machine.
    fn restore_snapshot(&mut self, snapshot: Vec<u8>) -> result::Result<(), Self::Error>;
}


text:
package com.nielsmasdorp.speculum.presenters;

import android.app.Application;
import android.os.Build;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import com.nielsmasdorp.speculum.R;
import com.nielsmasdorp.speculum.activity.MainActivity;
import com.nielsmasdorp.speculum.interactor.MainInteractor;
import com.nielsmasdorp.speculum.models.Configuration;
import com.nielsmasdorp.speculum.models.RedditPost;
import com.nielsmasdorp.speculum.models.Weather;
import com.nielsmasdorp.speculum.models.YoMommaJoke;
import com.nielsmasdorp.speculum.models.QuotePost;
import com.nielsmasdorp.speculum.util.Constants;
import com.nielsmasdorp.speculum.views.MainView;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;

/**
 * @author Niels Masdorp (NielsMasdorp)
 */
public class MainPresenterImpl implements MainPresenter, RecognitionListener, TextToSpeech.OnInitListener {

    private MainView view;
    private MainInteractor interactor;
    private Application application;
    private Configuration configuration;
    private SpeechRecognizer recognizer;
    private TextToSpeech textToSpeech;

    public MainPresenterImpl(MainView view, MainInteractor interactor, Application application) {

        this.view = view;
        this.interactor = interactor;
        this.application = application;
    }

    /*
    Begin presenter methods
     */
    @Override
    public void setConfiguration(Configuration configuration) {

        this.configuration = configuration;
    }

    @Override
    public void start(boolean hasAccessToCalendar) {
        if (null != configuration) {
            startWeather();
            if (configuration.isVoiceCommands()) {
                initSpeechRecognitionService();
                setupTts();
            }
            if (!configuration.isSimpleLayout()) {
                startReddit();
                if (hasAccessToCalendar) {
                    startCalendar();
                }
            }
        }
    }

    private void updateData() {
        interactor.unSubscribe();
        if (null != configuration) {
            startWeather();
            if (!configuration.isSimpleLayout()) {
                startReddit();
                startCalendar();
            }
        }
    }

    @Override
    public void showError(String error) {
        view.showError(error);
    }

    @Override
    public void finish() {
        if (recognizer != null) {
            recognizer.cancel();
            recognizer.shutdown();
        }
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        view.hideListening();
        view.hideMap();
        interactor.unSubscribe();
    }

    /*
    End presenter methods
     */

    /*
    Begin start background data methods
     */
    private void startWeather() {
        interactor.loadWeather(configuration.getLocation(), configuration.isCelsius(), configuration.getPollingDelay(), ((MainActivity)
                view).getString(R.string.forecast_api_key), new WeatherSubscriber());
    }

    private void startReddit() {
        interactor.loadTopRedditPost(configuration.getSubreddit(), configuration.getPollingDelay(), new RedditSubscriber());
    }

    private void startCalendar() {
        interactor.loadCalendarEvents(configuration.getPollingDelay(), new CalendarEventSubscriber());
    }
    /*
    End start background data methods
     */

    /*
    Begin speech recognition related initialisation
     */
    private void initSpeechRecognitionService() {
        interactor.getAssetsDirForSpeechRecognizer(new AssetSubscriber());
    }

    private void setupTts() {
        initTts()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Void>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onNext(Void aVoid) {

                    }
                });
    }

    public void setupRecognizer(File assetDir) {
        initRecognizer(assetDir)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Void>() {
                    @Override
                    public void onCompleted() {
                        setListeningMode(Constants.KWS_SEARCH);
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onNext(Void aVoid) {
                    }
                });
    }

    private Observable<Void> initTts() {
        return Observable.defer(() -> {
            textToSpeech = new TextToSpeech(application, this);
            return Observable.empty();
        });
    }

    private Observable<Void> initRecognizer(File assetDir) {
        return Observable.defer(() -> {
            try {
                recognizer = defaultSetup()
                        .setAcousticModel(new File(assetDir, "en-us-ptm"))
                        .setDictionary(new File(assetDir, "cmudict-en-us.dict"))
                        .setKeywordThreshold(1e-45f)
                        .getRecognizer();
                recognizer.addListener(this);
                recognizer.addKeyphraseSearch(Constants.KWS_SEARCH, Constants.KEYPHRASE);
                recognizer.addKeywordSearch(Constants.COMMANDS_SEARCH, new File(assetDir, "commands.gram"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return Observable.empty();
        });
    }
    /*
     End speech recognition related initialisation
     */

    /*
    Begin speech recognition logic methods
     */
    public void setListeningMode(String mode) {
        recognizer.stop();
        if (mode.equals(Constants.KWS_SEARCH)) {
            recognizer.startListening(mode);
        } else {
            recognizer.startListening(mode, (int) TimeUnit.MINUTES.toMillis(1));
        }
    }

    private void processVoiceCommand(String command) {
        switch (command) {
            case Constants.KEYPHRASE:
                speak(Constants.WAKE_NOTIFICATION);
                setListeningMode(Constants.COMMANDS_SEARCH);
                view.showListening();
                break;
            case Constants.SLEEP_PHRASE:
                speak(Constants.SLEEP_NOTIFICATION);
                setListeningMode(Constants.KWS_SEARCH);
                view.hideListening();
                break;
            case Constants.UPDATE_PHRASE:
                speak(Constants.UPDATE_NOTIFICATION);
                setListeningMode(Constants.COMMANDS_SEARCH);
                updateData();
                break;
            case Constants.JOKE_PHRASE:
                interactor.loadYoMommaJoke(new YoMammaJokeSubscriber());
                setListeningMode(Constants.COMMANDS_SEARCH);
                break;

            case Constants.MAP_PHRASE:
                speak(Constants.MAP_NOTIFICATION);
                setListeningMode(Constants.COMMANDS_SEARCH);
                showMap();
                break;
        }
    }

    private void showMap() {

        timeOut(10)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Void>() {

                    @Override
                    public void onStart() {
                        view.showMap(configuration.getLocation());
                    }

                    @Override
                    public void onCompleted() {
                        view.hideMap();
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onNext(Void aVoid) {
                    }
                });
    }

    private Observable<Void> timeOut(Integer seconds) {
        return Observable.defer(() -> {
            SystemClock.sleep(TimeUnit.SECONDS.toMillis(seconds));
            return Observable.empty();
        });
    }

    /*
    End speech recognition logic methods
     */

    /*
    Begin text to speech methods
     */
    @SuppressWarnings("deprecation")
    public void speak(String sentence) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            String utteranceId = this.hashCode() + "";
            textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
            textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, map);
        }
    }
    /*
    End text to speech methods
     */

    /*
    Begin speech recognition logic methods
     */
    @Override
    public void onBeginningOfSpeech() {
    }

    @Override
    public void onEndOfSpeech() {
    }

    @Override
    public void onPartialResult(Hypothesis hypothesis) {
        if (hypothesis == null) return;
        String command = hypothesis.getHypstr();
        processVoiceCommand(command);
    }

    @Override
    public void onResult(Hypothesis hypothesis) {

    }

    @Override
    public void onError(Exception e) {
        showError(e.getLocalizedMessage());
        Log.e(MainActivity.class.getSimpleName(), e.toString());
    }

    @Override
    public void onTimeout() {
        speak(Constants.SLEEP_NOTIFICATION);
        setListeningMode(Constants.KWS_SEARCH);
        view.hideListening();
    }
     /*
    End speech recognition logic methods
     */

    /*
   Begin tts lifecycle methods
    */
    @Override
    public void onInit(int status) {
    }
    /*
   End tts lifecycle methods
    */

    private final class WeatherSubscriber extends Subscriber<Weather> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            view.showError(e.getMessage());
        }

        @Override
        public void onNext(Weather weather) {
            view.displayCurrentWeather(weather, configuration.isSimpleLayout());
        }
    }

    private final class RedditSubscriber extends Subscriber<RedditPost> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            view.showError(e.getMessage());
        }

        @Override
        public void onNext(RedditPost redditPost) {
            view.displayTopRedditPost(redditPost);
        }
    }
    private final class QuoteSubscriber extends Subscriber<QuotePost> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            view.showError(e.getMessage());
        }

        @Override
        public void onNext(QuotePost quotePost) {
            view.displayQuotePost(quotePost);
        }
    }

    private final class CalendarEventSubscriber extends Subscriber<String> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            view.showError(e.getMessage());
        }

        @Override
        public void onNext(String events) {
            view.displayCalendarEvents(events);
        }
    }

    private final class YoMammaJokeSubscriber extends Subscriber<YoMommaJoke> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            view.showError(e.getMessage());
        }

        @Override
        public void onNext(YoMommaJoke joke) {
            speak(joke.getJoke());
        }
    }

    private final class AssetSubscriber extends Subscriber<File> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            view.showError(e.getMessage());
        }

        @Override
        public void onNext(File assetDir) {
            setupRecognizer(assetDir);
        }
    }
}


text:
package net.lshift.diffa.agent.client

import net.lshift.diffa.kernel.frontend.DomainDef
import javax.ws.rs.core.MediaType
import com.sun.jersey.api.client.ClientResponse
import com.sun.jersey.core.util.MultivaluedMapImpl
import net.lshift.diffa.client.{NotFoundException, ExternalRestClient}
import net.lshift.diffa.client.{RestClientParams, ExternalRestClient}
import collection.immutable.Map
import java.lang.String
import com.sun.jersey.api.representation.Form

class SystemConfigRestClient(rootUrl:String, params: RestClientParams = RestClientParams.default)
    extends ExternalRestClient(rootUrl, "root/", params) {

  @Deprecated
  def declareDomain(domain:DomainDef) = create("spaces", domain)

  def removeDomain(name: String) = delete("/spaces/" + name)

  def setConfigOption(key:String, value:String) = {
    val path = resource.path("/system/config/" + key)
    val response = path.`type`(MediaType.TEXT_PLAIN).put(classOf[ClientResponse], value)
    val status = response.getClientResponseStatus
    status.getStatusCode match {
      case 204 | 304    => ()
      case x:Int => handleHTTPError(x, path, status)
    }
  }

  def setConfigOptions(options: Map[String, String]) {
    val form = new Form()
    options.foreach { case (k, v) => form.add(k, v)}

    val path = resource.path("/system/config")
    val response = path.`type`(MediaType.APPLICATION_FORM_URLENCODED).post(classOf[ClientResponse], form)
    val status = response.getClientResponseStatus
    status.getStatusCode match {
      case 204 | 304    => ()
      case x:Int => handleHTTPError(x, path, status)
    }
  }

  def deleteConfigOption(key:String) = {
    val path = resource.path("/system/config/" + key)
    val response = path.delete(classOf[ClientResponse])
    val status = response.getClientResponseStatus
    status.getStatusCode match {
      case 204   => ()
      case x:Int => handleHTTPError(x, path, status)
    }
  }

  def setHardSystemLimit(name:String, value:Int) = setValue("/system/limits/" + name + "/hard", value)
  def setDefaultSystemLimit(name:String, value:Int) = setValue("/system/limits/" + name + "/default", value)

  def getEffectiveSystemLimit(name:String) : Int = {
    val path = resource.path("/system/limits/" + name)
    val media = path.accept(MediaType.TEXT_PLAIN)
    val response = media.get(classOf[ClientResponse])
    val status = response.getClientResponseStatus
    status.getStatusCode match {
      case 200   => response.getEntity(classOf[String]).toInt
      case 404   => throw new NotFoundException(path.toString)
      case x:Int => handleHTTPError(x, path, status)
    }
  }

  def getConfigOption(key:String) = {
    val path = resource.path("/system/config/" + key)
    val media = path.accept(MediaType.TEXT_PLAIN)
    val response = media.get(classOf[ClientResponse])
    val status = response.getClientResponseStatus
    status.getStatusCode match {
      case 200   => response.getEntity(classOf[String])
      case 404   => throw new NotFoundException(path.toString)
      case x:Int => handleHTTPError(x, path, status)
    }
  }

  private def setValue(resourcePath:String, value:Int) = {
    val path = resource.path(resourcePath)
    val response = path.`type`(MediaType.TEXT_PLAIN).put(classOf[ClientResponse], value.toString)
    val status = response.getClientResponseStatus
    status.getStatusCode match {
      case 204 | 304    => ()
      case 404   => throw new NotFoundException(path.toString)
      case x:Int => handleHTTPError(x, path, status)
    }
  }
}