text:
package id.jeval;

import static id.jeval.commands.CommandConstants.OPEN_COMMAND;
import static id.xfunction.function.Curry.curryAccept;
import static java.lang.System.err;
import static java.lang.System.exit;
import static java.lang.System.in;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Scanner;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import id.jeval.commands.DependencyResolver;
import id.jeval.commands.OpenScripts;
import id.xfunction.XUtils;
import id.xfunction.cli.ArgumentParsingException;
import id.xfunction.cli.SmartArgs;
import id.xfunction.function.ThrowingRunnable;
import id.xfunction.function.Unchecked;
import jdk.jshell.JShell;
import jdk.jshell.JShell.Builder;

public class Main {

    private static final String CLASSPATH_SEP = System.getProperty("path.separator", ":");
    private static JShell jshell;
    private static JshExecutor jshExec;
    private static EventHandler eventHandler;
    private static Optional<Path> scriptPath = Optional.empty();

    @SuppressWarnings("resource")
    private static void usage() throws IOException {
        Scanner scanner = new Scanner(Main.class.getResource("/jeval/README.md").openStream())
                .useDelimiter("\n");
        while (scanner.hasNext())
            System.out.println(scanner.next());
    }

    @SuppressWarnings("resource")
    private static void preloader(JshExecutor jshExec) throws IOException {
        eventHandler.setIsScript(true);
        Scanner scanner = new Scanner(Main.class.getResource("/jeval/preloader.jsh").openStream())
                .useDelimiter("\n");
        while (scanner.hasNext()) {
            eventHandler.onNextLine(Paths.get("preloader.jsh"));
            jshExec.onNext(scanner.next());
        }
    }

    private static void defineArgs(JshExecutor jshExec, List<String> args) {
        jshExec.onNext(String.format("args = new String[]{%s};",
            args.stream()
                .map(Main::asStringLiteral)
                .collect(joining(", "))));
    }

    private static void defineScriptPath(JshExecutor jshExec) {
        scriptPath.ifPresent(path -> {
            jshExec.onNext(String.format("scriptPath = Optional.of(Paths.get(%s));",
                asStringLiteral(path.toString())));});
    }

    private static String asStringLiteral(String str) {
        // mask backslash so that it can be used as Java string literal
        str = str.replace("\\", "\\\\");
        return XUtils.quote(str);
    }

    private static void runScript(Path file, Stream<String> stream) {
        eventHandler.setIsScript(true);
        OpenScripts opener = new OpenScripts();
        boolean[] firstLine = new boolean[] {true};
        stream.forEach(line -> {
            if (firstLine[0]) {
                firstLine[0] = false;
                if (line.startsWith("#!")) {
                    return;
                }
            }
            if (eventHandler.isError()) return;
            eventHandler.onNextLine(file);
            if (line.startsWith(OPEN_COMMAND)) {
                Path openFile = opener.open(file, line);
                runScript(openFile, Unchecked.get(() -> Files.readAllLines(openFile).stream()));
                return;
            }
            jshExec.onNext(line);
        });
    }

    private static void runSnippet(String snippet) {
        eventHandler.setIsScript(false);
        eventHandler.onNextLine(Paths.get(""));
        jshExec.onNext(snippet);
    }

    private static void mainInternal(String[] args) throws Exception {
        if (args.length < 1) {
            usage();
            exit(1);
        }

        List<String> classPathList = toClasspathList(System.getProperty("java.class.path", ""));

        ThrowingRunnable<Exception>[] runnable = new ThrowingRunnable[1];
        List<String> runnableArgs = new ArrayList<>();
        Map<String, Consumer<String>> handlers = Map.of(
            "-e", snippet -> runnable[0] = curryAccept(Main::runSnippet, snippet),
            "-classpath", cp -> classPathList.addAll(toClasspathList(cp)));
        Function<String, Boolean> defaultHandler = arg -> {
            if (arg.equals("-i")) {
                runnable[0] = () -> {
                    scriptPath = Optional.of(Paths.get("").toAbsolutePath());
                    Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(in)));
                    Iterator<String> iter = new Iterator<String>() {
                        @Override
                        public boolean hasNext() {
                            return scanner.hasNextLine();
                        }
                        @Override
                        public String next() {
                            return scanner.nextLine();
                        }
                    };
                    Stream<String> stream = StreamSupport.stream(
                        Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED),
                        false);
                    runScript(scriptPath.get(), stream);
                };
                return true;
            }
            if (runnable[0] != null) {
                // if we set the runnable already we can start
                // populate the args
                runnableArgs.add(arg);
                return true;
            }
            Path path = Paths.get(arg);
            scriptPath = Optional.of(path.toAbsolutePath());
            Unchecked.run(() -> classPathList.addAll(new DependencyResolver().resolve(path)));
            runnable[0] = () -> runScript(path, Files.readAllLines(path).stream());
            return true;
        };

        try {
            new SmartArgs(handlers, defaultHandler).parse(args);
            if (runnable[0] == null) throw new Exception();
        } catch (ArgumentParsingException e) {
            usage();
            exit(1);
        } catch (Exception e) {
            e.printStackTrace();
            exit(1);
        }

        String classPath = toClasspath(classPathList);
        Builder jshellBuilder = JShell.builder()
            .out(out)
            .in(in)
            .err(err)
            .executionEngine("local") // LocalExecutionControlProvider
            .compilerOptions("-g:none",
                "-implicit:none",
                "-proc:none",
                "-cp", classPath,
                "--add-modules", "ALL-MODULE-PATH");

        jshell = jshellBuilder.build();

        jshell.addToClasspath(classPath);

        eventHandler = new EventHandler(jshell);
        jshell.onSnippetEvent(eventHandler::onEvent);

        jshExec = new JshExecutor(jshell);
        preloader(jshExec);

        defineArgs(jshExec, runnableArgs);
        defineScriptPath(jshExec);

        try {
            runnable[0].run();
            jshExec.onComplete();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }

        eventHandler.close();
        jshell.close();

        exit(eventHandler.isError()? 1: 0);
    }

    private static String toClasspath(List<String> classPathList) {
        return classPathList.stream()
                .collect(joining(CLASSPATH_SEP));
    }

    private static List<String> toClasspathList(String classpath) {
        return new ArrayList<>(Arrays.asList(classpath
            .split(CLASSPATH_SEP)));
    }

    public static void main(String[] args) throws Exception {
        try {
            mainInternal(args);
        } catch (Throwable e) {
            e.printStackTrace();
            exit(1);
        }
    }
}


text:
/**
 * Licensed under Apache License v2. See LICENSE for more information.
 */
package org.inaetics.wiring.admin.https;

import java.net.URL;

/**
 * Interface for accessing HTTPS Admin configuration values.
 *
 * @author Amdatu Project Team
 */
public interface HttpsAdminConfiguration {

    /**
     * returns the base url for the HTTP admin
     *
     * @return the base url
     */
    public URL getBaseUrl();

    /**
     * returns the configured port for the tls connection.
     *
     * @return the secured port
     */
    public int getSecurePort();

    /**
     * returns the configuration if the client certificate should be validated
     *
     * @return the
     */
    public boolean shouldEenforceClientCertValidation();

    /**
     * returns the connect timeout for the client endpoint
     *
     * @return connect timeout in ms
     */
    public int getConnectTimeout();

    /**
     * returns the read timeout for the client endpoint
     *
     * @return read timeout in ms
     */
    public int getReadTimeout();

    /**
     * returns the zone id
     *
     * @return the zone id
     */
    public String getZone();

    /**
     * returns the node id
     *
     * @return the node id
     */
    public String getNode();

    /**
     * returns the truststore file name.
     *
     * @return truststore file name.
     */
    public String getTruststoreFileName();

    /**
     * returns the truststore password.
     *
     * @return the truststore password.
     */
    public String getTruststorePassword();

    /**
     * returns the truststore type (like/default "JKS").
     *
     * @return the type of the truststore.
     */
    public String getTruststoreType();
}

redpajama_set_name: RedPajamaGithub


text:
package ru.job4j.h1srp.input;

import java.util.Scanner;

/**
 * @author Vitaly Vasilyev, date: 09.04.2019, e-mail: rav.energ@rambler.ru
 * @version 1.0
 */
public class ConsoleInput implements Input {
    /**
     * Сканнер.
     */
    private Scanner scanner = new Scanner(System.in);

    /**
     * @param in строка с предложением.
     * @return строку, считываемую с консоли.
     */
    @Override
    public String askS(String in) {
        System.out.print(in);
        return scanner.nextLine();
    }

    /**
     * @param in строка с предложением.
     * @return целочисленное значение.
     */
    @Override
    public int askI(String in) {
        return Integer.parseInt(askS(in));
    }

    /**
     * Закрыть поток ввода.
     */
    @Override
    public void close() {
        this.scanner.close();
    }
}


text:
#pragma once

#include <memory>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>

#include "paddle/utils/string/printf.h"

namespace phi {
enum ErrorCode {
  // Legacy error.
  // Error type string: "Error"
  LEGACY = 0,

  // Client specified an invalid argument.
  // Error type string: "InvalidArgumentError"
  INVALID_ARGUMENT = 1,

  // Some requested entity (e.g., file or directory) was not found.
  // Error type string: "NotFoundError"
  NOT_FOUND = 2,

  // Operation tried to iterate past the valid input range.  E.g., seeking or
  // reading past end of file.
  // Error type string: "OutOfRangeError"
  OUT_OF_RANGE = 3,

  // Some entity that we attempted to create (e.g., file or directory)
  // already exists.
  // Error type string: "AlreadyExistsError"
  ALREADY_EXISTS = 4,

  // Some resource has been exhausted, perhaps a per-user quota, or
  // perhaps the entire file system is out of space.
  // Error type string: "ResourceExhaustedError"
  RESOURCE_EXHAUSTED = 5,

  // Operation was rejected because the system is not in a state
  // required for the operation's execution.
  // Error type string: "PreconditionNotMetError"
  PRECONDITION_NOT_MET = 6,

  // The caller does not have permission to execute the specified
  // operation.
  // Error type string: "PermissionDeniedError"
  PERMISSION_DENIED = 7,

  // Deadline expired before operation could complete.
  // Error type string: "ExecutionTimeout"
  EXECUTION_TIMEOUT = 8,

  // Operation is not implemented or not supported/enabled in this service.
  // Error type string: "UnimpelmentedError"
  UNIMPLEMENTED = 9,

  // The service is currently unavailable.  This is a most likely a
  // transient condition and may be corrected by retrying with
  // a backoff.
  // Error type string: "UnavailableError"
  UNAVAILABLE = 10,

