text:
<?php
/**
 * Created Vlad Karapetyan
 */

require_once 'Client_OXD_RP.php';

class Update_site_registration extends Client_OXD_RP
{
    /**start parameter for request!**/
    private $request_authorization_redirect_uri = null;
    private $request_logout_redirect_uri = null;
    private $request_application_type = null;
    private $request_redirect_uris = null;
    private $request_acr_values = null;
    private $request_client_jwks_uri = null;
    private $request_client_token_endpoint_auth_method = null;
    private $request_client_request_uris = null;
    private $request_contacts = null;
    private $request_scope = null;
    private $request_grant_types = null;
    private $request_response_types = null;
    private $request_client_logout_uri = null;
    private $request_oxd_id = null;
    /**end request parameter**/

    /**start parameter for response!**/
    private $response_oxd_id;
    /**end response parameter**/

    public function __construct($base_url='./', $oxd_host_ip= '127.0.0.1', $oxd_host_port=8099)
    {
        parent::__construct($base_url, $oxd_host_ip, $oxd_host_port); // TODO: Change the autogenerated stub
        $this->setRequestApplicationType();
    }

    /**
     * @return null
     */
    public function getRequestClientLogoutUri()
    {
        return $this->request_client_logout_uri;
    }

    /**
     * @param null $request_client_logout_uri
     */
    public function setRequestClientLogoutUri($request_client_logout_uri)
    {
        $this->request_client_logout_uri = $request_client_logout_uri;
    }

    /**
     * @return null
     */
    public function getRequestResponseTypes()
    {
        return $this->request_response_types;
    }

    /**
     * @param null $request_response_types
     */
    public function setRequestResponseTypes($request_response_types)
    {
        $this->request_response_types = $request_response_types;
    }

    /**
     * @return null
     */
    public function getRequestGrantTypes()
    {
        return $this->request_grant_types;
    }

    /**
     * @param null $request_grant_types
     */
    public function setRequestGrantTypes($request_grant_types)
    {
        $this->request_grant_types = $request_grant_types;
    }

    /**
     * @return null
     */
    public function getRequestScope()
    {
        return $this->request_scope;
    }

    /**
     * @param null $request_scope
     */
    public function setRequestScope($request_scope)
    {
        $this->request_scope = $request_scope;
    }

    /**
     * @return null
     */
    public function getRequestLogoutRedirectUri()
    {
        return $this->request_logout_redirect_uri;
    }

    /**
     * @param null $request_logout_redirect_uri
     */
    public function setRequestLogoutRedirectUri($request_logout_redirect_uri)
    {
        $this->request_logout_redirect_uri = $request_logout_redirect_uri;
    }

    /**
     * @return null
     */
    public function getRequestClientJwksUri()
    {
        return $this->request_client_jwks_uri;
    }

    /**
     * @param null $request_client_jwks_uri
     */
    public function setRequestClientJwksUri($request_client_jwks_uri)
    {
        $this->request_client_jwks_uri = $request_client_jwks_uri;
    }

    /**
     * @return null
     */
    public function getRequestClientTokenEndpointAuthMethod()
    {
        return $this->request_client_token_endpoint_auth_method;
    }

    /**
     * @param null $request_client_token_endpoint_auth_method
     */
    public function setRequestClientTokenEndpointAuthMethod($request_client_token_endpoint_auth_method)
    {
        $this->request_client_token_endpoint_auth_method = $request_client_token_endpoint_auth_method;
    }

    /**
     * @return null
     */
    public function getRequestClientRequestUris()
    {
        return $this->request_client_request_uris;
    }

    /**
     * @param null $request_client_request_uris
     */
    public function setRequestClientRequestUris($request_client_request_uris)
    {
        $this->request_client_request_uris = $request_client_request_uris;
    }

    /**
     * @return mixed
     */
    public function getRequestApplicationType()
    {
        return $this->request_application_type;
    }

    /**
     * @param mixed $request_application_type
     */
    public function setRequestApplicationType($request_application_type = 'web')
    {
        $this->request_application_type = $request_application_type;
    }

    /**
     * @return null
     */
    public function getRequestAuthorizationRedirectUri()
    {
        return $this->request_authorization_redirect_uri;
    }

    /**
     * @param null $request_authorization_redirect_uri
     */
    public function setRequestAuthorizationRedirectUri($request_authorization_redirect_uri)
    {
        $this->request_authorization_redirect_uri = $request_authorization_redirect_uri;
    }

    /**
     * @return null
     */
    public function getRequestRedirectUris()
    {
        return $this->request_redirect_uris;
    }

    /**
     * @param null $request_redirect_uris
     */
    public function setRequestRedirectUris($request_redirect_uris)
    {
        $this->request_redirect_uris = $request_redirect_uris;
    }

    /**
     * @return null
     */
    public function getRequestAcrValues()
    {
        return $this->request_acr_values;
    }

    /**
     * @param null $request_acr_values
     */
    public function setRequestAcrValues($request_acr_values = 'basic')
    {
        $this->request_acr_values = $request_acr_values;
    }

    /**
     * @return null
     */
    public function getRequestContacts()
    {
        return $this->request_contacts;
    }

    /**
     * @param null $request_contacts
     */
    public function setRequestContacts($request_contacts)
    {
        $this->request_contacts = $request_contacts;
    }

    /**
     * @return mixed
     */
    public function getResponseOxdId()
    {
        $this->response_oxd_id = $this->getResponseData()->oxd_id;
        return $this->response_oxd_id;
    }

    /**
     * @param mixed $response_oxd_id
     */
    public function setResponseOxdId($response_oxd_id)
    {
        $this->response_oxd_id = $response_oxd_id;
    }

    public function setCommand()
    {
        $this->command = 'update_site_registration';
    }

    /**
     * @return null
     */
    public function getRequestOxdId()
    {
        return $this->request_oxd_id;
    }

    /**
     * @param null $request_oxd_id
     */
    public function setRequestOxdId($request_oxd_id)
    {
        $this->request_oxd_id = $request_oxd_id;
    }

    public function setParams()
    {
        $this->params = array(
            "authorization_redirect_uri" => $this->getRequestAuthorizationRedirectUri(),
            "oxd_id" => $this->getRequestOxdId(),
            "post_logout_redirect_uri" => $this->getRequestLogoutRedirectUri(),
            "application_type" => $this->getRequestApplicationType(),
            "redirect_uris" => $this->getRequestRedirectUris(),
            "acr_values" => $this->getRequestAcrValues(),
            "scope" => $this->getRequestScope(),
            "client_jwks_uri" => $this->getRequestClientJwksUri(),
            "client_token_endpoint_auth_method" => $this->getRequestClientTokenEndpointAuthMethod(),
            "client_request_uris" => $this->getRequestClientRequestUris(),
            "contacts" => $this->getRequestContacts(),
            "grant_types" => $this->getRequestGrantTypes(),
            "response_types"=> $this->getRequestResponseTypes(),
            "client_secret_expires_at"=> 1916258400,
            "client_logout_uris"=> [$this->getRequestClientLogoutUri()]
        );
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AWSSQSGetQueueAttributesResult.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AWSSQSGetQueueAttributesResult</TokenIdentifier>
			<Abstract type="html">A list of returned queue attributes.</Abstract>
			<DeclaredIn>AWSSQSModel.h</DeclaredIn>

			<NodeRef refid="1313"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSSQSGetQueueAttributesResult/setAttributes:</TokenIdentifier>
			<Abstract type="html">
A map of attributes to the respective values.
</Abstract>
			<DeclaredIn>AWSSQSModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSDictionary<NSString*NSString*> *attributes</Declaration>

			<Anchor>//api/name/attributes</Anchor>
            <NodeRef refid="1313"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSSQSGetQueueAttributesResult/attributes</TokenIdentifier>
			<Abstract type="html">
A map of attributes to the respective values.
</Abstract>
			<DeclaredIn>AWSSQSModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSDictionary<NSString*NSString*> *attributes</Declaration>

			<Anchor>//api/name/attributes</Anchor>
            <NodeRef refid="1313"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSSQSGetQueueAttributesResult/attributes</TokenIdentifier>
			<Abstract type="html">
A map of attributes to the respective values.
</Abstract>
			<DeclaredIn>AWSSQSModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSDictionary<NSString*NSString*> *attributes</Declaration>

			<Anchor>//api/name/attributes</Anchor>
            <NodeRef refid="1313"/>
		</Token>

	</File>
</Tokens>


text:
package com.amazonaws.services.simpleemail.model.transform;

import java.util.Map;
import java.util.Map.Entry;

import javax.xml.stream.events.XMLEvent;

import com.amazonaws.services.simpleemail.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * IdentityDkimAttributes StAX Unmarshaller
 */
public class IdentityDkimAttributesStaxUnmarshaller implements
        Unmarshaller<IdentityDkimAttributes, StaxUnmarshallerContext> {

    public IdentityDkimAttributes unmarshall(StaxUnmarshallerContext context)
            throws Exception {
        IdentityDkimAttributes identityDkimAttributes = new IdentityDkimAttributes();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return identityDkimAttributes;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("DkimEnabled", targetDepth)) {
                    identityDkimAttributes
                            .setDkimEnabled(BooleanStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("DkimVerificationStatus",
                        targetDepth)) {
                    identityDkimAttributes
                            .setDkimVerificationStatus(StringStaxUnmarshaller
                                    .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("DkimTokens/member", targetDepth)) {
                    identityDkimAttributes.getDkimTokens().add(
                            StringStaxUnmarshaller.getInstance().unmarshall(
                                    context));
                    continue;
                }

            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return identityDkimAttributes;
                }
            }
        }
    }

    private static IdentityDkimAttributesStaxUnmarshaller instance;

    public static IdentityDkimAttributesStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new IdentityDkimAttributesStaxUnmarshaller();
        return instance;
    }
}


text:
(function (document, window) {
    'use strict';

    var apiKey = "df820485d6830e8a9ccad1703e7bf447";
    var apiURL = 'https://api.flickr.com/services/rest/';

    function searchText(parameters) {
        var requestParameters = Utility.extend(parameters, {
            method: 'flickr.photos.search',
            api_key: apiKey,
            format: 'json'
        });

        var script = document.createElement('script');
        script.src = Utility.buildUrl(apiURL, requestParameters);
        document.head.appendChild(script);
        document.head.removeChild(script);
    }

    function buildThumbnailUrl(photo) {
        return 'https://farm' + photo.farm + '.staticflickr.com/' + photo.server +
        '/' + photo.id + '_' + photo.secret + '_q.jpg';
    }

    function buildPhotoUrl(photo) {
        return 'https://farm' + photo.farm + '.staticflickr.com/' + photo.server +
               '/' + photo.id + '_' + photo.secret + '.jpg';
    }

    function buildPhotoLargeUrl(photo) {
        return 'https://farm' + photo.farm + '.staticflickr.com/' + photo.server +
        '/' + photo.id + '_' + photo.secret + '_b.jpg';
    }

    window.Flickr = Utility.extend(window.Flickr || {}, {
        buildThumbnailUrl: buildThumbnailUrl,
        buildPhotoUrl: buildPhotoUrl,
        buildPhotoLargeUrl: buildPhotoLargeUrl,
        searchText: searchText
    });
})(document, window);


