text:
__author__ = 'algol'

import cherrypy
from jinja2 import Environment, PackageLoader
import memin.core as mc
from configparser import ConfigParser

class Menu:
    def __init__(self):
        self.menu = [
            {'name': 'Главная', 'link': '/'},
            {'name': 'Персоны', 'link': '/persons'},
            {'name': 'Залы', 'link': '/classrooms'},
            {'name': 'Занятия', 'link': '/lessons'},
            {'name': 'Типы платежей', 'link': '/payment_types'}
        ]

class FrontendBase:
    def __init__(self):
        self.env = Environment(loader=PackageLoader('memin', 'templates'))
        self.menu = Menu()

    def get_template(self, template_name='index.html'):
        return self.env.get_template(template_name)

class Main(FrontendBase):

    def __init__(self):
        super().__init__()

    @staticmethod
    def checkPassword(realm, username, password):
        c = ConfigParser()
        c.read('config.ini')
        users = {k: c['users'][k].strip("'") for k in c['users']}
        if password == users.get(username, None):
            return True
        return False

    @cherrypy.expose
    def index(self, name=''):
        return self.get_template('index.html').render(nick=name,
                                                      title='Main page',
                                                      h1='Главная страница',
                                                      menu=self.menu.menu
                                                      )

    @cherrypy.expose
    def halt(self):
        cherrypy.engine.exit()

    @cherrypy.expose
    def persons(self):
        return self.get_template('persons.html').render(
            title='Main page',
            h1='Персоны',
            menu=self.menu.menu,
            table_title='Персоны',
            url_prefix='person',
            ptypes=str({a.pk_value: a.name for a in mc.PaymentType.get_all()}),
            classrooms=str({a.pk_value: a.name for a in mc.Classroom.get_all()}),
            lessons=str({a.pk_value: a.name for a in mc.Lesson.get_all()})
        )

    @cherrypy.expose
    def payment_types(self):
        return self.get_template('payment_types.html').render(
            title='Типы платежей',
            h1='Типы платежей',
            menu=self.menu.menu,
            table_title='Типы платежей',
            url_prefix='ptype'
        )

    @cherrypy.expose
    def classrooms(self):
        return self.get_template('classrooms.html').render(
            title='Залы для занятий',
            h1='Залы для занятий',
            menu=self.menu.menu,
            table_title='список залов',
            url_prefix='classroom'
        )

    @cherrypy.expose
    def lessons(self):
        return self.get_template('lessons.html').render(
            title='Занятия',
            h1='Занятия',
            menu=self.menu.menu,
            table_title='Список занятий',
            url_prefix='lesson'
        )

class MeminCrud(FrontendBase):
    def __init__(self):
        super().__init__()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list(self, **args):
        raise Exception("Not implemented yet")

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def create(self, **args):
        raise Exception("Not implemented yet")

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def update(self, **args):
        raise Exception("Not implemented yet")

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def delete(self, **args):
        raise Exception("Not implemented yet")

class Person(MeminCrud):
    def __init__(self):
        super().__init__()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list(self, **args):
        prs = mc.Person.get_all()
        persons = [{'PersonID': p.pk_value,
                    'Fname': p.fname,
                    'Lname': p.lname,
                    'Phone': p.phone,
                    'Email': p.email,
                    'InsertDate': p.insert_date
                    } for p in prs]
        res = {'Result': 'OK' if prs else 'ERROR', 'Records': persons, 'Args': args}
        return res

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def create(self, **args):
        p = mc.Person(args['Fname'], args['Lname'], args['Phone'], args['Email'])
        args['PersonID'] = p.save()
        return {'Result': 'OK', 'Record': args}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def update(self, **args):
        p = mc.Person.load(args['PersonID'])
        p.fname = args['Fname']
        p.lname = args['Lname']
        p.phone = args['Phone']
        p.email = args['Email']
        p.save()
        return {'Result': 'OK'}

class PaymentType(MeminCrud):
    def __init__(self):
        super().__init__()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list(self, **args):
        ptypes = mc.PaymentType.get_all()
        res = [{'Name': p.name,
                'Comment': p.comment,
                'PaymentTypeID': p.pk_value} for p in ptypes]
        return {'Result': 'OK' if ptypes else 'ERROR', 'Records': res}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def create(self, **args):
        pt = mc.PaymentType(args['Name'], args['Comment'])
        args['PaymenTypeID'] = pt.save()
        return {'Result': 'OK', 'Record': args}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def update(self, **args):
        pt = mc.PaymentType.load(args['PaymentTypeID'])
        pt.name = args['Name']
        pt.comment = args['Comment']
        pt.save()
        return {'Result': 'OK'}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def delete(self, **args):
        raise Exception("Not implemented yet")

class Classroom(MeminCrud):
    def __init__(self):
        super().__init__()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list(self, **args):
        cl = mc.Classroom.get_all()
        res = [{'Name': c.name,
                'Address': c.address,
                'Comment': c.comment,
                'Active': c.active,
                'ClassroomID': c.pk_value} for c in cl]
        return {'Result': 'OK' if cl else 'ERROR', 'Records': res}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def create(self, **args):
        cl = mc.Classroom(args['Name'],
                          args['Address'],
                          args['Comment'],
                          args['Active'] if 'Active' in args else 0
                          )
        args['ClassroomID'] = cl.save()
        return {'Result': 'OK', 'Record': args}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def update(self, **args):
        cl = mc.Classroom.load(args['ClassroomID'])
        cl.comment = args['Comment']
        cl.name = args['Name']
        cl.active = args['Active'] if 'Active' in args else 0
        cl.address = args['Address']
        cl.save()
        return {'Result': 'OK'}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def delete(self, **args):
        raise Exception("Not implemented yet")

class Lesson(MeminCrud):
    def __init__(self):
        super().__init__()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list(self, **args):
        lsns = mc.Lesson.get_all()
        res = [{'Name': l.name,
                'Comment': l.comment,
                'Duration': l.duration,
                'LessonID': l.pk_value
                } for l in lsns]
        return {'Result': 'OK' if lsns else 'ERROR', 'Records': res}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def create(self, **args):
        l = mc.Lesson(args['Name'], args['Duration'], args['Comment'])
        args['LessonID'] = l.save()
        return {'Result': 'OK', 'Record': args}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def update(self, **args):
        l = mc.Lesson.load(args['LessonID'])
        l.name = args['Name']
        l.comment = args['Comment']
        l.duration = args['Duration']
        l.save()
        return {'Result': 'OK'}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def delete(self, **args):
        raise Exception("Not implemented yet")

class Payment(MeminCrud):
    def __init__(self):
        super().__init__()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list(self, **args):
        pl = mc.Payment.get_all({'PersonID': args['PersonID']})
        res = [{'PersonID': p.person_id,
                'PaymentType': p.payment_type_id,
                'PaymentTypeID': p.payment_type_id,
                'PaymentID': p.pk_value,
                'Amount': p.amount,
                'Date': '-'.join(reversed(p.date.split('.')))
                } for p in pl]
        return {'Result': 'OK' if pl else 'ERROR', 'Records': res}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def create(self, **args):
        p = mc.Payment(args['PersonID'], args['Amount'], args['PaymentType'])
        args['PaymentID'] = p.save()
        args['Date'] = p.date
        return {'Result': 'OK', 'Record': args}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def update(self, **args):
        raise Exception("Not implemented yet")

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def delete(self, **args):
        raise Exception("Not implemented yet")

class Visit(MeminCrud):
    def __init__(self):
        super().__init__()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list(self, PersonID, **args):
        visits = mc.Visit.get_all({'PersonID': PersonID})
        res = [{'VisitID': a.pk_value,
                'Classroom': a.classroom_id,
                'Lesson': a.lesson_id,
                'Date': '-'.join(reversed(a.date.split('.')))
                } for a in visits]
        return {'Result': 'OK' if visits else 'ERROR', 'Records': res}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def create(self, **args):
        v = mc.Visit(args['PersonID'], args['Classroom'], args['Lesson'], args['Date'])
        args['VisitID'] = v.save()
        return {'Result': 'OK', 'Record': args}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def update(self, **args):
        v = mc.Visit.load(args.get('VisitID'))
        if v:
            v.classroom_id = args['Classroom']
            v.lesson_id = args['Lesson']
            v.date = args['Date']
            v.save()
            return {'Result': 'OK'}
        return {'Result': 'ERROR'}

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def delete(self, **args):
        raise Exception("Not implemented yet")


text:
from yos.ipc import Catalog
from collections import defaultdict
from threading import RLock
from ypage.nukleon import S

class CatalogHandler(Catalog):

    catalog_lock = RLock()
    catalog_root = defaultdict(dict)

    @staticmethod
    def store(key: str, value: object, catname: str=''):
        with CatalogHandler.catalog_lock:
            CatalogHandler.catalog_root[catname][key] = value

    @staticmethod
    def remove(key: str, value: object, catname: str=''):
        with CatalogHandler.catalog_lock:
            del CatalogHandler.catalog_root[catname][key]
            if len(CatalogHandler.catalog_root[catname]) == 0:
                del CatalogHandler.catalog_root[catname]

    @staticmethod
    def get(key: str, result1: callable, catname: str=''):
        with CatalogHandler.catalog_lock:
            try:
                val = CatalogHandler.catalog_root[catname][key]
            except KeyError:
                S.schedule(S.loc.tcb, result1, Catalog.NotFoundError)
            else:
                S.schedule(S.loc.tcb, result1, val)

    @staticmethod
    def gather(keys, result1: callable, catname: str=''):
        result = {}
        with CatalogHandler.catalog_lock:
            for key in keys:
                try:
                    result[key] = CatalogHandler.catalog_root[catname][key]
                except KeyError:
                   result[key] = Catalog.NotFoundError
        S.schedule(S.loc.tcb, result1, result)

    @staticmethod
    def scatter(kv: dict, catname: str=''):
        with CatalogHandler.catalog_lock:
            CatalogHandler.catalog_root[catname].update(kv)

import yos.ipc
yos.ipc.Catalog = CatalogHandler

redpajama_set_name: RedPajamaGithub


