text:
int main(int argc, char *argv[]) {
  try {
    using namespace kaldi;
    using namespace kaldi::nnet2;
    typedef kaldi::int32 int32;

    const char *usage =
        "Copy a (cpu-based) neural net and its associated transition model,\n"
        "but modify it to reduce the effective parameter count by limiting\n"
        "the rank of the last affine component, which is replaced with two\n"
        "affine components.  You specify the number of singlular values to\n"
        "retain as e.g. --dim=200\n"
        "\n"
        "Usage:  nnet-am-limit-rank-final [options] <nnet-in> <nnet-out>\n"
        "e.g.:\n"
        " nnet-am-limit-rank-final --dim=200 1.mdl 1_limited.mdl\n";

    bool binary_write = true;
    int32 dim = 200;

    ParseOptions po(usage);
    po.Register("binary", &binary_write, "Write output in binary mode");
    po.Register("dim", &dim, "Dimension to retain");

    po.Read(argc, argv);

    if (po.NumArgs() != 2) {
      po.PrintUsage();
      exit(1);
    }

    std::string nnet_rxfilename = po.GetArg(1), nnet_wxfilename = po.GetArg(2);

    TransitionModel trans_model;
    AmNnet am_nnet;
    {
      bool binary;
      Input ki(nnet_rxfilename, &binary);
      trans_model.Read(ki.Stream(), binary);
      am_nnet.Read(ki.Stream(), binary);
    }

    am_nnet.GetNnet().LimitRankOfLastLayer(dim);

    {
      Output ko(nnet_wxfilename, binary_write);
      trans_model.Write(ko.Stream(), binary_write);
      am_nnet.Write(ko.Stream(), binary_write);
    }
    KALDI_LOG << "Limited rank of neural net " << nnet_rxfilename
              << " and copied to " << nnet_wxfilename;
    return 0;
  } catch (const std::exception &e) {
    std::cerr << e.what() << '\n';
    return -1;
  }
}


text:
/**
 * Meta data stored in the bottom of the WAST File
 *
 * @code
 * (module
 * (import "env" "memory" (memory $0 256))
 * (table 0 anyfunc)
 * (export "fib" (func $fib))
 * (func $fib (param $0 i32) (result i32)
 * ....
 * )
 * )
 * ;; METADATA: { "asmConsts": {},"staticBump": 8, "initializers": [] }
 *
 * The last line is the meta data that we are interested in/
 */
export interface WastMetaData {

    /**
     * The static bump (static data stored in module
     */
    staticBump: number;

    /**
     * is string correct?
     */
    asmConsts: string[];

    /**
     * Is string correct?
     */
    initializers: string[];
}

redpajama_set_name: RedPajamaGithub


text:
<bill session="115" type="sr" number="159" updated="2017-06-17T10:08:12Z">
  <state datetime="2017-05-08">PASSED:SIMPLERES</state>
  <status>
    <unknown datetime="2017-05-08"/>
  </status>
  <introduced datetime="2017-05-08"/>
  <titles>
    <title type="official" as="introduced">A resolution recognizing and supporting the goals and ideals of National Sexual Assault Awareness Month.</title>
    <title type="display">A resolution recognizing and supporting the goals and ideals of National Sexual Assault Awareness Month.</title>
  </titles>
  <sponsor bioguide_id="G000386"/>
  <cosponsors>
    <cosponsor bioguide_id="E000295" joined="2017-05-08"/>
    <cosponsor bioguide_id="F000062" joined="2017-05-08"/>
  </cosponsors>
  <actions>
    <action datetime="2017-05-08">
      <text>Introduced in Senate</text>
    </action>
    <vote how="by Unanimous Consent" type="vote" datetime="2017-05-08" where="s" result="pass" state="PASSED:SIMPLERES">
      <text>Submitted in the Senate, considered, and agreed to without amendment and with a preamble by Unanimous Consent.</text>
      <reference ref="CR S2803" label="Sponsor introductory remarks on measure"/>
      <reference ref="CR S2314" label="consideration"/>
      <reference ref="CR S2802-2803" label="text as passed Senate"/>
    </vote>
  </actions>
  <committees/>
  <relatedbills>
    <bill type="hr" session="115" relation="unknown" number="269"/>
  </relatedbills>
  <subjects>
    <term name="Crime and law enforcement"/>
    <term name="Assault and harassment offenses"/>
    <term name="Commemorative events and holidays"/>
    <term name="Congressional tributes"/>
    <term name="Crime prevention"/>
    <term name="Crime victims"/>
    <term name="Crimes against women"/>
    <term name="Criminal investigation, prosecution, interrogation"/>
    <term name="Health personnel"/>
    <term name="Law enforcement officers"/>
    <term name="Sex offenses"/>
  </subjects>
  <amendments/>
  <summary date="2017-05-08T11:50:06Z" status="Passed Senate without amendment">(This measure has not been amended since it was introduced. The summary of that version is repeated here.)

Expresses support for the goals and ideals of National Sexual Assault Awareness Month.

Recognizes that National Sexual Assault Awareness Month provides an opportunity for sexual violence education and sexual assault prevention, treatment, and prosecution.

Calls for: (1) acknowledging survivors and commending volunteers and professionals who assist them; (2) recognizing and applauding national and community organizations and private sector supporters; and (3) recognizing and applauding public safety, law enforcement, and health professionals.</summary>
  <committee-reports/>
</bill>


text:
/**
 * This file was added automatically by CKEditor builder.
 * You may re-use it at any time to build CKEditor again.
 *
 * If you would like to build CKEditor online again
 * (for example to upgrade), visit one the following links:
 *
 * (1) http://ckeditor.com/builder
 *     Visit online builder to build CKEditor from scratch.
 *
 * (2) http://ckeditor.com/builder/102ae10b37cd822c2ab8327eccb884c5
 *     Visit online builder to build CKEditor, starting with the same setup as before.
 *
 * (3) http://ckeditor.com/builder/download/102ae10b37cd822c2ab8327eccb884c5
 *     Straight download link to the latest version of CKEditor (Optimized) with the same setup as before.
 *
 * NOTE:
 *    This file is not used by CKEditor, you may remove it.
 *    Changing this file will not change your CKEditor configuration.
 */

var CKBUILDER_CONFIG = {
	skin: 'bootstrapck',
	preset: 'basic',
	ignore: [
		'dev',
		'.gitignore',
		'.gitattributes',
		'README.md',
		'.mailmap'
	],
	plugins : {
		'about' : 1,
		'basicstyles' : 1,
		'clipboard' : 1,
		'enterkey' : 1,
		'entities' : 1,
		'floatingspace' : 1,
		'indentlist' : 1,
		'link' : 1,
		'list' : 1,
		'toolbar' : 1,
		'undo' : 1,
		'wysiwygarea' : 1
	},
	languages : {
		'en' : 1,
		'ru' : 1
	}
};


text:
require 'spec_helper'

describe RubyRTF::Colour do
  it 'also responds to Color' do
    lambda { RubyRTF::Color.new }.should_not raise_error
  end

  it 'returns the rgb when to_s is called' do
    c = RubyRTF::Colour.new(255, 200, 199)
    c.to_s.should == '[255, 200, 199]'
  end
end


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    /// <summary>
    /// Abstract base class for mutable and immutable type maps.
    /// </summary>
    internal abstract class AbstractTypeMap
    {
        /// <summary>
        /// Substitute for a type declaration.  May use alpha renaming if the container is substituted.
        /// </summary>
        private NamedTypeSymbol SubstituteMemberType(NamedTypeSymbol previous)
        {
            Debug.Assert((object)previous.ConstructedFrom == (object)previous);

            NamedTypeSymbol newContainingType = SubstituteNamedType(previous.ContainingType);
            if ((object)newContainingType == null)
            {
                return previous;
            }

            return previous.OriginalDefinition.AsMember(newContainingType);
        }

        /// <summary>
        /// SubstType, but for NamedTypeSymbols only.  This is used for concrete types, so no alpha substitution appears in the result.
        /// </summary>
        internal NamedTypeSymbol SubstituteNamedType(NamedTypeSymbol previous)
        {
            if (ReferenceEquals(previous, null))
                return null;

            if (previous.IsUnboundGenericType)
                return previous;

            if (previous.IsAnonymousType)
            {
                ImmutableArray<TypeSymbol> oldFieldTypes = AnonymousTypeManager.GetAnonymousTypePropertyTypes(previous);
                ImmutableArray<TypeSymbol> newFieldTypes = SubstituteTypes(oldFieldTypes);
                return (oldFieldTypes == newFieldTypes) ? previous : AnonymousTypeManager.ConstructAnonymousTypeSymbol(previous, newFieldTypes);
            }

            // TODO: we could construct the result's ConstructedFrom lazily by using a "deep"
            // construct operation here (as VB does), thereby avoiding alpha renaming in most cases.
            // Aleksey has shown that would reduce GC pressure if substitutions of deeply nested generics are common.
            NamedTypeSymbol oldConstructedFrom = previous.ConstructedFrom;
            NamedTypeSymbol newConstructedFrom = SubstituteMemberType(oldConstructedFrom);

            ImmutableArray<TypeSymbol> oldTypeArguments = previous.TypeArgumentsNoUseSiteDiagnostics;
            ImmutableArray<TypeSymbol> newTypeArguments = SubstituteTypes(oldTypeArguments);

            if (ReferenceEquals(oldConstructedFrom, newConstructedFrom) && oldTypeArguments == newTypeArguments)
            {
                return previous;
            }

            return newConstructedFrom.ConstructIfGeneric(newTypeArguments);
        }

        /// <summary>
        /// Perform the substitution on the given type.  Each occurrence of the type parameter is
        /// replaced with its corresponding type argument from the map.
        /// </summary>
        /// <param name="previous">The type to be rewritten.</param>
        /// <returns>The type with type parameters replaced with the type arguments.</returns>
        internal TypeSymbol SubstituteType(TypeSymbol previous)
        {
            if (ReferenceEquals(previous, null))
                return null;

            switch (previous.Kind)
            {
                case SymbolKind.NamedType:
                    return SubstituteNamedType((NamedTypeSymbol)previous);
                case SymbolKind.TypeParameter:
                    return SubstituteTypeParameter((TypeParameterSymbol)previous);
                case SymbolKind.ArrayType:
                    return SubstituteArrayType((ArrayTypeSymbol)previous);
                case SymbolKind.PointerType:
                    return SubstitutePointerType((PointerTypeSymbol)previous);
                case SymbolKind.DynamicType:
                    return SubstituteDynamicType();
                case SymbolKind.ErrorType:
                    return ((ErrorTypeSymbol)previous).Substitute(this);
                default:
                    return previous;
            }
        }

        protected virtual TypeSymbol SubstituteDynamicType()
        {
            return DynamicTypeSymbol.Instance;
        }

        protected virtual TypeSymbol SubstituteTypeParameter(TypeParameterSymbol typeParameter)
        {
            return typeParameter;
        }

        private ArrayTypeSymbol SubstituteArrayType(ArrayTypeSymbol t)
        {
            TypeSymbol element = SubstituteType(t.ElementType);
            if (ReferenceEquals(element, t.ElementType))
            {
                return t;
            }

            ImmutableArray<NamedTypeSymbol> interfaces = t.InterfacesNoUseSiteDiagnostics();
            Debug.Assert(0 <= interfaces.Length && interfaces.Length <= 2);

            if (interfaces.Length == 1)
            {
                Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T>
                interfaces = ImmutableArray.Create<NamedTypeSymbol>((NamedTypeSymbol)SubstituteType(interfaces[0]));
            }
            else if (interfaces.Length == 2)
            {
                Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T>
                interfaces = ImmutableArray.Create<NamedTypeSymbol>((NamedTypeSymbol)SubstituteType(interfaces[0]), (NamedTypeSymbol)SubstituteType(interfaces[1]));
            }

            return new ArrayTypeSymbol(
                element,
                t.Rank,
                t.BaseTypeNoUseSiteDiagnostics,
                interfaces,
                t.CustomModifiers);
        }

        private PointerTypeSymbol SubstitutePointerType(PointerTypeSymbol t)
        {
            TypeSymbol pointedAtType = SubstituteType(t.PointedAtType);
            if (ReferenceEquals(pointedAtType, t.PointedAtType))
            {
                return t;
            }

            return new PointerTypeSymbol(pointedAtType, t.CustomModifiers);
        }

        internal ImmutableArray<TypeSymbol> SubstituteTypes(ImmutableArray<TypeSymbol> original)
        {
            if (original.IsDefault)
            {
                return original;
            }

            TypeSymbol[] result = null;

            for (int i = 0; i < original.Length; i++)
            {
                var t = original[i];
                var substituted = SubstituteType(t);
                if (!Object.ReferenceEquals(substituted, t))
                {
                    if (result == null)
                    {
                        result = new TypeSymbol[original.Length];
                        for (int j = 0; j < i; j++)
                        {
                            result[j] = original[j];
                        }
                    }
                }

                if (result != null)
                {
                    result[i] = substituted;
                }
            }

            return result != null ? result.AsImmutableOrNull() : original;
        }

        /// <summary>
        /// Substitute types, and return the results without duplicates, preserving the original order.
        /// </summary>
        internal void SubstituteTypesDistinct(ImmutableArray<TypeSymbol> original, ArrayBuilder<TypeSymbol> result)
        {
            if (original.Length == 0)
            {
                return;
            }
            else if (original.Length == 1)
            {
                result.Add(SubstituteType(original[0]));
            }
            else
            {
                var set = new HashSet<TypeSymbol>();
                foreach (var type in original)
                {
                    var substituted = SubstituteType(type);
                    if (set.Add(substituted))
                    {
                        result.Add(substituted);
                    }
                }
            }
        }

        internal ImmutableArray<TypeParameterSymbol> SubstituteTypeParameters(ImmutableArray<TypeParameterSymbol> original)
        {
            return original.SelectAsArray((tp, m) => (TypeParameterSymbol)m.SubstituteTypeParameter(tp), this);
        }

        /// <summary>
        /// Like SubstTypes, but for NamedTypeSymbols.
        /// </summary>
        internal ImmutableArray<NamedTypeSymbol> SubstituteNamedTypes(ImmutableArray<NamedTypeSymbol> original)
        {
            NamedTypeSymbol[] result = null;

            for (int i = 0; i < original.Length; i++)
            {
                var t = original[i];
                var substituted = SubstituteNamedType(t);
                if (!Object.ReferenceEquals(substituted, t))
                {
                    if (result == null)
                    {
                        result = new NamedTypeSymbol[original.Length];
                        for (int j = 0; j < i; j++)
                        {
                            result[j] = original[j];
                        }
                    }
                }

                if (result != null)
                {
                    result[i] = substituted;
                }
            }

            return result != null ? result.AsImmutableOrNull() : original;
        }
    }
}


