text:
/*!
 * \file dnnl_quantized_batch_norm.cc
 * \author Yixin Bao
 */

#if MXNET_USE_ONEDNN == 1
#include "operator/nn/dnnl/dnnl_batch_norm-inl.h"
#include "operator/quantization/quantization_utils.h"

namespace mxnet {
namespace op {

template <bool fuse_relu>
static void DNNLQuantizedBatchNormForward(const nnvm::NodeAttrs& attrs,
                                          const OpContext& ctx,
                                          const std::vector<NDArray>& in_data,
                                          const std::vector<OpReqType>& req,
                                          const std::vector<NDArray>& outputs) {
  CHECK_EQ(in_data.size(), 7U);
  CHECK_EQ(outputs.size(), 3U);

  TmpMemMgr::Get()->Init(ctx.requested[batchnorm::kTempSpace]);
  const BatchNormParam& param = nnvm::get<BatchNormParam>(attrs.parsed);
  const NDArray& data         = in_data[quantized_batchnorm::kData];
  auto data_mem               = data.GetDNNLData();

  // reorder if data type = uint8
  if (in_data[quantized_batchnorm::kData].dtype() == mshadow::kUint8) {
    auto u8_md            = data_mem->get_desc();
    auto s8_md            = u8_md;
    s8_md.data.data_type  = static_cast<dnnl_data_type_t>(dnnl::memory::data_type::s8);
    auto data_reorder_mem = TmpMemMgr::Get()->Alloc(s8_md);

    std::vector<float> reorder_scale;
    reorder_scale = {static_cast<float>(kInt8Range) / kUint8Range};
    dnnl::primitive_attr reorder_attr;
    reorder_attr.set_output_scales(0, reorder_scale);
    dnnl::engine cpu_engine = CpuEngine::Get()->get_engine();
    const auto reorder_pd =
        dnnl::reorder::primitive_desc(cpu_engine, u8_md, cpu_engine, s8_md, reorder_attr);
    dnnl_args_map_t reorder_args;
    reorder_args[DNNL_ARG_SRC] = *data_mem;
    reorder_args[DNNL_ARG_DST] = *data_reorder_mem;
    DNNLStream::Get()->RegisterPrimArgs(dnnl::reorder(reorder_pd), reorder_args);
    data_mem = data_reorder_mem;
  }
  const size_t channelAxis = static_cast<size_t>(
      param.axis < 0 ? static_cast<int>(data.shape().ndim()) + param.axis : param.axis);
  const int channel_count  = data.shape()[channelAxis];
  const float min_data     = in_data[quantized_batchnorm::kDataMin].data().dptr<float>()[0];
  const float max_data     = in_data[quantized_batchnorm::kDataMax].data().dptr<float>()[0];
  const float max_abs_data = std::max(std::abs(min_data), std::abs(max_data));

  float* min_output_ptr = outputs[quantized_batchnorm::kOutMin].data().dptr<float>();
  float* max_output_ptr = outputs[quantized_batchnorm::kOutMax].data().dptr<float>();
  if (param.min_calib_range.has_value() && param.max_calib_range.has_value()) {
    *max_output_ptr = param.max_calib_range.value();
    *min_output_ptr = param.min_calib_range.value();
  } else {
    LOG(FATAL) << "min_calib_range or max_calib_range is not available. Quantized BN currently "
                  "don't support calib_mode=None";
  }
  const float max_abs_output = std::max(std::abs(*min_output_ptr), std::abs(*max_output_ptr));

  dnnl::normalization_flags flags =
      dnnl::normalization_flags::use_global_stats | dnnl::normalization_flags::use_scale_shift;
  auto& fwd                      = DNNLBNForward::GetCached(param, ctx, data_mem, fuse_relu, flags);
  const dnnl::memory& weight_mem = fwd.GetWeight();
  CHECK_EQ(weight_mem.get_desc().get_size(), channel_count * sizeof(float) * 2);
  float* weight_buf = reinterpret_cast<float*>(weight_mem.get_data_handle());

  float* gamma_ptr = in_data[quantized_batchnorm::kGamma].data().dptr<float>();
  float* beta_ptr  = in_data[quantized_batchnorm::kBeta].data().dptr<float>();

  const NDArray& moving_mean = in_data[quantized_batchnorm::kInMovingMean];
  const NDArray& moving_var  = in_data[quantized_batchnorm::kInMovingVar];
  float* moving_mean_ptr     = moving_mean.data().dptr<float>();
  float* moving_var_ptr      = moving_var.data().dptr<float>();

  // rescale gamma and beta, to make mean=0 and var=1
  auto rescaled_mean_mem   = TmpMemMgr::Get()->Alloc(moving_mean.GetDNNLData()->get_desc());
  auto rescaled_var_mem    = TmpMemMgr::Get()->Alloc(moving_var.GetDNNLData()->get_desc());
  float* rescaled_mean_ptr = reinterpret_cast<float*>(rescaled_mean_mem->get_data_handle());
  float* rescaled_var_ptr  = reinterpret_cast<float*>(rescaled_var_mem->get_data_handle());

#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
  for (int channel = 0; channel < channel_count; ++channel) {
    float invstd        = 1.0 / std::sqrt(moving_var_ptr[channel] + param.eps);
    weight_buf[channel] = gamma_ptr[channel] * invstd * max_abs_data / max_abs_output;
    weight_buf[channel_count + channel] =
        (beta_ptr[channel] - moving_mean_ptr[channel] * gamma_ptr[channel] * invstd) * kInt8Range /
        max_abs_output;
    rescaled_mean_ptr[channel] = 0.0f;
    rescaled_var_ptr[channel]  = 1.0f;
  }

  const NDArray& out = outputs[batchnorm::kOut];
  auto fwd_dst_desc  = fwd.GetPd().dst_desc();
  auto out_mem       = const_cast<NDArray&>(out).CreateDNNLData(&fwd_dst_desc);
  dnnl_args_map_t net_args;
  net_args[DNNL_ARG_SRC]         = *data_mem;
  net_args[DNNL_ARG_SCALE_SHIFT] = weight_mem;
  net_args[DNNL_ARG_DST]         = *out_mem;
  net_args[DNNL_ARG_MEAN]        = *rescaled_mean_mem;
  net_args[DNNL_ARG_VARIANCE]    = *rescaled_var_mem;

  DNNLStream::Get()->RegisterPrimArgs(fwd.GetFwd(), net_args);
  DNNLStream::Get()->Submit();
}

inline static bool QuantizedBatchNormStorageType(const nnvm::NodeAttrs& attrs,
                                                 const int dev_mask,
                                                 DispatchMode* dispatch_mode,
                                                 std::vector<int>* in_attrs,
                                                 std::vector<int>* out_attrs) {
  return DNNLStorageType(attrs, dev_mask, true, dispatch_mode, in_attrs, out_attrs);
}

inline static bool QuantizedBatchNormWithReLUStorageType(const nnvm::NodeAttrs& attrs,
                                                         const int dev_mask,
                                                         DispatchMode* dispatch_mode,
                                                         std::vector<int>* in_attrs,
                                                         std::vector<int>* out_attrs) {
  bool dispatched = false;
  if (!dispatched) {
    dispatched = DNNLStorageType(attrs, dev_mask, true, dispatch_mode, in_attrs, out_attrs);
  }
  return dispatched;
}

NNVM_REGISTER_OP(_contrib_quantized_batch_norm)
    .set_attr<FInferStorageType>("FInferStorageType", QuantizedBatchNormStorageType)
    .set_attr<FComputeEx>("FComputeEx<cpu>", DNNLQuantizedBatchNormForward</*fuse_relu*/ false>)
    .set_attr<FResourceRequest>("FResourceRequest",
                                [](const NodeAttrs& n) {
                                  return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
                                })
    .set_attr<bool>("TIsDNNL", true);

NNVM_REGISTER_OP(_contrib_quantized_batch_norm_relu)
    .set_attr<FInferStorageType>("FInferStorageType", QuantizedBatchNormWithReLUStorageType)
    .set_attr<FComputeEx>("FComputeEx<cpu>", DNNLQuantizedBatchNormForward</*fuse_relu*/ true>)
    .set_attr<FResourceRequest>("FResourceRequest",
                                [](const NodeAttrs& n) {
                                  return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
                                })
    .set_attr<bool>("TIsDNNL", true);

}  // namespace op
}  // namespace mxnet

#endif  // MXNET_USE_ONEDNN == 1


text:
using System;
using System.Collections.Generic;
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;

namespace ANTLR4.ParserHelpers
{
    public static class ListenerExtensions
    {
        public static void ListenTo(this IParseTreeListener listener, ICharStream input, ITreeBuilder treeBuilder,
            IEnumerable<IAntlrErrorListener<int>> lexerErrorListeners = null, IEnumerable<IAntlrErrorListener<IToken>> errorListeners = null)
        {
            if (listener == null)
                throw new ArgumentNullException("listener");

            if (input == null)
                throw new ArgumentNullException("input");

            if (treeBuilder == null)
                throw new ArgumentNullException("treeBuilder");

            var walker = new Walker(treeBuilder);
            walker.Walkthrough(input, listener, lexerErrorListeners ?? new IAntlrErrorListener<int>[0], errorListeners ?? new IAntlrErrorListener<IToken>[0]);
        }

        public static void ListenTo(this IParseTreeListener listener, ICharStream input, ITreeBuilderStrategy treeBuilderStrategy,
            IEnumerable<IAntlrErrorListener<int>> lexerErrorListeners = null, IEnumerable<IAntlrErrorListener<IToken>> errorListeners = null)
        {
            if (listener == null)
                throw new ArgumentNullException("listener");

            if (input == null)
                throw new ArgumentNullException("input");

            if (treeBuilderStrategy == null)
                throw new ArgumentNullException("treeBuilderStrategy");

            var walker = new Walker(treeBuilderStrategy);
            walker.Walkthrough(input, listener, lexerErrorListeners ?? new IAntlrErrorListener<int>[0], errorListeners ?? new IAntlrErrorListener<IToken>[0]);
        }