text:
Clazz.declarePackage ("J.adapter.readers.xtal");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader", "JU.List"], "J.adapter.readers.xtal.VaspPoscarReader", ["JU.SB", "J.util.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.atomLabels = null;
this.atomCount = 0;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.xtal, "VaspPoscarReader", J.adapter.smarter.AtomSetCollectionReader);
Clazz.prepareFields (c$, function () {
this.atomLabels =  new JU.List ();
});
$_V(c$, "initializeReader",
function () {
this.readJobTitle ();
this.readUnitCellVectors ();
this.readMolecularFormula ();
this.readCoordinates ();
this.continuing = false;
});
$_M(c$, "readJobTitle",
($fz = function () {
this.atomSetCollection.setAtomSetName (this.readLine ().trim ());
}, $fz.isPrivate = true, $fz));
$_M(c$, "readUnitCellVectors",
($fz = function () {
this.setSpaceGroupName ("P1");
this.setFractionalCoordinates (true);
var scaleFac = this.parseFloatStr (this.readLine ().trim ());
var unitCellData =  Clazz.newFloatArray (9, 0);
this.fillFloatArray (null, 0, unitCellData);
if (scaleFac != 1) for (var i = 0; i < unitCellData.length; i++) unitCellData[i] *= scaleFac;

this.addPrimitiveLatticeVector (0, unitCellData, 0);
this.addPrimitiveLatticeVector (1, unitCellData, 3);
this.addPrimitiveLatticeVector (2, unitCellData, 6);
}, $fz.isPrivate = true, $fz));
$_M(c$, "readMolecularFormula",
($fz = function () {
var elementLabel = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.discardLinesUntilNonBlank ());
var elementCounts = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.readLine ());
var mf =  new JU.SB ();
for (var i = 0; i < elementCounts.length; i++) {
var n = Integer.parseInt (elementCounts[i]);
this.atomCount += n;
var label = elementLabel[i];
mf.append (" ").append (label).appendI (n);
for (var j = n; --j >= 0; ) this.atomLabels.addLast (label);

}
var s = mf.toString ();
J.util.Logger.info ("VaspPoscar reader: " + this.atomCount + " atoms identified for" + s);
this.appendLoadNote (s);
this.atomSetCollection.newAtomSet ();
this.atomSetCollection.setAtomSetName (s);
}, $fz.isPrivate = true, $fz));
$_M(c$, "readCoordinates",
($fz = function () {
if (this.discardLinesUntilNonBlank ().toLowerCase ().contains ("selective")) this.readLine ();
if (this.line.toLowerCase ().contains ("cartesian")) this.setFractionalCoordinates (false);
for (var i = 0; i < this.atomCount; i++) {
var atom = this.atomSetCollection.addNewAtom ();
var tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.readLine ());
atom.atomName = this.atomLabels.get (i);
var x = this.parseFloatStr (tokens[0]);
var y = this.parseFloatStr (tokens[1]);
var z = this.parseFloatStr (tokens[2]);
this.setAtomCoordXYZ (atom, x, y, z);
}
}, $fz.isPrivate = true, $fz));
});


text:
<?php
namespace CodeDocs\Func;

use CodeDocs\Doc\MarkupFunction;

/**
 * Renders a list of the given array.
 */
class RenderList extends MarkupFunction
{
    const FUNC_NAME = 'list';

    /**
     * @param string[]    $of     The list items
     * @param string|null $prefix The list prefix
     *
     * @return string
     */
    public function __invoke(array $of, $prefix = null)
    {
        if ($prefix === null) {
            $prefix = '- ';
        }

        return array_map(
            function ($item) use ($prefix) {
                return $prefix . $item;
            },
            $of
        );
    }
}


text:
.. image:: https://travis-ci.org/josh-t/OpenRange.svg
    :target: https://travis-ci.org/josh-t/OpenRange

.. image:: https://readthedocs.org/projects/openrange/badge/
    :target: https://readthedocs.org/projects/openrange/
    :alt: Documentation Status

OpenRange
=========

**OpenRange** provides a simple interface for building custom range-like
objects for any type that can be represented numerically.

Documentation
=============

See the full documentation: `openrange.readthedocs.org <http://openrange.readthedocs.org/>`_

.. @divider@

Installation
============

**OpenRange** is easy to install using pip.

.. code-block:: bash

    $ pip install openrange

Support
=======

**OpenRange** is tested against:

* python ``2.7``, ``3.2``, ``3.3``, ``3.4``
* ``pypy`` and ``pypy3``

Primary development and testing were for python ``2.7``.

Contribute
==========

Contribution is welcome from those who propose new features, have ideas for improvement, or submit bug fixes. Here's a checklist for contributing to this project:

* Open or respond to an issue to discuss a feature or bug
* Fork the repo on GitHub and start making changes
* Write test(s) for the bug or feature
* Add yourself to **CONTRIBUTORS.rst**
* Send a pull request


text:
package org.mindinformatics.gwt.domeo.plugins.annotation.ddi.model;

public interface Iddi {

	public static final String LABEL = "ddi Annotation";
	//public static final String TYPE = "ao:expertstudyAnnotation";
	public static final String TYPE = "ao:ddiAnnotation";
	public static final String BODY_TYPE = "domeo:ddiUsage";

	public final String SIO_PREFIX = "http://semanticscience.org/resource/";
	public final String RXNORM_PREFIX = "http://purl.bioontology.org/ontology/RXNORM/";
	public final String DIKBD2R_PREFIX = "http://dbmi-icode-01.dbmi.pitt.edu:2020/vocab/resource/";
	public final String NCIT_PREFIX = "http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#";
	public final String PDDI_POC_PREFIX = "http://purl.org/net/nlprepository/pddi#";
	public final String DAILYMED_PREFIX = "http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/";
	public final String MP_PREFIX = "http://purl.org/mp/";

	public final String EX_PREFIX = "http://example.org/";
}


text:
package com.google.common.io;

import java.io.ByteArrayOutputStream;

/**
 * A {@see ByteArrayOutputStream} with an additional method {@link FastByteArrayOutputStream#writeTo(byte[],
 * int)}
 *
 * @author Chris Povirk
 * @author Bernd Hopp
 * @since 20.0
 */
class FastByteArrayOutputStream
        extends ByteArrayOutputStream {
    public FastByteArrayOutputStream(int initByteSize) {
        super(initByteSize);
    }

    /**
     * Writes the contents of the internal buffer to the given array starting at the given offset.
     * Assumes the array has space to hold count bytes.
     */
    void writeTo(byte[] b, int off) {
        System.arraycopy(buf, 0, b, off, count);
    }
}


text:
(function(ionic) {
'use strict';

  /**
   * The side menu view handles one of the side menu's in a Side Menu Controller
   * configuration.
   * It takes a DOM reference to that side menu element.
   */
  ionic.views.SideMenu = ionic.views.View.inherit({
    initialize: function(opts) {
      this.el = opts.el;
      this.width = opts.width;
      this.isEnabled = opts.isEnabled || true;
    },

    getFullWidth: function() {
      return this.width;
    },
    setIsEnabled: function(isEnabled) {
      this.isEnabled = isEnabled;
    },
    bringUp: function() {
      this.el.style.zIndex = 0;
    },
    pushDown: function() {
      this.el.style.zIndex = -1;
    }
  });

  ionic.views.SideMenuContent = ionic.views.View.inherit({
    initialize: function(opts) {
      var _this = this;

      ionic.extend(this, {
        animationClass: 'menu-animated',
        onDrag: function(e) {},
        onEndDrag: function(e) {},
      }, opts);

      ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el);
      ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el);
    },
    _onDrag: function(e) {
      this.onDrag && this.onDrag(e);
    },
    _onEndDrag: function(e) {
      this.onEndDrag && this.onEndDrag(e);
    },
    disableAnimation: function() {
      this.el.classList.remove(this.animationClass);
    },
    enableAnimation: function() {
      this.el.classList.add(this.animationClass);
    },
    getTranslateX: function() {
      return parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[0]);
    },
    setTranslateX: function(x) {
      this.el.style.webkitTransform = 'translate3d(' + x + 'px, 0, 0)';
    }
  });

})(ionic);


text:
package vpp2005

import (
	"fmt"
	"net"

	govppapi "git.fd.io/govpp.git/api"
	"go.ligato.io/cn-infra/v2/logging"
	"go.ligato.io/cn-infra/v2/logging/logrus"

	corevppcalls "go.ligato.io/vpp-agent/v3/plugins/govppmux/vppcalls"
	vpe_vpp2005 "go.ligato.io/vpp-agent/v3/plugins/govppmux/vppcalls/vpp2005"
	"go.ligato.io/vpp-agent/v3/plugins/netalloc"
	"go.ligato.io/vpp-agent/v3/plugins/vpp"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2005"
	vpp_dhcp "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2005/dhcp"
	vpp_ip "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2005/ip"
	vpp_ip_neighbor "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2005/ip_neighbor"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2005/ip_types"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2005/l3xc"
	vpp_vpe "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2005/vpe"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/ifaceidx"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vrfidx"
)

func init() {
	var msgs []govppapi.Message
	msgs = append(msgs, vpp_ip.AllMessages()...)
	msgs = append(msgs, vpp_ip_neighbor.AllMessages()...)
	msgs = append(msgs, vpp_vpe.AllMessages()...)
	msgs = append(msgs, vpp_dhcp.AllMessages()...)

	vppcalls.AddHandlerVersion(vpp2005.Version, msgs, NewL3VppHandler)
}

type L3VppHandler struct {
	*ArpVppHandler
	*ProxyArpVppHandler
	*RouteHandler
	*IPNeighHandler
	*VrfTableHandler
	*DHCPProxyHandler
	*L3XCHandler
	*TeibHandler
	*VrrpVppHandler
}

func NewL3VppHandler(
	c vpp.Client,
	ifIdx ifaceidx.IfaceMetadataIndex,
	vrfIdx vrfidx.VRFMetadataIndex,
	addrAlloc netalloc.AddressAllocator,
	log logging.Logger,
) vppcalls.L3VppAPI {
	ch, err := c.NewAPIChannel()
	if err != nil {
		logging.Warnf("creating channel failed: %v", err)
		return nil
	}
	return &L3VppHandler{
		ArpVppHandler:      NewArpVppHandler(ch, ifIdx, log),
		ProxyArpVppHandler: NewProxyArpVppHandler(ch, ifIdx, log),
		RouteHandler:       NewRouteVppHandler(ch, ifIdx, vrfIdx, addrAlloc, log),
		IPNeighHandler:     NewIPNeighVppHandler(c, ch, log),
		VrfTableHandler:    NewVrfTableVppHandler(ch, log),
		DHCPProxyHandler:   NewDHCPProxyHandler(ch, log),
		L3XCHandler:        NewL3XCHandler(c, ifIdx, log),
		TeibHandler:        NewTeibVppHandler(ch, ifIdx, log),
		VrrpVppHandler:     NewVrrpVppHandler(ch, ifIdx, log),
	}
}

// ArpVppHandler is accessor for ARP-related vppcalls methods
type ArpVppHandler struct {
	callsChannel govppapi.Channel
	ifIndexes    ifaceidx.IfaceMetadataIndex
	log          logging.Logger
}

// DHCPProxyHandler is accessor for DHCP proxy-related vppcalls methods
type DHCPProxyHandler struct {
	callsChannel govppapi.Channel
	log          logging.Logger
}

// ProxyArpVppHandler is accessor for proxy ARP-related vppcalls methods
type ProxyArpVppHandler struct {
	callsChannel govppapi.Channel
	ifIndexes    ifaceidx.IfaceMetadataIndex
	log          logging.Logger
}

// RouteHandler is accessor for route-related vppcalls methods
type RouteHandler struct {
	callsChannel govppapi.Channel
	ifIndexes    ifaceidx.IfaceMetadataIndex
	vrfIndexes   vrfidx.VRFMetadataIndex
	addrAlloc    netalloc.AddressAllocator
	log          logging.Logger
}

// IPNeighHandler is accessor for ip-neighbor-related vppcalls methods
type IPNeighHandler struct {
	callsChannel govppapi.Channel
	log          logging.Logger
	corevppcalls.VppCoreAPI
}

// VrfTableHandler is accessor for vrf-related vppcalls methods
type VrfTableHandler struct {
	callsChannel govppapi.Channel
	log          logging.Logger
}