text:
use std::fs;
use std::path::Path;

use anyhow::{Context, Error};

use compile_shaders::{ShaderModel, ShaderType};

static SOURCES: &[(&str, &str, &[(&str, &str)])] = &[("mask", "mask.hlsl", &[])];

static PROTOS: &[&str] = &["src/proto/messages.proto"];

fn main() {
    for &path in PROTOS {
        println!("cargo:rerun-if-changed={}", path);
    }
    let mut prost_build = prost_build::Config::new();
    // Use Bytes for bytes fields instead of a Vec<u8>
    prost_build.bytes(&["."]);
    prost_build.compile_protos(PROTOS, &["src/proto/"]).unwrap();

    let out_path = std::env::var("OUT_DIR").unwrap();
    let out_path = Path::new(&out_path);
    assert!(out_path.exists());
    let shader_dir = Path::new("src/bw_scr/shaders");
    for &(out_name, source, defines) in SOURCES.iter() {
        let source_path = shader_dir.join(source);
        println!("cargo:rerun-if-changed={}", source_path.to_str().unwrap());
        let bin_path = out_path.join(&format!("{}.sm5.bin", out_name));
        let asm_path = out_path.join(&format!("{}.sm5.asm", out_name));
        compile_prism_shader(
            &source_path,
            &bin_path,
            &asm_path,
            defines,
            shader_dir,
            ShaderType::Pixel,
            ShaderModel::Sm5,
        )
        .unwrap_or_else(|e| panic!("Failed to compile {}: {:?}", out_name, e));

        let bin_path = out_path.join(&format!("{}.sm4.bin", out_name));
        let asm_path = out_path.join(&format!("{}.sm4.asm", out_name));
        compile_prism_shader(
            &source_path,
            &bin_path,
            &asm_path,
            defines,
            shader_dir,
            ShaderType::Pixel,
            ShaderModel::Sm4,
        )
        .unwrap_or_else(|e| panic!("Failed to compile {}: {:?}", out_name, e));
    }
    println!(
        "cargo:rustc-env=SHIELDBATTERY_VERSION={}",
        package_json_version("../package.json")
    );
}

fn package_json_version(path: &str) -> String {
    println!("cargo:rerun-if-changed={}", path);
    let mut file = fs::File::open(path).unwrap();
    let json: serde_json::Value = serde_json::from_reader(&mut file).unwrap();
    json.as_object()
        .expect("package.json root not object")
        .get("version")
        .expect("package.json version not found")
        .as_str()
        .expect("package.json version not string")
        .into()
}

fn compile_prism_shader(
    source_path: &Path,
    out_path: &Path,
    disasm_path: &Path,
    defines: &[(&str, &str)],
    include_root: &Path,
    shader_type: ShaderType,
    model: ShaderModel,
) -> Result<(), Error> {
    let text_bytes = fs::read(source_path)
        .with_context(|| format!("Failed to read {}", source_path.display()))?;
    let result = compile_shaders::compile(&text_bytes, defines, include_root, shader_type, model)?;
    for path in result.include_files {
        println!("cargo:rerun-if-changed={}", path);
    }
    let shader_bytes = result.shader;
    let wrapped = compile_shaders::wrap_prism_shader(&shader_bytes);
    fs::write(&out_path, &wrapped)
        .with_context(|| format!("Failed to write {}", out_path.display()))?;
    disasm_shader(&shader_bytes, disasm_path).context("Failed to disassemble the result")?;
    Ok(())
}

/// Output disassembly if needed for debugging.
/// Not necessary for actually building.
fn disasm_shader(shader_bytes: &[u8], out_path: &Path) -> Result<(), Error> {
    let disasm = compile_shaders::disassemble(shader_bytes)?;
    fs::write(&out_path, &disasm)
        .with_context(|| format!("Failed to write {}", out_path.display()))?;
    Ok(())
}


text:
enum Fred  { One, Two, Three};

type Py = "ONE" | "TWO" | "THREE";

class Foo {
    constructor() { }
    public getStuff(): IStuff[] {
        return [];
    }
    public getFred(): Fred { return Fred.One};
    public getPy(): Py { return "ONE"};

};

class IStuff {
    constructor() {
    }
    public field: Fred;
}


text:
import numpy as np

from coremltools.models.neural_network import NeuralNetworkBuilder
from coremltools.models import datatypes

import tvm
from tvm import te
from tvm.contrib import graph_runtime
from tvm import topi
import tvm.topi.testing
from tvm import relay
from tvm.topi.testing import conv2d_nchw_python

import coremltools as cm
import model_zoo
import tvm.testing

def get_tvm_output(
    func, x, params, target, ctx, out_shape=(1, 1000), input_name="image", dtype="float32"
):
    with tvm.transform.PassContext(opt_level=3):
        lib = relay.build(func, target, params=params)
    m = graph_runtime.GraphModule(lib["default"](ctx))
    # set inputs
    m.set_input(input_name, tvm.nd.array(x.astype(dtype)))
    m.run()
    # get outputs
    out = m.get_output(0, tvm.nd.empty(out_shape, dtype))
    return out.asnumpy()

def run_model_checkonly(model_file, model_name="", input_name="image"):
    model = cm.models.MLModel(model_file)
    x = model_zoo.get_cat_image()
    shape_dict = {input_name: x.shape}
    # Some Relay passes change operators on the fly. Ensuring that we generate
    # new graph for each target.
    for target, ctx in tvm.testing.enabled_targets():
        mod, params = relay.frontend.from_coreml(model, shape_dict)
        tvm_output = get_tvm_output(mod["main"], x, params, target, ctx)
        print(target, ctx, model_name, "prediction id: ", np.argmax(tvm_output.flat))

@tvm.testing.uses_gpu
def test_mobilenet_checkonly():
    model_file = model_zoo.get_mobilenet()
    run_model_checkonly(model_file, "mobilenet")

@tvm.testing.uses_gpu
def test_resnet50_checkonly():
    model_file = model_zoo.get_resnet50()
    run_model_checkonly(model_file, "resnet50")

def run_tvm_graph(
    coreml_model, target, ctx, input_data, input_name, output_shape, output_dtype="float32"
):
    """ Generic function to compile on relay and execute on tvm """
    if isinstance(input_data, list):
        shape_dict = {}
        dtype_dict = {}
        for i, e in enumerate(input_name):
            shape_dict[e] = input_data[i].shape
            dtype_dict[e] = input_data[i].dtype
    else:
        shape_dict = {input_name: input_data.shape}
        dtype_dict = {input_name: input_data.dtype}

    mod, params = relay.frontend.from_coreml(coreml_model, shape_dict)
    with tvm.transform.PassContext(opt_level=3):
        lib = relay.build(mod, target, params=params)

    from tvm.contrib import graph_runtime

    m = graph_runtime.GraphModule(lib["default"](ctx))
    # set inputs
    if isinstance(input_data, list):
        for i, e in enumerate(input_name):
            m.set_input(e, tvm.nd.array(input_data[i].astype(input_data[i].dtype)))
    else:
        m.set_input(input_name, tvm.nd.array(input_data.astype(input_data.dtype)))

    # execute
    m.run()
    # get outputs
    if isinstance(output_shape, list) and isinstance(output_dtype, list):
        tvm_output_list = []
        for i, s in enumerate(output_shape):
            tvm_output = m.get_output(i, tvm.nd.empty((s), output_dtype[i]))
            tvm_output_list.append(tvm_output.asnumpy())
        return tvm_output_list
    else:
        if not output_shape:
            tvm_output = m.get_output(0)
        else:
            tvm_output = m.get_output(0, tvm.nd.empty((output_shape), output_dtype))
        return tvm_output.asnumpy()

