text:
try:
    from decimal import Decimal
except:
    from django.utils._decimal import Decimal

from django.core.exceptions import ImproperlyConfigured
from django.db.models import Q
from livesettings import config_value
from satchmo_store.contact.models import Contact
from l10n.models import AdminArea, Country
from satchmo_utils import is_string_like
from product.models import TaxClass
from tax.modules.base.processor import BaseProcessor
from models import TaxBoundry, TaxRate, Taxable
import logging
import re
import datetime

log = logging.getLogger('tax.us_sst')

class Processor(BaseProcessor):

    method = "us_sst"

    def _get_location(self):
        area=country=postal_code=None

        if self.order:
            street1 = self.order.ship_street1
            street2 = self.order.ship_street2
            city = self.order.ship_city
            state = self.order.ship_state
            postal_code = self.order.ship_postal_code
            country = self.order.ship_country
            log.debug('Using order country: %s' % country)
            if country == 'US':
                area = state

        elif self.user and self.user.is_authenticated():
            try:
                contact = Contact.objects.get(user=self.user)
                try:
                    area = contact.shipping_address.state
                    postal_code = contact.shipping_address.postal_code
                except AttributeError:
                    pass
                try:
                    country = contact.shipping_address.country.iso2code
                    log.debug('Using contact country: %s' % country)
                except AttributeError:
                    pass

            except Contact.DoesNotExist:
                log.debug('No contact entry found.')
                pass

        if country:
            try:
                country = Country.objects.get(iso2_code__exact=country)
                log.debug('Found country by ISO code: %s' % country)
            except Country.DoesNotExist:
                log.info("Couldn't find Country from string: %s", country)
                country = None

        if not country:
            from satchmo_store.shop.models import Config
            country = Config.objects.get_current().sales_country

        if area:
            try:
                area = AdminArea.objects.get(name__iexact=area,
                                             country=country)
            except AdminArea.DoesNotExist:
                try:
                    area = AdminArea.objects.get(abbrev__iexact=area,
                                                 country=country)
                except AdminArea.DoesNotExist:
                    log.info("Couldn't find AdminArea from string: %s", area)
                    area = None

        # We don't actually try and match 'A' records.
        street_name = None
        street_number = None
        street_prefix = None
        street_suffix = None
        odd_even = None
        zip_5 = None
        zip_4 = None

        if country.iso2_code == 'US':
            if '-' in postal_code:
                zip_5, zip_4 = postal_code.split('-')
                zip_5 = int(zip_5)
                zip_4 = int(zip_4)
            else:
                zip_5 = int(postal_code)
                zip_4 = None

        log.debug('Area: %s' % area)
        log.debug('Country: %s' % country)
        log.debug('Zip: %s-%s' % (zip_5, zip_4))
        return {
            'area':area,
            'country':country,
            #'street1': street1,
            #'street_number': street_number,
            #'street_name': street_name,
            #'street_prefix': street_prefix,
            #'street_suffix': street_suffix,
            'odd_even': odd_even,
            #'street2': street2,
            #'city':city,
            #'state': state,
            'postal_code': postal_code,
            'zip_4': zip_4,
            'zip_5': zip_5,
        }

    def get_percent(self, taxclass="Default", area=None, country=None):
        return 100*self.get_rate(taxclass=taxclass, area=area, country=country)

    def get_boundry(self, taxable_class, location, date=None):
        """
        Location is a dict of:
            'area', 'country': objects
            'street1', 'street2', 'city', 'state', 'postal_code': strings
        """
        boundry = TaxBoundry.lookup(location['zip_5'], location['zip_4'], date)
        log.debug('Boundry: %s' % boundry)
        return boundry

    def get_rate(self, taxclass=None, area=None, country=None, get_object=False, **kwargs):
        if not taxclass:
            taxclass = "Default"
        rate = None

        #if not (area or country):
        location = self._get_location()
        state = location['area']
        country = location['country']

        if is_string_like(taxclass):
            try:
                taxclass = TaxClass.objects.get(title__iexact=taxclass)

            except TaxClass.DoesNotExist:
                raise ImproperlyConfigured("Can't find a '%s' Tax Class", taxclass)

        # This module only works in the USA.
        if country.iso2_code != 'US':
            rate = None
        else:
            try:
                taxable = Taxable.objects.get(taxClass=taxclass, taxZone=state)
                if taxable.isTaxable is False:
                    rate = None
                else:
                    rate = self.get_boundry(taxable, location)
                    rate.useIntrastate = taxable.useIntrastate
                    rate.useFood = taxable.useFood

            except Taxable.DoesNotExist:
                rate = None

        log.debug("Got rate [%s] = %s", taxclass, rate)
        if get_object:
            return rate
        else:
            if rate:
                return rate.percentage
            else:
                return Decimal("0.00")

    def by_price(self, taxclass, price):
        rate = self.get_rate(taxclass)

        if not rate:
            t = Decimal("0.00")
        else:
            t = rate * price

        return t

    def by_product(self, product, quantity=Decimal('1')):
        """Get the tax for a given product"""
        price = product.get_qty_price(quantity)
        tc = product.taxClass
        return self.by_price(tc, price)

    def by_orderitem(self, orderitem):
        if orderitem.product.taxable:
            price = orderitem.sub_total
            taxclass = orderitem.product.taxClass
            return self.by_price(taxclass, price)
        else:
            return Decimal("0.00")

    #def shipping(self, subtotal=None):
    #    if subtotal is None and self.order:
    #        subtotal = self.order.shipping_sub_total
    #
    #    if subtotal:
    #        rate = None
    #        if config_value('TAX','TAX_SHIPPING'):
    #            try:
    #                tc = TaxClass.objects.get(title=config_value('TAX', 'TAX_CLASS'))
    #                rate = self.get_rate(taxclass=tc)
    #            except:
    #                log.error("'Shipping' TaxClass doesn't exist.")
    #
    #        if rate:
    #            t = rate * subtotal
    #        else:
    #            t = Decimal("0.00")
    #
    #    else:
    #        t = Decimal("0.00")
    #
    #    return t

    def process(self, order=None):
        """
        Calculate the tax and return it.

        Probably need to make a breakout.
        """
        if order:
            self.order = order
        else:
            order = self.order

        sub_total = Decimal('0.00')
        taxes = {}
        rates = {}

        items = [{'type':'item', 'item':x} for x in order.orderitem_set.filter(product__taxable=True)]
        items.append({'type':'shipping', 'price':self.order.shipping_sub_total})

        for i in items:
            if i['type'] == 'item':
                item = i['item']
                tc = item.product.taxClass
                price = item.sub_total
            else:
                if not config_value('TAX','TAX_SHIPPING'):
                    continue

                try:
                    tc = TaxClass.objects.get(title=config_value('TAX', 'TAX_CLASS'))
                    price = i['price']
                    #rate = self.get_rate(taxclass=tc)
                except:
                    log.error("'Shipping' TaxClass doesn't exist.")
                    continue

            if tc:
                tc_key = tc.title
            else:
                tc_key = "Default"

            if tc_key in rates:
                rate = rates[tc_key]
            else:
                rate = self.get_rate(tc, get_object=True)
                rates[tc_key] = rate

            for tax_rate in rate.rates():
                if rate.serCode:
                    tax_key = "%s (%s-SerCode-%s)" % (
                        tc_key, tax_rate.state, rate.serCode
                    )
                else:
                    tax_key = "%s (%s-%s-%s)" % (
                        tc_key, tax_rate.state, tax_rate.jurisdictionType,
                        tax_rate.jurisdictionFipsCode
                    )

                if not tax_key in taxes:
                    taxes[tax_key] = Decimal("0.00")

                if rate:
                    t = price*tax_rate.rate(intrastate=rate.useIntrastate, food=rate.useFood)
                else:
                    t = Decimal("0.00")
                sub_total += t
                taxes[tax_key] += t

        #ship = self.shipping()
        #sub_total += ship
        #taxes['Shipping'] = ship
        ## TODO: Fix this to do the same for shipping as items.

        for k in taxes:
            log.debug('Taxes: %s = %s' % (k, taxes[k]))
            taxes[k] = taxes[k]

        return sub_total, taxes


text:
<?php
namespace Vivo\CMS\UI;

use Vivo\UI;

/**
 * This component is used to substitude an unpublished document in the component tree.
 */
class UnpublishedDocument extends UI\Text
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct('<!-- Unpublished document -->');
    }
}

redpajama_set_name: RedPajamaGithub


text:
import requests
import xmltodict

class Queries:
    def __init__(self, url, key):
        self.url = url
        self.headers = {'content-type': 'text/xml'}
        self.xml_payload = """<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://thalesgroup.com/RTTI/2016-02-16/ldb/" xmlns:ns2="http://thalesgroup.com/RTTI/2013-11-28/Token/types">
  <SOAP-ENV:Header>
    <ns2:AccessToken>
      <ns2:TokenValue>{KEY}</ns2:TokenValue>
    </ns2:AccessToken>
  </SOAP-ENV:Header>
  <SOAP-ENV:Body>
    <ns1:GetDepBoardWithDetailsRequest>
      <ns1:numRows>20</ns1:numRows>
      <ns1:crs>{ORIG}</ns1:crs>
      <ns1:filterCrs>{DEST}</ns1:filterCrs>
      <ns1:filterType>to</ns1:filterType>
      <ns1:timeWindow>120</ns1:timeWindow>
    </ns1:GetDepBoardWithDetailsRequest>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
""".replace("{KEY}", key)

    def services_between(self, origin, destination):
        xml = self.xml_payload \
            .replace("{ORIG}", origin) \
            .replace("{DEST}", destination)
        response = requests.post(self.url, data=xml, headers=self.headers)

        data = xmltodict.parse(response.content)
        response = data["soap:Envelope"]["soap:Body"]["GetDepBoardWithDetailsResponse"]["GetStationBoardResult"]

        if "lt5:trainServices" in response:
            services = response["lt5:trainServices"]["lt5:service"]

            if type(services) is not list:
                services = [services]

            for service in services:
                yield {
                    "crs": origin,
                    "origin": service["lt5:origin"]["lt4:location"]["lt4:locationName"],
                    "destination": service["lt5:destination"]["lt4:location"]["lt4:locationName"],
                    "std": service.get("lt4:std"),
                    "etd": service.get("lt4:etd"),
                    "platform": service.get("lt4:platform", "-")
                }


text:
// Author:	(C) 1996 Uwe Jaeger, 1997 Armin Biere
// LastChange:	Fri Jul 11 11:14:26 MET DST 1997

/*TOC------------------------------------------------------------------------.
 | CexBuilder                                                                |
 `---------------------------------------------------------------------------*/

#include "cexbuild.h"
#include "evalmmc.h"
#include "evaltnc.h"
#include "io.h"
#include "iterator.h"
#include "list.h"
#include "npnftab.h"
#include "prepare.h"

extern TNCreationEvaluator * TableauNode::tnc;
extern EvalPredStore * TableauNode::store_etor;

/*---------------------------------------------------------------------------*/
/* exported variables -------------------------------------------------------*/
/*---------------------------------------------------------------------------*/

bool global_indent_cex = true;

/*---------------------------------------------------------------------------*/
/* function implementations -------------------------------------------------*/
/*---------------------------------------------------------------------------*/

void
CexBuilder::build_witness(Term *t)
{
  TNCreationEvaluator tnc;
  EvalPredStore store_etor;
  IterationVector iv;
  Context c;

  TableauNode::tnc = &tnc;
  TableauNode::store_etor = &store_etor;

  if(Preparator(t).check(store_etor.dependencies_graph()))
    if(store_etor.value(t) != 1) // Term is not true
      {
	error << "Can't build witness: term not true\n";
	return;
      }

  TableauNode * start = tnc.create(t,iv,c,false);
  cex_depthfirst(start,0);
  delete start;
}

