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

    Copyright 2016 Yahoo Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
  xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.yahoo.pulsar</groupId>
    <artifactId>pulsar</artifactId>
    <version>1.18-SNAPSHOT</version>
    <relativePath>..</relativePath>
  </parent>

  <artifactId>pulsar-checksum</artifactId>
  <packaging>nar</packaging>
  <name>Pulsar Checksum</name>
  <description>Checksum library</description>

  <properties>
    <nar.runtime>dynamic</nar.runtime>
    <nar.cpp.optionSet>-msse4.2 -mpclmul</nar.cpp.optionSet>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-all</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <dependency>
      <groupId>com.googlecode.jmockit</groupId>
      <artifactId>jmockit</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>com.github.maven-nar</groupId>
        <artifactId>nar-maven-plugin</artifactId>
        <version>3.1.0</version>
        <extensions>true</extensions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.4.1</version>
        <configuration>
          <descriptors>
            <descriptor>src/main/assembly/assembly.xml</descriptor>
          </descriptors>
          <appendAssemblyId>false</appendAssemblyId>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>mac</id>
      <activation>
        <os>
          <name>Mac OS X</name>
        </os>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>com.github.maven-nar</groupId>
            <artifactId>nar-maven-plugin</artifactId>
            <version>3.1.0</version>
            <extensions>true</extensions>
            <configuration>
              <runtime>${nar.runtime}</runtime>
              <output>pulsar-checksum</output>
              <libraries>
                <library>
                  <type>jni</type>
                </library>
              </libraries>
              <cpp>
                <optionSet>${nar.cpp.optionSet}</optionSet>
                <exceptions>false</exceptions>
                <rtti>false</rtti>
                <optimize>full</optimize>
              </cpp>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
    <profile>
      <id>Linux</id>
      <activation>
        <os>
          <name>Linux</name>
        </os>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>com.github.maven-nar</groupId>
            <artifactId>nar-maven-plugin</artifactId>
            <version>3.1.0</version>
            <extensions>true</extensions>
            <configuration>
              <runtime>${nar.runtime}</runtime>
              <output>pulsar-checksum</output>
              <libraries>
                <library>
                  <type>jni</type>
                </library>
              </libraries>
              <cpp>
                <optionSet>${nar.cpp.optionSet}</optionSet>
                <exceptions>false</exceptions>
                <rtti>false</rtti>
                <optimize>full</optimize>
              </cpp>
              <linker>
                <libSet>rt</libSet>
              </linker>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
class AddBranchOfficeToPatients < ActiveRecord::Migration[5.2]
  def change
    add_reference :patients, :branch_office, foreign_key: { on_delete: :nullify }
  end
end

redpajama_set_name: RedPajamaGithub


text:
import logging

from cms.apphook_pool import apphook_pool
from cms.menu_bases import CMSAttachMenu
from django.contrib.sites.shortcuts import get_current_site
from django.db.models.signals import post_delete, post_save
from django.urls import resolve
from django.utils.translation import get_language_from_request, gettext_lazy as _
from menus.base import Modifier, NavigationNode
from menus.menu_pool import menu_pool

from .cms_appconfig import BlogConfig
from .models import BlogCategory, Post
from .settings import MENU_TYPE_CATEGORIES, MENU_TYPE_COMPLETE, MENU_TYPE_NONE, MENU_TYPE_POSTS, get_setting

logger = logging.getLogger(__name__)

class BlogCategoryMenu(CMSAttachMenu):
    """
    Main menu class

    Handles all types of blog menu
    """

    name = _("Blog menu")
    _config = {}

    def get_nodes(self, request):
        """
        Generates the nodelist

        :param request:
        :return: list of nodes
        """
        nodes = []

        language = get_language_from_request(request, check_path=True)
        current_site = get_current_site(request)

        page_site = self.instance.node.site
        if self.instance and page_site != current_site:
            return []

        categories_menu = False
        posts_menu = False
        config = False
        if self.instance:
            if not self._config.get(self.instance.application_namespace, False):
                try:
                    self._config[self.instance.application_namespace] = BlogConfig.objects.get(
                        namespace=self.instance.application_namespace
                    )
                except BlogConfig.DoesNotExist as e:
                    logger.exception(e)
                    return []
            config = self._config[self.instance.application_namespace]
            if not getattr(request, "toolbar", False) or not request.toolbar.edit_mode_active:
                if self.instance == self.instance.get_draft_object():
                    return []
            else:
                if self.instance == self.instance.get_public_object():
                    return []
        if config and config.menu_structure in (MENU_TYPE_COMPLETE, MENU_TYPE_CATEGORIES):
            categories_menu = True
        if config and config.menu_structure in (MENU_TYPE_COMPLETE, MENU_TYPE_POSTS):
            posts_menu = True
        if config and config.menu_structure in (MENU_TYPE_NONE,):
            return nodes

        used_categories = []
        if posts_menu:
            posts = Post.objects
            if hasattr(self, "instance") and self.instance:
                posts = posts.namespace(self.instance.application_namespace).on_site()
            posts = (
                posts.active_translations(language)
                .distinct()
                .select_related("app_config")
                .prefetch_related("translations", "categories")
            )
            for post in posts:
                post_id = None
                parent = None
                used_categories.extend(post.categories.values_list("pk", flat=True))
                if categories_menu:
                    category = post.categories.first()
                    if category:
                        parent = "{}-{}".format(category.__class__.__name__, category.pk)
                        post_id = ("{}-{}".format(post.__class__.__name__, post.pk),)
                else:
                    post_id = ("{}-{}".format(post.__class__.__name__, post.pk),)
                if post_id:
                    node = NavigationNode(post.get_title(), post.get_absolute_url(language), post_id, parent)
                    nodes.append(node)

        if categories_menu:
            categories = BlogCategory.objects
            if config:
                categories = categories.namespace(self.instance.application_namespace)
            if config and not config.menu_empty_categories:
                categories = categories.active_translations(language).filter(pk__in=used_categories).distinct()
            else:
                categories = categories.active_translations(language).distinct()
            categories = (
                categories.order_by("parent__id", "translations__name")
                .select_related("app_config")
                .prefetch_related("translations")
            )
            added_categories = []
            for category in categories:
                if category.pk not in added_categories:
                    node = NavigationNode(
                        category.name,
                        category.get_absolute_url(),
                        "{}-{}".format(category.__class__.__name__, category.pk),
                        ("{}-{}".format(category.__class__.__name__, category.parent.id) if category.parent else None),
                    )
                    nodes.append(node)
                    added_categories.append(category.pk)

        return nodes

class BlogNavModifier(Modifier):
    """
    This navigation modifier makes sure that when
    a particular blog post is viewed,
    a corresponding category is selected in menu
    """

    _config = {}

    def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb):
        """
        Actual modifier function
        :param request: request
        :param nodes: complete list of nodes
        :param namespace: Menu namespace
        :param root_id: eventual root_id
        :param post_cut: flag for modifier stage
        :param breadcrumb: flag for modifier stage
        :return: nodeslist
        """
        app = None
        config = None
        if getattr(request, "current_page", None) and request.current_page.application_urls:
            app = apphook_pool.get_apphook(request.current_page.application_urls)

        if app and app.app_config:
            namespace = resolve(request.path).namespace
            if not self._config.get(namespace, False):
                self._config[namespace] = app.get_config(namespace)
            config = self._config[namespace]
        try:
            if config and (not isinstance(config, BlogConfig) or config.menu_structure != MENU_TYPE_CATEGORIES):
                return nodes
        except AttributeError:  # pragma: no cover
            # in case `menu_structure` is not present in config
            return nodes
        if post_cut:
            return nodes
        current_post = getattr(request, get_setting("CURRENT_POST_IDENTIFIER"), None)
        category = None
        if current_post and current_post.__class__ == Post:
            category = current_post.categories.first()
        if not category:
            return nodes

        for node in nodes:
            if "{}-{}".format(category.__class__.__name__, category.pk) == node.id:
                node.selected = True
        return nodes

menu_pool.register_modifier(BlogNavModifier)
menu_pool.register_menu(BlogCategoryMenu)

def clear_menu_cache(**kwargs):
    """
    Empty menu cache when saving categories
    """
    menu_pool.clear(all=True)

post_save.connect(clear_menu_cache, sender=BlogCategory)
post_delete.connect(clear_menu_cache, sender=BlogCategory)
post_delete.connect(clear_menu_cache, sender=BlogConfig)


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

<rootTag>
  <Award>
    <AwardTitle>First International Workshop on Small Satellites for Space Weather Research and Forecasting; Washington, District of Columbia; August 1-4, 2017</AwardTitle>
    <AwardEffectiveDate>06/01/2017</AwardEffectiveDate>
    <AwardExpirationDate>05/31/2018</AwardExpirationDate>
    <AwardAmount>46174</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      06020200
      <Directorate>
        <LongName>Directorate For Geosciences</LongName>
      </Directorate>
      <Division>
        <LongName>Div Atmospheric & Geospace Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>John Meriwether</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award would support the first dedicated scientific meeting focusing on specific needs of space weather studies using small satellite platforms. The proposed event would bridge this gap thus fulfilling a major need in the space weather community to have opportunities to generate and develop new projects based upon the new ideas created by this meeting activity.<br/><br/>The key intellectual merits of the proposed workshop are rooted in its interdisciplinarity. By bringing together scientists and engineers working on small satellite missions and space weather problems, the proposed workshop would facilitate innovative insights into both fields, provide new opportunities to brainstorm long-standing space weather problems, identify new observational targets, and develop recommendations for future small satellite missions serving the space weather community.</AbstractNarration>
    <MinAmdLetterDate>12/12/2016</MinAmdLetterDate>
    <MaxAmdLetterDate>12/12/2016</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1712718</AwardID>
    <Investigator>
      <FirstName>Teresa</FirstName>
      <LastName>Nieves-Chinchilla</LastName>
      <EmailAddress>nieveschinch@cua.edu</EmailAddress>
      <StartDate>12/12/2016</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Vadim</FirstName>
      <LastName>Uritsky</LastName>
      <EmailAddress>uritsky@cua.edu</EmailAddress>
      <StartDate>12/12/2016</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Silvina</FirstName>
      <LastName>Guidoni</LastName>
      <EmailAddress>silvina.e.guidoni@nasa.gov</EmailAddress>
      <StartDate>12/12/2016</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Robert</FirstName>
      <LastName>Robinson</LastName>
      <EmailAddress>robert.m.robinson@nasa.gov</EmailAddress>
      <StartDate>12/12/2016</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Catholic University of America</Name>
      <CityName>Washington</CityName>
      <ZipCode>200640001</ZipCode>
      <PhoneNumber>2026355000</PhoneNumber>
      <StreetAddress>620 Michigan Ave.N.E.</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>District of Columbia</StateName>
      <StateCode>DC</StateCode>
    </Institution>
    <ProgramElement>
      8089
      <Text>Space Weather Research</Text>
    </ProgramElement>
    <ProgramReference>
      7556
      <Text>CONFERENCE AND WORKSHOPS</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