def verify_AddLayerParams(input_dim, alpha=2):
    dtype = "float32"

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.add(a_np1, a_np2) + alpha
    inputs = [("input1", datatypes.Array(*input_dim)), ("input2", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_elementwise(
        name="Add", alpha=alpha, input_names=["input1", "input2"], output_name="output", mode="ADD"
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model, target, ctx, [a_np1, a_np2], ["input1", "input2"], b_np.shape, dtype
        )
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_AddLayerParams():
    verify_AddLayerParams((1, 2, 2), 0)
    verify_AddLayerParams((1, 2, 2), 1)
    verify_AddLayerParams((1, 3, 3), 2)

def verify_MultiplyLayerParams(input_dim, alpha):
    dtype = "float32"

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.multiply(a_np1, a_np2) * alpha
    inputs = [("input1", datatypes.Array(*input_dim)), ("input2", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_elementwise(
        name="Mul",
        alpha=alpha,
        input_names=["input1", "input2"],
        output_name="output",
        mode="MULTIPLY",
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model, target, ctx, [a_np1, a_np2], ["input1", "input2"], b_np.shape, dtype
        )
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_MultiplyLayerParams():
    verify_MultiplyLayerParams((1, 2, 2), 0)
    verify_MultiplyLayerParams((1, 2, 2), 1)
    verify_MultiplyLayerParams((1, 3, 3), 2)

def verify_ConcatLayerParams(input1_dim, input2_dim):
    dtype = "float32"

    a_np1 = np.random.uniform(size=input1_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input2_dim).astype(dtype)

    b_np = np.concatenate((a_np1, a_np2), axis=1)
    inputs = [("input1", datatypes.Array(*input1_dim)), ("input2", datatypes.Array(*input2_dim))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_elementwise(
        name="Concate", input_names=["input1", "input2"], output_name="output", mode="CONCAT"
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model, target, ctx, [a_np1, a_np2], ["input1", "input2"], b_np.shape, dtype
        )
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_ConcatLayerParams():
    verify_ConcatLayerParams((1, 1, 2, 2), (1, 2, 2, 2))
    verify_ConcatLayerParams((1, 2, 4, 4), (1, 3, 4, 4))

def verify_UpsampleLayerParams(input_dim, scale, mode):
    dtype = "float32"

    a_np = np.full(input_dim, 1, dtype=dtype)
    if mode == "NN":
        b_np = tvm.topi.testing.upsampling_python(a_np, (scale, scale))
    else:
        new_h = input_dim[2] * scale
        new_w = input_dim[3] * scale
        b_np = tvm.topi.testing.bilinear_resize_python(a_np, (new_h, new_w), "NCHW")

    input = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(input, output)
    builder.add_upsample(
        name="Upsample",
        scaling_factor_h=scale,
        scaling_factor_w=scale,
        mode=mode,
        input_name="input",
        output_name="output",
    )

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, a_np, "input", b_np.shape, dtype)
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_UpsampleLayerParams():
    verify_UpsampleLayerParams((1, 16, 32, 32), 2, "NN")
    verify_UpsampleLayerParams((1, 4, 6, 6), 3, "BILINEAR")

def verify_l2_normalize(input_dim, eps):
    dtype = "float32"

    a_np = np.random.uniform(size=input_dim).astype(dtype)
    b_np = tvm.topi.testing.l2_normalize_python(a_np, eps, 1)

    input = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(input, output)
    builder.add_l2_normalize(name="L2", epsilon=eps, input_name="input", output_name="output")

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, a_np, "input", b_np.shape, dtype)
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_l2_normalize():
    verify_l2_normalize((1, 3, 20, 20), 0.001)

def verify_lrn(input_dim, size, bias, alpha, beta):
    dtype = "float32"
    axis = 1
    a_np = np.random.uniform(size=input_dim).astype(dtype)
    b_np = tvm.topi.testing.lrn_python(a_np, size, axis, bias, alpha, beta)

    input = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(input, output)
    builder.add_lrn(
        name="LRN",
        input_name="input",
        output_name="output",
        alpha=alpha,
        beta=beta,
        k=bias,
        local_size=size,
    )

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, a_np, "input", b_np.shape, dtype)
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_lrn():
    verify_lrn((1, 3, 10, 20), 3, 1.0, 1.0, 0.5)

def verify_average(input_dim1, input_dim2, axis=0):
    dtype = "float32"

    a_np1 = np.random.uniform(size=input_dim1).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim2).astype(dtype)

    b_np = np.mean((a_np1, a_np2), axis=axis)

    inputs = [("input1", datatypes.Array(*input_dim1)), ("input2", datatypes.Array(*input_dim2))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_elementwise(
        name="MEAN", input_names=["input1", "input2"], output_name="output", mode="AVE"
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model, target, ctx, [a_np1, a_np2], ["input1", "input2"], b_np.shape, dtype
        )
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_average():
    verify_average((1, 3, 20, 20), (1, 3, 20, 20))
    verify_average((3, 20, 20), (1, 3, 20, 20))
    verify_average((20, 20), (1, 3, 20, 20))

def verify_max(input_dim):
    dtype = "float32"

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim).astype(dtype)
    a_np3 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.max((a_np1, a_np2, a_np3), axis=0)

    inputs = [
        ("input1", datatypes.Array(*input_dim)),
        ("input2", datatypes.Array(*input_dim)),
        ("input3", datatypes.Array(*input_dim)),
    ]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_elementwise(
        name="Max", input_names=["input1", "input2", "input3"], output_name="output", mode="MAX"
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model,
            target,
            ctx,
            [a_np1, a_np2, a_np3],
            ["input1", "input2", "input3"],
            b_np.shape,
            dtype,
        )
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_max():
    verify_max((1, 3, 20, 20))
    verify_max((20, 20))

def verify_min(input_dim):
    dtype = "float32"

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim).astype(dtype)
    a_np3 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.min((a_np1, a_np2, a_np3), axis=0)

    inputs = [
        ("input1", datatypes.Array(*input_dim)),
        ("input2", datatypes.Array(*input_dim)),
        ("input3", datatypes.Array(*input_dim)),
    ]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_elementwise(
        name="Min", input_names=["input1", "input2", "input3"], output_name="output", mode="MIN"
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model,
            target,
            ctx,
            [a_np1, a_np2, a_np3],
            ["input1", "input2", "input3"],
            b_np.shape,
            dtype,
        )
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_min():
    verify_min((1, 3, 20, 20))
    verify_min((20, 20))

def verify_unary_sqrt(input_dim):
    dtype = "float32"

    a_np = np.random.uniform(size=input_dim).astype(dtype)
    ref_val = np.sqrt(a_np)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(name="sqrt", input_name="input", output_name="output", mode="sqrt")

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def verify_unary_rsqrt(input_dim, epsilon=0):
    dtype = "float32"

    a_np = np.random.uniform(size=input_dim).astype(dtype)
    ref_val = 1 / np.sqrt(a_np + epsilon)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(
        name="rsqrt", input_name="input", output_name="output", mode="rsqrt", epsilon=epsilon
    )

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def verify_unary_inverse(input_dim, epsilon=0):
    dtype = "float32"

    a_np = np.random.uniform(size=input_dim).astype(dtype)
    ref_val = 1 / (a_np + epsilon)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(
        name="inverse", input_name="input", output_name="output", mode="inverse", epsilon=epsilon
    )

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def verify_unary_power(input_dim, alpha):
    dtype = "float32"

    a_np = np.random.uniform(size=input_dim).astype(dtype)
    ref_val = np.power(a_np, alpha)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(
        name="power", input_name="input", output_name="output", mode="power", alpha=alpha
    )

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def verify_unary_exp(input_dim):
    dtype = "float32"

    a_np = np.random.uniform(size=input_dim).astype(dtype)
    ref_val = np.exp(a_np)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(name="exp", input_name="input", output_name="output", mode="exp")

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def verify_unary_log(input_dim):
    dtype = "float32"

    a_np = np.random.uniform(size=input_dim).astype(dtype)
    ref_val = np.log(a_np)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(name="log", input_name="input", output_name="output", mode="log")

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def verify_unary_abs(input_dim):
    dtype = "float32"

    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)
    ref_val = np.abs(a_np)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(name="abs", input_name="input", output_name="output", mode="abs")

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def verify_unary_threshold(input_dim, alpha):
    dtype = "float32"

    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)
    ref_val = np.maximum(a_np, alpha)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_unary(
        name="threshold", input_name="input", output_name="output", mode="threshold", alpha=alpha
    )

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_unary():
    verify_unary_sqrt((1, 3, 20, 20))
    verify_unary_rsqrt((1, 3, 20, 20))
    verify_unary_rsqrt((1, 3, 20, 20), epsilon=1e-6)
    verify_unary_inverse((1, 3, 20, 20))
    verify_unary_inverse((1, 3, 20, 20), epsilon=1e-6)
    verify_unary_power((1, 3, 20, 20), alpha=0.5)
    verify_unary_power((1, 3, 20, 20), alpha=4)
    verify_unary_exp((1, 3, 20, 20))
    verify_unary_log((1, 3, 20, 20))
    verify_unary_abs((1, 3, 20, 20))
    verify_unary_threshold((1, 3, 20, 20), alpha=-6.0)
    verify_unary_threshold((1, 3, 20, 20), alpha=5.0)

@tvm.testing.uses_gpu
def test_forward_reduce():
    from enum import Enum

    class ReduceAxis(Enum):
        CHW = 0
        HW = 1
        C = 2
        H = 3
        W = 4

    def _verify_reduce(input_dim, mode, axis, ref_func, dtype="float32"):
        print(input_dim, mode, axis)
        a_np = np.random.uniform(size=input_dim).astype(dtype)

        # translate to axis from coreml format
        if axis == ReduceAxis.CHW:
            np_axis = (-3, -2, -1)
        elif axis == ReduceAxis.HW:
            np_axis = (-2, -1)
        elif axis == ReduceAxis.C:
            np_axis = -3
        elif axis == ReduceAxis.H:
            np_axis = -2
        elif axis == ReduceAxis.W:
            np_axis = -1

        if ref_func == np.argmax:
            ref_val = np.expand_dims(ref_func(a_np, np_axis), np_axis).astype(dtype)
        else:
            ref_val = ref_func(a_np, np_axis, keepdims=True)

        inputs = [("input", datatypes.Array(*input_dim))]
        output = [("output", datatypes.Array(*ref_val.shape))]
        builder = NeuralNetworkBuilder(inputs, output)
        builder.add_reduce(
            name=mode, input_name="input", output_name="output", axis=axis.name, mode=mode
        )

        model = cm.models.MLModel(builder.spec)
        for target, ctx in tvm.testing.enabled_targets():
            out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
            tvm.testing.assert_allclose(out, ref_val, rtol=1e-5, atol=1e-5)

    dshapes = [[10, 10], [1, 10, 10], [1, 3, 10, 10]]
    for dshape in dshapes:
        for axis in ReduceAxis:
            if len(dshape) < 3 and axis in [ReduceAxis.CHW, ReduceAxis.C]:
                # input must have rank at least 3
                continue
            _verify_reduce(dshape, "sum", axis, np.sum)
            _verify_reduce(dshape, "avg", axis, np.mean)
            _verify_reduce(dshape, "prod", axis, np.prod)
            _verify_reduce(dshape, "min", axis, np.min)
            _verify_reduce(dshape, "max", axis, np.max)
            if axis in [ReduceAxis.C, ReduceAxis.H, ReduceAxis.W]:
                # For mode ArgMax, axis must be [-1] or [-2] or [-3]
                _verify_reduce(dshape, "argmax", axis, np.argmax, dtype="int32")

