text:
define(
    'common/mainctrl',
    ['jquery'],
    function ($) {
        function MainController(selector) {
            this.context = $(selector);
            this._stack  = [];
            this.$backButton = this.context.find('.prev-group');
        }

        function disableDefault(e) {
            e.preventDefault();
        }

        $.extend(MainController.prototype, {
            enable: function () {
                var defaultGroupName = $.trim(this.context.attr('data-default'));

                if (defaultGroupName === '') {
                    defaultGroupName = this.context.children('[data-group]').eq(0).attr('data-group');
                }

                // Disable highlighting.
                this.context.on('click', 'a', disableDefault);
                this.context.on('mousedown', 'a', disableDefault);
                this.context.on('mouseup', 'a', disableDefault);

                // Bind generic events.
                this.context.on('click', 'a.prev-group', $.proxy(this.onReturningTriggerClick, this));
                this.context.on('click', 'a[data-next]', $.proxy(this.onNavigatingItemClick, this));

                this.context.attr('data-default', defaultGroupName);
                this._showGroup(defaultGroupName);
            },

            getTrigger: function (id) {
                return this.context.find('a[data-id="' + id + '"]');
            },

            toggleTriggerActive: function (id) {
                this.getTrigger(id).toggleClass('active');
            },

            setTriggerActive: function (id, isActive) {
                this.getTrigger(id)[isActive ? 'addClass' : 'removeClass']('active');
            },

            on: function (triggerId, handler) {
                this.context.on('click', 'a[data-id="' + triggerId + '"]', handler);
            },

            onReturningTriggerClick: function (e) {
                var destination = this._stack.pop();

                this._showGroup(destination);
            },

            onNavigatingItemClick: function (e) {
                var currentGroup = this._currentGroup().attr('data-group'),
                    destination  = $(e.currentTarget).attr('data-next')
                ;

                this._stack.push(currentGroup);
                this._showGroup(destination);
            },

            _showGroup: function (groupName) {
                var defaultGroupName = this.context.attr('data-default'),
                    isBackToDefault  = defaultGroupName === groupName
                ;

                $controlGroups = this.context.children('[data-group]');

                $controlGroups.removeClass('active');
                $controlGroups.filter('[data-group="' + groupName + '"]').addClass('active');

                this.context.attr('data-current', groupName);

                this.$backButton[isBackToDefault ? 'removeClass' : 'addClass']('enabled');
            },

            _currentGroup: function () {
                return this.context.children('[data-group].active');
            }
        });

        return MainController;
    }
);


text:
package org.eclipse.californium.core.network.interceptors;

import org.eclipse.californium.core.coap.EmptyMessage;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.coap.Response;
import org.eclipse.californium.core.network.CoAPEndpoint;

/**
 * The MessageLogger logs all incoming and outgoing messages. The MessageLogger
 * is used by an {@link CoAPEndpoint} and is located between the serializer/parser
 * and the matcher. Each message comes or goes to the connector is logged.
 */
public class MessageTracer implements MessageInterceptor {

	/* (non-Javadoc)
	 * @see ch.inf.vs.californium.network.MessageIntercepter#sendRequest(ch.inf.vs.californium.coap.Request)
	 */
	@Override
	public void sendRequest(Request request) {
		System.out.println(String.format("----------------------------------------------------------------\n" +
										 "%s:%d <== req %s\n" +
										 "----------------------------------------------------------------",
				request.getDestination(), request.getDestinationPort(), request));
	}

	/* (non-Javadoc)
	 * @see ch.inf.vs.californium.network.MessageIntercepter#sendResponse(ch.inf.vs.californium.coap.Response)
	 */
	@Override
	public void sendResponse(Response response) {
		System.out.println(String.format("----------------------------------------------------------------\n" +
										 "%s:%d <== res %s\n" +
										 "----------------------------------------------------------------",
				response.getDestination(), response.getDestinationPort(), response));
	}

	/* (non-Javadoc)
	 * @see ch.inf.vs.californium.network.MessageIntercepter#sendEmptyMessage(ch.inf.vs.californium.coap.EmptyMessage)
	 */
	@Override
	public void sendEmptyMessage(EmptyMessage message) {
		System.out.println(String.format("----------------------------------------------------------------\n" +
										 "%s:%d <== emp %s\n" +
										 "----------------------------------------------------------------",
				message.getDestination(), message.getDestinationPort(), message));
	}

	/* (non-Javadoc)
	 * @see ch.inf.vs.californium.network.MessageIntercepter#receiveRequest(ch.inf.vs.californium.coap.Request)
	 */
	@Override
	public void receiveRequest(Request request) {
		System.out.println(String.format("----------------------------------------------------------------\n" +
										 "%s:%d ==> req %s\n" +
										 "----------------------------------------------------------------",
				request.getSource(), request.getSourcePort(), request));
	}

	/* (non-Javadoc)
	 * @see ch.inf.vs.californium.network.MessageIntercepter#receiveResponse(ch.inf.vs.californium.coap.Response)
	 */
	@Override
	public void receiveResponse(Response response) {
		System.out.println(String.format("----------------------------------------------------------------\n" +
										 "%s:%d ==> res %s\n" +
										 "----------------------------------------------------------------",
				response.getSource(), response.getSourcePort(), response));
	}

	/* (non-Javadoc)
	 * @see ch.inf.vs.californium.network.MessageIntercepter#receiveEmptyMessage(ch.inf.vs.californium.coap.EmptyMessage)
	 */
	@Override
	public void receiveEmptyMessage(EmptyMessage message) {
		System.out.println(String.format("----------------------------------------------------------------\n" +
										 "%s:%d ==> emp %s\n" +
										 "----------------------------------------------------------------",
				message.getSource(), message.getSourcePort(), message));
	}

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace project_flux.Connection
{
    class Delete
    {
        private static async Task<bool> DeleteToApi(String ApiPath)
        {
            try
            {
                HttpClient _client = new HttpClient();
                HttpResponseMessage _response = await _client.DeleteAsync(Settings.GetApiPath() + ApiPath);

                if (_response.IsSuccessStatusCode)
                {
                    String _return = "";
                    using (HttpContent content = _response.Content)
                    {
                        string result = await content.ReadAsStringAsync();
                        _return = result;
                    }
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        public static async Task<bool> DeleteAndReturnResult(String ApiPath)
        {
            return await DeleteToApi(ApiPath);
        }
    }
}


text:
package costs

import (
	"fmt"
	"strings"
	"time"

	"github.com/olivere/elastic"
)

// aggregationBuilder is an alias for the function type that is used in the
// aggregationBuilder functions.
type aggregationBuilder func([]string) []paramAggrAndName

// paramNameToFuncPtr maps parameter names to functions building the aggregations.
// map of string keys and functions pointer as values. For each possible param
// after parsing (removing the ':<TAG_KEY>' in the case of the tag), there is a function associated to it
// that create the Aggregations needed by this param.
// If a new param, that is only creating aggregations, needs to be added,
// a functions with an aggregationBuilder prototype need to be added to the list below.
var paramNameToFuncPtr = map[string]aggregationBuilder{
	"product":          createAggregationPerProduct,
	"availabilityzone": createAggregationPerAvailabilityZone,
	"region":           createAggregationPerRegion,
	"account":          createAggregationPerAccount,
	"tag":              createAggregationPerTag,
	"cost":             createCostSumAggregation,
	"day":              createAggregationPerDay,
	"week":             createAggregationPerWeek,
	"month":            createAggregationPerMonth,
	"year":             createAggregationPerYear,
}

// paramAggrAndName is a structure containing the name of the parameter and
// corresponding aggregation. A parameter is a string that is passed to the
// GetElasticSearchParams and represents an aggregation. A list of those
// parameters can be found in the paramNameToFuncPtr map.
type paramAggrAndName struct {
	name string
	aggr elastic.Aggregation
}

// aggregationMaxSize is the maximum size of an Elastic Search Aggregation
const aggregationMaxSize = 0x7FFFFFFF

// createQueryAccountFilter creates and return a new *elastic.TermsQuery on the accountList array
func createQueryAccountFilter(accountList []string) *elastic.TermsQuery {
	accountListFormatted := make([]interface{}, len(accountList))
	for i, v := range accountList {
		accountListFormatted[i] = v
	}
	return elastic.NewTermsQuery("usageAccountId", accountListFormatted...)
}

// createQueryTimeRange creates and return a new *elastic.RangeQuery based on the duration
// defined by durationBegin and durationEnd
func createQueryTimeRange(durationBegin time.Time, durationEnd time.Time) *elastic.RangeQuery {
	return elastic.NewRangeQuery("usageStartDate").
		From(durationBegin).To(durationEnd)
}

// createAggregationPerProduct creates and returns a new []paramAggrAndName of size 1 which creates a
// bucket aggregation on the field 'product_name'
func createAggregationPerProduct(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-product",
			aggr: elastic.NewTermsAggregation().
				Field("productCode").Size(aggregationMaxSize),
		},
	}
}

// createAggregationPerAvailabilityZone creates and returns a new []paramAggrAndName of size 1 which creates a
// bucket aggregation on the field 'availability_zone'
func createAggregationPerAvailabilityZone(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-availabilityzone",
			aggr: elastic.NewTermsAggregation().
				Field("availabilityZone").Size(aggregationMaxSize),
		},
	}
}

