text:
package org.jimmutable.core.fields;

import java.util.HashMap;
import java.util.Map;

/**
 * An implementation of a {@link HashMap} that begins life as mutable but can,
 * at any time, be "{@link #freeze() frozen}" (made immutable). In other
 * words, a wrapper for a {@link HashMap} that implements {@link Field}.
 *
 *
Note: {@link HashMap}, and consequently {@code FieldHashMap} is
 * not thread safe. This is generally not a concern once "{@link #freeze() frozen}"
 * but if the construction process is multi-threaded, consider
 * {@link FieldConcurrentHashMap}.
 *
 *
In the standard case (construction in one thread), {@code FieldHashMap} will
 * work well.
 *
 * @author Jim Kane
 *
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 *
 * @see FieldMap
 * @see FieldConcurrentHashMap
 */
final public class FieldHashMap<K,V> extends FieldMap<K,V>
{
	/**
	 * Default constructor (for an empty map)
	 */
	public FieldHashMap()
	{
		super();
	}

	/**
     * Constructs a collection containing the elements of the specified {@link Map},
     * in the order they are returned by the {@link Iterable#iterator() iterator}.
     *
     * @param initial_values The {@code Map} whose elements are to be placed into this map
     *
     * @throws NullPointerException if the specified {@code Map} is {@code null}
	 */
	public FieldHashMap(Map<K,V> initial_values)
	{
		super(initial_values);
	}

	@Override
	protected Map<K, V> createNewMutableInstance()
	{
		return new HashMap<>();
	}
}


text:
from unittest import main, TestCase
from flask.ext.webtest import TestApp
import json
from api import app

class MyTests(TestCase):

    def setUp(self):
        self.app = app
        self.w = TestApp(self.app)

    def test_base_url_returns_response(self):
        r = self.w.get('/')
        self.assertFalse(r.flashes)

redpajama_set_name: RedPajamaGithub


text:
#import "RCTSourceCode.h"

#import "RCTAssert.h"
#import "RCTBridge.h"
#import "RCTUtils.h"

@implementation RCTSourceCode

RCT_EXPORT_MODULE()

@synthesize bridge = _bridge;

RCT_EXPORT_METHOD(getScriptText:(RCTResponseSenderBlock)successCallback
                  failureCallback:(RCTResponseErrorBlock)failureCallback)
{
  if (self.scriptText && self.scriptURL) {
    successCallback(@[@{@"text": self.scriptText, @"url": self.scriptURL.absoluteString}]);
  } else {
    failureCallback(RCTErrorWithMessage(@"Source code is not available"));
  }
}

- (NSDictionary *)constantsToExport
{
  NSString *URL = self.bridge.bundleURL.absoluteString ?: @"";
  return @{@"scriptURL": URL};
}

@end


text:
package ch.ninecode.np

import ch.ninecode.util.CIMReaderOptionsParser
import ch.ninecode.util.MainOptionsParser
import ch.ninecode.util.SparkOptionsParser

/**
 * Generic parser for command line operation.
 */
@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements"))
class NetworkParametersOptionsParser (options: NetworkParametersOptions)
    extends MainOptionsParser[NetworkParametersOptions](options)
    with SparkOptionsParser[NetworkParametersOptions]
    with CIMReaderOptionsParser[NetworkParametersOptions]
{
    opt[Unit]("verbose")
        .action((_, c) => c.copy(verbose = true))
        .text(s"emit progress messages [${options.verbose}]")

    opt[String]("export")
        .valueName("<RDF file>")
        .action((x, c) => c.copy(export = x))
        .text(s"save processed RDF file as this name [${options.export}]")

    note("Creates EquivalentInjection objects for the network that is supplying transformers using an external data file.\n")
}


text:
define([
    "hr/hr",
    "hr/promise"
], function(hr, Q) {
    hr.Resources.addNamespace("templates", {
        loader: "text"
    });

    hr.Resources.addNamespace("i18n", {
        loader: "require",
        base: "resources/langs/",
        extension: ".json"
    });

    return function() {
        return Q();
    };
});


text:
package org.apache.camel.component.crypto;

import java.net.MalformedURLException;
import java.net.URI;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.util.ObjectHelper;

/**
 * DigitalSignatureComponent
 */
@SuppressWarnings("unchecked")
public class DigitalSignatureComponent extends DefaultComponent {

    private DigitalSignatureConfiguration configuration;

    public DigitalSignatureComponent() {
    }

    public DigitalSignatureComponent(CamelContext context) {
        super(context);
    }

    protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception {
        ObjectHelper.notNull(getCamelContext(), "CamelContext");

        DigitalSignatureConfiguration config = getConfiguration().copy();
        setProperties(config, parameters);
        config.setCamelContext(getCamelContext());
        try {
            config.setCryptoOperation(new URI(remaining).getScheme());
        } catch (Exception e) {
            throw new MalformedURLException(String.format("An invalid crypto uri was provided '%s'."
                    + " Check the uri matches the format crypto:sign or crypto:verify", uri));
        }
        return new DigitalSignatureEndpoint(uri, this, config);
    }

    public DigitalSignatureConfiguration getConfiguration() {
        if (configuration == null) {
            configuration = new DigitalSignatureConfiguration();
        }
        return configuration;
    }

    public void setConfiguration(DigitalSignatureConfiguration configuration) {
        this.configuration = configuration;
    }
}


text:
import React from 'react';
import { Box } from 'ink';
import { Style } from '../Style';

export interface DividerRowProps {
	label: NonNullable<React.ReactNode>;
}

export function DividerRow({ label }: DividerRowProps) {
	return (
		<Box marginLeft={2}>
			<Style type="muted">{label || '────'}</Style>
		</Box>
	);
}


text:
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

import React from 'react';
import classNames from 'classnames';
import warning from 'warning';
import withStyles from '../styles/withStyles';

const TRANSITION_DURATION = 4; // 400ms

export const styles = theme => ({
  root: {
    position: 'relative',
    overflow: 'hidden',
    height: 5
  },
  primaryColor: {
    backgroundColor: theme.palette.primary[100]
  },
  primaryColorBar: {
    backgroundColor: theme.palette.primary[500]
  },
  primaryDashed: {
    background: `radial-gradient(${theme.palette.primary[100]} 0%, ${theme.palette.primary[100]} 16%, transparent 42%)`,
    backgroundSize: '10px 10px',
    backgroundPosition: '0px -23px'
  },
  accentColor: {
    backgroundColor: theme.palette.secondary.A100
  },
  accentColorBar: {
    backgroundColor: theme.palette.secondary.A400
  },
  accentDashed: {
    background: `radial-gradient(${theme.palette.secondary.A100} 0%, ${theme.palette.secondary.A100} 16%, transparent 42%)`,
    backgroundSize: '10px 10px',
    backgroundPosition: '0px -23px'
  },
  bar: {
    width: '100%',
    position: 'absolute',
    left: 0,
    bottom: 0,
    top: 0,
    transition: 'transform 0.2s linear',
    transformOrigin: 'left'
  },
  dashed: {
    position: 'absolute',
    marginTop: 0,
    height: '100%',
    width: '100%',
    animation: 'buffer 3s infinite linear'
  },
  bufferBar2: {
    transition: `transform .${TRANSITION_DURATION}s linear`
  },
  rootBuffer: {
    backgroundColor: 'transparent'
  },
  rootQuery: {
    transform: 'rotate(180deg)'
  },
  indeterminateBar1: {
    width: 'auto',
    willChange: 'left, right',
    animation: 'mui-indeterminate1 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite'
  },
  indeterminateBar2: {
    width: 'auto',
    willChange: 'left, right',
    animation: 'mui-indeterminate2 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite',
    animationDelay: '1.15s'
  },
  determinateBar1: {
    willChange: 'transform',
    transition: `transform .${TRANSITION_DURATION}s linear`
  },
  bufferBar1: {
    zIndex: 1,
    transition: `transform .${TRANSITION_DURATION}s linear`
  },
  bufferBar2Primary: {
    transition: `transform .${TRANSITION_DURATION}s linear`,
    backgroundColor: theme.palette.primary[100]
  },
  bufferBar2Accent: {
    transition: `transform .${TRANSITION_DURATION}s linear`,
    backgroundColor: theme.palette.secondary.A100
  },
  // Legends:
  // || represents the viewport
  // -  represents a light background
  // x  represents a dark background
  '@keyframes mui-indeterminate1': {
    //  |-----|---x-||-----||-----|
    '0%': {
      left: '-35%',
      right: '100%'
    },
    //  |-----|-----||-----||xxxx-|
    '60%': {
      left: '100%',
      right: '-90%'
    },
    '100%': {
      left: '100%',
      right: '-90%'
    }
  },
  '@keyframes mui-indeterminate2': {
    //  |xxxxx|xxxxx||-----||-----|
    '0%': {
      left: '-200%',
      right: '100%'
    },
    //  |-----|-----||-----||-x----|
    '60%': {
      left: '107%',
      right: '-8%'
    },
    '100%': {
      left: '107%',
      right: '-8%'
    }
  },
  '@keyframes buffer': {
    '0%': {
      opacity: 1,
      backgroundPosition: '0px -23px'
    },
    '50%': {
      opacity: 0,
      backgroundPosition: '0px -23px'
    },
    '100%': {
      opacity: 1,
      backgroundPosition: '-200px -23px'
    }
  }
});

class LinearProgress extends React.Component {

  render() {
    const _props = this.props,
          { classes, className, color, mode, value, valueBuffer } = _props,
          other = _objectWithoutProperties(_props, ['classes', 'className', 'color', 'mode', 'value', 'valueBuffer']);

    const dashedClass = classNames(classes.dashed, {
      [classes.primaryDashed]: color === 'primary',
      [classes.accentDashed]: color === 'accent'
    });

    const rootClassName = classNames(classes.root, {
      [classes.primaryColor]: color === 'primary',
      [classes.accentColor]: color === 'accent',
      [classes.rootBuffer]: mode === 'buffer',
      [classes.rootQuery]: mode === 'query'
    }, className);
    const primaryClassName = classNames(classes.bar, {
      [classes.primaryColorBar]: color === 'primary',
      [classes.accentColorBar]: color === 'accent',
      [classes.indeterminateBar1]: mode === 'indeterminate' || mode === 'query',
      [classes.determinateBar1]: mode === 'determinate',
      [classes.bufferBar1]: mode === 'buffer'
    });
    const secondaryClassName = classNames(classes.bar, {
      [classes.bufferBar2]: mode === 'buffer',
      [classes.primaryColorBar]: color === 'primary' && mode !== 'buffer',
      [classes.primaryColor]: color === 'primary' && mode === 'buffer',
      [classes.accentColorBar]: color === 'accent' && mode !== 'buffer',
      [classes.accentColor]: color === 'accent' && mode === 'buffer',
      [classes.indeterminateBar2]: mode === 'indeterminate' || mode === 'query'
    });
    const inlineStyles = { primary: {}, secondary: {} };
    const rootProps = {};

    if (mode === 'determinate') {
      if (value !== undefined) {
        inlineStyles.primary.transform = `scaleX(${value / 100})`;
        rootProps['aria-valuenow'] = Math.round(value);
      } else {
        warning(false, 'Material-UI: you need to provide a value property ' + 'when LinearProgress is in determinate mode.');
      }
    } else if (mode === 'buffer') {
      if (value !== undefined) {
        inlineStyles.primary.transform = `scaleX(${value / 100})`;
        inlineStyles.secondary.transform = `scaleX(${(valueBuffer || 0) / 100})`;
      } else {
        warning(false, 'Material-UI: you need to provide a value property when LinearProgress is ' + 'in buffer mode.');
      }
    }

    return React.createElement(
      'div',
      _extends({ className: rootClassName }, rootProps, other),
      mode === 'buffer' ? React.createElement('div', { className: dashedClass }) : null,
      React.createElement('div', { className: primaryClassName, style: inlineStyles.primary }),
      mode === 'determinate' ? null : React.createElement('div', { className: secondaryClassName, style: inlineStyles.secondary })
    );
  }
}

LinearProgress.defaultProps = {
  color: 'primary',
  mode: 'indeterminate'
};
export default withStyles(styles, { name: 'MuiLinearProgress' })(LinearProgress);


text:
The CFInputValidator - Cloud Factory Input Validator is a simple gem to **validate** the *spreadsheet data* inputs as per the given rules.