text:
require 'nokogiri'

module MetaInspector
  ##
  # Parses the document with Nokogiri.
  #
  # Delegates the parsing of the different elements to specialized parsers,
  # passing itself as a reference for coordination purposes
  #
  class Parser
    def initialize(document, options = {})
      @document        = document
      @head_links_parser = MetaInspector::Parsers::HeadLinksParser.new(self)
      @meta_tag_parser = MetaInspector::Parsers::MetaTagsParser.new(self)
      @links_parser    = MetaInspector::Parsers::LinksParser.new(self)
      @download_images = options[:download_images]
      @images_parser   = MetaInspector::Parsers::ImagesParser.new(self, download_images: @download_images)
      @texts_parser    = MetaInspector::Parsers::TextsParser.new(self)

      parsed           # parse early so we can fail early
    end

    extend Forwardable
    delegate [:url, :scheme, :host]                          => :@document
    delegate [:meta_tags, :meta_tag, :meta, :charset]        => :@meta_tag_parser
    delegate [:head_links, :stylesheets, :canonicals, :feed] => :@head_links_parser
    delegate [:links, :base_url]                             => :@links_parser
    delegate :images                                         => :@images_parser
    delegate [:title, :best_title, :description]             => :@texts_parser

    # Returns the whole parsed document
    def parsed
      @parsed ||= Nokogiri::HTML(@document.to_s)
    end
  end
end


text:
"""
.. module:: simulation_data
    :platform: Unix, Windows
    :synopsis: Data object for storing metadata and parameter about a simulation run in MongoDB, via the Ming ORM.

.. moduleauthor:: Mark E. Madsen <mark@madsenlab.org>

"""

import logging as log
from ming import Session, Field, schema
from ming.declarative import Document
from dbutils import generate_collection_id

__author__ = 'mark'

def _get_dataobj_id():
    """
        Returns the short handle used for this data object in Ming configuration
    """
    return 'simulations'

def _get_collection_id():
    """
    :return: returns the collection name for this data object
    """
    return generate_collection_id("_samples_raw")

def store_simulation_timing(sim_id,ruleclass,popclass,script,exp,elapsed,length):
    """Stores the parameters and metadata for a simulation run in the database.

    """
    SimulationTiming(dict(
        script_filename = script,
        rule_class = ruleclass,
        pop_class = popclass,
        simulation_run_id = sim_id,
        experiment_name = exp,
        elapsed_time = elapsed,
        run_length = length
    )).m.insert()
    return True

def columns_to_export_for_analysis():
    cols = [
        "simulation_run_id",
        "experiment_name",
        "elapsed_time",
        "run_length"
    ]
    return cols

class SimulationTiming(Document):

    class __mongometa__:
        session = Session.by_name(_get_dataobj_id())
        name = 'simulation_timing'

    _id = Field(schema.ObjectId)
    script_filename = Field(str)
    rule_class = Field(str)
    pop_class = Field(str)
    simulation_run_id = Field(str)
    experiment_name = Field(str)
    elapsed_time = Field(float)
    run_length = Field(int)


text:
//  Copyright 2022 Google LLC. All Rights Reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

using System.IO;

namespace NtApiDotNet.Utilities.ASN1
{
    internal class DERParserStream
    {
        private readonly MemoryStream _stm;
        private readonly BinaryReader _reader;
        private readonly long _offset;

        public DERParserStream(byte[] data, int index, int count, long offset)
        {
            _stm = new MemoryStream(data, index, count);
            _reader = new BinaryReader(_stm);
            _offset = offset;
        }

        public DERValue ReadValue()
        {
            DERValue ret = new DERValue();
            ret.Offset = _offset + _stm.Position;
            byte id = _reader.ReadByte();
            ret.Type = (DERTagType)(id >> 6);
            ret.Constructed = (id & 0x20) != 0;
            ret.Tag = id & 0x1F;
            if (ret.Tag == 0x1F)
            {
                ret.Tag = _reader.ReadEncodedInt();
            }
            // TODO: Handle indefinite length?
            int length = _reader.ReadLength();
            ret.DataOffset = _offset + _stm.Position;
            ret.Data = _reader.ReadAllBytes(length);
            return ret;
        }

        public bool Done => _stm.Position >= _stm.Length;
    }
}


text:
package gwtquery.plugins.droppable.client.draughtssample;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.ui.RootPanel;

import gwtquery.plugins.droppable.client.draughtssample.resources.DraughtsResources;

/**
 * Checker sample entry point !
 *
 * @author Julien Dramaix (julien.dramaix@gmail.com)
 *
 */
public class DraughtsSample implements EntryPoint {

  public static EventBus EVENT_BUS = new SimpleEventBus();

  public void onModuleLoad() {
    DraughtsResources.INSTANCE.css().ensureInjected();

    RootPanel.get("draughts").add(new CheckerBoard());
    RootPanel.get("score").add(new ScorePanel());

    GameController gameController = GameController.getInstance();
    gameController.reset();
    gameController.startGame();
  }

}


text:
using Newtonsoft.Json;

namespace IBM.Watson.Discovery.V2.Model
{
    /// <summary>
    /// A collection for storing documents.
    /// </summary>
    public class Collection
    {
        /// <summary>
        /// The unique identifier of the collection.
        /// </summary>
        [JsonProperty("collection_id", NullValueHandling = NullValueHandling.Ignore)]
        public virtual string CollectionId { get; private set; }
        /// <summary>
        /// The name of the collection.
        /// </summary>
        [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
        public string Name { get; set; }
    }
}


text:
#region License
// TableDependency, SqlTableDependency, SqlTableDependencyFilter
// Copyright (c) 2015-2020 Christian Del Bianco. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

using TableDependency.SqlClient.Base;
using TableDependency.SqlClient.Base.Abstracts;
using TableDependency.SqlClient.Where.Helpers;

namespace TableDependency.SqlClient.Where
{
    public class SqlTableDependencyFilter<T> : ExpressionVisitor, ITableDependencyFilter where T : class, new()
    {
        #region Constructors

        private readonly ParameterHelper _parameter = new ParameterHelper();
        private readonly Expression _filter;
        private readonly IDictionary<string, string> _modelMapperDictionary;

        private readonly StringBuilder _whereConditionBuilder = new StringBuilder();
        private readonly IList<Type> _types = new List<Type>()
        {
            typeof (short),
            typeof (short?),
            typeof (int),
            typeof (int?),
            typeof (long),
            typeof (long?),
            typeof (string),
            typeof (decimal),
            typeof (decimal?),
            typeof (float),
            typeof (float?),
            typeof (DateTime),
            typeof (DateTime?),
            typeof (double),
            typeof (double?),
            typeof (bool),
            typeof (bool?)
        };

        #endregion

        #region Constructors
        public SqlTableDependencyFilter(Expression filter, IModelToTableMapper<T> modelMapperDictionary = null)
        {
            _filter = filter;

            _modelMapperDictionary = modelMapperDictionary != null && modelMapperDictionary.Count() > 0
                ? modelMapperDictionary.GetMappings().ToDictionary(kvp => kvp.Key.Name, kvp => kvp.Value)
                : this.CreateModelToTableMapperHelper()?.GetMappings().ToDictionary(kvp => kvp.Key.Name, kvp => kvp.Value);
        }

        #endregion

        #region Public Methods

        public string Translate()
        {
            if (_whereConditionBuilder.Length > 0) return _whereConditionBuilder.ToString().Trim();

            this.Visit(_filter);
            return _whereConditionBuilder.ToString().Trim();
        }

        #endregion

        #region Protected Methods

        protected override Expression VisitMethodCall(MethodCallExpression m)
        {
            if (m.Method.DeclaringType == typeof(Queryable) && m.Method.Name == "Where")
            {
                throw new ArgumentException();
            }

            #region Trim

            if (m.Method.Name == "Trim")
            {
                _whereConditionBuilder.Append("LTRIM(RTRIM(");
                this.Visit(m.Object);
                _whereConditionBuilder.Append("))");

                return m;
            }

            #endregion

            #region StartsWith

            if (m.Method.Name == "StartsWith")
            {
                this.Visit(m.Object);
                _whereConditionBuilder.Append(" LIKE ");

                _parameter.Append = "%";
                this.Visit(m.Arguments[0]);
                return m;
            }

            #endregion

            #region EndsWith

            if (m.Method.Name == "EndsWith")
            {
                this.Visit(m.Object);
                _whereConditionBuilder.Append(" LIKE ");

                _parameter.Prepend = "%";
                this.Visit(m.Arguments[0]);
                return m;
            }

            #endregion

            #region Contains

            if (m.Method.Name == "Contains")
            {
                if (m.Object == null)
                {
                    this.Visit((MemberExpression)m.Arguments[1]);
                    _whereConditionBuilder.Append(" IN ");
                    var memberExpression = (MemberExpression)m.Arguments[0];
                    if (memberExpression.Expression.NodeType == ExpressionType.Constant) this.Visit(memberExpression.Expression);
                }
                else
                {
                    this.Visit(m.Object);
                    _whereConditionBuilder.Append(" LIKE ");

                    _parameter.Prepend = "%";
                    _parameter.Append = "%";
                    this.Visit(m.Arguments[0]);
                }

                return m;
            }

            #endregion

            #region TrimStart

            if (m.Method.Name == "TrimStart")
            {
                _whereConditionBuilder.Append("LTRIM(");
                this.Visit(m.Object);
                _whereConditionBuilder.Append(")");

                return m;
            }

            #endregion

            #region TrimEnd

            if (m.Method.Name == "TrimEnd")
            {
                _whereConditionBuilder.Append("RTRIM(");
                this.Visit(m.Object);
                _whereConditionBuilder.Append(")");

                return m;
            }

            #endregion

            #region ToUpper

            if (m.Method.Name == "ToUpper")
            {
                _whereConditionBuilder.Append("UPPER(");
                this.Visit(m.Object);
                _whereConditionBuilder.Append(")");

                return m;
            }

            #endregion

            #region ToLower

            if (m.Method.Name == "ToLower")
            {
                _whereConditionBuilder.Append("LOWER(");
                this.Visit(m.Object);
                _whereConditionBuilder.Append(")");

                return m;
            }

            #endregion

            #region Substring

            if (m.Method.Name == "Substring")
            {
                _whereConditionBuilder.Append("SUBSTRING(");
                this.Visit(m.Object);

                var startParameter = (ConstantExpression)m.Arguments[0];
                if (!int.TryParse(startParameter?.Value.ToString(), out int intResult)) throw new ArgumentNullException();
                _whereConditionBuilder.Append(", " + intResult);

                var lenParameter = (ConstantExpression)m.Arguments[1];
                if (!int.TryParse(lenParameter?.Value.ToString(), out intResult)) throw new ArgumentNullException();
                _whereConditionBuilder.Append(", " + intResult + ")");

                return m;
            }

            #endregion

            #region ToString

            if (m.Method.Name == "ToString")
            {
                _whereConditionBuilder.Append("CONVERT(varchar(MAX), ");
                this.Visit(m.Object);
                _whereConditionBuilder.Append(")");

                return m;
            }

            #endregion

            #region Equals

            if (m.Method.Name == "Equals" && m.Object != null)
            {
                this.Visit(m.Object);
                _whereConditionBuilder.Append(" = ");
                this.Visit(m.Arguments[0]);

                return m;
            }

            #endregion

            throw new NotSupportedException($"The method '{m.Method.Name}' is not supported.");
        }