/*---------------------------------------------------------------------------*/

void
CexBuilder::build_cex(Term *t)
{
  TNCreationEvaluator tnc;
  EvalPredStore store_etor;
  IterationVector iv;
  Context c;

  TableauNode::tnc = &tnc;
  TableauNode::store_etor = &store_etor;

  if(Preparator(t).check(store_etor.dependencies_graph()))
    if(store_etor.value(t) != 0) // Term is not false
      {
	error << "Can't build counter example: term not false\n";
	return;
      }

  TableauNode * start = tnc.create(t,iv,c,true);
  cex_depthfirst(start,0);
  delete start;
}

/*---------------------------------------------------------------------------*/

void CexBuilder::cex_depthfirst(TableauNode *tn, int level)
{
  level++;
  process_node(tn,level);
  tn->apply_rule();
  List<TableauNode*> * list = tn->successors();
  if (list)
    {
      ListIterator<TableauNode*> it(*list);
      it.first();
      if (!it.isLast() && global_indent_cex) output << inc();
      for (it.first();!it.isDone();it.next())
	cex_depthfirst(it.get(),level);
      // delete tn; delete start deletes all
      it .first();
      if (!it.isLast() && global_indent_cex) output << dec();
    }
}

/*---------------------------------------------------------------------------*/

#if 0

/* uncomment by Uwe */

TableauNode *
CexBuilder::build_path(TNCreationEvaluator &tn_etor,
				     Term *start, TableauNode *sn = 0)
{
  TableauNode *tn, *new_tn;

  verbose << "Building Path \n";

  if (sn)
    tn = tn_etor.create_tn(start, sn->iteration, sn->cont);
  else
    {
      IterationVector iv;
      Context c;
      tn = tn_etor.create_tn(start,iv,c);
    }

  while (tn) {

    process_node(tn);

    if (tn->branching())
      {
	verbose << "End of Path: branching";
	return tn;
      }
    else
      {
	new_tn = tn->apply_rule(tn_etor,store_etor);
	delete tn;
	tn = new_tn;
      }
  }
  verbose << "End of Path: end of branch\n";
  return tn;
}
#endif

/*---------------------------------------------------------------------------*/

void
CexBuilder::process_node(TableauNode *tn, int) { output << tn; }

/*---------------------------------------------------------------------------*/


text:
package planbuilder

import (
	"fmt"

	"github.com/youtube/vitess/go/vt/schema"
	"github.com/youtube/vitess/go/vt/sqlparser"
)

func analyzeSelect(sel *sqlparser.Select, getTable TableGetter) (plan *ExecPlan, err error) {
	// Default plan
	plan = &ExecPlan{
		PlanId:     PLAN_PASS_SELECT,
		FieldQuery: GenerateFieldQuery(sel),
		FullQuery:  GenerateSelectLimitQuery(sel),
	}

	// from
	tableName, hasHints := analyzeFrom(sel.From)
	if tableName == "" {
		plan.Reason = REASON_TABLE
		return plan, nil
	}
	tableInfo, err := plan.setTableInfo(tableName, getTable)
	if err != nil {
		return nil, err
	}

	// There are bind variables in the SELECT list
	if plan.FieldQuery == nil {
		plan.Reason = REASON_SELECT_LIST
		return plan, nil
	}

	if sel.Distinct != "" || sel.GroupBy != nil || sel.Having != nil {
		plan.Reason = REASON_SELECT
		return plan, nil
	}

	// Don't improve the plan if the select is locking the row
	if sel.Lock != "" {
		plan.Reason = REASON_LOCK
		return plan, nil
	}

	// Further improvements possible only if table is row-cached
	if tableInfo.CacheType == schema.CACHE_NONE || tableInfo.CacheType == schema.CACHE_W {
		plan.Reason = REASON_NOCACHE
		return plan, nil
	}

	// Select expressions
	selects, err := analyzeSelectExprs(sel.SelectExprs, tableInfo)
	if err != nil {
		return nil, err
	}
	if selects == nil {
		plan.Reason = REASON_SELECT_LIST
		return plan, nil
	}
	plan.ColumnNumbers = selects

	// where
	conditions := analyzeWhere(sel.Where)
	if conditions == nil {
		plan.Reason = REASON_WHERE
		return plan, nil
	}

	// order
	if sel.OrderBy != nil {
		plan.Reason = REASON_ORDER
		return plan, nil
	}

	// This check should never fail because we only cache tables with primary keys.
	if len(tableInfo.Indexes) == 0 || tableInfo.Indexes[0].Name != "PRIMARY" {
		panic("unexpected")
	}

	pkValues, err := getPKValues(conditions, tableInfo.Indexes[0])
	if err != nil {
		return nil, err
	}
	if pkValues != nil {
		plan.IndexUsed = "PRIMARY"
		offset, rowcount, err := sel.Limit.Limits()
		if err != nil {
			return nil, err
		}
		if offset != nil {
			plan.Reason = REASON_LIMIT
			return plan, nil
		}
		plan.Limit = rowcount
		plan.PlanId = PLAN_PK_IN
		plan.OuterQuery = GenerateSelectOuterQuery(sel, tableInfo)
		plan.PKValues = pkValues
		return plan, nil
	}

	// TODO: Analyze hints to improve plan.
	if hasHints {
		plan.Reason = REASON_HAS_HINTS
		return plan, nil
	}

	indexUsed := getIndexMatch(conditions, tableInfo.Indexes)
	if indexUsed == nil {
		plan.Reason = REASON_NOINDEX_MATCH
		return plan, nil
	}
	plan.IndexUsed = indexUsed.Name
	if plan.IndexUsed == "PRIMARY" {
		plan.Reason = REASON_PKINDEX
		return plan, nil
	}
	var missing bool
	for _, cnum := range selects {
		if indexUsed.FindDataColumn(tableInfo.Columns[cnum].Name) != -1 {
			continue
		}
		missing = true
		break
	}
	if !missing {
		plan.Reason = REASON_COVERING
		return plan, nil
	}
	plan.PlanId = PLAN_SELECT_SUBQUERY
	plan.OuterQuery = GenerateSelectOuterQuery(sel, tableInfo)
	plan.Subquery = GenerateSelectSubquery(sel, tableInfo, plan.IndexUsed)
	return plan, nil
}

func analyzeSelectExprs(exprs sqlparser.SelectExprs, table *schema.Table) (selects []int, err error) {
	selects = make([]int, 0, len(exprs))
	for _, expr := range exprs {
		switch expr := expr.(type) {
		case *sqlparser.StarExpr:
			// Append all columns.
			for colIndex := range table.Columns {
				selects = append(selects, colIndex)
			}
		case *sqlparser.NonStarExpr:
			name := sqlparser.GetColName(expr.Expr)
			if name == "" {
				// Not a simple column name.
				return nil, nil
			}
			colIndex := table.FindColumn(name)
			if colIndex == -1 {
				return nil, fmt.Errorf("column %s not found in table %s", name, table.Name)
			}
			selects = append(selects, colIndex)
		default:
			panic("unreachable")
		}
	}
	return selects, nil
}

func analyzeFrom(tableExprs sqlparser.TableExprs) (tablename string, hasHints bool) {
	if len(tableExprs) > 1 {
		return "", false
	}
	node, ok := tableExprs[0].(*sqlparser.AliasedTableExpr)
	if !ok {
		return "", false
	}
	return sqlparser.GetTableName(node.Expr), node.Hints != nil
}

func analyzeWhere(node *sqlparser.Where) (conditions []sqlparser.BoolExpr) {
	if node == nil {
		return nil
	}
	return analyzeBoolean(node.Expr)
}

func analyzeBoolean(node sqlparser.BoolExpr) (conditions []sqlparser.BoolExpr) {
	switch node := node.(type) {
	case *sqlparser.AndExpr:
		left := analyzeBoolean(node.Left)
		right := analyzeBoolean(node.Right)
		if left == nil || right == nil {
			return nil
		}
		if sqlparser.HasINClause(left) && sqlparser.HasINClause(right) {
			return nil
		}
		return append(left, right...)
	case *sqlparser.ParenBoolExpr:
		return analyzeBoolean(node.Expr)
	case *sqlparser.ComparisonExpr:
		switch {
		case sqlparser.StringIn(
			node.Operator,
			sqlparser.AST_EQ,
			sqlparser.AST_LT,
			sqlparser.AST_GT,
			sqlparser.AST_LE,
			sqlparser.AST_GE,
			sqlparser.AST_NSE,
			sqlparser.AST_LIKE):
			if sqlparser.IsColName(node.Left) && sqlparser.IsValue(node.Right) {
				return []sqlparser.BoolExpr{node}
			}
		case node.Operator == sqlparser.AST_IN:
			if sqlparser.IsColName(node.Left) && sqlparser.IsSimpleTuple(node.Right) {
				return []sqlparser.BoolExpr{node}
			}
		}
	case *sqlparser.RangeCond:
		if node.Operator != sqlparser.AST_BETWEEN {
			return nil
		}
		if sqlparser.IsColName(node.Left) && sqlparser.IsValue(node.From) && sqlparser.IsValue(node.To) {
			return []sqlparser.BoolExpr{node}
		}
	}
	return nil
}


text:
namespace python = boost::python;

// allows BitVects to be pickled
struct ebv_pickle_suite : python::pickle_suite {
  static python::tuple getinitargs(const ExplicitBitVect &self) {
    std::string res = self.toString();
    python::object retval = python::object(
        python::handle<>(PyBytes_FromStringAndSize(res.c_str(), res.length())));
    return python::make_tuple(retval);
  };
};

std::string ebvClassDoc =
    "A class to store explicit bit vectors.\n\
\n\
This class is most useful for situations where the size of the vector\n\
is relatively small (tens of thousands or smaller).\n\
\n\
For larger vectors, use the _SparseBitVect_ class instead.\n\
\n\
As you would expect, _ExplicitBitVects_ support a set of binary operations\n\
so you can do things like:\n\
  bv3 = bv1 & bv2  (bitwise and)\n\
  bv3 = bv1 | bv2  (bitwise or)\n\
  bv3 = bv1 ^ bv2  (bitwise xor)\n\
  bv3 = ~bv1       (bitwise negation)\n\
\n\
Bits can be set and read using either the Set/UnsetBit() and GetBit() methods\n\
or by indexing (i.e. bv[i] = 1 or if bv[i]).\n\
\n";

struct EBV_wrapper {
  static void wrap() {
    python::class_<ExplicitBitVect, boost::shared_ptr<ExplicitBitVect> >(
        "ExplicitBitVect", ebvClassDoc.c_str(), python::init<unsigned int>())
        .def(python::init<std::string>())
        .def(python::init<unsigned int, bool>())
        .def("SetBit", (bool (EBV::*)(unsigned int)) & EBV::setBit,
             "Turns on a particular bit.  Returns the original state of the "
             "bit.\n")
        .def("SetBitsFromList",
             (void (*)(EBV *, python::object))SetBitsFromList,
             "Turns on a set of bits.  The argument should be a tuple or list "
             "of bit ids.\n")
        .def("UnSetBit", (bool (EBV::*)(unsigned int)) & EBV::unsetBit,
             "Turns off a particular bit.  Returns the original state of the "
             "bit.\n")
        .def("UnSetBitsFromList",
             (void (*)(EBV *, python::object))UnSetBitsFromList,
             "Turns off a set of bits.  The argument should be a tuple or list "
             "of bit ids.\n")
        .def("GetBit", (bool (EBV::*)(unsigned int) const) & EBV::getBit,
             "Returns the value of a bit.\n")
        .def("GetNumBits", &EBV::getNumBits,
             "Returns the number of bits in the vector (the vector's size).\n")
        .def("__len__", &EBV::getNumBits)
        .def("GetNumOnBits", &EBV::getNumOnBits,
             "Returns the number of on bits.\n")
        .def("GetNumOffBits", &EBV::getNumOffBits,
             "Returns the number of off bits.\n")
        .def("__getitem__", (int (*)(const EBV &, int))get_VectItem)
        .def("__setitem__", (int (*)(EBV &, int, int))set_VectItem)
        .def("GetOnBits", (IntVect (*)(const EBV &))GetOnBits,
             "Returns a tuple containing IDs of the on bits.\n")
        .def("ToBinary", (python::object (*)(const EBV &))BVToBinary,
             "Returns an internal binary representation of the vector.\n")
        .def("FromBase64", (void (*)(EBV &, const std::string &))InitFromBase64,
             "Initializes the vector from a base64 encoded binary string.\n")
        .def("ToBase64", (std::string (*)(EBV &))ToBase64,
             "Converts the vector to a base64 string (the base64 encoded "
             "version of the results of ToString()).\n")
        .def(python::self & python::self)
        .def(python::self | python::self)
        .def(python::self ^ python::self)
        .def(python::self + python::self)
        .def(~python::self)
        .def(python::self == python::self)
        .def(python::self != python::self)
        .def(python::self += python::self)

        .def_pickle(ebv_pickle_suite());
  }
};