This gem is being developed for Project **Cloud Factory** Copyright© [Sprout Technology International Limited](http://sprout-technology.com)

![Sprout logo](http://sprout-technology.com/images/logo.png)

## Installation

In Gemfile
	source 'http://rubygems.org'
	gem 'unit_validator'

	bundle install

OR
	gem install unit_validator

	require 'rubygems'
	require 'unit_validator'

## Usage

The CFInputValidator checks if the **headers** of the provided spreadsheet matches with the corresponding **rules** *(checked by label)* and gives error message if it doesn't match.

The individual row of the spreadsheet undergoes the validation process and gives the final output as an array of **valid and invalid units**.
Later the valid and invalid units can be processed separately as required.

You can even check if a **file format** is supported by the gem.

The gem currently supports `validation_format` of `email`, `number`, `url`, `date` and `time` only.
It also checks if value is present if required is true.

## Example

1. Specify the rules, i.e `:label` `:required` `:validation_format`
		rules = [{:label => "company name",:required => true, :validation_format => "general"},
			 	 {:label => "email", :required => false, :validation_format => "email"}]

2. Provide data for validation:
		inputs = "company name,email\nSprout,info@sproutify.com\nApple,saroj@apple"

	**You can also give the file location as input**
		inputs = File.read("fixtures/gdoc.csv")

	* Check the file format with `check_extension(path)` method which gives you a 'boolean' value `:check`

		`file_location = "fixtures/gdoc.xlsxsfdsf"`

		`CFInputValidator.check_extension(file_location)[:check]`

	* This gem currently supports the following formats and 'must be converted into csv' before validation.
		* `inputs = File.read("fixtures/gdoc.csv")`
		* `inputs = Excel.new("fixtures/gdoc.xls").to_csv`
		* `inputs = Excelx.new("fixtures/gdoc.xlsx").to_csv`
		* `inputs = Openoffice.new("fixtures/gdoc.ods").to_csv`

3. Create a new constructor of *CF::InputValidator* class passing the above **rules** as argument.

		cloud_validator = CF::InputValidator.new(rules)

4. Call `parse_and_validate(data)` method passing the above inputs as arguments.
		val = cloud_validator.parse_and_validate(inputs)

5. Now you'll get both valid and invalid data in `:valid_units` and `:invalid_units` arrays respectively.
	* `val[:valid_units]`
	* `val[:invalid_units]`

6. It will give a `.errors` instance variable as error if the *headers* of spreadsheet data doesn't match with the *rules* or vice-versa saying *"Headers doesnot match the column counts"*.
 		rules = [{:field_id => "field_1", :label => "company name", :field_type => "text_data",
 		          :value => "Sprout", :required => true, :validation_format => "general"
 		         }]
 		inputs = "company name,email\nSprout,info@sproutify.com"

		cloud_validator = CF::InputValidator.new(rules)
    	val = cloud_validator.parse_and_validate(inputs)
		err = val.errors

## Note on Patches/Pull Requests

* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
  future version unintentionally.
* Commit, do not mess with rakefile, version, or history.
  (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
* Send me a pull request. Bonus points for topic branches.

### Copyright

Copyright© Sprout Technology International Limited. See LICENSE for details.


text:
package ruby

import (
	"bufio"
	"strings"
)

func Parse(src string) *RubyClass {
	p := &parser{Src: src}
	return p.Parse()
}

type parser struct {
	Src     string
	rc      *RubyClass
	mode    int
	level   int
	scratch string
}

const (
	base = iota
	class
	function
	selfClass
	classFunction
)

func (p *parser) Parse() *RubyClass {
	p.rc = &RubyClass{File: p.Src}
	s := bufio.NewScanner(strings.NewReader(p.Src))
	for s.Scan() {
		p.ParseLine(s.Text())
	}
	return p.rc
}

func (p *parser) ParseLine(line string) {
	trimmed := strings.TrimSpace(line)
	switch {
	case trimmed == "end":
		p.scratch += "\n" + line
		p.level--
		switch p.level {
		case 0:
			p.rc.Src = p.scratch
		case 1:
			switch p.mode {
			case function:
			case classFunction:
			}
		}
	case strings.HasPrefix(trimmed, "require"):
		p.rc.Libs = append(p.rc.Libs, strings.SplitN(trimmed, " ", 2)[1])
	case strings.HasPrefix(trimmed, "class "):
		className := strings.SplitN(trimmed, " ", 2)[1]
		classParts := strings.Split(className, "::")
		if len(classParts) == 1 {
			p.rc.Name = className
		} else {
			p.rc.Name = classParts[len(classParts)-1]
			p.rc.Modules = classParts[:len(classParts)-1]
		}
		p.mode = class
		p.level++
	}
}

type RubyClass struct {
	File string
	Src  string

	// from class ... < ...
	Modules []string
	Name    string
	Parent  string

	// attr_accessor, attr_writer, etc
	Attrs []Attr

	// from requires
	Libs []string

	// include ...
	Includes []string

	// unrecognized class functions
	Prelude string

	// def self. or class << self
	ClassFuncs []Func

	// Instance functions def ...
	InstFuncs []Func
}

type Attr struct {
	Doc  string
	Name string
	Type string
	Src  string
}

type Func struct {
	Name string
	Args []string
	Code string
	Src  string
}


text:
// This file was generated using Parlex's cpp_generator

#ifndef INCLUDED_PARENTHETICAL_HPP
#define INCLUDED_PARENTHETICAL_HPP

#include <optional>
#include <variant>
#include <vector>

#include "erased.hpp"

#include "parlex/detail/abstract_syntax_tree.hpp"
#include "parlex/detail/builtins.hpp"
#include "parlex/detail/document.hpp"

#include "plange_grammar.hpp"

namespace plc {

struct EXPRESSION;
struct IC;

struct PARENTHETICAL {
	parlex::detail::document::text<literal_0x28_t> dontCare0;

	std::vector<erased<IC>> field_1;

	erased<EXPRESSION> field_2;

	std::vector<erased<IC>> field_3;

	parlex::detail::document::text<literal_0x29_t> dontCare4;

	explicit PARENTHETICAL(
		parlex::detail::document::text<literal_0x28_t> && dontCare0, std::vector<erased<IC>> && field_1, erased<EXPRESSION> && field_2, std::vector<erased<IC>> && field_3, parlex::detail::document::text<literal_0x29_t> && dontCare4) : dontCare0(std::move(dontCare0)), field_1(std::move(field_1)), field_2(std::move(field_2)), field_3(std::move(field_3)), dontCare4(std::move(dontCare4)) {}

	PARENTHETICAL(PARENTHETICAL const & other) = default;
	PARENTHETICAL(PARENTHETICAL && move) = default;

	static PARENTHETICAL build(parlex::detail::ast_node const & n);
	static parlex::detail::state_machine const & state_machine();

};

} // namespace plc

#endif //INCLUDED_PARENTHETICAL_HPP


text:
/**
 * Object functions used to improve readability of Redux reducer code.
 *
 * @author Norman Fomferra
 */

import {isUndefined} from "./types";

/**
 * Encapsulate the idea of passing a new object as the first parameter
 * to Object.assign to ensure we correctly copy data instead of mutating.
 *
 * @param target The target object
 * @param sources The source objects
 * @returns a new {Object}
 */
export function updateObject(target, ...sources) {
    return Object.assign({}, target, ...sources);
}

/**
 * Similar to updateObject() but updates just the given property in *target*.
 *
 * @param target The target object
 * @param propertyName The property's name.
 * @param newValue The property's new value.
 * @returns a new {Object}
 */
export function updatePropertyObject(target, propertyName: string, newValue) {
    const oldValue = target[propertyName];
    return updateObject(target, {[propertyName]: updateObject(oldValue, newValue)});
}

/**
 * Similar to updateObject() but will only assign a property if
 * a given *source* property is undefined in *target*.
 *
 * @param target The target object
 * @param sources The source objects
 * @returns a new {Object}
 */
export function updateConditionally(target, ...sources) {
    target = updateObject(target);
    for (let source of sources) {
        for (let name of Object.keys(source)) {
            if (isUndefined(target[name])) {
                target[name] = source[name];
            }
        }
    }
    return target;
}


text:
require 'google/protobuf'

require 'src/proto/grpc/testing/empty'
require 'src/proto/grpc/testing/messages'
Google::Protobuf::DescriptorPool.generated_pool.build do
end

module Grpc
  module Testing
  end
end


text:
#pragma once
#include <aws/s3-crt/S3Crt_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace S3Crt
{
namespace Model
{

  /**
   *
Container for the stats details.

See Also:
   AWS API
   * Reference

   */
  class AWS_S3CRT_API Stats
  {
  public:
    Stats();
    Stats(const Aws::Utils::Xml::XmlNode& xmlNode);
    Stats& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;

    /**
     *
The total number of object bytes scanned.

     */
    inline long long GetBytesScanned() const{ return m_bytesScanned; }

    /**
     *
The total number of object bytes scanned.

     */
    inline bool BytesScannedHasBeenSet() const { return m_bytesScannedHasBeenSet; }

    /**
     *
The total number of object bytes scanned.

     */
    inline void SetBytesScanned(long long value) { m_bytesScannedHasBeenSet = true; m_bytesScanned = value; }

    /**
     *
The total number of object bytes scanned.

     */
    inline Stats& WithBytesScanned(long long value) { SetBytesScanned(value); return *this;}

    /**
     *
The total number of uncompressed object bytes processed.

     */
    inline long long GetBytesProcessed() const{ return m_bytesProcessed; }

    /**
     *
The total number of uncompressed object bytes processed.

     */
    inline bool BytesProcessedHasBeenSet() const { return m_bytesProcessedHasBeenSet; }

    /**
     *
The total number of uncompressed object bytes processed.

     */
    inline void SetBytesProcessed(long long value) { m_bytesProcessedHasBeenSet = true; m_bytesProcessed = value; }

    /**
     *
The total number of uncompressed object bytes processed.

     */
    inline Stats& WithBytesProcessed(long long value) { SetBytesProcessed(value); return *this;}

    /**
     *
The total number of bytes of records payload data returned.

     */
    inline long long GetBytesReturned() const{ return m_bytesReturned; }

    /**
     *
The total number of bytes of records payload data returned.

     */
    inline bool BytesReturnedHasBeenSet() const { return m_bytesReturnedHasBeenSet; }

    /**
     *
The total number of bytes of records payload data returned.

     */
    inline void SetBytesReturned(long long value) { m_bytesReturnedHasBeenSet = true; m_bytesReturned = value; }

    /**
     *
The total number of bytes of records payload data returned.

     */
    inline Stats& WithBytesReturned(long long value) { SetBytesReturned(value); return *this;}

  private:

    long long m_bytesScanned;
    bool m_bytesScannedHasBeenSet;

    long long m_bytesProcessed;
    bool m_bytesProcessedHasBeenSet;

    long long m_bytesReturned;
    bool m_bytesReturnedHasBeenSet;
  };

} // namespace Model
} // namespace S3Crt
} // namespace Aws


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.Timeline
{
	/// <summary>
	/// Timeline record contains information about the recorded activity.
	/// </summary>
	public class TimelineEvent
	{
		/// <summary>
		/// Gets or sets Event type.
		/// </summary>
		public string Type { get; set; }
		/// <summary>
		/// Gets or sets Event data.
		/// </summary>
		public object Data { get; set; }
		/// <summary>
		/// Gets or sets Start time.
		/// </summary>
		public double StartTime { get; set; }
		/// <summary>
		/// Gets or sets End time.
		/// </summary>
		public double EndTime { get; set; }
		/// <summary>
		/// Gets or sets Nested records.
		/// </summary>
		public TimelineEvent[] Children { get; set; }
		/// <summary>
		/// Gets or sets If present, identifies the thread that produced the event.
		/// </summary>
		public string Thread { get; set; }
		/// <summary>
		/// Gets or sets Stack trace.
		/// </summary>
		public Console.CallFrame[] StackTrace { get; set; }
		/// <summary>
		/// Gets or sets Unique identifier of the frame within the page that the event relates to.
		/// </summary>
		public string FrameId { get; set; }
	}
}


text:
#pragma strict

var AuxMataInimigo: CriaOrda;
var Vida: int;
var Pontuacao: int;
var destroysfx: AudioClip;
var Wave : int;
function Start () {
Vida = 10;
Pontuacao = 0;
Wave = 1;
}

function OnTriggerEnter (other : Collider)
{
	if(other.gameObject.tag == "Inimigo")
	{
	audio.PlayOneShot(destroysfx);
	Destroy(other.gameObject);
	AuxMataInimigo = GameObject.Find("respawn").GetComponent("CriaOrda");
	AuxMataInimigo.QntInimigosVivos--;
	Vida--;
 	}
}
function Update () {
	if (Vida==0)
	{
		Application.LoadLevel("Derrota");
	}
	if (Pontuacao == 100)
	{
		Application.LoadLevel("Vitoria");
	}
}
function OnGUI () {
GUI.color = Color.yellow;
GUI.Label(Rect(100, 10, 100, 50), "Vidas: " + Vida);
GUI.Label(Rect(200, 10, 250, 50), "Espaçonaves Destruidas: " + Pontuacao);
GUI.Label(Rect(400, 10, 250, 50), "Wave: " + Wave);
}


text:
#include <linux/vmalloc.h>
#include <linux/jhash.h>
#include <linux/slab.h>
#include <linux/sort.h>

#include "tracing_map.h"
#include "trace.h"

/*
 * NOTE: For a detailed description of the data structures used by
 * these functions (such as tracing_map_elt) please see the overview
 * of tracing_map data structures at the beginning of tracing_map.h.
 */

/**
 * tracing_map_update_sum - Add a value to a tracing_map_elt's sum field
 * @elt: The tracing_map_elt
 * @i: The index of the given sum associated with the tracing_map_elt
 * @n: The value to add to the sum
 *
 * Add n to sum i associated with the specified tracing_map_elt
 * instance.  The index i is the index returned by the call to
 * tracing_map_add_sum_field() when the tracing map was set up.
 */
void tracing_map_update_sum(struct tracing_map_elt *elt, unsigned int i, u64 n)
{
	atomic64_add(n, &elt->fields[i].sum);
}

/**
 * tracing_map_read_sum - Return the value of a tracing_map_elt's sum field
 * @elt: The tracing_map_elt
 * @i: The index of the given sum associated with the tracing_map_elt
 *
 * Retrieve the value of the sum i associated with the specified
 * tracing_map_elt instance.  The index i is the index returned by the
 * call to tracing_map_add_sum_field() when the tracing map was set
 * up.
 *
 * Return: The sum associated with field i for elt.
 */
u64 tracing_map_read_sum(struct tracing_map_elt *elt, unsigned int i)
{
	return (u64)atomic64_read(&elt->fields[i].sum);
}

int tracing_map_cmp_string(void *val_a, void *val_b)
{
	char *a = val_a;
	char *b = val_b;

	return strcmp(a, b);
}

int tracing_map_cmp_none(void *val_a, void *val_b)
{
	return 0;
}

static int tracing_map_cmp_atomic64(void *val_a, void *val_b)
{
	u64 a = atomic64_read((atomic64_t *)val_a);
	u64 b = atomic64_read((atomic64_t *)val_b);

	return (a > b) ? 1 : ((a < b) ? -1 : 0);
}

#define DEFINE_TRACING_MAP_CMP_FN(type)					\
static int tracing_map_cmp_##type(void *val_a, void *val_b)		\
{									\
	type a = *(type *)val_a;					\
	type b = *(type *)val_b;					\
									\
	return (a > b) ? 1 : ((a < b) ? -1 : 0);			\
}

DEFINE_TRACING_MAP_CMP_FN(s64);
DEFINE_TRACING_MAP_CMP_FN(u64);
DEFINE_TRACING_MAP_CMP_FN(s32);
DEFINE_TRACING_MAP_CMP_FN(u32);
DEFINE_TRACING_MAP_CMP_FN(s16);
DEFINE_TRACING_MAP_CMP_FN(u16);
DEFINE_TRACING_MAP_CMP_FN(s8);
DEFINE_TRACING_MAP_CMP_FN(u8);

tracing_map_cmp_fn_t tracing_map_cmp_num(int field_size,
					 int field_is_signed)
{
	tracing_map_cmp_fn_t fn = tracing_map_cmp_none;

	switch (field_size) {
	case 8:
		if (field_is_signed)
			fn = tracing_map_cmp_s64;
		else
			fn = tracing_map_cmp_u64;
		break;
	case 4:
		if (field_is_signed)
			fn = tracing_map_cmp_s32;
		else
			fn = tracing_map_cmp_u32;
		break;
	case 2:
		if (field_is_signed)
			fn = tracing_map_cmp_s16;
		else
			fn = tracing_map_cmp_u16;
		break;
	case 1:
		if (field_is_signed)
			fn = tracing_map_cmp_s8;
		else
			fn = tracing_map_cmp_u8;
		break;
	}

	return fn;
}

static int tracing_map_add_field(struct tracing_map *map,
				 tracing_map_cmp_fn_t cmp_fn)
{
	int ret = -EINVAL;

	if (map->n_fields < TRACING_MAP_FIELDS_MAX) {
		ret = map->n_fields;
		map->fields[map->n_fields++].cmp_fn = cmp_fn;
	}

	return ret;
}

/**
 * tracing_map_add_sum_field - Add a field describing a tracing_map sum
 * @map: The tracing_map
 *
 * Add a sum field to the key and return the index identifying it in
 * the map and associated tracing_map_elts.  This is the index used
 * for instance to update a sum for a particular tracing_map_elt using
 * tracing_map_update_sum() or reading it via tracing_map_read_sum().
 *
 * Return: The index identifying the field in the map and associated
 * tracing_map_elts, or -EINVAL on error.
 */
int tracing_map_add_sum_field(struct tracing_map *map)
{
	return tracing_map_add_field(map, tracing_map_cmp_atomic64);
}

/**
 * tracing_map_add_key_field - Add a field describing a tracing_map key
 * @map: The tracing_map
 * @offset: The offset within the key
 * @cmp_fn: The comparison function that will be used to sort on the key
 *
 * Let the map know there is a key and that if it's used as a sort key
 * to use cmp_fn.
 *
 * A key can be a subset of a compound key; for that purpose, the
 * offset param is used to describe where within the the compound key
 * the key referenced by this key field resides.
 *
 * Return: The index identifying the field in the map and associated
 * tracing_map_elts, or -EINVAL on error.
 */
int tracing_map_add_key_field(struct tracing_map *map,
			      unsigned int offset,
			      tracing_map_cmp_fn_t cmp_fn)

{
	int idx = tracing_map_add_field(map, cmp_fn);

	if (idx < 0)
		return idx;

	map->fields[idx].offset = offset;

	map->key_idx[map->n_keys++] = idx;

	return idx;
}

void tracing_map_array_clear(struct tracing_map_array *a)
{
	unsigned int i;

	if (!a->pages)
		return;

	for (i = 0; i < a->n_pages; i++)
		memset(a->pages[i], 0, PAGE_SIZE);
}

void tracing_map_array_free(struct tracing_map_array *a)
{
	unsigned int i;

	if (!a)
		return;

	if (!a->pages) {
		kfree(a);
		return;
	}

	for (i = 0; i < a->n_pages; i++) {
		if (!a->pages[i])
			break;
		free_page((unsigned long)a->pages[i]);
	}
}

struct tracing_map_array *tracing_map_array_alloc(unsigned int n_elts,
						  unsigned int entry_size)
{
	struct tracing_map_array *a;
	unsigned int i;

	a = kzalloc(sizeof(*a), GFP_KERNEL);
	if (!a)
		return NULL;

	a->entry_size_shift = fls(roundup_pow_of_two(entry_size) - 1);
	a->entries_per_page = PAGE_SIZE / (1 << a->entry_size_shift);
	a->n_pages = n_elts / a->entries_per_page;
	if (!a->n_pages)
		a->n_pages = 1;
	a->entry_shift = fls(a->entries_per_page) - 1;
	a->entry_mask = (1 << a->entry_shift) - 1;

	a->pages = kcalloc(a->n_pages, sizeof(void *), GFP_KERNEL);
	if (!a->pages)
		goto free;

	for (i = 0; i < a->n_pages; i++) {
		a->pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
		if (!a->pages[i])
			goto free;
	}
 out:
	return a;
 free:
	tracing_map_array_free(a);
	a = NULL;

	goto out;
}

static void tracing_map_elt_clear(struct tracing_map_elt *elt)
{
	unsigned i;

	for (i = 0; i < elt->map->n_fields; i++)
		if (elt->fields[i].cmp_fn == tracing_map_cmp_atomic64)
			atomic64_set(&elt->fields[i].sum, 0);

	if (elt->map->ops && elt->map->ops->elt_clear)
		elt->map->ops->elt_clear(elt);
}

static void tracing_map_elt_init_fields(struct tracing_map_elt *elt)
{
	unsigned int i;

	tracing_map_elt_clear(elt);

	for (i = 0; i < elt->map->n_fields; i++) {
		elt->fields[i].cmp_fn = elt->map->fields[i].cmp_fn;

		if (elt->fields[i].cmp_fn != tracing_map_cmp_atomic64)
			elt->fields[i].offset = elt->map->fields[i].offset;
	}
}

static void tracing_map_elt_free(struct tracing_map_elt *elt)
{
	if (!elt)
		return;

	if (elt->map->ops && elt->map->ops->elt_free)
		elt->map->ops->elt_free(elt);
	kfree(elt->fields);
	kfree(elt->key);
	kfree(elt);
}

static struct tracing_map_elt *tracing_map_elt_alloc(struct tracing_map *map)
{
	struct tracing_map_elt *elt;
	int err = 0;

	elt = kzalloc(sizeof(*elt), GFP_KERNEL);
	if (!elt)
		return ERR_PTR(-ENOMEM);

	elt->map = map;

	elt->key = kzalloc(map->key_size, GFP_KERNEL);
	if (!elt->key) {
		err = -ENOMEM;
		goto free;
	}

	elt->fields = kcalloc(map->n_fields, sizeof(*elt->fields), GFP_KERNEL);
	if (!elt->fields) {
		err = -ENOMEM;
		goto free;
	}

	tracing_map_elt_init_fields(elt);

	if (map->ops && map->ops->elt_alloc) {
		err = map->ops->elt_alloc(elt);
		if (err)
			goto free;
	}
	return elt;
 free:
	tracing_map_elt_free(elt);

	return ERR_PTR(err);
}

static struct tracing_map_elt *get_free_elt(struct tracing_map *map)
{
	struct tracing_map_elt *elt = NULL;
	int idx;

	idx = atomic_inc_return(&map->next_elt);
	if (idx < map->max_elts) {
		elt = *(TRACING_MAP_ELT(map->elts, idx));
		if (map->ops && map->ops->elt_init)
			map->ops->elt_init(elt);
	}

	return elt;
}

static void tracing_map_free_elts(struct tracing_map *map)
{
	unsigned int i;

	if (!map->elts)
		return;

	for (i = 0; i < map->max_elts; i++) {
		tracing_map_elt_free(*(TRACING_MAP_ELT(map->elts, i)));
		*(TRACING_MAP_ELT(map->elts, i)) = NULL;
	}

	tracing_map_array_free(map->elts);
	map->elts = NULL;
}

static int tracing_map_alloc_elts(struct tracing_map *map)
{
	unsigned int i;

	map->elts = tracing_map_array_alloc(map->max_elts,
					    sizeof(struct tracing_map_elt *));
	if (!map->elts)
		return -ENOMEM;

	for (i = 0; i < map->max_elts; i++) {
		*(TRACING_MAP_ELT(map->elts, i)) = tracing_map_elt_alloc(map);
		if (IS_ERR(*(TRACING_MAP_ELT(map->elts, i)))) {
			*(TRACING_MAP_ELT(map->elts, i)) = NULL;
			tracing_map_free_elts(map);

			return -ENOMEM;
		}
	}

	return 0;
}

static inline bool keys_match(void *key, void *test_key, unsigned key_size)
{
	bool match = true;

	if (memcmp(key, test_key, key_size))
		match = false;

	return match;
}

static inline struct tracing_map_elt *
__tracing_map_insert(struct tracing_map *map, void *key, bool lookup_only)
{
	u32 idx, key_hash, test_key;
	struct tracing_map_entry *entry;

	key_hash = jhash(key, map->key_size, 0);
	if (key_hash == 0)
		key_hash = 1;
	idx = key_hash >> (32 - (map->map_bits + 1));

	while (1) {
		idx &= (map->map_size - 1);
		entry = TRACING_MAP_ENTRY(map->map, idx);
		test_key = entry->key;

		if (test_key && test_key == key_hash && entry->val &&
		    keys_match(key, entry->val->key, map->key_size)) {
			atomic64_inc(&map->hits);
			return entry->val;
		}

		if (!test_key) {
			if (lookup_only)
				break;

			if (!cmpxchg(&entry->key, 0, key_hash)) {
				struct tracing_map_elt *elt;

				elt = get_free_elt(map);
				if (!elt) {
					atomic64_inc(&map->drops);
					entry->key = 0;
					break;
				}

				memcpy(elt->key, key, map->key_size);
				entry->val = elt;
				atomic64_inc(&map->hits);

				return entry->val;
			}
		}

		idx++;
	}

	return NULL;
}

/**
 * tracing_map_insert - Insert key and/or retrieve val from a tracing_map
 * @map: The tracing_map to insert into
 * @key: The key to insert
 *
 * Inserts a key into a tracing_map and creates and returns a new
 * tracing_map_elt for it, or if the key has already been inserted by
 * a previous call, returns the tracing_map_elt already associated
 * with it.  When the map was created, the number of elements to be
 * allocated for the map was specified (internally maintained as
 * 'max_elts' in struct tracing_map), and that number of
 * tracing_map_elts was created by tracing_map_init().  This is the
 * pre-allocated pool of tracing_map_elts that tracing_map_insert()
 * will allocate from when adding new keys.  Once that pool is
 * exhausted, tracing_map_insert() is useless and will return NULL to
 * signal that state.  There are two user-visible tracing_map
 * variables, 'hits' and 'drops', which are updated by this function.
 * Every time an element is either successfully inserted or retrieved,
 * the 'hits' value is incrememented.  Every time an element insertion
 * fails, the 'drops' value is incremented.
 *
 * This is a lock-free tracing map insertion function implementing a
 * modified form of Cliff Click's basic insertion algorithm.  It
 * requires the table size be a power of two.  To prevent any
 * possibility of an infinite loop we always make the internal table
 * size double the size of the requested table size (max_elts * 2).
 * Likewise, we never reuse a slot or resize or delete elements - when
 * we've reached max_elts entries, we simply return NULL once we've
 * run out of entries.  Readers can at any point in time traverse the
 * tracing map and safely access the key/val pairs.
 *
 * Return: the tracing_map_elt pointer val associated with the key.
 * If this was a newly inserted key, the val will be a newly allocated
 * and associated tracing_map_elt pointer val.  If the key wasn't
 * found and the pool of tracing_map_elts has been exhausted, NULL is
 * returned and no further insertions will succeed.
 */
struct tracing_map_elt *tracing_map_insert(struct tracing_map *map, void *key)
{
	return __tracing_map_insert(map, key, false);
}

/**
 * tracing_map_lookup - Retrieve val from a tracing_map
 * @map: The tracing_map to perform the lookup on
 * @key: The key to look up
 *
 * Looks up key in tracing_map and if found returns the matching
 * tracing_map_elt.  This is a lock-free lookup; see
 * tracing_map_insert() for details on tracing_map and how it works.
 * Every time an element is retrieved, the 'hits' value is
 * incrememented.  There is one user-visible tracing_map variable,
 * 'hits', which is updated by this function.  Every time an element
 * is successfully retrieved, the 'hits' value is incrememented.  The
 * 'drops' value is never updated by this function.
 *
 * Return: the tracing_map_elt pointer val associated with the key.
 * If the key wasn't found, NULL is returned.
 */
struct tracing_map_elt *tracing_map_lookup(struct tracing_map *map, void *key)
{
	return __tracing_map_insert(map, key, true);
}

/**
 * tracing_map_destroy - Destroy a tracing_map
 * @map: The tracing_map to destroy
 *
 * Frees a tracing_map along with its associated array of
 * tracing_map_elts.
 *
 * Callers should make sure there are no readers or writers actively
 * reading or inserting into the map before calling this.
 */
void tracing_map_destroy(struct tracing_map *map)
{
	if (!map)
		return;

	tracing_map_free_elts(map);

	tracing_map_array_free(map->map);
	kfree(map);
}

/**
 * tracing_map_clear - Clear a tracing_map
 * @map: The tracing_map to clear
 *
 * Resets the tracing map to a cleared or initial state.  The
 * tracing_map_elts are all cleared, and the array of struct
 * tracing_map_entry is reset to an initialized state.
 *
 * Callers should make sure there are no writers actively inserting
 * into the map before calling this.
 */
void tracing_map_clear(struct tracing_map *map)
{
	unsigned int i;

	atomic_set(&map->next_elt, -1);
	atomic64_set(&map->hits, 0);
	atomic64_set(&map->drops, 0);

	tracing_map_array_clear(map->map);

	for (i = 0; i < map->max_elts; i++)
		tracing_map_elt_clear(*(TRACING_MAP_ELT(map->elts, i)));
}

static void set_sort_key(struct tracing_map *map,
			 struct tracing_map_sort_key *sort_key)
{
	map->sort_key = *sort_key;
}

/**
 * tracing_map_create - Create a lock-free map and element pool
 * @map_bits: The size of the map (2 ** map_bits)
 * @key_size: The size of the key for the map in bytes
 * @ops: Optional client-defined tracing_map_ops instance
 * @private_data: Client data associated with the map
 *
 * Creates and sets up a map to contain 2 ** map_bits number of
 * elements (internally maintained as 'max_elts' in struct
 * tracing_map).  Before using, map fields should be added to the map
 * with tracing_map_add_sum_field() and tracing_map_add_key_field().
 * tracing_map_init() should then be called to allocate the array of
 * tracing_map_elts, in order to avoid allocating anything in the map
 * insertion path.  The user-specified map size reflects the maximum
 * number of elements that can be contained in the table requested by
 * the user - internally we double that in order to keep the table
 * sparse and keep collisions manageable.
 *
 * A tracing_map is a special-purpose map designed to aggregate or
 * 'sum' one or more values associated with a specific object of type
 * tracing_map_elt, which is attached by the map to a given key.
 *
 * tracing_map_create() sets up the map itself, and provides
 * operations for inserting tracing_map_elts, but doesn't allocate the
 * tracing_map_elts themselves, or provide a means for describing the
 * keys or sums associated with the tracing_map_elts.  All
 * tracing_map_elts for a given map have the same set of sums and
 * keys, which are defined by the client using the functions
 * tracing_map_add_key_field() and tracing_map_add_sum_field().  Once
 * the fields are defined, the pool of elements allocated for the map
 * can be created, which occurs when the client code calls
 * tracing_map_init().
 *
 * When tracing_map_init() returns, tracing_map_elt elements can be
 * inserted into the map using tracing_map_insert().  When called,
 * tracing_map_insert() grabs a free tracing_map_elt from the pool, or
 * finds an existing match in the map and in either case returns it.
 * The client can then use tracing_map_update_sum() and
 * tracing_map_read_sum() to update or read a given sum field for the
 * tracing_map_elt.
 *
 * The client can at any point retrieve and traverse the current set
 * of inserted tracing_map_elts in a tracing_map, via
 * tracing_map_sort_entries().  Sorting can be done on any field,
 * including keys.
 *
 * See tracing_map.h for a description of tracing_map_ops.
 *
 * Return: the tracing_map pointer if successful, ERR_PTR if not.
 */
struct tracing_map *tracing_map_create(unsigned int map_bits,
				       unsigned int key_size,
				       const struct tracing_map_ops *ops,
				       void *private_data)
{
	struct tracing_map *map;
	unsigned int i;

	if (map_bits < TRACING_MAP_BITS_MIN ||
	    map_bits > TRACING_MAP_BITS_MAX)
		return ERR_PTR(-EINVAL);

	map = kzalloc(sizeof(*map), GFP_KERNEL);
	if (!map)
		return ERR_PTR(-ENOMEM);

	map->map_bits = map_bits;
	map->max_elts = (1 << map_bits);
	atomic_set(&map->next_elt, -1);

	map->map_size = (1 << (map_bits + 1));
	map->ops = ops;

	map->private_data = private_data;

	map->map = tracing_map_array_alloc(map->map_size,
					   sizeof(struct tracing_map_entry));
	if (!map->map)
		goto free;

	map->key_size = key_size;
	for (i = 0; i < TRACING_MAP_KEYS_MAX; i++)
		map->key_idx[i] = -1;
 out:
	return map;
 free:
	tracing_map_destroy(map);
	map = ERR_PTR(-ENOMEM);

	goto out;
}

/**
 * tracing_map_init - Allocate and clear a map's tracing_map_elts
 * @map: The tracing_map to initialize
 *
 * Allocates a clears a pool of tracing_map_elts equal to the
 * user-specified size of 2 ** map_bits (internally maintained as
 * 'max_elts' in struct tracing_map).  Before using, the map fields
 * should be added to the map with tracing_map_add_sum_field() and
 * tracing_map_add_key_field().  tracing_map_init() should then be
 * called to allocate the array of tracing_map_elts, in order to avoid
 * allocating anything in the map insertion path.  The user-specified
 * map size reflects the max number of elements requested by the user
 * - internally we double that in order to keep the table sparse and
 * keep collisions manageable.
 *
 * See tracing_map.h for a description of tracing_map_ops.
 *
 * Return: the tracing_map pointer if successful, ERR_PTR if not.
 */
int tracing_map_init(struct tracing_map *map)
{
	int err;

	if (map->n_fields < 2)
		return -EINVAL; /* need at least 1 key and 1 val */

	err = tracing_map_alloc_elts(map);
	if (err)
		return err;

	tracing_map_clear(map);

	return err;
}

static int cmp_entries_dup(const struct tracing_map_sort_entry **a,
			   const struct tracing_map_sort_entry **b)
{
	int ret = 0;

	if (memcmp((*a)->key, (*b)->key, (*a)->elt->map->key_size))
		ret = 1;

	return ret;
}

static int cmp_entries_sum(const struct tracing_map_sort_entry **a,
			   const struct tracing_map_sort_entry **b)
{
	const struct tracing_map_elt *elt_a, *elt_b;
	struct tracing_map_sort_key *sort_key;
	struct tracing_map_field *field;
	tracing_map_cmp_fn_t cmp_fn;
	void *val_a, *val_b;
	int ret = 0;

	elt_a = (*a)->elt;
	elt_b = (*b)->elt;

	sort_key = &elt_a->map->sort_key;

	field = &elt_a->fields[sort_key->field_idx];
	cmp_fn = field->cmp_fn;

	val_a = &elt_a->fields[sort_key->field_idx].sum;
	val_b = &elt_b->fields[sort_key->field_idx].sum;

	ret = cmp_fn(val_a, val_b);
	if (sort_key->descending)
		ret = -ret;

	return ret;
}

static int cmp_entries_key(const struct tracing_map_sort_entry **a,
			   const struct tracing_map_sort_entry **b)
{
	const struct tracing_map_elt *elt_a, *elt_b;
	struct tracing_map_sort_key *sort_key;
	struct tracing_map_field *field;
	tracing_map_cmp_fn_t cmp_fn;
	void *val_a, *val_b;
	int ret = 0;

	elt_a = (*a)->elt;
	elt_b = (*b)->elt;

	sort_key = &elt_a->map->sort_key;

	field = &elt_a->fields[sort_key->field_idx];

	cmp_fn = field->cmp_fn;

	val_a = elt_a->key + field->offset;
	val_b = elt_b->key + field->offset;

	ret = cmp_fn(val_a, val_b);
	if (sort_key->descending)
		ret = -ret;

	return ret;
}

static void destroy_sort_entry(struct tracing_map_sort_entry *entry)
{
	if (!entry)
		return;

	if (entry->elt_copied)
		tracing_map_elt_free(entry->elt);

	kfree(entry);
}

/**
 * tracing_map_destroy_sort_entries - Destroy an array of sort entries
 * @entries: The entries to destroy
 * @n_entries: The number of entries in the array
 *
 * Destroy the elements returned by a tracing_map_sort_entries() call.
 */
void tracing_map_destroy_sort_entries(struct tracing_map_sort_entry **entries,
				      unsigned int n_entries)
{
	unsigned int i;

	for (i = 0; i < n_entries; i++)
		destroy_sort_entry(entries[i]);

	vfree(entries);
}

static struct tracing_map_sort_entry *
create_sort_entry(void *key, struct tracing_map_elt *elt)
{
	struct tracing_map_sort_entry *sort_entry;

	sort_entry = kzalloc(sizeof(*sort_entry), GFP_KERNEL);
	if (!sort_entry)
		return NULL;

	sort_entry->key = key;
	sort_entry->elt = elt;

	return sort_entry;
}

static struct tracing_map_elt *copy_elt(struct tracing_map_elt *elt)
{
	struct tracing_map_elt *dup_elt;
	unsigned int i;

	dup_elt = tracing_map_elt_alloc(elt->map);
	if (IS_ERR(dup_elt))
		return NULL;

	if (elt->map->ops && elt->map->ops->elt_copy)
		elt->map->ops->elt_copy(dup_elt, elt);

	dup_elt->private_data = elt->private_data;
	memcpy(dup_elt->key, elt->key, elt->map->key_size);

	for (i = 0; i < elt->map->n_fields; i++) {
		atomic64_set(&dup_elt->fields[i].sum,
			     atomic64_read(&elt->fields[i].sum));
		dup_elt->fields[i].cmp_fn = elt->fields[i].cmp_fn;
	}

	return dup_elt;
}

static int merge_dup(struct tracing_map_sort_entry **sort_entries,
		     unsigned int target, unsigned int dup)
{
	struct tracing_map_elt *target_elt, *elt;
	bool first_dup = (target - dup) == 1;
	int i;

	if (first_dup) {
		elt = sort_entries[target]->elt;
		target_elt = copy_elt(elt);
		if (!target_elt)
			return -ENOMEM;
		sort_entries[target]->elt = target_elt;
		sort_entries[target]->elt_copied = true;
	} else
		target_elt = sort_entries[target]->elt;

	elt = sort_entries[dup]->elt;

	for (i = 0; i < elt->map->n_fields; i++)
		atomic64_add(atomic64_read(&elt->fields[i].sum),
			     &target_elt->fields[i].sum);

	sort_entries[dup]->dup = true;

	return 0;
}

static int merge_dups(struct tracing_map_sort_entry **sort_entries,
		      int n_entries, unsigned int key_size)
{
	unsigned int dups = 0, total_dups = 0;
	int err, i, j;
	void *key;

	if (n_entries < 2)
		return total_dups;

	sort(sort_entries, n_entries, sizeof(struct tracing_map_sort_entry *),
	     (int (*)(const void *, const void *))cmp_entries_dup, NULL);

	key = sort_entries[0]->key;
	for (i = 1; i < n_entries; i++) {
		if (!memcmp(sort_entries[i]->key, key, key_size)) {
			dups++; total_dups++;
			err = merge_dup(sort_entries, i - dups, i);
			if (err)
				return err;
			continue;
		}
		key = sort_entries[i]->key;
		dups = 0;
	}

	if (!total_dups)
		return total_dups;

	for (i = 0, j = 0; i < n_entries; i++) {
		if (!sort_entries[i]->dup) {
			sort_entries[j] = sort_entries[i];
			if (j++ != i)
				sort_entries[i] = NULL;
		} else {
			destroy_sort_entry(sort_entries[i]);
			sort_entries[i] = NULL;
		}
	}

	return total_dups;
}

static bool is_key(struct tracing_map *map, unsigned int field_idx)
{
	unsigned int i;

	for (i = 0; i < map->n_keys; i++)
		if (map->key_idx[i] == field_idx)
			return true;
	return false;
}

static void sort_secondary(struct tracing_map *map,
			   const struct tracing_map_sort_entry **entries,
			   unsigned int n_entries,
			   struct tracing_map_sort_key *primary_key,
			   struct tracing_map_sort_key *secondary_key)
{
	int (*primary_fn)(const struct tracing_map_sort_entry **,
			  const struct tracing_map_sort_entry **);
	int (*secondary_fn)(const struct tracing_map_sort_entry **,
			    const struct tracing_map_sort_entry **);
	unsigned i, start = 0, n_sub = 1;

	if (is_key(map, primary_key->field_idx))
		primary_fn = cmp_entries_key;
	else
		primary_fn = cmp_entries_sum;

	if (is_key(map, secondary_key->field_idx))
		secondary_fn = cmp_entries_key;
	else
		secondary_fn = cmp_entries_sum;

	for (i = 0; i < n_entries - 1; i++) {
		const struct tracing_map_sort_entry **a = &entries[i];
		const struct tracing_map_sort_entry **b = &entries[i + 1];

		if (primary_fn(a, b) == 0) {
			n_sub++;
			if (i < n_entries - 2)
				continue;
		}

		if (n_sub < 2) {
			start = i + 1;
			n_sub = 1;
			continue;
		}

		set_sort_key(map, secondary_key);
		sort(&entries[start], n_sub,
		     sizeof(struct tracing_map_sort_entry *),
		     (int (*)(const void *, const void *))secondary_fn, NULL);
		set_sort_key(map, primary_key);

		start = i + 1;
		n_sub = 1;
	}
}

/**
 * tracing_map_sort_entries - Sort the current set of tracing_map_elts in a map
 * @map: The tracing_map
 * @sort_key: The sort key to use for sorting
 * @sort_entries: outval: pointer to allocated and sorted array of entries
 *
 * tracing_map_sort_entries() sorts the current set of entries in the
 * map and returns the list of tracing_map_sort_entries containing
 * them to the client in the sort_entries param.  The client can
 * access the struct tracing_map_elt element of interest directly as
 * the 'elt' field of a returned struct tracing_map_sort_entry object.
 *
 * The sort_key has only two fields: idx and descending.  'idx' refers
 * to the index of the field added via tracing_map_add_sum_field() or
 * tracing_map_add_key_field() when the tracing_map was initialized.
 * 'descending' is a flag that if set reverses the sort order, which
 * by default is ascending.
 *
 * The client should not hold on to the returned array but should use
 * it and call tracing_map_destroy_sort_entries() when done.
 *
 * Return: the number of sort_entries in the struct tracing_map_sort_entry
 * array, negative on error
 */
int tracing_map_sort_entries(struct tracing_map *map,
			     struct tracing_map_sort_key *sort_keys,
			     unsigned int n_sort_keys,
			     struct tracing_map_sort_entry ***sort_entries)
{
	int (*cmp_entries_fn)(const struct tracing_map_sort_entry **,
			      const struct tracing_map_sort_entry **);
	struct tracing_map_sort_entry *sort_entry, **entries;
	int i, n_entries, ret;

	entries = vmalloc(map->max_elts * sizeof(sort_entry));
	if (!entries)
		return -ENOMEM;

	for (i = 0, n_entries = 0; i < map->map_size; i++) {
		struct tracing_map_entry *entry;

		entry = TRACING_MAP_ENTRY(map->map, i);

		if (!entry->key || !entry->val)
			continue;

		entries[n_entries] = create_sort_entry(entry->val->key,
						       entry->val);
		if (!entries[n_entries++]) {
			ret = -ENOMEM;
			goto free;
		}
	}

	if (n_entries == 0) {
		ret = 0;
		goto free;
	}

	if (n_entries == 1) {
		*sort_entries = entries;
		return 1;
	}

	ret = merge_dups(entries, n_entries, map->key_size);
	if (ret < 0)
		goto free;
	n_entries -= ret;

	if (is_key(map, sort_keys[0].field_idx))
		cmp_entries_fn = cmp_entries_key;
	else
		cmp_entries_fn = cmp_entries_sum;

	set_sort_key(map, &sort_keys[0]);

	sort(entries, n_entries, sizeof(struct tracing_map_sort_entry *),
	     (int (*)(const void *, const void *))cmp_entries_fn, NULL);

	if (n_sort_keys > 1)
		sort_secondary(map,
			       (const struct tracing_map_sort_entry **)entries,
			       n_entries,
			       &sort_keys[0],
			       &sort_keys[1]);

	*sort_entries = entries;

	return n_entries;
 free:
	tracing_map_destroy_sort_entries(entries, n_entries);

	return ret;
}


text:
module Architecture
  # Context
  module Context
    class << self
      attr_accessor :config
    end
  end
end


text:
package org.ms123.common.workflow.converter;

import java.util.Map;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.FieldExtension;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.ImplementationType;
import org.activiti.bpmn.model.ServiceTask;
import org.apache.commons.lang.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.editor.language.json.converter.*;
import flexjson.*;

/**
 */
@SuppressWarnings("unchecked")
public class Simpl4RulesTaskJsonConverter extends BaseBpmnJsonConverter {

	protected JSONDeserializer m_ds = new JSONDeserializer();

	protected JSONSerializer m_js = new JSONSerializer();

	private final String RULESNAME_PROP = "rulesname";

	private final String RULESNAME = "rulesname";

	private final String RULESKEY_PROP = "ruleskey";

	private final String RULESKEY = "ruleskey";

	private final String VARMAPPING_PROP = "variablesmapping";

	private final String VARMAPPING = "variablesmapping";

	protected String getStencilId(BaseElement flowElement) {
		return "RulesTask";
	}

	protected void convertElementToJson(ObjectNode propertiesNode, BaseElement flowElement) {
		ServiceTask serviceTask = (ServiceTask) flowElement;
	}

	protected FlowElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap) {
		m_js.prettyPrint(true);
		ServiceTask task = new ServiceTask();
		Map elementMap = (Map) m_ds.deserialize(elementNode.toString());
		Map<String, Object> propMap = (Map) elementMap.get("properties");
		String clazz = Simpl4BpmnJsonConverter.getFullnameForTask("TaskRulesExecutor");
		task.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_CLASS);
		task.setImplementation(clazz);

		String variablesmapping = checkNull(VARMAPPING, propMap.get(VARMAPPING_PROP));
		FieldExtension field = new FieldExtension();
		field.setFieldName(VARMAPPING);
		field.setExpression(variablesmapping);
		task.getFieldExtensions().add(field);

		field = new FieldExtension();
		field.setFieldName(RULESNAME);
		field.setStringValue(getValue(RULESNAME, propMap.get(RULESNAME_PROP)));
		task.getFieldExtensions().add(field);

		field = new FieldExtension();
		field.setFieldName(RULESKEY);
		field.setStringValue(getValue(RULESKEY, propMap.get(RULESKEY_PROP)));
		task.getFieldExtensions().add(field);
		return task;
	}

	public static void fillTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap, Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap) {
		fillJsonTypes(convertersToBpmnMap);
	}

	public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
		convertersToBpmnMap.put("RulesTask", Simpl4RulesTaskJsonConverter.class);
	}

	private String checkNull(String name, Object value) {
		if (value == null)
			throw new RuntimeException("Simpl4RulesTaskJsonConverter:" + name + " is null");
		return value.toString();
	}
	private String getValue(String name, Object value) {
		if (value == null){
			return null;
		}
		return value.toString();
	}
}