// createAggregationPerRegion creates and returns a new []paramAggrAndName of size 1 which creates a
// bucket aggregation on the field 'region'
func createAggregationPerRegion(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-region",
			aggr: elastic.NewTermsAggregation().
				Field("region").Size(aggregationMaxSize),
		},
	}
}

// createAggregationPerAccount creates and returns a new []paramAggrAndName of size 1 which creates a
// bucket aggregation on the field 'linked_account_id'
func createAggregationPerAccount(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-account",
			aggr: elastic.NewTermsAggregation().
				Field("usageAccountId").Size(aggregationMaxSize),
		},
	}
}

// createAggregationPerDay creates and returns a new []paramAggrAndName of size 1 which creates a
// date histogram aggregation on the field 'usage_start_date' with a time range of a day
func createAggregationPerDay(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-day",
			aggr: elastic.NewDateHistogramAggregation().
				Field("usageStartDate").MinDocCount(0).Interval("day"),
		},
	}
}

// createAggregationPerWeek creates and returns a new []paramAggrAndName of size 1 which creates a
// date histogram aggregation on the field 'usage_start_date' with a time range of a week
func createAggregationPerWeek(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-week",
			aggr: elastic.NewDateHistogramAggregation().
				Field("usageStartDate").MinDocCount(0).Interval("week"),
		},
	}
}

// createAggregationPerMonth creates and returns a new []paramAggrAndName of size 1 which creates a
// date histogram aggregation on the field 'usage_start_date' with a time range of a month
func createAggregationPerMonth(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-month",
			aggr: elastic.NewDateHistogramAggregation().
				Field("usageStartDate").MinDocCount(0).Interval("month"),
		},
	}
}

// createAggregationPerYear creates and returns a new []paramAggrAndName of size 1 which creates a
// date histogram aggregation on the field 'usage_start_date' with a time range of a year
func createAggregationPerYear(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-year",
			aggr: elastic.NewDateHistogramAggregation().
				Field("usageStartDate").MinDocCount(0).Interval("year"),
		},
	}
}

// createAggregationPerTag creates and returns a new []paramAggrAndName of size 2 which consists
// of two aggregations that are required for the tag param.
// The first aggregation is a FilterAggregation on the field 'tag.key', and with a value of
// the tag key passed in the parameter 'paramSplit' in the form "user:<TAG_KEY_VALUE>".
// The second aggregation is a TermsAggregation that creates bucket aggregation on the field
// 'tag.value'.
// No SubAggregation is created in this function, as it needs to be created in the nestAggregation function
func createAggregationPerTag(paramSplit []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "by-tag_key",
			aggr: elastic.NewFilterAggregation().
				Filter(elastic.NewTermQuery("tag.key", fmt.Sprintf("user:%v", paramSplit[1])))},
		{
			name: "tag_value",
			aggr: elastic.NewTermsAggregation().
				Field("tag.value").Size(aggregationMaxSize)},
	}
}

// createCostSumAggregation : Creates and return a new []paramAggrAndName of size 1, which creates a
// SumAggregation on the field 'cost'
func createCostSumAggregation(_ []string) []paramAggrAndName {
	return []paramAggrAndName{
		{
			name: "value",
			aggr: elastic.NewSumAggregation().Field("unblendedCost"),
		},
	}
}

// reverseAggregationArray : reverse the paramAggrAndName slice that is passed to it
func reverseAggregationArray(aggregationArray []paramAggrAndName) []paramAggrAndName {
	for i := len(aggregationArray)/2 - 1; i >= 0; i-- {
		opp := len(aggregationArray) - 1 - i
		aggregationArray[i], aggregationArray[opp] = aggregationArray[opp], aggregationArray[i]
	}
	return aggregationArray
}

// nestAggregation takes a slice of paramAggrAndName type, and will nest the different aggregations.
// Aggregations are nested by creating a chain of SubAggregation
// A type switch is required to simulate downcasting from the interface elastic.Aggregation.
// Current types on the type switch are TermsAggregation, FilterAggregation, SumAggregation and
// DateHistogramAggregation.
// If a new function creating a type that is not listed here is added to the paramNameToFuncPtr map
// it should be added to the type switch, or the function will create bugged SubAggregations
func nestAggregation(allAggrSlice []paramAggrAndName) elastic.Aggregation {
	allAggrSlice = reverseAggregationArray(allAggrSlice)
	aggrToNest := allAggrSlice[0]
	for _, baseAggr := range allAggrSlice[1:] {
		switch assertedBaseAggr := baseAggr.aggr.(type) {
		case *elastic.TermsAggregation:
			aggrBuff := assertedBaseAggr.SubAggregation(aggrToNest.name, aggrToNest.aggr)
			aggrToNest = paramAggrAndName{name: baseAggr.name, aggr: aggrBuff}
		case *elastic.FilterAggregation:
			aggrBuff := assertedBaseAggr.SubAggregation(aggrToNest.name, aggrToNest.aggr)
			aggrToNest = paramAggrAndName{name: baseAggr.name, aggr: aggrBuff}
		case *elastic.DateHistogramAggregation:
			aggrBuff := assertedBaseAggr.SubAggregation(aggrToNest.name, aggrToNest.aggr)
			aggrToNest = paramAggrAndName{name: baseAggr.name, aggr: aggrBuff}
		}
	}
	return aggrToNest.aggr
}

// GetElasticSearchParams is used to construct an ElasticSearch *elastic.SearchService used to perform a request on ES
// It takes as parameters :
// 	- accountList []string : A slice of strings representing aws account number, in the format of the field
//	'awsdetailedlineitem.linked_account_id'
//	- durationBeing time.Time : A time.Time struct representing the beginning of the time range in the query
//	- durationEnd time.Time : A time.Time struct representing the end of the time range in the query
//	- param []string : A slice of strings representing the different parameters, in the nesting order,
//	that will create aggregations.
//	Those can be :
//		- "product" : It will create a TermsAggregation on the field 'product_name'
//		- "availabilityzone" : It will create a TermsAggregation on the field 'availability_zone'
//		- "region" : It will create a TermsAggregation on the field 'region'
//		- "account" : It will create a TermsAggregation on the field 'linked_account_id'
//		- "tag:<TAG_KEY>" : It will create a FilterAggregation on the field 'tag.key',
//		filtering on the value 'user:<TAG_KEY>'.
//		It will then create a TermsAggregation on the field 'tag.value'
//		- "[day|week|month|year]": It will create a DateHistogramAggregation on the specified duration on
//		the field 'usage_start_date'
//	- client *elastic.Client : an instance of *elastic.Client that represent an Elastic Search client.
//	It needs to be fully configured and ready to execute a client.Search()
//	- index string : The Elastic Search index on which to execute the query. In this context the default value
//	should be "awsdetailedlineitems"
// This function excepts arguments passed to it to be sanitize. If they are not, the following cases will make
// it crash :
//	- For the 'tag:<TAG_KEY>' param, if the separator is not present, or if there is no key that is passed to it,
//	the program will crash
//	- If a param in the slice is not present in the detailedLineItemsFieldsName, the program will crash.
//	- If the client is nil or malconfigured, it will crash
//	- If the index is not an index present in the ES, it will crash
// We are excluding AWSDataTransfer products because it's value is always zero.
// Data transfer costs are included in other products' costs.
func GetElasticSearchParams(accountList []string, durationBegin time.Time,
	durationEnd time.Time, params []string, client *elastic.Client, index string) *elastic.SearchService {
	query := elastic.NewBoolQuery()
	if len(accountList) > 0 {
		query = query.Filter(createQueryAccountFilter(accountList))
	}
	query = query.Filter(createQueryTimeRange(durationBegin, durationEnd),
		elastic.NewBoolQuery().MustNot(elastic.NewTermQuery("productCode", "AWSDataTransfer")))
	search := client.Search().Index(index).Size(0).Query(query)
	params = append(params, "cost")
	var allAggregationSlice []paramAggrAndName
	for _, paramName := range params {
		paramNameSplit := strings.Split(paramName, ":")
		paramAggr := paramNameToFuncPtr[paramNameSplit[0]](paramNameSplit)
		allAggregationSlice = append(allAggregationSlice, paramAggr...)
	}
	aggregationParamName := allAggregationSlice[0].name
	nestedAggregation := nestAggregation(allAggregationSlice)
	search.Aggregation(aggregationParamName, nestedAggregation)
	return search
}


