text:
import ast
import warnings

import astropy.units as u
import numpy as np
from astropy import log
from astropy.table import QTable, Table

from .extern.validator import validate_array, validate_scalar

__all__ = [
    "generate_energy_edges",
    "sed_conversion",
    "build_data_table",
    "estimate_B",
]

# Input validation tools

def validate_column(data_table, key, pt, domain="positive"):
    try:
        column = data_table[key]
        array = validate_array(
            key,
            u.Quantity(column, unit=column.unit),
            physical_type=pt,
            domain=domain,
        )
    except KeyError:
        raise TypeError(
            'Data table does not contain required column "{0}"'.format(key)
        )

    return array

def validate_data_table(data_table, sed=None):
    """
    Validate all columns of a data table. If a list of tables is passed, all
    tables will be validated and then concatenated

    Parameters
    ----------

    data_table : `astropy.table.Table` or list of `astropy.table.Table`.

    sed : bool, optional
        Whether to convert the fluxes to SED. If unset, all data tables are
        converted to the format of the first data table.
    """
    if isinstance(data_table, Table) or isinstance(data_table, QTable):
        data_table = [data_table]

    try:
        for dt in data_table:
            if not isinstance(dt, Table) and not isinstance(dt, QTable):
                raise TypeError(
                    "An object passed as data_table is not an astropy Table!"
                )
    except TypeError:
        raise TypeError(
            "Argument passed to validate_data_table is not a table and "
            "not a list"
        )

    def dt_sed_conversion(dt, sed):
        f_unit, sedf = sed_conversion(dt["energy"], dt["flux"].unit, sed)
        # roundtrip to Table to change the units
        t = Table(dt)
        for col in ["flux", "flux_error_lo", "flux_error_hi"]:
            t[col].unit = f_unit
        ndt = QTable(t)

        ndt["flux"] = (dt["flux"] * sedf).to(f_unit)
        ndt["flux_error_lo"] = (dt["flux_error_lo"] * sedf).to(f_unit)
        ndt["flux_error_hi"] = (dt["flux_error_hi"] * sedf).to(f_unit)

        return ndt

    data_list = []
    for group, dt in enumerate(data_table):
        dt_val = _validate_single_data_table(dt, group=group)
        data_list.append(dt_val)

    # concatenate input data tables
    data_new = data_list[0].copy()
    f_pt = data_new["flux"].unit.physical_type
    if sed is None:
        sed = f_pt in ["flux", "power"]

    data_new = dt_sed_conversion(data_new, sed)

    for dt in data_list[1:]:
        nf_pt = dt["flux"].unit.physical_type
        if ("flux" in nf_pt and "power" in f_pt) or (
            "power" in nf_pt and "flux" in f_pt
        ):
            raise TypeError(
                "The physical types of the data tables could not be "
                "matched: Some are in flux and others in luminosity units"
            )

        dt = dt_sed_conversion(dt, sed)

        for row in dt:
            data_new.add_row(row)

    return data_new

def _validate_single_data_table(data_table, group=0):

    data = QTable()

    flux_types = ["flux", "differential flux", "power", "differential power"]

    # Energy and flux arrays
    data["energy"] = validate_column(data_table, "energy", "energy")
    data["flux"] = validate_column(data_table, "flux", flux_types)

    # Flux uncertainties
    if "flux_error" in data_table.keys():
        dflux = validate_column(data_table, "flux_error", flux_types)
        data["flux_error_lo"] = dflux
        data["flux_error_hi"] = dflux
    elif (
        "flux_error_lo" in data_table.keys()
        and "flux_error_hi" in data_table.keys()
    ):
        data["flux_error_lo"] = validate_column(
            data_table, "flux_error_lo", flux_types
        )
        data["flux_error_hi"] = validate_column(
            data_table, "flux_error_hi", flux_types
        )
    else:
        raise TypeError(
            "Data table does not contain required column"
            ' "flux_error" or columns "flux_error_lo"'
            ' and "flux_error_hi"'
        )

    if "group" in data_table.colnames:
        # avoid overwriting groups
        data["group"] = data_table["group"]
    else:
        data["group"] = [group] * len(data["energy"])

    # Energy bin edges
    if "energy_width" in data_table.keys():
        energy_width = validate_column(data_table, "energy_width", "energy")
        data["energy_error_lo"] = energy_width / 2.0
        data["energy_error_hi"] = energy_width / 2.0
    elif "energy_error" in data_table.keys():
        energy_error = validate_column(data_table, "energy_error", "energy")
        data["energy_error_lo"] = energy_error
        data["energy_error_hi"] = energy_error
    elif (
        "energy_error_lo" in data_table.keys()
        and "energy_error_hi" in data_table.keys()
    ):
        energy_error_lo = validate_column(
            data_table, "energy_error_lo", "energy"
        )
        data["energy_error_lo"] = energy_error_lo
        energy_error_hi = validate_column(
            data_table, "energy_error_hi", "energy"
        )
        data["energy_error_hi"] = energy_error_hi
    elif "energy_lo" in data_table.keys() and "energy_hi" in data_table.keys():
        energy_lo = validate_column(data_table, "energy_lo", "energy")
        data["energy_error_lo"] = data["energy"] - energy_lo
        energy_hi = validate_column(data_table, "energy_hi", "energy")
        data["energy_error_hi"] = energy_hi - data["energy"]
    else:
        (
            data["energy_error_lo"],
            data["energy_error_hi"],
        ) = generate_energy_edges(data["energy"], groups=data["group"])

    # Upper limit flags
    if "ul" in data_table.keys():
        # Check if it is a integer or boolean flag
        ul_col = data_table["ul"]
        if ul_col.dtype.type is np.int_ or ul_col.dtype.type is np.bool_:
            data["ul"] = np.array(ul_col, dtype=bool)
        elif ul_col.dtype.type is np.str_:
            strbool = True
            for ul in ul_col:
                if ul != "True" and ul != "False":
                    strbool = False
            if strbool:
                data["ul"] = np.array(
                    [ast.literal_eval(ul) for ul in ul_col], dtype=bool
                )
            else:
                raise TypeError("UL column is in wrong format")
        else:
            raise TypeError("UL column is in wrong format")
    else:
        data["ul"] = np.array([False] * len(data["energy"]))

    if "flux_ul" in data_table.keys():
        data["flux"][data["ul"]] = u.Quantity(data_table["flux_ul"])[
            data["ul"]
        ]

    HAS_CL = False
    if "keywords" in data_table.meta.keys():
        if "cl" in data_table.meta["keywords"].keys():
            HAS_CL = True
            CL = validate_scalar(
                "cl", data_table.meta["keywords"]["cl"]["value"]
            )
            data["cl"] = [CL] * len(data["energy"])

    if not HAS_CL:
        data["cl"] = [0.9] * len(data["energy"])
        if np.sum(data["ul"]) > 0:
            log.warning(
                '"cl" keyword not provided in input data table, upper limits'
                " will be assumed to be at 90% confidence level"
            )

    return data

# Convenience tools

def sed_conversion(energy, model_unit, sed):
    """
    Manage conversion between differential spectrum and SED
    """

    model_pt = model_unit.physical_type
    is_integral = model_pt in {
        u.get_physical_type("power"),
        u.get_physical_type("energy"),
        u.get_physical_type("energy flux"),
    }
    is_differential = model_pt in {
        u.get_physical_type("differential flux"),
        u.get_physical_type("differential power"),
        u.get_physical_type("differential energy"),
        u.get_physical_type("differential number density"),
    }

    ones = np.ones(energy.shape)

    if (sed and is_integral) or (not sed and is_differential):
        sedf = ones
    elif sed and is_differential:
        sedf = energy ** 2
    elif not sed and is_integral:
        sedf = 1 / (energy ** 2)
    else:
        raise u.UnitsError(
            "Model physical type ({0}) is not supported".format(model_pt),
            "Supported physical types are: power, flux, differential"
            " power, differential flux",
        )

    is_energy_flux = model_pt in {
        u.get_physical_type("energy"),
        u.get_physical_type("differential energy"),
    }
    is_particle_flux = model_pt in {
        u.get_physical_type("energy flux"),
        u.get_physical_type("differential flux"),
    }

    if sed:
        if is_energy_flux:
            f_unit = u.erg
        elif is_particle_flux:
            f_unit = u.erg / u.s / u.cm ** 2
        else:
            f_unit = u.erg / u.s
    else:
        if is_energy_flux:
            f_unit = u.Unit("1/TeV")
        elif is_particle_flux:
            f_unit = u.Unit("1/(s TeV cm2)")
        else:
            f_unit = u.Unit("1/(s TeV)")

    log.debug(
        "Converted from {0} ({1}) into {2} ({3}) for sed={4}".format(
            model_unit, model_pt, f_unit, f_unit.physical_type, sed
        )
    )

    return f_unit, sedf