def verify_reshape(input_dim, target_shape, mode):
    dtype = "float32"

    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)
    ref_val = np.reshape(a_np, target_shape)

    inputs = [("input", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*ref_val.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_reshape(
        name="reshape",
        input_name="input",
        output_name="output",
        target_shape=target_shape,
        mode=mode,
    )

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input"], ref_val.shape, dtype)
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def test_forward_reshape():
    for mode in [0, 1]:
        verify_reshape((20,), (1, 2, 2, 5), mode)
        verify_reshape((1, 3, 20, 20), (1, 12, 10, 10), mode)

def verify_split(input_dim, nOutputs):
    dtype = "float32"

    a_np = np.random.uniform(-100.0, 100.0, size=input_dim).astype(dtype)
    ref_val = np.split(a_np, nOutputs, axis=-3)

    inputs = [("input", datatypes.Array(*input_dim))]

    output_names = []
    outputs = []
    output_shapes = []
    for i, out in enumerate(ref_val):
        output_name = "output" + str(i)
        output_names = output_names + [output_name]
        outputs = outputs + [(output_name, datatypes.Array(*out.shape))]
        output_shapes = output_shapes + [out.shape]

    builder = NeuralNetworkBuilder(inputs, outputs)
    builder.add_split(name="split", input_name="input", output_names=output_names)

    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model, target, ctx, [a_np], ["input"], output_shapes, [dtype] * len(output_shapes)
        )
        tvm.testing.assert_allclose(out, ref_val, rtol=1e-5)

def test_forward_split():
    verify_split(
        (
            1,
            4,
            4,
            4,
        ),
        2,
    )
    verify_split(
        (
            1,
            3,
            30,
            20,
        ),
        3,
    )

def verify_image_scaler(input_dim, blue_bias=0.0, green_bias=0.0, red_bias=0.0, image_scale=1.0):
    dtype = "float32"
    a_np = np.random.uniform(size=input_dim).astype(dtype)
    # make sure it is valid image format CHW.
    assert len(a_np.shape) == 3 and a_np.shape[0] == 3
    b_np = np.zeros(a_np.shape, dtype=dtype)
    b_np[0, :, :] = image_scale * a_np[0, :, :] + blue_bias
    b_np[1, :, :] = image_scale * a_np[1, :, :] + green_bias
    b_np[2, :, :] = image_scale * a_np[2, :, :] + red_bias
    b_np = np.add(a_np, b_np)
    inputs = [("input1", datatypes.Array(*input_dim)), ("input2", datatypes.Array(*input_dim))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.set_pre_processing_parameters(
        image_input_names=["input1"],
        is_bgr=True,
        blue_bias=blue_bias,
        green_bias=green_bias,
        red_bias=red_bias,
        image_scale=image_scale,
    )
    # add one add layer to make CoreML model format valid
    # add layer has been tested before.
    builder.add_elementwise(
        name="add", input_names=["input1", "input2"], output_name="output", alpha=0, mode="ADD"
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(
            model, target, ctx, [a_np, a_np], ["input1", "input2"], b_np.shape, dtype
        )
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_image_scaler():
    verify_image_scaler((3, 224, 224), image_scale=0.17)
    verify_image_scaler(
        (3, 224, 224),
        blue_bias=-1.7669800519943237,
        green_bias=-1.985260009765625,
        red_bias=-2.102560043334961,
        image_scale=0.379,
    )

def verify_convolution(input_dim, filter, padding):
    dtype = "float32"
    N, C, H, W = input_dim
    OC, _, KH, KW = filter
    a_np = np.random.uniform(size=input_dim).astype(dtype)
    w_np = np.random.uniform(size=(OC, C, KH, KW)).astype(dtype)
    w_np_cm = np.transpose(w_np, axes=(2, 3, 1, 0))
    b_np = conv2d_nchw_python(a_np, w_np, [1, 1], padding)
    inputs = [("input1", datatypes.Array(C, H, W))]
    output = [("output", datatypes.Array(*b_np.shape))]
    builder = NeuralNetworkBuilder(inputs, output)
    builder.add_convolution(
        name="conv",
        kernel_channels=3,
        output_channels=OC,
        height=KH,
        width=KW,
        stride_height=1,
        stride_width=1,
        border_mode=padding.lower(),
        groups=1,
        W=w_np_cm,
        b=None,
        has_bias=False,
        is_deconv=False,
        input_name="input1",
        output_name="output",
    )
    model = cm.models.MLModel(builder.spec)
    for target, ctx in tvm.testing.enabled_targets():
        out = run_tvm_graph(model, target, ctx, [a_np], ["input1"], output_shape=None)
        tvm.testing.assert_allclose(out, b_np, rtol=1e-5)

@tvm.testing.uses_gpu
def test_forward_convolution():
    verify_convolution((1, 3, 224, 224), filter=(32, 3, 3, 3), padding="VALID")
    verify_convolution((1, 3, 224, 224), filter=(32, 3, 3, 3), padding="SAME")

if __name__ == "__main__":
    test_forward_AddLayerParams()
    test_forward_ConcatLayerParams()
    test_forward_MultiplyLayerParams()
    test_forward_UpsampleLayerParams()
    test_forward_l2_normalize()
    test_forward_lrn()
    test_forward_average()
    test_forward_max()
    test_forward_min()
    test_forward_unary()
    test_forward_reduce()
    test_forward_reshape()
    test_forward_split()
    test_mobilenet_checkonly()
    test_resnet50_checkonly()
    test_forward_image_scaler()
    test_forward_convolution()


text:
FROM ubuntu:20.04

RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
  g++ \
  make \
  ninja-build \
  file \
  curl \
  ca-certificates \
  python3 \
  git \
  cmake \
  sudo \
  gdb \
  libssl-dev \
  pkg-config \
  xz-utils

COPY scripts/sccache.sh /scripts/
RUN sh /scripts/sccache.sh

ENV RUST_CONFIGURE_ARGS \
 --build=aarch64-unknown-linux-gnu \
 --enable-sanitizers \
 --enable-profiler \
 --enable-compiler-docs
ENV SCRIPT python3 ../x.py --stage 2 test


text:
layout: page
title: Rivera - Pace Wedding
date: 2016-05-24
author: Angela Ball
tags: weekly links, java
status: published
summary: Maecenas condimentum eros mauris, et pharetra nisl congue ac.
banner: images/banner/people.jpg
booking:
  startDate: 02/22/2018
  endDate: 02/25/2018
  ctyhocn: DVLNJHX
  groupCode: RPW
published: true
---
Quisque efficitur, tellus et ornare auctor, quam nunc imperdiet dui, nec sagittis velit dolor vel sem. Donec tincidunt nisl a dolor sodales accumsan. Praesent dapibus magna sed ex molestie posuere a vel diam. Vestibulum viverra eros sit amet metus egestas, et pharetra ligula ultrices. Praesent nec sollicitudin nibh, at rhoncus metus. Curabitur volutpat leo convallis, interdum augue sit amet, sollicitudin purus. Duis aliquam finibus justo, quis mollis justo porta ac. Suspendisse ornare vehicula massa non bibendum. Integer dignissim nibh ut nunc tincidunt luctus et a eros. Quisque ac neque commodo, consectetur arcu sollicitudin, vulputate risus. Fusce finibus quam hendrerit condimentum fermentum. Cras mattis sapien eu magna ultricies ultricies. Aliquam sed ex tortor.

* Pellentesque vitae justo eu dui tincidunt euismod
* Aenean tincidunt eros eu orci condimentum pretium
* Nunc ac velit quis arcu vulputate tincidunt a nec metus
* Suspendisse vitae neque consectetur, tincidunt nibh vel, congue dui
* Praesent tempor purus nec iaculis ullamcorper.

Cras congue ipsum vel mi consectetur fringilla. Integer volutpat, tellus eget viverra vulputate, lacus sem porta dui, eget pellentesque leo ligula ut lectus. Suspendisse potenti. Vestibulum aliquet nulla ut rutrum accumsan. Sed et bibendum nibh. Pellentesque magna erat, mollis ultrices iaculis sit amet, sollicitudin egestas dolor. Sed et libero at orci pharetra pellentesque nec vitae est. Nulla sed mi non ante mattis efficitur vel non est. Nulla facilisi. Quisque semper libero et ante semper, vel consequat enim aliquet. Nam iaculis velit quis justo scelerisque, ut finibus odio gravida. Proin erat quam, tincidunt consectetur lectus vitae, vulputate euismod quam. Phasellus hendrerit ipsum quis pellentesque commodo. Donec volutpat, leo eget tristique ultrices, sapien ante gravida purus, a dictum ligula orci sit amet purus. Ut id ligula enim. In imperdiet rutrum porta.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

  <title>Index of /supr/plugins/tiny_mce/plugins/emotions</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Index of /supr/plugins/tiny_mce/plugins/emotions

 Parent Directory

 editor_plugin.js

 editor_plugin_src.js

 emotions.htm

 img/

 js/

 langs/


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/load_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingBottom="10dip"
        android:paddingTop="10dip" >

        <ProgressBar
            style="?android:attr/progressBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="正在加载..."
            android:textColor="#000"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/load_nothing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:visibility="gone"
        android:orientation="horizontal"
        android:paddingBottom="10dip"
        android:paddingTop="10dip" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="亲,已经没有可加载的数据了"
            android:textColor="#000"/>
    </LinearLayout>

</LinearLayout>


text:
module Boson
  module PipeRunner
    PIPE = '+'

    # Splits array into array of arrays with given element
    def self.split_array_by(arr, divider)
      arr.inject([[]]) {|results, element|
        (divider == element) ? (results << []) : (results.last << element)
        results
      }
    end

    def parse_args(args)
      @all_args = PipeRunner.split_array_by(args, PIPE)
      args = @all_args[0]
      super(args).tap do |result|
        @all_args[0] = ([result[0]] + Array(result[2])).compact
      end
    end

    def execute_command(command, args)
      @all_args.inject(nil) do |acc, (cmd,*args)|
        args = translate_args(args, acc)
        super(cmd, args)
      end
    end

    def translate_args(args, piped)
      args.unshift piped if piped
      args
    end

    # Commands to executed, in order given by user
    def commands
      @commands ||= @all_args.map {|e| e[0]}
    end
  end

  if defined? BinRunner
    class BinRunner < BareRunner
      class << self; include PipeRunner; end
    end
  end
end


text:
using System.Xml.Linq;

namespace SpecAid.XmlAid.Infrastructure.Formatters
{
    public class XmlAidAttributeFormatter: IXmlAidFormatter
    {
        public XmlAidView Format(XObject xobject, int currentLevel)
        {
            var attribute = xobject as XAttribute;
            if (attribute != null)
            {
                if (attribute.Name == "xmlns") return null;

                return new XmlAidView()
                           {
                               NodeName = string.Format("+{0}", attribute.Name.LocalName),
                               Value = attribute.Value,
                               Level = currentLevel
                           };

            }
            return null;
        }
    }
}


text:
//
//  WebViewVC.m
//  STTwitterDemoIOS
//
//  Created by Nicolas Seriot on 06/08/14.
//  Copyright (c) 2014 Nicolas Seriot. All rights reserved.
//

#import "WebViewVC.h"

@interface WebViewVC ()

@end

@implementation WebViewVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)cancel:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        //
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


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

#include "chrome/browser/ui/webui/reset_password/reset_password_ui.h"

#include <memory>
#include <utility>

#include "base/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/reset_password/reset_password.mojom.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "components/safe_browsing/content/browser/password_protection/password_protection_service.h"
#include "components/safe_browsing/core/browser/password_protection/metrics_util.h"
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/strings/grit/components_strings.h"
#include "components/url_formatter/url_formatter.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui_data_source.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "ui/base/l10n/l10n_util.h"

using safe_browsing::LoginReputationClientResponse;
using safe_browsing::RequestOutcome;

namespace {

constexpr char kStringTypeUMAName[] = "PasswordProtection.InterstitialString";

// Used for UMA metric logging. Please don't reorder.
// Indicates which type of strings are shown on this page.
enum class StringType {
  GENERIC_NO_ORG_NAME = 0,
  GENERIC_WITH_ORG_NAME = 1,
  WARNING_NO_ORG_NAME = 2,
  WARNING_WITH_ORG_NAME = 3,
  kMaxValue = WARNING_WITH_ORG_NAME,
};

// Implementation of mojom::ResetPasswordHander.
class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler {
 public:
  ResetPasswordHandlerImpl(
      content::WebContents* web_contents,
      mojo::PendingReceiver<mojom::ResetPasswordHandler> receiver)
      : web_contents_(web_contents), receiver_(this, std::move(receiver)) {
    DCHECK(web_contents);
  }

  ResetPasswordHandlerImpl(const ResetPasswordHandlerImpl&) = delete;
  ResetPasswordHandlerImpl& operator=(const ResetPasswordHandlerImpl&) = delete;

  ~ResetPasswordHandlerImpl() override {}

  // mojom::ResetPasswordHandler overrides:
  void HandlePasswordReset() override {
    Profile* profile =
        Profile::FromBrowserContext(web_contents_->GetBrowserContext());
    safe_browsing::ChromePasswordProtectionService* service = safe_browsing::
        ChromePasswordProtectionService::GetPasswordProtectionService(profile);
    if (service) {
      service->OnUserAction(
          web_contents_,
          service->reused_password_account_type_for_last_shown_warning(),
          RequestOutcome::UNKNOWN,
          LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED,
          /*verdict_token=*/"", safe_browsing::WarningUIType::INTERSTITIAL,
          safe_browsing::WarningAction::CHANGE_PASSWORD);
    }
  }

 private:
  raw_ptr<content::WebContents> web_contents_;
  mojo::Receiver<mojom::ResetPasswordHandler> receiver_;
};

// Gets the reused password type from post data, or returns
// PASSWORD_TYPE_UNKNOWN if post data is not available.
PasswordType GetPasswordType(content::WebContents* web_contents) {
  content::NavigationEntry* nav_entry =
      web_contents->GetController().GetPendingEntry();
  if (!nav_entry || !nav_entry->GetHasPostData())
    return PasswordType::PASSWORD_TYPE_UNKNOWN;
  auto& post_data = nav_entry->GetPostData()->elements()->at(0);
  if (post_data.type() == network::DataElement::Tag::kBytes) {
    int post_data_int = -1;
    if (base::StringToInt(
            post_data.As<network::DataElementBytes>().AsStringPiece(),
            &post_data_int)) {
      return static_cast<PasswordType>(post_data_int);
    }
  }

  return PasswordType::PASSWORD_TYPE_UNKNOWN;
}

// Properly format host name based on text direction.
std::u16string GetFormattedHostName(const std::string host_name) {
  std::u16string host = url_formatter::IDNToUnicode(host_name);
  if (base::i18n::IsRTL())
    base::i18n::WrapStringWithLTRFormatting(&host);
  return host;
}

}  // namespace

ResetPasswordUI::ResetPasswordUI(content::WebUI* web_ui)
    : ui::MojoWebUIController(web_ui),
      password_type_(GetPasswordType(web_ui->GetWebContents())) {
  std::unique_ptr<content::WebUIDataSource> html_source(
      content::WebUIDataSource::Create(chrome::kChromeUIResetPasswordHost));
  html_source->DisableTrustedTypesCSP();
  html_source->AddResourcePath("reset_password.js", IDR_RESET_PASSWORD_JS);
  html_source->AddResourcePath("reset_password.mojom-webui.js",
                               IDR_RESET_PASSWORD_MOJOM_WEBUI_JS);
  html_source->SetDefaultResource(IDR_RESET_PASSWORD_HTML);
  html_source->AddLocalizedStrings(PopulateStrings());

  content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
                                html_source.release());
}

WEB_UI_CONTROLLER_TYPE_IMPL(ResetPasswordUI)

ResetPasswordUI::~ResetPasswordUI() {}

void ResetPasswordUI::BindInterface(
    mojo::PendingReceiver<mojom::ResetPasswordHandler> receiver) {
  ui_handler_ = std::make_unique<ResetPasswordHandlerImpl>(
      web_ui()->GetWebContents(), std::move(receiver));
}

base::DictionaryValue ResetPasswordUI::PopulateStrings() const {
  auto* service = safe_browsing::ChromePasswordProtectionService::
      GetPasswordProtectionService(Profile::FromWebUI(web_ui()));
  std::string org_name = service->GetOrganizationName(
      service->reused_password_account_type_for_last_shown_warning());
  bool known_password_type =
      password_type_ != PasswordType::PASSWORD_TYPE_UNKNOWN;

  int heading_string_id = known_password_type
                              ? IDS_RESET_PASSWORD_WARNING_HEADING
                              : IDS_RESET_PASSWORD_HEADING;
  std::u16string explanation_paragraph_string;
  if (org_name.empty()) {
    explanation_paragraph_string = l10n_util::GetStringUTF16(
        known_password_type ? IDS_RESET_PASSWORD_WARNING_EXPLANATION_PARAGRAPH
                            : IDS_RESET_PASSWORD_EXPLANATION_PARAGRAPH);
    UMA_HISTOGRAM_ENUMERATION(kStringTypeUMAName,
                              known_password_type
                                  ? StringType::WARNING_NO_ORG_NAME
                                  : StringType::GENERIC_NO_ORG_NAME);
  } else {
    std::u16string formatted_org_name = GetFormattedHostName(org_name);
    explanation_paragraph_string = l10n_util::GetStringFUTF16(
        known_password_type
            ? IDS_RESET_PASSWORD_WARNING_EXPLANATION_PARAGRAPH_WITH_ORG_NAME
            : IDS_RESET_PASSWORD_EXPLANATION_PARAGRAPH_WITH_ORG_NAME,
        formatted_org_name);
    UMA_HISTOGRAM_ENUMERATION(kStringTypeUMAName,
                              known_password_type
                                  ? StringType::WARNING_WITH_ORG_NAME
                                  : StringType::GENERIC_WITH_ORG_NAME);
  }

  base::DictionaryValue load_time_data;
  load_time_data.SetString("title",
                           l10n_util::GetStringUTF16(IDS_RESET_PASSWORD_TITLE));
  load_time_data.SetString("heading",
                           l10n_util::GetStringUTF16(heading_string_id));
  load_time_data.SetString("primaryParagraph", explanation_paragraph_string);
  load_time_data.SetString("primaryButtonText", l10n_util::GetStringUTF16(
                                                    IDS_RESET_PASSWORD_BUTTON));
  return load_time_data;
}


text:
/*
*  author: amit tank
*  module : network traffic analyzer
*  file : frameparser
*/

#include <stdafx.h>

/************************************************************************

FrameParser.c

				Data Link Frame
						|
						|
						|
						|
		-------------------------------------
		|									|
		|									|
	IEEE Frames 						Ethernet Frame
	(non-ethernet frames)						|
		|										|
		|										|
	RawIPX										|

									IPv4,  ARP, RARP, IPX
									  |
									  |
									  |
							-----------------------------
							|		|			|		|
							TCP	   UDP		  ICMP	  IGMP

*************************************************************************/

INT ParseFrame(PUCHAR CurrentFrame_p, UINT CurrentFrameLength, PCURRENT_FRAME FrameAttributes_p,PCHAR TestingString/*last parameter is temporary*/)
{

INT DataLinkFrameType,NetworkFrameType,TransportFrameType, RawIPXFrameType,TransportProtocolType;
INT uiOffset=0;

TransportProtocolType = RawIPXFrameType = DataLinkFrameType = NetworkFrameType = TransportFrameType = UNKNOWN_FRAMETYPE;

DataLinkFrameType = GetIntFromWord(CurrentFrame_p,DATALINKFRAME_IDENTIFICATION_OFFSET);

	if((DataLinkFrameType > 0) && (DataLinkFrameType < IEEE_FRAME_RANGE))
		{
			RawIPXFrameType = GetIntFromWord(CurrentFrame_p,RAWIPXFRAME_IDENTIFICATION_OFFSET);

			if(RawIPXFrameType == RAWIPX_PROTOCOL_STAMP)
			{
				FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = ETHERNET_FRAME;
				FrameAttributes_p->ProtocolTree.Network_ProtocolID  = NETWORKPROTOCOL_RAWIPX;
			}
			else
				{
					FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = IEEE_FRAME;
					uiOffset = IEEE_DATA_OFFSET;
				}
		}
	else
		{
			FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = ETHERNET_FRAME;
			uiOffset = ETHERNET_DATA_OFFSET;
		}

ParseAtNetworkLayer(CurrentFrame_p,uiOffset,FrameAttributes_p);

//	wsprintf(TestingString,"\r\n IP Header Length		:	 %d",FormTCPPacket(CurrentFrame_p, FrameAttributes_p));
//						lstrcat(TmpString,TmpStr);
//	wsprintf(TestingString,"\r\n Byte : %02x",GetIntFromByte(CurrentFrame_p,0));
	DebugPrintOutput(TestingString,FrameAttributes_p);
	return 0;
}

INT GetIntFromWord(PUCHAR TmpFrame_p, INT Offset)
{
	INT iValue;

	iValue = (INT) (0xff & (INT)*(TmpFrame_p + Offset)); //(BYTE)(TmpFrame_p + Offset);
	iValue = iValue << 8;
	iValue = iValue + ((INT) (0xff & (INT)*(TmpFrame_p + Offset+1)));

	return iValue;
}

INT GetIntFromByte(PUCHAR TmpFrame_p, INT Offset)
{
	INT iValue;

	iValue = (INT) (0x000000ff & (INT)*(TmpFrame_p + Offset)); //(BYTE)(TmpFrame_p + Offset);
//	iValue = iValue << 8;
//	iValue = iValue + ((INT) (0xff & (INT)*(TmpFrame_p + Offset+1)));

	return iValue;
}

VOID DebugPrintOutput(PCHAR TmpString,PCURRENT_FRAME FrameAttributes_p)
{
CHAR TmpStr[256];

IN_ADDR	tmpAdd;

lstrcpy(TmpString,"   Packet Details\r\n");
	if(FrameAttributes_p->ProtocolTree.DataLink_ProtocolID == ETHERNET_FRAME)
	{
		lstrcat(TmpString,"\r\n Data-Link Layer Frame Type     :	 Ethernet Frame");
	}
	else if(FrameAttributes_p->ProtocolTree.DataLink_ProtocolID == IEEE_FRAME)
	{
			lstrcat(TmpString,"\r\n Data-Link Layer Frame Type	:	 IEEE 802.3 Frame");
	}

		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_IPV4)
		{
				lstrcat(TmpString,"\r\n Network Layer Protocol Type    :	 IP Packet");
			if(FrameAttributes_p->ProtocolTree.Transport_ProtocolID != UNKNOWN_FRAMETYPE)
			{

				if(FrameAttributes_p->ProtocolTree.Transport_ProtocolID == TRANSPORTPROTOCOL_TCP)
				{
						lstrcat(TmpString,"\r\n Transport Layer Protocol Type  :	 TCP Protocol");
						//INT FormTCPPacket(CurrentFrame_p, FrameAttributes_p)
//						wsprintf(TmpStr,"\r\n IP Header Length		:	 %d",FormTCPPacket(CurrentFrame_p, FrameAttributes_p));
//						lstrcat(TmpString,TmpStr);
						wsprintf(TmpStr,"\r\n Source Port			:	 %d",FrameAttributes_p->uiSourcePort);
						lstrcat(TmpString,TmpStr);
						wsprintf(TmpStr,"\r\n Destination Port		:	 %d",FrameAttributes_p->uiDestinationPort);
						lstrcat(TmpString,TmpStr);

				}

				if(FrameAttributes_p->ProtocolTree.Transport_ProtocolID == TRANSPORTPROTOCOL_UDP)
				{
						lstrcat(TmpString,"\r\n Transport Layer Protocol Type  :	 UDP Protocol");

						wsprintf(TmpStr,"\r\n Source Port			:	 %d",FrameAttributes_p->uiSourcePort);
						lstrcat(TmpString,TmpStr);
						wsprintf(TmpStr,"\r\n Destination Port		:	 %d",FrameAttributes_p->uiDestinationPort);
						lstrcat(TmpString,TmpStr);

				}

				if(FrameAttributes_p->ProtocolTree.Transport_ProtocolID == TRANSPORTPROTOCOL_ICMP)
						lstrcat(TmpString,"\r\n Transport Layer Protocol Type  :	 ICMP Protocol");

				if(FrameAttributes_p->ProtocolTree.Transport_ProtocolID == TRANSPORTPROTOCOL_IGMP)
						lstrcat(TmpString,"\r\n Transport Layer Protocol Type  :	 IGMP Protocol");

			tmpAdd.S_un.S_addr = FrameAttributes_p->ulSourceAddress;
			wsprintf(TmpStr,"\r\n Source IP Address		:	 %s",inet_ntoa(tmpAdd));
			lstrcat(TmpString,TmpStr);

			tmpAdd.S_un.S_addr = FrameAttributes_p->ulDestinationAddress;
			wsprintf(TmpStr,"\r\n Destination IP Address		:	 %s",inet_ntoa(tmpAdd));
			lstrcat(TmpString,TmpStr);

			}
			else
				lstrcat(TmpString,"\r\n Transport Layer Protocol Type  :   Unknown Type");
		}

		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_ARP)
					lstrcat(TmpString,"\r\n Network Layer Protocol Type    :	 ARP Packet");

		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_RARP)
					lstrcat(TmpString,"\r\n Network Layer Protocol Type    :	 RARP Packet");

		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == IPX_ETHERNET_PROTOCOL_STAMP)
					lstrcat(TmpString,"\r\n Network Layer Protocol Type    :	 IPX Packet");

