text:
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace LCL.Reflection
{
    public static class TypeHelper
    {
        /// <summary>
        /// 获取继承层次列表,从子类到基类
        /// </summary>
        /// <param name="from"></param>
        /// <param name="exceptFrom"></param>
        /// <returns></returns>
        public static IEnumerable<Type> GetHierarchy(Type from, params Type[] exceptTypes)
        {
            var needExcept = exceptTypes.Length > 0;

            Type current = from;
            while (current != null && (!needExcept || !InExcept(current, exceptTypes)))
            {
                yield return current;
                current = current.BaseType;
            }
        }

        //public static List<Type> GetHierarchy(Type from)
        //{
        //    List<Type> list = new List<Type>();
        //    list.Add(from.BaseType);
        //    list.Add(from.BaseType.BaseType);
        //    list.Add(from.BaseType.BaseType.BaseType);
        //    return list;
        //}

        public static List<Type> GetHierarchy(Type from)
        {
            List<Type> list = new List<Type>();
            list.Add(from.BaseType);
            return GetHierarchy(from.BaseType);
        }

        private static bool InExcept(Type current, Type[] exceptTypes)
        {
            for (int i = 0, c = exceptTypes.Length; i < c; i++)
            {
                var exceptType = exceptTypes[i];

                //如果是泛型定义,则需要 current 类型是这个泛型的实例也可以。
                if (exceptType.IsGenericTypeDefinition)
                {
                    if (current.IsGenericType && current.GetGenericTypeDefinition() == exceptType) return true;
                }
                else
                {
                    if (exceptType == current) return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 判断指定的类型是不是数字类型。
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsNumber(Type type)
        {
            return type == typeof(int) ||
                type == typeof(long) ||
                type == typeof(float) ||
                type == typeof(double) ||
                type == typeof(decimal) ||
                type == typeof(uint) ||
                type == typeof(ulong) ||
                type == typeof(byte) ||
                type == typeof(sbyte);
        }

        public static object GetDefaultValue(Type targetType)
        {
            if (targetType.IsValueType) return Activator.CreateInstance(targetType);
            return null;
        }

        #region  CoerceValue

        /// <summary>
        /// 强制把 value 的值变换为 desiredType
        /// </summary>
        /// <param name="desiredType"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object CoerceValue(Type desiredType, object value)
        {
            if (value != null)
            {
                value = CoerceValue(desiredType, value.GetType(), value);
            }
            else
            {
                value = TypeHelper.GetDefaultValue(desiredType);
            }

            return value;
        }

        public static object CoerceValue(Type desiredType, Type valueType, object value)
        {
            // types match, just return value
            if (desiredType.IsAssignableFrom(valueType)) { return value; }

            if (desiredType == typeof(string) && value != null) return value.ToString();

            if (desiredType.IsGenericType && desiredType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                desiredType = Nullable.GetUnderlyingType(desiredType);

                if (value == null ||
                    valueType.Equals(typeof(string)) && Convert.ToString(value) == string.Empty) return null;
            }

            if (desiredType.IsEnum) { return Enum.Parse(desiredType, value.ToString()); }

            //空字符串转换为数字 0
            if ((desiredType.IsPrimitive || desiredType.Equals(typeof(decimal))) &&
                valueType.Equals(typeof(string)) && string.IsNullOrEmpty((string)value))
                value = 0;

            if (desiredType == typeof(Guid) && value is string) { return Guid.Parse(value as string); }

            try
            {
                return Convert.ChangeType(value, desiredType);
            }
            catch
            {
                var cnv = TypeDescriptor.GetConverter(desiredType);
                if (cnv != null && cnv.CanConvertFrom(valueType)) return cnv.ConvertFrom(value);

                throw;
            }
        }

        public static T CoerceValue<T>(Type valueType, object value)
        {
            return (T)(CoerceValue(typeof(T), valueType, value));
        }

        public static T CoerceValue<T>(object value)
        {
            if (value == null) throw new ArgumentNullException("value");

            return (T)(CoerceValue(typeof(T), value.GetType(), value));
        }

        #endregion

    }
}


text:
import os, sys

from BaseTraciEnv import BaseTraciEnv

if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")

import gym
from baselines.common import set_global_seeds, tf_util as U
from baselines import logger,logger_utils
from baselines.ppo1 import mlp_policy, pposgd_simple
from pathlib import Path
import Traci_2_cross_env.Traci_2_cross_env
import Traci_3_cross_env.Traci_3_cross_env
import tensorflow as tf

def test(environment_name, path_to_model, configured_environment, act, log_dir):
    def policy_fn(name, ob_space, ac_space):
        return mlp_policy.MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space,
                                    hid_size=64, num_hid_layers=2)                    #set these?
    if act is None:
        act = policy_fn('pi', configured_environment.observation_space, configured_environment.action_space)
        tf.train.Saver().restore(sess, path_to_model)
    # Setup path of logging, name of environment and save the current arguments (this script)
    if log_dir == "":
        log_dir = os.path.join(str(Path.home()), "Desktop")
    logger_path = logger_utils.path_with_date(log_dir, environment_name + "test_ppo")
    # Initialize logger
    logger.reset()
    logger.configure(logger_path, ["tensorboard", "stdout"])
    logger.logtxt(path_to_model, "Model path")
    #configured_environment.render()
    obs, done = configured_environment.reset(), False
    for i in range(10):
        episode_rew = 0
        while not done:
            obs, rew, done, _ = configured_environment.step(act.act(True, obs)[0])
            episode_rew += rew
        print("Episode reward", episode_rew)
        obs, done = configured_environment.reset(), False  # Done afterwards to ensure logging
    configured_environment.log_travel_time_table()

if __name__ == '__main__':
    sess = U.make_session(num_cpu=1)
    sess.__enter__()
    environment = 'Traci_3_cross_env-v0'
    path_to_model = "/home/nikolaj/Desktop/Traci_3_cross_env-v0-ppo/2017-10-25_13-37-55/ckpt_timesteps/saved_model"
    env = gym.make(environment)
    env.configure_traci(num_car_chances=1000,
                            start_car_probabilities=[1.0,0.1],
                            enjoy_car_probs=False,
                            reward_func=BaseTraciEnv.reward_total_waiting_vehicles,
                            action_func=BaseTraciEnv.set_light_phase_4_cross_green_dir,
                            state_contain_num_cars_in_queue_history=True,
                            state_contain_time_since_tl_change=True,
                            state_contain_tl_state_history=True,
                            state_contain_avg_speed_between_detectors_history=False,
                            num_actions_pr_trafficlight=2,
                            num_history_states=2)
    test(environment, path_to_model, env, None, "")

redpajama_set_name: RedPajamaGithub


text:
package com.realexpayments.hpp.sdk.domain;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.realexpayments.hpp.sdk.utils.GenerationUtils;

/**
 * Class representing the HPP response.
 *
 * @author markstanford
 *
 */
@JsonInclude(Include.NON_NULL)
public class HppResponse {

	/**
	 * This is the merchant id that Realex Payments assign to you.
	 */
	@JsonProperty("MERCHANT_ID")
	private String merchantId;

	/**
	 * The sub-account used in the transaction.
	 */
	@JsonProperty("ACCOUNT")
	private String account;

	/**
	 * The unique order id that you sent to us.
	 */
	@JsonProperty("ORDER_ID")
	private String orderId;

	/**
	 * The amount that was authorised. Returned in the lowest unit of the currency.
	 */
	@JsonProperty("AMOUNT")
	private String amount;

	/**
	 * Will contain a valid authcode if the transaction was successful. Will be empty otherwise.
	 */
	@JsonProperty("AUTHCODE")
	private String authCode;

	/**
	 * The date and time of the transaction.
	 */
	@JsonProperty("TIMESTAMP")
	private String timeStamp;

	/**
	 * A SHA-1 digital signature created using the HPP response fields and your shared secret.
	 */
	@JsonProperty("SHA1HASH")
	private String hash;

	/**
	 * The outcome of the transaction. Will contain "00" if the transaction was a success or another value (depending on the error) if not.
	 */
	@JsonProperty("RESULT")
	private String result;

	/**
	 * Will contain a text message that describes the result code.
	 */
	@JsonProperty("MESSAGE")
	private String message;

	/**
	 *

	 * The result of the Card Verification check (if enabled):
	 *

	 *
M: CVV Matched.

	 *
N: CVV Not Matched.

	 *
I: CVV Not checked due to circumstances.

	 *
U: CVV Not checked - issuer not certified.

	 *
P: CVV Not Processed.

	 *

	 *

	 *
	 */
	@JsonProperty("CVNRESULT")
	private String cvnResult;

	/**
	 * A unique reference that Realex Payments assign to your transaction.
	 */
	@JsonProperty("PASREF")
	private String pasRef;

	/**
	 * This is the Realex Payments batch that this transaction will be in.
	 * (This is equal to "-1" if the transaction was sent in with the autosettle flag off.
	 * After you settle it (either manually or programmatically) the response to that transaction will contain the batch id.)
	 */
	@JsonProperty("BATCHID")
	private String batchId;

	/**
	 * This is the ecommerce indicator (this will only be returned for 3DSecure transactions).
	 */
	@JsonProperty("ECI")
	private String eci;

	/**
	 * Cardholder Authentication Verification Value (this will only be returned for 3DSecure transactions).
	 */
	@JsonProperty("CAVV")
	private String cavv;

	/**
	 * Exchange Identifier (this will only be returned for 3DSecure transactions).
	 */
	@JsonProperty("XID")
	private String xid;

	/**
	 * Whatever data you have sent in the request will be returned to you.
	 */
	@JsonProperty("COMMENT1")
	private String commentOne;

	/**
	 * Whatever data you have sent in the request will be returned to you.
	 */
	@JsonProperty("COMMENT2")
	private String commentTwo;

	/**
	 * The Transaction Suitability Score for the transaction. The RealScore is comprised of various distinct tests.
	 * Using the RealControl application you can request that Realex Payments return certain individual scores to you.
	 * These are identified by numbers - thus TSS_1032 would be the result of the check with id 1032.
	 * You can then use these specific checks in conjunction with RealScore score to ascertain whether or not you wish to continue with the settlement.
	 */
	@JsonProperty("TSS")
	@JsonDeserialize(as = HashMap.class)
	private Map<String, String> tss;

	/**
	 * Anything else you sent to us in the request will be returned to you in supplementary data.
	 */
	private Map<String, String> supplementaryData = new HashMap<String, String>();

	/**
	 * Getter for merchant ID.
	 *
	 * @return String
	 */
	public String getMerchantId() {
		return merchantId;
	}

	/**
	 * Getter for account.
	 *
	 * @return String
	 */
	public String getAccount() {
		return account;
	}

	/**
	 * Getter for order ID.
	 *
	 * @return String
	 */
	public String getOrderId() {
		return orderId;
	}

	/**
	 * Getter for amount.
	 *
	 * @return String
	 */
	public String getAmount() {
		return amount;
	}

	/**
	 * Getter for auth code.
	 *
	 * @return String
	 */
	public String getAuthCode() {
		return authCode;
	}

	/**
	 * Getter for time stamp.
	 *
	 * @return String
	 */
	public String getTimeStamp() {
		return timeStamp;
	}

	/**
	 * Getter for hash.
	 *
	 * @return String
	 */
	public String getHash() {
		return hash;
	}

	/**
	 * Getter for result.
	 *
	 * @return String
	 */
	public String getResult() {
		return result;
	}

	/**
	 * Getter for message.
	 *
	 * @return String
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * Getter for CVN result.
	 *
	 * @return String
	 */
	public String getCvnResult() {
		return cvnResult;
	}

	/**
	 * Getter for pas ref.
	 *
	 * @return String
	 */
	public String getPasRef() {
		return pasRef;
	}

	/**
	 * Getter for batch ID.
	 *
	 * @return String
	 */
	public String getBatchId() {
		return batchId;
	}

	/**
	 * Getter for ECI.
	 *
	 * @return String
	 */
	public String getEci() {
		return eci;
	}

	/**
	 * Getter for CAAV.
	 *
	 * @return String
	 */
	public String getCavv() {
		return cavv;
	}

	/**
	 * Getter for XID.
	 *
	 * @return String
	 */
	public String getXid() {
		return xid;
	}

	/**
	 * Getter for comment one.
	 *
	 * @return String
	 */
	public String getCommentOne() {
		return commentOne;
	}

	/**
	 * Getter for comment two.
	 *
	 * @return String
	 */
	public String getCommentTwo() {
		return commentTwo;
	}

	/**
	 * Getter for TSS map.
	 *
	 * @return Map<String, String>
	 */
	public Map<String, String> getTss() {
		return tss;
	}

	/**
	 * Setter for merchant ID.
	 *
	 * @param merchantId
	 */
	public void setMerchantId(String merchantId) {
		this.merchantId = merchantId;
	}

	/**
	 * Setter for account.
	 *
	 * @param account
	 */
	public void setAccount(String account) {
		this.account = account;
	}

	/**
	 * Setter for order ID.
	 *
	 * @param orderId
	 */
	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	/**
	 * Setter for amount.
	 *
	 * @param amount
	 */
	public void setAmount(String amount) {
		this.amount = amount;
	}

	/**
	 * Setter for auth code.
	 *
	 * @param authCode
	 */
	public void setAuthCode(String authCode) {
		this.authCode = authCode;
	}

	/**
	 * Setter for time stamp.
	 *
	 * @param timeStamp
	 */
	public void setTimeStamp(String timeStamp) {
		this.timeStamp = timeStamp;
	}

	/**
	 * Setter for hash.
	 *
	 * @param hash
	 */
	public void setHash(String hash) {
		this.hash = hash;
	}

	/**
	 * Setter for result.
	 *
	 * @param result
	 */
	public void setResult(String result) {
		this.result = result;
	}

	/**
	 * Setter for message.
	 *
	 * @param message
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * Setter for CVN result.
	 *
	 * @param cvnResult
	 */
	public void setCvnResult(String cvnResult) {
		this.cvnResult = cvnResult;
	}

	/**
	 * Setter for pas ref.
	 *
	 * @param pasRef
	 */
	public void setPasRef(String pasRef) {
		this.pasRef = pasRef;
	}

	/**
	 * Setter for batch ID.
	 *
	 * @param batchId
	 */
	public void setBatchId(String batchId) {
		this.batchId = batchId;
	}

	/**
	 * Setter for ECI.
	 *
	 * @param eci
	 */
	public void setEci(String eci) {
		this.eci = eci;
	}

	/**
	 * Setter for CAVV.
	 *
	 * @param cavv
	 */
	public void setCavv(String cavv) {
		this.cavv = cavv;
	}

	/**
	 * Setter for XID.
	 *
	 * @param xid
	 */
	public void setXid(String xid) {
		this.xid = xid;
	}

	/**
	 * Setter for comment one.
	 *
	 * @param commentOne
	 */
	public void setCommentOne(String commentOne) {
		this.commentOne = commentOne;
	}

	/**
	 * Setter for comment two.
	 *
	 * @param commentTwo
	 */
	public void setCommentTwo(String commentTwo) {
		this.commentTwo = commentTwo;
	}

	/**
	 * Setter for TSS map.
	 *
	 * @param tss
	 */
	public void setTss(Map<String, String> tss) {
		this.tss = tss;
	}

	/**
	 * Getter for supplementary data.
	 *
	 * @return Map<String, String>
	 */
	@JsonAnyGetter
	public Map<String, String> getSupplementaryData() {
		return supplementaryData;
	}

	/**
	 * Setter for supplementary data value.
	 *
	 * @param name
	 * @param value
	 */
	@JsonAnySetter
	public void setSupplementaryDataValue(String name, String value) {
		supplementaryData.put(name, value);
	}

	/**
	 * Creates the security hash from a number of fields and the shared secret.
	 *
	 * @param secret
	 * @return HppResponse
	 */
	public HppResponse hash(String secret) {
		this.hash = generateHash(secret);
		return this;
	}

	/**
	 * Creates the security hash from a number of fields and the shared secret.
	 *
	 * @param secret
	 * @return String
	 */
	private String generateHash(String secret) {

		//check for any null values and set them to empty string for hashing
		String timeStamp = null == this.timeStamp ? "" : this.timeStamp;
		String merchantId = null == this.merchantId ? "" : this.merchantId;
		String orderId = null == this.orderId ? "" : this.orderId;
		String result = null == this.result ? "" : this.result;
		String message = null == this.message ? "" : this.message;
		String pasRef = null == this.pasRef ? "" : this.pasRef;
		String authCode = null == this.authCode ? "" : this.authCode;

		//create String to hash
		String toHash = new StringBuilder().append(timeStamp)
				.append(".")
				.append(merchantId)
				.append(".")
				.append(orderId)
				.append(".")
				.append(result)
				.append(".")
				.append(message)
				.append(".")
				.append(pasRef)
				.append(".")
				.append(authCode)
				.toString();

		return GenerationUtils.generateHash(toHash, secret);
	}

	/**
	 * Base64 encodes the HPP response values.
	 *
	 * @param charset
	 * @return HppResponse
	 * @throws UnsupportedEncodingException
	 */
	public HppResponse encode(String charset) throws UnsupportedEncodingException {

		if (null != this.merchantId) {
			this.merchantId = new String(Base64.encodeBase64(this.merchantId.getBytes(charset)), charset);
		}
		if (null != this.account) {
			this.account = new String(Base64.encodeBase64(this.account.getBytes(charset)), charset);
		}
		if (null != this.amount) {
			this.amount = new String(Base64.encodeBase64(this.amount.getBytes(charset)), charset);
		}
		if (null != this.authCode) {
			this.authCode = new String(Base64.encodeBase64(this.authCode.getBytes(charset)), charset);
		}
		if (null != this.batchId) {
			this.batchId = new String(Base64.encodeBase64(this.batchId.getBytes(charset)), charset);
		}
		if (null != this.cavv) {
			this.cavv = new String(Base64.encodeBase64(this.cavv.getBytes(charset)), charset);
		}
		if (null != this.cvnResult) {
			this.cvnResult = new String(Base64.encodeBase64(this.cvnResult.getBytes(charset)), charset);
		}
		if (null != this.eci) {
			this.eci = new String(Base64.encodeBase64(this.eci.getBytes(charset)), charset);
		}
		if (null != this.commentOne) {
			this.commentOne = new String(Base64.encodeBase64(this.commentOne.getBytes(charset)), charset);
		}
		if (null != this.commentTwo) {
			this.commentTwo = new String(Base64.encodeBase64(this.commentTwo.getBytes(charset)), charset);
		}
		if (null != this.message) {
			this.message = new String(Base64.encodeBase64(this.message.getBytes(charset)), charset);
		}
		if (null != this.pasRef) {
			this.pasRef = new String(Base64.encodeBase64(this.pasRef.getBytes(charset)), charset);
		}
		if (null != this.hash) {
			this.hash = new String(Base64.encodeBase64(this.hash.getBytes(charset)), charset);
		}
		if (null != this.result) {
			this.result = new String(Base64.encodeBase64(this.result.getBytes(charset)), charset);
		}
		if (null != this.xid) {
			this.xid = new String(Base64.encodeBase64(this.xid.getBytes(charset)), charset);
		}
		if (null != this.orderId) {
			this.orderId = new String(Base64.encodeBase64(this.orderId.getBytes(charset)), charset);
		}
		if (null != this.timeStamp) {
			this.timeStamp = new String(Base64.encodeBase64(this.timeStamp.getBytes(charset)), charset);
		}
		if (null != this.tss) {
			Map<String, String> tssMap = new HashMap<String, String>();
			for (String key : tss.keySet()) {
				tssMap.put(key, new String(Base64.encodeBase64(tss.get(key).getBytes(charset)), charset));
			}
			this.tss = new HashMap<String, String>();
			this.tss = tssMap;
		}
		if (null != this.supplementaryData) {
			Map<String, String> supplementaryDataMap = new HashMap<String, String>();
			for (String key : supplementaryData.keySet()) {
				supplementaryDataMap.put(key, new String(Base64.encodeBase64(supplementaryData.get(key).getBytes(charset)), charset));
			}
			this.supplementaryData = new HashMap<String, String>();
			this.supplementaryData.putAll(supplementaryDataMap);
		}
		return this;
	}

	/**
	 * Base64 decodes the HPP response values.
	 *
	 * @param charset
	 * @return HppResponse
	 * @throws UnsupportedEncodingException
	 */
	public HppResponse decode(String charset) throws UnsupportedEncodingException {

		if (null != this.merchantId) {
			this.merchantId = new String(Base64.decodeBase64(this.merchantId.getBytes(charset)), charset);
		}
		if (null != this.account) {
			this.account = new String(Base64.decodeBase64(this.account.getBytes(charset)), charset);
		}
		if (null != this.amount) {
			this.amount = new String(Base64.decodeBase64(this.amount.getBytes(charset)), charset);
		}
		if (null != this.authCode) {
			this.authCode = new String(Base64.decodeBase64(this.authCode.getBytes(charset)), charset);
		}
		if (null != this.batchId) {
			this.batchId = new String(Base64.decodeBase64(this.batchId.getBytes(charset)), charset);
		}
		if (null != this.cavv) {
			this.cavv = new String(Base64.decodeBase64(this.cavv.getBytes(charset)), charset);
		}
		if (null != this.cvnResult) {
			this.cvnResult = new String(Base64.decodeBase64(this.cvnResult.getBytes(charset)), charset);
		}
		if (null != this.eci) {
			this.eci = new String(Base64.decodeBase64(this.eci.getBytes(charset)), charset);
		}
		if (null != this.commentOne) {
			this.commentOne = new String(Base64.decodeBase64(this.commentOne.getBytes(charset)), charset);
		}
		if (null != this.commentTwo) {
			this.commentTwo = new String(Base64.decodeBase64(this.commentTwo.getBytes(charset)), charset);
		}
		if (null != this.message) {
			this.message = new String(Base64.decodeBase64(this.message.getBytes(charset)), charset);
		}
		if (null != this.pasRef) {
			this.pasRef = new String(Base64.decodeBase64(this.pasRef.getBytes(charset)), charset);
		}
		if (null != this.hash) {
			this.hash = new String(Base64.decodeBase64(this.hash.getBytes(charset)), charset);
		}
		if (null != this.result) {
			this.result = new String(Base64.decodeBase64(this.result.getBytes(charset)), charset);
		}
		if (null != this.xid) {
			this.xid = new String(Base64.decodeBase64(this.xid.getBytes(charset)), charset);
		}
		if (null != this.orderId) {
			this.orderId = new String(Base64.decodeBase64(this.orderId.getBytes(charset)), charset);
		}
		if (null != this.timeStamp) {
			this.timeStamp = new String(Base64.decodeBase64(this.timeStamp.getBytes(charset)), charset);
		}
		if (null != this.tss) {
			Map<String, String> tssMap = new HashMap<String, String>();
			for (String key : tss.keySet()) {
				tssMap.put(key, new String(Base64.decodeBase64(tss.get(key).getBytes(charset)), charset));
			}
			this.tss = new HashMap<String, String>();
			this.tss = tssMap;
		}
		if (null != this.supplementaryData) {
			Map<String, String> supplementaryDataMap = new HashMap<String, String>();
			for (String key : supplementaryData.keySet()) {
				supplementaryDataMap.put(key, new String(Base64.decodeBase64(supplementaryData.get(key).getBytes(charset)), charset));
			}
			this.supplementaryData = new HashMap<String, String>();
			this.supplementaryData.putAll(supplementaryDataMap);
		}
		return this;
	}

	/**
	 * Helper method to determine if the HPP response security hash is valid.
	 *
	 * @param secret
	 * @return boolean
	 */
	public boolean isHashValid(String secret) {
		String generatedHash = generateHash(secret);
		return generatedHash.equals(this.hash);
	}

}


text:
var prettySwag = require('../pretty-swag');

var colors = ['red', 'pink', 'purple', 'deep-purple', 'indigo', 'blue', 'light-blue', 'cyan', 'teal', 'green', 'light-green', 'lime', 'yellow', 'amber', 'orange', 'deep-orange', 'brown', 'grey', 'blue-grey', 'black', 'white'];

for (var i = 0; i< colors.length;i++) {
    var starter = `{"input":"/tmp/data/pet.json","format":"lite","markdown":true,"theme":"blue","fixedNav":true,"output":"/tmp/pet.html","autoTags":true,"noDate":false,"noCredit":false,"noNav":false,"noRequest":false,"indent_num":3,"collapse":{"path":false,"method":false,"tool":true}}`;
    var config = JSON.parse(starter);
    var color = colors[i];
    config.theme = color;
    config.output = "/tmp/pet-"+color+".html";
    prettySwag.run(config.input, config.output, config, function (err, msg) {

        // console.log(color);
        if (err) {
            console.log("Error: " + err);
            process.exit(1);
        }
        console.log("DONE");
    });

}


text:
<?php

namespace Magento\Directory\Model;

use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Currency information acquirer class
 */
class CountryInformationAcquirer implements \Magento\Directory\Api\CountryInformationAcquirerInterface
{
    /**
     * @var \Magento\Directory\Model\Data\CountryInformationFactory
     */
    protected $countryInformationFactory;

    /**
     * @var \Magento\Directory\Model\Data\RegionInformationFactory
     */
    protected $regionInformationFactory;

    /**
     * @var \Magento\Directory\Helper\Data
     */
    protected $directoryHelper;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param \Magento\Directory\Model\Data\CountryInformationFactory $countryInformationFactory
     * @param \Magento\Directory\Model\Data\RegionInformationFactory $regionInformationFactory
     * @param \Magento\Directory\Helper\Data $directoryHelper
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     */
    public function __construct(
        \Magento\Directory\Model\Data\CountryInformationFactory $countryInformationFactory,
        \Magento\Directory\Model\Data\RegionInformationFactory $regionInformationFactory,
        \Magento\Directory\Helper\Data $directoryHelper,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->countryInformationFactory = $countryInformationFactory;
        $this->regionInformationFactory = $regionInformationFactory;
        $this->directoryHelper = $directoryHelper;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
    }

    /**
     * {@inheritdoc}
     */
    public function getCountriesInfo()
    {
        $countriesInfo = [];

        /** @var \Magento\Store\Model\Store $store */
        $store = $this->storeManager->getStore();

        $storeLocale = $this->scopeConfig->getValue(
            'general/locale/code',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORES,
            $store->getCode()
        );

        $countries = $this->directoryHelper->getCountryCollection($store);
        $regions = $this->directoryHelper->getRegionData();
        foreach ($countries as $data) {
            $countryInfo = $this->setCountryInfo($data, $regions, $storeLocale);
            $countriesInfo[] = $countryInfo;
        }

        return $countriesInfo;
    }

    /**
     * {@inheritdoc}
     */
    public function getCountryInfo($countryId)
    {
        $store = $this->storeManager->getStore();
        $storeLocale = $this->scopeConfig->getValue(
            'general/locale/code',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORES,
            $store->getCode()
        );

        $countriesCollection = $this->directoryHelper->getCountryCollection($store)->load();
        $regions = $this->directoryHelper->getRegionData();
        $country = $countriesCollection->getItemById($countryId);

        if (!$country) {
            throw new NoSuchEntityException(
                __(
                    'Requested country is not available.'
                )
            );
        }
        $countryInfo = $this->setCountryInfo($country, $regions, $storeLocale);

        return $countryInfo;
    }

    /**
     * Creates and initializes the information for \Magento\Directory\Model\Data\CountryInformation
     *
     * @param \Magento\Directory\Model\ResourceModel\Country $country
     * @param array $regions
     * @param string $storeLocale
     * @return \Magento\Directory\Model\Data\CountryInformation
     */
    protected function setCountryInfo($country, $regions, $storeLocale)
    {
        $countryId = $country->getCountryId();
        $countryInfo = $this->countryInformationFactory->create();
        $countryInfo->setId($countryId);
        $countryInfo->setTwoLetterAbbreviation($country->getData('iso2_code'));
        $countryInfo->setThreeLetterAbbreviation($country->getData('iso3_code'));
        $countryInfo->setFullNameLocale($country->getName($storeLocale));
        $countryInfo->setFullNameEnglish($country->getName('en_US'));

        if (array_key_exists($countryId, $regions)) {
            $regionsInfo = [];
            foreach ($regions[$countryId] as $id => $regionData) {
                $regionInfo = $this->regionInformationFactory->create();
                $regionInfo->setId($id);
                $regionInfo->setCode($regionData['code']);
                $regionInfo->setName($regionData['name']);
                $regionsInfo[] = $regionInfo;
            }
            $countryInfo->setAvailableRegions($regionsInfo);
        }

        return $countryInfo;
    }
}


text:
business-site
=============
Foundation framework with SASS


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Moq;
using System.Data.Entity;
using RoboBraille.WebApi.Models;
using System.Text;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net.Http;
using RoboBraille.WebApi.Controllers;

namespace RoboBraille.WebApi.Test
{
    [TestClass]
    public class TestBraille
    {
        [TestMethod]
        public async Task TestPostSensusBraille()
        {
            //init
            var mockJobs = new Mock<DbSet<Job>>();
            var mockServiceUsers = new Mock<DbSet<ServiceUser>>();
            var mockContext = new Mock<RoboBrailleDataContext>();

            // arrange
            var users = new List<ServiceUser> {
                new ServiceUser
                {
                EmailAddress = "test@test.eu",
                UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
                ApiKey = Encoding.UTF8.GetBytes("7b76ae41-def3-e411-8030-0c8bfd2336cd"),
                FromDate = new DateTime(2015, 1, 1),
                ToDate = new DateTime(2020, 1, 1),
                UserName = "TestUser",
                Jobs = null
                }
            }.AsQueryable();

            BrailleJob brj = new BrailleJob()
            {
                Id = Guid.NewGuid(),
                FileContent = Encoding.GetEncoding(1252).GetBytes("Braille job one"),
                UserId = Guid.Parse("d2b97532-e8c5-e411-8270-f0def103cfd0"),
                FileExtension = ".txt",
                FileName = "test1",
                MimeType = "text/plain",
                Status = JobStatus.Started,
                SubmitTime = DateTime.Now,
                DownloadCounter = 0,
                InputFileHash = new byte[8],
                BrailleLanguage = Language.enGB,
                BrailleFormat = BrailleFormat.sixdot,
                CharactersPerLine = 20,
                LinesPerPage = 20,
                Contraction = BrailleContraction.grade1,
                ConversionPath = ConversionPath.texttobraille,
                OutputFormat = OutputFormat.Unicode
            };
            BrailleJob brj2 = new BrailleJob()
            {
                Id = Guid.NewGuid(),
                FileContent = Encoding.GetEncoding(1252).GetBytes("Braille job two"),
                UserId = Guid.Parse("d2b87532-e8c5-e411-8270-f0def103cfd0"),
                FileExtension = ".txt",
                FileName = "test2",
                MimeType = "text/plain",
                Status = JobStatus.Started,
                SubmitTime = DateTime.Now,
                DownloadCounter = 2,
                InputFileHash = new byte[2],
                BrailleLanguage = Language.enGB,
                BrailleFormat = BrailleFormat.sixdot,
                CharactersPerLine = 20,
                LinesPerPage = 20,
                Contraction = BrailleContraction.grade1,
                ConversionPath = ConversionPath.texttobraille,
                OutputFormat = OutputFormat.Unicode
            };
            var jobs = new List<BrailleJob> { brj2 }.AsQueryable();

            mockJobs.As<IDbAsyncEnumerable<Job>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<Job>(jobs.GetEnumerator()));
            mockJobs.As<IQueryable<Job>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<Job>(jobs.Provider));

            mockJobs.As<IQueryable<Job>>().Setup(m => m.Expression).Returns(jobs.Expression);
            mockJobs.As<IQueryable<Job>>().Setup(m => m.ElementType).Returns(jobs.ElementType);
            mockJobs.As<IQueryable<Job>>().Setup(m => m.GetEnumerator()).Returns(jobs.GetEnumerator());

            mockServiceUsers.As<IDbAsyncEnumerable<ServiceUser>>().Setup(m => m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator<ServiceUser>(users.GetEnumerator()));
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Provider).Returns(new TestDbAsyncQueryProvider<ServiceUser>(users.Provider));
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.Expression).Returns(users.Expression);
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.ElementType).Returns(users.ElementType);
            mockServiceUsers.As<IQueryable<ServiceUser>>().Setup(m => m.GetEnumerator()).Returns(users.GetEnumerator());

            mockContext.Setup(m => m.Jobs).Returns(mockJobs.Object);
            mockContext.Setup(m => m.ServiceUsers).Returns(mockServiceUsers.Object);

            var repo = new BrailleRepository(mockContext.Object);
            var request = new HttpRequestMessage();
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Hawk id=\"d2b97532-e8c5-e411-8270-f0def103cfd0\", ts=\"1470657024\", nonce=\"VkcMGB\", mac=\"hXW+BLRoqwlUaQZQtpPToOWnVAh5KbAXGGT5f8dLMVk=\"");
            var serviceController = new BrailleController(repo)
            {
                Request = request
            };
            //call
            await serviceController.Post(brj);
            //test
            mockJobs.Verify(m => m.Add(It.IsAny<Job>()), Times.Once());

            mockContext.Verify(m => m.SaveChanges(), Times.Exactly(1));
            //twice if it is synced
            //mockContext.Verify(m => m.SaveChanges(), Times.Exactly(2));
        }

        //[TestMethod]
        //public async Task TestPostLibLouisBraille()
        //{
        //}
    }
}


