text:
package org.unileipzig.persistence.nlp2rdf.ontologies.nifcore;

import static java.util.Collections.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jlss.JsonException;
import jlss.javajson.*;

/**
 * Automatically generated POJOs for ontology at http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#String.
 * DO NOT EDIT!
 */
public class String_ {
    private final Set<String_> subString = new HashSet<String_>();

    public Set<String_> getSubString() {
        return unmodifiableSet(this.subString);
    }

    public void setSubString(Set<String_> subString) {
        this.subString.clear();
        this.subString.addAll(subString);
    }

    public void addSubString(String_ subString) {
        this.subString.add(subString);
    }

    public boolean removeSubString(String_ subString) {
        return this.subString.remove(subString);
    }
    private final Set<String> anchorOf = new HashSet<String>();

    public Set<String> getAnchorOf() {
        return unmodifiableSet(this.anchorOf);
    }

    public void setAnchorOf(Set<String> anchorOf) {
        this.anchorOf.clear();
        this.anchorOf.addAll(anchorOf);
    }

    public void addAnchorOf(String anchorOf) {
        this.anchorOf.add(anchorOf);
    }

    public boolean removeAnchorOf(String anchorOf) {
        return this.anchorOf.remove(anchorOf);
    }

    public JSONObject toJSON() {
        return toJSON(DefaultJSONFactory.newInstance(), null);
    }

    public JSONObject toJSON(JSONFactory factory, String contextURI) {
        final JSONFactory.JSONObjectBuilder fields = factory.startObject();
        if(contextURI != null) {
            fields.put("@context", factory.mkString(contextURI));
        }

        {
            if(!getSubString().isEmpty()) {
                final JSONFactory.JSONArrayBuilder elements = factory.startArray();
                for(String_ elem : getSubString()) {
                    elements.add(elem == null ? factory.mkNull() : elem.toJSON());
                }
                fields.put("subString", elements.end());
            }
        }
        {
            if(!getAnchorOf().isEmpty()) {
                final JSONFactory.JSONArrayBuilder elements = factory.startArray();
                for(String elem : getAnchorOf()) {
                    elements.add(factory.mkString(elem));
                }
                fields.put("anchorOf", elements.end());
            }
        }

        return fields.end();
    }

    public static String_ fromJSON(JSONObject json) {
        final String_ object = new String_();

        while(json.hasNext()) {
            final JSONObject.JSONField field = json.next();
            if(field.key.equals("subString")) {
                if(!(field.value instanceof JSONArray)) {
                    throw new JsonException("subString should be an array but was " + field.value);
                }
                final JSONArray array = (JSONArray)field.value;
                while(array.hasNext()) {
                    final JSON value = array.next();

                    if(value instanceof JSONNull) {
                        object.addSubString(null);
                    }
                    if(!(value instanceof JSONObject)) {
                        throw new JsonException("subString should be an object or null but was " + value);
                    }
                    object.addSubString(String_.fromJSON((JSONObject)value));
                }
            }
            if(field.key.equals("anchorOf")) {
                if(!(field.value instanceof JSONArray)) {
                    throw new JsonException("anchorOf should be an array but was " + field.value);
                }
                final JSONArray array = (JSONArray)field.value;
                while(array.hasNext()) {
                    final JSON value = array.next();

                    if(!(value instanceof JSONString)) {
                        throw new JsonException("anchorOf should be a string but was " + value);
                    }
                    object.addAnchorOf(((JSONString)value).value());
                }
            }
        }

        return object;
    }
}


text:
"use strict";
var ts = require("typescript");
// https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
function escapeTypescriptPropertyName(str) {
    return isValidTypescriptIdentifier(str) ? str : JSON.stringify(str);
}
exports.escapeTypescriptPropertyName = escapeTypescriptPropertyName;
// TODO: these are made up lists. check the grammar
var tsKeywords = 'type class interface break case catch continue debugger default delete do else finally for function if in instanceof new return switch this throw try typeof var void while with'.split(' ');
var digitCodesL = "0".charCodeAt(0);
var digitCodesR = "9".charCodeAt(0);
var lowerCaseCodesL = "a".charCodeAt(0);
var lowerCaseCodesR = "z".charCodeAt(0);
var upperCaseCodesL = "A".charCodeAt(0);
var upperCaseCodesR = "Z".charCodeAt(0);
var digitChars = {}; //:boolean[] = []
var validChars = {}; //:boolean[] = []
//for(var i = 0 ; i < 128 ; i++){
//    digitCodes.push(false)
//    validCodes.push(false)
//}
for (var i = digitCodesL, end = digitCodesR; i <= end; i++) {
    digitChars[String.fromCharCode(i)] = true;
    validChars[String.fromCharCode(i)] = true;
}
for (var i = lowerCaseCodesL, end = lowerCaseCodesR; i <= end; i++) {
    validChars[String.fromCharCode(i)] = true;
}
for (var i = upperCaseCodesL, end = upperCaseCodesR; i <= end; i++) {
    validChars[String.fromCharCode(i)] = true;
}
"_ $".split(" ").forEach(function (x) { return validChars[x] = true; });
function isValidTypescriptIdentifier(str) {
    str = str.trim();
    if (str.length == 0) {
        return false;
    }
    if (tsKeywords.indexOf(str) >= 0) {
        return false;
    }
    if (digitChars[str.charAt(0)]) {
        return false;
    }
    for (var i = 0; i < str.length; i++) {
        if (!validChars[str.charAt(i)]) {
            return false;
        }
    }
    return true;
}
exports.isValidTypescriptIdentifier = isValidTypescriptIdentifier;
function escapeToIdentifier(str) {
    str = str.trim();
    var result = '';
    if (str.length > 0 && digitChars[str.charAt(0)]) {
        result += '_';
    }
    for (var i = 0; i < str.length; i++) {
        var ch = str.charAt(i);
        if (validChars[ch]) {
            result += ch;
        }
        else {
            result += '_';
        }
    }
    return result;
}
exports.escapeToIdentifier = escapeToIdentifier;
// Note: this uses ts.formatting which is part of the typescript 1.4 package but is not currently
//       exposed in the public typescript.d.ts. The typings should be exposed in the next release.
function format(text) {
    var options = getDefaultOptions();
    // Parse the source text
    var sourceFile = ts.createSourceFile("file.ts", text, ts.ScriptTarget.Latest, true);
    fixupParentReferences(sourceFile);
    // Get the formatting edits on the input sources
    var edits = ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options);
    // Apply the edits on the input code
    return applyEdits(text, edits);
    function getRuleProvider(options) {
        // Share this between multiple formatters using the same options.
        // This represents the bulk of the space the formatter uses.
        var ruleProvider = new ts.formatting.RulesProvider();
        ruleProvider.ensureUpToDate(options);
        return ruleProvider;
    }
    function applyEdits(text, edits) {
        // Apply edits in reverse on the existing text
        var result = text;
        for (var i = edits.length - 1; i >= 0; i--) {
            var change = edits[i];
            var head = result.slice(0, change.span.start);
            var tail = result.slice(change.span.start + change.span.length);
            result = head + change.newText + tail;
        }
        return result;
    }
    function getDefaultOptions() {
        return {
            IndentSize: 4,
            TabSize: 4,
            NewLineCharacter: '\n',
            ConvertTabsToSpaces: true,
            InsertSpaceAfterCommaDelimiter: true,
            InsertSpaceAfterSemicolonInForStatements: true,
            InsertSpaceBeforeAndAfterBinaryOperators: true,
            InsertSpaceAfterKeywordsInControlFlowStatements: true,
            InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
            InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
            PlaceOpenBraceOnNewLineForFunctions: false,
            PlaceOpenBraceOnNewLineForControlBlocks: false
        };
    }
    function fixupParentReferences(sourceFile) {
        var parent = sourceFile;
        function walk(n) {
            n.parent = parent;
            var saveParent = parent;
            parent = n;
            ts.forEachChild(n, walk);
            parent = saveParent;
        }
        ts.forEachChild(sourceFile, walk);
    }
}
exports.format = format;
var typeMap = {
    'string': 'string',
    'integer': 'number',
    'number': 'number',
    'boolean': 'boolean',
    'file': 'string',
    'date': 'string',
    'NumberType': 'number'
};
function ramlType2TSType(ramlType) {
    var tsType = typeMap[ramlType];
    if (!tsType) {
        tsType = 'any';
    }
    return tsType;
}
exports.ramlType2TSType = ramlType2TSType;
function escapeToJavaIdentifier(str) {
    str = escapeToIdentifier(str);
    return exports.javaReservedWords[str] ? str + '_' : str;
}
exports.escapeToJavaIdentifier = escapeToJavaIdentifier;
exports.tsToJavaTypeMap = {
    'number': 'Double',
    'string': 'String',
    'boolean': 'Boolean',
    'any': 'Object'
};
exports.javaReservedWords = {
    "abstract": true,
    "continue": true,
    "for": true,
    "new": true,
    "switch": true,
    "assert": true,
    "default": true,
    "goto": true,
    "package": true,
    "synchronized": true,
    "boolean": true,
    "do": true,
    "if": true,
    "private": true,
    "this": true,
    "break": true,
    "double": true,
    "implements": true,
    "protected": true,
    "throw": true,
    "byte": true,
    "else": true,
    "import": true,
    "public": true,
    "throws": true,
    "case": true,
    "enum": true,
    "instanceof": true,
    "return": true,
    "transient": true,
    "catch": true,
    "extends": true,
    "int": true,
    "short": true,
    "try": true,
    "char": true,
    "final": true,
    "interface": true,
    "static": true,
    "void": true,
    "class": true,
    "finally": true,
    "long": true,
    "strictfp": true,
    "volatile": true,
    "const": true,
    "float": true,
    "native": true,
    "super": true,
    "while": true,
};
//# sourceMappingURL=tsutil.js.map

redpajama_set_name: RedPajamaGithub


text:
#ifndef _HTTPP_UTILS_SORTED_VECTOR_KEY_PAIR_HPP_
#define _HTTPP_UTILS_SORTED_VECTOR_KEY_PAIR_HPP_

#include <algorithm>
#include <cstring>
#include <vector>

namespace HTTPP
{
namespace UTILS
{

struct case_insensitive
{
    template <typename StringLike>
    bool operator()(const StringLike& left, const StringLike& right) const
        noexcept
    {
        if (left.size() < right.size())
        {
            return true;
        }
        else if (left.size() == right.size())
        {
            return ::strncasecmp(left.data(), right.data(), left.size()) < 0;
        }
        else
        {
            return false;
        }
    }
};

template <typename Key, typename Value, typename Comparator = std::less<Key>>
class SortedVectorKP : private std::vector<std::pair<Key, Value>>
{
    using Base = std::vector<std::pair<Key, Value>>;
    using value_type = typename Base::value_type;

    static bool comparator(const value_type& lhs, const value_type& rhs)
    {
        return Comparator()(lhs.first, rhs.first);
    }

public:
    using Base::begin;
    using Base::end;
    using Base::operator[];

    SortedVectorKP(const std::vector<std::pair<Key, Value>>& vector)
    : Base(std::begin(vector), std::end(vector))
    {
        std::sort(begin(), end(), &comparator);
    }