/*		else
		{
		if(FrameAttributes_p->ProtocolTree.DataLink_ProtocolID == IEEE_FRAME)
			lstrcat(TmpString,"\r\n Data-Link Layer Frame Type  :    Non Ethernet Frame");
		}*/

		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_NETBIOS_NAMEQUERY)
					lstrcat(TmpString,"\r\n Network Layer Protocol Type    :	 NetBIOS Name Query");
		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_NETBIOS_STATUSQUERY)
					lstrcat(TmpString,"\r\n Network Layer Protocol Type    :	 NetBIOS Status Query");
		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_NETBIOS_DATAGRAM)
					lstrcat(TmpString,"\r\n Network Layer Protocol Type    :	 NetBIOS Datagram");

	return;
}

INT GetIPAddressForIPv4(PUCHAR CurrentFrame_p,UINT uiOffset, PCURRENT_FRAME FrameAttributes_p)
{

	PIP_HEADER TmpIPHeader;

	TmpIPHeader = (IP_HEADER *) (CurrentFrame_p + uiOffset);

	FrameAttributes_p->ulSourceAddress = TmpIPHeader->ulSourceIP;
	FrameAttributes_p->ulDestinationAddress = TmpIPHeader->ulDestinationIP;

return 0;
}

INT FormTCPPacket(PUCHAR CurrentFrame_p, UINT uiOffset, PCURRENT_FRAME FrameAttributes_p)
{
	PTCP_HEADER TmpTCPHeader;

	INT IPHeaderLength;

	IPHeaderLength = (0x0000000F & GetIntFromByte(CurrentFrame_p,uiOffset)) * 4;

	TmpTCPHeader = (TCP_HEADER *) (CurrentFrame_p + ETHERNET_DATA_OFFSET + IPHeaderLength);

	FrameAttributes_p->uiDestinationPort = ntohs(TmpTCPHeader->DestinationPortNumber);
	FrameAttributes_p->uiSourcePort = ntohs(TmpTCPHeader->SourcePortNumber);

return 0;
}