/** \defgroup Triangulation Triangulation module
 * @{  @}
 *
 * Example:
 *
 * @{  @}
 *
 * \brief
 * Contains all triangulation classes.
 */

#pragma once

#include <deque>
#include <set>
#include <stdio.h>

#include "AMDiS_fwd.hpp"
#include "BoundaryCondition.hpp"
#include "DOFAdmin.hpp"
#include "ElInfo.hpp"
#include "Element.hpp"
#include "FixVec.hpp"
#include "Line.hpp"
#include "Tetrahedron.hpp"
#include "Triangle.hpp"

namespace AMDiS
{
  /** \ingroup Triangulation
   * \brief
   * A Mesh holds all information about a triangulation.
   */
  class Mesh
  {
  public:
    /// Creates a mesh with the given name of dimension dim
    Mesh(std::string name, int dim);

    /// Destructor
    ~Mesh();

    /// Reads macro triangulation.
    void initialize();

    /// Assignment operator
    Mesh& operator=(Mesh const&);

    /** \name getting methods
     * \{
     */

    /// Returns geometric information about this mesh. With GeoIndex p it is
    /// specified which information is requested.
    int getGeo(GeoIndex p) const
    {
      return Global::getGeo(p, dim);
    }

    /// Returns \ref name of the mesh
    std::string getName() const
    {
      return name;
    }

    /// Returns \ref dim of the mesh
    int getDim() const
    {
      return dim;
    }

    /// Returns \ref nDofEl of the mesh
    int getNumberOfAllDofs() const
    {
      return nDofEl;
    }

    /// Returns \ref nNodeEl of the mesh
    int getNumberOfNodes() const
    {
      return nNodeEl;
    }

    /// Returns \ref nVertices of the mesh
    int getNumberOfVertices() const
    {
      return nVertices;
    }

    /// Returns \ref nEdges of the mesh
    int getNumberOfEdges() const
    {
      return nEdges;
    }

    /// Returns \ref nFaces of the mesh
    int getNumberOfFaces() const
    {
      return nFaces;
    }

    /// Returns \ref nLeaves of the mesh
    int getNumberOfLeaves() const
    {
      return nLeaves;
    }

    /// Returns \ref nElements of the mesh
    int getNumberOfElements() const
    {
      return nElements;
    }

    /// Returns \ref maxEdgeNeigh of the mesh
    int getMaxEdgeNeigh() const
    {
      return maxEdgeNeigh;
    }

    /// Returns \ref parametric of the mesh
    Parametric* getParametric() const
    {
      return parametric;
    }

    /// Returns \ref diam of the mesh
    WorldVector<double> const& getDiameter() const
    {
      return diam;
    }

    /// Returns \ref diam of the mesh
    std::pair<WorldVector<double>, WorldVector<double>> const& getBoundingBox() const
    {
      return boundingBox;
    }

    /// Returns nDof[i] of the mesh
    int getNumberOfDofs(int i) const
    {
      TEST_EXIT_DBG(i <= dim)("Wrong index: %d %d\n", i, dim);
      return nDof[i];
    }

    /// Returns \ref elementPrototype of the mesh
    Element* getElementPrototype()
    {
      return elementPrototype;
    }

    /// Returns \ref leafDataPrototype of the mesh
    ElementData* getElementDataPrototype()
    {
      return elementDataPrototype;
    }

    /// Returns node[i] of the mesh
    int getNode(int i) const
    {
      return node[i];
    }

    /// Allocates the number of DOFs needed at position and registers the DOFs
    /// at the DOFAdmins. The number of needed DOFs is the sum over the needed
    /// DOFs of all DOFAdmin objects belonging to this mesh.
    /// The return value is a pointer to the first allocated DOF.
    DegreeOfFreedom* getDof(GeoIndex position);

    /// Returns *(\ref admin[i]) of the mesh
    DOFAdmin const& getDofAdmin(int i) const
    {
      return *(admin[i]);
    }

    /// Creates a DOFAdmin with name lname. nDof specifies how many DOFs
    /// are needed at the different positions (see \ref DOFAdmin::nrDOF).
    /// A pointer to the created DOFAdmin is returned.
    DOFAdmin const* createDOFAdmin(std::string lname, DimVec<int> nDof);

    /// Returns the size of \ref admin which is the number of the DOFAdmins
    /// belonging to this mesh
    int getNumberOfDOFAdmin() const
    {
      return int(admin.size());
    }

    /// Returns the size of \ref macroElements which is the number of
    /// of macro elements of this mesh
    int getNumberOfMacros() const
    {
      return int(macroElements.size());
    }

    /// Returns a DOFAdmin which at least manages vertex DOFs
    DOFAdmin const* getVertexAdmin() const;

    /// Allocates an array of DOF pointers. The array holds one pointer for
    /// each node.
    DegreeOfFreedom** createDofPtrs();

    /// Returns \ref preserveCoarseDOFs of the mesh
    bool queryCoarseDOFs() const
    {
      return preserveCoarseDOFs;
    }

    /// Returns an iterator to the begin of \ref macroElements
    std::deque<MacroElement*>::iterator firstMacroElement()
    {
      return macroElements.begin();
    }

    /// Returns macroElements[i].
    MacroElement* getMacroElement(int i)
    {
      return macroElements[i];
    }

    /// Returns an iterator to the end of \ref macroElements
    std::deque<MacroElement*>::iterator endOfMacroElements()
    {
      return macroElements.end();
    }

    /// Returns \ref macroElements, the list of all macro elements in the mesh.
    std::deque<MacroElement*>& getMacroElements()
    {
      return macroElements;
    }

    /** \} */

    /** \name setting methods
     * \{
     */

    /// Sets \ref name of the mesh
    void setName(std::string aName)
    {
      name = aName;
    }

    /// Sets \ref nVertices of the mesh
    void setNumberOfVertices(int n)
    {
      nVertices = n;
    }

    /// Sets \ref nFaces of the mesh
    void setNumberOfFaces(int n)
    {
      nFaces = n;
    }

    /// Increments \ref nVertices by inc
    void incrementNumberOfVertices(int inc)
    {
      nVertices += inc;
    }

    /// Sets \ref nEdges of the mesh
    void setNumberOfEdges(int n)
    {
      nEdges = n;
    }

    /// Increments \ref nEdges by inc
    void incrementNumberOfEdges(int inc)
    {
      nEdges += inc;
    }

    /// Increments \ref nFaces by inc
    void incrementNumberOfFaces(int inc)
    {
      nFaces += inc;
    }

    /// Sets \ref nLeaves of the mesh
    void setNumberOfLeaves(int n)
    {
      nLeaves = n;
    }

    /// Increments \ref nLeaves by inc
    void incrementNumberOfLeaves(int inc)
    {
      nLeaves += inc;
    }

    /// Sets \ref nElements of the mesh
    void setNumberOfElements(int n)
    {
      nElements = n;
    }

    /// Increments \ref nElements by inc
    void incrementNumberOfElements(int inc)
    {
      nElements += inc;
    }

    /// Sets *\ref diam to w
    void setDiameter(WorldVector<double> const& w);

    /// Sets (*\ref diam)[i] to d
    void setDiameter(int i, double d);

    void setBoundingBox(WorldVector<double> const& min_corner,
                        WorldVector<double> const& max_corner);

    /// Sets \ref preserveCoarseDOFs = true
    void retainCoarseDOFs()
    {
      preserveCoarseDOFs = true;
    }

    /// Sets \ref preserveCoarseDOFs = b
    void setPreserveCoarseDOFs(bool b)
    {
      preserveCoarseDOFs = b;
    }

    /// Sets \ref preserveCoarseDOFs = false
    void noCoarseDOFs()
    {
      preserveCoarseDOFs = false;
    }

    /// Sets \ref elementPrototype of the mesh
    void setElementPrototype(Element* prototype)
    {
      elementPrototype = prototype;
    }

    /// Sets \ref elementDataPrototype of the mesh
    void setElementDataPrototype(ElementData* prototype)
    {
      elementDataPrototype = prototype;
    }

    ///
    void setParametric(Parametric* param)
    {
      parametric = param;
    }

    ///
    void setMaxEdgeNeigh(int m)
    {
      maxEdgeNeigh = m;
    }

    /** \} */

    /// Creates a new Element by cloning \ref elementPrototype
    Element* createNewElement(Element* parent = NULL);

    /// Creates a new ElInfo dependent of \ref dim of the mesh
    ElInfo* createNewElInfo();

    /// Frees DOFs at the given position pointed by dof
    void freeDof(DegreeOfFreedom* dof, GeoIndex position);

    /// Frees memory for the given element el
    void freeElement(Element* el);

    /// Performs DOF compression for all DOFAdmins (see \ref DOFAdmin::compress)
    void dofCompress();

    /// Adds a DOFAdmin to the mesh
    void addDOFAdmin(DOFAdmin* admin);

    /// Recalculates the number of leave elements.
    void updateNumberOfLeaves();

    /// Clears \ref macroElements
    void clearMacroElements()
    {
      macroElements.clear();
    }

    /// Adds a macro element to the mesh
    void addMacroElement(MacroElement* me);

    /// Removes a set of macro elements from the mesh. This works only for the
    /// case, that there are no global or local refinements, i.e., all macro
    /// elements have no children.
    void removeMacroElements(std::set<MacroElement*>& macros,
                             std::vector<FiniteElemSpace const*>& feSpaces);

    void removeAllMacroElements();

    /// Frees the array of DOF pointers (see \ref createDofPtrs)
    void freeDofPtrs(DegreeOfFreedom** ptrs);

    /// Used by \ref findElementAtPoint.
    bool findElInfoAtPoint(WorldVector<double> const& xy,
                           ElInfo* el_info,
                           DimVec<double>& bary,
                           MacroElement const* start_mel,
                           WorldVector<double> const* xy0,
                           double* sp);

    /** \brief
     * Access to an element at world coordinates xy. Some applications need the
     * access to elements at a special location in world coordinates. Examples
     * are characteristic methods for convection problems, or the implementation
     * of a special right hand side like point evaluations or curve integrals.
     * For such purposes, a routine is available which returns an element pointer
     * and corresponding barycentric coordinates.
     *
     * \param xy world coordinates of point
     * \param elp return address for a pointer to the element at xy
     * \param pary returns barycentric coordinates of xy
     * \param start_mel initial guess for the macro element containing xy or NULL
     * \param xy0 start point from a characteristic method, see below, or NULL
     * \param sp return address for relative distance to domain boundary in a
     *        characteristic method, see below, or NULL
     * \return true is xy is inside the domain , false otherwise
     *
     * For a characteristic method, where \f$ xy = xy_0 - V\tau \f$, it may be
     * convenient to know the point on the domain's boundary which lies on the
     * line segment between the old point xy0 and the new point xy, in case that
     * xy is outside the domain. Such information is returned when xy0 and a
     * pointer sp!=NULL are supplied: *sp is set to the value s such that
     * \f$ xy_0 +s (xy -xy_0) \in \partial Domain \f$, and the element and local
     * coordinates corresponding to that boundary point will be returned via elp
     * and bary.
     *
     * The implementation of findElementAtPoint() is based on the transformation
     * from world to local coordinates, available via the routine worldToCoord(),
     * At the moment, findElementAtPoint() works correctly only for domains with
     * non-curved boundary. This is due to the fact that the implementation first
     * looks for the macro-element containing xy and then finds its path through
     * the corresponding element tree based on the macro barycentric coordinates.
     * For non-convex domains, it is possible that in some cases a point inside
     * the domain is considered as external.
     */
    bool findElementAtPoint(WorldVector<double> const& xy,
                            Element** elp,
                            DimVec<double>& bary,
                            MacroElement const* start_mel,
                            WorldVector<double> const* xy0,
                            double* sp);

