text:
.. doctest-skip-all

.. _whatsnew-1.0:

************************
What's New in gala v1.0?
************************

Overview
========

Gala 1.0 is a major release with significant new functionality (some of which is
described below).

This release includes (among other things):

* :ref:`whatsnew-1.0-greatcircle`
* :ref:`whatsnew-1.0-new-potentials`
* :ref:`whatsnew-1.0-scf`
* :ref:`whatsnew-1.0-stream-frame-naming`
* :ref:`whatsnew-1.0-cov-matrix`

.. _whatsnew-1.0-greatcircle:

Great circle coordinate systems
===============================

Great circle coordinate frames (GCFs) are heliocentric coordinate systems that are
typically specified as a rotation away from standard equatorial ICRS
coordinates. The resulting longitude and latitude components of a GCF specify
the angle along the great circle and the angle perpendicular (in gala, we use
:math:`\phi_1` / ``phi1`` to represent the longitude, and :math:`\phi_2` /
``phi2`` to represent the latitude). These frames are typically defined by
specifying the coordinate of the pole of the great circle, and either the
origin, :math:`(\phi_1, \phi_2) = (0, 0)`, or the longitude of the old system
(i.e. ICRS) to put at longitude :math:`\phi_1 = 0` in the new frame. The  new
``GreatCircleICRSFrame`` supports both of these options, along with two other
possible ways for defining a GCF: by specifying two points along the great
circle in the old frame, and by directly specifying the cartesian basis of the
GCF in the old coordinate system. For example, to create a GCF from a pole and
longitude zero-point::

    >>> import astropy.units as u
    >>> from astropy.coordinates import SkyCoord
    >>> from gala.coordinates import GreatCircleICRSFrame
    >>> pole = SkyCoord(ra=255*u.deg, dec=-11.5*u.deg)
    >>> gcf = GreatCircleICRSFrame(pole=pole, ra0=170*u.deg)

Or, to create a GCF from two endpoints along a great circle::

    >>> pt1 = SkyCoord(ra=170.*u.deg, dec=23.18*u.deg)
    >>> pt2 = SkyCoord(ra=125.7*u.deg, dec=-72.2*u.deg)
    >>> gcf2 = GreatCircleICRSFrame.from_endpoints(pt1, pt2)

However you define a great circle frame, these can be used with the Astropy
coordinate transformation machinery to transform positions and velocity
components to and from this and other coordinate frames. For example, to
transform a grid of points along latitude=0 in one of these systems to Galactic
coordinates to plot the great circle on the sky, we can do::

    >>> import numpy as np
    >>> grid_c = SkyCoord(phi1=np.linspace(0, 360, 128)*u.deg, phi2=0*u.deg,
    ...                   frame=gcf2)
    >>> grid_c = grid_c.galactic

When plotted, this would show the track of the great circle in Galactic
coordinates, i.e.:

.. plot::
    :context: reset
    :align: center

    import astropy.units as u
    from astropy.coordinates import SkyCoord
    from gala.coordinates import GreatCircleICRSFrame
    import matplotlib.pyplot as plt

    pt1 = SkyCoord(ra=170.*u.deg, dec=23.18*u.deg)
    pt2 = SkyCoord(ra=125.7*u.deg, dec=-72.2*u.deg)
    gcf2 = GreatCircleICRSFrame.from_endpoints(pt1, pt2)

    grid_c = SkyCoord(phi1=np.linspace(0, 360, 128)*u.deg, phi2=0*u.deg,
                     frame=gcf2)
    grid_c = grid_c.galactic

    plt.figure(figsize=(6, 4))
    plt.plot(grid_c.l.degree[grid_c.l.degree.argsort()],
            grid_c.b.degree[grid_c.l.degree.argsort()],
            ls='-', marker='')
    plt.xlabel('$l$ [deg]')
    plt.ylabel('$b$ [deg]')
    plt.tight_layout()

.. _whatsnew-1.0-new-potentials:

New potential models, including MWPotential2014
===============================================

Gala now contains an implementation of the Galpy / `Bovy 2015
<https://ui.adsabs.harvard.edu/#abs/2015ApJS..216...29B/abstract>`_
``MWPotential2014``, here called `~gala.potential.BovyMWPotential2014`. This
potential class can be used like any other potential object in Gala, for
example, for orbit integration. As a brief demo, here we compare the orbit of a
Milky Way halo object in `~gala.potential.BovyMWPotential2014` as compared to
the default Gala Milky Way model implemented as
`~gala.potential.MilkyWayPotential`::

    >>> import gala.dynamics as gd
    >>> import gala.potential as gp
    >>> mw_gala = gp.MilkyWayPotential()
    >>> mw_bovy = gp.BovyMWPotential2014()
    >>> w0 = gd.PhaseSpacePosition(pos=[25., 0, 0]*u.kpc,
    ...                            vel=[0, 0, 200.]*u.km/u.s)
    >>> orbit_gala = mw_gala.integrate_orbit(w0, dt=1., n_steps=1000)
    >>> orbit_bovy = mw_bovy.integrate_orbit(w0, dt=1., n_steps=1000)

Here is a comparison of the two orbits over-plotted on the same axes:

.. plot::
    :context: reset
    :align: center

    import astropy.units as u
    import matplotlib.pyplot as plt
    import gala.dynamics as gd
    import gala.potential as gp

    mw_gala = gp.MilkyWayPotential()
    mw_bovy = gp.BovyMWPotential2014()
    w0 = gd.PhaseSpacePosition(pos=[25., 0, 0]*u.kpc,
                               vel=[0, 0, 200.]*u.km/u.s)
    orbit_gala = mw_gala.integrate_orbit(w0, dt=1., n_steps=1000)
    orbit_bovy = mw_bovy.integrate_orbit(w0, dt=1., n_steps=1000)

    fig, ax = plt.subplots(1, 1, figsize=(6, 6))
    orbit_gala.plot(['x', 'z'], label='Gala', marker='', axes=[ax])
    orbit_bovy.plot(['x', 'z'], label='Bovy2015', marker='', axes=[ax])
    plt.legend(loc='best')
    plt.tight_layout()

.. _whatsnew-1.0-scf:

Basis function expansion potential models with the self-consistent field method
===============================================================================

Gala now contains support for constructing and using flexible (static)
gravitational potential models using the self-consistent field (SCF) basis
function expansion method. Expansion coefficients can be computed from both
analytic density distributions or from discrete particle distributions (e.g.,
from an N-body simulation). For more information about this new subpackage, see
the :ref:`scf` documentation.

.. _whatsnew-1.0-stream-frame-naming:

Stellar stream coordinate frame names now reflect the source reference
======================================================================

Each of the stellar stream coordinate frames now contains the name of the author
that defined the frame. For example, the ``GD1`` frame has been renamed to
`~gala.coordaintes.GD1Koposov10` to indicate that the frame was defined in
Koposov et al. 2010. This is true for each of the major stellar stream frames:

* ``GD1`` has been renamed `~gala.coordinates.GD1Koposov10`
* ``Sagittarius`` has been renamed `~gala.coordinates.SagittariusLaw10`
* ``Orphan`` has been renamed `~gala.coordinates.OrphanNewberg10`, and a new
  Orphan stream coordinate frame has been added:
  `~gala.coordinates.OrphanKoposov19`
* ``Ophiuchus`` has been renamed `~gala.coordinates.OphiuchusPriceWhelan16`
* ``Pal5`` has been renamed `~gala.coordinates.Pal5PriceWhelan18`
* ``MagellanicStream`` has been renamed
  `~gala.coordinates.MagellanicStreamNidever08`

.. _whatsnew-1.0-cov-matrix:

Transforming proper motion covariance matrices
==============================================

The Gaia mission provides full astrometric covariance matrices for each of its
sources, which not only specify the uncertainty in each parameter, but also
specify the correlations between the uncertainties of the astrometric
parameters. These covariance matrices are provided in the ICRS coordinate
system, but often it is useful to transform the Gaia data to other coordinate
systems when, e.g., modeling stellar streams. The proper motion covariance
matrix can be analytically and straightforwardly transformed along with the
positions and proper motions themselves if the transformation is a rotation away
from ICRS, such as the case for the new ``GreatCircleICRSFrame`` or stellar
stream coordinate frames described above. As an example, we will transform the
Gaia proper motion covariance matrix for a source to the ``GD1Koposov10``
coordinate frame::

    >>> from gala.coordinates import transform_pm_cov, GD1Koposov10
    >>> cov = np.array([[ 0.07567177, -0.01698125],
    ...                 [-0.01698125,  0.03907039]])
    >>> c = SkyCoord(ra=130.99*u.deg, dec=34.53*u.deg,
    ...              distance=454.76*u.pc,
    ...              pm_ra_cosdec=11.5*u.mas/u.yr,
    ...              pm_dec=-23.46661*u.mas/u.yr)
    >>> cov_gd1 = transform_pm_cov(c, cov, GD1Koposov10)


text:
package GtsSoftware.personal;

import java.text.SimpleDateFormat;
import java.util.Vector;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import GtsSoftware.general.CoAccion;
import GtsSoftware.general.CoException;

public class AccionAgregarCurso extends CoAccion {