text:
package com.janeluo.jfinalplus.plugin.quartz;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.janeluo.jfinalplus.kit.Reflect;
import com.janeluo.jfinalplus.kit.ResourceKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;
import java.util.Map;
import java.util.Set;

public class QuartzPlugin implements IPlugin {
    public static final String VERSION_1 = "1";
    private static final String JOB = "job";
    private final Log logger = Log.getLog(getClass());
    private Map<Job, String> jobs = Maps.newLinkedHashMap();
    private String version;
    private SchedulerFactory sf;
    private Scheduler scheduler;
    private String jobConfig;
    private String confConfig;
    private Map<String, String> jobProp;

    public QuartzPlugin(String jobConfig, String confConfig) {
        this.jobConfig = jobConfig;
        this.confConfig = confConfig;
    }

    public QuartzPlugin(String jobConfig) {
        this.jobConfig = jobConfig;
    }

    public QuartzPlugin() {
    }

    public QuartzPlugin add(String jobCronExp, Job job) {
        jobs.put(job, jobCronExp);
        return this;
    }

    @Override
    public boolean start() {
        loadJobsFromProperties();
        startJobs();
        return true;
    }

    private void startJobs() {
        try {
            if (StrKit.notBlank(confConfig)) {
                sf = new StdSchedulerFactory(confConfig);
            } else {
                sf = new StdSchedulerFactory();
            }
            scheduler = sf.getScheduler();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
        Set<Map.Entry<Job, String>> set = jobs.entrySet();
        for (Map.Entry<Job, String> entry : set) {
            Job job = entry.getKey();
            String jobClassName = job.getClass().getName();
            String jobCronExp = entry.getValue();
            JobDetail jobDetail;
            CronTrigger trigger;
            //JobDetail and CornTrigger are classes in 1.x version,but are interfaces in 2.X version.
            if (VERSION_1.equals(version)) {
                jobDetail = Reflect.on("org.quartz.JobDetail").create(jobClassName, jobClassName, job.getClass()).get();
                trigger = Reflect.on("org.quartz.CronTrigger").create(jobClassName, jobClassName, jobCronExp).get();
            } else {
                jobDetail = Reflect.on("org.quartz.JobBuilder").call("newJob", job.getClass()).call("withIdentity", jobClassName, jobClassName)
                        .call("build").get();
                Object temp = Reflect.on("org.quartz.TriggerBuilder").call("newTrigger").get();
                temp = Reflect.on(temp).call("withIdentity", jobClassName, jobClassName).get();
                temp = Reflect.on(temp).call("withSchedule",
                        Reflect.on("org.quartz.CronScheduleBuilder").call("cronSchedule", jobCronExp).get())
                        .get();
                trigger = Reflect.on(temp).call("build").get();
            }
            Date ft = Reflect.on(scheduler).call("scheduleJob", jobDetail, trigger).get();
            logger.debug(Reflect.on(jobDetail).call("getKey") + " has been scheduled to run at: " + ft + " " +
                    "and repeat based on expression: " + Reflect.on(trigger).call("getCronExpression"));
        }
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
    }

    private void loadJobsFromProperties() {
        if (StrKit.isBlank(jobConfig)) {
            return;
        }
        jobProp = ResourceKit.readProperties(jobConfig);
        Set<Map.Entry<String, String>> entries = jobProp.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            if (!key.endsWith(JOB) || !isEnableJob(enable(key))) {
                continue;
            }
            String jobClassName = jobProp.get(key) + "";
            String jobCronExp = jobProp.get(cronKey(key)) + "";
            Class<Job> job = Reflect.on(jobClassName).get();
            try {
                jobs.put(job.newInstance(), jobCronExp);
            } catch (Exception e) {
                Throwables.propagate(e);
            }
        }
    }

    private String enable(String key) {
        return key.substring(0, key.lastIndexOf(JOB)) + "enable";
    }

    private String cronKey(String key) {
        return key.substring(0, key.lastIndexOf(JOB)) + "cron";
    }

    public QuartzPlugin version(String version) {
        this.version = version;
        return this;
    }

    private boolean isEnableJob(String enableKey) {
        Object enable = jobProp.get(enableKey);
        if (enable != null && "false".equalsIgnoreCase((enable + "").trim())) {
            return false;
        }
        return true;
    }

    @Override
    public boolean stop() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
        return true;
    }

    public QuartzPlugin confConfig(String confConfig) {
        this.confConfig = confConfig;
        return this;
    }

    public QuartzPlugin jobConfig(String jobConfig) {
        this.jobConfig = jobConfig;
        return this;
    }
}


text:
const _           = require('lodash');
const m           = require('mithril');
const Stream      = require('mithril/stream');
const AjaxHelper  = require('helpers/ajax_helper');

import sparkRoutes from "helpers/spark_routes";

class Material {
  selectRevision     = (revision) => {
    this.updateSearchText(revision);
    this.selection(revision);
  };
  updateSearchText   = (newText) => {
    this.selection('');
    this.searchText(newText);
    this.debouncedSearch();
  };
  isRevisionSelected = () => {
    return !_.isEmpty(this.selection());
  };
  performSearch      = () => {
    this.searchInProgress(true);
    return AjaxHelper.GET({
      url:        sparkRoutes.pipelineMaterialSearchPath(this.pipelineName, this.fingerprint, this.searchText),
      apiVersion: 'v1',
    }).then((result) => {
      this.searchResults(result);
      if ((result.length === 1) && (this.searchText() === result[0].revision)) {
        this.selection(this.searchText());
      }
    }).always(() => {
      this.searchInProgress(false);
      m.redraw();
    });
  };

  debouncedSearch = _.debounce(() => {
    this.performSearch();
  }, 200);

  validate = () => {
    if (this.selection() !== this.searchText()) {
      const msg = `Invalid revision ${this.searchText()} specified for material ${this.name}`;
      this.error(msg);
      return false;
    }
    return true;
  };

  constructor({type, name, fingerprint, folder, revision, pipelineName}) {
    this.type             = type;
    this.name             = name;
    this.fingerprint      = fingerprint;
    this.destination      = folder;
    this.revision         = revision;
    this.pipelineName     = pipelineName;
    this.selection        = Stream('');
    this.searchText       = Stream('');
    this.searchInProgress = Stream(false);
    this.searchResults    = Stream([]);
    this.error            = Stream();
  }
}

module.exports = Material;


text:
require 'spec_helper'

describe "the is_ip_address function" do
  let(:scope) { PuppetlabsSpec::PuppetInternals.scope }

  it "should exist" do
    Puppet::Parser::Functions.function("is_ip_address").should == "function_is_ip_address"
  end

  it "should raise a ParseError if there is less than 1 arguments" do
    lambda { scope.function_is_ip_address([]) }.should( raise_error(Puppet::ParseError))
  end

  it "should return true if an IPv4 address" do
    result = scope.function_is_ip_address(["1.2.3.4"])
    result.should(eq(true))
  end

  it "should return true if a full IPv6 address" do
    result = scope.function_is_ip_address(["fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74"])
    result.should(eq(true))
  end

  it "should return true if a compressed IPv6 address" do
    result = scope.function_is_ip_address(["fe00::1"])
    result.should(eq(true))
  end

  it "should return false if not valid" do
    result = scope.function_is_ip_address(["asdf"])
    result.should(eq(false))
  end

  it "should return false if IP octets out of range" do
    result = scope.function_is_ip_address(["1.1.1.300"])
    result.should(eq(false))
  end
end


text:
#include "rtperrors.h"
#include "rtpdefines.h"
#include "rtpinternalutils.h"
#include <stdio.h>

#include "rtpdebug.h"