    /** \brief
     * Returns for a given dof its world coordinates in this mesh. Because we do
     * not have any direct connection between dofs and coordinates, this function
     * has to search for the element in this mesh, that contains the dof. Than the
     * coordinates can be computed. Therefore, this function is very costly and
     * should be used for debugging purpose only.
     *
     * @param[in]    dof       A pointer to the dof we have to search for.
     * @param[in]    feSpace   The fe space to be used for the search.
     * @param[out]   coords    World vector that stores the coordinates of the dof.
     *
     * The function returns true, if the dof was found, otherwise false.
     */
    bool getDofIndexCoords(DegreeOfFreedom const* dof,
                           FiniteElemSpace const* feSpace,
                           WorldVector<double>& coords)
    {
      return getDofIndexCoords(*dof, feSpace, coords);
    }

    /// This function is equal to \ref getDofIndexCoords as defined above, but
    /// takes a DOF index instead of a DOF pointer.
    bool getDofIndexCoords(DegreeOfFreedom dof,
                           FiniteElemSpace const* feSpace,
                           WorldVector<double>& coords);

    /** \brief
     * Traverse the whole mesh and stores to each DOF the coordinates in a given
     * DOFVector. Works in the same way as the function \ref getDofIndexCoords
     * defined above.
     *
     * @param[out]  coords    DOF vector that stores the coordinates to each DOF.
     */
    void getDofIndexCoords(DOFVector<WorldVector<double>>& coords);

    /** \brief
     * Traverse the mesh and get all DOFs in this mesh for a given FE space.
     *
     * @param[in]   feSpace   The FE space to be used for collecting DOFs.
     * @param[out]  allDofs   The set which is filled with all DOFs.
     */
    void getAllDofs(FiniteElemSpace const* feSpace,
                    std::set<DegreeOfFreedom const*>& allDofs);

    /// Returns FILL_ANY_?D
    static Flag const& getFillAnyFlag(int dim)
    {
      switch (dim)
      {
      case 1:
        return FILL_ANY_1D;
        break;
      case 2:
        return FILL_ANY_2D;
        break;
      case 3:
        return FILL_ANY_3D;
        break;
      default:
        ERROR_EXIT("invalid dim\n");
        return FILL_ANY_1D;
      }
    }

    /// Returns \ref elementIndex and increments it by 1.
    int getNextElementIndex()
    {
      return elementIndex++;
    }

    /// Returns \ref initialized.
    bool isInitialized() const
    {
      return initialized;
    }

    ///
    std::map<BoundaryType, VertexVector*>& getPeriodicAssociations()
    {
      return periodicAssociations;
    }

    /// Returns the periodic association for a specific boundary type.
    VertexVector& getPeriodicAssociations(BoundaryType b)
    {
      FUNCNAME_DBG("Mesh::getPeriodicAssociations()");

      TEST_EXIT_DBG(periodicAssociations.count(b) == 1)
      ("There are no periodic assoications for boundary type %d!\n", b);

      return (*(periodicAssociations[b]));
    }

    void setPeriodicAssociations(BoundaryType b, VertexVector* vec)
    {
      periodicAssociations[b] = vec;
    }

    /// Returns whether the given boundary type is periodic, i.e., if there is
    /// a periodic association for this boundary type.
    bool isPeriodicAssociation(BoundaryType b) const
    {
      return (periodicAssociations.count(b) == 1 ? true : false);
    }

    ///
    bool associated(DegreeOfFreedom dof1, DegreeOfFreedom dof2);

    ///
    bool indirectlyAssociated(DegreeOfFreedom dof1, DegreeOfFreedom dof2);

    /// Returns \macroFileInfo
    MacroInfo* getMacroFileInfo()
    {
      return macroFileInfo;
    }

    /// Increment the value of mesh change index, see \ref changeIndex.
    void incChangeIndex()
    {
      changeIndex++;
    }

    /// Returns the mesh change index, see \ref changeIndex.
    long getChangeIndex() const
    {
      return changeIndex;
    }

    ///
    void clearMacroFileInfo();

    ///
    int calcMemoryUsage();

    ///
    void deleteMeshStructure();

#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
    /// In parallel computations the level of all macro elements is equal to the
    /// number of global pre refinements, \ref nParallelPreRefinements.
    int getMacroElementLevel() const
    {
      return nParallelPreRefinements;
    }
#else
    /// In sequentiel computations the level of all macro elements is always 0.
    int getMacroElementLevel() const
    {
      return 0;
    }
#endif

    /// Creates a map for all elements in mesh that maps from element indices
    /// to the corresponding pointers.
    void getElementIndexMap(std::map<int, Element*>& elIndexMap);

  public:
    ///
    static const Flag FILL_NOTHING;

    ///
    static const Flag FILL_COORDS;

    ///
    static const Flag FILL_BOUND;

    ///
    static const Flag FILL_NEIGH;

    ///
    static const Flag FILL_OPP_COORDS;

    ///
    static const Flag FILL_ORIENTATION;

    ///
    static const Flag FILL_ADD_ALL;

    ///
    static const Flag FILL_ANY_1D;

    ///
    static const Flag FILL_ANY_2D;

    ///
    static const Flag FILL_ANY_3D;

    ///
    static const Flag FILL_DET;

    ///
    static const Flag FILL_GRD_LAMBDA;

    //**************************************************************************
    //  flags for Mesh traversal
    //**************************************************************************

    ///
    static const Flag CALL_EVERY_EL_PREORDER;

    ///
    static const Flag CALL_EVERY_EL_INORDER;

    ///
    static const Flag CALL_EVERY_EL_POSTORDER;

    ///
    static const Flag CALL_LEAF_EL;

    ///
    static const Flag CALL_LEAF_EL_LEVEL;

    ///
    static const Flag CALL_EL_LEVEL;

    ///
    static const Flag CALL_MG_LEVEL;

    /// If set, left and right children are swapped in traverse.
    static const Flag CALL_REVERSE_MODE;

  protected:
    ///
    bool findElementAtPointRecursive(ElInfo* elinfo,
                                     DimVec<double> const& lambda,
                                     int outside,
                                     ElInfo* final_el_info);

#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
    /** \brief
     * This functions is called in parallel computations by the function \ref
     * Mesh::initialize(). It checks that the macro file has enough macro elements
     * for the number of used processors and that all macro elements are of type 0.
     * If this is not the case, that macro mesh is globally refined in an
     * apropriate way and is written to a new macro file.
     *
     * The function overwrittes the macro and periodic filenames, if a new macro
     * fule was created for the current parallel usage.
     *
     * \param[in/out]  macroFilename      Name of the macro mesh file.
     * \param[in/out]  periodicFilename   If periodic boundaries are used, name of the
     *                                    periodicity file. Otherwise, the string must
     *                                    be empty.
     * \param[in]      check              If the mesh should be checked to be a correct
     *                                    AMDiS macro mesh, the value must be 1 and 0
     *                                    otherwise.
     */
    void checkParallelMacroFile(std::string& macroFilename,
                                std::string& periodicFilename,
                                int check);
#endif

  protected:
    /// maximal number of DOFs at one position
    static const int MAX_DOF;

    /// Name of this Mesh
    std::string name;

    /// Dimension of this Mesh. Doesn't have to be equal to dimension of world.
    int dim;

    /// Number of vertices in this Mesh
    int nVertices;

    /// Number of Edges in this Mesh
    int nEdges;

    /// Number of leaf elements in this Mesh
    int nLeaves;

    /// Total number of elements in this Mesh
    int nElements;

    /// Number of faces in this Mesh
    int nFaces;

    /// Maximal number of elements that share one edge; used to allocate memory
    /// to store pointers to the neighbour at the refinement/coarsening edge
    /// (only 3d);
    int maxEdgeNeigh;

    /// Diameter of the mesh in the DIM_OF_WORLD directions
    WorldVector<double> diam;

    /// Corner coordinates of the bounding-box of the mesh
    std::pair<WorldVector<double>, WorldVector<double>> boundingBox;

    /// Is pointer to NULL if mesh contains no parametric elements else pointer
    /// to a Parametric object containing coefficients of the parameterization
    /// and related information
    Parametric* parametric;

    /// When an element is refined, not all dofs of the coarse element must be
    /// part of the new elements. An example are centered dofs when using higher
    /// lagrange basis functions. The midpoint dof of the parents element is not
    /// a dof of the both children elements. Therefore, the dof can be deleted.
    /// In some situation, e.g., when using multigrid techniques, it can be
    /// necessary to store this coarse dofs. Then this variable must be set to
    /// true. If false, the not required coarse dofs will be deleted.
    bool preserveCoarseDOFs;

    /// Number of all DOFs on a single element
    int nDofEl;

    /** \brief
     * Number of DOFs at the different positions VERTEX, EDGE, (FACE,) CENTER on
     * an element:
     *
     * - nDof[VERTEX]: number of DOFs at a vertex (>= 1)
     *
     * - nDof[EDGE]: number of DOFs at an edge; if no DOFs are associated to
     *   edges, then this value is 0
     *
     * - nDof[FACE]: number of DOFs at a face; if no DOFs are associated to
     *   faces, then this value is 0 (only 3d)
     *
     * - nDof[CENTER]: number of DOFs at the barycenter; if no DOFs are
     *   associated to the barycenter, then this value is 0
     */
    DimVec<int> nDof;

    /// Number of nodes on a single element where DOFs are located. Needed for
    /// the (de-) allocation of the DOF-vector on the element (\ref Element::dof).
    /// Here "node" is equivalent to the number of basis functions on the element.
    int nNodeEl;

    /** \brief
     * Gives the index of the first node at vertex, edge, face (only 3d), and
     * barycenter:
     *
     * - node[VERTEX]: has always value 0; dof[0],...,dof[N_VERTICES-1] are
     *   always DOFs at the vertices;
     *
     * - node[EDGE]: dof[node[EDGE]],..., dof[node[EDGE]+N_EDGES-1] are the DOFs
     *   at the N_EDGES edges, if DOFs are located at edges;
     *
     * - node[FACE]: dof[node[FACE]],..., dof[node[FACE]+N_FACES-1] are the DOFs
     *   at the N_FACES faces, if DOFs are located at faces (only 3d);
     *
     * - node[CENTER]: dof[node[CENTER]] are the DOFs at the barycenter, if DOFs
     *   are located at the barycenter;
     */
    DimVec<int> node;