// TeibHandler is accessor for TEIB-related vppcalls methods
type TeibHandler struct {
	callsChannel govppapi.Channel
	ifIndexes    ifaceidx.IfaceMetadataIndex
	log          logging.Logger
}

// VrrpVppHandler is accessor for TEIB-related vppcalls methods
type VrrpVppHandler struct {
	callsChannel govppapi.Channel
	ifIndexes    ifaceidx.IfaceMetadataIndex
	log          logging.Logger
}

// NewArpVppHandler creates new instance of IPsec vppcalls handler
func NewArpVppHandler(callsChan govppapi.Channel, ifIndexes ifaceidx.IfaceMetadataIndex, log logging.Logger) *ArpVppHandler {
	if log == nil {
		log = logrus.NewLogger("arp-handler")
	}
	return &ArpVppHandler{
		callsChannel: callsChan,
		ifIndexes:    ifIndexes,
		log:          log,
	}
}

// NewProxyArpVppHandler creates new instance of proxy ARP vppcalls handler
func NewProxyArpVppHandler(callsChan govppapi.Channel, ifIndexes ifaceidx.IfaceMetadataIndex, log logging.Logger) *ProxyArpVppHandler {
	if log == nil {
		log = logrus.NewLogger("proxy-arp-handler")
	}
	return &ProxyArpVppHandler{
		callsChannel: callsChan,
		ifIndexes:    ifIndexes,
		log:          log,
	}
}

// NewRouteVppHandler creates new instance of route vppcalls handler
func NewRouteVppHandler(callsChan govppapi.Channel, ifIndexes ifaceidx.IfaceMetadataIndex,
	vrfIdx vrfidx.VRFMetadataIndex, addrAlloc netalloc.AddressAllocator, log logging.Logger) *RouteHandler {
	if log == nil {
		log = logrus.NewLogger("route-handler")
	}
	return &RouteHandler{
		callsChannel: callsChan,
		ifIndexes:    ifIndexes,
		vrfIndexes:   vrfIdx,
		addrAlloc:    addrAlloc,
		log:          log,
	}
}

// NewIPNeighVppHandler creates new instance of ip neighbor vppcalls handler
func NewIPNeighVppHandler(c vpp.Client, callsChan govppapi.Channel, log logging.Logger) *IPNeighHandler {
	if log == nil {
		log = logrus.NewLogger("ip-neigh")
	}
	return &IPNeighHandler{
		callsChannel: callsChan,
		log:          log,
		VppCoreAPI:   vpe_vpp2005.NewVpeHandler(c),
	}
}

// NewVrfTableVppHandler creates new instance of vrf-table vppcalls handler
func NewVrfTableVppHandler(callsChan govppapi.Channel, log logging.Logger) *VrfTableHandler {
	if log == nil {
		log = logrus.NewLogger("vrf-table-handler")
	}
	return &VrfTableHandler{
		callsChannel: callsChan,
		log:          log,
	}
}

// NewDHCPProxyHandler creates new instance of vrf-table vppcalls handler
func NewDHCPProxyHandler(callsChan govppapi.Channel, log logging.Logger) *DHCPProxyHandler {
	if log == nil {
		log = logrus.NewLogger("dhcp-proxy-handler")
	}
	return &DHCPProxyHandler{
		callsChannel: callsChan,
		log:          log,
	}
}

// NewTeibVppHandler creates new instance of TEIB vppcalls handler
func NewTeibVppHandler(callsChan govppapi.Channel, ifIndexes ifaceidx.IfaceMetadataIndex, log logging.Logger) *TeibHandler {
	if log == nil {
		log = logrus.NewLogger("teib-handler")
	}
	return &TeibHandler{
		callsChannel: callsChan,
		ifIndexes:    ifIndexes,
		log:          log,
	}
}

type L3XCHandler struct {
	l3xc      l3xc.RPCService
	ifIndexes ifaceidx.IfaceMetadataIndex
	log       logging.Logger
}

// NewL3XCHandler creates new instance of L3XC vppcalls handler
func NewL3XCHandler(c vpp.Client, ifIndexes ifaceidx.IfaceMetadataIndex, log logging.Logger) *L3XCHandler {
	if log == nil {
		log = logrus.NewLogger("l3xc-handler")
	}
	h := &L3XCHandler{
		ifIndexes: ifIndexes,
		log:       log,
	}
	if c.IsPluginLoaded(l3xc.APIFile) {
		h.l3xc = l3xc.NewServiceClient(c)
	}
	return h
}

// NewVrrpVppHandler creates new instance of VRRP handler
func NewVrrpVppHandler(callsChan govppapi.Channel, ifIndexes ifaceidx.IfaceMetadataIndex, log logging.Logger) *VrrpVppHandler {
	if log == nil {
		log = logrus.NewLogger("vrrp-handler")
	}
	return &VrrpVppHandler{
		callsChannel: callsChan,
		ifIndexes:    ifIndexes,
		log:          log,
	}
}

func ipToAddress(ipstr string) (addr ip_types.Address, err error) {
	netIP := net.ParseIP(ipstr)
	if netIP == nil {
		return ip_types.Address{}, fmt.Errorf("invalid IP: %q", ipstr)
	}
	if ip4 := netIP.To4(); ip4 == nil {
		addr.Af = ip_types.ADDRESS_IP6
		var ip6addr ip_types.IP6Address
		copy(ip6addr[:], netIP.To16())
		addr.Un.SetIP6(ip6addr)
	} else {
		addr.Af = ip_types.ADDRESS_IP4
		var ip4addr ip_types.IP4Address
		copy(ip4addr[:], ip4)
		addr.Un.SetIP4(ip4addr)
	}
	return
}

func networkToPrefix(dstNetwork *net.IPNet) ip_types.Prefix {
	var addr ip_types.Address
	if dstNetwork.IP.To4() == nil {
		addr.Af = ip_types.ADDRESS_IP6
		var ip6addr ip_types.IP6Address
		copy(ip6addr[:], dstNetwork.IP.To16())
		addr.Un.SetIP6(ip6addr)
	} else {
		addr.Af = ip_types.ADDRESS_IP4
		var ip4addr ip_types.IP4Address
		copy(ip4addr[:], dstNetwork.IP.To4())
		addr.Un.SetIP4(ip4addr)
	}
	mask, _ := dstNetwork.Mask.Size()
	return ip_types.Prefix{
		Address: addr,
		Len:     uint8(mask),
	}
}

func uintToBool(value uint8) bool {
	if value == 0 {
		return false
	}
	return true
}

func boolToUint(input bool) uint8 {
	if input {
		return 1
	}
	return 0
}


text:
    function sendPass() {
    	pleasewait();
    	var email = dwr.util.getValue("email");
    	password.sendPassword(email, function(data) {

    		dwr.util.setValue("alerts", data);
    	});
    }


text:
package com.twitter.finagle.redis.protocol

import com.twitter.finagle.netty3.ChannelBufferBuf
import com.twitter.finagle.redis.util._
import com.twitter.io.Buf
import org.jboss.netty.buffer.ChannelBuffer

case object FlushAll extends Command {
  def command = Commands.FLUSHALL
  val toChannelBuffer = RedisCodec.toUnifiedFormat(Seq(CommandBytes.FLUSHALL))
}

case object FlushDB extends Command {
  def command = Commands.FLUSHDB
  val toChannelBuffer = RedisCodec.toUnifiedFormat(Seq(CommandBytes.FLUSHDB))
}

case class Select(index: Int) extends Command {
  def command = Commands.SELECT
  def toChannelBuffer = RedisCodec.toUnifiedFormat(Seq(CommandBytes.SELECT,
    StringToChannelBuffer(index.toString)))
}

case class Auth(code: Buf) extends Command {
  def command = Commands.AUTH
  def toChannelBuffer =
    RedisCodec.toUnifiedFormat(Seq(CommandBytes.AUTH, ChannelBufferBuf.Owned.extract(code)))
}

case class Info(section: Buf) extends Command {
  def command = Commands.INFO
  def toChannelBuffer = RedisCodec.toUnifiedFormat(
    section match {
      case Buf.Empty => Seq(CommandBytes.INFO)
      case _ => Seq(CommandBytes.INFO, ChannelBufferBuf.Owned.extract(section))
    }
  )
}

case object Ping extends Command {
  def command = Commands.PING
  val toChannelBuffer = RedisCodec.toUnifiedFormat(Seq(CommandBytes.PING))
}

case object Quit extends Command {
  def command = Commands.QUIT
  val toChannelBuffer = RedisCodec.toUnifiedFormat(Seq(CommandBytes.QUIT))
}

case class ConfigSet(
    param: ChannelBuffer,
    value: ChannelBuffer)
  extends Config(StringToChannelBuffer("SET"), Seq(param, value))

case class ConfigGet(param: ChannelBuffer) extends Config(StringToChannelBuffer("GET"), Seq(param))

case class ConfigResetStat() extends Config(StringToChannelBuffer("RESETSTAT"), Seq.empty)

abstract class Config(sub: ChannelBuffer, args: Seq[ChannelBuffer]) extends Command {
  def command = Commands.CONFIG
  def toChannelBuffer = RedisCodec.toUnifiedFormat(Seq(CommandBytes.CONFIG, sub) ++ args)
}