text:
/**
 *
 */
package org.synyx.minos.i18n.domain;

import org.synyx.hades.domain.AbstractPersistable;

import java.util.Locale;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;

/**
 * Domain class that defines that a language({@link LocaleWrapper}) is available/required for a basename.
 *
 * @author Marc Kannegiesser - kannegiesser@synyx.de
 */
@Entity
public class AvailableLanguage extends AbstractPersistable<Long> {

    private static final long serialVersionUID = -8825239414786003379L;

    @Embedded
    private LocaleWrapper locale;

    @Column(nullable = false, length = 63)
    private String basename;

    private boolean required = true;

    /**
     * Create a new empty instance of {@link AvailableLanguage}. This constructor is needed by the OR mapper.
     */
    protected AvailableLanguage() {
    }

    /**
     * Creates a new instance of {@link AvailableLanguage} for the given combination of language (wrapped via
     * {@link LocaleWrapper}) and basename. The language is flagged as not required.
     *
     * @param locale the language
     * @param basename the basename
     */
    public AvailableLanguage(LocaleWrapper locale, String basename) {

        super();
        this.locale = locale;
        this.basename = basename;
    }

    /**
     * Creates a new instance of {@link AvailableLanguage} for the given combination of language (wrapped via
     * {@link LocaleWrapper}) and basename.
     *
     * @param locale the language
     * @param basename the basename
     * @param required flag indicating that the language is required
     */
    public AvailableLanguage(LocaleWrapper locale, String basename, boolean required) {

        super();
        this.locale = locale;
        this.basename = basename;
        this.required = required;
    }