        public static Action<ICharStream> Action<TTreeBuilderStrategy>(this IParseTreeListener listener,
            IEnumerable<IAntlrErrorListener<int>> lexerErrorListeners = null, IEnumerable<IAntlrErrorListener<IToken>> errorListeners = null)
            where TTreeBuilderStrategy : ITreeBuilderStrategy, new()
        {
            if (listener == null)
                throw new ArgumentNullException("listener");

            return input => listener.ListenTo(input, new TTreeBuilderStrategy(), lexerErrorListeners ?? new IAntlrErrorListener<int>[0], errorListeners ?? new IAntlrErrorListener<IToken>[0]);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace BingAds\v10\CampaignManagement;

/**
 * Gets associations between a campaign and a shared entity such as a negative keyword list.
 *
 * @link http://msdn.microsoft.com/en-us/library/dn743773(v=msads.100).aspx GetSharedEntityAssociationsBySharedEntityIds Request Object
 *
 * @used-by BingAdsCampaignManagementService::GetSharedEntityAssociationsBySharedEntityIds
 */
final class GetSharedEntityAssociationsBySharedEntityIdsRequest
{
    public $EntityType;
    public $SharedEntityIds;
    public $SharedEntityType;
}


text:
<?php

namespace Davamigo\HttpClient\Domain;

/**
 * Generic HTTP response interface
 *
 * @package Davamigo\HttpClient\Domain
 * @author davamigo@gmail.com
 */
interface HttpResponse
{
    /** Contants: HTTP response codes */
    const HTTP_CODE_CONTINUE                        = 100;
    const HTTP_CODE_SWITCHING_PROTOCOLS             = 101;
    const HTTP_CODE_PROCESSING                      = 102;

    const HTTP_CODE_OK                              = 200;
    const HTTP_CODE_CREATED                         = 201;
    const HTTP_CODE_ACCEPTED                        = 202;
    const HTTP_CODE_NON_AUTHORITATIVE_INFORMATION   = 203;
    const HTTP_CODE_NO_CONTENT                      = 204;
    const HTTP_CODE_RESET_CONTENT                   = 205;
    const HTTP_CODE_PARTIAL_CONTENT                 = 206;
    const HTTP_CODE_MULTI_STATUS                    = 207;
    const HTTP_CODE_ALREADY_REPORTED                = 208;
    const HTTP_CODE_IM_USED                         = 226;

    const HTTP_CODE_MULTIPLE_CHOICES                = 300;
    const HTTP_CODE_MOVED_PERMANENTLY               = 301;
    const HTTP_CODE_FOUND                           = 302;
    const HTTP_CODE_SEE_OTHER                       = 303;
    const HTTP_CODE_NOT_MODIFIED                    = 304;
    const HTTP_CODE_USE_PROXY                       = 305;
    const HTTP_CODE_TEMPORARY_REDIRECT              = 307;
    const HTTP_CODE_PERMANENT_REDIRECT              = 308;

    const HTTP_CODE_BAD_REQUEST                     = 400;
    const HTTP_CODE_UNAUTHORIZED                    = 401;
    const HTTP_CODE_PAYMENT_REQUIRED                = 402;
    const HTTP_CODE_FORBIDDEN                       = 403;
    const HTTP_CODE_NOT_FOUND                       = 404;
    const HTTP_CODE_METHOD_NOT_ALLOWED              = 405;
    const HTTP_CODE_NOT_ACEPTABLE                   = 406;
    const HTTP_CODE_PROXY_AUTHETICATION_REQUIRED    = 407;
    const HTTP_CODE_REQUEST_TIMEOUT                 = 408;
    const HTTP_CODE_CONFLICT                        = 409;
    const HTTP_CODE_GONE                            = 410;
    const HTTP_CODE_LENGTH_REQUIRED                 = 411;
    const HTTP_CODE_PRECONDITION_FAILED             = 412;
    const HTTP_CODE_REQUEST_ENTITY_TOO_LARGE        = 413;
    const HTTP_CODE_REQUEST_URI_TOO_LONG            = 414;
    const HTTP_CODE_UNSUPPORTED_MEDIA_TYPE          = 415;
    const HTTP_CODE_REQUEST_RANGE_NOT_SATISFIABLE   = 416;
    const HTTP_CODE_EXPECTATION_FAILED              = 417;
    const HTTP_CODE_UNPROCESSABLE_ENTITY            = 422;
    const HTTP_CODE_LOCKED                          = 423;
    const HTTP_CODE_FAILED_DEPENDENCY               = 424;
    const HTTP_CODE_RESERVED_FOR_WEBDAV             = 425;
    const HTTP_CODE_UPGRADE_REQUIRED                = 426;
    const HTTP_CODE_PRECONDITION_REQUIRED           = 428;
    const HTTP_CODE_TOO_MANY_REQUESTS               = 429;
    const HTTP_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;

    const HTTP_CODE_INTERNAL_SERVER_ERROR           = 500;
    const HTTP_CODE_NOT_IMPLEMENTED                 = 501;
    const HTTP_CODE_BAD_GATEWAY                     = 502;
    const HTTP_CODE_SERVICE_UNAVAILABLE             = 503;
    const HTTP_CODE_GATEWAY_TIMEOUT                 = 504;
    const HTTP_CODE_HTTP_VERSION_NOT_SUPPORTED      = 505;
    const HTTP_CODE_VARIANT_ALSO_NEGOTIATES         = 506;
    const HTTP_CODE_INSUFFICIENT_STORAGE            = 507;
    const HTTP_CODE_LOOP_DETECTED                   = 508;
    const HTTP_CODE_NOT_EXTEDNDED                   = 510;
    const HTTP_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511;

    /** Contants: Header keys */
    const HEADER_ACCEPT_RANGES          = 'Accept-Ranges';
    const HEADER_AGE                    = 'Age';
    const HEADER_ALLOW                  = 'Allow';
    const HEADER_CACHE_CONTROL          = 'Cache-Control';
    const HEADER_CONNECTION             = 'Connection';
    const HEADER_CONTENT_ENCODING       = 'Content-Encoding';
    const HEADER_CONTENT_LANGUAGE       = 'Content-Language';
    const HEADER_CONTENT_LENGTH         = 'Content-Length';
    const HEADER_CONTENT_LOCATION       = 'Content-Location';
    const HEADER_CONTENT_DISPOSITION    = 'Content-Disposition';
    const HEADER_CONTENT_MD5            = 'Content-MD5';
    const HEADER_CONTENT_RANGE          = 'Content-Range';
    const HEADER_CONTENT_TYPE           = 'Content-Type';
    const HEADER_DATE                   = 'Date';
    const HEADER_E_TAG                  = 'ETag';
    const HEADER_EXPIRES                = 'Expires';
    const HEADER_LAST_MODIFIED          = 'Last-Modified';
    const HEADER_LOCATION               = 'Location';
    const HEADER_PRAGMA                 = 'Pragma';
    const HEADER_PROXY_AUTHETICATE      = 'Proxy-Authenticate';
    const HEADER_RETRY_AFTER            = 'Retry-After';
    const HEADER_SERVER                 = 'Server';
    const HEADER_SET_COOKIE             = 'Set-Cookie';
    const HEADER_TRAILER                = 'Trailer';
    const HEADER_TRANSFER_ENCODING      = 'Transfer-Encoding';
    const HEADER_VARY                   = 'Vary';
    const HEADER_VIA                    = 'Via';
    const HEADER_WARNING                = 'Warning';
    const HEADER_WWW_AUTHENTICATE       = 'WWW-Authenticate';

    /**
     * Returns the response internal data (usually the real response object).
     *
     * @return object|array
     */
    public function getResponseData();

    /**
     * Get the response body
     *
     * @param bool $asString Set to TRUE to return a string of the body rather than a full body object
     *
     * @return HttpBody|string
     */
    public function getBody($asString = false);

    /**
     * Get the entire response as a string
     *
     * @return string
     */
    public function getMessage();

    /**
     * Get a cURL transfer information
     *
     * @param string $key A single statistic to check
     * @return array|string|null Returns all stats if no key is set, a single stat if a key is set, or null if a key
     *                           is set and not found
     */
    public function getInfo($key = null);

    /**
     * Get the protocol used for the response (e.g. HTTP)
     *
     * @return string
     * @throws HttpException
     */
    public function getProtocol();

    /**
     * Get the HTTP protocol version
     *
     * @return string
     * @throws HttpException
     */
    public function getProtocolVersion();

    /**
     * Get the response status code
     *
     * @return integer
     * @throws HttpException
     */
    public function getStatusCode();

    /**
     * Get the response reason phrase: a human readable version of the numeric status code
     *
     * @return string
     * @throws HttpException
     */
    public function getReasonPhrase();

    /**
     * Get the the raw message headers as a string
     *
     * @return string
     */
    public function getRawHeaders();

    /**
     * Get all the headers as an array
     *
     * @return array
     */
    public function getHeaderLines();

    /**
     * Get a single header value
     *
     * @param string $header The name of the header
     * @return string|null Returns the value if the header found, or null if the header not found
     */
    public function getHeader($header);

    /**
     * Checks if HTTP Status code is Information (1xx)
     *
     * @return bool
     */
    public function isInformational();

    /**
     * Checks if HTTP Status code is Successful (2xx | 304)
     *
     * @return bool
     */
    public function isSuccessful();

    /**
     * Checks if HTTP Status code is a Redirect (3xx)
     *
     * @return bool
     */
    public function isRedirect();

    /**
     * Checks if HTTP Status code is a Client Error (4xx)
     *
     * @return bool
     */
    public function isClientError();

    /**
     * Checks if HTTP Status code is Server Error (5xx)
     *
     * @return bool
     */
    public function isServerError();

    /**
     * Checks if HTTP Status code is Server OR Client Error (4xx or 5xx)
     *
     * @return boolean
     */
    public function isError();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="@dimen/ui_widget_inset"
       android:insetTop="@dimen/ui_widget_inset"
       android:insetRight="@dimen/ui_widget_inset"
       android:insetBottom="@dimen/ui_widget_inset">

    <selector>
        <item android:drawable="@drawable/ui_spinner_input_activated" android:state_pressed="true"/>
        <item android:drawable="@drawable/ui_spinner_input_activated" android:state_focused="true"/>
		<item android:drawable="@drawable/ui_spinner_input_normal"/>
    </selector>
</inset>


text:
import {Language} from "../def/language";
import {ParsingTable} from "../def/parsingtable";
import {Lexer} from "../lexer/lexer";
import {Parser} from "./parser";

/**
 * Parserを生成するためのファクトリクラス
 */
export class ParserFactory {
	/**
	 * 言語
	 * @param {Language} language 解析する言語情報
	 * @param {ParsingTable} parsing_table 構文解析表
	 * @returns {Parser} 生成されたパーサ
	 */
	public static create(language: Language, parsing_table: ParsingTable): Parser {
		const lexer = new Lexer(language);
		return new Parser(lexer, language.grammar, parsing_table);
	}
}


text:
package com.hp.autonomy.hod.client.api.analysis.extractstructure;

import com.hp.autonomy.hod.client.api.authentication.TokenType;
import com.hp.autonomy.hod.client.error.HodErrorException;
import com.hp.autonomy.hod.client.token.TokenProxy;

import java.io.File;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Service for calling the ExtractStructure API
 */
public interface ExtractStructureService {
    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using a token proxy
     * provided by a {@link com.hp.autonomy.hod.client.token.TokenProxyService}
     * @param bytes The bytes of a file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws NullPointerException                                                           If a TokenProxyService has not been defined
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromFile(byte[] bytes) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using the given token proxy
     * @param tokenProxy The token proxy to use
     * @param bytes The bytes of a file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromFile(TokenProxy<?, TokenType.Simple> tokenProxy, byte[] bytes) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using a token proxy
     * provided by a {@link com.hp.autonomy.hod.client.token.TokenProxyService}
     * @param inputStream The stream of a file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws NullPointerException                                                           If a TokenProxyService has not been defined
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromFile(InputStream inputStream) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using the given token proxy
     * @param tokenProxy The token proxy to use
     * @param inputStream The stream of a file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromFile(TokenProxy<?, TokenType.Simple> tokenProxy, InputStream inputStream) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using a token proxy
     * provided by a {@link com.hp.autonomy.hod.client.token.TokenProxyService}
     * @param file The file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws NullPointerException                                                           If a TokenProxyService has not been defined
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromFile(File file) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using the given token proxy
     * @param tokenProxy The token proxy to use
     * @param file The file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromFile(TokenProxy<?, TokenType.Simple> tokenProxy, File file) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using the given token proxy
     * @param tokenProxy The token proxy to use
     * @param reference The object store reference containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromReference(TokenProxy<?, TokenType.Simple> tokenProxy, String reference) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using the given token proxy
     * @param reference The object store reference containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromReference(String reference) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using the given token proxy
     * @param tokenProxy The token proxy to use
     * @param url The url pointing to a file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromUrl(TokenProxy<?, TokenType.Simple> tokenProxy, String url) throws HodErrorException;

    /**
     * Extract content from a CSV file into a JSON format using Micro Focus Haven on Demand using the given token proxy
     * @param url The url pointing to a file containing the data to be extracted.
     * @return {@link List} of JSON objects stored as a {@link LinkedHashMap} with column names as keys and cell values as values.
     * @throws com.hp.autonomy.hod.client.api.authentication.HodAuthenticationFailedException If the token associated
     *                                                                                with the token proxy has expired
     */
    List<LinkedHashMap<String, String>> extractFromUrl(String url) throws HodErrorException;
}


text:
"""Test mempool persistence.

By default, planbcoind will dump mempool on shutdown and
then reload it on startup. This can be overridden with
the -persistmempool=0 command line option.

Test is as follows:

  - start node0, node1 and node2. node1 has -persistmempool=0
  - create 5 transactions on node2 to its own address. Note that these
    are not sent to node0 or node1 addresses because we don't want
    them to be saved in the wallet.
  - check that node0 and node1 have 5 transactions in their mempools
  - shutdown all nodes.
  - startup node0. Verify that it still has 5 transactions
    in its mempool. Shutdown node0. This tests that by default the
    mempool is persistent.
  - startup node1. Verify that its mempool is empty. Shutdown node1.
    This tests that with -persistmempool=0, the mempool is not
    dumped to disk when the node is shut down.
  - Restart node0 with -persistmempool=0. Verify that its mempool is
    empty. Shutdown node0. This tests that with -persistmempool=0,
    the mempool is not loaded from disk on start up.
  - Restart node0 with -persistmempool. Verify that it has 5
    transactions in its mempool. This tests that -persistmempool=0
    does not overwrite a previously valid mempool stored on disk.

"""
import time

from test_framework.mininode import wait_until
from test_framework.test_framework import PlanbcoinTestFramework
from test_framework.util import *

class MempoolPersistTest(PlanbcoinTestFramework):

    def __init__(self):
        super().__init__()
        # We need 3 nodes for this test. Node1 does not have a persistent mempool.
        self.num_nodes = 3
        self.setup_clean_chain = False
        self.extra_args = [[], ["-persistmempool=0"], []]

    def run_test(self):
        chain_height = self.nodes[0].getblockcount()
        assert_equal(chain_height, 200)

        self.log.debug("Mine a single block to get out of IBD")
        self.nodes[0].generate(1)
        self.sync_all()

        self.log.debug("Send 5 transactions from node2 (to its own address)")
        for i in range(5):
            self.nodes[2].sendtoaddress(self.nodes[2].getnewaddress(), Decimal("10"))
        self.sync_all()

        self.log.debug("Verify that node0 and node1 have 5 transactions in their mempools")
        assert_equal(len(self.nodes[0].getrawmempool()), 5)
        assert_equal(len(self.nodes[1].getrawmempool()), 5)

        self.log.debug("Stop-start node0 and node1. Verify that node0 has the transactions in its mempool and node1 does not.")
        self.stop_nodes()
        self.nodes = []
        self.nodes.append(self.start_node(0, self.options.tmpdir))
        self.nodes.append(self.start_node(1, self.options.tmpdir))
        # Give planbcoind a second to reload the mempool
        time.sleep(1)
        assert wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5)
        assert_equal(len(self.nodes[1].getrawmempool()), 0)

        self.log.debug("Stop-start node0 with -persistmempool=0. Verify that it doesn't load its mempool.dat file.")
        self.stop_nodes()
        self.nodes = []
        self.nodes.append(self.start_node(0, self.options.tmpdir, ["-persistmempool=0"]))
        # Give planbcoind a second to reload the mempool
        time.sleep(1)
        assert_equal(len(self.nodes[0].getrawmempool()), 0)

        self.log.debug("Stop-start node0. Verify that it has the transactions in its mempool.")
        self.stop_nodes()
        self.nodes = []
        self.nodes.append(self.start_node(0, self.options.tmpdir))
        assert wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5)

if __name__ == '__main__':
    MempoolPersistTest().main()


text:
package layer.module

import layer.configuration.Project

/**
 * HierarchyNode - Node in package ownership hierarchy
 * @author chanjinpark
 *
 */
class HierarchyNode(pn: PackageNode) {
  def pkgnode = pn