  // Fatal errors.  Means some invariant expected by the underlying
  // system has been broken.  If you see one of these errors,
  // something is very broken.
  // Error type string: "FatalError"
  FATAL = 11,

  // Third-party library error.
  // Error type string: "ExternalError"
  EXTERNAL = 12,
};

class ErrorSummary {
 public:
  // Note(chenweihang): Final deprecated constructor
  //   This constructor is used to be compatible with
  //   current existing untyped PADDLE_ENFORCE_*
  //   PADDLE_ENFORCE
  // Note(chenweihang): Windows openblas need this
  //   constructor for compiling PADDLE_ENFORCE in *.cu,
  //   this is a bug cause we can't remove this
  //   constructor now.
  template <typename... Args>
  explicit ErrorSummary(Args... args) {
    code_ = phi::ErrorCode::LEGACY;
    msg_ = paddle::string::Sprintf(args...);
  }

  // Note(chenweihang): Only recommended constructor
  //   No longer supports PADDLE_ENFORCE without type or without error message
  explicit ErrorSummary(ErrorCode code, std::string msg)
      : code_(code), msg_(msg) {}

  ErrorCode code() const { return code_; }

  const std::string& error_message() const { return msg_; }

  std::string to_string() const;

 private:
  ErrorCode code_;
  std::string msg_;
};

namespace errors {

#define REGISTER_ERROR(FUNC, CONST, ...)                            \
  template <typename... Args>                                       \
  ::phi::ErrorSummary FUNC(Args... args) {                          \
    return ::phi::ErrorSummary(::phi::CONST,                        \
                               ::paddle::string::Sprintf(args...)); \
  }

REGISTER_ERROR(InvalidArgument, ErrorCode::INVALID_ARGUMENT)
REGISTER_ERROR(NotFound, ErrorCode::NOT_FOUND)
REGISTER_ERROR(OutOfRange, ErrorCode::OUT_OF_RANGE)
REGISTER_ERROR(AlreadyExists, ErrorCode::ALREADY_EXISTS)
REGISTER_ERROR(ResourceExhausted, ErrorCode::RESOURCE_EXHAUSTED)
REGISTER_ERROR(PreconditionNotMet, ErrorCode::PRECONDITION_NOT_MET)
REGISTER_ERROR(PermissionDenied, ErrorCode::PERMISSION_DENIED)
REGISTER_ERROR(ExecutionTimeout, ErrorCode::EXECUTION_TIMEOUT)
REGISTER_ERROR(Unimplemented, ErrorCode::UNIMPLEMENTED)
REGISTER_ERROR(Unavailable, ErrorCode::UNAVAILABLE)
REGISTER_ERROR(Fatal, ErrorCode::FATAL)
REGISTER_ERROR(External, ErrorCode::EXTERNAL)

#undef REGISTER_ERROR

}  // namespace errors
}  // namespace phi


text:
namespace sequoia {

namespace render {

/// @brief Listen to changes in the position of the Camera
/// @ingroup render
class SEQUOIA_API CameraPositionListener {
public:
  virtual ~CameraPositionListener() {}

  /// @brief The camera position changed
  virtual void cameraListenerPositionChanged(Camera* camera) = 0;

  /// @brief The camera rotation changed
  virtual void cameraListenerRotationChanged(Camera* camera) = 0;
};

/// @brief A viewpoint from which the scene will be rendered
///
/// Sequoia renders scenes from a camera viewpoint into a buffer of some sort, normally a window or
/// a texture (a subclass of RenderTarget).
///
/// Note in the untransformed coordinate-system the camera is starring down the negative Z-axis and
/// the eye is located at the origin.
///
/// @verbatim
///           Y
///           |  center
///           | /
///           |/
///          eye-------X
///          /
///         /
///        Z
/// @endverbatim
///
/// @ingroup render
class SEQUOIA_API Camera final : public ViewFrustum,
                                 public ViewportListener,
                                 public Listenable<CameraPositionListener> {
protected:
  /// Translation of the camera
  math::vec3 position_;

  /// Orientation of the camera
  math::quat orientation_;

  /// Distance from eye to center
  float eyeToCenterDistance_;

  /// Model matrix (used to compute eye, center and up)
  mutable math::mat4 modelMatrix_;
  mutable bool modelMatrixIsDirty_;

public:
  /// @brief Initialize the camera
  ///
  /// By default the camera is located at `(0, 0, 10)` and stares down at `(0, 0, 0)`.
  Camera(const math::vec3& eye = math::vec3(0, 0, 10),
         const math::vec3& center = math::vec3(0, 0, 0),
         const math::vec3& up = math::vec3(0, 1, 0));

  virtual ~Camera() {}

  /// @brief Get/Set the `eye` of the camera (where the camera is located)
  math::vec3 getEye() const;

  /// @brief Get/Set the `center` of the camera (where the camera points to)
  math::vec3 getCenter() const;

  /// @brief Get/Set the `up` direction of the camera
  math::vec3 getUp() const;

  /// @brief Position the camera at the `eye` starring at `center`
  ///
  /// @param eye      Specifies the position of the eye point (where the camera is located)
  /// @param center   Specifies the position of the reference point (where the camera points to)
  /// @param up       Specifies the direction of the up vector
  void lookAt(const math::vec3& eye, const math::vec3& center,
              const math::vec3& up = math::vec3(0, 1, 0));

  /// @brief Compute the view-projection matrix
  ///
  /// This returns `matViewProj = matProj * matView` where `matProj` is the projection matrix and
  /// `matView` is the camera view matrix. This call is formally equivalent to:
  ///
  /// @code{.cpp}
  /// math::mat4 matProj = math::perspective(getFieldOfViewY(), getAspectRatio(),
  ///                                        getZNearClipping(), getZFarClipping());
  /// math::mat4 matView = math::lookAt(getEye(), getCenter(), getUp());
  /// math::mat4 matViewProj = matProj * matView;
  /// @endcode
  math::mat4 getViewProjectionMatrix() const;

  /// @brief Compute the view-projection matrix
  math::mat4 getProjectionMatrix() const;

  /// @brief Set the position of the camera (equivalent to `setEye()`)
  void setPosition(const math::vec3& position);

  /// @brief Set the orientation of the camera (in world space)
  void setOrientation(const math::quat& orientation);

  /// @brief Get the position (this is equivalent to `getEye()`)
  const math::vec3& getPosition() const { return position_; }

  /// @brief Get the orientation
  const math::quat& getOrientation() const { return orientation_; }

  /// @brief The geometry of the associated viewport changed, we need to update our aspect ratio
  void viewportGeometryChanged(Viewport* viewport) override;

  /// @brief Convert to string
  std::string toString() const;

private:
  /// @brief Get the model matrix
  const math::mat4& getModelMatrix() const;

  /// @brief Compute the model matrix
  void computeModelMatrix() const;
};

} // namespace render

} // namespace sequoia

#endif


text:
=begin
#ESP Documentation

#The Evident Security Platform API (version 2.0) is designed to allow users granular control over their Amazon Web Service security experience by allowing them to review alerts, monitor signatures, and create custom signatures.

OpenAPI spec version: v2_sdk

Generated by: https://github.com/swagger-api/swagger-codegen.git

=end

require 'spec_helper'
require 'json'

# Unit tests for ESP::SignaturesApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'SignaturesApi' do
  before do
    # run before each test
    @instance = ESP::SignaturesApi.new
  end

  after do
    # run after each test
  end

  describe 'test an instance of SignaturesApi' do
    it 'should create an instance of SignaturesApi' do
      expect(@instance).to be_instance_of(ESP::SignaturesApi)
    end
  end

  # unit tests for list
  # Get a list of Signatures
  #
  # @param [Hash] opts the optional parameters
  # @option opts [String] :include Related objects that can be included in the response:  service, suppressions See Including Objects for more information.
  # @option opts [Hash<String, String>] :filter Filter Params for Searching.  Equality Searchable Attributes: [id, risk_level, service_id, disabled, supports_user_attribution, name, identifier, description, resolution] Matching Searchable Attributes: [name, identifier, description, resolution] Limited Searchable Attributes: [service_provider_eq, service_provider_in, service_name_in] Sortable Attributes: [name, identifier, updated_at, created_at, id] Searchable Associations: [signature_copy, disabled_external_accounts, integrations, suppressions] See Searching Lists for more information. See the filter parameter of the association's list action to see what attributes are searchable on each association. See Conditions on Relationships in Searching Lists for more information.
  # @option opts [String] :page Page Number and Page Size.  Number is the page number of the collection to return, size is the number of items to return per page.
  # @return [PaginatedCollection]
  describe 'list test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for list_disabled_external_accounts
  # Get a list of disabled External Accounts for a signature
  #
  # @param signature_id The ID of the signature to get the list of disabled external accounts for
  # @param [Hash] opts the optional parameters
  # @option opts [String] :include Related objects that can be included in the response:  organization, sub_organization, team, scan_intervals, disabled_signatures, suppressions, azure_group See Including Objects for more information.
  # @option opts [Hash<String, String>] :filter Filter Params for Searching.  Equality Searchable Attributes: [id, nickname, name] Matching Searchable Attributes: [nickname, name] Limited Searchable Attributes: [account_eq, arn_eq, provider_eq, subscription_id_eq] Sortable Attributes: [name, updated_at, created_at, id] Searchable Associations: [organization, sub_organization, team, azure_group, compliance_standards, disabled_signatures, integrations, scheduled_exports, suppressions] See Searching Lists for more information. See the filter parameter of the association's list action to see what attributes are searchable on each association. See Conditions on Relationships in Searching Lists for more information.
  # @option opts [String] :page Page Number and Page Size.  Number is the page number of the collection to return, size is the number of items to return per page.
  # @return [PaginatedCollection]
  describe 'list_disabled_external_accounts test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for list_with_custom_risk_level_for_external_account
  # Get A list of Signatures with default and custom risk levels for an External Account
  # Return only signatures that have a custom risk level set by searching with `filter:{custom_risk_level_present: 1}`
  # @param external_account_id The ID of the external account to retrieve
  # @param [Hash] opts the optional parameters
  # @option opts [String] :include Related objects that can be included in the response:  service, suppressions See Including Objects for more information.
  # @option opts [Hash<String, String>] :filter Filter Params for Searching.  Equality Searchable Attributes: [id, risk_level, service_id, disabled, supports_user_attribution, name, identifier, description, resolution] Matching Searchable Attributes: [name, identifier, description, resolution] Limited Searchable Attributes: [custom_risk_level_present, service_provider_eq, service_provider_in, service_name_in] Sortable Attributes: [name, identifier, updated_at, created_at, id] Searchable Associations: [signature_copy, disabled_external_accounts, integrations, suppressions] See Searching Lists for more information. See the filter parameter of the association's list action to see what attributes are searchable on each association. See Conditions on Relationships in Searching Lists for more information.
  # @option opts [String] :page Page Number and Page Size.  Number is the page number of the collection to return, size is the number of items to return per page.
  # @return [PaginatedCollection]
  describe 'list_with_custom_risk_level_for_external_account test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for remove_custom_risk_level_for_external_account
  # Remove a custom risk level to a Signature for an External Account
  #
  # @param external_account_id The ID of the external account this signature custom risk level is for
  # @param signature_id The signature ID this signature custom risk level is for
  # @param [Hash] opts the optional parameters
  # @return [Meta]
  describe 'remove_custom_risk_level_for_external_account test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for set_custom_risk_level_for_external_account
  # Add a custom risk level to a Signature for an External Account
  #
  # @param external_account_id The ID of the external account this signature custom risk level is for
  # @param risk_level The custom risk-level of the problem identified by the signature for this external_account. Valid values are low, medium, high
  # @param signature_id The signature ID this signature custom risk level is for
  # @param [Hash] opts the optional parameters
  # @option opts [String] :include Related objects that can be included in the response:  service, suppressions See Including Objects for more information.
  # @return [Signature]
  describe 'set_custom_risk_level_for_external_account test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for show
  # Show a single Signature
  #
  # @param id Signature ID
  # @param [Hash] opts the optional parameters
  # @option opts [String] :include Related objects that can be included in the response:  service, suppressions See Including Objects for more information.
  # @return [Signature]
  describe 'show test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for update_custom_risk_level_for_external_account
  # Update a Signature's custom risk level for an External Account
  #
  # @param external_account_id The ID of the external account this signature custom risk level is for
  # @param signature_id The signature ID this signature custom risk level is for
  # @param [Hash] opts the optional parameters
  # @option opts [String] :include Related objects that can be included in the response:  service, suppressions See Including Objects for more information.
  # @option opts [String] :risk_level The custom risk-level of the problem identified by the signature for this external_account. Valid values are low, medium, high
  # @return [Signature]
  describe 'update_custom_risk_level_for_external_account test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

