text:
/**
 * @fileoverview Rule that warns when identifier names are shorter or longer
 * than the values provided in configuration.
 * @author Burak Yigit Kaya aka BYK
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "Enforce minimum and maximum identifier lengths",
            recommended: false,
            url: "https://eslint.org/docs/rules/id-length"
        },

        schema: [
            {
                type: "object",
                properties: {
                    min: {
                        type: "integer",
                        default: 2
                    },
                    max: {
                        type: "integer"
                    },
                    exceptions: {
                        type: "array",
                        uniqueItems: true,
                        items: {
                            type: "string"
                        }
                    },
                    exceptionPatterns: {
                        type: "array",
                        uniqueItems: true,
                        items: {
                            type: "string"
                        }
                    },
                    properties: {
                        enum: ["always", "never"]
                    }
                },
                additionalProperties: false
            }
        ],
        messages: {
            tooShort: "Identifier name '{{name}}' is too short (< {{min}}).",
            tooShortPrivate: "Identifier name '#{{name}}' is too short (< {{min}}).",
            tooLong: "Identifier name '{{name}}' is too long (> {{max}}).",
            tooLongPrivate: "Identifier name #'{{name}}' is too long (> {{max}})."
        }
    },

    create(context) {
        const options = context.options[0] || {};
        const minLength = typeof options.min !== "undefined" ? options.min : 2;
        const maxLength = typeof options.max !== "undefined" ? options.max : Infinity;
        const properties = options.properties !== "never";
        const exceptions = new Set(options.exceptions);
        const exceptionPatterns = (options.exceptionPatterns || []).map(pattern => new RegExp(pattern, "u"));
        const reportedNodes = new Set();

        /**
         * Checks if a string matches the provided exception patterns
         * @param {string} name The string to check.
         * @returns {boolean} if the string is a match
         * @private
         */
        function matchesExceptionPattern(name) {
            return exceptionPatterns.some(pattern => pattern.test(name));
        }

        const SUPPORTED_EXPRESSIONS = {
            MemberExpression: properties && function(parent) {
                return !parent.computed && (

                    // regular property assignment
                    (parent.parent.left === parent && parent.parent.type === "AssignmentExpression" ||

                    // or the last identifier in an ObjectPattern destructuring
                    parent.parent.type === "Property" && parent.parent.value === parent &&
                    parent.parent.parent.type === "ObjectPattern" && parent.parent.parent.parent.left === parent.parent.parent)
                );
            },
            AssignmentPattern(parent, node) {
                return parent.left === node;
            },
            VariableDeclarator(parent, node) {
                return parent.id === node;
            },
            Property(parent, node) {

                if (parent.parent.type === "ObjectPattern") {
                    const isKeyAndValueSame = parent.value.name === parent.key.name;

                    return (
                        !isKeyAndValueSame && parent.value === node ||
                        isKeyAndValueSame && parent.key === node && properties
                    );
                }
                return properties && !parent.computed && parent.key.name === node.name;
            },
            ImportDefaultSpecifier: true,
            RestElement: true,
            FunctionExpression: true,
            ArrowFunctionExpression: true,
            ClassDeclaration: true,
            FunctionDeclaration: true,
            MethodDefinition: true,
            PropertyDefinition: true,
            CatchClause: true,
            ArrayPattern: true
        };

        return {
            [[
                "Identifier",
                "PrivateIdentifier"
            ]](node) {
                const name = node.name;
                const parent = node.parent;

                const isShort = name.length < minLength;
                const isLong = name.length > maxLength;

                if (!(isShort || isLong) || exceptions.has(name) || matchesExceptionPattern(name)) {
                    return; // Nothing to report
                }

                const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type];

                /*
                 * We used the range instead of the node because it's possible
                 * for the same identifier to be represented by two different
                 * nodes, with the most clear example being shorthand properties:
                 * { foo }
                 * In this case, "foo" is represented by one node for the name
                 * and one for the value. The only way to know they are the same
                 * is to look at the range.
                 */
                if (isValidExpression && !reportedNodes.has(node.range.toString()) && (isValidExpression === true || isValidExpression(parent, node))) {
                    reportedNodes.add(node.range.toString());

                    let messageId = isShort ? "tooShort" : "tooLong";

                    if (node.type === "PrivateIdentifier") {
                        messageId += "Private";
                    }

                    context.report({
                        node,
                        messageId,
                        data: { name, min: minLength, max: maxLength }
                    });
                }
            }
        };
    }
};


text:
namespace eja
{
	make_thread_safe_component(session_map_component, std::map<std::string, std::shared_ptr<entity>>);

	class session_component final : public cipher_component
	{
		make_factory(session_component);

	private:
		diffie_hellman m_algorithm;
		std::string m_name;
		std::string m_password;

	public:
		session_component();
		session_component(const std::string& password);

		// Interface
		virtual void clear() override;

		// Utility
		virtual bool valid() const override { return cipher_component::valid() && has_id(); }

		void compute();
		void compute(const std::string& password);

		// Has
		bool has_name() const { return !m_name.empty(); }
		bool has_password() const { return !m_password.empty(); }

		// Set
		void set_name() { m_name.clear(); }
		void set_name(std::string&& name) { m_name = std::move(name); }
		void set_name(const std::string& name) { m_name = name; }

		void set_password() { m_password.clear(); }
		void set_password(std::string&& password) { m_password = std::move(password); }
		void set_password(const std::string& password) { m_password = password; }

		// Get
		const diffie_hellman& get_algorithm() const { return m_algorithm; }
		diffie_hellman& get_algorithm() { return m_algorithm; }

		const std::string& get_name() const { return m_name; }
		const std::string& get_password() const { return m_password; }

		// Static
		static ptr create(const std::string& password) { return std::make_shared<session_component>(password); }
	};
}

#endif

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `RandBigInt` trait in crate `num`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, RandBigInt">

    <title>num::bigint::RandBigInt - Rust</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

num::<wbr>bigint

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait num::<wbr>bigint::<wbr>RandBigInt

                [−]

        [src]

pub trait RandBigInt {
    fn gen_biguint(&mut self, bit_size: usize) -> BigUint;
    fn gen_bigint(&mut self, bit_size: usize) -> BigInt;
    fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
    fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
    fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
}

Required Methods

fn gen_biguint(&mut self, bit_size: usize) -> BigUint

Generate a random BigUint of the given bit size.

fn gen_bigint(&mut self, bit_size: usize) -> BigInt

Generate a random BigInt of the given bit size.

fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint

Generate a random BigUint less than the given bound. Fails
when the bound is zero.

fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint

Generate a random BigUint within the given range. The lower
bound is inclusive; the upper bound is exclusive. Fails when
the upper bound is not greater than the lower bound.

fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt

Generate a random BigInt within the given range. The lower
bound is inclusive; the upper bound is exclusive. Fails when
the upper bound is not greater than the lower bound.

Implementors

impl<R: Rng> RandBigInt for R

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
webParser
=========

Parse websites and accumulate a database of words.
Python and Django.