    Value const& find(const Key& key) const
    {
        const value_type value{key, not_found_};
        auto it = std::lower_bound(begin(), end(), value, &comparator);

        if (it != end() && !comparator(value, *it))
        {
            return it->second;
        }

        return not_found_;
    }

    Value const& operator[](const Key& key) const
    {
        return find(key);
    }

private:
    static const Value not_found_;
};

template <typename K, typename V, typename C = std::less<K>>
SortedVectorKP<K, V, C>
create_sorted_vector(const std::vector<std::pair<K, V>>& vector)
{
    return SortedVectorKP<K, V, C>(vector);
}

template <typename K, typename V, typename C>
const V SortedVectorKP<K, V, C>::not_found_{};

} // namespace UTILS
} // namespace HTTPP

#endif // !_HTTPP_UTILS_SORTED_VECTOR_KEY_PAIR_HPP_


text:
using namespace std;

namespace coda
{
    namespace db
    {
        namespace sqlite
        {
            resultset::resultset(const std::shared_ptr<sqlite::session> &sess, const shared_ptr<sqlite3_stmt> &stmt)
                : stmt_(stmt), sess_(sess), status_(-1)
            {
                if (sess_ == nullptr) {
                    throw database_exception("No database provided to sqlite3 resultset");
                }

                if (stmt_ == nullptr) {
                    throw database_exception("no statement provided to sqlite3 resultset");
                }
            }

            resultset::resultset(resultset &&other)
                : stmt_(std::move(other.stmt_)), sess_(std::move(other.sess_)), status_(other.status_)
            {
                other.sess_ = nullptr;
                other.stmt_ = nullptr;
            }

            resultset::~resultset()
            {
            }

            resultset &resultset::operator=(resultset &&other)
            {
                stmt_ = std::move(other.stmt_);
                sess_ = std::move(other.sess_);
                status_ = other.status_;
                other.sess_ = nullptr;
                other.stmt_ = nullptr;

                return *this;
            }

            bool resultset::is_valid() const noexcept
            {
                return stmt_ != nullptr && stmt_;
            }

            bool resultset::next()
            {
                if (!is_valid()) {
                    return false;
                }

                if (status_ == SQLITE_DONE) {
                    return false;
                }

                status_ = sqlite3_step(stmt_.get());

                return status_ == SQLITE_ROW;
            }

            void resultset::reset()
            {
                if (!is_valid()) {
                    //resultset::reset database not open
                    return;
                }

                if (sqlite3_reset(stmt_.get()) != SQLITE_OK) {
                    throw database_exception(sess_->last_error());
                }
                status_ = -1;
            }

            resultset::row_type resultset::current_row()
            {
                return row_type(make_shared<row>(sess_, stmt_));
            }
        }
    }
}


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

import java.util.Optional;

import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.metrics.ScanMetrics;

/**
 * Receives {@link Result} for an asynchronous scan.
 *

 * Notice that, the {@link #onNext(Result[], ScanController)} method will be called in the thread
 * which we send request to HBase service. So if you want the asynchronous scanner fetch data from
 * HBase in background while you process the returned data, you need to move the processing work to
 * another thread to make the {@code onNext} call return immediately. And please do NOT do any time
 * consuming tasks in all methods below unless you know what you are doing.
 * @since 2.0.0
 */
@InterfaceAudience.Public
public interface RawScanResultConsumer {

  /**
   * Used to resume a scan.
   */
  @InterfaceAudience.Public
  interface ScanResumer {

    /**
     * Resume the scan. You are free to call it multiple time but only the first call will take
     * effect.
     */
    void resume();
  }

  /**
   * Used to suspend or stop a scan, or get a scan cursor if available.
   *

   * Notice that, you should only call the {@link #suspend()} or {@link #terminate()} inside onNext
   * or onHeartbeat method. A IllegalStateException will be thrown if you call them at other places.
   *

   * You can only call one of the {@link #suspend()} and {@link #terminate()} methods(of course you
   * are free to not call them both), and the methods are not reentrant. An IllegalStateException
   * will be thrown if you have already called one of the methods.
   */
  @InterfaceAudience.Public
  interface ScanController {

    /**
     * Suspend the scan.
     *

     * This means we will stop fetching data in background, i.e., will not call onNext any more
     * before you resume the scan.
     * @return A resumer used to resume the scan later.
     */
    ScanResumer suspend();

    /**
     * Terminate the scan.
     *

     * This is useful when you have got enough results and want to stop the scan in onNext method,
     * or you want to stop the scan in onHeartbeat method because it has spent too many time.
     */
    void terminate();

    /**
     * Get the scan cursor if available.
     * @return The scan cursor.
     */
    Optional<Cursor> cursor();
  }

  /**
   * Indicate that we have receive some data.
   * @param results the data fetched from HBase service.
   * @param controller used to suspend or terminate the scan. Notice that the {@code controller}
   *          instance is only valid within scope of onNext method. You can only call its method in
   *          onNext, do NOT store it and call it later outside onNext.
   */
  void onNext(Result[] results, ScanController controller);

  /**
   * Indicate that there is a heartbeat message but we have not cumulated enough cells to call
   * {@link #onNext(Result[], ScanController)}.
   *

   * Note that this method will always be called when RS returns something to us but we do not have
   * enough cells to call {@link #onNext(Result[], ScanController)}. Sometimes it may not be a
   * 'heartbeat' message for RS, for example, we have a large row with many cells and size limit is
   * exceeded before sending all the cells for this row. For RS it does send some data to us and the
   * time limit has not been reached, but we can not return the data to client so here we call this
   * method to tell client we have already received something.
   *

   * This method give you a chance to terminate a slow scan operation.
   * @param controller used to suspend or terminate the scan. Notice that the {@code controller}
   *          instance is only valid within the scope of onHeartbeat method. You can only call its
   *          method in onHeartbeat, do NOT store it and call it later outside onHeartbeat.
   */
  default void onHeartbeat(ScanController controller) {
  }

  /**
   * Indicate that we hit an unrecoverable error and the scan operation is terminated.
   *

   * We will not call {@link #onComplete()} after calling {@link #onError(Throwable)}.
   */
  void onError(Throwable error);

  /**
   * Indicate that the scan operation is completed normally.
   */
  void onComplete();

  /**
   * If {@code scan.isScanMetricsEnabled()} returns true, then this method will be called prior to
   * all other methods in this interface to give you the {@link ScanMetrics} instance for this scan
   * operation. The {@link ScanMetrics} instance will be updated on-the-fly during the scan, you can
   * store it somewhere to get the metrics at any time if you want.
   */
  default void onScanMetricsCreated(ScanMetrics scanMetrics) {
  }
}


text:
require 'secret_data/version'
require 'secret_data/silencer'

##
# This class is intended as a helper for keeping track of
# pairs of secret data and generating unique, human-readable
# placeholders suitable for public release.
class SecretData
end


text:
from azure.cli.core.util import CLIError
from azure.cli.core.commands import LongRunningOperation
from azure.core.exceptions import HttpResponseError
from azure.cli.command_modules.servicefabric._sf_utils import (
    _get_resource_group_by_name,
    _create_resource_group_name
)
from azure.mgmt.servicefabricmanagedclusters.models import (
    ManagedCluster,
    Sku,
    ClientCertificate
)

from knack.log import get_logger

from .._client_factory import (resource_client_factory)

logger = get_logger(__name__)

# pylint:disable=too-many-locals
def create_cluster(cmd,
                   client,
                   resource_group_name,
                   cluster_name,
                   admin_password,
                   admin_user_name=None,
                   dns_name=None,
                   location=None,
                   sku=None,
                   client_connection_port=None,
                   gateway_connection_port=None,
                   client_cert_is_admin=None,
                   client_cert_thumbprint=None,
                   client_cert_common_name=None,
                   client_cert_issuer_thumbprint=None,
                   upgrade_mode=None,
                   upgrade_cadence=None,
                   code_version=None,
                   tags=None):
    try:

        rg = _get_resource_group_by_name(cmd.cli_ctx, resource_group_name)
        if rg is None:
            rg = _create_resource_group_name(cmd.cli_ctx, resource_group_name, location)

        #  set defult parameters
        if location is None:
            location = rg.location

        if dns_name is None:
            dns_name = cluster_name

        if admin_user_name is None:
            admin_user_name = 'vmadmin'

        if sku is None:
            sku = 'Basic'
        skuObj = Sku(name=sku)

        if client_connection_port is None:
            client_connection_port = 19000

        if gateway_connection_port is None:
            gateway_connection_port = 19080

        client_certs = None
        if client_cert_thumbprint is not None or client_cert_common_name is not None:
            client_certs = []

        if client_cert_thumbprint is not None:
            client_certs.append(ClientCertificate(is_admin=client_cert_is_admin, thumbprint=client_cert_thumbprint))
        elif client_cert_common_name is not None:
            if client_cert_issuer_thumbprint is not None:
                client_cert_issuer_thumbprint = ','.join(client_cert_issuer_thumbprint)
            client_certs.append(ClientCertificate(is_admin=client_cert_is_admin, common_name=client_cert_common_name, issuer_thumbprint=client_cert_issuer_thumbprint))

        new_cluster = ManagedCluster(location=location,
                                     dns_name=dns_name,
                                     admin_user_name=admin_user_name,
                                     admin_password=admin_password,
                                     sku=skuObj,
                                     client_connection_port=client_connection_port,
                                     http_gateway_connection_port=gateway_connection_port,
                                     clients=client_certs,
                                     cluster_upgrade_mode=upgrade_mode,
                                     cluster_upgrade_cadence=upgrade_cadence,
                                     cluster_code_version=code_version,
                                     tags=tags)

        logger.info("Creating managed cluster '%s'", cluster_name)
        poller = client.managed_clusters.begin_create_or_update(resource_group_name, cluster_name, new_cluster)
        cluster = LongRunningOperation(cmd.cli_ctx)(poller)
        return cluster
    except HttpResponseError as ex:
        logger.error("HttpResponseError: %s", ex)
        raise

def update_cluster(cmd,
                   client,
                   resource_group_name,
                   cluster_name,
                   client_connection_port=None,
                   gateway_connection_port=None,
                   dns_name=None,
                   tags=None):
    try:
        cluster = client.managed_clusters.get(resource_group_name, cluster_name)

        if client_connection_port is not None:
            cluster.client_connection_port = client_connection_port
        if gateway_connection_port is not None:
            cluster.http_gateway_connection_port = gateway_connection_port
        if dns_name is not None:
            cluster.dns_name = dns_name
        if tags is not None:
            cluster.tags = tags

        poller = client.managed_clusters.begin_create_or_update(resource_group_name, cluster_name, cluster)
        return LongRunningOperation(cmd.cli_ctx)(poller)
    except HttpResponseError as ex:
        logger.error("HttpResponseError: %s", ex)
        raise