text:
package dw.cli.commands.itest;

import dw.cli.Output;
import dw.cli.itest.TestHelper;

public class Test_Version extends TestHelper {

	@org.junit.Test
	public void optionVersion() throws Exception{
		Output output = runWithArguments("--version");
		assertGenericSuccess(output);
		assertNotNullOrEmpty(output.out);
	}
}


text:
import map from 'lodash/collection/map';
import pick from 'lodash/object/pick';
import last from 'lodash/array/last';
import isEqual from 'lodash/lang/isEqual';
import find from 'lodash/collection/find';
import classNames from 'classnames';
import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import createFragment from 'react-addons-create-fragment';
import DataGrid from 'react-datagrid';
import Helpers from '../utils/Helpers';
import Pagination from './Pagination';

class DataTable extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selected: null
    };

    // Cache as local variable
    this.columns = props.columns;

    this.handleCheckAll = (e) => {
      if (props.onCheckAll) {
        props.onCheckAll(e);
      }
    };

    this.handleCheck = (id, e) => {
      if (props.onCheck) {
        props.onCheck(id, e);
      }
    };

    this.getSelectorColumn = () => {
      return {
        name: 'index',
        width: 30,
        title: <input type="checkbox" id="select_all" onChange={this.handleCheckAll} checked={this.props.dataSource.length !== 0 && this.props.selectedIds && this.props.selectedIds.length === this.props.dataSource.length}/>,
        sortable: false,
        style: { textAlign: 'center' },
        render: (value, data) => {
          return <input data-record-id={data[this.props.idProperty]} type="checkbox" checked={this.props.selectedIds.indexOf(data[this.props.idProperty]) !== -1} onChange={this.handleCheck.bind(this, data[this.props.idProperty])} />;
        }
      };
    };

    this.handleColumnOrderChange = (index, dropIndex) => {
      if (this.props.selectable) {
        index -= 1;
        dropIndex -= 1;
      }
      const col = this.columns[index];
      this.columns.splice(index, 1); // delete from index, 1 item
      this.columns.splice(dropIndex, 0, col);
      this.setState({});
      // Send out new column info
      if (this.props.onStatusChange) {
        const newColumns = map(this.columns, (column) => {
          return pick(column, 'name', 'width');
        });
        this.props.onStatusChange({columns: newColumns});
      }
    };

    this.handleSortChange = (sortInfo) => {
      const _sortInfo = last(sortInfo) || {};
      // nextSortInfo for func onPageChange is a string, e.g. 'id,desc'
      let nextSortInfo = Helpers.stringifySort([_sortInfo]);
      // this.props.sortInfo is an array of object, e.g. [{name: 'id', dir: 'desc'}]
      const preSortInfo = this.props.sortInfo[0];

      // sort dir only need asc and desc
      if (!nextSortInfo && preSortInfo) {
        const dir = preSortInfo.dir === 'asc' ? 'desc' : 'asc';
        nextSortInfo = `${preSortInfo.name},${dir}`;
      }

      this.handlePageChange({order: nextSortInfo});
      // Send out new sort info
      if (this.props.onStatusChange) {
        this.props.onStatusChange({sort: _sortInfo});
      }
    };

    this.handlePageChange = (newQuery) => {
      let query;
      if (newQuery && (newQuery.hasOwnProperty('offset') || newQuery.hasOwnProperty('order'))) {
        query = newQuery;
      } else {
        query = Object.assign({}, newQuery, {offset: 0});
      }
      this.props.onPageChange(newQuery);
    };

    this.onColumnResize = (firstCol, firstSize) => {
      const columnMinWidth = firstCol.minWidth || this.props.columnMinWidth;
      firstCol.width = Math.max(firstSize, columnMinWidth);
      this.setState({});

      // Send out new column info
      if (this.props.onStatusChange) {
        const newColumns = map(this.columns, (column) => {
          const _column = (column.name === firstCol.name ? firstCol : column);
          return pick(_column, 'name', 'width');
        });
        this.props.onStatusChange({columns: newColumns});
      }
    };

    this.onSelectionChange = (newSelectedId) => {
      if (this.props.focusable) {
        this.setState({selected: newSelectedId});
      }
    };

    this.fixScrollbar = () => {
      const $scope = $(findDOMNode(this));
      const $hScrollbar = $scope.find('.z-horizontal-scrollbar');
      const $hScroller = $scope.find('.z-horizontal-scroller');

      if ($hScrollbar.width() >= $hScroller.outerWidth(true)) {
        $hScrollbar.css({display: 'none'});
      } else {
        $hScrollbar.css({display: ''});
      }

      if (this.props.scrollbarSize === 0) {
        $scope.find('.z-vertical-scrollbar').css({display: 'none'});
      }
    };
  }

  componentDidMount() {
    this.fixScrollbar();
  }

  componentWillReceiveProps(nextProps) {
    const oldColumnNames = map(this.columns, 'name').sort();
    const newColumnNames = map(nextProps.columns, 'name').sort();
    if (isEqual(oldColumnNames, newColumnNames)){
      this.columns = this.columns.map((oldColumn) => {
        return find(nextProps.columns, (column) => {
          return oldColumn.name === column.name;
        });
      });
    } else {
      this.columns = nextProps.columns;
    }
  }

  componentDidUpdate() {
    this.fixScrollbar();
  }

  render() {
    const columns = this.props.selectable ? [this.getSelectorColumn()].concat(this.columns) : this.columns;
    const pager = (
      <Pagination
        offset={this.props.offset}
        limit={this.props.limit}
        total={this.props.total}
        onPageChange={this.handlePageChange}
        paginationClassName={this.props.paginationClassName}
      />
    );
    const table = (
      <DataGrid
        idProperty={this.props.idProperty}
        dataSource={this.props.dataSource}
        columns={columns}
        style={this.props.style}
        rowStyle={this.props.rowStyle}
        rowClassName={this.props.rowClassName}
        sortInfo={this.props.sortInfo}
        emptyText={this.props.emptyText}
        withColumnMenu={false}
        defaultPageSize={25}
        selected={this.state.selected}
        onSelectionChange={this.onSelectionChange}
        onColumnOrderChange={this.handleColumnOrderChange}
        onSortChange={this.handleSortChange}
        onColumnResize={this.onColumnResize}
        resizableColumns={this.props.resizableColumns}
        scrollbarSize={this.props.scrollbarSize}
        rowHeight={this.props.rowHeight}
      />
    );

    // Append pager
    let components = table;
    if (this.props.pager) {
      if (this.props.pager === 'top') {
        components = createFragment({ pager: pager, table: table });
      } else if (this.props.pager === 'bottom') {
        components = createFragment({ table: table, pager: pager });
      }
    }

    return (
      <div className={classNames('datagrid-wrapper', this.props.wrapperClassName)}>
        {components}
      </div>
    );
  }
}