  var parent: HierarchyNode = null
  var leaves = List[HierarchyNode]()

  override def toString = {
    (if (pkgnode == null) "-" else pkgnode.value)
    /*+ "\n" +
    "parent - " + parent + "\n" +
    "leaves - " + leaves.mkString(",")*/
  }

  def toValue = {
    (if (pkgnode == null) "-" else pkgnode.value) + "\n" +
      "parent - " + parent + "\n" +
      "leaves - " + leaves.mkString(",")
  }
}

object HierarchyNode {
  def getParentStr(p: String) = if (p.indexOf('.') != -1) p.substring(0, p.lastIndexOf(".")) else "-"

  def ancestors(r: HierarchyNode): List[HierarchyNode] =
    if (r.parent == null) List[HierarchyNode]()
    else r.parent :: ancestors(r.parent)

  def descendants(p: HierarchyNode): List[HierarchyNode] =
    if (p.leaves.length == 0) p.leaves
    else p.leaves ::: p.leaves.flatMap(descendants(_))

  def makeHierarchy(pdg: PackageStructure, treeroot: HierarchyNode): Map[String, HierarchyNode] = {
    var pkg2hn = pdg.nodes.values.foldLeft(Map[String, HierarchyNode]())((result, pn) =>
      result + (pn.value -> new HierarchyNode(pn.asInstanceOf[PackageNode])))
    pkg2hn += ("-" -> treeroot)

    def getParent(pkgname: String): HierarchyNode = {
      def parent(p: String): HierarchyNode = {
        val index = p.lastIndexOf(".")
        if (index == -1) treeroot
        else {
          val p1 = p.substring(0, p.lastIndexOf("."))
          if (pkg2hn.contains(p1)) pkg2hn(p1)
          else parent(p1)
        }
      }
      if (pkgname == "-") null else parent(pkgname)
    }

    pkg2hn.foreach(p2hn => {
      val parent = getParent(p2hn._1)
      if (parent != null) {
        p2hn._2.parent = parent
        parent.leaves = p2hn._2 :: parent.leaves
      }
    })

    //println(pkg2hn.mkString("\n"))

    pkg2hn
  }
}

class PackageHierarchy(pdg: PackageStructure) {
  val treeroot = new HierarchyNode(null)
  // imaginary root node
  val pkg2hn = HierarchyNode.makeHierarchy(pdg, treeroot)

  def isRoot(p: String) = (p == "-")

  //println(pkg2hn.mkString("\n"))