def add_client_cert(cmd,
                    client,
                    resource_group_name,
                    cluster_name,
                    thumbprint=None,
                    common_name=None,
                    issuer_thumbprint=None,
                    is_admin=False):
    try:
        cluster = client.managed_clusters.get(resource_group_name, cluster_name)

        if cluster.clients is None:
            cluster.clients = []

        if thumbprint is not None:
            cluster.clients.append(ClientCertificate(is_admin=is_admin, thumbprint=thumbprint))
        elif common_name is not None:
            if issuer_thumbprint is not None:
                issuer_thumbprint = ','.join(issuer_thumbprint)
            cluster.clients.append(ClientCertificate(is_admin=is_admin, common_name=common_name, issuer_thumbprint=issuer_thumbprint))
        else:
            CLIError("Thumbprint and Common name are empty")

        poller = client.managed_clusters.begin_create_or_update(resource_group_name, cluster_name, cluster)
        return LongRunningOperation(cmd.cli_ctx)(poller)
    except HttpResponseError as ex:
        logger.error("HttpResponseError: %s", ex)
        raise

def delete_client_cert(cmd,
                       client,
                       resource_group_name,
                       cluster_name,
                       thumbprint=None,
                       common_name=None):
    try:
        cluster = client.managed_clusters.get(resource_group_name, cluster_name)

        if cluster.clients is not None:
            initial_size = len(cluster.clients)
            if thumbprint is not None:
                thumbprint = [x.lower() for x in thumbprint]
                cluster.clients = [cert for cert in cluster.clients if cert.thumbprint.lower() not in thumbprint]
            if common_name is not None:
                common_name = [x.lower() for x in common_name]
                cluster.clients = [cert for cert in cluster.clients if cert.common_name.lower() not in common_name]

            if initial_size > len(cluster.clients):
                poller = client.managed_clusters.begin_create_or_update(resource_group_name, cluster_name, cluster)
                return LongRunningOperation(cmd.cli_ctx)(poller)
        return cluster
    except HttpResponseError as ex:
        logger.error("HttpResponseError: %s", ex)
        raise

def list_clusters(client,
                  resource_group_name=None):
    try:
        if resource_group_name is None:
            logger.info("Getting managed clusters by subscription")
            return client.managed_clusters.list_by_subscription()

        logger.info("Getting managed clusters by resource group '%s'", resource_group_name)
        return client.managed_clusters.list_by_resource_group(resource_group_name)
    except HttpResponseError as ex:
        logger.error("HttpResponseError: %s", ex)
        raise

def _get_resource_group_location(cli_ctx, resource_group_name):
    resource_client = resource_client_factory(cli_ctx).resource_groups
    rg = resource_client.get(resource_group_name)
    return rg.location


text:
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace XperiCode.PluploadMvc.Tests
{
    [TestClass]
    public class UrlHelperExtensionsTests
    {
        [TestMethod]
        public void PluploadHandler_Should_Return_PluploadHandler_Url_When_Supplied_Reference()
        {
            var urlHelper = CreateUrlHelper();
            string reference = "123";

            string url = UrlHelperExtensions.PluploadHandler(urlHelper, reference);

            Assert.AreEqual(string.Concat("/Plupload.axd?reference=", reference), url);
        }

        [TestMethod]
        public void PluploadHandler_Should_Return_PluploadHandler_Url_When_Supplied_Collection()
        {
            var urlHelper = CreateUrlHelper();
            var collection = new PluploadFileCollection();

            string url = UrlHelperExtensions.PluploadHandler(urlHelper, collection);

            Assert.AreEqual(string.Concat("/Plupload.axd?reference=", collection.Reference), url);
        }

        [TestMethod, ExpectedException(typeof(ArgumentNullException))]
        public void PluploadHandler_Should_Throw_ArgumentNullException_When_Collection_Is_Null()
        {
            var urlHelper = CreateUrlHelper();
            PluploadFileCollection collection = null;

            UrlHelperExtensions.PluploadHandler(urlHelper, collection);
        }

        private UrlHelper CreateUrlHelper()
        {
            var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
            request.SetupGet(x => x.ApplicationPath).Returns("/");

            var context = new Mock<HttpContextBase>(MockBehavior.Strict);
            context.SetupGet(x => x.Request).Returns(request.Object);
            context.Setup(x => x.GetService(typeof(HttpWorkerRequest))).Returns(null);

            var urlHelper = new UrlHelper(new RequestContext(context.Object, new RouteData()), new RouteCollection());
            return urlHelper;
        }
    }
}


text:
require 'essay/abstract_features'

module Essay
  class AssociationFeatures < AbstractFeatures
    attr_reader :association
    alias this_association association

    def initialize(env)
      super
      @association = env.fetch(:association)
    end
  end
end


text:
<?php

namespace Telegram\Bot\Objects\Passport;

use Telegram\Bot\Objects\AbstractResponseObject;

/**
 * @property string $data             Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication
 * @property string $hash             Base64-encoded data hash for data authentication
 * @property string $secret           Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption
 *
 * @link https://core.telegram.org/bots/api#encryptedcredentials
 */