INT FormUDPPacket(PUCHAR CurrentFrame_p,UINT uiOffset,PCURRENT_FRAME FrameAttributes_p)
{
	PUDP_HEADER TmpUDPHeader;

	INT IPHeaderLength;

	IPHeaderLength = (0x0000000F & GetIntFromByte(CurrentFrame_p,uiOffset)) * 4;

	TmpUDPHeader = (UDP_HEADER *) (CurrentFrame_p + ETHERNET_DATA_OFFSET + IPHeaderLength);

	FrameAttributes_p->uiDestinationPort = ntohs(TmpUDPHeader->DestinationPortNumber);
	FrameAttributes_p->uiSourcePort = ntohs(TmpUDPHeader->SourcePortNumber);

return 0;
}

INT ExtractPacketContents(PUCHAR CurrentFrame_p, PCURRENT_FRAME FrameAttributes_p)
{

	return 0;
}

/********************

*********************/

INT ParseAtNetworkLayer(PUCHAR CurrentFrame_p, UINT uiOffset, PCURRENT_FRAME FrameAttributes_p)
{

INT NetworkProtocolType;

if(FrameAttributes_p->ProtocolTree.DataLink_ProtocolID == ETHERNET_FRAME)
{
	NetworkProtocolType = GetIntFromWord(CurrentFrame_p,ETHERNET_NETWORKPROTOCOL_IDENTIFICATION_OFFSET);
}
	else if(FrameAttributes_p->ProtocolTree.DataLink_ProtocolID == IEEE_FRAME)
	{
		NetworkProtocolType = GetIntFromByte(CurrentFrame_p,IEEE_NETWORKPROTOCOL_IDENTIFICATION_OFFSET+1);	//test

			if(NetworkProtocolType = NETBIOS_NAMEQUERY_STAMP)
				{
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_NETBIOS_NAMEQUERY;
				}
			else if(NetworkProtocolType = NETBIOS_STATUSQUERY_STAMP)
				{
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_NETBIOS_STATUSQUERY;
				}
			else if(NetworkProtocolType = NETBIOS_DATAGRAM_STAMP)
				{
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_NETBIOS_DATAGRAM;
				}

	}

			if(NetworkProtocolType == IPV4_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_IPV4;
					ParseAtTransportLayer(CurrentFrame_p,uiOffset,FrameAttributes_p);
				}

			if(NetworkProtocolType == ARP_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_ARP;
				}

			if(NetworkProtocolType == RARP_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_RARP;
				}

			if(NetworkProtocolType == IPX_ETHERNET_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_IPX_ETHERNET;
				}

return 0;
}

INT ParseAtTransportLayer(PUCHAR CurrentFrame_p, UINT uiOffset, PCURRENT_FRAME FrameAttributes_p)
{
INT TransportProtocolType;

		TransportProtocolType = GetIntFromByte(CurrentFrame_p,uiOffset+TRANSPORT_PROTOCOL_IDENTIFICATION_OFFSET);

		if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_IPV4)
		{
				GetIPAddressForIPv4(CurrentFrame_p,uiOffset,FrameAttributes_p);

				if(TransportProtocolType == TCP_PROTOCOL_STAMP)
					{
						FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_TCP;
						FormTCPPacket(CurrentFrame_p,uiOffset,FrameAttributes_p);
					}

				if(TransportProtocolType == UDP_PROTOCOL_STAMP)
					{
						FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_UDP;
						FormUDPPacket(CurrentFrame_p,uiOffset,FrameAttributes_p);

					}

				if(TransportProtocolType == ICMP_PROTOCOL_STAMP)
					{
						FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_ICMP;
					}

				if(TransportProtocolType == IGMP_PROTOCOL_STAMP)
					{
						FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_IGMP;
					}

		}

return 0;
}

/**********************************
INT ParseFrame(PUCHAR CurrentFrame_p, UINT CurrentFrameLength, PCURRENT_FRAME FrameAttributes_p,PCHAR TestingString )
{

INT DataLinkFrameType,NetworkFrameType,TransportFrameType, RawIPXFrameType,TransportProtocolType;

TransportProtocolType = RawIPXFrameType = DataLinkFrameType = NetworkFrameType = TransportFrameType = UNKNOWN_FRAMETYPE;

DataLinkFrameType = GetIntFromWord(CurrentFrame_p,DATALINKFRAME_IDENTIFICATION_OFFSET);

	if((DataLinkFrameType > 0) && (DataLinkFrameType < IEEE_FRAME_RANGE))
		{
			RawIPXFrameType = GetIntFromWord(CurrentFrame_p,RAWIPXFRAME_IDENTIFICATION_OFFSET);

			if(RawIPXFrameType == RAWIPX_PROTOCOL_STAMP)
			{
				FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = ETHERNET_FRAME;
				FrameAttributes_p->ProtocolTree.Network_ProtocolID  = NETWORKPROTOCOL_RAWIPX;
			}
			else
				{
					FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = IEEE_FRAME;
				}
		}
	else
		{

			if(DataLinkFrameType == IPV4_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = ETHERNET_FRAME;
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_IPV4;
				}

			if(DataLinkFrameType == ARP_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = ETHERNET_FRAME;
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_ARP;
				}

			if(DataLinkFrameType == RARP_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = ETHERNET_FRAME;
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_RARP;
				}
//IPX_ETHERNET_PROTOCOL_STAMP
			if(DataLinkFrameType == IPX_ETHERNET_PROTOCOL_STAMP)
				{
					FrameAttributes_p->ProtocolTree.DataLink_ProtocolID = ETHERNET_FRAME;
					FrameAttributes_p->ProtocolTree.Network_ProtocolID = NETWORKPROTOCOL_IPX_ETHERNET;
				}
//
		}

	if(FrameAttributes_p->ProtocolTree.Network_ProtocolID == NETWORKPROTOCOL_IPV4)
	{
		TransportProtocolType = GetIntFromByte(CurrentFrame_p,ETHERNET_DATA_OFFSET+TRANSPORT_PROTOCOL_IDENTIFICATION_OFFSET);

		GetIPAddressForIPv4(CurrentFrame_p,FrameAttributes_p);

		if(TransportProtocolType == TCP_PROTOCOL_STAMP)
			{
				FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_TCP;
				FormTCPPacket(CurrentFrame_p,FrameAttributes_p);
			}

		if(TransportProtocolType == UDP_PROTOCOL_STAMP)
			{
				FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_UDP;
				FormUDPPacket(CurrentFrame_p,FrameAttributes_p);

			}

		if(TransportProtocolType == ICMP_PROTOCOL_STAMP)
			{
				FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_ICMP;
			}

		if(TransportProtocolType == IGMP_PROTOCOL_STAMP)
			{
				FrameAttributes_p->ProtocolTree.Transport_ProtocolID = TRANSPORTPROTOCOL_IGMP;
			}

	}

//	wsprintf(TestingString,"\r\n IP Header Length		:	 %d",FormTCPPacket(CurrentFrame_p, FrameAttributes_p));
//						lstrcat(TmpString,TmpStr);
//	wsprintf(TestingString,"\r\n Byte : %02x",GetIntFromByte(CurrentFrame_p,0));
	DebugPrintOutput(TestingString,FrameAttributes_p);
	return 0;
}
***********************************/