DataTable.propTypes = {
  offset: PropTypes.number, // Offset params for calculate pagination staffs.
  limit: PropTypes.number, // Page size
  total: PropTypes.number, // Total count for data
  dataSource: PropTypes.array.isRequired, // Data
  columns: PropTypes.array.isRequired, // Columns
  style: PropTypes.object, // Global style, like width, height, etc.
  rowStyle: PropTypes.oneOfType([ // Row style
    PropTypes.object,
    PropTypes.func
  ]),
  rowClassName: PropTypes.oneOfType([ // Row className
    PropTypes.object,
    PropTypes.func
  ]),
  sortInfo: PropTypes.array, // Sort info
  selectable: PropTypes.bool, // Set to true to add select all column
  focusable: PropTypes.bool, // Set to true to selected the column
  resizableColumns: PropTypes.bool, // Set to true to make columns can be resized
  pager: PropTypes.oneOfType([ // Pagination: 'top', 'bottom' and false
    PropTypes.string,
    PropTypes.bool
  ]),
  onPageChange: PropTypes.func, // Interface for send out new page info.
  // Send out new grid status when
  // 1. column's order/width/visibility changed
  // 2. sort info changed
  onStatusChange: PropTypes.func,
  onCheckAll: PropTypes.func,
  onCheck: PropTypes.func,
  selectedIds: PropTypes.array,
  idProperty: PropTypes.string,
  wrapperClassName: PropTypes.string, // div wrapper className
  emptyText: PropTypes.string, // set empty text
  scrollbarSize: PropTypes.number, // set vertical scroll bar width
  rowHeight: PropTypes.number,
  columnMinWidth: PropTypes.number,
  paginationClassName: PropTypes.string
};