        protected override Expression VisitUnary(UnaryExpression u)
        {
            switch (u.NodeType)
            {
                case ExpressionType.Not:
                    _whereConditionBuilder.Append(" NOT ");
                    this.Visit(u.Operand);
                    break;

                case ExpressionType.Convert:
                    this.Visit(u.Operand);
                    break;

                default:
                    throw new NotSupportedException($"The unary operator '{u.NodeType}' is not supported.");
            }

            return u;
        }

        protected override Expression VisitBinary(BinaryExpression b)
        {
            _whereConditionBuilder.Append("(");

            this.Visit(b.Left);

            switch (b.NodeType)
            {
                case ExpressionType.And:
                    _whereConditionBuilder.Append(" AND ");
                    break;

                case ExpressionType.AndAlso:
                    _whereConditionBuilder.Append(" AND ");
                    break;

                case ExpressionType.Or:
                    _whereConditionBuilder.Append(" OR ");
                    break;

                case ExpressionType.OrElse:
                    _whereConditionBuilder.Append(" OR ");
                    break;

                case ExpressionType.Equal:
                    _whereConditionBuilder.Append(IsNullConstant(b.Right) ? " IS " : " = ");
                    break;

                case ExpressionType.NotEqual:
                    _whereConditionBuilder.Append(IsNullConstant(b.Right) ? " IS NOT " : " <> ");
                    break;

                case ExpressionType.LessThan:
                    _whereConditionBuilder.Append(" < ");
                    break;

                case ExpressionType.LessThanOrEqual:
                    _whereConditionBuilder.Append(" <= ");
                    break;

                case ExpressionType.GreaterThan:
                    _whereConditionBuilder.Append(" > ");
                    break;

                case ExpressionType.GreaterThanOrEqual:
                    _whereConditionBuilder.Append(" >= ");
                    break;

                default:
                    throw new NotSupportedException($"The binary operator '{b.NodeType}' is not supported.");
            }

            this.Visit(b.Right);

            _whereConditionBuilder.Append(")");

            return b;
        }

        protected override Expression VisitConstant(ConstantExpression c)
        {
            var q = c.Value as IQueryable;
            if (q == null && c.Value == null)
            {
                _whereConditionBuilder.Append("NULL");
            }
            else if (q == null)
            {
                switch (Type.GetTypeCode(c.Value.GetType()))
                {
                    case TypeCode.Boolean:
                        _whereConditionBuilder.Append(this.ToSqlFormat(c.Value.GetType(), c.Value));
                        break;

                    case TypeCode.String:
                        _whereConditionBuilder.Append("'");
                        _whereConditionBuilder.Append(_parameter.Prepend);
                        _whereConditionBuilder.Append(this.ToSqlFormat(c.Value.GetType(), c.Value));
                        _whereConditionBuilder.Append(_parameter.Append);
                        _whereConditionBuilder.Append("'");
                        break;

                    case TypeCode.Decimal:
                        _whereConditionBuilder.Append(this.ToSqlFormat(c.Value.GetType(), c.Value));
                        break;

                    case TypeCode.Double:
                        _whereConditionBuilder.Append(this.ToSqlFormat(c.Value.GetType(), c.Value));
                        break;

                    case TypeCode.DateTime:
                        _whereConditionBuilder.Append("'");
                        _whereConditionBuilder.Append(this.ToSqlFormat(c.Value.GetType(), c.Value));
                        _whereConditionBuilder.Append("'");
                        break;

                    case TypeCode.Object:
                        Type previousType = null;
                        var fieldInfos = c.Type.GetFields(BindingFlags.Public | BindingFlags.Instance);
                        if (typeof(IEnumerable).IsAssignableFrom(fieldInfos[0].FieldType))
                        {
                            var valuesToPrint = new List<string>();
                            var values = (IEnumerable)fieldInfos[0].GetValue(c.Value);
                            foreach (var value in values)
                            {
                                if (!_types.Contains(value.GetType())) throw new ArgumentException();
                                if (previousType != null && previousType != value.GetType()) throw new ArgumentException();

                                var quotes = this.Quotes(value.GetType());
                                valuesToPrint.Add($"{quotes}{this.ToSqlFormat(value.GetType(), value)}{quotes}");

                                previousType = value.GetType();
                            }
                            _whereConditionBuilder.Append("(" + string.Join(",", valuesToPrint) + ")");
                        }
                        else
                        {
                            throw new NotSupportedException($"The constant for '{c.Value}' is not supported");
                        }

                        break;

                    default:
                        _whereConditionBuilder.Append(this.ToSqlFormat(c.Value.GetType(), c.Value));
                        break;
                }
            }

            return c;
        }

        protected override Expression VisitMember(MemberExpression m)
        {
            if (m.Expression is ConstantExpression constantExpression)
            {
                var lambda = Expression.Lambda(m);
                var fn = lambda.Compile();
                return this.Visit(Expression.Constant(fn.DynamicInvoke(null), m.Type));
            }

            if (m.Expression is MemberExpression subMemberExpression)
            {
                throw new NotSupportedException("Cannot manage complex properties");
            }

            _whereConditionBuilder.Append($"[{this.GetDataBaseColumnName(m.Member.Name)}]");

            return m;
        }

        #endregion

        #region Private Methods

        private ModelToTableMapper<T> CreateModelToTableMapperHelper()
        {
            var modelPropertyInfosWithColumnAttribute = typeof(T)
                    .GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public)
                    .Where(x => CustomAttributeExtensions.IsDefined(x, typeof(ColumnAttribute), false))
                    .ToArray();

            if (!modelPropertyInfosWithColumnAttribute.Any()) return null;

            var mapper = new ModelToTableMapper<T>();
            foreach (var propertyInfo in modelPropertyInfosWithColumnAttribute)
            {
                var attribute = propertyInfo.GetCustomAttribute(typeof(ColumnAttribute));
                var dbColumnName = ((ColumnAttribute)attribute)?.Name;
                if (string.IsNullOrWhiteSpace(dbColumnName))
                {
                    dbColumnName = propertyInfo.Name;
                    mapper.AddMapping(propertyInfo, dbColumnName);
                }

                mapper.AddMapping(propertyInfo, dbColumnName);
            }

            return mapper;
        }

        private string GetDataBaseColumnName(string memberName)
        {
            if (_modelMapperDictionary == null || !_modelMapperDictionary.Any()) return memberName;
            var mapping = _modelMapperDictionary.FirstOrDefault(mm => mm.Key.ToLower() == memberName.ToLower());

            return default(KeyValuePair<string, string>).Equals(mapping)
                ? memberName
                : mapping.Value.Replace("[", string.Empty).Replace("]", string.Empty);
        }

        private string ToSqlFormat(Type type, object value)
        {
            if (type == typeof(bool)) return (bool)value ? "1" : "0";

            if (type == typeof(string)) return value.ToString();

            if (type == typeof(decimal)) return Convert.ToDecimal(value).ToString("g", CultureInfo.InvariantCulture);

            if (type == typeof(double)) return Convert.ToDouble(value).ToString("g", CultureInfo.InvariantCulture);

            if (type == typeof(DateTime)) return Convert.ToDateTime(value).ToString("s", CultureInfo.InvariantCulture);

            return value.ToString();
        }

        protected string Quotes(Type type)
        {
            if (type == typeof(string)) return "'";
            if (type == typeof(DateTime)) return "'";

            return string.Empty;
        }

        protected bool IsNullConstant(Expression exp)
        {
            return exp.NodeType == ExpressionType.Constant && ((ConstantExpression)exp).Value == null;
        }

        #endregion
    }
}


text:
namespace Microsoft.Azure.Management.ResourceManager.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The value of a parameter.
    /// </summary>
    public partial class ParameterValuesValue
    {
        /// <summary>
        /// Initializes a new instance of the ParameterValuesValue class.
        /// </summary>
        public ParameterValuesValue()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ParameterValuesValue class.
        /// </summary>
        /// <param name="value">The value of the parameter.</param>
        public ParameterValuesValue(object value = default(object))
        {
            Value = value;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the value of the parameter.
        /// </summary>
        [JsonProperty(PropertyName = "value")]
        public object Value { get; set; }

    }
}


text:
title: How to Create a Simple CSS Dropdown Menu
date: "2013-08-12T07:00:00.000Z"
path: "/articles/create-a-simple-css-dropdown/"
excerpt: "Dropdown menus provide a nice hierarchical view of your menu structure, allowing you to help narrow the visitors focus and find exactly what they're looking for and reducing navigation clutter."
category:
  label: 'Frontend'
  slug: 'frontend'
---

Dropdown menus provide a nice hierarchical view of your menu structure, allowing you to help narrow the visitors focus and find exactly what they're looking for and reducing navigation clutter. Today, we'll take a look at how to create a CSS dropdown menu. This is a very simple implementation that is ideal for just about any situation.

This is the same CSS dropdown that is used here on CSSForge, minus the jQuery slide out animation. If you decide to add jQuery animation, this also serves as a graceful fallback for slow connections and terrible browsers.

Without further ado:

See the Pen Simple CSS Dropdown Menu by Jon Bellah (@jonbellah) on CodePen.

### The HTML

There's not a lot about the HTML that's special. The main thing to note is that we've nested the sub-menu `ul` inside the `li` where we want it to drop from, in this case the Snippets `li`. This is the same way that WordPress nests menu and sub-menu items; so if you're using the built-in WordPress menu manager, then you don't need to make any changes to your HTML.