case class SlaveOf(host: Buf, port: Buf) extends Command {
  def command = Commands.SLAVEOF
  def toChannelBuffer = RedisCodec.bufToUnifiedChannelBuffer(Seq(CommandBytes.SLAVEOF, host, port))
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mygoproremote"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="16" />

    <permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.INTERNET" />

    <permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:name="com.mygoproremote.GlobalClass"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".FullscreenActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".PreviewActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_preview"
            android:theme="@style/AppTheme" >
        </activity>
        <activity
            android:name=".GoproNotFound"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_preview"
            android:theme="@style/AppTheme" >
        </activity>
        <activity
            android:name=".GlobalClass"
            android:label="@string/title_activity_global_class" >
        </activity>
    </application>

</manifest>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

using BitMiracle.LibJpeg.Classic;

namespace BitMiracle.LibJpeg
{
    class BitmapDestination : IDecompressDestination
    {
        /* Target file spec; filled in by djpeg.c after object is created. */
        private Stream m_output;

        private byte[][] m_pixels;

        private int m_rowWidth;       /* physical width of one row in the BMP file */

        private int m_currentRow;  /* next row# to write to virtual array */
        private LoadedImageAttributes m_parameters;

        public BitmapDestination(Stream output)
        {
            m_output = output;
        }

        public Stream Output
        {
            get
            {
                return m_output;
            }
        }

        public void SetImageAttributes(LoadedImageAttributes parameters)
        {
            if (parameters == null)
                throw new ArgumentNullException("parameters");

            m_parameters = parameters;
        }

        /// <summary>
        /// Startup: normally writes the file header.
        /// In this module we may as well postpone everything until finish_output.
        /// </summary>
        public void BeginWrite()
        {
            //Determine width of rows in the BMP file (padded to 4-byte boundary).
            m_rowWidth = m_parameters.Width * m_parameters.Components;
            while (m_rowWidth % 4 != 0)
                m_rowWidth++;

            m_pixels = new byte[m_rowWidth][];
            for (int i = 0; i < m_rowWidth; i++)
                m_pixels[i] = new byte[m_parameters.Height];

            m_currentRow = 0;
        }

        /// <summary>
        /// Write some pixel data.
        /// </summary>
        public void ProcessPixelsRow(byte[] row)
        {
            if (m_parameters.Colorspace == Colorspace.Grayscale || m_parameters.QuantizeColors)
            {
                putGrayRow(row);
            }
            else
            {
                if (m_parameters.Colorspace == Colorspace.CMYK)
                    putCmykRow(row);
                else
                    putRgbRow(row);
            }

            ++m_currentRow;
        }

        /// <summary>
        /// Finish up at the end of the file.
        /// Here is where we really output the BMP file.
        /// </summary>
        public void EndWrite()
        {
            writeHeader();
            writePixels();

            /* Make sure we wrote the output file OK */
            m_output.Flush();
        }

        /// <summary>
        /// This version is for grayscale OR quantized color output
        /// </summary>
        private void putGrayRow(byte[] row)
        {
            for (int i = 0; i < m_parameters.Width; ++i)
                m_pixels[i][m_currentRow] = row[i];
        }

        /// <summary>
        /// This version is for writing 24-bit pixels
        /// </summary>
        private void putRgbRow(byte[] row)
        {
            /* Transfer data.  Note destination values must be in BGR order
             * (even though Microsoft's own documents say the opposite).
             */
            for (int i = 0; i < m_parameters.Width; ++i)
            {
                int firstComponent = i * 3;
                byte red = row[firstComponent];
                byte green = row[firstComponent + 1];
                byte blue = row[firstComponent + 2];
                m_pixels[firstComponent][m_currentRow] = blue;
                m_pixels[firstComponent + 1][m_currentRow] = green;
                m_pixels[firstComponent + 2][m_currentRow] = red;
            }
        }

        /// <summary>
        /// This version is for writing 24-bit pixels
        /// </summary>
        private void putCmykRow(byte[] row)
        {
            /* Transfer data.  Note destination values must be in BGR order
             * (even though Microsoft's own documents say the opposite).
             */
            for (int i = 0; i < m_parameters.Width; ++i)
            {
                int firstComponent = i * 4;
                m_pixels[firstComponent][m_currentRow] = row[firstComponent + 2];
                m_pixels[firstComponent + 1][m_currentRow] = row[firstComponent + 1];
                m_pixels[firstComponent + 2][m_currentRow] = row[firstComponent + 0];
                m_pixels[firstComponent + 3][m_currentRow] = row[firstComponent + 3];
            }
        }

        /// <summary>
        /// Write a Windows-style BMP file header, including colormap if needed
        /// </summary>
        private void writeHeader()
        {
            int bits_per_pixel;
            int cmap_entries;

            /* Compute colormap size and total file size */
            if (m_parameters.Colorspace == Colorspace.Grayscale || m_parameters.QuantizeColors)
            {
                bits_per_pixel = 8;
                cmap_entries = 256;
            }
            else
            {
                cmap_entries = 0;

                if (m_parameters.Colorspace == Colorspace.RGB)
                    bits_per_pixel = 24;
                else if (m_parameters.Colorspace == Colorspace.CMYK)
                    bits_per_pixel = 32;
                else
                    throw new InvalidOperationException();
            }

            byte[] infoHeader = null;
            if (m_parameters.Colorspace == Colorspace.RGB)
                infoHeader = createBitmapInfoHeader(bits_per_pixel, cmap_entries);
            else
                infoHeader = createBitmapV4InfoHeader(bits_per_pixel);

            /* File size */
            const int fileHeaderSize = 14;
            int infoHeaderSize = infoHeader.Length;
            int paletteSize = cmap_entries * 4;
            int offsetToPixels = fileHeaderSize + infoHeaderSize + paletteSize; /* Header and colormap */
            int fileSize = offsetToPixels + m_rowWidth * m_parameters.Height;

            byte[] fileHeader = createBitmapFileHeader(offsetToPixels, fileSize);

            m_output.Write(fileHeader, 0, fileHeader.Length);
            m_output.Write(infoHeader, 0, infoHeader.Length);

            if (cmap_entries > 0)
                writeColormap(cmap_entries, 4);
        }

        private static byte[] createBitmapFileHeader(int offsetToPixels, int fileSize)
        {
            byte[] bmpfileheader = new byte[14];
            bmpfileheader[0] = 0x42;    /* first 2 bytes are ASCII 'B', 'M' */
            bmpfileheader[1] = 0x4D;
            PUT_4B(bmpfileheader, 2, fileSize);
            /* we leave bfReserved1 & bfReserved2 = 0 */
            PUT_4B(bmpfileheader, 10, offsetToPixels); /* bfOffBits */
            return bmpfileheader;
        }

        private byte[] createBitmapInfoHeader(int bits_per_pixel, int cmap_entries)
        {
            byte[] bmpinfoheader = new byte[40];
            fillBitmapInfoHeader(bits_per_pixel, cmap_entries, bmpinfoheader);
            return bmpinfoheader;
        }

        private void fillBitmapInfoHeader(int bitsPerPixel, int cmap_entries, byte[] infoHeader)
        {
            /* Fill the info header (Microsoft calls this a BITMAPINFOHEADER) */
            PUT_2B(infoHeader, 0, infoHeader.Length);   /* biSize */
            PUT_4B(infoHeader, 4, m_parameters.Width); /* biWidth */
            PUT_4B(infoHeader, 8, m_parameters.Height); /* biHeight */
            PUT_2B(infoHeader, 12, 1);   /* biPlanes - must be 1 */
            PUT_2B(infoHeader, 14, bitsPerPixel); /* biBitCount */
            /* we leave biCompression = 0, for none */
            /* we leave biSizeImage = 0; this is correct for uncompressed data */

            if (m_parameters.DensityUnit == DensityUnit.DotsCm)
            {
                /* if have density in dots/cm, then */
                PUT_4B(infoHeader, 24, m_parameters.DensityX * 100); /* XPels/M */
                PUT_4B(infoHeader, 28, m_parameters.DensityY * 100); /* XPels/M */
            }
            PUT_2B(infoHeader, 32, cmap_entries); /* biClrUsed */
            /* we leave biClrImportant = 0 */
        }

        private byte[] createBitmapV4InfoHeader(int bitsPerPixel)
        {
            byte[] infoHeader = new byte[40 + 68];
            fillBitmapInfoHeader(bitsPerPixel, 0, infoHeader);

            PUT_4B(infoHeader, 56, 0x02); /* CSType == 0x02 (CMYK) */

            return infoHeader;
        }

        /// <summary>
        /// Write the colormap.
        /// Windows uses BGR0 map entries; OS/2 uses BGR entries.
        /// </summary>
        private void writeColormap(int map_colors, int map_entry_size)
        {
            byte[][] colormap = m_parameters.Colormap;
            int num_colors = m_parameters.ActualNumberOfColors;

            int i = 0;
            if (colormap != null)
            {
                if (m_parameters.ComponentsPerSample == 3)
                {
                    /* Normal case with RGB colormap */
                    for (i = 0; i < num_colors; i++)
                    {
                        m_output.WriteByte(colormap[2][i]);
                        m_output.WriteByte(colormap[1][i]);
                        m_output.WriteByte(colormap[0][i]);
                        if (map_entry_size == 4)
                            m_output.WriteByte(0);
                    }
                }
                else
                {
                    /* Grayscale colormap (only happens with grayscale quantization) */
                    for (i = 0; i < num_colors; i++)
                    {
                        m_output.WriteByte(colormap[0][i]);
                        m_output.WriteByte(colormap[0][i]);
                        m_output.WriteByte(colormap[0][i]);
                        if (map_entry_size == 4)
                            m_output.WriteByte(0);
                    }
                }
            }
            else
            {
                /* If no colormap, must be grayscale data.  Generate a linear "map". */
                for (i = 0; i < 256; i++)
                {
                    m_output.WriteByte((byte)i);
                    m_output.WriteByte((byte)i);
                    m_output.WriteByte((byte)i);
                    if (map_entry_size == 4)
                        m_output.WriteByte(0);
                }
            }

            /* Pad colormap with zeros to ensure specified number of colormap entries */
            if (i > map_colors)
                throw new InvalidOperationException("Too many colors");

            for (; i < map_colors; i++)
            {
                m_output.WriteByte(0);
                m_output.WriteByte(0);
                m_output.WriteByte(0);
                if (map_entry_size == 4)
                    m_output.WriteByte(0);
            }
        }

        private void writePixels()
        {
            for (int row = m_parameters.Height - 1; row >= 0; --row)
                for (int col = 0; col < m_rowWidth; ++col)
                    m_output.WriteByte(m_pixels[col][row]);
        }

        private static void PUT_2B(byte[] array, int offset, int value)
        {
            array[offset] = (byte)((value) & 0xFF);
            array[offset + 1] = (byte)(((value) >> 8) & 0xFF);
        }

        private static void PUT_4B(byte[] array, int offset, int value)
        {
            array[offset] = (byte)((value) & 0xFF);
            array[offset + 1] = (byte)(((value) >> 8) & 0xFF);
            array[offset + 2] = (byte)(((value) >> 16) & 0xFF);
            array[offset + 3] = (byte)(((value) >> 24) & 0xFF);
        }
    }
}


text:
package main

import "fmt"

func main() {

	g := Group{
		"Accounting",
		[]string{"Jane", "Bob", "Pat"},
	}

	fmt.Println(g)
	// OUTPUT:
	// {Accounting [Jane Bob Pat]}

}

type Group struct {
	title   string
	members []string
}


text:
require 'httparty'

module InPay
  class CaseNormalizer
    def self.call(query)
      query = Hash[query.map { |k, v| [camelize(k), v] }]
      HTTParty::HashConversions.to_params query
    end

    def self.camelize(key)
      capitalize = lambda { |w, i| i == 0 ? w : w.capitalize }
      key.to_s.split('_').map.with_index(&capitalize).join
    end
  end
end


text:
describe("less.js browser test - relative url's", function() {
    testLessEqualsInDocument();
});


text:
import json
import unittest
from urllib.parse import *
from urllib.request import urlopen
from urllib.error import *

from config import API_ROOT
from utils import RestTestCase

class TestBaseUser(RestTestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_01_creation(self):

        response = urlopen(API_ROOT+'/create/user_01')

        # 响应码应当为 200
        self.assertEqual(response.status, 200)

        headers = response.getheaders()
        content = response.read().decode()
        result = json.loads(content)

        # 1. 用户创建的结果
        # 1.1. 返回用户名称正确
        self.assertEqual(result['username'], 'user_01')
        # 1.2. 新建用户的状态应该为正常(1)
        self.assertEqual(result['status'], 1)
        # 1.3. 返回数据的字段包含如下
        self.assertSetEqual(
            set(result.keys()),
            {'username', 'password', 'status', 'remark'}
        )

    def test_02_duplicate_user_creation(self):

        # 2. 再次创建应该要卡住,因为用户名重复
        with self.assertRaises(HTTPError):
            response = urlopen(API_ROOT+'/create/user_01')


text:
package org.bitcoinj.core;

@SuppressWarnings("serial")
public class AddressFormatException extends Exception {
    public AddressFormatException() {
        super();
    }

    public AddressFormatException(String message) {
        super(message);
    }
}


text:
'use strict';

var watch = require('./watch');

var zkflowWatcher = {
  watch: watch
};

module.exports = zkflowWatcher;


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.CosmosDB.Models
{
    internal partial class ContinuousBackupInformation
    {
        internal static ContinuousBackupInformation DeserializeContinuousBackupInformation(JsonElement element)
        {
            Optional<DateTimeOffset> latestRestorableTimestamp = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("latestRestorableTimestamp"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    latestRestorableTimestamp = property.Value.GetDateTimeOffset("O");
                    continue;
                }
            }
            return new ContinuousBackupInformation(Optional.ToNullable(latestRestorableTimestamp));
        }
    }
}


text:
package edu.mayo.cts2.framework.webapp.soap.directoryuri;

import java.io.Serializable;
import java.util.Set;

import edu.mayo.cts2.framework.model.core.types.SetOperator;
import edu.mayo.cts2.framework.model.service.core.FilterComponent;

public interface SoapDirectoryUri<T> extends Serializable {

	public Set<FilterComponent> getFilterComponents();

	public T getRestrictions();

	public SetOperation<T> getSetOperation();

	public static class SetOperation<T> implements Serializable {

		private static final long serialVersionUID = -6445696738700141690L;

		private SetOperator setOperator;
		private SoapDirectoryUri<T> soapDirectoryUri1;
		private SoapDirectoryUri<T> soapDirectoryUri2;
		public SetOperator getSetOperator() {
			return setOperator;
		}
		public void setSetOperator(SetOperator setOperator) {
			this.setOperator = setOperator;
		}
		public SoapDirectoryUri<T> getSoapDirectoryUri1() {
			return soapDirectoryUri1;
		}
		public void setSoapDirectoryUri1(SoapDirectoryUri<T> soapDirectoryUri1) {
			this.soapDirectoryUri1 = soapDirectoryUri1;
		}
		public SoapDirectoryUri<T> getSoapDirectoryUri2() {
			return soapDirectoryUri2;
		}
		public void setSoapDirectoryUri2(SoapDirectoryUri<T> soapDirectoryUri2) {
			this.soapDirectoryUri2 = soapDirectoryUri2;
		}
	}
}


text:
package models

import (
	"testing"

	envmanModels "github.com/bitrise-io/envman/models"
	"github.com/bitrise-io/go-utils/pointers"
)

const (
	testKey    = "test_key"
	testValue  = "test_value"
	testKey1   = "test_key1"
	testValue1 = "test_value1"
	testKey2   = "test_key2"
	testValue2 = "test_value2"

	title   = "name 1"
	desc    = "desc 1"
	website = "web/1"
	git     = "https://git.url"
	fork    = "fork/1"

	testTitle       = "test_title"
	testDescription = "test_description"
	testTrue        = true
	testFalse       = false
)

var (
	testValueOptions = []string{testKey2, testValue2}
)

func TestValidateStep(t *testing.T) {
	step := StepModel{
		Title:   pointers.NewStringPtr("title"),
		Summary: pointers.NewStringPtr("summary"),
		Website: pointers.NewStringPtr("website"),
		Source: StepSourceModel{
			Git:    "https://github.com/bitrise-io/bitrise.git",
			Commit: "1e1482141079fc12def64d88cb7825b8f1cb1dc3",
		},
	}

	if err := step.ValidateStep(true); err != nil {
		t.Fatal(err)
	}

	step.Title = nil
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: no Title defined")
	}
	step.Title = new(string)

	*step.Title = ""
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: empty Title")
	}

	step.Description = nil
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: no Description defined")
	}
	step.Description = new(string)

	*step.Description = ""
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: empty Description")
	}

	step.Website = nil
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: no Website defined")
	}
	step.Website = new(string)

	*step.Website = ""
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: empty Website")
	}

	step.Source.Git = ""
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: empty Source.Git")
	}

	step.Source.Git = "git@github.com:bitrise-io/bitrise.git"
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: Source.Git has invalid prefix")
	}

	step.Source.Git = "https://github.com/bitrise-io/bitrise"
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: Source.Git has invalid suffix")
	}

	step.Source.Commit = ""
	if err := step.ValidateStep(true); err == nil {
		t.Fatal("Invalid step: empty Source.Commit")
	}
}