    /**
     * Get the locale (wrapped via {@link LocaleWrapper}) of this available language.
     *
     * @return the locale of this available language.
     */
    public LocaleWrapper getLocale() {

        return locale;
    }

    /**
     * Set the locale (wrapped via {@link LocaleWrapper}) of this available language.
     *
     * @param locale the locale to set.
     */
    public void setLocale(LocaleWrapper locale) {

        this.locale = locale;
    }

    /**
     * Get the {@link Locale} of this available language.
     *
     * @return the {@link Locale} of this available language.
     */
    public Locale getRealLocale() {

        return locale.getLocale();
    }

    /**
     * Set the {@link Locale} of this available language.
     *
     * @param locale the {@link Locale} to set.
     */
    public void setRealLocale(Locale locale) {

        this.locale = new LocaleWrapper(locale);
    }

    /**
     * Get the basename of this available language.
     *
     * @return the basename of this available language.
     */
    public String getBasename() {

        return basename;
    }

    /**
     * Set the basename of this available language.
     *
     * @param basename the basename to set.
     */
    public void setBasename(String basename) {

        this.basename = basename;
    }

    /**
     * Get the required flag of this available language.
     *
     * @return the required flag of this available language.
     */
    public boolean isRequired() {

        return required;
    }

    /**
     * Set the required flag of this available language.
     *
     * @param required the required flag to set.
     */
    public void setRequired(boolean required) {

        this.required = required;
    }