end


text:
/**
 * this is the index for a browserify-build
 * which produces a single file that can be embedded into the html
 * and used via window.RxDB
 */

import '@babel/polyfill';
import * as RxDB from './index.js';
import * as RxDbPouchPlugin from './plugins/pouchdb/index.js';
RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb'));
RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http'));
window['RxDB'] = RxDB;
//# sourceMappingURL=browserify.index.js.map


text:
var userPrototype = function(){

};

module.exports = userPrototype;


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chromoting;

import static org.chromium.chromoting.CardboardDesktopRenderer.makeFloatBuffer;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.opengl.GLES20;

import java.nio.FloatBuffer;

/**
 * Chromoting Cardboard activity desktop, which is used to display host desktop.
 */
public class CardboardActivityDesktop {
    private static final String VERTEX_SHADER =
            "uniform mat4 u_CombinedMatrix;"
            + "attribute vec4 a_Position;"
            + "attribute vec2 a_TexCoordinate;"
            + "varying vec2 v_TexCoordinate;"
            + "void main() {"
            + "  v_TexCoordinate = a_TexCoordinate;"
            + "  gl_Position = u_CombinedMatrix * a_Position;"
            + "}";

    private static final String FRAGMENT_SHADER =
            "precision mediump float;"
            + "uniform sampler2D u_Texture;"
            + "varying vec2 v_TexCoordinate;"
            + "void main() {"
            + "  gl_FragColor = texture2D(u_Texture, v_TexCoordinate);"
            + "}";

    private static final FloatBuffer TEXTURE_COORDINATES = makeFloatBuffer(new float[] {
            // Texture coordinate data.
            0.0f, 0.0f,
            0.0f, 1.0f,
            1.0f, 0.0f,
            0.0f, 1.0f,
            1.0f, 1.0f,
            1.0f, 0.0f
    });

    private static final int POSITION_DATA_SIZE = 3;
    private static final int TEXTURE_COORDINATE_DATA_SIZE = 2;

    // Fix the desktop height and adjust width accordingly.
    private static final float HALF_HEIGHT = 1.0f;

    // Number of vertices passed to glDrawArrays().
    private static final int VERTICES_NUMBER = 6;

    private int mVertexShaderHandle;
    private int mFragmentShaderHandle;
    private int mProgramHandle;
    private int mCombinedMatrixHandle;
    private int mTextureUniformHandle;
    private int mPositionHandle;
    private int mTextureDataHandle;
    private int mTextureCoordinateHandle;
    private FloatBuffer mPosition;
    private float[] mCombinedMatrix;
    private float mHalfWidth;

    // Lock to allow multithreaded access to mHalfWidth.
    private final Object mHalfWidthLock = new Object();

    private Bitmap mVideoFrame;

    // Lock to allow multithreaded access to mVideoFrame.
    private final Object mVideoFrameLock = new Object();

    public CardboardActivityDesktop() {
        mVertexShaderHandle =
                ShaderHelper.compileShader(GLES20.GL_VERTEX_SHADER, VERTEX_SHADER);
        mFragmentShaderHandle =
                ShaderHelper.compileShader(GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER);
        mProgramHandle = ShaderHelper.createAndLinkProgram(mVertexShaderHandle,
                mFragmentShaderHandle, new String[] {"a_Position", "a_TexCoordinate",
                    "u_CombinedMatrix", "u_Texture"});
        mCombinedMatrixHandle =
                GLES20.glGetUniformLocation(mProgramHandle, "u_CombinedMatrix");
        mTextureUniformHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_Texture");
        mPositionHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_Position");
        mTextureCoordinateHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_TexCoordinate");
        mTextureDataHandle = TextureHelper.createTextureHandle();
    }

    /**
     * Draw the desktop. Make sure texture, position, and model view projection matrix
     * are passed in before calling this method.
     */
    public void draw() {
        GLES20.glUseProgram(mProgramHandle);

        // Pass in model view project matrix.
        GLES20.glUniformMatrix4fv(mCombinedMatrixHandle, 1, false, mCombinedMatrix, 0);

        // Pass in texture coordinate.
        GLES20.glVertexAttribPointer(mTextureCoordinateHandle, TEXTURE_COORDINATE_DATA_SIZE,
                GLES20.GL_FLOAT, false, 0, TEXTURE_COORDINATES);
        GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);

        GLES20.glVertexAttribPointer(mPositionHandle, POSITION_DATA_SIZE, GLES20.GL_FLOAT, false,
                0, mPosition);
        GLES20.glEnableVertexAttribArray(mPositionHandle);

        // Link texture data with texture unit.
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);
        GLES20.glUniform1i(mTextureUniformHandle, 0);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, VERTICES_NUMBER);
    }

    /**
     *  Update the desktop frame data based on the mVideoFrame. Note here we fix the
     *  height of the desktop and vary width accordingly.
     */
    public void updateVideoFrame(Bitmap videoFrame) {
        float newHalfDesktopWidth;
        synchronized (mVideoFrameLock) {
            mVideoFrame = videoFrame;
            TextureHelper.linkTexture(mTextureDataHandle, videoFrame);
            newHalfDesktopWidth = videoFrame.getWidth() * HALF_HEIGHT / videoFrame.getHeight();
        }

        synchronized (mHalfWidthLock) {
            if (Math.abs(mHalfWidth - newHalfDesktopWidth) > 0.0001) {
                mHalfWidth = newHalfDesktopWidth;
                mPosition = makeFloatBuffer(new float[] {
                        // Desktop model coordinates.
                        -mHalfWidth, HALF_HEIGHT, 0.0f,
                        -mHalfWidth, -HALF_HEIGHT, 0.0f,
                        mHalfWidth, HALF_HEIGHT, 0.0f,
                        -mHalfWidth, -HALF_HEIGHT, 0.0f,
                        mHalfWidth, -HALF_HEIGHT, 0.0f,
                        mHalfWidth, HALF_HEIGHT, 0.0f
                });
            }
        }
    }

    /**
     * Clean up opengl data.
     */
    public void cleanup() {
        GLES20.glDeleteShader(mVertexShaderHandle);
        GLES20.glDeleteShader(mFragmentShaderHandle);
        GLES20.glDeleteTextures(1, new int[] {mTextureDataHandle}, 0);
    }

    public void setCombinedMatrix(float[] combinedMatrix) {
        mCombinedMatrix = combinedMatrix.clone();
    }

    /**
     * Return true if video frame data are already loaded in.
     */
    public boolean hasVideoFrame() {
        synchronized (mVideoFrameLock) {
            return mVideoFrame != null;
        }
    }

    public float getHalfHeight() {
        return HALF_HEIGHT;
    }

    public float getHalfWidth() {
        synchronized (mHalfWidthLock) {
            return mHalfWidth;
        }
    }

    /**
     * Get desktop height and width in pixels.
     */
    public Point getFrameSizePixels() {
        synchronized (mVideoFrameLock) {
            return new Point(mVideoFrame == null ? 0 : mVideoFrame.getHeight(),
                    mVideoFrame == null ? 0 : mVideoFrame.getWidth());
        }
    }
}


text:
<?php

namespace Geo\Geocoder;

use Cake\Core\Configure;
use Cake\Core\InstanceConfigTrait;
use Geo\Exception\CalculatorException;

/**
 * Used by Geo.GeocoderBehavior
 *
 * @author Mark Scherer
 * @license MIT
 */
class Calculator {

	use InstanceConfigTrait;

	/**
	 * @var string
	 */
	public const UNIT_KM = 'K';

	/**
	 * @var string
	 */
	public const UNIT_NAUTICAL = 'N';

	/**
	 * @var string
	 */
	public const UNIT_FEET = 'F';

	/**
	 * @var string
	 */
	public const UNIT_INCHES = 'I';

	/**
	 * @var string
	 */
	public const UNIT_MILES = 'M';

	/**
	 * @var array
	 */
	protected $_units = [
		self::UNIT_KM => 1.609344,
		self::UNIT_NAUTICAL => 0.868976242,
		self::UNIT_FEET => 5280,
		self::UNIT_INCHES => 63360,
		self::UNIT_MILES => 1,
	];