text:
package com.salesforce.phoenix.end2end.index;

import static com.salesforce.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.common.collect.Maps;
import com.salesforce.phoenix.jdbc.PhoenixConnection;
import com.salesforce.phoenix.query.ConnectionQueryServices;
import com.salesforce.phoenix.schema.PIndexState;
import com.salesforce.phoenix.schema.PTableType;
import com.salesforce.phoenix.util.ReadOnlyProps;
import com.salesforce.phoenix.util.StringUtil;

/**
 *
 * Test for failure of region server to write to index table. Keep in its own
 * separate test, as otherwise it makes tests run after it fail.
 *
 * @author jtaylor
 * @since 2.1
 */
public class MutableIndexFailureTest extends BaseMutableIndexTest {
    @BeforeClass
    public static void doSetup() throws Exception {
        Map<String,String> props = Maps.newHashMapWithExpectedSize(1);
        props.put("hbase.client.retries.number", Integer.toString(2));
        props.put("hbase.client.pause", Integer.toString(5000));
        // Must update config before starting server
        startServer(getUrl(), new ReadOnlyProps(props.entrySet().iterator()));
    }

    private static void destroyIndexTable() throws Exception {
        Properties props = new Properties(TEST_PROPERTIES);
        ConnectionQueryServices services = DriverManager.getConnection(getUrl(), props).unwrap(PhoenixConnection.class).getQueryServices();
        HBaseAdmin admin = services.getAdmin();
        try {
            admin.disableTable(INDEX_TABLE_FULL_NAME);
            admin.deleteTable(INDEX_TABLE_FULL_NAME);
        } catch (TableNotFoundException e) {
        } finally {
            admin.close();
        }
    }

    @Test
    public void testWriteFailureDisablesIndex() throws Exception {
        String query;
        ResultSet rs;

        Properties props = new Properties(TEST_PROPERTIES);
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.setAutoCommit(false);
        conn.createStatement().execute("CREATE TABLE " + DATA_TABLE_FULL_NAME + " (k VARCHAR NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)");
        query = "SELECT * FROM " + DATA_TABLE_FULL_NAME;
        rs = conn.createStatement().executeQuery(query);
        assertFalse(rs.next());

        conn.createStatement().execute("CREATE INDEX " + INDEX_TABLE_NAME + " ON " + DATA_TABLE_FULL_NAME + " (v1) INCLUDE (v2)");
        query = "SELECT * FROM " + INDEX_TABLE_FULL_NAME;
        rs = conn.createStatement().executeQuery(query);
        assertFalse(rs.next());

        // Verify the metadata for index is correct.
        rs = conn.getMetaData().getTables(null, StringUtil.escapeLike(SCHEMA_NAME), INDEX_TABLE_NAME, new String[] {PTableType.INDEX.toString()});
        assertTrue(rs.next());
        assertEquals(INDEX_TABLE_NAME, rs.getString(3));
        assertEquals(PIndexState.ACTIVE.toString(), rs.getString("INDEX_STATE"));
        assertFalse(rs.next());

        destroyIndexTable();

        PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + DATA_TABLE_FULL_NAME + " VALUES(?,?,?)");
        stmt.setString(1,"a");
        stmt.setString(2, "x");
        stmt.setString(3, "1");
        stmt.execute();
        try {
            conn.commit();
            fail();
        } catch (SQLException e) {
        }

        // Verify the metadata for index is correct.
        rs = conn.getMetaData().getTables(null, StringUtil.escapeLike(SCHEMA_NAME), INDEX_TABLE_NAME, new String[] {PTableType.INDEX.toString()});
        assertTrue(rs.next());
        assertEquals(INDEX_TABLE_NAME, rs.getString(3));
        assertEquals(PIndexState.DISABLE.toString(), rs.getString("INDEX_STATE"));
        assertFalse(rs.next());
    }
}