text:
* Fibonacci array is described on:
  * Kimmo Fredriksson and Fedor Nikitin. 2007. Simple compression code supporting random access and fast string matching. In Proc. of the 6th international conference on Experimental algorithms (WEA'07). Springer-Verlag. http://dl.acm.org/citation.cfm?id=1551895
  * Kimmo Fredriksson and Fedor Nikitin. 2009. Simple Random Access Compression. Fundam. Inf. 92, 1-2 (January 2009). http://dl.acm.org/citation.cfm?id=1768592

* For the design of serializer/deserializer, I refer chainer:
  * http://chainer.org/

* How to use HDF5 (in Japanese):
  * http://yukisakamoto.hatenablog.com/entry/2013/08/24/001303
  * http://bigvalley.hatenablog.com/entry/2015/11/02/003242

* Tips for bit manipulation:
  * ヘンリー・S・ウォーレン、ジュニア. 2004. ハッカーのたのしみ. エスアイビーアクセス. (In Japanese)
  * English version is:
    * Henry S. Warren, Jr. 2002. Hacker's Delight. Addison-Wesley Professional.

* Textbook for succinct data structures:
  * 岡野原大輔. 2012. 高速文字列解析の世界. 岩波書店. (In Japanese)


text:
// Copyright 2014 The Closure Library Authors. 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.

/**
 * @fileoverview Utilities for HTML element tag names.
 */
goog.provide('goog.dom.tags');

goog.require('goog.object');

/**
 * The void elements specified by
 * http://www.w3.org/TR/html-markup/syntax.html#void-elements.
 * @const @private {!Object<string, boolean>}
 */
goog.dom.tags.VOID_TAGS_ = goog.object.createSet(
    'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
    'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr');

/**
 * Checks whether the tag is void (with no contents allowed and no legal end
 * tag), for example 'br'.
 * @param {string} tagName The tag name in lower case.
 * @return {boolean}
 */
goog.dom.tags.isVoidTag = function(tagName) {
  return goog.dom.tags.VOID_TAGS_[tagName] === true;
};


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace AuctionTracker.Models
{
	public class Player
	{
		[JsonProperty("id")]
		public int ID { get; set; }

		[JsonProperty("fullName")]
		public string FullName { get; set; }

		[JsonProperty("nflTeam")]
		public string NflTeam { get; set; }

		[JsonProperty("teamId")]
		public int TeamID { get; set; }

		[JsonIgnore()]
		public Team Team { get; set;  }

		[JsonProperty("position")]
		public string Position { get; set; }

		[JsonProperty("auctionAmount")]
		public int AuctionAmount { get; set; }

		[NotMapped]
		[JsonProperty("team")]
		public string TeamName { get; set; }
	}
}


text:
Android MVVM Architecture Components based on [MVPArms](https://github.com/JessYanCoding/MVPArms) and [Android Architecture Components](https://developer.android.com/topic/libraries/architecture/index.html).

[中文](https://github.com/xiaobailong24/MVVMArms/blob/master/README_CN.md)

> This is **BETA** Version.
Welcome to communicate and discuss.

## Architecture

## Demo
### APK
[MVVMArms APK](https://github.com/xiaobailong24/MVVMArms/blob/master/image/MVVMArms.apk)
### Google Play

<a href='https://play.google.com/store/apps/details?id=<%= appPackage %>.weather&pcampaignid=MKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1'>

### Video
[![MVVMArms demo video](https://img.youtube.com/vi/Ja8nHGoWGjo/0.jpg)](https://youtu.be/Ja8nHGoWGjo)

## Libraries & References
- [MVPArms](https://github.com/JessYanCoding/MVPArms)
- [android-architecture-components](https://github.com/googlesamples/android-architecture-components)
- [Data Binding Library](https://developer.android.com/topic/libraries/data-binding/index.html)
- [Lifecycles](https://developer.android.com/topic/libraries/architecture/lifecycle.html)
- [LiveData](https://developer.android.com/topic/libraries/architecture/livedata.html)
- [ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel.html)
- [Room Persistence Library](https://developer.android.com/topic/libraries/architecture/room.html)
- [Dagger](https://github.com/google/dagger)
- [Retrofit](https://github.com/square/retrofit)
- [Okhttp](https://github.com/square/okhttp)
- [Glide](https://github.com/bumptech/glide)
- [Gson](https://github.com/google/gson)
- [RxJava](https://github.com/ReactiveX/RxJava)
- [RxAndroid](https://github.com/ReactiveX/RxAndroid)
- [RxCache](https://github.com/VictorAlbertos/RxCache)
- [Timber](https://github.com/JakeWharton/timber)
- [LeakCanary](https://github.com/square/leakcanary)
- [AndroidEventBus](https://github.com/hehonghui/AndroidEventBus)
- [RxErrorHandler](https://github.com/JessYanCoding/RxErrorHandler)
- [BaseRecyclerViewAdapterHelper](https://github.com/CymChad/BaseRecyclerViewAdapterHelper)
- [SuperTextView](https://github.com/lygttpod/SuperTextView)
- [MaterialSearchView](https://github.com/MiguelCatalan/MaterialSearchView)
- [Weather API](https://www.seniverse.com)
- etc...

## Update Log
- [RepositoryComponent](https://github.com/xiaobailong24/MVVMArms/blob/master/repository/src/main/java/<%= appPackage %>/repository/di/component/RepositoryComponent.java) Provides [Cache](https://github.com/xiaobailong24/MVVMArms/blob/master/repository/src/main/java/<%= appPackage %>/repository/cache/Cache.java) & RxCache. - 2017/10/11.
- [lifecycle](https://github.com/xiaobailong24/MVVMArms/tree/master/lifecycle) & [repository](https://github.com/xiaobailong24/MVVMArms/tree/master/repository). - 2017/10/01.
- [ArmsFragment](https://github.com/xiaobailong24/MVVMArms/blob/master/arms/src/main/java/<%= appPackage %>/base/ArmsFragment.java) Support Lazy load. - 2017/09/24.
- [ViewModel&LiveData](https://github.com/xiaobailong24/MVVMArms/blob/master/weather/src/main/java/<%= appPackage %>/weather/mvvm/viewmodel/WeatherViewModel.java) Activity share data between fragments, and ViewModel retain data across configuration changes. - 2017/09/23.
- [IRepositoryManager](https://github.com/xiaobailong24/MVVMArms/blob/master/arms/src/main/java/<%= appPackage %>/repository/IRepositoryManager.java) Support RoomDatabase for customization(GlobalConfigModule.Builder) BUT injectRoomDatabase(DBClass) first in ConfigModule#registerComponents(). - 2017/09/22.
- [ArmsUtils](https://github.com/xiaobailong24/MVVMArms/blob/master/arms/src/main/java/<%= appPackage %>/utils/ArmsUtils.java) to obtain [**ArmsComponent**](https://github.com/xiaobailong24/MVVMArms/blob/master/arms/src/main/java/<%= appPackage %>/di/component/ArmsComponent.java) easily. - 2017/08/23.
- [ImageLoader](https://github.com/xiaobailong24/MVVMArms/blob/master/arms/src/main/java/<%= appPackage %>/http/imageloader/ImageLoader.java) default Glide. - 2017/08/17.
- Survives configuration changes for ViewPager using Fragment. - 2017/08/16
- MVVMArms was BORN!!! - 2017/08/02

## Thanks
Thanks to all the authors and organizations that contributed to the open source library!

## License
```
Copyright 2017 xiaobailong24

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.
```


text:
import React, { PureComponent } from 'react';
import { bool, element, func, number } from 'prop-types';

export default class Loop extends PureComponent {
    static propTypes = {
        children: element.isRequired,
        in: bool,
        interval: number,
        iterations: number,
        onComplete: func,
        onIterate: func,
    };

    static defaultProps = {
        in: false,
        interval: 500,
        iterations: Infinity,
        onComplete: Function.prototype,
        onIterate: Function.prototype,
    };

    state = {
        in: this.props.in,
    };

    componentWillReceiveProps(nextProps) {
        if (nextProps.in) {
            this.setState({ in: true });
        }
    }

    componentWillUnmount() {
        this._clearTimeouts();
    }

    count = 0;
    pendingOnComplete = null;
    pendingStateChange = null;

    _clearTimeouts() {
        clearTimeout(this.pendingStateChange);
        clearTimeout(this.pendingOnComplete);
    }

    _toggleIn = () => {
        this.setState(state => {
            return {
                in: !state.in,
            };
        });
    };

    _iterate = () => {
        this.count = this.count + 0.5;
        this.props.onIterate(this.count);

        if (this.count < this.props.iterations) {
            this.pendingStateChange = setTimeout(
                this._toggleIn,
                this.props.interval
            );
        } else {
            this.pendingOnComplete = setTimeout(
                this.props.onComplete,
                this.props.interval
            );
        }
    };

    render() {
        return React.cloneElement(this.props.children, {
            duration: this.props.interval,
            in: this.state.in,
            onEntered: this._iterate,
            onExiting: this._iterate,
        });
    }
}


text:
<?php
namespace Concrete\Core\Url;

interface UrlInterface extends \League\Url\UrlInterface
{

    const TRAILING_SLASHES_DISABLED = 0;
    const TRAILING_SLASHES_ENABLED = 1;
    const TRAILING_SLASHES_AUTO = 2;

    /**
     * @param integer $port
     */
    public function setPortIfNecessary($port);

}


text:
"""
WSGI config for voteswap project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings")

application = get_wsgi_application()

try:
    from google.appengine.ext import vendor
    vendor.add('lib')
except ImportError:
    pass


text:
namespace utils {

    void FillShaderModuleBuilder(const dawn::ShaderModuleBuilder& builder,
                                 dawn::ShaderStage stage,
                                 const char* source) {
        shaderc::Compiler compiler;
        shaderc::CompileOptions options;

        shaderc_shader_kind kind;
        switch (stage) {
            case dawn::ShaderStage::Vertex:
                kind = shaderc_glsl_vertex_shader;
                break;
            case dawn::ShaderStage::Fragment:
                kind = shaderc_glsl_fragment_shader;
                break;
            case dawn::ShaderStage::Compute:
                kind = shaderc_glsl_compute_shader;
                break;
            default:
                UNREACHABLE();
        }

        auto result = compiler.CompileGlslToSpv(source, strlen(source), kind, "myshader?", options);
        if (result.GetCompilationStatus() != shaderc_compilation_status_success) {
            std::cerr << result.GetErrorMessage();
            return;
        }

        // result.cend and result.cbegin return pointers to uint32_t.
        const uint32_t* resultBegin = result.cbegin();
        const uint32_t* resultEnd = result.cend();
        // So this size is in units of sizeof(uint32_t).
        ptrdiff_t resultSize = resultEnd - resultBegin;
        // SetSource takes data as uint32_t*.
        builder.SetSource(static_cast<uint32_t>(resultSize), result.cbegin());

#ifdef DUMP_SPIRV_ASSEMBLY
        {
            auto resultAsm = compiler.CompileGlslToSpvAssembly(source, strlen(source), kind,
                                                               "myshader?", options);
            size_t sizeAsm = (resultAsm.cend() - resultAsm.cbegin());

            char* buffer = reinterpret_cast<char*>(malloc(sizeAsm + 1));
            memcpy(buffer, resultAsm.cbegin(), sizeAsm);
            buffer[sizeAsm] = '\0';
            printf("SPIRV ASSEMBLY DUMP START\n%s\nSPIRV ASSEMBLY DUMP END\n", buffer);
            free(buffer);
        }
#endif

#ifdef DUMP_SPIRV_JS_ARRAY
        printf("SPIRV JS ARRAY DUMP START\n");
        for (size_t i = 0; i < size; i++) {
            printf("%#010x", result.cbegin()[i]);
            if ((i + 1) % 4 == 0) {
                printf(",\n");
            } else {
                printf(", ");
            }
        }
        printf("\n");
        printf("SPIRV JS ARRAY DUMP END\n");
#endif
    }

    dawn::ShaderModule CreateShaderModule(const dawn::Device& device,
                                          dawn::ShaderStage stage,
                                          const char* source) {
        dawn::ShaderModuleBuilder builder = device.CreateShaderModuleBuilder();
        FillShaderModuleBuilder(builder, stage, source);
        return builder.GetResult();
    }

    dawn::Buffer CreateBufferFromData(const dawn::Device& device,
                                      const void* data,
                                      uint32_t size,
                                      dawn::BufferUsageBit usage) {
        dawn::Buffer buffer = device.CreateBufferBuilder()
                                  .SetAllowedUsage(dawn::BufferUsageBit::TransferDst | usage)
                                  .SetSize(size)
                                  .GetResult();
        buffer.SetSubData(0, size, reinterpret_cast<const uint8_t*>(data));
        return buffer;
    }

    BasicRenderPass CreateBasicRenderPass(const dawn::Device& device,
                                          uint32_t width,
                                          uint32_t height) {
        BasicRenderPass result;
        result.width = width;
        result.height = height;

        result.colorFormat = dawn::TextureFormat::R8G8B8A8Unorm;
        result.color = device.CreateTextureBuilder()
                           .SetDimension(dawn::TextureDimension::e2D)
                           .SetExtent(width, height, 1)
                           .SetFormat(result.colorFormat)
                           .SetMipLevels(1)
                           .SetAllowedUsage(dawn::TextureUsageBit::OutputAttachment |
                                            dawn::TextureUsageBit::TransferSrc)
                           .GetResult();

        dawn::TextureView colorView = result.color.CreateTextureViewBuilder().GetResult();
        result.renderPassInfo = device.CreateRenderPassDescriptorBuilder()
                                    .SetColorAttachment(0, colorView, dawn::LoadOp::Clear)
                                    .GetResult();

        return result;
    }

    dawn::SamplerDescriptor GetDefaultSamplerDescriptor() {
        dawn::SamplerDescriptor desc;

        desc.minFilter = dawn::FilterMode::Linear;
        desc.magFilter = dawn::FilterMode::Linear;
        desc.mipmapFilter = dawn::FilterMode::Linear;
        desc.addressModeU = dawn::AddressMode::Repeat;
        desc.addressModeV = dawn::AddressMode::Repeat;
        desc.addressModeW = dawn::AddressMode::Repeat;

        return desc;
    }

    dawn::PipelineLayout MakeBasicPipelineLayout(const dawn::Device& device,
                                                 const dawn::BindGroupLayout* bindGroupLayout) {
        dawn::PipelineLayoutDescriptor descriptor;
        if (bindGroupLayout) {
            descriptor.numBindGroupLayouts = 1;
            descriptor.bindGroupLayouts = bindGroupLayout;
        } else {
            descriptor.numBindGroupLayouts = 0;
            descriptor.bindGroupLayouts = nullptr;
        }
        return device.CreatePipelineLayout(&descriptor);
    }

    dawn::BindGroupLayout MakeBindGroupLayout(
        const dawn::Device& device,
        std::initializer_list<dawn::BindGroupBinding> bindingsInitializer) {
        std::vector<dawn::BindGroupBinding> bindings;
        dawn::ShaderStageBit kNoStages{};
        for (const dawn::BindGroupBinding& binding : bindingsInitializer) {
            if (binding.visibility != kNoStages) {
                bindings.push_back(binding);
            }
        }

        dawn::BindGroupLayoutDescriptor descriptor;
        descriptor.numBindings = static_cast<uint32_t>(bindings.size());
        descriptor.bindings = bindings.data();
        return device.CreateBindGroupLayout(&descriptor);
    }

}  // namespace utils


text:
@org.osgi.annotation.versioning.Version("1.1.0")
package aQute.bnd.junit;


text:
#ifndef _PROJECTIONS_EPSG_TRAITS_HPP
#define _PROJECTIONS_EPSG_TRAITS_HPP

// Boost.Geometry (aka GGL, Generic Geometry Library)
//
// Copyright Barend Gehrels 2007-2009, Geodan, Amsterdam, the Netherlands.
// Copyright Bruno Lalande 2008, 2009
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>

namespace boost { namespace geometry { namespace projection
{

/*!
    \brief EPSG traits
    \details With help of the EPSG traits library users can statically use projections
        or coordinate systems specifying an EPSG code. The correct projections for transformations
        are used automically then, still keeping static polymorphism.
    \ingroup projection
    \tparam EPSG epsg code
    \tparam LL latlong point type
    \tparam XY xy point type
    \tparam PAR parameter type, normally not specified
*/
template <size_t EPSG, typename LLR, typename XY, typename PAR = parameters>
struct epsg_traits
{
    // Specializations define:
    // - type to get projection type
    // - function par to get parameters
};

}}} // namespace boost::geometry::projection

#endif


text:
module Xsub

  class OutputHelper

    def self.run
      is_json_mode = (ENV['XSUB_FORCE_JSON'] == '1')
      is_success = true

      if is_json_mode then
        require 'stringio'
        require 'json'
        original_stdout = $stdout
        original_stderr = $stderr
        $stdout = StringIO.new
        $stderr = StringIO.new
        error = nil
      end

      begin
        yield
      rescue => e
        if is_json_mode then
          error = e
        else
          raise e
        end
      end

      if is_json_mode then
        results = {}
        merge_json!(results, :STDOUT, $stdout.string)
        merge_json!(results, :STDERR, $stderr.string)
        merge_json!(results, :ERROR, error == nil ? "" : error.message)

        original_stdout.write JSON.pretty_generate(results)
        $stdout = original_stdout
        $stderr = original_stderr

        if error != nil then
          raise error
        end
      end
    end

    def self.merge_json!(hash, key, json_string)
      unless json_string.eql?("") then
        begin
          hash.merge!(JSON.parse(json_string))
        rescue
          hash[key] = json_string
        end
      end
    end
  end
end


text:
from __future__ import print_function
import sys
import os
import khmer

def write_dist(dist, fp):
    for n, i in enumerate(dist):
        fp.write('%d %d\n' % (n, i))

def main():
    hashfile = sys.argv[1]
    filename = sys.argv[2]
    outfile = os.path.basename(filename)

    print('loading kh file', hashfile)
    ht = khmer.load_countgraph(hashfile)

    x = ht.fasta_count_kmers_by_position(filename, 100, 1)
    write_dist(x, open(outfile + '.pos.abund=1', 'w'))
    print('wrote', outfile + '.pos.abund=1')

    y = ht.fasta_count_kmers_by_position(filename, 100, 255)
    write_dist(y, open(outfile + '.pos.abund=255', 'w'))
    print('wrote', outfile + '.pos.abund=255')

if __name__ == '__main__':
    main()


text:
<?php
/* @var $this MenusController */
/* @var $model SBMenu */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'menu_id'); ?>
		<?php echo $form->textField($model,'menu_id'); ?>

		<?php echo $form->label($model,'parent_id'); ?>
		<?php echo $form->textField($model,'parent_id'); ?>

		<?php echo $form->label($model,'menu_name'); ?>
		<?php echo $form->textField($model,'menu_name',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->label($model,'action'); ?>
		<?php echo $form->textField($model,'action',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->label($model,'page_id'); ?>
		<?php echo $form->textField($model,'page_id'); ?>

		<?php echo $form->label($model,'category_news_id'); ?>
		<?php echo $form->textField($model,'category_news_id'); ?>

		<?php echo $form->label($model,'url_link'); ?>
		<?php echo $form->textField($model,'url_link',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->label($model,'link_key'); ?>
		<?php echo $form->textField($model,'link_key',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->label($model,'target'); ?>
		<?php echo $form->textField($model,'target',array('size'=>50,'maxlength'=>50)); ?>

		<?php echo $form->label($model,'positions'); ?>
		<?php echo $form->textField($model,'positions'); ?>

		<?php echo CHtml::submitButton('Search'); ?>

<?php $this->endWidget(); ?>


text:
function NavToggle(){
    $(".navbar-minimalize").trigger("click")
}
function SmoothlyMenu(){
    $("body").hasClass("mini-navbar")?$("body").hasClass("fixed-sidebar")?($("#side-menu").hide(),setTimeout(
        function(){
            $("#side-menu").fadeIn(500)},300)):$("#side-menu").removeAttr("style"):($("#side-menu").hide(),setTimeout(
                function(){
                    $("#side-menu").fadeIn(500)},100))
}
function localStorageSupport(){
    return"localStorage"in window&&null!==window.localStorage
}
layer.config({
    extend:["extend/layer.ext.js","skin/moon/style.css"],skin:"layer-ext-moon"
}),$(document).ready(
    function(){
        function e(){
            var e=$("body > #wrapper").height()-61;$(".sidebard-panel").css("min-height",e+"px"
            )}
            $("#side-menu").metisMenu(),
            $(".right-sidebar-toggle").click(
                function(){
                    $("#right-sidebar").toggleClass("sidebar-open")
                }),
                $(".sidebar-container").slimScroll({
                    height:"100%",railOpacity:.4,wheelStep:10
                }),
                $(".open-small-chat").click(
                    function(){
                        $(this).children().toggleClass("fa-comments").toggleClass("fa-remove"),
                            $(".small-chat-box").toggleClass("active")
                    }),
                $(".small-chat-box .content").slimScroll({
                    height:"234px",railOpacity:.4
                }),
                $(".check-link").click(
                    function(){
                        var e=$(this).find("i"),
                            a=$(this).next("span");
                        return e.toggleClass("fa-check-square").toggleClass("fa-square-o"),
                            a.toggleClass("todo-completed"),
                            !1
                    }),
                $(function(){
                    $(".sidebar-collapse").slimScroll({
                        height:"100%",railOpacity:.9,alwaysVisible:!1
                    })
                }),
                $(".navbar-minimalize").click(
                    function(){
                        $("body").toggleClass("mini-navbar"),SmoothlyMenu()
                    }),
                e(),
                $(window).bind("load resize click scroll",
                    function(){
                    $("body").hasClass("body-small")||e()
                }),
                $(window).scroll(
                    function(){
                        $(window).scrollTop()>0&&!$("body").hasClass("fixed-nav")?$("#right-sidebar").addClass("sidebar-top"):$("#right-sidebar").removeClass("sidebar-top")}),
                $(".full-height-scroll").slimScroll({
                    height:"100%"
                }),
                $("#side-menu>li").click(
                    function(){
                        $("body").hasClass("mini-navbar")&&NavToggle()
                    }),
                $("#side-menu>li li a").click(
                    function(){
                        $(window).width()<769&&NavToggle()
                    }),
                $(".nav-close").click(NavToggle),
            /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)&&$("#content-main").css("overflow-y","auto")
    }),
    $(window).bind("load resize",function(){
        $(this).width()<769&&($("body").addClass("mini-navbar"),
            $(".navbar-static-side").fadeIn())}),
    $(function(){
        if($("#fixednavbar").click(
            function(){
                $("#fixednavbar").is(":checked")?($(".navbar-static-top").removeClass("navbar-static-top").addClass("navbar-fixed-top"),
                    $("body").removeClass("boxed-layout"),
                    $("body").addClass("fixed-nav"),
                    $("#boxedlayout").prop("checked",!1),
                localStorageSupport&&localStorage.setItem("boxedlayout","off"),
                localStorageSupport&&localStorage.setItem("fixednavbar","on")):($(".navbar-fixed-top").removeClass("navbar-fixed-top").addClass("navbar-static-top"),
                    $("body").removeClass("fixed-nav"),
                localStorageSupport&&localStorage.setItem("fixednavbar","off"))
            }),
                $("#collapsemenu").click(
                    function(){
                        $("#collapsemenu").is(":checked")?(
                            $("body").addClass("mini-navbar"),
                                SmoothlyMenu(),
                            localStorageSupport&&localStorage.setItem("collapse_menu","on")):(
                                $("body").removeClass("mini-navbar"),
                                    SmoothlyMenu(),
                                localStorageSupport&&localStorage.setItem("collapse_menu","off"))
                    }),
                $("#boxedlayout").click(
                    function(){
                        $("#boxedlayout").is(":checked")?($("body").addClass("boxed-layout"),
                            $("#fixednavbar").prop("checked",!1),
                            $(".navbar-fixed-top").removeClass("navbar-fixed-top").addClass("navbar-static-top"),
                            $("body").removeClass("fixed-nav"),
                        localStorageSupport&&localStorage.setItem("fixednavbar","off"),
                        localStorageSupport&&localStorage.setItem("boxedlayout","on")):($("body").removeClass("boxed-layout"),
                        localStorageSupport&&localStorage.setItem("boxedlayout","off"))}),
                $(".s-skin-0").click(
                            function(){
                                return $("body").removeClass("skin-1"),
                                    $("body").removeClass("skin-2"),
                                    $("body").removeClass("skin-3"),!1}),
                $(".s-skin-1").click(
                    function(){
                        return $("body").removeClass("skin-2"),
                            $("body").removeClass("skin-3"),
                            $("body").addClass("skin-1"),
                            !1
                    }),
                $(".s-skin-3").click(
                    function(){
                        return $("body").removeClass("skin-1"),
                            $("body").removeClass("skin-2"),
                            $("body").addClass("skin-3"),
                            !1
                    }),
                localStorageSupport){
            var e=localStorage.getItem("collapse_menu"),
                a=localStorage.getItem("fixednavbar"),
                o=localStorage.getItem("boxedlayout");
            "on"==e&&$("#collapsemenu").prop("checked","checked"),
            "on"==a&&$("#fixednavbar").prop("checked","checked"),
            "on"==o&&$("#boxedlayout").prop("checked","checked")
        }
        if(localStorageSupport){
            var e=localStorage.getItem("collapse_menu"),
                a=localStorage.getItem("fixednavbar"),
                o=localStorage.getItem("boxedlayout"),
                l=$("body");
            "on"==e&&(l.hasClass("body-small")||l.addClass("mini-navbar")),
            "on"==a&&($(".navbar-static-top").removeClass("navbar-static-top").addClass("navbar-fixed-top"),
                l.addClass("fixed-nav")),
            "on"==o&&l.addClass("boxed-layout")}});


text:
package ch.ethz.inf.vs.californium.network.layer;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

import ch.ethz.inf.vs.californium.coap.EmptyMessage;
import ch.ethz.inf.vs.californium.coap.Request;
import ch.ethz.inf.vs.californium.coap.Response;
import ch.ethz.inf.vs.californium.network.CoAPEndpoint;
import ch.ethz.inf.vs.californium.network.Exchange;
import ch.ethz.inf.vs.californium.server.MessageDeliverer;

/**
 * A layer processes requests, responses and empty messages. Layers can be
 * stacked upon each other to compose a processing stack.
 *

 * When the {@link CoAPEndpoint} receives a message, it forwards it to the bottom
 * layer by calling the corresponding receive-method. Each layer processes the
 * message and either forwards it to its upper layer or decides not to. The
 * uppermost layer forwards the message to the {@link MessageDeliverer} which
 * delivers the message to the server, e.g., a request to the target resource or
 * a response to the origin request.
 *

 * When an {@link CoAPEndpoint} sends a message, it forwards it to the uppermost
 * layer by calling the corresponding send-method. Each layer forwards the
 * message to its lower layer. The lowest layer forwards the message back to the
 * endpoint.
 *

 * The {@link Exchange} contains all information concerning an exchange of a
 * request with a response. Layers access the exchange concurrently but in most
 * cases it is only possible for a single thread to be active on fields of the
 * exchange since we usually only deal with one request or one response at time
 * and duplicates are stopped to travel through the stack beforehand. If this is
 * not the case, however, synchronization is required.
 *

 * Each layer should receive a {@link ScheduledExecutorService}. On this
 * executer, any task can be scheduled, e.g., retransmission. Many layers of
 * potentially many endpoints of potentially multiple servers can share the same
 * executor or have separate ones with different properties, e.g., size of
 * thread pool or priority of threads.
 */
public interface Layer {

	/**
	 * Process request before sending.
	 *
	 * @param exchange the exchange
	 * @param request the request
	 */
	public void sendRequest(Exchange exchange, Request request);

	/**
	 * Send response.
	 *
	 * @param exchange the exchange
	 * @param response the response
	 */
	public void sendResponse(Exchange exchange, Response response);

	/**
	 * Send empty message.
	 *
	 * @param exchange the exchange
	 * @param emptyMessage the empty message
	 */
	public void sendEmptyMessage(Exchange exchange, EmptyMessage emptyMessage);

	/**
	 * Receive request.
	 *
	 * @param exchange the exchange
	 * @param request the request
	 */
	public void receiveRequest(Exchange exchange, Request request);

	/**
	 * Receive response.
	 *
	 * @param exchange the exchange
	 * @param response the response
	 */
	public void receiveResponse(Exchange exchange, Response response);

	/**
	 * Receive empty message.
	 *
	 * @param exchange the exchange
	 * @param message the message
	 */
	public void receiveEmptyMessage(Exchange exchange, EmptyMessage message);

	/**
	 * Sets the lower layer.
	 *
	 * @param layer the new lower layer
	 */
	public void setLowerLayer(Layer layer);

	/**
	 * Sets the upper layer.
	 *
	 * @param layer the new upper layer
	 */
	public void setUpperLayer(Layer layer);

	/**
	 * Sets the executor.
	 *
	 * @param executor the new executor
	 */
	public void setExecutor(ScheduledExecutorService executor);

	/**
	 * A builder that constructs the stack from the top to the bottom. The
	 * returned list of layers is in the same order as added to the stack.
	 */
	public static class TopDownBuilder {

		/** The stack in order as added */
		private LinkedList<Layer> stack = new LinkedList<Layer>();

		/**
		 * Adds the specified layer below the currently lowest layer.
		 *
		 * @param layer the layer
		 * @return the builder
		 */
		public TopDownBuilder add(Layer layer) {
			if (stack.size() > 0)
				stack.getLast().setLowerLayer(layer);
			stack.add(layer);
			return this;
		}

		/**
		 * Creates the stack.
		 *
		 * @return the stack
		 */
		public List<Layer> create() {
			return stack;
		}

	}

	/**
	 * A builder that constructs the stack from the bottom upwards. The returned
	 * list of layers is in the same order as added to the stack.
	 */
	public static class BottomUpBuilder {

		/** The layers in order as added. */
		private LinkedList<Layer> stack = new LinkedList<Layer>();

		/**
		 * Adds the specified layer above the currently uppermost layer.
		 *
		 * @param layer the layer
		 * @return the bottom up builder
		 */
		public BottomUpBuilder add(Layer layer) {
			stack.getLast().setUpperLayer(layer);
			return this;
		}

		/**
		 * Creates the stack
		 *
		 * @return the stack
		 */
		public List<Layer> create() {
			return stack;
		}
	}

}


text:
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
from urllib.parse import parse_qs, urljoin, urlparse

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat

from .. import models as _models
from ..._serialization import Serializer
from .._vendor import _convert_request, _format_url_section

T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False

def build_list_by_resource_request(resource_uri: str, **kwargs: Any) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations")
    path_format_arguments = {
        "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

def build_list_by_rule_request(
    resource_group_name: str, data_collection_rule_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

def build_get_request(resource_uri: str, association_name: str, **kwargs: Any) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url", "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}"
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1),
        "associationName": _SERIALIZER.url("association_name", association_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

def build_create_request(resource_uri: str, association_name: str, **kwargs: Any) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
    content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url", "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}"
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1),
        "associationName": _SERIALIZER.url("association_name", association_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)

def build_delete_request(resource_uri: str, association_name: str, **kwargs: Any) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url", "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}"
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1),
        "associationName": _SERIALIZER.url("association_name", association_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)

class DataCollectionRuleAssociationsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~$(python-base-namespace).v2019_11_01_preview.MonitorManagementClient`'s
        :attr:`data_collection_rule_associations` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs):
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_resource(
        self, resource_uri: str, **kwargs: Any
    ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]:
        """Lists associations for the specified resource.

        Lists associations for the specified resource.

        :param resource_uri: The identifier of the resource. Required.
        :type resource_uri: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or
         the result of cls(response)
        :rtype:
         ~azure.core.paging.ItemPaged[~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_resource_request(
                    resource_uri=resource_uri,
                    api_version=api_version,
                    template_url=self.list_by_resource.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urlparse(next_link)
                _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query))
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params)
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize(
                "DataCollectionRuleAssociationProxyOnlyResourceListResult", pipeline_response
            )
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"}  # type: ignore

    @distributed_trace
    def list_by_rule(
        self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any
    ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]:
        """Lists associations for the specified data collection rule.

        Lists associations for the specified data collection rule.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param data_collection_rule_name: The name of the data collection rule. The name is case
         insensitive. Required.
        :type data_collection_rule_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or
         the result of cls(response)
        :rtype:
         ~azure.core.paging.ItemPaged[~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_by_rule_request(
                    resource_group_name=resource_group_name,
                    data_collection_rule_name=data_collection_rule_name,
                    subscription_id=self._config.subscription_id,
                    api_version=api_version,
                    template_url=self.list_by_rule.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urlparse(next_link)
                _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query))
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params)
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize(
                "DataCollectionRuleAssociationProxyOnlyResourceListResult", pipeline_response
            )
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    list_by_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations"}  # type: ignore

    @distributed_trace
    def get(
        self, resource_uri: str, association_name: str, **kwargs: Any
    ) -> _models.DataCollectionRuleAssociationProxyOnlyResource:
        """Returns the specified association.

        Returns the specified association.

        :param resource_uri: The identifier of the resource. Required.
        :type resource_uri: str
        :param association_name: The name of the association. The name is case insensitive. Required.
        :type association_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response)
        :rtype:
         ~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource]

        request = build_get_request(
            resource_uri=resource_uri,
            association_name=association_name,
            api_version=api_version,
            template_url=self.get.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}"}  # type: ignore

    @overload
    def create(
        self,
        resource_uri: str,
        association_name: str,
        body: Optional[_models.DataCollectionRuleAssociationProxyOnlyResource] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DataCollectionRuleAssociationProxyOnlyResource:
        """Creates or updates an association.

        Creates or updates an association.

        :param resource_uri: The identifier of the resource. Required.
        :type resource_uri: str
        :param association_name: The name of the association. The name is case insensitive. Required.
        :type association_name: str
        :param body: The payload. Default value is None.
        :type body:
         ~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response)
        :rtype:
         ~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def create(
        self,
        resource_uri: str,
        association_name: str,
        body: Optional[IO] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.DataCollectionRuleAssociationProxyOnlyResource:
        """Creates or updates an association.

        Creates or updates an association.

        :param resource_uri: The identifier of the resource. Required.
        :type resource_uri: str
        :param association_name: The name of the association. The name is case insensitive. Required.
        :type association_name: str
        :param body: The payload. Default value is None.
        :type body: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response)
        :rtype:
         ~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def create(
        self,
        resource_uri: str,
        association_name: str,
        body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None,
        **kwargs: Any
    ) -> _models.DataCollectionRuleAssociationProxyOnlyResource:
        """Creates or updates an association.

        Creates or updates an association.

        :param resource_uri: The identifier of the resource. Required.
        :type resource_uri: str
        :param association_name: The name of the association. The name is case insensitive. Required.
        :type association_name: str
        :param body: The payload. Is either a model type or a IO type. Default value is None.
        :type body:
         ~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource
         or IO
        :keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
         Default value is None.
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response)
        :rtype:
         ~$(python-base-namespace).v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
        content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource]

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(body, (IO, bytes)):
            _content = body
        else:
            if body is not None:
                _json = self._serialize.body(body, "DataCollectionRuleAssociationProxyOnlyResource")
            else:
                _json = None

        request = build_create_request(
            resource_uri=resource_uri,
            association_name=association_name,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            template_url=self.create.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if response.status_code == 200:
            deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    create.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}"}  # type: ignore

    @distributed_trace
    def delete(  # pylint: disable=inconsistent-return-statements
        self, resource_uri: str, association_name: str, **kwargs: Any
    ) -> None:
        """Deletes an association.

        Deletes an association.

        :param resource_uri: The identifier of the resource. Required.
        :type resource_uri: str
        :param association_name: The name of the association. The name is case insensitive. Required.
        :type association_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview"))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[None]

        request = build_delete_request(
            resource_uri=resource_uri,
            association_name=association_name,
            api_version=api_version,
            template_url=self.delete.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})

    delete.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}"}  # type: ignore


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager, JhiAlertService } from 'ng-jhipster';

import { ResourceBlockChainInfo } from './resource-block-chain-info.model';
import { ResourceBlockChainInfoPopupService } from './resource-block-chain-info-popup.service';
import { ResourceBlockChainInfoService } from './resource-block-chain-info.service';

import { CoinBlockChainInfo, CoinBlockChainInfoService } from '../coin';

@Component({
    selector: 'jhi-resource-block-chain-info-dialog',
    templateUrl: './resource-block-chain-info-dialog.component.html'
})
export class ResourceBlockChainInfoDialogComponent implements OnInit {

    resource: ResourceBlockChainInfo;
    isSaving: boolean;

    coins: CoinBlockChainInfo[];

    constructor(
        public activeModal: NgbActiveModal,
        private jhiAlertService: JhiAlertService,
        private resourceService: ResourceBlockChainInfoService,
        private coinService: CoinBlockChainInfoService,
        private eventManager: JhiEventManager
    ) {
    }

    ngOnInit() {
        this.isSaving = false;
        this.coinService.query()
            .subscribe((res: HttpResponse<CoinBlockChainInfo[]>) => { this.coins = res.body; }, (res: HttpErrorResponse) => this.onError(res.message));
    }

    clear() {
        this.activeModal.dismiss('cancel');
    }

    save() {
        this.isSaving = true;
        if (this.resource.id !== undefined) {
            this.subscribeToSaveResponse(
                this.resourceService.update(this.resource));
        } else {
            this.subscribeToSaveResponse(
                this.resourceService.create(this.resource));
        }
    }

    private subscribeToSaveResponse(result: Observable<HttpResponse<ResourceBlockChainInfo>>) {
        result.subscribe((res: HttpResponse<ResourceBlockChainInfo>) =>
            this.onSaveSuccess(res.body), (res: HttpErrorResponse) => this.onSaveError());
    }

    private onSaveSuccess(result: ResourceBlockChainInfo) {
        this.eventManager.broadcast({ name: 'resourceListModification', content: 'OK'});
        this.isSaving = false;
        this.activeModal.dismiss(result);
    }

    private onSaveError() {
        this.isSaving = false;
    }

    private onError(error: any) {
        this.jhiAlertService.error(error.message, null, null);
    }

    trackCoinById(index: number, item: CoinBlockChainInfo) {
        return item.id;
    }
}

@Component({
    selector: 'jhi-resource-block-chain-info-popup',
    template: ''
})
export class ResourceBlockChainInfoPopupComponent implements OnInit, OnDestroy {

    routeSub: any;

    constructor(
        private route: ActivatedRoute,
        private resourcePopupService: ResourceBlockChainInfoPopupService
    ) {}

    ngOnInit() {
        this.routeSub = this.route.params.subscribe((params) => {
            if ( params['id'] ) {
                this.resourcePopupService
                    .open(ResourceBlockChainInfoDialogComponent as Component, params['id']);
            } else {
                this.resourcePopupService
                    .open(ResourceBlockChainInfoDialogComponent as Component);
            }
        });
    }

    ngOnDestroy() {
        this.routeSub.unsubscribe();
    }
}


text:
<?php

namespace stz184\CaptchaBundle\Validator;

use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Translation\TranslatorInterface;

class CaptchaValidator {

    /** @var SessionInterface  */
    protected $session;
    /** @var TranslatorInterface */
    protected $translator;
    /** @var string */
    protected $sessionKey;
    protected $invalidMessage;

    public function __construct(SessionInterface $session, TranslatorInterface $translator, $sessionKey, $invalidMessage)
    {
        $this->session 			= $session;
        $this->translator 		= $translator;
        $this->sessionKey		= $sessionKey;
        $this->invalidMessage	= $invalidMessage;
    }

    protected function getExpectedCode()
    {
        return $this->session->get($this->sessionKey);
    }

    public function validate(FormEvent $event)
    {
        $form			= $event->getForm();
        $submittedCode	= $event->getData();
        $expectedCode 	= $this->getExpectedCode();

        if (!($submittedCode && is_string($submittedCode) && mb_strtolower($submittedCode) == mb_strtolower($expectedCode))) {
            $form->addError(
                new FormError($this->translator->trans($this->invalidMessage . '('.$expectedCode.')', array(), 'validators'))
            );
        }
    }
}


text:
package org.apache.deltaspike.data.test.ee7.domain;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@NamedQueries({
        @NamedQuery(name = Simple.BY_NAME_LIKE,
                   query = "select e from Simple e where e.name like ?1"),
        @NamedQuery(name = Simple.BY_NAME_ENABLED,
                   query = "select s from Simple s where s.name = ?1 and s.enabled = ?2 order by s.id asc"),
        @NamedQuery(name = Simple.BY_ID,
                   query = "select s from Simple s where s.id = :id and s.enabled = :enabled")
})
@Table(name = "SIMPLE_TABLE")
public class Simple extends SuperSimple
{
    public static final String BY_NAME_LIKE = "simple.byNameLike";
    public static final String BY_NAME_ENABLED = "simple.byNameAndEnabled";
    public static final String BY_ID = "simple.byId";

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;

    private String name;
    private String camelCase;
    private Boolean enabled = Boolean.TRUE;
    private Integer counter = Integer.valueOf(0);
    @Temporal(TemporalType.TIMESTAMP)
    private Date temporal;
    private EmbeddedSimple embedded;

    protected Simple()
    {
    }

    public Simple(String name)
    {
        this.name = name;
    }

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Boolean getEnabled()
    {
        return enabled;
    }

    public void setEnabled(Boolean enabled)
    {
        this.enabled = enabled;
    }

    public Integer getCounter()
    {
        return counter;
    }

    public void setCounter(Integer counter)
    {
        this.counter = counter;
    }

    public String getCamelCase()
    {
        return camelCase;
    }

    public void setCamelCase(String camelCase)
    {
        this.camelCase = camelCase;
    }

    public Date getTemporal()
    {
        return temporal;
    }

    public void setTemporal(Date temporal)
    {
        this.temporal = temporal;
    }

    public EmbeddedSimple getEmbedded()
    {
        return embedded;
    }

    public void setEmbedded(EmbeddedSimple embedded)
    {
        this.embedded = embedded;
    }

    @Override
    public String toString()
    {
        return "Simple [id=" + id + ", name=" + name + ", camelCase=" + camelCase + ", enabled=" + enabled
                + ", counter=" + counter + ", temporal=" + temporal + ", embedded=" + embedded + "]";
    }

}


text:
package handler

import (
	"errors"
	"testing"

	"github.com/mouadino/go-nano/protocol"
	"github.com/mouadino/go-nano/protocol/dummy"
	"github.com/mouadino/go-nano/utils"
)

type EchoService struct{}

func (s *EchoService) NanoStart() error {
	return nil
}

func (s *EchoService) Echo(text string) (string, error) {
	return text, nil
}

func (s *EchoService) Fail(text string) (string, error) {
	return "", errors.New("Fail!")
}

func TestReflection(t *testing.T) {
	handler := newStructHandler(&EchoService{})

	if len(handler.methods) != 2 {
		t.Errorf("Expected %d method, got %d", 2, len(handler.methods))
	}
}

func TestHandling(t *testing.T) {
	handler := newStructHandler(&EchoService{})
	req := protocol.Request{
		Method: "echo",
		Params: utils.ParamsFormat("foobar"),
	}
	resp := &dummy.ResponseWriter{}

	handler.Handle(resp, &req)

	ret, ok := resp.Data.(string)
	if !ok {
		t.Errorf("Return data is not string")
	}

	if ret != "foobar" {
		t.Errorf("Expected handler to return %s, got %s", "foobar", resp.Data)
	}
}

func TestUnknownMethod(t *testing.T) {
	handler := newStructHandler(&EchoService{})
	req := protocol.Request{
		Method: "blabla",
		Params: utils.ParamsFormat("foobar"),
	}
	resp := &dummy.ResponseWriter{}

	handler.Handle(resp, &req)

	if resp.Error != protocol.UnknownMethod {
		t.Errorf("Expected handle to fail with %s, got %s", protocol.UnknownMethod, resp.Error)
	}
}

func TestWrongArgumentsMethod(t *testing.T) {
	handler := newStructHandler(&EchoService{})
	req := protocol.Request{
		Method: "echo",
		Params: utils.ParamsFormat("foobar", 1),
	}
	resp := &dummy.ResponseWriter{}

	handler.Handle(resp, &req)

	if resp.Error != protocol.ParamsError {
		t.Errorf("Expected handle to fail with %s, got %s", protocol.ParamsError, resp.Error)
	}
}

func TestRemoteError(t *testing.T) {
	handler := newStructHandler(&EchoService{})
	req := protocol.Request{
		Method: "fail",
		Params: utils.ParamsFormat("foobar"),
	}
	resp := &dummy.ResponseWriter{}

	handler.Handle(resp, &req)

	if resp.Error == nil || resp.Error.Error() != "Fail!" {
		t.Errorf("expected to fail with 'Fail!' got %s", resp.Error)
	}
}


text:
package com.googlecode.android_scripting.facade;

import com.google.common.collect.Maps;
import com.googlecode.android_scripting.Log;
import com.googlecode.android_scripting.facade.ui.UiFacade;
import com.googlecode.android_scripting.jsonrpc.RpcReceiver;
import com.googlecode.android_scripting.rpc.MethodDescriptor;
import com.googlecode.android_scripting.rpc.RpcDeprecated;
import com.googlecode.android_scripting.rpc.RpcMinSdk;
import com.googlecode.android_scripting.rpc.RpcStartEvent;
import com.googlecode.android_scripting.rpc.RpcStopEvent;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Encapsulates the list of supported facades and their construction.
 *
 * @author Damon Kohler (damonkohler@gmail.com)
 * @author Igor Karp (igor.v.karp@gmail.com)
 */
public class FacadeConfiguration {
  private final static Set<Class<? extends RpcReceiver>> sFacadeClassList;
  private final static SortedMap<String, MethodDescriptor> sRpcs =
      new TreeMap<String, MethodDescriptor>();

  private static int sSdkLevel;

  static {

    if (android.os.Build.VERSION.SDK == null) {
      sSdkLevel = 3;
    } else {
      try {
        sSdkLevel = Integer.parseInt(android.os.Build.VERSION.SDK);
      } catch (NumberFormatException e) {
        Log.e(e);
      }
    }

    sFacadeClassList = new HashSet<Class<? extends RpcReceiver>>();
    sFacadeClassList.add(AndroidFacade.class);
    sFacadeClassList.add(ApplicationManagerFacade.class);
    sFacadeClassList.add(CameraFacade.class);
    sFacadeClassList.add(CommonIntentsFacade.class);
    sFacadeClassList.add(ContactsFacade.class);
    sFacadeClassList.add(EventFacade.class);
    sFacadeClassList.add(LocationFacade.class);
    sFacadeClassList.add(PhoneFacade.class);
    sFacadeClassList.add(MediaRecorderFacade.class);
    sFacadeClassList.add(SensorManagerFacade.class);
    sFacadeClassList.add(SettingsFacade.class);
    sFacadeClassList.add(SmsFacade.class);
    sFacadeClassList.add(SpeechRecognitionFacade.class);
    sFacadeClassList.add(ToneGeneratorFacade.class);
    sFacadeClassList.add(WakeLockFacade.class);
    sFacadeClassList.add(WifiFacade.class);
    sFacadeClassList.add(UiFacade.class);
    sFacadeClassList.add(BatteryManagerFacade.class);
    sFacadeClassList.add(ActivityResultFacade.class);
    sFacadeClassList.add(MediaPlayerFacade.class);
    sFacadeClassList.add(PreferencesFacade.class);

    if (sSdkLevel >= 4) {
      sFacadeClassList.add(TextToSpeechFacade.class);
    } else {
      sFacadeClassList.add(EyesFreeFacade.class);
    }

    if (sSdkLevel >= 5) {
      sFacadeClassList.add(BluetoothFacade.class);
    }

    if (sSdkLevel >= 7) {
      sFacadeClassList.add(SignalStrengthFacade.class);
    }

    if (sSdkLevel >= 8) {
      sFacadeClassList.add(WebCamFacade.class);
    }

    for (Class<? extends RpcReceiver> recieverClass : sFacadeClassList) {
      for (MethodDescriptor rpcMethod : MethodDescriptor.collectFrom(recieverClass)) {
        sRpcs.put(rpcMethod.getName(), rpcMethod);
      }
    }
  }

  private FacadeConfiguration() {
    // Utility class.
  }

  public static int getSdkLevel() {
    return sSdkLevel;
  }

  /** Returns a list of {@link MethodDescriptor} objects for all facades. */
  public static List<MethodDescriptor> collectMethodDescriptors() {
    return new ArrayList<MethodDescriptor>(sRpcs.values());
  }

  /**
   * Returns a list of not deprecated {@link MethodDescriptor} objects for facades supported by the
   * current SDK version.
   */
  public static List<MethodDescriptor> collectSupportedMethodDescriptors() {
    List<MethodDescriptor> list = new ArrayList<MethodDescriptor>();
    for (MethodDescriptor descriptor : sRpcs.values()) {
      Method method = descriptor.getMethod();
      if (method.isAnnotationPresent(RpcDeprecated.class)) {
        continue;
      } else if (method.isAnnotationPresent(RpcMinSdk.class)) {
        int requiredSdkLevel = method.getAnnotation(RpcMinSdk.class).value();
        if (sSdkLevel < requiredSdkLevel) {
          continue;
        }
      }
      list.add(descriptor);
    }
    return list;
  }

  public static Map<String, MethodDescriptor> collectStartEventMethodDescriptors() {
    Map<String, MethodDescriptor> map = Maps.newHashMap();
    for (MethodDescriptor descriptor : sRpcs.values()) {
      Method method = descriptor.getMethod();
      if (method.isAnnotationPresent(RpcStartEvent.class)) {
        String eventName = method.getAnnotation(RpcStartEvent.class).value();
        if (map.containsKey(eventName)) {
          throw new RuntimeException("Duplicate start event method descriptor found.");
        }
        map.put(eventName, descriptor);
      }
    }
    return map;
  }

  public static Map<String, MethodDescriptor> collectStopEventMethodDescriptors() {
    Map<String, MethodDescriptor> map = Maps.newHashMap();
    for (MethodDescriptor descriptor : sRpcs.values()) {
      Method method = descriptor.getMethod();
      if (method.isAnnotationPresent(RpcStopEvent.class)) {
        String eventName = method.getAnnotation(RpcStopEvent.class).value();
        if (map.containsKey(eventName)) {
          throw new RuntimeException("Duplicate stop event method descriptor found.");
        }
        map.put(eventName, descriptor);
      }
    }
    return map;
  }

  /** Returns a method by name. */
  public static MethodDescriptor getMethodDescriptor(String name) {
    return sRpcs.get(name);
  }

  public static Collection<Class<? extends RpcReceiver>> getFacadeClasses() {
    return sFacadeClassList;
  }
}


text:
import { FileBuilderService } from './file-builder.service';
const service = new FileBuilderService();

describe('FileBuilderService', () => {
  const file = new File(['FileContent12345'], 'nice/file5?.jpg');
  const result = service.buildResult(file);

  describe('buildResult', () => {
    it('contains a id with a slash', () => {
      expect(result.id).toContain('-');
    });

    it('contains the file', () => {
      expect(result.file).toEqual(file);
    });

    it('splits correctly the names and extension', () => {
      expect(result.orginalName).toEqual('nice/file5?.jpg');
      expect(result.cleanName).toEqual('nicefile5.jpg');
      expect(result.name).toEqual('nicefile5');
      expect(result.extension).toEqual('jpg');
    });

    it('contains the unsent status', () => {
      expect(result.uploadProgressInPercent).toEqual(0);
      expect(result.uploadStatus).toEqual(0);
      expect(result.uploadStatusText).toEqual('unsent');
    });

    it('do not have a publicUrl or filePath', () => {
      expect(result.publicUrl).toBeUndefined();
      expect(result.filePath).toBeUndefined();
    });
  });

  describe('getPublicUrl', () => {
    it('returns the public Url', () => {
      expect(service.getPublicUrl(result, '//public/url/')).toEqual('//public/url/nicefile5.jpg');
    });
  });

  describe('getFilePath', () => {
    it('returns the file path', () => {
      expect(service.getFilePath(result, 'path/to/file/')).toEqual('path/to/file/nicefile5.jpg');
    });
  });
});


text:
define([
    'jquery',
    'oroui/js/mediator',
    'oroworkflow/js/transition-event-handlers'
], function($, mediator, TransitionEventHandlers) {
    'use strict';

    /**
     * Transition executor
     *
     * @export  oroworkflow/js/transition-executor
     * @class   oro.WorkflowTransitionExecutor
     */
    return function(element, data, pageRefresh) {
        TransitionEventHandlers.getOnStart(element, pageRefresh)();

        $.post(element.data('transition-url'), data ? {data: data} : null, null, 'json')
            .done(TransitionEventHandlers.getOnSuccess(element, pageRefresh))
            .fail(TransitionEventHandlers.getOnFailure(element, pageRefresh));
    };
});


text:
package ma.glasnost.orika.test.community;

import static org.junit.Assert.assertEquals;
import ma.glasnost.orika.BoundMapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingException;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import org.junit.Test;

public class Issue132TestCase {

    @Test(expected=MappingException.class)
    public void test() {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.classMap(Person1.class, Person2.class)
                .constructorB("fn")
                .field("firstname", "forename")
                .register();

        BoundMapperFacade<Person1,Person2> mapperFacade = mapperFactory.getMapperFacade(Person1.class, Person2.class);
        Person1 otto1 = new Person1("Otto");
        Person2 otto2 = mapperFacade.map(otto1);

        assertEquals(otto1.getFirstname(), otto2.getForename());
    }

    @Test
    public void testMappedNamesWithSpecifiedConstructor() {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.classMap(Person1.class, Person2.class)
                .constructorB("fn")
                .fieldAToB("firstname", "fn")
                .fieldBToA("forename","firstname")
                .register();

        BoundMapperFacade<Person1,Person2> mapperFacade = mapperFactory.getMapperFacade(Person1.class, Person2.class);
        Person1 otto1 = new Person1("Otto");
        Person2 otto2 = mapperFacade.map(otto1);

        assertEquals(otto1.getFirstname(), otto2.getForename());
    }

    @Test
    public void testMappedNamesWithoutSpecifiedConstructor() {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.classMap(Person1.class, Person2.class)
                .fieldAToB("firstname", "fn")
                .fieldBToA("forename","firstname")
                .register();

        BoundMapperFacade<Person1,Person2> mapperFacade = mapperFactory.getMapperFacade(Person1.class, Person2.class);
        Person1 otto1 = new Person1("Otto");
        Person2 otto2 = mapperFacade.map(otto1);

        assertEquals(otto1.getFirstname(), otto2.getForename());
    }

    public static class Person1 {
        private final String firstname;

        public Person1(String firstname) {
            this.firstname = firstname;
        }

        public String getFirstname() {
            return firstname;
        }
    }

    public static class Person2 {
        private final String forename;

        public Person2(String fn) {
            this.forename = fn;
        }

        public String getForename() {
            return forename;
        }
    }
}