text:
import re
import string
import sys
import mimetools
import StringIO
from elementtree import ElementTree

class recollector:
    def __init__(self):
        self.res = {}
        self.regs = {}

    def add(self, name, reg, mods=None):
        self.regs[name] = reg % self.regs
        # print "%s = %s" % (name, self.regs[name])
        if mods:
            self.res[name] = re.compile(self.regs[
                                        name], mods)  # check that it is valid
        else:
            self.res[name] = re.compile(self.regs[
                                        name])  # check that it is valid

collector = recollector()
a = collector.add

a("TextSE", "[^<]+")
a("UntilHyphen", "[^-]*-")
a("Until2Hyphens", "%(UntilHyphen)s(?:[^-]%(UntilHyphen)s)*-")
a("CommentCE", "%(Until2Hyphens)s>?")
a("UntilRSBs", "[^\\]]*](?:[^\\]]+])*]+")
a("CDATA_CE", "%(UntilRSBs)s(?:[^\\]>]%(UntilRSBs)s)*>")
a("S", "[ \\n\\t\\r]+")
a("NameStrt", "[A-Za-z_:]|[^\\x00-\\x7F]")
a("NameChar", "[A-Za-z0-9_:.-]|[^\\x00-\\x7F]")
a("Name", "(?:%(NameStrt)s)(?:%(NameChar)s)*")
a("QuoteSE", "\"[^\"]*\"|'[^']*'")
a("DT_IdentSE", "%(S)s%(Name)s(?:%(S)s(?:%(Name)s|%(QuoteSE)s))*")

# http://bugs.activestate.com/show_bug.cgi?id=28765
# a("MarkupDeclCE" , "(?:[^\\]\"'><]+|%(QuoteSE)s)*>" )
a("MarkupDeclCE", "(?:[^\\]\"'> \\n\\t\\r<]+|%(QuoteSE)s)*>")

a("S1", "[\\n\\r\\t ]")
a("UntilQMs", "[^?]*\\?+")
a("PI_Tail", "\\?>|%(S1)s%(UntilQMs)s(?:[^>?]%(UntilQMs)s)*>")
a("DT_ItemSE",
    "<(?:!(?:--%(Until2Hyphens)s>|[^-]%(MarkupDeclCE)s)|\\?%(Name)s(?:%(PI_Tail)s))|%%%(Name)s;|%(S)s"
  )
a("DocTypeCE",
  "%(DT_IdentSE)s(?:%(S)s)?(?:\\[(?:%(DT_ItemSE)s)*](?:%(S)s)?)?>?")
a("DeclCE",
    "--(?:%(CommentCE)s)?|\\[CDATA\\[(?:%(CDATA_CE)s)?|DOCTYPE(?:%(DocTypeCE)s)?")
a("PI_CE", "%(Name)s(?:%(PI_Tail)s)?")
a("EndTagCE", "(?P<endtag>%(Name)s)(?:%(S)s)?>?")
a("AttValSE", "\"[^<\"]*\"|'[^<']*'")
a("ElemTagCE",
    "(?P<tag>%(Name)s)(?P<attrs>(?:%(S)s%(Name)s(?:%(S)s)?=(?:%(S)s)?(?:%(AttValSE)s))*)(?:%(S)s)?/?>?")

a("MarkupSPE",
    "<(?:!(?:%(DeclCE)s)?|\\?(?:%(PI_CE)s)?|/(?:%(EndTagCE)s)?|(?:%(ElemTagCE)s)?)")
a("XML_SPE", "%(TextSE)s|%(MarkupSPE)s")
a("XML_MARKUP_ONLY_SPE", "%(MarkupSPE)s")

a("DOCTYPE",
  r'<!DOCTYPE\s+(?P<type>\S+)\s+(?P<ident>PUBLIC|SYSTEM)\s+(?P<data1>%(QuoteSE)s)\s*(?P<data2>%(QuoteSE)s)?\s*(?:\[|>)', re.S)

a("attrfinderRE",
  "(?:[\n \t]*)(%(Name)s)(?:%(S)s)?=(?:%(S)s)?(%(AttValSE)s)", re.S | re.U)
attrfinder = collector.res["attrfinderRE"]

is_not_ascii = re.compile(eval(r'u"[\u0080-\uffff]"')).search

def parseiter(data, markuponly=0):
    if markuponly:
        reg = "XML_MARKUP_ONLY_SPE"
    else:
        reg = "XML_SPE"
    regex = collector.res[reg]
    return regex.finditer(data)

def strip_quotes(str):
    if not str:
        return None
    if str[0] in ["'", '"']:
        return str[1:-1]
    return str

# XXX this should realy be done via DTD/Schema, but that would be a major
# pain.  For general purposes, this will work fine and be faster

# these tags are defined to NOT ALLOW end tags at all in html.  They never
# have children and never have end tags
# defined in dtd as ELEMENT NAME - O EMPTY
html_no_close_tags = set([
    "basefont", "br", "area", "link", "img", "param", "hr", "input",
    "col", "frame", "isindex", "base", "meta"
])
# defined in dtd as ELEMENT NAME - O *
html_optional_close_tags = set([
    "p", "dt", "dd", "li", "option", "thead", "tfoot", "colgroup",
    "col", "tr", "th", "td"
])

html_block_tags = set([
    "p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "pre", "dl", "div", "noscript",
    "blockquote", "form", "hr", "table", "fieldset", "address"
])

# these are optional end tag and cannot contain other block tags defined above
html_cannot_contain_block_tags = set([
    "p", "dt"
])

html_close_tag_unnecessary = html_no_close_tags.union(html_optional_close_tags)

class HTMLTreeBuilder(ElementTree.TreeBuilder):

    def __init__(self, encoding="iso-8859-1"):
        ElementTree.TreeBuilder.__init__(self)
        self.encoding = encoding
        self.nodes = []
        self.nodemap = {}  # {child_elem: parent_elem, ... }
        self._rootnodes = []
        self.current = None

    def start(self, tag, attrs, loc_start, loc_end):
        if not tag:
            return
        # print loc
        if tag == "meta":
            # look for encoding directives
            http_equiv = content = None
            for k, v in attrs:
                if k == "http-equiv":
                    http_equiv = string.lower(v)
                elif k == "content":
                    content = v
            if http_equiv == "content-type" and content:
                # use mimetools to parse the http header
                header = mimetools.Message(
                    StringIO.StringIO("%s: %s\n\n" % (http_equiv, content))
                )
                encoding = header.getparam("charset")
                if encoding:
                    self.encoding = encoding
        l_tag = tag.lower()
        if self._elem:
            p_tag = self._elem[-1].tag.lower()
            # if the parent and child are the same tag, then close the
            # parent if it uses optional close tags
            if l_tag in html_optional_close_tags and p_tag == l_tag:
                self.end(tag)
            # special case table tags that should be autoclosed only when
            # hitting a new table row
            elif p_tag in ("td", "th") and l_tag == "tr":
                self.end_tag(p_tag)
            # if the parent and child are block tags, close the parent
            elif p_tag in html_cannot_contain_block_tags and l_tag in html_block_tags:
                self.end_tag(p_tag)
        attrib = {}
        for attr in attrs:
            attrib[attr[0]] = strip_quotes(attr[1])
        ElementTree.TreeBuilder.start(self, tag, attrib)
        el = self._elem[-1]
        self.current = el
        el.ns = None
        el.localName = el.tag
        el.start = loc_start
        el.end = None
        self.nodes.append(el)
        if len(self._elem) > 1:
            self.nodemap[el] = self._elem[-2]
        else:
            self.nodemap[el] = None
        if l_tag in html_no_close_tags:
            self.end_tag(tag, loc_end)

    def end(self, tag, loc=None):
        if not self._elem:
            return None
        l_tag = tag
        l_lasttag = lasttag = self._elem[-1].tag
        if l_tag:
            l_tag = l_tag.lower()
        if l_lasttag:
            l_lasttag = lasttag.lower()
        while (l_tag != l_lasttag
               and l_lasttag in html_optional_close_tags
               and len(self._elem) > 1
               and self._last.start[2] < self._elem[-1].start[2]):
            self.end_tag(lasttag)
            if self._elem:
                lasttag = self._elem[-1].tag
                l_lasttag = lasttag.lower()
            else:
                self.current = self._last
                return self._last

        # protect against a previous close of this tag
        if l_tag in html_close_tag_unnecessary and l_tag != self._elem[-1].tag.lower():
            return None
        return self.end_tag(tag, loc)

    def end_tag(self, tag, loc=None):
        if not tag:
            return None
        self._flush()
        # find this tag:
        tags = [e.localName for e in self._elem]
        if tag not in tags:
            # invalid end tag?
            return None
        last = self._elem.pop()
        while last.tag != tag:
            last = self._elem.pop()
        self._last = last
        if not self._elem:
            self._rootnodes.append(self._last)
        if loc:
            self._last.end = loc

        self._tail = 1
        self.current = self._last
        return self._last

    def data(self, data):
        if isinstance(data, type('')) and is_not_ascii(data):
            # convert to unicode, but only if necessary
            data = unicode(data, self.encoding, "ignore")
        ElementTree.TreeBuilder.data(self, data)

    def close(self):
        if self._elem:
            return self._elem[0]
        return self._last

class Parser:
    def __init__(self, builder=None):
        if not builder:
            builder = ElementTree.TreeBuilder()
        self._builder = builder
        self.doctype = None
        self.publicId = None
        self.systemId = None
        self.locator = {}
        self._lastloc = None
        self.data = None

    def parse_doctype(self, data):
        m = collector.res["DOCTYPE"].match(data)
        if m is None:
            return
        result = m.groupdict()
        self.doctype = result
        self.publicId = None
        if result['ident'] == "PUBLIC":
            self.publicId = strip_quotes(result['data1'])
            self.systemId = strip_quotes(result['data2'])
        else:
            self.systemId = strip_quotes(result['data1'])

    def getLocation(self, loc):
        pos = 0
        last_lines = 0
        if self._lastloc:
            pos = self._lastloc
            last_lines = self.locator[pos][0]
        lines = last_lines + self.data.count("\n", pos, loc)
        col = 0
        if lines > last_lines:
            col = loc - self.data.rfind("\n", pos, loc) - 1
        elif pos in self.locator:
            col = loc - pos + self.locator[pos][1]
        self.locator[loc] = [lines, col]
        self._lastloc = loc
        return (lines + 1, col, loc)

    def feed(self, data, markuponly=0):
        no_close_tag = []
        opt_close_tag = []
        self.data = data
        for matchObj in parseiter(data, markuponly):
            x = matchObj.group(0)
            m = matchObj.groupdict()
            if x.startswith("<!"):
                continue
            # XXX
                if x.startswith("<!DOCTYPE"):
                    self.parse_doctype(x)
            elif x.startswith("<?"):
                # processing tag
                continue
            elif x.startswith("</"):
                self._builder.end(m[
                                  "endtag"], self.getLocation(matchObj.end(0)))
            elif x.startswith("<"):
                # get the tag and attrs
                attrs = []
                if "attrs" in m and m["attrs"] is not None:
                    attrs = attrfinder.findall(m["attrs"])
                start = self.getLocation(matchObj.start(0))
                end = self.getLocation(matchObj.end(0))
                self._builder.start(m["tag"], attrs, start, end)
                if x.endswith("/>"):
                    self._builder.end(m["tag"], end)
            else:
                self._builder.data(x)

    def close(self):
        return self._builder.close()