def trapz_loglog(y, x, axis=-1, intervals=False):
    """
    Integrate along the given axis using the composite trapezoidal rule in
    loglog space.

    Integrate `y` (`x`) along given axis in loglog space.

    Parameters
    ----------
    y : array_like
        Input array to integrate.
    x : array_like, optional
        Independent variable to integrate over.
    axis : int, optional
        Specify the axis.

    Returns
    -------
    trapz : float
        Definite integral as approximated by trapezoidal rule in loglog space.
    """
    try:
        y_unit = y.unit
        y = y.value
    except AttributeError:
        y_unit = 1.0
    try:
        x_unit = x.unit
        x = x.value
    except AttributeError:
        x_unit = 1.0

    y = np.asanyarray(y)
    x = np.asanyarray(x)

    slice1 = [slice(None)] * y.ndim
    slice2 = [slice(None)] * y.ndim
    slice1[axis] = slice(None, -1)
    slice2[axis] = slice(1, None)

    slice1 = tuple(slice1)
    slice2 = tuple(slice2)

    if x.ndim == 1:
        shape = [1] * y.ndim
        shape[axis] = x.shape[0]
        x = x.reshape(shape)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        # Compute the power law indices in each integration bin
        b = np.log10(y[slice2] / y[slice1]) / np.log10(x[slice2] / x[slice1])

        # if local powerlaw index is -1, use \int 1/x = log(x); otherwise use
        # normal powerlaw integration
        trapzs = np.where(
            np.abs(b + 1.0) > 1e-10,
            (
                y[slice1]
                * (x[slice2] * (x[slice2] / x[slice1]) ** b - x[slice1])
            )
            / (b + 1),
            x[slice1] * y[slice1] * np.log(x[slice2] / x[slice1]),
        )

    tozero = (y[slice1] == 0.0) + (y[slice2] == 0.0) + (x[slice1] == x[slice2])
    trapzs[tozero] = 0.0

    if intervals:
        return trapzs * x_unit * y_unit

    ret = np.add.reduce(trapzs, axis) * x_unit * y_unit

    return ret

def _generate_energy_edges_single(ene):
    """Generate energy edges for single group"""
    midene = np.sqrt((ene[1:] * ene[:-1]))
    elo, ehi = np.zeros(len(ene)) * ene.unit, np.zeros(len(ene)) * ene.unit
    elo[1:] = ene[1:] - midene
    ehi[:-1] = midene - ene[:-1]
    elo[0] = ene[0] * (1 - ene[0] / (ene[0] + ehi[0]))
    ehi[-1] = elo[-1]
    return u.Quantity([elo, ehi])

def generate_energy_edges(ene, groups=None):
    """Generate energy bin edges from given energy array.

    Generate an array of energy edges from given energy array to be used as
    abcissa error bar limits when no energy uncertainty or energy band is
    provided.

    Parameters
    ----------
    ene : `astropy.units.Quantity` array instance
        1-D array of energies with associated phsyical units.

    Returns
    -------
    energy_err_lo, energy_error_hi : `astropy.units.Quantity` arrays
        Arrays of low and high energy edges corresponding to each given energy
        of the input array.
    """
    if groups is None or len(ene) != len(groups):
        return _generate_energy_edges_single(ene)
    else:
        eloehi = np.zeros((2, len(ene))) * ene.unit
        for g in np.unique(groups):
            group_edges = _generate_energy_edges_single(ene[groups == g])
            eloehi[:, groups == g] = group_edges
        # hstack throws away units
        return eloehi

def build_data_table(
    energy,
    flux,
    flux_error=None,
    flux_error_lo=None,
    flux_error_hi=None,
    energy_width=None,
    energy_lo=None,
    energy_hi=None,
    ul=None,
    cl=None,
):
    """
    Read data into data dict.

    Parameters
    ----------

    energy : :class:`~astropy.units.Quantity` array instance
        Observed photon energy array [physical type ``energy``]

    flux : :class:`~astropy.units.Quantity` array instance
        Observed flux array [physical type ``flux`` or ``differential flux``]

    flux_error, flux_error_hi, flux_error_lo : :class:`~astropy.units.Quantity`
    array instance
        68% CL gaussian uncertainty of the flux [physical type ``flux`` or
        ``differential flux``]. Either ``flux_error`` (symmetrical uncertainty)
        or ``flux_error_hi`` and ``flux_error_lo`` (asymmetrical uncertainties)
        must be provided.

    energy_width, energy_lo, energy_hi : :class:`~astropy.units.Quantity` array
    instance, optional
        Width of the energy bins [physical type ``energy``]. Either
        ``energy_width`` (bin width) or ``energy_lo`` and ``energy_hi``
        (Energies of the lower and upper bin edges) can be provided. If none
        are provided, ``generate_energy_edges`` will be used.

    ul : boolean or int array, optional
        Boolean array indicating which of the flux values given in ``flux``
        correspond to upper limits.

    cl : float, optional
        Confidence level of the flux upper limits given by ``ul``.

    Returns
    -------
    data : :class:`astropy.table.QTable`
        Data stored in an astropy Table.
    """
    table = QTable()

    if cl is not None:
        cl = validate_scalar("cl", cl)
        table.meta["keywords"] = {"cl": {"value": cl}}

    table["energy"] = energy

    if energy_width is not None:
        table["energy_width"] = energy_width
    elif energy_lo is not None and energy_hi is not None:
        table["energy_lo"] = energy_lo
        table["energy_hi"] = energy_hi

    table["flux"] = flux

    if flux_error is not None:
        table["flux_error"] = flux_error
    elif flux_error_lo is not None and flux_error_hi is not None:
        table["flux_error_lo"] = flux_error_lo
        table["flux_error_hi"] = flux_error_hi
    else:
        raise TypeError("Flux error not provided!")

    if ul is not None:
        ul = np.array(ul, dtype=int)
        table["ul"] = ul

    table.meta["comments"] = ["Table generated with naima.build_data_table"]

    # test table units, format, etc
    validate_data_table(table)

    return table

def estimate_B(
    xray_table, vhe_table, photon_energy_density=0.261 * u.eV / u.cm ** 3
):
    """Estimate magnetic field from synchrotron to Inverse Compton luminosity
    ratio

    Estimate the magnetic field from the ratio of X-ray to gamma-ray emission
    according to:

    .. math::

        \\frac{L_\\mathrm{xray}}{L_\\gamma} =
        \\frac{u_\\mathrm{B}}{u_\\mathrm{ph}} =
        \\frac{B^2}{ 8 \\pi u_\\mathrm{ph}}

    where :math:`L_\\mathrm{xray}` is the X-ray luminosity, :math:`L_\\gamma`
    is the gamma-ray luminosity, and :math:`u_\\mathrm{ph}` is the seed photon
    field energy density.

    Note that this assumes that the ratio of observed fluxes is equal to the
    ratio of bolometric synchrotron and IC luminosities, and that IC proceeds
    in the Thomson regims. This assumption is safe as long as the X-ray and
    gamma-ray emission contain the bulk of the bolometric emission (i.e., the
    peak in the SED is in the X-ray and gamma-ray observed bands). Even if the
    assumption does not hold, this is a good starting point for the magnetic
    field when doing simultaneous X-ray and gamma-ray spectral fits.

    Parameters
    ----------

    xray_table : :class:`~astropy.table.Table`
        Data table (see :ref:`dataformat` for details on the format) containing
        the X-ray spectrum.
    vhe_table : :class:`~astropy.table.Table`
        Data table (see :ref:`dataformat` for details on the format) containing
        the HE/VHE gamma-ray spectrum.

    photon_energy_density : :class:`~astropy.units.Quantity` float, optional
        Energy density of the seed photon field for IC emission. Defaults to
        0.261 eV/cm3, the energy density of the CMB.

    Returns
    -------

    B : :class:`~astropy.units.Quantity` float
        Estimate of the magnetic flux density at the emitter.
    """

    xray = validate_data_table(xray_table, sed=False)
    vhe = validate_data_table(vhe_table, sed=False)

    xray_lum = trapz_loglog(xray["flux"] * xray["energy"], xray["energy"])
    vhe_lum = trapz_loglog(vhe["flux"] * vhe["energy"], vhe["energy"])

    uph = (photon_energy_density.to("erg/cm3")).value

    B0 = (
        np.sqrt((xray_lum / vhe_lum).decompose().value * 8 * np.pi * uph) * u.G
    ).to("uG")

    return B0


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>QDynamicPropertyChangeEvent Class Reference</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

QDynamicPropertyChangeEvent Class Reference

[com.trolltech.qt.core package]

Inherits QEvent.

Constructor

void QDynamicPropertyChangeEvent(QByteArray name)

Constructor Properties

prototype: The QDynamicPropertyChangeEvent prototype object

Prototype Object Properties

The QDynamicPropertyChangeEvent prototype object inherits properties from the QEvent prototype object and also has the following properties.

QByteArray propertyName()

Instance Properties

QDynamicPropertyChangeEvent objects have no special properties beyond those inherited from the QDynamicPropertyChangeEvent prototype object.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tests;

use Doctrine\ORM\EntityManagerInterface;
use Liip\FunctionalTestBundle\Test\WebTestCase as LiipTest;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Response;