  def toDotPackageHierarchy(dotname: String) = {
    val hierarchy = new DependencyGraph() {
      def addEdge(from: String, to: String): DepEdge = {
        addEdge(new DepEdge(nodes(from), nodes(to)))
      }
    }
    pkg2hn.foreach(s2np => hierarchy.addNode(new NodeElem(s2np._1)))

    def addEdgeR(hn: HierarchyNode): Unit = {
      hn.leaves.foreach(leaf => {
        hierarchy.addEdge((if (hn == treeroot) "-" else hn.pkgnode.value), leaf.pkgnode.value);
        addEdgeR(leaf)
      })
    }
    addEdgeR(treeroot)

    val project = Project.get
    Graph2Dot.toDotType(hierarchy, dotname)
  }
}

object PackageHierarchy {
  def getHiearchy(pdg: PackageStructure) = {
    (new PackageHierarchy(pdg))
  }
}


text: MathJax.Localization.addTranslation("cs","MathML",{version:"2.3",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/cs/MathML.js");


text:
import { Component, Input, OnInit, ViewChild } from '@angular/core';

import {
  Asset,
  MutateRecord,
  MutateAction,
  AssetConnType,
  MutateAsset,
  AssetType,
  TextAsset,
  VideoAsset,
} from './../model/asset';
import { Account } from '../model/account';
import { AssetService } from './../services/asset.service';
import { STATUS } from '../model/response';
import { MatSnackBar } from '@angular/material/snack-bar';
import {
  AccountStructComponent,
  AdGroupRow,
  AssetConn,
} from '../account-struct/account-struct.component';
import { Subscription } from 'rxjs';
import { SelectionModel } from '@angular/cdk/collections';
import { setClassMetadata } from '@angular/core/src/r3_symbols';

@Component({
  selector: 'app-asset-details',
  templateUrl: './asset-details.component.html',
  styleUrls: ['./asset-details.component.css'],
})
export class AssetDetailsComponent implements OnInit {
  private _subscriptions: Subscription[] = [];

  private _account: Account;
  private _activeAsset: Asset;
  assetType = AssetType;

  /** Update button params */
  updateInProgress: boolean = false;
  updateMessage: string = '';
  isErrorMessage: boolean = false;

  get asset(): any {
    return this._activeAsset;
  }

  @Input()
  set account(account: Account) {
    this._account = account;
  }

  get account(): Account {
    return this._account;
  }

  @Input() closeAssetDetails: Function;
  @ViewChild('accountAdGroups') accountAdGroups: AccountStructComponent;

  constructor(
    private dataService: AssetService,
    private _snackBar: MatSnackBar
  ) {}

  ngOnInit(): void {
    this._subscriptions.push(
      this.dataService.activeAsset$.subscribe((asset) => {
        this._activeAsset = asset;
      })
    );

    this._subscriptions.push(
      this.dataService.activeAssetAdGroups$.subscribe((_) => {
        this.updateMessage = '';
        this.isErrorMessage = false;
      })
    );

    this._subscriptions.push(
      this.dataService.updateFinished$.subscribe((response) => {
        this.updateInProgress = false;
        if (response) {
          this.updateMessage = response.msg;
          this.isErrorMessage = response.status_code !== STATUS.SUCCESS;
          if (!this.isErrorMessage) {
            // Update succeeded - reset the checkboxes edit state
            this.accountAdGroups.resetEditedRows();
            this._snackBar.open('Updated Successfully', '', {
              duration: 2000,
              horizontalPosition: 'center',
              verticalPosition: 'bottom',
            });
          }
        }
      })
    );
  }

  ngOnDestroy() {
    for (let sub of this._subscriptions) {
      sub.unsubscribe();
    }
  }

  onClose() {
    this.closeAssetDetails();
  }

  updateAsset() {
    let mutateRecords: MutateRecord[] = [];
    this.accountAdGroups.getUpdatedRows().forEach((row) => {
      mutateRecords.push(...this.createMutateRecord(row));
    });

    console.log('Mutate: ', mutateRecords);

    if (mutateRecords.length) {
      this.updateInProgress = true;
      this.dataService.updateAsset(this.asset, mutateRecords);
    }
  }

  loadAdGroups() {
    this.accountAdGroups.sortBySelection();
    this.accountAdGroups.resetEditedRows();
  }

  private createMutateRecord(row: AdGroupRow): MutateRecord[] {
    // Assume it's a non-text asset unless it is text
    let selArray: any;
    let mutateObjs = [];
    let connection = AssetConnType.ADGROUP;

    if (this.asset.type != this.assetType.TEXT) {
      selArray = this.accountAdGroups.adgroup_sel;
      mutateObjs.push(this.createMutateObj(connection, row, selArray));
    } else {
      if (row.isEdited[AssetConn.HEADLINE]) {
        connection = AssetConnType.HEADLINE;
        selArray = this.accountAdGroups.headline_sel;
        mutateObjs.push(this.createMutateObj(connection, row, selArray));
      }
      if (row.isEdited[AssetConn.DESC]) {
        connection = AssetConnType.DESC;
        selArray = this.accountAdGroups.description_sel;
        mutateObjs.push(this.createMutateObj(connection, row, selArray));
      }
    }
    return mutateObjs;
  }

  /** Helper function to create the mutate Object */
  private createMutateObj(
    connection: AssetConnType,
    row: AdGroupRow,
    selArray: SelectionModel<AdGroupRow>
  ) {
    // Check if its added or removed
    let action = selArray.isSelected(row)
      ? MutateAction.ADD
      : MutateAction.REMOVE;

    let assetObj = this.createAssetObj(connection);
    let mutateObj: MutateRecord = {
      account: this._account.id,
      adgroup: row.id,
      action: action,
      asset: assetObj,
    };

    return mutateObj;
  }

  /** Helper function that creates the appropriate asset object */
  private createAssetObj(connection: AssetConnType) {
    let assetObj: MutateAsset = {
      id: this._activeAsset.id,
      type: <AssetType>this._activeAsset.type,
    };
    switch (this._activeAsset.type) {
      case AssetType.TEXT:
        assetObj.asset_text = (this._activeAsset as TextAsset).asset_text;
        assetObj.text_type_to_assign = connection.toLowerCase();
        break;
      case AssetType.VIDEO:
        assetObj.video_id = (this._activeAsset as VideoAsset).video_id;
        break;
    }
    return assetObj;
  }
}


text:
package com.dianping.paas.api.controller.console;

import com.dianping.paas.core.dto.request.AllocateWebPackageRequest;
import com.dianping.paas.core.dto.request.DownloadWebPackageRequest;
import com.dianping.paas.core.dto.request.UploadWebPackageRequest;
import com.dianping.paas.core.dto.response.AllocateWebPackageResponse;
import com.dianping.paas.core.dto.response.UploadWebPackageResponse;
import com.dianping.paas.core.message.nats.request.RepositoryRequester;
import com.dianping.paas.repository.service.WebPackageService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by yuchao on 12/3/15.
 */
@RestController
@RequestMapping("/v1/repository/webpackages")
public class WebPackageController {

    @Resource
    private WebPackageService webPackageService;

    @Resource
    private RepositoryRequester repositoryRequester;

    /**
     * 分配 web package 的上传地址的时候 需要向repository发消息
     */
    @RequestMapping(value = "/allocations", method = RequestMethod.POST)
    public AllocateWebPackageResponse allocateWebPackage(AllocateWebPackageRequest request) {

        return repositoryRequester.allocateWebPackage(request);
    }

    /**
     * 上传 web package 的时候已经落在了本机,所以直接执行,不用nats来发消息
     */
    @RequestMapping(method = RequestMethod.POST)
    public UploadWebPackageResponse uploadWebPackage(UploadWebPackageRequest request) throws IOException {

        return webPackageService.upload(request);
    }

    /**
     * 下载 web package 的时候已经落在了本机,所以直接执行,不用nats来发消息
     */
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public FileSystemResource downloadWebPackage(DownloadWebPackageRequest request) {

        return webPackageService.download(request).getFileSystemResource();
    }
}


text:
set -e
set -o pipefail

if [ "$#" -ne 3 ]; then
    echo "ERROR: Wrong number of arguments. Usage '$0 VERSION_TAG BUILD_OS OUTPUT_DIR'"
    exit 1
fi
VERSION_TAG=$1
BUILD_OS=$2
OUTPUT_DIR=$3

TEMP_RELEASE_DIR=~/heron-release

# Clear out the pex cache
rm -rf /var/lib/jenkins/.pex/build/*

# Build with docker
chmod +x scripts/release/status.sh
chmod +x heron/downloaders/src/shell/heron-downloader.sh
chmod +x heron/tools/apiserver/src/shell/heron-apiserver.sh

bash scripts/release/status.sh

# Create a temporary directory for generated files
mkdir -p $TEMP_RELEASE_DIR
rm -f $TEMP_RELEASE_DIR/*.*
./docker/scripts/build-artifacts.sh $BUILD_OS $VERSION_TAG $TEMP_RELEASE_DIR

# Cherry-pick files to output dir
mkdir -p $OUTPUT_DIR
cp $TEMP_RELEASE_DIR/heron-${VERSION_TAG}-${BUILD_OS}.tar.gz $OUTPUT_DIR
cp $TEMP_RELEASE_DIR/heron-install-${VERSION_TAG}-${BUILD_OS}.sh $OUTPUT_DIR

# Remove temporary directory
rm -rf $TEMP_RELEASE_DIR


text:
Imports System.Xml.Serialization
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.Math

Namespace MarkupData.nmrML

    Public Class spectrum1D

        Public Property spectrumDataArray As fidData
        Public Property xAxis As xAxis

        Public Function ParseMatrix(SW As Double) As LibraryMatrix
            Dim spec1r As Double() = spectrumDataArray.DecodeBytes
            Dim ppm As Double() = xAxis.GetPPM(spec1r.Length, SW)

            Call Array.Reverse(ppm)

            Return New LibraryMatrix With {
                .ms2 = ppm _
                    .Select(Function(p, i)
                                Return New ms2 With {
                                    .mz = p,
                                    .intensity = spec1r(i)
                                }
                            End Function) _
                    .ToArray
            }
        End Function

    End Class

    Public Class xAxis

        <XmlAttribute> Public Property unitAccession As String
        <XmlAttribute> Public Property unitName As String
        <XmlAttribute> Public Property unitCvRef As String
        <XmlAttribute> Public Property startValue As Double
        <XmlAttribute> Public Property endValue As Double

        ''' <summary>
        '''
        ''' </summary>
        ''' <param name="SI">size of the spectrum</param>
        ''' <returns></returns>
        Public Function GetPPM(SI As Integer, SW As Double) As Double()
            Dim dppm As Double = SW / (SI - 1)
            Dim ppm_max = startValue
            Dim ppm_min = endValue
            Dim ppm As Double() = seq(from:=ppm_min, to:=ppm_max, by:=dppm).ToArray

            Return ppm
        End Function
    End Class

    Public Class spectrumList

        <XmlElement> Public Property spectrum1D As spectrum1D()

    End Class
End Namespace


text:
namespace blink {

class GraphicsContext;
struct PaintInfo;
class IntRect;
class LayoutPoint;
class LayoutRect;
class RenderScrollbar;
class RenderScrollbarPart;

class ScrollbarPainter {
public:
    ScrollbarPainter(RenderScrollbar& renderScrollbar) : m_renderScrollbar(renderScrollbar) { }

    void paintPart(GraphicsContext*, ScrollbarPart, const IntRect&);
    static void paintIntoRect(RenderScrollbarPart*, GraphicsContext*, const LayoutPoint& paintOffset, const LayoutRect&);

private:
    RenderScrollbar& m_renderScrollbar;
};

} // namespace blink

#endif // ScrollbarPainter_h


text:
import React from 'react';
import PropTypes from 'prop-types';

const Bookmark = (props) => {
  const color = props.color == 'inherit' ? undefined : props.color;
  const aria = props.title ? 'svg-bookmark-title' : '' +
    props.title && props.description ? ' ' : '' +
    props.description ? 'svg-bookmark-desc' : '';
  return (
    <svg width={props.width} height={props.height} viewBox='0 0 24 24'
      xmlns='http://www.w3.org/2000/svg' role='img'
      aria-labelledby={aria}
    >
      {!props.title ? null :
        <title id='svg-bookmark-title'>{props.title}</title>
      }
      {!props.description ? null :
        <desc id='svg-bookmark-desc'>{props.description}</desc>
      }
      <path fill={color} d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/>
    </svg>
  );
};

Bookmark.defaultProps = {
  color: 'inherit',
  width: undefined,
  height: undefined,
  title: '',
  description: ''
};

Bookmark.propTypes = {
  color: PropTypes.string,
  width: PropTypes.string,
  height: PropTypes.string,
  title: PropTypes.string,
  description: PropTypes.string
};

export default Bookmark;


text:
/**
 * @ngdoc directive
 * @name cheekyEditable
 */
angular.module('cheeky').directive('cheekyEditable', ['$rootScope', '$document', 'cheekyCMS', 'cheekyEvents',
    function ($rootScope, $document, content, ckEvents) {
        return {
            restrict: 'A',
            link: function (scope, $element, attrs) {
                if (!window.aloha) return; // if aloha does not exist, editing is disabled

                var path = (attrs.path || attrs.cheekyContent);

                // editing ckEvents
                scope.$on(ckEvents.showEditor, onShowEditor);
                scope.$on(ckEvents.showPreview, onShowPreview);

                function onShowEditor(){
                    $element.addClass('cheeky-editable');
                    $element.on('click', onEditableClick);
                }

                function onShowPreview(){
                    onEditableBlur();
                    $element.removeClass('cheeky-editable');
                    $element.off('click', onEditableClick);
                    $document.off('click', onDocumentClick);
                }

                function onEditableClick(){
                    window.aloha($element[0]);
                    $element.addClass('cheeky-edit-active');
                    $rootScope.$broadcast(ckEvents.beginEdit, { element: $element[0] });
                    $document.on('click', onDocumentClick);
                }

                function onEditableBlur(){
                    if($element.hasClass('cheeky-edit-active')){
                        window.aloha.mahalo($element[0]);
                        $element.removeClass('cheeky-edit-active');
                        $rootScope.$broadcast(ckEvents.endEdit, { element: $element[0] });
                        $document.off('click', onDocumentClick);
                    }
                }

                function onDocumentClick(event) {
                    // TODO: we need to do mouse math here instead for more accuracy
                    var eventOutsideTarget = (element[0] !== event.target) && (0 === element.find(event.target).length),
                        isRibbon = angular.element('#cheeky-ribbon').find(event.target).length > 0;

                    if (eventOutsideTarget && !isRibbon) {
                        scope.$apply(onEditableBlur);
                    }
                }

                // data ckEvents
                scope.$on(ckEvents.cancelChanges, onCancelChanges);
                scope.$on(ckEvents.saveChanges, onSaveChanges);

                function onCancelChanges(){

                }
                function onSaveChanges(){

                }

                // destroy the scope
                scope.$on('$destroy', function(){
                    $element.off('click', onEditableClick);
                    $document.off('click', onDocumentClick);
                });
            }
        };
    }
]);


text:
package org.apache.oozie.command.coord;

import java.io.ByteArrayOutputStream;
import java.util.List;

import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import org.apache.oozie.CoordinatorActionBean;
import org.apache.oozie.CoordinatorJobBean;
import org.apache.oozie.client.CoordinatorAction;
import org.apache.oozie.client.CoordinatorJob;
import org.apache.oozie.coord.CoordELFunctions;
import org.apache.oozie.dependency.DependencyChecker;
import org.apache.oozie.executor.jpa.CoordActionGetJPAExecutor;
import org.apache.oozie.executor.jpa.JPAExecutorException;
import org.apache.oozie.service.CallableQueueService;
import org.apache.oozie.service.HCatAccessorService;
import org.apache.oozie.service.JPAService;
import org.apache.oozie.service.PartitionDependencyManagerService;
import org.apache.oozie.service.RecoveryService;
import org.apache.oozie.service.Services;
import org.apache.oozie.test.XDataTestCase;
import org.apache.oozie.util.HCatURI;
import org.apache.oozie.util.XmlUtils;
import org.jdom.Element;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestCoordPushDependencyCheckXCommand extends XDataTestCase {
    private String server;
    private Services services = null;

    @Before
    protected void setUp() throws Exception {
        super.setUp();
        services = super.setupServicesForHCatalog();
        services.init();
        server = getMetastoreAuthority();
    }

    @After
    protected void tearDown() throws Exception {
        Services.get().destroy();
        super.tearDown();
    }

    @Test
    public void testUpdateCoordTableSingleDep() throws Exception {
        // Test for single dependency which is already in the hcat server
        String db = "default";
        String table = "tablename";
        String newHCatDependency = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";

        populateTable(db, table);

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);

        new CoordPushDependencyCheckXCommand(actionId).call();

        checkCoordAction(actionId, "", CoordinatorAction.Status.READY);

    }

    @Test
    public void testUpdateCoordTableMultipleDepsV1() throws Exception {
        // Test for two dependencies which are already in the hcat server
        String db = "default";
        String table = "tablename";
        String newHCatDependency1 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120412;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;
        populateTable(db, table);

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);

        new CoordPushDependencyCheckXCommand(actionId).call();

        checkCoordAction(actionId, "", CoordinatorAction.Status.READY);

    }

    @Test
    public void testUpdateCoordTableMultipleDepsV2() throws Exception {
        // Test for two dependencies : one of them is already existing in the
        // hcat server. Other one is not.
        // Expected to see both action in WAITING as first one is not available and we only check for first.
        // Later make the other partition also available. action is expected to
        // be READY
        String db = "default";
        String table = "tablename";
        String newHCatDependency1 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;
        populateTable(db, table);

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);

        // Checks only for first missing dependency
        new CoordPushDependencyCheckXCommand(actionId).call();

        // Checks dependencies in order. So list does not change if first one is not available
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);