func TestValidateStepInputOutputModel(t *testing.T) {
	// Filled env
	env := envmanModels.EnvironmentItemModel{
		testKey: testValue,
		envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
			Title:             pointers.NewStringPtr(testTitle),
			Description:       pointers.NewStringPtr(testDescription),
			ValueOptions:      testValueOptions,
			IsRequired:        pointers.NewBoolPtr(testTrue),
			IsExpand:          pointers.NewBoolPtr(testFalse),
			IsDontChangeValue: pointers.NewBoolPtr(testTrue),
		},
	}

	err := ValidateStepInputOutputModel(env)
	if err != nil {
		t.Fatal(err)
	}

	// Empty key
	env = envmanModels.EnvironmentItemModel{
		"": testValue,
		envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
			Title:             pointers.NewStringPtr(testTitle),
			Description:       pointers.NewStringPtr(testDescription),
			ValueOptions:      testValueOptions,
			IsRequired:        pointers.NewBoolPtr(testTrue),
			IsExpand:          pointers.NewBoolPtr(testFalse),
			IsDontChangeValue: pointers.NewBoolPtr(testTrue),
		},
	}

	err = ValidateStepInputOutputModel(env)
	if err == nil {
		t.Fatal("Empty key, should fail")
	}

	// Title is empty
	env = envmanModels.EnvironmentItemModel{
		testKey: testValue,
		envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
			Description:       pointers.NewStringPtr(testDescription),
			ValueOptions:      testValueOptions,
			IsRequired:        pointers.NewBoolPtr(testTrue),
			IsExpand:          pointers.NewBoolPtr(testFalse),
			IsDontChangeValue: pointers.NewBoolPtr(testTrue),
		},
	}

	err = ValidateStepInputOutputModel(env)
	if err == nil {
		t.Fatal("Empty Title, should fail")
	}
}

func TestFillMissingDefaults(t *testing.T) {
	title := "name 1"
	// desc := "desc 1"
	website := "web/1"
	git := "https://git.url"
	// fork := "fork/1"

	step := StepModel{
		Title:   pointers.NewStringPtr(title),
		Website: pointers.NewStringPtr(website),
		Source: StepSourceModel{
			Git: git,
		},
		HostOsTags:      []string{"osx"},
		ProjectTypeTags: []string{"ios"},
		TypeTags:        []string{"test"},
	}

	err := step.FillMissingDefaults()
	if err != nil {
		t.Fatal(err)
	}

	if step.Description == nil || *step.Description != "" {
		t.Fatal("Description missing")
	}
	if step.SourceCodeURL == nil || *step.SourceCodeURL != "" {
		t.Fatal("SourceCodeURL missing")
	}
	if step.SupportURL == nil || *step.SupportURL != "" {
		t.Fatal("SourceCodeURL missing")
	}
	if step.IsRequiresAdminUser == nil || *step.IsRequiresAdminUser != DefaultIsRequiresAdminUser {
		t.Fatal("IsRequiresAdminUser missing")
	}
	if step.IsAlwaysRun == nil || *step.IsAlwaysRun != DefaultIsAlwaysRun {
		t.Fatal("IsAlwaysRun missing")
	}
	if step.IsSkippable == nil || *step.IsSkippable != DefaultIsSkippable {
		t.Fatal("IsSkippable missing")
	}
	if step.RunIf == nil || *step.RunIf != "" {
		t.Fatal("RunIf missing")
	}
}

func TestGetStep(t *testing.T) {
	defaultIsRequiresAdminUser := DefaultIsRequiresAdminUser

	step := StepModel{
		Title:         pointers.NewStringPtr(title),
		Description:   pointers.NewStringPtr(desc),
		Website:       pointers.NewStringPtr(website),
		SourceCodeURL: pointers.NewStringPtr(fork),
		Source: StepSourceModel{
			Git: git,
		},
		HostOsTags:          []string{"osx"},
		ProjectTypeTags:     []string{"ios"},
		TypeTags:            []string{"test"},
		IsRequiresAdminUser: pointers.NewBoolPtr(defaultIsRequiresAdminUser),
		Inputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_1": "Value 1",
			},
			envmanModels.EnvironmentItemModel{
				"KEY_2": "Value 2",
			},
		},
		Outputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_3": "Value 3",
			},
		},
	}

	collection := StepCollectionModel{
		FormatVersion:        "1.0.0",
		GeneratedAtTimeStamp: 0,
		Steps: StepHash{
			"step": StepGroupModel{
				Versions: map[string]StepModel{
					"1.0.0": step,
				},
			},
		},
		SteplibSource: "source",
		DownloadLocations: []DownloadLocationModel{
			DownloadLocationModel{
				Type: "zip",
				Src:  "amazon/",
			},
			DownloadLocationModel{
				Type: "git",
				Src:  "step.git",
			},
		},
	}

	step, found := collection.GetStep("step", "1.0.0")
	if !found {
		t.Fatal("Step not found (step) (1.0.0)")
	}
}

func TestGetDownloadLocations(t *testing.T) {
	defaultIsRequiresAdminUser := DefaultIsRequiresAdminUser

	// Zip & git download locations
	step := StepModel{
		Title:         pointers.NewStringPtr(title),
		Description:   pointers.NewStringPtr(desc),
		Website:       pointers.NewStringPtr(website),
		SourceCodeURL: pointers.NewStringPtr(fork),
		Source: StepSourceModel{
			Git: git,
		},
		HostOsTags:          []string{"osx"},
		ProjectTypeTags:     []string{"ios"},
		TypeTags:            []string{"test"},
		IsRequiresAdminUser: pointers.NewBoolPtr(defaultIsRequiresAdminUser),
		Inputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_1": "Value 1",
			},
			envmanModels.EnvironmentItemModel{
				"KEY_2": "Value 2",
			},
		},
		Outputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_3": "Value 3",
			},
		},
	}

	collection := StepCollectionModel{
		FormatVersion:        "1.0.0",
		GeneratedAtTimeStamp: 0,
		Steps: StepHash{
			"step": StepGroupModel{
				Versions: map[string]StepModel{
					"1.0.0": step,
				},
			},
		},
		SteplibSource: "source",
		DownloadLocations: []DownloadLocationModel{
			DownloadLocationModel{
				Type: "zip",
				Src:  "amazon/",
			},
			DownloadLocationModel{
				Type: "git",
				Src:  "step.git",
			},
		},
	}

	locations, err := collection.GetDownloadLocations("step", "1.0.0")
	if err != nil {
		t.Fatal(err)
	}

	zipFound := false
	gitFount := false
	zipIdx := -1
	gitIdx := -1

	for idx, location := range locations {
		if location.Type == "zip" {
			if location.Src != "amazon/step/1.0.0/step.zip" {
				t.Fatalf("Incorrect zip location (%s)", location.Src)
			}
			zipFound = true
			zipIdx = idx
		} else if location.Type == "git" {
			if location.Src != git {
				t.Fatalf("Incorrect git location (%s)", location.Src)
			}
			gitFount = true
			gitIdx = idx
		}
	}

	if zipFound == false {
		t.Fatal("No zip location found")
	}
	if gitFount == false {
		t.Fatal("No zip location found")
	}
	if gitIdx < zipIdx {
		t.Fatal("Incorrect download locations order")
	}
}