class WebTestCase extends LiipTest
{
    /**
     * The last response returned by the application.
     *
     * @var Response
     */
    protected $response;

    /**
     * The Client instance.
     *
     * @var Client
     */
    protected $client;

    /**
     * The DomCrawler instance.
     *
     * @var Crawler
     */
    protected $crawler;

    /**
     * The current URL being viewed.
     *
     * @var string
     */
    protected $currentUri;

    protected function setUp()
    {
        parent::setUp();

        $this->loadFixtureFiles([
            __DIR__.'/fixtures/users.yml',
            __DIR__.'/fixtures/scoring_systems.yml',
            __DIR__.'/fixtures/seasons.yml',
            __DIR__.'/fixtures/circuits.yml',
            __DIR__.'/fixtures/races.yml',
            __DIR__.'/fixtures/drivers.yml',
            __DIR__.'/fixtures/constructors.yml',
            __DIR__.'/fixtures/teams.yml',
            __DIR__.'/fixtures/qualifying.yml',
            __DIR__.'/fixtures/finishing_status.yml',
            __DIR__.'/fixtures/results.yml',
            __DIR__.'/fixtures/predictions.yml',
            __DIR__.'/fixtures/finishing_positions.yml',
            __DIR__.'/fixtures/driver_standings.yml',
            __DIR__.'/fixtures/constructor_standings.yml',
            __DIR__.'/fixtures/user_standings.yml',
        ]);
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->client = null;
        $this->response = null;
        $this->crawler = null;
        $this->currentUri = null;
    }

    protected function get(string $service)
    {
        return $this->getContainer()->get($service);
    }

    protected function call(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], $content = null, bool $changeHistory = true)
    {
        $this->client = static::createClient();
        $this->client->enableProfiler();

        $this->crawler = $this->client->request($method, $uri, $parameters, $files, $server, $content, $changeHistory);
        $this->response = $this->client->getResponse();
        $this->currentUri = $uri;

        return $this;
    }

    protected function isOk()
    {
        $this->responseStatusIs(200);

        return $this;
    }

    protected function isNotFound()
    {
        $this->responseStatusIs(404);

        return $this;
    }

    protected function responseStatusIs(int $code)
    {
        $actual = $this->response->getStatusCode();

        $this->assertSame($code, $this->response->getStatusCode(), "Expected status code {$code}, got {$actual} (uri: {$this->currentUri}).");

        return $this;
    }

    protected function visit(string $uri)
    {
        return $this->call('GET', $uri);
    }

    protected function seePageIs(string $uri)
    {
        $this->assertSame($uri, $this->currentUri, "Did not land on expected page [{$uri}].\n");

        return $this;
    }

    protected function see(string $text)
    {
        $this->assertGreaterThan(0, $this->crawler->filter('html:contains("'.$text.'")')->count());

        return $this;
    }

    protected function dontSee($text)
    {
        $this->assertSame(0, $this->crawler->filter('html:contains("'.$text.'")')->count());

        return $this;
    }

    public function seeInElement(string $element, string $text)
    {
        $this->assertContains($text, $this->crawler->filter($element)->text());

        return $this;
    }

    protected function seeInDatabase($className, array $criteria)
    {
        /* @var $em EntityManagerInterface */
        $em = $this->get('doctrine')->getEntityManager();
        $data = $em->getRepository($className)->findBy($criteria);

        $this->assertGreaterThan(0, count($data), sprintf(
            'Unable to find row in database table [%s] that matched attributes [%s].', $className, json_encode($data)
        ));

        return $this;
    }

    protected function dontSeeInDatabase($className, array $criteria)
    {
        /* @var $em EntityManagerInterface */
        $em = $this->get('doctrine')->getEntityManager();
        $data = $em->getRepository($className)->findBy($criteria);

        $this->assertEmpty($data, sprintf(
            'Found unexpected records in database table [%s] that matched attributes [%s].', $className, json_encode($data)
        ));

        return $this;
    }

    protected function inMaxQueries(int $number)
    {
        $profile = $this->client->getProfile();
        $queryCount = $profile->getCollector('db')->getQueryCount();

        $this->assertLessThanOrEqual($number, $queryCount, sprintf(
            'Checks that query count is less than %d (token %s)',
            $number,
            $profile->getToken()
        ));
    }
}


text:
package stubs

import (
	"fmt"

	"google.golang.org/api/googleapi"
	"k8s.io/kubernetes/federation/pkg/dnsprovider/providers/google/clouddns/internal/interfaces"
)

// Compile time check for interface adeherence
var _ interfaces.ManagedZonesCreateCall = ManagedZonesCreateCall{}

type ManagedZonesCreateCall struct {
	Error       *error // Use to override response for testing
	Service     *ManagedZonesService
	Project     string
	ManagedZone interfaces.ManagedZone
}

func (call ManagedZonesCreateCall) Do(opts ...googleapi.CallOption) (interfaces.ManagedZone, error) {
	if call.Error != nil {
		return nil, *call.Error
	}
	if call.Service.Impl[call.Project][call.ManagedZone.DnsName()] != nil {
		return nil, fmt.Errorf("Error - attempt to create duplicate zone %s in project %s.",
			call.ManagedZone.DnsName(), call.Project)
	}
	if call.Service.Impl == nil {
		call.Service.Impl = map[string]map[string]interfaces.ManagedZone{}
	}
	if call.Service.Impl[call.Project] == nil {
		call.Service.Impl[call.Project] = map[string]interfaces.ManagedZone{}
	}
	call.Service.Impl[call.Project][call.ManagedZone.DnsName()] = call.ManagedZone
	return call.ManagedZone, nil
}