	@Override
	public void ejecutar(ServletContext sc, HttpServletRequest request,
			HttpServletResponse response) throws CoException {

		Integer tipo = Integer.parseInt(request.getParameter("tipo"));
		HttpSession sesion= request.getSession(true);
		if(tipo==2){
			CursoData cursoData = new CursoData();
			cursoData = new PersonalFuncion().crearCurso(request, response);
			boolean result = new PersonalFuncion().agregarCurso(cursoData);
			//Combo Curso
			Vector<CursoData> cmbCurso = new PersonalFuncion().comboCurso();
			sesion.setAttribute("cmbCurso", cmbCurso);
			this.direccionar(sc, request, response, "/Gts/curso/buscarcurso.jsp");
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
"""RequestContext: context for requests that persist through all of nova."""

import copy

from keystoneclient import auth
from keystoneclient import service_catalog
from oslo.utils import timeutils
import six

from nova import exception
from nova.openstack.common import context
from nova.i18n import _, _LW
from nova.openstack.common import local
from nova.openstack.common import log as logging
from nova import policy

LOG = logging.getLogger(__name__)

class _ContextAuthPlugin(auth.BaseAuthPlugin):
    """A keystoneclient auth plugin that uses the values from the Context.

    Ideally we would use the plugin provided by auth_token middleware however
    this plugin isn't serialized yet so we construct one from the serialized
    auth data.
    """

    def __init__(self, auth_token, sc):
        super(_ContextAuthPlugin, self).__init__()

        self.auth_token = auth_token
        sc = {'serviceCatalog': sc}
        self.service_catalog = service_catalog.ServiceCatalogV2(sc)

    def get_token(self, *args, **kwargs):
        return self.auth_token

    def get_endpoint(self, session, service_type=None, interface=None,
                     region_name=None, service_name=None, **kwargs):
        return self.service_catalog.url_for(service_type=service_type,
                                            service_name=service_name,
                                            endpoint_type=interface,
                                            region_name=region_name)

class RequestContext(object):
    """Security context and request information.

    Represents the user taking a given action within the system.

    """

    def __init__(self, user_id, project_id, is_admin=None, read_deleted="no",
                 roles=None, remote_address=None, timestamp=None,
                 request_id=None, auth_token=None, overwrite=True,
                 quota_class=None, user_name=None, project_name=None,
                 service_catalog=None, instance_lock_checked=False,
                 user_auth_plugin=None, **kwargs):
        """:param read_deleted: 'no' indicates deleted records are hidden,
                'yes' indicates deleted records are visible,
                'only' indicates that *only* deleted records are visible.

           :param overwrite: Set to False to ensure that the greenthread local
                copy of the index is not overwritten.

           :param user_auth_plugin: The auth plugin for the current request's
                authentication data.

           :param kwargs: Extra arguments that might be present, but we ignore
                because they possibly came in from older rpc messages.
        """
        if kwargs:
            LOG.warning(_LW('Arguments dropped when creating context: %s') %
                        str(kwargs))

        self.user_id = user_id
        self.project_id = project_id
        self.roles = roles or []
        self.read_deleted = read_deleted
        self.remote_address = remote_address
        if not timestamp:
            timestamp = timeutils.utcnow()
        if isinstance(timestamp, six.string_types):
            timestamp = timeutils.parse_strtime(timestamp)
        self.timestamp = timestamp
        if not request_id:
            request_id = context.generate_request_id()
        self.request_id = request_id
        self.auth_token = auth_token

        if service_catalog:
            # Only include required parts of service_catalog
            self.service_catalog = [s for s in service_catalog
                if s.get('type') in ('volume', 'volumev2')]
        else:
            # if list is empty or none
            self.service_catalog = []

        self.instance_lock_checked = instance_lock_checked

        # NOTE(markmc): this attribute is currently only used by the
        # rs_limits turnstile pre-processor.
        # See https://lists.launchpad.net/openstack/msg12200.html
        self.quota_class = quota_class
        self.user_name = user_name
        self.project_name = project_name
        self.is_admin = is_admin
        self.user_auth_plugin = user_auth_plugin
        if self.is_admin is None:
            self.is_admin = policy.check_is_admin(self)
        if overwrite or not hasattr(local.store, 'context'):
            self.update_store()

    def get_auth_plugin(self):
        if self.user_auth_plugin:
            return self.user_auth_plugin
        else:
            return _ContextAuthPlugin(self.auth_token, self.service_catalog)

    def _get_read_deleted(self):
        return self._read_deleted

    def _set_read_deleted(self, read_deleted):
        if read_deleted not in ('no', 'yes', 'only'):
            raise ValueError(_("read_deleted can only be one of 'no', "
                               "'yes' or 'only', not %r") % read_deleted)
        self._read_deleted = read_deleted

    def _del_read_deleted(self):
        del self._read_deleted

    read_deleted = property(_get_read_deleted, _set_read_deleted,
                            _del_read_deleted)

    def update_store(self):
        local.store.context = self

    def to_dict(self):
        return {'user_id': self.user_id,
                'project_id': self.project_id,
                'is_admin': self.is_admin,
                'read_deleted': self.read_deleted,
                'roles': self.roles,
                'remote_address': self.remote_address,
                'timestamp': timeutils.strtime(self.timestamp),
                'request_id': self.request_id,
                'auth_token': self.auth_token,
                'quota_class': self.quota_class,
                'user_name': self.user_name,
                'service_catalog': self.service_catalog,
                'project_name': self.project_name,
                'instance_lock_checked': self.instance_lock_checked,
                'tenant': self.tenant,
                'user': self.user}

    @classmethod
    def from_dict(cls, values):
        values.pop('user', None)
        values.pop('tenant', None)
        return cls(**values)

    def elevated(self, read_deleted=None, overwrite=False):
        """Return a version of this context with admin flag set."""
        context = copy.deepcopy(self)
        context.is_admin = True

        if 'admin' not in context.roles:
            context.roles.append('admin')

        if read_deleted is not None:
            context.read_deleted = read_deleted

        return context

    # NOTE(sirp): the openstack/common version of RequestContext uses
    # tenant/user whereas the Nova version uses project_id/user_id. We need
    # this shim in order to use context-aware code from openstack/common, like
    # logging, until we make the switch to using openstack/common's version of
    # RequestContext.
    @property
    def tenant(self):
        return self.project_id

    @property
    def user(self):
        return self.user_id

def get_admin_context(read_deleted="no"):
    return RequestContext(user_id=None,
                          project_id=None,
                          is_admin=True,
                          read_deleted=read_deleted,
                          overwrite=False)

def is_user_context(context):
    """Indicates if the request context is a normal user."""
    if not context:
        return False
    if context.is_admin:
        return False
    if not context.user_id or not context.project_id:
        return False
    return True

def require_admin_context(ctxt):
    """Raise exception.AdminRequired() if context is an admin context."""
    if not ctxt.is_admin:
        raise exception.AdminRequired()

def require_context(ctxt):
    """Raise exception.Forbidden() if context is not a user or an
    admin context.
    """
    if not ctxt.is_admin and not is_user_context(ctxt):
        raise exception.Forbidden()

def authorize_project_context(context, project_id):
    """Ensures a request has permission to access the given project."""
    if is_user_context(context):
        if not context.project_id:
            raise exception.Forbidden()
        elif context.project_id != project_id:
            raise exception.Forbidden()

def authorize_root_or_parent_project_context(context,project_id):
    """Ensures a request has permission to access root or parent project"""
    if not context.project_id:
        raise exception.Forbidden()
    elif context.project_id != project_id:
        raise exception.Forbidden()

def authorize_user_context(context, user_id):
    """Ensures a request has permission to access the given user."""
    if is_user_context(context):
        if not context.user_id:
            raise exception.Forbidden()
        elif context.user_id != user_id:
            raise exception.Forbidden()

def authorize_quota_class_context(context, class_name):
    """Ensures a request has permission to access the given quota class."""
    if is_user_context(context):
        if not context.quota_class:
            raise exception.Forbidden()
        elif context.quota_class != class_name:
            raise exception.Forbidden()


text:
layout:     post
author:     Christoph Broschinski
author_lnk: https://github.com/cbroschinski
title:      University of Milan reports its 2017 APC expenditures
date:       2018-02-09 10:00:00
summary:
categories: [general, openAPC]
comments: true
---

The [University of Milan](http://www.unimi.it/ENG/) has reported its APC expenditures for the 2017 period.

Contact person is [Paola Galimberti](mailto:paola.galimberti@unimi.it).

## Cost data

The new dataset covers publication fees for 83 articles. Total expenditure amounts to 142 671€ and the average fee is 1 719€.

The following table shows the payments the University of Milan has made to publishers in 2017:

|                                            | Articles| Fees paid in EURO| Mean Fee paid|
|:-------------------------------------------|--------:|-----------------:|-------------:|
|Springer Nature                             |       20|             33216|          1661|
|Frontiers Media SA                          |       14|             28170|          2012|
|Public Library of Science (PLoS)            |        9|             13545|          1505|
|MDPI AG                                     |        7|             10130|          1447|
|Elsevier BV                                 |        6|              9588|          1598|
|Wiley-Blackwell                             |        5|             11258|          2252|
|Hindawi Publishing Corporation              |        4|              6450|          1612|
|Informa UK Limited                          |        4|              5821|          1455|
|American Chemical Society (ACS)             |        3|              8000|          2667|
|Walter de Gruyter GmbH                      |        3|              3500|          1167|
|OMICS Publishing Group                      |        2|              1839|           920|
|AIP Publishing                              |        1|              2500|          2500|
|American Society of Agronomy                |        1|              1400|          1400|
|American Society of Plant Biologists (ASPB) |        1|               950|           950|
|Impact Journals, LLC                        |        1|              3506|          3506|
|Oxford University Press (OUP)               |        1|              1799|          1799|
|Scientific Research Publishing, Inc,        |        1|               999|           999|

## Overview

With the recent contribution included, the overall APC data for the University of Milan now looks as follows:

### Fees paid per publisher (in EURO)

![plot of chunk tree_milan_2018_02_09_full](/figure/tree_milan_2018_02_09_full-1.png)

###  Average costs per year (in EURO)

![plot of chunk box_milan_2018_02_09_year_full](/figure/box_milan_2018_02_09_year_full-1.png)

###  Average costs per publisher (in EURO)

![plot of chunk box_milan_2018_02_09_publisher_full](/figure/box_milan_2018_02_09_publisher_full-1.png)


text:
HTTPLIB_OPEN_NAMESPACE

boost::optional<const extension_parameter_t &> extension_t::parameter(boost::string_view name) const {
    auto it = std::find_if(parameters.begin(), parameters.end(),
        [&name](const auto &v) {
            return v.name == name;
        }
    );

    if (it != parameters.end()) {
        return *it;
    } else {
        return boost::none;
    }
}

bool extension_t::equals(boost::string_view other) const {
 return boost::algorithm::iequals(name, other);
}

boost::optional<const extension_t &> extension_list_t::get(boost::string_view name) const {
    auto it = std::find_if(extensions.begin(), extensions.end(),
        [&name](const auto &v) {
            return v.equals(name);
        }
    );

    if (it != extensions.end()) {
        return *it;
    } else {
        return boost::none;
    }
}

namespace {

boost::optional<extension_parameter_t> parse_extension_parameter(boost::string_view &data) {
    boost::string_view leftover_data = data;

    extension_parameter_t result;

    if (auto name = detail::parse_token(leftover_data)) {
        result.name = std::move(*name);
    } else {
        return boost::none;
    }

    detail::skip_optional_whitespaces(leftover_data);

    if (leftover_data.empty() || leftover_data[0] != '=') {
        return boost::none;
    }

    leftover_data = leftover_data.substr(1);
    detail::skip_optional_whitespaces(leftover_data);

    if (leftover_data.empty()) {
        return boost::none;
    }

    boost::optional<std::string> value;

    if (leftover_data[0] == '"') {
        value = detail::parse_quoted_string(leftover_data);
    } else {
        value = detail::parse_token(leftover_data);
    }

    if (value) {
        data = leftover_data;
        result.value = std::move(*value);
        return result;
    } else {
        return boost::none;
    }
}

boost::optional<extension_t> parse_extension(boost::string_view &data) {
    boost::string_view leftover_data = data;

    extension_t result;

    if (auto token = detail::parse_token(leftover_data)) {
        result.name = std::move(*token);
    } else {
        return boost::none;
    }

    while (true) {
        detail::skip_optional_whitespaces(leftover_data);

        if (leftover_data.empty() || leftover_data[0] != ';') {
            data = leftover_data;
            return result;
        }

        leftover_data = leftover_data.substr(1);
        detail::skip_optional_whitespaces(leftover_data);

        if (auto parameter = parse_extension_parameter(leftover_data)) {
            result.parameters.emplace_back(std::move(*parameter));
        } else {
            return boost::none;
        }
    }
}

} // namespace

bool detail::parse_extension_list(boost::string_view data, extension_list_t &result) {
    while (true) {
        if (data.empty()) {
            return false;
        }

        if (data[0] == ',') {
            data = data.substr(1);
        } else {
            break;
        }

        detail::skip_optional_whitespaces(data);
    }

    if (auto extension = parse_extension(data)) {
        result.extensions.emplace_back(std::move(*extension));
    } else {
        return false;
    }

    while (true) {
        detail::skip_optional_whitespaces(data);

        if (data.empty()) {
            return true;
        }

        if (data[0] != ',') {
            return false;
        }

        data = data.substr(1);
        detail::skip_optional_whitespaces(data);

        if (data.empty() || data[0] == ',') {
            continue;
        }

        if (auto extension = parse_extension(data)) {
            result.extensions.emplace_back(std::move(*extension));
        } else {
            return false;
        }
    }
}

boost::optional<extension_list_t> parse_extension_list(boost::string_view data) {
    extension_list_t result;

    if (detail::parse_extension_list(data, result)) {
        return result;
    } else {
        return boost::none;
    }
}

HTTPLIB_CLOSE_NAMESPACE


text:
package com.fincatto.documentofiscal.cte300.classes.enviolote;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;

import com.fincatto.documentofiscal.DFAmbiente;
import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.DFUnidadeFederativa;

/**
 * @author Caio
 * @info Tipo Retorno do Pedido de Concessão de Autorização da CT-e
 */

@Root(name = "retEnviCte")
@Namespace(reference = "http://www.portalfiscal.inf.br/cte")
public class CTeEnvioLoteRetorno extends DFBase {
    private static final long serialVersionUID = -8644637411545424540L;

    @Element(name = "tpAmb", required = false)
    private DFAmbiente ambiente;

    @Element(name = "cUF", required = false)
    private DFUnidadeFederativa uf;

    @Element(name = "verAplic", required = false)
    private String versaoAplicacao;

    @Element(name = "cStat", required = false)
    private String status;

    @Element(name = "xMotivo", required = false)
    private String motivo;

    @Element(name = "infRec", required = false)
    private CTeEnvioLoteRetornoInfoRecebimento infoRecebimento;

    @Attribute(name = "versao", required = false)
    private String versao;

    public CTeEnvioLoteRetorno() {
        this.ambiente = null;
        this.uf = null;
        this.versaoAplicacao = null;
        this.status = null;
        this.motivo = null;
        this.infoRecebimento = null;
        this.versao = null;
    }

    public DFAmbiente getAmbiente() {
        return this.ambiente;
    }

    /**
     * Identificação do Ambiente:1 - Produção; 2 - Homologação
     */
    public void setAmbiente(final DFAmbiente ambiente) {
        this.ambiente = ambiente;
    }

    public DFUnidadeFederativa getUf() {
        return this.uf;
    }

    /**
     * Identificação da UF
     */
    public void setUf(final DFUnidadeFederativa uf) {
        this.uf = uf;
    }

    public String getVersaoAplicacao() {
        return this.versaoAplicacao;
    }

    /**
     * Versão do Aplicativo que recebeu o Lote.
     */
    public void setVersaoAplicacao(final String versaoAplicacao) {
        this.versaoAplicacao = versaoAplicacao;
    }

    public String getStatus() {
        return this.status;
    }

    /**
     * Código do status da mensagem enviada.
     */
    public void setStatus(final String status) {
        this.status = status;
    }

    public String getMotivo() {
        return this.motivo;
    }

    /**
     * Descrição literal do status do serviço solicitado.
     */
    public void setMotivo(final String motivo) {
        this.motivo = motivo;
    }

    public CTeEnvioLoteRetornoInfoRecebimento getInfoRecebimento() {
        return this.infoRecebimento;
    }

    /**
     * Dados do Recibo do Lote
     */
    public void setInfoRecebimento(final CTeEnvioLoteRetornoInfoRecebimento infoRecebimento) {
        this.infoRecebimento = infoRecebimento;
    }

    public String getVersao() {
        return this.versao;
    }

    /**
     * versão da aplicação
     */
    public void setVersao(final String versao) {
        this.versao = versao;
    }
}


text:
class ActivityIncentive
  include ActiveModel::Model
  attr_accessor :value, :data_element_ext_ref

  validates :value, presence: true
  validates :name, presence: true

  def activity
    @activity ||= ActivityForm.new
  end

  delegate :external_reference=, to: :activity

  delegate :external_reference, to: :activity

  delegate :name=, to: :activity

  delegate :name, to: :activity
end


text:
package org.apache.commons.beanutils;

import java.util.Map;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

/**
 * A PropertyUtilsBean which customises the behaviour of the
 * setNestedProperty and getNestedProperty methods to look for
 * simple properties in preference to map entries.
 */
public class PropsFirstPropertyUtilsBean extends PropertyUtilsBean {

    public PropsFirstPropertyUtilsBean() {
        super();
    }

    /**
     * Note: this is a *very rough* override of this method. In particular,
     * it does not handle MAPPED_DELIM and INDEXED_DELIM chars in the
     * propertyName, so propertyNames like "a(b)" or "a[3]" will not
     * be correctly handled.
     */
    protected Object getPropertyOfMapBean(Map bean, String propertyName)
    throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

        PropertyDescriptor descriptor = getPropertyDescriptor(bean, propertyName);
        if (descriptor == null) {
            // no simple property exists so return the value from the map
            return bean.get(propertyName);
        } else {
            // a simple property exists so return its value instead.
            return getSimpleProperty(bean, propertyName);
        }
    }

    /**
     * Note: this is a *very rough* override of this method. In particular,
     * it does not handle MAPPED_DELIM and INDEXED_DELIM chars in the
     * propertyName, so propertyNames like "a(b)" or "a[3]" will not
     * be correctly handled.
     */
    protected void setPropertyOfMapBean(Map bean, String propertyName, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        PropertyDescriptor descriptor = getPropertyDescriptor(bean, propertyName);
        if (descriptor == null) {
            // no simple property exists so put the value into the map
            bean.put(propertyName, value);
        } else {
            // a simple property exists so set that instead.
            setSimpleProperty(bean, propertyName, value);
        }
    }
}


text:
package com.clearlyspam23.GLE.basic.layers.tile.edit.actions;

import com.clearlyspam23.GLE.basic.layers.tile.TileLocation;
import com.clearlyspam23.GLE.basic.layers.tile.gui.MovableTileSelection;
import com.clearlyspam23.GLE.edit.EditAction;

public class MoveSelectionAction implements EditAction {

	private TileLocation originalLocation;
	private TileLocation newLocation;
	private MovableTileSelection selection;

	public MoveSelectionAction(TileLocation originalLocation, TileLocation newLocation, MovableTileSelection selection){
		this.originalLocation = originalLocation;
		this.newLocation = newLocation;
		this.selection = selection;
	}

	@Override
	public void undoAction() {
		selection.setToOffset(originalLocation);
	}

	@Override
	public void doAction() {
		selection.setToOffset(newLocation);
	}

	@Override
	public String getDescription() {
		return "Moved Selection from " + originalLocation + " to " + newLocation;
	}

}


text:
//
// $Id: Reader.cpp 6141 2014-05-05 21:03:47Z chambm $
//
//
// Original author: Jay Holman <jay.holman .@. vanderbilt.edu>
//
// Copyright 2008 Spielberg Family Center for Applied Proteomics
//   Cedars Sinai Medical Center, Los Angeles, California  90048
// Copyright 2008 Vanderbilt University - Nashville, TN 37232
//
// 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.
//

#include "Reader.hpp"

using System::Exception;
using System::String;

//#pragma unmanaged
//#include <boost/utility/mutexed_singleton.hpp>
//#pragma managed

namespace pwiz {
namespace CLI {
namespace tradata {

static array<System::String^>^ vectorToStringArray(const std::vector<std::string>& v)
{
    array<System::String^>^ idStrings = gcnew array<System::String^>(v.size());
    for (size_t i = 0; i < v.size(); i++)
        idStrings[i] = ToSystemString(v[i]);
    return idStrings;
}

bool Reader::accept(System::String^ filename, System::String^ head)
{
    try {return base_->accept(ToStdString(filename), ToStdString(head));} CATCH_AND_FORWARD
}

void Reader::read(System::String^ filename, System::String^ head, TraData^ result)
{
    read(filename, head, result, 0);
}

void Reader::read(System::String^ filename, System::String^ head, TraData^ result, int sampleIndex)
{
    try {base_->read(ToStdString(filename), ToStdString(head), **result->base_, sampleIndex);} CATCH_AND_FORWARD
}

void Reader::read(System::String^ filename, System::String^ head, TraDataList^ results)
{
    try {base_->read(ToStdString(filename), ToStdString(head), *results->base_);} CATCH_AND_FORWARD
}

System::String^ ReaderList::identify(System::String^ filename)
{
    try {return ToSystemString(base_->identify(ToStdString(filename)));} CATCH_AND_FORWARD
}

System::String^ ReaderList::identify(System::String^ filename, System::String^ head)
{
    try {return ToSystemString(base_->identify(ToStdString(filename), ToStdString(head)));} CATCH_AND_FORWARD
}

void ReaderList::read(System::String^ filename, System::String^ head, TraData^ result)
{
    read(filename, head, result, 0);
}

void ReaderList::read(System::String^ filename, System::String^ head, TraData^ result, int sampleIndex)
{
    try {base_->read(ToStdString(filename), ToStdString(head), **result->base_, sampleIndex);} CATCH_AND_FORWARD
}

void ReaderList::read(System::String^ filename, System::String^ head, TraDataList^ results)
{
    try {base_->read(ToStdString(filename), ToStdString(head), *results->base_);} CATCH_AND_FORWARD
}

void ReaderList::read(System::String^ filename, TraData^ result)
{
    read(filename, result, 0);
}

void ReaderList::read(System::String^ filename, TraData^ result, int sampleIndex)
{
    try {base_->read(ToStdString(filename), **result->base_, sampleIndex);} CATCH_AND_FORWARD
}

void ReaderList::read(System::String^ filename, TraDataList^ results)
{
    try {base_->read(ToStdString(filename), *results->base_);} CATCH_AND_FORWARD
}

namespace {

/*#pragma unmanaged
struct FullReaderListSingleton : public boost::mutexed_singleton<FullReaderListSingleton>
{
    FullReaderListSingleton(boost::restricted) {}

    pwiz::tradata::FullReaderList list;
};
#pragma managed*/

} // namespace

ReaderList^ ReaderList::DefaultReaderList::get()
{
    try
    {
        pwiz::tradata::DefaultReaderList* list = new pwiz::tradata::DefaultReaderList();
        return gcnew ReaderList(list, gcnew System::Object());
    }
    CATCH_AND_FORWARD
}

} // namespace tradata
} // namespace CLI
} // namespace pwiz


text:
package org.apache.kafka.clients;

import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.network.NetworkReceive;
import org.apache.kafka.common.network.Selectable;
import org.apache.kafka.common.network.Send;
import org.apache.kafka.common.protocol.ApiKeys;
import org.apache.kafka.common.protocol.ProtoUtils;
import org.apache.kafka.common.protocol.types.Struct;
import org.apache.kafka.common.requests.MetadataRequest;
import org.apache.kafka.common.requests.MetadataResponse;
import org.apache.kafka.common.requests.RequestHeader;
import org.apache.kafka.common.requests.RequestSend;
import org.apache.kafka.common.requests.ResponseHeader;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * A network client for asynchronous request/response network i/o. This is an internal class used to implement the
 * user-facing producer and consumer clients.
 * <p>
 * This class is not thread-safe!
 */
public class NetworkClient implements KafkaClient {

    private static final Logger log = LoggerFactory.getLogger(NetworkClient.class);

    /* the selector used to perform network i/o */
    private final Selectable selector;

    private final MetadataUpdater metadataUpdater;

    /* a list of nodes we've connected to in the past */
    private final List<Integer> nodesEverSeen;
    private final Map<Integer, Node> nodesEverSeenById;

    /* random offset into nodesEverSeen list */
    private final Random randOffset;

    /* the state of each node's connection */
    private final ClusterConnectionStates connectionStates;

    /* the set of requests currently being sent or awaiting a response */
    private final InFlightRequests inFlightRequests;

    /* the socket send buffer size in bytes */
    private final int socketSendBuffer;

    /* the socket receive size buffer in bytes */
    private final int socketReceiveBuffer;

    /* the client id used to identify this client in requests to the server */
    private final String clientId;

    /* a random offset to use when choosing nodes to avoid having all nodes choose the same node */
    private final int nodeIndexOffset;

    /* the current correlation id to use when sending requests to servers */
    private int correlation;

    /* max time in ms for the producer to wait for acknowledgement from server*/
    private final int requestTimeoutMs;

    private final Time time;

    public NetworkClient(Selectable selector,
                         Metadata metadata,
                         String clientId,
                         int maxInFlightRequestsPerConnection,
                         long reconnectBackoffMs,
                         int socketSendBuffer,
                         int socketReceiveBuffer,
                         int requestTimeoutMs,
                         Time time) {
        this(null, metadata, selector, clientId, maxInFlightRequestsPerConnection,
                reconnectBackoffMs, socketSendBuffer, socketReceiveBuffer, requestTimeoutMs, time);
    }

    public NetworkClient(Selectable selector,
                         MetadataUpdater metadataUpdater,
                         String clientId,
                         int maxInFlightRequestsPerConnection,
                         long reconnectBackoffMs,
                         int socketSendBuffer,
                         int socketReceiveBuffer,
                         int requestTimeoutMs,
                         Time time) {
        this(metadataUpdater, null, selector, clientId, maxInFlightRequestsPerConnection, reconnectBackoffMs,
                socketSendBuffer, socketReceiveBuffer, requestTimeoutMs, time);
    }

    private NetworkClient(MetadataUpdater metadataUpdater,
                          Metadata metadata,
                          Selectable selector,
                          String clientId,
                          int maxInFlightRequestsPerConnection,
                          long reconnectBackoffMs,
                          int socketSendBuffer,
                          int socketReceiveBuffer,
                          int requestTimeoutMs,
                          Time time) {

        /* It would be better if we could pass `DefaultMetadataUpdater` from the public constructor, but it's not
         * possible because `DefaultMetadataUpdater` is an inner class and it can only be instantiated after the
         * super constructor is invoked.
         */
        if (metadataUpdater == null) {
            if (metadata == null)
                throw new IllegalArgumentException("`metadata` must not be null");
            this.metadataUpdater = new DefaultMetadataUpdater(metadata);
        } else {
            this.metadataUpdater = metadataUpdater;
        }
        this.selector = selector;
        this.clientId = clientId;
        this.inFlightRequests = new InFlightRequests(maxInFlightRequestsPerConnection);
        this.connectionStates = new ClusterConnectionStates(reconnectBackoffMs);
        this.socketSendBuffer = socketSendBuffer;
        this.socketReceiveBuffer = socketReceiveBuffer;
        this.correlation = 0;
        this.randOffset = new Random();
        this.nodeIndexOffset = this.randOffset.nextInt(Integer.MAX_VALUE);
        this.requestTimeoutMs = requestTimeoutMs;
        this.nodesEverSeen = new ArrayList<>();
        this.nodesEverSeenById = new HashMap<>();

        this.time = time;
    }

    /**
     * Begin connecting to the given node, return true if we are already connected and ready to send to that node.
     *
     * @param node The node to check
     * @param now The current timestamp
     * @return True if we are ready to send to the given node
     */
    @Override
    public boolean ready(Node node, long now) {
        if (isReady(node, now))
            return true;

        if (connectionStates.canConnect(node.idString(), now))
            // if we are interested in sending to a node and we don't have a connection to it, initiate one
            initiateConnect(node, now);

        return false;
    }

    /**
     * Closes the connection to a particular node (if there is one).
     *
     * @param nodeId The id of the node
     */
    @Override
    public void close(String nodeId) {
        selector.close(nodeId);
        for (ClientRequest request : inFlightRequests.clearAll(nodeId))
            metadataUpdater.maybeHandleDisconnection(request);
        connectionStates.remove(nodeId);
    }

    /**
     * Returns the number of milliseconds to wait, based on the connection state, before attempting to send data. When
     * disconnected, this respects the reconnect backoff time. When connecting or connected, this handles slow/stalled
     * connections.
     *
     * @param node The node to check
     * @param now The current timestamp
     * @return The number of milliseconds to wait.
     */
    @Override
    public long connectionDelay(Node node, long now) {
        return connectionStates.connectionDelay(node.idString(), now);
    }

    /**
     * Check if the connection of the node has failed, based on the connection state. Such connection failure are
     * usually transient and can be resumed in the next {@link #ready(org.apache.kafka.common.Node, long)} }
     * call, but there are cases where transient failures needs to be caught and re-acted upon.
     *
     * @param node the node to check
     * @return true iff the connection has failed and the node is disconnected
     */
    @Override
    public boolean connectionFailed(Node node) {
        return connectionStates.connectionState(node.idString()).equals(ConnectionState.DISCONNECTED);
    }

    /**
     * Check if the node with the given id is ready to send more requests.
     *
     * @param node The node
     * @param now The current time in ms
     * @return true if the node is ready
     */
    @Override
    public boolean isReady(Node node, long now) {
        // if we need to update our metadata now declare all requests unready to make metadata requests first
        // priority
        return !metadataUpdater.isUpdateDue(now) && canSendRequest(node.idString());
    }

    /**
     * Are we connected and ready and able to send more requests to the given connection?
     *
     * @param node The node
     */
    private boolean canSendRequest(String node) {
        return connectionStates.isConnected(node) && selector.isChannelReady(node) && inFlightRequests.canSendMore(node);
    }

    /**
     * Queue up the given request for sending. Requests can only be sent out to ready nodes.
     *
     * @param request The request
     * @param now The current timestamp
     */
    @Override
    public void send(ClientRequest request, long now) {
        String nodeId = request.request().destination();
        if (!canSendRequest(nodeId))
            throw new IllegalStateException("Attempt to send a request to node " + nodeId + " which is not ready.");
        doSend(request, now);
    }

    private void doSend(ClientRequest request, long now) {
        request.setSendTimeMs(now);
        this.inFlightRequests.add(request);
        selector.send(request.request());
    }

    /**
     * Do actual reads and writes to sockets.
     *
     * @param timeout The maximum amount of time to wait (in ms) for responses if there are none immediately,
     *                must be non-negative. The actual timeout will be the minimum of timeout, request timeout and
     *                metadata timeout
     * @param now The current time in milliseconds
     * @return The list of responses received
     */
    @Override
    public List<ClientResponse> poll(long timeout, long now) {
        long metadataTimeout = metadataUpdater.maybeUpdate(now);
        try {
            this.selector.poll(Utils.min(timeout, metadataTimeout, requestTimeoutMs));
        } catch (IOException e) {
            log.error("Unexpected error during I/O in producer network thread", e);
        }

        // process completed actions
        long updatedNow = this.time.milliseconds();
        List<ClientResponse> responses = new ArrayList<>();
        handleCompletedSends(responses, updatedNow);
        handleCompletedReceives(responses, updatedNow);
        handleDisconnections(responses, updatedNow);
        handleConnections();
        handleTimedOutRequests(responses, updatedNow);

        // invoke callbacks
        for (ClientResponse response : responses) {
            if (response.request().hasCallback()) {
                try {
                    response.request().callback().onComplete(response);
                } catch (Exception e) {
                    log.error("Uncaught error in request completion:", e);
                }
            }
        }

        return responses;
    }

    /**
     * Get the number of in-flight requests
     */
    @Override
    public int inFlightRequestCount() {
        return this.inFlightRequests.inFlightRequestCount();
    }

    /**
     * Get the number of in-flight requests for a given node
     */
    @Override
    public int inFlightRequestCount(String node) {
        return this.inFlightRequests.inFlightRequestCount(node);
    }

    /**
     * Generate a request header for the given API key
     *
     * @param key The api key
     * @return A request header with the appropriate client id and correlation id
     */
    @Override
    public RequestHeader nextRequestHeader(ApiKeys key) {
        return new RequestHeader(key.id, clientId, correlation++);
    }

    /**
     * Generate a request header for the given API key and version
     *
     * @param key The api key
     * @param version The api version
     * @return A request header with the appropriate client id and correlation id
     */
    @Override
    public RequestHeader nextRequestHeader(ApiKeys key, short version) {
        return new RequestHeader(key.id, version, clientId, correlation++);
    }

    /**
     * Interrupt the client if it is blocked waiting on I/O.
     */
    @Override
    public void wakeup() {
        this.selector.wakeup();
    }

    /**
     * Close the network client
     */
    @Override
    public void close() {
        this.selector.close();
    }

    /**
     * Choose the node with the fewest outstanding requests which is at least eligible for connection. This method will
     * prefer a node with an existing connection, but will potentially choose a node for which we don't yet have a
     * connection if all existing connections are in use. This method will never choose a node for which there is no
     * existing connection and from which we have disconnected within the reconnect backoff period.
     *
     * @return The node with the fewest in-flight requests.
     */
    @Override
    public Node leastLoadedNode(long now) {
        List<Node> nodes = this.metadataUpdater.fetchNodes();
        int inflight = Integer.MAX_VALUE;
        Node found = null;
        for (int i = 0; i < nodes.size(); i++) {
            int idx = Utils.abs((this.nodeIndexOffset + i) % nodes.size());
            Node node = nodes.get(idx);
            int currInflight = this.inFlightRequests.inFlightRequestCount(node.idString());
            if (currInflight == 0 && this.connectionStates.isConnected(node.idString())) {
                // if we find an established connection with no in-flight requests we can stop right away
                return node;
            } else if (!this.connectionStates.isBlackedOut(node.idString(), now) && currInflight < inflight) {
                // otherwise if this is the best we have found so far, record that
                inflight = currInflight;
                found = node;
            }
        }

        // if we found no node in the current list, try one from the nodes seen before
        if (found == null && nodesEverSeen.size() > 0) {
            int offset = randOffset.nextInt(nodesEverSeen.size());
            for (int i = 0; i < nodesEverSeen.size(); i++) {
                int idx = Utils.abs((offset + i) % nodesEverSeen.size());
                Node node = nodesEverSeenById.get(nodesEverSeen.get(idx));
                log.debug("No node found. Trying previously-seen node with ID {}", node.id());
                if (!this.connectionStates.isBlackedOut(node.idString(), now)) {
                    found = node;
                }
            }
        }

        return found;
    }

    /**
     * Post process disconnection of a node
     *
     * @param responses The list of responses to update
     * @param nodeId Id of the node to be disconnected
     * @param now The current time
     */
    private void processDisconnection(List<ClientResponse> responses, String nodeId, long now) {
        connectionStates.disconnected(nodeId, now);
        for (ClientRequest request : this.inFlightRequests.clearAll(nodeId)) {
            log.trace("Cancelled request {} due to node {} being disconnected", request, nodeId);
            if (!metadataUpdater.maybeHandleDisconnection(request))
                responses.add(new ClientResponse(request, now, true, null));
        }
    }

    /**
     * Iterate over all the inflight requests and expire any requests that have exceeded the configured the requestTimeout.
     * The connection to the node associated with the request will be terminated and will be treated as a disconnection.
     *
     * @param responses The list of responses to update
     * @param now The current time
     */
    private void handleTimedOutRequests(List<ClientResponse> responses, long now) {
        List<String> nodeIds = this.inFlightRequests.getNodesWithTimedOutRequests(now, this.requestTimeoutMs);
        for (String nodeId : nodeIds) {
            // close connection to the node
            this.selector.close(nodeId);
            log.debug("Disconnecting from node {} due to request timeout.", nodeId);
            processDisconnection(responses, nodeId, now);
        }

        // we disconnected, so we should probably refresh our metadata
        if (nodeIds.size() > 0)
            metadataUpdater.requestUpdate();
    }

    /**
     * Handle any completed request send. In particular if no response is expected consider the request complete.
     *
     * @param responses The list of responses to update
     * @param now The current time
     */
    private void handleCompletedSends(List<ClientResponse> responses, long now) {
        // if no response is expected then when the send is completed, return it
        for (Send send : this.selector.completedSends()) {
            ClientRequest request = this.inFlightRequests.lastSent(send.destination());
            if (!request.expectResponse()) {
                this.inFlightRequests.completeLastSent(send.destination());
                responses.add(new ClientResponse(request, now, false, null));
            }
        }
    }

    /**
     * Handle any completed receives and update the response list with the responses received.
     *
     * @param responses The list of responses to update
     * @param now The current time
     */
    private void handleCompletedReceives(List<ClientResponse> responses, long now) {
        for (NetworkReceive receive : this.selector.completedReceives()) {
            String source = receive.source();
            ClientRequest req = inFlightRequests.completeNext(source);
            ResponseHeader header = ResponseHeader.parse(receive.payload());
            // Always expect the response version id to be the same as the request version id
            short apiKey = req.request().header().apiKey();
            short apiVer = req.request().header().apiVersion();
            Struct body = (Struct) ProtoUtils.responseSchema(apiKey, apiVer).read(receive.payload());
            correlate(req.request().header(), header);
            if (!metadataUpdater.maybeHandleCompletedReceive(req, now, body))
                responses.add(new ClientResponse(req, now, false, body));
        }
    }

    /**
     * Handle any disconnected connections
     *
     * @param responses The list of responses that completed with the disconnection
     * @param now The current time
     */
    private void handleDisconnections(List<ClientResponse> responses, long now) {
        for (String node : this.selector.disconnected()) {
            log.debug("Node {} disconnected.", node);
            processDisconnection(responses, node, now);
        }
        // we got a disconnect so we should probably refresh our metadata and see if that broker is dead
        if (this.selector.disconnected().size() > 0)
            metadataUpdater.requestUpdate();
    }

    /**
     * Record any newly completed connections
     */
    private void handleConnections() {
        for (String node : this.selector.connected()) {
            log.debug("Completed connection to node {}", node);
            this.connectionStates.connected(node);
        }
    }

    /**
     * Validate that the response corresponds to the request we expect or else explode
     */
    private void correlate(RequestHeader requestHeader, ResponseHeader responseHeader) {
        if (requestHeader.correlationId() != responseHeader.correlationId())
            throw new IllegalStateException("Correlation id for response (" + responseHeader.correlationId()
                    + ") does not match request (" + requestHeader.correlationId() + ")");
    }

    /**
     * Initiate a connection to the given node
     */
    private void initiateConnect(Node node, long now) {
        String nodeConnectionId = node.idString();
        try {
            log.debug("Initiating connection to node {} at {}:{}.", node.id(), node.host(), node.port());
            this.connectionStates.connecting(nodeConnectionId, now);
            selector.connect(nodeConnectionId,
                             new InetSocketAddress(node.host(), node.port()),
                             this.socketSendBuffer,
                             this.socketReceiveBuffer);
        } catch (IOException e) {
            /* attempt failed, we'll try again after the backoff */
            connectionStates.disconnected(nodeConnectionId, now);
            /* maybe the problem is our metadata, update it */
            metadataUpdater.requestUpdate();
            log.debug("Error connecting to node {} at {}:{}:", node.id(), node.host(), node.port(), e);
        }
    }

    class DefaultMetadataUpdater implements MetadataUpdater {

        /* the current cluster metadata */
        private final Metadata metadata;

        /* true iff there is a metadata request that has been sent and for which we have not yet received a response */
        private boolean metadataFetchInProgress;

        /* the last timestamp when no broker node is available to connect */
        private long lastNoNodeAvailableMs;

        DefaultMetadataUpdater(Metadata metadata) {
            this.metadata = metadata;
            this.metadataFetchInProgress = false;
            this.lastNoNodeAvailableMs = 0;
        }

        @Override
        public List<Node> fetchNodes() {
            return metadata.fetch().nodes();
        }

        @Override
        public boolean isUpdateDue(long now) {
            return !this.metadataFetchInProgress && this.metadata.timeToNextUpdate(now) == 0;
        }

        @Override
        public long maybeUpdate(long now) {
            // should we update our metadata?
            long timeToNextMetadataUpdate = metadata.timeToNextUpdate(now);
            long timeToNextReconnectAttempt = Math.max(this.lastNoNodeAvailableMs + metadata.refreshBackoff() - now, 0);
            long waitForMetadataFetch = this.metadataFetchInProgress ? Integer.MAX_VALUE : 0;
            // if there is no node available to connect, back off refreshing metadata
            long metadataTimeout = Math.max(Math.max(timeToNextMetadataUpdate, timeToNextReconnectAttempt),
                    waitForMetadataFetch);

            if (metadataTimeout == 0) {
                // Beware that the behavior of this method and the computation of timeouts for poll() are
                // highly dependent on the behavior of leastLoadedNode.
                Node node = leastLoadedNode(now);
                maybeUpdate(now, node);
            }

            return metadataTimeout;
        }

        @Override
        public boolean maybeHandleDisconnection(ClientRequest request) {
            ApiKeys requestKey = ApiKeys.forId(request.request().header().apiKey());

            if (requestKey == ApiKeys.METADATA) {
                metadataFetchInProgress = false;
                return true;
            }

            return false;
        }

        @Override
        public boolean maybeHandleCompletedReceive(ClientRequest req, long now, Struct body) {
            short apiKey = req.request().header().apiKey();
            if (apiKey == ApiKeys.METADATA.id && req.isInitiatedByNetworkClient()) {
                handleResponse(req.request().header(), body, now);
                return true;
            }
            return false;
        }

        @Override
        public void requestUpdate() {
            this.metadata.requestUpdate();
        }

        /*
         * Keep track of any nodes we've ever seen. Add current
         * alive nodes to this tracking list.
         * @param nodes Current alive nodes
         */
        private void updateNodesEverSeen(List<Node> nodes) {
            for (Node n : nodes) {
                Node existing = nodesEverSeenById.get(n.id());
                if (existing == null) {
                    nodesEverSeenById.put(n.id(), n);
                    log.debug("Adding node {} to nodes ever seen", n.id());
                    nodesEverSeen.add(n.id());
                } else {
                    // check if the nodes are really equal. There could be a case
                    // where node.id() is the same but node has moved to different host
                    if (!existing.equals(n)) {
                        nodesEverSeenById.put(n.id(), n);
                    }
                }
            }
        }

        private void handleResponse(RequestHeader header, Struct body, long now) {
            this.metadataFetchInProgress = false;
            MetadataResponse response = new MetadataResponse(body);
            Cluster cluster = response.cluster();
            // check if any topics metadata failed to get updated
            if (response.errors().size() > 0) {
                log.warn("Error while fetching metadata with correlation id {} : {}", header.correlationId(), response.errors());
            }
            // don't update the cluster if there are no valid nodes...the topic we want may still be in the process of being
            // created which means we will get errors and no nodes until it exists
            if (cluster.nodes().size() > 0) {
                this.metadata.update(cluster, now);
                this.updateNodesEverSeen(cluster.nodes());
            } else {
                log.trace("Ignoring empty metadata response with correlation id {}.", header.correlationId());
                this.metadata.failedUpdate(now);
            }
        }

        /**
         * Create a metadata request for the given topics
         */
        private ClientRequest request(long now, String node, Set<String> topics) {
            MetadataRequest metadata = new MetadataRequest(new ArrayList<>(topics));
            RequestSend send = new RequestSend(node, nextRequestHeader(ApiKeys.METADATA), metadata.toStruct());
            return new ClientRequest(now, true, send, null, true);
        }

        /**
         * Add a metadata request to the list of sends if we can make one
         */
        private void maybeUpdate(long now, Node node) {
            if (node == null) {
                log.debug("Give up sending metadata request since no node is available");
                // mark the timestamp for no node available to connect
                this.lastNoNodeAvailableMs = now;
                return;
            }
            String nodeConnectionId = node.idString();

            if (canSendRequest(nodeConnectionId)) {
                Set<String> topics = metadata.needMetadataForAllTopics() ? new HashSet<String>() : metadata.topics();
                this.metadataFetchInProgress = true;
                ClientRequest metadataRequest = request(now, nodeConnectionId, topics);
                log.debug("Sending metadata request {} to node {}", metadataRequest, node.id());
                doSend(metadataRequest, now);
            } else if (connectionStates.canConnect(nodeConnectionId, now)) {
                // we don't have a connection to this node right now, make one
                log.debug("Initialize connection to node {} for sending metadata request", node.id());
                initiateConnect(node, now);
                // If initiateConnect failed immediately, this node will be put into blackout and we
                // should allow immediately retrying in case there is another candidate node. If it
                // is still connecting, the worst case is that we end up setting a longer timeout
                // on the next round and then wait for the response.
            } else { // connected, but can't send more OR connecting
                // In either case, we just need to wait for a network event to let us know the selected
                // connection might be usable again.
                this.lastNoNodeAvailableMs = now;
            }
        }

    }

}


text:
package net.sourcewalker.olv.messages;

public class DecodeException extends Exception {

    private static final long serialVersionUID = 1102616192132639136L;

    public DecodeException() {
        super();
    }

    public DecodeException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }

    public DecodeException(String detailMessage) {
        super(detailMessage);
    }

    public DecodeException(Throwable throwable) {
        super(throwable);
    }

}


text:
import WebMap = require("esri/WebMap");
import FeatureLayer = require("esri/layers/FeatureLayer");
import MapView = require("esri/views/MapView");
import Legend = require("esri/widgets/Legend");
import LayerList = require("esri/widgets/LayerList");
import { SimpleRenderer } from "esri/renderers";
import { SimpleMarkerSymbol } from "esri/symbols";

const map = new WebMap({
  basemap: "topo-vector"
});

const view = new MapView({
  container: "viewDiv",
  map: map,
  zoom: 3,
  center: [-100, 40]
});

const layer = new FeatureLayer({
  url:
    "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Landscape_Trees/FeatureServer/0",
  renderer: new SimpleRenderer({
    symbol: new SimpleMarkerSymbol({
      style: "circle",
      size: 6,
      color: "forestgreen",
      outline: {
        color: "white",
        width: 1
      }
    }),
    visualVariables: [
      {
        // Size the tree symbol based on the Crown_Base attribute
        // It represents the diameter of the crown of the tree
        // https://developers.arcgis.com/javascript/latest/api-reference/esri-renderers-Renderer.html#RealWorldSize
        type: "size",
        field: "Crown_Base",
        valueUnit: "feet",
        valueRepresentation: "radius"
      },
      {
        // Color the tree symbol continously based on its carbon storage
        type: "color",
        field: "C_Storage",
        // values from statistics https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Landscape_Trees/FeatureServer/0/query?outStatistics=%5B%7B+onStatisticField%3A+%22C_Storage%22%2C+statisticType%3A+%22min%22+%7D%2C+%7B+onStatisticField%3A+%22C_Storage%22%2C+statisticType%3A+%22max%22+%7D%2C+%7B+onStatisticField%3A+%22C_Storage%22%2C+statisticType%3A+%22stddev%22+%7D%5D
        stops: [
          {
            value: 0,
            color: "lightgreen"
          },
          {
            value: 13228,
            color: "darkgreen"
          }
        ],
        legendOptions: {
          title: "Carbon Storage"
        }
      }
    ]
  })
});

map.add(layer);

layer.load().then(() => {
  view.extent = layer.fullExtent;
});

view.ui.add(
  new Legend({
    view
  }),
  "bottom-left"
);

view.ui.add(
  new LayerList({
    view
  }),
  "top-right"
);


text:
/*! Content script */
$(function() {
  function versionsActualAtDate(date, versions) {
    return _.chain(versions)
      .map(function(version) {
        version.fromDate = (version.fromDate) ? new Date(version.fromDate) : new Date('1970/01/01');
        version.fromDate.setHours(0, 0, 0, 0);

        version.toDate = (version.toDate) ? new Date(version.toDate) : new Date();
        version.toDate.setHours(23, 59, 59, 999);

        return version;
      })
      .sortBy(function(version) { return version.fromDate })
      .filter(function(version) { return (date >= version.fromDate && date <= version.toDate) })
      .value()
  }

  var questionPage = $('body.question-page')
  if (!questionPage) { return }

  var tags = _.pluck(questionPage.find('.question [rel=tag]'), 'text'),
      platform = _.max(versionHint.platformData, function(platform) { return _.intersection(platform.tags, tags).length })
  if (!platform) { return }

  var questionDate = new Date( questionPage.find('.question .post-signature.owner .relativetime').attr('title') ),
      versions = versionsActualAtDate(questionDate, platform.versions)
  if (versions.length == 0) { return }

  var versionsString = _.reduce(versions, function(memo, version) { return memo + ' ' + version.name + '' }, ''),
      postVersionsString = (versions.length > 1) ? 'where the most recent versions.' : 'was the most recent version.'
  questionPage.find('.question .post-text').prepend('
At time of writing' + versionsString + ' ' + postVersionsString + '
')
});


text:
require 'mocha/api'

RSpec.configure do |config|
  config.mock_framework = :mocha
end


text:
/**
 * DO NOT MODIFY, GENERATED BY TOOLS
 */
package com.titanium.zhuanyelvli.controller.base;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.titanium.zhuanyelvli.models.TechDeptManagerCheck;
import com.titanium.zhuanyelvli.service.TechDeptManagerCheckService;
import com.titanium.zhuanyelvli.mapper.TechDeptManagerCheckSearchTerms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ResponseBody;

import com.titanium.component.date.CustomTimestampEditor;

 import com.titanium.component.query.Condition;
 import  com.titanium.component.pagenation.Page;

public class   TechDeptManagerCheckControllerBase {

	 @InitBinder
    protected void initBinder(WebDataBinder binder) throws ServletException {
                binder.registerCustomEditor(Date.class, new CustomTimestampEditor("yyyy-MM-dd HH:mm"));
    }

	@Autowired
	protected TechDeptManagerCheckService techDeptManagerCheckService;

	protected Map<String, Object> successMap(){
		Map<String, Object> json = new  HashMap();
		json.put("result", "success");
		return json;
	}

	@RequestMapping(value="/admin/zhuanyelvli/createTechDeptManagerCheck.do")
	public @ResponseBody Map<String, Object> createTechDeptManagerCheck(@ModelAttribute("techDeptManagerCheck")  TechDeptManagerCheck techDeptManagerCheck) {
		techDeptManagerCheckService.createTechDeptManagerCheck(techDeptManagerCheck);
		return successMap();
	}

	@RequestMapping(value="/admin/zhuanyelvli/updateTechDeptManagerCheck.do")
	public @ResponseBody Map<String, Object> updateTechDeptManagerCheck(@ModelAttribute("techDeptManagerCheck")  TechDeptManagerCheck techDeptManagerCheck)  {
		techDeptManagerCheckService.updateTechDeptManagerCheck(techDeptManagerCheck);
		return successMap();
	}

	@RequestMapping(value="/admin/zhuanyelvli/deleteTechDeptManagerCheck.do")
	public @ResponseBody Map<String, Object> deleteTechDeptManagerCheck(@RequestParam("id") int id) {
		techDeptManagerCheckService.deleteTechDeptManagerCheck(id);
		return successMap();
	}

	@RequestMapping(value="/admin/zhuanyelvli/getTechDeptManagerCheck.do")
	public String getTechDeptManagerCheck(@RequestParam("id") int id, ModelMap model){
		 setReferBean(model);
		 model.addAttribute("techDeptManagerCheck", techDeptManagerCheckService.getTechDeptManagerCheck(id));
		  return "admin/zhuanyelvli/editTechDeptManagerCheck";
	}

	@RequestMapping(value="/admin/zhuanyelvli/toCreateTechDeptManagerCheck.do")
	public String toCreateTechDeptManagerCheck( ModelMap model){
		 setReferBean(model);
		 model.addAttribute("techDeptManagerCheck", new TechDeptManagerCheck());
		  return "admin/zhuanyelvli/addTechDeptManagerCheck";
	}

	@RequestMapping(value="/admin/zhuanyelvli/listTechDeptManagerCheck.do")
	public String listTechDeptManagerCheck(@ModelAttribute("techDeptManagerCheckSearchTerms") TechDeptManagerCheckSearchTerms techDeptManagerCheckSearchTerms, ModelMap model){
 			setListTechDeptManagerCheck(techDeptManagerCheckSearchTerms,  model);
		     return "admin/zhuanyelvli/listTechDeptManagerCheck";
	}

	public List<TechDeptManagerCheck> setListTechDeptManagerCheck(@ModelAttribute("techDeptManagerCheckSearchTerms") TechDeptManagerCheckSearchTerms techDeptManagerCheckSearchTerms, ModelMap model){
 			if(techDeptManagerCheckSearchTerms.getPageNum()==-1){
 				techDeptManagerCheckSearchTerms.setPageNum(1);
 			}
 			if(techDeptManagerCheckSearchTerms.getNumPerPage()==-1){
 				techDeptManagerCheckSearchTerms.setNumPerPage(10);
 			}
 			List<TechDeptManagerCheck> techDeptManagerCheckList = techDeptManagerCheckService.listTechDeptManagerCheck(techDeptManagerCheckSearchTerms);
 			 model.addAttribute("techDeptManagerCheckSearchTerms",techDeptManagerCheckSearchTerms );
 			 long totalCount = techDeptManagerCheckService.countTechDeptManagerCheck(techDeptManagerCheckSearchTerms);
 			 techDeptManagerCheckSearchTerms.getPage().setTotalCount(totalCount);
 			 model.addAttribute("techDeptManagerCheckCount", totalCount);
 			  model.addAttribute("page", techDeptManagerCheckSearchTerms.getPage());
		    model.addAttribute("techDeptManagerCheckList", techDeptManagerCheckList);
		    setReferBean(model);
		    setBigDataReferBean(model, techDeptManagerCheckService.listTechDeptManagerCheck(techDeptManagerCheckSearchTerms));
		   return  techDeptManagerCheckList;
	}

	protected void setReferBean(ModelMap model){

	}

	protected void setBigDataReferBean(ModelMap model,List<TechDeptManagerCheck> list){
		if(list.size()>0){
		}

	}

	protected void setBigDataReferBeanByMap(ModelMap model,List<Map> list){
		if(list.size()>0){
		}

	}

public class KVMap{

	public KVMap(String key, String value){
		this.key = key;
		this.value = value;
	}
	String key;
	String value;
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

}

}


text:
package com.navercorp.pinpoint.profiler.instrument.classloading;

import java.io.InputStream;

import com.navercorp.pinpoint.exception.PinpointException;
import com.navercorp.pinpoint.profiler.instrument.BootstrapPackage;

/**
 * @author Woonduk Kang(emeroad)
 */
public class DebugTransformerClassInjector implements ClassInjector {

    private final BootstrapPackage bootstrapPackage = new BootstrapPackage();

    public DebugTransformerClassInjector() {
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> Class<? extends T> injectClass(ClassLoader classLoader, String className) {

        ClassLoader targetClassLoader = getClassLoader(classLoader);

        targetClassLoader = filterBootstrapPackage(targetClassLoader, className);

        try {
            return (Class<? extends T>) targetClassLoader.loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new PinpointException("ClassNo class " + className + " with classLoader " + classLoader, e);
        }
    }

    @Override
    public InputStream getResourceAsStream(ClassLoader classLoader, String classPath) {
        ClassLoader targetClassLoader = getClassLoader(classLoader);

        targetClassLoader = filterBootstrapPackage(targetClassLoader, classPath);

        return targetClassLoader.getResourceAsStream(classPath);
    }

    private static ClassLoader getClassLoader(ClassLoader classLoader) {
        if (classLoader == null) {
            return ClassLoader.getSystemClassLoader();
        }
        return classLoader;
    }

    private ClassLoader filterBootstrapPackage(ClassLoader classLoader, String classPath) {
        if (bootstrapPackage.isBootstrapPackage(classPath)) {
            return ClassLoader.getSystemClassLoader();
        }
        return classLoader;
    }
}


text:
<?php

namespace Cncal\Getui\Sdk\IGetui\Req;

use Cncal\Getui\Sdk\Protobuf\PBMessage;

class EndBatchTask extends PBMessage
{
    var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED;

    public function __construct($reader = NULL)
    {
        parent::__construct($reader);
        $this->fields["1"] = "PBString";
        $this->values["1"] = "";
        $this->fields["2"] = "PBString";
        $this->values["2"] = "";
    }

    function taskId()
    {
        return $this->_get_value("1");
    }

    function set_taskId($value)
    {
        return $this->_set_value("1", $value);
    }

    function seqId()
    {
        return $this->_get_value("2");
    }

    function set_seqId($value)
    {
        return $this->_set_value("2", $value);
    }
}


text:
'use strict';

angular.module('profile', [
    'ui.router',
    'gameService',
    'ngMaterial'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
    $stateProvider
    .state('profile', {
        url: '/profile',
        abstract: true,
        template: '<ui-view />'
    })
    .state('profile.games', {
        url: '/games',
        templateUrl: 'app/profile/usergames/usergames.html',
        controller: 'UserGamesController',
        onEnter: ['userService', '$state', function(userService, $state) {
            if (!userService.isAuthenticated())
                $state.go('main.home');
        }],
        resolve: {
            games: ['gameService', function(gameService) {
                return gameService.getAllActiveGamesForCurrentUser();
            }],
            gmGames: ['gameService', function(gameService) {
                return gameService.getAllActiveGamesOwnedByCurrentUser();
            }]
        }
    })
    .state('profile.verify', {
        url: '/verify/{token}',
        controller: 'VerifyController',
        templateUrl: 'app/profile/verify/verify.html'
    })
    .state('profile.view', {
        url: '/:id',
        templateUrl: 'app/profile/view/view.html',
        controller: 'ProfileViewController',
        onEnter: ['userService', '$state', function(userService, $state) {
            if (!userService.isAuthenticated())
                $state.go('main.home');
        }]
    })
    .state('profile.edit', {
        url: '/edit',
        templateUrl: 'app/profile/edit/edit.html',
        controller: 'ProfileEditController',
        onEnter: ['userService', '$state', function(userService, $state) {
            if (!userService.isAuthenticated())
                $state.go('main.home');
        }]
    });
}]);


text:
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
from scrapy.http import Request
import json
from .. import items
from . import urls
from . import xpaths
from .utils import *

class ActBillSpider(BaseSpider):

    name = 'actBillSpider'

    def start_requests(self):
        yield Request(urls.bill_index, method='GET')

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        max_page = extract_max_page(hxs,'goToPage')
        print("extracted page is %s" % max_page)
        for i in range(1, int(max_page)+1):
            yield Request(urls.bill_index_per_page % i, callback=self.parse_bill)

    def parse_bill(self, response):
        hxs = HtmlXPathSelector(response)
        ids = extract_ids(hxs, 'mbill')
        for id in ids:
            yield Request(urls.bill_vote % int(id), callback=self.parse_bill_detail)

    def parse_bill_detail(self, response):
        id = extract_url(response.url, 'mbill')
        hxs = HtmlXPathSelector(response)
        link_id = extract_word_id(hxs,'bill_id')
        yield items.ACT_BILL_ITEM(id=id,link_id=link_id)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary">
    <TextView android:id="@+id/place"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_gravity="center"
        android:layout_margin="24dp"
        android:textColor="@android:color/white"/>
</LinearLayout>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.hadoop.metrics2.MetricsTag (Hadoop 1.0.4-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2013-04-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.hadoop.metrics2.MetricsTag

Packages that use MetricsTag

org.apache.hadoop.metrics2
Metrics 2.0

org.apache.hadoop.metrics2.impl

org.apache.hadoop.metrics2.lib

org.apache.hadoop.metrics2.util

Uses of MetricsTag in org.apache.hadoop.metrics2

Methods in org.apache.hadoop.metrics2 that return types with arguments of type MetricsTag

 Iterable<MetricsTag>
MetricsRecord.tags()

          Get the tags of the record

Methods in org.apache.hadoop.metrics2 with parameters of type MetricsTag

abstract  boolean
MetricsFilter.accepts(MetricsTag tag)

          Whether to accept the tag

abstract  MetricsRecordBuilder
MetricsRecordBuilder.add(MetricsTag tag)

          Add an immutable metrics tag object

Method parameters in org.apache.hadoop.metrics2 with type arguments of type MetricsTag

abstract  boolean
MetricsFilter.accepts(Iterable<MetricsTag> tags)

          Whether to accept the tags

Uses of MetricsTag in org.apache.hadoop.metrics2.impl

Methods in org.apache.hadoop.metrics2.impl that return types with arguments of type MetricsTag

 Iterable<MetricsTag>
MetricsRecordImpl.tags()

Constructor parameters in org.apache.hadoop.metrics2.impl with type arguments of type MetricsTag

MetricsRecordImpl(String name,
                  long timestamp,
                  Iterable<MetricsTag> tags,
                  Iterable<Metric> metrics)

          Construct a metrics record

Uses of MetricsTag in org.apache.hadoop.metrics2.lib

Methods in org.apache.hadoop.metrics2.lib that return types with arguments of type MetricsTag

 Set<Map.Entry<String,MetricsTag>>
MetricsRegistry.tags()

          Get the tags

Uses of MetricsTag in org.apache.hadoop.metrics2.util

Method parameters in org.apache.hadoop.metrics2.util with type arguments of type MetricsTag

 MetricsCache.Record
MetricsCache.get(String name,
    Collection<MetricsTag> tags)

          Get the cached record

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2009 The Apache Software Foundation


text:
use std::{error, fmt, result};

use persistent_log::Log;
use LogIndex;
use ServerId;
use Term;

/// This is a `Log` implementation that stores entries in a simple in-memory vector. Other data
/// is stored in a struct. It is chiefly intended for testing.
///
/// # Panic
///
/// No bounds checking is performed and attempted access to non-existing log
/// indexes will panic.
#[derive(Clone, Debug)]
pub struct MemLog {
    current_term: Term,
    voted_for: Option<ServerId>,
    entries: Vec<(Term, Vec<u8>)>,
}

/// Non-instantiable error type for MemLog
pub enum Error { }

impl fmt::Display for Error {
    fn fmt(&self, _fmt: &mut fmt::Formatter) -> fmt::Result {
        unreachable!()
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, _fmt: &mut fmt::Formatter) -> fmt::Result {
        unreachable!()
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        unreachable!()
    }
}

impl MemLog {
    pub fn new() -> MemLog {
        MemLog {
            current_term: Term(0),
            voted_for: None,
            entries: Vec::new(),
        }
    }
}

impl Log for MemLog {
    type Error = Error;

    fn current_term(&self) -> result::Result<Term, Error> {
        Ok(self.current_term)
    }

    fn set_current_term(&mut self, term: Term) -> result::Result<(), Error> {
        self.voted_for = None;
        Ok(self.current_term = term)
    }

    fn inc_current_term(&mut self) -> result::Result<Term, Error> {
        self.voted_for = None;
        self.current_term = self.current_term + 1;
        self.current_term()
    }

    fn voted_for(&self) -> result::Result<Option<ServerId>, Error> {
        Ok(self.voted_for)
    }

    fn set_voted_for(&mut self, address: ServerId) -> result::Result<(), Error> {
        Ok(self.voted_for = Some(address))
    }

    fn latest_log_index(&self) -> result::Result<LogIndex, Error> {
        Ok(LogIndex(self.entries.len() as u64))
    }

    fn latest_log_term(&self) -> result::Result<Term, Error> {
        let len = self.entries.len();
        if len == 0 {
            Ok(Term::from(0))
        } else {
            Ok(self.entries[len - 1].0)
        }
    }

    fn entry(&self, index: LogIndex) -> result::Result<(Term, &[u8]), Error> {
        let (term, ref bytes) = self.entries[(index - 1).as_u64() as usize];
        Ok((term, bytes))
    }

    fn append_entries(&mut self,
                      from: LogIndex,
                      entries: &[(Term, &[u8])])
                      -> result::Result<(), Error> {
        assert!(self.latest_log_index().unwrap() + 1 >= from);
        self.entries.truncate((from - 1).as_u64() as usize);
        Ok(self.entries.extend(entries.iter().map(|&(term, command)| (term, command.to_vec()))))
    }
}

#[cfg(test)]
mod test {

    use super::*;
    use LogIndex;
    use ServerId;
    use Term;
    use persistent_log::Log;

    #[test]
    fn test_current_term() {
        let mut store = MemLog::new();
        assert_eq!(Term(0), store.current_term().unwrap());
        store.set_voted_for(ServerId::from(0)).unwrap();
        store.set_current_term(Term(42)).unwrap();
        assert_eq!(None, store.voted_for().unwrap());
        assert_eq!(Term(42), store.current_term().unwrap());
        store.inc_current_term().unwrap();
        assert_eq!(Term(43), store.current_term().unwrap());
    }

    #[test]
    fn test_voted_for() {
        let mut store = MemLog::new();
        assert_eq!(None, store.voted_for().unwrap());
        let id = ServerId::from(0);
        store.set_voted_for(id).unwrap();
        assert_eq!(Some(id), store.voted_for().unwrap());
    }

    #[test]
    fn test_append_entries() {
        let mut store = MemLog::new();
        assert_eq!(LogIndex::from(0), store.latest_log_index().unwrap());
        assert_eq!(Term::from(0), store.latest_log_term().unwrap());

        // [0.1, 0.2, 0.3, 1.4]
        store.append_entries(LogIndex(1),
                             &[(Term::from(0), &[1]),
                               (Term::from(0), &[2]),
                               (Term::from(0), &[3]),
                               (Term::from(1), &[4])])
             .unwrap();
        assert_eq!(LogIndex::from(4), store.latest_log_index().unwrap());
        assert_eq!(Term::from(1), store.latest_log_term().unwrap());
        assert_eq!((Term::from(0), &*vec![1u8]),
                   store.entry(LogIndex::from(1)).unwrap());
        assert_eq!((Term::from(0), &*vec![2u8]),
                   store.entry(LogIndex::from(2)).unwrap());
        assert_eq!((Term::from(0), &*vec![3u8]),
                   store.entry(LogIndex::from(3)).unwrap());
        assert_eq!((Term::from(1), &*vec![4u8]),
                   store.entry(LogIndex::from(4)).unwrap());

        // [0.1, 0.2, 0.3]
        store.append_entries(LogIndex::from(4), &[]).unwrap();
        assert_eq!(LogIndex(3), store.latest_log_index().unwrap());
        assert_eq!(Term::from(0), store.latest_log_term().unwrap());
        assert_eq!((Term::from(0), &*vec![1u8]),
                   store.entry(LogIndex::from(1)).unwrap());
        assert_eq!((Term::from(0), &*vec![2u8]),
                   store.entry(LogIndex::from(2)).unwrap());
        assert_eq!((Term::from(0), &*vec![3u8]),
                   store.entry(LogIndex::from(3)).unwrap());

        // [0.1, 0.2, 2.3, 3.4]
        store.append_entries(LogIndex::from(3), &[(Term(2), &[3]), (Term(3), &[4])]).unwrap();
        assert_eq!(LogIndex(4), store.latest_log_index().unwrap());
        assert_eq!(Term::from(3), store.latest_log_term().unwrap());
        assert_eq!((Term::from(0), &*vec![1u8]),
                   store.entry(LogIndex::from(1)).unwrap());
        assert_eq!((Term::from(0), &*vec![2u8]),
                   store.entry(LogIndex::from(2)).unwrap());
        assert_eq!((Term::from(2), &*vec![3u8]),
                   store.entry(LogIndex::from(3)).unwrap());
        assert_eq!((Term::from(3), &*vec![4u8]),
                   store.entry(LogIndex::from(4)).unwrap());
    }
}

impl Default for MemLog {
    fn default() -> Self {
        MemLog::new()
    }
}


text:
![the-princess-dao](the-princess-dao.jpg "the-princess-dao")

ThePrincessDAO是持有the-princess-dao著作權的Decentralized autonomous organization(DAO),用來測試與探索DAO在分散式智財管理的實務應用。

ThePrincessDAO Account = 0x565ff487b6bde426c0d2ee405e90231a3d09bbab

https://kovan.etherscan.io/address/0x565ff487b6bde426c0d2ee405e90231a3d09bbab

the-princess-dao利用fast-style-transfer專案學習Leonid Afremov的Rain Princess畫風加上英國政府釋出1943年的public domain授權照片合成,本著作以創用CC 姓名標示 4.0 國際 授權條款釋出。詳細授權條款,請至http://creativecommons.org/licenses/by/4.0/ 。

#### Fast Style Transfer in floydhub

```
$ floyd run --gpu --env keras:py2 --data Js534T344XYBPMvWqhxJNj "python evaluate.py --allow-different-dimensions --checkpoint /input/rain_princess.ckpt --in-path ./images/ --out-path /output/"
```

#### References
* artist Leonid Afremov making a recreation of Rain Princess - YouTube https://www.youtube.com/watch?v=iANCevmDzTI
* https://commons.wikimedia.org/wiki/File%3AA_little_girl_holding_an_umbrella_watches_a_despatch_rider_attempt_to_clear_the_carbuerettor_of_his_motorcycle_in_torrential_rain%2C_4_October_1943._NA7526.jpg
* Decentralized autonomous organization - Wikipedia  https://en.wikipedia.org/wiki/Decentralized_autonomous_organization
* AragonOne/aragon https://github.com/AragonOne/aragon/releases
* Style Transfer - FloydHub  http://docs.floydhub.com/guides/style_transfer/
* The DAO (organization) - Wikipedia  https://en.wikipedia.org/wiki/The_DAO_(organization)
* 被稱為心理治療效用的藝術,Leonid Afremov撼動人心的油畫世界! | 時尚華爾滋  http://www.fashionwaltz.com/?p=3693
* 「你的名字」電影濾鏡火爆的背後 - INSIDE 硬塞的網路趨勢觀察  https://www.inside.com.tw/2016/12/04/your-name-filter

## DarkOrangeCo

DarkOrangeCo Account = 0x49655afc08a30223cb36438d085362e04404ff85

https://kovan.etherscan.io/address/0x49655afc08a30223cb36438d085362e04404ff85

### References
* darkorange at master · y12studio/dltdojo  https://github.com/y12studio/dltdojo/tree/master/docs/chains/darkorange


text:
MatrixModel.prototype.__updateSelectionGroups = function() {
	if ( this.__isDirtyState( "selectionCount" ) ) {
		var selectionCount = this.state.get( "selectionCount" );
		var hashSelectionGroups = this.get( "hashSelectionGroups" ) || {};
		var allSelectionGroups = this.get( "allSelectionGroups" ) || [];

		// Create controls
		var newSelectionGroups = [];
		for ( var selectionIndex = 0; selectionIndex < selectionCount; selectionIndex++ ) {
			if ( ! hashSelectionGroups.hasOwnProperty( selectionIndex ) ) {
				var selection = {
					"key" : selectionIndex,
					"selectionIndex" : selectionIndex,
					"dataType" : "selection"
				};
				hashSelectionGroups[ selectionIndex ] = selection;
				newSelectionGroups.push( selection );
			}
		}
		if ( newSelectionGroups.length > 0 ) {
			this.__setDirtyModelAndValue( "hashSelectionGroups", hashSelectionGroups );
			this.__setDirtyModelAndValue( "allSelectionGroups", allSelectionGroups.concat( newSelectionGroups ) );
		}
	}

	var allSelectionGroups = this.get( "allSelectionGroups" ) || [];

	if ( this.__getDirtyModel( "allSelectionGroups" ) === true || this.__isDirtyState( "selectionLabels" ) ) {
		var selectionLabels = this.state.get( "selectionLabels" );
		var selectionIndexes = this.__selectionIndexes( this.__getDirtyState( "selectionLabels" ) );
		for ( var i = 0; i < selectionIndexes.length; i++ ) {
			var selectionIndex = selectionIndexes[i];
			var selection = allSelectionGroups[ selectionIndex ];
			var text = selectionLabels[ selectionIndex ];
			if ( text !== selection.text ) {
				selection.text = text;
				this.setDirty( "allSelectionGroups", selectionIndex, "text" );
				this.__setDirtyModel( "allSelectionGroups", "text" );
			}
		}
	}
	if ( this.__getDirtyModel( "allSelectionGroups" ) === true || this.__isDirtyState( "selectionColors" ) ) {
		var selectionColors = this.state.get( "selectionColors" );
		var selectionIndexes = this.__selectionIndexes( this.__getDirtyState( "selectionColors" ) );
		for ( var i = 0; i < selectionIndexes.length; i++ ) {
			var selectionIndex = selectionIndexes[i];
			var selection = allSelectionGroups[ selectionIndex ];
			var color = selectionColors[ selectionIndex ];
			if ( color !== selection.color ) {
				selection.color = color;
				this.setDirty( "allSelectionGroups", selectionIndex, "color" );
				this.__setDirtyModel( "allSelectionGroups", "color" );
			}
		}
	}
	if ( this.__getDirtyModel( "allSelectionGroups" ) === true || this.__isDirtyState( "selectionBackgrounds" ) ) {
		var selectionBackgrounds = this.state.get( "selectionBackgrounds" );
		var selectionIndexes = this.__selectionIndexes( this.__getDirtyState( "selectionBackgrounds" ) );
		for ( var i = 0; i < selectionIndexes.length; i++ ) {
			var selectionIndex = selectionIndexes[i];
			var selection = allSelectionGroups[ selectionIndex ];
			var background = selectionBackgrounds[ selectionIndex ];
			if ( background !== selection.background ) {
				selection.background = background;
				this.setDirty( "allSelectionGroups", selectionIndex, "background" );
				this.__setDirtyModel( "allSelectionGroups", "background" );
			}
		}
	}
	if ( this.__getDirtyModel( "allSelectionGroups" ) === true || this.__isDirtyState( "columnSelections" ) ) {
		var columnSelections = this.state.get( "columnSelections" );
		var allColumnElements = this.get( "allColumnElements" );
		var selectionColumnIndexes = new Array( allSelectionGroups.length );
		for ( var selectionIndex = 0; selectionIndex < selectionColumnIndexes.length; selectionIndex++ )
			selectionColumnIndexes[ selectionIndex ] = {};
		for ( var t in columnSelections ) {
			var t = parseInt(t);
			var element = allColumnElements[ t ];
			var selectionIndex = columnSelections[ t ];
			selectionColumnIndexes[ selectionIndex ][ t ] = element;
		}
		for ( var selectionIndex = 0; selectionIndex < allSelectionGroups.length; selectionIndex++ ) {
			var selection = allSelectionGroups[ selectionIndex ];
			var a = selectionColumnIndexes[ selectionIndex ];
			var b = selection.columnIndexes;
			var aKeys = _.keys( a );
			var bKeys = ( b ? _.keys( b ) : [] );
			if ( b === undefined || _.difference( aKeys, bKeys ).length > 0 || _.difference( bKeys, aKeys ).length > 0 ) {
				selection.columnIndexes = selectionColumnIndexes[ selectionIndex ];
				this.setDirty( "allSelectionGroups", selectionIndex, "columnIndexes" );
				this.__setDirtyModel( "allSelectionGroups", "columnIndexes" );
			}
		}
	}
};


text:
#ifndef PROTON_NETADDR_H
#define PROTON_NETADDR_H

#include <proton/import_export.h>
#include <proton/types.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @file
 *
 * @copybrief pn_netaddr_t
 *
 * @addtogroup proactor
 * @{
 */

/**
 * **Unsettled API** - The network address of a proactor transport.
 */
typedef struct pn_netaddr_t pn_netaddr_t;

/**
 * Format a network address string in `buf`.
 *
 * @return the length of the string (excluding trailing '\0'), if >= size then
 * the address was truncated.
 */
PNP_EXTERN int pn_netaddr_str(const pn_netaddr_t *addr, char *buf, size_t size);

/**
 * Get the local address of a transport. Return `NULL` if not available.
 * Pointer is invalid after the transport closes (PN_TRANSPORT_CLOSED event is handled)
 */
PNP_EXTERN const pn_netaddr_t *pn_transport_local_addr(pn_transport_t *t);

/**
 * Get the local address of a transport. Return `NULL` if not available.
 * Pointer is invalid after the transport closes (PN_TRANSPORT_CLOSED event is handled)
 */
PNP_EXTERN const pn_netaddr_t *pn_transport_remote_addr(pn_transport_t *t);

/**
 * Get the listening addresses of a listener.
 * Addresses are only available after the @ref PN_LISTENER_OPEN event for the listener.
 *
 * A listener can have more than one address for several reasons:
 * - DNS host records may indicate more than one address
 * - On a multi-homed host, listening on the default host "" will listen on all local addresses.
 * - Some IPv4/IPV6 configurations may expand a single address into a v4/v6 pair.
 *
 * pn_netaddr_next() will iterate over the addresses in the list.
 *
 * @param l points to the listener
 * @return The first listening address or NULL if there are no addresses are available.
 * Use pn_netaddr_next() to iterate over the list.
 * Pointer is invalid after the listener closes (PN_LISTENER_CLOSED event is handled)
 */
PNP_EXTERN const pn_netaddr_t *pn_listener_addr(pn_listener_t *l);

/**
 * @return Pointer to the next address in a list of addresses, NULL if at the end of the list or
 * if this address is not part of a list.
 */
PNP_EXTERN const pn_netaddr_t *pn_netaddr_next(const pn_netaddr_t *na);

struct sockaddr;

/**
 * On POSIX or Windows, get the underlying `struct sockaddr`.
 * Return NULL if not available.
 */
PNP_EXTERN const struct sockaddr *pn_netaddr_sockaddr(const pn_netaddr_t *na);

/**
 * On POSIX or Windows, get the size of the underlying `struct sockaddr`.
 * Return 0 if not available.
 */
PNP_EXTERN size_t pn_netaddr_socklen(const pn_netaddr_t *na);

/**
 * Get the host and port name from na as separate strings.
 * Returns 0 if successful, non-0 on error.
 */
PNP_EXTERN int pn_netaddr_host_port(const pn_netaddr_t* na, char *host, size_t hlen, char *port, size_t plen);

/**
 * **Deprecated** - Use ::pn_transport_local_addr()
 */
PN_DEPRECATED("Use pn_transport_local_addr")
PNP_EXTERN const pn_netaddr_t *pn_netaddr_local(pn_transport_t *t);

/**
 * **Deprecated** - Use ::pn_transport_remote_addr()
 */
PN_DEPRECATED("Use pn_transport_remote_addr")
PNP_EXTERN const pn_netaddr_t *pn_netaddr_remote(pn_transport_t *t);

/**
 * **Deprecated** - Use ::pn_listener_addr()
 */
PN_DEPRECATED("Use pn_listener_addr")
PNP_EXTERN const pn_netaddr_t *pn_netaddr_listening(pn_listener_t *l);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* PROTON_NETADDR_H */