try:
    import sgmlop
    ReParser = Parser

    class SgmlopParser(ReParser):
        def __init__(self, builder=None):
            ReParser.__init__(self, builder)
            self.__parser = sgmlop.XMLParser()
            self.__parser.register(self)

        def finish_starttag(self, tag, attrib, loc_start, loc_end):
            # builder expects a list of tuples
            attrs = list(attrib.items())
            self._builder.start(tag, attrs, self.getLocation(
                loc_start), self.getLocation(loc_end))

        def finish_endtag(self, tag, loc):
            self._builder.end(tag, self.getLocation(loc))

        def handle_data(self, data):
            self._builder.data(data)

        def handle_special(self, data, token_type=None):
            # here's where we figure out if we've got a doctype
            if (token_type == 0x105 or  # from sgmlop.c
                    data and data.startswith("DOCTYPE")):
                # we get everything inside <!...>
                self.parse_doctype("<!%s>" % data)

        def feed(self, data, markuponly=0):
            self.data = data
            return self.__parser.feed(data)

        def close(self):
            if self.__parser:
                self.__parser.close()
                self.__parser = None
            return ReParser.close(self)

    Parser = SgmlopParser
except:
    pass

def HTML(data, ParserClass=Parser):
    p = ParserClass(HTMLTreeBuilder())
    p.feed(data)
    return p.close()

if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1:
        import time
        # read the file and parse it to get a time.
        f = open(sys.argv[1])
        data = f.read()
        f.close()
        t1 = time.time()
        tree = HTML(data, ReParser)
        t2 = time.time()
        print "RE parsing took %s" % (t2-t1)
        t1 = time.time()
        tree = HTML(data, SgmlopParser)
        t2 = time.time()
        print "sgmlop parsing took %s" % (t2-t1)
        sys.exit(0)

    data = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 <title>my title</title>

blah blah...

"""
    tree = HTML(data)
    print ElementTree.tostring(tree)
    sys.exit(0)

    data = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

"""
    tree = HTML(data)
    print ElementTree.tostring(tree)
    sys.exit(0)

    data = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

"""
    #

    #

    #

    #

    #

    #

    #

    #

    #

    #
    #
    #"""
    data = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">

<link rel="stylesheet" type="text/css" href="aspn.css">

<link rel="icon" href="favicon.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
<title>XML Catalogs</title>

XML Catalogs

Komodo can add XML
autocompletion support for any XML dialect with a DTD or RelaxNG Schema.
This is done by mapping external identifier entries to local copies of the DTD
or RelaxNG Schema for that document type using XML
Catalogs.

Using an Existing XML Catalog

Some toolkits bundle DTDs or RelaxNG Schemas with their own XML
catalogs. As long as the relative path from the catalog to the .dtd or
.rng file is preserved on the local filesystem, you can add support for
the dialect by specifying the catalog file in Preferences under SGML/XML Catalogs.

Creating an XML Catalog

If the DTD or RelaxNG Schema for the dialect does not have a catalog
file, you can create one by mapping the external identifiers and URI
references in the document's namespace declaration to a local filesystem
URI. For example, the
<acronym title="XML Shareable Playlist Format">XSPF</acronym>
playlist format uses the following namespace declaration:

  <playlist version="1" xmlns="http://xspf.org/ns/0/">

A simple catalog for this XML dialect would look like this:

  <?xml version='1.0'?>
  <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
  prefer="public">

    <uri name="http://xspf.org/ns/0/" uri="xspf-draft8.rng"/>

  </catalog>

If your documents use the DOCTYPE declaration, you can add support
for that in the catalog by using the public and system identifier. For
example,
<acronym title="XML User Interface Language">XUL</acronym> uses
DOCTYPE declarations like this one:

  <!DOCTYPE overlay PUBLIC "-//MOZILLA//DTD XUL V1.0//EN"
  "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

Komodo's catalog for XUL uses publicId and
systemId in addition to uri for the
mapping.

  <?xml version='1.0'?>
  <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="public">

      <public publicId="-//MOZILLA//DTD XUL V1.0//EN"
              uri="xul.dtd"/>
      <system systemId="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
              uri="xul.dtd"/>
      <uri name="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           uri="xul.dtd"/>

  </catalog>

XML Catalog Resources

The XML Catalog specification can be found at:

  http://www.oasis-open.org/committees/entity/spec.html

Examples of XML catalog files can be found in the Komodo installation
under:

<komodo-install-directory>\lib\support\catalogs
  (Windows)

/Applications/Komodo.app/Contents/SharedSupport/catalogs/ (OS
  X)

<komodo-install-directory>/lib/support/catalogs
  (Linux)

"""
    tree = HTML(data)
    # print ElementTree.tostring(tree)

    data = """

<?php print $javascript->link('calendar') ?>

    <?php $othAuth->init($othAuth->data);?>

    <?php echo $html->css{'hack'};?>

"""
    tree = HTML(data)
    # print ElementTree.tostring(tree)

    data = """<%= error_messages_for 'product' %>

Title

<%= text_field 'product', 'title'  %>

Description

<%= text_area 'product', 'description'  %>

Image url

<%= text_field 'product', 'image_url'  %>

Price

<%= text_field 'product', 'price'  %>

Date available

<%= datetime_select 'product', 'date_available'  %>