namespace jrtplib
{

struct RTPErrorInfo
{
	int code;
	const char *description;
};

static RTPErrorInfo ErrorDescriptions[]=
{
	{ ERR_RTP_OUTOFMEM,"Out of memory" },
	{ ERR_RTP_NOTHREADSUPPORT, "No JThread support was compiled in"},
	{ ERR_RTP_COLLISIONLIST_BADADDRESS, "Passed invalid address (null) to collision list"},
	{ ERR_RTP_HASHTABLE_ELEMENTALREADYEXISTS, "Element already exists in hash table"},
	{ ERR_RTP_HASHTABLE_ELEMENTNOTFOUND, "Element not found in hash table"},
	{ ERR_RTP_HASHTABLE_FUNCTIONRETURNEDINVALIDHASHINDEX, "Function returned an illegal hash index"},
	{ ERR_RTP_HASHTABLE_NOCURRENTELEMENT, "No current element selected in hash table"},
	{ ERR_RTP_KEYHASHTABLE_FUNCTIONRETURNEDINVALIDHASHINDEX, "Function returned an illegal hash index"},
	{ ERR_RTP_KEYHASHTABLE_KEYALREADYEXISTS, "Key value already exists in key hash table"},
	{ ERR_RTP_KEYHASHTABLE_KEYNOTFOUND, "Key value not found in key hash table"},
	{ ERR_RTP_KEYHASHTABLE_NOCURRENTELEMENT, "No current element selected in key hash table"},
	{ ERR_RTP_PACKBUILD_ALREADYINIT, "RTP packet builder is already initialized"},
	{ ERR_RTP_PACKBUILD_CSRCALREADYINLIST, "The specified CSRC is already in the RTP packet builder's CSRC list"},
	{ ERR_RTP_PACKBUILD_CSRCLISTFULL, "The RTP packet builder's CSRC list already contains 15 entries"},
	{ ERR_RTP_PACKBUILD_CSRCNOTINLIST, "The specified CSRC was not found in the RTP packet builder's CSRC list"},
	{ ERR_RTP_PACKBUILD_DEFAULTMARKNOTSET, "The RTP packet builder's default mark flag is not set"},
	{ ERR_RTP_PACKBUILD_DEFAULTPAYLOADTYPENOTSET, "The RTP packet builder's default payload type is not set"},
	{ ERR_RTP_PACKBUILD_DEFAULTTSINCNOTSET, "The RTP packet builder's default timestamp increment is not set"},
	{ ERR_RTP_PACKBUILD_INVALIDMAXPACKETSIZE, "The specified maximum packet size for the RTP packet builder is invalid"},
	{ ERR_RTP_PACKBUILD_NOTINIT, "The RTP packet builder is not initialized"},
	{ ERR_RTP_PACKET_BADPAYLOADTYPE, "Invalid payload type"},
	{ ERR_RTP_PACKET_DATAEXCEEDSMAXSIZE, "Tried to create an RTP packet which would exceed the specified maximum packet size"},
	{ ERR_RTP_PACKET_EXTERNALBUFFERNULL, "Illegal value (null) passed as external buffer for the RTP packet"},
	{ ERR_RTP_PACKET_ILLEGALBUFFERSIZE, "Illegal buffer size specified for the RTP packet"},
	{ ERR_RTP_PACKET_INVALIDPACKET, "Invalid RTP packet format"},
	{ ERR_RTP_PACKET_TOOMANYCSRCS, "More than 15 CSRCs specified for the RTP packet"},
	{ ERR_RTP_POLLTHREAD_ALREADYRUNNING, "Poll thread is already running"},
	{ ERR_RTP_POLLTHREAD_CANTINITMUTEX, "Can't initialize a mutex for the poll thread"},
	{ ERR_RTP_POLLTHREAD_CANTSTARTTHREAD, "Can't start the poll thread"},
	{ ERR_RTP_RTCPCOMPOUND_INVALIDPACKET, "Invalid RTCP compound packet format"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_ALREADYBUILDING, "Already building this RTCP compound packet"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_ALREADYBUILT, "This RTCP compound packet is already built"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_ALREADYGOTREPORT, "There's already a SR or RR in this RTCP compound packet"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_APPDATALENTOOBIG, "The specified APP data length for the RTCP compound packet is too big"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_BUFFERSIZETOOSMALL, "The specified buffer size for the RTCP comound packet is too small"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_ILLEGALAPPDATALENGTH, "The APP data length must be a multiple of four"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_ILLEGALSUBTYPE, "The APP packet subtype must be smaller than 32"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_INVALIDITEMTYPE, "Invalid SDES item type specified for the RTCP compound packet"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_MAXPACKETSIZETOOSMALL, "The specified maximum packet size for the RTCP compound packet is too small"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_NOCURRENTSOURCE, "Tried to add an SDES item to the RTCP compound packet when no SSRC was present"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_NOREPORTPRESENT, "An RTCP compound packet must contain a SR or RR"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_NOTBUILDING, "The RTCP compound packet builder is not initialized"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_NOTENOUGHBYTESLEFT, "Adding this data would exceed the specified maximum RTCP compound packet size"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_REPORTNOTSTARTED, "Tried to add a report block to the RTCP compound packet when no SR or RR was started"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_TOOMANYSSRCS, "Only 31 SSRCs will fit into a BYE packet for the RTCP compound packet"},
	{ ERR_RTP_RTCPCOMPPACKBUILDER_TOTALITEMLENGTHTOOBIG, "The total data for the SDES PRIV item exceeds the maximum size (255 bytes) of an SDES item"},
	{ ERR_RTP_RTCPPACKETBUILDER_ALREADYINIT, "The RTCP packet builder is already initialized"},
	{ ERR_RTP_RTCPPACKETBUILDER_ILLEGALMAXPACKSIZE, "The specified maximum packet size for the RTCP packet builder is too small"},
	{ ERR_RTP_RTCPPACKETBUILDER_ILLEGALTIMESTAMPUNIT, "Speficied an illegal timestamp unit for the the RTCP packet builder"},
	{ ERR_RTP_RTCPPACKETBUILDER_NOTINIT, "The RTCP packet builder was not initialized"},
	{ ERR_RTP_RTCPPACKETBUILDER_PACKETFILLEDTOOSOON, "The RTCP compound packet filled sooner than expected"},
	{ ERR_RTP_SCHEDPARAMS_BADFRACTION, "Illegal sender bandwidth fraction specified"},
	{ ERR_RTP_SCHEDPARAMS_BADMINIMUMINTERVAL, "The minimum RTCP interval specified for the scheduler is too small"},
	{ ERR_RTP_SCHEDPARAMS_INVALIDBANDWIDTH, "Invalid RTCP bandwidth specified for the RTCP scheduler"},
	{ ERR_RTP_SDES_LENGTHTOOBIG, "Specified size for the SDES item exceeds 255 bytes"},
	{ ERR_RTP_SDES_PREFIXNOTFOUND, "The specified SDES PRIV prefix was not found"},
	{ ERR_RTP_SESSION_ALREADYCREATED, "The session is already created"},
	{ ERR_RTP_SESSION_CANTGETLOGINNAME, "Can't retrieve login name"},
	{ ERR_RTP_SESSION_CANTINITMUTEX, "A mutex for the RTP session couldn't be initialized"},
	{ ERR_RTP_SESSION_MAXPACKETSIZETOOSMALL, "The maximum packet size specified for the RTP session is too small"},
	{ ERR_RTP_SESSION_NOTCREATED, "The RTP session was not created"},
	{ ERR_RTP_SESSION_UNSUPPORTEDTRANSMISSIONPROTOCOL, "The requested transmission protocol for the RTP session is not supported"},
	{ ERR_RTP_SESSION_USINGPOLLTHREAD, "This function is not available when using the RTP poll thread feature"},
	{ ERR_RTP_SESSION_USERDEFINEDTRANSMITTERNULL, "A user-defined transmitter was requested but the supplied transmitter component is NULL"},
	{ ERR_RTP_SOURCES_ALREADYHAVEOWNSSRC, "Only one source can be marked as own SSRC in the source table"},
	{ ERR_RTP_SOURCES_DONTHAVEOWNSSRC, "No source was marked as own SSRC in the source table"},
	{ ERR_RTP_SOURCES_ILLEGALSDESTYPE, "Illegal SDES type specified for processing into the source table"},
	{ ERR_RTP_SOURCES_SSRCEXISTS, "Can't create own SSRC because this SSRC identifier is already in the source table"},
	{ ERR_RTP_UDPV4TRANS_ALREADYCREATED, "The transmitter was already created"},
	{ ERR_RTP_UDPV4TRANS_ALREADYINIT, "The transmitter was already initialized"},
	{ ERR_RTP_UDPV4TRANS_ALREADYWAITING, "The transmitter is already waiting for incoming data"},
	{ ERR_RTP_UDPV4TRANS_CANTBINDRTCPSOCKET, "The 'bind' call for the RTCP socket failed"},
	{ ERR_RTP_UDPV4TRANS_CANTBINDRTPSOCKET, "The 'bind' call for the RTP socket failed"},
	{ ERR_RTP_UDPV4TRANS_CANTCREATESOCKET, "Couldn't create the RTP or RTCP socket"},
	{ ERR_RTP_UDPV4TRANS_CANTINITMUTEX, "Failed to initialize a mutex used by the transmitter"},
	{ ERR_RTP_UDPV4TRANS_CANTSETRTCPRECEIVEBUF, "Couldn't set the receive buffer size for the RTCP socket"},
	{ ERR_RTP_UDPV4TRANS_CANTSETRTCPTRANSMITBUF, "Couldn't set the transmission buffer size for the RTCP socket"},
	{ ERR_RTP_UDPV4TRANS_CANTSETRTPRECEIVEBUF, "Couldn't set the receive buffer size for the RTP socket"},
	{ ERR_RTP_UDPV4TRANS_CANTSETRTPTRANSMITBUF, "Couldn't set the transmission buffer size for the RTP socket"},
	{ ERR_RTP_UDPV4TRANS_COULDNTJOINMULTICASTGROUP, "Unable to join the specified multicast group"},
	{ ERR_RTP_UDPV4TRANS_DIFFERENTRECEIVEMODE, "The function called doesn't match the current receive mode"},
	{ ERR_RTP_UDPV4TRANS_ILLEGALPARAMETERS, "Illegal parameters type passed to the transmitter"},
	{ ERR_RTP_UDPV4TRANS_INVALIDADDRESSTYPE, "Specified address type isn't compatible with this transmitter"},
	{ ERR_RTP_UDPV4TRANS_NOLOCALIPS, "Couldn't determine the local host name since the local IP list is empty"},
	{ ERR_RTP_UDPV4TRANS_NOMULTICASTSUPPORT, "Multicast support is not available"},
	{ ERR_RTP_UDPV4TRANS_NOSUCHENTRY, "Specified entry could not be found"},
	{ ERR_RTP_UDPV4TRANS_NOTAMULTICASTADDRESS, "The specified address is not a multicast address"},
	{ ERR_RTP_UDPV4TRANS_NOTCREATED, "The 'Create' call for this transmitter has not been called"},
	{ ERR_RTP_UDPV4TRANS_NOTINIT, "The 'Init' call for this transmitter has not been called"},
	{ ERR_RTP_UDPV4TRANS_NOTWAITING, "The transmitter is not waiting for incoming data"},
	{ ERR_RTP_UDPV4TRANS_PORTBASENOTEVEN, "The specified port base is not an even number"},
	{ ERR_RTP_UDPV4TRANS_SPECIFIEDSIZETOOBIG, "The maximum packet size is too big for this transmitter"},
	{ ERR_RTP_UDPV6TRANS_ALREADYCREATED, "The transmitter was already created"},
	{ ERR_RTP_UDPV6TRANS_ALREADYINIT, "The transmitter was already initialized"},
	{ ERR_RTP_UDPV6TRANS_ALREADYWAITING, "The transmitter is already waiting for incoming data"},
	{ ERR_RTP_UDPV6TRANS_CANTBINDRTCPSOCKET, "The 'bind' call for the RTCP socket failed"},
	{ ERR_RTP_UDPV6TRANS_CANTBINDRTPSOCKET, "The 'bind' call for the RTP socket failed"},
	{ ERR_RTP_UDPV6TRANS_CANTCREATESOCKET, "Couldn't create the RTP or RTCP socket"},
	{ ERR_RTP_UDPV6TRANS_CANTINITMUTEX, "Failed to initialize a mutex used by the transmitter"},
	{ ERR_RTP_UDPV6TRANS_CANTSETRTCPRECEIVEBUF, "Couldn't set the receive buffer size for the RTCP socket"},
	{ ERR_RTP_UDPV6TRANS_CANTSETRTCPTRANSMITBUF, "Couldn't set the transmission buffer size for the RTCP socket"},
	{ ERR_RTP_UDPV6TRANS_CANTSETRTPRECEIVEBUF, "Couldn't set the receive buffer size for the RTP socket"},
	{ ERR_RTP_UDPV6TRANS_CANTSETRTPTRANSMITBUF, "Couldn't set the transmission buffer size for the RTP socket"},
	{ ERR_RTP_UDPV6TRANS_COULDNTJOINMULTICASTGROUP, "Unable to join the specified multicast group"},
	{ ERR_RTP_UDPV6TRANS_DIFFERENTRECEIVEMODE, "The function called doesn't match the current receive mode"},
	{ ERR_RTP_UDPV6TRANS_ILLEGALPARAMETERS, "Illegal parameters type passed to the transmitter"},
	{ ERR_RTP_UDPV6TRANS_INVALIDADDRESSTYPE, "Specified address type isn't compatible with this transmitter"},
	{ ERR_RTP_UDPV6TRANS_NOLOCALIPS, "Couldn't determine the local host name since the local IP list is empty"},
	{ ERR_RTP_UDPV6TRANS_NOMULTICASTSUPPORT, "Multicast support is not available"},
	{ ERR_RTP_UDPV6TRANS_NOSUCHENTRY, "Specified entry could not be found"},
	{ ERR_RTP_UDPV6TRANS_NOTAMULTICASTADDRESS, "The specified address is not a multicast address"},
	{ ERR_RTP_UDPV6TRANS_NOTCREATED, "The 'Create' call for this transmitter has not been called"},
	{ ERR_RTP_UDPV6TRANS_NOTINIT, "The 'Init' call for this transmitter has not been called"},
	{ ERR_RTP_UDPV6TRANS_NOTWAITING, "The transmitter is not waiting for incoming data"},
	{ ERR_RTP_UDPV6TRANS_PORTBASENOTEVEN, "The specified port base is not an even number"},
	{ ERR_RTP_UDPV6TRANS_SPECIFIEDSIZETOOBIG, "The maximum packet size is too big for this transmitter"},
	{ ERR_RTP_TRANS_BUFFERLENGTHTOOSMALL,"The hostname is larger than the specified buffer size"},
	{ ERR_RTP_SDES_MAXPRIVITEMS,"The maximum number of SDES private item prefixes was reached"},
	{ ERR_RTP_INTERNALSOURCEDATA_INVALIDPROBATIONTYPE,"An invalid probation type was specified"},
	{ ERR_RTP_FAKETRANS_ALREADYCREATED, "The transmitter was already created"},
	{ ERR_RTP_FAKETRANS_ALREADYINIT, "The transmitter was already initialized"},
	{ ERR_RTP_FAKETRANS_CANTINITMUTEX, "Failed to initialize a mutex used by the transmitter"},
	{ ERR_RTP_FAKETRANS_COULDNTJOINMULTICASTGROUP, "Unable to join the specified multicast group"},
	{ ERR_RTP_FAKETRANS_DIFFERENTRECEIVEMODE, "The function called doesn't match the current receive mode"},
	{ ERR_RTP_FAKETRANS_ILLEGALPARAMETERS, "Illegal parameters type passed to the transmitter"},
	{ ERR_RTP_FAKETRANS_INVALIDADDRESSTYPE, "Specified address type isn't compatible with this transmitter"},
	{ ERR_RTP_FAKETRANS_NOLOCALIPS, "Couldn't determine the local host name since the local IP list is empty"},
	{ ERR_RTP_FAKETRANS_NOMULTICASTSUPPORT, "Multicast support is not available"},
	{ ERR_RTP_FAKETRANS_NOSUCHENTRY, "Specified entry could not be found"},
	{ ERR_RTP_FAKETRANS_NOTAMULTICASTADDRESS, "The specified address is not a multicast address"},
	{ ERR_RTP_FAKETRANS_NOTCREATED, "The 'Create' call for this transmitter has not been called"},
	{ ERR_RTP_FAKETRANS_NOTINIT, "The 'Init' call for this transmitter has not been called"},
	{ ERR_RTP_FAKETRANS_PORTBASENOTEVEN, "The specified port base is not an even number"},
	{ ERR_RTP_FAKETRANS_SPECIFIEDSIZETOOBIG, "The maximum packet size is too big for this transmitter"},
	{ ERR_RTP_FAKETRANS_WAITNOTIMPLEMENTED, "The WaitForIncomingData is not implemented in the Gst transmitter"},
	{ ERR_RTP_RTPRANDOMURANDOM_CANTOPEN, "Unable to open /dev/urandom for reading"},
	{ ERR_RTP_RTPRANDOMURANDOM_ALREADYOPEN, "The device /dev/urandom was already opened"},
	{ ERR_RTP_RTPRANDOMRANDS_NOTSUPPORTED, "The rand_s call is not supported on this platform"},
	{ ERR_RTP_EXTERNALTRANS_ALREADYCREATED, "The external transmission component was already created"},
	{ ERR_RTP_EXTERNALTRANS_ALREADYINIT, "The external transmission component was already initialized"},
	{ ERR_RTP_EXTERNALTRANS_ALREADYWAITING, "The external transmission component is already waiting for incoming data"},
	{ ERR_RTP_EXTERNALTRANS_BADRECEIVEMODE, "The external transmission component only supports accepting all incoming packets"},
	{ ERR_RTP_EXTERNALTRANS_CANTINITMUTEX, "The external transmitter was unable to initialize a required mutex"},
	{ ERR_RTP_EXTERNALTRANS_ILLEGALPARAMETERS, "Only parameters of type RTPExternalTransmissionParams can be passed to the external transmission component"},
	{ ERR_RTP_EXTERNALTRANS_NOACCEPTLIST, "The external transmitter does not have an accept list"},
	{ ERR_RTP_EXTERNALTRANS_NODESTINATIONSSUPPORTED, "The external transmitter does not have a destination list"},
	{ ERR_RTP_EXTERNALTRANS_NOIGNORELIST, "The external transmitter does not have an ignore list"},
	{ ERR_RTP_EXTERNALTRANS_NOMULTICASTSUPPORT, "The external transmitter does not support the multicast functions"},
	{ ERR_RTP_EXTERNALTRANS_NOSENDER, "No sender has been set for this external transmitter"},
	{ ERR_RTP_EXTERNALTRANS_NOTCREATED, "The external transmitter has not been created yet"},
	{ ERR_RTP_EXTERNALTRANS_NOTINIT, "The external transmitter has not been initialized yet"},
	{ ERR_RTP_EXTERNALTRANS_NOTWAITING, "The external transmitter is not currently waiting for incoming data"},
	{ ERR_RTP_EXTERNALTRANS_SENDERROR, "The external transmitter was unable to actually send the data"},
	{ ERR_RTP_EXTERNALTRANS_SPECIFIEDSIZETOOBIG, "The specified data size exceeds the maximum amount that has been set"},
    { ERR_RTP_UDPV4TRANS_CANTGETSOCKETPORT, "Unable to obtain the existing socket info using 'getsockname'"},
	{ ERR_RTP_UDPV4TRANS_NOTANIPV4SOCKET, "The existing socket specified does not appear to be an IPv4 socket"},
	{ ERR_RTP_UDPV4TRANS_SOCKETPORTNOTSET, "The existing socket that was specified does not have its port set yet"},
	{ ERR_RTP_UDPV4TRANS_CANTGETSOCKETTYPE, "Can't get the socket type of the specified existing socket"},
	{ ERR_RTP_UDPV4TRANS_INVALIDSOCKETTYPE, "The specified existing socket is not an UDP socket"},
	{ ERR_RTP_UDPV4TRANS_CANTGETVALIDSOCKET, "Can't get a valid socket when trying to choose a port automatically"},
	{ ERR_RTP_UDPV4TRANS_TOOMANYATTEMPTSCHOOSINGSOCKET, "Can't seem to get RTP/RTCP ports automatically, too many attempts"},
	{ ERR_RTP_RTPSESSION_CHANGEREQUESTEDBUTNOTIMPLEMENTED, "Flag to change data was requested, but OnChangeRTPOrRTCPData was not reimplemented"},
	{ ERR_RTP_SECURESESSION_CONTEXTALREADYINITIALIZED, "The initialization function was already called"},
	{ ERR_RTP_SECURESESSION_CANTINITIALIZE_SRTPCONTEXT, "Unable to initialize libsrtp context"},
	{ ERR_RTP_SECURESESSION_CANTINITMUTEX, "Unable to initialize a mutex" },
	{ ERR_RTP_SECURESESSION_CONTEXTNOTINITIALIZED, "The libsrtp context initilization function must be called before it can be used"},
	{ ERR_RTP_SECURESESSION_NOTENOUGHDATATOENCRYPT, "There's not enough RTP or RTCP data to encrypt"},
	{ ERR_RTP_SECURESESSION_CANTENCRYPTRTPDATA, "Unable to encrypt RTP data"},
	{ ERR_RTP_SECURESESSION_CANTENCRYPTRTCPDATA, "Unable to encrypt RTCP data"},
	{ ERR_RTP_SECURESESSION_NOTENOUGHDATATODECRYPT, "There's not enough RTP or RTCP data to decrypt"},
	{ ERR_RTP_SECURESESSION_CANTDECRYPTRTPDATA, "Unable to decrypt RTP data"},
	{ ERR_RTP_SECURESESSION_CANTDECRYPTRTCPDATA, "Unable to decrypt RTCP data"},
	{ ERR_RTP_ABORTDESC_ALREADYINIT, "The RTPAbortDescriptors instance is already initialized" },
	{ ERR_RTP_ABORTDESC_NOTINIT, "The RTPAbortDescriptors instance is not yet initialized" },
	{ ERR_RTP_ABORTDESC_CANTCREATEABORTDESCRIPTORS, "Unable to create two connected TCP sockets for the abort descriptors" },
	{ ERR_RTP_ABORTDESC_CANTCREATEPIPE, "Unable to create a pipe for the abort descriptors" },
	{ ERR_RTP_SESSION_THREADSAFETYCONFLICT, "For the background poll thread to be used, thread safety must also be set" },
	{ ERR_RTP_SELECT_ERRORINSELECT, "Error in the call to 'select'" },
	{ ERR_RTP_SELECT_SOCKETDESCRIPTORTOOLARGE, "A socket descriptor value is too large for a call to 'select' (exceeds FD_SETSIZE)" },
	{ ERR_RTP_SELECT_ERRORINPOLL, "Error in the call to 'poll' or 'WSAPoll'" },
	{ ERR_RTP_TCPTRANS_NOTINIT, "The TCP transmitter is not yet initialized" },
	{ ERR_RTP_TCPTRANS_ALREADYINIT, "The TCP transmitter is already initialized" },
	{ ERR_RTP_TCPTRANS_NOTCREATED, "The TCP transmitter is not yet created" },
	{ ERR_RTP_TCPTRANS_ALREADYCREATED, "The TCP transmitter is already created" },
	{ ERR_RTP_TCPTRANS_ILLEGALPARAMETERS, "The parameters for the TCP transmitter are invalid" },
	{ ERR_RTP_TCPTRANS_CANTINITMUTEX, "Unable to initialize a mutex during the initialization of the TCP transmitter" },
	{ ERR_RTP_TCPTRANS_ALREADYWAITING, "The TCP transmitter is already waiting for data" },
	{ ERR_RTP_TCPTRANS_INVALIDADDRESSTYPE, "The address specified is not a valid address for the TCP transmitter" },
	{ ERR_RTP_TCPTRANS_NOSOCKETSPECIFIED, "No socket was specified in the address used for the TCP transmitter" },
	{ ERR_RTP_TCPTRANS_NOMULTICASTSUPPORT, "The TCP transmitter does not support multicasting" },
	{ ERR_RTP_TCPTRANS_RECEIVEMODENOTSUPPORTED, "The TCP transmitter does not support receive modes other than 'accept all'" },
	{ ERR_RTP_TCPTRANS_SPECIFIEDSIZETOOBIG, "The maximum packet size for the TCP transmitter is limited to 64KB" },
	{ ERR_RTP_TCPTRANS_NOTWAITING, "The TCP transmitter is not waiting for data" },
	{ ERR_RTP_TCPTRANS_SOCKETALREADYINDESTINATIONS, "The specified destination address (socket) was already added to the destination list of the TCP transmitter" },
	{ ERR_RTP_TCPTRANS_SOCKETNOTFOUNDINDESTINATIONS, "The specified destination address (socket) was not found in the list of destinations of the TCP transmitter" },
	{ ERR_RTP_TCPTRANS_ERRORINSEND, "An error occurred in the TCP transmitter while sending a packet" },
	{ ERR_RTP_TCPTRANS_ERRORINRECV, "An error occurred in the TCP transmitter while receiving a packet" },
	{ 0,0 }
};

std::string RTPGetErrorString(int errcode)
{
	int i;

	if (errcode >= 0)
		return std::string("No error");

	i = 0;
	while (ErrorDescriptions[i].code != 0)
	{
		if (ErrorDescriptions[i].code == errcode)
			return std::string(ErrorDescriptions[i].description);
		i++;
	}

	char str[16];

	RTP_SNPRINTF(str,16,"(%d)",errcode);

	return std::string("Unknown error code") + std::string(str);
}

} // end namespace


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