	/**
	 * Validation and retrieval options
	 * - use:
	 * - log: false logs only real errors, true all activities
	 * - pause: timeout to prevent blocking
	 * - ...
	 *
	 * @var array<string, mixed>
	 */
	protected $_defaultConfig = [
		'units' => [
		],
	];

	/**
	 * @param array $config
	 */
	public function __construct(array $config = []) {
		$this->setConfig($config);

		$additionalUnits = (array)Configure::read('Geo.Calculator.units');
		foreach ($additionalUnits as $additionalUnit => $value) {
			$this->_units[$additionalUnit] = $value;
		}
	}

	/**
	 * Convert between units
	 *
	 * @param float $value
	 * @param string $fromUnit (using class constants)
	 * @param string $toUnit (using class constants)
	 * @throws \Exception
	 * @return float convertedValue
	 */
	public function convert($value, $fromUnit, $toUnit) {
		$fromUnit = strtoupper($fromUnit);
		$toUnit = strtoupper($toUnit);

		if (!isset($this->_units[$fromUnit]) || !isset($this->_units[$toUnit])) {
			throw new CalculatorException('Invalid Unit');
		}

		if ($fromUnit === static::UNIT_MILES) {
			$value *= $this->_units[$toUnit];
		} elseif ($toUnit === static::UNIT_MILES) {
			$value /= $this->_units[$fromUnit];
		} else {
			$value /= $this->_units[$fromUnit];
			$value *= $this->_units[$toUnit];
		}

		return $value;
	}

	/**
	 * Calculates Distance between two points - each: array('lat'=>x,'lng'=>y)
	 * DB:
	 * '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
	 * 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' .
	 * 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' .
	 * 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' .
	 * 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' .
	 * 'AS distance'
	 *
	 * @param array $pointX
	 * @param array $pointY
	 * @param string|null $unit Unit char or constant (M=miles, K=kilometers, N=nautical miles, I=inches, F=feet)
	 * @return int Distance in km
	 */
	public function distance(array $pointX, array $pointY, $unit = null) {
		if (empty($unit)) {
			$unit = array_keys($this->_units);
			$unit = $unit[0];
		}
		$unit = strtoupper($unit);
		if (!isset($this->_units[$unit])) {
			throw new CalculatorException(sprintf('Invalid Unit: %s', $unit));
		}

		$res = $this->calculateDistance($pointX, $pointY);
		if (isset($this->_units[$unit])) {
			$res *= $this->_units[$unit];
		}

		return (int)ceil($res);
	}

	/**
	 * Geocoder::calculateDistance()
	 *
	 * @param \ArrayObject|array $pointX
	 * @param \ArrayObject|array $pointY
	 * @return float
	 */
	public static function calculateDistance($pointX, $pointY) {
		$res = 69.09 * rad2deg(acos(sin(deg2rad($pointX['lat'])) * sin(deg2rad($pointY['lat']))
			+ cos(deg2rad($pointX['lat'])) * cos(deg2rad($pointY['lat'])) * cos(deg2rad($pointX['lng']
			- $pointY['lng']))));

		return $res;
	}

	/**
	 * Fuzziness filter for coordinates (lat or lng).
	 * Useful if you store other users' locations and want to grant some
	 * privacy protection. This way the coordinates will be slightly modified.
	 *
	 * @param float $coordinate Coordinate
	 * @param int $level The Level of blurriness (0...n), 0 means no blur
	 * @throws \Exception
	 * @return float Coordinates
	 */
	public static function blur($coordinate, $level = 0) {
		if (!$level) {
			return $coordinate;
		}

		$scrambleVal = 0.000001 * mt_rand(10, 200) * pow(2, $level) * (mt_rand(0, 1) === 0 ? 1 : -1);

		return $coordinate + $scrambleVal;

		//$scrambleVal *= (float)(2^$level);
		// TODO: + - by chance!!!
	}

}


text:
package com.rabriel;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.function.Predicate;

import static junit.framework.TestCase.assertEquals;

import static com.rabriel.GivenWhenThen.given;

/**
 * Created by Rabriel on 11/28/2016.
 */
public class ExceptionsAreThrownTest {

    public static final String EVERYTHING_WILL_BE_FINE = "everything will be fine";
    public static final String BAD_THINGS_HAPPEN = "bad things happen";
    private ExecutorService executor = Executors.newSingleThreadExecutor();

    @Test(expected=RuntimeException.class)
    public void testExceptionIsThrownFromWhen(){
        GivenWhenThen.given(null)
            .when(whenReceivedValue -> {throw new NullPointerException(BAD_THINGS_HAPPEN); });
    }

    @Test
    public void testExceptionMessageFromWhen(){
        try{
            GivenWhenThen.given(null)
                    .when(whenReceivedValue -> {throw new NullPointerException(BAD_THINGS_HAPPEN); });
        } catch (RuntimeException ex){
            assertEquals("Exception message should match.",GivenWhenThen.WHEN_FUNCTION_FAILED, ex.getMessage());
        }

        try{
            GivenWhenThen.given(null)
                    .when(EVERYTHING_WILL_BE_FINE, whenReceivedValue -> {throw new NullPointerException("bad things happen"); });
        } catch (RuntimeException ex){
            assertEquals("Exception message should match.",EVERYTHING_WILL_BE_FINE + GivenWhenThen.FAILED, ex.getMessage());
        }

    }

    @Test
    public void testExceptionMessageFromThen(){
        try{
            GivenWhenThen.given(null)
                    .when(value -> null)
                    .then((Consumer<Object>) whenReceivedValue -> { throw new NullPointerException(BAD_THINGS_HAPPEN); });

        } catch (RuntimeException ex){
            assertEquals("Exception message should match.",GivenWhenThen.THEN_FUNCTION_FAILED, ex.getMessage());
        }

        try{
            GivenWhenThen.given(null)
                    .when(value -> null)
                    .then(EVERYTHING_WILL_BE_FINE, (Consumer<Object>) whenReceivedValue -> { throw new NullPointerException(BAD_THINGS_HAPPEN); });
        } catch (RuntimeException ex){
            assertEquals("Exception message should match.",EVERYTHING_WILL_BE_FINE + GivenWhenThen.FAILED, ex.getMessage());
        }

        try{
            GivenWhenThen.given(null)
                    .when(value -> null)
                    .then((Predicate<Object>) whenReceivedValue -> { throw new NullPointerException(BAD_THINGS_HAPPEN); });

        } catch (RuntimeException ex){
            assertEquals("Exception message should match.",BAD_THINGS_HAPPEN, ex.getMessage());
        }

        try{
            GivenWhenThen.given(null)
                    .when(value -> null)
                    .then(whenReceivedValue -> false);
        } catch (RuntimeException ex){
            assertEquals("Exception message should match.", GivenWhenThen.THEN_NOT_SATISFIED, ex.getMessage());
        }

    }

    @Test(expected=RuntimeException.class)
    public void testExceptionFromGivenFuture(){
        GivenWhenThen.given(executor.submit(() ->{ throw new RuntimeException("future will fail"); }));
    }

    @Test
    public void testExceptionMessageFromGivenFuture(){
        try{
            GivenWhenThen.given(executor.submit(() ->{ throw new RuntimeException("future will fail"); }));
        } catch (RuntimeException ex){
            assertEquals("Exception message should match.", GivenWhenThen.FUTURE_FAILED, ex.getMessage());
        }
    }
}


text:
begin
  require 'berkshelf'
rescue LoadError
  raise ChefSpec::Error::GemLoadError.new(gem: 'berkshelf', name: 'Berkshelf')
end

module ChefSpec
  class Berkshelf
    class << self
      extend Forwardable
      def_delegators :instance, :setup!, :teardown!
    end

    include Singleton

    def initialize
      @tmpdir = Dir.mktmpdir
    end

    #
    # Setup and install the necessary dependencies in the temporary directory.
    #
    def setup!
      berksfile = ::Berkshelf::Berksfile.from_file('Berksfile')

      # Grab a handle to tmpdir, since Berkshelf 2 modifies it a bit
      tmpdir = File.join(@tmpdir, 'cookbooks')

      ::Berkshelf.ui.mute do
        if ::Berkshelf::Berksfile.method_defined?(:vendor)
          # Berkshelf 3.0 requires the directory to not exist
          FileUtils.rm_rf(tmpdir)
          berksfile.vendor(tmpdir)
        else
          berksfile.install(path: tmpdir)
        end
      end

      filter = Coverage::BerkshelfFilter.new(berksfile)
      Coverage.add_filter(filter)

      ::RSpec.configure { |config| config.cookbook_path = tmpdir }
    end

    #
    # Destroy the installed Berkshelf at the temporary directory.
    #
    def teardown!
      FileUtils.rm_rf(@tmpdir) if File.exist?(@tmpdir)
    end
  end
end

RSpec.configure do |config|
  config.before(:suite) { ChefSpec::Berkshelf.setup! }
  config.after(:suite)  { ChefSpec::Berkshelf.teardown! }
end


text:
UIListViewTest_Vertical_Editor::UIListViewTest_Vertical_Editor()
: _displayValueLabel(nullptr)
{

}

UIListViewTest_Vertical_Editor::~UIListViewTest_Vertical_Editor()
{

}

void UIListViewTest_Vertical_Editor::switchLoadMethod(cocos2d::Ref *pSender)
{
    MenuItemToggle *item = (MenuItemToggle*)pSender;

    if (item->getSelectedIndex() == 0){
        _layout->removeFromParentAndCleanup(true);

        _layout = static_cast<Layout*>(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("cocosui/UIEditorTest/UIListView_Editor/UIListView_Vertical_Editor/ui_listview_editor_1.json"));
        _touchGroup->addChild(_layout);

        this->configureGUIScene();
    }else{
        _layout->removeFromParentAndCleanup(true);

        _layout = static_cast<Layout*>(cocostudio::GUIReader::getInstance()->widgetFromBinaryFile("cocosui/UIEditorTest/UIListView_Editor/UIListView_Vertical_Editor/ui_listview_editor_1.csb"));
        _touchGroup->addChild(_layout);

        this->configureGUIScene();
    }
}

