text:
package graphql

import (
	"encoding/json"
	"fmt"
	"math"
	"reflect"
	"sort"
	"strings"

	"github.com/equinux/graphql/gqlerrors"
	"github.com/equinux/graphql/language/ast"
	"github.com/equinux/graphql/language/kinds"
	"github.com/equinux/graphql/language/printer"
)

// Prepares an object map of variableValues of the correct type based on the
// provided variable definitions and arbitrary input. If the input cannot be
// parsed to match the variable definitions, a GraphQLError will be returned.
func getVariableValues(
	schema Schema,
	definitionASTs []*ast.VariableDefinition,
	inputs map[string]interface{}) (map[string]interface{}, error) {
	values := map[string]interface{}{}
	for _, defAST := range definitionASTs {
		if defAST == nil || defAST.Variable == nil || defAST.Variable.Name == nil {
			continue
		}
		varName := defAST.Variable.Name.Value
		if varValue, err := getVariableValue(schema, defAST, inputs[varName]); err != nil {
			return values, err
		} else {
			values[varName] = varValue
		}
	}
	return values, nil
}

// Prepares an object map of argument values given a list of argument
// definitions and list of argument AST nodes.
func getArgumentValues(
	argDefs []*Argument, argASTs []*ast.Argument,
	variableValues map[string]interface{}) map[string]interface{} {

	argASTMap := map[string]*ast.Argument{}
	for _, argAST := range argASTs {
		if argAST.Name != nil {
			argASTMap[argAST.Name.Value] = argAST
		}
	}
	results := map[string]interface{}{}
	for _, argDef := range argDefs {
		var (
			tmp   interface{}
			value ast.Value
		)
		if tmpValue, ok := argASTMap[argDef.PrivateName]; ok {
			value = tmpValue.Value
		}
		if tmp = valueFromAST(value, argDef.Type, variableValues); isNullish(tmp) {
			tmp = argDef.DefaultValue
		}
		if !isNullish(tmp) {
			results[argDef.PrivateName] = tmp
		}
	}
	return results
}

// Given a variable definition, and any value of input, return a value which
// adheres to the variable definition, or throw an error.
func getVariableValue(schema Schema, definitionAST *ast.VariableDefinition, input interface{}) (interface{}, error) {
	ttype, err := typeFromAST(schema, definitionAST.Type)
	if err != nil {
		return nil, err
	}
	variable := definitionAST.Variable

	if ttype == nil || !IsInputType(ttype) {
		return "", gqlerrors.NewError(
			fmt.Sprintf(`Variable "$%v" expected value of type `+
				`"%v" which cannot be used as an input type.`, variable.Name.Value, printer.Print(definitionAST.Type)),
			[]ast.Node{definitionAST},
			"",
			nil,
			[]int{},
			nil,
		)
	}

	isValid, messages := isValidInputValue(input, ttype)
	if isValid {
		if isNullish(input) {
			if definitionAST.DefaultValue != nil {
				return valueFromAST(definitionAST.DefaultValue, ttype, nil), nil
			}
		}
		return coerceValue(ttype, input), nil
	}
	if isNullish(input) {
		return "", gqlerrors.NewError(
			fmt.Sprintf(`Variable "$%v" of required type `+
				`"%v" was not provided.`, variable.Name.Value, printer.Print(definitionAST.Type)),
			[]ast.Node{definitionAST},
			"",
			nil,
			[]int{},
			nil,
		)
	}
	// convert input interface into string for error message
	bts, _ := json.Marshal(input)
	var (
		inputStr = string(bts)
		msg      string
	)
	if len(messages) > 0 {
		msg = "\n" + strings.Join(messages, "\n")
	}

	return "", gqlerrors.NewError(
		fmt.Sprintf(`Variable "$%v" got invalid value `+
			`%v.%v`, variable.Name.Value, inputStr, msg),
		[]ast.Node{definitionAST},
		"",
		nil,
		[]int{},
		nil,
	)
}

// Given a type and any value, return a runtime value coerced to match the type.
func coerceValue(ttype Input, value interface{}) interface{} {
	if isNullish(value) {
		return nil
	}
	switch ttype := ttype.(type) {
	case *NonNull:
		return coerceValue(ttype.OfType, value)
	case *List:
		var values = []interface{}{}
		valType := reflect.ValueOf(value)
		if valType.Kind() == reflect.Slice {
			for i := 0; i < valType.Len(); i++ {
				val := valType.Index(i).Interface()
				values = append(values, coerceValue(ttype.OfType, val))
			}
			return values
		}
		return append(values, coerceValue(ttype.OfType, value))
	case *InputObject:
		var obj = map[string]interface{}{}
		valueMap, _ := value.(map[string]interface{})
		if valueMap == nil {
			valueMap = map[string]interface{}{}
		}

		for name, field := range ttype.Fields() {
			fieldValue := coerceValue(field.Type, valueMap[name])
			if isNullish(fieldValue) {
				fieldValue = field.DefaultValue
			}
			if !isNullish(fieldValue) {
				obj[name] = fieldValue
			}
		}
		return obj
	case *Scalar:
		if parsed := ttype.ParseValue(value); !isNullish(parsed) {
			return parsed
		}
	case *Enum:
		if parsed := ttype.ParseValue(value); !isNullish(parsed) {
			return parsed
		}
	}

	return nil
}

// graphql-js/src/utilities.js`
// TODO: figure out where to organize utils
// TODO: change to *Schema
func typeFromAST(schema Schema, inputTypeAST ast.Type) (Type, error) {
	switch inputTypeAST := inputTypeAST.(type) {
	case *ast.List:
		innerType, err := typeFromAST(schema, inputTypeAST.Type)
		if err != nil {
			return nil, err
		}
		return NewList(innerType), nil
	case *ast.NonNull:
		innerType, err := typeFromAST(schema, inputTypeAST.Type)
		if err != nil {
			return nil, err
		}
		return NewNonNull(innerType), nil
	case *ast.Named:
		nameValue := ""
		if inputTypeAST.Name != nil {
			nameValue = inputTypeAST.Name.Value
		}
		ttype := schema.Type(nameValue)
		return ttype, nil
	default:
		return nil, invariant(inputTypeAST.GetKind() == kinds.Named, "Must be a named type.")
	}
}

// isValidInputValue alias isValidJSValue
// Given a value and a GraphQL type, determine if the value will be
// accepted for that type. This is primarily useful for validating the
// runtime values of query variables.
func isValidInputValue(value interface{}, ttype Input) (bool, []string) {
	if isNullish(value) {
		if ttype, ok := ttype.(*NonNull); ok {
			if ttype.OfType.Name() != "" {
				return false, []string{fmt.Sprintf(`Expected "%v!", found null.`, ttype.OfType.Name())}
			}
			return false, []string{"Expected non-null value, found null."}
		}
		return true, nil
	}
	switch ttype := ttype.(type) {
	case *NonNull:
		return isValidInputValue(value, ttype.OfType)
	case *List:
		valType := reflect.ValueOf(value)
		if valType.Kind() == reflect.Ptr {
			valType = valType.Elem()
		}
		if valType.Kind() == reflect.Slice {
			messagesReduce := []string{}
			for i := 0; i < valType.Len(); i++ {
				val := valType.Index(i).Interface()
				_, messages := isValidInputValue(val, ttype.OfType)
				for idx, message := range messages {
					messagesReduce = append(messagesReduce, fmt.Sprintf(`In element #%v: %v`, idx+1, message))
				}
			}
			return (len(messagesReduce) == 0), messagesReduce
		}
		return isValidInputValue(value, ttype.OfType)

	case *InputObject:
		messagesReduce := []string{}

		valueMap, ok := value.(map[string]interface{})
		if !ok {
			return false, []string{fmt.Sprintf(`Expected "%v", found not an object.`, ttype.Name())}
		}
		fields := ttype.Fields()

		// to ensure stable order of field evaluation
		fieldNames := []string{}
		valueMapFieldNames := []string{}

		for fieldName := range fields {
			fieldNames = append(fieldNames, fieldName)
		}
		sort.Strings(fieldNames)

		for fieldName := range valueMap {
			valueMapFieldNames = append(valueMapFieldNames, fieldName)
		}
		sort.Strings(valueMapFieldNames)

		// Ensure every provided field is defined.
		for _, fieldName := range valueMapFieldNames {
			if _, ok := fields[fieldName]; !ok {
				messagesReduce = append(messagesReduce, fmt.Sprintf(`In field "%v": Unknown field.`, fieldName))
			}
		}

		// Ensure every defined field is valid.
		for _, fieldName := range fieldNames {
			_, messages := isValidInputValue(valueMap[fieldName], fields[fieldName].Type)
			if messages != nil {
				for _, message := range messages {
					messagesReduce = append(messagesReduce, fmt.Sprintf(`In field "%v": %v`, fieldName, message))
				}
			}
		}
		return (len(messagesReduce) == 0), messagesReduce
	case *Scalar:
		if parsedVal := ttype.ParseValue(value); isNullish(parsedVal) {
			return false, []string{fmt.Sprintf(`Expected type "%v", found "%v".`, ttype.Name(), value)}
		}
	case *Enum:
		if parsedVal := ttype.ParseValue(value); isNullish(parsedVal) {
			return false, []string{fmt.Sprintf(`Expected type "%v", found "%v".`, ttype.Name(), value)}
		}
	}

	return true, nil
}

// Returns true if a value is null, undefined, or NaN.
func isNullish(src interface{}) bool {
	if src == nil {
		return true
	}
	value := reflect.ValueOf(src)
	if value.Kind() == reflect.Ptr {
		if value.IsNil() {
			return true
		}
		value = value.Elem()
	}
	if value.Kind() == reflect.Invalid {
		return true
	}
	switch value.Kind() {
	case reflect.String:
		// if src is ptr type and len(string)=0, it returns false
		if !value.IsValid() {
			return true
		}
	case reflect.Int:
		return math.IsNaN(float64(value.Int()))
	case reflect.Float32, reflect.Float64:
		return math.IsNaN(float64(value.Float()))
	}
	return false
}

// Returns true if src is a slice or an array
func isIterable(src interface{}) bool {
	if src == nil {
		return false
	}
	t := reflect.TypeOf(src)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	return t.Kind() == reflect.Slice || t.Kind() == reflect.Array
}

/**
 * Produces a value given a GraphQL Value AST.
 *
 * A GraphQL type must be provided, which will be used to interpret different
 * GraphQL Value literals.
 *
 * | GraphQL Value        | JSON Value    |
 * | -------------------- | ------------- |
 * | Input Object         | Object        |
 * | List                 | Array         |
 * | Boolean              | Boolean       |
 * | String / Enum Value  | String        |
 * | Int / Float          | Number        |
 *
 */