        // Make first dependency available
        dropPartition(db, table, "dt=20120430;country=usa");
        addPartition(db, table, "dt=20120430;country=brazil");
        new CoordPushDependencyCheckXCommand(actionId).call();
        checkCoordAction(actionId, newHCatDependency2, CoordinatorAction.Status.WAITING);

        addPartition(db, table, "dt=20120430;country=usa");
        new CoordPushDependencyCheckXCommand(actionId).call();
        checkCoordAction(actionId, "", CoordinatorAction.Status.READY);
    }

    @Test
    public void testUpdateCoordTableMultipleDepsV3() throws Exception {
        // Test for two dependencies : one of them is already existing in the
        // hcat server. Other one is not.
        // Expected to see only first action in WAITING as we check for all dependencies.
        // Later make the other partition also available. action is expected to
        // be READY
        String db = "default";
        String table = "tablename";
        String newHCatDependency1 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;
        populateTable(db, table);

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);

        // Checks for all missing dependencies
        new CoordPushDependencyCheckXCommand(actionId, true).call();
        checkCoordAction(actionId, newHCatDependency1, CoordinatorAction.Status.WAITING);
        PartitionDependencyManagerService pdms = Services.get().get(PartitionDependencyManagerService.class);
        HCatAccessorService hcatService = Services.get().get(HCatAccessorService.class);
        assertTrue(pdms.getWaitingActions(new HCatURI(newHCatDependency1)).contains(actionId));
        assertTrue(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));
        assertNull(pdms.getWaitingActions(new HCatURI(newHCatDependency2)));

        // Make first dependency available
        addPartition(db, table, "dt=20120430;country=brazil");
        new CoordPushDependencyCheckXCommand(actionId).call();
        checkCoordAction(actionId, "", CoordinatorAction.Status.READY);
        assertNull(pdms.getWaitingActions(new HCatURI(newHCatDependency1)));
        assertFalse(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));
    }

    @Test
    public void testResolveCoordConfiguration() throws Exception {
        String db = "default";
        String table = "tablename";
        String newHCatDependency1 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120412;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;
        populateTable(db, table);

        CoordinatorJobBean job = addRecordToCoordJobTableForWaiting("coord-job-for-action-input-check.xml",
                CoordinatorJob.Status.RUNNING, false, true);

        CoordinatorActionBean action = addRecordToCoordActionTableForWaiting(job.getId(), 1,
                CoordinatorAction.Status.WAITING, "coord-action-for-action-push-check.xml", null, newHCatDependency,
                "Z");

        String actionId = action.getId();
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);

        new CoordPushDependencyCheckXCommand(actionId).call();

        CoordinatorActionBean caBean = checkCoordAction(actionId, "", CoordinatorAction.Status.READY);
        Element eAction = XmlUtils.parseXml(caBean.getActionXml());
        Element configElem = eAction.getChild("action", eAction.getNamespace())
                .getChild("workflow", eAction.getNamespace()).getChild("configuration", eAction.getNamespace());
        List<?> elementList = configElem.getChildren("property", configElem.getNamespace());
        Element e1 = (Element) elementList.get(0);
        Element e2 = (Element) elementList.get(1);
        assertEquals(
                "hcat://dummyhcat:1000/db1/table1/ds=/2009-29,hcat://dummyhcat:1000/db1/table1/ds=/2009-29," +
                "hcat://dummyhcat:1000/db1/table1/ds=/2009-29",
                e1.getChild("value", e1.getNamespace()).getValue());
        assertEquals("hcat://dummyhcat:1000/db1/table1/ds=/2009-29", e2.getChild("value", e1.getNamespace()).getValue());

    }

    @Test
    public void testTimeOut() throws Exception {
        String db = "default";
        String table = "tablename";
        String newHCatDependency1 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;
        populateTable(db, table);

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);
        new CoordPushDependencyCheckXCommand(actionId, true).call();
        checkCoordAction(actionId, newHCatDependency1, CoordinatorAction.Status.WAITING);
        PartitionDependencyManagerService pdms = Services.get().get(PartitionDependencyManagerService.class);
        HCatAccessorService hcatService = Services.get().get(HCatAccessorService.class);
        assertTrue(pdms.getWaitingActions(new HCatURI(newHCatDependency1)).contains(actionId));
        assertTrue(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));

        // Timeout is 10 mins. Change action created time to before 12 min to make the action
        // timeout.
        long timeOutCreationTime = System.currentTimeMillis() - (12 * 60 * 1000);
        setCoordActionCreationTime(actionId, timeOutCreationTime);
        new CoordPushDependencyCheckXCommand(actionId).call();
        Thread.sleep(100);
        // Check for timeout status and unregistered missing dependencies
        checkCoordAction(actionId, newHCatDependency1, CoordinatorAction.Status.TIMEDOUT);
        assertNull(pdms.getWaitingActions(new HCatURI(newHCatDependency1)));
        assertFalse(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));

    }

    @Test
    public void testTimeOutWithUnresolvedMissingDependencies() throws Exception {
        String db = "default";
        String table = "tablename";
        String newHCatDependency1 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";
        String newHCatDependency3 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=uk";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;
        populateTable(db, table);

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);
        new CoordPushDependencyCheckXCommand(actionId, true).call();
        checkCoordAction(actionId, newHCatDependency1, CoordinatorAction.Status.WAITING);
        PartitionDependencyManagerService pdms = Services.get().get(PartitionDependencyManagerService.class);
        HCatAccessorService hcatService = Services.get().get(HCatAccessorService.class);
        assertTrue(pdms.getWaitingActions(new HCatURI(newHCatDependency1)).contains(actionId));
        assertTrue(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));

        // Timeout is 10 mins. Change action created time to before 12 min to make the action
        // timeout.
        long timeOutCreationTime = System.currentTimeMillis() - (12 * 60 * 1000);
        setCoordActionCreationTime(actionId, timeOutCreationTime);
        // Set some missing dependency. Instead of latest or future just setting a current one for testing as
        // we are only interested in ensuring CoordActionInputCheckXCommand is run
        setMissingDependencies(actionId, newHCatDependency + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency3);
        addPartition(db, table, "dt=20120430;country=brazil");
        checkDependencies(actionId, newHCatDependency + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency3,
                newHCatDependency1);
        new CoordPushDependencyCheckXCommand(actionId).call();
        // Somehow with hive 0.10 it takes 1 second more.
        Thread.sleep(1300);

        checkDependencies(actionId, newHCatDependency3, "");
        assertNull(pdms.getWaitingActions(new HCatURI(newHCatDependency1)));
        assertFalse(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));
    }

    @Test
    public void testTimeOutWithException1() throws Exception {
        // Test timeout when missing dependencies are from a non existing table
        String newHCatDependency1 = "hcat://" + server + "/nodb/notable/dt=20120430;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/nodb/notable/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);
        try {
            new CoordPushDependencyCheckXCommand(actionId, true).call();
            fail();
        }
        catch (Exception e) {
            assertTrue(e.getMessage().contains("NoSuchObjectException"));
        }
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);
        PartitionDependencyManagerService pdms = Services.get().get(PartitionDependencyManagerService.class);
        HCatAccessorService hcatService = Services.get().get(HCatAccessorService.class);
        assertNull(pdms.getWaitingActions(new HCatURI(newHCatDependency1)));
        assertFalse(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));

        // Timeout is 10 mins. Change action created time to before 12 min to make the action
        // timeout.
        long timeOutCreationTime = System.currentTimeMillis() - (12 * 60 * 1000);
        setCoordActionCreationTime(actionId, timeOutCreationTime);
        try {
            new CoordPushDependencyCheckXCommand(actionId).call();
            fail();
        }
        catch (Exception e) {
            assertTrue(e.getMessage().contains("NoSuchObjectException"));
        }
        Thread.sleep(100);
        // Check for timeout status and unregistered missing dependencies
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.TIMEDOUT);
    }

    @Test
    public void testTimeOutWithException2() throws Exception {
        // Test timeout when table containing missing dependencies is dropped in between
        String db = "default";
        String table = "tablename";
        String newHCatDependency1 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;
        populateTable(db, table);

        String actionId = addInitRecords(newHCatDependency);
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);
        new CoordPushDependencyCheckXCommand(actionId, true).call();
        checkCoordAction(actionId, newHCatDependency1, CoordinatorAction.Status.WAITING);
        PartitionDependencyManagerService pdms = Services.get().get(PartitionDependencyManagerService.class);
        HCatAccessorService hcatService = Services.get().get(HCatAccessorService.class);
        assertTrue(pdms.getWaitingActions(new HCatURI(newHCatDependency1)).contains(actionId));
        assertTrue(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));

        // Timeout is 10 mins. Change action created time to before 12 min to make the action
        // timeout.
        long timeOutCreationTime = System.currentTimeMillis() - (12 * 60 * 1000);
        setCoordActionCreationTime(actionId, timeOutCreationTime);
        dropTable(db, table, true);
        try {
            new CoordPushDependencyCheckXCommand(actionId).call();
            fail();
        }
        catch (Exception e) {
            assertTrue(e.getMessage().contains("NoSuchObjectException"));
        }
        Thread.sleep(100);
        // Check for timeout status and unregistered missing dependencies
        checkCoordAction(actionId, newHCatDependency1, CoordinatorAction.Status.TIMEDOUT);
        assertNull(pdms.getWaitingActions(new HCatURI(newHCatDependency1)));
        assertFalse(hcatService.isRegisteredForNotification(new HCatURI(newHCatDependency1)));
    }

    @Test
    public void testRequeueOnException() throws Exception {
        Services.get().getConf().setInt(RecoveryService.CONF_SERVICE_INTERVAL, 6000);
        // Test timeout when table containing missing dependencies is dropped in between
        String newHCatDependency1 = "hcat://" + server + "/nodb/notable/dt=20120430;country=brazil";
        String newHCatDependency2 = "hcat://" + server + "/nodb/notable/dt=20120430;country=usa";
        String newHCatDependency = newHCatDependency1 + CoordELFunctions.INSTANCE_SEPARATOR + newHCatDependency2;

        CoordinatorJobBean job = addRecordToCoordJobTableForWaiting("coord-job-for-action-input-check.xml",
                CoordinatorJob.Status.RUNNING, false, true);

        CoordinatorActionBean action = addRecordToCoordActionTableForWaiting(job.getId(), 1,
                CoordinatorAction.Status.WAITING, "coord-action-for-action-input-check.xml", null,
                newHCatDependency, "Z");
        String actionId = action.getId();
        checkCoordAction(actionId, newHCatDependency, CoordinatorAction.Status.WAITING);
        try {
            new CoordPushDependencyCheckXCommand(actionId, true).call();
            fail();
        }
        catch (Exception e) {
            assertTrue(e.getMessage().contains("NoSuchObjectException"));
        }
        // Nothing should be queued as there are no pull dependencies
        CallableQueueService callableQueueService = Services.get().get(CallableQueueService.class);
        assertEquals(0, callableQueueService.getQueueDump().size());

        // Nothing should be queued as there are no pull missing dependencies
        // but only push missing deps are there
        new CoordActionInputCheckXCommand(actionId, job.getId()).call();
        callableQueueService = Services.get().get(CallableQueueService.class);
        assertEquals(0, callableQueueService.getQueueDump().size());

        setMissingDependencies(actionId, newHCatDependency1);
        try {
            new CoordPushDependencyCheckXCommand(actionId, true).call();
            fail();
        }
        catch (Exception e) {
            assertTrue(e.getMessage().contains("NoSuchObjectException"));
        }
        // Should be requeued at the recovery service interval
        final List<String> queueDump = callableQueueService.getQueueDump();
        assertEquals(1, callableQueueService.getQueueDump().size());
        assertTrue(queueDump.get(0).contains(CoordPushDependencyCheckXCommand.class.getName()));
        log.info("Queue dump is " + queueDump.toString());
        // Delay should be something like delay=599999. Ignore last three digits
        assertTrue(queueDump.get(0).matches("delay=599[0-9]{3}, .*"));
    }

    @Test
    public void testLogMessagePrefix() throws Exception {
        Logger logger = Logger.getLogger(DependencyChecker.class);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Layout layout = new SimpleLayout();
        Appender appender = new WriterAppender(layout, out);
        logger.addAppender(appender);

        String db = "default";
        String table = "tablename";
        populateTable(db, table);

        String newHCatDependency = "hcat://" + server + "/" + db + "/" + table + "/dt=20120430;country=brazil";
        String actionId1 = addInitRecords(newHCatDependency);
        new CoordPushDependencyCheckXCommand(actionId1).call();
        assertTrue(out.toString().contains("ACTION[" + actionId1 + "]"));
        out.reset();
        String actionId2 = addInitRecords(newHCatDependency);
        new CoordPushDependencyCheckXCommand(actionId2).call();
        assertFalse(out.toString().contains("ACTION[" + actionId1 + "]"));
        assertTrue(out.toString().contains("ACTION[" + actionId2 + "]"));
    }

    private void populateTable(String db, String table) throws Exception {
        dropTable(db, table, true);
        dropDatabase(db, true);
        createDatabase(db);
        createTable(db, table, "dt,country");
        addPartition(db, table, "dt=20120430;country=usa");
        addPartition(db, table, "dt=20120412;country=brazil");
        addPartition(db, table, "dt=20120413;country=brazil");
    }

    private CoordinatorActionBean checkCoordAction(String actionId, String expDeps, CoordinatorAction.Status stat)
            throws Exception {
        try {
            JPAService jpaService = Services.get().get(JPAService.class);
            CoordinatorActionBean action = jpaService.execute(new CoordActionGetJPAExecutor(actionId));
            String missDeps = action.getPushMissingDependencies();
            assertEquals(expDeps, missDeps);
            assertEquals(stat, action.getStatus());

            return action;
        }
        catch (JPAExecutorException se) {
            throw new Exception("Action ID " + actionId + " was not stored properly in db");
        }
    }

    private CoordinatorActionBean checkDependencies(String actionId, String expDeps, String expPushDeps)
            throws Exception {
        try {
            JPAService jpaService = Services.get().get(JPAService.class);
            CoordinatorActionBean action = jpaService.execute(new CoordActionGetJPAExecutor(actionId));
            assertEquals(expDeps, action.getMissingDependencies());
            assertEquals(expPushDeps, action.getPushMissingDependencies());
            return action;
        }
        catch (JPAExecutorException se) {
            throw new Exception("Action ID " + actionId + " was not stored properly in db");
        }
    }

}