text:
class ChaptersController < ApplicationController
  def new
    @chapter = Chapter.new
  end

  def create
    @chapter = Chapter.new(chapter_params)
  end

  def show
    respond_to do |format|
      format.html {
        unless params['_escaped_fragment_'].nil?
          @data = get_chapter(params[:compilation], params[:volume], params[:url])
        end
      }
      format.json {
        chapter = get_chapter(params[:compilation], params[:volume], params[:url])
        render json: chapter
      }
    end
  end

  def index
    result = find_chapter(params)
    chapter = result[:chapter].attributes.select{|attr| ["t", "dt", "desc", "txt"].include? attr}
    render json: chapter
  end

  def update
    result = find_chapter(params)
    diff = {}

    txt = result[:chapter].txt
    txt_updated = params[:chapter][:txt].strip rescue nil
    unless txt === txt_updated
      diff[:txt] = Diffy::Diff.new(txt, txt_updated, :context => 0).to_s(:html)
    end

    desc = result[:chapter].desc
    desc_updated = params[:chapter][:desc].strip rescue nil
    unless desc === desc_updated
      diff[:desc] = Diffy::Diff.new(desc, desc_updated, :context => 0).to_s(:html)
    end

    dt = Date.parse(result[:chapter].dt) rescue nil
    dt_updated = Date.parse(params[:chapter][:dt]) rescue nil
    unless dt_updated === dt
      diff[:dt] = Diffy::Diff.new(dt, dt_updated, :context => 0).to_s(:html)
    end

    audit = {}
    audit[:diff] = diff
    audit[:user] = current_user.uid
    audit[:type] = result[:chapter].class.to_s
    audit[:url] = result[:chapter].url
    audit[:oid] = Hash.new.tap do |oid|
      oid[:bid] = params[:bid] if params[:bid]
      oid[:pid] = params[:pid] if params[:pid]
      oid[:sid] = params[:sid] if params[:sid]
      oid[:suid] = params[:suid] if params[:suid]
      oid[:cid] = params[:cid] if params[:cid]
    end

    Audit.create(audit)

    result[:chapter].assign_attributes(chapter_params)
    result[:volume].update
    render nothing: true
  end

  private

  def find_chapter params
    if params[:bid]
      vol = Volume.where('books._id' => BSON::ObjectId.from_string(params[:bid])).first
      book = vol.books.detect { |b| b.id.to_s == params[:bid] }
      if book.parts?
        part = book.parts.detect { |p| p.id.to_s == params[:pid] }
        if part.chapters?
          chapter = part.chapters.detect { |c| c.id.to_s == params[:cid] }
        elsif part.sections?
          section = part.sections.detect { |s| s.id.to_s == params[:sid] }
          if section.subsections?
            subsection = section.subsections.detect { |su| su.id.to_s == params[:suid] }
            chapter = subsection.chapters.detect { |c| c.id.to_s == params[:cid] }
          elsif section.chapters?
            chapter = section.chapters.detect { |c| c.id.to_s == params[:cid] }
          end
        end
      elsif book.chapters?
        chapter = book.chapters.detect { |c| c.id.to_s == params[:cid] }
      end
    elsif params[:pid]
      vol = Volume.where('parts._id' => BSON::ObjectId.from_string(params[:pid])).first
      part = vol.parts.detect { |p| p.id.to_s == params[:pid] }
      if part.chapters?
        chapter = part.chapters.detect { |c| c.id.to_s == params[:cid] }
      elsif part.sections?
        section = part.sections.detect { |s| s.id.to_s == params[:sid] }
        if section.subsections?
          subsection = section.subsections.detect { |su| su.id.to_s == params[:suid] }
          chapter = subsection.chapters.detect { |c| c.id.to_s == params[:cid] }
        elsif section.chapters?
          chapter = section.chapters.detect { |c| c.id.to_s == params[:cid] }
        end
      end
    end
    {
      chapter: chapter,
      volume: vol
    }
  end

  def get_chapter(compilation, volume, url)
    volume = Volume.where(comp: compilation, vol: volume)
    found = false
    chapter = nil
    if volume.exists?
      chapters_query = { 'chapters._slugs' => url }
      parts_chapters_query = { 'parts.chapters._slugs' => url }
      books_parts_chapters_query = { 'books.parts.chapters._slugs' => url }
      books_chapters_query = { 'books.chapters._slugs' => url }
      books_parts_sections_chapters_query = { 'books.parts.sections.chapters._slugs' => url }
      parts_sections_chapters_query = { 'parts.sections.chapters._slugs' => url }
      books_parts_sections_subsections_chapters_query = { 'books.parts.sections.subsections.chapters._slugs' => url }
      parts_sections_subsections_chapters_query = { 'parts.sections.subsections.chapters._slugs' => url }

      meta = {}

      if (result = volume.where(parts_chapters_query)).exists?
        result.first.parts.each do |p|
          chapter = p.chapters.find(url)
          next if chapter.nil?
          meta[:pid] = p.id.to_s
          meta[:cid] = chapter.id.to_s
          break
        end
      elsif (result = volume.where(parts_sections_chapters_query)).exists?
        result.first.parts.each do |p|
          p.sections.each do |s|
            chapter = s.chapters.find(url)
            next if chapter.nil?
            meta[:sid] = s.id.to_s
            meta[:cid] = chapter.id.to_s
            break
          end
          next if chapter.nil?
          meta[:pid] = p.id.to_s
          break
        end
      elsif (result = volume.where(books_parts_sections_chapters_query)).exists?
        result.first.books.each do |b|
          b.parts.each do |p|
            p.sections.each do |s|
              chapter = s.chapters.find(url)
              next if chapter.nil?
              meta[:sid] = s.id.to_s
              meta[:cid] = chapter.id.to_s
              break
            end
            next if chapter.nil?
            meta[:pid] = p.id.to_s
            break
          end
          next if chapter.nil?
          meta[:bid] = b.id.to_s
          break
        end
      elsif (result = volume.where(books_parts_chapters_query)).exists?
        result.first.books.each do |b|
          b.parts.each do |p|
            chapter = p.chapters.find(url)
            next if chapter.nil?
            meta[:pid] = p.id.to_s
            meta[:cid] = chapter.id.to_s
            break
          end
          next if chapter.nil?
          meta[:bid] = b.id.to_s
          break
        end
      elsif (result = volume.where(books_chapters_query)).exists?
        result.first.books.each do |b|
          chapter = b.chapters.find(url)
          next if chapter.nil?
          meta[:bid] = b.id.to_s
          meta[:cid] = chapter.id.to_s
          break
        end
      elsif (result = volume.where(chapters_query)).exists?
        chapter = result.first.chapters.find(url)
        meta[:cid] = chapter.id.to_s
      elsif (result = volume.where(books_parts_sections_subsections_chapters_query)).exists?
        result.first.books.each do |b|
          b.parts.each do |p|
            p.sections.each do |s|
              s.subsections.each do |subs|
                chapter = subs.chapters.find(url)
                next if chapter.nil?
                meta[:suid] = subs.id.to_s
                meta[:cid] = chapter.id.to_s
                break
              end
              next if chapter.nil?
              meta[:sid] = s.id.to_s
              break
            end
            next if chapter.nil?
            meta[:pid] = p.id.to_s
            break
          end
          next if chapter.nil?
          meta[:bid] = b.id.to_s
          break
        end
      elsif (result = volume.where(parts_sections_subsections_chapters_query)).exists?
        result.first.parts.each do |p|
          p.sections.each do |s|
            s.subsections.each do |subs|
              chapter = subs.chapters.find(url)
              next if chapter.nil?
              meta[:suid] = subs.id.to_s
              meta[:cid] = chapter.id.to_s
              break
            end
            next if chapter.nil?
            meta[:sid] = s.id.to_s
            break
          end
          next if chapter.nil?
          meta[:pid] = p.id.to_s
          break
        end
      end
      if admin_user
        chapter[:meta] = meta
      end
      chapter
    end
  end

  def chapter_params
    params.require(:chapter).permit(:title, :subtitle, :txt, :dt, :desc)
  end
end


text:
set(CMAKE_IMPORT_FILE_VERSION 1)

# Import target "c10" for configuration "Release"
set_property(TARGET c10 APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(c10 PROPERTIES
  IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libc10.so"
  IMPORTED_SONAME_RELEASE "libc10.so"
  )

list(APPEND _IMPORT_CHECK_TARGETS c10 )
list(APPEND _IMPORT_CHECK_FILES_FOR_c10 "${_IMPORT_PREFIX}/lib/libc10.so" )

# Import target "caffe2" for configuration "Release"
set_property(TARGET caffe2 APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(caffe2 PROPERTIES
  IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libcaffe2.so"
  IMPORTED_SONAME_RELEASE "libcaffe2.so"
  )

list(APPEND _IMPORT_CHECK_TARGETS caffe2 )
list(APPEND _IMPORT_CHECK_FILES_FOR_caffe2 "${_IMPORT_PREFIX}/lib/libcaffe2.so" )

# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)


text:
import Tree from './treeview';
import TreeNode from './treenode';
require('./react-treeview.css');

exports.Tree = Tree;
exports.TreeNode = TreeNode;


text:
namespace gameplay {
namespace gl {

using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Value;
using v8::Isolate;
using v8::String;
using v8::Exception;
using v8::ArrayBufferView;

static void ActiveTexture(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum texture = static_cast<GLenum>(args[0]->IntegerValue());
  glActiveTexture(texture);
}

static void AttachShader(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint program = static_cast<GLuint>(args[0]->IntegerValue());
  GLuint shader = static_cast<GLuint>(args[1]->IntegerValue());

  glAttachShader(program, shader);
}

static void BindBuffer(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum target = static_cast<GLenum>(args[0]->IntegerValue());
  GLuint buffer = static_cast<GLuint>(args[1]->IntegerValue());

  glBindBuffer(target, buffer);
}

static void BufferData(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsArrayBufferView() ||
      !args[2]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum target = static_cast<GLenum>(args[0]->IntegerValue());
  Local<ArrayBufferView> srcData = Local<ArrayBufferView>::Cast(args[1]);
  GLenum usage = static_cast<GLenum>(args[2]->IntegerValue());

  glBufferData(target,
    srcData->ByteLength(), srcData->Buffer()->GetContents().Data(), usage);
}

static void BindTexture(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum target = static_cast<GLenum>(args[0]->Int32Value());
  GLuint texture = static_cast<GLuint>(args[1]->Int32Value());

  glBindTexture(target, texture);
}

static void BindVertexArray(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint array = static_cast<GLuint>(args[0]->IntegerValue());
  glBindVertexArray(array);
}

static void BlendFunc(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum sfactor = static_cast<GLenum>(args[0]->Int32Value());
  GLenum dfactor = static_cast<GLenum>(args[1]->Int32Value());

  glBlendFunc(sfactor, dfactor);
}

static void Clear(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLbitfield mask = static_cast<GLbitfield>(args[0]->Int32Value());

  glClear(mask);
}

static void ClearColor(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber() || !args[3]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLfloat r = static_cast<GLfloat>(args[0]->NumberValue());
  GLfloat g = static_cast<GLfloat>(args[1]->NumberValue());
  GLfloat b = static_cast<GLfloat>(args[2]->NumberValue());
  GLfloat a = static_cast<GLfloat>(args[3]->NumberValue());

  glClearColor(r, g, b, a);
}

static void CompileShader(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint shader = static_cast<GLuint>(args[0]->IntegerValue());

  glCompileShader(shader);
}

static void CreateBuffer(const FunctionCallbackInfo<Value>& args) {
  GLuint buffer;
  glGenBuffers(1, &buffer);
  args.GetReturnValue().Set(buffer);
}

static void CreateShader(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum shaderType = static_cast<GLenum>(args[0]->IntegerValue());

  args.GetReturnValue().Set(glCreateShader(shaderType));
}

static void CreateProgram(const FunctionCallbackInfo<Value>& args) {
  args.GetReturnValue().Set(glCreateProgram());
}

static void CreateTexture(const FunctionCallbackInfo<Value>& args) {
  GLuint texture;
  glGenTextures(1, &texture);
  args.GetReturnValue().Set(texture);
}

static void CreateVertexArray(const FunctionCallbackInfo<Value>& args) {
  GLuint vertexArray;
  glGenVertexArrays(1, &vertexArray);
  args.GetReturnValue().Set(vertexArray);
}

static void CullFace(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum mode = static_cast<GLenum>(args[0]->IntegerValue());
  glCullFace(mode);
}

static void DepthMask(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsBoolean()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  glDepthMask(static_cast<GLboolean>(args[0]->BooleanValue()));
}

static void Disable(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum cap = static_cast<GLenum>(args[0]->Int32Value());
  glDisable(cap);
}

static void DrawArrays(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum mode = static_cast<GLenum>(args[0]->IntegerValue());
  GLint first = static_cast<GLint>(args[1]->IntegerValue());
  GLsizei count = static_cast<GLsizei>(args[2]->IntegerValue());

  glDrawArrays(mode, first, count);
}

static void DrawElements(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber() || !args[3]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum mode = static_cast<GLenum>(args[0]->Int32Value());
  GLsizei count = static_cast<GLsizei>(args[1]->Int32Value());
  GLenum type = static_cast<GLenum>(args[2]->Int32Value());
  GLvoid *offset = reinterpret_cast<GLvoid*>(args[3]->Uint32Value());

  glDrawElements(mode, count, type, offset);
}

static void Enable(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum cap = static_cast<GLenum>(args[0]->Int32Value());
  glEnable(cap);
}

static void EnableVertexAttribArray(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint index = static_cast<GLuint>(args[0]->Int32Value());
  glEnableVertexAttribArray(index);
}

static void FrontFace(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum mode = static_cast<GLenum>(args[0]->IntegerValue());
  glFrontFace(mode);
}

static void GetAttribLocation(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsString()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint program = static_cast<GLuint>(args[0]->Int32Value());
  String::Utf8Value name(args[1]);

  GLint location = glGetAttribLocation(program, *name);
  args.GetReturnValue().Set(location);
}

static void GetError(const FunctionCallbackInfo<Value>& args) {
  args.GetReturnValue().Set(glGetError());
}

static void GetParameter(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum pname = static_cast<GLenum>(args[0]->IntegerValue());

  GLint status;
  glGetIntegerv(pname, &status);
  args.GetReturnValue().Set(status);
}

static void GetProgramInfoLog(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint shader = static_cast<GLuint>(args[0]->IntegerValue());

  char message[512];
  glGetProgramInfoLog(shader, 512, NULL, message);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, message));
}

static void GetProgramParameter(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint shader = static_cast<GLuint>(args[0]->IntegerValue());
  GLenum pname = static_cast<GLenum>(args[1]->IntegerValue());

  GLint status;
  glGetProgramiv(shader, pname, &status);
  args.GetReturnValue().Set(status);
}

static void GetShaderInfoLog(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint shader = static_cast<GLuint>(args[0]->IntegerValue());

  char message[512];
  glGetShaderInfoLog(shader, 512, NULL, message);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, message));
}