    @Override
    public String toString() {

        return String.format("%s %s", basename, locale.toString());
    }
}


text:
package com.capitalone.dashboard.util;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupDir;

/**
 * Provides dynamic variable access to the available source system queries for
 * the feature widget.
 *
 * @author kfk884
 *
 */
@Component
public class FeatureWidgetQueries {
	private final STGroup folder;

	/**
	 * Constructs the source system query configuration class, based on system
	 * settings.
	 *
	 * @param featureSettings
	 *            Feature collector system settings
	 */
	@Autowired
	public FeatureWidgetQueries(FeatureSettings featureSettings) {
		this.folder = new STGroupDir(featureSettings.getQueryFolder(), '$', '$');
	}

	/**
	 * Retrieves source system queries based on the query name (without the file
	 * type) and a specified change date parameter.
	 *
	 * @param changeDatePara
	 *            The change date specified from which to pull data with a given
	 *            query template.
	 * @param queryName
	 *            The source system query name (without the file type).
	 * @return A given source system query, in String format.
	 */
	public String getQuery(String changeDatePara, String queryName) {
		ST st = folder.getInstanceOf(queryName);
		st.add("changeDate", changeDatePara);
		String query = st.render();

		return query;
	}

	/**
	 * Retrieves source system queries based on the query name (without the file
	 * type). This will only grab a non-parametered query.
	 *
	 * @param queryName
	 *            The source system query name (without the file type).
	 * @return A given source system query, in String format.
	 */
	public String getQuery(String queryName) {
		ST st = folder.getInstanceOf(queryName);
		String query = st.render();

		return query;
	}

	/**
	 * Retrieves source system queries based on the query name (without the file
	 * type) and a specified epic key parameter.
	 *
	 * @param epicKeyParam
	 *            The Epic key for a given issue.
	 * @param queryName
	 *            The source system query name (without the file type).
	 * @return A given source system query, in String format.
	 */
	public String getEpicQuery(String epicKeyParam, String queryName) {
		ST st = folder.getInstanceOf(queryName);
		st.add("epicKey", epicKeyParam);
		String query = st.render();

		return query;
	}

	public String getEpicQuery(List<String> epicKeysParam, String queryName) {
		ST st = folder.getInstanceOf(queryName);
		st.add("epicKeys", epicKeysParam);
		String query = st.render();

		return query;
	}

	/**
	 * Retrieves source system queries based on the query name (without the file
	 * type) and a specified change date parameter.
	 *
	 * @param changeDatePara
	 *            The change date specified from which to pull data with a given
	 *            query template.
	 * @param issueType
	 *            The Jira IssueType specified from which to pull data with a
	 *            given query template.
	 * @param queryName
	 *            The source system query name (without the file type).
	 * @return A given source system query, in String format.
	 */
	public String getStoryQuery(String changeDatePara, String issueType, String queryName) {
		ST st = folder.getInstanceOf(queryName);
		st.add("changeDate", changeDatePara);
		st.add("issueType", issueType);
		String query = st.render();

		return query;
	}
}


text:
package peerchat

import com.typesafe.config.{Config => TConfig, ConfigFactory}

class TwitterConfig(config: TConfig) {
  val consumerKey     = config.getString("ConsumerKey")
  val consumerSecret  = config.getString("ConsumerSecret")
  val callbackURL     = config.getString("CallbackURL")
}
class GithubConfig(config: TConfig) {
  val clientID        = config.getString("ClientID")
  val clientSecret    = config.getString("ClientSecret")
  val accsessTokenURL = config.getString("AccsessTokenURL")
  val userAPIURL      = config.getString("UserAPIURL")
}

class DefaultDBConfig {
  val host = "127.0.0.1"
  val port = 27017
}

class DBConfig(config: TConfig) extends DefaultDBConfig {
  override val host = config.getString("host")
  override val port = config.getInt("port")
}

object Config {
  private val authConfig = xitrum.Config.application.getConfig("auth")
  val twitter    = new TwitterConfig(authConfig.getConfig("twitter"))
  val github     = new GithubConfig(authConfig.getConfig("github"))
  val secureKey  = authConfig.getString("secureKey")

  val dumpEnable =
    if (xitrum.Config.application.hasPath("dumpEnable"))
      Some(xitrum.Config.application.getBoolean("dumpEnable"))
    else
      None

  val db =
    if (xitrum.Config.application.hasPath("db"))
      new DBConfig(xitrum.Config.application.getConfig("db"))
    else
      new DefaultDBConfig()
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Qwack.Math;
using static System.Math;

namespace Qwack.Math.Tests
{
    public class BondUtilsFacts
    {
        [Fact]
        //https://www.investopedia.com/terms/y/yieldtocall.asp
        public void YtcFromPriceFacts()
        {
            var cleanPrice = 1175.0;
            var couponRate = 0.1;
            var faceValue = 1000.0;
            var callPrice = 1100.0;
            var tCall = 5.0;

            var ytc = BondUtils.YtcFromPrice(couponRate, callPrice/faceValue, tCall, cleanPrice/faceValue);
            //var ytc = BondUtils.YtcFromPrice(couponRate * faceValue, callPrice , tCall, cleanPrice );

            Assert.Equal(0.0743, ytc, 4);
        }

        [Fact]
        public void YtmRoundTrip()
        {
            var cleanPrice = 1175.0;
            var couponRate = 0.1;
            var faceValue = 1000.0;
            var t = 5.0;

            var ytm = BondUtils.YieldToMaturity(couponRate, faceValue, cleanPrice, t);
            var price = BondUtils.PriceFromYtm(couponRate, faceValue, ytm, t);

            Assert.Equal(cleanPrice, price, 8);
        }

        [Fact]
        //https://www.investopedia.com/terms/d/duration.asp
        public void MacaulayTests()
        {
            var cleanPrice = 110.83;
            var couponRate = 0.1;
            var couponsPerYear = 2.0;
            var faceValue = 100;
            var ytm = 0.06;
            var t = 3.0;
            var tNext = 0.5;

            var mac = BondUtils.MacaulayDuration(couponRate, faceValue, ytm, couponsPerYear, t, tNext, cleanPrice);

            Assert.Equal(2.684, mac, 3);
        }

        [Fact]

        public void xccyTests()
        {
            var dirtyPrice = 101.50 / 100;
            var couponRate = 0.05875;
            var couponsPerYear = 2.0;
            var faceValue = 100;
            var t = 2.75;
            var tNext = 0.25;
            var fxRates = (double t) => Exp(t * 0.02);
            var ytm = BondUtils.YieldToMaturity(couponRate * faceValue, faceValue, dirtyPrice*100, t);
            var ytmX = BondUtils.YtmInBase(couponRate, faceValue, couponsPerYear, t, tNext, fxRates, dirtyPrice);

            Assert.Equal(0.083453953662142838, ytmX, 3);

            couponsPerYear = 1.0;
            tNext = 0.75;
            ytm = BondUtils.YieldToMaturity(couponRate * faceValue, faceValue, dirtyPrice * 100, t);
            ytmX = BondUtils.YtmInBase(couponRate, faceValue, couponsPerYear, t, tNext, fxRates, dirtyPrice);

            Assert.Equal(0.07988081304417495, ytmX, 3);
        }
    }
}


text:
<?php

namespace Phlexible\Bundle\ProblemBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Add problem checkers pass.
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class AddProblemCheckersPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $problemCheckers = [];
        foreach (array_keys($container->findTaggedServiceIds('phlexible_problem.checker')) as $id) {
            $problemCheckers[] = new Reference($id);
        }
        $container->getDefinition('phlexible_problem.problem_checkers')->replaceArgument(0, $problemCheckers);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="ru.tests.RemoveContactFromGroup" tests="1" skipped="1" failures="0" errors="0" timestamp="2017-03-21T20:59:24" hostname="User-Asus" time="0.0">
  <properties/>
  <testcase name="testContactRemovingFromGroup" classname="ru.tests.RemoveContactFromGroup" time="0.0">
    <skipped/>
  </testcase>
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>


text:
package de.badw.strauss.glyphpicker.controller.action;

import de.badw.strauss.glyphpicker.view.TabPanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import java.util.Set;

/**
 * An action to reload the list model.
 */
public class ReloadAction extends AbstractPickerAction {

    /**
     * The key of the action.
     */
    public static final String KEY = "reload";
    private static final long serialVersionUID = 1L;
    /**
     * The name of the class.
     */
    private static final String CLASS_NAME = ReloadAction.class.getSimpleName();
    /**
     * The actions affected by this action.
     */
    private final Set<Action> actions;

    /**
     * Instantiates a new ReloadAction.
     *
     * @param panel    The container tab panel
     * @param listener the property change listener to be added to this action
     * @param actions  The actions affected by this action
     */
    public ReloadAction(TabPanel panel, PropertyChangeListener listener, Set<Action> actions) {
        super(CLASS_NAME, "/images/oxygen/Refresh16.png", "ctrl L");
        addPropertyChangeListener(listener);
        this.actions = actions;
        bindAcceleratorToComponent(this, panel);
    }