text:
[![npm version](https://badge.fury.io/js/ember-themed-syntax.svg)](https://badge.fury.io/js/ember-themed-syntax)
[![Build Status](https://travis-ci.org/crodriguez1a/ember-themed-syntax.svg?branch=master)](https://travis-ci.org/crodriguez1a/ember-themed-syntax)
[![Ember Observer Score](http://emberobserver.com/badges/ember-themed-syntax.svg)](https://emberobserver.com/addons/ember-themed-syntax)

# ember-themed-syntax

An out-of-the-box solution for syntax highlighting with a couple of themes included

## Installation

```bash
ember install ember-themed-syntax
```

## Languages

List of [supported highlight.js languages](https://github.com/isagalaev/highlight.js/tree/9.10.0/src/languages)

## Demo and Documentation

http://crodriguez1a.github.io/ember-themed-syntax/

## Usage

The following params are accepted

  - `lang`: *default **html*** - The coding language inside the block
  - `theme`: *default **light*** - Your theme selection
  - `transparent`: *default **false*** - When set to true, a background color will not be applied
  - `withBuffers`: *default **true*** - Adds a line break to beginning and end of each block
  - `code`: *default **''*** - Use instead of template block parameter to bind code input

Template

```handlebars
  {{#themed-syntax lang="htmlbars" theme="dark"}}
    {{! Some code }}
  {{/themed-syntax}}
```

The default theme is set to light

```handlebars
	{{#themed-syntax lang="htmlbars"}}
  	  {{! Some code }}
	{{/themed-syntax}}
```


text:
<?php

declare(strict_types=1);

namespace Genkgo\Camt\Camt053\Decoder;

use Genkgo\Camt\Camt053\DTO as Camt053DTO;
use Genkgo\Camt\Decoder\Message as BaseMessageDecoder;
use Genkgo\Camt\DTO;
use Genkgo\Camt\Iban;
use SimpleXMLElement;

class Message extends BaseMessageDecoder
{
    public function addRecords(DTO\Message $message, SimpleXMLElement $document): void
    {
        $statements = [];

        $xmlStatements = $this->getRootElement($document)->Stmt;
        foreach ($xmlStatements as $xmlStatement) {
            $statement = new Camt053DTO\Statement(
                (string) $xmlStatement->Id,
                $this->dateDecoder->decode((string) $xmlStatement->CreDtTm),
                $this->getAccount($xmlStatement)
            );

            if (isset($xmlStatement->StmtPgntn)) {
                $statement->setPagination(new DTO\Pagination(
                    (string) $xmlStatement->StmtPgntn->PgNb,
                    ('true' === (string) $xmlStatement->StmtPgntn->LastPgInd) ? true : false
                ));
            }

            if (isset($xmlStatement->AddtlStmtInf)) {
                $statement->setAdditionalInformation((string) $xmlStatement->AddtlStmtInf);
            }

            $this->addCommonRecordInformation($statement, $xmlStatement);
            $this->recordDecoder->addBalances($statement, $xmlStatement);
            $this->recordDecoder->addEntries($statement, $xmlStatement);

            $statements[] = $statement;
        }

        $message->setRecords($statements);
    }

    /**
     * @inheritDoc
     */
    public function getRootElement(SimpleXMLElement $document): SimpleXMLElement
    {
        return $document->BkToCstmrStmt;
    }

    protected function getAccount(SimpleXMLElement $xmlRecord): DTO\Account
    {
        if (isset($xmlRecord->Acct->Id->IBAN)) {
            return new DTO\IbanAccount(new Iban((string) $xmlRecord->Acct->Id->IBAN));
        }

        $xmlOtherIdentification = $xmlRecord->Acct->Id->Othr;
        $otherAccount = new DTO\OtherAccount((string) $xmlOtherIdentification->Id);

        if (isset($xmlOtherIdentification->SchmeNm)) {
            if (isset($xmlOtherIdentification->SchmeNm->Cd)) {
                $otherAccount->setSchemeName((string) $xmlOtherIdentification->SchmeNm->Cd);
            }

            if (isset($xmlOtherIdentification->SchmeNm->Prtry)) {
                $otherAccount->setSchemeName((string) $xmlOtherIdentification->SchmeNm->Prtry);
            }
        }

        if (isset($xmlOtherIdentification->Issr)) {
            $otherAccount->setIssuer((string) $xmlOtherIdentification->Issr);
        }

        return $otherAccount;
    }
}


text:
var describe = require('Jody').describe;
var assert = require("assert");

describe("Test 1").it("Should pass",function () {
  assert.equal(1,1);
});

describe("Test 2").
  it("Should fail",function () {
  assert.equal(1,2);
}).
  afterAll(function (done) {
    console.log("Woohoo");
    done();
  });

var value = 0;
describe("Before Test").beforeEach (function (done) {
  value = 2;
  done();
}).it ("Should run before to pass", function () {
  console.log("before test test");
  assert.equal(value,2);
});

describe("Multiple tests in context").
it("First in context", function () {
  assert.equal(2,2);
}).
it("Second in context", function () {
  assert.equal(2,2);
});

describe("Matchers and should").
it("Should be able to use should to assert a passing test", function () {
  var testString = "hello";
  testString.should().beEqual("hello");

}).
it("Should assert failing test", function () {
  var testObj = function () { };
  testObj.voice = "blah";

  testObj.voice.should().beEqual("hello");

});

describe("Exception").
it("Should throw exception", function () {
  (function () {
    throw { message: "My exception" }
  }).should().throwError();
}).
it("Should fail as no exception thrown", function () {
  (function () {
  }).should().throwError();
})

describe("Array matchers").
  it("Should check for containing item", function () {
    var test = [1,2,3,4];

    test.should().contain(3);
  }).
  it("Should fail as item not in array", function () {
    var test = [1,2,4];

    test.should().contain(3);
  });

var beforeAllCounter = 0;

describe("Before All").
  beforeAll(function (done) {
    beforeAllCounter += 1;
    done();
  }).
  it("One before all ", function () {
    beforeAllCounter.should().beEqual(1);
  }).
  it("One before all ", function () {
    beforeAllCounter.should().beEqual(1);
  })

describe("After All").
  it("Should reset variable after all finished", function (async) {
    setTimeout(async(function () {
      console.log("timeout");
    }), 200);
  }).
  afterAll(function (done) {
    console.log("after all called");
    done();
  });


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

using System;

namespace DeltaDNA {

    using JSONObject = System.Collections.Generic.Dictionary<string, object>;

    public class Engagement<T> where T : Engagement<T> {

        private readonly Params parameters;
        private string response = null;

        /// <summary>
        /// Creates a new Engagement with a decision point.
        /// </summary>
        /// <param name="decisionPoint">The Decision Point.</param>
        public Engagement(string decisionPoint)
        {
            if (String.IsNullOrEmpty(decisionPoint)) {
                throw new ArgumentException("decisionPoint cannot be null or empty");
            }

            this.DecisionPoint = decisionPoint;
            this.Flavour = "engagement";
            this.parameters = new Params();
        }

        /// <summary>
        /// Gets the decision point.
        /// </summary>
        /// <value>The decision point for this Engagement.</value>
        public string DecisionPoint { get; private set; }

        /// <summary>
        /// Gets the flavour.
        /// </summary>
        /// <value>The flavour of this Engagement.</value>
        public string Flavour { get; private set; }

        /// <summary>
        /// Add a parameter to the engage request.
        /// </summary>
        public T AddParam(string key, object value)
        {
            this.parameters.AddParam(key, value);
            return (T) this;
        }

        /// <summary>
        /// The Engagement as a JSON dictionary.
        /// </summary>
        /// <returns>The dictionary.</returns>
        public JSONObject AsDictionary()
        {
            return new JSONObject() {
                { "decisionPoint", DecisionPoint },
                { "flavour", Flavour },
                { "parameters", new JSONObject(parameters.AsDictionary()) }
            };
        }

        /// <summary>
        /// The Raw response from the Engage service.  A successful engagement will be a json string, else the error that occurred.
        /// </summary>
        /// <value>The raw response from Engage.</value>
        public string Raw {
            get { return this.response; }
            set {
                JSONObject json = null;
                if (!String.IsNullOrEmpty(value)) {
                    try {
                        json = DeltaDNA.MiniJSON.Json.Deserialize(value) as JSONObject;
                    } catch (Exception) {
                        // not valid json
                    }
                }
                this.response = value;
                this.JSON = json ?? new JSONObject();
            }
        }

        /// <summary>
        /// The HTTP status code from the engage service.
        /// </summary>
        /// <value>The status code.</value>
        public int StatusCode { get; set; }

        /// <summary>
        /// Records any error that may have occurred.
        /// </summary>
        /// <value>The error.</value>
        public string Error { get; set; }

        /// <summary>
        /// The JSON response for the Engagement.  Will be empty if the engagement was unsuccessful,
        /// or marked with 'isCachedResponse=true' key if the cache was used.
        /// </summary>
        /// <value>The response from Engage as JSON.</value>
        public JSONObject JSON { get; private set; }

        public override string ToString ()
        {
            return string.Format ("[Engagement: DecisionPoint={0}, Flavour={1}, Raw={2}, StatusCode={3}, Error={4}, JSON={5}]",
                DecisionPoint, Flavour, Raw, StatusCode, Error, JSON);
        }
    }

    /// <summary>
    /// Creates an Engagement to make a request to engage.  If you want to extend the behaviour
    /// use <see cref="Engagement{T}"/> so chaining works correctly.
    /// </summary>
    public class Engagement : Engagement<Engagement>
    {
        public Engagement(string decisionPoint) : base(decisionPoint) {}
    };

} // namespace DeltaDNA


text:
@interface WJYPublishView : UIView

+ (instancetype) publishView;

@end


text:
<?php

namespace eig\APIAuth\Tests;

use eig\APIAuth\Facades\ClientRegistrar;
use eig\Configurator\Configurator;
use eig\Configurator\Options as ConfigOptions;
use Lcobucci\JWT\Parser;
use PasswordLib\PasswordLib;
use eig\APIAuth\Facades\JWT;
use Mockery;

class ClientRegistrarFacadeTest extends TestAbstract
{
    protected $clientPersistence;

    protected $sessionPersistence;

    protected $tokenGenerator;

    protected $library;

    protected $fingerprint;

    protected $jwtPersistence;

    /**
     * @var
     */
    protected $type;

    protected $configFiles = [
        [
            'source' => 'APIAuth.php',
            'path' => 'src/config/',
            'pathType' => 'relative',
            'type' => 'array',
            'alias' => 'APIAuth'
        ]
    ];

    protected $configOptions;

    protected $config;

    public function setUp ()
    {
        $this->configOptions = new ConfigOptions();
        $this->configOptions->basePath = realpath('src/config');
        $this->config = new Configurator($this->configFiles, $this->configOptions);
        $this->fingerprint = md5('this is the clients guid');
        $this->type = 'Android';
        $this->library = new PasswordLib();
        $this->clientPersistence = Mockery::mock('eig\APIAuth\Contracts\ClientPersistenceInterface');
        $this->sessionPersistence = Mockery::mock('eig\APIAuth\Contracts\SessionPersistenceInterface');
        $this->jwtPersistence = Mockery::mock('eig\APIAuth\Abstracts\AbstractJWTPersistence');
        $this->jwtPersistence->shouldReceive('issued');
        $this->jwtPersistence->shouldReceive('expiration');
        $this->jwtPersistence->shouldReceive('notBefore');
        $this->jwtPersistence->shouldReceive('token');
        $this->jwtPersistence->shouldReceive('save');
        JWT::initialize($this->config, $this->jwtPersistence);

        parent::setUp();
    }

    public function tearDown ()
    {
        \Mockery::close();
        parent::tearDown();
    }

    public function testRegister() {
        $ctoken = $this->library->createPasswordHash($this->fingerprint . $this->type, '$2a$', array('cost' => 10));
        $this->jwtPersistence->shouldReceive('create');
        $this->jwtPersistence->shouldReceive('id')->andReturn('123456543');
        $this->clientPersistence->shouldReceive('fingerprint')->andReturn(true);
        $this->clientPersistence->shouldReceive('exists')->andReturn(false);
        $this->clientPersistence->shouldReceive('type');
        $this->clientPersistence->shouldReceive('create');
        $this->clientPersistence->shouldReceive('token')->andReturn($ctoken);
        $this->clientPersistence->shouldReceive('save')->andReturn(true);
        $this->sessionPersistence->shouldReceive('client')->andReturn(true);
        $this->sessionPersistence->shouldReceive('setRevoked');
        $this->sessionPersistence->shouldReceive('create');
        $this->sessionPersistence->shouldReceive('timeout');
        $this->sessionPersistence->shouldReceive('exists')->andReturn(false);
        $this->sessionPersistence->shouldReceive('token')->andReturn(
            $this->library->createPasswordHash($ctoken . $this->fingerprint, '$2a$', array('cost' => 10))
        );
        $this->sessionPersistence->shouldReceive('save')->andReturn(true);

        ClientRegistrar::initialize($this->clientPersistence, $this->sessionPersistence, null, $this->jwtPersistence);
        $data = ClientRegistrar::register($this->fingerprint, $this->type);
        $data = (new Parser())->parse((string) $data);
        //$data->getHeaders();
        //$data->getClaims();
        $registrarData = (array)json_decode($data->getClaim('data'));
        //print_r($registrarData);
        $clientToken = $registrarData['ClientToken'];
        $sessionToken = $registrarData['SessionToken'];
        $this->assertTrue($this->library->verifyPasswordHash($this->fingerprint . $this->type, $clientToken));
        $this->assertTrue($this->library->verifyPasswordHash($ctoken . $this->fingerprint, $sessionToken));
    }
}


text:
/**
 * An utility class to store a projection of an edge on an axis, used by the
 * intersects operation
 *
 * @author Johan
 */
public class Projection {

    private double min;
    private double max;

    public Projection(double min, double max) {
        this.min = min;
        this.max = max;
    }

    public Boolean overlap(Projection p2) {
        return !(this.min > p2.max || p2.min > this.max);
    }
}


text:
set -e

yum groupinstall -y 'Development Tools'

for arg
do
	cpanm --installdeps --with-recommends "$arg"
done


text:
require "test_helper"

class Folio::Console::MergesControllerTest < Folio::Console::BaseControllerTest
  test "new" do
    original = create(:folio_page)
    duplicate = create(:folio_page)

    get new_console_merge_path("Folio::Page", original, duplicate)

    assert_select ".f-c-merges-form__form"
    assert_select ".f-c-merges-form__invalid", false
  end

  test "new - invalid" do
    original = create(:folio_page)
    duplicate = create(:folio_page)
    original.update_column(:title, nil)
    assert_not(original.valid?)

    get new_console_merge_path("Folio::Page", original, duplicate)

    assert_select ".f-c-merges-form__form", false
    assert_select ".f-c-merges-form__invalid"
  end

  test "create" do
    original = create(:folio_page, title: "foo")
    duplicate = create(:folio_page, title: "bar")

    post console_merge_path("Folio::Page", original, duplicate), params: {
      merge: {
        title: Folio::Merger::DUPLICATE,
      }
    }
    assert_redirected_to url_for([:edit, :console, original])

    assert_equal("bar", original.reload.title)
    assert_not(Folio::Page.exists?(id: duplicate.id))
  end

  test "redirects to given url on success" do
    original = create(:folio_page, title: "foo")
    duplicate = create(:folio_page, title: "bar")

    url = "/foo/bar/baz"
    post console_merge_path("Folio::Page", original, duplicate, url:), params: {
      merge: {
        title: Folio::Merger::DUPLICATE,
      }
    }
    assert_redirected_to url
  end

  test "original == duplicate" do
    original = create(:folio_page, title: "foo")

    url = "/foo/bar/baz"
    get new_console_merge_path("Folio::Page", original, original, url:)
    assert_redirected_to console_pages_path
  end
end


text:
import rollupBabel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import json from 'rollup-plugin-json';
import uglify from 'rollup-plugin-uglify';
import replace from 'rollup-plugin-replace';
import filesize from 'rollup-plugin-filesize';

const input = 'src/qPool.js';

const name = 'queue-pool';

const minify = process.env.MINIFY;
const format = process.env.FORMAT;

const es = format === 'es';
const umd = format === 'umd';
const cjs = format === 'cjs';

let output;

const fnPath = 'dist/qPool';

if (es) {
  output = [{
    file: `${fnPath}.es.js`,
    format: 'es',
  }];
} else if (umd) {
  if (minify) {
    output = [{
      file: `${fnPath}.umd.min.js`,
      format: 'umd',
      sourcemap: true,
    }];
  } else {
    output = [{
      file: `${fnPath}.umd.js`,
      format: 'umd',
      sourcemap: true,
    }];
  }
} else if (cjs) {
  output = [{
    file: `${fnPath}.cjs.js`,
    format: 'cjs',
  }];
} else if (format) {
  throw new Error(`invalid format specified: "${format}".`);
} else {
  throw new Error('no format specified. --environment FORMAT:xxx');
}

export default {
  input,
  output,
  name,
  plugins: [
    umd ? replace({ 'process.env.NODE_ENV': JSON.stringify(minify ? 'production' : 'development') }) : null,
    resolve({
      jsnext: true,
      main: true,
    }),
    commonjs(),
    json(),
    rollupBabel({
      exclude: 'node_modules/**',
      babelrc: false,
      presets: [
        ['env', {
          modules: false,
        }],
        ['stage-2'],
      ],
      plugins: ['external-helpers'],
      comments: false,
    }),
    minify ? uglify() : null,
    filesize(),
  ].filter(Boolean),
};