text:
#ifndef BOOST_MULTI_INDEX_DETAIL_ITER_ADAPTOR_HPP
#define BOOST_MULTI_INDEX_DETAIL_ITER_ADAPTOR_HPP

#if defined(_MSC_VER)&&(_MSC_VER>=1200)
#pragma once
#endif

#include <lslboost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <lslboost/mpl/apply.hpp>
#include <lslboost/multi_index/detail/prevent_eti.hpp>
#include <lslboost/operators.hpp>

namespace lslboost{

namespace multi_index{

namespace detail{

/* Poor man's version of lslboost::iterator_adaptor. Used instead of the
 * original as compile times for the latter are significantly higher.
 * The interface is not replicated exactly, only to the extent necessary
 * for internal consumption.
 */

/* NB. The purpose of the (non-inclass) global operators ==, < and - defined
 * above is to partially alleviate a problem of MSVC++ 6.0 by * which
 * friend-injected operators on T are not visible if T is instantiated only
 * in template code where T is a dependent type.
 */

class iter_adaptor_access
{
public:
  template<class Class>
    static typename Class::reference dereference(const Class& x)
  {
    return x.dereference();
  }

  template<class Class>
  static bool equal(const Class& x,const Class& y)
  {
    return x.equal(y);
  }

  template<class Class>
  static void increment(Class& x)
  {
    x.increment();
  }

  template<class Class>
  static void decrement(Class& x)
  {
    x.decrement();
  }

  template<class Class>
  static void advance(Class& x,typename Class::difference_type n)
  {
    x.advance(n);
  }

  template<class Class>
  static typename Class::difference_type distance_to(
    const Class& x,const Class& y)
  {
    return x.distance_to(y);
  }
};

template<typename Category>
struct iter_adaptor_selector;

template<class Derived,class Base>
class forward_iter_adaptor_base:
  public forward_iterator_helper<
    Derived,
    typename Base::value_type,
    typename Base::difference_type,
    typename Base::pointer,
    typename Base::reference>
{
public:
  typedef typename Base::reference reference;

  reference operator*()const
  {
    return iter_adaptor_access::dereference(final());
  }

  friend bool operator==(const Derived& x,const Derived& y)
  {
    return iter_adaptor_access::equal(x,y);
  }

  Derived& operator++()
  {
    iter_adaptor_access::increment(final());
    return final();
  }

private:
  Derived& final(){return *static_cast<Derived*>(this);}
  const Derived& final()const{return *static_cast<const Derived*>(this);}
};

template<class Derived,class Base>
bool operator==(
  const forward_iter_adaptor_base<Derived,Base>& x,
  const forward_iter_adaptor_base<Derived,Base>& y)
{
  return iter_adaptor_access::equal(
    static_cast<const Derived&>(x),static_cast<const Derived&>(y));
}

template<>
struct iter_adaptor_selector<std::forward_iterator_tag>
{
  template<class Derived,class Base>
  struct apply
  {
    typedef forward_iter_adaptor_base<Derived,Base> type;
  };
};

template<class Derived,class Base>
class bidirectional_iter_adaptor_base:
  public bidirectional_iterator_helper<
    Derived,
    typename Base::value_type,
    typename Base::difference_type,
    typename Base::pointer,
    typename Base::reference>
{
public:
  typedef typename Base::reference reference;

  reference operator*()const
  {
    return iter_adaptor_access::dereference(final());
  }

  friend bool operator==(const Derived& x,const Derived& y)
  {
    return iter_adaptor_access::equal(x,y);
  }

  Derived& operator++()
  {
    iter_adaptor_access::increment(final());
    return final();
  }

  Derived& operator--()
  {
    iter_adaptor_access::decrement(final());
    return final();
  }

private:
  Derived& final(){return *static_cast<Derived*>(this);}
  const Derived& final()const{return *static_cast<const Derived*>(this);}
};

template<class Derived,class Base>
bool operator==(
  const bidirectional_iter_adaptor_base<Derived,Base>& x,
  const bidirectional_iter_adaptor_base<Derived,Base>& y)
{
  return iter_adaptor_access::equal(
    static_cast<const Derived&>(x),static_cast<const Derived&>(y));
}

template<>
struct iter_adaptor_selector<std::bidirectional_iterator_tag>
{
  template<class Derived,class Base>
  struct apply
  {
    typedef bidirectional_iter_adaptor_base<Derived,Base> type;
  };
};

template<class Derived,class Base>
class random_access_iter_adaptor_base:
  public random_access_iterator_helper<
    Derived,
    typename Base::value_type,
    typename Base::difference_type,
    typename Base::pointer,
    typename Base::reference>
{
public:
  typedef typename Base::reference       reference;
  typedef typename Base::difference_type difference_type;

  reference operator*()const
  {
    return iter_adaptor_access::dereference(final());
  }

  friend bool operator==(const Derived& x,const Derived& y)
  {
    return iter_adaptor_access::equal(x,y);
  }

  friend bool operator<(const Derived& x,const Derived& y)
  {
    return iter_adaptor_access::distance_to(x,y)>0;
  }

  Derived& operator++()
  {
    iter_adaptor_access::increment(final());
    return final();
  }

  Derived& operator--()
  {
    iter_adaptor_access::decrement(final());
    return final();
  }

  Derived& operator+=(difference_type n)
  {
    iter_adaptor_access::advance(final(),n);
    return final();
  }

  Derived& operator-=(difference_type n)
  {
    iter_adaptor_access::advance(final(),-n);
    return final();
  }

  friend difference_type operator-(const Derived& x,const Derived& y)
  {
    return iter_adaptor_access::distance_to(y,x);
  }

private:
  Derived& final(){return *static_cast<Derived*>(this);}
  const Derived& final()const{return *static_cast<const Derived*>(this);}
};

template<class Derived,class Base>
bool operator==(
  const random_access_iter_adaptor_base<Derived,Base>& x,
  const random_access_iter_adaptor_base<Derived,Base>& y)
{
  return iter_adaptor_access::equal(
    static_cast<const Derived&>(x),static_cast<const Derived&>(y));
}

template<class Derived,class Base>
bool operator<(
  const random_access_iter_adaptor_base<Derived,Base>& x,
  const random_access_iter_adaptor_base<Derived,Base>& y)
{
  return iter_adaptor_access::distance_to(
    static_cast<const Derived&>(x),static_cast<const Derived&>(y))>0;
}

template<class Derived,class Base>
typename random_access_iter_adaptor_base<Derived,Base>::difference_type
operator-(
  const random_access_iter_adaptor_base<Derived,Base>& x,
  const random_access_iter_adaptor_base<Derived,Base>& y)
{
  return iter_adaptor_access::distance_to(
    static_cast<const Derived&>(y),static_cast<const Derived&>(x));
}

template<>
struct iter_adaptor_selector<std::random_access_iterator_tag>
{
  template<class Derived,class Base>
  struct apply
  {
    typedef random_access_iter_adaptor_base<Derived,Base> type;
  };
};

template<class Derived,class Base>
struct iter_adaptor_base
{
  typedef iter_adaptor_selector<
    typename Base::iterator_category>        selector;
  typedef typename prevent_eti<
    selector,
    typename mpl::apply2<
      selector,Derived,Base>::type
  >::type                                    type;
};

template<class Derived,class Base>
class iter_adaptor:public iter_adaptor_base<Derived,Base>::type
{
protected:
  iter_adaptor(){}
  explicit iter_adaptor(const Base& b_):b(b_){}

  const Base& base_reference()const{return b;}
  Base&       base_reference(){return b;}

private:
  Base b;
};

} /* namespace multi_index::detail */

} /* namespace multi_index */

} /* namespace lslboost */

#endif


text:
/*
Theme Name:     Line & Plan
Theme URI:      http: //lineid.com/
Description:    Child theme of mystile <http://www.woothemes.com/products/mystile/>
Author:         Meathill
Author URI:     http: //meathill.com/
Template:       mystile
Version:        0.1.0
*/

@import url(../mystile/style.css);

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 *   @file index.php
 *   @brief Browse view of records / splash screen
 *
 *   @author adarby
 *   @date Nov, 2011; last mod dec 2014
 */

use SubjectsPlus\Control\Dropdown;
use SubjectsPlus\Control\Record;
use SubjectsPlus\Control\LinkChecker;
use SubjectsPlus\Control\Querier;

$subcat = "records";
$subsubcat = "index.php";
$page_title = "Browse Items";

// init some vars
$atoz = "";
$letter = "";
$ctag = "";
$full_query = "";

include("../includes/header.php");

$db = new Querier;

// Where to start?
// Choose initial letter to display

$alpha_query = "SELECT  distinct left(title,1) as 'initial' FROM  title, restrictions, location, location_title, source where title.title_id = location_title.title_id and location.location_id = location_title.location_id and restrictions_id = access_restrictions ORDER BY initial";

$alpha_result = $db->query($alpha_query);

$count = 0;
$firstletter = "A";

foreach ($alpha_result as $myletter) {

	if (isset($myletter[0][0])) {

    if ($count == 0) { $firstletter = $myletter[0][0];}

    $atoz .=""
            . $myletter[0][0]
            . "  ";

    $count++;

	}
}

$atoz .= "[all]";

// end A-Z header for now

$results = "
" . _("Please select a letter or tag to browse.") . "
";

if (isset($_GET["ctag"])) {
    $alpha_id = $_GET["ctag"];
    $full_query = "select distinct title, description, location, restrictions_id, title.title_id as 'this_record', eres_display, ctags  from title, restrictions, location, location_title, source where title.title_id = location_title.title_id and location.location_id = location_title.location_id and restrictions_id = access_restrictions  and ctags like '%$alpha_id%' order by title.title";
} elseif (!isset($_GET['letter'])) {
    $alpha_id = $firstletter;
    $full_query = "select distinct title, description, location, restrictions_id, title.title_id as 'this_record', eres_display, ctags  from title, restrictions, location, location_title, source where title.title_id = location_title.title_id and location.location_id = location_title.location_id and restrictions_id = access_restrictions  and title like '$firstletter%' order by title.title";
    //$alpha_id = FALSE;
} elseif ($_GET['letter'] == "all") {
    $alpha_id = "All Records";
    $full_query = "select distinct title, description, location, restrictions_id, title.title_id as 'this_record', eres_display, ctags from title, restrictions, location, location_title, source where title.title_id = location_title.title_id and location.location_id = location_title.location_id and restrictions_id = access_restrictions order by title.title";
} elseif ($_GET['letter'] == "restricted") {
    $alpha_id = "Restricted Items";
    $full_query = "select distinct title, description, location, restrictions_id, title.title_id as 'this_record', eres_display, ctags from title, restrictions, location, location_title, source where title.title_id = location_title.title_id and location.location_id = location_title.location_id and restrictions_id = access_restrictions and restrictions_id != '1' order by title.title";
} elseif ($_GET['letter'] == "unrestricted") {
    $alpha_id = "Unrestricted Items";
    $full_query = "select distinct title, description, location, restrictions_id, title.title_id as 'this_record', eres_display, ctags from title, restrictions, location, location_title, source where title.title_id = location_title.title_id and location.location_id = location_title.location_id and restrictions_id = access_restrictions and restrictions_id = '1' order by title.title";
} else {
    $alpha_id = $_GET['letter'];
    //$alpha_id = FALSE;
    $full_query = "select distinct title, description, location, restrictions_id, title.title_id as 'this_record', eres_display, ctags from title, restrictions, location, location_title, source where title.title_id = location_title.title_id and location.location_id = location_title.location_id and restrictions_id = access_restrictions  and title like '$alpha_id%' order by title.title";
}