DataTable.defaultProps = {
  selectable: true, // Set to true to add select all column
  focusable: true, // Set to true to selected the column
  resizableColumns: true, // Columns can be resized
  pager: 'top', // Set default pager position is top right.
  style: {
    height: 300
  },
  wrapperClassName: '',
  idProperty: 'id',
  emptyText: 'No records',
  scrollbarSize: 20,
  rowHeight: 30,
  columnMinWidth: 50
};

DataTable.Pagination = Pagination;

export default DataTable;


text:
package akin.lang.nodes;

import akin.lang.*;

public class InstanceVariableAssignNode extends Node {
  private String name;
  private Node expression;

  public InstanceVariableAssignNode(String name, Node expression) {
    this.name = name;
    this.expression = expression;
  }

  public AkinObject eval(Context context) throws AkinException {
    AkinObject value = expression.eval(context);
    context.getCurrentSelf().setInstanceVariable(name, value);
    return value;
  }
}


text:
var child_process = require('child_process');

module.exports = {
	enabled: false,
	useBreak: false,

	port: 5859,

	hookChild: function(module, name, internals) {
		var me = this;
		var original, replacement;

		original = module[name];
		replacement = function() {
			if (me.enabled) {
				return internals.call(this, original, arguments);
			}
			else {
				return original.apply(this, arguments);
			}
		};

		module[name] = replacement;
	},

	/**
	 * Monkey-patch `fork` function to enable debugging on child processes.
	 */
	hookChildren: function() {
		var me = this;

		this.hookChild(
			child_process,
			'fork',
			function(original, forkArgs) {
				var module = forkArgs[0];
				var args = forkArgs[1];
				var options = forkArgs[2];

				if (util.isArray(args)) {
					options = util._extend({}, options);
				}
				else {
					options = util._extend({}, args);
					args = [];
				}

				options.execArgv = options.execArgv || [];
				me.addDebugArg(options.execArgv, module);

				return original.call(this, module, args, options);
			}
		);
	},

	/**
	 * Monkey-patch grunt `spawn` function to enable debugging on child processes.
	 */
	hookGrunt: function(grunt) {
		var me = this;

		this.hookChild(
			grunt.util,
			'spawn',
			function(original, spawnArgs) {
				var options = spawnArgs[0];
				var callback = spawnArgs[1];

				if (options.cmd === process.argv[0]) {
					var module;

					for (var i = 0; i < options.args.length; i++) {
						if (options.args[i].lastIndexOf('--') != 0) {
							module = options.args[i];
							break;
						}
					}

					me.addDebugArg(options.args, module);
				}

				return original.call(this, options, callback);
			}
		);
	},

	addDebugArg: function(array, module) {
		if (this.callback) {
			this.callback(module, this.port);
		}

		var arg =
			'--debug'
			+ (this.useBreak ? '-brk' : '')
			+ '='
			+ (this.port++);

		// If a previous debug parameter is included, replace it
		for (var i = 0; i < array.length; i++) {
			if (array[i].lastIndexOf('--debug') == 0) {
				array[i] = arg;
				return;
			}
		}

		// Otherwise, include it at the beginning
		array.unshift(arg);
	},

	enableHooks: function(brk, callback) {
		this.enabled = true;
		this.useBreak = brk;
		this.callback = callback;
	}
};


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.AzureMarkdownRewriters
{
    using System.IO;
    using System.Text.RegularExpressions;

    using Microsoft.DocAsCode.Common;
    using Microsoft.DocAsCode.MarkdownLite;
    using Microsoft.DocAsCode.Utility;

    public class AzureIncludeBlockRule : IMarkdownRule
    {
        public virtual string Name => "AZURE.INCLUDE.BLOCK";

        private static readonly Regex _azureIncludeRegex = new Regex(@"^\[AZURE.INCLUDE\s*\[((?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*)\]\(\s*<?([^)]*?)>?(?:\s+(['""])([\s\S]*?)\3)?\s*\)\]\s*(\n|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        public virtual Regex AzureIncludeRegex => _azureIncludeRegex;

        public IMarkdownToken TryMatch(IMarkdownParser engine, ref string source)
        {
            var match = AzureIncludeRegex.Match(source);
            if (match.Length == 0)
            {
                return null;
            }
            source = source.Substring(match.Length);

            // [!azure.include[title](path "optionalTitle")]
            // 1. Get include file path
            var path = match.Groups[2].Value;

            // 2. Get title
            var value = match.Groups[1].Value;
            var title = match.Groups[4].Value;

            if (!PathUtility.IsRelativePath(path))
            {
                Logger.LogWarning($"Azure inline include path {path} is not a relative path, can't expand it");
                return new MarkdownTextToken(this, engine.Context, match.Value, match.Value);
            }

            object currentFilePath;
            if (!engine.Context.Variables.TryGetValue("path", out currentFilePath))
            {
                Logger.LogWarning($"Can't get path for the file that ref azure block include file, return MarkdownTextToken. Raw: {match.Value}");
                return new MarkdownTextToken(this, engine.Context, match.Value, match.Value);
            }

            var includeFilePath = PathUtility.NormalizePath(Path.Combine(Path.GetDirectoryName(currentFilePath.ToString()), path));
            if (!File.Exists(includeFilePath))
            {
                Logger.LogWarning($"Can't get include file path {includeFilePath} in the file {currentFilePath}, return MarkdownTextToken. Raw: {match.Value}");
                return new MarkdownTextToken(this, engine.Context, match.Value, match.Value);
            }

            return new TwoPhaseBlockToken(this, engine.Context, match.Value, (p, t) =>
            {
                var blockTokens = p.Tokenize(MarkdownEngine.Normalize(File.ReadAllText(includeFilePath)));
                blockTokens = TokenHelper.ParseInlineToken(p, t.Rule, blockTokens, true);
                return new AzureIncludeBlockToken(t.Rule, t.Context, path, value, title, blockTokens, match.Groups[0].Value, match.Value);
            });
        }
    }
}


text:
import os
from tests.beeswax.impala_beeswax import ImpalaBeeswaxException
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
from tests.common.impala_cluster import ImpalaCluster
from tests.common.skip import SkipIfS3
from tests.util.filesystem_utils import get_fs_path, IS_S3
from subprocess import call

class TestUdfs(ImpalaTestSuite):
  @classmethod
  def get_workload(cls):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestUdfs, cls).add_test_dimensions()
    # Without limiting the test suite to a single exec option, the tests will fail
    # because the same test case may be executed in parallel with different exec option
    # values leading to conflicting DDL ops.
    cls.TestMatrix.add_dimension(create_single_exec_option_dimension())

    # There is no reason to run these tests using all dimensions.
    cls.TestMatrix.add_dimension(create_uncompressed_text_dimension(cls.get_workload()))

  def test_native_functions(self, vector):
    database = 'native_function_test'

    self.__load_functions(
      self.create_udfs_template, vector, database,
      get_fs_path('/test-warehouse/libTestUdfs.so'))
    self.__load_functions(
      self.create_sample_udas_template, vector, database,
      get_fs_path('/test-warehouse/libudasample.so'))
    self.__load_functions(
      self.create_test_udas_template, vector, database,
      get_fs_path('/test-warehouse/libTestUdas.so'))

    self.run_test_case('QueryTest/udf', vector, use_db=database)
    if not IS_S3: # S3 doesn't support INSERT
      self.run_test_case('QueryTest/udf-init-close', vector, use_db=database)
    self.run_test_case('QueryTest/uda', vector, use_db=database)

  def test_ir_functions(self, vector):
    database = 'ir_function_test'
    self.__load_functions(
      self.create_udfs_template, vector, database,
      get_fs_path('/test-warehouse/test-udfs.ll'))
    self.run_test_case('QueryTest/udf', vector, use_db=database)
    if not IS_S3: # S3 doesn't support INSERT
      self.run_test_case('QueryTest/udf-init-close', vector, use_db=database)

  def test_udf_errors(self, vector):
    self.run_test_case('QueryTest/udf-errors', vector)

  def test_udf_invalid_symbol(self, vector):
    """ IMPALA-1642: Impala crashes if the symbol for a Hive UDF doesn't exist
        Crashing is non-deterministic so we run the UDF several times."""
    drop_fn_stmt = "drop function if exists default.fn_invalid_symbol(STRING)"
    create_fn_stmt = ("create function default.fn_invalid_symbol(STRING) returns "
        "STRING LOCATION '%s' SYMBOL='not.a.Symbol'" %
        get_fs_path('/test-warehouse/impala-hive-udfs.jar'))
    query = "select default.fn_invalid_symbol('test')"

    self.client.execute(drop_fn_stmt)
    try:
      self.client.execute(create_fn_stmt)
      for _ in xrange(5):
        ex = self.execute_query_expect_failure(self.client, query)
        assert "Unable to find class" in str(ex)
    finally:
      self.client.execute(drop_fn_stmt)

  def test_hive_udfs(self, vector):
    #self.client.execute('create database if not exists udf_test')
    #self.client.execute('create database if not exists uda_test')
    self.run_test_case('QueryTest/load-hive-udfs', vector)
    self.run_test_case('QueryTest/hive-udf', vector)

  def test_libs_with_same_filenames(self, vector):
    self.run_test_case('QueryTest/libs_with_same_filenames', vector)

  def test_udf_update_via_drop(self, vector):
    """Test updating the UDF binary without restarting Impala. Dropping
    the function should remove the binary from the local cache."""
    # Run with sync_ddl to guarantee the drop is processed by all impalads.
    exec_options = vector.get_value('exec_option')
    exec_options['sync_ddl'] = 1
    old_udf = os.path.join(os.environ['IMPALA_HOME'],
        'testdata/udfs/impala-hive-udfs.jar')
    new_udf = os.path.join(os.environ['IMPALA_HOME'],
        'tests/test-hive-udfs/target/test-hive-udfs-1.0.jar')
    udf_dst = get_fs_path('/test-warehouse/impala-hive-udfs2.jar')

    drop_fn_stmt = 'drop function if exists default.udf_update_test_drop()'
    create_fn_stmt = "create function default.udf_update_test_drop() returns string "\
        "LOCATION '" + udf_dst + "' SYMBOL='com.cloudera.impala.TestUpdateUdf'"
    query_stmt = "select default.udf_update_test_drop()"

    # Put the old UDF binary on HDFS, make the UDF in Impala and run it.
    call(["hadoop", "fs", "-put", "-f", old_udf, udf_dst])
    self.execute_query_expect_success(self.client, drop_fn_stmt, exec_options)
    self.execute_query_expect_success(self.client, create_fn_stmt, exec_options)
    self.__run_query_all_impalads(exec_options, query_stmt, ["Old UDF"])

    # Update the binary, drop and create the function again. The new binary should
    # be running.
    call(["hadoop", "fs", "-put", "-f", new_udf, udf_dst])
    self.execute_query_expect_success(self.client, drop_fn_stmt, exec_options)
    self.execute_query_expect_success(self.client, create_fn_stmt, exec_options)
    self.__run_query_all_impalads(exec_options, query_stmt, ["New UDF"])

  def test_udf_update_via_create(self, vector):
    """Test updating the UDF binary without restarting Impala. Creating a new function
    from the library should refresh the cache."""
    # Run with sync_ddl to guarantee the create is processed by all impalads.
    exec_options = vector.get_value('exec_option')
    exec_options['sync_ddl'] = 1
    old_udf = os.path.join(os.environ['IMPALA_HOME'],
        'testdata/udfs/impala-hive-udfs.jar')
    new_udf = os.path.join(os.environ['IMPALA_HOME'],
        'tests/test-hive-udfs/target/test-hive-udfs-1.0.jar')
    udf_dst = get_fs_path('/test-warehouse/impala-hive-udfs3.jar')
    old_function_name = "udf_update_test_create1"
    new_function_name = "udf_update_test_create2"

    drop_fn_template = 'drop function if exists default.%s()'
    self.execute_query_expect_success(
      self.client, drop_fn_template % old_function_name, exec_options)
    self.execute_query_expect_success(
      self.client, drop_fn_template % new_function_name, exec_options)

    create_fn_template = "create function default.%s() returns string "\
        "LOCATION '" + udf_dst + "' SYMBOL='com.cloudera.impala.TestUpdateUdf'"
    query_template = "select default.%s()"

    # Put the old UDF binary on HDFS, make the UDF in Impala and run it.
    call(["hadoop", "fs", "-put", "-f", old_udf, udf_dst])
    self.execute_query_expect_success(
      self.client, create_fn_template % old_function_name, exec_options)
    self.__run_query_all_impalads(
      exec_options, query_template % old_function_name, ["Old UDF"])

    # Update the binary, and create a new function using the binary. The new binary
    # should be running.
    call(["hadoop", "fs", "-put", "-f", new_udf, udf_dst])
    self.execute_query_expect_success(
      self.client, create_fn_template % new_function_name, exec_options)
    self.__run_query_all_impalads(
      exec_options, query_template % new_function_name, ["New UDF"])

    # The old function should use the new library now
    self.__run_query_all_impalads(
      exec_options, query_template % old_function_name, ["New UDF"])

  def test_drop_function_while_running(self, vector):
    self.client.execute("drop function if exists default.drop_while_running(BIGINT)")
    self.client.execute("create function default.drop_while_running(BIGINT) returns "\
        "BIGINT LOCATION '%s' SYMBOL='Identity'" %
        get_fs_path('/test-warehouse/libTestUdfs.so'))
    query = \
        "select default.drop_while_running(l_orderkey) from tpch.lineitem limit 10000";

    # Run this query asynchronously.
    handle = self.execute_query_async(query, vector.get_value('exec_option'),
                                      table_format=vector.get_value('table_format'))

    # Fetch some rows from the async query to make sure the UDF is being used
    results = self.client.fetch(query, handle, 1)
    assert results.success
    assert len(results.data) == 1

    # Drop the function while the original query is running.
    self.client.execute("drop function default.drop_while_running(BIGINT)")

    # Fetch the rest of the rows, this should still be able to run the UDF
    results = self.client.fetch(query, handle, -1)
    assert results.success
    assert len(results.data) == 9999

  # Run serially because this will blow the process limit, potentially causing other
  # queries to fail
  @pytest.mark.execute_serially
  def test_mem_limits(self, vector):
    # Set the mem limit high enough that a simple scan can run
    mem_limit = 1024 * 1024
    vector.get_value('exec_option')['mem_limit'] = mem_limit

    try:
      self.run_test_case('QueryTest/udf-mem-limit', vector)
      assert False, "Query was expected to fail"
    except ImpalaBeeswaxException, e:
      self.__check_exception(e)

    try:
      self.run_test_case('QueryTest/uda-mem-limit', vector)
      assert False, "Query was expected to fail"
    except ImpalaBeeswaxException, e:
      self.__check_exception(e)

  def __check_exception(self, e):
    # The interesting exception message may be in 'e' or in its inner_exception
    # depending on the point of query failure.
    if 'Memory limit exceeded' in str(e) or 'Cancelled' in str(e):
      return
    if e.inner_exception is not None\
       and ('Memory limit exceeded' in e.inner_exception.message
            or 'Cancelled' not in e.inner_exception.message):
      return
    raise e

  def __run_query_all_impalads(self, exec_options, query, expected):
    impala_cluster = ImpalaCluster()
    for impalad in impala_cluster.impalads:
      client = impalad.service.create_beeswax_client()
      result = self.execute_query_expect_success(client, query, exec_options)
      assert result.data == expected

  def __load_functions(self, template, vector, database, location):
    queries = template.format(database=database, location=location)
    # Split queries and remove empty lines
    queries = [q for q in queries.split(';') if q.strip()]
    exec_options = vector.get_value('exec_option')
    for query in queries:
      if query.strip() == '': continue
      result = self.execute_query_expect_success(self.client, query, exec_options)
      assert result is not None

  # Create sample UDA functions in {database} from library {location}
  create_sample_udas_template = """
drop function if exists {database}.test_count(int);
drop function if exists {database}.hll(int);
drop function if exists {database}.sum_small_decimal(decimal(9,2));

create database if not exists {database};

create aggregate function {database}.test_count(int) returns bigint
location '{location}' update_fn='CountUpdate';

create aggregate function {database}.hll(int) returns string
location '{location}' update_fn='HllUpdate';

create aggregate function {database}.sum_small_decimal(decimal(9,2))
returns decimal(9,2) location '{location}' update_fn='SumSmallDecimalUpdate';
"""

  # Create test UDA functions in {database} from library {location}
  create_test_udas_template = """
drop function if exists {database}.trunc_sum(double);

create database if not exists {database};

create aggregate function {database}.trunc_sum(double)
returns bigint intermediate double location '{location}'
update_fn='TruncSumUpdate' merge_fn='TruncSumMerge'
serialize_fn='TruncSumSerialize' finalize_fn='TruncSumFinalize';
"""

  # Create test UDF functions in {database} from library {location}
  create_udfs_template = """
drop function if exists {database}.identity(boolean);
drop function if exists {database}.identity(tinyint);
drop function if exists {database}.identity(smallint);
drop function if exists {database}.identity(int);
drop function if exists {database}.identity(bigint);
drop function if exists {database}.identity(float);
drop function if exists {database}.identity(double);
drop function if exists {database}.identity(string);
drop function if exists {database}.identity(timestamp);
drop function if exists {database}.identity(decimal(9,0));
drop function if exists {database}.identity(decimal(18,1));
drop function if exists {database}.identity(decimal(38,10));
drop function if exists {database}.all_types_fn(
    string, boolean, tinyint, smallint, int, bigint, float, double, decimal(2,0));
drop function if exists {database}.no_args();
drop function if exists {database}.var_and(boolean...);
drop function if exists {database}.var_sum(int...);
drop function if exists {database}.var_sum(double...);
drop function if exists {database}.var_sum(string...);
drop function if exists {database}.var_sum(decimal(4,2)...);
drop function if exists {database}.var_sum_multiply(double, int...);
drop function if exists {database}.constant_timestamp();
drop function if exists {database}.validate_arg_type(string);
drop function if exists {database}.count_rows();
drop function if exists {database}.constant_arg(int);
drop function if exists {database}.validate_open(int);
drop function if exists {database}.mem_test(bigint);
drop function if exists {database}.mem_test_leaks(bigint);
drop function if exists {database}.unmangled_symbol();
drop function if exists {database}.four_args(int, int, int, int);
drop function if exists {database}.five_args(int, int, int, int, int);
drop function if exists {database}.six_args(int, int, int, int, int, int);
drop function if exists {database}.seven_args(int, int, int, int, int, int, int);
drop function if exists {database}.eight_args(int, int, int, int, int, int, int, int);

create database if not exists {database};

create function {database}.identity(boolean) returns boolean
location '{location}' symbol='Identity';

create function {database}.identity(tinyint) returns tinyint
location '{location}' symbol='Identity';

create function {database}.identity(smallint) returns smallint
location '{location}' symbol='Identity';

create function {database}.identity(int) returns int
location '{location}' symbol='Identity';

create function {database}.identity(bigint) returns bigint
location '{location}' symbol='Identity';

create function {database}.identity(float) returns float
location '{location}' symbol='Identity';

create function {database}.identity(double) returns double
location '{location}' symbol='Identity';

create function {database}.identity(string) returns string
location '{location}'
symbol='_Z8IdentityPN10impala_udf15FunctionContextERKNS_9StringValE';

create function {database}.identity(timestamp) returns timestamp
location '{location}'
symbol='_Z8IdentityPN10impala_udf15FunctionContextERKNS_12TimestampValE';

create function {database}.identity(decimal(9,0)) returns decimal(9,0)
location '{location}'
symbol='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10DecimalValE';

create function {database}.identity(decimal(18,1)) returns decimal(18,1)
location '{location}'
symbol='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10DecimalValE';

create function {database}.identity(decimal(38,10)) returns decimal(38,10)
location '{location}'
symbol='_Z8IdentityPN10impala_udf15FunctionContextERKNS_10DecimalValE';

create function {database}.all_types_fn(
    string, boolean, tinyint, smallint, int, bigint, float, double, decimal(2,0))
returns int
location '{location}' symbol='AllTypes';

create function {database}.no_args() returns string
location '{location}'
symbol='_Z6NoArgsPN10impala_udf15FunctionContextE';

create function {database}.var_and(boolean...) returns boolean
location '{location}' symbol='VarAnd';

create function {database}.var_sum(int...) returns int
location '{location}' symbol='VarSum';

create function {database}.var_sum(double...) returns double
location '{location}' symbol='VarSum';

create function {database}.var_sum(string...) returns int
location '{location}' symbol='VarSum';

create function {database}.var_sum(decimal(4,2)...) returns decimal(18,2)
location '{location}' symbol='VarSum';

create function {database}.var_sum_multiply(double, int...) returns double
location '{location}'
symbol='_Z14VarSumMultiplyPN10impala_udf15FunctionContextERKNS_9DoubleValEiPKNS_6IntValE';

create function {database}.constant_timestamp() returns timestamp
location '{location}' symbol='ConstantTimestamp';

create function {database}.validate_arg_type(string) returns boolean
location '{location}' symbol='ValidateArgType';

create function {database}.count_rows() returns bigint
location '{location}' symbol='Count' prepare_fn='CountPrepare' close_fn='CountClose';

create function {database}.constant_arg(int) returns int
location '{location}' symbol='ConstantArg' prepare_fn='ConstantArgPrepare' close_fn='ConstantArgClose';

create function {database}.validate_open(int) returns boolean
location '{location}' symbol='ValidateOpen'
prepare_fn='ValidateOpenPrepare' close_fn='ValidateOpenClose';

create function {database}.mem_test(bigint) returns bigint
location '{location}' symbol='MemTest'
prepare_fn='MemTestPrepare' close_fn='MemTestClose';

create function {database}.mem_test_leaks(bigint) returns bigint
location '{location}' symbol='MemTest'
prepare_fn='MemTestPrepare';

-- Regression test for IMPALA-1475
create function {database}.unmangled_symbol() returns bigint
location '{location}' symbol='UnmangledSymbol';

create function {database}.four_args(int, int, int, int) returns int
location '{location}' symbol='FourArgs';

create function {database}.five_args(int, int, int, int, int) returns int
location '{location}' symbol='FiveArgs';

create function {database}.six_args(int, int, int, int, int, int) returns int
location '{location}' symbol='SixArgs';

create function {database}.seven_args(int, int, int, int, int, int, int) returns int
location '{location}' symbol='SevenArgs';

create function {database}.eight_args(int, int, int, int, int, int, int, int) returns int
location '{location}' symbol='EightArgs';
"""