static void GetShaderParameter(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint shader = static_cast<GLuint>(args[0]->IntegerValue());
  GLenum pname = static_cast<GLenum>(args[1]->IntegerValue());

  GLint status;
  glGetShaderiv(shader, pname, &status);
  args.GetReturnValue().Set(status);
}

static void GetUniformLocation(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsString()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint program = static_cast<GLuint>(args[0]->Int32Value());
  String::Utf8Value name(args[1]);

  GLint location = glGetUniformLocation(program, *name);
  args.GetReturnValue().Set(location);
}

static void Init(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (gl3wInit()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Failed to initialize OpenGL")));
  }
}

static void LinkProgram(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint program = static_cast<GLuint>(args[0]->IntegerValue());
  glLinkProgram(program);
}

static void PixelStorei(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum pname = static_cast<GLenum>(args[0]->Int32Value());
  GLint param = static_cast<GLint>(args[1]->Int32Value());

  glPixelStorei(pname, param);
}

static void ShaderSource(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsString()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint shader = static_cast<GLuint>(args[0]->IntegerValue());
  String::Utf8Value source(args[1]);
  const char* s[1] = {*source};

  glShaderSource(shader, 1, s, NULL);
}

static void TexImage2D(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber() || !args[3]->IsNumber() ||
      !args[4]->IsNumber() || !args[5]->IsNumber() ||
      !args[6]->IsNumber() || !args[7]->IsNumber() ||
      (!args[8]->IsArrayBufferView() && !args[8]->IsNull())) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum target = static_cast<GLenum>(args[0]->Int32Value());
  GLint level = static_cast<GLint>(args[1]->Int32Value());
  GLint internalFormat = static_cast<GLint>(args[2]->Int32Value());
  GLsizei width = static_cast<GLsizei>(args[3]->Int32Value());
  GLsizei height = static_cast<GLsizei>(args[4]->Int32Value());
  GLint border = static_cast<GLint>(args[5]->Int32Value());
  GLenum format = static_cast<GLenum>(args[6]->Int32Value());
  GLenum type = static_cast<GLenum>(args[7]->Int32Value());
  GLvoid* data = nullptr;

  if (!args[8]->IsNull()) {
    data = static_cast<GLvoid*>(
      Local<ArrayBufferView>::Cast(args[8])->Buffer()->GetContents().Data());
  }
  glTexImage2D(target, level,
    internalFormat, width, height, border, format, type, data);
}

static void TexSubImage2D(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber() || !args[3]->IsNumber() ||
      !args[4]->IsNumber() || !args[5]->IsNumber() ||
      !args[6]->IsNumber() || !args[7]->IsNumber() ||
      (!args[8]->IsArrayBufferView() && !args[8]->IsNull())) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum target = static_cast<GLenum>(args[0]->Int32Value());
  GLint level = static_cast<GLint>(args[1]->Int32Value());
  GLint xoffset = static_cast<GLint>(args[2]->Int32Value());
  GLint yoffset = static_cast<GLint>(args[3]->Int32Value());
  GLsizei width = static_cast<GLsizei>(args[4]->Int32Value());
  GLsizei height = static_cast<GLsizei>(args[5]->Int32Value());
  GLenum format = static_cast<GLenum>(args[6]->Int32Value());
  GLenum type = static_cast<GLenum>(args[7]->Int32Value());
  GLvoid* pixels = nullptr;

  if (!args[8]->IsNull()) {
    pixels = static_cast<GLvoid*>(
      Local<ArrayBufferView>::Cast(args[8])->Buffer()->GetContents().Data());
  }
  glTexSubImage2D(target, level,
    xoffset, yoffset, width, height, format, type, pixels);
}

static void TexParameteri(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLenum target = static_cast<GLenum>(args[0]->Int32Value());
  GLenum pname = static_cast<GLenum>(args[1]->Int32Value());
  GLint param = static_cast<GLint>(args[2]->Int32Value());

  glTexParameteri(target, pname, param);
}

static void Uniform1f(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLint location = static_cast<GLint>(args[0]->Int32Value());
  GLfloat v0 = static_cast<GLfloat>(args[1]->NumberValue());

  glUniform1f(location, v0);
}

static void Uniform1i(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLint location = static_cast<GLint>(args[0]->Int32Value());
  GLint v0 = static_cast<GLint>(args[1]->NumberValue());

  glUniform1i(location, v0);
}

static void Uniform3f(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber() || !args[3]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLint location = static_cast<GLint>(args[0]->Int32Value());
  GLfloat v0 = static_cast<GLfloat>(args[1]->NumberValue());
  GLfloat v1 = static_cast<GLfloat>(args[2]->NumberValue());
  GLfloat v2 = static_cast<GLfloat>(args[3]->NumberValue());

  glUniform3f(location, v0, v1, v2);
}

static void UniformMatrix4fv(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsBoolean() ||
      !args[2]->IsArrayBufferView()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLint location = static_cast<GLint>(args[0]->Int32Value());
  GLboolean transpose = static_cast<GLboolean>(args[1]->BooleanValue());
  GLfloat* value = static_cast<GLfloat*>(
      Local<ArrayBufferView>::Cast(args[2])->Buffer()->GetContents().Data());

  glUniformMatrix4fv(location, 1, transpose, value);
}

static void UseProgram(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint program = static_cast<GLuint>(args[0]->IntegerValue());
  glUseProgram(program);
}

static void VertexAttribPointer(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber() || !args[3]->IsBoolean() ||
      !args[4]->IsNumber() || !args[5]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  GLuint index = static_cast<GLuint>(args[0]->Int32Value());
  GLint size = static_cast<GLint>(args[1]->Int32Value());
  GLenum type = static_cast<GLenum>(args[2]->Int32Value());
  GLboolean normalized = static_cast<GLboolean>(args[3]->BooleanValue());
  GLsizei stride = static_cast<GLsizei>(args[4]->Int32Value());
  GLvoid *offset = (GLvoid *)args[5]->Int32Value();

  glVertexAttribPointer(index, size, type, normalized, stride, offset);
}

static void ViewPort(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (!args[0]->IsNumber() || !args[1]->IsNumber() ||
      !args[2]->IsNumber() || !args[3]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }
  int x = args[0]->IntegerValue();
  int y = args[1]->IntegerValue();
  int w = args[2]->IntegerValue();
  int h = args[3]->IntegerValue();

  glViewport(x, y, w, h);
}