text:
require 'action_view'
require 'action_view/context'

module Referrari
  module Helpers
    class Referrals
      # so that this instance can actually "render"
      include ::ActionView::Context

      def initialize(options)
        @options = options
        @output_buffer = ActionView::OutputBuffer.new
      end

      # render given block as a view template
      def render_box(&block)
        @output_buffer
      end

      def to_s
        "Some content"
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using DataExplorer.Domain.Colors;

namespace DataExplorer.Presentation.Panes.Layout.Color
{
    public class ColorPaletteViewModel
    {
        private readonly ColorPalette _colorPalette;

        public ColorPaletteViewModel(ColorPalette colorPalette)
        {
            _colorPalette = colorPalette;
        }

        public List<System.Windows.Media.Color> Colors
        {
            get
            {
                return _colorPalette.Colors
                    .Select(p => System.Windows.Media.Color.FromRgb(p.Red, p.Green, p.Blue))
                    .ToList();
            }
        }

        public ColorPalette ColorPalette
        {
            get { return _colorPalette; }
        }

        public override bool Equals(object obj)
        {
            if (!(obj is ColorPaletteViewModel))
                return false;

            var other = (ColorPaletteViewModel) obj;

            return _colorPalette.Name == other._colorPalette.Name;
        }

        public override int GetHashCode()
        {
            return (_colorPalette != null ? _colorPalette.GetHashCode() : 0);
        }
    }
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150519_123210_cms_alter_drop_publications_and_page_options extends Migration
{
    public function safeUp()
    {
        $this->execute("ALTER TABLE {{%cms_tree%}} DROP `page_options`;");
        $this->execute("ALTER TABLE {{%cms_storage_file%}} DROP `page_options`;");

        $tableExist = $this->db->getTableSchema("{{%cms_publication}}", true);
        if ($tableExist)
        {
            $this->execute("DROP TABLE {{%cms_publication}}");
        }
    }

    public function down()
    {
        echo "m150519_123210_cms_alter_drop_publications_and_page_options cannot be reverted.\n";
        return false;
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Brownpapertickets" do
  before(:each) do
    @invalid_attributes1 = {
      :id => "citizen_client",
      :account => nil
    }
    @invalid_attributes2 = {
      :id => nil,
      :account => "XsIhXp7K8CknZsC"
    }
    @invalid_attributes3 = {
      :id => nil,
      :account => nil
    }
    @valid_attributes = {
      :account => "citizen_client",
      :id => "XsIhXp7K8CknZsC"
    }
    @resp = mock("resp")
    @resp2 = mock("resp2")
    @resp3 = mock("resp3")
    @resp.stub!(:options).and_return({})
    @resp.stub!(:perform).and_return(@resp2)
    @resp2.stub!(:response).and_return(@resp3)
    @bpt = BrownPaperTickets::Base.new(@valid_attributes[:id],@valid_attributes[:account])
  end

  it "should Raise an exception when creating a new instance of brownpapertickets with invalid arguments" do
    lambda { BrownPaperTickets::Base.new(@invalid_attributes1[:id],@invalid_attributes1[:account]) }.should raise_error(ArgumentError)
  end

  it "should Raise an exception when creating a new instance of brownpapertickets with invalid arguments" do
    lambda { BrownPaperTickets::Base.new(@invalid_attributes2[:id],@invalid_attributes2[:account]) }.should raise_error(ArgumentError)
  end

  it "should Raise an exception when creating a new instance of brownpapertickets with invalid arguments" do
    lambda { BrownPaperTickets::Base.new(@invalid_attributes3[:id],@invalid_attributes3[:account]) }.should raise_error(ArgumentError)
  end

  it "should get a list of all events" do
    stub_get('https://www.brownpapertickets.com/api2/eventlist?id=XsIhXp7K8CknZsC&account=citizen_client', 'all_events.xml')
    @bpt.events.stub!(:all).and_return(fetch_all_events(HTTParty::Parser.call(fixture_file('all_events.xml'),:xml)["document"]["event"]))
    bpt = @bpt.events.all
    bpt.size.should == 5
    bpt.first.event_id.should == '106861'
    bpt.first.title.gsub("\n","").should == 'Nichole Canuso Dance Company Second Annual Benefit Cabaret'
    bpt.last.event_id.should == '1068612'
    bpt.last.title.gsub("\n","").should == 'Nichole Canuso Dance Company Second Annual Benefit Cabaret2'
  end

  it "should get a single event" do
    stub_get('https://www.brownpapertickets.com/api2/eventlist?id=XsIhXp7K8CknZsC&account=citizen_client&event_id=106861', 'event.xml')
    @bpt.events.stub!(:find).with(106861).and_return(BrownPaperTickets::Event.new(@id,@account,HTTParty::Parser.call(fixture_file('event.xml'),:xml)["document"]["event"]))
    bpt = @bpt.events.find(106861)
    bpt.event_id.should == '106861'
    bpt.title.gsub("\n","").should == 'Nichole Canuso Dance Company Second Annual Benefit Cabaret'
  end

  it "should raise a exception that is missing an attr" do
    event = @bpt.events.new
    event.save!.should  == false
    event.server_response.blank?.should == false
  end

  it "should raise a exception that is missing an attr" do
    @bpt.events.create({}).should == false
  end

  it "Should save the event" do
    @resp3.stub!(:body).and_return(fixture_file('create_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.save!
    event.event_id.should == "120266"
  end

  it "Should not save the event and rise a ArgumentError" do
    @resp3.stub!(:body).and_return(fixture_file('create_not_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.save!.should == false
  end

  it "Should update the event with one attr" do
    @resp3.stub!(:body).and_return(fixture_file('update_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.update_attribute(:e_name, "This Awsome Title").should == true
    event.server_response.should == "success"
  end

  it "Should not update the event with one attr" do
    @resp3.stub!(:body).and_return(fixture_file('update_not_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.update_attribute(:e_name, "This Awsome Title").should == false
    event.server_response.should == "Event does not belong to account"
  end

  it "Should update the event with few attr" do
    @resp3.stub!(:body).and_return(fixture_file('update_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.update_attributes({:e_name => "This Awsome Title2",:e_address1 => "Evergreen av 123", :e_phone => "5553335588"}).should == true
    event.server_response.should == "success"
  end

  it "Should not update the event with few attr" do
    @resp3.stub!(:body).and_return(fixture_file('update_not_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.update_attributes({:e_name => "This Awsome Title2",:e_address1 => "Evergreen av 123", :e_phone => "5553335588"}).should == false
    event.server_response.should == "Event does not belong to account"
  end

  it "Should save the event" do
    @resp3.stub!(:body).and_return(fixture_file('update_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("event_id"=> "120266","e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.title = "hello world"
    event.save!.should == true
    event.event_id.should == "120266"
    event.e_name.should == "hello world"
  end

  it "Should not save the event and rise a ArgumentError" do
    @resp3.stub!(:body).and_return(fixture_file('update_not_ok.xml'))
    BrownPaperTickets::Httpost.stub!(:new).and_return(@resp)
    event = @bpt.events.new("e_zip" => "90210", "e_name"=>"test", "e_city"=> "Sprinfield", "e_state"=>"CA", "e_short_description"=>"this is a test", "e_description"=>"this is a test")
    event.save!.should == false
  end

end


text:
<?php

class DmAutoSeoTable extends PluginDmAutoSeoTable
{

    public static function getInstance()
    {
        return Doctrine_Core::getTable('DmAutoSeo');
    }
}


text:
@implementation DDPromptCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        _promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//        [_promptLabel setBackgroundColor:RGB(193, 193, 193)];
        [_promptLabel setBackgroundColor:[UIColor grayColor]];
        [_promptLabel setTextColor:[UIColor whiteColor]];
        [_promptLabel setFont:[UIFont systemFontOfSize:12]];
        [_promptLabel setTextAlignment:NSTextAlignmentCenter];
        [_promptLabel.layer setCornerRadius:5];
        [_promptLabel setClipsToBounds:YES];
        [self.contentView addSubview:_promptLabel];
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setprompt:(NSString*)prompt
{
    UIFont* font = [UIFont systemFontOfSize:12];
    CGSize size = [prompt sizeWithFont:font constrainedToSize:CGSizeMake(320, 1000000) lineBreakMode:NSLineBreakByWordWrapping];
    [_promptLabel setSize:CGSizeMake(size.width + 30, size.height + 6)];
    CGPoint tmpCenter = self.contentView.center;
    tmpCenter.x=FULL_WIDTH/2+6;
    [_promptLabel setCenter:tmpCenter];
    [_promptLabel setText:prompt];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.opengamma.strata</groupId>
    <artifactId>strata-parent</artifactId>
    <version>0.8.0-SNAPSHOT</version>
    <relativePath>..</relativePath>
  </parent>
  <artifactId>strata-finance-beta</artifactId>
  <packaging>jar</packaging>
  <name>Strata-Finance-Beta</name>
  <description>Entities in financial markets - Beta code, subject to change</description>

  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <skipIfEmpty>false</skipIfEmpty>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>

    <dependency>
      <groupId>com.opengamma.strata</groupId>
      <artifactId>strata-collect</artifactId>
    </dependency>
    <dependency>
      <groupId>com.opengamma.strata</groupId>
      <artifactId>strata-basics</artifactId>
    </dependency>
    <dependency>
      <groupId>com.opengamma.strata</groupId>
      <artifactId>strata-finance</artifactId>
    </dependency>

    <dependency>
      <groupId>com.opengamma.strata</groupId>
      <artifactId>strata-collect</artifactId>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <properties>

    <windowtitle>OpenGamma Strata Finance, Beta code</windowtitle>
    <doctitle><![CDATA[
OpenGamma Strata Finance, Beta code
]]></doctitle>
  </properties>

</project>


text:
  <md-card class="card" *ngIf=user>
    <button md-button [mdMenuTriggerFor]="settings" class="settings-btn">
        <md-icon>settings</md-icon>
    </button>
    <md-menu class="settings-menu" #settings="mdMenu">
      <button md-menu-item (click)="openDialog('password')"><md-icon>lock</md-icon> Reset password</button>
      <button md-menu-item (click)="openDialog('email')"><md-icon>email</md-icon> Change email</button>
      <button md-menu-item (click)="openDialog('picture')"><md-icon>photo</md-icon> Change picture</button>
    </md-menu>
    <md-card-header>

        <md-icon>account_circle</md-icon>

      <md-card-title id="user-fullname">{{user.firstName + ' ' + user.lastName}}</md-card-title>
      <md-card-subtitle id="username">Username: {{user.username}}</md-card-subtitle>
      <md-card-subtitle id="user-email">Email: {{user.email}}</md-card-subtitle>
    </md-card-header>

    <md-card-content>
    </md-card-content>

      <md-card-actions class="card-actions">
        <button routerLink="/user/collection" md-button><md-icon>favorite border</md-icon> My Collection</button>
      </md-card-actions>

  </md-card>


text:
namespace Microsoft.DotNet.Cli.Utils
{
    internal class LocalizableStrings
    {
        public const string MalformedText = "Malformed command text '{0}'";

        public const string BuildOutputPathDoesNotExist = "outputpathresolver: {0} does not exist";

        public const string AttemptingToFindCommand = "{0}: attempting to find command {1} in {2}";

        public const string FailedToFindToolAssembly = "{0}: failed to find toolAssembly for {1}";

        public const string FailedToFindCommandPath = "{0}: failed to find commandPath {1}";

        public const string UnableToLocateDotnetMultiplexer = "Unable to locate dotnet multiplexer";

        public const string LookingForPreferCliRuntimeFile = "{0}: Looking for prefercliruntime file at `{1}`";

        public const string AttemptingToResolve = "{0}: attempting to resolve {1}";

        public const string DidNotFindAMatchingProject = "{0}: Did not find a matching project {1}.";

        public const string InvalidCommandResolverArguments = "{0}: invalid commandResolverArguments";

        public const string DoesNotExist = "{0}: {1} does not exist";

        public const string AmbiguousCommandName = "Ambiguous command name: {0}";

        public const string ToolLibraryFound = "{0}: tool library found {1}";

        public const string MSBuildExePath = "{0}: MSBUILD_EXE_PATH = {1}";

        public const string MSBuildProjectPath = "{0}: MSBuild project path = {1}";

        public const string MultipleProjectFilesFound = "Specify which project file to use because this '{0}' contains more than one project file.";

        public const string DidNotFindProject = "{0}: ProjectFactory did not find Project.";

        public const string ResolvingCommandSpec = "{0}: resolving commandspec from {1} Tool Libraries.";

        public const string FailedToResolveCommandSpec = "{0}: failed to resolve commandspec from library.";

        public const string AttemptingToResolveCommandSpec = "{0}: Attempting to resolve command spec from tool {1}";

        public const string NuGetPackagesRoot = "{0}: nuget packages root:\n{1}";

        public const string FoundToolLockFile = "{0}: found tool lockfile at : {1}";

        public const string LibraryNotFoundInLockFile = "{0}: library not found in lock file.";

        public const string AttemptingToCreateCommandSpec = "{0}: attempting to create commandspec";

        public const string CommandSpecIsNull = "{0}: commandSpec is null.";

        public const string ExpectDepsJsonAt = "{0}: expect deps.json at: {1}";

        public const string GeneratingDepsJson = "Generating deps.json at: {0}";

        public const string UnableToGenerateDepsJson = "unable to generate deps.json, it may have been already generated: {0}";

        public const string UnableToDeleteTemporaryDepsJson = "unable to delete temporary deps.json file: {0}";

        public const string VersionForPackageCouldNotBeResolved = "Version for package `{0}` could not be resolved.";

        public const string FileNotFound = "File not found `{0}`.";

        public const string ProjectNotRestoredOrRestoreFailed = "The project may not have been restored or restore failed - run `dotnet restore`";

        public const string NoExecutableFoundMatchingCommand = "No executable found matching command \"{0}\"";

        public const string CommandAssembliesNotFound = "The command executable for \"{0}\" was not found. The project may not have been restored or restore failed - run `dotnet restore`";

        public const string WaitingForDebuggerToAttach = "Waiting for debugger to attach. Press ENTER to continue";

        public const string ProcessId = "Process ID: {0}";

        public const string CouldNotAccessAssetsFile = "Could not access assets file.";

        public const string DotNetCommandLineTools = ".NET Command Line Tools";

        public const string WriteLineForwarderSetPreviously = "WriteLine forwarder set previously";

        public const string AlreadyCapturingStream = "Already capturing stream!";

        public const string RunningFileNameArguments = "Running {0} {1}";

        public const string ProcessExitedWithCode = "< {0} exited with {1} in {2} ms.";

        public const string UnableToInvokeMemberNameAfterCommand = "Unable to invoke {0} after the command has been run";
    }
}


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

<TITLE>
NoSuchUserException (GNU cryptographic primitives and tools)
</TITLE>
<META NAME="keywords" CONTENT="gnu.crypto.sasl.NoSuchUserException,NoSuchUserException class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY:  NESTED | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

gnu.crypto.sasl

Class NoSuchUserException

java.lang.Object
  |
  +--java.lang.Throwable
        |
        +--java.lang.Exception
              |
              +--java.io.IOException
                    |
                    +--javax.security.sasl.SaslException
                          |
                          +--javax.security.sasl.AuthenticationException
                                |
                                +--gnu.crypto.sasl.NoSuchUserException

All Implemented Interfaces:
java.io.Serializable

public class NoSuchUserException
extends AuthenticationException

A checked exception thrown to indicate that a designated user is unknown to
 the authentication layer.

See Also:
Serialized Form

Constructor Summary

NoSuchUserException()

          Constructs a NoSuchUserException with no detail message.

NoSuchUserException(java.lang.String arg)

          Constructs a NoSuchUserException with the specified detail
 message.

Methods inherited from class javax.security.sasl.SaslException

getCause, printStackTrace, printStackTrace, printStackTrace, toString

Methods inherited from class java.lang.Throwable

fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace

Methods inherited from class java.lang.Object

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

Constructor Detail

NoSuchUserException

public NoSuchUserException()

Constructs a NoSuchUserException with no detail message.

NoSuchUserException

public NoSuchUserException(java.lang.String arg)

Constructs a NoSuchUserException with the specified detail
 message. In the case of this exception, the detail message designates
 the offending username.

Parameters:
arg - the detail message, which in this case is the username.

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY:  NESTED | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 2001, 2002, 2003, 2004 Free Software Foundation, Inc.


text:
package org.apache.jackrabbit.oak.plugins.document;

import org.apache.jackrabbit.oak.cache.CacheStats;
import org.apache.jackrabbit.oak.commons.json.JsopReader;
import org.apache.jackrabbit.oak.commons.json.JsopTokenizer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * A cache for child node diffs.
 */
abstract class DiffCache {

    /**
     * Returns a jsop diff for the child nodes at the given path. The returned
     * String may contain the following changes on child nodes:
     *

     *
Changed child nodes: e.g. {@code ^"foo":{}}

     *
Added child nodes: e.g. {@code +"bar":{}}

     *
Removed child nodes: e.g. {@code -"baz"}

     *

     * A {@code null} value indicates that this cache does not have an entry
     * for the given revision range at the path.
     *
     * @param from the from revision.
     * @param to the to revision.
     * @param path the path of the parent node.
     * @param loader an optional loader for the cache entry.
     * @return the diff or {@code null} if unknown and no loader was passed.
     */
    @Nullable
    abstract String getChanges(@NotNull RevisionVector from,
                               @NotNull RevisionVector to,
                               @NotNull Path path,
                               @Nullable Loader loader);

    /**
     * Starts a new cache entry for the diff cache. Actual changes are added
     * to the entry with the {@link Entry#append(Path, String)} method.
     *
     * @param from the from revision.
     * @param to the to revision.
     * @param local true indicates that the entry results from a local change,
     * false if it results from an external change
     * @return the cache entry.
     */
    @NotNull
    abstract Entry newEntry(@NotNull RevisionVector from,
                            @NotNull RevisionVector to,
                            boolean local);

    /**
     * @return the statistics for this cache.
     */
    @NotNull
    abstract Iterable<CacheStats> getStats();

    /**
     * Parses the jsop diff returned by
     * {@link #getChanges(RevisionVector, RevisionVector, Path, Loader)} and reports the
     * changes by calling the appropriate methods on {@link Diff}.
     *
     * @param jsop the jsop diff to parse.
     * @param diff the diff handler.
     * @return {@code true} it the complete jsop was processed or {@code false}
     *      if one of the {@code diff} callbacks requested a stop.
     * @throws IllegalArgumentException if {@code jsop} is malformed.
     */
    static boolean parseJsopDiff(@NotNull String jsop,
                                 @NotNull Diff diff) {
        if (jsop.trim().isEmpty()) {
            return true;
        }
        JsopTokenizer t = new JsopTokenizer(jsop);
        boolean continueComparison = true;
        while (continueComparison) {
            int r = t.read();
            if (r == JsopReader.END) {
                break;
            }
            switch (r) {
                case '+': {
                    String name = t.readString();
                    t.read(':');
                    t.read('{');
                    while (t.read() != '}') {
                        // skip properties
                    }
                    continueComparison = diff.childNodeAdded(name);
                    break;
                }
                case '-': {
                    String name = t.readString();
                    continueComparison = diff.childNodeDeleted(name);
                    break;
                }
                case '^': {
                    String name = t.readString();
                    t.read(':');
                    t.read('{');
                    t.read('}');
                    continueComparison = diff.childNodeChanged(name);
                    break;
                }
                default:
                    throw new IllegalArgumentException("jsonDiff: illegal token '"
                            + t.getToken() + "' at pos: " + t.getLastPos() + ' ' + jsop);
            }
        }
        return continueComparison;
    }

    interface Entry {

        /**
         * Appends changes about children of the node at the given path.
         *
         * @param path the path of the parent node.
         * @param changes the child node changes.
         */
        void append(@NotNull Path path,
                    @NotNull String changes);

        /**
         * Called when all changes have been appended and the entry is ready
         * to be used by the cache.
         *
         * @return {@code true} if the entry was successfully added to the
         *          cache, {@code false} otherwise.
         */
        boolean done();
    }

    interface Loader {

        String call();
    }

    interface Diff {

        boolean childNodeAdded(String name);

        boolean childNodeChanged(String name);

        boolean childNodeDeleted(String name);

    }
}