### The CSS

There are a few important parts of our CSS. The first is `.site-navigation ul li ul { visibility: hidden; }`. This hides our dropdown menu by default. The second important piece of CSS is the `.site-navigation ul li:hover > ul { visibility: visible; }`. This makes our dropdown menu display whenever the visitor hovers over the associated `li`. To ensure that our dropdown menu displays under the correct menu item, we set our `.site-navigation li { position: relative; }`, so that we can `positon:absolute;` the dropdown `ul`


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>maJoo</title>

        <link href="css/bootstrap.css" media="all" rel="stylesheet" type="text/css" />
        <link href="css/font-awesome.css" media="all" rel="stylesheet" type="text/css" />
        <link href="css/style.css" media="all" rel="stylesheet" type="text/css" />
        <link href="css/style-responsive.css" media="all" rel="stylesheet" type="text/css" />
        <link rel="stylesheet" type="text/css" media="all" href="css/colors/default.css" id="colors">
        <link href="css/flexslider.css" media="all" rel="stylesheet" type="text/css" />

        <link rel="stylesheet" type="text/css" href="css/switcher.css">

                                Home

Default

Static Video Header

Version 3

                                PAGES

ABOUT US

SERVICES

FULL WIDTH

SIDEBAR RIGHT

SIDEBAR LEFT

FAQs

                                BLOG

SINGLE POST

BLOG POSTS

                                PORTFOLIO

2 COLUMNS

3 COLUMNS

4 COLUMNS

SINGLE PROJECT

                                FEATURES

SHORTCODES

PRICING TABLE

MARKETING PAGE

FEATURES PAGE

GALLERY

CONTACT US

All

Interior Design

Architecture

Scenery

Real Estate

Portfolio / 2 Columns

Maritime Details

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

Grand Canyon

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

Pine Tree Near Water

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

Grand Canyon

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

Pine Tree Near Water

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

Pine Tree Near Water

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

Maritime Details

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

Grand Canyon

Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim ligula non nibh ornare tempus. Fusce iaculis diam mattis vestibulum.

About Us

Press

Partner with maJoo

Terms

Privacy Policy

Jobs

Contact Us

Predefined Colors

Reset


text:
using System;
using System.Linq;
using FlaUI.Core;
using FlaUI.Core.AutomationElements.Infrastructure;
using FlaUI.Core.Conditions;
using FlaUI.Core.Definitions;
using FlaUI.Core.EventHandlers;
using FlaUI.Core.Identifiers;
using FlaUI.Core.Shapes;
using FlaUI.Core.Tools;
using FlaUI.UIA3.Converters;
using FlaUI.UIA3.EventHandlers;
using FlaUI.UIA3.Extensions;
using UIA = Interop.UIAutomationClient;

namespace FlaUI.UIA3
{
    public class UIA3BasicAutomationElement : BasicAutomationElementBase
    {
        public UIA3BasicAutomationElement(UIA3Automation automation, UIA.IUIAutomationElement nativeElement) : base(automation)
        {
            Automation = automation;
            NativeElement = nativeElement;
            Patterns = new UIA3AutomationElementPatternValues(this);
        }

        /// <summary>
        /// Concrete implementation of the automation object
        /// </summary>
        public new UIA3Automation Automation { get; }

        /// <summary>
        /// Native object for the ui element
        /// </summary>
        public UIA.IUIAutomationElement NativeElement { get; }

        /// <summary>
        /// Native object for Windows 8 ui element
        /// </summary>
        public UIA.IUIAutomationElement NativeElement2 => GetAutomationElementAs<UIA.IUIAutomationElement2>();

        /// <summary>
        /// Native object for Windows 8.1 ui element
        /// </summary>
        public UIA.IUIAutomationElement NativeElement3 => GetAutomationElementAs<UIA.IUIAutomationElement3>();

        public override void SetFocus()
        {
            NativeElement.SetFocus();
        }

        protected override object InternalGetPropertyValue(int propertyId, bool cached, bool useDefaultIfNotSupported)
        {
            var ignoreDefaultValue = useDefaultIfNotSupported ? 0 : 1;
            var returnValue = cached ?
                NativeElement.GetCachedPropertyValueEx(propertyId, ignoreDefaultValue) :
                NativeElement.GetCurrentPropertyValueEx(propertyId, ignoreDefaultValue);
            return returnValue;
        }

        protected override object InternalGetPattern(int patternId, bool cached)
        {
            var returnedValue = cached
                ? NativeElement.GetCachedPattern(patternId)
                : NativeElement.GetCurrentPattern(patternId);
            return returnedValue;
        }

        /// <inheritdoc />
        public override AutomationElement[] FindAll(TreeScope treeScope, ConditionBase condition)
        {
            var nativeFoundElements = CacheRequest.IsCachingActive
                ? NativeElement.FindAllBuildCache((UIA.TreeScope)treeScope, ConditionConverter.ToNative(Automation, condition), CacheRequest.Current.ToNative(Automation))
                : NativeElement.FindAll((UIA.TreeScope)treeScope, ConditionConverter.ToNative(Automation, condition));
            return AutomationElementConverter.NativeArrayToManaged(Automation, nativeFoundElements);
        }

        /// <inheritdoc />
        public override AutomationElement FindFirst(TreeScope treeScope, ConditionBase condition)
        {
            var nativeFoundElement = CacheRequest.IsCachingActive
                ? NativeElement.FindFirstBuildCache((UIA.TreeScope)treeScope, ConditionConverter.ToNative(Automation, condition), CacheRequest.Current.ToNative(Automation))
                : NativeElement.FindFirst((UIA.TreeScope)treeScope, ConditionConverter.ToNative(Automation, condition));
            return AutomationElementConverter.NativeToManaged(Automation, nativeFoundElement);
        }

        /// <inheritdoc />
        public override AutomationElement FindIndexed(TreeScope treeScope, int index, ConditionBase condition)
        {
            var nativeFoundElements = CacheRequest.IsCachingActive
                ? NativeElement.FindAllBuildCache((UIA.TreeScope)treeScope, ConditionConverter.ToNative(Automation, condition), CacheRequest.Current.ToNative(Automation))
                : NativeElement.FindAll((UIA.TreeScope)treeScope, ConditionConverter.ToNative(Automation, condition));
            var nativeElement = nativeFoundElements.GetElement(index);
            return nativeElement == null ? null : AutomationElementConverter.NativeToManaged(Automation, nativeElement);
        }

        public override bool TryGetClickablePoint(out Point point)
        {
            var tagPoint = new UIA.tagPOINT { x = 0, y = 0 };
            var success = Com.Call(() => NativeElement.GetClickablePoint(out tagPoint)) != 0;
            if (success)
            {
                point = new Point(tagPoint.x, tagPoint.y);
            }
            else
            {
                success = Properties.ClickablePoint.TryGetValue(out point);
            }
            return success;
        }

        public override IAutomationEventHandler RegisterEvent(EventId @event, TreeScope treeScope, Action<AutomationElement, EventId> action)
        {
            var eventHandler = new UIA3BasicEventHandler(Automation, action);
            Automation.NativeAutomation.AddAutomationEventHandler(@event.Id, NativeElement, (UIA.TreeScope)treeScope, null, eventHandler);
            return eventHandler;
        }

        public override IAutomationPropertyChangedEventHandler RegisterPropertyChangedEvent(TreeScope treeScope, Action<AutomationElement, PropertyId, object> action, PropertyId[] properties)
        {
            var eventHandler = new UIA3PropertyChangedEventHandler(Automation, action);
            var propertyIds = properties.Select(p => p.Id).ToArray();
            Automation.NativeAutomation.AddPropertyChangedEventHandler(NativeElement,
                (UIA.TreeScope)treeScope, null, eventHandler, propertyIds);
            return eventHandler;
        }

        public override IAutomationStructureChangedEventHandler RegisterStructureChangedEvent(TreeScope treeScope, Action<AutomationElement, StructureChangeType, int[]> action)
        {
            var eventHandler = new UIA3StructureChangedEventHandler(Automation, action);
            Automation.NativeAutomation.AddStructureChangedEventHandler(NativeElement, (UIA.TreeScope)treeScope, null, eventHandler);
            return eventHandler;
        }

        public override void RemoveAutomationEventHandler(EventId @event, IAutomationEventHandler eventHandler)
        {
            Automation.NativeAutomation.RemoveAutomationEventHandler(@event.Id, NativeElement, (UIA3BasicEventHandler)eventHandler);
        }

        public override void RemovePropertyChangedEventHandler(IAutomationPropertyChangedEventHandler eventHandler)
        {
            Automation.NativeAutomation.RemovePropertyChangedEventHandler(NativeElement, (UIA3PropertyChangedEventHandler)eventHandler);
        }

        public override void RemoveStructureChangedEventHandler(IAutomationStructureChangedEventHandler eventHandler)
        {
            Automation.NativeAutomation.RemoveStructureChangedEventHandler(NativeElement, (UIA3StructureChangedEventHandler)eventHandler);
        }

        public override PatternId[] GetSupportedPatterns()
        {
            Automation.NativeAutomation.PollForPotentialSupportedPatterns(NativeElement, out int[] rawIds, out string[] _);
            return rawIds.Select(id => PatternId.Find(Automation.AutomationType, id)).ToArray();
        }

        public override PropertyId[] GetSupportedProperties()
        {
            Automation.NativeAutomation.PollForPotentialSupportedProperties(NativeElement, out int[] rawIds, out string[] _);
            return rawIds.Select(id => PropertyId.Find(Automation.AutomationType, id)).ToArray();
        }

        public override AutomationElement GetUpdatedCache()
        {
            if (CacheRequest.Current != null)
            {
                var updatedElement = NativeElement.BuildUpdatedCache(CacheRequest.Current.ToNative(Automation));
                return AutomationElementConverter.NativeToManaged(Automation, updatedElement);
            }
            return null;
        }

        public override AutomationElement[] GetCachedChildren()
        {
            var cachedChildren = NativeElement.GetCachedChildren();
            return AutomationElementConverter.NativeArrayToManaged(Automation, cachedChildren);
        }

        public override AutomationElement GetCachedParent()
        {
            var cachedParent = NativeElement.GetCachedParent();
            return AutomationElementConverter.NativeToManaged(Automation, cachedParent);
        }

        public override int GetHashCode()
        {
            return NativeElement.GetHashCode();
        }

        /// <summary>
        /// Tries to cast the automation element to a specific interface.
        /// Throws an exception if that is not possible.
        /// </summary>
        private T GetAutomationElementAs<T>() where T : class, UIA.IUIAutomationElement
        {
            var element = NativeElement as T;
            if (element == null)
            {
                throw new NotSupportedException($"OS does not have {typeof(T).Name} support.");
            }
            return element;
        }
    }
}