use App\Driver;

class SignController extends Controller
{
    public function postRent(Request $request) {
        $validator = Validator::make(
            $request->all(),
            [
                'first' => 'required|string',
                'last' => 'required|string',
                'age' => 'required',
                'phone' => 'required',
                'address' => 'required',
                'zip' => 'required',
                'license' => 'required|numeric|unique:drivers',
                'social' => 'required',
                'bank' => 'required',
                'image' => 'required|unique:drivers'
            ]
        );

        if ($validator->fails() || !Input::hasFile('image')) {
            //dd($validator->messages()->all());

            return view('response', ['messages' => $validator->messages()->all()]);
        }

        $md5file = md5_file(Input::file('image')) . '.' . Input::file('image')->getClientOriginalExtension();

        Input::file('image')->move(storage_path('passport'), $md5file);

        $driver = Driver::create([
            'first' => $request->first,
            'last' => $request->last,
            'age' => $request->age,
            'phone' => $request->phone,
            'address' => $request->address,
            'zip' => $request->zip,
            'license' => $request->license,
            'social' => $request->social,
            'bank' => $request->bank,
            'image' => $md5file
        ]);

        return view('response');
    }

    public function getPdf($id) {
        if (empty($id)) {
            return 'Empty ID';
        }

        $driver = Driver::find($id);
        if (empty($driver)) {
            return 'Not found';
        }

        $pdf = \PDF::loadView('pdf', ['driver' => $driver]);

        return $pdf->download($driver->first . '_' . $driver->license . '.pdf');
    }
}