void UIListViewTest_Vertical_Editor::configureGUIScene()
{
    Size screenSize = CCDirector::getInstance()->getWinSize();
    Size rootSize = _layout->getContentSize();
    _touchGroup->setPosition(Vec2((screenSize.width - rootSize.width) / 2,
                                  (screenSize.height - rootSize.height) / 2));

    Layout* root = static_cast<Layout*>(_layout->getChildByName("root_Panel"));

    Text* back_label = static_cast<Text*>(Helper::seekWidgetByName(root, "back"));
    back_label->addTouchEventListener(CC_CALLBACK_2(UIScene_Editor::toGUIEditorTestScene,this));

    _sceneTitle = static_cast<Text*>(Helper::seekWidgetByName(root, "UItest"));

    //        ListView* listView = static_cast<ListView*>(UIHelper::seekWidgetByName(root, "ListView_1214"));
    //        CCLOG("listView isBounceEnabled = %d", listView->isBounceEnabled());

    Button* left_button = Button::create();
    left_button->loadTextures("Images/b1.png", "Images/b2.png", "");
    left_button->setPosition(Vec2(_layout->getContentSize().width / 2 - left_button->getContentSize().width,
                                  left_button->getContentSize().height * 0.625));
    left_button->setTouchEnabled(true);
    left_button->addTouchEventListener(CC_CALLBACK_2(UIScene_Editor::previousCallback,this));

    left_button->setLocalZOrder(_layout->getLocalZOrder() + 1);
    _layout->addChild(left_button);

    Button* right_button = Button::create();
    right_button->loadTextures("Images/f1.png", "Images/f2.png", "");
    right_button->setPosition(Vec2(_layout->getContentSize().width / 2 + right_button->getContentSize().width,
                                   right_button->getContentSize().height * 0.625));
    right_button->setTouchEnabled(true);
    right_button->setLocalZOrder(_layout->getLocalZOrder() + 1);
    right_button->addTouchEventListener(CC_CALLBACK_2(UIScene_Editor::nextCallback,this));
    _layout->addChild(right_button);

}

bool UIListViewTest_Vertical_Editor::init()
{
    if (UIScene_Editor::init())
    {
        _layout = static_cast<Layout*>(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("cocosui/UIEditorTest/UIListView_Editor/UIListView_Vertical_Editor/ui_listview_editor_1.json"));
        _touchGroup->addChild(_layout);
        this->configureGUIScene();

        return true;
    }

    return false;
}

// UIListViewTest_Horizontal_Editor

UIListViewTest_Horizontal_Editor::UIListViewTest_Horizontal_Editor()
: _displayValueLabel(nullptr)
{

}

void UIListViewTest_Horizontal_Editor::switchLoadMethod(cocos2d::Ref *pSender)
{
    MenuItemToggle *item = (MenuItemToggle*)pSender;

    if (item->getSelectedIndex() == 0){
        _layout->removeFromParentAndCleanup(true);

        _layout = static_cast<Layout*>(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("cocosui/UIEditorTest/UIListView_Editor/UIListView_Horizontal_Editor/ui_listview_horizontal_editor_1.json"));
        _touchGroup->addChild(_layout);

        this->configureGUIScene();
    }else{
        _layout->removeFromParentAndCleanup(true);

        _layout = static_cast<Layout*>(cocostudio::GUIReader::getInstance()->widgetFromBinaryFile("cocosui/UIEditorTest/UIListView_Editor/UIListView_Horizontal_Editor/ui_listview_horizontal_editor_1.csb"));
        _touchGroup->addChild(_layout);

        this->configureGUIScene();
    }
}

void UIListViewTest_Horizontal_Editor::configureGUIScene()
{
    Size screenSize = CCDirector::getInstance()->getWinSize();
    Size rootSize = _layout->getContentSize();
    _touchGroup->setPosition(Vec2((screenSize.width - rootSize.width) / 2,
                                  (screenSize.height - rootSize.height) / 2));

    Layout* root = static_cast<Layout*>(_layout->getChildByName("root_Panel"));

    Text* back_label = static_cast<Text*>(Helper::seekWidgetByName(root, "back"));
    back_label->addTouchEventListener(CC_CALLBACK_2(UIScene_Editor::toGUIEditorTestScene,this));

    _sceneTitle = static_cast<Text*>(Helper::seekWidgetByName(root, "UItest"));

    Button* left_button = Button::create();
    left_button->loadTextures("Images/b1.png", "Images/b2.png", "");
    left_button->setPosition(Vec2(_layout->getContentSize().width / 2 - left_button->getContentSize().width,
                                  left_button->getContentSize().height * 0.625));
    left_button->setTouchEnabled(true);
    left_button->addTouchEventListener(CC_CALLBACK_2(UIScene_Editor::previousCallback,this));
    left_button->setLocalZOrder(_layout->getLocalZOrder() + 1);
    _layout->addChild(left_button);

    Button* right_button = Button::create();
    right_button->loadTextures("Images/f1.png", "Images/f2.png", "");
    right_button->setPosition(Vec2(_layout->getContentSize().width / 2 + right_button->getContentSize().width,
                                   right_button->getContentSize().height * 0.625));
    right_button->setTouchEnabled(true);
    right_button->setLocalZOrder(_layout->getLocalZOrder() + 1);
    right_button->addTouchEventListener(CC_CALLBACK_2(UIScene_Editor::nextCallback, this));
    _layout->addChild(right_button);

}

UIListViewTest_Horizontal_Editor::~UIListViewTest_Horizontal_Editor()
{

}

bool UIListViewTest_Horizontal_Editor::init()
{
    if (UIScene_Editor::init())
    {
        _layout = static_cast<Layout*>(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("cocosui/UIEditorTest/UIListView_Editor/UIListView_Horizontal_Editor/ui_listview_horizontal_editor_1.json"));
        _touchGroup->addChild(_layout);

        this->configureGUIScene();
        return true;
    }

    return false;
}


text:
@extends('cmauth::emails.userMailTemplate')

@section('icerikHeader')
	{!! trans('cmauth::emails.pwdresettitle') !!}
@stop

@section('icerikUst')
	{!! trans('cmauth::emails.pwdresetheader', ['minutes' => Config::get('auth.reminder.expire', 60)]) !!}
@stop

@section('icerikDugme')
	{!! trans('cmauth::emails.resetpassword') !!}
@stop

@section('icerikAlt')
	{!! trans('cmauth::emails.pwdresetfooter', ['url' => URL::to('password/reset', array($token))]) !!}
@stop


text:
#ifndef GCBIPROTOCOL_H
#define GCBIPROTOCOL_H

//
// CGCBIProtocol
//

#define GCBI_HEADER_CONSTANT		249

#define REJECTGCBI_INVALID			1
#define REJECTGCBI_NOTFOUND			2

class CIncomingGarenaUser;

class CGCBIProtocol
{
public:
	enum Protocol {
		GCBI_INIT				= 1
	};

	CGCBIProtocol( );
	~CGCBIProtocol( );

	// receive functions
	CIncomingGarenaUser *RECEIVE_GCBI_INIT( BYTEARRAY data );

	// send functions

	// other functions

private:
	bool AssignLength( BYTEARRAY &content );
	bool ValidateLength( BYTEARRAY &content );
};

//
// CIncomingGarenaUser
//

class CIncomingGarenaUser
{
private:
	uint32_t m_IP;
	uint32_t m_UserID;
	uint32_t m_RoomID;
	uint32_t m_UserExp;
	string m_CountryCode;

public:
	CIncomingGarenaUser( uint32_t nIP, uint32_t nUserID, uint32_t nRoomID, uint32_t nUserExp, string nCountryCode );
	~CIncomingGarenaUser( );

	uint32_t GetIP( ) { return m_IP; }
	uint32_t GetUserID( ) { return m_UserID; }
	uint32_t GetRoomID( ) { return m_RoomID; }
	uint32_t GetUserExp( ) { return m_UserExp; }
	string GetCountryCode( ) { return m_CountryCode; }
};

#endif


text:
package org.asynchttpclient.util;

import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static org.asynchttpclient.util.MiscUtils.*;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.List;

import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.Param;
import org.asynchttpclient.Request;
import org.asynchttpclient.uri.Uri;

/**
 * {@link org.asynchttpclient.AsyncHttpClient} common utilities.
 */
public class HttpUtils {

    public static final IOException REMOTELY_CLOSED_EXCEPTION = buildStaticIOException("Remotely closed");
    public static final IOException CHANNEL_CLOSED_EXCEPTION = buildStaticIOException("Channel closed");

    public final static Charset DEFAULT_CHARSET = ISO_8859_1;

    public static final void validateSupportedScheme(Uri uri) {
        final String scheme = uri.getScheme();
        if (scheme == null || !scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https") && !scheme.equalsIgnoreCase("ws") && !scheme.equalsIgnoreCase("wss")) {
            throw new IllegalArgumentException("The URI scheme, of the URI " + uri + ", must be equal (ignoring case) to 'http', 'https', 'ws', or 'wss'");
        }
    }

    public final static String getBaseUrl(Uri uri) {
        return uri.getScheme() + "://" + getAuthority(uri);
    }

    public final static String getAuthority(Uri uri) {
        int port = uri.getPort() != -1 ? uri.getPort() : uri.getExplicitPort();
        return uri.getHost() + ":" + port;
    }

    public final static boolean isSameBase(Uri uri1, Uri uri2) {
        return uri1.getScheme().equals(uri2.getScheme()) && uri1.getHost().equals(uri2.getHost()) && uri1.getExplicitPort() == uri2.getExplicitPort();
    }

    /**
     * @param uri the uri
     * @return the raw path or "/" if it's null
     */
    public final static String getNonEmptyPath(Uri uri) {
        return isNonEmpty(uri.getPath()) ? uri.getPath() : "/";
    }

    public static Charset parseCharset(String contentType) {
        for (String part : contentType.split(";")) {
            if (part.trim().startsWith("charset=")) {
                String[] val = part.split("=");
                if (val.length > 1) {
                    String charset = val[1].trim();
                    // Quite a lot of sites have charset="CHARSET",
                    // e.g. charset="utf-8". Note the quotes. This is
                    // not correct, but client should be able to handle
                    // it (all browsers do, Grizzly strips it by default)
                    // This is a poor man's trim("\"").trim("'")
                    String charsetName = charset.replaceAll("\"", "").replaceAll("'", "");
                    return Charset.forName(charsetName);
                }
            }
        }
        return null;
    }

    public static int requestTimeout(AsyncHttpClientConfig config, Request request) {
        return request.getRequestTimeout() != 0 ? request.getRequestTimeout() : config.getRequestTimeout();
    }

    public static boolean followRedirect(AsyncHttpClientConfig config, Request request) {
        return request.getFollowRedirect() != null ? request.getFollowRedirect().booleanValue() : config.isFollowRedirect();
    }

    private static StringBuilder urlEncodeFormParams0(List<Param> params) {
        StringBuilder sb = StringUtils.stringBuilder();
        for (Param param : params) {
            encodeAndAppendFormParam(sb, param.getName(), param.getValue());
        }
        sb.setLength(sb.length() - 1);
        return sb;
    }