void Initialize(Local<Object> target,
                Local<Value> unused,
                Local<Context> context) {
  NODE_SET_METHOD(target, "activeTexture", ActiveTexture);
  NODE_SET_METHOD(target, "attachShader", AttachShader);
  NODE_SET_METHOD(target, "blendFunc", BlendFunc);
  NODE_SET_METHOD(target, "bufferData", BufferData);
  NODE_SET_METHOD(target, "bindBuffer", BindBuffer);
  NODE_SET_METHOD(target, "bindTexture", BindTexture);
  NODE_SET_METHOD(target, "bindVertexArray", BindVertexArray);
  NODE_SET_METHOD(target, "clear", Clear);
  NODE_SET_METHOD(target, "clearColor", ClearColor);
  NODE_SET_METHOD(target, "compileShader", CompileShader);
  NODE_SET_METHOD(target, "createBuffer", CreateBuffer);
  NODE_SET_METHOD(target, "createProgram", CreateProgram);
  NODE_SET_METHOD(target, "createShader", CreateShader);
  NODE_SET_METHOD(target, "createTexture", CreateTexture);
  NODE_SET_METHOD(target, "createVertexArray", CreateVertexArray);
  NODE_SET_METHOD(target, "cullFace", CullFace);
  NODE_SET_METHOD(target, "depthMask", DepthMask);
  NODE_SET_METHOD(target, "disable", Disable);
  NODE_SET_METHOD(target, "drawArrays", DrawArrays);
  NODE_SET_METHOD(target, "drawElements", DrawElements);
  NODE_SET_METHOD(target, "enable", Enable);
  NODE_SET_METHOD(target, "enableVertexAttribArray", EnableVertexAttribArray);
  NODE_SET_METHOD(target, "frontFace", FrontFace);
  NODE_SET_METHOD(target, "getAttribLocation", GetAttribLocation);
  NODE_SET_METHOD(target, "getError", GetError);
  NODE_SET_METHOD(target, "getParameter", GetParameter);
  NODE_SET_METHOD(target, "getProgramInfoLog", GetProgramInfoLog);
  NODE_SET_METHOD(target, "getProgramParameter", GetProgramParameter);
  NODE_SET_METHOD(target, "getShaderInfoLog", GetShaderInfoLog);
  NODE_SET_METHOD(target, "getShaderParameter", GetShaderParameter);
  NODE_SET_METHOD(target, "getUniformLocation", GetUniformLocation);
  NODE_SET_METHOD(target, "init", Init);
  NODE_SET_METHOD(target, "linkProgram", LinkProgram);
  NODE_SET_METHOD(target, "pixelStorei", PixelStorei);
  NODE_SET_METHOD(target, "shaderSource", ShaderSource);
  NODE_SET_METHOD(target, "texImage2D", TexImage2D);
  NODE_SET_METHOD(target, "texSubImage2D", TexSubImage2D);
  NODE_SET_METHOD(target, "texParameteri", TexParameteri);
  NODE_SET_METHOD(target, "uniform1f", Uniform1f);
  NODE_SET_METHOD(target, "uniform1i", Uniform1i);
  NODE_SET_METHOD(target, "uniform3f", Uniform3f);
  NODE_SET_METHOD(target, "uniformMatrix4fv", UniformMatrix4fv);
  NODE_SET_METHOD(target, "useProgram", UseProgram);
  NODE_SET_METHOD(target, "vertexAttribPointer", VertexAttribPointer);
  NODE_SET_METHOD(target, "viewport", ViewPort);
}

}  // namespace gl
}  // namespace gameplay

NODE_MODULE(gl, gameplay::gl::Initialize)


text:
package game

import (
	"geo"
	"fmt"
)

type Game struct {
	Id         uint64
	Name       string
	City       string
	Rect       geo.Rectangle
	MaxPlayers int
	Players    map[string]*Player
	HostPlayer *Player
	State      int
	GameType   string
	Beans	[]*geo.Point
	Row			int
	Column		int
}

func (this *Game) getXRange() (float64,float64){
	if this.Rect.MinX > this.Rect.MaxX{
		return this.Rect.MaxX, this.Rect.MinX
	}
	return this.Rect.MinX, this.Rect.MaxX
}

func (this *Game) getYRange() (float64,float64){
	if this.Rect.MinY > this.Rect.MaxY{
		return this.Rect.MaxY, this.Rect.MinY
	}
	return this.Rect.MinY, this.Rect.MaxY
}

func (this *Game) SetupMap() {

	startX, stopX := this.getXRange()
	startY, stopY := this.getYRange()

	distanceX := 2/11000.0 // 2m
	distanceY := distanceX

	beans := []*geo.Point{}

	this.Row = (int) ((stopY-startY)/distanceY)
	this.Column = (int) ((stopX - startX)/distanceX)

	for i := 0; i < this.Row; i++{
		for j:=0;j<this.Column;j++{
			pointX := startX + 0.5*distanceX + float64(i)*distanceX
			pointY := startY + 0.5*distanceY + float64(j)*distanceY
			point := &geo.Point{RowIndex: i, ColumnIndex: j, X : pointX, Y : pointY, Role:1}
			beans = append(beans, point)
		}
	}

	for _,player:=range this.Players{
		beansIndex :=0
		if player.X > startX && player.X < stopX && player.Y > startY && player.Y < stopY{
			playerRow := int( (player.X - startX)/distanceX)
			playerColumn := int( (player.Y - startY)/distanceY)
			beansIndex = playerRow*this.Column + playerColumn
		}
		for beans[beansIndex].Role == -1{
			beansIndex = (beansIndex+1)%(this.Row*this.Column)
		}
		player.X = beans[beansIndex].X
		player.Y = beans[beansIndex].Y
		beans[beansIndex].Role = -1
	}
	this.Beans = beans
}

func (this *Game) UpdateMap(X float64, Y float64) (score int) {
	distanceX := 0.5/11000.0 // 0.5m
	distanceY := distanceX
	score = 0
	for _,bean:=range this.Beans{
		if bean.Role == 1{
			startX := bean.X - distanceX
			stopX := bean.X + distanceX
			startY := bean.Y - distanceY
			stopY := bean.Y + distanceY

			if X > startX && X < stopX && Y > startY && Y < stopY{
				log.Debug(fmt.Sprintf("UpdateMap: eat [%f]:[%f]", bean.X, bean.Y))
				bean.Role = -1
				score = score+1
			}
		}
	}
	return score
}


text:
"""Functions for getting common objectives and constraints."""

import numpy as np

from desc.backend import block_diag, jnp, put
from desc.compute import arg_order
from desc.utils import svd_inv_null

from ._equilibrium import (
    CurrentDensity,
    Energy,
    ForceBalance,
    HelicalForceBalance,
    RadialForceBalance,
)
from .linear_objectives import (
    FixBoundaryR,
    FixBoundaryZ,
    FixCurrent,
    FixIota,
    FixLambdaGauge,
    FixPressure,
    FixPsi,
)
from .objective_funs import ObjectiveFunction

def get_fixed_boundary_constraints(profiles=True, iota=True):
    """Get the constraints necessary for a typical fixed-boundary equilibrium problem.

    Parameters
    ----------
    profiles : bool
        Whether to also return constraints to fix input profiles.
    iota : bool
        Whether to add FixIota or FixCurrent as a constraint.

    Returns
    -------
    constraints, tuple of _Objectives
        A list of the linear constraints used in fixed-boundary problems.

    """
    constraints = (
        FixBoundaryR(fixed_boundary=True),
        FixBoundaryZ(fixed_boundary=True),
        FixLambdaGauge(),
        FixPsi(),
    )
    if profiles:
        constraints += (FixPressure(),)

        if iota:
            constraints += (FixIota(),)
        else:
            constraints += (FixCurrent(),)
    return constraints

def get_equilibrium_objective(mode="force"):
    """Get the objective function for a typical force balance equilibrium problem.

    Parameters
    ----------
    mode : {"force", "forces", "energy", "vacuum"}
        which objective to return. "force" computes force residuals on unified grid.
        "forces" uses two different grids for radial and helical forces. "energy" is
        for minimizing MHD energy. "vacuum" directly minimizes current density.

    Returns
    -------
    objective, ObjectiveFunction
        An objective function with default force balance objectives.

    """
    if mode == "energy":
        objectives = Energy()
    elif mode == "force":
        objectives = ForceBalance()
    elif mode == "forces":
        objectives = (RadialForceBalance(), HelicalForceBalance())
    elif mode == "vacuum":
        objectives = CurrentDensity()
    else:
        raise ValueError("got an unknown equilibrium objective type '{}'".format(mode))
    return ObjectiveFunction(objectives)