    /// List of all DOFAdmins
    std::vector<DOFAdmin*> admin;

    /// List of all MacroElements of this Mesh
    std::deque<MacroElement*> macroElements;

    /// Used by check functions
    static std::vector<DegreeOfFreedom> dof_used;

    static std::set<std::string> refinedMeshNames;

    /// This map is used for serialization and deserialization of mesh elements.
    /// During the serialization process, all elements are visited and their
    /// DOF indices are written to the file. If a dof index at a position, i.e.
    /// vertex, line or face, was written to file, the combination of dof index
    /// and position is inserted to this map. That ensures that the same dof at
    /// the same position, but being part of another element, is not written
    /// twice to the file. When a state should be deserialized, the information
    /// can be used to construct exactly the same dof structure.
    static std::map<std::pair<DegreeOfFreedom, int>, DegreeOfFreedom*> serializedDOFs;

    /// Used while mesh refinement. To create new elements
    /// elementPrototype->clone() is called, which returns a Element of the
    /// same type as elementPrototype. So e.g. Elements of the different
    /// dimensions can be created in a uniform way.
    Element* elementPrototype;

    /// Prototype for leaf data. Used for creation of new leaf data while
    /// refinement.
    ElementData* elementDataPrototype;

    /// Used for enumeration of all mesh elements
    int elementIndex;

    /// True if the mesh is already initialized, false otherwise.
    bool initialized;

    /// Map of managed periodic vertex associations.
    std::map<BoundaryType, VertexVector*> periodicAssociations;

    /// If the mesh has been created by reading a macro file, here the information
    /// are stored about the content of the file.
    MacroInfo* macroFileInfo;

    /// This index is incremented every time the mesh is changed, e.g. by the
    /// refinement or the coarsening manager. It can be used by other object if
    /// the mesh has been changed by first copying this variable elsewhere and
    /// comparing its values.
    long changeIndex;

#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
    /// In parallel computations the mesh may be globally prerefined to achieve a
    /// fine enought starting mesh for the given number of ranks. The value of the
    /// variable will be defined in function \ref checkParallelMacroFile.
    int nParallelPreRefinements;
#endif

  protected:
    /// for findElement-Fcts
    DimVec<double> final_lambda;

    /// Temporary variables that are used in functions \ref findElInfoAtPoint
    /// and \ref findElementAtPointRecursive.
    WorldVector<double> const *g_xy0, *g_xy;

    /// Temporary variable that is used in functions \ref findElInfoAtPoint and
    /// \ref findElementAtPointRecursive.
    double* g_sp;

    friend class MacroInfo;
    friend class io::MacroReader;
    friend struct io::MacroWriter;
  };

  /// Accessor class used as passkey pattern in the setIndex method
  /// to provide access to this specific method only.
  class MeshAccessor
  {
    MeshAccessor() = default;
    MeshAccessor(MeshAccessor const&) = default;

    friend class Mesh;
  };

  class BoundaryWrapper
  {
  public:
    BoundaryWrapper(BoundaryType nr, Mesh* mesh = NULL)
      : nr(nr),
        mesh(mesh)
    {}

    Mesh* getMesh()
    {
      return mesh;
    }

    Mesh const* getMesh() const
    {
      return mesh;
    }

    BoundaryType getBoundary() const
    {
      return nr;
    }

  private:
    BoundaryType nr;
    Mesh* mesh;
  };

  // generator function for \ref BoundaryWrapper
  inline auto boundary(BoundaryType nr, Mesh* mesh = NULL)
    -> BoundaryWrapper
  {
    return {nr, mesh};
  }

} // end namespace AMDiS


text:
package org.shaolin.javacc.sql.node;

import org.shaolin.javacc.sql.IOQLNodeVisitor;
import org.shaolin.javacc.sql.exception.QueryParsingException;

public class OQLExtendField extends OQLSimpleField
{
    public OQLExtendField(String fieldName)
    {
        this.fieldName = fieldName;
    }

    public String getFieldName()
    {
        return fieldName;
    }

    public void visitWith(IOQLNodeVisitor v) throws QueryParsingException
    {
        v.visitExtendField(this);
    }

    private String fieldName = null;

    private static final long serialVersionUID = 2606896145662708323L;
}


text:
import { RainScatteredNight24 } from "../../";

export = RainScatteredNight24;


text:
local addon, ns = ...
local E = ns.E

if not E:C('auras', 'enabled') then return end;

local size = E:C('auras', 'size')
local spacing = E:C('auras', 'spacing')
local max_per_row = E:C('auras', 'max_per_row')

local sInterfaceBuffFrame = CreateFrame('Frame', addon..'BuffFrame', UIParent)
local sInterfaceBuffFrameWidth = (size * E:C('auras', 'max_per_row')) + ((-E:C('auras', 'spacing') - 1) * E:C('auras', 'max_per_row'))
local sInterfaceBuffFrameHeight  = size
sInterfaceBuffFrame:SetSize(sInterfaceBuffFrameWidth, sInterfaceBuffFrameHeight)

local function updateBuffFrameAnchor()
	if (Minimap:IsShown()) then
		sInterfaceBuffFrame:SetPoint("TOPRIGHT", Minimap, "TOPLEFT", E:C('auras', 'spacing'), 0);
	else
		sInterfaceBuffFrame:SetPoint("TOPRIGHT", sInterfaceFrame, "TOPRIGHT", -E:C('general', 'edgeSpacing'), -E:C('general', 'edgeSpacing'));
	end
end
updateBuffFrameAnchor()

Minimap:HookScript("OnHide", updateBuffFrameAnchor)
Minimap:HookScript("OnShow", updateBuffFrameAnchor)

local function style(aura)
	if not aura or (aura and aura.styled) then return end

	local name = aura:GetName()
	local icon = _G[name.."Icon"]
	icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)

	local border = _G[name.."Border"]
	if border then border:SetAlpha(0) end

	aura:SetSize(size, size)

	aura.duration:SetParent(aura)
	aura.duration:SetPoint("TOP", aura, "BOTTOM", 0, 6)
	aura.duration:SetJustifyH("CENTER")
	aura.duration:SetFontObject("GameFontNormalOutline")

	E:ShadowedBorder(aura)

	aura.styled = true
end

local function updateBuffAnchors()
	local previousBuff, aboveBuff

	local buffs = {}

	for i = 1, BuffFrame.numEnchants do
		local buff = _G["TempEnchant"..i]
		if not buff then return end
		if buff:IsShown() then
			table.insert(buffs, buff)
		end
	end

	for i = 1, BUFF_ACTUAL_DISPLAY do
		local buff = _G["BuffButton"..i]
		if not buff then return end
		if buff:IsShown() then
			table.insert(buffs, buff)
		end
	end

	for i, buff in next, buffs do
		style(buff)

		buff:ClearAllPoints()

		if i > 1 and mod(i, max_per_row) == 1 then
			buff:SetPoint("TOPRIGHT", aboveBuff, "BOTTOMRIGHT", 0, spacing*2)
			aboveBuff = buff
		elseif i == 1 then
			buff:SetPoint("TOPRIGHT", sInterfaceBuffFrame, "TOPRIGHT", 0, 0)
			aboveBuff = buff
		else
			buff:SetPoint("RIGHT", previousBuff, "LEFT", spacing, 0)
		end
		previousBuff = buff
	end
end

local function updateDebuffAnchors()
	local debuff, previousDebuff, aboveDebuff
	for i = 1, DEBUFF_MAX_DISPLAY do
		debuff = _G["DebuffButton"..i]
		if not debuff then return end
		style(debuff)

		if i > 1 and mod(i, max_per_row) == 1 then
			debuff:SetPoint("TOPRIGHT", aboveDebuff, "BOTTOMRIGHT", 0, spacing*2)
			aboveDebuff = debuff
		elseif i ==1 then
			if BUFF_ACTUAL_DISPLAY == 0 then
				debuff:SetPoint("TOPRIGHT", sInterfaceBuffFrame, "TOPRIGHT", 0, 0)
			else
				local anchorIndex, anchor, modulo, ab
				modulo = BUFF_ACTUAL_DISPLAY % max_per_row
				ab = abs(modulo - 1)
				anchorIndex = modulo == 0 and (BUFF_ACTUAL_DISPLAY - (max_per_row - 1)) or (BUFF_ACTUAL_DISPLAY - ab)
				anchor = _G["BuffButton"..anchorIndex]
				debuff:ClearAllPoints()
				debuff:SetPoint("TOPRIGHT", anchor, "BOTTOMRIGHT", 0, spacing*6)
			end
			aboveDebuff = debuff
		else
			debuff:SetPoint("RIGHT", previousDebuff, "LEFT", spacing, 0)
		end
		previousDebuff = debuff
	end
end

hooksecurefunc("BuffFrame_UpdateAllBuffAnchors", updateBuffAnchors)
hooksecurefunc("DebuffButton_UpdateAnchors", updateDebuffAnchors)


text:
package org.apache.avro;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

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

import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.junit.Test;

public class TestSchema {
  @Test
  public void testSplitSchemaBuild() {
    Schema s = SchemaBuilder
       .record("HandshakeRequest")
       .namespace("org.apache.avro.ipc").fields()
         .name("clientProtocol").type().optional().stringType()
         .name("meta").type().optional().map().values().bytesType()
         .endRecord();

    String schemaString = s.toString();
    final int mid = schemaString.length() / 2;

    Schema parsedStringSchema = new org.apache.avro.Schema.Parser().parse(s.toString());
    Schema parsedArrayOfStringSchema =
      new org.apache.avro.Schema.Parser().parse
      (schemaString.substring(0, mid), schemaString.substring(mid));
    assertNotNull(parsedStringSchema);
    assertNotNull(parsedArrayOfStringSchema);
    assertEquals(parsedStringSchema.toString(), parsedArrayOfStringSchema.toString());
  }

  @Test
  public void testDuplicateRecordFieldName() {
    final Schema schema = Schema.createRecord("RecordName", null, null, false);
    final List<Field> fields = new ArrayList<Field>();
    fields.add(new Field("field_name", Schema.create(Type.NULL), null, null));
    fields.add(new Field("field_name", Schema.create(Type.INT), null, null));
    try {
      schema.setFields(fields);
      fail("Should not be able to create a record with duplicate field name.");
    } catch (AvroRuntimeException are) {
      assertTrue(are.getMessage().contains("Duplicate field field_name in record RecordName"));
    }
  }
}


text:
package com.github.bingoohuang.utils.time;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

// 规整时间日期表示字符串(例如:2018-10-23 21:47,2018/10/23 21:48:15,2018-10-23T21:48:15.235)
@RequiredArgsConstructor @Slf4j
public class DateTimeRegular {
    private final String dateTimeStr;

    private int year = 1970;
    private int monthOfYear = 1;
    private int dayOfMonth = 1;
    private int hourOfDay = 0;
    private int minuteOfHour = 0;
    private int secondOfMinute = 0;
    private int millisOfSecond = 0;