text:
namespace common
{

	class cTPSemaphore
	{
	public:
		cTPSemaphore();
		virtual ~cTPSemaphore();

		bool Init(const int threadCount = -1);
		bool PushTask(cTask *task);
		cTask* PopTask();
		bool RemoveTask(const StrId &taskName);
		bool RemoveTask(const int taskId);
		void Wait();
		bool IsInit();
		void Terminate();
		void Clear();

		static int ThreadFunction(cTPSemaphore *tpSemaphore);

	public:
		CriticalSection m_cs;
		cSemaphore m_sema;
		std::deque<cTask*> m_tasks;
		vector<std::thread*> m_threads;
		bool m_isThreadLoop;
	};

}


text:
#include <ccl.h>
#include <daal.h>

#include "service.h"

#include <chrono>
#include <iostream>

#include "org_apache_spark_ml_feature_PCADALImpl.h"

using namespace std;
using namespace daal;
using namespace daal::algorithms;

const int ccl_root = 0;

typedef double algorithmFPType; /* Algorithm floating-point type */

/*
 * Class:     org_apache_spark_ml_feature_PCADALImpl
 * Method:    cPCATrainDAL
 * Signature: (JIIILorg/apache/spark/ml/feature/PCAResult;)J
 */
JNIEXPORT jlong JNICALL Java_org_apache_spark_ml_feature_PCADALImpl_cPCATrainDAL(
    JNIEnv *env, jobject obj, jlong pNumTabData, jint k, jint executor_num, jint executor_cores,
    jobject resultObj) {
  size_t rankId;
  ccl_get_comm_rank(NULL, &rankId);

  const size_t nBlocks = executor_num;
  const int comm_size = executor_num;

  NumericTablePtr pData = *((NumericTablePtr*)pNumTabData);
  // Source data already normalized
  pData->setNormalizationFlag(NumericTableIface::standardScoreNormalized);

  // Set number of threads for oneDAL to use for each rank
  services::Environment::getInstance()->setNumberOfThreads(executor_cores);

  int nThreadsNew = services::Environment::getInstance()->getNumberOfThreads();
  cout << "oneDAL (native): Number of threads used: " << nThreadsNew << endl;

  pca::Distributed<step1Local, algorithmFPType, pca::svdDense> localAlgorithm;

  /* Set the input data set to the algorithm */
  localAlgorithm.input.set(pca::data, pData);

  /* Compute PCA decomposition */
  localAlgorithm.compute();

  /* Serialize partial results required by step 2 */
  services::SharedPtr<byte> serializedData;
  InputDataArchive dataArch;
  localAlgorithm.getPartialResult()->serialize(dataArch);
  size_t perNodeArchLength = dataArch.getSizeOfArchive();

  serializedData = services::SharedPtr<byte>(new byte[perNodeArchLength * nBlocks]);

  byte* nodeResults = new byte[perNodeArchLength];
  dataArch.copyArchiveToArray(nodeResults, perNodeArchLength);

  ccl_request_t request;

  size_t* recv_counts = new size_t[comm_size * perNodeArchLength];
  for (int i = 0; i < comm_size; i++) recv_counts[i] = perNodeArchLength;

  cout << "PCA (native): ccl_allgatherv receiving " << perNodeArchLength * nBlocks << " bytes" << endl;

  auto t1 = std::chrono::high_resolution_clock::now();

  /* Transfer partial results to step 2 on the root node */
  // MPI_Gather(nodeResults, perNodeArchLength, MPI_CHAR, serializedData.get(),
  // perNodeArchLength, MPI_CHAR, ccl_root, MPI_COMM_WORLD);
  ccl_allgatherv(nodeResults, perNodeArchLength, serializedData.get(), recv_counts,
                 ccl_dtype_char, NULL, NULL, NULL, &request);
  ccl_wait(request);

  auto t2 = std::chrono::high_resolution_clock::now();

  auto duration = std::chrono::duration_cast<std::chrono::seconds>( t2 - t1 ).count();
  std::cout << "PCA (native): ccl_allgatherv took " << duration << " secs" << std::endl;

  delete[] nodeResults;

  if (rankId == ccl_root) {
    auto t1 = std::chrono::high_resolution_clock::now();

    /* Create an algorithm for principal component analysis using the svdDense method
     * on the master node */
    pca::Distributed<step2Master, algorithmFPType, pca::svdDense> masterAlgorithm;

    for (size_t i = 0; i < nBlocks; i++) {
      /* Deserialize partial results from step 1 */
      OutputDataArchive dataArch(serializedData.get() + perNodeArchLength * i,
                                 perNodeArchLength);

      services::SharedPtr<pca::PartialResult<pca::svdDense> >
          dataForStep2FromStep1 =
              services::SharedPtr<pca::PartialResult<pca::svdDense> >(
                  new pca::PartialResult<pca::svdDense>());
      dataForStep2FromStep1->deserialize(dataArch);

      /* Set local partial results as input for the master-node algorithm */
      masterAlgorithm.input.add(pca::partialResults, dataForStep2FromStep1);
    }

    /* Merge and finalizeCompute PCA decomposition on the master node */
    masterAlgorithm.compute();
    masterAlgorithm.finalizeCompute();

    /* Retrieve the algorithm results */
    pca::ResultPtr result = masterAlgorithm.getResult();

    auto t2 = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::seconds>( t2 - t1 ).count();
    std::cout << "PCA (native): master step took " << duration << " secs" << std::endl;

    /* Print the results */
    printNumericTable(result->get(pca::eigenvalues), "First 10 Eigenvalues:", 10);
    printNumericTable(result->get(pca::eigenvectors), "First 10 Eigenvectors:", 10);

    // Return all eigenvalues & eigenvectors

    // Get the class of the input object
    jclass clazz = env->GetObjectClass(resultObj);
    // Get Field references
    jfieldID pcNumericTableField = env->GetFieldID(clazz, "pcNumericTable", "J");
    jfieldID explainedVarianceNumericTableField = env->GetFieldID(clazz, "explainedVarianceNumericTable", "J");

    NumericTablePtr *eigenvalues = new NumericTablePtr(result->get(pca::eigenvalues));
    NumericTablePtr *eigenvectors = new NumericTablePtr(result->get(pca::eigenvectors));

    env->SetLongField(resultObj, pcNumericTableField, (jlong)eigenvectors);
    env->SetLongField(resultObj, explainedVarianceNumericTableField, (jlong)eigenvalues);
  }

  return 0;
}