void wrap_EBV() { EBV_wrapper::wrap(); }


text:
creds=$(echo "$1" | cut -d '|' -f 1)
LGID=$(echo "$1" | cut -d '|' -f 2)
apikey=$(echo "$1" | cut -d '|' -f 3)
url=$(echo "$1" | cut -d '|' -f 4)

CurrentUser=`/usr/bin/stat -f%Su /dev/console`
currDate=$(date +"%Y-%m-%d_%H-%M-%S")
fileName="$CurrentUser-HubLogs-$currDate"

mkdir -p "/tmp/Workspace ONE/$fileName"
mkdir -p "/tmp/Workspace ONE/$fileName/Data"
mkdir -p "/tmp/Workspace ONE/$fileName/Munki"
mkdir -p "/tmp/Workspace ONE/$fileName/Daemon"
mkdir -p "/tmp/Workspace ONE/$fileName/User"

cp -rf "/Library/Application Support/AirWatch/Data/CustomAttributes" "/tmp/Workspace ONE/$fileName/Data/CustomAttributes"
cp -rf "/Library/Application Support/AirWatch/Data/CustomAttributesCache" "/tmp/Workspace ONE/$fileName/Data/CustomAttributesCache"
cp -rf "/Library/Application Support/AirWatch/Data/Munki" "/tmp/Workspace ONE/$fileName/Data/Munki"
rm -f "/tmp/Workspace ONE/$fileName/Data/Munki/Managed Installs/b.receiptdb"
cp -rf "/Library/Application Support/AirWatch/Data/ProductsNew" "/tmp/Workspace ONE/$fileName/Data/ProductsNew"
cp -f "/Library/Application Support/AirWatch/Data/AppStatuses_WS1.plist" "/tmp/Workspace ONE/$fileName/Data/AppStatuses_WS1.plist"

cp -f "/Library/Application Support/AirWatch/Data/Munki/Managed Installs/Logs/ManagedSoftwareUpdate.log" "/tmp/Workspace ONE/$fileName/Munki/ManagedSoftwareUpdate.log"
cp -f "/Library/Application Support/AirWatch/Data/Munki/Managed Installs/Logs/install.log" "/tmp/Workspace ONE/$fileName/Munki/install.log"

cp -rf "/Library/Logs/IntelligentHub" "/tmp/Workspace ONE/$fileName/Daemon/Logs"

cp -rf "/Users/$CurrentUser/Library/Logs/IntelligentHub" "/tmp/Workspace ONE/$fileName/User/Logs"

cd "/tmp/Workspace ONE/"
zip -rqX "$fileName.zip" "$fileName"

category="0"
categoryJSON=$(curl -X GET --header 'Content-Type: application/json' --header 'Accept: application/json' --header "Authorization: Basic $creds" --header "aw-tenant-code: $apikey" "$url/API/mcm/categories?locationgroupid=$LGID" 2>/dev/null)