    public static ByteBuffer urlEncodeFormParams(List<Param> params, Charset charset) {
        return StringUtils.charSequence2ByteBuffer(urlEncodeFormParams0(params), charset);
    }

    private static void encodeAndAppendFormParam(final StringBuilder sb, final CharSequence name, final CharSequence value) {
        Utf8UrlEncoder.encodeAndAppendFormElement(sb, name);
        if (value != null) {
            sb.append('=');
            Utf8UrlEncoder.encodeAndAppendFormElement(sb, value);
        }
        sb.append('&');
    }

    public static String hostHeader(Request request, Uri uri) {
        String virtualHost = request.getVirtualHost();
        if (virtualHost != null)
            return virtualHost;
        else {
            String host = uri.getHost();
            int port = uri.getPort();
            return port == -1 || port == uri.getSchemeDefaultPort() ? host : host + ":" + port;
        }
    }
}


text:
package org.apache.accumulo.test;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.junit.Test;

public class ZooKeeperPropertiesIT extends AccumuloClusterHarness {

  @Test(expected = AccumuloException.class)
  public void testNoFiles() throws Exception {
    Connector conn = getConnector();
    // Should throw an error as this property can't be changed in ZooKeeper
    conn.instanceOperations().setProperty(Property.GENERAL_RPC_TIMEOUT.getKey(), "60s");
  }

}


text:
from __future__ import print_function

from eventlet import event as _event

class metaphore(object):
    """This is sort of an inverse semaphore: a counter that starts at 0 and
    waits only if nonzero. It's used to implement a "wait for all" scenario.

    >>> from eventlet import coros, spawn_n
    >>> count = coros.metaphore()
    >>> count.wait()
    >>> def decrementer(count, id):
    ...     print("{0} decrementing".format(id))
    ...     count.dec()
    ...
    >>> _ = spawn_n(decrementer, count, 'A')
    >>> _ = spawn_n(decrementer, count, 'B')
    >>> count.inc(2)
    >>> count.wait()
    A decrementing
    B decrementing
    """

    def __init__(self):
        self.counter = 0
        self.event = _event.Event()
        # send() right away, else we'd wait on the default 0 count!
        self.event.send()

    def inc(self, by=1):
        """Increment our counter. If this transitions the counter from zero to
        nonzero, make any subsequent :meth:`wait` call wait.
        """
        assert by > 0
        self.counter += by
        if self.counter == by:
            # If we just incremented self.counter by 'by', and the new count
            # equals 'by', then the old value of self.counter was 0.
            # Transitioning from 0 to a nonzero value means wait() must
            # actually wait.
            self.event.reset()

    def dec(self, by=1):
        """Decrement our counter. If this transitions the counter from nonzero
        to zero, a current or subsequent wait() call need no longer wait.
        """
        assert by > 0
        self.counter -= by
        if self.counter <= 0:
            # Don't leave self.counter < 0, that will screw things up in
            # future calls.
            self.counter = 0
            # Transitioning from nonzero to 0 means wait() need no longer wait.
            self.event.send()

    def wait(self):
        """Suspend the caller only if our count is nonzero. In that case,
        resume the caller once the count decrements to zero again.
        """
        self.event.wait()


text:
        <form name="sessionForm" ng-submit="save()" class="form-horizontal" novalidate="" role="form">

                    <button type="button" class="close" aria-label="Close" ng-click="$hide()">×</button>

                    <fieldset>

                                Asiakas

                                    <input class="form-control" id="customer" ng-model="session.customerId"
                                           ng-options="customer.id as customer.firstName + ' ' + customer.lastName for customer in customers"
                                           placeholder="Valitse asiakas" bs-typeahead type="text">

                                Alkaen pvm
                                <input class="form-control" id="startDate" ng-model="session.sessionDate"
                                       placeholder="Alkaen" data-time-type="text"
                                       data-date-format="dd.MM.yyyy"
                                       bs-datepicker type="text">

                                Päättyen pvm
                                <input class="form-control" id="untilDate" ng-model="untilDate"
                                       data-min-date="{{sessionDate}}"
                                       placeholder="Päättyen" data-time-type="text"
                                       data-date-format="dd.MM.yyyy"
                                       bs-datepicker type="text">

                                Alkamisaika
                                <input class="form-control" id="startTime" ng-model="session.startTime"
                                       data-time-format="HH:mm"
                                       data-time-type="date" data-autoclose="1" name="startime"
                                       bs-timepicker type="text">

                                Päättymisaika
                                <input class="form-control" id="endTime" ng-model="session.endTime"
                                       data-time-format="HH:mm"
                                       data-time-type="date" data-autoclose="1" name="endTime"
                                       bs-timepicker type="text">

                            <validated-input label="Hinta" property-name="price" ng-model="session.price"
                                             error="errors.price"></validated-input>

                    </fieldset>

                    <button type="button" class="btn btn-default" ng-click="$hide()">Peruuta</button>
                    <button type="button" class="btn btn-primary" ng-click="$saveSession()">Tallenna</button>

        </form>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    Copyright (c) 2012 Hai Bison

    See the file LICENSE at the root directory of this project for copying
    permission.
-->

<resources>

    <dimen name="anhuu_f5be488d_widget_search_view_button_clear_size">60px</dimen>
    <dimen name="anhuu_f5be488d_button_navigators_min_height">60px</dimen>
    <dimen name="anhuu_f5be488d_button_ok_saveas_size">60px</dimen>
    <dimen name="anhuu_f5be488d_thumbnail_size">60px</dimen>
    <dimen name="anhuu_f5be488d_file_icon_size">60px</dimen>

</resources>


text:
<?php

namespace Podcast\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PodcastAdminBundle extends Bundle
{
}


text:
Meteor accounts-tudelft
=======================

TU Delft OAuth login service for Meteor Accounts

## Installation

```
meteor add rmachielse:accounts-tudelft
```

## Usage

You can now login using TU Delft NetID by calling:

```javascript
Meteor.loginWithTudelft();
```

A TU Delft button will also be added to accounts-ui when using

```
{{> loginButtons}}
```

## API & Configuration

For using the TU Delft API and configuring the package, see https://github.com/rmachielse/meteor-tudelft


text:
class Error: public std::exception {
    std::string message;
public:
    Error(const std::string&);
    virtual ~Error() throw();
    virtual const char* what() const throw();
};

#endif // _ERROR_H_


text: Hi, First Check


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('sponsorship', '0021_auto_20180821_1448'),
    ]

    operations = [
        migrations.AddField(
            model_name='sponsorlevel',
            name='display',
            field=models.BooleanField(default=True),
        ),
        migrations.AddField(
            model_name='sponsorpackage',
            name='display',
            field=models.BooleanField(default=True),
        ),
        migrations.AlterField(
            model_name='sponsor',
            name='web_logo',
            field=models.ImageField(help_text='For display on our sponsor webpage. High resolution PNG or JPG, smallest dimension no less than 256px', upload_to=b'sponsor_files', null=True, verbose_name='Web logo'),
        ),
    ]


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

namespace Buildstation_Server.Class
{
    static class ContentLoader
    {
        public static void AddTexture(string SpriteState, string TexturePath)
        {

        }
    }
}


text:
/*jshint node: true*/
/**
 *
 * @author pmeijer / https://github.com/pmeijer
 */

'use strict';

var webgme = require('webgme'),
    Express = require('express'),
    path = require('path'),
    Q = require('q'),
    bodyParser = require('body-parser'),
    mongodb = require('mongodb'),
    binRunPlugin = require('webgme-engine/src/bin/run_plugin'),
    GUID = requireJS('common/util/guid'),
    configDir = path.join(process.cwd(), 'config'),
    gmeConfig = require(configDir),
    componentJson = require(path.join(process.cwd(), 'config', 'components.json')),
    hookConfig = global.constraintCheckerHookConfig || componentJson.ConstraintCheckerHook ||
        require(path.join('..', '..', '..', 'config', 'components.json')).ConstraintCheckerHook,
    HOOK_ID = hookConfig.id,
    logger = webgme.Logger.create('gme:' + HOOK_ID, gmeConfig.bin.log, false);

webgme.addToRequireJsPaths(gmeConfig);

/**
 * @param {string} [options.port] - Port for server
 * @param {string} [options.mongoUri]
 * @constructor
 */