text:
<?php
namespace Lcobucci\DependencyInjection\Generators;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

/**
 * @author Luís Otávio Cobucci Oblonczyk <lcobucci@gmail.com>
 */
class XmlTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     *
     * @covers Lcobucci\DependencyInjection\Generator::__construct
     * @covers Lcobucci\DependencyInjection\Generators\Xml::getLoader
     */
    public function getLoaderShouldReturnAXmlLoader()
    {
        $container = $this->getMock(ContainerBuilder::class);
        $generator = new Xml();

        $this->assertInstanceOf(XmlFileLoader::class, $generator->getLoader($container, []));
    }
}


text:
package com.bwsw.sj.common.utils.benchmark

import com.typesafe.config.ConfigFactory

/**
  * Sends a sequence of numbers from <first> to <last> into Kafka topic
  *
  * Configuration:
  *
  * test.kafka.address - Kafka server's address. Environment variable KAFKA_ADDRESS.
  *
  * test.kafka.topic - Kafka topic. Environment variable KAFKA_TOPIC.
  *
  * test.kafka.first - <first> (1 by default). Environment variable FIRST.
  *
  * test.kafka.last - <last>. Environment variable LAST.
  *
  * @author Pavel Tomskikh
  */
object KafkaNumberSequenceSender extends App {
  private val config = ConfigFactory.load()
  private val kafkaAddress = config.getString("test.kafka.address")
  private val topic = config.getString("test.kafka.topic")
  private val first = config.getInt("test.kafka.first")
  private val last = config.getInt("test.kafka.last")
  private val sender = new KafkaDataSender(kafkaAddress)

  sender.send((first to last).map(Int.box), topic)
}


text:
package kr.debop4j.data.mapping.model.annotated.join;

import com.google.common.base.Objects;
import kr.debop4j.core.ValueObjectBase;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
 * org.annotated.mapping.domain.model.join.JpaJoinAddress
 *
 * @author 배성혁 ( sunghyouk.bae@gmail.com )
 * @since 12. 12. 5.
 */
@Embeddable
@Getter
@Setter
public class JpaJoinAddress extends ValueObjectBase {

    private static final long serialVersionUID = -3754337530016792857L;

    @Column(name = "STREET", length = 128)
    private String street;

    @Column(name = "ZIPCODE", length = 12)
    private String zipcode;

    @Column(name = "CITY", length = 64)
    private String city;

    @Override
    public int hashCode() {
        return Objects.hashCode(street, zipcode, city);
    }

    @Override
    protected Objects.ToStringHelper buildStringHelper() {
        return super.buildStringHelper()
                .add("street", street)
                .add("zipcode", zipcode)
                .add("city", city);
    }
}


text:
This package provides models for running real-time hand pose detection.

Currently, we provide 1 model option:

#### MediaPipe:
[Demo](https://storage.googleapis.com/tfjs-models/demos/hand-pose-detection/index.html?model=mediapipe_hands)

MediaPipe Hands can detect multiple hands, each hand contains 21 3D hand keypoints.

More background information about the model, as well as its performance characteristics on different datasets, can be found here: [Model Card](https://drive.google.com/file/d/1-rmIgTfuCbBPW_IFHkh3f0-U_lnGrWpg/view)

-------------------------------------------------------------------------------
## Table of Contents
1. [How to Run It](#how-to-run-it)
2. [Keypoint Diagram](#keypoint-diagram)
3. [Example Code and Demos](#example-code-and-demos)

-------------------------------------------------------------------------------
## How to Run It
In general there are two steps:

You first create a detector by choosing one of the models from `SupportedModels`,
including `MediaPipeHands`.

For example:

```javascript
const model = handPoseDetection.SupportedModels.MediaPipeHands;
const detectorConfig = {
  runtime: 'mediapipe', // or 'tfjs',
  solutionPath: 'https://cdn.jsdelivr.net/npm/@mediapipe/hands',
  modelType: 'full'
}
const detector = await handPoseDetection.createDetector(model, detectorConfig);
```

Then you can use the detector to detect hands.

```
const hands = await detector.estimateHands(image);
```

The returned hands list contains detected hands for each hand in the image.
If the model cannot detect any hands, the list will be empty.

For each hand, it contains a prediction of the handedness (left or right), a confidence score of this prediction, as well as an array of keypoints.
MediaPipeHands returns 21 keypoints.
Each keypoint contains x and y, as well as a name. In addition, an array of 3D keypoints is returned.

Example output:
```
[
  {
    score: 0.8,
    handedness: 'Right',
    keypoints: [
      {x: 105, y: 107, name: "wrist"},
      {x: 108, y: 160, name: "pinky_finger_tip"},
      ...
    ],
    keypoints3D: [
      {x: 0.00388, y: -0.0205, z: 0.0217, name: "wrist"},
      {x: -0.025138, y: -0.0255, z: -0.0051, name: "pinky_finger_tip"},
      ...
    ]
  }
]
```

The `score` ranges from 0 to 1. It represents the model's confidence of the detected hand.

`handedness` is set to either 'Left' or 'Right', which is the model prediction of the detected hand's handedness.

For the `keypoints`, x and y represent the actual keypoint position in the image pixel space.

For the `keypoints3D`, x, y and z represent absolute distance in a metric scale, where the origin is formed as an average between the first knuckles of index, middle, ring and pinky fingers.

The name provides a label for each keypoint, such as 'wrist', 'pinky_finger_tip', etc.

Refer to each model's documentation for specific configurations for the model
and their performance.

[MediaPipeHands MediaPipe Documentation](https://github.com/tensorflow/tfjs-models/tree/master/hand-pose-detection/src/mediapipe)

[MediaPipeHands TFJS Documentation](https://github.com/tensorflow/tfjs-models/tree/master/hand-pose-detection/src/tfjs)

-------------------------------------------------------------------------------

## Keypoint Diagram
See the diagram below for what those keypoints are and their index in the array.

### MediaPipe Hands Keypoints: Used in MediaPipe Hands
![MediaPipeHands Keypoints](https://mediapipe.dev/images/mobile/hand_landmarks.png)
0: wrist  \
1: thumb_cmc \
2: thumb_mcp  \
3: thumb_ip  \
4: thumb_tip  \
5: index_finger_mcp  \
6: index_finger_pip  \
7: index_finger_dip  \
8: index_finger_tip  \
9: middle_finger_mcp  \
10: middle_finger_pip  \
11: middle_finger_dip  \
12: middle_finger_tip  \
13: ring_finger_mcp  \
14: ring_finger_pip  \
15: ring_finger_dip  \
16: ring_finger_tip  \
17: pinky_finger_mcp  \
18: pinky_finger_pip  \
19: pinky_finger_dip  \
20: pinky_finger_tip

-------------------------------------------------------------------------------

## Example Code and Demos
You may reference the demos for code examples. Details for how to run the demos
are included in the `demos/`
[folder](https://github.com/tensorflow/tfjs-models/tree/master/hand-pose-detection/demos).


text:
package eu.dnetlib.iis.wf.referenceextraction.covid19.input;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;

import eu.dnetlib.iis.common.java.io.HdfsUtils;
import eu.dnetlib.iis.common.spark.JavaSparkContextFactory;
import eu.dnetlib.iis.referenceextraction.covid19.schemas.DocumentMetadata;
import eu.dnetlib.iis.transformers.metadatamerger.schemas.ExtractedDocumentMetadataMergedWithOriginal;
import pl.edu.icm.sparkutils.avro.SparkAvroLoader;
import pl.edu.icm.sparkutils.avro.SparkAvroSaver;

/**
 *
 * @author mhorst
 *
 */
public class Covid19ReferenceExtractionInputTransformerJob {

    private static SparkAvroLoader avroLoader = new SparkAvroLoader();
    private static SparkAvroSaver avroSaver = new SparkAvroSaver();

    //------------------------ LOGIC --------------------------

    public static void main(String[] args) throws IOException {
        Covid19ReferenceExtractionInputTransformerJobParameters params = new Covid19ReferenceExtractionInputTransformerJobParameters();
        JCommander jcommander = new JCommander(params);
        jcommander.parse(args);

        try (JavaSparkContext sc = JavaSparkContextFactory.withConfAndKryo(new SparkConf())) {
            HdfsUtils.remove(sc.hadoopConfiguration(), params.output);

            JavaRDD<ExtractedDocumentMetadataMergedWithOriginal> inputMeta = avroLoader
                    .loadJavaRDD(sc, params.input, ExtractedDocumentMetadataMergedWithOriginal.class);

            JavaRDD<DocumentMetadata> output = inputMeta.filter(x -> StringUtils.isNotBlank(x.getTitle()))
                    .map(x -> convertMetadata(x));

            avroSaver.saveJavaRDD(output, DocumentMetadata.SCHEMA$, params.output);
        }

    }

    //------------------------ PRIVATE --------------------------

    private static DocumentMetadata convertMetadata(ExtractedDocumentMetadataMergedWithOriginal input) {
        DocumentMetadata.Builder metaBuilder = DocumentMetadata.newBuilder();
        metaBuilder.setId(input.getId());
        metaBuilder.setTitle(input.getTitle());
        metaBuilder.setAbstract$(input.getAbstract$());
        if (input.getYear() != null) {
            metaBuilder.setDate(String.valueOf(input.getYear()));
        }
        return metaBuilder.build();
    }

    @Parameters(separators = "=")
    private static class Covid19ReferenceExtractionInputTransformerJobParameters {

        @Parameter(names = "-input", required = true)
        private String input;

        @Parameter(names = "-output", required = true)
        private String output;

    }
}


text:
using System.Collections.Generic;

namespace RaptoRCon.Games.Dice
{
    /// <summary>
    /// Base class for all <see cref="Timeout"/> implementations
    /// </summary>
    public abstract class Timeout : ITimeout
    {
        /// <summary>
        /// Creates a new <see cref="Timeout"/> instance
        /// </summary>
        /// <param name="type"></param>
        protected Timeout(TimeoutType type)
        {
            this.Type = type;
        }

        /// <summary>
        /// Gets the type of the timeout
        /// </summary>
        public TimeoutType Type { get; private set; }

        /// <summary>
        /// Transforms the current instance into words for communication with the remote console
        /// of the game server
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable<IDiceWord> ToWords()
        {
            yield return new DiceWord(this.Type.ToString().ToLower());
        }
    }
}


text:
var TransaksiNamespace = {};

TransaksiNamespace.initTransactionEntryViewModel = function(transaction){
    var transactionViewModel = ko.validatedObservable({
        tid: ko.observable(transaction.tid),
        user: ko.observable(transaction.user),
        info: ko.observable(transaction.info).extend({ required: true }),
        amount: ko.observable(transaction.amount).extend({ required: true }).extend({ number: true }),
        transdate: ko.observable(transaction.transdate),
        memo: ko.observable(transaction.memo).extend({ required: true }),

    });

    var validationOptions =
      { insertMessages: true, decorateElement: true, errorElementClass: 'help-inline' };
    ko.validation.init(validationOptions);

    return transactionViewModel;
}

TransaksiNamespace.bindData = function(transaction) {

    // Create the view model
    TransaksiNamespace.viewModel =
      TransaksiNamespace.initTransactionEntryViewModel(transaction);
    ko.applyBindings(this.viewModel);
}

TransaksiNamespace.getTransactionEntries = function(user) {
    $.ajax({
        url: "/services/trans",
        type: 'post',
        data: "{'user':'1' }",
        contentType: 'application/json',
        cache: false,
        success: function (result) {
            TransaksiNamespace.bindData(result);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            var errorMessage = '';
            $('#message').html(jqXHR.responseText);
        }
    });
}

function transaksiEntri(data) {
    var self = this;
    self.tid = data.tid;
    self.user = data.user;
    self.info = data.info;
    self.amount = data.amount;
    self.transdate = data.transdate;
    self.memo = data.memo;

};

function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

jQuery.postJSON = function(url, args, callback) {
    args._xsrf = getCookie("_xsrf");
    $.ajax({url: url, data: $.param(args), dataType: "text", type: "POST",
    success: function(response) {
    callback(eval("(" + response + ")"));
    }});
};

function transaksiViewModel() {
    var self = this;
    self.tid = ko.observable('');
    self.user = ko.observable('');
    self.transdate = ko.observable('');
    self.info = ko.observable('').extend({required: true});
    self.amount = ko.observable('').extend({
                required: true,
                number: true
                });
    self.memo = ko.observable('');

    self.addText = ko.observable('Add');
    self.resetText = ko.observable('Reset');
    self.selectedIndex = -1;

    self.transaksiEntries = ko.observableArray([]);

    self.total = ko.computed(function() {
        var tot = 0;
        for (var i = 0; i < self.transaksiEntries().length; i++)  {
               tot += self.transaksiEntries()[i]["amount"]
        }
        return tot;
    });

    self.add = function () {
        var entry = new transaksiEntri({
            info : self.info(),
            amount : self.amount(),
            memo : self.memo(),

        });

        self.transaksiEntries.push(entry);
    };

    self.addTransaksitoServer = function(){

            $.ajax({
                url: "/services/trans",
                type: "post",
                data: ko.toJSON({
                    info : self.info(),
                    amount : self.amount(),
                    memo : self.memo()
                }),
                contentType: "application/json",
                success: function(response){
                    console.log(response);
                    data = $.parseJSON(response)
                    self.transaksiEntries.push(new transaksiEntri(data));

                },
             error:function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
             }
        })
     };

    self.postTransaksi = function() {
        console.log('process form post to server');

        console.log('formValidation validate ');

        var self = this;
        console.log(ko.toJSON(self))
        $.ajax({
            url: '/services/trans',
            type: 'post',
            data: ko.toJSON(self),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (jsondata) {
                self.transaksiEntries.push(new transaksiEntri(jsondata));

            }
        })
    };

    self.edit = function (transaksiEntri) {
        self.info(transaksiEntri.info);
        self.amount(transaksiEntri.amount);
        self.memo(transaksiEntri.memo);
    };

    self.delete = function (transaksiEntri) {
        self.transaksiEntries.destroy(transaksiEntri);
    };

    self.reset = function () {
    };

    self.load = function () {
        $.getJSON("/services/trans", function(allData) {
            var mappedEntri = $.map(allData, function(entry) { return new transaksiEntri(entry) });
        self.transaksiEntries(mappedEntri);
    });
    };

    self.post = function (transaksiEntri) {

    };

    self.load();
}
ko.applyBindings(new transaksiViewModel());


text:
const { startCase } = require('lodash');
const utils = require('../utils');

/**
 * The default is to use a file path string. It implies use of the template method.
 * For any other config an object { file:.., method:.., template:.. } can be used
 */
const entityClientI18nFiles = {
  entityBaseFiles: [
    {
      templates: [
        {
          sourceFile: context => `i18n/entity_${context.lang}.json.ejs`,
          destinationFile: context => `${context.clientSrcDir}i18n/${context.lang}/${context.entityTranslationKey}.json`,
        },
      ],
    },
  ],
};

const enumClientI18nFiles = {
  enumBaseFiles: [
    {
      templates: [
        {
          sourceFile: 'i18n/enum.json.ejs',
          destinationFile: context => `${context.clientSrcDir}i18n/${context.lang}/${context.clientRootFolder}${context.enumInstance}.json`,
        },
      ],
    },
  ],
};

module.exports = {
  entityClientI18nFiles,
  enumClientI18nFiles,
  writeFiles,
};

function writeFiles() {
  return {
    async writeEnumFiles() {
      if (this.skipClient || !this.enableTranslation) return;
      const { clientSrcDir, packageName, frontendAppName } = this;
      await Promise.all(
        this.fields
          .map(field => {
            if (!field.fieldIsEnum) return undefined;
            // Copy for each
            const languages = this.languages || this.getAllInstalledLanguages();
            return languages.map(lang =>
              this.writeFiles({
                sections: enumClientI18nFiles,
                context: {
                  ...utils.getEnumInfo(field, this.clientRootFolder),
                  lang,
                  frontendAppName,
                  packageName,
                  clientSrcDir,
                },
              })
            );
          })
          .flat()
      );
    },

    async writeClientFiles() {
      if (this.skipClient || !this.enableTranslation) return;

      // Copy each
      const { clientSrcDir, frontendAppName, languages = this.getAllInstalledLanguages() } = this;
      await Promise.all(
        languages.map(async lang => {
          await this.writeFiles({ sections: entityClientI18nFiles, context: { ...this.entity, clientSrcDir, frontendAppName, lang } });
          this.addEntityTranslationKey(this.entityTranslationKeyMenu, this.entityClassHumanized || startCase(this.entityClass), lang);
        })
      );
    },
  };
}


text:
Hello adversaria
================

Adversaria is git-baesd not app.

Usage
-----

1. Install
2. Use it.


text:
<?php

namespace ZendTest\Service\StrikeIron;

/**
 * Test helper
 */

/**
 * @see \Zend\Service\StrikeIron\Exception
 */

/**
 * @category   Zend
 * @package    Zend_Service_StrikeIron
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Service
 * @group      Zend_Service_StrikeIron
 */
class ExceptionTest extends \PHPUnit_Framework_TestCase
{
    public function testInheritsFromZendException()
    {
        $exception = new \Zend\Service\StrikeIron\Exception\RuntimeException();
        $this->assertInstanceOf('Zend\Service\StrikeIron\Exception', $exception);
    }
}


text:
package com.quebic.searchbox.common;

public class ErrorMessage {
	public static final String annotation_id_not_found = "unable to find @ID field";
	public static final String id_field_null = "@ID field cannot br null";
	public static final String id_duplicate = "duplicate id";
	public static final String id_value_not_found = "id value not found";

	public static final String redis_server_connection_error = "unable to connect redis server";
	public static final String query_function_not_found = "unable to found query function {functionName: %1$s}";
	public static final String query_function_parms_not_found = "unable to found query parameters {functionName: %1$s, parms: %2$s}";
	public static final String input_request_parms_not_found = "unable to found input request parms : %1$s";
}


text:
package com.googlecode.jmeter.plugins.webdriver.config;

import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.*;

import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.verifyNew;
import static org.powermock.api.mockito.PowerMockito.whenNew;

@RunWith(PowerMockRunner.class)
@PrepareForTest(HtmlUnitDriverConfig.class)
public class HtmlUnitDriverConfigTest {

    private HtmlUnitDriverConfig config;
    private JMeterVariables variables;

    @Before
    public void createConfig() {
        config = new HtmlUnitDriverConfig();
        variables = new JMeterVariables();
        JMeterContextService.getContext().setVariables(variables);
    }

    @After
    public void resetConfig() {
        config.clearThreadBrowsers();
        JMeterContextService.getContext().setVariables(null);
    }

    @Test
    public void shouldBeAbleToSerialiseAndDeserialise() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        ObjectOutputStream output = new ObjectOutputStream(bytes);

        output.writeObject(config);
        output.flush();
        output.close();

        ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
        final HtmlUnitDriverConfig deserializedConfig = (HtmlUnitDriverConfig) input.readObject();

        assertThat(deserializedConfig, is(config));
    }

    @Test
    public void shouldCreateHtmlUnit() throws Exception {
        HtmlUnitDriver mockHtmlUnitDriver = Mockito.mock(HtmlUnitDriver.class);
        whenNew(HtmlUnitDriver.class).withParameterTypes(Capabilities.class).withArguments(isA(Capabilities.class)).thenReturn(mockHtmlUnitDriver);

        final HtmlUnitDriver browser = config.createBrowser();

        assertThat(browser, is(mockHtmlUnitDriver));
        verifyNew(HtmlUnitDriver.class, times(1)).withArguments(isA(Capabilities.class));
    }

    @Test
    public void shouldHaveProxyInCapability() {
        final Capabilities capabilities = config.createCapabilities();
        assertThat(capabilities.getCapability(CapabilityType.PROXY), is(notNullValue()));
    }
}


text:
require_relative "abstract_unit"
require "openssl"
require "active_support/time"
require "active_support/json"
require_relative "metadata/shared_metadata_tests"

class MessageEncryptorTest < ActiveSupport::TestCase
  class JSONSerializer
    def dump(value)
      ActiveSupport::JSON.encode(value)
    end

    def load(value)
      ActiveSupport::JSON.decode(value)
    end
  end

  def setup
    @secret    = SecureRandom.random_bytes(32)
    @verifier  = ActiveSupport::MessageVerifier.new(@secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
    @encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    @data = { some: "data", now: Time.local(2010) }
  end

  def test_encrypting_twice_yields_differing_cipher_text
    first_message = @encryptor.encrypt_and_sign(@data).split("--").first
    second_message = @encryptor.encrypt_and_sign(@data).split("--").first
    assert_not_equal first_message, second_message
  end

  def test_messing_with_either_encrypted_values_causes_failure
    text, iv = @verifier.verify(@encryptor.encrypt_and_sign(@data)).split("--")
    assert_not_decrypted([iv, text] * "--")
    assert_not_decrypted([text, munge(iv)] * "--")
    assert_not_decrypted([munge(text), iv] * "--")
    assert_not_decrypted([munge(text), munge(iv)] * "--")
  end

  def test_messing_with_verified_values_causes_failures
    text, iv = @encryptor.encrypt_and_sign(@data).split("--")
    assert_not_verified([iv, text] * "--")
    assert_not_verified([text, munge(iv)] * "--")
    assert_not_verified([munge(text), iv] * "--")
    assert_not_verified([munge(text), munge(iv)] * "--")
  end

  def test_signed_round_tripping
    message = @encryptor.encrypt_and_sign(@data)
    assert_equal @data, @encryptor.decrypt_and_verify(message)
  end

  def test_backwards_compat_for_64_bytes_key
    # 64 bit key
    secret = ["3942b1bf81e622559ed509e3ff274a780784fe9e75b065866bd270438c74da822219de3156473cc27df1fd590e4baf68c95eeb537b6e4d4c5a10f41635b5597e"].pack("H*")
    # Encryptor with 32 bit key, 64 bit secret for verifier
    encryptor = ActiveSupport::MessageEncryptor.new(secret[0..31], secret)
    # Message generated with 64 bit key
    message = "eHdGeExnZEwvMSt3U3dKaFl1WFo0TjVvYzA0eGpjbm5WSkt5MXlsNzhpZ0ZnbWhBWFlQZTRwaXE1bVJCS2oxMDZhYVp2dVN3V0lNZUlWQ3c2eVhQbnhnVjFmeVVubmhRKzF3WnZyWHVNMDg9LS1HSisyakJVSFlPb05ISzRMaXRzcFdBPT0=--831a1d54a3cda8a0658dc668a03dedcbce13b5ca"
    assert_equal "data", encryptor.decrypt_and_verify(message)[:some]
  end

  def test_alternative_serialization_method
    prev = ActiveSupport.use_standard_json_time_format
    ActiveSupport.use_standard_json_time_format = true
    encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.random_bytes(32), SecureRandom.random_bytes(128), serializer: JSONSerializer.new)
    message = encryptor.encrypt_and_sign({ :foo => 123, "bar" => Time.utc(2010) })
    exp = { "foo" => 123, "bar" => "2010-01-01T00:00:00.000Z" }
    assert_equal exp, encryptor.decrypt_and_verify(message)
  ensure
    ActiveSupport.use_standard_json_time_format = prev
  end

  def test_message_obeys_strict_encoding
    bad_encoding_characters = "\n!@#"
    message, iv = @encryptor.encrypt_and_sign("This is a very \n\nhumble string" + bad_encoding_characters)

    assert_not_decrypted("#{::Base64.encode64 message.to_s}--#{::Base64.encode64 iv.to_s}")
    assert_not_verified("#{::Base64.encode64 message.to_s}--#{::Base64.encode64 iv.to_s}")

    assert_not_decrypted([iv,  message] * bad_encoding_characters)
    assert_not_verified([iv,  message] * bad_encoding_characters)
  end

  def test_aead_mode_encryption
    encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
    message = encryptor.encrypt_and_sign(@data)
    assert_equal @data, encryptor.decrypt_and_verify(message)
  end

  def test_aead_mode_with_hmac_cbc_cipher_text
    encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")

    assert_aead_not_decrypted(encryptor, "eHdGeExnZEwvMSt3U3dKaFl1WFo0TjVvYzA0eGpjbm5WSkt5MXlsNzhpZ0ZnbWhBWFlQZTRwaXE1bVJCS2oxMDZhYVp2dVN3V0lNZUlWQ3c2eVhQbnhnVjFmeVVubmhRKzF3WnZyWHVNMDg9LS1HSisyakJVSFlPb05ISzRMaXRzcFdBPT0=--831a1d54a3cda8a0658dc668a03dedcbce13b5ca")
  end

  def test_messing_with_aead_values_causes_failures
    encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
    text, iv, auth_tag = encryptor.encrypt_and_sign(@data).split("--")
    assert_aead_not_decrypted(encryptor, [iv, text, auth_tag] * "--")
    assert_aead_not_decrypted(encryptor, [munge(text), iv, auth_tag] * "--")
    assert_aead_not_decrypted(encryptor, [text, munge(iv), auth_tag] * "--")
    assert_aead_not_decrypted(encryptor, [text, iv, munge(auth_tag)] * "--")
    assert_aead_not_decrypted(encryptor, [munge(text), munge(iv), munge(auth_tag)] * "--")
    assert_aead_not_decrypted(encryptor, [text, iv] * "--")
    assert_aead_not_decrypted(encryptor, [text, iv, auth_tag[0..-2]] * "--")
  end

  def test_backwards_compatibility_decrypt_previously_encrypted_messages_without_metadata
    secret = "\xB7\xF0\xBCW\xB1\x18`\xAB\xF0\x81\x10\xA4$\xF44\xEC\xA1\xDC\xC1\xDDD\xAF\xA9\xB8\x14\xCD\x18\x9A\x99 \x80)"
    encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm")
    encrypted_message = "9cVnFs2O3lL9SPvIJuxBOLS51nDiBMw=--YNI5HAfHEmZ7VDpl--ddFJ6tXA0iH+XGcCgMINYQ=="

    assert_equal "Ruby on Rails", encryptor.decrypt_and_verify(encrypted_message)
  end

  def test_rotating_secret
    old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], cipher: "aes-256-gcm").encrypt_and_sign("old")

    encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
    encryptor.rotate secrets[:old]

    assert_equal "old", encryptor.decrypt_and_verify(old_message)
  end

  def test_rotating_serializer
    old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], cipher: "aes-256-gcm", serializer: JSON).
      encrypt_and_sign({ ahoy: :hoy })

    encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm", serializer: JSON)
    encryptor.rotate secrets[:old]

    assert_equal({ "ahoy" => "hoy" }, encryptor.decrypt_and_verify(old_message))
  end

  def test_rotating_aes_cbc_secrets
    old_encryptor = ActiveSupport::MessageEncryptor.new(secrets[:old], "old sign", cipher: "aes-256-cbc")
    old_message = old_encryptor.encrypt_and_sign("old")

    encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    encryptor.rotate secrets[:old], "old sign", cipher: "aes-256-cbc"

    assert_equal "old", encryptor.decrypt_and_verify(old_message)
  end

  def test_multiple_rotations
    older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign("older")
    old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], "old sign").encrypt_and_sign("old")

    encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    encryptor.rotate secrets[:old], "old sign"
    encryptor.rotate secrets[:older], "older sign"

    assert_equal "new",   encryptor.decrypt_and_verify(encryptor.encrypt_and_sign("new"))
    assert_equal "old",   encryptor.decrypt_and_verify(old_message)
    assert_equal "older", encryptor.decrypt_and_verify(older_message)
  end

  def test_on_rotation_is_called_and_returns_modified_messages
    older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign({ encoded: "message" })

    encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    encryptor.rotate secrets[:old]
    encryptor.rotate secrets[:older], "older sign"

    rotated = false
    message = encryptor.decrypt_and_verify(older_message, on_rotation: proc { rotated = true })

    assert_equal({ encoded: "message" }, message)
    assert rotated
  end

  def test_on_rotation_can_be_passed_at_the_constructor_level
    older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign({ encoded: "message" })

    rotated = rotated = false  # double assigning to suppress "assigned but unused variable" warning
    encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true })
    encryptor.rotate secrets[:older], "older sign"

    assert_changes(:rotated, from: false, to: true) do
      message = encryptor.decrypt_and_verify(older_message)

      assert_equal({ encoded: "message" }, message)
    end
  end

  def test_on_rotation_option_takes_precedence_over_the_one_given_in_constructor
    older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign({ encoded: "message" })

    rotated = rotated = false  # double assigning to suppress "assigned but unused variable" warning
    encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true })
    encryptor.rotate secrets[:older], "older sign"

    assert_changes(:rotated, from: false, to: "Yes") do
      message = encryptor.decrypt_and_verify(older_message, on_rotation: proc { rotated = "Yes" })

      assert_equal({ encoded: "message" }, message)
    end
  end

  def test_with_rotated_metadata
    old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], cipher: "aes-256-gcm").
      encrypt_and_sign("metadata", purpose: :rotation)

    encryptor = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm")
    encryptor.rotate secrets[:old]

    assert_equal "metadata", encryptor.decrypt_and_verify(old_message, purpose: :rotation)
  end

  private
    def assert_aead_not_decrypted(encryptor, value)
      assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
        encryptor.decrypt_and_verify(value)
      end
    end

    def assert_not_decrypted(value)
      assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
        @encryptor.decrypt_and_verify(@verifier.generate(value))
      end
    end

    def assert_not_verified(value)
      assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
        @encryptor.decrypt_and_verify(value)
      end
    end

    def secrets
      @secrets ||= Hash.new { |h, k| h[k] = SecureRandom.random_bytes(32) }
    end

    def munge(base64_string)
      bits = ::Base64.strict_decode64(base64_string)
      bits.reverse!
      ::Base64.strict_encode64(bits)
    end