text: from .autoh2o import *


text:
<?php
/**
 * Created by PhpStorm.
 * User: Samuel
 * Date: 31/05/2015
 * Time: 21:28
 */

namespace Samcrosoft\Placeholder;

/**
 * Class Placeholder
 * @package Samcrosoft\Placeholder
 */
class Placeholder
{
    const DEFAULT_BACKGROUND_COLOR = '#333';
    const DEFAULT_FOREGROUND_COLOR = '#FFF';
    const DEFAULT_FONT_SIZE = 10;

    const DEFAULT_IMAGE_WIDTH = 100;
    const DEFAULT_IMAGE_HEIGHT = 100;

    const IMAGE_PNG_TYPE = 0x1;
    const IMAGE_JPG_TYPE = 0x2;

    /**
     * Generate a placeholder using the query string parameters
     * @return resource
     */
    public function makePlaceholderFromURL(){
        $oURLResolver = new UrlResolver();
        return $this->makePlaceHolder($oURLResolver->getWidthValue(), $oURLResolver->getHeightValue(),
        $oURLResolver->getText(), $oURLResolver->getBackgroundColor(), $oURLResolver->getForegroundColor());
    }

    /**
     * This will create a typed image and echo it out to the browser, the image content cant be trapped using
     * output buffering
     * @param int $iImageType
     */
    public function makeTypedPlaceHolderFromURL($iImageType = self::IMAGE_PNG_TYPE)
    {
        $oImage = $this->makePlaceholderFromURL();
        switch($iImageType){
            case self::IMAGE_JPG_TYPE:
                imagepng($oImage);
                break;
            case self::IMAGE_PNG_TYPE:
            default:
                imagejpeg($oImage);
                break;
        }

        imagedestroy($oImage);
    }