i=1
substring=`echo "$categoryJSON" | cut -d '{' -f $i`
while [ -n "$substring" ]
do
	if echo "$substring" | grep -q "macOS Logs"; then
		tmp=${substring##*\"categoryId\":}
		category=${tmp:1:36}
		#echo "Found existing category: $category"
		break
	fi
	i=$((i + 1))
    substring=`echo "$categoryJSON" | cut -d '{' -f $i`
done

if [ "$category" == "0" ]; then
	echo "No existing category"

	categoryJSON=$(curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header "Authorization: Basic $creds" --header "aw-tenant-code: $apikey" -d "{ \"name\": \"macOS Logs\", \"hasSubCategories\": false, \"locationGroupId\": $LGID }" "$url/API/mcm/categories" 2>/dev/null)

	tmp=${categoryJSON##*\"categoryId\":}
	category=${tmp:1:36}
	#echo "Created new category: $category"
fi

if [ "$category" != "0" ]; then
	fileJSON=$(curl -v -X POST --header 'Content-Type: application/octet-stream' --header 'Accept: application/json' --header "Authorization: Basic $creds" --header "aw-tenant-code: $apikey" --data-binary "@/tmp/Workspace ONE/$fileName.zip" "$url/API/mcm/api/AwContentV2?fileName=$fileName.zip&categoryId=$category&effectiveDate=2500-01-01T12%3A00%3A00.000&locationGroupId=$LGID" 2>/dev/null)
fi

rm -rf "/tmp/Workspace ONE/$fileName"
rm -f "/tmp/Workspace ONE/$fileName.zip"
rm -f "/tmp/Workspace ONE/CreateHubLogs/tempinfo"


text:
package org.estatio.fixture.asset;

import org.estatio.dom.asset.PropertyType;
import org.estatio.dom.geography.Country;
import org.estatio.dom.party.Party;
import org.estatio.fixture.geography.CountriesRefData;
import org.estatio.fixture.party.OrganisationForHelloWorldNl;
import org.estatio.fixture.party.PersonForJohnDoeNl;
import org.estatio.fixture.security.tenancy.ApplicationTenancyForFr;

import static org.estatio.integtests.VT.ld;

public class _PropertyForVivFr extends PropertyAbstract {

    public static final String REF = "VIV";
    public static final String PARTY_REF_OWNER = OrganisationForHelloWorldNl.REF;
    public static final String PARTY_REF_MANAGER = PersonForJohnDoeNl.REF;
    public static final String AT_PATH_COUNTRY = ApplicationTenancyForFr.PATH;

    public static String unitReference(String suffix) {
        return REF + "-" + suffix;
    }

    @Override
    protected void execute(ExecutionContext executionContext) {

        // prereqs
        if(isExecutePrereqs()) {
            executionContext.executeChild(this, new OrganisationForHelloWorldNl());
            executionContext.executeChild(this, new PersonForJohnDoeNl());
        }

        // exec
        Party owner = parties.findPartyByReference(PARTY_REF_OWNER);
        Party manager = parties.findPartyByReference(PARTY_REF_MANAGER);

        Country france = countries.findCountry(CountriesRefData.FRA);
        createPropertyAndUnits(
                AT_PATH_COUNTRY,
                REF, "Vive les shops", "Paris", france, PropertyType.SHOPPING_CENTER,
                5, ld(2004, 5, 6), ld(2008, 6, 1), owner, manager,
                "48.8740002697085;2.326230019708498", executionContext);
    }

}


text:
import reverbjs from './reverb';

let r
let ctx

export default new Promise((resolve, reject) => {
    r = resolve
})

/**
 * For IOS, audio context can only be created inside of a touch event.
 */
export const init = () => {
    if (ctx)
        return ctx

    ctx = new (window.AudioContext || window.webkitAudioContext)()
    reverbjs.extend(ctx)
    var oscillator = ctx.createOscillator()
    oscillator.frequency.value = 1
    oscillator.connect(ctx.destination)
    oscillator.start(0)
    oscillator.stop(0)
    r(ctx)
    return ctx
}

const onIos = () =>
    /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream

// The audio context must be created inside of a touch event on IOS
if (onIos()) {
    document.body.addEventListener('touchstart', () => init(), false);
} else {
    init()
}


text:
using System.Runtime.Serialization;

namespace SharpRemote
{
	/// <summary>
	///     The reason why the server dropped the connection to the client:
	///     Is only used as part of the connection handshake between client and server.
	/// </summary>
	[DataContract]
	public enum ConnectionDropReason
	{
		/// <summary>
		///     The connection isn't being dropped.
		/// </summary>
		[EnumMember] None = 0,

		/// <summary>
		///     The server doesn't accept the protocol version choices offered by the client.
		/// </summary>
		[EnumMember] UnacceptableVersion = 1,

		/// <summary>
		///     The server doesn't accept the serializer choices offered by the client.
		/// </summary>
		[EnumMember] UnacceptableSerializer = 2,

		/// <summary>
		///     The server doesn't accept the type model sent by the client.
		///     This may be because the type model uses types the server doesn't want to use,
		///     or cannot resolve, etc...
		/// </summary>
		[EnumMember] UnacceptableTypeModel = 3
	}
}


text:
import { ChildProcess, fork } from 'child_process';
import { IDisposable } from 'vs/base/common/lifecycle';
import { TPromise } from 'vs/base/common/winjs.base';
import { Delayer } from 'vs/base/common/async';
import { clone, assign } from 'vs/base/common/objects';
import { Emitter } from 'vs/base/common/event';
import { fromEventEmitter } from 'vs/base/node/event';
import { createQueuedSender } from 'vs/base/node/processes';
import { ChannelServer as IPCServer, ChannelClient as IPCClient, IChannelClient, IChannel } from 'vs/base/parts/ipc/common/ipc';

export class Server extends IPCServer {
	constructor() {
		super({
			send: r => { try { process.send(r); } catch (e) { /* not much to do */ } },
			onMessage: fromEventEmitter(process, 'message', msg => msg)
		});

		process.once('disconnect', () => this.dispose());
	}
}

export interface IIPCOptions {

	/**
	 * A descriptive name for the server this connection is to. Used in logging.
	 */
	serverName: string;

	/**
	 * Time in millies before killing the ipc process. The next request after killing will start it again.
	 */
	timeout?: number;

	/**
	 * Arguments to the module to execute.
	 */
	args?: string[];

	/**
	 * Environment key-value pairs to be passed to the process that gets spawned for the ipc.
	 */
	env?: any;

	/**
	 * Allows to assign a debug port for debugging the application executed.
	 */
	debug?: number;

	/**
	 * Allows to assign a debug port for debugging the application and breaking it on the first line.
	 */
	debugBrk?: number;

	/**
	 * See https://github.com/Microsoft/vscode/issues/27665
	 * Allows to pass in fresh execArgv to the forked process such that it doesn't inherit them from `process.execArgv`.
	 * e.g. Launching the extension host process with `--inspect-brk=xxx` and then forking a process from the extension host
	 * results in the forked process inheriting `--inspect-brk=xxx`.
	 */
	freshExecArgv?: boolean;

	/**
	 * Enables our createQueuedSender helper for this Client. Uses a queue when the internal Node.js queue is
	 * full of messages - see notes on that method.
	 */
	useQueue?: boolean;
}

export class Client implements IChannelClient, IDisposable {

	private disposeDelayer: Delayer<void>;
	private activeRequests: TPromise<void>[];
	private child: ChildProcess;
	private _client: IPCClient;
	private channels: { [name: string]: IChannel };

	constructor(private modulePath: string, private options: IIPCOptions) {
		const timeout = options && options.timeout ? options.timeout : 60000;
		this.disposeDelayer = new Delayer<void>(timeout);
		this.activeRequests = [];
		this.child = null;
		this._client = null;
		this.channels = Object.create(null);
	}

	getChannel<T extends IChannel>(channelName: string): T {
		const call = (command: string, arg: any) => this.request(channelName, command, arg);
		return { call } as T;
	}

	protected request(channelName: string, name: string, arg: any): TPromise<void> {
		if (!this.disposeDelayer) {
			return TPromise.wrapError(new Error('disposed'));
		}

		this.disposeDelayer.cancel();

		const channel = this.channels[channelName] || (this.channels[channelName] = this.client.getChannel(channelName));
		const request: TPromise<void> = channel.call(name, arg);

		// Progress doesn't propagate across 'then', we need to create a promise wrapper
		const result = new TPromise<void>((c, e, p) => {
			request.then(c, e, p).done(() => {
				if (!this.activeRequests) {
					return;
				}

				this.activeRequests.splice(this.activeRequests.indexOf(result), 1);

				if (this.activeRequests.length === 0) {
					this.disposeDelayer.trigger(() => this.disposeClient());
				}
			});
		}, () => request.cancel());

		this.activeRequests.push(result);
		return result;
	}

	private get client(): IPCClient {
		if (!this._client) {
			const args = this.options && this.options.args ? this.options.args : [];
			const forkOpts = Object.create(null);

			forkOpts.env = assign(clone(process.env), { 'VSCODE_PARENT_PID': String(process.pid) });

			if (this.options && this.options.env) {
				forkOpts.env = assign(forkOpts.env, this.options.env);
			}

			if (this.options && this.options.freshExecArgv) {
				forkOpts.execArgv = [];
			}

			if (this.options && typeof this.options.debug === 'number') {
				forkOpts.execArgv = ['--nolazy', '--inspect=' + this.options.debug];
			}

			if (this.options && typeof this.options.debugBrk === 'number') {
				forkOpts.execArgv = ['--nolazy', '--inspect-brk=' + this.options.debugBrk];
			}

			this.child = fork(this.modulePath, args, forkOpts);

			const onMessageEmitter = new Emitter<any>();
			const onRawMessage = fromEventEmitter(this.child, 'message', msg => msg);

			onRawMessage(msg => {
				// Handle console logs specially
				if (msg && msg.type === '__$console') {
					let args = ['%c[IPC Library: ' + this.options.serverName + ']', 'color: darkgreen'];
					try {
						const parsed = JSON.parse(msg.arguments);
						args = args.concat(Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
					} catch (error) {
						args.push(msg.arguments);
					}

					console[msg.severity].apply(console, args);
					return null;
				}

				// Anything else goes to the outside
				else {
					onMessageEmitter.fire(msg);
				}
			});

			const sender = this.options.useQueue ? createQueuedSender(this.child) : this.child;
			const send = r => this.child && this.child.connected && sender.send(r);
			const onMessage = onMessageEmitter.event;
			const protocol = { send, onMessage };

			this._client = new IPCClient(protocol);

			const onExit = () => this.disposeClient();
			process.once('exit', onExit);

			this.child.on('error', err => console.warn('IPC "' + this.options.serverName + '" errored with ' + err));

			this.child.on('exit', (code: any, signal: any) => {
				process.removeListener('exit', onExit);

				if (this.activeRequests) {
					this.activeRequests.forEach(req => req.cancel());
					this.activeRequests = [];
				}

				if (code !== 0 && signal !== 'SIGTERM') {
					console.warn('IPC "' + this.options.serverName + '" crashed with exit code ' + code);
					this.disposeDelayer.cancel();
					this.disposeClient();
				}
			});
		}

		return this._client;
	}

	private disposeClient() {
		if (this._client) {
			this.child.kill();
			this.child = null;
			this._client = null;
			this.channels = Object.create(null);
		}
	}

	dispose() {
		this.disposeDelayer.cancel();
		this.disposeDelayer = null;
		this.disposeClient();
		this.activeRequests = null;
	}
}


text:
package com.hortonworks.simulator.impl.messages;

public class StopSimulation {

}


text:
package org.swellrt.beta.client.platform.web.editor.annotation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;

import org.swellrt.beta.client.platform.web.editor.JsEditorUtils;
import org.swellrt.beta.client.platform.web.editor.SEditorException;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.client.editor.Editor;
import org.waveprotocol.wave.client.editor.content.ContentElement;
import org.waveprotocol.wave.client.editor.content.ContentNode;
import org.waveprotocol.wave.client.editor.content.paragraph.Paragraph;
import org.waveprotocol.wave.client.editor.content.paragraph.Paragraph.LineStyle;
import org.waveprotocol.wave.client.editor.content.paragraph.ParagraphBehaviour;
import org.waveprotocol.wave.client.editor.util.EditorAnnotationUtil;
import org.waveprotocol.wave.model.document.RangedAnnotation;
import org.waveprotocol.wave.model.document.util.Annotations;
import org.waveprotocol.wave.model.document.util.IRange;
import org.waveprotocol.wave.model.document.util.Point;
import org.waveprotocol.wave.model.document.util.Range;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.ReadableStringSet;
import org.waveprotocol.wave.model.util.ReadableStringSet.Proc;
import org.waveprotocol.wave.model.util.StringSet;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * A single place to put all annotation related logic.
 *

 * Static methods implement set/unset logic for annotations.
 *

 * Instances of this class are wrappers of each annotation type, merely to track
 * them and manage event handlers.
 *
 * @author pablojan@gmail.com (Pablo Ojanguren)
 *
 */
public class AnnotationController {

  public interface AttributeGenerator {

    public Map<String, String> generate(Range range, String styleKey);

  }

  public enum Type {

    TEXT, PARAGRAPH_STYLE, PARAGRAPH_ACTION

  }

  //
  //
  //

  /**
   * A single method to set annotations of any type.
   *
   * @param editor
   * @param key
   * @param value
   * @param range
   * @throws SEditorException
   */
  public static AnnotationValue set(Editor editor, String key, final String value, IRange range)
      throws SEditorException {

    final AnnotationController ac = AnnotationRegistry.get(key);

    if (ac == null)
      throw new SEditorException(SEditorException.UNKNOWN_ANNOTATION,
          "Annotation key is not registered");

    //
    // Text
    //

    if (ac.getType().equals(AnnotationController.Type.TEXT)) {

      if (Annotations.isLocal(key)) {
        editor.getContent().getLocalAnnotations().setAnnotation(range.getStart(), range.getEnd(),
            key, value);
      } else {
        EditorAnnotationUtil.setAnnotationOverRange(editor.getDocument(),
            editor.getCaretAnnotations(), key, value, range.getStart(), range.getEnd());
      }

    } else if (ac.getType().equals(AnnotationController.Type.PARAGRAPH_STYLE)) {

      //
      // Paragraph value
      //
      applyParagraphStyle(editor, key, value, Range.copy(range));

    } else if (ac.getType().equals(AnnotationController.Type.PARAGRAPH_ACTION)) {

      editor.undoableSequence(new Runnable() {
        @Override
        public void run() {

          ContentElement.Action action = ac.actions.get(value);
          if (action == null)
            return;

          Paragraph.traverse(editor.getContent().getLocationMapper(), range.getStart(),
              range.getEnd(), action);
        }
      });

    }

    return AnnotationValueBuilder.buildWithRange(editor.getContent().getMutableDoc(), key, value,
        Range.copy(range),
        AnnotationValue.MATCH_IN);

  }

  protected static void applyParagraphStyle(Editor editor, String key, String value, Range range) {

    final AnnotationController controller = AnnotationRegistry.get(key);

    if (controller == null)
      return;

    if (value != null && !value.isEmpty() && !controller.styles.containsKey(value))
      return;

    boolean isOn = (value != null && !value.isEmpty() && !value.equals("default"));
    String styleValue = null;
    if (!isOn)
      styleValue = "default";
    else
      styleValue = value;

    Paragraph.LineStyle style = controller.styles.get(styleValue);
    if (controller.attributeGenerator != null)
      style.setAttributes(controller.attributeGenerator.generate(range, styleValue));

    Paragraph.apply(editor.getContent().getLocationMapper(), range.getStart(), range.getEnd(),
        style, isOn);
    style.setAttributes(null);

  }

  public static void clearAnnotation(Editor editor, ReadableStringSet keys, Range range) {

    StringSet paragraphKeySet = CollectionUtils.createStringSet();
    StringSet textKeySet = CollectionUtils.createStringSet();
    filterOutKeys(keys, paragraphKeySet, textKeySet, AnnotationRegistry::isParagraphAnnotation);

    StringSet textLocalKeySet = CollectionUtils.createStringSet();
    StringSet textRemoteKeySet = CollectionUtils.createStringSet();
    filterOutKeys(textKeySet, textLocalKeySet, textRemoteKeySet,  Annotations::isLocal);

    editor.undoableSequence(new Runnable() {

      @Override
      public void run() {

        // Local annotations
        EditorAnnotationUtil.clearAnnotationsOverRange(editor.getContent().getLocalAnnotations(), editor.getCaretAnnotations(), textLocalKeySet, range.getStart(), range.getEnd());

        // Persisted annotations
        EditorAnnotationUtil.clearAnnotationsOverRange(editor.getDocument(),
            editor.getCaretAnnotations(), textRemoteKeySet, range.getStart(), range.getEnd());

        // Paragraph annotations
        paragraphKeySet.each(new Proc() {

          @Override
          public void apply(String key) {

            final AnnotationController ac = AnnotationRegistry.get(key);

            if (ac == null)
              return;

            if (ac.getType().equals(AnnotationController.Type.PARAGRAPH_STYLE)) {

              //
              // Paragraph value
              //
              applyParagraphStyle(editor, key, null, range);

            } else if (ac.getType().equals(AnnotationController.Type.PARAGRAPH_ACTION)) {

              //
              // Paragraph action
              //
              if (ac.resetAction != null) {
                Paragraph.traverse(editor.getContent().getLocationMapper(), range.getStart(),
                    range.getEnd(), ac.resetAction);
              }

            }

          }

        });

      }
    });

  }

  private static void filterOutKeys(ReadableStringSet keySet, StringSet inSet, StringSet outSet,
      Function<String, Boolean> matcher) {
    keySet.each(new Proc() {

      @Override
      public void apply(String key) {

        if (matcher.apply(key)) {
          inSet.add(key);
        } else {
          outSet.add(key);
        }

      }
    });

  }

  /**
   * Adjust a given range in order to be used to get annotations. If range is
   * collapsed, range must be expanded by 1 char in the current paragraph
   *
   * @param editor
   * @param range
   * @return
   */
  private static Range selectionRangeForGetAnnotation(Editor editor, Range range) {

    if (!range.isCollapsed()) {
      return range;
    } else {

      Point<ContentNode> startPoint = editor.getDocument().locate(range.getStart());
      Point<ContentNode> endPoint = editor.getDocument().locate(range.getStart() + 1);

      if (startPoint.getContainer().equals(endPoint.getContainer())) {
        return Range.create(range.getStart(), range.getStart() + 1);
      }

      startPoint = editor.getDocument().locate(range.getStart() - 1);
      endPoint = editor.getDocument().locate(range.getStart());

      if (startPoint.getContainer().equals(endPoint.getContainer())) {
        return Range.create(range.getStart() - 1, range.getStart());
      }

      return range;
    }

  }

  public static JavaScriptObject getAnnotationsWithFilters(Editor editor, JavaScriptObject keys,
      Range range, Function<Object, Boolean> valueMatcher)
      throws SEditorException {

    JsoView result = JsoView.as(JavaScriptObject.createObject());
    ReadableStringSet keySet = AnnotationRegistry.normalizeKeys(JsEditorUtils.toStringSet(keys));
    StringSet paragraphKeySet = CollectionUtils.createStringSet();
    StringSet textKeySet = CollectionUtils.createStringSet();
    filterOutKeys(keySet, paragraphKeySet, textKeySet, AnnotationRegistry::isParagraphAnnotation);

    Range searchRange = selectionRangeForGetAnnotation(editor, range);

    // Note: scan local annotations cause them include remote ones

    // get all annotations, filter later
    editor.getContent().getLocalAnnotations()
        .rangedAnnotations(searchRange.getStart(), searchRange.getEnd(), null)
        .forEach((RangedAnnotation<Object> ra) -> {

          // ignore annotations with null value, are just editor's internal
          // stuff
          if (ra.value() == null)
            return;

          // get all annotations and filter here
          if (!keySet.isEmpty() && !AnnotationRegistry.matchKeys(textKeySet, ra.key()))
            return;

          AnnotationController a = AnnotationRegistry.get(ra.key());
          if (a == null)
            return; // skip not registered annotations

          Range anotRange = new Range(ra.start(), ra.end());
          int rangeMatch = AnnotationValueBuilder.getRangeMatch(searchRange, anotRange);

          if (valueMatcher != null && !valueMatcher.apply(ra.value()))
            return; // skip

          if (!result.containsKey(ra.key())) {
            result.setJso(ra.key(), JavaScriptObject.createArray());
          }

          AnnotationValue anotationValue = AnnotationValueBuilder.buildWithRange(
              editor.getContent().getMutableDoc(), ra.key(), ra.value(), anotRange, rangeMatch);

          JsEditorUtils.addToArray(result.getJso(ra.key()), anotationValue);
        });

    //
    // Paragraph annotations
    //

    List<AnnotationController> controllers = new ArrayList<AnnotationController>();
    boolean allParagraphAnnotations = false;

    // all annotations case and paragraph prefix selector
    if (keySet.isEmpty() || keySet.contains(AnnotationRegistry.PARAGRAPH_PREFIX)) {
      allParagraphAnnotations = true;
    }

    if (!allParagraphAnnotations) {
      paragraphKeySet.each(new Proc() {

        @Override
        public void apply(String key) {

          AnnotationController c = AnnotationRegistry.get(key);
          if (c.isParagraphStyle()) {
            controllers.add(c);
          }
        }

      });
    }

    final AnnotationController[] paragraphControllers = allParagraphAnnotations
        ? AnnotationRegistry.PARAGRAPH_STYLED_CONTROLLERS
        : controllers.toArray(new AnnotationController[] {});

    Paragraph.traverse(editor.getContent().getLocationMapper(), searchRange.getStart(),
        searchRange.getEnd(),
        new ContentElement.Action() {

          @Override
          public void execute(ContentElement e) {

            for (AnnotationController c : paragraphControllers) {
              String styleValue = c.isAppliedParagraphStyle(e);
              if (styleValue != null) {

                AnnotationValue anotationValue = AnnotationValueBuilder.buildForParagraphNode(
                    editor.getContent().getMutableDoc(), c.key, styleValue, e,
                    AnnotationValue.MATCH_IN);

                if (!result.containsKey(c.key)) {
                  result.setJso(c.key, JavaScriptObject.createArray());
                }

                JsEditorUtils.addToArray(result.getJso(c.key), anotationValue);

              }
            }

          }

        });

    return result;

  }

  private final Type type;

  /** Annotation key */
  private String key;

  //
  // Paragraph annotations
  //

  private ParagraphBehaviour paragraphBehaviour;

  /** Paragraph styles */
  private Map<String, LineStyle> styles;

  /** Paragraph auto generated attributes */
  private AttributeGenerator attributeGenerator;

  //
  // Action-based paragraph annotations
  //

  private Map<String, ContentElement.Action> actions;
  private ContentElement.Action resetAction;

  private final ParagraphEventHandler paragraphEventHandler;
  private final TextEventHandler textEventHandler;

  /**
   * Constructor for text annotations.
   *
   * @param key
   * @param emptyValue
   */
  public AnnotationController(String key) {
    this.type = Type.TEXT;
    this.key = key;
    this.textEventHandler = new TextEventHandler(key);
    this.paragraphEventHandler = null;
  }

  /**
   * Constructor for paragraph annotations.
   *
   * @param key
   * @param styles
   * @param attributeGenerator
   */
  public AnnotationController(ParagraphBehaviour paragraphBehaviour, String key,
      Map<String, LineStyle> styles,
      AttributeGenerator attributeGenerator) {
    this.type = Type.PARAGRAPH_STYLE;
    this.paragraphBehaviour = paragraphBehaviour;
    this.key = key;
    this.styles = styles;
    this.attributeGenerator = attributeGenerator;
    this.textEventHandler = null;
    this.paragraphEventHandler = new ParagraphEventHandler(key, paragraphBehaviour);
    ParagraphEventHandler.register(key, this.paragraphEventHandler);
  }

  /**
   * Constructor action-based paragraph annotations.
   *
   * @param key
   * @param actions
   * @param resetAction
   */
  public AnnotationController(String key, Map<String, ContentElement.Action> actions,
      ContentElement.Action resetAction) {
    this.type = Type.PARAGRAPH_ACTION;
    this.actions = actions;
    this.resetAction = resetAction;
    this.textEventHandler = null;
    this.paragraphEventHandler = null;
  }

  public Type getType() {
    return type;
  }

  protected String getKey() {
    return key;
  }

  protected Map<String, LineStyle> getStyles() {
    return styles;
  }

  protected AttributeGenerator getAttributeGenerator() {
    return attributeGenerator;
  }

  public void setEventHandler(AnnotationEvent.Handler h) {

    if (h == null)
      return;

    if (type.equals(Type.TEXT)) {
      textEventHandler.setHandler(h);
    } else if (type.equals(Type.PARAGRAPH_STYLE)) {
      paragraphEventHandler.setHandler(h);
    }

  }

  public void unsetEventHandler() {
    if (type.equals(Type.TEXT)) {
      textEventHandler.setHandler(null);
    } else if (type.equals(Type.PARAGRAPH_STYLE)) {
      paragraphEventHandler.setHandler(null);
    }
  }

  public TextEventHandler getTextEventHanlder() {
    return textEventHandler;
  }

  /**
   * @return the style value, null if style is not applied
   */
  public String isAppliedParagraphStyle(ContentElement element) {
    if (styles == null) return null;

    String[] value = { null };

    styles.entrySet().forEach((Entry<String, LineStyle> e) -> {

      if (value[0] == null && e.getValue().isApplied(element)) {
        value[0] = e.getKey();
      }

    });

    return value[0];

  }

  public boolean isParagraphStyle() {
    return styles != null;
  }

}


text:
package com.totsp.tom.util;

import org.junit.Test;

import java.math.BigDecimal;

import static org.junit.Assert.assertEquals;

/**
 *
 */
public class NumberStatisticsTest {

    @Test
    public void testMedians(){
        NumberStatistics<Integer> stats = new NumberStatistics<Integer>();
        for(int i = 0; i < 100; i++){
            stats.add(i);
        }
        assertEquals((Integer) 49, stats.median());
        //System.out.println(stats.median());
        assertEquals(new BigDecimal(49.5), stats.medianAveraged());
        //System.out.println(stats.medianAveraged());
    }

    @Test
    public void testMode(){
        NumberStatistics<Double> stats = new NumberStatistics<Double>();
        stats.add(1.0D);
        stats.add(1.5D);
        stats.add(3.0D);
        stats.add(1.5D);
        stats.add(0D);

        assertEquals(Double.valueOf(1.5), stats.mode());
    }

    @Test
    public void testMean(){
        NumberStatistics<Long> stats = new NumberStatistics<Long>();
        stats.add(2L);
        stats.add(2L);
        stats.add(3L);
        stats.add(3L);
        assertEquals(new BigDecimal(2.5), stats.mean());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <integer name="ayo_notify_animation_default_duration">300</integer>
</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nfcwormhole.liquor.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="读防伪信息"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:checked="true"
        android:text="是否原装"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/checkBox"
        android:text="2015.5.14"
        android:layout_alignRight="@+id/checkBox"
        android:layout_alignEnd="@+id/checkBox" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editText"
        android:text="GuangDong"
        android:layout_alignRight="@+id/editText3"
        android:layout_alignEnd="@+id/editText3" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/checkBox"
        android:layout_alignRight="@+id/checkBox"
        android:layout_below="@+id/editText2"
        android:text="QS3600 1505 0001"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editText3"
        android:text="写防伪信息"
        android:layout_alignRight="@+id/button"
        android:layout_alignEnd="@+id/button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="For Test:awong1900@163.com"
        android:id="@+id/textView2"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true" />

</RelativeLayout>


text:
package sedion.jeffli.wmuitp.constant;

import sedion.jeffli.wmuitp.constant.main.Constant;

public class CourseConstant
{
	public static final String QR_CODE_PATH  		= Constant.getImgRealPath()+"/qrcode";		//二维码图片存储地址
	public static final String ALL_QR_CODE_PATH  	= "/qrcode/";	        					//二维码图片全路径地址

	public static final String COURSE_URL			= "../course/courses";
	public static final String COURSE_REF			= "courses";
	public static final String COURSE_OBJECT		= "course";
	public static final String COURSE_OBJECT_LIST   = "courses";

	public static String getCourseUrl()
	{
		return COURSE_URL;
	}
	public static String getCourseRef()
	{
		return COURSE_REF;
	}
	public static String getCourseObject()
	{
		return COURSE_OBJECT;
	}
	public static String getCourseObjectList()
	{
		return COURSE_OBJECT_LIST;
	}

}


text:
package org.javacore.scheduler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Guosi Chen on 2017/5/15.
 * ScheduledExecutorService的使用
 */
public class SchedulerExecutorTest implements Runnable {

    private final String jobName;

    public SchedulerExecutorTest(String jobName) {
        this.jobName = jobName;
    }

    @Override
    public void run() {
        System.out.println("running =>" + jobName);
    }

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        // 一秒
        executorService.scheduleAtFixedRate(new SchedulerExecutorTest("job1"), 1, 1, TimeUnit.SECONDS);
        // 两秒
        executorService.scheduleWithFixedDelay(new SchedulerExecutorTest("job2"), 1, 2, TimeUnit.SECONDS);
    }
}


text:
namespace devtools_service {

class DevToolsService;

class DevToolsHttpServer : public mojo::HttpServerDelegate {
 public:
  // |service| must outlive this object.
  DevToolsHttpServer(DevToolsService* service, uint16_t remote_debugging_port);
  ~DevToolsHttpServer() override;

 private:
  class HttpConnectionDelegateImpl;

  // mojo::HttpServerDelegate implementation.
  void OnConnected(
      mojo::HttpConnectionPtr connection,
      mojo::InterfaceRequest<mojo::HttpConnectionDelegate> delegate) override;

  // The following three methods are called by HttpConnectionDelegateImpl.
  using OnReceivedRequestCallback =
      mojo::HttpConnectionDelegate::OnReceivedRequestCallback;
  void OnReceivedRequest(HttpConnectionDelegateImpl* connection,
                         mojo::HttpRequestPtr request,
                         const OnReceivedRequestCallback& callback);
  using OnReceivedWebSocketRequestCallback =
      mojo::HttpConnectionDelegate::OnReceivedWebSocketRequestCallback;
  void OnReceivedWebSocketRequest(
      HttpConnectionDelegateImpl* connection,
      mojo::HttpRequestPtr request,
      const OnReceivedWebSocketRequestCallback& callback);
  void OnConnectionClosed(HttpConnectionDelegateImpl* connection);

  mojo::HttpResponsePtr ProcessJsonRequest(mojo::HttpRequestPtr request);

  // Not owned by this object.
  DevToolsService* const service_;

  const uint16_t remote_debugging_port_;

  scoped_ptr<mojo::Binding<mojo::HttpServerDelegate>>
      http_server_delegate_binding_;

  // Owns the elements.
  std::set<HttpConnectionDelegateImpl*> connections_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsHttpServer);
};

}  // namespace devtools_service

#endif  // COMPONENTS_DEVTOOLS_SERVICE_DEVTOOLS_HTTP_SERVER_H_


text:
Tools for EPsolar Tracer solar charge controller
================================================
[Product link](http://www.epsolarpv.com/en/index.php/Product/pro_content/id/573/am_id/136)
[Windows software & nice pictures](http://gwl-power.tumblr.com/tagged/tracer)

Linux driver for Exar USB UART
------------------------------
In [directory](xr_usb_serial_common-1a) there is a Linux driver for Exar based USB RS-485 adapter.
[Original source](https://www.exar.com/common/content/default.aspx?id=10296)

Protocol
--------
[Protocol](http://www.solar-elektro.cz/data/dokumenty/1733_modbus_protocol.pdf)
See for [windows capture](archive/epsolar.txt) for some extra commands.

Python module
-------------
Uses modbus library (https://github.com/bashwork/pymodbus)
Example output
```
# python info.py
Manufacturer: 'EPsolar Tech co., Ltd'
Model: 'Tracer2215BN'
Version: 'V02.05+V07.12'
Charging equipment rated input voltage = 150.0V
Charging equipment rated input voltage = 150.0V
Charging equipment rated input current = 20.0A
...
```


text:
import django.core.validators
from django.db import migrations, models
import report.models

class Migration(migrations.Migration):

    dependencies = [
        ('report', '0005_auto_20210119_0815'),
    ]

    operations = [
        migrations.CreateModel(
            name='ReportSnippet',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('snippet', models.FileField(help_text='Report snippet file', upload_to=report.models.rename_snippet, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])])),
                ('description', models.CharField(help_text='Snippet file description', max_length=250)),
            ],
        ),
    ]


text:
@implementation FNKHistogramBucketData

-(id) init
{
    if(self == [super init])
    {
        self.data = @(0);
    }

    return self;
}

-(void)addDate:(NSDate*)date
{
    if(self.minDate == nil || [date compare:self.minDate] == NSOrderedAscending)
    {
        self.minDate = date;
    }

    if(self.maxDate == nil || [date compare:self.maxDate] == NSOrderedAscending)
    {
        self.maxDate = date;
    }
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:rep="internal"
    jcr:primaryType="rep:SystemUser"
    jcr:uuid="0cdb16c9-534e-3f02-b307-55083160bb30"
    rep:authorizableId="acs-commons-dispatcher-flush-service"
    rep:principalName="acs-commons-dispatcher-flush-service"/>


text:
<!doctype html>

    <link rel="stylesheet" href="../css/jspsych.css"></link>


text:
'use strict';

var empower = require('..');
var espower = require('espower');
var acorn = require('acorn');
var escodegen = require('escodegen');
var baseAssert = require('assert');
var busterAssertions = require('buster-assertions');

    var weave = function (line) {
        var filepath = '/absolute/path/to/project/test/some_test.js';
        var espowerOptions = {
            source: line,
            path: filepath,
            sourceRoot: '/absolute/path/to/project/',
            destructive: true,
            patterns: [
                'assert(actual, [message])',
                'assert.isNull(object, [message])',
                'assert.same(actual, expected, [message])',
                'assert.near(actual, expected, delta, [message])'
            ]
        };
        var jsAST = acorn.parse(line, {ecmaVersion: 6, locations: true, sourceType: 'module', sourceFile: filepath});
        var espoweredAST = espower(jsAST, espowerOptions);
        return escodegen.generate(espoweredAST, {format: {compact: true}});
    },
    fakeFormatter = function (context) {
        var events = context.args.reduce(function (accum, arg) {
            return accum.concat(arg.events);
        }, []);
        return [
            context.source.filepath,
            context.source.content,
            JSON.stringify(events)
        ].join('\n');
    };

    var assert = empower(busterAssertions.assert, {
        modifyMessageBeforeAssert: function (ev) {
            var message = ev.originalMessage;
            var powerAssertText = fakeFormatter(ev.powerAssertContext);
            return message ? message + ' ' + powerAssertText : powerAssertText;
        },
        patterns: [
            'assert(actual, [message])',
            'assert.isNull(object, [message])',
            'assert.same(actual, expected, [message])',
            'assert.near(actual, expected, delta, [message])'
        ]
    });

    it('buster assertion is also an assert function', function () {
        var falsy = 0;
        try {
            eval(weave('assert(falsy);'));
            baseAssert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.message, [
                'test/some_test.js',
                'assert(falsy)',
                '[{"value":0,"espath":"arguments/0"}]'
            ].join('\n'));
            baseAssert(/^AssertionError/.test(e.name));
        }
    });

    describe('buster assertion with one argument', function () {
        it('isNull method', function () {
            var falsy = 0;
            try {
                eval(weave('assert.isNull(falsy);'));
                baseAssert.ok(false, 'AssertionError should be thrown');
            } catch (e) {
                baseAssert.equal(e.message, [
                    '[assert.isNull] test/some_test.js',
                    'assert.isNull(falsy)',
                    '[{"value":0,"espath":"arguments/0"}]: Expected 0 to be null'
                ].join('\n'));
                baseAssert(/^AssertionError/.test(e.name));
            }
        });
    });

    describe('buster assertion method with two arguments', function () {
        it('both Identifier', function () {
            var foo = 'foo', bar = 'bar';
            try {
                eval(weave('assert.same(foo, bar);'));
                baseAssert.ok(false, 'AssertionError should be thrown');
            } catch (e) {
                baseAssert.equal(e.message, [
                    '[assert.same] test/some_test.js',
                    'assert.same(foo, bar)',
                    '[{"value":"foo","espath":"arguments/0"},{"value":"bar","espath":"arguments/1"}]: foo expected to be the same object as bar'
                ].join('\n'));
                baseAssert(/^AssertionError/.test(e.name));
            }
        });

        it('first argument is Literal', function () {
            var bar = 'bar';
            try {
                eval(weave('assert.same("foo", bar);'));
                baseAssert.ok(false, 'AssertionError should be thrown');
            } catch (e) {
                baseAssert.equal(e.message, [
                    '[assert.same] test/some_test.js',
                    'assert.same("foo", bar)',
                    '[{"value":"bar","espath":"arguments/1"}]: foo expected to be the same object as bar'
                ].join('\n'));
                baseAssert(/^AssertionError/.test(e.name));
            }
        });

        it('second argument is Literal', function () {
            var foo = 'foo';
            try {
                eval(weave('assert.same(foo, "bar");'));
                baseAssert.ok(false, 'AssertionError should be thrown');
            } catch (e) {
                baseAssert.equal(e.message, [
                    '[assert.same] test/some_test.js',
                    'assert.same(foo, "bar")',
                    '[{"value":"foo","espath":"arguments/0"}]: foo expected to be the same object as bar'
                ].join('\n'));
                baseAssert(/^AssertionError/.test(e.name));
            }
        });
    });

    describe('buster assertion method with three arguments', function () {
        it('when every argument is Identifier', function () {
            var actualVal = 10.6, expectedVal = 10, delta = 0.5;
            try {
                eval(weave('assert.near(actualVal, expectedVal, delta);'));
                baseAssert.ok(false, 'AssertionError should be thrown');
            } catch (e) {
                baseAssert.equal(e.message, [
                    '[assert.near] test/some_test.js',
                    'assert.near(actualVal, expectedVal, delta)',
                    '[{"value":10.6,"espath":"arguments/0"},{"value":10,"espath":"arguments/1"},{"value":0.5,"espath":"arguments/2"}]: Expected 10.6 to be equal to 10 +/- 0.5'
                ].join('\n'));
                baseAssert(/^AssertionError/.test(e.name));
            }
        });

        it('optional fourth argument', function () {
            var actualVal = 10.6, expectedVal = 10, delta = 0.5, messageStr = 'not in delta';
            try {
                eval(weave('assert.near(actualVal, expectedVal, delta, messageStr);'));
                baseAssert.ok(false, 'AssertionError should be thrown');
            } catch (e) {
                baseAssert.equal(e.message, [
                    '[assert.near] not in delta test/some_test.js',
                    'assert.near(actualVal, expectedVal, delta, messageStr)',
                    '[{"value":10.6,"espath":"arguments/0"},{"value":10,"espath":"arguments/1"},{"value":0.5,"espath":"arguments/2"}]: Expected 10.6 to be equal to 10 +/- 0.5'
                ].join('\n'));
                baseAssert(/^AssertionError/.test(e.name));
            }
        });
    });


text:
FROM python:3.7

RUN set -ex \
    && apt-get update \
    && apt-get install -y --no-install-recommends dumb-init openssh-server cron \
    && pip3 install --no-cache-dir salt==2019.2.3 pycryptodomex==3.9.7 CherryPy==18.6.0 pyOpenSSL==19.1.0 msgpack==0.6.2 \
    && rm -rf /var/lib/apt/lists/*

RUN set -ex \
    && mkdir -p /etc/pki /etc/salt/pki /etc/salt/minion.d/ /etc/salt/master.d /etc/salt/proxy.d /var/cache/salt /var/log/salt /var/run/salt /run/sshd /root/.ssh

COPY saltinit.py /usr/local/bin/saltinit
ENTRYPOINT ["/usr/bin/dumb-init"]
CMD ["/usr/local/bin/saltinit"]
EXPOSE 22 4505 4506 8000

RUN salt-run salt.cmd tls.create_self_signed_cert


text:
package ClusterHW;

import static org.junit.Assert.*;

import org.junit.Test;

public class Test_DoubleCompare {

	@Test
	public void test() {
		assertEquals(0, DoubleCompare.compare(0, 0, 0));
		assertEquals(1, DoubleCompare.compare(1, 0, 0.5));
		assertEquals(-1, DoubleCompare.compare(-1, 0, 0.01));
	}

}


text:
namespace clang {

namespace LangAS {

/// \brief Defines the set of possible language-specific address spaces.
///
/// This uses a high starting offset so as not to conflict with any address
/// space used by a target.
enum ID {
  Offset = 0x7FFF00,

  opencl_global = Offset,
  opencl_local,
  opencl_constant,
  opencl_generic,

  cuda_device,
  cuda_constant,
  cuda_shared,

  Last,
  Count = Last-Offset
};

/// The type of a lookup table which maps from language-specific address spaces
/// to target-specific ones.
typedef unsigned Map[Count];

}

}

#endif


text:
using DatenMeister.Core.EMOF.Interface.Reflection;

namespace DatenMeister.Core.EMOF.Interface.Identifiers
{
    public interface IExtentCachesObject
    {
        /// <summary>
        /// Returns true, if the object is in the given extent.
        /// This interface can be implemented to speed up access
        /// </summary>
        /// <param name="value">Value to be checked</param>
        /// <returns>true, if object is in</returns>
        bool HasObject(IObject value);
    }
}


text:
using namespace SideCar::GUI::PPIDisplay;

HistorySettings::HistorySettings(BoolSetting* enabled, IntSetting* retentionSize) :
    Super(enabled), retentionSize_(retentionSize)
{
    connect(retentionSize, SIGNAL(valueChanged(int)), SIGNAL(retentionSizeChanged(int)));
}


text:
'use strict';

var $ = require('jquery');
require('./core');
require('./ui.pureview');
var UI = $.AMUI;

function galleryInit() {
  var $gallery = $('[data-am-widget="gallery"]');
  var $galleryOne = $gallery.filter('.am-gallery-one');

  $gallery.each(function() {
    var options = UI.utils.parseOptions($(this).attr('data-am-gallery'));

    if (options.pureview) {
      (typeof options.pureview === 'object') ?
        $(this).pureview(options.pureview) : $(this).pureview();
    }
  });

  $galleryOne.each(function() {
    galleryMore($(this));
  });
}

function galleryMore($elements) {
  var moreData = $('
' +
  '更多 >>
');

  if ($elements.children().length > 6) {
    $elements.children().each(function(index) {
      if (index > 5) {
        $(this).hide();
      }
    });

    $elements.find('.am-gallery-more').remove();
    $elements.append(moreData);
  }

  $elements.find('.am-gallery-more').on('click', function() {
    $elements.children().show();
    $(this).hide();
  });
}

$(function() {
  galleryInit();
});

module.exports = $.AMUI.gallery = {
  VERSION: '2.0.2',
  init: galleryInit
};


text:
import Component from '@glimmer/component';
import {action} from '@ember/object';
import {tracked} from '@glimmer/tracking';

const FILTER_OPTIONS = {
    subscriptionPriceInterval: [
        {label: 'Monthly', name: 'month'},
        {label: 'Yearly', name: 'year'}
    ],
    status: [
        {label: 'Paid', name: 'paid'},
        {label: 'Free', name: 'free'},
        {label: 'Complimentary', name: 'comped'}
    ],
    subscribed: [
        {label: 'Subscribed', name: 'true'},
        {label: 'Unsubscribed', name: 'false'}
    ],
    subscriptionStripeStatus: [
        {label: 'Active', name: 'active'},
        {label: 'Trialing', name: 'trialing'},
        {label: 'Canceled', name: 'canceled'},
        {label: 'Unpaid', name: 'unpaid'},
        {label: 'Past Due', name: 'past_due'},
        {label: 'Incomplete', name: 'incomplete'},
        {label: 'Incomplete - Expired', name: 'incomplete_expired'}
    ]
};

export default class MembersFilterValue extends Component {
    @tracked filterValue;

    constructor(...args) {
        super(...args);
        this.availableFilterOptions = FILTER_OPTIONS;
        this.filterValue = this.args.filter.value;
    }

    get productFilterValue() {
        if (this.args.filter?.type === 'product') {
            const tiers = this.args.filter?.value || [];
            return tiers.map((tier) => {
                return {
                    slug: tier
                };
            });
        }
        return [];
    }

    @action
    setInputFilterValue(filter, event) {
        this.filterValue = event.target.value;
    }

    @action
    updateInputFilterValue(filter, event) {
        if (event.type === 'blur') {
            this.filterValue = event.target.value;
        }
        this.args.setFilterValue(filter, this.filterValue);
    }

    @action
    updateInputFilterValueOnEnter(filter, event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            this.args.setFilterValue(filter, this.filterValue);
        }
    }

    @action
    setLabelsFilterValue(filter, labels) {
        this.args.setFilterValue(filter, labels.map(label => label.slug));
    }

    @action
    setProductsFilterValue(filter, tiers) {
        this.args.setFilterValue(filter, tiers.map(tier => tier.slug));
    }
}


text:
extern std::ostream* sout;

#endif // GLOBALOSTREAM_H


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.ext.spock;

import com.google.common.annotations.VisibleForTesting;
import com.intellij.openapi.util.RecursionManager;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Sergey Evdokimov
 */
public class SpockVariableDescriptor {

  private final String myName;

  private final PsiElement myNavigationElement;

  private final List<GrExpression> myExpressions;
  private List<GrExpression> myExpressionsOfCollection;

  private PsiVariable myVariable;

  public SpockVariableDescriptor(PsiElement navigationElement, String name) {
    myName = name;
    myNavigationElement = navigationElement;
    myExpressions = new ArrayList<>();
  }

  public SpockVariableDescriptor addExpression(@Nullable GrExpression expression) {
    myExpressions.add(expression);
    return this;
  }

  public SpockVariableDescriptor addExpressionOfCollection(@Nullable GrExpression expression) {
    if (myExpressionsOfCollection == null) {
      myExpressionsOfCollection = new ArrayList<>();
    }

    myExpressionsOfCollection.add(expression);
    return this;
  }

  public String getName() {
    return myName;
  }

  public PsiElement getNavigationElement() {
    return myNavigationElement;
  }

  public PsiVariable getVariable() {
    if (myVariable == null) {
      PsiType type = getType();
      myVariable = new SpockVariable(myNavigationElement.getManager(), myName, type, myNavigationElement);
    }
    return myVariable;
  }

  @VisibleForTesting
  @NotNull
  public PsiType getType() {
    PsiManager manager = myNavigationElement.getManager();
    PsiType type = RecursionManager.doPreventingRecursion(this, true, () -> {
      PsiType res = null;

      for (GrExpression expression : myExpressions) {
        if (expression == null) continue;

        res = TypesUtil.getLeastUpperBoundNullable(res, expression.getType(), manager);
      }

      if (myExpressionsOfCollection != null) {
        for (GrExpression expression : myExpressionsOfCollection) {
          if (expression == null) continue;

          PsiType listType = expression.getType();
          PsiType type1 = PsiUtil.extractIterableTypeParameter(listType, true);

          if (type1 == null) {
            if (listType == null) continue;

            if (listType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
              type1 = PsiType.getJavaLangString(expression.getManager(), expression.getResolveScope());
            }
          }

          res = TypesUtil.getLeastUpperBoundNullable(res, type1, manager);
        }
      }

      return res;
    });

    if (type == null) {
      return PsiType.getJavaLangObject(manager, myNavigationElement.getResolveScope());
    }
    else {
      return type;
    }
  }

  private static class SpockVariable extends GrLightVariable {
    SpockVariable(PsiManager manager,
                         @NonNls String name,
                         @NotNull PsiType type,
                         @NotNull PsiElement navigationElement) {
      super(manager, name, type, navigationElement);
    }

    @Override
    public boolean isEquivalentTo(PsiElement another) {
      return super.isEquivalentTo(another)
             || (another instanceof SpockVariable && getNavigationElement() == another.getNavigationElement());
    }
  }

  @Override
  public String toString() {
    return myName;
  }
}


text:
import SmartArgs from './lib/smartArguments.js';
import createSearchFilters from '../lib/createSearchFilters';

export default class Link {
    get config() { return this.linker.linkConfig; }

    get isVirtual() { return this.linker.isVirtual() }

    constructor(linker, object, collection) {
        this.linker = linker;
        this.object = object;
        this.linkedCollection = (collection) ? collection : linker.getLinkedCollection();

        if (this.linker.isVirtual()) {
            this.linkStorageField = this.config.relatedLinker.linkConfig.field;
        } else {
            this.linkStorageField = this.config.field;
        }
    }

    /**
     * Gets the stored link information value
     * @returns {*}
     */
    value() {
        if (this.isVirtual) {
            throw new Meteor.Error('You can only take the value from the main link.');
        }

        return this.object[this.linkStorageField];
    }

    /**
     * Finds linked data.
     *
     * @param filters
     * @param options
     * @returns {*}
     * @param userId
     */
    find(filters = {}, options = {}, userId = undefined) {
        let linker = this.linker;
        const linkedCollection = this.linkedCollection;

        let $metaFilters;
        if (filters.$meta) {
            $metaFilters = filters.$meta;
            delete filters.$meta;
        }

        const searchFilters = createSearchFilters(
            this.object,
            this.linkStorageField,
            linker.strategy,
            linker.isVirtual(),
            $metaFilters
        );

        let appliedFilters = _.extend({}, filters, searchFilters);

        // see https://github.com/cult-of-coders/grapher/issues/134
        // happens due to recursive importing of modules
        // TODO: find another way to do this
        if (linkedCollection.find) {
            return linkedCollection.find(appliedFilters, options, userId)
        } else {
            return linkedCollection.default.find(appliedFilters, options, userId);
        }
    }

    /**
     * @param filters
     * @param options
     * @param others
     * @returns {*|{content}|any}
     */
    fetch(filters, options, ...others) {
        let result = this.find(filters, options, ...others).fetch();

        if (this.linker.isOneResult()) {
            return _.first(result);
        }

        return result;
    }

    /**
     * This is just like fetch() but forces to get an array even if it's single result
     *
     * @param {*} filters
     * @param {*} options
     * @param  {...any} others
     */
    fetchAsArray(filters, options, ...others) {
        return this.find(filters, options, ...others).fetch()
    }

    /**
     * When we are dealing with multiple type relationships, $in would require an array. If the field value is null, it will fail
     * We use clean to make it an empty array by default.
     */
    clean() {}

    /**
     * Extracts a single id
     */
    identifyId(what, saveToDatabase) {
        return SmartArgs.getId(what, {
            saveToDatabase,
            collection: this.linkedCollection
        });
    }

    /**
     * Extracts the ids of object(s) or strings and returns an array.
     */
    identifyIds(what, saveToDatabase) {
        return SmartArgs.getIds(what, {
            saveToDatabase,
            collection: this.linkedCollection
        });
    }

    /**
     * Checks when linking data, if the ids are valid with the linked collection.
     * @throws Meteor.Error
     * @param ids
     *
     * @protected
     */
    _validateIds(ids) {
        if (!_.isArray(ids)) {
            ids = [ids];
        }

        const validIds = this.linkedCollection.find({
            _id: {$in: ids}
        }, {fields: {_id: 1}}).fetch().map(doc => doc._id);

        if (validIds.length != ids.length) {
            throw new Meteor.Error('not-found', `You tried to create links with non-existing id(s) inside "${this.linkedCollection._name}": ${_.difference(ids, validIds).join(', ')}`)
        }
    }

    _checkWhat(what) {
        if (what === undefined || what === null) {
            throw new Error(`The argument passed: ${what} is not accepted.`);
        }
    }

    /**
     * This is for allowing commands such as set/unset/add/remove/metadata from the virtual link.
     *
     * @param action
     * @param what
     * @param metadata
     *
     * @protected
     */
    _virtualAction(action, what, metadata) {
        const linker = this.linker.linkConfig.relatedLinker;

        // its an unset operation most likely.
        if (what === undefined) {
            const reversedLink = linker.createLink(this.fetch());
            reversedLink.unset();

            return;
        }

        if (!_.isArray(what)) {
            what = [what];
        }

        what = _.map(what, element => {
            if (!_.isObject(element)) {
                return linker.mainCollection.findOne(element);
            } else {
                if (!element._id) {
                    const elementId = linker.mainCollection.insert(element);
                    _.extend(element, linker.mainCollection.findOne(elementId));
                }

                return element;
            }
        });

        return _.map(what, element => {
            const reversedLink = linker.createLink(element);

            if (action == 'metadata') {
                if (linker.isSingle()) {
                    return reversedLink.metadata(metadata);
                } else {
                    return reversedLink.metadata(this.object, metadata);
                }
            } else if (action == 'add' || action == 'set') {
                if (linker.isSingle()) {
                    reversedLink.set(this.object, metadata);
                } else {
                    reversedLink.add(this.object, metadata);
                }
            } else {
                if (linker.isSingle()) {
                    reversedLink.unset();
                } else {
                    reversedLink.remove(this.object);
                }
            }
        });
    }
}


text:
package com.buuz135.industrial.utils;

import net.minecraft.block.Blocks;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.ICraftingRecipe;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.IRecipeType;
import net.minecraft.world.World;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CraftingUtils {

    public static Set<ItemStack[]> missingRecipes = new HashSet<>();
    private static HashMap<ItemStack, ItemStack> crushedRecipes = new HashMap<>();
    private static HashMap<ItemStack, ItemStack> cachedRecipes = new HashMap<>();

    public static ItemStack findOutput(int size, ItemStack input, World world) {
        ItemStack cachedStack = input.copy();
        cachedStack.setCount(size * size);
        for (Map.Entry<ItemStack, ItemStack> entry : cachedRecipes.entrySet()) {
            if (entry.getKey().isItemEqual(cachedStack) && entry.getKey().getCount() == cachedStack.getCount()) {
                return entry.getValue().copy();
            }
        }
        CraftingInventory inventoryCrafting = new CraftingInventory(new Container(null, 0) {
            @Override
            public boolean canInteractWith(PlayerEntity playerIn) {
                return false;
            }
        }, size, size);
        for (int i = 0; i < size * size; i++) {
            inventoryCrafting.setInventorySlotContents(i, input.copy());
        }
        ICraftingRecipe recipe = world.getRecipeManager().getRecipe(IRecipeType.CRAFTING, inventoryCrafting, world).orElseGet(null);
        if (recipe != null) {
            ItemStack output = recipe.getRecipeOutput();
            cachedRecipes.put(cachedStack, output.copy());
            return output.copy();
        }
        return ItemStack.EMPTY;
    }

    public static CraftingInventory genCraftingInventory(World world, ItemStack... inputs) {
        CraftingInventory inventoryCrafting = new CraftingInventory(new Container(null, 0) {
            @Override
            public boolean canInteractWith(PlayerEntity playerIn) {
                return false;
            }
        }, 3, 3);
        for (int i = 0; i < 9; ++i) {
            inventoryCrafting.setInventorySlotContents(i, inputs[i]);
        }
        return inventoryCrafting;
    }

    public static IRecipe findRecipe(World world, ItemStack... inputs) {
        for (ItemStack[] missingRecipe : missingRecipes) {
            if (doesStackArrayEquals(missingRecipe, inputs)) return null;
        }
        IRecipe recipe = world.getRecipeManager().getRecipe(IRecipeType.CRAFTING, genCraftingInventory(world, inputs), world).orElseGet(null);
        if (recipe == null) missingRecipes.add(inputs);
        return recipe;
    }

    public static boolean doesStackArrayEquals(ItemStack[] original, ItemStack[] compare) {
        if (original.length != compare.length) return false;
        for (int i = 0; i < original.length; i++) {
            if (original[i].isEmpty() && compare[i].isEmpty()) continue;
            if (!original[i].isItemEqual(compare[i])) return false;
        }
        return true;
    }

    public static ItemStack getCrushOutput(ItemStack stack) {
        for (Map.Entry<ItemStack, ItemStack> entry : crushedRecipes.entrySet()) {
            if (entry.getKey().isItemEqual(stack)) {
                return entry.getValue();
            }
        }
        return ItemStack.EMPTY;
    }

    public static void generateCrushedRecipes() {
        //crushedRecipes.put(new ItemStack(Blocks.STONE), new ItemStack(Blocks.COBBLESTONE));
        crushedRecipes.put(new ItemStack(Blocks.COBBLESTONE), new ItemStack(Blocks.GRAVEL));
        crushedRecipes.put(new ItemStack(Blocks.GRAVEL), new ItemStack(Blocks.SAND));
        ItemStack latest = new ItemStack(Blocks.SAND);

        //if (BlockRegistry.materialStoneWorkFactoryBlock.produceExNihiloDust() && ModList.get().isLoaded("exnihilocreatio")) {
        //    Block dust = Block.REGISTRY.get(new ResourceLocation("exnihilocreatio:block_dust"));
        //    crushedRecipes.put(new ItemStack(Blocks.SAND), latest = new ItemStack(dust));
        //}
        //if (BlockRegistry.materialStoneWorkFactoryBlock.produceSilicon()) {
        //    NonNullList<ItemStack> items = NonNullList.create(); //OreDictionary.getOres("itemSilicon");
        //    if (items.size() > 0) crushedRecipes.put(latest, items.get(0));
        //}TODO
    }
}


text:
/*
 $Id$
 */
#include <stdio.h>
#include <unistd.h>

#ifdef MPI
#include <mpi.h>
#endif
#include "ga.h"
#include "macdecls.h"
/* This makes each process sleep for Mpirank/factor microsec*/
/*#define DEBUG 1*/
void FATR util_mpinap_(Integer *factor)
{
  int myid, sleeptime;
#ifdef MPI
  MPI_Comm_rank(MPI_COMM_WORLD,&myid);
#else
  myid=GA_Nodeid();
#endif
  sleeptime=(myid+1)/((long) *factor);
#ifdef DEBUG
  printf(" %d sleeping for %d usec %d factor \n", myid, sleeptime, (long) *factor);
#endif
  usleep(sleeptime);
}


text:
require 'share-tools/etrade_account'
require 'share-tools/spreadsheet'


text:
"""Create Common Workflow Language (CWL) runnable files and tools from a world object.
"""
import copy
import json
import operator
import os

import toolz as tz
import yaml

from bcbio import utils

def from_world(world, run_info_file):
    base = utils.splitext_plus(os.path.basename(run_info_file))[0]
    out_dir = utils.safe_makedir("%s-workflow" % (base))
    out_file = os.path.join(out_dir, "%s-main.cwl" % (base))
    samples = [xs[0] for xs in world]  # unpack world data objects
    analyses = list(set([x["analysis"] for x in samples]))
    assert len(analyses) == 1, "Currently support writing CWL for a single analysis type"
    if analyses[0].startswith("variant"):
        prep_variant_cwl(samples, out_dir, out_file)
    else:
        raise NotImplementedError("Unsupported CWL analysis type: %s" % analyses[0])

def _standard_bcbio_cwl(samples, inputs):
    """Retrieve CWL inputs shared amongst different workflows.

    ToDo: calculate system requirements (cores/memory) from input configuration.
    """
    return {"class": "Workflow",
            "hints": [{"class": "DockerRequirement",
                       "dockerImport": "bcbio/bcbio",
                       "dockerImageId": "bcbio/bcbio"}],
            "requirements": [{"class": "EnvVarRequirement",
                              "envDef": [{"envName": "MPLCONFIGDIR", "envValue": "."}]},
                             {"class": "ScatterFeatureRequirement"}],
            "inputs": inputs,
            "outputs": [],
            "steps": []}

def _write_tool(step_dir, name, inputs, outputs):
    out_file = os.path.join(step_dir, "%s.cwl" % name)
    out = {"class": "CommandLineTool",
           "baseCommand": ["bcbio_nextgen.py", "runfn", name, "cwl"],
           "inputs": [],
           "outputs": []}
    for i, inp in enumerate(inputs):
        assert inp["type"]["type"] == "array", inp
        inp_tool = copy.deepcopy(inp)
        inp_tool["inputBinding"] = {"prefix": "%s=" % inp["id"].replace("#", ""), "separate": False,
                                     "itemSeparator": ";;", "position": i}
        inp_tool["type"] = inp["type"]["items"]
        out["inputs"].append(inp_tool)
    # XXX Need to generalize outputs, just a hack for now to test align_prep
    for outp in outputs:
        outp_tool = copy.deepcopy(outp)
        outp_tool["type"] = {"type": "array", "items": "File"}
        outp_tool["default"] = None
        outp_tool["outputBinding"] = {"glob": "align_prep/*.gz",
                                      "secondaryFiles": [".gbi"]}
        out["outputs"].append(outp_tool)
    with open(out_file, "w") as out_handle:
        yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
    return os.path.join("steps", os.path.basename(out_file))

def _step_template(name, step_dir, inputs, outputs, source=""):
    """Templating function for writing a step to avoid repeating namespaces.
    """
    outputs = [x for x in inputs if x["id"].endswith(tuple(outputs))]
    step_file = _write_tool(step_dir, name, inputs, outputs)
    inputs = [{"id": "#%s.%s" % (name, inp["id"].replace("#", "")),
               "source": "#" + ("%s." % source if source else "") + inp["id"].replace("#", "")}
              for inp in inputs]
    return {"run": {"import": step_file},
            "id": "#%s" % name,
            "scatterMethod": "dotproduct",
            "scatter": [x["id"] for x in inputs],
            "inputs": inputs,
            "outputs": [{"id": "#%s.%s" % (name, output["id"].replace("#", ""))} for output in outputs]}

def prep_variant_cwl(samples, out_dir, out_file):
    """Output a CWL decription for running a variant calling workflow.
    """
    step_dir = utils.safe_makedir(os.path.join(out_dir, "steps"))
    sample_json, variables = _flatten_samples(samples, out_file)
    out = _standard_bcbio_cwl(samples, variables)
    s1 = _step_template("prep_align_inputs", step_dir, variables, ["files"])
    out["steps"] = [s1]
    with open(out_file, "w") as out_handle:
        yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
    return out_file, sample_json

def _flatten_samples(samples, base_file):
    """Create a flattened JSON representation of data from the bcbio world map.
    """
    out_file = "%s-samples.json" % utils.splitext_plus(base_file)[0]
    flat_data = []
    for data in samples:
        cur_flat = {}
        for key_path in [["description"], ["rgnames"], ["config", "algorithm"], ["metadata"], ["genome_build"],
                         ["files"], ["reference"], ["genome_resources"], ["vrn_file"]]:
            cur_key = "__".join(key_path)
            for flat_key, flat_val in _to_cwldata(cur_key, tz.get_in(key_path, data)):
                cur_flat[flat_key] = flat_val
        flat_data.append(cur_flat)
    out = {}
    for key in sorted(list(set(reduce(operator.add, [d.keys() for d in flat_data])))):
        out[key] = []
        for cur_flat in flat_data:
            out[key].append(cur_flat.get(key))
    with open(out_file, "w") as out_handle:
        json.dump(out, out_handle, sort_keys=True, indent=4, separators=(',', ': '))
        return out_file, _samplejson_to_inputs(out)

def _add_avro_type(inp, val):
    inp["type"] = _get_avro_type(val)
    return inp

def _get_avro_type(val):
    """Infer avro type for the current input.
    """
    if isinstance(val, dict):
        assert val.get("class") == "File"
        return "File"
    elif isinstance(val, (tuple, list)):
        types = []
        for ctype in [_get_avro_type(v) for v in val]:
            if isinstance(ctype, dict):
                nested_types = [x["items"] for x in types if isinstance(x, dict)]
                if ctype["items"] not in nested_types:
                    types.append(ctype)
            elif ctype not in types:
                types.append(ctype)
        return {"type": "array", "items": (types[0] if len(types) == 1 else types)}
    elif val is None:
        return "null"
    else:
        return "string"

def _samplejson_to_inputs(svals):
    """Convert sample output into inputs for CWL configuration files, with types.
    """
    out = []
    for key, val in svals.items():
        out.append(_add_avro_type({"id": "#%s" % key}, val))
    return out

def _to_cwldata(key, val):
    """Convert nested dictionary into CWL data, flatening and marking up files.

    Moves file objects to the top level, enabling insertion in CWL inputs/outputs.
    """
    out = []
    if isinstance(val, dict):
        remain_val = {}
        for nkey, nval in val.items():
            cur_nkey = "%s__%s" % (key, nkey)
            cwl_nval = _item_to_cwldata(nval)
            if isinstance(cwl_nval, dict):
                out.extend(_to_cwldata(cur_nkey, nval))
            elif cwl_nval == nval:
                remain_val[nkey] = nval
            else:
                out.append((cur_nkey, cwl_nval))
        if remain_val:
            out.append((key, json.dumps(remain_val, separators=(',', ':'))))
    else:
        out.append((key, _item_to_cwldata(val)))
    return out

def _item_to_cwldata(x):
    """"Markup an item with CWL specific metadata.
    """
    if isinstance(x, (list, tuple)):
        return [_item_to_cwldata(subx) for subx in x]
    elif x and isinstance(x, basestring) and (os.path.isfile(x) or os.path.isdir(x)) and os.path.exists(x):
        return {"class": "File", "path": x}
    else:
        return x