func TestGetLatestStepVersion(t *testing.T) {
	defaultIsRequiresAdminUser := DefaultIsRequiresAdminUser

	step := StepModel{
		Title:         pointers.NewStringPtr(title),
		Description:   pointers.NewStringPtr(desc),
		Website:       pointers.NewStringPtr(website),
		SourceCodeURL: pointers.NewStringPtr(fork),
		Source: StepSourceModel{
			Git: git,
		},
		HostOsTags:          []string{"osx"},
		ProjectTypeTags:     []string{"ios"},
		TypeTags:            []string{"test"},
		IsRequiresAdminUser: pointers.NewBoolPtr(defaultIsRequiresAdminUser),
		Inputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_1": "Value 1",
			},
			envmanModels.EnvironmentItemModel{
				"KEY_2": "Value 2",
			},
		},
		Outputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_3": "Value 3",
			},
		},
	}

	collection := StepCollectionModel{
		FormatVersion:        "1.0.0",
		GeneratedAtTimeStamp: 0,
		Steps: StepHash{
			"step": StepGroupModel{
				Versions: map[string]StepModel{
					"1.0.0": step,
					"2.0.0": step,
				},
				LatestVersionNumber: "2.0.0",
			},
		},
		SteplibSource: "source",
		DownloadLocations: []DownloadLocationModel{
			DownloadLocationModel{
				Type: "zip",
				Src:  "amazon/",
			},
			DownloadLocationModel{
				Type: "git",
				Src:  "step.git",
			},
		},
	}

	latest, err := collection.GetLatestStepVersion("step")
	if err != nil {
		t.Fatal(err)
	}
	if latest != "2.0.0" {
		t.Fatalf("Latest version (%s), should be (2.0.0)", latest)
	}
}


text:
					<button type="button"
					class="close"
					ng-click="vm.ajustarModal.hide()" >×</button >

<form
 class="form-horizontal"
 ng-submit="vm.createNcf(vm.ncf, ncfForm.$valid)" id="ncfForm" name="ncfForm" novalidate>

		Tipo NCF

			<oi-select
			oi-options="item.desc for item in vm.paramRestServices.ncfList track by item.code"
			ng-model="vm.ncf.codes"
			placeholder="Tipos de NCF"
			name="code"
			></oi-select required>

		Serie:

			<input maxlength="1" type="text" class="form-control" ng-model="vm.ncf.serie" name="serie" autocomplete="off" required>

		Div. de Negocios:

			<input maxlength="2" type="text" class="form-control" name="dn" ng-model="vm.ncf.dn" autocomplete="off" required>

		Punto Emisión:

			<input maxlength="3" type="text" class="form-control" name="pe" ng-model="vm.ncf.pe" autocomplete="off" required>

		Área de Impresión:

			<input maxlength="3" type="text" class="form-control" name="ai" ng-model="vm.ncf.ai" autocomplete="off" required>

		Sec. Inicial:

			<input type="number" class="form-control" id="email" autocomplete="off" required name="SecInicial" ng-model="vm.ncf.secInicial" min="1">

		Sec. Final:

			<input type="number" class="form-control" id="email" autocomplete="off" required name="SecFinal" ng-model="vm.ncf.secFinal" min="1">

			Cancelar
			<button type="submit" class="btn btn-primary">Guardar</button>

</form>


text:
package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/fsouza/go-dockerclient"
)

const (
	version = "0.1.0" // Program version

	exitOK  = 0 // Terminate without error
	exitErr = 1 // Terminate with error
)

var (
	// Flags
	host        string // Docker host
	fragment    string // Search string for reloading the right Docker containers
	versionFlag bool   // If true, only print the program version and exit

	// Global functions for unit testing
	newDockerClient newDockerManager = func(host string) (dockerManager, error) { return docker.NewClient(host) }
	exit            exiter           = func(code int) { os.Exit(code) }
	stdout          io.Writer        = os.Stdout
	stderr          io.Writer        = os.Stderr
)

// Takes care of exiting the program
type exiter func(code int)

// Defines the condition of the program exit
type exitCondition struct {
	code int
	err  error
}

// Function type for newDockerClient
type newDockerManager func(host string) (dockerManager, error)

// Interface for dockerClient
type dockerManager interface {
	ListContainers(docker.ListContainersOptions) ([]docker.APIContainers, error)
	KillContainer(docker.KillContainerOptions) error
}

func init() {
	// Flags
	flag.StringVar(&fragment, "fragment", "nginx", "All running Docker containers whose names contain this fragement will receive the SIGHUP signal.")
	flag.StringVar(&host, "host", "unix:///var/run/docker.sock", "The Docker socket to connect to, specified using tcp://host:port or unix:///path/to/socket.")
	flag.BoolVar(&versionFlag, "version", false, "Print the version of docker-nginx-reloader and exit.")
}

func main() {
	defer handleExit() // Graceful and testable exit

	flag.Parse()

	// Does the user only want the version?
	if versionFlag {
		fmt.Fprintln(stdout, version)
		panic(exitCondition{exitOK, nil})
	}

	// Get a Docker client
	dockerClient, err := newDockerClient(host)
	if err != nil {
		panic(exitCondition{exitErr, err})
	}

	// Get a list of all running Docker containers
	containers, err := dockerClient.ListContainers(docker.ListContainersOptions{})
	if err != nil {
		panic(exitCondition{exitErr, err})
	}

	for _, container := range containers {
		for _, containerName := range container.Names {
			if strings.Index(containerName, fragment) >= 0 {
				dockerClient.KillContainer(
					docker.KillContainerOptions{
						ID:     container.ID,
						Signal: docker.SIGHUP,
					},
				)
				fmt.Fprintf(
					stdout,
					"Sent SIGHUP signal to %s (%s)\n",
					containerName[1:],
					container.ID,
				)
			}
		}
	}
}

func handleExit() {
	// Recover the thrown panic
	if err := recover(); err != nil {
		// Check if the panic was thrown by us
		if p, ok := err.(exitCondition); ok {
			// If there was an error, print it
			if p.code == exitErr {
				fmt.Fprintln(stderr, p.err)
			}
			// Terminate the program with the appropriate exit code
			exit(p.code)
		}
	}
}


text:
/*jslint node: true */

"use strict";

var clone = require('clone');
var w = require('winston');
w.level = process.env.LOG_LEVEL;

var Lock = require("./Lock.js");
var Entity = require("./Entity.js");
var Action = require("./Action.js");

var Promise = require('bluebird');

function valid(o) {
    return ((o !== undefined) && (o !== null));
}

// TODO: support initialization with old format
function Flow(flow) {
    if(!valid(Flow.OpTypes))
        throw new Error("Flow has not been initialized. Call init of ULocks first.");

    if(!valid(flow)) {
        throw new Error("Flow: Error: Cannot construct flow from undefined flow.");
    }

    if(!flow.hasOwnProperty('op') || !valid(flow.op))
        throw new Error("Flow '"+JSON.stringify(flow)+"' does not specify underlying operation!");
    else
        this.op = flow.op;

    if(!valid(Flow.OpTypes[this.op]))
        throw new Error("Flow '"+JSON.stringify(flow)+"' specification uses unknown operation!");

    var totalLocks = 0;
    var numLocks = {};

    // TODO: check whether simple cloning is more efficient!
    if(flow.hasOwnProperty('locks') && valid(flow.locks)) {
        this.locks = {};

        // be downwards compatible to old policy format
        // where locks was a pure array
        if(flow.locks instanceof Array) {
            for(var i in flow.locks) {
                var l = Lock.createLock(flow.locks[i]);
                var key = l.lock;
                if(!this.locks.hasOwnProperty(key))
                    this.locks[key] = [];
                this.locks[key].push(l);
                numLocks[key]++;
                totalLocks++;
            }
        } else {
            for(var k in flow.locks) {
                this.locks[k] = [];
                numLocks[k] = 0;
                for(var j in flow.locks[k]) {
                    numLocks[k]++;
                    totalLocks++;
                    this.locks[k].push(Lock.createLock((flow.locks[k][j])));
                }
            }
        }

        if(totalLocks === 0) {
            delete this.locks;
        } else {
            for(var n in numLocks) {
                if(numLocks[n] === 0) {
                    delete this.locks[n];
                }
            }
        }
    }

    // TODO: Disable as actions moved up to Policy level (for now)
    /* if(flow.hasOwnProperty('actions') && valid(flow.actions)) {
        this.actions = [];
        for(var i in flow.actions) {
            try {
                this.actions.push(Action.createAction(flow.actions[i]));
            } catch(e) {
                this.actions = null;
                w.debug("Invalid action specification. Drop complete action chain and always delete data!");
                w.debug(e);
                break;
            }
        }
    }*/
}

Flow.OpTypes = null;

Flow.init = function(settings) {
    if(!settings.hasOwnProperty('opTypes'))
        return Promise.reject(new Error("ULocks: Flow cannot be initialized. Settings do not specify operation types!"))

    Flow.OpTypes = settings.opTypes;

    return Promise.resolve();
}

Flow.prototype.hasSrc = function() {
    return !(Flow.OpTypes[this.op] === 1)
};

Flow.prototype.hasTrg = function() {
    return (Flow.OpTypes[this.op] === 1)
};

Flow.prototype.eq = function(otherFlow, conflicts) {
    var showConflicts = false;
    var matched = true;

    if(valid(conflicts)) {
        showConflicts = conflicts;
        if(showConflicts)
            matched = [];
    }

    if(!valid(this.op) || !valid(otherFlow.op) || this.op !== otherFlow.op)
        return false;

    var thisFlow = this;

    if((!valid(thisFlow.locks) || !valid(otherFlow.locks)) &&
       thisFlow.locks !== otherFlow.locks)
        return false;

    var tlength = 0;
    var olength = 0;
    if(valid(thisFlow.locks)) {
        tlength = Object.keys(thisFlow.locks).length;
        olength = Object.keys(otherFlow.locks).length;
    }

    if(!showConflicts && tlength != olength)
        return false;

    if(tlength > olength) {
        var tmpFlow = thisFlow;
        thisFlow = otherFlow;
        otherFlow = tmpFlow;
    }

    var thisHasLocks = thisFlow.hasOwnProperty('locks');
    if(thisHasLocks !== otherFlow.hasOwnProperty('locks'))
        return false;

    // TODO: Generate test case in which locks have length 0
    if(thisHasLocks) {
        for(var type in otherFlow.locks) {
            if(thisFlow.locks.hasOwnProperty(type)) {
                var l1 = thisFlow.locks[type];
                var l2 = otherFlow.locks[type];
                if(l2.length > l1.length) {
                    var tmp = l2;
                    l2 = l1;
                    l1 = tmp;
                }

                for(var k in l1) {
                    var found = false;

                    for(var i in l2) {
                        if(l1[k].eq(l2[i])) {
                            found = true;
                            break;
                        }
                    }
                    if(!found) {
                        if(showConflicts)
                            matched.push(Lock.createLock(l1[k]));
                        else
                            matched = false;
                    }
                }
            } else {
                if(showConflicts)
                    // put all locks in array which were not matched
                    for(var j in otherFlow.locks[type]) {
                        matched.push(Lock.createLock(otherFlow.locks[type][j]));
                    }
                else
                    matched = false;
            }
        }
    }

    return matched;
};