func valueFromAST(valueAST ast.Value, ttype Input, variables map[string]interface{}) interface{} {
	if valueAST == nil {
		return nil
	}
	// precedence: value > type
	if valueAST, ok := valueAST.(*ast.Variable); ok {
		if valueAST.Name == nil || variables == nil {
			return nil
		}
		// Note: we're not doing any checking that this variable is correct. We're
		// assuming that this query has been validated and the variable usage here
		// is of the correct type.
		return variables[valueAST.Name.Value]
	}
	switch ttype := ttype.(type) {
	case *NonNull:
		return valueFromAST(valueAST, ttype.OfType, variables)
	case *List:
		values := []interface{}{}
		if valueAST, ok := valueAST.(*ast.ListValue); ok {
			for _, itemAST := range valueAST.Values {
				values = append(values, valueFromAST(itemAST, ttype.OfType, variables))
			}
			return values
		}
		return append(values, valueFromAST(valueAST, ttype.OfType, variables))
	case *InputObject:
		var (
			ok bool
			ov *ast.ObjectValue
			of *ast.ObjectField
		)
		if ov, ok = valueAST.(*ast.ObjectValue); !ok {
			return nil
		}
		fieldASTs := map[string]*ast.ObjectField{}
		for _, of = range ov.Fields {
			if of == nil || of.Name == nil {
				continue
			}
			fieldASTs[of.Name.Value] = of
		}
		obj := map[string]interface{}{}
		for name, field := range ttype.Fields() {
			var value interface{}
			if of, ok = fieldASTs[name]; ok {
				value = valueFromAST(of.Value, field.Type, variables)
			} else {
				value = field.DefaultValue
			}
			if !isNullish(value) {
				obj[name] = value
			}
		}
		return obj
	case *Scalar:
		return ttype.ParseLiteral(valueAST)
	case *Enum:
		return ttype.ParseLiteral(valueAST)
	}

	return nil
}

func invariant(condition bool, message string) error {
	if !condition {
		return gqlerrors.NewFormattedError(message)
	}
	return nil
}

func invariantf(condition bool, format string, a ...interface{}) error {
	if !condition {
		return gqlerrors.NewFormattedError(fmt.Sprintf(format, a...))
	}
	return nil
}


text:
require 'rubygems'
require 'sinatra'
require 'config/init'

get '/' do
  @person = Person.rand
  erb :home
end

get '/people' do
  @people = Person.all
  erb :people_index
end

get '/people/new' do
  @person = Person.new
  erb :people_new
end

post '/people' do
  person = Person.new(params).save or halt 400
  redirect "/people/#{person.id}"
end

get '/people/:id' do
  @person = Person[params[:id]] or halt 404
  erb :people_show
end

get '/people/:id/edit' do
  @person = Person[params[:id]] or halt 404
  erb :people_edit
end

put '/people/:id' do
  @person = Person[params[:id]] or halt 404
  @person.update(params) or halt 400
  redirect "/people/#{@person.id}"
end

delete '/people/:id' do
  @person = Person[params[:id]] or halt 404
  @person.delete
  redirect '/people'
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

-->
<sugarcolors version="1.0">
    <charts>
        <docBorder>0xcccccc</docBorder>
		<docBackground>0xffffff</docBackground>
		<labelFontFamily>Arial</labelFontFamily>
		<labelFontColor>0x000000</labelFontColor>
        <scrollButtonFill>0x999999</scrollButtonFill>
        <scrollButtonArrow>0x333333</scrollButtonArrow>
        <scrollBarHighlight>off</scrollBarHighlight>
        <scrollBarFill>0xcccccc</scrollBarFill>
		<scrollBarEdge>0x777777</scrollBarEdge>
        <scrollBarTrackFill>0xdddddd</scrollBarTrackFill>
        <scrollBarTrackEdge>0x999999</scrollBarTrackEdge>

        <chartGlow>0xffffff</chartGlow>
        <chartFill>0xBBBBBB</chartFill>
        <chartEdge>off</chartEdge>
        <chartHighlight>0xeeeeee</chartHighlight>
		<chartHighlightAlpha>off</chartHighlightAlpha>

		<lineThickness>1</lineThickness>
		<gridLineThickness>1</gridLineThickness>
		<linesOn>on</linesOn>

		<needleColor>0xff0000</needleColor>
		<needleAlpha>50</needleAlpha>

        <yAxisBack>off</yAxisBack>
        <gridLines>0xcccccc</gridLines>

        <legendFill>0xf0f0f0</legendFill>
		<legendEdge>0xdddddd</legendEdge>
        <legendFill2>0xf0f0f0</legendFill2>
		<legendEdge2>off</legendEdge2>
        <legendEntryEdge>0x999999</legendEntryEdge>

		<toolTipAlpha>80</toolTipAlpha>
		<toolTipBack>0xffffff</toolTipBack>
		<toolTipBorder>0x666666</toolTipBorder>

		<flyOutAlpha>100</flyOutAlpha>
		<flyOutBack>0xdddddd</flyOutBack>
		<flyOutTitleBack>0x333333</flyOutTitleBack>
		<flyOutBorder>0x000000</flyOutBorder>
		<flyOutDisplayDisabled>off</flyOutDisplayDisabled>

		<thumbnailEdge>0xeeeeee</thumbnailEdge>
		<thumbnailColor1>0xDD5555</thumbnailColor1>
		<thumbnailColor2>0xDDAA55</thumbnailColor2>
		<thumbnailColor3>0x5555AA</thumbnailColor3>

		<printEdge>0xffffff</printEdge>
		<printFill>0xffffff</printFill>

		<labelColor>style</labelColor>
		<chartElementColors>
			<color>0x8c2b2b</color>
			<color>0x468c2b</color>
			<color>0x2b5d8c</color>
			<color>0xcd5200</color>
			<color>0xe6bf00</color>
			<color>0x7f3acd</color>
			<color>0x00a9b8</color>
			<color>0x572323</color>
			<color>0x004d00</color>
			<color>0x000087</color>
			<color>0xe48d30</color>
			<color>0x9fba09</color>
			<color>0x560066</color>
			<color>0x009f92</color>
			<color>0xb36262</color>
			<color>0x38795c</color>
			<color>0x3D3D99</color>
			<color>0x99623d</color>
			<color>0x998a3d</color>
			<color>0x994e78</color>
			<color>0x3d6899</color>
			<color>0xCC0000</color>
			<color>0x00CC00</color>
			<color>0x0000CC</color>
			<color>0xcc5200</color>
			<color>0xccaa00</color>
			<color>0x6600cc</color>
			<color>0x005fcc</color>
		</chartElementColors>
		<gaugeChartElementColors>
			<color>0xcc0000</color>
			<color>0x990000</color>
			<color>0xe65c00</color>
			<color>0xe6bf00</color>
			<color>0x009900</color>
		</gaugeChartElementColors>

		<fadedEdges>off</fadedEdges>

		<lightColor>0.2</lightColor>
		<darkColor>0.2</darkColor>
		<darkerColor>0.45</darkerColor>

		<squeezedPieWedgeLabel>on</squeezedPieWedgeLabel>
		<squeezedPieWedgeThreshold>0.22</squeezedPieWedgeThreshold>
		<pieLabelBackFill>0xeeeeee</pieLabelBackFill>
		<pieLabelBackEdge>0x666666</pieLabelBackEdge>
		<pieLabelAlpha>100</pieLabelAlpha>
    </charts>
</sugarcolors>


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

package my.home.lehome.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class CommonUtils {

    public static String removeLastChar(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        return s.substring(0, s.length() - 1);
    }

    public static boolean copyStringToClipboard(Context context, String label, String src) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, src);
        clipboard.setPrimaryClip(clip);
        return true;
    }

    public static String getDateFormatString(String format) {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat(format, Locale.getDefault()); //called without pattern
        return df.format(c.getTime());
    }

    public static String concatenateStrings(String[] targets) {
        StringBuilder sb = new StringBuilder();
        for (String target :
                targets) {
            sb.append(target);
        }
        return sb.toString();
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />

<link rel="stylesheet" href="css/poole.css" />
<link rel="stylesheet" href="css/syntax.css" />
<link rel="stylesheet" href="css/hyde.css" />
<link rel="stylesheet" href="css/theme.css" />
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=PT+Sans:400,700|Russo+One" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" />

Děkujeme za podporu Blokády. To je důvod, proč může být tato aplikace zdearma, bezpečná a nezávislá. Prosím zvolte možnost darovat,která vám vyhovuje. V případě problému nás kontaktujte na adrese hello@blokada.org.

Darovat (doporučeno)

Pokud nemáte specifické požadavky, použijte tlačítko níže, aby se provedl váš dar. Kreditní karty, PayPal a další jsou podporovány.

Darovat

Staňte se Partnerem

Pomáte nám zajistit udržitelný rozvoj Blokády a stal se jejím Partnerem. Zkontrolujte, zda jste odměny dostal-la za vaši podporu!

Darovat Bitcoiny

Pokud dáváte přednost, aby jste nás podpořil s BTC, tady je naše peněženka:

16rJ49uNKCohVhHvWNganP6Y48Ba9BTyKd

Darování ethereum

V neposlední řadě, ETH dary jsou vítány zde:

0x91F94632B8269F92E6B41E016458EeA682a10395


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

package org.flowable.engine.impl.cmd;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.engine.common.api.FlowableObjectNotFoundException;
import org.flowable.engine.impl.interceptor.Command;
import org.flowable.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.runtime.Execution;

/**
 * @author Tom Baeyens
 * @author Joram Barrez
 */
public class FindActiveActivityIdsCmd implements Command<List<String>>, Serializable {

  private static final long serialVersionUID = 1L;
  protected String executionId;

  public FindActiveActivityIdsCmd(String executionId) {
    this.executionId = executionId;
  }

  public List<String> execute(CommandContext commandContext) {
    if (executionId == null) {
      throw new FlowableIllegalArgumentException("executionId is null");
    }

    ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
    ExecutionEntity execution = executionEntityManager.findById(executionId);

    if (execution == null) {
      throw new FlowableObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class);
    }

    return findActiveActivityIds(execution);
  }

  public List<String> findActiveActivityIds(ExecutionEntity executionEntity) {
    List<String> activeActivityIds = new ArrayList<String>();
    collectActiveActivityIds(executionEntity, activeActivityIds);
    return activeActivityIds;
  }

  protected void collectActiveActivityIds(ExecutionEntity executionEntity, List<String> activeActivityIds) {
    if (executionEntity.isActive() && executionEntity.getActivityId() != null) {
      activeActivityIds.add(executionEntity.getActivityId());
    }

    for (ExecutionEntity childExecution : executionEntity.getExecutions()) {
      collectActiveActivityIds(childExecution, activeActivityIds);
    }
  }

}


text:
classdef Experiment < handle
    %UNTITLED Summary of this class goes here
    %   Detailed explanation goes here

    properties (SetAccess = private)
        name

        conditions

        parameters

        dataOutputFile

        objectTree

        objectTable

        ID
    end

    methods
        function obj = Experiment(name)
            %experiment name
            obj.name = name{1};

            %uniqe ID
            obj.ID = java.rmi.server.UID;

            disp('new Experiment created...');

            %create object reference (handles) table - required for
            %modification of objects later on (a link between objects and
            %their ID within the tree)
            obj.objectTable = Tree2Object();
            obj.objectTable.addObj(obj.ID,'experiment');
            %initialize a structure for conditions
            obj.conditions = Condition.empty(0,0);

        end

        function result = addCondition(obj,condition)
            %initialize variable donotadd
            donotadd = false;

            %check if condition doesn't already exist
            if(size(obj.conditions) == 0)
                obj.conditions(end+1) = condition;
                disp(['added condition ',condition.name,' to experiment']);
                obj.objectTable.addObj(condition.getID,'condition');
                result = true;
            else
                for i=1 : numel(obj.conditions)
                    if(strcmp(obj.conditions(i).name,condition.name))
                        disp('name already found in experiment, aborting addition of condition');
                        donotadd = true;
                        result = false;
                        break;
                    end
                end

                if ~donotadd
                    %return true, the addition will be made
                    result = true;
                    %add new object to the object table
                    obj.objectTable.addObj(condition.getID,'condition');
                    %add the condition object handle to conditions in
                    %object
                    obj.conditions(end+1) = condition;
                    disp(['added condition ',condition.name,' to experiment']);
                end % end of if
            end
        end % end of function

        function removeCondition(obj,condition)
            %seek condition by name and remove it
            for i=1 : numel(obj.conditions)
                if(strcmp(obj.conditions(i).name,condition))
                    disp('removing condition ');
                    obj.conditions(i) = [];
                    obj.objectTable.removeObj(condition(i).getID);
                    break;
                end
            end
        end

        function set.objectTree(obj,treeH)
            obj.objectTree = treeH;
            disp('added the object Tree to the experiment');
            %maybe i will need to add some code to the setting of the tree
        end

        %retrieve a handle to the condition with the specified name
        function conditionObj = getCondition(obj,ID)
            for i=1:size(obj.conditions,2)
                if(strcmp(obj.conditions(i).getID.toString,ID.toString))
                    conditionObj = obj.conditions(i);
                    break;
                end
            end
        end

        function type = findObjType(obj,ID)
            type = obj.objectTable.getType(ID);
        end

        function result = getID(obj)
           result = obj.ID ;
        end
    end % end of methods