def factorize_linear_constraints(constraints, objective_args):
    """Compute and factorize A to get pseudoinverse and nullspace.

    Given constraints of the form Ax=b, factorize A to find a particular solution xp
    and the null space Z st. Axp=b and AZ=0, so that the full space of solutions to
    Ax=b can be written as x=xp + Zy where y is now unconstrained.

    Parameters
    ----------
    constraints : tuple of Objectives
        linear objectives/constraints to factorize for projection method.
    objective_args : list of str
        names of all arguments used by the desired objective.

    Returns
    -------
    xp : ndarray
        particular solution to Ax=b
    A : dict of ndarray
        Individual constraint matrices, keyed by argument
    Ainv : dict of ndarray
        Individual pseudoinverses of constraint matrices
    b : dict of ndarray
        Individual rhs vectors
    Z : ndarray
        Null space operator for full combined A
    unfixed_idx : ndarray
        indices of x that correspond to non-fixed values
    project, recover : function
        functions to project full vector x into reduced vector y,
        and recovering x from y.

    """
    # set state vector
    args = np.concatenate([obj.args for obj in constraints])
    args = np.concatenate((args, objective_args))
    # this is all args used by both constraints and objective
    args = [arg for arg in arg_order if arg in args]
    dimensions = constraints[0].dimensions
    dim_x = 0
    x_idx = {}
    for arg in objective_args:
        x_idx[arg] = np.arange(dim_x, dim_x + dimensions[arg])
        dim_x += dimensions[arg]

    A = {}
    b = {}
    Ainv = {}
    xp = jnp.zeros(dim_x)  # particular solution to Ax=b
    constraint_args = []  # all args used in constraints
    unfixed_args = []  # subset of constraint args for unfixed objectives

    # linear constraint matrices for each objective
    for obj in constraints:
        if len(obj.args) > 1:
            raise ValueError("Linear constraints must have only 1 argument.")
        arg = obj.args[0]
        if arg not in objective_args:
            continue
        constraint_args.append(arg)
        if obj.fixed and obj.dim_f == obj.dimensions[obj.target_arg]:
            # if all coefficients are fixed the constraint matrices are not needed
            xp = put(xp, x_idx[obj.target_arg], obj.target)
        else:
            unfixed_args.append(arg)
            A_ = obj.derivatives["jac"][arg](jnp.zeros(obj.dimensions[arg]))
            b_ = obj.target
            if A_.shape[0]:
                Ainv_, Z_ = svd_inv_null(A_)
            else:
                Ainv_ = A_.T
            A[arg] = A_
            b[arg] = b_
            Ainv[arg] = Ainv_

    # catch any arguments that are not constrained
    for arg in x_idx.keys():
        if arg not in constraint_args:
            unfixed_args.append(arg)
            A[arg] = jnp.zeros((1, constraints[0].dimensions[arg]))
            b[arg] = jnp.zeros((1,))

    # full A matrix for all unfixed constraints
    if len(A):
        unfixed_idx = jnp.concatenate(
            [x_idx[arg] for arg in arg_order if arg in A.keys()]
        )
        A_full = block_diag(*[A[arg] for arg in arg_order if arg in A.keys()])
        b_full = jnp.concatenate([b[arg] for arg in arg_order if arg in b.keys()])
        Ainv_full, Z = svd_inv_null(A_full)
        xp = put(xp, unfixed_idx, Ainv_full @ b_full)

    def project(x):
        """Project a full state vector into the reduced optimization vector."""
        x_reduced = jnp.dot(Z.T, (x - xp)[unfixed_idx])
        return jnp.atleast_1d(jnp.squeeze(x_reduced))

    def recover(x_reduced):
        """Recover the full state vector from the reduced optimization vector."""
        dx = put(jnp.zeros(dim_x), unfixed_idx, Z @ x_reduced)
        return jnp.atleast_1d(jnp.squeeze(xp + dx))

    return xp, A, Ainv, b, Z, unfixed_idx, project, recover


text:
namespace MinVR {

	VRLookAtNode::VRLookAtNode(const std::string &name, VRMatrix4 initiallookAtMatrix) :
		VRDisplayNode(name),_lookAtMatrix(initiallookAtMatrix)
{
}

VRLookAtNode::~VRLookAtNode()
{
}

void
VRLookAtNode::render(VRDataIndex *renderState, VRRenderHandler *renderHandler)
{
	renderState->pushState();

	renderState->addData("LookAtMatrix", _lookAtMatrix);
	VRDisplayNode::render(renderState, renderHandler);

	renderState->popState();
}

VRDisplayNode* VRLookAtNode::create(VRMainInterface *vrMain, VRDataIndex *config, const std::string &nameSpace) {

	VRMatrix4 lookAtMatrix;

	if (config->exists("LookAtMatrix", nameSpace)){
		lookAtMatrix = config->getValue("LookAtMatrix", nameSpace);
	}
	else if (config->exists("LookAtUp", nameSpace) && config->exists("LookAtEye", nameSpace) && config->exists("LookAtCenter", nameSpace))
	{
		VRVector3 up = config->getValue("LookAtUp", nameSpace);
		VRVector3 eye = config->getValue("LookAtEye", nameSpace);
		VRVector3 center = config->getValue("LookAtCenter", nameSpace);

		VRVector3 z = center - eye;
		z = z.normalize();
		VRVector3 x = up.cross(z);
		x = x.normalize();
		VRVector3 y = z.cross(x);

		VRMatrix4 M1(	x[0], y[0], z[0], 0,
						x[1], y[1], z[1], 0,
						x[2], y[2], z[2], 0,
						0, 0, 0, 1);

		VRMatrix4 M2(	1, 0, 0, -eye[0],
						0, 1, 0, -eye[1],
						0, 0, 1, -eye[2],
						0, 0, 0, 1);

		lookAtMatrix =  M1 * M2;
	}
	else
	{
		std::cerr << "Warning : no LookAtMatrix defined for " << nameSpace << std::endl;
		std::cerr << "Either Define  LookAtMatrix or LookAtUp,LookAEye and LookAtCenter" << std::endl;
		std::cerr << "Using IdentityMatrix as default 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 " << std::endl;
	}

	VRLookAtNode *node = new VRLookAtNode(nameSpace, lookAtMatrix);

	return node;
}

} // end namespace


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.features.start_surface;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ViewGroup;

import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.feed.FeedProcessScopeFactory;
import org.chromium.chrome.browser.feed.FeedSurfaceCoordinator;
import org.chromium.chrome.browser.feed.StreamLifecycleManager;
import org.chromium.chrome.browser.feed.library.api.client.stream.Stream;
import org.chromium.chrome.browser.feed.shared.FeedSurfaceDelegate;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.ntp.snippets.SectionHeaderView;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.start_surface.R;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.modelutil.PropertyModelChangeProcessor;

/** The coordinator to control the explore surface. */
class ExploreSurfaceCoordinator implements FeedSurfaceDelegate {
    private final ChromeActivity mActivity;
    private final PropertyModelChangeProcessor mPropertyModelChangeProcessor;
    private final FeedSurfaceCreator mFeedSurfaceCreator;
    private final boolean mHasHeader;

    // mExploreSurfaceNavigationDelegate is lightweight, we keep it across FeedSurfaceCoordinators
    // after creating it during the first show.
    private ExploreSurfaceNavigationDelegate mExploreSurfaceNavigationDelegate;

    /** Interface to create {@link FeedSurfaceCoordinator} */
    interface FeedSurfaceCreator {
        /**
         * Creates the {@link FeedSurfaceCoordinator} for the specified mode.
         * @param isInNightMode Whether or not the feed surface is going to display in night mode.
         * @return The {@link FeedSurfaceCoordinator}.
         */
        FeedSurfaceCoordinator createFeedSurfaceCoordinator(boolean isInNightMode);
    }

    ExploreSurfaceCoordinator(ChromeActivity activity, ViewGroup parentView,
            PropertyModel containerPropertyModel, boolean hasHeader) {
        mActivity = activity;
        mHasHeader = hasHeader;

        mPropertyModelChangeProcessor = PropertyModelChangeProcessor.create(
                containerPropertyModel, parentView, ExploreSurfaceViewBinder::bind);
        mFeedSurfaceCreator = new FeedSurfaceCreator() {
            @Override
            public FeedSurfaceCoordinator createFeedSurfaceCoordinator(boolean isInNightMode) {
                return internalCreateFeedSurfaceCoordinator(mHasHeader, isInNightMode);
            }
        };
    }

    /**
     * Gets the {@link FeedSurfaceCreator}.
     * @return the {@link FeedSurfaceCreator}.
     */
    FeedSurfaceCreator getFeedSurfaceCreator() {
        return mFeedSurfaceCreator;
    }