    public DateTime regular() {
        if (StringUtils.isEmpty(dateTimeStr)) return null;

        String dts = dateTimeStr.trim();
        dts = dts.replaceAll("\\s+", "T");
        dts = dts.replace('日', 'T');
        val posT = dts.indexOf("T");

        val splitter = Splitter.onPattern("[^\\d]+");

        String ts;
        if (posT > 0) {
            String ds = dts.substring(0, posT);
            val parts = Iterables.toArray(splitter.split(ds), String.class);
            parseDate(parts);

            ts = dts.substring(posT + 1);
        } else {
            ts = dts;
        }

        val parts = Iterables.toArray(splitter.split(ts), String.class);
        if (ts.contains(":")) {
            parseTime(parts);
        } else {
            parseDate(parts);
        }

        if (year < 100) year += 2000;

        return new DateTime(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
    }

    private void parseTime(String[] parts) {
        int partsLen = parts.length;
        if (parts[partsLen - 1].length() == 3) {
            millisOfSecond = Integer.parseInt(parts[partsLen - 1]);
            partsLen--;
        }

        if (partsLen >= 2) {
            hourOfDay = Integer.parseInt(parts[0]);
            minuteOfHour = Integer.parseInt(parts[1]);
        }

        if (partsLen >= 3) {
            secondOfMinute = Integer.parseInt(parts[2]);
        }
    }

    private void parseDate(String[] parts) {
        if (parts.length == 3 || parts.length == 2) {
            if (parts[0].length() == 4) {
                year = Integer.parseInt(parts[0]);
                monthOfYear = Integer.parseInt(parts[1]);
                if (parts.length == 3) dayOfMonth = Integer.parseInt(parts[2]);
            } else if (parts.length == 3) {
                year = Integer.parseInt(parts[0]);
                monthOfYear = Integer.parseInt(parts[1]);
                dayOfMonth = Integer.parseInt(parts[2]);
            } else {
                monthOfYear = Integer.parseInt(parts[0]);
                dayOfMonth = Integer.parseInt(parts[1]);
            }
        } else {
            log.warn("unknown format for datetime {}", dateTimeStr);
        }
    }
}


text:
@implementation LastModifiedBy

@synthesize application;
@synthesize user;

@end


text:
from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
import h2o

from lifelines import CoxPHFitter
from pandas.testing import assert_frame_equal
from pandas import read_csv

import numpy as np

from tests import pyunit_utils
from h2o.estimators.coxph import H2OCoxProportionalHazardsEstimator

def coxph_concordance_and_baseline():
    shelter = read_csv(pyunit_utils.locate("smalldata/coxph_test/shelter.csv"), low_memory=False)
    shelter.drop("animal_id", axis=1, inplace=True)
    for colname in ["animal_type", "animal_breed", "activity_number", "census_tract", "activity_sequence"
                    , "intake_condition1", "intake_condition2", "intake_condition3", "council_district"
                    , "intake_type", "intake_subtype", "due_out", "outcome_type", "outcome_subtype"
                    , "intake_condition", "outcome_condition", "chip_status"]:
        shelter[colname] = shelter[colname].astype("category")
    for colname in ["end_ts", "intake_date", "intake_time", "start_ts"]:
        shelter[colname] = shelter[colname].astype("datetime64")

    without_strata(shelter)
    with_strata(shelter)
    with_strata_one_column(shelter)

def without_strata(shelter):
    check_cox(shelter
              , x=["intake_condition", "intake_type", "animal_breed", "chip_status", "surv_hours"]
              , expected_hazard_cols=["baseline hazard"]
              , expected_survival_cols=["baseline survival"]
              , stratify_by=[]
              )

def with_strata(shelter):
    baseline_cols = ["(" + c1 + ", " + c2 + ")" for c1 in ["CONFISCATED", "OWNER SURRENDER", "STRAY"]
                     for c2 in ["NONE", "TREATABLE MANAGEABLE", "TREATABLE REHABILITABLE", "UNHEALTHY UNTREATABLE"]]

    check_cox(shelter
              , x=["intake_condition1", "intake_condition2", "intake_type", "animal_breed", "chip_status", "surv_hours"]
              , expected_hazard_cols=baseline_cols
              , expected_survival_cols=baseline_cols
              , stratify_by=["intake_type", "intake_condition1"]
              )

def with_strata_one_column(shelter):
    baseline_cols = ["(CONFISCATED)", "(OWNER SURRENDER)", "(STRAY)"]
    check_cox(shelter
              , x=["intake_condition1", "intake_condition2", "intake_type", "animal_breed", "chip_status", "surv_hours"]
              , expected_hazard_cols=baseline_cols
              , expected_survival_cols=baseline_cols
              , stratify_by=["intake_type"]
              )

def check_cox(shelter, x, expected_hazard_cols, expected_survival_cols, stratify_by=None, weight=None):
    shelter = shelter[x + ['event'] + ([weight] if weight else [])]

    for col in stratify_by:
        shelter[col] = shelter[col].astype('category')

    shelter_h2o = h2o.H2OFrame(shelter)

    for col in stratify_by:
        shelter_h2o[col] = shelter_h2o[col].asfactor()

    cph_h2o = H2OCoxProportionalHazardsEstimator(stop_column="surv_hours", stratify_by=stratify_by)
    cph_h2o.train(x=x, y="event", weights_column=weight, training_frame=shelter_h2o)

    assert cph_h2o.model_id != ""

    pred_h2o = cph_h2o.predict(test_data=shelter_h2o)
    assert len(pred_h2o) == len(shelter)
    hazard_h2o_as_pandas = cph_h2o.baseline_hazard_frame.as_data_frame(use_pandas=True)

    hazard_h2o_reordered_columns = hazard_h2o_as_pandas.drop('t', axis="columns")\
                                                       .reset_index( drop=True)\
                                                       .sort_index(axis=1)

    assert hazard_h2o_reordered_columns.columns.values.tolist() == expected_hazard_cols

    survival_h2o_as_pandas = cph_h2o.baseline_survival_frame.as_data_frame(use_pandas=True)

    survival_h2o_reordered_columns = survival_h2o_as_pandas.drop('t', axis="columns")\
                                                       .reset_index( drop=True)\
                                                       .sort_index(axis=1)

    assert survival_h2o_reordered_columns.columns.values.tolist() == expected_survival_cols

# There are different API versions for concordance in lifelines library
def concordance_for_lifelines(cph):
    if "_model" in cph.__dict__.keys():
        py_concordance = cph._model._concordance_index_
    elif "_concordance_index_" in cph.__dict__.keys():
        py_concordance = cph._concordance_index_
    else:
        py_concordance = cph._concordance_score_
    return py_concordance

if __name__ == "__main__":
    pyunit_utils.standalone_test(coxph_concordance_and_baseline)
else:
    coxph_concordance_and_baseline()


text:
package org.motechproject.security.model;

import org.motechproject.security.domain.MotechUser;

import java.util.List;

public class UserDto {

    private String externalId;

    private String userName;

    private String password;

    private String email;

    private List<String> roles;

    private boolean active;

    private String openId;

    private boolean generatePassword;

    public UserDto() {
    }

    public UserDto(MotechUser motechUser) {
        this.externalId = motechUser.getExternalId();
        this.userName = motechUser.getUserName();
        this.password = motechUser.getPassword();
        this.email = motechUser.getEmail();
        this.roles = motechUser.getRoles();
        this.active = motechUser.isActive();
        this.openId = motechUser.getOpenId();
        this.generatePassword = false;
    }

    public String getExternalId() {
        return externalId;
    }