    /**
     * This is just an alias for placeholder from url with IMAGE_JPG_TYPE
     */
    public function makeJpegImageFromURL()
    {
        $this->makeTypedPlaceHolderFromURL(self::IMAGE_JPG_TYPE);
    }

    /**
     * This is just an alias for the default make placeholder from url method
     */
    public function makePngImageFromURL(){
        $this->makeTypedPlaceHolderFromURL();
    }

    /**
     * @param int $iWidth
     * @param int $iHeight
     * @param $sText
     * @param string $sBackColor
     * @param string $sForeColor
     * @return resource
     */
    protected function makePlaceHolder($iWidth = self::DEFAULT_IMAGE_WIDTH, $iHeight = self::DEFAULT_IMAGE_HEIGHT,
                                    $sText, $sBackColor = self::DEFAULT_BACKGROUND_COLOR,
                                    $sForeColor = self::DEFAULT_FOREGROUND_COLOR)
    {
        // make the image
        $oImage = $this->getImage($iWidth, $iHeight);
        // add color to the image
        $aColorifyValues = $this->colorifyImage($oImage, $sBackColor, $sForeColor);
        // add text to the image
        $aForeColorInt = $aColorifyValues[0];
        $this->textifyImage($oImage, $sText, $aForeColorInt);
        return $oImage;
    }