"""
    tree = HTML(data)
    print ElementTree.tostring(tree)
    p = Parser(HTMLTreeBuilder())
    p.feed(data)
    p.close()


text:
package org.guvnor.ala.ui.backend.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.guvnor.common.services.project.model.Module;
import org.guvnor.common.services.project.service.ModuleService;
import org.guvnor.structure.organizationalunit.OrganizationalUnit;
import org.guvnor.structure.organizationalunit.OrganizationalUnitService;
import org.guvnor.structure.repositories.Branch;
import org.guvnor.structure.repositories.Repository;
import org.guvnor.structure.repositories.RepositoryService;
import org.jboss.errai.security.shared.api.identity.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.uberfire.backend.vfs.Path;
import org.uberfire.security.authz.AuthorizationManager;
import org.uberfire.spaces.Space;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.Silent.class)
public class SourceServiceImplTest {

    private static final int OU_SIZE = 7;

    private static final int REPOSITORIES_SIZE = 10;

    private static final String OU_NAME = "OU_NAME";

    private static final String REPO_NAME = "REPO_NAME";

    private static final String BRANCH_NAME = "BRANCH_NAME";

    private static final Space SPACE = new Space(OU_NAME);

    @Mock
    private OrganizationalUnitService organizationalUnitService;

    @Mock
    private RepositoryService repositoryService;

    @Mock
    private ModuleService<? extends Module> moduleService;

    @Mock
    private AuthorizationManager authorizationManager;

    @Mock
    private User identity;

    private SourceServiceImpl service;

    private List<OrganizationalUnit> organizationalUnits;

    @Before
    public void setUp() {
        organizationalUnits = mockOrganizationalUnits(OU_NAME,
                                                      OU_SIZE);

        service = new SourceServiceImpl(organizationalUnitService,
                                        repositoryService,
                                        moduleService,
                                        authorizationManager,
                                        identity);
    }

    @Test
    public void testGetOrganizationalUnits() {
        when(organizationalUnitService.getOrganizationalUnits()).thenReturn(organizationalUnits);
        List<String> expectedResult = organizationalUnits.stream()
                .map(OrganizationalUnit::getName)
                .collect(Collectors.toList());

        Collection<String> result = service.getOrganizationUnits();
        assertEquals(expectedResult,
                     result);
    }

    @Test
    public void testGetRepositories() {
        List<Repository> repositories = mockRepositories("RepoName.",
                                                         REPOSITORIES_SIZE);
        OrganizationalUnit organizationalUnit = mock(OrganizationalUnit.class);
        when(organizationalUnit.getName()).thenReturn(OU_NAME);

        //the organizational unit not exists.
        when(organizationalUnitService.getOrganizationalUnit(OU_NAME)).thenReturn(null);
        Collection<String> result = service.getRepositories(OU_NAME);
        //nothing is returned.
        assertTrue(result.isEmpty());

        //there organizational unit exists, but no repository is authorized.
        when(organizationalUnitService.getOrganizationalUnit(OU_NAME)).thenReturn(organizationalUnit);
        when(organizationalUnit.getRepositories()).thenReturn(repositories);

        result = service.getRepositories(OU_NAME);
        //nothing is returned since there are no authorized repository.
        assertTrue(result.isEmpty());

        //finally we authorize some repositories. Take some arbitrary indexes.
        List<Integer> authorizedIndexes = new ArrayList<>();
        List<String> authorizedNames = new ArrayList<>();
        authorizedIndexes.add(1);
        authorizedIndexes.add(4);
        authorizedIndexes.add(6);

        authorizedIndexes.forEach(index -> {
            when(authorizationManager.authorize(repositories.get(index),
                                                identity)).thenReturn(true);
            authorizedNames.add(repositories.get(index).getAlias());
        });

        result = service.getRepositories(OU_NAME);
        assertEquals(authorizedNames,
                     result);
    }

    @Test
    public void testGetBranches() {
        final List<Branch> branches = new ArrayList<>();
        branches.add(new Branch("branch1",
                                mock(Path.class)));
        branches.add(new Branch("branch2",
                                mock(Path.class)));
        branches.add(new Branch("branch3",
                                mock(Path.class)));
        Repository repository = mock(Repository.class);
        when(repository.getBranches()).thenReturn(branches);

        when(repositoryService.getRepositoryFromSpace(SPACE, REPO_NAME)).thenReturn(repository);

        final Collection<String> result = service.getBranches(SPACE, REPO_NAME);

        final List<String> originalBranchNames = new ArrayList<>();
        for (final Branch branch : branches) {
            originalBranchNames.add(branch.getName());
        }

        assertEquals(originalBranchNames,
                     result);
    }

    @Test
    public void testProjects() {
        final Repository repository = mock(Repository.class);
        final Branch branch = new Branch(BRANCH_NAME,
                                         mock(Path.class));
        doReturn(Optional.of(branch)).when(repository).getBranch(eq(BRANCH_NAME));
        @SuppressWarnings("unchecked")
        final Set<Module> modules = mock(Set.class);

        when(repositoryService.getRepositoryFromSpace(SPACE, REPO_NAME)).thenReturn(repository);
        when(moduleService.getAllModules(branch)).thenReturn(modules);

        final Collection<Module> result = service.getModules(SPACE,
                                                             REPO_NAME,
                                                             BRANCH_NAME);
        assertEquals(modules,
                     result);
    }

    private List<OrganizationalUnit> mockOrganizationalUnits(String suffix,
                                                             int count) {
        List<OrganizationalUnit> result = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            OrganizationalUnit ou = mock(OrganizationalUnit.class);
            when(ou.getName()).thenReturn(suffix + i);
            result.add(ou);
        }
        return result;
    }

    private List<Repository> mockRepositories(String suffix,
                                              int count) {
        List<Repository> result = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            Repository repo = mock(Repository.class);
            when(repo.getAlias()).thenReturn(suffix + i);
            result.add(repo);
        }
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
int main(int argc, const char * argv[]) {
unsigned long int hexdouble;
int a;
a = atoi(argv[1]);
int b;
b = atoi(argv[2]);
double c;
sscanf(argv[3], "%lX", &hexdouble);
c = *(double*)(&hexdouble);
double result = gsl_sf_legendre_Plm(a, b, c);
//printf("%.15f\n", result);
VALGRIND_PRINT_VALUES("result", 1, &result);
return 0;
}


text:
 The following packages are for Julia optimization software
 http://www.juliaopt.org/
=#

Pkg.add("Optim")     # This is the closest to the software we'll build in this class

Pkg.add("JuMP")         # high level modeling language like CVX, AMPL
Pkg.add("Convex")       # Convex models like CVX
Pkg.add("MathProgBase") # probably included in above, but why not?

# These all involve installing software and are likely to be less reliable.
# But don't let that discourage you! Give them try as the authors are all
# committeed to wide compatiblity and will likely be amenable to help solving
# problems.

Pkg.add("NLopt")
Pkg.add("Ipopt")
Pkg.add("Clp")
Pkg.add("SCS")
Pkg.add("GLPK")
Pkg.add("CSDP")


text:
title: Count the coins
localeTitle: عد العملات
---
## عد العملات

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/count-the-coins/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;

namespace Pru1Aio
{
    public class Pru1AioEventArgs : EventArgs
    {
        public readonly MessageType Type;
        public readonly Reading MeanReading;
        public readonly bool WarmUp;
        public readonly int BufferStartIndex;
        public readonly int BufferSize;

        public Pru1AioEventArgs(MessageType Type, Reading MeanReading, bool WarmUp, int BufferStartIndex, int BufferSize)
        {
            this.Type = Type;
            this.MeanReading = MeanReading;
            this.WarmUp = WarmUp;
            this.BufferStartIndex = BufferStartIndex - BufferSize;
            this.BufferSize = BufferSize;
        }
    }

	[StructLayout (LayoutKind.Sequential, Pack=1)]
    public unsafe struct PruControl
    {
		public uint CurrentBuffer;			// 0x0		Complete
		public uint BufferCount;				// 0x4		Complete
		public byte BufferSize;				// 0x8		Complete
		public byte ChannelEnabledMask;		// 0x9		Complete
		public byte SampleAverage;			// 0xA		Complete
		public byte SampleSoc;				// 0xB		Complete
		public uint SampleRate;				// 0xC		Complete
		public byte SampleMode;				// 0x10		Complete
		public byte ChannelCount;				// 0x11		Complete
		public uint BufferMemoryBytes;		// 0X12		Complete
		public uint BufferPosition;			// 0X16		Complete
		public uint ReadCount;				// 0x1A		Complete
		public uint IepClockCount;			// 0x1E
		public uint WriteMask;				// 0x22
		public uint DigitalOut;				// 0x26
        [MarshalAs(UnmanagedType.ByValArray)]
		public unsafe fixed byte Scratch[14];			// 0x2A
	}

	[StructLayout (LayoutKind.Sequential, Pack=1)]
    public unsafe struct PruSharedMemory
    {
		public PruControl Control;
		public ushort* Buffer1;
		public ushort* Buffer2;
	}

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public unsafe struct Pru1AioConditional
    {
        [MarshalAs(UnmanagedType.ByValArray)]
		public unsafe fixed char Name[33];
		public Comparator Condition;
		public Signal Signal;
		public ushort Comp1;
		public ushort Comp2;

		public int LastSignal;

		public TriggerState Triggered;
		public ushort TriggerCount;
	}

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public unsafe struct Pru1AioConditions
    {
		public char Count;
		public Pru1AioConditional *Conditionals;
	}

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
	public unsafe struct Pru1AioReading {
		public byte Buffer;
        [MarshalAs(UnmanagedType.ByValArray)]
        public unsafe fixed ushort Readings[8];
		public ushort DigitalIn;
	}

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public unsafe struct CallState
    {
		public Pru1AioReading *Readings;
		public Pru1AioReading BufferMean;
		public int Records;
		public int MaximumRecords;
		public int Signals;
		public IntPtr CallerState;
		public Pru1AioConditions *Conditions;
	}

    public class Reading
    {
        public byte Buffer;
        public ushort[] Readings;
        public ushort DigitalIn;

        public Reading()
        {
            Readings = new ushort[8];
        }
    }

    public struct Conditional
    {
        public string Name;
        public Comparator Condition;
        public Signal Signal;
        public ushort Comparator1;
        public ushort Comparator2;
        public TriggerState Triggered;
        public int Triggers;
        public uint LastSignal;

        public override string ToString()
        {
            return Name + ":\n\t" + Condition.ToString() + "\n\t" + Signal + "\n\t" + Comparator1 + "\n\t" + Comparator2;
        }
    }

}


text:
package com.iluwatar.semaphore;

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

import org.junit.jupiter.api.Test;

/**
 * Test case for acquiring and releasing a Semaphore
 */
public class SemaphoreTest {

  @Test
  public void acquireReleaseTest() {
    var sphore = new Semaphore(3);

    assertEquals(3, sphore.getAvailableLicenses());

    for (var i = 2; i >= 0; i--) {
      try {
        sphore.acquire();
        assertEquals(i, sphore.getAvailableLicenses());
      } catch (InterruptedException e) {
        fail(e.toString());
      }
    }

    for (var i = 1; i <= 3; i++) {
      sphore.release();
      assertEquals(i, sphore.getAvailableLicenses());
    }

    sphore.release();
    assertEquals(3, sphore.getAvailableLicenses());
  }
}


text:
Home

Select Classes

	Generate

			Visual Filter

Favorites

Course Listings


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta http-equiv="content-security-policy" content="">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="https://cdn.jsdelivr.net/gh/slidevjs/slidev/assets/favicon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Helvetica+Neue:wght@200;400;600&display=swap" type="text/css">

  <link rel="stylesheet" href="/talks/2022-05-09-chalmers-entrepreneurship-inner-development/assets/index.be5879df.css">

	<link rel="modulepreload" href="/_app/immutable/start-3e219d8f.js">
	<link rel="modulepreload" href="/_app/immutable/chunks/index-16cdd259.js">
	<link rel="modulepreload" href="/_app/immutable/pages/__layout-raw.svelte-c01653c7.js">
	<link rel="modulepreload" href="/_app/immutable/pages/talks/_slug_/index@raw.svelte-2f63cd7e.js">


text:
package com.vmware.vim25;

/**
 * @author Steve Jin (http://www.doublecloud.org)
 * @version 5.1
 */

@SuppressWarnings("all")
public class VmRelocateSpecEvent extends VmEvent {
}


text:
import {expect} from 'chai'
import wait from 'ember-test-helpers/wait'
import {beforeEach, describe, it} from 'mocha'

import {expectCollapsibleHandles} from 'dummy/tests/helpers/ember-frost-bunsen'
import selectors from 'dummy/tests/helpers/selectors'
import {setupDetailComponentTest} from 'dummy/tests/helpers/utils'

describe('Integration: Component / frost-bunsen-detail / renderer / select enum', function () {
  setupDetailComponentTest({
    bunsenModel: {
      properties: {
        foo: {
          enum: [
            'bar',
            'baz'
          ],
          type: 'string'
        }
      },
      type: 'object'
    },
    hook: 'my-form'
  })

  describe('when no initial value', function () {
    beforeEach(function () {
      this.set('value', undefined)
      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0, 'my-form')

      expect(
        this.$(selectors.bunsen.renderer.static),
        'renders a bunsen static input'
      )
        .to.have.length(1)

      expect(
        this.$(selectors.bunsen.label).text().trim(),
        'renders expected label text'
      )
        .to.equal('Foo')

      expect(
        this.$(selectors.bunsen.value).text().trim(),
        'renders expected value'
      )
        .to.equal('—')
    })

    describe('when label defined in view', function () {
      beforeEach(function () {
        this.set('bunsenView', {
          cells: [
            {
              label: 'FooBar Baz',
              model: 'foo'
            }
          ],
          type: 'form',
          version: '2.0'
        })

        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(0, 'my-form')

        expect(
          this.$(selectors.bunsen.renderer.static),
          'renders a bunsen static input'
        )
          .to.have.length(1)

        expect(
          this.$(selectors.bunsen.label).text().trim(),
          'renders expected label text'
        )
          .to.equal('FooBar Baz')

        expect(
          this.$(selectors.bunsen.value).text().trim(),
          'renders expected value'
        )
          .to.equal('—')
      })
    })

    describe('when collapsible is set to true in view', function () {
      beforeEach(function () {
        this.set('bunsenView', {
          cells: [
            {
              collapsible: true,
              model: 'foo'
            }
          ],
          type: 'form',
          version: '2.0'
        })

        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(1, 'my-form')

        expect(
          this.$(selectors.bunsen.renderer.static),
          'renders a bunsen static input'
        )
          .to.have.length(1)

        expect(
          this.$(selectors.bunsen.label).text().trim(),
          'renders expected label text'
        )
          .to.equal('Foo')

        expect(
          this.$(selectors.bunsen.value).text().trim(),
          'renders expected value'
        )
          .to.equal('—')
      })
    })

    describe('when collapsible is set to false in view', function () {
      beforeEach(function () {
        this.set('bunsenView', {
          cells: [
            {
              collapsible: false,
              model: 'foo'
            }
          ],
          type: 'form',
          version: '2.0'
        })

        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(0, 'my-form')

        expect(
          this.$(selectors.bunsen.renderer.static),
          'renders a bunsen static input'
        )
          .to.have.length(1)

        expect(
          this.$(selectors.bunsen.label).text().trim(),
          'renders expected label text'
        )
          .to.equal('Foo')

        expect(
          this.$(selectors.bunsen.value).text().trim(),
          'renders expected value'
        )
          .to.equal('—')
      })
    })
  })

  describe('when initial value', function () {
    beforeEach(function () {
      this.set('value', {
        foo: 'bar'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0, 'my-form')

      expect(
        this.$(selectors.bunsen.renderer.static),
        'renders a bunsen static input'
      )
        .to.have.length(1)

      expect(
        this.$(selectors.bunsen.label).text().trim(),
        'renders expected label text'
      )
        .to.equal('Foo')

      expect(
        this.$(selectors.bunsen.value).text().trim(),
        'renders expected value'
      )
        .to.equal('bar')
    })

    describe('when label defined in view', function () {
      beforeEach(function () {
        this.set('bunsenView', {
          cells: [
            {
              label: 'FooBar Baz',
              model: 'foo'
            }
          ],
          type: 'form',
          version: '2.0'
        })

        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(0, 'my-form')

        expect(
          this.$(selectors.bunsen.renderer.static),
          'renders a bunsen static input'
        )
          .to.have.length(1)

        expect(
          this.$(selectors.bunsen.label).text().trim(),
          'renders expected label text'
        )
          .to.equal('FooBar Baz')

        expect(
          this.$(selectors.bunsen.value).text().trim(),
          'renders expected value'
        )
          .to.equal('bar')
      })
    })

    describe('when collapsible is set to true in view', function () {
      beforeEach(function () {
        this.set('bunsenView', {
          cells: [
            {
              collapsible: true,
              model: 'foo'
            }
          ],
          type: 'form',
          version: '2.0'
        })

        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(1, 'my-form')

        expect(
          this.$(selectors.bunsen.renderer.static),
          'renders a bunsen static input'
        )
          .to.have.length(1)

        expect(
          this.$(selectors.bunsen.label).text().trim(),
          'renders expected label text'
        )
          .to.equal('Foo')

        expect(
          this.$(selectors.bunsen.value).text().trim(),
          'renders expected value'
        )
          .to.equal('bar')
      })
    })

    describe('when collapsible is set to false in view', function () {
      beforeEach(function () {
        this.set('bunsenView', {
          cells: [
            {
              collapsible: false,
              model: 'foo'
            }
          ],
          type: 'form',
          version: '2.0'
        })

        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(0, 'my-form')

        expect(
          this.$(selectors.bunsen.renderer.static),
          'renders a bunsen static input'
        )
          .to.have.length(1)

        expect(
          this.$(selectors.bunsen.label).text().trim(),
          'renders expected label text'
        )
          .to.equal('Foo')

        expect(
          this.$(selectors.bunsen.value).text().trim(),
          'renders expected value'
        )
          .to.equal('bar')
      })
    })
  })
})


text:
package net.minecraft.client.renderer;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;

public class ActiveRenderInfo
{
    private static final IntBuffer field_178814_a = GLAllocation.createDirectIntBuffer(16);
    private static final FloatBuffer field_178812_b = GLAllocation.createDirectFloatBuffer(16);
    private static final FloatBuffer field_178813_c = GLAllocation.createDirectFloatBuffer(16);
    private static final FloatBuffer field_178810_d = GLAllocation.createDirectFloatBuffer(3);
    private static Vec3 field_178811_e = new Vec3(0.0D, 0.0D, 0.0D);

    /** The X component of the entity's yaw rotation */
    private static float rotationX;

    /** The combined X and Z components of the entity's pitch rotation */
    private static float rotationXZ;

    /** The Z component of the entity's yaw rotation */
    private static float rotationZ;

    /**
     * The Y component (scaled along the Z axis) of the entity's pitch rotation
     */
    private static float rotationYZ;

    /**
     * The Y component (scaled along the X axis) of the entity's pitch rotation
     */
    private static float rotationXY;
    private static final String __OBFID = "CL_00000626";

    /**
     * Updates the current render info and camera location based on entity look angles and 1st/3rd person view mode
     */
    public static void updateRenderInfo(EntityPlayer p_74583_0_, boolean p_74583_1_)
    {
        GlStateManager.getFloat(2982, field_178812_b);
        GlStateManager.getFloat(2983, field_178813_c);
        GL11.glGetInteger(GL11.GL_VIEWPORT, field_178814_a);
        float var2 = (float)((field_178814_a.get(0) + field_178814_a.get(2)) / 2);
        float var3 = (float)((field_178814_a.get(1) + field_178814_a.get(3)) / 2);
        GLU.gluUnProject(var2, var3, 0.0F, field_178812_b, field_178813_c, field_178814_a, field_178810_d);
        field_178811_e = new Vec3((double)field_178810_d.get(0), (double)field_178810_d.get(1), (double)field_178810_d.get(2));
        int var4 = p_74583_1_ ? 1 : 0;
        float var5 = p_74583_0_.rotationPitch;
        float var6 = p_74583_0_.rotationYaw;
        rotationX = MathHelper.cos(var6 * (float)Math.PI / 180.0F) * (float)(1 - var4 * 2);
        rotationZ = MathHelper.sin(var6 * (float)Math.PI / 180.0F) * (float)(1 - var4 * 2);
        rotationYZ = -rotationZ * MathHelper.sin(var5 * (float)Math.PI / 180.0F) * (float)(1 - var4 * 2);
        rotationXY = rotationX * MathHelper.sin(var5 * (float)Math.PI / 180.0F) * (float)(1 - var4 * 2);
        rotationXZ = MathHelper.cos(var5 * (float)Math.PI / 180.0F);
    }

    public static Vec3 func_178806_a(Entity p_178806_0_, double p_178806_1_)
    {
        double var3 = p_178806_0_.prevPosX + (p_178806_0_.posX - p_178806_0_.prevPosX) * p_178806_1_;
        double var5 = p_178806_0_.prevPosY + (p_178806_0_.posY - p_178806_0_.prevPosY) * p_178806_1_;
        double var7 = p_178806_0_.prevPosZ + (p_178806_0_.posZ - p_178806_0_.prevPosZ) * p_178806_1_;
        double var9 = var3 + field_178811_e.xCoord;
        double var11 = var5 + field_178811_e.yCoord;
        double var13 = var7 + field_178811_e.zCoord;
        return new Vec3(var9, var11, var13);
    }

    public static Block func_180786_a(World worldIn, Entity p_180786_1_, float p_180786_2_)
    {
        Vec3 var3 = func_178806_a(p_180786_1_, (double)p_180786_2_);
        BlockPos var4 = new BlockPos(var3);
        IBlockState var5 = worldIn.getBlockState(var4);
        Block var6 = var5.getBlock();

        if (var6.getMaterial().isLiquid())
        {
            float var7 = 0.0F;

            if (var5.getBlock() instanceof BlockLiquid)
            {
                var7 = BlockLiquid.getLiquidHeightPercent(((Integer)var5.getValue(BlockLiquid.LEVEL)).intValue()) - 0.11111111F;
            }

            float var8 = (float)(var4.getY() + 1) - var7;

            if (var3.yCoord >= (double)var8)
            {
                var6 = worldIn.getBlockState(var4.offsetUp()).getBlock();
            }
        }

        return var6;
    }

    public static Vec3 func_178804_a()
    {
        return field_178811_e;
    }

    public static float func_178808_b()
    {
        return rotationX;
    }

    public static float func_178809_c()
    {
        return rotationXZ;
    }

    public static float func_178803_d()
    {
        return rotationZ;
    }

    public static float func_178805_e()
    {
        return rotationYZ;
    }

    public static float func_178807_f()
    {
        return rotationXY;
    }
}


text:
#ifndef _NUTI_POINTDRAWDATA_H_
#define _NUTI_POINTDRAWDATA_H_

#include "core/MapPos.h"
#include "renderers/drawdatas/VectorElementDrawData.h"

#include <memory>

namespace Nuti {
    class Bitmap;
    class PointGeometry;
    class PointStyle;
    class Projection;

    class PointDrawData : public VectorElementDrawData {
    public:
        PointDrawData(const PointGeometry& geometry, const PointStyle& style, const Projection& projection);
        virtual ~PointDrawData();

        const std::shared_ptr<Bitmap> getBitmap() const;

        float getClickScale() const;

        const MapPos& getPos() const;

        float getSize() const;

        virtual void offsetHorizontally(double offset);

    private:
        static const int IDEAL_CLICK_SIZE = 64;

        static const float CLICK_SIZE_COEF;

        std::shared_ptr<Bitmap> _bitmap;

        float _clickScale;

        MapPos _pos;

        float _size;
    };

}

#endif


text:
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var db = null;

module.exports = function(app) {

  if (!db) {
    var config = app.src.config.config;
    var sequelize = new Sequelize(
      config.database,
      config.username,
      config.password,
      config.params
    );
    db = {
      sequelize,
      Sequelize,
      models: {}
    };

    var dirModels = path.join(__dirname, "models");
    fs.readdirSync(dirModels).forEach(dir => {
      if(fs.statSync(`${dirModels}/${dir}`).isDirectory()) {
        var subDirModels = path.join(dirModels, dir);
        fs.readdirSync(subDirModels).forEach(file => {
          var pathFile = path.join(subDirModels, file);
          var model = sequelize.import(pathFile);
          db.models[model.name] = model;
        });
      }
    });

    Object.keys(db.models).forEach(key => {
      if(db.models[key].associate) {
        db.models[key].associate(db.models);
      }
    });
  }

  return db;
};


text:
A super simple [datamapper](http://martinfowler.com/eaaCatalog/dataMapper.html)
built on top of Sequel. For creating
[repository](http://martinfowler.com/eaaCatalog/repository.html) like objects.

## Installation

Add this line to your application's Gemfile:

    gem 'sequel-mapper'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install sequel-mapper

## Usage

```ruby
require 'sequel/mapper'

class Account
  def initialize(attrs={})
    #some way to covert attrs to @attibutes
  end
end

class Accounts
  include Sequel::Mapper
  dataset :accounts
end

DB = Sequel.connect

accounts = Accounts.new(DB)

accounts.all #=> all accounts

# CRUD

account = Account.new(email: 'dave@example.com')

accounts.create(account)

accounts.find(1)

accounts.update(account)

accounts.delete(account)
```

TODO: Improve usage instructions :)

## Contributing

1. Fork it ( https://github.com/stengland/sequel-mapper/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
module Mongoid
  module Fields
    class Timespan
      include Mongoid::Fields::Serializable

      def self.instantiate(name, options = {})
        super
      end

      # Deserialize a Timespan given the hash stored by Mongodb
      #
      # @param [Hash] Timespan as hash
      # @return [Timespan] deserialized Timespan
      def deserialize(hash)
        return if !hash
        ::Timespan.new :from => from(hash), :to => to(hash)
      end

      # Serialize a Timespan or a Hash (with Timespan units) or a Duration in some form to
      # a BSON serializable type.
      #
      # @param [Timespan, Hash, Integer, String] value
      # @return [Hash] Timespan in seconds
      def serialize(value)
        return if value.blank?
        timespan = case value
        when ::Timespan
          value
        else
          ::Timespan.new(value)
        end
        {:from => serialize_time(timespan.start_time), :to => serialize_time(timespan.end_time.to_i), :duration => timespan.duration.total }
      end
    end
  end
end


text:
<?php
// $Header: /var/cvs/arsgate/client_cpanel/include/html2pdf/css.border.left.color.inc.php,v 1.2 2008-06-08 18:29:01 cvs Exp $

class CSSBorderLeftColor extends CSSSubProperty {
  function CSSBorderLeftColor(&$owner) {
    $this->CSSSubProperty($owner);
  }

  function setValue(&$owner_value, &$value) {
    $owner_value->left->setColor($value);
  }

  function getValue(&$owner_value) {
    return $owner_value->left->color->copy();
  }

  function getPropertyCode() {
    return CSS_BORDER_LEFT_COLOR;
  }

  function getPropertyName() {
    return 'border-left-color';
  }

  function parse($value) {
    if ($value == 'inherit') {
      return CSS_PROPERTY_INHERIT;
    }

    return parse_color_declaration($value);
  }
}

?>


text:
<?php

namespace Ums\Controllers;

use Phalcon\Mvc\Controller;
use Phalcon\Mvc\View;
use Phalcon\Db\RawValue;
use Phalcon\Mvc\Model\Query;

use Ums\i18n;

class IndexController extends ControllerBase {
    public function initialize() {
        parent::initialize();
        $this->tag->prependTitle($this->i18n->title_welcome);
    }
    public function indexAction() {
    }
}


text:
package moe.pingu.iii.lab;

import moe.pingu.iii.shared.gen.Triangle;

public class hw042101 {

	public static void main(String[] args) {
		Triangle obj = new Triangle(10, false);
		// obj.setAlt(true, true, '.');
		obj.fillAll();
		// System.out.print("end");
	}

}


text:
<!DOCTYPE html>
<html>
  <head>
    <script>
      chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
        chrome.pageAction.show(tabId);
      });
      chrome.pageAction.onClicked.addListener(function(tab){
        chrome.tabs.sendRequest(tab.id, {addvid: "true"}, function(response) {
          console.log(response.farewell);
        });
      });
    </script>
  </head>
</html>


text: Tests a full top-level XML declaration.


text:
<?php
date_default_timezone_set('Europe/London');
$data = $_POST['spider'];
$customer = $_POST['customer'];
$chartType = $_POST['chartType'];
list($type, $data) = explode(';', $data);
list($type, $data) = explode(',', $data);
$data = str_replace(' ','+',$data);
$data = base64_decode($data);
#file_put_contents("charts/".$customer."-".$chartType."-".date('Y-m-d').'.png', $data);
file_put_contents("charts/".$customer."-".$chartType.'.png', $data);
die;
?>


text:
require 'git_version_bumper/version_bumper/bumper'

module GitVersionBumper
  module VersionBumper
    # Implementation of Bumper that increases the patch version number.
    class PatchVersionBumper < Bumper
      private

      def tag
        git.add_tag(
          "v#{current_major_version}." \
          "#{current_minor_version}." \
          "#{current_patch_version + 1}"
        )
      end
    end
  end
end


text:
<!--
Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
for details. All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
-->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
    <title>Single page app using Polymer</title>
    <link rel="stylesheet" href="styles/main.css">
    <link rel="import" href="packages/polymer/polymer.html"/>
    <link rel="import" href="packages/fridge_watcher/fridge_element.html">
    <link rel="import" href="packages/fridge_watcher/fridge_elements.html">

    <link rel="import" href="packages/core_elements/core_scaffold.html">
    <link rel="import" href="packages/core_elements/core_icons.html">
    <link rel="import" href="packages/core_elements/core_animated_pages.html">
    <link rel="import" href="packages/core_elements/core_slide.html">
    <link rel="import" href="packages/core_elements/core_transition.html">
    <link rel="import" href="packages/core_elements/core_icon.html">
    <link rel="import" href="packages/core_elements/core_icon_button.html">
    <link rel="import" href="packages/core_elements/core_menu.html">

    <link rel="import" href="packages/paper_elements/paper_input.html">
    <link rel="import" href="packages/paper_elements/paper_item.html">
    <link rel="import" href="packages/paper_elements/paper_fab.html">
    <link rel="import" href="packages/paper_elements/paper_icon_button.html">
    <link rel="import" href="packages/paper_elements/paper_checkbox.html">
    <link rel="import" href="packages/paper_elements/paper_toast.html">

    <link rel="import" href="watcher_app.html">

</head>
<body unresolved fullbleed>

<watcher-app></watcher-app>

<script type='application/dart' src="main.dart">
</script>
</body>
</html>


text:
<?php

/* AirAdminBundle:AdminPanel:index.html.twig */
class __TwigTemplate_0d0525a2b7ca74e641032fb4138e6c6b8f802e36325be98cc1720dd4a0f15d2e extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
    }

    public function getTemplateName()
    {
        return "AirAdminBundle:AdminPanel:index.html.twig";
    }

    public function getDebugInfo()
    {
        return array ();
    }
}


text:
/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://visualizationlibrary.org                                                   */
/*                                                                                */
/*  Copyright (c) 2005-2020, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#include <vlGraphics/ActorKdTree.hpp>
#include <vlCore/Log.hpp>
#include <algorithm>

using namespace vl;

namespace
{
  //-----------------------------------------------------------------------------
  // sortX
  //-----------------------------------------------------------------------------
  bool sortX(const ref<Actor>& a1, const ref<Actor>& a2) /*const*/
  {
    VL_CHECK(a1->lod(0))
    VL_CHECK(a2->lod(0))
    return a1->boundingBox().minCorner().x() < a2->boundingBox().minCorner().x();
  }
  //-----------------------------------------------------------------------------
  // sortY
  //-----------------------------------------------------------------------------
  bool sortY(const ref<Actor>& a1, const ref<Actor>& a2) /*const*/
  {
    VL_CHECK(a1->lod(0))
    VL_CHECK(a2->lod(0))
    return a1->boundingBox().minCorner().y() < a2->boundingBox().minCorner().y();
  }
  //-----------------------------------------------------------------------------
  // sortZ
  //-----------------------------------------------------------------------------
  bool sortZ(const ref<Actor>& a1, const ref<Actor>& a2) /*const*/
  {
    VL_CHECK(a1->lod(0))
    VL_CHECK(a2->lod(0))
    return a1->boundingBox().minCorner().z() < a2->boundingBox().minCorner().z();
  }
}

//-----------------------------------------------------------------------------
ref<ActorKdTree> ActorKdTree::kdtreeFromNonLeafyActors(int max_depth, float minimum_volume)
{
  ActorCollection acts;
  harvestNonLeafActors(acts);
  ref<ActorKdTree> newtree = new ActorKdTree;
  newtree->buildKdTree(acts, max_depth, minimum_volume);
  return newtree;
}
//-----------------------------------------------------------------------------
void ActorKdTree::harvestNonLeafActors(ActorCollection& acts)
{
  VL_CHECK( (actors()->size() && (mChildN == 0 && mChildP == 0)) || !(mChildN == 0 && mChildP == 0) );

  if ( mChildN || mChildP )
  {
    for(int i=0; i<(int)actors()->size(); ++i)
      acts.push_back(actors()->at(i));
    actors()->clear();
  }

  if(mChildN) childN()->harvestNonLeafActors( acts );
  if(mChildP) childP()->harvestNonLeafActors( acts );
}
//-----------------------------------------------------------------------------
void ActorKdTree::computeLocalAABB(const ActorCollection& acts)
{
  mAABB.setNull();
  for(int i=0; i<(int)acts.size(); ++i)
  {
    VL_CHECK( acts[i]->lod(0) )
    mAABB += acts[i]->boundingBox();
  }
}
//-----------------------------------------------------------------------------
void ActorKdTree::buildKdTree(ActorCollection& acts, int max_depth, float minimum_volume)
{
  int counter = 0;
  prepareActors(acts);
  compileTree_internal(acts, counter, max_depth, minimum_volume);
}
//-----------------------------------------------------------------------------
void ActorKdTree::rebuildKdTree(int max_depth, float minimum_volume)
{
  ActorCollection acts;
  extractActors(acts);
  buildKdTree(acts, max_depth, minimum_volume);
}
//-----------------------------------------------------------------------------
void ActorKdTree::compileTree_internal(ActorCollection& acts, int& counter, int max_depth, float minimum_volume)
{
  mChildN = NULL;
  mChildP = NULL;
  actors()->clear();
  mAABB.setNull();
  mPlane = Plane();

  if (acts.size() == 0)
    return;

  computeLocalAABB(acts);

  if (acts.size() == 1 || max_depth == 0 || mAABB.volume() < minimum_volume)
  {
    mActors = acts;
    return;
  }

  if ( !findBestPlane(mPlane, counter, acts) )
  {
    mActors = acts;
    return;
  }

  ActorCollection actorsN;
  ActorCollection actorsP;
  actorsN.reserve(acts.size());
  actorsP.reserve(acts.size());

  for(int i=0; i<(int)acts.size(); ++i)
  {
    VL_CHECK(acts[i]->lod(0))
    switch( mPlane.classify(acts[i]->boundingBox()) )
    {
    case  0: actors()->push_back(acts[i].get()); break;
    case -1: actorsN.  push_back(acts[i].get()); break;
    case +1: actorsP.  push_back(acts[i].get()); break;
    }
  }

  int counter1 = counter;
  int counter2 = counter;
  if (actorsN.size())
  {
    setChildN(new ActorKdTree);
    childN()->compileTree_internal(actorsN, counter1, max_depth-1, minimum_volume);
  }

  if (actorsP.size())
  {
    setChildP(new ActorKdTree);
    childP()->compileTree_internal(actorsP, counter2, max_depth-1, minimum_volume);
  }

}
//-----------------------------------------------------------------------------
int ActorKdTree::scorePlane(const Plane& plane, const ActorCollection& acts)
{
  int cN=0, cC=0, cP=0;
  for(int i=0; i<(int)acts.size(); ++i)
  {
    VL_CHECK(acts[i]->lod(0))
    switch( plane.classify(acts[i]->boundingBox()) )
    {
    case -1: cN++; break;
    case 0:  cC++; break;
    case +1: cP++; break;
    }
  }
  return cC + ::abs(cN-cP);
}
//-----------------------------------------------------------------------------
//! Finds the best plane among different x/y/z orientation in order to divide the given list of actors included in the given AABB.
bool ActorKdTree::findBestPlane(Plane& plane, int& counter, ActorCollection& acts)
{
  int median = (int)acts.size() / 2;
  if (counter%3 == 0)
  {
    std::sort(acts.vector().begin(), acts.vector().end(), sortX);
    VL_CHECK(acts[median]->lod(0))
    plane = Plane(acts[median]->boundingBox().minCorner().x(), vec3(1,0,0));
    counter++;
    if (scorePlane(plane, acts) == (int)acts.size())
    {
      std::sort(acts.vector().begin(), acts.vector().end(), sortY);
      VL_CHECK(acts[median]->lod(0))
      plane = Plane(acts[median]->boundingBox().minCorner().y(), vec3(0,1,0));
      counter++;
      if (scorePlane(plane, acts) == (int)acts.size())
      {
        std::sort(acts.vector().begin(), acts.vector().end(), sortZ);
        VL_CHECK(acts[median]->lod(0))
        plane = Plane(acts[median]->boundingBox().minCorner().z(), vec3(0,0,1));
        counter++;
        if (scorePlane(plane, acts) == (int)acts.size())
          return false;
      }
    }
  }
  else
  if (counter%3 == 1)
  {
    std::sort(acts.vector().begin(), acts.vector().end(), sortY);
    VL_CHECK(acts[median]->lod(0))
    plane = Plane(acts[median]->boundingBox().minCorner().y(), vec3(0,1,0));
    counter++;
    if (scorePlane(plane, acts) == (int)acts.size())
    {
      std::sort(acts.vector().begin(), acts.vector().end(), sortZ);
      VL_CHECK(acts[median]->lod(0))
      plane = Plane(acts[median]->boundingBox().minCorner().z(), vec3(0,0,1));
      counter++;
      if (scorePlane(plane, acts) == (int)acts.size())
      {
        std::sort(acts.vector().begin(), acts.vector().end(), sortX);
        VL_CHECK(acts[median]->lod(0))
        plane = Plane(acts[median]->boundingBox().minCorner().x(), vec3(1,0,0));
        counter++;
        if (scorePlane(plane, acts) == (int)acts.size())
          return false;
      }
    }
  }
  else
  if (counter%3 == 2)
  {
    std::sort(acts.vector().begin(), acts.vector().end(), sortZ);
    VL_CHECK(acts[median]->lod(0))
    plane = Plane(acts[median]->boundingBox().minCorner().z(), vec3(0,0,1));
    counter++;
    if (scorePlane(plane, acts) == (int)acts.size())
    {
      std::sort(acts.vector().begin(), acts.vector().end(), sortX);
      VL_CHECK(acts[median]->lod(0))
      plane = Plane(acts[median]->boundingBox().minCorner().x(), vec3(1,0,0));
      counter++;
      if (scorePlane(plane, acts) == (int)acts.size())
      {
        std::sort(acts.vector().begin(), acts.vector().end(), sortY);
        VL_CHECK(acts[median]->lod(0))
        plane = Plane(acts[median]->boundingBox().minCorner().y(), vec3(0,1,0));
        counter++;
        if (scorePlane(plane, acts) == (int)acts.size())
          return false;
      }
    }
  }
  return true;
}
//-----------------------------------------------------------------------------
ActorKdTree* ActorKdTree::insertActor(Actor* actor)
{
  VL_CHECK(actor->lod(0))
  if (childN() == 0 && childP() == 0)
    actors()->push_back(actor);
  else
  {
    switch( mPlane.classify(actor->boundingBox()) )
    {
      case -1: if (!childN()) setChildN(new ActorKdTree); return childN()->insertActor(actor);
      case 0:  actors()->push_back(actor); break;
      case +1: if (!childP()) setChildP(new ActorKdTree); return childP()->insertActor(actor);
    }
  }
  return this;
}
//-----------------------------------------------------------------------------
int ActorKdTree::childrenCount() const
{
  if (mChildN && mChildP)
    return 2;
  else
  if (mChildN || mChildP)
    return 1;
  else
    return 0;
}
//-----------------------------------------------------------------------------
ActorTreeAbstract* ActorKdTree::child(int i)
{
  if (i == 0)
    return mChildN ? mChildN.get() : mChildP.get();
  else
  if (i == 1)
    return mChildP.get();
  else
  {
    vl::Log::error( "ActorKdTree::child(int): bad child node requested, a ActorKdTree can have only 2 child nodes.\n" );
    return NULL;
  }
}
//-----------------------------------------------------------------------------
const ActorTreeAbstract* ActorKdTree::child(int i) const
{
  if (i == 0)
    return mChildN ? mChildN.get() : mChildP.get();
  else
  if (i == 1)
    return mChildP.get();
  else
  {
    vl::Log::error( "ActorKdTree::child(int): bad child node requested, a ActorKdTree can have only 2 child nodes.\n" );
    return NULL;
  }
}
//-----------------------------------------------------------------------------


text:
<?xml version="1.0" encoding="utf-8"?>
<merger version="3"><dataSet config="main"><source path="/home/alin/AndroidStudioProjects/PracticalTest01Var01/app/src/androidTest/assets"/></dataSet></merger>


text:
{% from 'events/notes/_note.html' import render_toggle_button %}

{% macro _render_note_editor(item) -%}

        {% if item.has_note %}
            {% set title = _('Edit minutes') %}
        {% else %}
            {% set title = _('Add minutes') %}
        {% endif %}

            {{- title -}}

{%- endmacro %}

{% macro _render_dropdown(item, item_type, show_note_operations=false) -%}

        {% if item_type == 'EVENT' %}
            {% if item.can_manage(session.user) %}

                        {% trans %}Edit Event{% endtrans %}

                        {% trans %}Clone Event{% endtrans %}

            {% endif %}
            {% if item.can_edit_note(session.user) %}
                {% if item.type != 'lecture' %}
                    {{ _render_note_editor(item) }}
                    {% if item.scheduled_notes %}

                                {% trans %}Compile Minutes{% endtrans %}

                    {% endif %}
                {% endif %}
            {% endif %}
        {% elif item_type == 'SESSION_BLOCK' %}
            {% set session_ = item.session %}
            {% if item.can_edit_note(session.user) %}
                {% if not session_.has_note or show_note_operations %}
                    {{ _render_note_editor(session_) }}
                {% endif %}

                        {%- trans %}Material Editor{% endtrans -%}

            {% endif %}
            {% if item.can_manage(session.user) %}

                        {% trans %}Edit session block{% endtrans %}

            {% endif %}
            {% if session_.can_manage(session.user, 'coordinate') %}

                        {% trans %}Edit session timetable{% endtrans %}

            {% endif %}
            {% if session_.can_manage(session.user) %}

                        {% trans %}Edit session protection{% endtrans %}

            {% endif %}
        {% elif item_type == 'CONTRIBUTION' %}
            {% if item.can_manage_attachments(session.user) %}
                {% if not item.has_note or show_note_operations %}
                    {{ _render_note_editor(item) }}
                {% endif %}
            {% endif %}
            {% if item.can_manage(session.user) %}

                        {% trans %}Edit contribution{% endtrans %}

                        {% trans %}Edit protection{% endtrans %}

            {% endif %}
        {% elif item_type == 'SUBCONTRIBUTION' %}
            {% if item.can_edit_note(session.user) %}
                {% if not item.has_note or show_note_operations %}
                    {{ _render_note_editor(item) }}
                {% endif %}
            {% endif %}
            {% if item.can_manage(session.user) %}

                        {% trans %}Edit subcontribution{% endtrans %}

            {% endif %}
        {% endif %}
        {% if item_type != 'SESSION_BLOCK' and item.can_manage_attachments(session.user) %}

                    {%- trans %}Material editor{% endtrans -%}

        {% endif %}
        {% if item_type == 'CONTRIBUTION' and item.can_manage(session.user) %}

                    {% trans %}Manage subcontributions{% endtrans %}

        {% endif %}

{%- endmacro %}

{% macro render_manage_button(item, item_type, show_notes=true,
                              toggle_notes=true, show_note_operations=false,
                              show_button=true, anchor=none) -%}

        {% if toggle_notes and item.has_note %}
            {% set req = request.args.get('note') %}
            {% set note_id = item.note.id|string %}
            {{ render_toggle_button(item.note, note_is_hidden=(req != note_id and not show_notes), anchor=anchor) }}
        {% endif %}
        {% if show_button %}

                {{ _render_dropdown(item, item_type, show_note_operations=show_note_operations) }}

        {% endif %}

{%- endmacro %}


text:
<?php

namespace PhpPlatform\RESTFul;

use PhpPlatform\Config\Settings;
use PhpPlatform\Errors\Exceptions\Http\_4XX\NotAcceptable;
use PhpPlatform\Errors\Exceptions\Http\_5XX\InternalServerError;

class HTTPRequest {
	private $method = null;
	private $protocol = null;
	private $host = null;
	private $appPath = null;
	private $uri = null;
	private $queryParams = null;
	private $headers = null;
	private $data = null;

	private static $instance = null;

	private function __construct(){
		$this->method = $_SERVER['REQUEST_METHOD'];

		$this->protocol = isset($_SERVER['HTTPS'])?"https":"http";

		$this->host = $_SERVER['HTTP_HOST'];

		$this->appPath = $_SERVER['PLATFORM_APPLICATION_PATH'];

		$this->uri = $_SERVER['REQUEST_URI'];

		$this->queryParams = $_GET;
		$_GET = array();
		$this->headers = getallheaders();

		// deserialize the content
		if(strtoupper($this->method) != 'GET' && strtoupper($this->method) != 'TRACE'){
			$data = file_get_contents('php://input');
			if(array_key_exists('Content-Type', $this->headers)){
				$contentType = $this->headers['Content-Type'];
				$positionOfSemiColonInContentType = strpos($contentType, ';');
				if($positionOfSemiColonInContentType !== false){
					$contentType = substr($contentType, 0, $positionOfSemiColonInContentType);
				}
				$internalContentType = $_SERVER['PLATFORM_SERVICE_CONSUMES'];

				$deserializer = Settings::getSettings(Package::Name,"deserializers.$contentType.$internalContentType");

				if(!class_exists($deserializer, true)){
					throw new NotAcceptable("$contentType Not Acceptable");
				}

				$deserializerReflectionClass = new \ReflectionClass($deserializer);
				$deserializerInterface = 'PhpPlatform\RESTFul\Serialization\Deserialize';
				if(!in_array($deserializerInterface, $deserializerReflectionClass->getInterfaceNames())){
					throw new InternalServerError("$deserializer does not implement $deserializerInterface");
				}

				$reflectionMethod = $deserializerReflectionClass->getMethod('deserialize');

				$this->data = $reflectionMethod->invoke(null,$data);
			}else{
				$this->data = $data;
			}

		}
	}

	/**
	 * returns the singleton instance of the HTTPRequest Object
	 *
	 * @return HTTPRequest
	 */
	static function getInstance(){
		if(self::$instance === null){
			self::$instance = new HTTPRequest();
		}
		return self::$instance;
	}

	/**
	 * Returns HTTP method
	 * @return string
	 */
	function getMethod() {
		return $this->method;
	}

	/**
	 * Returns Protocol of this request
	 * @return string either http ot https
	 */
	function getProtocol() {
		return $this->protocol;
	}

	/**
	 * Returns Host
	 * @return string
	 */
	function getHost() {
		return $this->host;
	}

	/**
	 * Returns Application path
	 * @return string
	 */
	function getAppPath() {
		return $this->appPath;
	}

	/**
	 * Returns the uri of this request
	 * @return string
	 */
	function getUri(){
		return $this->uri;
	}

	/**
	 * Returns the query parameter value for the provided parameter name
	 * @param string $name
	 * @return string
	 */
	function getQueryParam($name){
		if(array_key_exists($name, $this->queryParams)){
			return $this->queryParams[$name];
		}else{
			return null;
		}
	}

	/**
	 * Returns the header value for the provided header name
	 * @param string $name
	 * @return string
	 */
	function getHeader($name){
		if(array_key_exists($name, $this->headers)){
			return $this->headers[$name];
		}else{
			return null;
		}
	}

	/**
	 * Returns Data with this request
	 *
	 * @return mixed the type of the return object depends on $_SERVER['PLATFORM_SERVICE_CONSUMES']
	 */
	function getData(){
		return $this->data;
	}

}


text:
$(function () {

    defineStartDatePicker();
    defineEndDatePicker();

    // submit hook
    $('form').on('submit', onSubmit);

    $.each(["started", "left"], function (index, prefix) {
        applyToDatePicker(prefix);
    });
});

function defineStartDatePicker(){
    $('#startedDatePicker').datetimepicker({
        pickTime: false
    });
    $('#startedDatePicker').on('dp.show', function (e) {
        var moment = e.date;
        $('#startedMoment').val(moment.valueOf());
    });
    $('#startedDatePicker').on("dp.change", function (e) {
        var moment = e.date;
        $('#startedMoment').val(moment.valueOf());
    });
    $('#startedDatePicker').on("change", function (e) {
        var input = $("#startedMoment").val();
        if ($.isNumeric(input)) {
            var startMoment = moment(Number(input));
            $('#startedDatePicker').data("DateTimePicker").setDate(startMoment);
        } else {
            $("#startedMoment").val("");
        }
    });
    $('#startedClearButton').on("click", function (e) {
        $("#startedDate").val("");
        $("#startedMoment").val("");
    });
}

function defineEndDatePicker() {
    $('#leftDatePicker').datetimepicker({
        pickTime: false
    });
    $('#leftDatePicker').on('dp.show', function (e) {
        var moment = e.date;
        $('#leftMoment').val(moment.valueOf());
    });
    $('#leftDatePicker').on("dp.change", function (e) {
        var moment = e.date;
        $('#leftMoment').val(moment.valueOf());
    });
    $('#leftDatePicker').on("change", function (e) {
        var input = $("#leftMoment").val();
        if ($.isNumeric(input)) {
            var endMoment = moment(Number(input));
            $('#leftDatePicker').data("DateTimePicker").setDate(endMoment);
        } else {
            $("#leftMoment").val("");
        }
    });
    $('#leftClearButton').on("click", function (e) {
        $("#leftDate").val("");
        $("#leftMoment").val("");
    });
}

function applyToDatePicker(prefix) {
    var targetMoment = inputToMoment(prefix);
    if (!targetMoment) {
        return;
    }
    $('#' + prefix + 'DatePicker').data("DateTimePicker").setDate(targetMoment);
    $('#' + prefix + 'Moment').val(targetMoment.valueOf());
}

function inputToMoment(prefix) {
    var year = $("input[name='" + prefix + "_employment_year']").val();
    var month = $("input[name='" + prefix + "_employment_month']").val();
    var day = $("input[name='" + prefix + "_employment_day']").val();
    var date = moment(year + "-" + month + "-" + day, "YYYY-MM-DD");
    return date.isValid() ? date : null;
}

function onSubmit() {
    var form = $("form");
    $.each(["started", "left"], function (index, prefix) {
        applyMomentToHidden(prefix);
    });

    // TODO validate

    form.off('submit', onSubmit);
    form.submit();
}

function applyMomentToHidden(prefix) {
    var target = $("#" + prefix + "Moment").val();
    var targetMoment = $.isNumeric(target) ? moment(Number(target)) : null;

    var year = "";
    var month = "";
    var day = "";
    if (targetMoment) {
        year = targetMoment.year();
        month = targetMoment.month() + 1;
        day = targetMoment.date();
    }
    $("input[name='" + prefix + "_employment_year']").val(year);
    $("input[name='" + prefix + "_employment_month']").val(month);
    $("input[name='" + prefix + "_employment_day']").val(day);
}


text:
package org.apache.yoko.rmi.impl;

import java.util.logging.Logger;
import java.util.logging.Level;

import org.omg.CORBA.LocalObject;
import org.omg.CORBA.UserException;
import org.omg.IOP.Codec;
import org.omg.IOP.CodecFactory;
import org.omg.IOP.ENCODING_CDR_ENCAPS;
import org.omg.IOP.Encoding;
import org.omg.PortableInterceptor.ORBInitInfo;
import org.omg.PortableInterceptor.ORBInitializer;

public class RMIInitializer extends LocalObject implements ORBInitializer {
    static final Logger logger = Logger.getLogger(RMIInitializer.class
            .getName());

    public void pre_init(ORBInitInfo info) {
        Encoding encoding = new Encoding(ENCODING_CDR_ENCAPS.value, (byte)1,(byte) 0);
        CodecFactory codecFactory = info.codec_factory();
        try {
            Codec codec = codecFactory.create_codec(encoding);
            RMIInterceptor rmiInterceptor = new RMIInterceptor(codec);
            info.add_ior_interceptor(rmiInterceptor);
        } catch (UserException e) {
            logger.log(Level.FINER, "cannot register RMI Interceptor" + e.getMessage(), e);
        }
    }

    public void post_init(ORBInitInfo info) {
    }
}


text:
<?php namespace App\Kernel;

interface ServiceInterface
{

    /**
     * Service register name
     */
    public function name();

    /**
     * Register new service on dependency container
     */
    public function register();
}


text:
package org.vaadin.gwtol3.client;

import java.util.Iterator;

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

/**
 * Wrapper for the ol3 collection
 */
public class Collection<T extends JavaScriptObject> extends JavaScriptObject implements Iterable<T> {

	protected Collection() {
	}

	public static native <C extends JavaScriptObject> Collection<C> create() /*-{
		return new $wnd.ol.Collection();
	}-*/;

	public static native <C extends JavaScriptObject> Collection<C> create(JsArray<C> array) /*-{
		var coll = new $wnd.ol.Collection();
		return coll.extend(array);
	}-*/;

	public native final void clear() /*-{
		this.clear();
	}-*/;

	public native final void setAt(int index, T element) /*-{
		this.setAt(index, element);
	}-*/;

	public native final void removeAt(int index) /*-{
		this.removeAt(index);
	}-*/;

	public native final void remove(T element) /*-{
		this.remove(element);
	}-*/;

	public native final void push(T element) /*-{
		this.push(element);
	}-*/;

	public native final T pop() /*-{
		return this.pop();
	}-*/;

	public native final T item(int index) /*-{
		return this.item(index);
	}-*/;

	public native final void insertAt(int index, T elem) /*-{
		this.insertAt(index, elem);
	}-*/;

	public native final int getLength() /*-{
		return this.getLength();
	}-*/;

	@Override
	public final Iterator<T> iterator() {
		return new CollectionIterator();
	}

	protected class CollectionIterator implements Iterator<T> {

		int actual = 0;

		@Override
		public boolean hasNext() {
			return getLength() - actual > 0;
		}

		@Override
		public T next() {
			return item(actual++);
		}

		@Override
		public void remove() {
			removeAt(actual);
		}

	}

}


text:
package org.apache.isis.core.metamodel.specloader.facetprocessor;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import org.apache.isis.core.commons.lang.ListExtensions;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facetapi.FeatureType;
import org.apache.isis.core.metamodel.facetapi.MethodRemover;
import org.apache.isis.core.metamodel.facets.ContributeeMemberFacetFactory;
import org.apache.isis.core.metamodel.facets.FacetFactory;
import org.apache.isis.core.metamodel.facets.FacetFactory.ProcessClassContext;
import org.apache.isis.core.metamodel.facets.FacetFactory.ProcessMethodContext;
import org.apache.isis.core.metamodel.facets.FacetFactory.ProcessParameterContext;
import org.apache.isis.core.metamodel.facets.FacetedMethod;
import org.apache.isis.core.metamodel.facets.FacetedMethodParameter;
import org.apache.isis.core.metamodel.facets.MethodFilteringFacetFactory;
import org.apache.isis.core.metamodel.facets.MethodPrefixBasedFacetFactory;
import org.apache.isis.core.metamodel.facets.MethodRemoverConstants;
import org.apache.isis.core.metamodel.facets.ObjectSpecIdFacetFactory;
import org.apache.isis.core.metamodel.facets.ObjectSpecIdFacetFactory.ProcessObjectSpecIdContext;
import org.apache.isis.core.metamodel.facets.PropertyOrCollectionIdentifyingFacetFactory;
import org.apache.isis.core.metamodel.progmodel.ProgrammingModel;
import org.apache.isis.core.metamodel.services.ServicesInjector;
import org.apache.isis.core.metamodel.services.ServicesInjectorAware;
import org.apache.isis.core.metamodel.spec.feature.ObjectMember;

public class FacetProcessor implements ServicesInjectorAware {

    private final ProgrammingModel programmingModel;

    /**
     * Class<FacetFactory> => FacetFactory
     */
    private final Map<Class<? extends FacetFactory>, FacetFactory> factoryByFactoryType = Maps.newHashMap();

    /**
     * {@link FacetFactory Facet factories}, in order they were
     * {@link #registerFactory(FacetFactory) registered}.
     */
    private final List<FacetFactory> factories = Lists.newArrayList();

    /**
     * All method prefixes to check in {@link #recognizes(Method)}.
     *
     *

     * Derived from factories that implement
     * {@link MethodPrefixBasedFacetFactory}.
     *
     *

     * If <tt>null</tt>, indicates that the cache hasn't been built.
     */
    private List<String> cachedMethodPrefixes;

    /**
     * All registered {@link FacetFactory factories} that implement
     * {@link MethodFilteringFacetFactory}.
     *
     *

     * Used within {@link #recognizes(Method)}.
     *
     *

     * If <tt>null</tt>, indicates that the cache hasn't been built.
     */
    private List<MethodFilteringFacetFactory> cachedMethodFilteringFactories;

    /**
     * All registered {@link FacetFactory factories} that implement
     * {@link ContributeeMemberFacetFactory}.
     *
     *

     * If <tt>null</tt>, indicates that the cache hasn't been built.
     */
    private List<ContributeeMemberFacetFactory> cachedContributeeMemberFacetFactories;

    /**
     * All registered {@link FacetFactory factories} that implement
     * {@link PropertyOrCollectionIdentifyingFacetFactory}.
     *
     *

     * Used within {@link #recognizes(Method)}.
     *
     *

     * If <tt>null</tt>, indicates that the cache hasn't been built.
     */
    private List<PropertyOrCollectionIdentifyingFacetFactory> cachedPropertyOrCollectionIdentifyingFactories;

    /**
     * ObjectFeatureType => List<FacetFactory>
     *
     *

     * Lazily initialized, then cached. The lists remain in the same order that
     * the factories were {@link #registerFactory(FacetFactory) registered}.
     */
    private Map<FeatureType, List<FacetFactory>> factoryListByFeatureType = null;

    public FacetProcessor(final ProgrammingModel programmingModel) {
        this.programmingModel = programmingModel;
    }

    // //////////////////////////////////////////////////
    // init, shutdown (application scoped)
    // //////////////////////////////////////////////////

    public void init() {
        final List<FacetFactory> facetFactoryList = programmingModel.getList();
        for (final FacetFactory facetFactory : facetFactoryList) {
            registerFactory(facetFactory);
        }
    }

    public void shutdown() {
    }

    public void registerFactory(final FacetFactory factory) {
        clearCaches();
        factoryByFactoryType.put(factory.getClass(), factory);
        factories.add(factory);

        injectDependenciesInto(factory);
    }

    /**
     * This is <tt>public</tt> so that can be used for <tt>@Facets</tt>
     * processing.
     */
    public void injectDependenciesInto(final FacetFactory factory) {
        servicesInjector.injectInto(factory);
    }

    /**
     * Appends to the supplied {@link Set} all of the {@link Method}s that may
     * represent a property or collection.
     *
     *

     * Delegates to all known
     * {@link PropertyOrCollectionIdentifyingFacetFactory}s.
     */
    public Set<Method> findAssociationCandidateAccessors(final List<Method> methods, final Set<Method> candidates) {
        cachePropertyOrCollectionIdentifyingFacetFactoriesIfRequired();
        for (final Method method : methods) {
            if (method == null) {
                continue;
            }
            for (final PropertyOrCollectionIdentifyingFacetFactory facetFactory : cachedPropertyOrCollectionIdentifyingFactories) {
                if (facetFactory.isPropertyOrCollectionAccessorCandidate(method)) {
                    candidates.add(method);
                }
            }
        }
        return candidates;
    }

    /**
     * Use the provided {@link MethodRemover} to have all known
     * {@link PropertyOrCollectionIdentifyingFacetFactory}s to remove all
     * property accessors, and append them to the supplied methodList.
     *
     *

     * Intended to be called after {@link #findAndRemovePropertyAccessors(org.apache.isis.core.metamodel.facetapi.MethodRemover, java.util.List)} once only reference properties remain.
     */
    public void findAndRemovePropertyAccessors(final MethodRemover methodRemover, final List<Method> methodListToAppendTo) {
        cachePropertyOrCollectionIdentifyingFacetFactoriesIfRequired();
        for (final PropertyOrCollectionIdentifyingFacetFactory facetFactory : cachedPropertyOrCollectionIdentifyingFactories) {
            facetFactory.findAndRemovePropertyAccessors(methodRemover, methodListToAppendTo);
        }
    }

    /**
     * Use the provided {@link MethodRemover} to have all known
     * {@link PropertyOrCollectionIdentifyingFacetFactory}s to remove all
     * property accessors, and append them to the supplied methodList.
     *
     * @see PropertyOrCollectionIdentifyingFacetFactory#findAndRemoveCollectionAccessors(MethodRemover,
     *      List)
     */
    public void findAndRemoveCollectionAccessors(final MethodRemover methodRemover, final List<Method> methodListToAppendTo) {
        cachePropertyOrCollectionIdentifyingFacetFactoriesIfRequired();
        for (final PropertyOrCollectionIdentifyingFacetFactory facetFactory : cachedPropertyOrCollectionIdentifyingFactories) {
            facetFactory.findAndRemoveCollectionAccessors(methodRemover, methodListToAppendTo);
        }
    }

    /**
     * Whether this {@link Method method} is recognized by any of the
     * {@link FacetFactory}s.
     *
     *

     * Typically this is when method has a specific prefix, such as
     * <tt>validate</tt> or <tt>hide</tt>. Specifically, it checks:
     *

     *
the method's prefix against the prefixes supplied by any
     * {@link MethodPrefixBasedFacetFactory}

     *
the method against any {@link MethodFilteringFacetFactory}

     *

     *
     *

     * The design of {@link MethodPrefixBasedFacetFactory} (whereby this facet
     * factory set does the work) is a slight performance optimization for when
     * there are multiple facet factories that search for the same prefix.
     */
    public boolean recognizes(final Method method) {
        cacheMethodPrefixesIfRequired();
        final String methodName = method.getName();
        for (final String prefix : cachedMethodPrefixes) {
            if (methodName.startsWith(prefix)) {
                return true;
            }
        }

        cacheMethodFilteringFacetFactoriesIfRequired();
        for (final MethodFilteringFacetFactory factory : cachedMethodFilteringFactories) {
            if (factory.recognizes(method)) {
                return true;
            }
        }

        return false;
    }

    public void processObjectSpecId(final Class<?> cls, final FacetHolder facetHolder) {
        final List<ObjectSpecIdFacetFactory> factoryList = getObjectSpecIfFacetFactoryList();
        for (final ObjectSpecIdFacetFactory facetFactory : factoryList) {
            facetFactory.process(new ProcessObjectSpecIdContext(cls, facetHolder));
        }
    }

    private List<ObjectSpecIdFacetFactory> objectSpecIfFacetFactoryList = null;
    private List<ObjectSpecIdFacetFactory> getObjectSpecIfFacetFactoryList() {
        if(objectSpecIfFacetFactoryList == null) {
            List<ObjectSpecIdFacetFactory> facetFactories = Lists.newArrayList();
            final List<FacetFactory> factoryList = getFactoryListByFeatureType(FeatureType.OBJECT);
            for (final FacetFactory facetFactory : factoryList) {
                if (facetFactory instanceof ObjectSpecIdFacetFactory) {
                    final ObjectSpecIdFacetFactory objectSpecIdFacetFactory = (ObjectSpecIdFacetFactory) facetFactory;
                    facetFactories.add(objectSpecIdFacetFactory);
                }
            }
            objectSpecIfFacetFactoryList = Collections.unmodifiableList(facetFactories);
        }
        return objectSpecIfFacetFactoryList;
    }

    /**
     * Attaches all facets applicable to the provided {@link FeatureType#OBJECT
     * object}) to the supplied {@link FacetHolder}.
     *
     *

     * Delegates to {@link FacetFactory#process(org.apache.isis.core.metamodel.facets.FacetFactory.ProcessClassContext)} for each
     * appropriate factory.
     *
     * @see FacetFactory#process(ProcessClassContext)
     *
     * @param cls
     *            - class to process
     * @param facetHolder
     *            - holder to attach facets to.
     */
    public void process(
            final Class<?> cls,
            final Properties metadataProperties,
            final MethodRemover methodRemover,
            final FacetHolder facetHolder) {
        final List<FacetFactory> factoryList = getFactoryListByFeatureType(FeatureType.OBJECT);
        for (final FacetFactory facetFactory : factoryList) {
            facetFactory.process(new ProcessClassContext(cls, metadataProperties, removerElseNullRemover(methodRemover), facetHolder));
        }
    }

    /**
     * Attaches all facets applicable to the provided {@link FeatureType type of
     * feature} to the supplied {@link FacetHolder}.
     *
     *

     * Delegates to {@link FacetFactory#process(org.apache.isis.core.metamodel.facets.FacetFactory.ProcessMethodContext)} for each
     * appropriate factory.
     *
     * @param cls
     *            - class in which introspect; allowing the helper methods to be
     *            found is subclasses of that which the method was originally
     *            found.
     * @param method
     *            - method to process
     * @param facetedMethod
     *            - holder to attach facets to.
     * @param featureType
     *            - what type of feature the method represents (property,
     *            action, collection etc)
     * @param metadataProperties
     *            - additional properties to parse and use
     */
    public void process(
            final Class<?> cls,
            final Method method,
            final MethodRemover methodRemover,
            final FacetedMethod facetedMethod,
            final FeatureType featureType,
            final Properties metadataProperties) {
        final List<FacetFactory> factoryList = getFactoryListByFeatureType(featureType);
        final ProcessMethodContext processMethodContext =
                new ProcessMethodContext(cls, featureType, metadataProperties, method, removerElseNullRemover(methodRemover), facetedMethod);
        for (final FacetFactory facetFactory : factoryList) {
            facetFactory.process(processMethodContext);
        }
    }

    public void processMemberOrder(
            final Properties metadataProperties,
            final ObjectMember facetHolder) {
        cacheContributeeMemberFacetFactoriesIfRequired();
        final ContributeeMemberFacetFactory.ProcessContributeeMemberContext processMemberContext =
                new ContributeeMemberFacetFactory.ProcessContributeeMemberContext(metadataProperties, facetHolder);
        for (final ContributeeMemberFacetFactory facetFactory : cachedContributeeMemberFacetFactories) {
            facetFactory.process(processMemberContext);
        }
    }

    /**
     * Attaches all facets applicable to the provided parameter to the supplied
     * {@link FacetHolder}.
     *
     *

     * Delegates to {@link FacetFactory#processParams(ProcessParameterContext)}
     * for each appropriate factory.
     *
     * @see FacetFactory#processParams(ProcessParameterContext)
     *
     * @param introspectedClass
     * @param method
     *            - action method to process
     * @param paramNum
*            - 0-based
     * @param methodRemover
     * @param facetedMethodParameter
     */
    public void processParams(
            final Class<?> introspectedClass,
            final Method method,
            final int paramNum,
            final MethodRemover methodRemover,
            final FacetedMethodParameter facetedMethodParameter) {
        for (FeatureType featureType : FeatureType.PARAMETERS_ONLY) {
            processParams(introspectedClass, method, paramNum, methodRemover, facetedMethodParameter, featureType);
        }
    }

    public void processParams(
            final Class<?> introspectedClass,
            final Method method,
            final int paramNum,
            final MethodRemover methodRemover,
            final FacetedMethodParameter facetedMethodParameter,
            final FeatureType featureType) {
        final List<FacetFactory> factoryList = getFactoryListByFeatureType(featureType);
        final ProcessParameterContext processParameterContext =
                new ProcessParameterContext(introspectedClass, method, paramNum, methodRemover, facetedMethodParameter);
        for (final FacetFactory facetFactory : factoryList) {
            facetFactory.processParams(processParameterContext);
        }
    }

    private List<FacetFactory> getFactoryListByFeatureType(final FeatureType featureType) {
        cacheByFeatureTypeIfRequired();
        List<FacetFactory> list = factoryListByFeatureType.get(featureType);
        return list != null? list: Collections.<FacetFactory>emptyList();
    }

    private void clearCaches() {
        factoryListByFeatureType = null;
        cachedMethodPrefixes = null;
        cachedMethodFilteringFactories = null;
        cachedPropertyOrCollectionIdentifyingFactories = null;
    }

    private synchronized void cacheByFeatureTypeIfRequired() {
        if (factoryListByFeatureType != null) {
            return;
        }
        factoryListByFeatureType = Maps.newHashMap();
        for (final FacetFactory factory : factories) {
            final List<FeatureType> featureTypes = factory.getFeatureTypes();
            for (final FeatureType featureType : featureTypes) {
                final List<FacetFactory> factoryList = getList(factoryListByFeatureType, featureType);
                factoryList.add(factory);
            }
        }
    }

    private synchronized void cacheMethodPrefixesIfRequired() {
        if (cachedMethodPrefixes != null) {
            return;
        }
        cachedMethodPrefixes = Lists.newArrayList();
        for (final FacetFactory facetFactory : factories) {
            if (facetFactory instanceof MethodPrefixBasedFacetFactory) {
                final MethodPrefixBasedFacetFactory methodPrefixBasedFacetFactory = (MethodPrefixBasedFacetFactory) facetFactory;
                ListExtensions.mergeWith(cachedMethodPrefixes, methodPrefixBasedFacetFactory.getPrefixes());
            }
        }
    }

    private synchronized void cacheMethodFilteringFacetFactoriesIfRequired() {
        if (cachedMethodFilteringFactories != null) {
            return;
        }
        cachedMethodFilteringFactories = Lists.newArrayList();
        for (final FacetFactory factory : factories) {
            if (factory instanceof MethodFilteringFacetFactory) {
                final MethodFilteringFacetFactory methodFilteringFacetFactory = (MethodFilteringFacetFactory) factory;
                cachedMethodFilteringFactories.add(methodFilteringFacetFactory);
            }
        }
    }

    private synchronized void cacheContributeeMemberFacetFactoriesIfRequired() {
        if (cachedContributeeMemberFacetFactories != null) {
            return;
        }
        cachedContributeeMemberFacetFactories = Lists.newArrayList();
        for (final FacetFactory factory : factories) {
            if (factory instanceof ContributeeMemberFacetFactory) {
                final ContributeeMemberFacetFactory memberOrderingFacetFactory = (ContributeeMemberFacetFactory) factory;
                cachedContributeeMemberFacetFactories.add(memberOrderingFacetFactory);
            }
        }
    }

    private synchronized void cachePropertyOrCollectionIdentifyingFacetFactoriesIfRequired() {
        if (cachedPropertyOrCollectionIdentifyingFactories != null) {
            return;
        }
        cachedPropertyOrCollectionIdentifyingFactories = Lists.newArrayList();
        for (FacetFactory factory : factories) {
            if (factory instanceof PropertyOrCollectionIdentifyingFacetFactory) {
                final PropertyOrCollectionIdentifyingFacetFactory identifyingFacetFactory = (PropertyOrCollectionIdentifyingFacetFactory) factory;
                cachedPropertyOrCollectionIdentifyingFactories.add(identifyingFacetFactory);
            }
        }
    }

    private static <K, T> List<T> getList(final Map<K, List<T>> map, final K key) {
        List<T> list = map.get(key);
        if (list == null) {
            list = Lists.newArrayList();
            map.put(key, list);
        }
        return list;
    }

    private MethodRemover removerElseNullRemover(final MethodRemover methodRemover) {
        return methodRemover != null ? methodRemover : MethodRemoverConstants.NULL;
    }

    //region > dependencies

    private ServicesInjector servicesInjector;

    @Override
    public void setServicesInjector(final ServicesInjector servicesInjector) {
        this.servicesInjector = servicesInjector;
    }

    //endregion

}