    /* (non-Javadoc)
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        firePropertyChange(KEY, null, null);
        for (Action action : actions) {
            action.setEnabled(false);
        }
    }
}


text:
Describe 'Describe-Scoped Test Case setup' {
    BeforeEach {
        $testVariable = 'From BeforeEach'
    }

    $testVariable = 'Set in Describe'

    It 'Assigns the correct value in first test' {
        $testVariable | Should Be 'From BeforeEach'
        $testVariable = 'Set in It'
    }

    It 'Assigns the correct value in subsequent tests' {
        $testVariable | Should Be 'From BeforeEach'
    }
}

Describe 'Context-scoped Test Case setup' {
    $testVariable = 'Set in Describe'

    Context 'The context' {
        BeforeEach {
            $testVariable = 'From BeforeEach'
        }

        It 'Assigns the correct value inside the context' {
            $testVariable | Should Be 'From BeforeEach'
        }
    }

    It 'Reports the original value after the Context' {
        $testVariable | Should Be 'Set in Describe'
    }
}

Describe 'Multiple Test Case setup blocks' {
    $testVariable = 'Set in Describe'

    BeforeEach {
        $testVariable = 'Set in Describe BeforeEach'
    }

    Context 'The context' {
        It 'Executes Describe setup blocks first, then Context blocks in the order they were defined (even if they are defined after the It block.)' {
            $testVariable | Should Be 'Set in the second Context BeforeEach'
        }

        BeforeEach {
            $testVariable = 'Set in the first Context BeforeEach'
        }

        BeforeEach {
            $testVariable = 'Set in the second Context BeforeEach'
        }
    }

    It 'Continues to execute Describe setup blocks after the Context' {
        $testVariable | Should Be 'Set in Describe BeforeEach'
    }
}

Describe 'Describe-scoped Test Case teardown' {
    $testVariable = 'Set in Describe'

    AfterEach {
        $testVariable = 'Set in AfterEach'
    }

    It 'Does not modify the variable before the first test' {
        $testVariable | Should Be 'Set in Describe'
    }

    It 'Modifies the variable after the first test' {
        $testVariable | Should Be 'Set in AfterEach'
    }
}

Describe 'Multiple Test Case teardown blocks' {
    $testVariable = 'Set in Describe'

    AfterEach {
        $testVariable = 'Set in Describe AfterEach'
    }

    Context 'The context' {
        AfterEach {
            $testVariable = 'Set in the first Context AfterEach'
        }

        It 'Performs a test in Context' { "some output to prevent the It being marked as Pending and failing because of Strict mode"}

        It 'Executes Describe teardown blocks after Context teardown blocks' {
            $testVariable | Should Be 'Set in the second Describe AfterEach'
        }
    }

    AfterEach {
        $testVariable = 'Set in the second Describe AfterEach'
    }
}

$script:DescribeBeforeAllCounter = 0
$script:DescribeAfterAllCounter  = 0
$script:ContextBeforeAllCounter  = 0
$script:ContextAfterAllCounter   = 0

Describe 'Test Group Setup and Teardown' {
    It 'Executed the Describe BeforeAll regardless of definition order' {
        $script:DescribeBeforeAllCounter | Should Be 1
    }

    It 'Did not execute any other block yet' {
        $script:DescribeAfterAllCounter | Should Be 0
        $script:ContextBeforeAllCounter | Should Be 0
        $script:ContextAfterAllCounter  | Should Be 0
    }

    BeforeAll {
        $script:DescribeBeforeAllCounter++
    }

    AfterAll {
        $script:DescribeAfterAllCounter++
    }

    Context 'Context scoped setup and teardown' {
        BeforeAll {
            $script:ContextBeforeAllCounter++
        }

        AfterAll {
            $script:ContextAfterAllCounter++
        }

        It 'Executed the Context BeforeAll block' {
            $script:ContextBeforeAllCounter | Should Be 1
        }

        It 'Has not executed any other blocks yet' {
            $script:DescribeBeforeAllCounter | Should Be 1
            $script:DescribeAfterAllCounter  | Should Be 0
            $script:ContextAfterAllCounter   | Should Be 0
        }
    }

    It 'Executed the Context AfterAll block' {
        $script:ContextAfterAllCounter | Should Be 1
    }
}

Describe 'Finishing TestGroup Setup and Teardown tests' {
    It 'Executed each Describe and Context group block once' {
        $script:DescribeBeforeAllCounter | Should Be 1
        $script:DescribeAfterAllCounter  | Should Be 1
        $script:ContextBeforeAllCounter  | Should Be 1
        $script:ContextAfterAllCounter   | Should Be 1
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="GalleryTilePreview">
        <attr name="maxTiles" format="integer"/>
        <attr name="showMask" format="boolean"/>
        <attr name="showAnimation" format="boolean"/>
        <attr name="placeholderRes" format="reference"/>
        <attr name="failureRes" format="reference"/>
        <attr name="progressBarRes" format="reference"/>
        <attr name="progressBarAutoRotateIntervalSeconds" format="integer"/>
    </declare-styleable>
</resources>


text:
class CreateRatings < ActiveRecord::Migration
  def change
    create_table :ratings do |t|
      t.integer :rating
      t.integer :recipe_id
      t.integer :user_id

      t.timestamps
    end
  end
end


text:
//
// (C) Copyright 2015 Martin E. Nordberg III
// Apache 2.0 License
//

package org.steamflake.templates.domain.parser.impl;

import org.steamflake.core.persistence.codeio.scanning.FileScanner;
import org.steamflake.templates.domain.model.api.directives.ISteamflakeTmAbstractDirective;
import org.steamflake.templates.domain.model.api.directives.ISteamflakeTmCompositeDirective;
import org.steamflake.templates.domain.model.api.elements.ISteamflakeTmDirectiveSequence;
import org.steamflake.templates.domain.model.api.elements.ISteamflakeTmRule;
import org.steamflake.templates.domain.parser.api.SteamflakeTmParser;

import java.util.Optional;

import static org.steamflake.templates.domain.parser.impl.SteamflakeTmParserUtil.originOf;

/**
 * Implementation of Steamflake template rule body parsing.
 */
public class SteamflakeTmRuleBodyParser {

    /**
     * Constructs a new parser for the given input code and output rule.
     *
     * @param rule     the rule to parse the result into.
     * @param ruleBody the code to parse.
     */
    public SteamflakeTmRuleBodyParser(
        ISteamflakeTmRule rule,
        FileScanner.Token ruleBody,
        String directiveOpenDelimiter,
        String directiveCloseDelimiter
    ) {

        this.rule = rule;
        this.scanner = new FileScanner(
            ruleBody.getText(),
            ruleBody.getFileName(),
            ruleBody.getLine(),
            ruleBody.getColumn()
        );
        this.directiveOpenDelimiter = directiveOpenDelimiter;
        this.directiveCloseDelimiter = directiveCloseDelimiter;
    }

    /**
     * Parses the entire code of the rule body.
     *
     * @throws SteamflakeTmParser.SteamflakeTmParserException
     */
    public void parse() throws SteamflakeTmParser.SteamflakeTmParserException {

        try {
            this.parseDirectiveSequence( this.rule.getDirectiveSequence(), "rule" );
        }
        catch ( FileScanner.FileScannerException e ) {
            throw new SteamflakeTmParser.SteamflakeTmParserException( e.getMessage(), e );
        }

    }

    /**
     * Parses the tokens in the body of a rule.
     *
     * @param container the rule or composite directive to contain the parsed results.
     *
     * @throws FileScanner.FileScannerException               if a syntax error is found.
     * @throws SteamflakeTmParser.SteamflakeTmParserException if a parsing error occurs.
     */
    private void parseDirectiveSequence( ISteamflakeTmDirectiveSequence container, String keyword )
        throws FileScanner.FileScannerException,
               SteamflakeTmParser.SteamflakeTmParserException {

        // Look for text up to the next opening delimiter.
        Optional<FileScanner.Token> text = this.scanner.acceptUntil( this.directiveOpenDelimiter );

        // While there is text followed by an opening delimiter...
        while ( text.isPresent() ) {

            // Add the text to the rule if not empty.
            if ( !text.get().getText().isEmpty() ) {
                container.addTextDirective( originOf( text.get() ), text.get().getText() );
            }

            this.scanner.scan( this.directiveOpenDelimiter );

            // Handle a closing tag if present.
            if ( this.scanner.accept( "/" ).isPresent() ) {
                this.scanner.scan( keyword );
                this.scanner.acceptWhitespace();
                this.scanner.scan( this.directiveCloseDelimiter );
                return;
            }

            // Scan the body of the directive.
            FileScanner.Token directiveBody = this.scanner.scanUntil( this.directiveCloseDelimiter );

            // Parse the code directive into the rule or composite directive.
            ISteamflakeTmAbstractDirective directive = new SteamflakeTmDirectiveParser(
                container,
                directiveBody
            ).parse();

            this.scanner.scan( this.directiveCloseDelimiter );

            // If it was a composite directive...
            if ( directive.isComposite() ) {
                ISteamflakeTmCompositeDirective compositeDirective = (ISteamflakeTmCompositeDirective) directive;

                // Recursively parse until the closing directive.
                this.parseDirectiveSequence(
                    compositeDirective.getDirectiveSequence(),
                    compositeDirective.getKeyword()
                );
            }

            // Scan the next block of text up to an opening delimiter.
            text = this.scanner.acceptUntil( this.directiveOpenDelimiter );

        }

        // Trigger an error if we found no closing directive for a composite directive.
        if ( !"rule".equals( keyword ) ) {
            throw new SteamflakeTmParser.SteamflakeTmParserException(
                "Missing closing directive: '" + this.directiveOpenDelimiter + "/" + keyword + this.directiveCloseDelimiter + "'.",
                this.scanner.scanNothing()
            );
        }

        // Parse the remaining text, if any, into the final directive for the rule.
        FileScanner.Token remainderText = this.scanner.scanUntilEndOfInput();

        if ( !remainderText.getText().isEmpty() ) {
            container.addTextDirective( originOf( remainderText ), remainderText.getText() );
        }

    }

    /** The delimiter that indicates the end of a code directive (usually "}}"). */
    private final String directiveCloseDelimiter;

    /** The delimiter that indicates the start of a code directive (usually "{{"). */
    private final String directiveOpenDelimiter;

    /** The rule to which the parsed rule body tokens are to be added. */
    private final ISteamflakeTmRule rule;