    /**
     * @param int $iWidth
     * @param int $iHeight
     * @return resource
     */
    private function getImage($iWidth = 100, $iHeight = 100)
    {
        $oImage = imagecreate($iWidth, $iHeight);
        return $oImage;
    }

    /**
     * @param resource $oImage
     * @param string $sBkColor
     * @param string $sFgColor
     * @return array
     */
    private function colorifyImage(&$oImage, $sBkColor = self::DEFAULT_BACKGROUND_COLOR,
                                   $sFgColor = self::DEFAULT_FOREGROUND_COLOR)
    {
        /*
         * Implement the background
         */
        $aBackColor = $this->hex2rgb($sBkColor);
        list($iRed, $iGreen, $iBlue) = $aBackColor;
        $aBackColorInt = imagecolorallocate($oImage, $iRed, $iGreen, $iBlue);

        /*
         * Implement the foreground for text
         */
        $aForegroundColor = $this->hex2rgb($sFgColor);
        list($iRed2, $iGreen2, $iBlue2) = $aForegroundColor;
        $aForeColorInt = imagecolorallocate($oImage, $iRed2, $iGreen2, $iBlue2);

        return [$aForeColorInt, $aBackColorInt];
    }

    /**
     * Simple helper class to get the RGB values from a hex string
     * @param $hex
     * @return array
     */
    private function hex2rgb($hex)
    {
        $hex = str_replace("#", "", $hex);

        if (strlen($hex) == 3) {
            $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
            $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
            $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
        } else {
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, self::DEFAULT_FONT_SIZE, 2));
        }
        $aRGB = [$r, $g, $b];
        return $aRGB;
    }

    /**
     * This method will add text to the image
     * @param resource $oImage
     * @param string $sText
     * @param $aForeColorInt
     */
    protected function textifyImage(&$oImage, $sText, $aForeColorInt)
    {
        /*
         * Calculate the text positioning
         */
        $iFontSize = self::DEFAULT_FONT_SIZE;
        $iFontWidth = imagefontwidth($iFontSize);
        $iFontHeight = imagefontheight($iFontSize);
        $length = strlen($sText);
        $fTextWidth = $length * $iFontWidth;
        $fxPos = (imagesx($oImage) - $fTextWidth) / 2;
        $fyPos = (imagesy($oImage) - $iFontHeight) / 2;

        // Generate text
        imagestring($oImage, $iFontSize, $fxPos, $fyPos, $sText, $aForeColorInt);
    }
}


text:
import { visualizationLoaderProvider } from 'plugins/kibana/dashboard/components/panel/lib/visualization';
import { searchLoaderProvider } from 'plugins/kibana/dashboard/components/panel/lib/search';

export function loadPanelProvider(Private) { // Inject services here
  return function (panel, $scope) { // Function parameters here
    const panelTypes = {
      visualization: Private(visualizationLoaderProvider),
      search: Private(searchLoaderProvider)
    };

    try {
      return panelTypes[panel.type](panel, $scope);
    } catch (e) {
      throw new Error('Loader not found for unknown panel type: ' + panel.type);
    }

  };
};


text:
<?php

class PercentComplete {

    protected static $instance = null;

    /**
     * @var array
     */
    protected $items = array();

    private function __construct() {
    }

    /**
     * Singleton implementation
     * @return PercentComplete
     */
    public static function getInstance() {
        if ( self::$instance == null ) {
            self::$instance = new PercentComplete();
        }

        return self::$instance;
    }

    /**
     * Registers an Item
     *
     * @param ITodoItem $item
     *
     * @return $this
     */
    public function register( ITodoItem $item ) {
        // completed items go to the beginning
        $function = 'array_push';
        if ( $item->isComplete() ) {
            $function = 'array_unshift';
        }
        $function( $this->items, $item );

        return $this;
    }

    /**
     * @return ITodoItem[]
     */
    public function getItems() {
        return $this->items;
    }

    /**
     * Returns the % number of completed elements. Ex.: 0.8
     * @return float
     */
    public function getPercentComplete() {
        $completed = 0;
        foreach ( $this->getItems() as $item ) {
            /* @var $item ITodoItem */
            if ( $item->isComplete() ) {
                $completed = $completed + 1;
            }
        }

        return $completed / count( $this->getItems() );
    }

}


text:
package net.openhft.chronicle.map.fromdocs.acid.revelations;

import net.openhft.chronicle.map.ChronicleMap;
import net.openhft.chronicle.map.ChronicleMapBuilder;
import net.openhft.chronicle.map.fromdocs.BondVOInterface;

import java.io.File;
import java.io.IOException;

public class DirtyReadTolerance<K, V> {

    public static void main(String[] args) throws Exception {
        System.out.println("DirtyReadOffender,chrAig[" + args[0] + "]coupon=3.50,DirtyReadVictim");
        String isoLevel = args[0];

        ChronicleMap<String, BondVOInterface> chm =
                DirtyReadTolerance.offHeap(
                        args[2]
                                + "OPERAND_CHRONICLE_MAP"
                );
        System.out.println(",Established chm,");
    }

    static ChronicleMap<String, BondVOInterface> offHeap(String operand) throws IOException {

        return ChronicleMapBuilder.of(String.class, BondVOInterface.class)
                .entries(16)
                .averageKeySize("123456789".length())
                .createPersistedTo(
                        new File(
                                operand
                                //  "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP"
                        )
                );
        //.create();
    }
}