Flow.prototype.le = function(otherFlow, _showConflicts) {
    var showConflicts = false;
    var conflicts = false;
    if(valid(_showConflicts)) {
        showConflicts = _showConflicts;
        if(showConflicts)
            conflicts = [];
    }

    // incompatible flows to be compared
    // TODO: decide whether to better throw an error here
    // TODO: better compare operations!
    if(!valid(this.op) || !valid(otherFlow.op) || this.op !== otherFlow.op)
        return false;

    var thisFlow = this;

    var thisHasLocks = thisFlow.hasOwnProperty('locks');
    var otherHasLocks = otherFlow.hasOwnProperty('locks');

    // either this flow has no locks and the other has, then it is less restrictive
    // or both locks have no locks at all
    if(!thisHasLocks && otherHasLocks || (!thisHasLocks && !otherHasLocks))
        return true;
    else
        // if the other flow has no locks but this one has
        // the other flow is less restrictive (data can always flow)
        if(thisHasLocks && !otherHasLocks)
            return false;

    // at this point we can assume both flows have locks
    // if one flow has more lock types, it must be considered
    // to be more restrictive as it requires one more condition
    // to hold
    var thisTypes = Object.keys(thisFlow.locks).length;
    var otherTypes = Object.keys(otherFlow.locks).length;

    if(thisTypes > otherTypes)
        return false;
    else
        if(thisTypes < otherTypes)
            return true;

    for(var type in otherFlow.locks) {
        w.debug("\tcheck locks of type '"+type+"'");
        if(thisFlow.locks.hasOwnProperty(type)) {
            var l1 = thisFlow.locks[type];
            var l2 = otherFlow.locks[type];

            // find out whether every lock
            // in otherFlow has a smaller
            // counterpart in this flow
            var covered = [];
            for(var k in l1) {
                var found = false;
                for(var i in l2) {
                    w.debug("\t\t"+l1[k]+" <= "+l2[i]);
                    if(l1[k].le(l2[i])) {
                        found = true;
                        covered[i] = true;
                        w.debug("\t\t\t===> true");
                    } else
                        w.debug("\t\t\t===> false");
                }

                if(!found) {
                    if(showConflicts)
                        conflicts.push(Lock.createLock(l1[k]));
                    else
                        conflicts = true;
                }
            }

            for(var j in l2) {
                if(covered[j] !== true) {
                    if(showConflicts)
                        conflicts.push(Lock.createLock(l2[j]));
                    else
                        conflicts = true;
                }
            }
        } else {
            if(showConflicts)
                // put all locks in array which were not matched
                for(var h in otherFlow.locks[type]) {
                    conflicts.push(Lock.createLock(otherFlow.locks[type][h]));
                }
            else
                conflicts = true;
        }
    }

    if(showConflicts)
        return conflicts;
    else
        return !conflicts;
};

Flow.prototype.getClosedLocks = function(context, scope, showConflicts) {
    w.debug(">>> Flow.prototype.getClosedLocks: ", this);
    var f = this;

    return new Promise(function(resolve, reject) {
        var allopen = true;
        var cond = false;
        var resLocks = [];

        if(f.hasOwnProperty('locks')) {
            var promises = [];

            var checkLock = function(lock, i) {
                var s;

                /* console.log("\t\tlock: "+lock);
                   console.log("\t\tCurrent lock state: ",context.locks); */

                // check whether lockstate is already in context
                /* if(context) {
                   s = context.getLockState(lock, context.sender);
                   }
                   console.log("LOCK STATE: ",s);
                   console.log("CONTEXT STATE: ",context.isStatic);*/

                // lock state is not know => compute it

                if(s === undefined) {
                    w.debug("Flow.prototype.getClosedLocks: lock state of '"+lock+"' not cached => get current value");
                    promises.push(lock.isOpen(context, scope));
                } else {
                    promises.push(Promise.resolve({ open : s, cond : false, lock : lock }));
                }
            };

            for(var type in f.locks) {
                var locks = f.locks[type];
                locks.forEach(checkLock);
            }

            Promise.all(promises).then(function(lockStates) {
                w.debug("all resolved/rejected ", lockStates);
                var conflicts = [];
                for(var i in lockStates) {
                    // if(context && s && s.cond == false)
                    // context.addLockState(lock, context.subject, s.result);

                    allopen = allopen && lockStates[i].open;
                    cond = cond || lockStates[i].cond;

                    if(!lockStates[i].open || lockStates[i].cond) {
                        if(lockStates[i].lock) {
                            conflicts.push(lockStates[i].lock);
                        }
                    }
                }

                var result = { open : allopen, cond : cond };

                if(conflicts.length > 0)
                    result.locks = conflicts;
                resolve(result);
            }, function(error) {
                w.error("Failed to evaluate lock in flow '"+f+"'!");
                w.error(error);
                reject(error);
            });
        } else {
            resolve({ open: true, cond: false });
        }
    });
};

// multiplies the locks in this flow with the lock in factor
// this method assumes that the array of locks is always
// minimal, i.e. there are no redundant locks
Flow.prototype.lubLock = function(factor) {
    var l = this.locks ? this.locks.length : 0;
    var newLocks = [];
    var merged = false;

    var lock = Lock.createLock(factor);

    if(this.locks && this.locks[lock.lock]) {
        var toMultiply = this.locks[lock.lock];

        for(var i in toMultiply) {
            var lub = (toMultiply[i]).lub(lock);
            if(lub) {
                newLocks.push(lub);
                merged = true;
            } /*else {
                newLocks.push(Lock.createLock(toMultiply[i]));
            }*/
        }
    }

    if(!merged)
        newLocks.push(lock);

    return newLocks;
};

Flow.prototype.getLocks = function(type) {
    if(!valid(type)) {
        var all = [];
        for(var type in this.locks) {
            var l = clone(this.locks[type]);
            all = all.concat(l);
        }
        return all;
    } else {
        if(this.flows.hasOwnProperty(op)) {
            return clone(this.locks[op]);
        }
        else
            return null;
    }
}

Flow.prototype.addLock = function(lock) {
    var type = lock.lock;

    if(!this.hasOwnProperty("locks"))
        this.locks = {};

    if(!this.locks.hasOwnProperty(type))
        this.locks[type] = [];

    var locks = this.locks[type];
    var found = false;
    for(var i in locks) {
        var l = locks[i];
        if(l.eq(lock)) {
            found = true;
        } else {
            if(l.lub(lock) === null)
                closed = true;
        }
    }

    // TODO: insert closed lock and delete all other -> flow is always forbidden
    // if(closed)

    if(!found)
        this.locks[type].push(lock);
}

Flow.prototype.lub = function(flow) {
    w.debug(">>> Flow.prototype.lub(\n\t"+this+",\n\t"+flow+")");

    // flows are incompatible and there is
    // no upper bound on them; we would need
    // a new policy for this
    if(!valid(this.op) || !valid(flow.op) || this.op !== flow.op) {
        // console.log("Error: try to lub source and target flow");
        return null;
    } else {
        var newFlow = new Flow(this);

        for(var type in flow.locks) {
            for(var i in flow.locks[type]) {
                var r = newFlow.lubLock((flow.locks[type])[i]);

                if(!newFlow.hasOwnProperty("locks"))
                    newFlow.locks = {};
                newFlow.locks[type] = [];

                if(r.length > 0) {
                    for(var k in r) {
                        newFlow.addLock(r[k]);
                    }
                }
            }
        }

        return newFlow;
    }
};

Flow.prototype.toString = function() {
    var str = "";
    var l = this.hasOwnProperty('locks') ? this.locks.length : 0;

    if(Flow.OpTypes[this.op] === 1) {
        if(this.hasOwnProperty('locks')) {
            var c = 0;
            for(var t  in this.locks) {
                (this.locks[t]).forEach(function(lock,i) {
                    if(c > 0  || i > 0)
                        str += " ^ ";
                    str += lock;
                });
                c++;
            }
        } else
            str += "always";

        str = "{ "+str+" ==> TARGET";

        // TODO: Disabled for now as actions moved up to policy level
        /* if(this.hasOwnProperty('actions')) {
            var al = this.actions.length
            str += " do ";

            this.actions.forEach(function(action,i) {
                str += action;
                if(i < al - 1)
                    str += " then ";
            });

            str += " ";
        }*/
        str += " }";
    } else {
        str = "{ SOURCE ==> ";
        if(this.hasOwnProperty('locks')) {
            var c = 0;
            for(var t  in this.locks) {
                (this.locks[t]).forEach(function(lock,i) {
                    str += lock;
                    if(i < l - 1)
                        str += " ^ ";
                });
            }
        } else
            str += "always";

        // TODO: Disabled for now as actions moved up to policy level
        /* if(this.hasOwnProperty('actions')) {
            var al = this.actions.length
            str += " do ";

            this.actions.forEach(function(action,i) {
                str += action;
                if(i < al - 1)
                    str += " then ";
            });

            str += " ";
        }*/

        str += " }";
    }
    return str;
};

// TODO: Disabled for now as actions moved up to policy level
/* Flow.prototype.actOn = function(data, context, scope) {
    var self = this;
    return new Promise(function(resolve, reject) {
        if(self.hasOwnProperty('actions')) {
            if(self.actions !== null) {
                var newData = Promise.resolve(clone(data));
                self.actions.forEach(function(action) {
                    newData = newData.then(function(v) {
                        if(action.apply !== undefined)
                            return action.apply(v, context, scope);
                        else
                            return Promise.reject(new Error("Action does not define method 'apply'"));
                    }, function(e) {
                        w.error("Flow.prototype.actOn is not able to apply actions as one action is defined inappropriately.");
                        return Promise.reject(e);
                    });
                });

                newData.then(function(v) {
                    w.debug("All actions have been applied.");
                    resolve(v);
                });
            } else {
                resolve(null);
            }
        } else
            resolve(clone(data));
    });
}*/

Flow.prototype.compile2PolicyEval = function() {
    var srctrg = this.source ? this.source.compile2PolicyEval() : this.target.compile2PolicyEval();

    var condition = "";
    for(var l in this.locks) {
        if(l > 0)
            condition += " && ";
        condition += '(' + this.locks[l].compile2PolicyEval() + ')';
    }

    var result = "";

    if(this.target) {
        if(condition.length)
            result = srctrg + " = (!"+condition+") ? "+srctrg+" : ";
        else
            result = srctrg + " = ";
    } else {
        if(condition.length)
            result = " = "+condition+" ? " + srctrg + " : ";
        else
            result = " = " + srctrg + ";";
    }

    return result;
};

module.exports = Flow;


text:
#ifndef _CHAP_H
#define _CHAP_H

//Dependencies
#include "core/net.h"
#include "ppp/ppp.h"

//CHAP authentication support
#ifndef CHAP_SUPPORT
   #define CHAP_SUPPORT DISABLED