class EncryptedCredentials extends AbstractResponseObject
{
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Custom_auth
{
    public function __construct()
    {

    }

	/**
	 * __get
	 *
	 * Enables the use of CI super-global without having to define an extra variable.
	 *
	 * I can't remember where I first saw this, so thank you if you are the original author. -Militis
	 *
	 * @access	public
	 * @param	$var
	 * @return	mixed
	 */
	public function __get($var)
	{
		return get_instance()->$var;
	}

    public function is_allowed_to($class,$method)
    {
        $this->load->model('webmodules_model', 'webmodules');

        $webmodules = $this->webmodules->get_by(array('webmodules_class'=>$class,'webmodules_method'=>$method,'status'=>'1'));

        if(count($webmodules) > 0)
        {
            if($webmodules->need_login && !$this->ion_auth->logged_in()){ return false; }

            $arrGroups  = @unserialize($webmodules->groups_access);
            if($arrGroups == true)
            {
                if($this->ion_auth->in_group($arrGroups)){ return true;}
                else{ return false; }
            }
            else
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }

    public function checkPermission()
    {
        $fnc    = $this->router->method;
        switch($fnc)
        {
            case 'insert'   : $fnc = 'add';     break;
            case 'update'   : $fnc = 'edit';    break;
            case 'remove'   : $fnc = 'delete';  break;
        }

        if(($this->config->item('maintenance_mode') == TRUE && $this->session->userdata('is_maintenance_login') == TRUE) || $this->config->item('maintenance_mode') == FALSE)
        {
            if($this->router->class == 'auth' && $fnc == 'login_dev' && !$this->ion_auth->logged_in())
            {
                redirect(links_url(array('class'=>'auth','method'=>'login')), 'refresh');
            }

            if($this->ion_auth->logged_in())
            {
                if($this->router->class == 'auth' && $fnc == 'login') redirect(secure_url(), 'refresh');

                if($this->ion_auth->is_locked())
                {
                    if($this->router->class <> 'auth' && $fnc <> 'locked') redirect(links_url(array('class'=>'auth','method'=>'locked')), 'refresh');
                }
                else
                {
                    if($this->router->class == 'auth' && ($fnc <> 'lock' && $fnc <> 'logout' && $fnc <> 'login_otp')) redirect(links_url(array('class'=>'home','method'=>'index')), 'refresh');
                }
            }

            $this->load->model('webmodules_model', 'webmodules');

            $webmodules = $this->webmodules->get_by(array('webmodules_class'=>$this->router->class,'webmodules_method'=>$fnc,'status'=>'1'));

            if(count($webmodules) > 0)
            {
                if($webmodules->need_login && !$this->ion_auth->logged_in())
                {
                    if(!$this->input->is_ajax_request())
                    {
                        redirect(links_url(array('class'=>'auth','method'=>'login')), 'refresh');
                    }
                    else
                    {
                        $this->output
                             ->set_content_type('application/json')
                             ->set_status_header(403)
                             ->set_output(json_encode(array()));exit;
                    }
                }

                $webmodules_name    = @unserialize($webmodules->webmodules_name);

                $arrGroups  = @unserialize($webmodules->groups_access);
                if($arrGroups == true)
                {
                    if($this->ion_auth->in_group($arrGroups))  return true;
                    else show_404();exit;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                show_404();exit;
            }
        }
        else
        {
            if($this->config->item('maintenance_mode') == TRUE && $this->session->userdata('is_maintenance_login') == FALSE && $this->router->method <> 'login_dev')
            {
                redirect(links_url(array('class'=>'auth','method'=>'login_dev')), 'refresh');
            }

            return true;
        }
    }

    public function generateNavigationData()
    {
        $data = array();
        $themes = $this->session->userdata('themes').'/';

        $this->load->model('webmenu_model', 'webmenu');

        $logged     = (!$this->ion_auth->logged_in()) ? 0 : 1;
        $mainmenus  = $this->webmenu->order_by('webmenu_order','asc')->getWebmenu($logged);

        if(count($mainmenus) > 0)
        {
            $i  = 0;
            $countlead  = 0;
            foreach($mainmenus as $mainmenu)
            {
                $arrGroups = @unserialize($mainmenu->groups_access);
                if(($themes == $mainmenu->webthemes_name.'/' || (is_null($mainmenu->webthemesmenu_id) && empty($mainmenu->webthemesmenu_id))) && $mainmenu->status == '1' &&
                    (
                        (empty($arrGroups) || $arrGroups == false) ||
                        (
                            ($this->ion_auth->logged_in() && $this->ion_auth->in_group($arrGroups)) ||
                            ($this->ion_auth->logged_in() && $this->ion_auth->in_group($arrGroups) && ($mainmenu->need_login == 2 || $mainmenu->need_login == 4)) ||
                            (!$this->ion_auth->logged_in() && ($mainmenu->need_login == 0 || $mainmenu->need_login == 2 || $mainmenu->need_login == 3))
                        )
                    )
                )
                {
                    $webthemesmenu_name   = str_replace(' ', '_',preg_replace('/[^A-Za-z_ ]/', '', strtolower($mainmenu->webthemesmenu_name)));
                    $data[((empty($webthemesmenu_name)) ? 'main_navigation' : $webthemesmenu_name)][$i] = $mainmenu;
                    $i++;
                }
            }
        }
        //echo "<pre>";print_r($data);echo "</pre>";
        return $data;
    }

	public function login()
	{

	}

	public function logout()
	{

	}

	public function lock()
	{

	}

	public function unlock()
	{

	}

	public function is_logged()
	{
		return TRUE;
	}

	public function is_locked()
	{
		return FALSE;
	}
}

/* End of file Auth.php */
/* Location: private/apps/libraries/Auth.php */


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace Nixxis.Windows.Controls
{
    public partial class ScoreSelection : UserControl
    {
        #region Class data
        private int m_Length = 5;
        private Image m_ActiveImage = global::crCustomControl.Resource.rated_16;
        private Image m_InActiveImage = global::crCustomControl.Resource.unrated_16;
        private int m_Value = 0;

        private PictureBox[] m_Score;
        #endregion

        public ScoreSelection()
        {
            InitializeComponent();
        }

        #region Properties
        public int Length
        {
            get { return m_Length; }
            set { m_Length = value;  }
        }
        public Image ActiveImage
        {
            get { return m_ActiveImage; }
            set { m_ActiveImage = value; }
        }
        public Image InActiveImage
        {
            get { return m_InActiveImage; }
            set { m_InActiveImage = value; }
        }
        public int Value
        {
            get { return m_Value; }
            set { m_Value = value; SetValue(value); }
        }
        #endregion

        private void ScoreSelection_Load(object sender, EventArgs e)
        {
            m_Score = new PictureBox[m_Length];

            for (int i = 0; i < m_Score.Length; i++)
                m_Score[i] = CreateScoreItem();

            Draw();
        }
        private PictureBox CreateScoreItem()
        {
            PictureBox item = new PictureBox();
            item.Image = m_InActiveImage;
            item.Height = m_InActiveImage.Height + 2;
            item.Width = m_InActiveImage.Width + 2;
            item.Click += new EventHandler(Score_Click);
            item.SizeMode = PictureBoxSizeMode.CenterImage;

            return item;
        }

        void Score_Click(object sender, EventArgs e)
        {
            PictureBox item = (PictureBox)sender;
            SetValue(((int)item.Tag) + 1);

        }
        private void SetValue(int value)
        {
            //if (value == null) return;
            if (m_Score == null) return;

            for (int i = 0; i < m_Score.Length; i++)
            {
                if (i < value)
                    m_Score[i].Image = m_ActiveImage;
                else
                    m_Score[i].Image = m_InActiveImage;
            }
            m_Value = value;
        }
        private void Draw()
        {
            for (int i = 0; i < m_Score.Length; i++)
            {
                m_Score[i].Left = i * (m_InActiveImage.Width + 1);
                m_Score[i].Top = 0;
                m_Score[i].Tag = i;
                this.Controls.Add(m_Score[i]);
            }
        }

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


text:
package ru.stqa.pft.addressbook.generators;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.thoughtworks.xstream.XStream;
import ru.stqa.pft.addressbook.model.CantactData;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Denis on 14.04.2017.
 */
public class ContactDataGenerator {

    @Parameter(names = "-c", description = "Contact count")
    public int count;
    @Parameter(names = "-f", description = "Target file")
    public String file;

    @Parameter(names = "-d", description = "Date format")
    public String format;

    public static void main(String[] args) throws IOException {
        ContactDataGenerator generator = new ContactDataGenerator();
        JCommander jCommander = new JCommander(generator);
        try {
            jCommander.parse(args);
        } catch (ParameterException ex) {
            jCommander.usage();
            return;
        }

        generator.run();
    }

    private void run() throws IOException {
        List<CantactData> contacts = generateContacts(count);
        if (format.equals("csv")) {
            saveAsCsv(contacts, new File(file));
        } else if (format.equals("xml")) {
            saveAsXml(contacts, new File(file));
        } else {
            System.out.println("Unknown format"+format);
        }

    }

    private void saveAsXml(List<CantactData> contacts, File file) throws IOException {
        XStream xstream = new XStream();
        xstream.processAnnotations(CantactData.class);
        String xml = xstream.toXML(contacts);
        Writer writer = new FileWriter(file);
        writer.write(xml);
        writer.close();
    }

    private void saveAsCsv(List<CantactData> contacts, File file) throws IOException {
        Writer writer = new FileWriter(file);
        for (CantactData contact : contacts) {
            writer.write(String.format("%s;%s;%s;%s;%s\n",
                    contact.getFirstname(), contact.getLastname(), contact.getAddress(),
                    contact.getEmail(), contact.getHomePhone()));

        }
        writer.close();
    }

    private static List<CantactData> generateContacts(int count) {
        List<CantactData> contacts = new ArrayList<CantactData>();
        for (int i = 0; i < count; i++) {
            contacts.add(new CantactData()
                    .withtFirstname(String.format("Firstname %s", i))
                    .withLastname(String.format("Lastname %s", i))
                    .withAddress(String.format("Address %s", i))
                    .withEmail(String.format("Email%s@test.ru", i))
                    .withHomePhone(String.format("495-777-55-0%s", i))
                    .withMobilePhone(String.format("495-777-55-0%s", i))
                    .withWorkPhone(String.format("495-777-55-0%s", i))
                    .withEmail2(String.format("Email%s@test.ru", i))
                    .withEmail3(String.format("Email%s@test.ru", i))
                    .withHome2Phone(String.format("495-777-55-0%s", i))

                    .withPhoto(new File("src/test/resources/ring.gif"))

            );

        }
        return contacts;
    }

}


text:
<?php

namespace backend\modules\auth\models;

use Yii;

/**
 * This is the model class for table "auth_item".
 *
 * @property string $name
 * @property integer $type
 * @property string $description
 * @property string $rule_name
 * @property string $data
 *
 * @property AuthAssignment $authAssignment
 * @property AuthRule $ruleName
 * @property AuthItemChild $authItemChild
 */
class AuthItem extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'auth_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'type'], 'required'],
            [['type'], 'integer'],
            [['description', 'data'], 'string'],
            [['name', 'rule_name'], 'string', 'max' => 64]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Name',
            'type' => 'Type',
            'description' => 'Description',
            'rule_name' => 'Rule Name',
            'data' => 'Data',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthAssignment()
    {
        return $this->hasOne(AuthAssignment::className(), ['item_name' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRuleName()
    {
        return $this->hasOne(AuthRule::className(), ['name' => 'rule_name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthItemChild()
    {
        return $this->hasOne(AuthItemChild::className(), ['child' => 'name']);
    }
}


text:
\hypertarget{Domain_8hpp}{}\section{source/subdomain/\+Domain.hpp File Reference}
\label{Domain_8hpp}\index{source/subdomain/\+Domain.\+hpp@{source/subdomain/\+Domain.\+hpp}}

Defines the \mbox{\hyperlink{classDomain}{Domain}} class.

{\ttfamily \#include $<$map$>$}\newline
{\ttfamily \#include $<$string$>$}\newline
{\ttfamily \#include $<$vector$>$}\newline
{\ttfamily \#include $<$array$>$}\newline
{\ttfamily \#include $<$mpi.\+h$>$}\newline
{\ttfamily \#include \char`\"{}S\+D\+Distributed.\+hpp\char`\"{}}\newline
{\ttfamily \#include \char`\"{}number/number.\+hpp\char`\"{}}\newline
{\ttfamily \#include \char`\"{}exception/exception.\+hpp\char`\"{}}\newline
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \mbox{\hyperlink{classDomain}{Domain}}
\begin{DoxyCompactList}\small\item\em \mbox{\hyperlink{classDomain}{Domain}} on which a scheme is executed. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
int \mbox{\hyperlink{Domain_8hpp_a6903b26593721539bf47d813a2a5ce86}{is\+Power\+Of}} (unsigned int N, unsigned int r)
\begin{DoxyCompactList}\small\item\em If $N = r^p$, returns $p$. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
Defines the \mbox{\hyperlink{classDomain}{Domain}} class.

\subsection{Function Documentation}
\mbox{\Hypertarget{Domain_8hpp_a6903b26593721539bf47d813a2a5ce86}\label{Domain_8hpp_a6903b26593721539bf47d813a2a5ce86}}
\index{Domain.\+hpp@{Domain.\+hpp}!is\+Power\+Of@{is\+Power\+Of}}
\index{is\+Power\+Of@{is\+Power\+Of}!Domain.\+hpp@{Domain.\+hpp}}
\subsubsection{\texorpdfstring{is\+Power\+Of()}{isPowerOf()}}
{\footnotesize\ttfamily int is\+Power\+Of (\begin{DoxyParamCaption}\item[{unsigned int}]{N,  }\item[{unsigned int}]{r }\end{DoxyParamCaption})}

If $N = r^p$, returns $p$.

\begin{DoxyParams}{Parameters}
{\em N} & number to test \\
\hline
{\em r} & corresponding power \\
\hline
\end{DoxyParams}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid src: port-leading-dash</title>
<iframe src="http://foo:-80/"></iframe>


text:
#ifndef NRF_COMP_H_
#define NRF_COMP_H_

#include <nrfx.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @defgroup nrf_comp_hal COMP HAL
 * @{
 * @ingroup nrf_comp
 * @brief   Hardware access layer (HAL) for managing the Comparator (COMP) peripheral.
 */

/** @brief COMP analog pin selection. */
typedef enum
{
    NRF_COMP_INPUT_0   = COMP_PSEL_PSEL_AnalogInput0, /*!< AIN0 selected as analog input. */
    NRF_COMP_INPUT_1   = COMP_PSEL_PSEL_AnalogInput1, /*!< AIN1 selected as analog input. */
    NRF_COMP_INPUT_2   = COMP_PSEL_PSEL_AnalogInput2, /*!< AIN2 selected as analog input. */
    NRF_COMP_INPUT_3   = COMP_PSEL_PSEL_AnalogInput3, /*!< AIN3 selected as analog input. */
#if defined (COMP_PSEL_PSEL_AnalogInput4) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_INPUT_4   = COMP_PSEL_PSEL_AnalogInput4, /*!< AIN4 selected as analog input. */
#endif
#if defined (COMP_PSEL_PSEL_AnalogInput5) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_INPUT_5   = COMP_PSEL_PSEL_AnalogInput5, /*!< AIN5 selected as analog input. */
#endif
#if defined (COMP_PSEL_PSEL_AnalogInput6) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_INPUT_6   = COMP_PSEL_PSEL_AnalogInput6, /*!< AIN6 selected as analog input. */
#endif
#if defined (COMP_PSEL_PSEL_AnalogInput7) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_INPUT_7   = COMP_PSEL_PSEL_AnalogInput7, /*!< AIN7 selected as analog input. */
#endif
#if defined (COMP_PSEL_PSEL_VddDiv2) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_VDD_DIV2  = COMP_PSEL_PSEL_VddDiv2,      /*!< VDD/2 selected as analog input. */
#endif
#if defined (COMP_PSEL_PSEL_VddhDiv5) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_VDDH_DIV5 = COMP_PSEL_PSEL_VddhDiv5,     /*!< VDDH/5 selected as analog input. */
#endif
} nrf_comp_input_t;

/** @brief COMP reference selection. */
typedef enum
{
    NRF_COMP_REF_Int1V2 = COMP_REFSEL_REFSEL_Int1V2, /*!< VREF = internal 1.2 V reference (VDD >= 1.7 V). */
    NRF_COMP_REF_Int1V8 = COMP_REFSEL_REFSEL_Int1V8, /*!< VREF = internal 1.8 V reference (VDD >= VREF + 0.2 V). */
    NRF_COMP_REF_Int2V4 = COMP_REFSEL_REFSEL_Int2V4, /*!< VREF = internal 2.4 V reference (VDD >= VREF + 0.2 V). */
    NRF_COMP_REF_VDD = COMP_REFSEL_REFSEL_VDD,       /*!< VREF = VDD. */
    NRF_COMP_REF_ARef = COMP_REFSEL_REFSEL_ARef      /*!< VREF = AREF (VDD >= VREF >= AREFMIN). */
} nrf_comp_ref_t;

/** @brief COMP external analog reference selection. */
typedef enum
{
    NRF_COMP_EXT_REF_0 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference0, /*!< Use AIN0 as external analog reference. */
    NRF_COMP_EXT_REF_1 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference1, /*!< Use AIN1 as external analog reference. */
    NRF_COMP_EXT_REF_2 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference2, /*!< Use AIN2 as external analog reference. */
    NRF_COMP_EXT_REF_3 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference3, /*!< Use AIN3 as external analog reference. */
#if defined (COMP_EXTREFSEL_EXTREFSEL_AnalogReference4) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_EXT_REF_4 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference4, /*!< Use AIN4 as external analog reference. */
#endif
#if defined (COMP_EXTREFSEL_EXTREFSEL_AnalogReference5) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_EXT_REF_5 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference5, /*!< Use AIN5 as external analog reference. */
#endif
#if defined (COMP_EXTREFSEL_EXTREFSEL_AnalogReference6) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_EXT_REF_6 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference6, /*!< Use AIN6 as external analog reference. */
#endif
#if defined (COMP_EXTREFSEL_EXTREFSEL_AnalogReference7) || defined (__NRFX_DOXYGEN__)
    NRF_COMP_EXT_REF_7 = COMP_EXTREFSEL_EXTREFSEL_AnalogReference7  /*!< Use AIN7 as external analog reference. */
#endif
} nrf_comp_ext_ref_t;

/** @brief COMP THDOWN and THUP values that are used to calculate the threshold voltages VDOWN and VUP. */
typedef struct
{
    uint8_t th_down; /*!< THDOWN value. */
    uint8_t th_up;   /*!< THUP value. */
} nrf_comp_th_t;

/** @brief COMP main operation mode. */
typedef enum
{
    NRF_COMP_MAIN_MODE_SE = COMP_MODE_MAIN_SE,    /*!< Single-ended mode. */
    NRF_COMP_MAIN_MODE_Diff = COMP_MODE_MAIN_Diff /*!< Differential mode. */
} nrf_comp_main_mode_t;

/** @brief COMP speed and power mode. */
typedef enum
{
    NRF_COMP_SP_MODE_Low = COMP_MODE_SP_Low,       /*!< Low power mode. */
    NRF_COMP_SP_MODE_Normal = COMP_MODE_SP_Normal, /*!< Normal mode. */
    NRF_COMP_SP_MODE_High = COMP_MODE_SP_High      /*!< High-speed mode. */
} nrf_comp_sp_mode_t;

/** @brief COMP comparator hysteresis. */
typedef enum
{
    NRF_COMP_HYST_NoHyst = COMP_HYST_HYST_NoHyst, /*!< Comparator hysteresis disabled. */
    NRF_COMP_HYST_50mV = COMP_HYST_HYST_Hyst50mV  /*!< Comparator hysteresis enabled. */
} nrf_comp_hyst_t;

#if defined (COMP_ISOURCE_ISOURCE_Msk) || defined (__NRFX_DOXYGEN__)
/** @brief COMP current source selection on analog input. */
typedef enum
{
    NRF_COMP_ISOURCE_Off = COMP_ISOURCE_ISOURCE_Off,         /*!< Current source disabled. */
    NRF_COMP_ISOURCE_Ien2uA5 = COMP_ISOURCE_ISOURCE_Ien2mA5, /*!< Current source enabled (+/- 2.5 uA). */
    NRF_COMP_ISOURCE_Ien5uA = COMP_ISOURCE_ISOURCE_Ien5mA,   /*!< Current source enabled (+/- 5 uA). */
    NRF_COMP_ISOURCE_Ien10uA = COMP_ISOURCE_ISOURCE_Ien10mA  /*!< Current source enabled (+/- 10 uA). */
} nrf_isource_t;
#endif

/** @brief COMP tasks. */
typedef enum
{
    NRF_COMP_TASK_START  = offsetof(NRF_COMP_Type, TASKS_START), /*!< COMP start sampling task. */
    NRF_COMP_TASK_STOP   = offsetof(NRF_COMP_Type, TASKS_STOP),  /*!< COMP stop sampling task. */
    NRF_COMP_TASK_SAMPLE = offsetof(NRF_COMP_Type, TASKS_SAMPLE) /*!< Sample comparator value. */
} nrf_comp_task_t;

/** @brief COMP events. */
typedef enum
{
    NRF_COMP_EVENT_READY = offsetof(NRF_COMP_Type, EVENTS_READY), /*!< COMP is ready and output is valid. */
    NRF_COMP_EVENT_DOWN  = offsetof(NRF_COMP_Type, EVENTS_DOWN),  /*!< Input voltage crossed the threshold going down. */
    NRF_COMP_EVENT_UP    = offsetof(NRF_COMP_Type, EVENTS_UP),    /*!< Input voltage crossed the threshold going up. */
    NRF_COMP_EVENT_CROSS = offsetof(NRF_COMP_Type, EVENTS_CROSS)  /*!< Input voltage crossed the threshold in any direction. */
} nrf_comp_event_t;

/** @brief COMP reference configuration. */
typedef struct
{
    nrf_comp_ref_t     reference; /*!< COMP reference selection. */
    nrf_comp_ext_ref_t external;  /*!< COMP external analog reference selection. */
} nrf_comp_ref_conf_t;

/**
 * @brief Function for enabling the COMP peripheral.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 */
NRF_STATIC_INLINE void nrf_comp_enable(NRF_COMP_Type * p_reg);

/**
 * @brief Function for disabling the COMP peripheral.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 */
NRF_STATIC_INLINE void nrf_comp_disable(NRF_COMP_Type * p_reg);

/**
 * @brief Function for checking if the COMP peripheral is enabled.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @retval true  The COMP peripheral is enabled.
 * @retval false The COMP peripheral is not enabled.
 */
NRF_STATIC_INLINE bool nrf_comp_enable_check(NRF_COMP_Type const * p_reg);

/**
 * @brief Function for setting the reference source.
 *
 * @param[in] p_reg     Pointer to the structure of registers of the peripheral.
 * @param[in] reference COMP reference selection.
 */
NRF_STATIC_INLINE void nrf_comp_ref_set(NRF_COMP_Type * p_reg, nrf_comp_ref_t reference);

/**
 * @brief Function for setting the external analog reference source.
 *
 * @param[in] p_reg   Pointer to the structure of registers of the peripheral.
 * @param[in] ext_ref COMP external analog reference selection.
 */
NRF_STATIC_INLINE void nrf_comp_ext_ref_set(NRF_COMP_Type * p_reg, nrf_comp_ext_ref_t ext_ref);

/**
 * @brief Function for setting threshold voltages.
 *
 * @param[in] p_reg     Pointer to the structure of registers of the peripheral.
 * @param[in] threshold COMP VDOWN and VUP thresholds.
 */
NRF_STATIC_INLINE void nrf_comp_th_set(NRF_COMP_Type * p_reg, nrf_comp_th_t threshold);

/**
 * @brief Function for setting the main mode.
 *
 * @param[in] p_reg     Pointer to the structure of registers of the peripheral.
 * @param[in] main_mode COMP main operation mode.
 */
NRF_STATIC_INLINE void nrf_comp_main_mode_set(NRF_COMP_Type *      p_reg,
                                              nrf_comp_main_mode_t main_mode);

/**
 * @brief Function for setting the speed mode.
 *
 * @param[in] p_reg      Pointer to the structure of registers of the peripheral.
 * @param[in] speed_mode COMP speed and power mode.
 */
NRF_STATIC_INLINE void nrf_comp_speed_mode_set(NRF_COMP_Type *    p_reg,
                                               nrf_comp_sp_mode_t speed_mode);

/**
 * @brief Function for setting the hysteresis.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] hyst  COMP comparator hysteresis.
 */
NRF_STATIC_INLINE void nrf_comp_hysteresis_set(NRF_COMP_Type * p_reg, nrf_comp_hyst_t hyst);

#if defined (COMP_ISOURCE_ISOURCE_Msk) || defined (__NRFX_DOXYGEN__)
/**
 * @brief Function for setting the current source on the analog input.
 *
 * @param[in] p_reg   Pointer to the structure of registers of the peripheral.
 * @param[in] isource COMP current source selection on analog input.
 */
NRF_STATIC_INLINE void nrf_comp_isource_set(NRF_COMP_Type * p_reg, nrf_isource_t isource);
#endif

/**
 * @brief Function for selecting the active input of the COMP.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] input Input to be selected.
 */
NRF_STATIC_INLINE void nrf_comp_input_select(NRF_COMP_Type * p_reg, nrf_comp_input_t input);

/**
 * @brief Function for getting the last COMP compare result.
 *
 * @note If VIN+ == VIN-, the return value depends on the previous result.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @return The last compare result. If 0, then VIN+ < VIN-. If 1, then VIN+ > VIN-.
 */
NRF_STATIC_INLINE uint32_t nrf_comp_result_get(NRF_COMP_Type const * p_reg);

/**
 * @brief Function for enabling interrupts from COMP.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of interrupts to be enabled.
 *
 * @sa nrf_comp_int_enable_check
 */
NRF_STATIC_INLINE void nrf_comp_int_enable(NRF_COMP_Type * p_reg, uint32_t mask);

/**
 * @brief Function for disabling interrupts from COMP.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of interrupts to be disabled.
 *
 * @sa nrf_comp_int_enable_check
 */
NRF_STATIC_INLINE void nrf_comp_int_disable(NRF_COMP_Type * p_reg, uint32_t mask);

/**
 * @brief Function for checking if the specified interrupts are enabled.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of interrupts to be checked.
 *
 * @return Mask of enabled interrupts.
 */
NRF_STATIC_INLINE uint32_t nrf_comp_int_enable_check(NRF_COMP_Type const * p_reg, uint32_t mask);

/**
 * @brief Function for getting the address of the specified COMP task register.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] task  COMP task.
 *
 * @return Address of the specified COMP task.
 */
NRF_STATIC_INLINE uint32_t nrf_comp_task_address_get(NRF_COMP_Type const * p_reg,
                                                     nrf_comp_task_t       task);

/**
 * @brief Function for getting the address of the specified COMP event register.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] event COMP event.
 *
 * @return Address of the specified COMP event.
 */
NRF_STATIC_INLINE uint32_t nrf_comp_event_address_get(NRF_COMP_Type const * p_reg,
                                                      nrf_comp_event_t      event);

/**
 * @brief  Function for setting COMP shortcuts.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of shortcuts.
 */
NRF_STATIC_INLINE void nrf_comp_shorts_enable(NRF_COMP_Type * p_reg, uint32_t mask);

/**
 * @brief Function for clearing COMP shortcuts by mask.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of shortcuts.
 */
NRF_STATIC_INLINE void nrf_comp_shorts_disable(NRF_COMP_Type * p_reg, uint32_t mask);

/**
 * @brief Function for setting the specified COMP task.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] task  Task to be activated.
 */
NRF_STATIC_INLINE void nrf_comp_task_trigger(NRF_COMP_Type * p_reg, nrf_comp_task_t task);

/**
 * @brief Function for clearing the specified COMP event.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] event COMP event to be cleared.
 */
NRF_STATIC_INLINE void nrf_comp_event_clear(NRF_COMP_Type * p_reg, nrf_comp_event_t event);

/**
 * @brief Function for retrieving the state of the UARTE event.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] event Event to be checked.
 *
 * @retval true  The event has been generated.
 * @retval false The event has not been generated.
 */
NRF_STATIC_INLINE bool nrf_comp_event_check(NRF_COMP_Type const * p_reg, nrf_comp_event_t event);

#ifndef NRF_DECLARE_ONLY

NRF_STATIC_INLINE void nrf_comp_enable(NRF_COMP_Type * p_reg)
{
    p_reg->ENABLE = (COMP_ENABLE_ENABLE_Enabled << COMP_ENABLE_ENABLE_Pos);
}

NRF_STATIC_INLINE void nrf_comp_disable(NRF_COMP_Type * p_reg)
{
    p_reg->ENABLE = (COMP_ENABLE_ENABLE_Disabled << COMP_ENABLE_ENABLE_Pos);
}

NRF_STATIC_INLINE bool nrf_comp_enable_check(NRF_COMP_Type const * p_reg)
{
    return ((p_reg->ENABLE) & COMP_ENABLE_ENABLE_Enabled);
}

NRF_STATIC_INLINE void nrf_comp_ref_set(NRF_COMP_Type * p_reg, nrf_comp_ref_t reference)
{
    p_reg->REFSEL = (reference << COMP_REFSEL_REFSEL_Pos);
}

NRF_STATIC_INLINE void nrf_comp_ext_ref_set(NRF_COMP_Type * p_reg, nrf_comp_ext_ref_t ext_ref)
{
    p_reg->EXTREFSEL = (ext_ref << COMP_EXTREFSEL_EXTREFSEL_Pos);
}

NRF_STATIC_INLINE void nrf_comp_th_set(NRF_COMP_Type * p_reg, nrf_comp_th_t threshold)
{
    p_reg->TH =
        (((uint32_t)threshold.th_down << COMP_TH_THDOWN_Pos) & COMP_TH_THDOWN_Msk) |
        (((uint32_t)threshold.th_up << COMP_TH_THUP_Pos) & COMP_TH_THUP_Msk);
}

NRF_STATIC_INLINE void nrf_comp_main_mode_set(NRF_COMP_Type *      p_reg,
                                              nrf_comp_main_mode_t main_mode)
{
    p_reg->MODE |= (main_mode << COMP_MODE_MAIN_Pos);
}

NRF_STATIC_INLINE void nrf_comp_speed_mode_set(NRF_COMP_Type *    p_reg,
                                               nrf_comp_sp_mode_t speed_mode)
{
    p_reg->MODE |= (speed_mode << COMP_MODE_SP_Pos);
}

NRF_STATIC_INLINE void nrf_comp_hysteresis_set(NRF_COMP_Type * p_reg, nrf_comp_hyst_t hyst)
{
    p_reg->HYST = (hyst << COMP_HYST_HYST_Pos) & COMP_HYST_HYST_Msk;
}

#if defined (COMP_ISOURCE_ISOURCE_Msk)
NRF_STATIC_INLINE void nrf_comp_isource_set(NRF_COMP_Type * p_reg, nrf_isource_t isource)
{
    p_reg->ISOURCE = (isource << COMP_ISOURCE_ISOURCE_Pos) & COMP_ISOURCE_ISOURCE_Msk;
}
#endif

NRF_STATIC_INLINE void nrf_comp_input_select(NRF_COMP_Type * p_reg, nrf_comp_input_t input)
{
    p_reg->PSEL   = ((uint32_t)input << COMP_PSEL_PSEL_Pos);
}

NRF_STATIC_INLINE uint32_t nrf_comp_result_get(NRF_COMP_Type const * p_reg)
{
    return (uint32_t)p_reg->RESULT;
}

NRF_STATIC_INLINE void nrf_comp_int_enable(NRF_COMP_Type * p_reg, uint32_t mask)
{
    p_reg->INTENSET = mask;
}

NRF_STATIC_INLINE void nrf_comp_int_disable(NRF_COMP_Type * p_reg, uint32_t mask)
{
    p_reg->INTENCLR = mask;
}

NRF_STATIC_INLINE uint32_t nrf_comp_int_enable_check(NRF_COMP_Type const * p_reg, uint32_t mask)
{
    return p_reg->INTENSET & mask; // When read, this register returns the value of INTEN.
}

NRF_STATIC_INLINE uint32_t nrf_comp_task_address_get(NRF_COMP_Type const * p_reg,
                                                     nrf_comp_task_t       task)
{
    return (uint32_t)((uint8_t *)p_reg + (uint32_t)task);
}

NRF_STATIC_INLINE uint32_t nrf_comp_event_address_get(NRF_COMP_Type const * p_reg,
                                                      nrf_comp_event_t      event)
{
    return (uint32_t)((uint8_t *)p_reg + (uint32_t)event);
}

NRF_STATIC_INLINE void nrf_comp_shorts_enable(NRF_COMP_Type * p_reg, uint32_t mask)
{
    p_reg->SHORTS |= mask;
}

NRF_STATIC_INLINE void nrf_comp_shorts_disable(NRF_COMP_Type * p_reg, uint32_t mask)
{
    p_reg->SHORTS &= ~mask;
}

NRF_STATIC_INLINE void nrf_comp_task_trigger(NRF_COMP_Type * p_reg, nrf_comp_task_t task)
{
    *( (volatile uint32_t *)( (uint8_t *)p_reg + (uint32_t)task) ) = 1;
}

NRF_STATIC_INLINE void nrf_comp_event_clear(NRF_COMP_Type * p_reg, nrf_comp_event_t event)
{
    *( (volatile uint32_t *)( (uint8_t *)p_reg + (uint32_t)event) ) = 0;
    nrf_event_readback((uint8_t *)p_reg + (uint32_t)event);
}

NRF_STATIC_INLINE bool nrf_comp_event_check(NRF_COMP_Type const * p_reg, nrf_comp_event_t event)
{
    return (bool) (*(volatile uint32_t *)( (uint8_t *)p_reg + (uint32_t)event));
}

#endif // NRF_DECLARE_ONLY

/** @} */

#ifdef __cplusplus
}
#endif

#endif // NRF_COMP_H_


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

/**
 * Test: Schema\Validation\ControllerPathValidation
 */

require_once __DIR__ . '/../../../bootstrap.php';

use Apitte\Core\Exception\Logical\InvalidSchemaException;
use Apitte\Core\Schema\SchemaBuilder;
use Apitte\Core\Schema\Validation\ControllerPathValidation;
use Tester\Assert;

// Validate: success
test(function (): void {
	$validation = new ControllerPathValidation();
	$builder = new SchemaBuilder();

	$c1 = $builder->addController('c1');
	$c1->setPath('/foo');

	Assert::noError(function () use ($validation, $builder): void {
		$validation->validate($builder);
	});
});

// Validate: no path
test(function (): void {
	$validation = new ControllerPathValidation();
	$builder = new SchemaBuilder();

	$builder->addController('c1');

	Assert::exception(function () use ($validation, $builder): void {
		$validation->validate($builder);
	}, InvalidSchemaException::class, '@Path in "c1" must be set.');
});

// Validate: start with /
test(function (): void {
	$validation = new ControllerPathValidation();
	$builder = new SchemaBuilder();

	$c1 = $builder->addController('c1');
	$c1->setPath('foo');

	Assert::exception(function () use ($validation, $builder): void {
		$validation->validate($builder);
	}, InvalidSchemaException::class, '@Path "foo" in "c1" must starts with "/" (slash).');
});

// Validate: end with /
test(function (): void {
	$validation = new ControllerPathValidation();
	$builder = new SchemaBuilder();

	$c1 = $builder->addController('c1');
	$c1->setPath('/foo/');

	Assert::exception(function () use ($validation, $builder): void {
		$validation->validate($builder);
	}, InvalidSchemaException::class, '@Path "/foo/" in "c1" must not ends with "/" (slash).');
});

// Validate: invalid characters
test(function (): void {
	$validation = new ControllerPathValidation();
	$builder = new SchemaBuilder();

	$c1 = $builder->addController('c1');
	$c1->setPath('/{foo$}');

	Assert::exception(function () use ($validation, $builder): void {
		$validation->validate($builder);
	}, InvalidSchemaException::class, '@Path "/{foo$}" in "c1" contains illegal characters "{". Allowed characters are only [a-zA-Z0-9-_/].');
});


text:
<?php
/**
 * A thin wrapper for the wpdb, the WordPress database API.
 */
class Wslm_WpDatabase extends Wslm_Database {
	/** @var wpdb */
	private $wpdb;

	public function __construct() {
		$this->wpdb = $GLOBALS['wpdb'];
	}

	public function getResults($query, $parameters = array()) {
		if ( !empty($parameters) ) {
			$query = str_replace('?', '%s', $query);
			$query = $this->wpdb->prepare($query, $parameters);
		}
		return $this->wpdb->get_results($query, ARRAY_A);
	}

	public function query($query, $parameters = array()) {
		if ( !empty($parameters) ) {
			$query = str_replace('?', '%s', $query);
			$query = $this->wpdb->prepare($query, $parameters);
		}
		return $this->wpdb->query($query);
	}
}


text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<title>

</title>

[idx3d::API]

Hashtable_Inspector.java

package

idx3d.debug
;

import

idx3d.*
;

import

java.util.Vector
;

import

java.util.Enumeration
;

import

java.awt.*
;

import

java.applet.*
;

public class Hashtable_Inspector extends InspectorFrame

public

Hashtable_Inspector
(java.util.Hashtable hash, String id)

idx3d

SubPages

Demos

Download

Releases

Feature list

Documentation

API [Interface]

Source Code

Class Diagrams

Links

Material Lab

idx3d.debug.Inspector

© 2000 by Peter Walser     |
proxima@active.ch       |
http://www2.active.ch/~proxima


text:
import mock

from datetime import datetime
from app import DISPLAY_DATE_FORMAT

from ...helpers import LoggedInApplicationTest

class TestServiceUpdates(LoggedInApplicationTest):
    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_render_activity_page_with_date(self, data_api_client):
        today = datetime.utcnow().strftime(DISPLAY_DATE_FORMAT)

        response = self.client.get('/admin/service-updates')
        self.assertEquals(200, response.status_code)

        date_header = """

            Activity for

        {}

        """.format(today)

        self.assertIn(
            self._replace_whitespace(date_header),
            self._replace_whitespace(response.get_data(as_text=True))
        )

        data_api_client.find_audit_events.assert_called()

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_render_correct_form_defaults(self, data_api_client):
        response = self.client.get('/admin/service-updates')
        self.assertEquals(200, response.status_code)

        self.assertIn(
            '<input class="filter-field-text" id="audit_date" name="audit_date" type="text" value="">',  # noqa
            response.get_data(as_text=True)
        )

        self.assertIn(
            self._replace_whitespace(
                '<input name="acknowledged" value="false" id="acknowledged-3" type="radio" aria-controls="" checked>'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )

        data_api_client.find_audit_events.assert_called()

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_not_allow_invalid_dates(self, data_api_client):
        response = self.client.get('/admin/service-updates?audit_date=invalid')
        self.assertEquals(400, response.status_code)
        self.assertIn(
            "Not a valid date value",
            response.get_data(as_text=True)
        )
        self.assertIn(
            '<input class="filter-field-text" id="audit_date" name="audit_date" type="text" value="invalid">',  # noqa
            response.get_data(as_text=True)
        )

        self.assertIn(
            '
',  # noqa
            response.get_data(as_text=True)
        )

        self.assertIn(
            self._replace_whitespace(
                'Audit Date'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )

        data_api_client.find_audit_events.assert_not_called()

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_not_allow_invalid_acknowledges(self, data_api_client):
        response = self.client.get(
            '/admin/service-updates?acknowledged=invalid'
        )
        self.assertEquals(400, response.status_code)

        self.assertIn(
            self._replace_whitespace(
                'acknowledged'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        data_api_client.find_audit_events.assert_not_called()

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_allow_valid_submission_all(self, data_api_client):
        data_api_client.find_audit_events.return_value = {
            'auditEvents': []
        }

        response = self.client.get('/admin/service-updates?audit_date=2006-01-01&acknowledged=all')  # noqa
        self.assertEquals(200, response.status_code)
        self.assertIn(
            '<input class="filter-field-text" id="audit_date" name="audit_date" type="text" value="2006-01-01">',  # noqa
            response.get_data(as_text=True)
        )

        self.assertIn(
            self._replace_whitespace(
                '<inputname="acknowledged"value="all"id="acknowledged-1"type="radio"aria-controls=""checked>'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        data_api_client.find_audit_events.assert_called()

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_allow_valid_submission_date_fields(self, data_api_client):
        data_api_client.find_audit_events.return_value = {'auditEvents': []}

        response = self.client.get('/admin/service-updates?audit_date=2006-01-01')  # noqa
        self.assertEquals(200, response.status_code)
        self.assertIn(
            '<input class="filter-field-text" id="audit_date" name="audit_date" type="text" value="2006-01-01">',  # noqa
            response.get_data(as_text=True)
        )

        self.assertIn(
            self._replace_whitespace(
                '<inputname="acknowledged"value="false"id="acknowledged-3"type="radio"aria-controls=""checked>'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        data_api_client.find_audit_events.assert_called_with(
            audit_date='2006-01-01',
            audit_type='update_service',
            acknowledged='false')

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_allow_acknowledged_fields(self, data_api_client):
        data_api_client.find_audit_events.return_value = {'auditEvents': []}

        response = self.client.get('/admin/service-updates?acknowledged=false')  # noqa
        self.assertEquals(200, response.status_code)
        self.assertIn(
            '<input class="filter-field-text" id="audit_date" name="audit_date" type="text" value="">',  # noqa
            response.get_data(as_text=True)
        )

        self.assertIn(
            self._replace_whitespace(
                '<inputname="acknowledged"value="false"id="acknowledged-3"type="radio"aria-controls=""checked>'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        data_api_client.find_audit_events.assert_called_with(
            audit_date=None,
            audit_type='update_service',
            acknowledged='false')

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_call_api_with_correct_params(self, data_api_client):
        data_api_client.find_audit_events.return_value = {'auditEvents': []}

        response = self.client.get('/admin/service-updates?audit_date=2006-01-01&acknowledged=all')  # noqa
        self.assertEquals(200, response.status_code)

        data_api_client.find_audit_events.assert_called_with(
            audit_type='update_service',
            audit_date='2006-01-01',
            acknowledged='all')

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_call_api_with_none_date(self, data_api_client):
        data_api_client.find_audit_events.return_value = {'auditEvents': []}

        response = self.client.get('/admin/service-updates?acknowledged=all')  # noqa
        self.assertEquals(200, response.status_code)

        data_api_client.find_audit_events.assert_called_with(
            audit_type='update_service',
            audit_date=None,
            acknowledged='all')

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_render_activity_page_with_form_date(self, data_api_client):
        response = self.client.get(
            '/admin/service-updates?audit_date=2010-01-01'
        )

        self.assertEquals(200, response.status_code)

        date_header = """

            Activity for

        01/01/2010

        """

        self.assertIn(
            self._replace_whitespace(date_header),
            self._replace_whitespace(response.get_data(as_text=True))
        )

        data_api_client.find_audit_events.assert_called()

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_redirect_to_update_page(self, data_api_client):
        response = self.client.post(
            '/admin/service-updates/123/acknowledge',
            data={
                'acknowledged': 'false',
                'audit_date': '2010-01-05'
            }
        )

        self.assertEquals(302, response.status_code)
        self.assertIn(
            'http://localhost/admin/service-updates',
            response.location)
        self.assertIn(
            'acknowledged=false',
            response.location)
        self.assertIn(
            'audit_date=2010-01-05',
            response.location)

        data_api_client.acknowledge_audit_event.assert_called(
            audit_event_id=123,
            user='test@example.com'
        )

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_not_call_api_when_form_errors(self, data_api_client):
        response = self.client.post(
            '/admin/service-updates/123/acknowledge',
            data={
                'acknowledged': 'false',
                'audit_date': 'invalid'
            }
        )

        self.assertEquals(400, response.status_code)
        data_api_client.acknowledge_audit_event.assert_not_called()
        self.assertIn(
            self._replace_whitespace(
                '<inputname="acknowledged"value="false"id="acknowledged-3"type="radio"aria-controls=""checked>'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        self.assertIn(
            '<input class="filter-field-text" id="audit_date" name="audit_date" type="text" value="invalid">',  # noqa
            response.get_data(as_text=True)
        )

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_show_no_updates_if_none_returned(self, data_api_client):
        data_api_client.find_audit_events.return_value = {'auditEvents': []}

        response = self.client.get('/admin/service-updates?audit_date=2006-01-01')  # noqa
        self.assertEquals(200, response.status_code)

        self.assertIn(
            self._replace_whitespace(
                'No activity for this search'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        data_api_client.find_audit_events.assert_called_with(
            audit_date='2006-01-01',
            audit_type='update_service',
            acknowledged='false')

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_show_no_updates_if_invalid_search(self, data_api_client):
        response = self.client.get('/admin/service-updates?audit_date=invalid')  # noqa
        self.assertEquals(400, response.status_code)

        self.assertIn(
            self._replace_whitespace(
                'No activity for this search'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        data_api_client.find_audit_events.assert_not_called()

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_show_updates_if_valid_search(self, data_api_client):

        audit_event = {
            'auditEvents': [
                {
                    'links': {
                        'self': 'http://localhost:5000/adit-events'
                    },
                    'data': {
                        'serviceName': 'new name',
                        'supplierId': 93518,
                        'supplierName': 'Clouded Networks'
                    },
                    'user': 'joeblogs',
                    'type': 'update_service',
                    'id': 25,
                    'createdAt': '2015-06-17T08:49:22.999Z'
                }
            ],
            'links': {}
        }

        data_api_client.find_audit_events.return_value = audit_event
        response = self.client.get('/admin/service-updates?audit_date=2010-01-01')  # noqa
        self.assertEquals(200, response.status_code)

        self.assertIn(
            self._replace_whitespace(
               'Clouded Networks	'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        self.assertIn(
            self._replace_whitespace(
               '08:49:22
17/06/2015	'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        self.assertIn(
            self._replace_whitespace(
               'View changes	'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        self.assertIn(
            self._replace_whitespace(
               '<form action="/admin/service-updates/25/acknowledge" method="post">'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        self.assertIn(
            self._replace_whitespace(
               '<input name="audit_date" type="hidden" value="2010-01-01">'),  # noqa
            self._replace_whitespace(response.get_data(as_text=True))
        )
        data_api_client.find_audit_events.assert_called_with(
            audit_type='update_service',
            acknowledged='false',
            audit_date='2010-01-01')

    @mock.patch('app.main.views.service_updates.data_api_client')
    def test_should_call_api_ack_audit_event(self, data_api_client):
        response = self.client.post('/admin/service-updates/123/acknowledge?audit_date=2010-01-01&acknowledged=all')  # noqa
        self.assertEquals(302, response.status_code)

        data_api_client.acknowledge_audit_event.assert_called_with(
            '123', 'test@example.com'
        )


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Popup : MonoBehaviour
{

    //pause popup
    public Button pauseButton;
    public Button contButton;
    public Button pauseExitButton;
    public GameObject pausePopup;

    bool paused = false;

    //sound
    public Button bgmButton;
    public AudioSource bgm;

    public Button sfxButton;
    public AudioSource sfx;

    //death popup
    public Button playAgainButton;
    public Button deathExitButton;
    public GameObject deathPopup;

    bool dead;

    public GameObject character;
    Health health;

    //score after death
    public GameObject timer;
    Timer score;
    public GameObject currentScore;
    Text curScore;
    public GameObject bestScore;
    Text beScore;
    float _score;
    static int _best;

    // Tutorial Variables
    public GameObject avoidObstaclePopup;
    public GameObject WOncePopup;
    public GameObject WTwicePopup;
    public GameObject tapOncePopup;
    public GameObject tapTwicePopup;
    bool runOnce = false;
    GameObject[] tutPCObjs;
    GameObject[] tutDroidObjs;
    float waitTime = 0.0f;
    int count = 0;
    TouchInput touchInput;

    // PlayerPrefs
    int playedOnce;

    // Use this for initialization
    void Start()
    {
        //pause
        Button pauseBtn = pauseButton.GetComponent<Button>();
        pauseBtn.onClick.AddListener(Pause);

        Button contBtn = contButton.GetComponent<Button>();
        contBtn.onClick.AddListener(Continue);

        Button pExitBtn = pauseExitButton.GetComponent<Button>();
        pauseExitButton.onClick.AddListener(ExitGame);

        pausePopup.SetActive(false);

        //sound

        Button bgmBtn = bgmButton.GetComponent<Button>();
        bgmBtn.onClick.AddListener(delegate { BgmMute(bgm); });

        Button sfxBtn = sfxButton.GetComponent<Button>();
        sfxBtn.onClick.AddListener(delegate { SfxMute(sfx); });

        if (PlayerPrefs.GetInt("bgmOff") == 1)
        {
            bgm.volume = 1;
        }
        else
        {
            bgm.volume = 0;
        }

        if (PlayerPrefs.GetInt("sfxOff") == 1)
        {
            sfx.volume = 1;
        }
        else
        {
            sfx.volume = 0;
        }

        //death
        Button playAgainBtn = playAgainButton.GetComponent<Button>();
        playAgainBtn.onClick.AddListener(PlayAgain);

        Button dExitBtn = deathExitButton.GetComponent<Button>();
        dExitBtn.onClick.AddListener(ExitGame);

        deathPopup.SetActive(false);

        health = character.GetComponent<Health>();
        dead = health.Over;

        //score
        score = timer.GetComponent<Timer>();

        curScore = currentScore.GetComponent<Text>();
        curScore.text = "" + (int)score.time;

        beScore = bestScore.GetComponent<Text>();
        _best = PlayerPrefs.GetInt("_best", _best);
        beScore.text = "" + _best;

        // Tutorial
        tutPCObjs = new GameObject[3];

        tutPCObjs[0] = WOncePopup;
        tutPCObjs[1] = WTwicePopup;
        tutPCObjs[2] = avoidObstaclePopup;

        tutDroidObjs = new GameObject[3];

        tutDroidObjs[0] = tapOncePopup;
        tutDroidObjs[1] = tapTwicePopup;
        tutDroidObjs[2] = avoidObstaclePopup;

        GameObject player = GameObject.Find("Spaceman");
        touchInput = player.GetComponent<TouchInput>();

        // PlayerPrefs
        playedOnce = PlayerPrefs.GetInt("Played");
    }

    // Update is called once per frame
    void Update()
    {
        dead = health.Over;

        if (Paused == false && Dead == false)
        {
            Time.timeScale = 1;
        }
        else
        {
            Death();
            Time.timeScale = 0;
        }

        if ((playedOnce == 0))
        {

            if (!(count > 2))
            {
                RunTutorial();
                PlayerPrefs.SetInt("Played", 1);
                PlayerPrefs.Save();
            }
        }

    }

    public void Pause()
    {
        if (pausePopup.activeSelf == false)
        {
            pausePopup.SetActive(true);
            Paused = true;
        }
    }
    public void Death()
    {
        if (dead == true && deathPopup.activeSelf == false)
        {
            if ((int)score.time > _best)
            {
                _best = (int)score.time;
                beScore.text = "" + _best;
                PlayerPrefs.SetInt("_best", _best);
            }

            curScore.text = "" + (int)score.time;
            deathPopup.SetActive(true);
            Dead = true;
        }
    }
    void Continue()
    {
        if (pausePopup.activeSelf == true)
        {
            pausePopup.SetActive(false);
            Paused = false;
        }
    }

    void ExitGame()
    {
        if (pausePopup.activeSelf == true || deathPopup == true)
        {
            Application.Quit();
        }
    }

    public bool Paused
    {
        get
        {
            return paused;
        }

        set
        {
            paused = value;
        }
    }

    void PlayAgain()
    {
        if (deathPopup.activeSelf == true)
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    }
    public bool Dead
    {
        get
        {
            return dead;
        }
        set
        {
            dead = value;
        }
    }

    void BgmMute(AudioSource source)
    {
        if (PlayerPrefs.GetInt("bgmOff") == 1)
        {
            source.volume = 0;
            PlayerPrefs.SetInt("bgmOff", 0);
        }
        else
        {
            source.volume = 1;
            PlayerPrefs.SetInt("bgmOff", 1);
        }
    }

    void SfxMute(AudioSource source)
    {
        if (PlayerPrefs.GetInt("sfxOff") == 1)
        {
            source.volume = 0;
            PlayerPrefs.SetInt("sfxOff", 0);
        }
        else
        {
            source.volume = 1;
            PlayerPrefs.SetInt("sfxOff", 1);
        }
    }

    public void RunTutorial()
    {
        if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            if (count > 0)
                tutPCObjs[count - 1].SetActive(false);

            if (Input.GetKey(KeyCode.W) && count == 0)
            {
                count = 1;
            }

            if (Input.GetKey(KeyCode.W) && count == 1 && touchInput.NumJumps == 2)
            {
                count = 2;
            }

            if (!tutPCObjs[count].activeSelf)
                tutPCObjs[count].SetActive(true);

            if (count == 2)
            {
                if (Time.time >= waitTime)
                {
                    if (waitTime != 0)
                    {
                        tutDroidObjs[2].SetActive(false);
                        tutPCObjs[2].SetActive(false);

                        count = 3;
                    }

                    waitTime = Time.time + 2.0f;
                }

            }

        }

        if (Application.platform == RuntimePlatform.WindowsPlayer)
        {
            if (count > 0)
                tutPCObjs[count - 1].SetActive(false);
            if (!tutPCObjs[count].activeSelf)
                tutPCObjs[count].SetActive(true);
            count++;
        }

        if (Application.platform == RuntimePlatform.Android)
        {
            if (count > 0)
                tutDroidObjs[count - 1].SetActive(false);
            if (!tutDroidObjs[count].activeSelf)
                tutDroidObjs[count].SetActive(true);
            count++;

        }
    }
}


text:
<?php
namespace cymapgt\core\application\authentication\UserCredential\services;

use cymapgt\Exception\UserCredentialException;

class UserCredentialSmsTokenLoginService extends UserCredentialPasswordLoginService
{
    protected $userTotpProfile = array();    //the totp profile for the user
    protected $keyLength = null;    //key length to use for generating the one time enc key
    protected $verificationHash = null;    //the hash to verify against
    protected $currentOneTimeToken = null;   //the onen time token we expect user to put for this session
    protected $oneTimeToken = null;    //the one time token the user inputs for this session

    //Constructor method
    public function __construct() {

    }

    /**
     * initialize the service, bootstrap before any processing
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-25
     *
     * @access public
     */
    public function initialize() {
        //revert to password only functionality if multi-factor flag is off
        if ($this->_multiFactorFlag === false) {
            parent::initialize();
            return;
        }

        //verify that multi-factor stages is set
        if (
            !(isset($this->_multiFactorStages))
            || !(is_array($this->_multiFactorStages))
            || !(isset($this->_multiFactorStages['current']))
            || !(is_int($this->_multiFactorStages['current']))
            || !(isset($this->_multiFactorStages[1]))
            || !(is_array($this->_multiFactorStages[1]))
            || !(isset($this->keyLength))
        ) {
            throw new UserCredentialException('The multi factor stages register is initialized with an an unknown state', 2100);
        }

        //get the current stage (1 or 2)
        $currentStage = $this->_multiFactorStages['current'];

        //bootstrap depends on which stage we are in
        if ($currentStage == 1) {
            $this->_multiFactorStages[1]['statuss'] = false;
            parent::initialize();
            return;
        } elseif ($currentStage != 2) {
            throw new UserCredentialException('The current stage of the multi factor auth process is in an unknown state', 2101);
        }

        //get the user TOTP profile
        $userTotpProfile = $this->userTotpProfile;

        //we are in stage 2, check that all items are in order
        if (
            !(is_array($userTotpProfile))
            || !(isset($userTotpProfile['enc_key']))
            || !(is_string($userTotpProfile['enc_key']))
            || !(isset($userTotpProfile['totp_timestamp']))
            || !($userTotpProfile['totp_timestamp'] instanceof \DateTime)
            || !(isset($userTotpProfile['totp_timelimit']))
            || !(is_int($userTotpProfile['totp_timelimit']))
            || !(isset($this->verificationHash))
            || !(is_string($this->verificationHash))
            || !(isset($this->oneTimeToken))
            || !(is_string($this->oneTimeToken))
            || !(isset($this->currentOneTimeToken))
            || !(is_string($this->currentOneTimeToken))
        ) {
            throw new UserCredentialException('The user TOTP profile is not initialized properly', 2102);
        }
    }

    /**
     * authenticate the user after initialization
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @access public
     */
    public function authenticate() {
        $currentStage = $this->_multiFactorStages['current'];

        //set stage as inactive
        if ($currentStage == 1) {
            $this->_multiFactorStages[1]['statuss'] = parent::authenticate();

            //stage one sucessfull, bootstrap stage 2
            if ($this->_multiFactorStages[1]['statuss'] === true ) {
                $this->_multiFactorStages[2] = array (
                    'enc_key' => \openssl_random_pseudo_bytes($this->getEncKeyLength()),
                    'statuss' => false
                );
            }

            return $this->_multiFactorStages;
        } elseif ($currentStage != 2) {
            throw new UserCredentialException('The current stage of the multi factor auth process is in an unknown state', 2101);
        }

        //authenticate stage 2
        $totpTimestamp = $this->userTotpProfile['totp_timestamp'];
        $totpTimelimit = $this->userTotpProfile['totp_timelimit'];
        $currDateTime = new \DateTime();
        $totpTimeElapsed = $currDateTime->getTimestamp() - $totpTimestamp->getTimestamp();
        $encKey = $this->userTotpProfile['enc_key'];
        $verificationHash = $this->getVerificationHash();
        $comparisonHash = \crypt($this->getCurrentPassword(), $encKey);
        $currentOneTimeToken = $this->getCurrentOneTimeToken();
        $oneTimeToken = $this->oneTimeToken;

        //initialize verification - comparison
        $verificationEqualsComparison = false;

        //verify if verification hash equals comparison hash. Use hash_equals function if exists
        if (!\function_exists('hash_equals')) {
            if ($verificationHash === $comparisonHash) {
                $verificationEqualsComparison = true;
            }
        } else {
            if (\hash_equals($verificationHash, $comparisonHash)) {
                $verificationEqualsComparison = true;
            }
        }

        if (
            !($totpTimeElapsed < $totpTimelimit)
            || !($verificationEqualsComparison === true)
            || !(\password_verify($oneTimeToken,$currentOneTimeToken))
        ) {
            return false;
        } else {
            return true;
        }
    }

    /**
     *  Return the hashed user password
     *
     * Cyril Ogana <cogana@gmail.com> - 2014-02-13
     *
     * @param  bool $unhashed - flag if true, return unhashed
     *
     * @return string - the hashed password
     *
     * @access public
     */
    public function getPassword(bool $unhashed = false): string {
        //unhashed has no bearing, we want it false
        $unhashedForce = false;
        return parent::getPassword($unhashedForce);
    }

    /**
     *  Set the TOTP profile of the user
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @param  array $totpProfile - TOTP profile array of user
     *
     * @access public
     */
    public function setUserTotpProfile(array $totpProfile) {
        if (!(is_array($totpProfile))) {
            throw new UserCredentialException('The TOTP Profile must be an array', 2104);
        }

        $this->userTotpProfile = $totpProfile;
    }

    /**
     *  Return the user totp profile
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @return array
     * @access public
     */
    public function getUserTotpProfile(): array {
        return $this->userTotpProfile;
    }

    /**
     *  Set the encryption key length
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-22
     *
     * @param  int $keyLength - Length of the encryption key
     *
     * @access public
     */
    public function setEncKeyLength(int $keyLength) {
        $keyLengthCast = (int) $keyLength;

        if (!($keyLengthCast > 0)) {
            throw new UserCredentialException('The encryption key length must be an integer', 2105);
        }

        $this->keyLength = $keyLengthCast;
    }

    /**
     *  Return the encryption key length
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @return int
     * @access public
     */
    public function getEncKeyLength(): int {
        return $this->keyLength;
    }

    /**
     *  Set the verification hash for Stage 2 authentication
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @param  string $verificationHash - Hash to verify for stage 2
     *
     * @access public
     */
    public function setVerificationHash(string $verificationHash) {
        $this->verificationHash = (string) $verificationHash;
    }

    /**
     *  Return the verification hash
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @return string
     * @access public
     */
    public function getVerificationHash():string {
        return $this->verificationHash;
    }

    /**
     *  Set the current one time password
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @param  string $verificationToken - SMS token for the one time login (bcrypt hashed)
     *
     * @access public
     */
    public function setCurrentOneTimeToken(string $verificationToken) {
        $this->currentOneTimeToken = (string) $verificationToken;
    }

    /**
     *  Return the current one time token
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @return string - the hashed password
     * @access public
     */
    public function getCurrentOneTimeToken(): string {
        return $this->currentOneTimeToken;
    }

    /**
     *  Set the verification token expected from user
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @param  string $verificationToken - SMS token for the one time login (bcrypt hashed)
     *
     * @access public
     */
    public function setOneTimeToken(string $verificationToken) {
        $this->oneTimeToken = (string) $verificationToken;
    }

    /**
     *  Return the verification token
     *
     * Cyril Ogana <cogana@gmail.com> - 2015-07-24
     *
     * @param  bool $unhashed - flag if true, return unhashed
     *
     * @return string - the hashed password
     * @access public
     */
    public function getOneTimeToken(bool $unhashed = false): string {
        if ((bool) $unhashed === true) {
            return $this->oneTimeToken;
        } else {
            return \password_hash($this->oneTimeToken, \PASSWORD_DEFAULT);
        }
    }
}


text:
clone-merge
===========

Simple lib to clone and optionally merge json data objects.

This is a wrapper around Underscore and Clone. Making it possible to clone and merge a json object (eg. default options) in one command.