text:
/**
 * Classes that support the {@link com.capricoinj.core.Wallet}, which knows how to find and save transactions relevant to
 * a set of keys or scripts, calculate balances, and spend money: the wallet has many features and can be extended
 * in various ways, please refer to the website for documentation on how to use it.
 */
package com.capricoinj.wallet;


text:
<?php

namespace denbora\R_T_G_Services\examples\RESTv2\Service;

use denbora\R_T_G_Services\casino\CasinoRestV2;
use denbora\R_T_G_Services\examples\RESTv2\RestExample;
use denbora\R_T_G_Services\R_T_G_ServiceException;

class GetCustomerCategoriesGET extends RestExample
{
    /**
     * GetCustomerCategoriesGET constructor.
     * @param CasinoRestV2 $casino
     */
    public function __construct(CasinoRestV2 $casino)
    {
        try {
            $query = [
                'typeId' => 'b524a32e-b2bb-4a18-896e-c3a08ef0022e', // "description": "Comment",
            ];

            $result = $casino->ServiceService->getCustomerCategoriesGET(json_encode($query));

            dd($result);
        } catch (R_T_G_ServiceException $exception) {
            dd($exception->getMessage());
        }
    }
}


text:
// fairly simple test case
/* 404 IS LEET */
System.out.println( 404 15 1337! );;


text:
using Nest;
using Tests.Framework.Integration;
using Tests.Framework.MockData;

namespace Tests.QueryDsl.Span.Container
{
	public class SpanContainingUsageTests : QueryDslUsageTestsBase
	{
		public SpanContainingUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }

		protected override object QueryJson => new
		{
			span_containing = new
			{
				_name = "named_query",
				boost = 1.1,
				little = new
				{
					span_term = new
					{
						field1 = new
						{
							value = "hoya"
						}
					}
				},
				big = new
				{
					span_term = new
					{
						field1 = new
						{
							value = "hoya2"
						}
					}
				}
			}
		};