#elif (CHAP_SUPPORT != ENABLED && CHAP_SUPPORT != DISABLED)
   #error CHAP_SUPPORT parameter is not valid
#endif

//Restart timer
#ifndef CHAP_RESTART_TIMER
   #define CHAP_RESTART_TIMER 3000
#elif (CHAP_RESTART_TIMER < 1000)
   #error CHAP_RESTART_TIMER parameter is not valid
#endif

//Maximum number of retransmissions for Challenge packets
#ifndef CHAP_MAX_CHALLENGES
   #define CHAP_MAX_CHALLENGES 5
#elif (CHAP_MAX_CHALLENGES < 1)
   #error CHAP_MAX_CHALLENGES parameter is not valid
#endif

/**
 * @brief CHAP states
 **/

typedef enum
{
   CHAP_STATE_0_INITIAL        = 0,
   CHAP_STATE_1_STARTED        = 1,
   CHAP_STATE_2_CHALLENGE_SENT = 2,
   CHAP_STATE_3_CHALLENGE_RCVD = 3,
   CHAP_STATE_4_RESPONSE_SENT  = 4,
   CHAP_STATE_5_RESPONSE_RCVD  = 5,
   CHAP_STATE_6_SUCCESS_SENT   = 6,
   CHAP_STATE_7_SUCCESS_RCVD   = 7,
   CHAP_STATE_8_FAILURE_SENT   = 8,
   CHAP_STATE_9_FAILURE_RCVD   = 9
} ChapState;

/**
 * @brief Code field values
 **/

typedef enum
{
   CHAP_CODE_CHALLENGE = 1, ///<Challenge
   CHAP_CODE_RESPONSE  = 2, ///<Response
   CHAP_CODE_SUCCESS   = 3, ///<Success
   CHAP_CODE_FAILURE   = 4  ///<Failure
} ChapCode;

/**
 * @brief CHAP algorithm identifiers
 **/

typedef enum
{
   CHAP_ALGO_ID_CHAP_MD5   = 5,   //CHAP with MD5
   CHAP_ALGO_ID_MS_CHAP    = 128, //MS-CHAP
   CHAP_ALGO_ID_MS_CHAP_V2 = 129  //MS-CHAP-2
} ChapAlgoId;

//CodeWarrior or Win32 compiler?
#if defined(__CWCC__) || defined(_WIN32)
   #pragma pack(push, 1)
#endif

/**
 * @brief Challenge packet
 **/

typedef __start_packed struct
{
   uint8_t code;       //0
   uint8_t identifier; //1
   uint16_t length;    //2-3
   uint8_t valueSize;  //4
   uint8_t value[];    //5
} __end_packed ChapChallengePacket;

/**
 * @brief Response packet
 **/

typedef __start_packed struct
{
   uint8_t code;       //0
   uint8_t identifier; //1
   uint16_t length;    //2-3
   uint8_t valueSize;  //4
   uint8_t value[];    //5
} __end_packed ChapResponsePacket;

/**
 * @brief Success packet
 **/

typedef __start_packed struct
{
   uint8_t code;       //0
   uint8_t identifier; //1
   uint16_t length;    //2-3
   uint8_t message[];  //4
} __end_packed ChapSuccessPacket;

/**
 * @brief Failure packet
 **/

typedef __start_packed struct
{
   uint8_t code;       //0
   uint8_t identifier; //1
   uint16_t length;    //2-3
   uint8_t message[];  //4
} __end_packed ChapFailurePacket;

//CodeWarrior or Win32 compiler?
#if defined(__CWCC__) || defined(_WIN32)
   #pragma pack(pop)
#endif

/**
 * @brief CHAP finite state machine
 **/

typedef struct
{
   uint_t localState;       ///<Local state
   uint_t peerState;        ///<Peer state
   uint8_t identifier;      ///<Identifier used to match requests and replies
   uint_t restartCounter;   ///<Restart counter
   systime_t timestamp;     ///<Timestamp to manage retransmissions
   uint8_t challenge[16];   ///<Challenge value sent to the peer
   const uint8_t *response; ///<Response value from the peer
} ChapFsm;

//CHAP related functions
error_t chapStartAuth(PppContext *context);
error_t chapAbortAuth(PppContext *context);

void chapTick(PppContext *context);

void chapProcessPacket(PppContext *context,
   const PppPacket *packet, size_t length);

error_t chapProcessChallenge(PppContext *context,
   const ChapChallengePacket *challengePacket, size_t length);

error_t chapProcessResponse(PppContext *context,
   const ChapResponsePacket *responsePacket, size_t length);

error_t chapProcessSuccess(PppContext *context,
   const ChapSuccessPacket *successPacket, size_t length);

error_t chapProcessFailure(PppContext *context,
   const ChapFailurePacket *failurePacket, size_t length);

error_t chapSendChallenge(PppContext *context);

error_t chapSendResponse(PppContext *context,
   uint8_t identifier, const uint8_t *value);

error_t chapSendSuccess(PppContext *context, uint8_t identifier);
error_t chapSendFailure(PppContext *context, uint8_t identifier);

bool_t chapCheckPassword(PppContext *context, const char_t *password);

#endif


text:
namespace AsoiafWikiDb.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Http;
    using System.Web.Mvc;

    using AsoiafWikiDb.Models;

    public class CategoryController : Controller
    {
        public ViewResult Index([FromUri]CategoryIndexViewModel vm)
        {
            var categories = Repository.Instance.Categories;
            if (vm.Hide == Hide.Yes)
            {
                categories = categories.Where(c => c.info.hidden);
            }
            else if (vm.Hide == Hide.No)
            {
                categories = categories.Where(c => !c.info.hidden);
            }

            if (vm.MinSize > 0)
            {
                categories = categories.Where(c => c.info.size >= vm.MinSize);
            }

            if (vm.MaxSize > 0)
            {
                categories = categories.Where(c => c.info.size <= vm.MaxSize);
            }

            if (!string.IsNullOrEmpty(vm.OrderBy))
            {
                if (vm.OrderBy.Equals("pages", StringComparison.InvariantCultureIgnoreCase))
                {
                    categories = vm.Desc ? categories.OrderByDescending(c => c.info.pages) : categories.OrderBy(c => c.info.pages);
                }
            }

            if (vm.Top > 0)
            {
                categories = categories.Take(vm.Top);
            }

            vm.Categories = categories.ToList();
            return this.View(vm);
        }
    }
}


text:
require 'test_helper'

class MultipleSequencesTest < ActiveSupport::TestCase
  test "works with simple multiple sequences" do
    doppelganger = Doppelganger.create!
    assert_equal 1, doppelganger.sequential_id_one
    assert_equal 1000, doppelganger.sequential_id_two
  end

  test "raises error on multiple definitions for the same column" do
    assert_raise Sequenced::ActsAsSequenced::SequencedColumnExists do
      Doppelganger.class_eval do
        acts_as_sequenced column: :sequential_id_one, start_at: 99
      end
    end

    doppelganger = Doppelganger.create!
    assert_equal 1, doppelganger.sequential_id_one
  end
end


text:
@interface DropboxShareFolderLaunchEnumParser : NSObject

+ (DropboxShareFolderLaunchEnum)enumFromString:(NSString * _Nonnull)string;

@end


text:
var gulp  = require('gulp'),
    gutil = require('gulp-util'),
	webpack = require('webpack'),
	path = require('path'),
	clean = require('gulp-clean'),
	less = require('gulp-less'),
	cssmin = require('gulp-cssmin'),
	rename = require('gulp-rename'),
	zip = require('gulp-zip'),
	webpackConfig = require("./webpack-config/webpack.gulp.config.js"),
	args   = require('yargs').argv,
	config = [];

config.copyFiles = [
	'./application/**',
	'./system/**',
	'./upload/**',
	'./minified/**',
	'./fonts/**',
	'./images/**',
	'./logs/**',
	'./index.php',
	'./license.txt',
	/********/
	'./less/**',
	'./compiled/**',
	'./libs/**'
];
config.lessFiles = [
	'./less/angular-styles.less',
	'./less/angular-admin.less',
	'./less/react-styles.less'
];

config.cleanFile = [
	'build/',
	'css/',
	'zip/'
];

// create a default task and just log a message
/*gulp.task('default', function() {
  return gutil.log('Gulp is running!')
});*/

gulp.task('webpack', function(done) {
	webpack(webpackConfig).run(function(err, stats) {
		if(err) {
		  console.log('Error', err);
		}
		else {
		  console.log(stats.toString());
		}
		done();
	});
});

gulp.task('clean', ['webpack'], function () {
    return gulp.src(config.cleanFile, {read: false})
        .pipe(clean());
});

gulp.task('less', ['clean'], function () {
  return gulp.src(config.lessFiles)
    .pipe(less({
      paths: [ path.join(__dirname, 'less', 'includes') ]
    }))
	.pipe(cssmin())
	.pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./css'));
});

gulp.task('copy', ['clean', 'less'], function () {
	return gulp.src(config.copyFiles, {
            base: './'
        })
		.pipe(gulp.dest('build'));
});

gulp.task('zip', ['clean', 'copy'], function () {
	var buildNumber = args.build || "0.0.0";
	var buildName = "build " + buildNumber + ".zip";
    return gulp.src('build/*')
        .pipe(zip(buildName))
        .pipe(gulp.dest('zip'));
});

gulp.task('default', ['webpack','clean', 'less', 'copy', 'zip']);


text:
package org.gradle.api.internal.tasks.testing.junit;

import org.gradle.api.internal.tasks.testing.detection.TestClassVisitor;
import org.gradle.api.internal.tasks.testing.detection.TestFrameworkDetector;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

class JUnitTestClassDetecter extends TestClassVisitor {
    private boolean isAbstract;
    private String className;
    private String superClassName;
    private boolean test;

    JUnitTestClassDetecter(final TestFrameworkDetector detector) {
        super(detector);
    }

    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        isAbstract = (access & Opcodes.ACC_ABSTRACT) != 0;

        this.className = name;
        this.superClassName = superName;
    }

    @Override
    public void visitInnerClass(String name, String outerName, String innerName, int access) {
        if (name.equals(className) && (access & Opcodes.ACC_STATIC) == 0) {
            isAbstract = true;
        }
    }

    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
        if ("Lorg/junit/runner/RunWith;".equals(desc)) {
            test = true;
        }

        return null;
    }

    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        if (!test) {
            return new JUnitTestMethodDetecter(this);
        } else {
            return null;
        }
    }

    public String getClassName() {
        return className;
    }

    public boolean isAbstract() {
        return isAbstract;
    }

    public boolean isTest() {
        return test;
    }

    void setTest(boolean test) {
        this.test = test;
    }

    public String getSuperClassName() {
        return superClassName;
    }
}


text:
using DragonSpark.Model.Selection.Conditions;
using DragonSpark.Runtime.Activation;
using System.Collections.Generic;

namespace DragonSpark.Model.Sequences.Collections;

public class NotHave<T> : InverseCondition<T>, IActivateUsing<ICollection<T>>, IActivateUsing<IEnumerable<T>>
{
	public NotHave(ICollection<T> source) : base(new Has<T>(source)) {}

	public NotHave(IEnumerable<T> source) : base(new Has<T>(source)) {}
}