end

class MessageEncryptorWithHybridSerializerAndMarshalDumpTest < MessageEncryptorTest
  def setup
    @secret    = SecureRandom.random_bytes(32)
    @verifier  = ActiveSupport::MessageVerifier.new(@secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
    @data      = { some: "data", now: Time.local(2010) }
    @encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    @default_message_encryptor_serializer        = ActiveSupport::MessageEncryptor.default_message_encryptor_serializer
    @default_fallback_to_marshal_deserialization = ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization
    ActiveSupport::MessageEncryptor.default_message_encryptor_serializer = :hybrid
  end

  def teardown
    ActiveSupport::MessageEncryptor.default_message_encryptor_serializer       = @default_message_encryptor_serializer
    ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization = @default_fallback_to_marshal_deserialization
    super
  end

  def test_backwards_compatibility_decrypt_previously_marshal_serialized_messages_when_fallback_to_marshal_deserialization_is_true
    secret = "\xB7\xF0\xBCW\xB1\x18`\xAB\xF0\x81\x10\xA4$\xF44\xEC\xA1\xDC\xC1\xDDD\xAF\xA9\xB8\x14\xCD\x18\x9A\x99 \x80)"
    data = "this_is_data"
    marshal_message = ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm", serializer: Marshal).encrypt_and_sign(data)
    assert_equal data, ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm").decrypt_and_verify(marshal_message)
  end

  def test_failure_to_decrypt_marshal_serialized_messages_when_fallback_to_marshal_deserialization_is_false
    ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization = false
    secret = "\xB7\xF0\xBCW\xB1\x18`\xAB\xF0\x81\x10\xA4$\xF44\xEC\xA1\xDC\xC1\xDDD\xAF\xA9\xB8\x14\xCD\x18\x9A\x99 \x80)"
    data = "this_is_data"
    marshal_message = ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm", serializer: Marshal).encrypt_and_sign(data)
    assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
      ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm").decrypt_and_verify(marshal_message)
    end
  end
end

class MessageEncryptorWithJsonSerializerTest < MessageEncryptorTest
  def setup
    @secret    = SecureRandom.random_bytes(32)
    @verifier  = ActiveSupport::MessageVerifier.new(@secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
    @data      = { "some" => "data", "now" => Time.local(2010) }
    @encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    @default_message_encryptor_serializer = ActiveSupport::MessageEncryptor.default_message_encryptor_serializer
    ActiveSupport::MessageEncryptor.default_message_encryptor_serializer = :json
  end

  def teardown
    ActiveSupport::MessageEncryptor.default_message_encryptor_serializer = @default_message_encryptor_serializer
    super
  end

  def test_backwards_compat_for_64_bytes_key
    # 64 bit key
    secret = ["3942b1bf81e622559ed509e3ff274a780784fe9e75b065866bd270438c74da822219de3156473cc27df1fd590e4baf68c95eeb537b6e4d4c5a10f41635b5597e"].pack("H*")
    # Encryptor with 32 bit key, 64 bit secret for verifier
    encryptor = ActiveSupport::MessageEncryptor.new(secret[0..31], secret)
    # Message generated with 64 bit key using the JSON serializer
    message = "YWZPOVBzcS8ycGZpVWpjWWU5NXZoanRtRGkzTVRjZk16UUpuRE9wa0pNNGI0dGxMRU5RdC94ZVhiQzUwYktFL2NEUjBnUm1QSlRDQ1RrMGlvakVZcGc9PS0tbXROMVdDUnNxWlRxMXA4dEtjWi9oZz09--3489b03e85aa14d8ed8cdd455507246f2e2884ae"
    assert_equal "data", encryptor.decrypt_and_verify(message)["some"]
  end

  def test_backwards_compatibility_decrypt_previously_encrypted_messages_without_metadata
    secret = "\xB7\xF0\xBCW\xB1\x18`\xAB\xF0\x81\x10\xA4$\xF44\xEC\xA1\xDC\xC1\xDDD\xAF\xA9\xB8\x14\xCD\x18\x9A\x99 \x80)"
    encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm")
    # Message generated with MessageEncryptor given JSON as the serializer.
    encrypted_message = "NIevxlF4gFUETmYTm3GJ--SIlwA5xxwpqNtiiv--woA9eLuVMbmapIDGDj7HQQ=="

    assert_equal "Ruby on Rails", encryptor.decrypt_and_verify(encrypted_message)
  end

  def test_on_rotation_is_called_and_returns_modified_messages
    older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign({ encoded: "message" })

    encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    encryptor.rotate secrets[:old]
    encryptor.rotate secrets[:older], "older sign"

    rotated = false
    message = encryptor.decrypt_and_verify(older_message, on_rotation: proc { rotated = true })

    assert_equal({ "encoded" => "message" }, message)
    assert rotated
  end

  def test_on_rotation_can_be_passed_at_the_constructor_level
    older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign({ encoded: "message" })

    rotated = rotated = false  # double assigning to suppress "assigned but unused variable" warning
    encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true })
    encryptor.rotate secrets[:older], "older sign"

    assert_changes(:rotated, from: false, to: true) do
      message = encryptor.decrypt_and_verify(older_message)

      assert_equal({ "encoded" => "message" }, message)
    end
  end

  def test_on_rotation_option_takes_precedence_over_the_one_given_in_constructor
    older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign({ encoded: "message" })

    rotated = rotated = false  # double assigning to suppress "assigned but unused variable" warning
    encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true })
    encryptor.rotate secrets[:older], "older sign"

    assert_changes(:rotated, from: false, to: "Yes") do
      message = encryptor.decrypt_and_verify(older_message, on_rotation: proc { rotated = "Yes" })

      assert_equal({ "encoded" => "message" }, message)
    end
  end