    public void setExternalId(String externalId) {
        this.externalId = externalId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<String> getRoles() {
        return roles;
    }

    public void setRoles(List<String> roles) {
        this.roles = roles;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public String getOpenId() {
        return openId;
    }

    public void setOpenId(String openId) {
        this.openId = openId;
    }

    public boolean isGeneratePassword() {
        return generatePassword;
    }

    public void setGeneratePassword(boolean generatePassword) {
        this.generatePassword = generatePassword;
    }
}


text:
package com.google.template.soy.jssrc;

import com.google.common.base.Preconditions;

/**
 * Compilation options for the JS Src output target (backend).
 *
 */
public class SoyJsSrcOptions implements Cloneable {

  /**
   * The two supported code styles.
   */
  public static enum CodeStyle {
    STRINGBUILDER, CONCAT;
  }

  /** Whether to allow deprecated syntax (semi backwards compatible mode). */
  private boolean shouldAllowDeprecatedSyntax;

  /** Whether to enable use of injected data. */
  private boolean isUsingIjData;

  /** The output variable code style to use. */
  private CodeStyle codeStyle;

  /** Whether we should generate JSDoc with type info for the Closure Compiler. */
  private boolean shouldGenerateJsdoc;

  /** Whether we should generate code to provide/require Soy namespaces. */
  private boolean shouldProvideRequireSoyNamespaces;

  /** Whether we should generate code to provide/require template JS functions. */
  private boolean shouldProvideRequireJsFunctions;

  /** Whether we should generate code to provide both Soy namespaces and JS functions. */
  private boolean shouldProvideBothSoyNamespacesAndJsFunctions;

  /** Whether we should generate code to declare the top level namespace. */
  private boolean shouldDeclareTopLevelNamespaces;

  /** Whether we should generate Closure Library message definitions (i.e. goog.getMsg). */
  private boolean shouldGenerateGoogMsgDefs;

  /** Whether the Closure Library messages are external, i.e. "MSG_EXTERNAL_[soyGeneratedMsgId]". */
  private boolean googMsgsAreExternal;

  /**
   * The bidi global directionality as a static value, 1: ltr, -1: rtl, 0: unspecified. If 0, and
   * useGoogIsRtlForBidiGlobalDir is false, the bidi global directionality will actually be inferred
   * from the message bundle locale. This must not be the case when shouldGenerateGoogMsgDefs is
   * true, but is the recommended mode of operation otherwise.
   */
  private int bidiGlobalDir;

  /**
   * Whether to determine the bidi global direction at template runtime by evaluating
   * goog.i18n.bidi.IS_RTL. May only be true when both shouldGenerateGoogMsgDefs and either
   * shouldProvideRequireSoyNamespaces or shouldProvideRequireJsFunctions is true.
   */
  private boolean useGoogIsRtlForBidiGlobalDir;

  public SoyJsSrcOptions() {
    shouldAllowDeprecatedSyntax = false;
    isUsingIjData = false;
    codeStyle = CodeStyle.STRINGBUILDER;
    shouldGenerateJsdoc = false;
    shouldProvideRequireSoyNamespaces = false;
    shouldProvideRequireJsFunctions = false;
    shouldProvideBothSoyNamespacesAndJsFunctions = false;
    shouldDeclareTopLevelNamespaces = true;
    shouldGenerateGoogMsgDefs = false;
    googMsgsAreExternal = false;
    bidiGlobalDir = 0;
    useGoogIsRtlForBidiGlobalDir = false;
  }

  /**
   * Sets whether to allow deprecated syntax (semi backwards compatible mode).
   * @param shouldAllowDeprecatedSyntax The value to set.
   */
  public void setShouldAllowDeprecatedSyntax(boolean shouldAllowDeprecatedSyntax) {
    this.shouldAllowDeprecatedSyntax = shouldAllowDeprecatedSyntax;
  }

  /** Returns whether we're set to allow deprecated syntax (semi backwards compatible mode). */
  public boolean shouldAllowDeprecatedSyntax() {
    return shouldAllowDeprecatedSyntax;
  }

  /**
   * Sets whether to enable use of injected data (syntax is '$ij.*').
   * @param isUsingIjData The code style to set.
   */
  public void setIsUsingIjData(boolean isUsingIjData) {
    this.isUsingIjData = isUsingIjData;
  }

  /** Returns whether use of injected data is currently enabled. */
  public boolean isUsingIjData() {
    return isUsingIjData;
  }

  /**
   * Sets the output variable code style to use.
   * @param codeStyle The code style to set.
   */
  public void setCodeStyle(CodeStyle codeStyle) {
    this.codeStyle = codeStyle;
  }

  /** Returns the currently set code style. */
  public CodeStyle getCodeStyle() {
    return codeStyle;
  }

  /**
   * Sets whether we should generate JSDoc with type info for the Closure Compiler.
   * @param shouldGenerateJsdoc The value to set.
   */
  public void setShouldGenerateJsdoc(boolean shouldGenerateJsdoc) {
    this.shouldGenerateJsdoc = shouldGenerateJsdoc;
  }

  /** Returns whether we should generate JSDoc with type info for the Closure Compiler. */
  public boolean shouldGenerateJsdoc() {
    return shouldGenerateJsdoc;
  }

  /**
   * Sets whether we should generate code to provide/require Soy namespaces.
   * @param shouldProvideRequireSoyNamespaces The value to set.
   */
  public void setShouldProvideRequireSoyNamespaces(
      boolean shouldProvideRequireSoyNamespaces) {
    this.shouldProvideRequireSoyNamespaces = shouldProvideRequireSoyNamespaces;
    Preconditions.checkState(
        !(this.shouldProvideRequireSoyNamespaces && this.shouldProvideRequireJsFunctions),
        "Must not enable both shouldProvideRequireSoyNamespaces and" +
        " shouldProvideRequireJsFunctions.");
    Preconditions.checkState(
        !(!this.shouldDeclareTopLevelNamespaces && this.shouldProvideRequireSoyNamespaces),
        "Turning off shouldDeclareTopLevelNamespaces has no meaning when" +
        " shouldProvideRequireSoyNamespaces is enabled.");
  }

  /** Returns whether we're set to generate code to provide/require Soy namespaces. */
  public boolean shouldProvideRequireSoyNamespaces() {
    return shouldProvideRequireSoyNamespaces;
  }

  /**
   * Sets whether we should generate code to provide/require template JS functions.
   * @param shouldProvideRequireJsFunctions The value to set.
   */
  public void setShouldProvideRequireJsFunctions(
      boolean shouldProvideRequireJsFunctions) {
    this.shouldProvideRequireJsFunctions = shouldProvideRequireJsFunctions;
    Preconditions.checkState(
        !(this.shouldProvideRequireSoyNamespaces && this.shouldProvideRequireJsFunctions),
        "Must not enable both shouldProvideRequireSoyNamespaces and" +
        " shouldProvideRequireJsFunctions.");
    Preconditions.checkState(
        !(!this.shouldDeclareTopLevelNamespaces && this.shouldProvideRequireJsFunctions),
        "Turning off shouldDeclareTopLevelNamespaces has no meaning when" +
        " shouldProvideRequireJsFunctions is enabled.");
  }

  /** Returns whether we're set to generate code to provide/require template JS functions. */
  public boolean shouldProvideRequireJsFunctions() {
    return shouldProvideRequireJsFunctions;
  }

  /**
   * Sets whether we should generate code to provide both Soy namespaces and JS functions.
   * @param shouldProvideBothSoyNamespacesAndJsFunctions The value to set.
   */
  public void setShouldProvideBothSoyNamespacesAndJsFunctions(
      boolean shouldProvideBothSoyNamespacesAndJsFunctions) {
    this.shouldProvideBothSoyNamespacesAndJsFunctions =
        shouldProvideBothSoyNamespacesAndJsFunctions;
    if (shouldProvideBothSoyNamespacesAndJsFunctions) {
      Preconditions.checkState(
          this.shouldProvideRequireSoyNamespaces || this.shouldProvideRequireJsFunctions,
          "Must only enable shouldProvideBothSoyNamespacesAndJsFunctions after enabling either" +
          " shouldProvideRequireSoyNamespaces or shouldProvideRequireJsFunctions.");
    }
  }

  /** Returns whether we should generate code to provide both Soy namespaces and JS functions. */
  public boolean shouldProvideBothSoyNamespacesAndJsFunctions() {
    return shouldProvideBothSoyNamespacesAndJsFunctions;
  }

  /**
   * Sets whether we should generate code to declare the top level namespace.
   * @param shouldDeclareTopLevelNamespaces The value to set.
   */
  public void setShouldDeclareTopLevelNamespaces(
      boolean shouldDeclareTopLevelNamespaces) {
    this.shouldDeclareTopLevelNamespaces = shouldDeclareTopLevelNamespaces;
    Preconditions.checkState(
        !(!this.shouldDeclareTopLevelNamespaces && this.shouldProvideRequireSoyNamespaces),
        "Turning off shouldDeclareTopLevelNamespaces has no meaning when" +
        " shouldProvideRequireSoyNamespaces is enabled.");
    Preconditions.checkState(
        !(!this.shouldDeclareTopLevelNamespaces && this.shouldProvideRequireJsFunctions),
        "Turning off shouldDeclareTopLevelNamespaces has no meaning when" +
        " shouldProvideRequireJsFunctions is enabled.");
  }

  /** Returns whether we should attempt to declare the top level namespace. */
  public boolean shouldDeclareTopLevelNamespaces() {
    return shouldDeclareTopLevelNamespaces;
  }

  /**
   * Sets whether we should generate Closure Library message definitions (i.e. goog.getMsg).
   * @param shouldGenerateGoogMsgDefs The value to set.
   */
  public void setShouldGenerateGoogMsgDefs(boolean shouldGenerateGoogMsgDefs) {
    this.shouldGenerateGoogMsgDefs = shouldGenerateGoogMsgDefs;
  }

  /** Returns whether we should generate Closure Library message definitions (i.e. goog.getMsg). */
  public boolean shouldGenerateGoogMsgDefs() {
    return shouldGenerateGoogMsgDefs;
  }

  /**
   * Sets whether the generated Closure Library message definitions are for external messages
   * (only applicable if shouldGenerateGoogMsgDefs is true).
   *
   * If this option is true, then we generate
   *     var MSG_EXTERNAL_[soyGeneratedMsgId] = goog.getMsg(...);
   * If this option is false, then we generate
   *     var MSG_UNNAMED_[uniquefier] = goog.getMsg(...);
   *
   * @param googMsgsAreExternal The value to set.
   */
  public void setGoogMsgsAreExternal(boolean googMsgsAreExternal) {
    this.googMsgsAreExternal = googMsgsAreExternal;
  }

  /**
   * Returns whether the generated Closure Library message definitions are for external messages
   * (only applicable if shouldGenerateGoogMsgDefs is true).
   *
   * If this option is true, then we generate
   *     var MSG_EXTERNAL_[soyGeneratedMsgId] = goog.getMsg(...);
   * If this option is false, then we generate
   *     var MSG_UNNAMED_[uniquefier] = goog.getMsg(...);
   */
  public boolean googMsgsAreExternal() {
    return googMsgsAreExternal;
  }

  /**
   * Sets the bidi global directionality to a static value, 1: ltr, -1: rtl, 0: unspecified. If 0,
   * and useGoogIsRtlForBidiGlobalDir is false, the bidi global directionality will actually be
   * inferred from the message bundle locale. This is the recommended mode of operation when
   * shouldGenerateGoogMsgDefs is false. When shouldGenerateGoogMsgDefs is true, the bidi global
   * direction can not be left unspecified, but the recommended way of doing so is via
   * setUseGoogIsRtlForBidiGlobalDir(true). Thus, whether shouldGenerateGoogMsgDefs is true or not,
   * THERE IS USUALLY NO NEED TO USE THIS METHOD!
   *
   * @param bidiGlobalDir 1: ltr, -1: rtl, 0: unspecified. Checks that no other value is used.
   */
  public void setBidiGlobalDir(int bidiGlobalDir) {
    Preconditions.checkArgument(
        bidiGlobalDir >= -1 && bidiGlobalDir <= 1,
        "bidiGlobalDir must be 1 for LTR, or -1 for RTL (or 0 to leave unspecified).");
    Preconditions.checkState(
        !useGoogIsRtlForBidiGlobalDir || bidiGlobalDir == 0,
        "Must not specify both bidiGlobalDir and useGoogIsRtlForBidiGlobalDir.");
    this.bidiGlobalDir = bidiGlobalDir;
  }

  /**
   * Returns the static bidi global directionality, 1: ltr, -1: rtl, 0: unspecified.
   */
  public int getBidiGlobalDir() {
    return bidiGlobalDir;
  }

  /**
   * Sets the Javascript code snippet that will evaluate at template runtime to a boolean value
   * indicating whether the bidi global direction is rtl. Can only be used when
   * shouldGenerateGoogMsgDefs is true.
   *
   * @param useGoogIsRtlForBidiGlobalDir Whether to determine the bidi global direction at template
   *     runtime by evaluating goog.i18n.bidi.IS_RTL.
   */
  public void setUseGoogIsRtlForBidiGlobalDir(boolean useGoogIsRtlForBidiGlobalDir) {
    Preconditions.checkState(
        !useGoogIsRtlForBidiGlobalDir || shouldGenerateGoogMsgDefs,
        "Do not specify useGoogIsRtlForBidiGlobalDir without shouldGenerateGoogMsgDefs.");
    Preconditions.checkState(
        !useGoogIsRtlForBidiGlobalDir ||
        shouldProvideRequireSoyNamespaces || shouldProvideRequireJsFunctions,
        "Do not specify useGoogIsRtlForBidiGlobalDir without either" +
        " shouldProvideRequireSoyNamespaces or shouldProvideRequireJsFunctions.");
    Preconditions.checkState(
        !useGoogIsRtlForBidiGlobalDir || bidiGlobalDir == 0,
        "Must not specify both bidiGlobalDir and useGoogIsRtlForBidiGlobalDir.");
    this.useGoogIsRtlForBidiGlobalDir = useGoogIsRtlForBidiGlobalDir;
  }

  /**
   * Returns whether to determine the bidi global direction at template runtime by evaluating
   * goog.i18n.bidi.IS_RTL. May only be true when shouldGenerateGoogMsgDefs is true.
   */
  public boolean getUseGoogIsRtlForBidiGlobalDir() {
    return useGoogIsRtlForBidiGlobalDir;
  }

  @Override public SoyJsSrcOptions clone() {
    try {
      return (SoyJsSrcOptions) super.clone();
    } catch (CloneNotSupportedException cnse) {
      throw new RuntimeException("Cloneable interface removed from SoyJsSrcOptions.");
    }
  }

}


text:
Labels in maps are a huge headache, and have been for a long time. There are lots of solutions for 2D mapping, but not so many when you work in 3D, and especially not when your map shifts between 2D and 3D.

###The Experiements

The main trick is a 2D projection of the geometry to place the text, within the canvas. Like a heads-up display layer between the 3D geometry and the camera.

Like this:
![HUD](images/Pg_24_top.JPG)

In the canvas:
![projection](images/projection.png)

Pros:

* Fonts don't need to be resized on zoom

* No off-screen computations

* We know exactly what the user sees

Cons:

* Occlusion becomes a problem: Should labels be visible through buildings? Which labels to prioritize, how to prioritize them? For now, these have no occlusion.

### Line Labels

* Fit and repeat

```
	float lastSeed = 0.0;
	for (int i = 0; i < _anchorLine.size()-1; i++) {
		float offset = _anchorLine.getDistances()[i];
		float segmentLength = _anchorLine.getDistances()[i+1]-_anchorLine.getDistances()[i];//_anchorLine.getPolars()[i].r;

		//  Fits?
		//
		if( segmentLength >= (m_label.width+_maxDistance) ){
			//  How many times?
			int nTimes = segmentLength/(m_label.width+_maxDistance);

			//  At what distance between each other?
			float margin = (segmentLength-m_label.width*(float)nTimes)/((float)nTimes+1.0);

			//  Add anchors points for seeds
			float seed = margin;
			for (int i = 0; i < nTimes; i++) {
				float potentialSeed = offset + seed ;
				if( potentialSeed-lastSeed > _minDistance ){
					lastSeed = potentialSeed;
					_anchorLine.marks.push_back(lastSeed);
					seed += m_label.width+margin;
				}
			}
		} else if ( segmentLength >= m_label.width+_minDistance){
			//  Only one time
			//
			float margin = (segmentLength-m_label.width)*0.5;
			float potentialSeed = offset + margin ;
			if( potentialSeed-lastSeed > _minDistance){
				lastSeed = potentialSeed;
				_anchorLine.marks.push_back(lastSeed);
			}
		}
	}
```

![01](images/01.gif)

* Fade according to tilt angle

```
	float angle = glm::dot(glm::normalize( *m_cameraPos - shapes[0].getCentroid()),glm::vec3(0.,0.,1.));
	m_alpha = lerpValue(m_alpha,powf( CLAMP(angle,0.01,1.0), 1.15 ),0.1);
```

![02](images/02.gif)

* Curved path following

```
	float angle = PI;
	glm::vec3 diff = _anchorLine[0]-_anchorLine[_anchorLine.size()-1];
	angle = atan2f(-diff.y, diff.x);

	if(angle < PI*0.5 && angle > -PI*0.5){
		for (int i = m_text.length()-1; i >=0 ; i--) {
			glm::vec3 src = _anchorLine.getPositionAt(_offset);
			if(screen.inside(src)){
				double rot = _anchorLine.getAngleAt(_offset);
				glPushMatrix();
				glTranslated(src.x, src.y, src.z);
				glScalef(1,-1,1);
				glRotated(rot*RAD_TO_DEG, 0, 0, -1);
				glScaled(-1, -1, 1);
				glTranslated(-m_lettersWidth[i], 0, 0);
				glTranslatef(0., -m_label.height*0.5,0.);
				m_font->drawString( std::string(1,m_text[i]), m_alpha );
				glPopMatrix();
				_offset += m_lettersWidth[i];
			} else {
				break;
			}
		}
	} else {
		for (int i = 0; i < m_text.length(); i++) {
			glm::vec3 src = _anchorLine.getPositionAt(_offset);
			if(screen.inside(src)){
				double rot = _anchorLine.getAngleAt(_offset);
				glPushMatrix();
				glTranslated(src.x, src.y, src.z);
				glScalef(1,-1,1);
				glRotated(rot*RAD_TO_DEG, 0, 0, -1);
				glTranslatef(0., -m_label.height*0.5,0.);
				m_font->drawString( std::string(1,m_text[i]), m_alpha );
				glPopMatrix();
				_offset += m_lettersWidth[i];
			} else {
				break;
			}
		}
	}
```

![07](images/07.gif)

### Point Labels

* Project top points

```
	glm::ivec4 viewport;
	glm::mat4x4 mvmatrix, projmatrix;
	glGetIntegerv(GL_VIEWPORT, &viewport[0]);
	glGetFloatv(GL_MODELVIEW_MATRIX, &mvmatrix[0][0]);
	glGetFloatv(GL_PROJECTION_MATRIX, &projmatrix[0][0]);
	m_anchorPoint = glm::project(m_centroid+m_offset, mvmatrix, projmatrix, viewport);
```

![03](images/03.gif)

* Mutual occlusion using depth sort and bounding boxes

```
	bool depthSort(const glmFeatureLabelPointRef &_A, const glmFeatureLabelPointRef &_B){
		return _A->getAnchorPoint().z < _B->getAnchorPoint().z;
	}

	…

	std::sort(pointLabels.begin(),pointLabels.end(), depthSort);
	for (int i = 0; i < pointLabels.size(); i++) {
		if(pointLabels[i]->bVisible){
			for (int j = i-1; j >= 0 ; j--) {
				if (pointLabels[i]->isOver( pointLabels[j].get() ) ){
					pointLabels[i]->bVisible = false;
					break;
				}
			}
		}
	}
```

![04](images/04.gif)

* Occlude line labels with bounding box

```
	double rot = _anchorLine.getAngleAt(_offset);
	glmRectangle boundingBox = glmPolyline(m_label,angle).getBoundingBox();
	boundingBox.translate(_anchorLine.getPositionAt(_offset+m_label.width*0.5));

	bool bOver = false;
	for (int i = 0; i < pointLabels->size(); i++ ){
		if(pointLabels->at(i)->bVisible){
			if( boundingBox.intersects(pointLabels->at(i)->getLabel(0) ) ){
				bOver = true;
				break;
			}
		}
	}
```

![06](images/06.gif)

* Street level point of view
![05](images/05.gif)

## Dependencies

* [glmTools](https://github.com/tangram-map/glmTools)
	-	[openGL](http://www.opengl.org/)
	- [glm](http://glm.g-truc.net/0.9.5/index.html)

* [glmFTGL](https://github.com/tangram-map/glmFTGL)
	- [FTGL](http://sourceforge.net/projects/ftgl/)

* [cURL](http://curl.haxx.se/libcurl/)
* [JsonCpp](https://github.com/open-source-parsers/jsoncpp)

## Notes

Compile with linker flags ```-lcurl```


text:
package org.elasticsearch.client;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;

public class NodesResponseHeaderTestUtils {

    public static void toXContent(NodesResponseHeader header, String clusterName, XContentBuilder builder) throws IOException {
        builder.startObject("_nodes");
        builder.field("total", header.getTotal());
        builder.field("successful", header.getSuccessful());
        builder.field("failed", header.getFailed());

        if (header.getFailures().isEmpty() == false) {
            builder.startArray("failures");
            for (ElasticsearchException failure : header.getFailures()) {
                builder.startObject();
                failure.toXContent(builder, ToXContent.EMPTY_PARAMS);
                builder.endObject();
            }
            builder.endArray();
        }

        builder.endObject();
        builder.field("cluster_name", clusterName);
    }

}


text:
<?php

namespace api\models;

use common\models\Token;
use common\models\User;
use yii\base\Model;

/**
 * Registration form
 */
class RegistrationForm extends Model
{
    public $username;
    public $password;
    public $email;
    public $create_at;
    public $password_hash;

    private $_user;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
        ];
    }
}


text:
<?php $this->load->view('include/header.php'); ?>

<?php $this->load->view('include/navbar.php'); ?>
<?php $this->load->view('include/sidebar.php'); ?>

                        Editable Table

Gestion du parc : <?php echo $all_domains; ?> Domaines et <?php echo $all_subdomains; ?> Sous-domaines

                                  <button class="btn btn-success btn-ls" data-title="Ajouter" data-toggle="modal" data-target="#serptools" >Simulateur de SERP</button>

                                    <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">Tools
                                    </button>

Print

Save as PDF

Export to Excel

                                Nom
                                SERP
                                Meta Title
                                Meta Description
                                <?php if($this->uri->total_segments() != 2){ ?>
                                  Analyse Site
                                <?php } ?>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Simulateur de SERP

        <form id="form-serptools" method="post" action="<?php echo site_url('/dashboard/add'); ?>">

           70 Nombre de caractères 0 / 500 Nombre de pixels
            <input class="form-control" type="text" name="meta_title" id="meta_title" placeholder="Titre">

            <input class="form-control" type="text" name="meta_url" id="meta_url" placeholder="Url">

            156 Nombre de caractères 0 / 930 Nombre de pixels
            <textarea class="form-control" type="text" name="meta_description" id="meta_description" placeholder="Description"></textarea>

          <button type="submit" class="btn btn-success btn-lg"> Enregistrer</button>
          <button type="button" class="btn btn-default btn-lg" data-dismiss="modal"> Annuler</button>
        </form>

This is an Example of a Title Tag that is Seventy Characters in Length

                    www.website.com

                     - Here is an example of what a snippet looks like in Google's SERPs. The content that appears here is usually taken from the Meta Description tag if relevant.

<?php $this->load->view('include/footer.php'); ?>


text:
var gridOptions = {
    columnDefs: [
        { field: 'country', rowGroup: true, hide: true },
        { field: 'athlete' },
        { field: 'year' },
        { field: 'gold', aggFunc: 'sum' },
        { field: 'silver', aggFunc: 'sum' },
        { field: 'bronze', aggFunc: 'sum' },
        { field: 'total', aggFunc: 'sum' },
        { field: 'age' },
        { field: 'date' },
        { field: 'sport' },
    ],
    defaultColDef: {
        flex: 1,
        minWidth: 150,
        resizable: true,
    },
    autoGroupColumnDef: {
        headerName: 'Country',
        minWidth: 300,
    },
    animateRows: true,
    showOpenedGroup: true
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);

    agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' })
        .then(function(data) {
            gridOptions.api.setRowData(data);
        });
});


text:
// Code generated by client-gen. DO NOT EDIT.

package scheme

import (
	registered "k8s.io/apimachinery/pkg/apimachinery/registered"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	serializer "k8s.io/apimachinery/pkg/runtime/serializer"
	wardle "k8s.io/sample-apiserver/pkg/apis/wardle/install"
)

var Scheme = runtime.NewScheme()
var Codecs = serializer.NewCodecFactory(Scheme)
var ParameterCodec = runtime.NewParameterCodec(Scheme)

var Registry = registered.NewAPIRegistrationManager()

func init() {
	v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
	Install(Registry, Scheme)
}

// Install registers the API group and adds types to a scheme
func Install(registry *registered.APIRegistrationManager, scheme *runtime.Scheme) {
	wardle.Install(registry, scheme)
}


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

namespace Esiur.Security.Authority;
public enum AuthenticationState : int
{
    Denied = 0x1,
    Succeeded = 0x2,
    Blocked = 0x4,
    Rejected = 0x8,
    NeedsUpdate = 0x10,
    NotFound = 0x20
}


text:
package lightning.evaluator

import argonaut.Parse
import scalaz.std.iterable._
import scalaz.syntax.foldable._
import lightning.model.{ Dependency, Graph, Node, Visibility }
import lightning.model.Visibility

case class StatusEvaluatorSet(node: Node, evaluators: Set[StatusEvaluator]) {
  def apply(): Graph = evaluators.toList.par.map { e => transformResponse(e()) }.seq.suml

  private def transformResponse(response: StatusResponse): Graph = {
    val me = Visibility(node, true)
    response match {
    case ErrorStatusResponse(dl, nl, message) => Graph.empty ⊕ me ⥅ Visibility(Dependency(node, nl, s"$dl ($message)"), false)
      case UnsuccessfulStatusResponse(dl, nl) ⇒ Graph.empty ⊕ me ⥅ Visibility(Dependency(node, nl, dl), false)
      case SuccessfulStatusResponse(dl, g) => g.graph ⊕ me ⥅ Visibility(Dependency(node, g.root, dl), true)
    }
  }
}


text: The news section is in development.


text:
package org.renderdoc.renderdoccmd;
import android.app.Activity;

public class Loader extends android.app.NativeActivity
{
    /* load our native library */
    static {
        System.loadLibrary("renderdoc");
    }

    @Override
    protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Popup a dialog if we haven't granted Android storage permissions.
        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }
}


text:
package com.iluwatar.singleton;

/**
 * Enum based singleton implementation.
 * Effective Java 2nd Edition (Joshua Bloch) p. 18
 */
public enum EnumIvoryTower {

  INSTANCE;

  @Override
  public String toString() {
    return getDeclaringClass().getCanonicalName() + "@" + hashCode();
  }
}


text:
Creates lava by dropping 4x of any logWood into cryotheum.
`mods.inworldcrafting.FluidToFluid.transform(<liquid:lava>, <liquid:cryotheum>, [<ore:logWood> * 4]);`

* * *

Creates Treated Wood by dropping some Birch Planks in Creosote. `mods.inworldcrafting.FluidToItem.transform(<immersiveengineering:treated_wood>, <liquid:creosote>, [<minecraft:planks:2>]);`

* * *

Creates a Water Bottle by dropping a Glass Bottle in Water, consumes the Water sourceblock.
`mods.inworldcrafting.FluidToItem.transform(<minecraft:potion>.withTag({Potion: "minecraft:water"}), <liquid:water>, [<minecraft:glass_bottle>], true);`

* * *

Create Steel 15% of the time when ingotIron dropped in the world is hit by an Explosion.
`mods.inworldcrafting.ExplosionCrafting.explodeItemRecipe(<ore:ingotSteel>.firstItem, <ore:ingotIron>, 15);`

* * *

Create 8 sticks 75% of the time when Acacia Planks placed in the world is hit by an Explosion. `mods.inworldcrafting.ExplosionCrafting.explodeBlockRecipe(<minecraft:stick> * 8, <minecraft:planks:4>, 75);`

* * *

Create a Block of Charcoal when 4 pieces of logWood has burned for 60 ticks. `mods.inworldcrafting.FireCrafting.addRecipe(<thermalfoundation:storage_resource>, <ore:logWood> * 4, 60);`

# Documentation

## Note on fluidcrafting

**Don't add the same ingredient multiple times, use `<ingredient> * count`. It's there for a reason.**
The game merges nearby items into stacks so finding multiple ingredients of the same type in one BlockSpace only happens when the first EntityItem gets a full stack of items, so the craft won't happen like you would expect.

### BAAD!

`FluidToItem.transform(<minecraft:diamond>, <liquid:blueslime>, [<ore:ingotSteel>, <ore:ingotSteel>, <ore:dustCobalt>, <ore:nuggetEnderpearl>], true);`

### Goooood

`FluidToItem.transform(<minecraft:diamond>, <liquid:blueslime>, [<ore:ingotSteel> * 2, <ore:dustCobalt>, <ore:nuggetEnderpearl>], true);`

## Fluid to Item Transformation

import should be `mods.inworldcrafting.FluidToItem`

**Usage**
`FluidToItem.transform(IItemStack output, ILiquidStack inputFluid, IIngredient[] inputItems, @Optional boolean consume);`

The default consume value for this method is `true`, so if you don't want the `inputItem` to be consumed when transforming the liquid you have to pass `false` as the 4th paramater to the method.

## Fluid to Fluid Transformation

import should be `mods.inworldcrafting.FluidToFluid`

**Usage**
`FluidToFluid.transform(ILiquidStack output, ILiquidStack inputFluid, IIngredient[] inputItems, @Optional boolean consume);`

The default consume value for this method is `true`, so if you don't want the `inputItem` to be consumed when transforming the liquid you have to pass `false` as the 4th paramater to the method.

## Burning Items

import should be `mods.inworldcrafting.FireCrafting`

**Usage**
`FireCrafting.addRecipe(IItemStack output, IIngredient inputItem, @Optional int ticks);`

The default number of ticks to create the output is `40` (2 seconds)

## Exploding Items/Blocks

import should be `mods.inworldcrafting.ExplosionCrafting`

### Exploding items

**Usage**
`ExplosionCrafting.explodeItemRecipe(IItemStack output, IIngredient inputItem, @Optional int survicechance);`

Survivechance sets the chance for how likely the recipe is to be successful. Default value is `100`%

### Exploding Blocks

**Usage**
`ExplosionCrafting.explodeBlockRecipe(IItemStack output, IItemStack blockStack, @Optional int itemSpawnChance);`

`blockStack` should be a `Block` in its stackform. It will compare against metadata. `itemSpawnChance` sets the chance for how likely the block is to spawn the output when the block is destroyed by an explosion. Default value is `100`%


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe GroupsController do
  it_should_behave_like "an authorized controller"
  include_context "authorized"
  include_context "authenticated"

  def mock_group(stubs={})
    @mock_group ||= mock_model(Group, stubs)
  end

  before do
    @mock_school=mock_school(:groups=>Group)
    controller.stub!(:current_school=>@mock_school)
  end

  describe "responding to GET index" do

    it "should expose all groups as @groups" do
      Group.should_receive(:paged_by_title).and_return(g=[mock_group])
      g.stub!(:out_of_bounds? => false)
      get :index
      assigns(:groups).should == [mock_group]
    end

  end

  describe "responding to GET show" do

    it "should expose the requested group as @group" do
      Group.should_receive(:find).with("37").and_return(mock_group)
      get :show, :id => "37"
      assigns(:group).should equal(mock_group)
    end

  end

  describe "responding to GET new" do

    it "should expose a new group as @group" do
      Group.should_receive(:new).and_return(mock_group)
      get :new
      assigns(:group).should equal(mock_group)
    end

  end

  describe "responding to GET edit" do

    it "should expose the requested group as @group" do
      Group.should_receive(:find).with("37").and_return(mock_group)
      get :edit, :id => "37"
      assigns(:group).should equal(mock_group)
    end

  end

  describe "responding to POST create" do

    describe "with valid params" do

      it "should expose a newly created group as @group" do
        Group.should_receive(:build).with({'these' => 'params'}).and_return(mock_group(:save => true))
        post :create, :group => {:these => 'params'}
        assigns(:group).should equal(mock_group)
      end

      it "should redirect to the created group" do
        Group.stub!(:build).and_return(mock_group(:save => true))
        post :create, :group => {}
        response.should redirect_to(group_url(mock_group))
      end

      it "should have a link to the group in the flash" do
        Group.stub!(:build).and_return(mock_group(:save => true))
        post :create, :group => {}
        flash[:notice].should match(/#{edit_group_path(mock_group)}/)
      end

    end

    describe "with invalid params" do

      it "should expose a newly created but unsaved group as @group" do
        Group.stub!(:build).with({'these' => 'params'}).and_return(mock_group(:save => false))
        post :create, :group => {:these => 'params'}
        assigns(:group).should equal(mock_group)
      end

      it "should re-render the 'new' template" do
        Group.stub!(:build).and_return(mock_group(:save => false))
        post :create, :group => {}
        response.should render_template('new')
      end

    end

  end

  describe "responding to PUT udpate" do

    describe "with valid params" do

      it "should update the requested group" do
        Group.should_receive(:find).with("37").and_return(mock_group)
        mock_group.should_receive(:update_attributes).with({'these' => 'params'})
        put :update, :id => "37", :group => {:these => 'params'}
      end

      it "should expose the requested group as @group" do
        Group.stub!(:find).and_return(mock_group(:update_attributes => true))
        put :update, :id => "1"
        assigns(:group).should equal(mock_group)
      end

      it "should redirect to the group" do
        Group.stub!(:find).and_return(mock_group(:update_attributes => true))
        put :update, :id => "1"
        response.should redirect_to(group_url(mock_group))
      end

      it "should have a link to the group in the flash" do
        Group.stub!(:find).and_return(mock_group(:update_attributes => true))
        put :update, :id => "1"
        flash[:notice].should match(/#{edit_group_path(mock_group)}/)
      end

    end

    describe "with invalid params" do

      it "should update the requested group" do
        Group.should_receive(:find).with("37").and_return(mock_group)
        mock_group.should_receive(:update_attributes).with({'these' => 'params'})
        put :update, :id => "37", :group => {:these => 'params'}
      end

      it "should expose the group as @group" do
        Group.stub!(:find).and_return(mock_group(:update_attributes => false))
        put :update, :id => "1"
        assigns(:group).should equal(mock_group)
      end

      it "should re-render the 'edit' template" do
        Group.stub!(:find).and_return(mock_group(:update_attributes => false))
        put :update, :id => "1"
        response.should render_template('edit')
      end

    end

  end

  describe "responding to DELETE destroy" do

    it "should destroy the requested group" do
      Group.should_receive(:find).with("37").and_return(mock_group)
      mock_group.should_receive(:destroy)
      delete :destroy, :id => "37"
    end

    it "should redirect to the groups list" do
      Group.stub!(:find).and_return(mock_group(:destroy => true))
      delete :destroy, :id => "1"
      response.should redirect_to(groups_url)
    end

  end

  describe "responding to DELETE remove_user"  do
    it "should remove the user from the group" do
      mg=mock_group
      Group.should_receive(:find).and_return(mg)
      mg.should_receive(:user_group_assignments).and_return( UserGroupAssignment)
      UserGroupAssignment.should_receive(:find).with("222").and_return(muga=mock_user_group_assignment)
      muga.should_receive(:destroy)
      delete "remove_user", :id=>"1", :user_assignment_id=>"222"
      response.should redirect_to(group_url(mg))
    end

  end

end