// print $full_query;

// Now we continue to make our
// gather ctags

$tag_list = "restricted
free";

// init the ctag
$selected_ctag = "";

if (isset($_GET["ctag"])) {
  $selected_ctag = $_GET["ctag"];
}

// loop through the ctags as defined in the config.php file
foreach ($all_ctags as $value) {
    if ($value == $selected_ctag) {
        $tag_class = "ctag-on";
    } else {
        $tag_class = "ctag-off";
    }

    $tag_list .= " $value";
}

// Output our header text
//print $intro;

if ($alpha_id & $full_query) {

    $full_result = $db->query($full_query);

    $row_count = 0;
    $colour1 = "oddrow";
    $colour2 = "evenrow";

    if ($full_result) {
        foreach ($full_result as $myrow) {

            $label = $myrow[0];
            $url = $myrow[2];
            $blurb = $myrow[1];
            $id = $myrow[4];

            $row_colour = ($row_count % 2) ? $colour1 : $colour2;

            // weed out extraneous P tags
            $blurb = stripP($blurb);

            $results .= "
   $label\n";

        $results .= "
\n";

            $row_count++;
        }
    }
}

// let's put it together

$letter_header_body = "
$atoz
\n

$tag_list

$alpha_id

$results

";
 $new_record_body = "

" . _("Make sure the item doesn't already exist!") . "

" . _("Create new item") . "

";
print "

  ";
makePluslet(_("Browse Records"), $letter_header_body, "no_overflow");

print "
"; // close pure-u-2-3
print "
";

makePluslet(_("New Record"), $new_record_body, "no_overflow");

print "
"; // close pure-u-1-3
print "
"; // close pure-g

include("../includes/footer.php");
?>


text: Settings Settings<caret> other


text:
package org.jsonschema2pojo.rules;

import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JDocCommentable;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;

import org.jsonschema2pojo.GenerationConfig;
import org.jsonschema2pojo.Schema;

import static org.apache.commons.lang3.StringUtils.capitalize;

/**
 * Applies the schema rules that represent a property definition.
 *
 * @see http:/
 *      /tools.ietf.org/html/draft-zyp-json-schema-03#section-5.2
 */
public class PropertyRule implements Rule<JDefinedClass, JDefinedClass> {

    private final RuleFactory ruleFactory;

    protected PropertyRule(RuleFactory ruleFactory) {
        this.ruleFactory = ruleFactory;
    }

    /**
     * Applies this schema rule to take the required code generation steps.
     *

     * This rule adds a property to a given Java class according to the Java
     * Bean spec. A private field is added to the class, along with accompanying
     * accessor methods.
     *

     * If this rule's schema mapper is configured to include builder methods
     * (see {@link GenerationConfig#isGenerateBuilders()} ),
     * then a builder method of the form withFoo(Foo foo); is also
     * added.
     *
     * @param nodeName
     *            the name of the property to be applied
     * @param node
     *            the node describing the characteristics of this property
     * @param jclass
     *            the Java class which should have this property added
     * @return the given jclass
     */
    @Override
    public JDefinedClass apply(String nodeName, JsonNode node, JDefinedClass jclass, Schema schema) {
        String propertyName = ruleFactory.getNameHelper().getPropertyName(nodeName, node);

        String pathToProperty;
        if (schema.getId() == null || schema.getId().getFragment() == null) {
            pathToProperty = "#properties/" + nodeName;
        } else {
            pathToProperty = "#" + schema.getId().getFragment() + "/properties/" + nodeName;
        }
        JType propertyType = ruleFactory.getSchemaRule().apply(nodeName, node, jclass, ruleFactory.getSchemaStore().create(schema, pathToProperty));

        node = resolveRefs(node, schema);

        int accessModifier = ruleFactory.getGenerationConfig().isIncludeAccessors() ? JMod.PRIVATE : JMod.PUBLIC;
        JFieldVar field = jclass.field(accessModifier, propertyType, propertyName);
        propertyAnnotations(nodeName, node, schema, field);

        ruleFactory.getAnnotator().propertyField(field, jclass, nodeName, node);

        if (ruleFactory.getGenerationConfig().isIncludeAccessors()) {
            JMethod getter = addGetter(jclass, field, nodeName, node);
            ruleFactory.getAnnotator().propertyGetter(getter, nodeName);
            propertyAnnotations(nodeName, node, schema, getter);

            JMethod setter = addSetter(jclass, field, nodeName, node);
            ruleFactory.getAnnotator().propertySetter(setter, nodeName);
            propertyAnnotations(nodeName, node, schema, setter);
        }

        if (ruleFactory.getGenerationConfig().isGenerateBuilders()) {
            addBuilder(jclass, field);
        }

        if (node.has("pattern")) {
            ruleFactory.getPatternRule().apply(nodeName, node.get("pattern"), field, schema);
        }

        ruleFactory.getDefaultRule().apply(nodeName, node.get("default"), field, schema);

        ruleFactory.getMinimumMaximumRule().apply(nodeName, node, field, schema);

        ruleFactory.getMinItemsMaxItemsRule().apply(nodeName, node, field, schema);

        ruleFactory.getMinLengthMaxLengthRule().apply(nodeName, node, field, schema);

        if (isObject(node) || isArray(node)) {
            ruleFactory.getValidRule().apply(nodeName, node, field, schema);
        }

        return jclass;
    }

    private void propertyAnnotations(String nodeName, JsonNode node, Schema schema, JDocCommentable generatedJavaConstruct) {
        if (node.has("title")) {
            ruleFactory.getTitleRule().apply(nodeName, node.get("title"), generatedJavaConstruct, schema);
        }

        if (node.has("javaName")) {
            ruleFactory.getJavaNameRule().apply(nodeName, node.get("javaName"), generatedJavaConstruct, schema);
        }

        if (node.has("description")) {
            ruleFactory.getDescriptionRule().apply(nodeName, node.get("description"), generatedJavaConstruct, schema);
        }

        if (node.has("required")) {
            ruleFactory.getRequiredRule().apply(nodeName, node.get("required"), generatedJavaConstruct, schema);
        }
    }

    private JsonNode resolveRefs(JsonNode node, Schema parent) {
        if (node.has("$ref")) {
            Schema refSchema = ruleFactory.getSchemaStore().create(parent, node.get("$ref").asText());
            JsonNode refNode = refSchema.getContent();
            return resolveRefs(refNode, parent);
        } else {
            return node;
        }
    }

    private boolean isObject(JsonNode node) {
        return node.path("type").asText().equals("object");
    }

    private boolean isArray(JsonNode node) {
        return node.path("type").asText().equals("array");
    }

    private JMethod addGetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node) {
        JMethod getter = c.method(JMod.PUBLIC, field.type(), getGetterName(jsonPropertyName, field.type(), node));

        // add @returns
        getter.javadoc().addReturn().append("The " + ruleFactory.getNameHelper().getPropertyName(jsonPropertyName, node));

        JBlock body = getter.body();
        body._return(field);

        return getter;
    }

    private JMethod addSetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node) {
        JMethod setter = c.method(JMod.PUBLIC, void.class, getSetterName(jsonPropertyName, node));

        // add @param
        setter.javadoc().addParam(ruleFactory.getNameHelper().getPropertyName(jsonPropertyName, node)).append("The " + jsonPropertyName);

        JVar param = setter.param(field.type(), field.name());
        JBlock body = setter.body();
        body.assign(JExpr._this().ref(field), param);

        return setter;
    }

    private JMethod addBuilder(JDefinedClass c, JFieldVar field) {
        JMethod builder = c.method(JMod.PUBLIC, c, getBuilderName(field.name()));

        JVar param = builder.param(field.type(), field.name());
        JBlock body = builder.body();
        body.assign(JExpr._this().ref(field), param);
        body._return(JExpr._this());

        return builder;
    }

    private String getBuilderName(String propertyName) {
        propertyName = ruleFactory.getNameHelper().replaceIllegalCharacters(propertyName);
        return "with" + capitalize(ruleFactory.getNameHelper().capitalizeTrailingWords(propertyName));
    }

    private String getSetterName(String propertyName, JsonNode node) {
        return ruleFactory.getNameHelper().getSetterName(propertyName, node);
    }

    private String getGetterName(String propertyName, JType type, JsonNode node) {
        return ruleFactory.getNameHelper().getGetterName(propertyName, type, node);
    }

}


text:
'use strict';

import React from 'react';
import {AppBar} from 'material-ui';

export default class MyAppBar extends React.Component {
  render() {
    return (
      <AppBar onLeftIconButtonTouchTap={() => this.props.toggle()} title="DriveSense"/>
    );
  }
}


text:
/**
 * @author Alexander Y. Kleymenov
 * @version $Revision$
 */

package org.apache.harmony.xnet.provider.jsse;

import java.io.PrintStream;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * This class provides debug logging for JSSE provider implementation
 * TODO: Use java.util.logging
 */
public class Logger {

    public static class Stream extends PrintStream {
        private final String prefix;
        private static int indent = 0;

        public Stream(String name) {
            super(System.err);
            prefix = name + "["+Thread.currentThread().getName()+"] ";
        }

        public void print(String msg) {
            for (int i=0; i<indent; i++) {
                super.print("  ");
            }
            super.print(msg);
        }

        public void newIndent() {
            indent ++;
        }

        public void endIndent() {
            indent --;
        }

        public void println(String msg) {
            print(prefix);
            super.println(msg);
        }

        public void print(byte[] data) {
            printAsHex(16, " ", "", data, 0, data.length);
        }

        public void print(byte[] data, int offset, int len) {
            printAsHex(16, " ", "", data, offset, len);
        }

        public void printAsHex(int perLine,
                String prefix,
                String delimiter,
                byte[] data) {
            printAsHex(perLine, prefix, delimiter, data, 0, data.length);
        }

        public void printAsHex(int perLine,
                String prefix,
                String delimiter,
                byte[] data, int offset, int len) {
            String line = "";
            for (int i=0; i<len; i++) {
                String tail =
                    Integer.toHexString(0x00ff & data[i+offset]).toUpperCase();
                if (tail.length() == 1) {
                    tail = "0" + tail;
                }
                line += prefix + tail + delimiter;

                if (((i+1)%perLine) == 0) {
                    super.println(line);
                    line = "";
                }
            }
            super.println(line);
        }
    }