function Handler(options) {
    var app = new Express(),
        db,
        jobQueue = [],
        running = [],
        results = [],
        serverUrl,
        server;

    if (gmeConfig.webhooks.enable !== true) {
        throw new Error('gmeConfig.webhooks.enable must be true in order to dispatch events from the webgme server!');
    }

    options.mongoUri = options.mongoUri || hookConfig.mongoUri;
    options.port = options.port || hookConfig.port;

    function processJobQueue() {
        var job,
            coll;

        if (!hookConfig.maximumConcurrentJobs || running.length < hookConfig.maximumConcurrentJobs) {
            job = jobQueue.shift();

            if (job) {
                running.push(job);
                runPlugin(job.payload)
                    .finally(function () {
                        var j;
                        logger.info('done!!', job.id);

                        for (j = 0; j < running.length; j += 1) {
                            if (running[j].id === job.id) {
                                running.splice(j, 1);
                                break;
                            }
                        }

                        processJobQueue();
                    });
            }
        } else {
            job = jobQueue[jobQueue.length - 1];
            coll = db.collection(job.payload.projectId);
            coll.updateOne({_id: job.payload.data.commitHash},
                {_id: job.payload.data.commitHash, isQueued: true},
                {upsert: true}
            );
        }
    }

    function runPlugin(payload) {
        var args = ['node', 'dummy.js', 'ConstraintChecker', payload.projectName],
            result = {
                payload: payload,
                pluginResult: null,
                exception: null
            };

        results.unshift(result);

        if (results.length > 100) {
            results.pop();
        }

        args = args.concat([
            '-o', payload.owner,
            '-u', payload.data.userId,
            '-c', payload.data.commitHash
        ]);

        return binRunPlugin.main(args)
            .then(function (pluginResult) {
                result.pluginResult = pluginResult;
                if (pluginResult.success === true) {
                    logger.debug('success');
                } else if (pluginResult.error) {
                    logger.error('Unexpected error:');
                    logger.error(JSON.stringify(pluginResult, null, 2));
                } else {
                    logger.debug('constraints not met');
                }
            })
            .catch(function (err) {
                result.exception = err.stack;
                logger.error('EXCEPTION:', err);
            });
    }

    this.start = function (callback) {
        var deferred = Q.defer();
        // Start server and connect to mongodb // connection will be available at global.db.

        app.use(bodyParser.json());

        app.post('/' + HOOK_ID, function (req, res) {
            var payload = req.body;
            logger.debug('hook triggered');
            if (payload.event === 'COMMIT') {
                jobQueue.push({
                    payload: payload,
                    id: GUID()
                });
                processJobQueue();
            } else {
                logger.warn('Unexpected event', JSON.stringify(payload));
            }

            res.sendStatus(200);
        });

        app.get('/' + HOOK_ID + '/:ownerId/:projectName/status/:commitHash', function (req, res, next) {
            var collection = db.collection(req.params.ownerId + '+' + req.params.projectName);
            collection.findOne({_id: '#' + req.params.commitHash})
                .then(function (result) {
                    var status = {
                        exists: false,
                        isRunning: false,
                        metaInconsistent: false,
                        hasViolation: false
                    };

                    if (result) {
                        status.exists = true;
                        status.isRunning = result.isRunning;
                        status.isQueued = result.isQueued;
                        status.metaInconsistent = result.metaInconsistent;
                        status.hasViolation = result.hasViolation;
                    }

                    res.json(status);
                })
                .catch(function (err) {
                    logger.error(err);
                    next(err);
                });
        });

        app.get('/' + HOOK_ID + '/:ownerId/:projectName/result/:commitHash', function (req, res, next) {
            var collection = db.collection(req.params.ownerId + '+' + req.params.projectName);
            collection.findOne({_id: '#' + req.params.commitHash})
                .then(function (result) {
                    if (result) {
                        res.json(result);
                    } else {
                        res.sendStatus(404);
                    }
                })
                .catch(function (err) {
                    logger.error(err);
                    next(err);
                });
        });

        app.get('/' + HOOK_ID + '/status', function (req, res) {
            res.json({
                jobQueue: jobQueue,
                running: running,
                results: results
            });
        });

        server = app.listen(options.port);
        serverUrl = 'http://127.0.0.1:' + options.port;
        logger.info('Webhook listening at:', serverUrl);
        logger.info('Connecting to mongodb at:' + options.mongoUri);

        mongodb.MongoClient.connect(options.mongoUri, hookConfig.mongoOptions)
            .then(function (db_) {
                db = db_;
                global.db = db;
                deferred.resolve({
                    db: db,
                    server: server
                });
            })
            .catch(deferred.reject);

        return deferred.promise.nodeify(callback);
    };

    this.stop = function (callback) {
        var deferred = Q.defer();
        // Shutdown server and disconnect from mongodb.
        if (running.length > 0 || jobQueue.length > 0) {
            logger.warn('Running and queued jobs will be lost', running.length, jobQueue.length);
        }

        if (server) {
            server.close();
            server = null;
        }

        if (db) {
            db.close(function () {
                db = null;
                deferred.resolve();
            });
        } else {
            deferred.resolve();
        }

        global.db = null;

        return deferred.promise.nodeify(callback);
    };

    this.getUrl = function () {
        return serverUrl;
    };
}

module.exports = Handler;


text:
package org.ballerinalang.containers.docker.cmd;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import org.apache.commons.io.FilenameUtils;
import org.ballerinalang.containers.Constants;
import org.ballerinalang.containers.docker.BallerinaDockerClient;
import org.ballerinalang.containers.docker.cmd.validator.DockerHostValidator;
import org.ballerinalang.containers.docker.cmd.validator.DockerImageNameValidator;
import org.ballerinalang.containers.docker.exception.BallerinaDockerClientException;
import org.ballerinalang.containers.docker.impl.DefaultBallerinaDockerClient;
import org.ballerinalang.containers.docker.utils.Utils;
import org.ballerinalang.launcher.BLauncherCmd;
import org.ballerinalang.launcher.LauncherUtils;

import java.io.Console;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Ballerina Command to support Docker based packaging Ballerina packages.
 */
@Parameters(commandNames = "docker", commandDescription = "create docker images for Ballerina program archives")
public class DockerCmd implements BLauncherCmd {

    private static final String BALLERINA_MAIN_PACKAGE_EXTENSION = "bmz";
    private static final String BALLERINA_SERVICE_PACKAGE_EXTENSION = "bsz";
    private static final String DEFAULT_DOCKER_HOST = "localhost";

    private static PrintStream outStream = System.err;
    private JCommander parentCmdParser = null;
    private BallerinaDockerClient dockerClient = new DefaultBallerinaDockerClient();

    @Parameter(arity = 1, description = "package names")
    private List<String> packagePathNames;

    @Parameter(names = {"--tag", "-t"}, validateWith = DockerImageNameValidator.class,
            description = "docker image name. <image-name>:<version>")
    private String dockerImageName;

    @Parameter(names = {"--host", "-H"}, validateWith = DockerHostValidator.class,
            description = "docker Host. http://<ip-address>:<port>")
    private String dockerHost;

    @Parameter(names = {"--help", "-h"}, hidden = true, description = "show usage")
    private boolean helpFlag;

    @Parameter(names = {"--yes", "-y"}, description = "assume yes for prompts")
    private boolean assumeYes;

    /**
     * Create an image name and image version from the given (if) image name and the package names.
     *
     * @param givenImageName The provided image name
     * @param packageName    The provided package name.
     * @return A {@link String} array containing the image name [0] and image version [1].
     */
    private static String[] getImageNameDetails(String givenImageName, String packageName) {
        if (givenImageName != null) {
            givenImageName = givenImageName.toLowerCase(Locale.getDefault());
            if (givenImageName.contains(":")) {
                return givenImageName.split(":");
            } else {
                return new String[]{givenImageName.toLowerCase(Locale.getDefault()), Constants.IMAGE_VERSION_LATEST};
            }
        } else {
            return new String[]{packageName.toLowerCase(Locale.getDefault()), Constants.IMAGE_VERSION_LATEST};
        }
    }

    @Override
    public void execute() {
        if (helpFlag) {
            String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(parentCmdParser, getName());
            outStream.println(commandUsageInfo);
            return;
        }

        if (packagePathNames == null || packagePathNames.size() == 0) {
            throw LauncherUtils.createUsageException("no ballerina package is provided\n");
        }

        // extract the package name and extension
        String packageCompletePath = packagePathNames.get(0);
        if (!Files.exists(Paths.get(packageCompletePath))) {
            throw LauncherUtils.createUsageException("cannot find ballerina package: " + packageCompletePath);
        }

        String packageName = FilenameUtils.getBaseName(packageCompletePath);
        String packageExtension = FilenameUtils.getExtension(packageCompletePath);
        List<Path> packagePaths = new ArrayList<>();
        packagePaths.add(Paths.get(packageCompletePath));

        String[] imageNameParts = getImageNameDetails(dockerImageName, packageName);
        String imageName = imageNameParts[0];
        String imageVersion = imageNameParts[1];

        if (!assumeYes && !canProceed(imageName, imageVersion)) {
            outStream.println("ballerina: aborting..\n");
            return;
        }

        switch (packageExtension) {
            case BALLERINA_SERVICE_PACKAGE_EXTENSION:
                try {
                    String createdImageName = dockerClient.createServiceImage(packageName, dockerHost,
                            packagePaths, imageName, imageVersion);
                    if (createdImageName != null) {
                        printServiceImageSuccessMessage(createdImageName);
                    } else {
                        throw LauncherUtils.createUsageException("Docker image build failed for image "
                                + imageName + ":" + imageVersion + ".");
                    }
                } catch (BallerinaDockerClientException | IOException | InterruptedException e) {
                    throw LauncherUtils.createUsageException(e.getMessage());
                }
                break;

            case BALLERINA_MAIN_PACKAGE_EXTENSION:
                try {
                    String createdImageName = dockerClient.createMainImage(packageName, dockerHost, packagePaths,
                            imageName, imageVersion);
                    if (createdImageName != null) {
                        printMainImageSuccessMessage(createdImageName);
                    } else {
                        throw LauncherUtils.createUsageException("Docker image build failed for image "
                                + imageName + ":" + imageVersion + ".");
                    }
                } catch (BallerinaDockerClientException | IOException | InterruptedException e) {
                    throw LauncherUtils.createUsageException(e.getMessage());
                }
                break;

            default:
                throw LauncherUtils.createUsageException("invalid package extension\n");
        }
    }

    @Override
    public String getName() {
        return "docker";
    }

    @Override
    public void printUsage(StringBuilder out) {
        out.append("ballerina docker <package-name> [--tag | -t <image-name>] [--host | -H <docker-hostURL>] " +
                "--help | -h --yes | -y\n");
    }

    @Override
    public void setParentCmdParser(JCommander parentCmdParser) {
        this.parentCmdParser = parentCmdParser;
    }

    @Override
    public void setSelfCmdParser(JCommander selfCmdParser) {
    }

    /**
     * Prompt user to continue Docker image building.
     *
     * @param imageName    Name of the image to be built.
     * @param imageVersion Version of the image to be built
     * @return True if confirmed, false if aborted or exceeded attempts.
     */
    private boolean canProceed(String imageName, String imageVersion) {
        Console console = System.console();
        String choice;
        String dockerHostToPrint = (dockerHost != null) ? dockerHost : DEFAULT_DOCKER_HOST;

        int attempts = 3;
        do {
            choice = console.readLine("Build docker image [" + imageName + ":" + imageVersion
                    + "] in docker host [" + dockerHostToPrint + "]? (y/n): ");

            if (choice.equalsIgnoreCase("y")) {
                return true;
            }

            if (choice.equalsIgnoreCase("n")) {
                return false;
            }

        } while (--attempts > 0);

        return false;
    }

    /*
    Print helpful messages for functionality to perform after image build for a Ballerina Service.
     */
    private void printServiceImageSuccessMessage(String imageName) {
        String containerName = Utils.generateContainerName();
        int portNumber = Utils.generateContainerPort();
        outStream.println("\nDocker image " + imageName + " successfully built.");
        outStream.println();
        outStream.println("Use the following command to start a container.");
        outStream.println("\tdocker run -p " + portNumber + ":9090 --name " + containerName + " -d " + imageName);
        outStream.println();
        outStream.println("Use the following command to inspect the logs.");
        outStream.println("\tdocker logs " + containerName);
        outStream.println();
        outStream.println("Use the following command to retrieve the IP address of the container");
        outStream.println("\tdocker inspect " + containerName + " | grep IPAddress");
        outStream.println();
        outStream.println("Ballerina service will be running on the following ports.");
        outStream.println("\thttp://localhost:" + portNumber);
        outStream.println("\thttp://<container-ip>:9090");
        outStream.println();
        outStream.println("Make requests using the format [curl -X <http-method> http://localhost:" + portNumber
                + "/<service-name>]");
        outStream.println();
    }