		protected override QueryContainer QueryInitializer => new SpanContainingQuery
		{
			Name = "named_query",
			Boost = 1.1,
			Little = new SpanQuery { SpanTerm = new SpanTermQuery { Field = "field1", Value = "hoya"} },
			Big = new SpanQuery { SpanTerm = new SpanTermQuery { Field = "field1", Value = "hoya2"} },
		};

		protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> q) => q
			.SpanContaining(sn => sn
				.Name("named_query")
				.Boost(1.1)
				.Little(i=>i
					.SpanTerm(st=>st.Field("field1").Value("hoya"))
				)
				.Big(e=>e
					.SpanTerm(st=>st.Field("field1").Value("hoya2"))
				)
			);

		protected override ConditionlessWhen ConditionlessWhen => new ConditionlessWhen<ISpanContainingQuery>(a => a.SpanContaining)
		{
			q => {
				q.Big = null;
				q.Little = null;
			},
			q => {
				q.Big = new SpanQuery { };
				q.Little = new SpanQuery { };
			},
		};
	}
}


text:
SSH_USERS=$1

echo 'Upgrade system'
apt-get update && apt-get upgrade -y

echo 'Configure locale'
localedef ru_RU.UTF-8 -i ru_RU -fUTF-8
localedef en_US.UTF-8 -i en_US -fUTF-8

echo 'Configure timezone'
echo 'Europe/Moscow' > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata

echo 'Install minimal programs'
apt-get install -y ssh sudo vim-nox htop iftop git build-essential software-properties-common python-software-properties

echo 'Configure ssh'
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sed "s/PermitRootLogin yes/PermitRootLogin no/g;s/LoginGraceTime 120/LoginGraceTime 45/g;" /etc/ssh/sshd_config.bak > /etc/ssh/sshd_config
echo 'ClientAliveInterval 300' >> /etc/ssh/sshd_config
echo "AllowUsers $SSH_USERS" >> /etc/ssh/sshd_config
service ssh restart


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.codesoftware.logica.inventario;

import co.com.codesoftware.persistencia.HibernateUtil;
import co.com.codesoftware.persistencia.entidad.admin.ClienteEntity;
import co.com.codesoftware.persistencia.entidad.generico.producto.ProductoGenEntity;
import co.com.codesoftware.persistencia.entidad.pedido.PedidoEntity;
import co.com.codesoftware.persistencia.entidad.pedido.PedidoProductoEntity;
import co.com.codesoftware.persistencia.entidad.pedido.RespuestaPedidoEntity;
import co.com.codesoftware.persistencia.utilities.RespuestaEntity;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.GenericJDBCException;

/**
 *
 * @author root
 */
public class PedidosProductoLogica implements AutoCloseable {

    private Session sesion;
    private Transaction tx;
    private String msn;

    /**
     * metodo que inserta los productos del pedido
     *
     * @param Id
     * @param listaProductos
     * @return
     */
    public RespuestaEntity insertaProductoPedido(ArrayList<PedidoProductoEntity> listaProductos, Integer Id) {
        RespuestaEntity respuesta = new RespuestaEntity();
        try {
             this.initOperation();
            for (PedidoProductoEntity item : listaProductos) {
                item.setId(selectMaxPedidoProdcuto());
                item.setPedido(Id);
                try {
                sesion.save(item);
                } catch (GenericJDBCException e) {
                    e.printStackTrace();
                    System.out.println("erro"+e.getCause().getMessage());
                }

                respuesta.setCodigoRespuesta(Id);
                respuesta.setDescripcionRespuesta("INSERTO CORRECTAMENTE LOS PRODUCTOS");
                respuesta.setMensajeRespuesta("OK");

            }
        } catch (Exception e) {
            respuesta.setCodigoRespuesta(0);
            respuesta.setDescripcionRespuesta(e.toString());
            respuesta.setMensajeRespuesta("ERROR");
            e.printStackTrace();
        }
        return respuesta;
    }

    /**
     * metodo que consulta el id de la tabla
     *
     * @return
     */
    public Integer selectMaxPedidoProdcuto() {
        Integer resultado = 1;
        try {
            Criteria crit = sesion.createCriteria(PedidoProductoEntity.class)
                    .setProjection(Projections.max("id"));
            resultado = (Integer) crit.uniqueResult() + 1;
        } catch (Exception e) {
            resultado = 1;
            e.printStackTrace();
        }
        return resultado;
    }

    /**
     * Metodo que consulta los pedidos y los productos de los pedidos, se mapean
     * en el objeto necesario
     *
     * @param idPedido
     * @return
     */
    public RespuestaPedidoEntity consultaProductosXPedido(Integer idPedido) {
        RespuestaPedidoEntity respuesta = new RespuestaPedidoEntity();
        List<ProductoGenEntity> productos = new ArrayList<>();
        List<PedidoProductoEntity> listaProductos = new ArrayList<>();
        ClienteEntity cliente = new ClienteEntity();
        RespuestaEntity res = new RespuestaEntity();
        try {
            initOperation();
            PedidoEntity pedido = new PedidoEntity();
            pedido = consultaPedidoFacturado(idPedido);
            if (!"FA".equalsIgnoreCase(pedido.getEstado())) {
                Criteria crit = sesion.createCriteria(PedidoProductoEntity.class)
                        .add(Restrictions.eq("pedido", idPedido));
                listaProductos = crit.list();
                cliente = consultaCliente(pedido.getCliente().getId());
                productos = mapeoGenericoProducto(listaProductos);
                respuesta.setCliente(cliente);
                respuesta.setListaProductos(productos);
                res.setCodigoRespuesta(1);
                res.setDescripcionRespuesta("OK");
                res.setMensajeRespuesta("OK");
                respuesta.setRespuesta(res);
            } else {
                res.setCodigoRespuesta(0);
                res.setDescripcionRespuesta("EL PEDIDO YA FUE FACTURADO");
                res.setMensajeRespuesta("ERROR");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respuesta;
    }

    /**
     * metodo que consulta el pedido
     *
     * @param pedido
     * @return
     */
    public PedidoEntity consultaPedidoFacturado(Integer pedido) {
        PedidoEntity resultado = new PedidoEntity();
        try {
            initOperation();
            Criteria crit = sesion.createCriteria(PedidoEntity.class)
                    .add(Restrictions.eq("id", pedido))
                    .setFetchMode("sede", FetchMode.JOIN)
                    .setFetchMode("usuario", FetchMode.JOIN)
                    .setFetchMode("cliente", FetchMode.JOIN);
            resultado = (PedidoEntity) crit.uniqueResult();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultado;
    }

    /**
     * Funcion que consulta el objeto cliente
     *
     * @param idCliente
     * @return
     */
    public ClienteEntity consultaCliente(Integer idCliente) {
        ClienteEntity repuesta = new ClienteEntity();
        try {
            initOperation();
            Criteria crit = sesion.createCriteria(ClienteEntity.class).
                    add(Restrictions.eq("id", idCliente));
            repuesta = (ClienteEntity) crit.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return repuesta;
    }

    /**
     * funcion que mapea la list de la consulta al generico
     *
     * @param listaProductos
     * @return
     */
    public List<ProductoGenEntity> mapeoGenericoProducto(List<PedidoProductoEntity> listaProductos) {
        List<ProductoGenEntity> respuesta = new ArrayList<ProductoGenEntity>();
        try {
            for (PedidoProductoEntity item : listaProductos) {
                ProductoGenEntity entidad = new ProductoGenEntity();
                entidad.setAmount(item.getCantidad());
                entidad.setCode(item.getCodigo());
                entidad.setName(item.getNombre());
                entidad.setPrice(item.getPrecio());
                entidad.setTotalPrice(item.getPrecio().multiply(new BigDecimal(item.getCantidad())));
                entidad.setType(1);
                entidad.setId(item.getProducto());
                respuesta.add(entidad);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respuesta;
    }

    /**
     * Funcion que inicializa la clase de hibernate
     *
     * @throws HibernateException
     */
    private void initOperation() throws HibernateException {
        sesion = HibernateUtil.getSessionFactory().openSession();
        tx = sesion.beginTransaction();
    }

    /**
     * Funcion para cerrar la sesion
     *
     * @throws Exception
     */
    @Override
    public void close() {
        try {
            if (tx != null) {
                tx.commit();
                tx = null;
            }
            if (sesion != null) {
                sesion.close();
                sesion = null;
            }
        } catch (GenericJDBCException e) {
                    e.printStackTrace();
                    System.out.println("erro"+e.getCause().getMessage());

        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getMsn() {
        return msn;
    }

    public void setMsn(String msn) {
        this.msn = msn;
    }

}


text:
FROM golang:1.5.1-wheezy
MAINTAINER Francois Hill <francoishill11@gmail.com>

WORKDIR /go/src
EXPOSE 80