    // Implements FeedSurfaceDelegate.
    @Override
    public StreamLifecycleManager createStreamLifecycleManager(Stream stream, Activity activity) {
        return new ExploreSurfaceStreamLifecycleManager(stream, activity, mHasHeader);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

    private FeedSurfaceCoordinator internalCreateFeedSurfaceCoordinator(
            boolean hasHeader, boolean isInNightMode) {
        if (mExploreSurfaceNavigationDelegate == null) {
            mExploreSurfaceNavigationDelegate = new ExploreSurfaceNavigationDelegate(mActivity);
        }
        Profile profile = Profile.getLastUsedRegularProfile();
        ExploreSurfaceActionHandler exploreSurfaceActionHandler =
                new ExploreSurfaceActionHandler(mExploreSurfaceNavigationDelegate,
                        FeedProcessScopeFactory.getFeedConsumptionObserver(),
                        FeedProcessScopeFactory.getFeedLoggingBridge(), mActivity, profile);

        SectionHeaderView sectionHeaderView = null;
        if (hasHeader) {
            LayoutInflater inflater = LayoutInflater.from(mActivity);
            if (ChromeFeatureList.isEnabled(ChromeFeatureList.REPORT_FEED_USER_ACTIONS)) {
                sectionHeaderView = (SectionHeaderView) inflater.inflate(
                        R.layout.new_tab_page_snippets_expandable_header_with_menu, null, false);
            } else {
                sectionHeaderView =
                        (SectionHeaderView) inflater.inflate(R.layout.ss_feed_header, null, false);
            }
        }
        FeedSurfaceCoordinator feedSurfaceCoordinator =
                new FeedSurfaceCoordinator(mActivity, mActivity.getSnackbarManager(),
                        mActivity.getTabModelSelector(), mActivity.getActivityTabProvider(), null,
                        null, sectionHeaderView, exploreSurfaceActionHandler, isInNightMode, this,
                        mExploreSurfaceNavigationDelegate, profile);
        feedSurfaceCoordinator.getView().setId(R.id.start_surface_explore_view);
        return feedSurfaceCoordinator;
        // TODO(crbug.com/982018): Customize surface background for incognito and dark mode.
        // TODO(crbug.com/982018): Hide signin promo UI in incognito mode.
    }
}


text:
sfera_webserver::head_request_processor::head_request_processor(sfera_webserver::http_request *req,
                                                                client_connection *connection,
                                                                callback_t callback) :
    request_processor(req, connection, callback)
{
    b_fs::path requestedPath(_connection->server().localHomeDir());
    requestedPath /= req->resourcePath();
    _requestedFileInfo = file_info(requestedPath);

    if (_requestedFileInfo.isDirectory()) {
        _requestedFileInfo = file_info(requestedPath / "index.html");
    }

    _createAndSendResponse();
}

void sfera_webserver::head_request_processor::_handleResponseSent()
{
    _callback(this);
}

auto sfera_webserver::head_request_processor::_determineStatus() -> http_response::status
{
    if (!_requestedFileInfo.exists()) {
        return http_response::status::notFound;
    } else {
        return http_response::status::ok;
    }
}

void sfera_webserver::head_request_processor::_fillResponse()
{
    if (_response->isOK()) {

        _response->headers()["Content-Length"] = std::to_string(_requestedFileInfo.size());
        _response->headers()["Content-Type"] = _requestedFileInfo.mimeType();
    }
}


text:
@interface BlogSearchViewController : ABFRealmSearchViewController

@end


text:
package com.albul.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.view.View;

import com.albul.commonhelpers.CommonHelper;
import com.albul.supportdatetimepickers.date.DatePickerDialog;
import com.albul.supportdatetimepickers.month.MonthPickerDialog;
import com.albul.supportdatetimepickers.time.TimePickerDialog;
import com.albul.supportdatetimepickers.year.YearPickerDialog;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class SampleActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String DATE_TAG = "DATE_DLG";

    public static final String TIME_TAG = "TIME_TAG";

    public static final String MONTH_TAG = "MONTH_TAG";

    public static final String YEAR_TAG = "YEAR_TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CommonHelper.setResources(getResources());

        setContentView(R.layout.activity_sample);

        findViewById(R.id.time_btn).setOnClickListener(this);
        findViewById(R.id.date_btn).setOnClickListener(this);
        findViewById(R.id.month_btn).setOnClickListener(this);
        findViewById(R.id.year_btn).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.time_btn:
                final TimePickerDialog timeDlg = new TimePickerDialog();
                final Calendar c = GregorianCalendar.getInstance();
                timeDlg.initialize(null, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), 0, DateFormat.is24HourFormat(this));
                timeDlg.show(getSupportFragmentManager(), TIME_TAG);
                break;

            case R.id.date_btn:
                final DatePickerDialog dateDlg = new DatePickerDialog();
                dateDlg.show(getSupportFragmentManager(), DATE_TAG);
                break;

            case R.id.month_btn:
                final MonthPickerDialog monthDlg = new MonthPickerDialog();
                monthDlg.show(getSupportFragmentManager(), MONTH_TAG);
                break;

            case R.id.year_btn:
                final YearPickerDialog yearDlg = new YearPickerDialog();
                yearDlg.show(getSupportFragmentManager(), MONTH_TAG);
                break;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- pressed -->
    <item android:state_pressed="true">
	    <shape>
	    <solid android:color="@color/io_openkit_general_pressed"/>
	    <corners android:radius="3dp"/>
	    </shape>
    </item>

    <!-- focused -->
    <item android:state_focused="true">
        <shape>
	    <solid android:color="@color/io_openkit_general_focused"/>
	    <corners android:radius="3dp"/>
	    </shape>
    </item>

	<!-- hovered -->
    <item android:state_hovered="true">
        <shape>
	    <solid android:color="@color/io_openkit_general_hovered"/>
	    <corners android:radius="3dp"/>
	    </shape>
	</item>

    <!-- default -->
    <item>
        <shape>
	    <solid android:color="@color/io_openkit_general_default"/>
	    <corners android:radius="3dp"/>
	    </shape>
    </item>

</selector>


text:
exports.parseLenBuff = function (socket, encoding) {

  var waiting = 0
    , buf
    , bufOffset
    ;

  function parseData(data, offset) {
    var len = data.length;
    var left = len - offset;
    if(waiting) {
      var toRead = Math.min(left, waiting);
      if(waiting <= left) {
        data.copy(buf, bufOffset, offset, offset + waiting);
        offset += waiting;
        waiting = 0;
        if(encoding) {
            socket.emit('message', buf.toString(encoding));
        } else {
            socket.emit('message', buf);
        }
        if (offset < len) {
          parseData(data, offset);
        }
      } else {
        data.copy(buf, bufOffset, offset, len);
        waiting -= (len - offset);
      }
    } else {
      waiting = data.readUInt16BE(offset);
      buf = new Buffer(waiting);
      // UINT length is 2
      parseData(data, offset + 2)
    }
  }

  socket.on('data', function(data) {
      parseData(data, 0);
  })
}

exports.sendBufferMessage = function(socket, buffMsg) {
    var len = buffMsg.length;
    var buff = new Buffer(2 + len);
    buff.writeUInt16BE(len, 0);
    buffMsg.copy(buff, 2);
    socket.write(buff);
}

exports.sendStringMessage = function(socket, buffStr) {
    var len = Buffer.byteLength(buffStr);
    var buff = new Buffer(2 + len);
    buff.writeUInt16BE(len, 0);
    buff.write(buffStr, 2);
    socket.write(buff);
}

exports.joinBufferPrependLength = function() {
    var totalLength = 0;
    for(var i = 0; i < arguments.length; i++) {
        var v = arguments[i];
        totalLength += Buffer.isBuffer(v) ? v.length : Buffer.byteLength(v);
    }
    var buff = new Buffer(2 + totalLength);
    buff.writeUInt16BE(totalLength, 0);
    var offset = 2;
    for(var i = 0; i < arguments.length; i++) {
        var v = arguments[i];
        if(Buffer.isBuffer(v)) {
            v.copy(buff, offset);
            offset += v.length;
        } else {
            buff.write(v, offset);
            offset += Buffer.byteLength(v);
        }
    }
    return buff;
}

// read len string
exports.bufferReadString = function(buff, offset) {
    var len = buff.readUInt16BE(offset);
    var str = buff.toString('utf8', offset+=2, offset+=len);
    return [str, offset];
}

exports.merge = function(dest, src) {
    for(var name in src) {
        dest[name] = src[name];
    }
    return dest;
}

var util = require('util');
exports.merge(exports, util);


text:
release = Meteor.release ? "1.1.0.2" : "(checkout)";

Template.registerHelper("release", release);

Template.registerHelper("fullApi", function () {
  return Session.get("fullApi");
});

Template.registerHelper('dstache', function() {
  return '{{';
});

Template.registerHelper('tstache', function() {
  return '{{{';
});

Template.registerHelper('lt', function () {
  return '<';
});


text:
module Verneuil
  class NameError < StandardError; end
end

require 'verneuil/address'
require 'verneuil/method'
require 'verneuil/symbol_table'
require 'verneuil/block'
require 'verneuil/program'

require 'verneuil/generator'
require 'verneuil/compiler'

require 'verneuil/scope'
require 'verneuil/process'
require 'verneuil/process_group'


text:
package br.com.navita.mobile.console.service;

import br.com.navita.mobile.console.domain.Connector;
import br.com.navita.mobile.console.exception.EntityNotFoundException;
import br.com.navita.mobile.console.view.rawdata.ConnectorRaw;

public interface ConnectorService<T extends Connector, W extends ConnectorRaw> extends BaseConnectorService<Connector> {
	T create(W connectorRaw) throws EntityNotFoundException;
	void update(W connectorRaw) throws EntityNotFoundException;

}