end


text:
Bootstrap based website for a Finnish charity organization. Fighting for Lives helps street kids in many countries around the world.

### Author / Contact
* ![](https://dl.dropboxusercontent.com/u/633848/Images/github_24_black.png) [github](http://www.github.com/argoncode)
* ![](https://dl.dropboxusercontent.com/u/633848/Images/twitter.png) [twitter](http://twitter.com/argoncode)
* [personal website](http://argoncode.com/contact)

### Used tech and libraries
* HTML
* CSS
* Bootstrap

## Copying / License
MIT

## Bugs
1. Report via pull request and/or comments.
2. Current bugs are on [github issus](https://github.com/ArgonCode/fighting-for-lives/issues) and [waffle](https://waffle.io/ArgonCode/fighting-for-lives).


text:
#pragma once
#include <aws/iotdeviceadvisor/IoTDeviceAdvisor_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/iotdeviceadvisor/model/GroupResult.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTDeviceAdvisor
{
namespace Model
{

  /**
   *
Show each group result.

See Also:
   AWS
   * API Reference

   */
  class AWS_IOTDEVICEADVISOR_API TestResult
  {
  public:
    TestResult();
    TestResult(Aws::Utils::Json::JsonView jsonValue);
    TestResult& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Show each group of test results.

     */
    inline const Aws::Vector<GroupResult>& GetGroups() const{ return m_groups; }

    /**
     *
Show each group of test results.

     */
    inline bool GroupsHasBeenSet() const { return m_groupsHasBeenSet; }

    /**
     *
Show each group of test results.

     */
    inline void SetGroups(const Aws::Vector<GroupResult>& value) { m_groupsHasBeenSet = true; m_groups = value; }

    /**
     *
Show each group of test results.

     */
    inline void SetGroups(Aws::Vector<GroupResult>&& value) { m_groupsHasBeenSet = true; m_groups = std::move(value); }

    /**
     *
Show each group of test results.

     */
    inline TestResult& WithGroups(const Aws::Vector<GroupResult>& value) { SetGroups(value); return *this;}

    /**
     *
Show each group of test results.

     */
    inline TestResult& WithGroups(Aws::Vector<GroupResult>&& value) { SetGroups(std::move(value)); return *this;}

    /**
     *
Show each group of test results.

     */
    inline TestResult& AddGroups(const GroupResult& value) { m_groupsHasBeenSet = true; m_groups.push_back(value); return *this; }

    /**
     *
Show each group of test results.

     */
    inline TestResult& AddGroups(GroupResult&& value) { m_groupsHasBeenSet = true; m_groups.push_back(std::move(value)); return *this; }

  private:

    Aws::Vector<GroupResult> m_groups;
    bool m_groupsHasBeenSet;
  };

} // namespace Model
} // namespace IoTDeviceAdvisor
} // namespace Aws


text:
import time

from annotypes import Anno, add_call_types

from malcolm.core import PartRegistrar
from malcolm.modules import builtin

# Pull re-used annotypes into our namespace in case we are subclassed
APartName = builtin.parts.APartName
AMri = builtin.parts.AMri

with Anno("The demand value to move our counter motor to"):
    ADemand = float
with Anno("The amount of time to get to the demand position"):
    ADuration = float

# How long between ticks of the "motor" position while moving
UPDATE_TICK = 0.1

# We will set these attributes on the child block, so don't save them
@builtin.util.no_save("counter")
class CounterMovePart(builtin.parts.ChildPart):
    """Provides control of a `counter_block` within a `ManagerController`"""

    def __init__(self, name: APartName, mri: AMri) -> None:
        super().__init__(name, mri, stateful=False, initial_visibility=True)

    def setup(self, registrar: PartRegistrar) -> None:
        super().setup(registrar)
        # Method
        registrar.add_method_model(self.move, self.name + "Move", needs_context=True)

    @add_call_types
    def move(
        self, context: builtin.hooks.AContext, demand: ADemand, duration: ADuration = 0
    ) -> None:
        """Move the counter to the demand value, taking duration seconds like
        a motor would do"""
        start = time.time()
        child = context.block_view(self.mri)
        distance = demand - child.counter.value
        remaining = duration
        # "Move" the motor, ticking at UPDATE_TICK rate
        while remaining > 0:
            child.counter.put_value(demand - distance * remaining / duration)
            context.sleep(min(remaining, UPDATE_TICK))
            remaining = start + duration - time.time()
        # Final move to make sure we end up at the right place
        child.counter.put_value(demand)


text:
/** @babel */

import {createRunner} from "atom-jasmine3-test-runner";

module.exports = createRunner({
	specHelper: {
		customMatchers: true,
		attachToDom: true,
		ci: true,
	},
}, () => {
	beforeEach(() => {
		jasmine.clock().install();
	});

	afterEach(() => {
		jasmine.clock().uninstall();
	});
});


text: * First CocoaPods release.


text:
import os, time, datetime
import pygame
from pygame.locals import *
import threading, Queue

TIMEOUT = 20	# seconds
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0,255,255)
VIOLET = (255,0,255)
WHITE = (255,255,255)
BLACK = (0, 0, 0)
ROWHEIGHT = 20
ROWCOUNT = 4

class Screen(threading.Thread):

	def __init__(self):
		self.Event = threading.Event()
		threading.Thread.__init__(self, name='myemulator')
		self.q = Queue.Queue(maxsize=6)
		x = 20
		y = 300
		os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
		pygame.init()
		self.xmax = 220
		self.ymax = 160
		self.ytop = 100
		self.screen = pygame.display.set_mode((self.xmax, self.ymax))
		pygame.display.set_caption('uoled emulator')
		self.background = pygame.Surface(self.screen.get_size())
		self.background = self.background.convert()
		self.background.fill(BLACK)
		self.buttons()
		self.last_prog_row = ROWCOUNT - 2
		self.oldtext = []
		for i in range(ROWCOUNT):
			self.oldtext.append('')
		self.button = ''

	def run(self):
		myevent = False
		while not myevent:
			while not self.q.empty():
				entry = self.q.get()
				self.writerow(entry[0], entry[1])
				self.q.task_done()
			myevent = self.Event.wait(.5)	# wait for this timeout or the flag being set.
			self.master_checks()
		self.cleanup()

	def buttons(self):
		ytop = self.ytop
		pygame.draw.rect(self.background, GREEN ,(20,ytop,20,20))
		pygame.draw.rect(self.background, YELLOW ,(50,ytop,20,20))
		pygame.draw.rect(self.background, BLUE ,(80,ytop,20,20))
		pygame.draw.rect(self.background, CYAN ,(110,ytop,20,20))
		pygame.draw.rect(self.background, WHITE ,(140,ytop,20,20))
		font = pygame.font.Font(None, 12)
		text = font.render('Next', 1, BLACK)
		self.background.blit(text, (20,ytop+5))
		text = font.render('Stop', 1, BLACK)
		self.background.blit(text, (50,ytop+5))
		text = font.render('Vol+', 1, BLACK)
		self.background.blit(text, (80,ytop+5))
		text = font.render('Vol-', 1, BLACK)
		self.background.blit(text, (110,ytop+5))
		text = font.render('Quit', 1, BLACK)
		self.background.blit(text, (140,ytop+5))
		self.screen.blit(self.background, (0, 0))

	def writerow(self, rownumber, string):
		if rownumber > ROWCOUNT-1:
			print 'Row number exceeded:', rownumber
			return(1)
		pygame.draw.rect(self.background, BLACK ,(0,rownumber*ROWHEIGHT,self.xmax,ROWHEIGHT))	# delete old text
		ytop = 100
		ypos = ROWHEIGHT / 2 + (rownumber) * ROWHEIGHT
		font = pygame.font.Font(None, 24)
		text = font.render(string, 1, WHITE)
		textpos = text.get_rect(centery = ypos)
		self.background.blit(text, textpos)
		self.screen.blit(self.background, (0, 0), (0,0,self.xmax,ytop))
		self.oldtext[rownumber] = string
		self.display()

	def display(self):
		pygame.display.update()
		return(0)

	def test(self):
		self.writerow(0,'Emulator test.')
		self.writerow(1,'01234567890')

	def _button_click_test(self):
		mousex, mousey = pygame.mouse.get_pos()
		if mousey > self.ytop and mousey < self.ytop+20:
			if mousex > 20 and mousex < 40:
				print 'next button click'
				self.button = 'Next'
				return(True)
			if mousex > 50 and mousex < 70:
				print 'stop button click'
			if mousex > 80 and mousex < 100:
				print 'vol+ button click'
			if mousex > 110 and mousex < 130:
				print 'vol- button click'
			if mousex > 140 and mousex < 160:
				print 'quit button click'
				self.Event.set()
				return(False)
			return(True)
		else:
			print 'click'
			return(True)

	def master_checks(self):
		timeout = datetime.timedelta(seconds=TIMEOUT)
		start_time = datetime.datetime.now()	 # need to complete this!!
		runner = True
		now = datetime.datetime.now()	 # need to complete this!!
		if (now - start_time) > timeout:
			print 'Timeout'
			myEmulator.q.put([0, 'Timeout'])
			runner = False
		else:
			runner = self._chk_for_quit()
		if self.button == 'Next':
			myEmulator.q.put([0, 'Next button'])
		return(runner)

	def master_loop(self):
		timeout = datetime.timedelta(seconds=TIMEOUT)
		start_time = datetime.datetime.now()	 # need to complete this!!
		runner = True
		while runner:
			pygame.time.wait(500)
			now = datetime.datetime.now()	 # need to complete this!!
			if (now - start_time) > timeout:
				print 'Timeout'
				runner = False
			else:
				runner = self._chk_for_quit()
			if self.button == 'Next':
				myEmulator.q.put([0, 'Next button'])
		print 'Exiting master loop'

	def _chk_for_quit(self):
		for event in pygame.event.get():
			if event.type == QUIT:
				return(False)
				self.Event.set()
			if event.type == MOUSEBUTTONDOWN:
				return(self._button_click_test())
		return(True)

	def info(self):
		return(ROWCOUNT,20)

	def write_radio_extras(self, clock, temperature):
		self.q.put([ROWCOUNT-1,'{0:5s}{1:7.1f}^C'.format(clock.ljust(10),float(temperature))])
		return(0)

	def write_button_labels(self, next, stop):
		return(0)

	def cleanup(self):
		print 'Quiting pygame'
		pygame.quit()

if __name__ == "__main__":
	print 'Emulator test'
	myEmulator = Screen()
	myEmulator.start()
	print threading.enumerate()
	time.sleep(2)
	myEmulator.q.put([0, 'Emulator test'])
	time.sleep(2)
	myEmulator.q.put([1, 'Second row. This is a very long row.'])
	myEmulator.master_loop()

#	myEmulator.test()
#	myEmulator.buttons()
#	myEmulator.display()
#	myEmulator.master_loop()
#	time.sleep(10)
#	myEmulator.Event.set()
#	myEmulator.cleanup()


text:
package snmp

import (
	"fmt"
	"strings"
	"testing"
)

type GetTest struct {
	oid    string
	expect interface{}
}

var getTests = []GetTest{
	{stringType, []byte(nil)},
	{oidType, []int(nil)},
	{timeticksType, int64(0)},
	{counter32Type, int64(0)},
	{counter64Type, int64(0)},
	{gauge32Type, int64(0)},
}

func TestGetNil(t *testing.T) {
	var v interface{}
	for _, test := range getTests {
		if err := Get("localhost", "public", test.oid, &v); err != nil {
			t.Errorf("%s unexpected error: %v", test.oid, err)
			continue
		}
		have := fmt.Sprintf("%T", v)
		want := fmt.Sprintf("%T", test.expect)
		if have != want {
			t.Errorf("%s bad type, want=%s, have=%s", test.oid, want, have)
		}
	}
}

type HostTest struct {
	host   string
	expect string
}

var hostTests = []string{
	"localhost",
	"localhost:161",
}

func TestHostPort(t *testing.T) {
	var want string
	for i, host := range hostTests {
		var v []byte
		if err := Get(host, "public", stringType, &v); err != nil {
			t.Errorf("%s unexpected error: %v", host, err)
			continue
		}
		if have := string(v); i == 0 {
			want = have
		} else if have != want {
			t.Errorf("%s wrong host, want=%s, have=%s", host, want, have)
		}
	}
}

type CommunityTest struct {
	str string
	ok  bool
	err error
}

var communityTests = []CommunityTest{
	{str: "", ok: false},
	{str: "public", ok: true},
	{str: "invalid", ok: false},
}

func TestCommunity(t *testing.T) {
	ch := make(chan CommunityTest)
	for _, test := range communityTests {
		str := test.str
		test := test
		go func() {
			var v interface{}
			test.err = Get("localhost", str, stringType, &v)
			ch <- test
		}()
	}
	for _ = range communityTests {
		test := <-ch
		if (test.err == nil) != test.ok {
			t.Errorf("%s invalid err: %s", test.str, test.err)
		}
	}
}

type TestRun struct {
	req *Request
}

func TestParallel(t *testing.T) {
	const N = 1000
	done := make(chan bool)
	for i := 0; i < N; i++ {
		go func() {
			var v interface{}
			if err := Get("localhost", "public", stringType, &v); err != nil {
				t.Errorf("%d unexpected error: %v", i, err)
			}
			done <- true
		}()
	}
	for i := 0; i < N; i++ {
		<-done
	}
}

type MultiTest struct {
	args   []interface{}
	expect string
}

var outInt int

var multiTests = []MultiTest{
	{[]interface{}{}, ""},
	{[]interface{}{"IF-MIB::ifMtu.1", &outInt}, ""},
	{[]interface{}{"IF-MIB::ifMtu.1", &outInt, "IF-MIB::ifSpeed.1", &outInt}, ""},
}

func TestGetMulti(t *testing.T) {
	for _, test := range multiTests {
		err := Get("localhost", "public", test.args...)
		if (test.expect == "") != (err == nil) {
			t.Errorf("%v: unexpected error: %v", test.args, err)
			continue
		}
		if err == nil {
			continue
		}
		if i := strings.Index(err.Error(), test.expect); i < 0 {
			t.Errorf("%v: unexpected error: %v", test.args, err)
		}
	}
}


text:
[![NPM version](https://badge.fury.io/js/xss.png)](http://badge.fury.io/js/xss)
[![Build Status](https://secure.travis-ci.org/leizongmin/js-xss.png?branch=master)](http://travis-ci.org/leizongmin/js-xss)
[![Dependencies Status](https://david-dm.org/leizongmin/js-xss.png)](https://david-dm.org/leizongmin/js-xss)
[![testling badge](https://ci.testling.com/leizongmin/js-xss.png)](https://ci.testling.com/leizongmin/js-xss)

Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.
======

![xss](https://nodei.co/npm/xss.png?downloads=true&stars=true)

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

**[中文版文档](https://github.com/leizongmin/js-xss/blob/master/README.zh.md)**

`xss` is a module used to filter input from users to prevent XSS attacks.
([What is XSS attack?](http://en.wikipedia.org/wiki/Cross-site_scripting))

This module is needed for situations that allows users to input HTML for
typesetting or formatting, including fourms, blogs, e-shops, etc.

The `xss` module controls the usage of tags and their attributes, according to
the whitelist. It is also extendable with a series of APIs privided, which make
it become more flexible, compares with other modules.

**Project Homepage:** http://jsxss.com

**Try Online:** http://jsxss.com/en/try.html

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

## Features

+ Specifies HTML tags and their attributes allowed with whitelist
+ Handle any tags or attributes using custom function.

## Reference

+ [XSS与字符编码的那些事儿 ---科普文](http://drops.wooyun.org/tips/689)
+ [腾讯实例教程:那些年我们一起学XSS](http://www.wooyun.org/whitehats/%E5%BF%83%E4%BC%A4%E7%9A%84%E7%98%A6%E5%AD%90)
+ [mXSS攻击的成因及常见种类](http://drops.wooyun.org/tips/956)
+ [XSS Filter Evasion Cheat Sheet](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet)
+ [Data URI scheme](http://en.wikipedia.org/wiki/Data_URI_scheme)
+ [XSS with Data URI Scheme](http://hi.baidu.com/badzzzz/item/bdbafe83144619c199255f7b)

## Benchmark (for references only)

+ the xss module: 8.2 MB/s
+ `xss()` function from module `validator@0.3.7`: 4.4 MB/s

For test code please refer to `benchmark` directory.

## Unit Test

Run `npm test` command in the source directary.

## Install

### NPM

```bash
$ npm install xss
```

### Bower

```bash
$ bower install xss
```

Or

```bash
$ bower install https://github.com/leizongmin/js-xss.git
```

## Usages

### On Node.js

```JavaScript
var xss = require('xss');
var html = xss('<script>alert("xss");</script>');
console.log(html);
```

### On Browser

Shim mode (reference file `test/test.html`):

```HTML
<script src="https://raw.github.com/leizongmin/js-xss/master/dist/xss.js"></script>
<script>
// apply function filterXSS in the same way
var html = filterXSS('<script>alert("xss");</scr' + 'ipt>');
alert(html);
</script>
```

AMD mode (reference file `test/test_amd.html`):

```HTML
<script>
require.config({
  baseUrl: './'
})
require(['xss'], function (xss) {
  var html = xss('<script>alert("xss");</scr' + 'ipt>');
  alert(html);
});
</script>
```

## Command Line Tool

### Process File

You can use the xss command line tool to process a file. Usage:

```bash
xss -i <input_file> -o <output_file>
```

Example:

```bash
$ xss -i origin.html -o target.html
```

### Active Test

Run the following command, them you can type HTML
code in the command-line, and check the filtered output:

```bash
$ xss -t
```

For more details, please run `$ xss -h` to see it.

## Custom filter rules

When using the `xss()` function, the second parameter could be used to specify
custom rules:

```JavaScript
options = {};  // Custom rules
html = xss('<script>alert("xss");</script>', options);
```

To avoid passing `options` every time, you can also do it in a faster way by
creating a `FilterXSS` instance:

```JavaScript
options = {};  // Custom rules
myxss = new xss.FilterXSS(options);
// then apply myxss.process()
html = myxss.process('<script>alert("xss");</script>');
```

Details of parameters in `options` would be described below.

### Whitelist

By specifying a `whiteList`, e.g. `{ 'tagName': [ 'attr-1', 'attr-2' ] }`. Tags
and attributes not in the whitelist would be filter out. For example:

```JavaScript
// only tag a and its attributes href, title, target are allowed
var options = {
  whiteList: {
    a: ['href', 'title', 'target']
  }
};
// With the configuration specified above, the following HTML:
// <a href="#" onclick="hello()"><i>Hello</i></a>
// would become:
// <a href="#">Hello</a>
```

For the default whitelist, please refer `xss.whiteList`.

### Customize the handler function for matched tags

By specifying the handler function with `onTag`:

```JavaScript
function onTag (tag, html, options) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // html is the HTML of this tag, e.g. '<a>' for tag <a>
  // options is some addition informations:
  //   isWhite    boolean, whether the tag is in whitelist
  //   isClosing  boolean, whether the tag is a closing tag, e.g. true for </a>
  //   position        integer, the position of the tag in output result
  //   sourcePosition  integer, the position of the tag in input HTML source
  // If a string is returned, the current tag would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter attributes using onTagAttr, as described below
  //   If not in whitelist: handle by onIgnoreTag, as described below
}
```

### Customize the handler function for attributes of matched tags

By specifying the handler function with `onTagAttr`:

```JavaScript
function onTagAttr (tag, name, value, isWhiteAttr) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // name is the name of current attribute, e.g. 'href' for href="#"
  // isWhiteAttr whether the tag is in whitelist
  // If a string is returned, the attribute would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter the value using safeAttrValue as described below
  //   If not in whitelist: handle by onIgnoreTagAttr, as described below
}
```

### Customize the handler function for tags not in the whitelist

By specifying the handler function with `onIgnoreTag`:

```JavaScript
function onIgnoreTag (tag, html, options) {
  // Parameters are the same with onTag
  // If a string is returned, the tag would be replaced with the string
  // If return nothing, the default measure would be taken (specifies using
  // escape, as described below)
}
```

### Customize the handler function for attributes not in the whitelist

By specifying the handler function with `onIgnoreTagAttr`:

```JavaScript
function onIgnoreTagAttr (tag, name, value, isWhiteAttr) {
  // Parameters are the same with onTagAttr
  // If a string is returned, the value would be replaced with this string
  // If return nothing, then keep default (remove the attribute)
}
```

### Customize escaping function for HTML

By specifying the handler function with `escapeHtml`. Following is the default
function **(Modification is not recommended)**:

```JavaScript
function escapeHtml (html) {
  return html.replace(/</g, '<').replace(/>/g, '>');
}
```

### Customize escaping function for value of attributes

By specifying the handler function with `safeAttrValue`:

```JavaScript
function safeAttrValue (tag, name, value) {
  // Parameters are the same with onTagAttr (without options)
  // Return the value as a string
}
```

### Quick Start

#### Filter out tags not in the whitelist

By using `stripIgnoreTag` parameter:

+ `true` filter out tags not in the whitelist
+ `false`: by default: escape the tag using configured `escape` function

Example:

If `stripIgnoreTag = true` is set, the following code:

```HTML
code:<script>alert(/xss/);</script>
```

would output filtered:

```HTML
code:alert(/xss/);
```

#### Filter out tags and tag bodies not in the whitelist

By using `stripIgnoreTagBody` parameter:

+ `false|null|undefined` by default: do nothing
+ `'*'|true`: filter out all tags not in the whitelist
+ `['tag1', 'tag2']`: filter out only specified tags not in the whitelist

Example:

If `stripIgnoreTagBody = ['script']` is set, the following code:

```HTML
code:<script>alert(/xss/);</script>
```

would output filtered:

```HTML
code:
```

#### Filter out HTML comments

By using `allowCommentTag` parameter:

+ `true`: do nothing
+ `false` by default: filter out HTML comments

Example:

If `allowCommentTag = false` is set, the following code:

```HTML
code:<!-- something --> END
```

would output filtered:

```HTML
code: END
```

## Examples

### Allow attributes of whitelist tags start with `data-`

```JavaScript
var source = '<div a="1" b="2" data-a="3" data-b="4">hello</div>';
var html = xss(source, {
  onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
    if (name.substr(0, 5) === 'data-') {
      // escape its value using built-in escapeAttrValue function
      return name + '="' + xss.escapeAttrValue(value) + '"';
    }
  }
});

console.log('%s\nconvert to:\n%s', source, html);
```

Result:

```
<div a="1" b="2" data-a="3" data-b="4">hello</div>
convert to:
<div data-a="3" data-b="4">hello</div>
```

### Allow tags start with `x-`

```JavaScript
var source = '<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>';
var html = xss(source, {
  onIgnoreTag: function (tag, html, options) {
    if (tag.substr(0, 2) === 'x-') {
      // do not filter its attributes
      return html;
    }
  }
});

console.log('%s\nconvert to:\n%s', source, html);
```

Result:

```
<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>
convert to:
<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>
```

### Parse images in HTML

```JavaScript
var source = '<img src="img1">a<img src="img2">b<img src="img3">c<img src="img4">d';
var list = [];
var html = xss(source, {
  onTagAttr: function (tag, name, value, isWhiteAttr) {
    if (tag === 'img' && name === 'src') {
      // Use the built-in friendlyAttrValue function to escape attribute
      // values. It supports converting entity tags such as < to printable
      // characters such as <
      list.push(xss.friendlyAttrValue(value));
    }
    // Return nothing, means keep the default handling measure
  }
});

console.log('image list:\n%s', list.join(', '));
```

Result:

```
image list:
img1, img2, img3, img4
```

### Filter out HTML tags (keeps only plain text)

```JavaScript
var source = '<strong>hello</strong><script>alert(/xss/);</script>end';
var html = xss(source, {
  whiteList:          [],        // empty, means filter out all tags
  stripIgnoreTag:     true,      // filter out all HTML not in the whilelist
  stripIgnoreTagBody: ['script'] // the script tag is a special case, we need
                                 // to filter out its content
});

console.log('text: %s', html);
```

Result:

```
text: helloend
```

## License

The MIT License


text:
/* global angular */
(function(angular) {
	angular.module('angularScreenfull', []);
})(angular);
/* global angular, screenfull */
(function(angular) {
    angular.module('angularScreenfull')
    .directive('ngsfFullscreen',ngsfFullscreenDirective);

    ngsfFullscreenDirective.$inject = ['$parse'];
    function ngsfFullscreenDirective ($parse) {
        return {
            restrict: 'A',
            require: 'ngsfFullscreen',
            controller: ngsfFullscreenController,
            link: function(scope, elm, attrs, ctrl) {
                // If the directive has a value, add the controller to the scope under that name
                if (attrs.ngsfFullscreen && attrs.ngsfFullscreen !== '') {
                    var p = $parse(attrs.ngsfFullscreen);
                        p.assign(scope, ctrl);
                }

                // Make this the current fullscreen element
                ctrl.setFullScreenElement(elm[0]);
            }
        };
    }

    ngsfFullscreenController.$inject = ['$scope', '$document'];
    function ngsfFullscreenController ($scope, $document) {
        var ctrl = this;

        ctrl.setFullScreenElement = setFullScreenElement;
        ctrl.onFullscreenChange = onFullscreenChange;
        ctrl.requestFullscreen = requestFullscreen;
        ctrl.removeFullscreen = removeFullscreen;
        ctrl.toggleFullscreen = toggleFullscreen;
        ctrl.isFullscreen = isFullscreen;
        ctrl.fullscreenEnabled = fullscreenEnabled;

        function subscribeToEvents () {
            if (ctrl.fullscreenEnabled()) {
                var fullscreenchange = function () {
                    if (ctrl.isFullscreen()) {
                        angular.element(_elm).addClass('fullscreen');
                    } else {
                        angular.element(_elm).removeClass('fullscreen');
                    }
                    $scope.$emit('fullscreenchange');
                };

                $document[0].addEventListener(screenfull.raw.fullscreenchange, fullscreenchange);
                $scope.$on('$destroy', function() {
                    $document[0].removeEventListener(screenfull.raw.fullscreenchange, fullscreenchange);
                });

            }
        }

        var _elm;

        function setFullScreenElement (elm) {
            _elm = elm;
        }

        function onFullscreenChange (handler) {
            return $scope.$on('fullscreenchange', handler);
        }

        function requestFullscreen () {
            if (ctrl.fullscreenEnabled()) {
                screenfull.request(_elm);
                $scope.$emit('fullscreenEnabled');
                return true;
            }
            return false;
        }

        function removeFullscreen () {
            if (ctrl.fullscreenEnabled()) {
                if (ctrl.isFullscreen()) {
                    ctrl.toggleFullscreen();
                }
            }
        }

        function toggleFullscreen () {
            if (ctrl.fullscreenEnabled()) {
                var isFullscreen = screenfull.isFullscreen;
                screenfull.toggle(_elm);
                if (isFullscreen) {
                    $scope.$emit('fullscreenDisabled');
                } else {
                    $scope.$emit('fullscreenEnabled');
                }
                return true;
            }
            return false;
        }

        function isFullscreen () {
            if (ctrl.fullscreenEnabled()) {
                return screenfull.isFullscreen;
            }
            return false;
        }

        function fullscreenEnabled () {
            if (typeof screenfull !== 'undefined') {
                return screenfull.enabled;
            }
            return false;
        }

        subscribeToEvents();

    }
})(angular);

/* global angular */
(function(angular) {
    angular.module('angularScreenfull')
    .directive('showIfFullscreenEnabled', showIfFullscreenEnabledDirective);

    showIfFullscreenEnabledDirective.$inject = ['$animate'];

    function showIfFullscreenEnabledDirective ($animate) {
        return {
            restrict: 'A',
            require: '^ngsfFullscreen',
            link: function(scope, elm, attrs,fullScreenCtrl) {
                if (fullScreenCtrl.fullscreenEnabled()) {
                    $animate.removeClass(elm, 'ng-hide');
                } else {
                    $animate.addClass(elm, 'ng-hide');
                }
            }
        };
    }
})(angular);

/* global angular */
(function(angular) {
    angular.module('angularScreenfull')

    .directive('showIfFullscreen', showIfFullscreenDirective);
    showIfFullscreenDirective.$inject = ['$animate'];
    function showIfFullscreenDirective ($animate) {
        return {
            restrict: 'A',
            require: '^ngsfFullscreen',
            link: function(scope, elm, attrs,fullScreenCtrl) {
                var hideOrShow = function () {

                    var show = fullScreenCtrl.isFullscreen();
                    if (attrs.showIfFullscreen === 'false' || attrs.showIfFullscreen === false) {
                        show = !show;
                    }

                    if ( show ) {
                        $animate.removeClass(elm, 'ng-hide');
                    } else {
                        $animate.addClass(elm, 'ng-hide');
                    }
                };
                hideOrShow();
                var unwatch = fullScreenCtrl.onFullscreenChange(hideOrShow);
                scope.$on('$destroy', unwatch);
            }
        };
    }
})(angular);

/* global angular */
(function(angular) {
    angular.module('angularScreenfull')
    .directive('ngsfToggleFullscreen', ngsfToggleFullscreenDirective);

    function ngsfToggleFullscreenDirective () {
        return {
            restrict: 'A',
            require: '^ngsfFullscreen',
            link: function(scope, elm, attrs, fullScreenCtrl) {
                elm.on('click', function() {
                    fullScreenCtrl.toggleFullscreen();
                });
            }
        };
    }
})(angular);


text:
'use strict'

const cssesc = require('cssesc');

/**
 * Checks if the browser is initialized. Exits the process if it's not
 */
exports.browserIsInitialized = function browserIsInitialized () {
  if (!this.isInitialized()) {
    console.error('HeadlessChrome is not ready; call browser.init() before requesting other actions')
    process.exit(1)
  }
}

/**
 * As the selectors may contain colons, it's necessary to escape them in order to correctly match an element
 * @param {string} selector - The selector string
 * @return {string} - The selector with colons escaped (One backslash to escape the ':' for CSS, and other to escape the first one for JS)
 */
exports.fixSelector = function fixSelector (selector) {
  return cssesc(selector)
}

/**
 * Creates some delay
 * @param {number} delay - Delay in miliseconds
 * @return {promise} - The promise that will solve after the delay
 */
const sleep = exports.sleep = function (delay) {
  return new Promise(resolve => setTimeout(resolve, delay))
}

/**
 * Runs a promise and throws an error if it's not resolved before the timeout
 * @param {promise} promise - The promise to run
 * @param {number} timeout - The timeout time, in ms
 */
exports.promiseTimeout = function (promise, timeout) {
  // https://stackoverflow.com/questions/30936824/what-is-the-best-general-practice-to-timeout-a-function-in-promise
  // Handles the timeout internally, clearing it when the promise resolves.
  // It prevents the library to hang until the timeout is resolved
  let timer = null

  return Promise.race([
    new Promise((resolve, reject) => {
      timer = setTimeout(() => {
        const err = new Error('[Headless Chrome] Timeout after ' + timeout + ' ms')
        err.code = 'TIMEOUT'
        throw err
      }, timeout)
      return timer
    }),
    promise.then((value) => {
      clearTimeout(timer)
      return value
    })
  ])
}

/**
 * Transforms an interleave array into a key - value object
 * @param {array} interleaveArray - The interleave array
 * @return {object} - The key value object
 */
exports.interleaveArrayToObject = function (interleaveArray) {
  let attributes = {}
  for (let i = 0; i < interleaveArray.length; i++) {
    let key = interleaveArray[i]
    let value = interleaveArray[++i]
    attributes[key] = value
  }
  return attributes
}

/**
 * Given an object, transforms it's properties to a URL encoded string
 * @param {object} object - The object to transform
 * @return {string} - The URL Enconded object
 */
exports.objectToEncodedUri = function (object) {
  var encodedString = ''
  for (var prop in object) {
    if (object.hasOwnProperty(prop)) {
      if (encodedString.length > 0) {
        encodedString += '&'
      }
      encodedString += encodeURI(prop + '=' + object[prop])
    }
  }
  return encodedString
}


text:
#include "Creators.h"

#include <boost/range/adaptor/reversed.hpp>

#include "DexPosition.h"
#include "IROpcode.h"
#include "RedexContext.h"
#include "Show.h"
#include "Transform.h"

namespace {

// TODO: make naming of methods smart
const DexString* get_name(DexMethod* meth) {
  std::string name = "__st__" + meth->get_name()->str();
  return DexString::make_string(name);
}

DexProto* make_static_sig(DexMethod* meth) {
  auto proto = meth->get_proto();
  auto rtype = proto->get_rtype();
  DexTypeList::ContainerType arg_list;
  arg_list.push_back(meth->get_class());
  auto* args = proto->get_args();
  arg_list.insert(arg_list.end(), args->begin(), args->end());
  auto new_args = DexTypeList::make_type_list(std::move(arg_list));
  return DexProto::make_proto(rtype, new_args);
}

} // namespace

std::string ClassCreator::show_cls(const DexClass* cls) { return show(cls); }
std::string ClassCreator::show_type(const DexType* type) { return show(type); }

DexClass* ClassCreator::create() {
  always_assert_log(m_cls->m_self, "Self cannot be null in a DexClass");
  if (m_cls->m_super_class == nullptr) {
    if (m_cls->m_self != type::java_lang_Object()) {
      always_assert_log(m_cls->m_super_class, "No supertype found for %s",
                        show_type(m_cls->m_self).c_str());
    }
  }
  m_cls->m_interfaces = DexTypeList::make_type_list(std::move(m_interfaces));
  g_redex->publish_class(m_cls);
  return m_cls;
}

MethodBlock::MethodBlock(const IRList::iterator& iterator,
                         MethodCreator* creator)
    : mc(creator), curr(iterator) {
  mc->blocks.push_back(std::unique_ptr<MethodBlock>(this));
}

void MethodBlock::invoke(DexMethod* meth, const std::vector<Location>& args) {
  always_assert(meth->is_concrete());
  IROpcode opcode = opcode::invoke_for_method(meth);

  invoke(opcode, meth, args);
}

void MethodBlock::invoke(IROpcode opcode,
                         DexMethodRef* meth,
                         const std::vector<Location>& args) {
  always_assert(opcode::is_an_invoke(opcode));
  auto invk = new IRInstruction(opcode);
  uint16_t arg_count = static_cast<uint16_t>(args.size());
  invk->set_method(meth)->set_srcs_size(arg_count);
  for (uint16_t i = 0; i < arg_count; i++) {
    auto arg = args.at(i);
    invk->set_src(i, arg.get_reg());
  }
  push_instruction(invk);
}

void MethodBlock::new_instance(DexType* type, Location& dst) {
  auto insn = new IRInstruction(OPCODE_NEW_INSTANCE);
  insn->set_type(type);
  push_instruction(insn);
  push_instruction((new IRInstruction(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT))
                       ->set_dest(dst.get_reg()));
}

void MethodBlock::new_array(DexType* type,
                            const Location& size,
                            const Location& dst) {
  auto insn = new IRInstruction(OPCODE_NEW_ARRAY);
  insn->set_type(type);
  insn->set_srcs_size(1);
  insn->set_src(0, size.get_reg());
  push_instruction(insn);
  push_instruction((new IRInstruction(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT))
                       ->set_dest(dst.get_reg()));
}

void MethodBlock::throwex(Location ex) {
  auto insn = new IRInstruction(OPCODE_THROW);
  insn->set_src(0, ex.get_reg());
  push_instruction(insn);
}

void MethodBlock::iget(DexField* field, Location obj, Location& dst) {
  always_assert(field->is_concrete() && !is_static(field));
  IROpcode opcode;
  char t = type::type_shorty(field->get_type());
  switch (t) {
  case 'Z':
    opcode = OPCODE_IGET_BOOLEAN;
    break;
  case 'B':
    opcode = OPCODE_IGET_BYTE;
    break;
  case 'S':
    opcode = OPCODE_IGET_SHORT;
    break;
  case 'C':
    opcode = OPCODE_IGET_CHAR;
    break;
  case 'I':
  case 'F':
    opcode = OPCODE_IGET;
    break;
  case 'J':
  case 'D':
    opcode = OPCODE_IGET_WIDE;
    break;
  case 'L':
  case '[':
    opcode = OPCODE_IGET_OBJECT;
    break;
  default:
    not_reached();
  }
  ifield_op(opcode, field, obj, dst);
}

void MethodBlock::iput(DexField* field, Location obj, Location src) {
  always_assert(field->is_concrete() && !is_static(field));
  IROpcode opcode;
  char t = type::type_shorty(field->get_type());
  switch (t) {
  case 'Z':
    opcode = OPCODE_IPUT_BOOLEAN;
    break;
  case 'B':
    opcode = OPCODE_IPUT_BYTE;
    break;
  case 'S':
    opcode = OPCODE_IPUT_SHORT;
    break;
  case 'C':
    opcode = OPCODE_IPUT_CHAR;
    break;
  case 'I':
  case 'F':
    opcode = OPCODE_IPUT;
    break;
  case 'J':
  case 'D':
    opcode = OPCODE_IPUT_WIDE;
    break;
  case 'L':
  case '[':
    opcode = OPCODE_IPUT_OBJECT;
    break;
  default:
    not_reached();
  }
  ifield_op(opcode, field, obj, src);
}

void MethodBlock::ifield_op(IROpcode opcode,
                            DexField* field,
                            Location obj,
                            Location& src_or_dst) {
  always_assert(opcode::is_an_ifield_op(opcode));
  if (opcode::is_an_iget(opcode)) {
    auto iget = new IRInstruction(opcode);
    iget->set_field(field);
    src_or_dst.type = field->get_type();
    iget->set_src(0, obj.get_reg());
    push_instruction(iget);
    push_instruction(
        (new IRInstruction(opcode::move_result_pseudo_for_iget(opcode)))
            ->set_dest(src_or_dst.get_reg()));
  } else {
    auto iput = new IRInstruction(opcode);
    iput->set_field(field);
    iput->set_src(0, src_or_dst.get_reg());
    iput->set_src(1, obj.get_reg());
    push_instruction(iput);
  }
}

void MethodBlock::sget(DexField* field, Location& dst) {
  always_assert(field->is_concrete() && is_static(field));
  IROpcode opcode;
  char t = type::type_shorty(field->get_type());
  switch (t) {
  case 'Z':
    opcode = OPCODE_SGET_BOOLEAN;
    break;
  case 'B':
    opcode = OPCODE_SGET_BYTE;
    break;
  case 'S':
    opcode = OPCODE_SGET_SHORT;
    break;
  case 'C':
    opcode = OPCODE_SGET_CHAR;
    break;
  case 'I':
  case 'F':
    opcode = OPCODE_SGET;
    break;
  case 'J':
  case 'D':
    opcode = OPCODE_SGET_WIDE;
    break;
  case 'L':
  case '[':
    opcode = OPCODE_SGET_OBJECT;
    break;
  default:
    not_reached();
  }
  sfield_op(opcode, field, dst);
}

void MethodBlock::sput(DexField* field, Location src) {
  always_assert(field->is_concrete() && is_static(field));
  IROpcode opcode;
  char t = type::type_shorty(field->get_type());
  switch (t) {
  case 'Z':
    opcode = OPCODE_SPUT_BOOLEAN;
    break;
  case 'B':
    opcode = OPCODE_SPUT_BYTE;
    break;
  case 'S':
    opcode = OPCODE_SPUT_SHORT;
    break;
  case 'C':
    opcode = OPCODE_SPUT_CHAR;
    break;
  case 'I':
  case 'F':
    opcode = OPCODE_SPUT;
    break;
  case 'J':
  case 'D':
    opcode = OPCODE_SPUT_WIDE;
    break;
  case 'L':
  case '[':
    opcode = OPCODE_SPUT_OBJECT;
    break;
  default:
    not_reached();
  }
  sfield_op(opcode, field, src);
}

void MethodBlock::sfield_op(IROpcode opcode,
                            DexField* field,
                            Location& src_or_dst) {
  always_assert(opcode::is_an_sfield_op(opcode));
  if (opcode::is_an_sget(opcode)) {
    auto sget = new IRInstruction(opcode);
    sget->set_field(field);
    src_or_dst.type = field->get_type();
    push_instruction(sget);
    push_instruction(
        (new IRInstruction(opcode::move_result_pseudo_for_sget(opcode)))
            ->set_dest(src_or_dst.get_reg()));
  } else {
    auto sput = new IRInstruction(opcode);
    sput->set_field(field)->set_src(0, src_or_dst.get_reg());
    push_instruction(sput);
  }
}

void MethodBlock::move(Location src, Location& dst) {
  always_assert(src.is_compatible(dst.type));
  auto ch = type::type_shorty(dst.type);
  redex_assert(ch != 'V');
  IROpcode opcode;
  if (ch == 'L')
    opcode = OPCODE_MOVE_OBJECT;
  else if (ch == 'J' || ch == 'D')
    opcode = OPCODE_MOVE_WIDE;
  else
    opcode = OPCODE_MOVE;
  IRInstruction* move = new IRInstruction(opcode);
  move->set_dest(dst.get_reg());
  move->set_src(0, src.get_reg());
  dst.type = src.type;
  push_instruction(move);
}

void MethodBlock::move_result(Location& dst, DexType* type) {
  always_assert(dst.is_compatible(type));
  auto ch = type::type_shorty(type);
  redex_assert(ch != 'V');
  IROpcode opcode;
  if (ch == 'L')
    opcode = OPCODE_MOVE_RESULT_OBJECT;
  else if (ch == 'J' || ch == 'D')
    opcode = OPCODE_MOVE_RESULT_WIDE;
  else
    opcode = OPCODE_MOVE_RESULT;

  IRInstruction* mov_res = new IRInstruction(opcode);
  mov_res->set_dest(dst.get_reg());
  dst.type = type;
  push_instruction(mov_res);
}

void MethodBlock::check_cast(Location& src_and_dst, DexType* type) {
  IRInstruction* check_cast = new IRInstruction(OPCODE_CHECK_CAST);
  auto reg = src_and_dst.get_reg();
  check_cast->set_type(type)->set_src(0, reg);
  push_instruction(check_cast);
  push_instruction(
      (new IRInstruction(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT))->set_dest(reg));
}

void MethodBlock::instance_of(Location& obj, Location& dst, DexType* type) {
  always_assert(obj.is_ref());
  always_assert(dst.type == type::_boolean());
  IRInstruction* insn = new IRInstruction(OPCODE_INSTANCE_OF);
  insn->set_src(0, obj.get_reg());
  insn->set_type(type);
  push_instruction(insn);
  push_instruction(
      (new IRInstruction(IOPCODE_MOVE_RESULT_PSEUDO))->set_dest(dst.get_reg()));
}

void MethodBlock::ret(Location loc) {
  auto ch = type::type_shorty(loc.type);
  redex_assert(ch != 'V');
  IROpcode opcode;
  if (ch == 'L')
    opcode = OPCODE_RETURN_OBJECT;
  else if (ch == 'J' || ch == 'D')
    opcode = OPCODE_RETURN_WIDE;
  else
    opcode = OPCODE_RETURN;

  auto ret = new IRInstruction(opcode);
  ret->set_src(0, loc.get_reg());
  push_instruction(ret);
}

void MethodBlock::ret_void() {
  push_instruction(new IRInstruction(OPCODE_RETURN_VOID));
}

void MethodBlock::ret(DexType* rtype, Location loc) {
  if (rtype != type::_void()) {
    ret(loc);
  } else {
    ret_void();
  }
}

void MethodBlock::load_const(Location& loc, int32_t value) {
  always_assert(!loc.is_wide());
  IRInstruction* load = new IRInstruction(OPCODE_CONST);
  load->set_dest(loc.get_reg());
  load->set_literal(value);
  loc.type = type::_int();
  push_instruction(load);
}

void MethodBlock::load_const(Location& loc, int64_t value, DexType* type) {
  always_assert(type::is_wide_type(type) == loc.is_wide());
  IRInstruction* load =
      new IRInstruction(loc.is_wide() ? OPCODE_CONST_WIDE : OPCODE_CONST);
  load->set_dest(loc.get_reg());
  load->set_literal(value);
  loc.type = type;
  push_instruction(load);
}

void MethodBlock::load_const(Location& loc, double value) {
  always_assert(loc.is_wide());
  IRInstruction* load = new IRInstruction(OPCODE_CONST_WIDE);
  load->set_dest(loc.get_reg());
  load->set_literal(value);
  loc.type = type::_double();
  push_instruction(load);
}

void MethodBlock::load_const(Location& loc, const DexString* value) {
  always_assert(!loc.is_wide());
  IRInstruction* load = new IRInstruction(OPCODE_CONST_STRING);
  load->set_string(value);
  push_instruction(load);
  IRInstruction* move_result_pseudo =
      new IRInstruction(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT);
  loc.type = type::java_lang_String();
  move_result_pseudo->set_dest(loc.get_reg());
  push_instruction(move_result_pseudo);
}

void MethodBlock::load_const(Location& loc, DexType* value) {
  always_assert(!loc.is_wide());
  IRInstruction* load = new IRInstruction(OPCODE_CONST_CLASS);
  load->set_type(value);
  push_instruction(load);
  IRInstruction* move_result_pseudo =
      new IRInstruction(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT);
  loc.type = type::java_lang_Class();
  move_result_pseudo->set_dest(loc.get_reg());
  push_instruction(move_result_pseudo);
}

void MethodBlock::load_null(Location& loc) {
  always_assert(!loc.is_wide());
  IRInstruction* load = new IRInstruction(OPCODE_CONST);
  load->set_dest(loc.get_reg());
  load->set_literal(0);
  loc.type = type::java_lang_Object();
  push_instruction(load);
}

void MethodBlock::init_loc(Location& loc) {
  if (loc.is_ref()) {
    load_null(loc);
  } else if (loc.is_wide()) {
    load_const(loc, 0.0);
  } else {
    load_const(loc, 0);
  }
}

void MethodBlock::binop_lit(IROpcode op,
                            const Location& dest,
                            const Location& src,
                            int16_t literal) {
  always_assert(OPCODE_ADD_INT_LIT <= op && op <= OPCODE_USHR_INT_LIT);
  always_assert(dest.type == src.type);
  always_assert(dest.type == type::_int());
  IRInstruction* insn = new IRInstruction(op);
  insn->set_dest(dest.get_reg());
  insn->set_src(0, src.get_reg());
  insn->set_literal(literal);
  push_instruction(insn);
}

MethodBlock* MethodBlock::if_test(IROpcode if_op,
                                  Location first,
                                  Location second) {
  always_assert(OPCODE_IF_EQ <= if_op && if_op <= OPCODE_IF_LE);
  IRInstruction* op = new IRInstruction(if_op);
  op->set_src(0, first.get_reg());
  op->set_src(1, second.get_reg());
  return make_if_block(op);
}

MethodBlock* MethodBlock::if_testz(IROpcode if_op, Location test) {
  always_assert(OPCODE_IF_EQZ <= if_op && if_op <= OPCODE_IF_LEZ);
  IRInstruction* op = new IRInstruction(if_op);
  op->set_src(0, test.get_reg());
  return make_if_block(op);
}

MethodBlock* MethodBlock::if_else_test(IROpcode if_op,
                                       Location first,
                                       Location second,
                                       MethodBlock** true_block) {
  always_assert(OPCODE_IF_EQ <= if_op && if_op <= OPCODE_IF_LE);
  IRInstruction* op = new IRInstruction(if_op);
  op->set_src(0, first.get_reg());
  op->set_src(1, second.get_reg());
  return make_if_else_block(op, true_block);
}

MethodBlock* MethodBlock::if_else_testz(IROpcode if_op,
                                        Location test,
                                        MethodBlock** true_block) {
  always_assert(OPCODE_IF_EQZ <= if_op && if_op <= OPCODE_IF_LEZ);
  IRInstruction* op = new IRInstruction(if_op);
  op->set_src(0, test.get_reg());
  return make_if_else_block(op, true_block);
}

MethodBlock* MethodBlock::switch_op(Location test,
                                    std::map<int, MethodBlock*>& cases) {
  auto sw_opcode = new IRInstruction(OPCODE_SWITCH);
  sw_opcode->set_src(0, test.get_reg());
  // Convert to SwitchIndices map.
  std::map<SwitchIndices, MethodBlock*> indices_cases;
  for (auto it : cases) {
    SwitchIndices indices = {it.first};
    indices_cases[indices] = it.second;
  }
  auto mb = make_switch_block(sw_opcode, indices_cases);
  // Copy initialized case blocks back.
  for (const auto& it : indices_cases) {
    SwitchIndices indices = it.first;
    always_assert(indices.size());
    int idx = *indices.begin();
    cases[idx] = it.second;
  }
  return mb;
}

MethodBlock* MethodBlock::switch_op(
    Location test, std::map<SwitchIndices, MethodBlock*>& cases) {
  auto sw_opcode = new IRInstruction(OPCODE_SWITCH);
  sw_opcode->set_src(0, test.get_reg());
  return make_switch_block(sw_opcode, cases);
}

void MethodCreator::load_locals(DexMethod* meth) {
  auto ii = InstructionIterable(meth->get_code()->get_param_instructions());
  auto it = ii.begin();
  if (!is_static(meth)) {
    make_local_at(meth->get_class(), it->insn->dest());
    ++it;
  }
  auto proto = meth->get_proto();
  auto args = proto->get_args();
  if (args) {
    for (auto arg : *args) {
      make_local_at(arg, it->insn->dest());
      ++it;
    }
  }
  always_assert(it == ii.end());
}

void MethodBlock::push_instruction(IRInstruction* insn) {
  curr = mc->push_instruction(curr, insn);
}

IRList::iterator MethodCreator::push_instruction(const IRList::iterator& curr,
                                                 IRInstruction* insn) {
  if (curr == meth_code->end()) {
    meth_code->push_back(insn);
    return std::prev(meth_code->end());
  } else {
    return meth_code->insert_after(curr, insn);
  }
}

MethodBlock* MethodBlock::make_if_block(IRInstruction* insn) {
  IRList::iterator false_block;
  curr = mc->make_if_block(curr, insn, &false_block);
  return new MethodBlock(false_block, mc);
}

IRList::iterator MethodCreator::make_if_block(IRList::iterator curr,
                                              IRInstruction* insn,
                                              IRList::iterator* false_block) {
  return meth_code->make_if_block(++curr, insn, false_block);
}

MethodBlock* MethodBlock::make_if_else_block(IRInstruction* insn,
                                             MethodBlock** true_block) {
  IRList::iterator if_it;
  IRList::iterator else_it;
  curr = mc->make_if_else_block(curr, insn, &if_it, &else_it);
  *true_block = new MethodBlock(else_it, mc);
  return new MethodBlock(if_it, mc);
}

IRList::iterator MethodCreator::make_if_else_block(
    IRList::iterator curr,
    IRInstruction* insn,
    IRList::iterator* false_block,
    IRList::iterator* true_block) {
  return meth_code->make_if_else_block(++curr, insn, false_block, true_block);
}

MethodBlock* MethodBlock::make_switch_block(
    IRInstruction* insn, std::map<SwitchIndices, MethodBlock*>& cases) {
  IRList::iterator default_it;
  std::map<SwitchIndices, IRList::iterator> mt_cases;
  for (const auto& cases_it : cases) {
    mt_cases[cases_it.first] = curr;
  }
  curr = mc->make_switch_block(curr, insn, &default_it, mt_cases);
  for (auto& cases_it : cases) {
    cases_it.second = new MethodBlock(mt_cases[cases_it.first], mc);
  }
  return new MethodBlock(default_it, mc);
}

IRList::iterator MethodCreator::make_switch_block(
    IRList::iterator curr,
    IRInstruction* insn,
    IRList::iterator* default_block,
    std::map<SwitchIndices, IRList::iterator>& cases) {
  return meth_code->make_switch_block(++curr, insn, default_block, cases);
}

std::vector<Location> MethodCreator::get_reg_args() {
  std::vector<Location> args;
  uint32_t args_size = method->get_proto()->get_args()->size();
  if (!is_static(method)) {
    args_size += 1;
  }
  args.insert(args.end(), locals.begin(), locals.begin() + args_size);
  return args;
}

MethodCreator::MethodCreator(DexMethod* meth)
    : method(meth), meth_code(meth->get_code()) {
  always_assert_log(meth->is_concrete(),
                    "Method must be concrete or use the other ctor");
  load_locals(meth);
  main_block = new MethodBlock(meth_code->main_block(), this);
}

MethodCreator::MethodCreator(DexMethodRef* ref,
                             DexAccessFlags access,
                             std::unique_ptr<DexAnnotationSet> anno,
                             bool with_debug_item)
    : MethodCreator(ref->get_class(),
                    ref->get_name(),
                    ref->get_proto(),
                    access,
                    std::move(anno),
                    with_debug_item){};

MethodCreator::MethodCreator(DexType* cls,
                             const DexString* name,
                             DexProto* proto,
                             DexAccessFlags access,
                             std::unique_ptr<DexAnnotationSet> anno,
                             bool with_debug_item)
    : method(static_cast<DexMethod*>(DexMethod::make_method(cls, name, proto))),
      m_with_debug_item(with_debug_item) {
  always_assert_log(!method->is_concrete(), "Method already defined");
  if (anno) {
    method->attach_annotation_set(std::move(anno));
  }
  method->make_concrete(
      access, !(access & (ACC_STATIC | ACC_PRIVATE | ACC_CONSTRUCTOR)));
  method->set_deobfuscated_name(show_deobfuscated(method));
  method->set_code(std::make_unique<IRCode>(method, 0));
  meth_code = method->get_code();
  if (with_debug_item) {
    meth_code->set_debug_item(std::make_unique<DexDebugItem>());
  }
  load_locals(method);
  main_block = new MethodBlock(meth_code->main_block(), this);
}

DexMethod* MethodCreator::create() {
  auto param_insns = meth_code->get_param_instructions();
  auto param_reg = meth_code->get_registers_size();
  transform::RegMap reg_map;
  // allocate all the params at the end of the register frame
  for (const auto& mie : boost::adaptors::reverse(param_insns)) {
    auto insn = mie.insn;
    param_reg -= insn->dest_is_wide() ? 2 : 1;
    reg_map[insn->dest()] = param_reg;
    if (insn->dest_is_wide()) {
      reg_map[insn->dest() + 1] = param_reg + 1;
    }
  }
  // now allocate the rest at the start
  size_t temp_reg{0};
  for (size_t i = 0; i < meth_code->get_registers_size(); ++i) {
    if (reg_map.find(i) != reg_map.end()) {
      continue;
    }
    reg_map[i] = temp_reg++;
  }
  always_assert(temp_reg == param_reg);
  transform::remap_registers(meth_code, reg_map);

  if (m_with_debug_item) {
    // Insert a fake position entry for redex generated method when we
    // add debug item.
    auto main_block_it = meth_code->get_param_instructions().end();
    auto position = std::make_unique<DexPosition>(0);
    position->bind(DexString::make_string(show(method)),
                   DexString::make_string("RedexGenerated"));
    meth_code->insert_before(main_block_it, std::move(position));
  }
  return method;
}

DexMethod* MethodCreator::make_static_from(DexMethod* meth,
                                           DexClass* target_cls) {
  auto name = get_name(meth);
  return make_static_from(name, meth, target_cls);
}

DexMethod* MethodCreator::make_static_from(const DexString* name,
                                           DexMethod* meth,
                                           DexClass* target_cls) {
  auto proto = make_static_sig(meth);
  return make_static_from(name, proto, meth, target_cls);
}

DexMethod* MethodCreator::make_static_from(const DexString* name,
                                           DexProto* proto,
                                           DexMethod* meth,
                                           DexClass* target_cls) {
  redex_assert(!is_static(meth));
  redex_assert(!method::is_init(meth) && !method::is_clinit(meth));
  auto smeth = static_cast<DexMethod*>(
      DexMethod::make_method(target_cls->get_type(), name, proto));
  smeth->make_concrete(meth->get_access() | ACC_STATIC, meth->release_code(),
                       false);
  target_cls->add_method(smeth);
  return smeth;
}


text:
class AddPoolIdColumn < ActiveRecord::Migration
  def up
    change_table :iseq_flowcell do |t|
      t.column 'id_pool_lims',     :string, limit: 20, null: false, comment: 'Most specific LIMs identifier associated with the pool'
    end
  end

  def down
    # rubocop:disable Rails/BulkChangeTable
    change_table :iseq_flowcell do |t|
      t.remove 'id_pool_lims', :string, limit: 20, null: false, comment: 'Most specific LIMs identifier associated with the pool'
    end
    # rubocop:enable Rails/BulkChangeTable
  end
end


text:
Tangram allows raster data sources to be loaded, displayed, and combined with vector data sources in a variety of ways, including with real-time image manipulation.

## Basic Raster Display

The simplest way to use raster data is to display it directly, without any combinations or modifications. This is done by specifying a [`source`](../Syntax-Reference/sources.md) of type `raster`, either tiled or untiled. A source `url` which includes the `{x}/{y}/{z}` url token pattern. Sources without this pattern will be treated as untiled.

The example below loads a tiled raster data source:

```yaml
sources:
    stamen-terrain:
        type: Raster
        url: http://a.tile.stamen.com/terrain-background/{z}/{x}/{y}.jpg
```

Then it is rendered with the built-in [`raster` style](../Syntax-Reference/styles.md#raster), which is provided for typical rendering cases. This style generates tile-sized geometry and textures it with the appropriate raster data.

```yaml
layers:
    terrain:
        data: { source: stamen-terrain }
        draw:
            raster:
                order: 0 # draw on bottom
```

This allows the raster layer to be used as a basemap, with other vector data drawn on top.

![tangram-wed mar 30 2016 16-51-48 gmt-0400 edt](https://cloud.githubusercontent.com/assets/16733/14157176/e57c96dc-f697-11e5-9c6d-c1a47f8e4d1d.png)

## Tinting

The `raster` style can take a `color` parameter, which will be multiplied by the raster's color as a tint. This parameter's value defaults to "white" and accepts all standard `color` values including JavaScript functions.

This example darkens the underlying tiles by 50%:

```yaml
layers:
    terrain:
        data: { source: stamen-terrain }
        draw:
            raster:
                color: [0.5, 0.5, 0.5]
                order: 0 # draw on bottom
```

![tangram-wed mar 30 2016 16-56-31 gmt-0400 edt](https://cloud.githubusercontent.com/assets/16733/14157295/64e6683a-f698-11e5-9171-75adc131243f.png)

### Geometry Masking

The `raster` style can also be applied to a non-`Raster` source that has a raster sampler attached, using the [`rasters`](../Syntax-Reference/sources.md#rasters) parameter. In this case, the Stamen terrain is attached to and masked against the OSM landuse polygons:

```yaml
sources:
    stamen-terrain:
        type: Raster
        url: http://a.tile.stamen.com/terrain-background/{z}/{x}/{y}.jpg
    mapzen-osm:
        type: TopoJSON
        url: https://tile.nextzen.org/tilezen/vector/v1/256/all/{z}/{x}/{y}.topojson
        rasters: [stamen-terrain] # attach stamen terrain

layers:
   terrain:
       data: { source: nextzen-osm, layer: landuse } # render landuse layer from vector data source
       draw:
           raster:
               order: 0 # draw on bottom
```

![Raster terrain data with vector mask](https://cloud.githubusercontent.com/assets/16733/14157713/52108590-f69a-11e5-8553-361a7893e257.png)

This technique can be used for combining shaded relief with landcover classifications. For example, here is a base raster terrain layer in gray, with vector landuse polygons tinted green:

![Raster terrain data with tinted landuse polygons](https://cloud.githubusercontent.com/assets/16733/14213503/4b24aa5a-f806-11e5-8bbc-ba3d61f33bed.png)

## High-Resolution Tile Support

### Multiple-Resolution Sources

Some raster tile sources support multiple resolutions for better quality on high-density displays, following the `@2x` file naming convention for web and mobile assets. This is supported by Tangram raster data sources with the `{r}` URL template token, as shown below:

`https://tiles.maps.com/{z}/{x}/{y}{r}.png`

The most common case is a source that supports 1x and 2x tiles, and this is the default configuration. However, other resolutions are also possible. Multiple resolutions can be supported with the [`url_density_scales`](../Syntax-Reference/sources.md#url_density_scales) parameter. For example, Wikimedia maps has several resolutions, which can be rendered in Tangram with:

```yaml
sources:
  raster:
    type: Raster
    url: https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}{r}.png
    url_density_scales: [1, 1.3, 1.5, 2, 2.6, 3]
```

The default value for url_density_scales is [1, 2], meaning it will load either "plain" tile URLs like tile.png, or tile@2x.png tiles on displays with a display density >= 2.

### Downsampling

In some circumstances, the default tiles for a source may be either too large (in file size) or too detailed (in feature density or coordinate precision) than needed for the current application. The [`zoom_offset`](../Syntax-Reference/sources.md#zoom_offset) parameter allows the user to request lower zooms for each zoom level, reducing tile size and visual detail. (`zoom_offset` also works for vector data!)

This gif compares Mapzen terrain normal tiles to a version using `zoom_offset: 1`, effectively generalizing the terrain while lowering network bandwidth:
    ![zoom_offset terrain](https://user-images.githubusercontent.com/16733/51883976-53669400-2353-11e9-9241-9de27eea6f6d.gif)

## Untiled Raster Sources

Untiled raster image data may also be loaded, by specifying a single image file in the source's `url` parameter, as well as a bounding box in the `bounds` parameter:

```yaml
sources:
  chelan:
    type: Raster # can now indicate either tiled or un-tiled image source
    url: images/chelan.jpg # no tile XYZ pattern in URL indicates standalone image
    bounds: [-120.588, 47.467, -119.904, 48.033] # geo-extent of the image
```

This example shows a USGS historical map from the Chelan, WA area, overlaid on top of the Mapzen Walkabout base map:

![Raster map positioned over vector data](https://user-images.githubusercontent.com/16733/51869261-0ae0b380-231e-11e9-9fd5-55ec4120a9fc.png)

Three additional parameters exist for fine-tuning raster behavior:

- [`composite`](../Syntax-Reference/sources.md#rasters-composite) allows multiple images to be combined into a single data source;
- [`alpha`](../Syntax-Reference/sources.md#rasters-alpha) sets an alpha value for the entire data source;
- [`max-display-density`](../Syntax-Reference/sources.md#rasters-max-display-density) allows a cap to be set on oversampling, to limit texture memory use.

## Custom Styles

The `raster` style is derived from the `polygons` rendering style, and provides the same shader blocks. This allows for custom raster styles to be defined with `base: raster`. For example, this style converts raster tiles to grayscale:

```yaml
sources:
    stamen-terrain:
        type: Raster
        url: http://a.tile.stamen.com/terrain-background/{z}/{x}/{y}.jpg

styles:
    grayscale:
        base: raster
        shaders:
            blocks:
                filter: |
                    # get luminance of rgb value
                    float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114));
                    color.rgb = vec3(luma);

layers:
    terrain:
        data: { source: stamen-terrain }
        draw:
            grayscale:
                order: 0
```

![tangram-wed mar 30 2016 16-59-03 gmt-0400 edt](https://cloud.githubusercontent.com/assets/16733/14157381/b90ec916-f698-11e5-8697-5e99a66faf23.png)

### Advanced Raster Styles

Styles can enable raster samplers with the `raster` parameter, which can have the following values:

- `color`: Applies the value of the raster texture as the `color` in the fragment shader. This is the most common case, and is set as the default by the `raster` rendering style.
- `normal`: To support terrain shading, there is also built-in support for applying a raster source as a normal map.
- `custom`: This value is for cases where you want access to raster samplers, but the data is not formatted for direct use as a color or normal. Mapzen's RGB-packed elevation tiles are an example; the raw data must be decoded and re-interpreted for usable results, and is not intended for display.

### Normal Maps

This example loads pre-computed "normal" tiles as a normal map, which can be lit by standard Tangram lights:

```yaml
sources:
    terrain-normals:
        type: Raster
        url: https://tile.nextzen.org/tilezen/terrain/v1/normal/{z}/{x}/{y}.png

    mapzen-osm:
        type: TopoJSON
        url: https://tile.nextzen.org/tilezen/vector/v1/256/all/{z}/{x}/{y}.topojson
        rasters: [terrain-normals]

styles:
    normals:
        base: polygons
        raster: normal

lights:
    point1:
        type: point

layers:
    earth:
        data: { source: nextzen-osm }
        draw:
            normals:
                color: white
                order: 0
```

![tangram-wed mar 30 2016 21-39-44 gmt-0400 edt](https://cloud.githubusercontent.com/assets/16733/14163150/7bff64d6-f6c0-11e5-9c22-555d8075b8dd.png)

### Direct Sampler Access

When a style declares `raster: custom`, any shaders defined in that style can directly sample the raster for custom effects.

This example uses the [`sampleRaster()`](../Syntax-Reference/styles.md#raster) method to unpack Mapzen elevation tiles for color display:

```yaml
styles:
    elevation:
        base: polygons
        raster: custom
        shaders:
            blocks:
                global: |
                    // Unpack RGB elevation
                    float unpack(vec4 h) {
                        return (h.r * 1. + h.g / 256. + h.b / 65536.);
                    }
                color: |
                    color.rgb = vec3(unpack(sampleRaster(0)));
                    color.rgb = (color.rgb - .5) * 20.; // re-scale to a visible range for contrast
```

![tangram-wed mar 30 2016 21-59-05 gmt-0400 edt](https://cloud.githubusercontent.com/assets/16733/14163364/a9429a10-f6c2-11e5-81c7-c0561e5919be.png)

### Multiple Raster Samplers

This example shows the use of two raster samplers in the same rendering style. First, sources are defined for Stamen's Watercolor and Toner tiles. To make them both available in the same rendering `style`, the watercolor source is attached as the second sampler for the toner source.

A simple `style` that does a 50/50 blend of the two samplers is then defined. Finally, the toner source is drawn with the blend style.

```yaml
sources:
    stamen-watercolor:
        type: Raster
        url: http://tile.stamen.com/watercolor/{z}/{x}/{y}.jpg
    stamen-toner:
        type: Raster
        url: http://tile.stamen.com/toner/{z}/{x}/{y}.png
        rasters: [stamen-watercolor] # add watercolor sampler alongside toner

styles:
    # blend two raster samplers together
    blend-rasters:
        base: polygons
        raster: color
        shaders:
            blocks:
                filter: |
                    color = (sampleRaster(0) + sampleRaster(1)) * 0.5;

layers:
    earth:
        data: { source: stamen-toner }
        draw:
            blend-rasters:
                order: 0
```

![tangram-wed mar 30 2016 17-20-15 gmt-0400 edt](https://cloud.githubusercontent.com/assets/16733/14158040/074abc0e-f69c-11e5-9cc5-a2852f24b46d.png)