    /*
    Print helpful messages for functionality to perform after image build for a Ballerina Main program.
     */
    private void printMainImageSuccessMessage(String imageName) {
        String containerName = Utils.generateContainerName();
        outStream.println("\nDocker image " + imageName + " successfully built.");
        outStream.println("\nUse the following command to execute the archive in a container.");
        outStream.println("\tdocker run --name " + containerName + " -it " + imageName);
        outStream.println();
    }
}


text:
#include "txt/test_font_manager.h"
#include "flutter/fml/logging.h"

namespace txt {

TestFontManager::TestFontManager(
    std::unique_ptr<FontAssetProvider> font_provider,
    std::string test_font_family_name)
    : AssetFontManager(std::move(font_provider)),
      test_font_family_name_(test_font_family_name) {}

TestFontManager::~TestFontManager() = default;

SkFontStyleSet* TestFontManager::onMatchFamily(const char family_name[]) const {
  return AssetFontManager::onMatchFamily(test_font_family_name_.c_str());
}

}  // namespace txt


text:
package de.mirakon.java.mazegrapher.main;

import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.Injectable;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class StringsTest {

    // http://stackoverflow.com/questions/38797588/verify-that-a-private-method-was-not-executed-jmockit

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Injectable
    private ResourceBundle mockedStrings;

    /**
     * {@link Strings#getString(String)}
     *

     * case: {@code strings != null}
     */
    @Test
    public void getStringKeyV1() throws Exception {
        String key = "a key";
        String value = "string for given key";
        Deencapsulation.setField(Strings.class, "strings", mockedStrings);

        new StringsTestExpectations(key, value, 0, 1);

        String result = Strings.getString(key);
        assertThat(result, is(value));
    }

    /**
     * {@link Strings#getString(String)}
     *

     * case: {@code strings == null}
     */
    @Test
    @Ignore
    public void getStringKeyV2() throws Exception {
        String key = "a key";
        String value = "string for given key";

        Deencapsulation.setField(Strings.class, "strings", null);

        new Expectations(Strings.class) {
            {
                Deencapsulation.invoke(Strings.class, "loadStringResources");
                times = 1;
                Deencapsulation.setField(Strings.class, "strings", mockedStrings);
                mockedStrings.getString(key);
                result = value;
            }
        };

        String result = Strings.getString(key);
        assertThat(result, is(value));
    }

    /**
     * {@link Strings#getString(String)}
     *

     * case: {@code strings != null} & no value for the given key
     */
    @Test
    public void getStringKeyV3(@Injectable MissingResourceException e) throws Exception {

        String key = "a key";
        String value = "string for given key";
        Deencapsulation.setField(Strings.class, "strings", mockedStrings);

        new StringsTestExpectations(key, e, 0, 1);

        expectedException.expect(is(e));

        Strings.getString(key);
    }

    @Test
    public void getStringKeyAndValuesV1() throws Exception {

    }

    private final class StringsTestExpectations extends Expectations {
        StringsTestExpectations(String key, Object value, int loadStringResourcesTimes, int
                getStringTimes) {
            super(Strings.class);
            {
                Deencapsulation.invoke(Strings.class, "loadStringResources");
                times = loadStringResourcesTimes;
                mockedStrings.getString(key);
                result = value;
                times = getStringTimes;
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SharpKit.Compiler
{
    static class CssCompressorExtensions
    {
        public static int AppendReplacement(this Capture capture,
                                            StringBuilder value,
                                            string input,
                                            string replacement,
                                            int index)
        {
            string preceding = input.Substring(index,
                                               capture.Index - index);

            value.Append(preceding);
            value.Append(replacement);

            return capture.Index + capture.Length;
        }

        public static void AppendTail(this StringBuilder value,
                                      string input,
                                      int index)
        {
            value.Append(input.Substring(index));
        }

        public static string RegexReplace(this string input,
                                          string pattern,
                                          string replacement)
        {
            return Regex.Replace(input, pattern, replacement);
        }

        public static string RegexReplace(this string input,
                                          string pattern,
                                          string replacement,
                                          RegexOptions options)
        {
            return Regex.Replace(input,
                                 pattern,
                                 replacement,
                                 options);
        }

        public static string Fill(this string format,
                                  params object[] args)
        {
            return String.Format(CultureInfo.InvariantCulture,
                                 format,
                                 args);
        }

        public static string RemoveRange(this string input,
                                         int startIndex,
                                         int endIndex)
        {
            return input.Remove(startIndex,
                                endIndex - startIndex);
        }

        public static bool EqualsIgnoreCase(this string left,
                                            string right)
        {
            return String.Compare(left,
                                  right,
                                  StringComparison.OrdinalIgnoreCase) == 0;
        }

        // NOTE: To check out some decimal -> Hex converstions,
        //       goto http://www.openstrike.co.uk/cgi-bin/decimalhex.cgi
        public static string ToHexString(this int value)
        {
            return value.ToString("X");
        }

        public static string ToPluralString(this int value)
        {
            return value == 1 ? string.Empty : "s";
        }

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> value)
        {
            return value == null ||
                   value.Count() <= 0
                       ? true
                       : false;
        }

        public static IList<T> ToListIfNotNullOrEmpty<T>(this IList<T> value)
        {
            return value.IsNullOrEmpty() ? null : value;
        }

        public static string Replace(this string value, int startIndex, int endIndex, string newContent)
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("value");
            }

            // Chop the string into two parts, the before and then the after.
            string before = value.Substring(0, startIndex);
            string after = value.Substring(endIndex);
            return before + newContent + after;
        }
    }
}


text:
/**
文件删除 Exception
Author:GongChunQuan
Date:2003.05.16
*/

package com.frameworkset.platform.cms.util;

public class FileDelException extends FileOperException implements java.io.Serializable
{

}


text:
package davidkellis.seven.domain

import davidkellis.seven.domain.CoreTypes.Decimal
import java.time.ZonedDateTime

trait QuotationService {
  def bid(security: Security, time: ZonedDateTime): Option[Decimal]
  def ask(security: Security, time: ZonedDateTime): Option[Decimal]

  def market(buyOrSell: OrderAction, security: Security, time: ZonedDateTime): Option[Decimal] = buyOrSell match {
    case Buy | BuyToCover => ask(security, time)    // In our simplified world, a market buy order would buy at the ask price
    case Sell | SellShort => bid(security, time)    // In our simplified world, a market sell order would sell at the bid price
  }
}

class SimpleQuotationService() extends QuotationService {
  def bid(security: Security, time: ZonedDateTime): Option[Decimal] = ???

  def ask(security: Security, time: ZonedDateTime): Option[Decimal] = ???
}


text:
title: Fansoro 1.0.0
date: 2014-01-18 16:00
template: blog_post
author:
  name: Sergey Romanenko
---

Hello Everyone :)
I am happy to introduce Fansoro CMS 1.0.0 :)

Download: [Fansoro 1.0.0](https://github.com/fansoro/fansoro/archive/v1.0.0.zip)

[ Discuss this article on the Gitter Chat](https://gitter.im/fansoro/fansoro)


text:
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/dist/";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({

/***/ 0:
/***/ function(module, exports, __webpack_require__) {

	module.exports = __webpack_require__(326);

/***/ },

/***/ 3:
/***/ function(module, exports) {

	module.exports = function normalizeComponent (
	  rawScriptExports,
	  compiledTemplate,
	  scopeId,
	  cssModules
	) {
	  var esModule
	  var scriptExports = rawScriptExports = rawScriptExports || {}

	  // ES6 modules interop
	  var type = typeof rawScriptExports.default
	  if (type === 'object' || type === 'function') {
	    esModule = rawScriptExports
	    scriptExports = rawScriptExports.default
	  }

	  // Vue.extend constructor export interop
	  var options = typeof scriptExports === 'function'
	    ? scriptExports.options
	    : scriptExports

	  // render functions
	  if (compiledTemplate) {
	    options.render = compiledTemplate.render
	    options.staticRenderFns = compiledTemplate.staticRenderFns
	  }

	  // scopedId
	  if (scopeId) {
	    options._scopeId = scopeId
	  }

	  // inject cssModules
	  if (cssModules) {
	    var computed = options.computed || (options.computed = {})
	    Object.keys(cssModules).forEach(function (key) {
	      var module = cssModules[key]
	      computed[key] = function () { return module }
	    })
	  }

	  return {
	    esModule: esModule,
	    exports: scriptExports,
	    options: options
	  }
	}

/***/ },

/***/ 326:
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _tag = __webpack_require__(327);

	var _tag2 = _interopRequireDefault(_tag);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	/* istanbul ignore next */
	_tag2.default.install = function (Vue) {
	  Vue.component(_tag2.default.name, _tag2.default);
	};

	exports.default = _tag2.default;

/***/ },

/***/ 327:
/***/ function(module, exports, __webpack_require__) {

	var Component = __webpack_require__(3)(
	  /* script */
	  __webpack_require__(328),
	  /* template */
	  __webpack_require__(329),
	  /* scopeId */
	  null,
	  /* cssModules */
	  null
	)

	module.exports = Component.exports

/***/ },

/***/ 328:
/***/ function(module, exports) {

	'use strict';

	exports.__esModule = true;
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//

	exports.default = {
	  name: 'ElTag',
	  props: {
	    text: String,
	    closable: Boolean,
	    type: String,
	    hit: Boolean,
	    closeTransition: Boolean,
	    color: String
	  },
	  methods: {
	    handleClose: function handleClose(event) {
	      this.$emit('close', event);
	    }
	  }
	};

/***/ },

/***/ 329:
/***/ function(module, exports) {

	module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
	  return _c('transition', {
	    attrs: {
	      "name": _vm.closeTransition ? '' : 'el-zoom-in-center'
	    }
	  }, [_c('span', {
	    staticClass: "el-tag",
	    class: [_vm.type ? 'el-tag--' + _vm.type : '', {
	      'is-hit': _vm.hit
	    }],
	    style: ({
	      backgroundColor: _vm.color
	    })
	  }, [_vm._t("default"), (_vm.closable) ? _c('i', {
	    staticClass: "el-tag__close el-icon-close",
	    on: {
	      "click": _vm.handleClose
	    }
	  }) : _vm._e()], 2)])
	},staticRenderFns: []}

/***/ }

/******/ });