    /** The scanner of template file input. */
    private final FileScanner scanner;

}


text:
package video

import "bitbucket.org/ikeikeikeike/antenna/ormapper"

type RankingsController struct {
	BaseController
}

func (c *RankingsController) NestFinish() {
	c.PushInAccessLog()
}

func (c *RankingsController) Dayly() {
	c.TplNames = "video/rankings/dayly.tpl"

	db := ormapper.VideoRankings().
		Where("video_ranking.rank > ?", 0).
		Where("video_ranking.begin_name = ?", "dayly").
		Where("video_ranking.begin_time = ?", c.GetParamatedNow().BeginningOfDay()).
		Limit(100)

	var rankings []*ormapper.VideoRanking
	db.Order("video_ranking.rank ASC").Find(&rankings)

	for _, s := range rankings {
		s.RankingsLoader()
	}

	c.Data["Rankings"] = rankings
}

func (c *RankingsController) Weekly() {
	c.TplNames = "video/rankings/weekly.tpl"

	db := ormapper.VideoRankings().
		Where("video_ranking.rank > ?", 0).
		Where("video_ranking.begin_name = ?", "weekly").
		Where("video_ranking.begin_time = ?", c.GetParamatedNow().BeginningOfWeek()).
		Limit(100)

	var rankings []*ormapper.VideoRanking
	db.Order("video_ranking.rank ASC").Find(&rankings)

	for _, s := range rankings {
		s.RankingsLoader()
	}

	c.Data["Rankings"] = rankings
}

func (c *RankingsController) Monthly() {
	c.TplNames = "video/rankings/monthly.tpl"

	db := ormapper.VideoRankings().
		Where("video_ranking.rank > ?", 0).
		Where("video_ranking.begin_name = ?", "monthly").
		Where("video_ranking.begin_time = ?", c.GetParamatedNow().BeginningOfMonth()).
		Limit(100)

	var rankings []*ormapper.VideoRanking
	db.Order("video_ranking.rank ASC").Find(&rankings)

	for _, s := range rankings {
		s.RankingsLoader()
	}

	c.Data["Rankings"] = rankings
}

func (c *RankingsController) Yearly() {
	c.TplNames = "video/rankings/yearly.tpl"

	db := ormapper.VideoRankings().
		Where("video_ranking.rank > ?", 0).
		Where("video_ranking.begin_name = ?", "yearly").
		Where("video_ranking.begin_time = ?", c.GetParamatedNow().BeginningOfYear()).
		Limit(100)

	var rankings []*ormapper.VideoRanking
	db.Order("video_ranking.rank ASC").Find(&rankings)

	for _, s := range rankings {
		s.RankingsLoader()
	}

	c.Data["Rankings"] = rankings
}


text:
* Add support of HTTPS connections through proxy. See #186. (@Connorhd)

## 0.8.2 (2015-04-06)

* Fix Celluloid::IO compatibility. See #203. (@ixti)
* Cleanup obsolete code. (@zanker)

## 0.8.1 (2015-04-02)

* Add missing `require "resolv"`. See #202. (@ixti)
* Add block-form `#persistent` calls. See #200, #201. (@ixti)

## 0.8.0 (2015-04-01)

* Properly handle WaitWritable for SSL. See #199. (@zanker)
* Add support for non-ASCII URis. See #197. (@ixti)
* Add configurable connection timeouts. See #187, #194, #195. (@zanker)
* Refactor requests redirect following logic. See #179. (@ixti)
* Support for persistent HTTP connections (@zanker)
* Add caching support. See #77 and #177. (@Asmod4n, @pezra)
* Improve servers used in specs boot up. Issue was initially raised up
  by @olegkovalenko. See #176. (@ixti)
* Reflect FormData rename changes (FormData -> HTTP::FormData). (@ixti)
* `HTTP::Headers` now raises `HTTP::InvalidHeaderNameError` in case of
  (surprise) invalid HTTP header field name (e.g.`"Foo:Bar"`). See #173.
  (@ixti)

## 0.7.3 (2015-03-24)

* SECURITY FIX: http.rb failed to call the `#post_connection_check` method on
  SSL connections. This method implements hostname verification, and without it
  `http.rb` was vulnerable to MitM attacks. The problem was corrected by calling
  `#post_connection_check` (CVE-2015-1828) (@zanker)

## 0.7.2 (2015-03-02)

* Swap from `form_data` to `http-form_data` (changed gem name).

## 0.7.1 (2015-01-03)

* Gemspec fixups
* Remove superfluous space in HTTP::Response inspection

## 0.7.0 (2015-01-02)

* Add support of multipart form data. See #73, #167. (@ixti)
* Fix URI path normalization: `https://github.com` -> `https://github.com/`.
  (@ixti)
* Fix handling of EOF which caused infinite loop. See #163, #166 and #152. (@mickm, @ixti)
* Drop Ruby 1.8.7 support. (@ixti)
* Fix default Host header value. See #150. (@ixti)
* Remove BearerToken authorization header. (@ixti)
* `#auth` sugar now accepts only string value of Authorization header.
  Calling `#auth(:basic, opts)` is deprecated, use `#basic_auth(opts)` instead.
  (@ixti)
* Fix handling of chunked responses without Content-Length header. (@ixti)
* Remove `HTTP::Request#method` and deprecate `HTTP::Request#__method__`
  (@sferik)
* Deprecate `HTTP::Response::STATUS_CODES`,
  use `HTTP::Response::Status::REASONS` instead (@ixti)
* Deprecate `HTTP::Response::SYMBOL_TO_STATUS_CODE` (@ixti)
* Deprecate `HTTP::Response#status_code` (@ixti)
* `HTTP::Response#status` now returns `HTTP::Response::Status`. (@ixti)
* `HTTP::Response#reason` and `HTTP::Response#code` are proxies them
  to corresponding methods of `HTTP::Response#status` (@ixti)
* Rename `HTTP.with_follow` to `HTTP.follow` and mark former one as being
  deprecated (@ixti)
* Delegate `HTTP::Response#readpartial` to `HTTP::Response::Body` (@ixti)

## 0.6.4 (2015-03-25)

* SECURITY FIX: http.rb failed to call the `#post_connection_check` method on
  SSL connections. This method implements hostname verification, and without it
  `http.rb` was vulnerable to MitM attacks. The problem was corrected by calling
  `#post_connection_check` (CVE-2015-1828) (@zanker, backported by @nicoolas25)

## 0.6.3 (2014-11-14)

* Backported EOF fix from master branch. See #166. (@ixti)

## 0.6.2 (2014-08-06)

* Fix default Host header value. See #150. (@ixti)
* Deprecate BearerToken authorization header. (@ixti)
* Fix handling of chunked responses without Content-Length header. (@ixti)
* Rename `HTTP.with_follow` to `HTTP.follow` and mark former one as being
  deprecated (@ixti)

## 0.6.1 (2014-05-07)

* Fix request `Content-Length` calculation for Unicode (@challengeechallengee)
* Add `Response#flush` (@ixti)
* Fix `Response::Body#readpartial` default size (@hannesg, @ixti)
* Add missing `CRLF` for chunked bodies (@hannesg)
* Fix forgotten CGI require (@ixti)
* Improve README (@tarcieri)

## 0.6.0 (2014-04-04)

* Rename `HTTP::Request#method` to `HTTP::Request#verb` (@krainboltgreene)
* Add `HTTP::ResponseBody` class (@tarcieri)
* Change API of response on `HTTP::Client.request` and "friends" (`#get`, `#post`, etc) (@tarcieri)
* Add `HTTP::Response#readpartial` (@tarcieri)
* Add `HTTP::Headers` class (@ixti)
* Fix and improve following redirects (@ixti)
* Add `HTTP::Request#redirect` (@ixti)
* Add `HTTP::Response#content_type` (@ixti)
* Add `HTTP::Response#mime_type` (@ixti)
* Add `HTTP::Response#charset` (@ixti)
* Improve error message upon invalid URI scheme (@ixti)
* Consolidate errors under common `HTTP::Error` namespace (@ixti)
* Add easy way of adding Authorization header (@ixti)
* Fix proxy support (@hundredwatt)
* Fix and improve query params handing (@jwinter)
* Change API of custom MIME type parsers (@ixti)
* Remove `HTTP::Chainable#with_response` (@ixti)
* Remove `HTTP::Response::BodyDelegator` (@ixti)
* Remove `HTTP::Response#parsed_body` (@ixti)
* Bump up input buffer from 4K to 16K (@tarcieri)

``` ruby
# Main API change you will mention is that `request` method and it's
# syntax sugar helpers like `get`, `post`, etc. now returns Response
# object instead of BodyDelegator:

response = HTTP.get "http://example.com"
raw_body = HTTP.get("http://example.com").to_s
parsed_body = HTTP.get("http://example.com/users.json").parse

# Second major change in API is work with request/response headers
# It is now delegated to `HTTP::Headers` class, so you can check it's
# documentation for details, here we will only outline main difference.
# Duckface (`[]=`) does not appends headers anymore

request[:content_type] = "text/plain"
request[:content_type] = "text/html"
request[:content_type] # => "text/html"

# In order to add multiple header values, you should pass array:

request[:cookie] = ["foo=bar", "woo=hoo"]
request[:cookie] # => ["foo=bar", "woo=hoo"]

# or call `#add` on headers:

request.headers.add :accept, "text/plain"
request.headers.add :accept, "text/html"
request[:accept] # => ["text/plain", "text/html"]

# Also, you can now read body in chunks (stream):

res = HTTP.get "http://example.com"
File.open "/tmp/dummy.bin", "wb" do |io|
  while (chunk = res.readpartial)
    io << chunk
  end
end
```

[Changes discussion](https://github.com/httprb/http.rb/issues/116)

## 0.5.1 (2014-05-27)

* Backports redirector fixes from 0.6.0 (@ixti)
* EOL of 0.5.X branch.

## 0.5.0 (2013-09-14)

* Add query string support
* New response delegator allows HTTP.get(uri).response
* HTTP::Chainable#stream provides a shorter alias for
  with_response(:object)
* Better string inspect for HTTP::Response
* Curb compatibility layer removed

## 0.4.0 (2012-10-12)

* Fix bug accessing https URLs
* Fix several instances of broken redirect handling
* Add default user agent
* Many additional minor bugfixes

## 0.3.0 (2012-09-01)

* New implementation based on tmm1's http_parser.rb instead of Net::HTTP
* Support for following redirects
* Support for request body through {:body => ...} option
* HTTP#with_response (through Chainable)

## 0.2.0 (2012-03-05)

* Request and response objects
* Callback system
* Internal refactoring ensuring true chainability
* Use the certified gem to ensure SSL certificate verification

## 0.1.0 (2012-01-26)

* Testing against WEBrick
* Curb compatibility (require 'http/compat/curb')

## 0.0.1 (2011-10-11)

* Initial half-baked release

## 0.0.0 (2011-10-06)

* Vapoware release to claim the "http" gem name >:D


text:
logfile="/var/log/patchsystemvm.log"

# To use existing console proxy .zip-based package file
patch_systemvm() {
   local patchfile=$1
   local backupfolder="/tmp/.conf.backup"
   if [ -f /usr/local/cloud/systemvm/conf/cloud.jks ]; then
      rm -fr $backupfolder
      mkdir -p $backupfolder
      cp -r /usr/local/cloud/systemvm/conf/* $backupfolder/
   fi
   rm /usr/local/cloud/systemvm -rf
   mkdir -p /usr/local/cloud/systemvm
   echo "All" | unzip $patchfile -d /usr/local/cloud/systemvm >$logfile 2>&1
   find /usr/local/cloud/systemvm/ -name \*.sh | xargs chmod 555
   if [ -f $backupfolder/cloud.jks ]; then
      cp -r $backupfolder/* /usr/local/cloud/systemvm/conf/
      echo "Restored keystore file and certs using backup" >> $logfile
   fi
   rm -fr $backupfolder
   # Import global cacerts into 'cloud' service's keystore
   keytool -importkeystore -srckeystore /etc/ssl/certs/java/cacerts -destkeystore /usr/local/cloud/systemvm/certs/realhostip.keystore -srcstorepass changeit -deststorepass vmops.com -noprompt || true
   return 0
}

CMDLINE=/var/cache/cloud/cmdline
PATCH_MOUNT=$1
TYPE=$2

# Refresh and setup systemd
chmod -x /etc/systemd/system/cloud*.service
systemctl daemon-reload

echo "Patching systemvm for cloud service with mount=$PATCH_MOUNT for type=$TYPE" >> $logfile

if [ "$TYPE" == "consoleproxy" ] || [ "$TYPE" == "secstorage" ]  && [ -f ${PATCH_MOUNT}/agent.zip ]
then
  patch_systemvm ${PATCH_MOUNT}/agent.zip
  if [ $? -gt 0 ]
  then
    echo "Failed to apply patch systemvm\n" >> $logfile
    exit 1
  fi
fi


text:
		<button class="navbar-toggle" type="button" data-ng-click="toggleCollapsibleMenu()">
			Toggle navigation

		</button>
		세월호 - 손바닥으로 하늘을 가릴쏘냐

				대통령께

				기사모음

				Signup

				Signin

                    {{authentication.user.displayName}}

						Signout


text:
module Fog
  module Compute
    class Fogdocker
      class Real
        def container_commit(options)
          raise ArgumentError, "instance id is a required parameter" unless options.has_key? :id
          container = Docker::Container.get(options[:id])
          downcase_hash_keys container.commit(camelize_hash_keys(options)).json
        end
      end

      class Mock
        def container_commit(options)
          {'id'=>'a6b02c7ca29a22619f7d0e59062323247739bc0cd375d619f305f0b519af4ef3',
           'repotags' => ['repo/other'],
           'created' => 1389877693,
           'size' => 3265536}
        end

      end
    end
  end
end


text:
package org.apache.hadoop.hbase.regionserver;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * A {@link FlushPolicy} that only flushes store larger a given threshold. If no store is large
 * enough, then all stores will be flushed.
 */
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
public class FlushAllLargeStoresPolicy extends FlushLargeStoresPolicy {

  private static final Log LOG = LogFactory.getLog(FlushAllLargeStoresPolicy.class);

  @Override
  protected void configureForRegion(HRegion region) {
    super.configureForRegion(region);
    int familyNumber = region.getTableDescriptor().getColumnFamilyCount();
    if (familyNumber <= 1) {
      // No need to parse and set flush size lower bound if only one family
      // Family number might also be zero in some of our unit test case
      return;
    }
    this.flushSizeLowerBound = getFlushSizeLowerBound(region);
  }

  @Override
  public Collection<HStore> selectStoresToFlush() {
    // no need to select stores if only one family
    if (region.getTableDescriptor().getColumnFamilyCount() == 1) {
      return region.stores.values();
    }
    // start selection
    Collection<HStore> stores = region.stores.values();
    Set<HStore> specificStoresToFlush = new HashSet<>();
    for (HStore store : stores) {
      if (shouldFlush(store)) {
        specificStoresToFlush.add(store);
      }
    }
    if (!specificStoresToFlush.isEmpty()) {
      return specificStoresToFlush;
    }

    // Didn't find any CFs which were above the threshold for selection.
    if (LOG.isDebugEnabled()) {
      LOG.debug("Since none of the CFs were above the size, flushing all.");
    }
    return stores;
  }

  @Override
  protected boolean shouldFlush(HStore store) {
    return super.shouldFlush(store) || region.shouldFlushStore(store);
  }

}


text:
package egovframework.com.sym.ccm.cca.service;

import java.io.Serializable;

import kr.pe.courage.common.annotation.KeepCondition;
import kr.pe.courage.common.core.CommonDefaultVO;

/**
 *

 * egovframework.com.sym.ccm.cca.service
 * CmmnCodeVo.java
 * 공통코드 VO
 *

 *
 * @Author : Seok Chang Ho
 * @Date : 2013. 11. 1.
 * @Version : 1.0
 * @see
 *
 *

 * << 개정이력 >>
 * ================================================================
 * 		수정일		|		수정자			|			수정내용
 * 2013-11-01		석창호					최초등록
 * ================================================================
 *

 */
public class CmmnCodeVO extends CommonDefaultVO implements Serializable {

	private static final long serialVersionUID = -7338736811532692450L;

	/*
	 * 코드ID
	 */
	private String codeId = "";

	/*
	 * 코드ID명
	 */
	private String codeIdNm = "";

	/*
	 * 상세코드 갯수
	 */
	private int detailCodeCount;

	/*
	 * 코드ID설명
	 */
	private String codeIdDc = "";

	/*
	 * 사용여부
	 */
	private String useAt = "";

	/*
	 * 엑셀일괄등록 파일
	 */
	private String excelUploadFile;

	/*
	 * 최초등록자ID
	 */
	private String frstRegisterId = "";

	/*
	 * 최초등록자명
	 */
	private String frstRegisterNm = "";

	/*
	 * 최초등록일시
	 */
	private String frstRegistPnttm = "";

	/*
	 * 최종수정자ID
	 */
	private String lastUpdusrId = "";

	/*
	 * 최종수정자명
	 */
	private String lastUpdusrNm = "";

	/*
	 * 최종수정일시
	 */
	private String lastUpdtPnttm = "";

	private boolean validateError;
	private StringBuilder validateErrorStr;

	@KeepCondition
	private String condCodeId;
	@KeepCondition
	private String condCodeIdNm;
	@KeepCondition
	private String condUseAt;
	@KeepCondition
	private String condFrstRegisterId;

	public String getCodeId() {
		return codeId;
	}

	public void setCodeId(String codeId) {
		this.codeId = codeId;
	}

	public String getCodeIdNm() {
		return codeIdNm;
	}

	public void setCodeIdNm(String codeIdNm) {
		this.codeIdNm = codeIdNm;
	}

	public int getDetailCodeCount() {
		return detailCodeCount;
	}

	public void setDetailCodeCount(int detailCodeCount) {
		this.detailCodeCount = detailCodeCount;
	}

	public String getCodeIdDc() {
		return codeIdDc;
	}

	public void setCodeIdDc(String codeIdDc) {
		this.codeIdDc = codeIdDc;
	}

	public String getUseAt() {
		return useAt;
	}

	public void setUseAt(String useAt) {
		this.useAt = useAt;
	}

	public String getExcelUploadFile() {
		return excelUploadFile;
	}

	public void setExcelUploadFile(String excelUploadFile) {
		this.excelUploadFile = excelUploadFile;
	}

	public String getFrstRegisterId() {
		return frstRegisterId;
	}

	public void setFrstRegisterId(String frstRegisterId) {
		this.frstRegisterId = frstRegisterId;
	}

	public String getFrstRegisterNm() {
		return frstRegisterNm;
	}

	public void setFrstRegisterNm(String frstRegisterNm) {
		this.frstRegisterNm = frstRegisterNm;
	}

	public String getFrstRegistPnttm() {
		return frstRegistPnttm;
	}

	public void setFrstRegistPnttm(String frstRegistPnttm) {
		this.frstRegistPnttm = frstRegistPnttm;
	}

	public String getLastUpdusrId() {
		return lastUpdusrId;
	}

	public void setLastUpdusrId(String lastUpdusrId) {
		this.lastUpdusrId = lastUpdusrId;
	}

	public String getLastUpdusrNm() {
		return lastUpdusrNm;
	}

	public void setLastUpdusrNm(String lastUpdusrNm) {
		this.lastUpdusrNm = lastUpdusrNm;
	}

	public String getLastUpdtPnttm() {
		return lastUpdtPnttm;
	}

	public void setLastUpdtPnttm(String lastUpdtPnttm) {
		this.lastUpdtPnttm = lastUpdtPnttm;
	}

	public boolean isValidateError() {
		return validateError;
	}

	public void setValidateError(boolean validateError) {
		this.validateError = validateError;
	}

	public StringBuilder getValidateErrorStr() {
		return validateErrorStr;
	}

	public void setValidateErrorStr(StringBuilder validateErrorStr) {
		this.validateErrorStr = validateErrorStr;
	}

	public String getCondCodeId() {
		return condCodeId;
	}

	public void setCondCodeId(String condCodeId) {
		this.condCodeId = condCodeId;
	}

	public String getCondCodeIdNm() {
		return condCodeIdNm;
	}

	public void setCondCodeIdNm(String condCodeIdNm) {
		this.condCodeIdNm = condCodeIdNm;
	}

	public String getCondUseAt() {
		return condUseAt;
	}

	public void setCondUseAt(String condUseAt) {
		this.condUseAt = condUseAt;
	}

	public String getCondFrstRegisterId() {
		return condFrstRegisterId;
	}

	public void setCondFrstRegisterId(String condFrstRegisterId) {
		this.condFrstRegisterId = condFrstRegisterId;
	}
}


text:
<?php namespace Anomaly\Streams\Platform\Entry\Parser;

use Anomaly\Streams\Platform\Stream\Contract\StreamInterface;

/**
 * Class EntryTranslationForeignKeyParser
 *
 * @link    http://pyrocms.com/
 * @author  PyroCMS, Inc. <support@pyrocms.com>
 * @author  Ryan Thompson <ryan@pyrocms.com>
 */
class EntryTranslationForeignKeyParser
{

    /**
     * Return the translation foreign key attribute.
     *
     * @param  StreamInterface $stream
     * @return null|string
     */
    public function parse(StreamInterface $stream)
    {
        if (!$stream->isTranslatable()) {
            return null;
        }

        return 'protected $translationForeignKey = \'entry_id\';';
    }
}


text:
package org.apache.pinot.controller.recommender.rules.io.configs;

import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.Nulls;
import java.util.HashSet;
import java.util.Set;

/**
 * The output format of index, bloomFilter, and dictionary recommendation,
 * can also be used as input to overwrite index configurations
 */
public class IndexConfig {
    Set<String> _invertedIndexColumns = new HashSet<>();
    Set<String> _rangeIndexColumns = new HashSet<>();
    String _sortedColumn = "";
    Set<String> _bloomFilterColumns = new HashSet<>();

    Set<String> _noDictionaryColumns = new HashSet<>();
    Set<String> _onHeapDictionaryColumns = new HashSet<>();
    Set<String> _variedLengthDictionaryColumns = new HashSet<>();

    boolean _isSortedColumnOverwritten = false;

    @JsonSetter(nulls = Nulls.SKIP)
    public void setVariedLengthDictionaryColumns(Set<String> variedLengthDictionaryColumns) {
        _variedLengthDictionaryColumns = variedLengthDictionaryColumns;
    }

    @JsonSetter(nulls = Nulls.SKIP)
    public void setBloomFilterColumns(Set<String> bloomFilterColumns) {
        _bloomFilterColumns = bloomFilterColumns;
    }

    @JsonSetter(nulls = Nulls.SKIP)
    public void setNoDictionaryColumns(Set<String> noDictionaryColumns) {
        _noDictionaryColumns = noDictionaryColumns;
    }

    @JsonSetter(nulls = Nulls.SKIP)
    public void setOnHeapDictionaryColumns(Set<String> onHeapDictionaryColumns) {
        _onHeapDictionaryColumns = onHeapDictionaryColumns;
    }

    @JsonSetter(nulls = Nulls.SKIP)
    public void setInvertedIndexColumns(Set<String> invertedIndexColumns) {
        this._invertedIndexColumns = invertedIndexColumns;
    }

    @JsonSetter(nulls = Nulls.SKIP)
    public void setSortedColumn(String sortedColumn) {
        this._sortedColumn = sortedColumn;
        this._isSortedColumnOverwritten = true;
    }

    @JsonSetter(nulls = Nulls.SKIP)
    public void setRangeIndexColumns(Set<String> rangeIndexColumns) {
        this._rangeIndexColumns = rangeIndexColumns;
    }

    public boolean isSortedColumnOverwritten() {
        return _isSortedColumnOverwritten;
    }

    public void setSortedColumnOverwritten(boolean sortedColumnOverwritten) {
        _isSortedColumnOverwritten = sortedColumnOverwritten;
    }

    public Set<String> getVariedLengthDictionaryColumns() {
        return _variedLengthDictionaryColumns;
    }

    public Set<String> getBloomFilterColumns() {
        return _bloomFilterColumns;
    }

    public Set<String> getNoDictionaryColumns() {
        return _noDictionaryColumns;
    }

    public Set<String> getOnHeapDictionaryColumns() {
        return _onHeapDictionaryColumns;
    }

    public Set<String> getInvertedIndexColumns() {
        return _invertedIndexColumns;
    }

    public String getSortedColumn() {
        return _sortedColumn;
    }

    public Set<String> getRangeIndexColumns() {
        return _rangeIndexColumns;
    }

    public boolean hasInvertedIndex(String colname){
        return _invertedIndexColumns.contains(colname);
    }

    public boolean hasSortedIndex(String colName){
        return _sortedColumn.equals(colName);
    };

    public boolean hasRangeIndex(String colName){
        return _rangeIndexColumns.contains(colName);
    };

    public boolean hasAnyIndex(){
        return !_sortedColumn.isEmpty() || !_rangeIndexColumns.isEmpty() || !_invertedIndexColumns.isEmpty();
    }
}


text:
import { ChangesStream, Datastore, Document, FieldDocument, FindResult, ObserverUtil, Query, Resource } from 'idai-field-core';
import { Observable, Observer } from 'rxjs';
import * as tsfun from 'tsfun';
import { AngularUtility } from '../../../angular/angular-utility';
import { Loading } from '../../../components/widgets/loading';
import { ModelUtil } from '../../model/model-util';
import { ResourcesStateManager } from './resources-state-manager';
import { ResourcesState } from './state/resources-state';
import hasId = ModelUtil.hasId;
import hasEqualId = ModelUtil.hasEqualId;

const LIES_WITHIN_EXIST = 'liesWithin:exist';
const LIES_WITHIN_CONTAIN = 'liesWithin:contain';
const RECORDED_IN_CONTAIN = 'isRecordedIn:contain';
const UNKNOWN = 'UNKNOWN';

export const DEFAULT_DOCUMENTS_LIMIT: number = 20000;
export const TYPES_MANAGEMENT_DOCUMENTS_LIMIT: number = 5000;

/**
 * @author Thomas Kleinke
 * @author Sebastian Cuy
 * @author Daniel de Oliveira
 */
export class DocumentsManager {

    private documents: Array<FieldDocument>;
    private newDocumentsFromRemote: Array<Resource.Id> = [];

    private totalDocumentCount: number;

    private deselectionObservers: Array<Observer<Document>> = [];
    private populateDocumentsObservers: Array<Observer<Array<Document>>> = [];
    private documentChangedFromRemoteObservers: Array<Observer<undefined>> = [];
    private childrenCountMap: { [resourceId: string]: number } = {};

    private currentQueryId: string;
    private populateInProgress: boolean = false;

    constructor(
        private datastore: Datastore,
        changesStream: ChangesStream,
        private resourcesStateManager: ResourcesStateManager,
        private loading: Loading,
        private getIndexMatchTermCount: (indexName: string, matchTerm: string) => number
    ) {
        changesStream.remoteChangesNotifications()
            .subscribe(document => this.handleRemoteChange(document));
    }

    public getDocuments = () => this.documents;

    public getTotalDocumentCount = () => this.totalDocumentCount;

    public getChildrenCount = (document: FieldDocument) => this.childrenCountMap[document.resource.id];

    public deselectionNotifications = (): Observable<Document> =>
        ObserverUtil.register(this.deselectionObservers);

    public populateDocumentsNotifactions = (): Observable<Array<Document>> =>
        ObserverUtil.register(this.populateDocumentsObservers);

    public documentChangedFromRemoteNotifications = (): Observable<undefined> =>
        ObserverUtil.register(this.documentChangedFromRemoteObservers);

    public isPopulateInProgress = () => this.populateInProgress;

    public isNewDocumentFromRemote(document: Document): boolean {

        if (!document.resource.id) return false;
        return this.newDocumentsFromRemote.includes(document.resource.id);
    }

    public async setQueryString(q: string, populate: boolean = true) {

        this.resourcesStateManager.setQueryString(q);
        if (populate) await this.populateAndDeselectIfNecessary();
    }

    public async setCategoryFilters(categories: string[], populate: boolean = true) {

        this.resourcesStateManager.setCategoryFilters(categories);
        if (populate) await this.populateAndDeselectIfNecessary();
    }

    public async setCustomConstraints(constraints: { [name: string]: string}) {

        this.resourcesStateManager.setCustomConstraints(constraints);
        await this.populateAndDeselectIfNecessary();
    }

    public async setExtendedSearchMode(extendedSearchMode: boolean) {

        this.resourcesStateManager.setExtendedSearchMode(extendedSearchMode);
        await this.populateAndDeselectIfNecessary();
    }

    public async moveInto(document: FieldDocument|string|undefined, resetFiltersAndSelection: boolean = false,
                          rebuildNavigationPath: boolean = false) {

        try {
            if (tsfun.isString(document)) {
                document = FieldDocument.fromDocument(await this.datastore.get(document));
            } else if (document) {
                await this.datastore.get(document.resource.id);
            }
        } catch (errWithParams) {
            throw errWithParams; // Throw error if the resource has been deleted from remote
        }

        if (rebuildNavigationPath && document) {
            await this.resourcesStateManager.updateNavigationPathForDocument(document, true);
        }

        await this.resourcesStateManager.moveInto(document);

        if (resetFiltersAndSelection) {
            await this.setCategoryFilters([], false);
            await this.setQueryString('', false);
            await this.deselect();
            await this.populateDocumentList();
        } else {
            await this.populateAndDeselectIfNecessary();
        }
    }

    public deselect() {

        if (ResourcesState.getSelectedDocument(this.resourcesStateManager.get())) {
            this.selectAndNotify(undefined);
            this.removeNewDocument();
            this.resourcesStateManager.setActiveDocumentViewTab(undefined);
        }
    }

    public addNewDocument(document: FieldDocument) {

        this.documents = [document].concat(this.documents);
        this.selectAndNotify(document);
    }

    public removeNewDocument() {

        if (this.documents.find(document => !hasId(document))) {
            this.documents = this.documents.filter(hasId);
        }
    }

    public async setSelected(resourceId: string, adjustListIfNecessary: boolean = true): Promise<any> {

        this.removeNewDocument();

        const documentToSelect = FieldDocument.fromDocument(await this.datastore.get(resourceId));
        this.newDocumentsFromRemote
            = tsfun.subtract([documentToSelect.resource.id])(this.newDocumentsFromRemote);

        if (adjustListIfNecessary && !(await this.isDocumentInList(documentToSelect))) {
            await this.makeSureSelectedDocumentAppearsInList(documentToSelect);
            await this.populateDocumentList();
        }

        this.selectAndNotify(documentToSelect);
    }

    public async navigateDocumentList(direction: 'previous'|'next'): Promise<any> {

        if (!this.documents || this.documents.length === 0) return;

        const selectedDocument: FieldDocument|undefined
            = ResourcesState.getSelectedDocument(this.resourcesStateManager.get());

        if (!selectedDocument) {
            await this.setSelected(this.documents[0].resource.id);
        } else {
            let index: number = this.documents.findIndex(document => {
                return document.resource.id === selectedDocument.resource.id;
            }) + (direction === 'next' ? 1 : -1);
            if (index < 0) index = this.documents.length - 1;
            if (index === this.documents.length) index = 0;
            await this.setSelected(this.documents[index].resource.id);
        }
    }

    public async populateDocumentList(reset: boolean = true) {

        this.populateInProgress = true;
        if (this.loading) this.loading.start();

        if (reset) {
            this.newDocumentsFromRemote = [];
            this.documents = [];
        }

        await AngularUtility.refresh();

        this.currentQueryId = new Date().toISOString();
        const queryId = this.currentQueryId;
        const result = await this.createUpdatedDocumentList();

        await this.updateChildrenCountMap(result.documents.map(FieldDocument.fromDocument));

        if (this.loading) this.loading.stop();
        if (queryId !== this.currentQueryId) {
            this.populateInProgress = false;
            return;
        }

        this.documents = result.documents.map(FieldDocument.fromDocument);
        this.totalDocumentCount = result.totalCount;

        this.populateInProgress = false;
        ObserverUtil.notify(this.populateDocumentsObservers, this.documents);
    }

    public async createUpdatedDocumentList(): Promise<FindResult> {

        const isRecordedInTarget = this.makeIsRecordedInTarget();
        if (!isRecordedInTarget && !this.resourcesStateManager.isInSpecialView()) {
            return { documents: [], ids: [], totalCount: 0 };
        }

        const operationId: string|undefined = this.resourcesStateManager.isInSpecialView()
            ? undefined
            : this.resourcesStateManager.get().view;

        const query = DocumentsManager.buildQuery(
            operationId,
            this.resourcesStateManager,
            this.getAllowedTypeNames()
        );

        return (await this.fetchDocuments(query));
    }

    private getAllowedTypeNames(): string[] {

        return this.resourcesStateManager.isInOverview()
                && !this.resourcesStateManager.isInExtendedSearchMode()
            ? this.resourcesStateManager.getOverviewCategoryNames()
            : this.resourcesStateManager.isInTypesManagement()
                ? this.resourcesStateManager.getAbstractCategoryNames()
                : this.resourcesStateManager.getConcreteCategoryNames();
    }

    private async updateChildrenCountMap(documents: Array<FieldDocument>) {

        for (let document of documents) {
           this.childrenCountMap[document.resource.id] = this.getIndexMatchTermCount(
               LIES_WITHIN_CONTAIN, document.resource.id
           );
        }
    }

    private async isDocumentInList(document: FieldDocument): Promise<boolean> {

        return (await this.createUpdatedDocumentList()).documents.find(hasEqualId(document)) !== undefined;
    }

    private selectAndNotify(document: FieldDocument|undefined) {

        if (ResourcesState.getSelectedDocument(this.resourcesStateManager.get())) {
            ObserverUtil.notify(this.deselectionObservers,
                ResourcesState.getSelectedDocument(this.resourcesStateManager.get()) as Document|undefined);
        }

        this.resourcesStateManager.setSelectedDocument(document);
    }

    private async populateAndDeselectIfNecessary() {

        await this.populateDocumentList();

        if (!this.documents.find(hasEqualId(ResourcesState.getSelectedDocument(this.resourcesStateManager.get())))) {
            this.deselect();
        }
    }

    private async handleRemoteChange(changedDocument: Document) {

        if (!this.documents) return;

        if (this.documents.find(hasEqualId(changedDocument))) {
            return ObserverUtil.notify(this.documentChangedFromRemoteObservers, undefined);
        }

        this.newDocumentsFromRemote = tsfun.set(this.newDocumentsFromRemote.concat([changedDocument.resource.id]));
        await this.populateDocumentList(false);
    }

    private makeIsRecordedInTarget(): string|undefined {

        return this.resourcesStateManager.isInOverview()
            ? undefined
            : this.resourcesStateManager.get().view;
    }

    private async makeSureSelectedDocumentAppearsInList(documentToSelect: FieldDocument) {

        await this.resourcesStateManager.updateNavigationPathForDocument(documentToSelect);
        await this.adjustQuerySettingsIfNecessary(documentToSelect);
    }

    private async adjustQuerySettingsIfNecessary(documentToSelect: Document) {

        if (!(await this.updatedDocumentListContainsSelectedDocument(documentToSelect))) {
            this.resourcesStateManager.setQueryString('');
            this.resourcesStateManager.setCategoryFilters([]);
            this.resourcesStateManager.setCustomConstraints({});
        }
    }

    private async updatedDocumentListContainsSelectedDocument(documentToSelect: Document): Promise<boolean> {

        return (await this.createUpdatedDocumentList()).documents.find(hasEqualId(documentToSelect)) !== undefined;
    }

    private async fetchDocuments(query: Query): Promise<FindResult> {

        try {
            const ignoreCategories = !query.categories
                && !(this.resourcesStateManager.isInOverview() && ResourcesState.isInExtendedSearchMode(this.resourcesStateManager.get()));
            return await this.datastore.find(query, ignoreCategories);

        } catch (errWithParams) {
            DocumentsManager.handleFindErr(errWithParams, query);
            return { documents: [], ids: [], totalCount: 0 };
        }
    }

    private static buildQuery(operationId: string|undefined,
                              resourcesStateManager: ResourcesStateManager,
                              allowedCategoryNames: string[]): Query {

        const extendedSearchMode = resourcesStateManager.isInExtendedSearchMode();
        const state = resourcesStateManager.get();
        const categoryFilters = ResourcesState.getCategoryFilters(state);
        const customConstraints = ResourcesState.getCustomConstraints(state);

        return {
            q: ResourcesState.getQueryString(state),
            constraints: DocumentsManager.buildConstraints(
                customConstraints,
                operationId,
                ResourcesState.getNavigationPath(state).selectedSegmentId,
                !extendedSearchMode
            ),
            categories: (categoryFilters.length > 0)
                ? categoryFilters
                : allowedCategoryNames,
            limit: extendedSearchMode && ResourcesState.isLimitSearchResults(state)
                ? this.getDocumentsLimit(resourcesStateManager)
                : undefined
        };
    }

    private static buildConstraints(customConstraints: { [name: string]: string },
                                    operationId: string|undefined,
                                    liesWithinId: string|undefined,
                                    addLiesWithinConstraints: boolean): { [name: string]: string|string[]} {

        const constraints = tsfun.clone(customConstraints);

        if (addLiesWithinConstraints) {
            if (liesWithinId) {
                constraints[LIES_WITHIN_CONTAIN] = liesWithinId;
            } else {
                constraints[LIES_WITHIN_EXIST] = UNKNOWN;
            }
        }

        if (operationId) constraints[RECORDED_IN_CONTAIN] = operationId;

        return constraints;
    }

    private static handleFindErr(errWithParams: Array<string>, query: Query) {

        console.error('Error with find. Query:', query);
        if (errWithParams.length === 2) console.error('Error with find. Cause:', errWithParams[1]);
    }

    private static getDocumentsLimit(resourcesStateManager: ResourcesStateManager): number {

        return resourcesStateManager.isInTypesManagement()
            ? TYPES_MANAGEMENT_DOCUMENTS_LIMIT
            : DEFAULT_DOCUMENTS_LIMIT;
    }
}


text:
import React from 'react'
import './HeroLogo.scss'
import Logo from './logo.svg'

export default () => (
  <div className='hero-logo'>
    <Logo className='logo-background' />
  </div>
)


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.

package com.microsoft.alm.plugin.external.exceptions;

/**
 * Exception for a case when a workspace could not be determined from any argument paths or the current working directory.
 */
public class WorkspaceCouldNotBeDeterminedException extends ToolException {
    public WorkspaceCouldNotBeDeterminedException() {
        super(ToolException.KEY_TF_WORKSPACE_COULD_NOT_BE_DETERMINED);
    }
}