    private static String[] names;

    static {
        try {
            names = AccessController
                    .doPrivileged(new PrivilegedAction<String[]>() {
                        public String[] run() {
                            return System.getProperty("jsse", "").split(",");
                        }
                    });
        } catch (Exception e) {
            names = new String[0];
        }
    }

    public static Stream getStream(String name) {
        for (int i=0; i<names.length; i++) {
            if (names[i].equals(name)) {
                return new Stream(name);
            }
        }
        return null;
    }
}


text:
package org.apache.sysml.parser;

import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.misc.Interval;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class Statement implements ParseInfo
{

	protected static final Log LOG = LogFactory.getLog(Statement.class.getName());

	public static final String OUTPUTSTATEMENT = "WRITE";

	// parameter names for seq()
	public static final String SEQ_FROM = "from";
	public static final String SEQ_TO   = "to";
	public static final String SEQ_INCR	= "incr";

	public static final String SOURCE  	= "source";
	public static final String SETWD 	= "setwd";

	public static final String MATRIX_DATA_TYPE = "matrix";
	public static final String FRAME_DATA_TYPE = "frame";
	public static final String SCALAR_DATA_TYPE = "scalar";

	public static final String DOUBLE_VALUE_TYPE = "double";
	public static final String BOOLEAN_VALUE_TYPE = "boolean";
	public static final String INT_VALUE_TYPE = "int";
	public static final String STRING_VALUE_TYPE = "string";

	// String constants related to Grouped Aggregate parameters
	public static final String GAGG_TARGET  = "target";
	public static final String GAGG_GROUPS  = "groups";
	public static final String GAGG_WEIGHTS = "weights";
	public static final String GAGG_FN      = "fn";
	public static final String GAGG_FN_SUM      = "sum";
	public static final String GAGG_FN_COUNT    = "count";
	public static final String GAGG_FN_MEAN     = "mean";
	public static final String GAGG_FN_VARIANCE = "variance";
	public static final String GAGG_FN_CM       = "centralmoment";
	public static final String GAGG_FN_CM_ORDER = "order";
	public static final String GAGG_NUM_GROUPS  = "ngroups";

	public abstract boolean controlStatement();

	public abstract VariableSet variablesRead();
	public abstract VariableSet variablesUpdated();

	public abstract void initializeforwardLV(VariableSet activeIn) throws LanguageException;
	public abstract VariableSet initializebackwardLV(VariableSet lo) throws LanguageException;

	public abstract Statement rewriteStatement(String prefix) throws LanguageException;

	// Used only insider python parser to allow for ignoring newline logic
	private boolean isEmptyNewLineStatement = false;
	public boolean isEmptyNewLineStatement() {
		return isEmptyNewLineStatement;
	}
	public void setEmptyNewLineStatement(boolean isEmptyNewLineStatement) {
		this.isEmptyNewLineStatement = isEmptyNewLineStatement;
	}

	///////////////////////////////////////////////////////////////////////////
	// store exception info + position information for statements
	///////////////////////////////////////////////////////////////////////////

	private String _filename;
	private int _beginLine, _beginColumn;
	private int _endLine,   _endColumn;
	private String _text;

	public void setFilename(String passed)  { _filename = passed;	}
	public void setBeginLine(int passed)    { _beginLine = passed;	}
	public void setBeginColumn(int passed) 	{ _beginColumn = passed;}
	public void setEndLine(int passed) 		{ _endLine = passed;   }
	public void setEndColumn(int passed)	{ _endColumn = passed; }

	/**
	 * Set ParserRuleContext values (begin line, begin column, end line, end
	 * column, and text).
	 *
	 * @param ctx
	 *            the antlr ParserRuleContext
	 */
	public void setCtxValues(ParserRuleContext ctx) {
		setBeginLine(ctx.start.getLine());
		setBeginColumn(ctx.start.getCharPositionInLine());
		setEndLine(ctx.stop.getLine());
		setEndColumn(ctx.stop.getCharPositionInLine());
		// preserve whitespace if possible
		if ((ctx.start != null) && (ctx.stop != null) && (ctx.start.getStartIndex() != -1)
				&& (ctx.stop.getStopIndex() != -1) && (ctx.start.getStartIndex() <= ctx.stop.getStopIndex())
				&& (ctx.start.getInputStream() != null)) {
			String text = ctx.start.getInputStream()
					.getText(Interval.of(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
			if (text != null) {
				text = text.trim();
			}
			setText(text);
		} else {
			String text = ctx.getText();
			if (text != null) {
				text = text.trim();
			}
			setText(text);
		}
	}

	/**
	 * Set ParserRuleContext values (begin line, begin column, end line, end
	 * column, and text) and file name.
	 *
	 * @param ctx
	 *            the antlr ParserRuleContext
	 * @param filename
	 *            the filename (if it exists)
	 */
	public void setCtxValuesAndFilename(ParserRuleContext ctx, String filename) {
		setCtxValues(ctx);
		setFilename(filename);
	}

	public int getBeginLine()	{ return _beginLine;   }
	public int getBeginColumn() { return _beginColumn; }
	public int getEndLine() 	{ return _endLine;   }
	public int getEndColumn()	{ return _endColumn; }
	public String getFilename() { return _filename;  }

	public String printErrorLocation() {
		String file = _filename;
		if (file == null) {
			file = "";
		} else {
			file = file + " ";
		}
		if (getText() != null) {
			return "ERROR: " + file + "[line " + _beginLine + ":" + _beginColumn + "] -> " + getText() + " -- ";
		} else {
			return "ERROR: " + file + "[line " + _beginLine + ":" + _beginColumn + "] -- ";
		}
	}

	public String printWarningLocation() {
		String file = _filename;
		if (file == null) {
			file = "";
		} else {
			file = file + " ";
		}
		if (getText() != null) {
			return "WARNING: " + file + "[line " + _beginLine + ":" + _beginColumn + "] -> " + getText() + " -- ";
		} else {
			return "WARNING: " + file + "[line " + _beginLine + ":" + _beginColumn + "] -- ";
		}
	}

	public void raiseValidateError(String msg, boolean conditional) throws LanguageException {
		raiseValidateError(msg, conditional, null);
	}

	public void raiseValidateError(String msg, boolean conditional, String errorCode) throws LanguageException {
		if (conditional) {// warning if conditional
			String fullMsg = this.printWarningLocation() + msg;
			LOG.warn(fullMsg);
		} else {// error and exception if unconditional
			String fullMsg = this.printErrorLocation() + msg;
			if (errorCode != null)
				throw new LanguageException(fullMsg, errorCode);
			else
				throw new LanguageException(fullMsg);
		}
	}

	public String getText() {
		return _text;
	}

	public void setText(String text) {
		this._text = text;
	}

	/**
	 * Set parse information.
	 *
	 * @param parseInfo
	 *            parse information, such as beginning line position, beginning
	 *            column position, ending line position, ending column position,
	 *            text, and filename
	 * @param filename
	 *            the DML/PYDML filename (if it exists)
	 */
	public void setParseInfo(ParseInfo parseInfo) {
		_beginLine = parseInfo.getBeginLine();
		_beginColumn = parseInfo.getBeginColumn();
		_endLine = parseInfo.getEndLine();
		_endColumn = parseInfo.getEndColumn();
		_text = parseInfo.getText();
		_filename = parseInfo.getFilename();
	}

}


text:
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">

    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,600,700,800,300">
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">

    <!--[if lte IE 8]>
      <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-old-ie-min.css">
    <![endif]-->
    <!--[if gt IE 8]><!-->
      <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-min.css">
    <!--<![endif]-->

    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="bower_components/nvd3/nv.d3.css"/>

    <title>Crrnts</title>
  </head>

  <body ng-app="trrntsApp">
    <div ui-view></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js"></script>
    <script src="bower_components/datamaps/dist/datamaps.world.min.js"></script>
    <script src="bower_components/d3-tip/index.js"></script>
    <script src="bower_components/ngInfiniteScroll/build/ng-infinite-scroll.min.js"></script>
    <script src="bower_components/nvd3/nv.d3.js"></script>
    <script src="bower_components/angularjs-nvd3-directives/dist/angularjs-nvd3-directives.js"></script>

    <script src="dist/main.min.js"></script>
  </body>
</html>


text:
"""Tests for tensorflow.quantized.mangle.copy_graph."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.quantize.python import copy_graph
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest

class CopyGraphTest(test_util.TensorFlowTestCase):

  def _CompareNodeInGraph(self, node, graph):
    graph_node = graph.get_operation_by_name(node.name)
    self.assertEqual(str(node.node_def), str(graph_node.node_def))

  def testCopyGraph(self):
    graph = ops.Graph()
    with graph.as_default():
      a = constant_op.constant(1.0)
      b = variables.Variable(2.0)
      c = a + b
    graph_copy = copy_graph.CopyGraph(graph)
    # Ensure that the three original nodes are in the new graph.
    # import_meta_graph also adds a saver node to the graph which we don't care
    # about in this specific use case.
    for tensor in [a, b, c]:
      self._CompareNodeInGraph(tensor.op, graph_copy)
    # Test that the graph collections are the same.
    for key in graph.get_all_collection_keys():
      self.assertEqual(
          len(graph.get_collection(key)),
          len(graph_copy.get_collection(key)), 'Collection %s differs.')

if __name__ == '__main__':
  googletest.main()


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//-----------------------------------------------------------------------------
var BUGNUMBER = 341877;
var summary = 'GC hazard with for-in loop';
var actual = 'No Crash';
var expect = 'No Crash';

printBugNumber(BUGNUMBER);
printStatus (summary);

var obj = { };

var prop = "xsomePropety".substr(1);

obj.first = "first"

  obj[prop] = 1;

for (var elem in obj) {
  var tmp = elem.toString();
  delete obj[prop];
  // ensure that prop is cut from all roots
  prop = "xsomePropety".substr(2);
  obj[prop] = 2;
  delete obj[prop];
  prop = null;
  if (typeof gc == 'function')
    gc();
  for (var i = 0; i != 50000; ++i) {
    var tmp = 1 / 3;
    tmp /= 10;
  }
}

reportCompare(expect, actual, summary);


text:
from pyxer.base import *

@controller
def index():
    return "/index"


text:
from msrest.serialization import Model

class EventsPerformanceCounterInfo(Model):
    """The performance counter info.

    :param value: The value of the performance counter
    :type value: float
    :param name: The name of the performance counter
    :type name: str
    :param category: The category of the performance counter
    :type category: str
    :param counter: The counter of the performance counter
    :type counter: str
    :param instance_name: The instance name of the performance counter
    :type instance_name: str
    :param instance: The instance of the performance counter
    :type instance: str
    """

    _attribute_map = {
        'value': {'key': 'value', 'type': 'float'},
        'name': {'key': 'name', 'type': 'str'},
        'category': {'key': 'category', 'type': 'str'},
        'counter': {'key': 'counter', 'type': 'str'},
        'instance_name': {'key': 'instanceName', 'type': 'str'},
        'instance': {'key': 'instance', 'type': 'str'},
    }

    def __init__(self, *, value: float=None, name: str=None, category: str=None, counter: str=None, instance_name: str=None, instance: str=None, **kwargs) -> None:
        super(EventsPerformanceCounterInfo, self).__init__(**kwargs)
        self.value = value
        self.name = name
        self.category = category
        self.counter = counter
        self.instance_name = instance_name
        self.instance = instance


text:
var Promise = require('rsvp').Promise;
var System = require('systemjs');

var asp = require('rsvp').denodeify;
var fs = require('fs');
var path = require('path');

var toFileURL = require('./utils').toFileURL;

var attachCompilers = require('./compile').attachCompilers;
var compileOutputs = require('./compile').compileOutputs;
var compileLoad = require('./compile').compileLoad;

var writeOutputs = require('./output').writeOutputs;

var traceExpression = require('./arithmetic').traceExpression;

var Trace = require('./trace');

var getCanonicalName = require('./utils').getCanonicalName;

require('rsvp').on('error', function(reason) {
  throw new Error('Unhandled promise rejection.\n' + reason && reason.stack || reason || '' + '\n');
});

function processOpts(opts_, outFile) {
  var opts = {
    config: {},
    outFile: outFile,
    normalize: true,
    anonymous: false,

    runtime: false,
    minify: false,
    mangle: true,

    sfx: false,
    sfxFormat: 'global',
    sfxEncoding: true,
    sfxGlobals: {},
    sfxGlobalName: null,

    sourceMaps: false,
    sourceMapContents: opts_ && opts_.sourceMaps == 'inline',
    lowResSourceMaps: false
  };
  for (var key in opts_)
    opts[key] = opts_[key];
  return opts;
}

function Builder(baseURL, cfg) {
  if (typeof baseURL == 'object') {
    cfg = baseURL;
    baseURL = null;
  }

  this.loader = null;
  this.reset();

  this.loader.getCanonical = this.getCanonicalName.bind(this);

  if (baseURL)
    this.config({ baseURL: baseURL });

  if (typeof cfg == 'object')
    this.config(cfg);
  else if (typeof cfg == 'string')
    this.loadConfigSync(cfg);
}

// reverse mapping from globbed address
Builder.prototype.getCanonicalName = function(normalized) {
  return getCanonicalName(this.loader, normalized);
};

Builder.prototype.reset = function(baseLoader) {
  baseLoader = baseLoader || this.loader || System;

  var loader = this.loader = new baseLoader.constructor();
  loader.constructor = baseLoader.constructor;
  loader.baseURL = baseLoader.baseURL;

  loader.normalize = baseLoader.normalize;
  loader.normalizeSync = baseLoader.normalizeSync;
  loader.locate = baseLoader.locate;
  loader.fetch = baseLoader.fetch;
  loader.translate = baseLoader.translate;
  loader.instantiate = baseLoader.instantiate;

  loader.builder = true;

  attachCompilers(loader);
  global.System = loader;

  // clear the cache
  this.setCache({});
};

Builder.prototype.setCache = function(cacheObj) {
  this.cache = {
    compile: cacheObj.compile || {},
    trace: cacheObj.trace || {}
  };
  this.tracer = new Trace(this.loader, this.cache.trace);
};

Builder.prototype.getCache = function() {
  return this.cache;
};

function executeConfigFile(source) {
  var self = this;
  var curSystem = global.System;
  var configSystem = global.System = {
    config: function(cfg) {
      self.config(cfg);
    }
  };
  // jshint evil:true
  new Function(source.toString()).call(global);
  global.System = curSystem;
}

Builder.prototype.loadConfig = function(configFile) {
  return asp(fs.readFile)(configFile)
  .then(executeConfigFile.bind(this));
};

Builder.prototype.loadConfigSync = function(configFile) {
  var source = fs.readFileSync(configFile);
  executeConfigFile.call(this, source);
};

Builder.prototype.config = function(config) {
  var loader = this.loader;

  var cfg = {};
  for (var p in config) {
    if (p != 'bundles')
      cfg[p] = config[p];
  }
  loader.config(cfg);
};

Builder.prototype.compile = function(moduleName, outFile, opts) {
  if (outFile && typeof outFile == 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = processOpts(opts, outFile);

  opts.anonymous = true;

  var self = this;
  return this.tracer.getLoadRecord(moduleName)
  .then(function(load) {
    return compileLoad(self.loader, load, opts);
  })
  .then(function(output) {
    return writeOutputs(opts, [output], self.loader.baseURL);
  });
};

Builder.prototype.build = function(expression, outFile, opts) {
  var self = this;

  // Allow passing opts as second argument.
  if (outFile && typeof outFile === 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = opts || {};

  if (opts.config)
    this.config(opts.config);

  return this.trace(expression)
  .then(function(tree) {
    return self.buildTree(tree, outFile, opts);
  });
};

function addExtraOutputs(output, tree, opts) {
  output.modules = Object.keys(tree).filter(function(moduleName) {
    return tree[moduleName].metadata.build !== false;
  });
}

Builder.prototype.buildTree = function(tree, outFile, opts) {
  var loader = this.loader;
  var self = this;

  // Allow passing opts as second argument.
  if (outFile && typeof outFile === 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = processOpts(opts, outFile);

  var cache = this.cache.compile;

  return compileOutputs(loader, tree, opts, false, cache)
  .then(function(outputs) {
    return writeOutputs(opts, outputs, loader.baseURL);
  })
  .then(function(output) {
    addExtraOutputs.call(self, output, tree, opts, loader);
    return output;
  });
};

Builder.prototype.buildSFX = function(expression, outFile, opts) {
  var loader = this.loader;
  var self = this;

  // Allow passing opts as second argument.
  if (outFile && typeof outFile === 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = opts || {};
  opts.normalize = true;
  opts.sfx = true;

  // include runtime by default if needed
  if (opts.runtime !== false)
    opts.runtime = true;

  opts = processOpts(opts, outFile);
  var tree;

  if (opts.config)
    this.config(opts.config);

  var cache = this.cache.compile;

  return traceExpression(this, expression, true)
  .then(function(trace) {
    tree = trace.tree;
    return compileOutputs(loader, tree, opts, trace.entryPoints, cache);
  })
  .then(function(outputs) {
    return writeOutputs(opts, outputs, loader.baseURL);
  })
  .then(function(output) {
    addExtraOutputs.call(self, output, tree, opts, loader);
    return output;
  });
};

Builder.prototype.trace = function(expression) {
  return traceExpression(this, expression);
};

var namedRegisterRegEx = /(System\.register(Dynamic)?|define)\(('[^']+'|"[^"]+")/g;

Builder.prototype.traceModule = function(moduleName) {

  var loader = this.loader;

  var self = this;

  var System = loader.global.System;
  loader.global.System = loader;

  return Promise.resolve(loader.normalize(moduleName))
  .then(function(_moduleName) {
    moduleName = getCanonicalName(loader, _moduleName);
    return self.tracer.getAllLoadRecords(moduleName);
  })
  .then(function(loads) {
    loader.global.System = System;

    if (moduleName == '@empty')
      return {
        moduleName: moduleName,
        tree: loads
      };

    // if it is a bundle, we just use a regex to extract the list of loads
    // as null records for subtraction arithmetic use only
    var thisLoad = loads[moduleName];
    if (thisLoad.metadata.bundle) {
      namedRegisterRegEx.lastIndex = 0;
      var curMatch;
      while ((curMatch = namedRegisterRegEx.exec(thisLoad.source)))
        loads[curMatch[3].substr(1, curMatch[3].length - 2)] = null;
    }

    return {
      moduleName: moduleName,
      tree: loads
    };
  })
  .catch(function(e) {
    loader.global.System = System;
    throw e;
  });
};

// returns a new tree containing tree1 n tree2
Builder.prototype.intersectTrees = function(tree1, tree2) {
  var name;
  var intersectTree = {};

  var tree1Names = [];
  for (name in tree1)
    tree1Names.push(name);

  for (name in tree2) {
    if (tree1Names.indexOf(name) == -1)
      continue;

    intersectTree[name] = tree1[name] || tree2[name] || null;
  }

  return intersectTree;
};

// returns a new tree containing tree1 + tree2
Builder.prototype.addTrees = function(tree1, tree2) {
  var name;
  var unionTree = {};

  for (name in tree2)
    unionTree[name] = tree2[name] || tree1[name] || null;

  for (name in tree1)
    unionTree[name] = tree1[name] || tree2[name] || null;

  return unionTree;
};

// returns a new tree containing tree1 - tree2
Builder.prototype.subtractTrees = function(tree1, tree2) {
  var name;
  var subtractTree = {};

  for (name in tree1)
    subtractTree[name] = tree1[name];

  for (name in tree2)
    delete subtractTree[name];

  return subtractTree;
};

// given a tree, creates a depCache for it
Builder.prototype.getDepCache = function(tree) {
  var depCache = {};
  Object.keys(tree).forEach(function(moduleName) {
    var load = tree[moduleName];
    if (load.deps.length)
      depCache[moduleName] = load.deps.map(function(dep) {
        return load.depMap[dep];
      });
  });
  return depCache;
};

module.exports = Builder;


text:
require 'test_helper'

class TitleTest < ActiveSupport::TestCase
  test "length of name" do
    title = Title.new(name: '', post: posts(:published))
    assert !title.save
    assert title.errors.has_key?(:base)

    title.name = 'a'
    assert title.save, title.errors.full_messages.to_sentence
  end

  test "uniqueness" do
    persisted = titles(:draft)
    title = Title.new(name: persisted.name, post: posts(:published))
    assert !title.save, title.errors.full_messages.to_a
    assert title.errors.has_key?(:uniqueness), title.errors.full_messages.to_a
  end

  test "editing only possible when it's a draft" do
    title = titles(:draft)
    title.name = "Changing it."
    assert title.save, title.errors.full_messages.to_sentence

    title = titles(:published_history)
    title.name = "Shouldn't change"
    assert !title.save
  end

end


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="br.com.mobity.sunshine.SettingsActivity">
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" app:showAsAction="never" />
</menu>


text:
package com.thesett.aima.search;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

import com.thesett.aima.search.util.backtracking.ReTraversable;
import com.thesett.common.util.Filterator;
import com.thesett.common.util.Function;
import com.thesett.common.util.StackQueue;

/**
 * InstrumentedTraversableState is a wrapper class that wraps a TraversableState so as to intercept its method calls in
 * order to gather test statistics.
 *
 * <p>Some stats are gathered in statics to make gathering stats accross many states easier.Use the {@link #resetStats}
 * method to clear them out.
 */
public class InstrumentedTraversableState<O> extends TraversableState<O> implements GoalState, ReTraversable<O>
{
    /** Used to hold a reference to a collection to put all goal tested states in for test routines to examine. */
    public static Collection<InstrumentedTraversableState> examinedStates =
        new LinkedList<InstrumentedTraversableState>();

    /** Used to hold a stack of states for checking back-tracking searches back-track in reverse order. */
    private static Queue<Traversable> backtrackStack = new StackQueue<Traversable>();

    /** Holds a reference to the underlying wrapped TraversableState object. */
    Traversable<O> testState;

    /** Used in order to record that the correct node was visited upon backtracking. */
    public boolean correctNodeVisitedOnBacktracking = false;

    /** Used in order to record that the apply operator method was called. */
    public boolean operatorApplied = false;

    /**
     * Used to mark this state as having its successors nodes expanded. Set to true when the {@link #successors} method
     * has been called.
     */
    public boolean expanded = false;

    /** Wraps a TraversableState in this test rig to gather stats on the test calls made to it. */
    public InstrumentedTraversableState(Traversable<O> testState)
    {
        this.testState = testState;
    }

    /** Resets the static test stats. */
    public static void resetStats()
    {
        examinedStates.clear();
        backtrackStack.clear();
    }

    /** Returns whether this state is a goal node. */
    public boolean isGoal()
    {
        // Keep track of the fact that this state was goal tested.
        examinedStates.add(this);

        return ((GoalState) testState).isGoal();
    }

    /**
     * A helper method to perform the goal test without modifiying the examined states collection or else a concurrent
     * modification exception will arise.
     */
    public boolean isGoalHelper()
    {
        return ((GoalState) testState).isGoal();
    }

    /**
     * Returns an enumeration of successors of the state.
     *
     * @param reverse Use a reverse ordering.
     */
    public Iterator<Successor<O>> successors(boolean reverse)
    {
        // Keep track of the fact that this state had its successors expanded.
        expanded = true;

        return new Filterator<Successor<O>, Successor<O>>(testState.successors(reverse),
            new Function<Successor<O>, Successor<O>>()
            {
                public Successor<O> apply(Successor<O> successor)
                {
                    return new Successor<O>(new InstrumentedTraversableState<O>(successor.getState()),
                        successor.getOperator(), successor.getCost());
                }
            });
    }

    /**
     * Returns the state obtained by applying the specified operation. If the operation is not valid then this should
     * return null.
     */
    public Traversable<O> getChildStateForOperator(Operator op)
    {
        return new InstrumentedTraversableState<O>(testState.getChildStateForOperator(op));
    }

    /** Returns the cost of applying the specified operations. */
    public float costOf(Operator op)
    {
        return testState.costOf(op);
    }

    /**
     * Gets all operators valid from this state.
     *
     * @param reverse Don't care about reverse orderings. Ignored.
     */
    public Iterator<Operator<O>> validOperators(boolean reverse)
    {
        return testState.validOperators(reverse);
    }

    /** Apply any globally visible state changes required by the operator that generated this state. */
    public void applyOperator()
    {
        if (testState instanceof ReTraversable)
        {
            ((ReTraversable) testState).applyOperator();

            backtrackStack.offer(testState);

            operatorApplied = true;
        }
        else
        {
            throw new IllegalStateException("'testState' is not an instance of ReTraversable.");
        }
    }

    /** Undo any globally visible state changes made by applying an operator to this states parent state. */
    public void undoOperator()
    {
        if (testState instanceof ReTraversable)
        {
            ((ReTraversable) testState).undoOperator();

            Traversable<O> comparator = backtrackStack.poll();

            correctNodeVisitedOnBacktracking = (testState.equals(comparator));
        }
        else
        {
            throw new IllegalStateException("'testState' is not an instance of ReTraversable.");
        }
    }

    public String toString()
    {
        return testState.toString();
    }
}


text:
[![npm version](https://badge.fury.io/js/tyranid-graphql.svg)](https://badge.fury.io/js/tyranid-graphql)
[![codecov](https://codecov.io/gh/tyranid-org/tyranid-graphql/branch/master/graph/badge.svg)](https://codecov.io/gh/tyranid-org/tyranid-graphql)

This library adds a graphql query interpreter for the [`tyranid`](https://github.com/tyranid-org/tyranid)
mongodb ORM. The graphql schema is created from tyranid collection schemas using [`graphql-js`](https://github.com/graphql/graphql-js).

## Quick Example

After calling `graphqlize(Tyr)` on tyranid, use graphql queries for complex populations...

```javascript
import { Tyr } from 'tyranid';
import { graphqlize } from 'tyranid-graphql';

// ...
graphqlize(Tyr); // (synchronous)
// ...

// template tag syntax
const results = await Tyr.graphql`
  query userTeams {
    users {
      name
      teamIds {
        name,
        organizationId {
          name
        }
      }
    }
  }
`;

console.log(users[1].teamIds[2].organizationId.name); // => "Chipotle"
```

## Interactive graphql server Example

![Apollo server example](/test/example/example.gif)

To see an example of `apollo-server` (http://dev.apollodata.com/core/)
being used with a generated schema from tyranid, clone the repo, install deps...

```shell
npm install
```

and run the example server

```shell
npm start
```

## Detailed Code Example

Say we have the following tyranid collections...

```javascript
import { Tyr } from 'tyranid';

export const User = new Tyr.Collection({
  id: 'u00',
  name: 'user',
  dbName: 'users',
  fields: {
    _id: { is: 'mongoid' },
    name: { is: 'string' },
    teamIds: {
      is: 'array',
      of: {
        link: 'team'
      }
    },
    organizationId: { link: 'organization' }
  }
});

export const Team = new Tyr.Collection({
  id: 't00',
  name: 'team',
  dbName: 'teams',
  fields: {
    _id: { is: 'mongoid' },
    name: { is: 'string' },
    organizationId: { link: 'organization' }
  }
});

export const Organization = new Tyr.Collection({
  id: 'o00',
  name: 'organization',
  dbName: 'organizations',
  fields: {
    _id: { is: 'mongoid' },
    name: { is: 'string' }
  }
});
```

We then can add graphql functionality to tyranid as follows

```javascript
import { Tyr } from 'tyranid';
import { graphqlize } from 'tyranid-graphql';

(async() => {
  const db = await mongodb
    .MongoClient
    .connect('mongodb://127.0.0.1:27017/tyranid_gracl_test');

  Tyr.config({
    db: db,
    validate: [
      { dir: __dirname,
        fileMatch: 'models.js' }
    ]
  });

  graphqlize(Tyr);
})();
```

Then, elsewhere in the app, we can use graphql queries
for complex population of linked collections.

Additionally, if a `Tyr.secure` plugin like `tyranid-gracl` is being utilized,
we can provide `auth` and `perm` parameters to have
properties / documents filtered by user permissions.

```javascript

const results = await Tyr.graphql({
  query: `
    query userTeams {
      users {
        name
        teamIds {
          name,
          organizationId {
            name
          }
        }
      }
    }
  `
  auth: req.user,
  perm: 'view'
});

// result === {
//     'data': {
//       'users': [
//         {
//           'name': 'ben',
//           'teamIds': [
//             {
//               'name': 'burritoMakers',
//               'organizationId': {
//                 'name': 'Chipotle'
//               }
//             },
//             {
//               'name': 'chipotleMarketing',
//               'organizationId': {
//                 'name': 'Chipotle'
//               }
//             }
//           ]
//         },
//         {
//           'name': 'ted',
//           'teamIds': [
//             {
//               'name': 'cavaEngineers',
//               'organizationId': {
//                 'name': 'Cava'
//               }
//             }
//           ]
//         },
//         {
//           'name': 'noTeams',
//           'teamIds': []
//         }
//       ]
//     }
//   };
```

## Installation

```bash
npm install tyranid-graphql
```

## License

MIT


text:
import React from 'react';

export const Block = () => (

Block

);


text:
package com.jin.business.exception;

public class BusinessException extends RuntimeException {

	public BusinessException(String message) {
		// TODO Auto-generated constructor stub
	}

	/**
	 *
	 */
	private static final long serialVersionUID = -8131024595922673389L;

}


text:
import standalone from '../src/pact-standalone';
import childProcess = require('child_process');

const status = childProcess.spawnSync(
  standalone.mockServiceFullPath,
  process.argv.slice(2),
  { stdio: 'inherit' }
).status;
process.exit(status);


text:
package com.github.shredder121.gh_event_api.model;

import java.time.ZonedDateTime;

import org.springframework.http.MediaType;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.github.shredder121.gh_event_api.model.json.PropertyBasedJsonCreator;
import com.google.common.collect.ImmutableList;

/**
 * A release is the tagging of a particular version.
 */
@lombok.Value
@JsonNaming(LowerCaseWithUnderscoresStrategy.class)
@lombok.RequiredArgsConstructor(
        access = lombok.AccessLevel.MODULE,
        onConstructor = @__(@PropertyBasedJsonCreator)
)
public class Release {

    /**
     * The id of the release, for GitHub bookkeeping.
     */
    Long id;

    /**
     * The (API) URL to view this release.
     */
    String url;

    /**
     * The (GitHub Web UI) URL to view this release.
     */
    String htmlUrl;

    /**
     * The (API) URL to view this releases's assets.
     */
    String assetsUrl;

    /**
     * The (API) URL to upload additional assets.
     */
    String uploadUrl;

    /**
     * Text describing the contents of the tag.
     */
    String body;

    /**
     * The user that performed the release.
     */
    User author;

    /**
     * The name of the tag.
     */
    String tagName;

    /**
     * The commitish value that determines where the Git tag is created from.
     */
    String targetCommitish;

    /**
     * A list with assets.
     */
    ImmutableList<Asset> assets;

    /**
     * The date this release was created.
     */
    ZonedDateTime createdAt;

    /**
     * The date this release was created.
     */
    ZonedDateTime publishedAt;

    /**
     * Whether the release is a published one.
     */
    Boolean draft;

    /**
     * Whether the release is a prerelease or a full release.
     */
    Boolean prerelease;

    /**
     * An asset is an additional resource bundled with a release.
     */
    @lombok.Value
    @JsonNaming(LowerCaseWithUnderscoresStrategy.class)
    @lombok.RequiredArgsConstructor(
            access = lombok.AccessLevel.MODULE,
            onConstructor = @__(@PropertyBasedJsonCreator)
    )
    public static class Asset {

        /**
         * The id of the release, for GitHub bookkeeping.
         */
        Long id;

        /**
         * The (API) URL to view this asset.
         */
        String url;

        /**
         * The URL where the asset can be downloaded.
         */
        String browserDownloadUrl;

        /**
         * THe name of this asset.
         * This is typically the file name.
         */
        String name;

        /**
         * A short description of this asset.
         */
        String label;

        /**
         * The content type of this asset.
         */
        MediaType contentType;

        /**
         * The state of the asset.
         */
        String state;

        /**
         * The size of this asset.
         */
        Long size;

        /**
         * The amount of downloads this asset has seen.
         */
        Long downloadCount;

        /**
         * The user who uploaded the asset.
         */
        User uploader;
    }
}


text:
package org.jetbrains.plugins.scala
package lang
package psi
package api
package statements

/**
* @author Alexander Podkhalyuzin
* Date: 22.02.2008
* Time: 9:49:23
*/
trait ScFunctionDeclaration extends ScFunction with ScTypedDeclaration


text:
HLOPBLD ;ALB/CJM-HL7 - Building segments ;10/24/2006
 ;;1.6;HEALTH LEVEL SEVEN;**126,132**;Oct 13, 1995;Build 6
 ;Per VHA Directive 2004-038, this routine should not be modified.
 ;
 ;
BUILDSEG(HLMSTATE,SEG,TOARY,ERROR) ;Builds the segment from the individual values
 ;Input:
 ;  HLMSTATE() - (pass by reference, required) Used to track the progress of the message. Uses these subscripts:
 ;    ("HDR","FIELD SEPARATOR")
 ;    ("HDR","ENCODING CHARACTERS")
 ;  SEG() - (pass by reference, required) Contains the data.  It must be built by calls to SET^HLOAPI prior to calling $$BUILDSEG.
 ;
 ;Note#1:  The '0' field must be a 3 character segment type
 ;Note#2: ***SEG is killed upon successfully adding the segment***
 ;
 ;Output:
 ;  Function - returns 1 on success, 0 on failure
 ;  TOARY (pass by reference) This will return the segment in an array format TOARY(1),TOARY(2),... For segments that are shorter than the MUMPS maximum string length, there will be only TOARY(1)
 ;  ERROR (optional, pass by reference) - returns an error message on failure
 ;
 ;
 K ERROR,TOARY
 N TEMP1,TEMP2,LINE,LAST,SEQ,MAX,COUNT,SEGTYPE
 S COUNT=0
 S MAX=HLMSTATE("SYSTEM","MAXSTRING")-1 ;save some room for the <CR>
 S SEGTYPE=$G(SEG(0,1,1,1))
 S LAST=0,(TEMP1,TEMP2)="",LINE=SEGTYPE_HLMSTATE("HDR","FIELD SEPARATOR")
 F  S SEQ=$O(SEG(LAST)) Q:'SEQ  D
 .S TEMP2="",$P(TEMP2,HLMSTATE("HDR","FIELD SEPARATOR"),$S(LAST=0:SEQ,1:SEQ-LAST+1))=""
 .S TEMP1=TEMP2
 .S LAST=SEQ
 .N REP,LAST
 .S LAST=0
 .F  S REP=$O(SEG(SEQ,LAST)) Q:'REP  D
 ..S TEMP2="",$P(TEMP2,$E(HLMSTATE("HDR","ENCODING CHARACTERS"),2),$S(LAST=0:REP,1:REP-LAST+1))=""
 ..S TEMP1=TEMP1_TEMP2
 ..S LAST=REP
 ..;
 ..N COMP,LAST
 ..S LAST=0
 ..F  S COMP=$O(SEG(SEQ,REP,LAST)) Q:'COMP  D
 ...S TEMP2="",$P(TEMP2,$E(HLMSTATE("HDR","ENCODING CHARACTERS"),1),$S(LAST=0:COMP,1:COMP-LAST+1))=""
 ...S TEMP1=TEMP1_TEMP2
 ...S LAST=COMP
 ...;
 ...N SUBCOMP,LAST
 ...S LAST=0
 ...F  S SUBCOMP=$O(SEG(SEQ,REP,COMP,LAST)) Q:'SUBCOMP  D
 ....N VALUE
 ....S TEMP2="",$P(TEMP2,$E(HLMSTATE("HDR","ENCODING CHARACTERS"),4),$S(LAST=0:SUBCOMP,1:SUBCOMP-LAST+1))=""
 ....S VALUE=$G(SEG(SEQ,REP,COMP,SUBCOMP))
 ....K SEG(SEQ,REP,COMP,SUBCOMP)
 ....S:((SEGTYPE'="MSH")&(SEGTYPE'="BHS"))!(SEQ'=2) VALUE=$$ESCAPE(.HLMSTATE,VALUE)
 ....S TEMP2=TEMP2_VALUE
 ....S TEMP1=TEMP1_TEMP2
 ....I $L(LINE)+$L(TEMP1)<MAX D
 .....S LINE=LINE_TEMP1
 ....E  D
 .....D ADDLINE(.TOARY,LINE_$E(TEMP1,1,MAX-$L(LINE)),.COUNT)
 .....S LINE=$E(TEMP1,MAX-$L(LINE)+1,MAX+100)
 ....S TEMP1=""
 ....S LAST=SUBCOMP
 I $L(LINE) D ADDLINE(.TOARY,LINE,.COUNT)
 K SEG
 Q 1
 ;
ADDLINE(TOARY,LINE,COUNT) ;
 S COUNT=COUNT+1
 S TOARY(COUNT)=LINE
 Q
 ;
ESCAPE(HLMSTATE,VALUE) ;
 ;Replaces the HL7 encoding characters with the corresponding escape sequences and returns the result as the function value
 ;
 N ESC,CHARS,I,NEWVALUE,LEN,CUR
 S CHARS=HLMSTATE("HDR","ENCODING CHARACTERS")
 S ESC=$E(CHARS,3)
 S NEWVALUE="",LEN=$L(VALUE)
 F I=1:1:LEN D
 .S CUR=$E(VALUE,I)
 .S NEWVALUE=NEWVALUE_$S(CUR=HLMSTATE("HDR","FIELD SEPARATOR"):ESC_"F"_ESC,CUR=ESC:ESC_"E"_ESC,CUR=$E(CHARS,1):ESC_"S"_ESC,CUR=$E(CHARS,4):ESC_"T"_ESC,CUR=$E(CHARS,2):ESC_"R"_ESC,1:CUR)
 Q NEWVALUE
 ;
REPLACE(VALUE,CHAR,STRING) ;
 ;Takes the input string=VALUE and replaces each instance of the character
 ;=CHAR with the string=STRING and returns the resultant string
 ;as the function value
 ;
 N I,NEWVALUE,CURCHAR
 S NEWVALUE=""
 F I=1:1:$L(VALUE) D
 .S CURCHAR=$E(VALUE,I)
 .S NEWVALUE=NEWVALUE_$S(CURCHAR=CHAR:STRING,1:CURCHAR)
 Q NEWVALUE


text:
/**
 * Unit tests for the SitesFS object.
 */
"use strict";

// Require the super classes for this class.
const UnitTest = require("./base.unit.js");
const SitesUnitTest = require("./sites.unit.js");
const BaseFsUnit = require("./base.fs.unit.js");
const JSONItemFS = require(UnitTest.API_PATH + "lib/JSONItemFS.js");

// Require the node modules used in this test file.
const fs = require("fs");
const sinon = require("sinon");

// Require the local module being tested.
const fsApi = require(UnitTest.API_PATH + "lib/sitesFS.js").instance;

// The default API context used for unit tests.
const context = UnitTest.DEFAULT_API_CONTEXT;

class SitesFsUnitTest extends BaseFsUnit {
    constructor () {
        super();
    }

    run () {
        super.run(fsApi, SitesUnitTest.VALID_SITE_1, SitesUnitTest.VALID_SITE_2);
    }

    testGetItemPath(fsApi, itemName1, itemName2) {
        describe("getItemPath", function () {
            it("should succeed with various inputs", function (done) {
                // Should return undefined for an undefined input item.
                expect(fsApi.getItemPath(context, undefined)).to.not.exist;

                // Should return undefined for an empty input item.
                expect(fsApi.getItemPath(context, {})).to.not.exist;

                // Verify the expected path for the default site.
                const extension = fsApi.getExtension();
                let itemPath = fsApi.getItemPath(context, {"id": "default", "name": "foo", "status": "ready"});
                expect(itemPath.endsWith("default" + extension)).to.equal(true);

                // Verify the expected path for the default draft site.
                itemPath = fsApi.getItemPath(context, {"id": "default:draft", "name": "foo", "status": "draft"});
                expect(itemPath.endsWith("default_wchdraft" + extension)).to.equal(true);

                // Verify the expected path for a non-default ready site.
                itemPath = fsApi.getItemPath(context, {
                    "id": "foo",
                    "name": "bar",
                    "contextRoot": "some-other-value",
                    "status": "ready"
                });
                expect(itemPath.endsWith("some-other-value" + extension)).to.equal(true);

                // Verify the expected path for a non-default draft site.
                itemPath = fsApi.getItemPath(context, {
                    "id": "foo",
                    "name": "bar",
                    "contextRoot": "some-other-value",
                    "status": "draft"
                });
                expect(itemPath.endsWith("some-other-value_wchdraft" + extension)).to.equal(true);

                // Verify the expected path for a non-default draft site in a project.
                itemPath = fsApi.getItemPath(context, {
                    "id": "foo",
                    "name": "bar",
                    "contextRoot": "some-other-value",
                    "status": "draft",
                    "projectId": "project-id"
                });
                expect(itemPath.endsWith("some-other-value_wchdraft_project-id" + extension)).to.equal(true);

                done();
            });
        });
    }

    // Override the base FS test to cover the renaming logic for sites.
    listNamesSuccess(fsApi, itemName1, itemName2, done) {
        // Create a stub for super.listNames to resolve with known values.
        const stubSuper = sinon.stub(JSONItemFS.prototype, "listNames");
        stubSuper.resolves([{id: "default", path: "default", status: "ready"},
            {id: "foo:draft", path: "foo_wchdraft", contextRoot: "foo", status: "draft"},
            {id: "bar:draft", path: "bar", contextRoot: "bar", status: "draft"},
            {id: "ack", path: "ack_wchdraft", contextRoot: "ack", status: "ready"}]);

        // Create a spy for fsApi.getFileName to verify it is called the expected number of times.
        const spyFileName = sinon.spy(fsApi, "getFileName");

        // Create a spy for fsApi.getPath to verify it is called the expected number of times.
        const spyPath = sinon.spy(fsApi, "getPath");

        // Create a stub for fs.existsSync that will return false the first two times and true the next two times.
        const stubExists = sinon.stub(fs, "existsSync");
        stubExists.onCall(0).returns(false);
        stubExists.onCall(1).returns(false);
        stubExists.onCall(2).returns(true);
        stubExists.onCall(3).returns(true);

        // Create a stub for fs.renameSync to keep it from being called.
        const stubRename = sinon.stub(fs, "renameSync");

        this.addTestDouble(stubSuper);
        this.addTestDouble(spyFileName);
        this.addTestDouble(spyPath);
        this.addTestDouble(stubExists);
        this.addTestDouble(stubRename);

        // Call the method being tested.
        let error;

        // Set the current working directory to the "valid resources" directory.
        fsApi.listNames(context, {"workingDir": UnitTest.API_PATH + UnitTest.VALID_RESOURCES_DIRECTORY})
            .then(function (items) {
                // Verify that the filename spy was called three times (not for the first item).
                expect(spyFileName).to.have.been.calledThrice;

                // Verify that the path spy was called twice (for the third and fourth items).
                expect(spyPath).to.have.been.calledTwice;

                // Verify that the rename stub was called twice (for the fourth item).
                expect(stubRename).to.have.been.calledTwice;

                // Verify that the expected values are returned.
                expect(items).to.have.lengthOf(4);
                expect(items[0].id).to.equal("default");
                expect(items[1].id).to.equal("foo:draft");
                expect(items[2].id).to.equal("bar:draft");
                expect(items[3].id).to.equal("ack");
            })
            .catch(function (err) {
                // NOTE: A failed expectation from above will be handled here.
                // Pass the error to the "done" function to indicate a failed test.
                error = err;
            })
            .finally(function () {
                // noinspection JSUnresolvedFunction
                // Restore the default options.
                UnitTest.restoreOptions(context);

                // Call mocha's done function to indicate that the test is over.
                done(error);
            });
    }
}

module.exports = SitesFsUnitTest;


text:
"""
Tests of io.axonio
"""

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO

class TestAxonIO(BaseTestIO, unittest.TestCase):
    files_to_test = ['File_axon_1.abf',
                     'File_axon_2.abf',
                     'File_axon_3.abf',
                     'File_axon_4.abf',
                     'File_axon_5.abf',
                     'File_axon_6.abf',

                        ]
    files_to_download = files_to_test
    ioclass = AxonIO

if __name__ == "__main__":
    unittest.main()


text:
package org.ihtsdo.buildcloud.core.dao;

import org.apache.commons.codec.binary.Base64;
import org.ihtsdo.buildcloud.core.entity.Build;
import org.ihtsdo.buildcloud.core.entity.Product;
import org.ihtsdo.buildcloud.core.service.BuildService;
import org.ihtsdo.buildcloud.rest.pojo.BuildPage;
import org.ihtsdo.buildcloud.test.AbstractTest;
import org.junit.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import static org.junit.jupiter.api.Assertions.assertEquals;

@Transactional
public class BuildDAOImplTest extends AbstractTest {

	public static final String TEST_FILE_NAME = "der2_Refset_SimpleDelta_INT_20140831.txt";

	@Autowired
	protected BuildDAOImpl buildDAO;

	@Autowired
	protected ProductDAO productDAO;

	private Product product;

	private Build build;

	private String buildId;

	@Before
	public void setup() throws Exception {
		super.setup();
		product = productDAO.find(1L);
		final Date creationTime = new GregorianCalendar(2014, 1, 4, 10, 30, 1).getTime();
		build = new Build(creationTime, product.getReleaseCenter().getBusinessKey(), product.getBusinessKey(), product.getBuildConfiguration(), product.getQaTestConfig());
		buildDAO.save(build);
		buildId = build.getId();
	}

	@Test
	public void testFind() {
		// saved build
		Build foundBuild = buildDAO.find(product.getReleaseCenter().getBusinessKey(), product.getBusinessKey(), buildId, null, null, null, null);
		Assert.assertNotNull(foundBuild);
		Assert.assertEquals("2014-02-04T10:30:01", foundBuild.getCreationTime());
		Assert.assertEquals(Build.Status.PENDING, foundBuild.getStatus());

		// no existing build id
		foundBuild = buildDAO.find(product.getReleaseCenter().getBusinessKey(), product.getBusinessKey(), "2014-02-04T10:30:02", null, null, null, null);
		Assert.assertNull(foundBuild);
	}

	@Test
	public void testPutOutputFile() throws Exception {

		//Leaving this as offline to remove external dependency, but set to true to check Amazon is happy with our MD5 Encoding.
		final String testFile = getClass().getResource("/org/ihtsdo/buildcloud/core/service/build/" + TEST_FILE_NAME).getFile();

		final boolean calcMD5 = true;
		final String md5Received = buildDAO.putOutputFile(build, new File(testFile), calcMD5);

		System.out.println(md5Received);

		//Amazon are expecting the md5 to be xWJD6+IqEtukiwI9rz4pNw==
		//Offline test is just going to return the MD5 input, so this test only makes sense in online mode.
		final byte[] md5BytesExpected = Base64.decodeBase64("xWJD6+IqEtukiwI9rz4pNw==");
		final byte[] md5BytesReceived =  Base64.decodeBase64(md5Received);
		Assert.assertArrayEquals(md5BytesExpected, md5BytesReceived);

		//Now lets see if we can get that file back out again
		final InputStream is = buildDAO.getOutputFileInputStream(build, TEST_FILE_NAME);
		Assert.assertNotNull(is);
	}

	@Test
	public void findAllDescPage_ShouldReturnExpectedPage_WhenRequestingAll() throws IOException, InterruptedException {
		// given
		createBuild();
		createBuild();
		createBuild();
		createBuild();

		// when
		BuildPage<Build> result = buildDAO.findAllDescPage(product.getReleaseCenter().getBusinessKey(), product.getBusinessKey(), null, null, null, null, BuildService.View.ALL_RELEASES, PageRequest.of(0, 10));

		// then
		assertEquals(5, result.getTotalElements());
	}

	@Test
	public void findAllDescPage_ShouldReturnExpectedPage_WhenRequestingSubPage() throws IOException, InterruptedException {
		// given
		Date build1 = createBuild();
		Date build2 = createBuild();
		Date build3 = createBuild();
		Date build4 = createBuild();

		// when
		BuildPage<Build> result = buildDAO.findAllDescPage(product.getReleaseCenter().getBusinessKey(), product.getBusinessKey(), null, null, null, null, BuildService.View.ALL_RELEASES, PageRequest.of(3, 1));

		// then
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		String lhs = simpleDateFormat.format(build1);
		String rhs = result.getContent().get(0).getCreationTime();
		assertEquals(lhs, rhs);
	}

	private Date createBuild() throws InterruptedException, IOException {
		Thread.sleep(1000); // Sleep for different time
		Date date = new Date();
		Build build4 = new Build(date, product.getReleaseCenter().getBusinessKey(), product.getBusinessKey(), product.getBuildConfiguration(), product.getQaTestConfig());
		buildDAO.save(build4);

		return date;
	}

}


text:
layout: post
title: Reading List (#16)
permalink: Reading-List-16
comments: True
---

Interesting **general programming** links are:

* A Toolkit to Measure Basic System Performance and OS Jitter - High Scalability -!

* Rust for Python Programmers | Armin Ronacher's Thoughts and Writings!

* Live streaming web audio and video!

* Riding the Magic Escalator of Acquired Knowledge — Medium!

* Delegating Is Not Just for Managers!

* How I Was Able to Ace Exams Without Studying : zen habits!

* How to Empower Your Quality Assurance Teams!

* A new mobile browser is Google's worst nightmare!

* the responsibility we have as software engineers!

* Service-Disoriented Architecture and Microservice Envy!

{% include twitter_plug.html %}


text:
title: Notification template examples
sort_rank: 8
---
# Notification Template Examples

The following are all different examples of alerts and corresponding Alertmanager configuration file setups (alertmanager.yml).
Each use the [Go templating](http://golang.org/pkg/text/template/) system.

## Customizing Slack notifications

In this example we've customised our Slack notification to send a URL to our organisation's wiki on how to deal with the particular alert that's been sent.

```
global:
  slack_api_url: '<slack_webhook_url>'

route:
  receiver: 'slack-notifications'
  group_by: [alertname, datacenter, app]

receivers:
- name: 'slack-notifications'
  slack_configs:
  - channel: '#alerts'
    text: 'https://internal.myorg.net/wiki/alerts/{{ .GroupLabels.app }}/{{ .GroupLabels.alertname }}'
```

## Accessing annotations in CommonAnnotations

In this example we again customize the text sent to our Slack receiver accessing the `summary` and `description` stored in the `CommonAnnotations` of the data sent by the Alertmanager.

Alert

```
groups:
- name: Instances
  rules:
  - alert: InstanceDown
    expr: up == 0
    for: 5m
    labels:
      severity: page
    # Prometheus templates apply here in the annotation and label fields of the alert.
    annotations:
      description: '{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 5 minutes.'
      summary: 'Instance {{ $labels.instance }} down'
```

Receiver

```
- name: 'team-x'
  slack_configs:
  - channel: '#alerts'
    # Alertmanager templates apply here.
    text: "<!channel> \nsummary: {{ .CommonAnnotations.summary }}\ndescription: {{ .CommonAnnotations.description }}"
```

## Ranging over all received Alerts

Finally, assuming the same alert as the previous example, we customize our receiver to range over all of the alerts received from the Alertmanager, printing their respective annotation summaries and descriptions on new lines.

Receiver

```
- name: 'default-receiver'
  slack_configs:
  - channel: '#alerts'
    title: "{{ range .Alerts }}{{ .Annotations.summary }}\n{{ end }}"
    text: "{{ range .Alerts }}{{ .Annotations.description }}\n{{ end }}"
```

## Defining reusable templates

Going back to our first example, we can also provide a file containing named templates which are then loaded by Alertmanager in order to avoid complex templates that span many lines.
Create a file under `/alertmanager/template/myorg.tmpl` and create a template in it named "slack.myorg.txt":

```
{{ define "slack.myorg.text" }}https://internal.myorg.net/wiki/alerts/{{ .GroupLabels.app }}/{{ .GroupLabels.alertname }}{{ end}}
```

The configuration now loads the template with the given name for the "text" field and we provide a path to our custom template file:

```
global:
  slack_api_url: '<slack_webhook_url>'

route:
  receiver: 'slack-notifications'
  group_by: [alertname, datacenter, app]

receivers:
- name: 'slack-notifications'
  slack_configs:
  - channel: '#alerts'
    text: '{{ template "slack.myorg.text" . }}'

templates:
- '/etc/alertmanager/templates/myorg.tmpl'
```

This example is explained in further detail in this [blogpost](https://prometheus.io/blog/2016/03/03/custom-alertmanager-templates/).


text:
// transformation.test
/* eslint-env jest */

import {
  addTransformations,
  removeTransformations,
  getTransformations,
  findTransformations,
  execPreParser,
  execPostParser
} from './transformation.js'

describe('test transformations apis', () => {
  test(' add one transformation object', () => {
    const result = addTransformations({
      patterns: [
        /http(s?):\/\/([\w]+.)?def.tld\/*/
      ],
      pre: (document) => {
        return document
      },
      post: (document) => {
        return document
      }
    })
    expect(result).toEqual(1)
  })

  test(' add multi transformation object', () => {
    const result = addTransformations([
      {
        patterns: [
          /http(s?):\/\/google.com\/*/,
          /http(s?):\/\/goo.gl\/*/
        ]
      },
      {
        patterns: [
          /http(s?):\/\/goo.gl\/*/,
          /http(s?):\/\/google.inc\/*/
        ]
      }
    ])
    expect(result).toEqual(2)
  })

  test(' add transformation object without patterns', () => {
    const result = addTransformations({
      pre: (document) => {
        return document
      },
      post: (document) => {
        return document
      }
    })
    expect(result).toEqual(0)
  })

  test(' add transformation object without valid patterns', () => {
    const result = addTransformations({
      patterns: 123,
      pre: (document) => {
        return document
      },
      post: (document) => {
        return document
      }
    })
    expect(result).toEqual(0)
  })

  test(' get all transformations', () => {
    const result = getTransformations()
    expect(result).toHaveLength(3)
    expect(result[0].patterns[0]).toEqual(/http(s?):\/\/([\w]+.)?def.tld\/*/)
  })

  test(' remove one transformation', () => {
    addTransformations([
      {
        patterns: [
          /http(s?):\/\/abc.com\/*/,
          /http(s?):\/\/def.gl\/*/
        ]
      },
      {
        patterns: [
          /http(s?):\/\/hik.gl\/*/,
          /http(s?):\/\/lmn.inc\/*/
        ]
      },
      {
        patterns: [
          /http(s?):\/\/opq.gl\/*/,
          /http(s?):\/\/rst.inc\/*/
        ]
      }
    ])
    const result = removeTransformations([
      /http(s?):\/\/goo.gl\/*/
    ])
    expect(result).toEqual(2)
  })

  test(' get all transformations again', () => {
    const result = getTransformations()
    expect(result).toHaveLength(4)
    expect(result[3].patterns[1]).toEqual(/http(s?):\/\/rst.inc\/*/)
  })

  test(' find transformations', () => {
    addTransformations([
      {
        patterns: [
          /http(s?):\/\/def.gl\/*/,
          /http(s?):\/\/uvw.inc\/*/
        ]
      }
    ])
    const notFound = findTransformations([
      'https://goo.gl/docs/article.html'
    ])
    expect(notFound).toEqual([])

    const foundOne = findTransformations([
      'https://lmn.inc/docs/article.html'
    ])
    expect(foundOne).toHaveLength(1)

    const foundTwo = findTransformations([
      'https://def.gl/docs/article.html'
    ])
    expect(foundTwo).toHaveLength(2)
  })

  test(' run execPreParser', () => {
    addTransformations([
      {
        patterns: [
          /http(s?):\/\/xyz.com\/*/
        ],
        pre: (doc) => {
          doc.querySelectorAll('.adv').forEach((element) => {
            element.parentNode.removeChild(element)
          })
          return doc
        }
      }
    ])
    const html = `

        hi user, this is an advertisement element

free product now!

    `
    const result = execPreParser(html, 'https://xyz.com/article')
    expect(result.includes('hi user, this is an advertisement element')).toBeTruthy()
    expect(result.includes('
free product now!
')).toBeFalsy()
  })

  test(' run execPostParser', () => {
    addTransformations([
      {
        patterns: [
          /http(s?):\/\/xyz.com\/*/
        ],
        post: (doc) => {
          doc.querySelectorAll('b').forEach((element) => {
            const itag = doc.createElement('i')
            itag.innerHTML = element.innerHTML
            element.parentNode.replaceChild(itag, element)
          })
          return doc
        }
      }
    ])
    const html = `

        hi user,

Thank you for your feedback!

    `
    const result = execPostParser(html, 'https://xyz.com/article')
    expect(result.includes('user')).toBeTruthy()
    expect(result.includes('user')).toBeFalsy()
  })

  test(' remove all transformations', () => {
    const result = removeTransformations()
    expect(result).toEqual(7)
    expect(getTransformations()).toEqual([])
  })
})


text:
require "omniauth-td/version"
require "omniauth/strategies/td"


text:
namespace backend {
namespace {{namespace}} {

    namespace {

        {% set methodsWithExtraValidation = (
            "CommandBufferBuilderGetResult",
            "QueueSubmit",
        ) %}

        {% for type in by_category["object"] %}
            {% for method in native_methods(type) %}
                {% set suffix = as_MethodSuffix(type.name, method.name) %}

                //* Entry point without validation, forwards the arguments to the method directly
                {{as_backendType(method.return_type)}} NonValidating{{suffix}}(
                    {{-as_backendType(type)}} self
                    {%- for arg in method.arguments -%}
                        , {{as_annotated_backendType(arg)}}
                    {%- endfor -%}
                ) {
                    {% if method.return_type.name.canonical_case() != "void" %}
                        auto result =
                    {%- endif %}
                    self->{{method.name.CamelCase()}}(
                        {%- for arg in method.arguments -%}
                            {%- if not loop.first %}, {% endif -%}
                            {%- if arg.type.category in ["enum", "bitmask"] -%}
                                static_cast<dawn::{{as_cppType(arg.type.name)}}>({{as_varName(arg.name)}})
                            {%- elif arg.type.category == "structure" and arg.annotation != "value" -%}
                                reinterpret_cast<const dawn::{{as_cppType(arg.type.name)}}*>({{as_varName(arg.name)}})
                            {%- else -%}
                                {{as_varName(arg.name)}}
                            {%- endif -%}
                        {%- endfor -%}
                    );
                    {% if method.return_type.name.canonical_case() != "void" %}
                        return reinterpret_cast<{{as_backendType(method.return_type)}}>(result);
                    {% endif %}
                }

                //* Autogenerated part of the entry point validation
                //*  - Check that enum and bitmaks are in the correct range
                //*  - Check that builders have not been consumed already
                //*  - Others TODO
                bool ValidateBase{{suffix}}(
                    {{-as_backendType(type)}} self
                    {%- for arg in method.arguments -%}
                        , {{as_annotated_backendType(arg)}}
                    {%- endfor -%}
                ) {
                    {% if type.is_builder and method.name.canonical_case() not in ("release", "reference") %}
                        if (!self->CanBeUsed()) {
                            self->GetDevice()->HandleError("Builder cannot be used after GetResult");
                            return false;
                        }
                    {% else %}
                        (void) self;
                    {% endif %}
                    bool error = false;
                    {% for arg in method.arguments %}
                        {% set cppType = as_cppType(arg.type.name) %}
                        {% set argName = as_varName(arg.name) %}
                        {% if arg.type.category in ["enum", "bitmask"] %}
                            MaybeError {{argName}}Valid = Validate{{cppType}}(static_cast<dawn::{{cppType}}>({{argName}}));
                            if ({{argName}}Valid.IsError()) {
                                delete {{argName}}Valid.AcquireError();
                                error = true;
                            }
                        {% else %}
                            (void) {{argName}};
                        {% endif %}
                        if (error) {
                            {% if type.is_builder %}
                                self->HandleError("Bad value in {{suffix}}");
                            {% else %}
                                self->GetDevice()->HandleError("Bad value in {{suffix}}");
                            {% endif %}
                            return false;
                        }
                    {% endfor %}
                    return true;
                }

                //* Entry point with validation
                {{as_backendType(method.return_type)}} Validating{{suffix}}(
                    {{-as_backendType(type)}} self
                    {%- for arg in method.arguments -%}
                        , {{as_annotated_backendType(arg)}}
                    {%- endfor -%}
                ) {
                    //* Do the autogenerated checks
                    bool valid = ValidateBase{{suffix}}(self
                        {%- for arg in method.arguments -%}
                            , {{as_varName(arg.name)}}
                        {%- endfor -%}
                    );

                    //* Some function have very heavy checks in a seperate method, so that they
                    //* can be skipped in the NonValidatingEntryPoints.
                    {% if suffix in methodsWithExtraValidation %}
                        if (valid) {
                            MaybeError error = self->Validate{{method.name.CamelCase()}}(
                                {%- for arg in method.arguments -%}
                                    {% if not loop.first %}, {% endif %}{{as_varName(arg.name)}}
                                {%- endfor -%}
                            );
                            //* Builders want to handle error themselves, unpack the error and make
                            //* the builder handle it.
                            {% if type.is_builder %}
                                if (error.IsError()) {
                                    ErrorData* errorData = error.AcquireError();
                                    self->HandleError(errorData->GetMessage().c_str());
                                    delete errorData;
                                    valid = false;
                                }
                            {% else %}
                                //* Non-builder errors are handled by the device
                                valid = !self->GetDevice()->ConsumedError(std::move(error));
                            {% endif %}
                        }
                    {% endif %}

                    //* HACK(cwallez@chromium.org): special casing GetResult so that the error callback
                    //* is called if needed. Without this, no call to HandleResult would happen, and the
                    //* error callback would always get called with an Unknown status
                    {% if type.is_builder and method.name.canonical_case() == "get result" %}
                        if (!valid) {
                            {{as_backendType(method.return_type)}} fakeResult = nullptr;
                            bool shouldBeFalse = self->HandleResult(fakeResult);
                            ASSERT(shouldBeFalse == false);
                        }
                    {% endif %}

                    {% if method.return_type.name.canonical_case() == "void" %}
                        if (!valid) return;
                    {% else %}
                        if (!valid) {
                            return {};
                        }
                        auto result =
                    {%- endif %}
                    self->{{method.name.CamelCase()}}(
                        {%- for arg in method.arguments -%}
                            {%- if not loop.first %}, {% endif -%}
                            {%- if arg.type.category in ["enum", "bitmask"] -%}
                                static_cast<dawn::{{as_cppType(arg.type.name)}}>({{as_varName(arg.name)}})
                            {%- elif arg.type.category == "structure" and arg.annotation != "value" -%}
                                reinterpret_cast<const dawn::{{as_cppType(arg.type.name)}}*>({{as_varName(arg.name)}})
                            {%- else -%}
                                {{as_varName(arg.name)}}
                            {%- endif -%}
                        {%- endfor -%}
                    );
                    {% if method.return_type.name.canonical_case() != "void" %}
                        return reinterpret_cast<{{as_backendType(method.return_type)}}>(result);
                    {% endif %}
                }
            {% endfor %}
        {% endfor %}
    }

    dawnProcTable GetNonValidatingProcs() {
        dawnProcTable table;
        {% for type in by_category["object"] %}
            {% for method in native_methods(type) %}
                table.{{as_varName(type.name, method.name)}} = reinterpret_cast<{{as_cProc(type.name, method.name)}}>(NonValidating{{as_MethodSuffix(type.name, method.name)}});
            {% endfor %}
        {% endfor %}
        return table;
    }

    dawnProcTable GetValidatingProcs() {
        dawnProcTable table;
        {% for type in by_category["object"] %}
            {% for method in native_methods(type) %}
                table.{{as_varName(type.name, method.name)}} = reinterpret_cast<{{as_cProc(type.name, method.name)}}>(Validating{{as_MethodSuffix(type.name, method.name)}});
            {% endfor %}
        {% endfor %}
        return table;
    }
}
}