end

class MessageEncryptorWithHybridSerializerAndWithoutMarshalDumpTest < MessageEncryptorWithJsonSerializerTest
  def setup
    @secret    = SecureRandom.random_bytes(32)
    @verifier  = ActiveSupport::MessageVerifier.new(@secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
    @data      = { "some" => "data", "now" => Time.local(2010) }
    @encryptor = ActiveSupport::MessageEncryptor.new(@secret)
    @default_message_encryptor_serializer = ActiveSupport::MessageEncryptor.default_message_encryptor_serializer
    @default_use_marshal_serialization    = ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization
    ActiveSupport::MessageEncryptor.default_message_encryptor_serializer = :hybrid
    ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization     = false
  end

  def teardown
    ActiveSupport::MessageEncryptor.default_message_encryptor_serializer = @default_message_encryptor_serializer
    ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization     = @default_use_marshal_serialization
    super
  end
end

class MessageEncryptorMetadataTest < ActiveSupport::TestCase
  include SharedMessageMetadataTests

  setup do
    @secret    = SecureRandom.random_bytes(32)
    @encryptor = ActiveSupport::MessageEncryptor.new(@secret, **encryptor_options)
  end

  private
    def generate(message, **options)
      @encryptor.encrypt_and_sign(message, **options)
    end

    def parse(data, **options)
      @encryptor.decrypt_and_verify(data, **options)
    end

    def encryptor_options; {} end
end

class MessageEncryptorMetadataMarshalTest < MessageEncryptorMetadataTest
  private
    def encryptor_options
      { serializer: Marshal }
    end
end

class MessageEncryptorMetadataJSONTest < MessageEncryptorMetadataTest
  private
    def encryptor_options
      { serializer: MessageEncryptorTest::JSONSerializer.new }
    end
end

class MessageEncryptorMetadataJsonWithMarshalFallbackTest < MessageEncryptorMetadataTest
  private
    def encryptor_options
      { serializer: ActiveSupport::JsonWithMarshalFallback }
    end
end


text:
__author__ = "Patrick Lampe"
__email__ = "uni at lampep.de"

class Point:
    def __init__(self, id, location):
        self.id = id
        self.location = location

    def getId(self):
        return self.id

    def get_distance_in_m(self, snd_node):
        return self.get_distance_in_km(snd_node) * 1000

    def get_distance_in_km(self, snd_node):
        return self.location.get_distance_in_km(snd_node.location)

    def get_heading(self, snd_node):
        return self.location.get_heading(snd_node.location)

    def get_lat(self):
        return self.location.get_lat_lon().to_string()[0]

    def get_lon(self):
        return self.location.get_lat_lon().to_string()[1]


text:
<?php

require_once( '../../php/util.php' );
eval( getPluginConf( 'geoip' ) );
require_once( 'ip_db.php' );

$db = new ipDB();
$db->add($_REQUEST["ip"],$_REQUEST["comment"]);

cachedEcho( json_encode( array( "ip"=>$_REQUEST["ip"], "comment"=>$_REQUEST["comment"] ) ), "application/json" );


text:
using namespace std;

std::unordered_set<std::string> usedTypeNames;

std::string getRandomString(const int len) {
	string s;
	s.resize(len);

	for (auto i = 0; i < len; ++i) {
		// just pick a random byte
		s[i] = rand() % 0xff;
	}

	s[len] = 0;

	return s;
}

int main(int argc, char* argv[])
{
	cout << "===== RTTI obfuscator by koemeet =====" << endl;

	srand(time(nullptr));

	try
	{
		if (argc < 2)
		{
			throw std::exception("Please provide a path or drop a file into me.");
		}

		// path to input binary
		string path = argv[1];

		std::ifstream fs(path, std::fstream::binary);
		if (fs.fail())
		{
			throw std::exception("Could not open source binary");
		}

		// read file contents
		std::stringstream ss;
		ss << fs.rdbuf();
		auto contents = ss.str();

		boost::regex reg(R"(\.(\?AV|PEAV)(.+?)@@\0)");

		// replace RTTI types
		contents = boost::regex_replace(contents, reg, [&](const boost::smatch& m)
		{
			auto prefix = m[1].str();
			auto typeName = m[2].str();

			auto length = 1 + prefix.size() + typeName.size() + 2;

			// max length of the new type name
			auto maxNewLength = 3;

			// get a new random name untill we have one we never used before
			std::string newTypeName;
			do
			{
				newTypeName = getRandomString(length);
				if (newTypeName.size() > maxNewLength)
				{
					memset(const_cast<char*>(newTypeName.data()) + maxNewLength, 0, length - maxNewLength);
				}

			} while (usedTypeNames.find(newTypeName) != usedTypeNames.end());

			usedTypeNames.emplace(newTypeName);

			return newTypeName + '\0';
		});

		// generate output path
		boost::filesystem::path p(path);
		auto outputPath = p.parent_path().string() + "\\" + p.stem().string() + p.extension().string();

		// write to file
		std::ofstream os(outputPath, std::ofstream::trunc | std::ofstream::binary);
		if (!os.write(contents.data(), contents.size()))
		{
			throw std::exception((std::string("Unable to write to file ") + outputPath).c_str());
		}
		else
		{
			cout << "Successfully obfuscated RTTI information. Output written to " << outputPath << endl;
			system("pause");
		}
	}
	catch (std::exception &e)
	{
		cout << e.what() << endl;
		system("pause");
		return 1;
	}

    return 0;
}


text:
namespace ChipTuna.Emulation.SN76489
{
    public class PsgCommand
    {
    }
}


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

<title>Timer.StaticInterface (wpilibj API)</title>
<meta name="date" content="2017-01-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

edu.wpi.first.wpilibj

Interface Timer.StaticInterface

All Known Implementing Classes:

HardwareTimer

Enclosing class:

Timer

public static interface Timer.StaticInterface

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
delay(double seconds)

double
getFPGATimestamp()

double
getMatchTime()

Timer.Interface
newTimer()

Method Detail

getFPGATimestamp

double getFPGATimestamp()

getMatchTime

double getMatchTime()

delay

void delay(double seconds)

newTimer

Timer.Interface newTimer()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
namespace HealthCheck
{
    /// <summary>
    /// A status listener listens for and processes the result of an execution of a Health Check Plug-in.
    /// </summary>
    public interface IStatusListener
    {
        /// <summary>
        /// Gets or sets the threshold of this listener.
        /// </summary>
        CheckResult Threshold { get; set; }

        /// <summary>
        /// Perform any startup initialization.
        /// </summary>
        void Initialize();

        /// <summary>
        /// Process a health check result.
        /// </summary>
        /// <param name="status">The status of a health check.</param>
        /// <returns><c>true</c> if the listener processed the status; otherwise, <c>false</c></returns>
        bool Process(IHealthStatus status);
    }
}