text:
"""
This module contains some script utils that are used in the chemenv package.
"""

import re

import numpy as np

from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import (
    SimplestChemenvStrategy,
)
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import (
    UNCLEAR_ENVIRONMENT_SYMBOL,
    AllCoordinationGeometries,
)
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometry_finder import (
    AbstractGeometry,
    LocalGeometryFinder,
)
from pymatgen.analysis.chemenv.utils.chemenv_errors import (
    NeighborsNotComputedChemenvError,
)
from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import rotateCoords
from pymatgen.analysis.chemenv.utils.defs_utils import chemenv_citations
from pymatgen.core.sites import PeriodicSite
from pymatgen.core.structure import Molecule
from pymatgen.ext.matproj import MPRester
from pymatgen.io.cif import CifParser

try:
    from pymatgen.vis.structure_vtk import StructureVis

    no_vis = False
except ImportError:
    StructureVis = None  # type: ignore
    no_vis = True

__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__credits__ = "Geoffroy Hautier"
__version__ = "2.0"
__maintainer__ = "David Waroquiers"
__email__ = "david.waroquiers@gmail.com"
__date__ = "Feb 20, 2016"

strategies_class_lookup = {}
strategies_class_lookup["SimplestChemenvStrategy"] = SimplestChemenvStrategy

# strategies_class_lookup['SimpleAbundanceChemenvStrategy'] = SimpleAbundanceChemenvStrategy
# strategies_class_lookup['TargettedPenaltiedAbundanceChemenvStrategy'] = TargettedPenaltiedAbundanceChemenvStrategy

def draw_cg(
    vis,
    site,
    neighbors,
    cg=None,
    perm=None,
    perfect2local_map=None,
    show_perfect=False,
    csm_info=None,
    symmetry_measure_type="csm_wcs_ctwcc",
    perfect_radius=0.1,
    show_distorted=True,
    faces_color_override=None,
):
    """
    Draw cg.

    :param vis:
    :param site:
    :param neighbors:
    :param cg:
    :param perm:
    :param perfect2local_map:
    :param show_perfect:
    :param csm_info:
    :param symmetry_measure_type:
    :param perfect_radius:
    :param show_distorted:
    :param faces_color_override:
    :return:
    """
    if show_perfect:
        if csm_info is None:
            raise ValueError("Not possible to show perfect environment without csm_info")
        csm_suffix = symmetry_measure_type[4:]
        perf_radius = (perfect_radius - 0.2) / 0.002
    if perm is not None and perfect2local_map is not None:
        raise ValueError('Only "perm" or "perfect2local_map" should be provided in draw_cg, not both')
    if show_distorted:
        vis.add_bonds(neighbors, site)
        for n in neighbors:
            vis.add_site(n)
    if len(neighbors) < 3:
        if show_distorted:
            vis.add_bonds(neighbors, site, color=[0.0, 1.0, 0.0], opacity=0.4, radius=0.175)
        if show_perfect:
            if len(neighbors) == 2:
                perfect_geometry = AbstractGeometry.from_cg(cg)
                trans = csm_info["other_symmetry_measures"][f"translation_vector_{csm_suffix}"]
                rot = csm_info["other_symmetry_measures"][f"rotation_matrix_{csm_suffix}"]
                scale = csm_info["other_symmetry_measures"][f"scaling_factor_{csm_suffix}"]
                points = perfect_geometry.points_wcs_ctwcc()
                rotated_points = rotateCoords(points, rot)
                points = [scale * pp + trans for pp in rotated_points]
                if "wcs" in csm_suffix:
                    ef_points = points[1:]
                else:
                    ef_points = points
                edges = cg.edges(ef_points, input="coords")
                vis.add_edges(edges, color=[1.0, 0.0, 0.0])
                for point in points:
                    vis.add_partial_sphere(
                        coords=point,
                        radius=perf_radius,
                        color=[0.0, 0.0, 0.0],
                        start=0,
                        end=360,
                        opacity=1,
                    )
    else:
        if show_distorted:
            if perm is not None:
                faces = cg.faces(neighbors, permutation=perm)
                edges = cg.edges(neighbors, permutation=perm)
            elif perfect2local_map is not None:
                faces = cg.faces(neighbors, perfect2local_map=perfect2local_map)
                edges = cg.edges(neighbors, perfect2local_map=perfect2local_map)
            else:
                faces = cg.faces(neighbors)
                edges = cg.edges(neighbors)
            symbol = list(site.species.keys())[0].symbol
            if faces_color_override:
                mycolor = faces_color_override
            else:
                mycolor = [float(i) / 255 for i in vis.el_color_mapping[symbol]]
            vis.add_faces(faces, mycolor, opacity=0.4)
            vis.add_edges(edges)
        if show_perfect:
            perfect_geometry = AbstractGeometry.from_cg(cg)
            trans = csm_info["other_symmetry_measures"][f"translation_vector_{csm_suffix}"]
            rot = csm_info["other_symmetry_measures"][f"rotation_matrix_{csm_suffix}"]
            scale = csm_info["other_symmetry_measures"][f"scaling_factor_{csm_suffix}"]
            points = perfect_geometry.points_wcs_ctwcc()
            rotated_points = rotateCoords(points, rot)
            points = [scale * pp + trans for pp in rotated_points]
            if "wcs" in csm_suffix:
                ef_points = points[1:]
            else:
                ef_points = points
            edges = cg.edges(ef_points, input="coords")
            vis.add_edges(edges, color=[1.0, 0.0, 0.0])
            for point in points:
                vis.add_partial_sphere(
                    coords=point,
                    radius=perf_radius,
                    color=[0.0, 0.0, 0.0],
                    start=0,
                    end=360,
                    opacity=1,
                )

def visualize(cg, zoom=None, vis=None, myfactor=1.0, view_index=True, faces_color_override=None):
    """
    Visualizing a coordination geometry
    :param cg:
    :param zoom:
    :param vis:
    :param myfactor:
    :param view_index:
    :param faces_color_override:
    :return:
    """
    if vis is None:
        vis = StructureVis(show_polyhedron=False, show_unit_cell=False)
    myspecies = ["O"] * (cg.coordination_number + 1)
    myspecies[0] = "Cu"
    coords = [np.zeros(3, np.float_) + cg.central_site]

    for pp in cg.points:
        coords.append(np.array(pp) + cg.central_site)
    coords = [cc * myfactor for cc in coords]
    structure = Molecule(species=myspecies, coords=coords)
    vis.set_structure(structure=structure, reset_camera=True)
    # neighbors_list = coords[1:]
    draw_cg(
        vis,
        site=structure[0],
        neighbors=structure[1:],
        cg=cg,
        faces_color_override=faces_color_override,
    )
    if view_index:
        for ineighbor, neighbor in enumerate(structure[1:]):
            vis.add_text(neighbor.coords, f"{ineighbor}", color=(0, 0, 0))
    if zoom is not None:
        vis.zoom(zoom)
    return vis

def welcome(chemenv_config):
    """
    Show welcome message.
    :param chemenv_config:
    :return:
    """
    print("Chemical Environment package (ChemEnv)")
    print(chemenv_citations())
    print(chemenv_config.package_options_description())

def thankyou():
    """
    Show thank you message.
    :return:
    """
    print("Thank you for using the ChemEnv package")
    print(chemenv_citations())

def compute_environments(chemenv_configuration):
    """
    Compute the environments.

    :param chemenv_configuration:
    :return:
    """
    string_sources = {
        "cif": {"string": "a Cif file", "regexp": r".*\.cif$"},
        "mp": {"string": "the Materials Project database", "regexp": r"mp-[0-9]+$"},
    }
    questions = {"c": "cif"}
    questions["m"] = "mp"
    lgf = LocalGeometryFinder()
    lgf.setup_parameters()
    allcg = AllCoordinationGeometries()
    strategy_class = strategies_class_lookup[chemenv_configuration.package_options["default_strategy"]["strategy"]]
    # TODO: Add the possibility to change the parameters and save them in the chemenv_configuration
    default_strategy = strategy_class()
    default_strategy.setup_options(chemenv_configuration.package_options["default_strategy"]["strategy_options"])
    max_dist_factor = chemenv_configuration.package_options["default_max_distance_factor"]
    firsttime = True
    while True:
        if len(questions) > 1:
            found = False
            print("Enter the source from which the structure is coming or <q> to quit :")
            for key_character, qq in questions.items():
                print(f" - <{key_character}> for a structure from {string_sources[qq]['string']}")
            test = input(" ... ")
            if test == "q":
                break
            if test not in list(questions.keys()):
                for key_character, qq in questions.items():
                    if re.match(string_sources[qq]["regexp"], str(test)) is not None:
                        found = True
                        source_type = qq
                if not found:
                    print("Wrong key, try again ...")
                    continue
            else:
                source_type = questions[test]
        else:
            found = False
            source_type = list(questions.values())[0]
        if found and len(questions) > 1:
            input_source = test
        if source_type == "cif":
            if not found:
                input_source = input("Enter path to cif file : ")
            cp = CifParser(input_source)
            structure = cp.get_structures()[0]
        elif source_type == "mp":
            if not found:
                input_source = input('Enter materials project id (e.g. "mp-1902") : ')
            a = MPRester()
            structure = a.get_structure_by_material_id(input_source)
        lgf.setup_structure(structure)
        print(f"Computing environments for {structure.composition.reduced_formula} ... ")
        se = lgf.compute_structure_environments(maximum_distance_factor=max_dist_factor)
        print("Computing environments finished")
        while True:
            test = input(
                "See list of environments determined for each (unequivalent) site ? "
                '("y" or "n", "d" with details, "g" to see the grid) : '
            )
            strategy = default_strategy
            if test in ["y", "d", "g"]:
                strategy.set_structure_environments(se)
                for eqslist in se.equivalent_sites:
                    site = eqslist[0]
                    isite = se.structure.index(site)
                    try:
                        if strategy.uniquely_determines_coordination_environments:
                            ces = strategy.get_site_coordination_environments(site)
                        else:
                            ces = strategy.get_site_coordination_environments_fractions(site)
                    except NeighborsNotComputedChemenvError:
                        continue
                    if ces is None:
                        continue
                    if len(ces) == 0:
                        continue
                    comp = site.species
                    # ce = strategy.get_site_coordination_environment(site)
                    if strategy.uniquely_determines_coordination_environments:
                        ce = ces[0]
                        if ce is None:
                            continue
                        thecg = allcg.get_geometry_from_mp_symbol(ce[0])
                        mystring = "Environment for site #{} {} ({}) : {} ({})\n".format(
                            str(isite),
                            comp.get_reduced_formula_and_factor()[0],
                            str(comp),
                            thecg.name,
                            ce[0],
                        )
                    else:
                        mystring = "Environments for site #{} {} ({}) : \n".format(
                            str(isite),
                            comp.get_reduced_formula_and_factor()[0],
                            str(comp),
                        )
                        for ce in ces:
                            cg = allcg.get_geometry_from_mp_symbol(ce[0])
                            csm = ce[1]["other_symmetry_measures"]["csm_wcs_ctwcc"]
                            mystring += " - {} ({}): {:.2f} % (csm : {:2f})\n".format(
                                cg.name, cg.mp_symbol, 100.0 * ce[2], csm
                            )
                    if test in ["d", "g"] and strategy.uniquely_determines_coordination_environments:
                        if thecg.mp_symbol != UNCLEAR_ENVIRONMENT_SYMBOL:
                            mystring += "  <Continuous symmetry measures>  "
                            mingeoms = se.ce_list[isite][thecg.coordination_number][0].minimum_geometries()
                            for mingeom in mingeoms:
                                csm = mingeom[1]["other_symmetry_measures"]["csm_wcs_ctwcc"]
                                mystring += f"{mingeom[0]} : {csm:.2f}       "
                    print(mystring)
            if test == "g":
                while True:
                    test = input(
                        "Enter index of site(s) (e.g. 0 1 2, separated by spaces) for which you want to see the grid "
                        "of parameters : "
                    )
                    try:
                        indices = [int(x) for x in test.split()]
                        print(str(indices))
                        for isite in indices:
                            if isite < 0:
                                raise IndexError
                            se.plot_environments(isite)
                        break
                    except ValueError:
                        print("This is not a valid site")
                    except IndexError:
                        print("This site is out of the site range")

            if no_vis:
                test = input('Go to next structure ? ("y" to do so)')
                if test == "y":
                    break
                continue
            test = input('View structure with environments ? ("y" for the unit cell or "m" for a supercell or "n") : ')
            if test in ["y", "m"]:
                if test == "m":
                    mydeltas = []
                    while True:
                        try:
                            test = input("Enter multiplicity (e.g. 3 2 2) : ")
                            nns = test.split()
                            for i0 in range(int(nns[0])):
                                for i1 in range(int(nns[1])):
                                    for i2 in range(int(nns[2])):
                                        mydeltas.append(np.array([1.0 * i0, 1.0 * i1, 1.0 * i2], np.float_))
                            break

                        except (ValueError, IndexError):
                            print("Not a valid multiplicity")
                else:
                    mydeltas = [np.zeros(3, np.float_)]
                if firsttime:
                    vis = StructureVis(show_polyhedron=False, show_unit_cell=True)
                    vis.show_help = False
                    firsttime = False
                vis.set_structure(se.structure)
                strategy.set_structure_environments(se)
                for isite, site in enumerate(se.structure):
                    try:
                        ces = strategy.get_site_coordination_environments(site)
                    except NeighborsNotComputedChemenvError:
                        continue
                    if len(ces) == 0:
                        continue
                    ce = strategy.get_site_coordination_environment(site)
                    if ce is not None and ce[0] != UNCLEAR_ENVIRONMENT_SYMBOL:
                        for mydelta in mydeltas:
                            psite = PeriodicSite(
                                site.species,
                                site.frac_coords + mydelta,
                                site.lattice,
                                properties=site.properties,
                            )
                            vis.add_site(psite)
                            neighbors = strategy.get_site_neighbors(psite)
                            draw_cg(
                                vis,
                                psite,
                                neighbors,
                                cg=lgf.allcg.get_geometry_from_mp_symbol(ce[0]),
                                perm=ce[1]["permutation"],
                            )
                vis.show()
            test = input('Go to next structure ? ("y" to do so) : ')
            if test == "y":
                break
        print()


text:
from ._base import BaseDbdevCommand

class Command(BaseDbdevCommand):
    help = 'Run the database server for the database specified in the --database config in the foreground.'

    def dbdev_handle(self):
        self.dbdev_backend.run_database_server_in_foreground()

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Bus\DispatchesJobs;

class Mail extends Model
{
    use HasFactory, HashId, DispatchesJobs;

    protected static $hashConnection = 'bounce';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['draw_id'];

    /**
     * The model's default values for attributes.
     *
     * @var array
     */
    protected $attributes = [
        'delivery_status' => self::CREATED,
        'version' => 0,
    ];

    public const CREATED = 'created';
    public const SENDING = 'sending';
    public const SENT = 'sent';
    public const ERROR = 'error';
    public const RECEIVED = 'received';

    public static $deliveryStatuses = [
        self::CREATED,
        self::SENDING,
        self::SENT,
        self::ERROR,
        self::RECEIVED,
    ];

    public function updateDeliveryStatus($status)
    {
        $this->delivery_status = $status;

        // Force update, in case the delivery_status did not change
        $this->updated_at = Carbon::now();

        if ($status === self::CREATED) {
            $this->version++;
        }

        $this->save();
    }

    public function draw()
    {
        return $this->belongsTo(Draw::class);
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "delivery".
 *
 * @property integer $id
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $delivered_at
 * @property integer $order
 * @property integer $shipper
 *
 * @property Order $order0
 * @property Shipper $shipper0
 * @property DeliveryToProduct[] $deliveryToProducts
 * @property Product[] $products
 */
class Delivery extends \yii\db\ActiveRecord
{
    const STATUS_DELETED = 30;
    const STATUS_INACTIVE = 20;
    const STATUS_ACTIVE = 10;
    const STATUS_SHIPPED = 11;
    const STATUS_DELIVERED = 12;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'delivery';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status', 'created_at', 'updated_at', 'delivered_at', 'order', 'shipper'], 'integer'],
            [['order', 'shipper'], 'required'],
            [['order'], 'exist', 'skipOnError' => true, 'targetClass' => Order::className(), 'targetAttribute' => ['order' => 'id']],
            [['shipper'], 'exist', 'skipOnError' => true, 'targetClass' => Shipper::className(), 'targetAttribute' => ['shipper' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'Номер',
            'status' => 'Статус',
            'created_at' => 'Создана',
            'updated_at' => 'Изменена',
            'delivered_at' => 'Завершена',
            'order' => 'Заказ',
            'shipper' => 'Перевозчик',
        ];
    }

    /**
    * @return array
    */
    public static function getStatusArray()
    {
        $statusArray = [
            Delivery::STATUS_ACTIVE => 'Новая',
            Delivery::STATUS_SHIPPED => 'Отгружена',
            Delivery::STATUS_DELIVERED => 'Доставлена',
            Delivery::STATUS_INACTIVE => 'Неактивна',
            Delivery::STATUS_DELETED => 'Удалена',
        ];
        return $statusArray;
    }

    /**
    * @return string
    */
    public function getStatusName()
    {
        $statusArray = Delivery::getStatusArray();
        return isset($statusArray[$this->status])? $statusArray[$this->status]: '';
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrder()
    {
        return $this->hasOne(Order::className(), ['id' => 'order']);
    }

    /**
    * @return Order
    */
    public function getOrderOne()
    {
        return $this->getOrder()->exists()? $this->getOrder()->one(): null;
    }

    public function getOrderName()
    {
        return $this->getOrderOne()? $this->getOrderOne()->getName(): '';
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getShipper()
    {
        return $this->hasOne(Shipper::className(), ['id' => 'shipper']);
    }

    /**
    * @return Shipper
    */
    public function getShipperOne()
    {
        return $this->getShipper()->exists()? $this->getShipper()->one(): '';
    }

    public function getShipperName()
    {
        return $this->getShipper()->exists()? $this->getShipperOne()->getName(): '';
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDeliveryToProducts()
    {
        return $this->hasMany(DeliveryToProduct::className(), ['delivery' => 'id']);
    }

    /**
     * @param integer|null $id
     * @return DeliveryToProduct[]
     */
    public function getDeliveryToProductsAll($id = null)
    {
        if (is_null($id)) {
            return $this->getDeliveryToProducts()->all();
        }
        $orderToProducts = $this->getOrderToProductsAll($id);
        $deliveryToProducts = [];
        foreach ($orderToProducts as $orderToProduct) {
            $deliveryToProduct = new DeliveryToProduct();
            $deliveryToProduct->product = $orderToProduct->product;
            $deliveryToProduct->quantity = $orderToProduct->quantity;
            $deliveryToProducts[] = $deliveryToProduct;
        }
        return $deliveryToProducts;
    }

        /**
     * @param integer|null $id
     * @return ActiveQuery
     */
    public function getOrderToProducts($id = null)
    {
        if (!is_null($id)) {
            $order = Order::findOne(['id' => $id]);
            return $order->getOrderToProducts();
        }

        if (isset($this->order)) {
            return $this->getOrderOne()->getOrderToProducts();
        }
    }

    /**
     * @param integer|null $id
     * @return OrderToProduct[]
     */
    public function getOrderToProductsAll($id = null)
    {
        return $this->getOrderToProducts($id)->all();
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProducts()
    {
        return $this->hasMany(Product::className(), ['id' => 'product'])->viaTable('delivery_to_product', ['delivery' => 'id']);
    }

    /**
    * @return Product[]
    */
    public function getProductsAll()
    {
        return $this->getProducts()->exists()? $this->getProducts()->all(): [];
    }

    public function beforeSave($insert)
    {
        $today = new \DateTime();
        $this->updated_at = $today->getTimestamp();

        if ($insert) {
            $this->created_at = $today->getTimestamp();
        }

        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    public function getName()
    {
        return implode(' - ', [
            $this->id,
            $this->getOrderName(),
            $this->getShipperName(),
        ]);
    }
}


text:
===============
keystone-manage
===============

---------------------------
Keystone Management Utility
---------------------------

:Author: openstack@lists.openstack.org
:Date:   2013-10-17
:Copyright: OpenStack Foundation
:Version: 2013.2
:Manual section: 1
:Manual group: cloud computing

SYNOPSIS
========

  keystone-manage [options]

DESCRIPTION
===========

keystone-manage is the command line tool that interacts with the keystone
service to initialize and update data within Keystone.  Generally,
keystone-manage is only used for operations that can not be accomplished
with through the keystone REST api, such data import/export and schema
migrations.

USAGE
=====

    ``keystone-manage [options] action [additional args]``

General keystone-manage options:
--------------------------------

* ``--help`` : display verbose help output.

Invoking keystone-manage by itself will give you some usage information.

Available commands:

* ``db_sync``: Sync the database.
* ``db_version``: Print the current migration version of the database.
* ``pki_setup``: Initialize the certificates used to sign tokens.
* ``ssl_setup``: Generate certificates for SSL.
* ``token_flush``: Purge expired tokens.

OPTIONS
=======

  -h, --help            show this help message and exit
  --config-dir DIR      Path to a config directory to pull \*.conf files from.
                        This file set is sorted, so as to provide a
                        predictable parse order if individual options are
                        over-ridden. The set is parsed after the file(s)
                        specified via previous --config-file, arguments hence
                        over-ridden options in the directory take precedence.
  --config-file PATH    Path to a config file to use. Multiple config files
                        can be specified, with values in later files taking
                        precedence. The default files used are: None
  --debug, -d           Print debugging output (set logging level to DEBUG
                        instead of default WARNING level).
  --log-config PATH     If this option is specified, the logging configuration
                        file specified is used and overrides any other logging
                        options specified. Please see the Python logging
                        module documentation for details on logging
                        configuration files.
  --log-date-format DATE_FORMAT
                        Format string for %(asctime)s in log records. Default:
                        None
  --log-dir LOG_DIR, --logdir LOG_DIR
                        (Optional) The base directory used for relative
                        --log-file paths
  --log-file PATH, --logfile PATH
                        (Optional) Name of log file to output to. If no
                        default is set, logging will go to stdout.
  --log-format FORMAT   DEPRECATED. A logging.Formatter log message format
                        string which may use any of the available
                        logging.LogRecord attributes. This option is
                        deprecated. Please use logging_context_format_string
                        and logging_default_format_string instead.
  --nodebug             The inverse of --debug
  --nostandard-threads  The inverse of --standard-threads
  --nouse-syslog        The inverse of --use-syslog
  --noverbose           The inverse of --verbose
  --pydev-debug-host PYDEV_DEBUG_HOST
                        Host to connect to for remote debugger.
  --pydev-debug-port PYDEV_DEBUG_PORT
                        Port to connect to for remote debugger.
  --standard-threads    Do not monkey-patch threading system modules.
  --syslog-log-facility SYSLOG_LOG_FACILITY
                        syslog facility to receive log lines
  --use-syslog          Use syslog for logging.
  --verbose, -v         Print more verbose output (set logging level to INFO
                        instead of default WARNING level).
  --version             show program's version number and exit

FILES
=====

None

SEE ALSO
========

* `Keystone <http://github.com/openstack/keystone>`__

SOURCE
======

* Keystone is sourced in GitHub `Keystone <http://github.com/openstack/keystone>`__
* Keystone bugs are managed at Launchpad `Keystone <https://bugs.launchpad.net/keystone>`__


text:
package com.peike.theatersubtitle.settings;

import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.view.View;

import com.peike.theatersubtitle.R;

public class SettingsFragment extends PreferenceFragment implements SettingsActivity.FragView {

    private Preference storagePreference;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings_prefs);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        storagePreference = findPreference("pref_storage");
        setupClickListener();
    }

    @Override
    public void setSummary(String summary) {
        storagePreference.setSummary(summary);
    }

    private void setupClickListener() {
        storagePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                ((SettingsActivity) getActivity()).onStoragePreferenceClicked();
                return true;
            }
        });
    }
}


text:
<!DOCTYPE html>

		<title>Justin Wagner Week 4 Technical Blog</title>
		<link rel="stylesheet" type="text/css" href="stylesheets/blog_template.css">
		<link href='http://fonts.googleapis.com/css?family=Ubuntu:300,400,700,400italic' rel='stylesheet' type='text/css'>
		<link href='http://fonts.googleapis.com/css?family=Josefin+Slab:300,400,700,400italic' rel='stylesheet' type='text/css'>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

Cultural Blog

Justin W

Week 4

In this post, I'll take a loog at the Enumerable#cycle method.

Enumerable#cycle

I found cycle to be an interesting method to use. When using cycle, you call it after an object, and give it a block to pass. The method will then cycle through each element in the array, and perform the action that is in the block. If an argument is given after the cycle, it will cycle through that amount of times. If no argument is given, it will cycle infinitely. Changes made through the first cycle will have no affect on the next cycles, and it will always be the same.

For example, look at the code pictured in this post. I take an array and call cycle on it. I used an argument of 3, so it will cycle through the array 3 times. I then use the block to puts the value of each number times 2. This will output the result 3 times, without changing it each time.

Cycle can be a really useful method if you know when to use it. If you just want to cycle through an array a certain amount of times, use this, but if you want to be able to be more specific and specify which elements in an array you want to cycle through, use something like each. Also remember, if you use cycle to make an infinite loop, keep all necessary code inside the cycle block, otherwise it won't run!

© Justin Wagner - My Index


text:
require "singleton"
require "forwardable"

class Integer
  # Re-composes a prime factorization and returns the product.
  #
  # See Prime#int_from_prime_division for more details.
  def Integer.from_prime_division(pd)
    Prime.int_from_prime_division(pd)
  end

  # Returns the factorization of +self+.
  #
  # See Prime#prime_division for more details.
  def prime_division(generator = Prime::Generator23.new)
    Prime.prime_division(self, generator)
  end

  # Returns true if +self+ is a prime number, false for a composite.
  def prime?
    Prime.prime?(self)
  end

  # Iterates the given block over all prime numbers.
  #
  # See +Prime+#each for more details.
  def Integer.each_prime(ubound, &block) # :yields: prime
    Prime.each(ubound, &block)
  end
end

#
# The set of all prime numbers.
#
# == Example
#  Prime.each(100) do |prime|
#    p prime  #=> 2, 3, 5, 7, 11, ...., 97
#  end
#
# == Retrieving the instance
# +Prime+.new is obsolete. Now +Prime+ has the default instance and you can
# access it as +Prime+.instance.
#
# For convenience, each instance method of +Prime+.instance can be accessed
# as a class method of +Prime+.
#
# e.g.
#  Prime.instance.prime?(2)  #=> true
#  Prime.prime?(2)           #=> true
#
# == Generators
# A "generator" provides an implementation of enumerating pseudo-prime
# numbers and it remembers the position of enumeration and upper bound.
# Futhermore, it is a external iterator of prime enumeration which is
# compatible to an Enumerator.
#
# +Prime+::+PseudoPrimeGenerator+ is the base class for generators.
# There are few implementations of generator.
#
# [+Prime+::+EratosthenesGenerator+]
#   Uses eratosthenes's sieve.
# [+Prime+::+TrialDivisionGenerator+]
#   Uses the trial division method.
# [+Prime+::+Generator23+]
#   Generates all positive integers which is not divided by 2 nor 3.
#   This sequence is very bad as a pseudo-prime sequence. But this
#   is faster and uses much less memory than other generators. So,
#   it is suitable for factorizing an integer which is not large but
#   has many prime factors. e.g. for Prime#prime? .
class Prime
  include Enumerable
  @the_instance = Prime.new

  # obsolete. Use +Prime+::+instance+ or class methods of +Prime+.
  def initialize
    @generator = EratosthenesGenerator.new
    extend OldCompatibility
    warn "Prime::new is obsolete. use Prime::instance or class methods of Prime."
  end

  class<<self
    extend Forwardable
    include Enumerable
    # Returns the default instance of Prime.
    def instance; @the_instance end

    def method_added(method) # :nodoc:
      (class<<self;self;end).def_delegator :instance, method
    end
  end

  # Iterates the given block over all prime numbers.
  #
  # == Parameters
  # +ubound+::
  #   Optional. An arbitrary positive number.
  #   The upper bound of enumeration. The method enumerates
  #   prime numbers infinitely if +ubound+ is nil.
  # +generator+::
  #   Optional. An implementation of pseudo-prime generator.
  #
  # == Return value
  # An evaluated value of the given block at the last time.
  # Or an enumerator which is compatible to an +Enumerator+
  # if no block given.
  #
  # == Description
  # Calls +block+ once for each prime number, passing the prime as
  # a parameter.
  #
  # +ubound+::
  #   Upper bound of prime numbers. The iterator stops after
  #   yields all prime numbers p <= +ubound+.
  #
  # == Note
  # +Prime+.+new+ returns a object extended by +Prime+::+OldCompatibility+
  # in order to compatibility to Ruby 1.8, and +Prime+#each is overwritten
  # by +Prime+::+OldCompatibility+#+each+.
  #
  # +Prime+.+new+ is now obsolete. Use +Prime+.+instance+.+each+ or simply
  # +Prime+.+each+.
  def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
    generator.upper_bound = ubound
    generator.each(&block)
  end

  # Returns true if +value+ is prime, false for a composite.
  #
  # == Parameters
  # +value+:: an arbitrary integer to be checked.
  # +generator+:: optional. A pseudo-prime generator.
  def prime?(value, generator = Prime::Generator23.new)
    value = -value if value < 0
    return false if value < 2
    for num in generator
      #q,r = value.divmod num
      q = value / num; r = value % num
      return true if q < num
      return false if r == 0
    end
  end

  # Re-composes a prime factorization and returns the product.
  #
  # == Parameters
  # +pd+:: Array of pairs of integers. The each internal
  #        pair consists of a prime number -- a prime factor --
  #        and a natural number -- an exponent.
  #
  # == Example
  # For [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]], it returns
  # p_1**e_1 * p_2**e_2 * .... * p_n**e_n.
  #
  #  Prime.int_from_prime_division([[2,2], [3,1]])  #=> 12
  def int_from_prime_division(pd)
    pd.inject(1){|value, (prime, index)|
      value *= prime**index
    }
  end

  # Returns the factorization of +value+.
  #
  # == Parameters
  # +value+:: An arbitrary integer.
  # +generator+:: Optional. A pseudo-prime generator.
  #               +generator+.succ must return the next
  #               pseudo-prime number in the ascendent
  #               order. It must generate all prime numbers,
  #               but may generate non prime numbers.
  #
  # === Exceptions
  # +ZeroDivisionError+:: when +value+ is zero.
  #
  # == Example
  # For an arbitrary integer
  # n = p_1**e_1 * p_2**e_2 * .... * p_n**e_n,
  # prime_division(n) returns
  # [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]].
  #
  #  Prime.prime_division(12) #=> [[2,2], [3,1]]
  #
  def prime_division(value, generator= Prime::Generator23.new)
    raise ZeroDivisionError if value == 0
    pv = []
    for prime in generator
      count = 0
      while (value1, mod = value.divmod(prime)
	     mod) == 0
	value = value1
	count += 1
      end
      if count != 0
	pv.push [prime, count]
      end
      break if value1 <= prime
    end
    if value > 1
      pv.push [value, 1]
    end
    return pv
  end

  # An abstract class for enumerating pseudo-prime numbers.
  #
  # Concrete subclasses should override succ, next, rewind.
  class PseudoPrimeGenerator
    include Enumerable

    def initialize(ubound = nil)
      @ubound = ubound
    end

    def upper_bound=(ubound)
      @ubound = ubound
    end
    def upper_bound
      @ubound
    end

    # returns the next pseudo-prime number, and move the internal
    # position forward.
    #
    # +PseudoPrimeGenerator+#succ raises +NotImplementedError+.
    def succ
      raise NotImplementedError, "need to define `succ'"
    end

    # alias of +succ+.
    def next
      raise NotImplementedError, "need to define `next'"
    end

    # Rewinds the internal position for enumeration.
    #
    # See +Enumerator+#rewind.
    def rewind
      raise NotImplementedError, "need to define `rewind'"
    end

    # Iterates the given block for each prime numbers.
    def each()
      return self.dup unless block_given?
      if @ubound
	last_value = nil
	loop do
	  prime = succ
	  break last_value if prime > @ubound
	  last_value = yield(prime)
	end
      else
	loop do
	  yield(succ)
	end
      end
    end

    # see +Enumerator+#with_index.
    alias with_index each_with_index

    # see +Enumerator+#with_object.
    def with_object(obj)
      return enum_for(:with_object) unless block_given?
      each do |prime|
	yield prime, obj
      end
    end
  end

  # An implementation of +PseudoPrimeGenerator+.
  #
  # Uses +EratosthenesSieve+.
  class EratosthenesGenerator < PseudoPrimeGenerator
    def initialize
      @last_prime = nil
    end

    def succ
      @last_prime = @last_prime ? EratosthenesSieve.instance.next_to(@last_prime) : 2
    end
    def rewind
      initialize
    end
    alias next succ
  end

  # An implementation of +PseudoPrimeGenerator+ which uses
  # a prime table generated by trial division.
  class TrialDivisionGenerator<PseudoPrimeGenerator
    def initialize
      @index = -1
    end

    def succ
      TrialDivision.instance[@index += 1]
    end
    def rewind
      initialize
    end
    alias next succ
  end

  # Generates all integer which are greater than 2 and
  # are not divided by 2 nor 3.
  #
  # This is a pseudo-prime generator, suitable on
  # checking primality of a integer by brute force
  # method.
  class Generator23<PseudoPrimeGenerator
    def initialize
      @prime = 1
      @step = nil
    end

    def succ
      loop do
	if (@step)
	  @prime += @step
	  @step = 6 - @step
	else
	  case @prime
	  when 1; @prime = 2
	  when 2; @prime = 3
	  when 3; @prime = 5; @step = 2
	  end
	end
	break @prime
      end
    end
    alias next succ
    def rewind
      initialize
    end
  end

  # Internal use. An implementation of prime table by trial division method.
  class TrialDivision
    include Singleton

    def initialize # :nodoc:
      # These are included as class variables to cache them for later uses.  If memory
      #   usage is a problem, they can be put in Prime#initialize as instance variables.

      # There must be no primes between @primes[-1] and @next_to_check.
      @primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
      # @next_to_check % 6 must be 1.
      @next_to_check = 103            # @primes[-1] - @primes[-1] % 6 + 7
      @ulticheck_index = 3            # @primes.index(@primes.reverse.find {|n|
      #   n < Math.sqrt(@@next_to_check) })
      @ulticheck_next_squared = 121   # @primes[@ulticheck_index + 1] ** 2
    end

    # Returns the cached prime numbers.
    def cache
      return @primes
    end
    alias primes cache
    alias primes_so_far cache

    # Returns the +index+th prime number.
    #
    # +index+ is a 0-based index.
    def [](index)
      while index >= @primes.length
	# Only check for prime factors up to the square root of the potential primes,
	#   but without the performance hit of an actual square root calculation.
	if @next_to_check + 4 > @ulticheck_next_squared
	  @ulticheck_index += 1
	  @ulticheck_next_squared = @primes.at(@ulticheck_index + 1) ** 2
	end
	# Only check numbers congruent to one and five, modulo six. All others

	#   are divisible by two or three.  This also allows us to skip checking against
	#   two and three.
	@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
	@next_to_check += 4
	@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
	@next_to_check += 2
      end
      return @primes[index]
    end
  end

  # Internal use. An implementation of eratosthenes's sieve
  class EratosthenesSieve
    include Singleton

    def initialize # :nodoc:
      # bitmap for odd prime numbers less than 256.
      # For an arbitrary odd number n, @table[i][j] is 1 when n is prime where i,j = n.divmod(32) .
      @table = [0xcb6e, 0x64b4, 0x129a, 0x816d, 0x4c32, 0x864a, 0x820d, 0x2196]
    end

    # returns the least odd prime number which is greater than +n+.
    def next_to(n)
      n = (n-1).div(2)*2+3 # the next odd number of given n
      i,j = n.divmod(32)
      loop do
	extend_table until @table.length > i
	if !@table[i].zero?
	  (j...32).step(2) do |k|
	    return 32*i+k if !@table[i][k.div(2)].zero?
	  end
	end
	i += 1; j = 1
      end
    end

    private
    def extend_table
      orig_len = @table.length
      new_len = [orig_len**2, orig_len+256].min
      lbound = orig_len*32
      ubound = new_len*32
      @table.fill(0xFFFF, orig_len...new_len)
      (3..Integer(Math.sqrt(ubound))).step(2) do |p|
	i, j = p.divmod(32)
	next if @table[i][j.div(2)].zero?

	start = (lbound.div(2*p)*2+1)*p    # odd multiple of p which is greater than or equal to lbound
	(start...ubound).step(2*p) do |n|
	  i, j = n.divmod(32)
	  @table[i] &= 0xFFFF ^ (1<<(j.div(2)))
	end
      end
    end
  end

  # Provides a +Prime+ object with compatibility to Ruby 1.8 when instanciated via +Prime+.+new+.
  module OldCompatibility
    # Returns the next prime number and forwards internal pointer.
    def succ
      @generator.succ
    end
    alias next succ

    # Overwrites Prime#each.
    #
    # Iterates the given block over all prime numbers. Note that enumeration starts from
    # the current position of internal pointer, not rewound.
    def each
      return @generator.dup unless block_given?
      loop do
	yield succ
      end
    end
  end
end


text:
package DNS::LDNS::DNSSecTrustTree;

use 5.008008;
use strict;
use warnings;

use DNS::LDNS;

our $VERSION = '0.06';

sub add_parent {
    my ($self, $parent, $sig, $parent_status) = @_;

    if (DNS::LDNS::GC::is_owned($parent)) {
	die "Cannot add to multiple trees.";
    }
    my $s = _add_parent($self, $parent, $sig, $parent_status);
    DNS::LDNS::GC::own($parent, $self);
    $DNS::LDNS::last_status = $s;
    return $s;
}

sub contains_keys {
    my ($self, $trusted_keys) = @_;

    my $s = _contains_keys($self, $trusted_keys);
    $DNS::LDNS::last_status = $s;
    return $s;
}

sub rr {
    my $self = shift;
    return DNS::LDNS::GC::own($self->_rr, $self);
}

sub rrset {
    my $self = shift;
    return DNS::LDNS::GC::own($self->_rrset, $self);
}

sub parent {
    my ($self, $i) = @_;
    return DNS::LDNS::GC::own($self->_parent($i), $self);
}

sub parent_status {
    my ($self, $i) = @_;
    my $s = _parent_status($self, $i);
    $DNS::LDNS::last_status = $s;
    return $s;
}

sub parent_signature {
    my ($self, $i) = @_;
    return DNS::LDNS::GC::own($self->_parent_signature($i), $self);
}

1;
__END__

=head1 NAME

DNS::LDNS::DNSSecTrustTree - Trust tree from signed RR to trust anchors

=head1 SYNOPSIS

  use DNS::LDNS ':all'

  tree = new DNS::LDNS::DNSSecTrustTree
  tree->print(fp)
  d = tree->depth
  status = tree->add_parent(parent, sig, parent_status)
  status = tree->contains_keys(trusted_keys)

  # Node attributes
  rr = tree->rr;
  rrset = tree->rrset
  ptree = tree->parent(i)
  pstatus = tree->parent_status(i)
  rr = tree->parent_signature(i)
  count = tree->parent_count

=head1 SEE ALSO

http://www.nlnetlabs.nl/projects/ldns

=head1 AUTHOR

Erik Pihl Ostlyngen, E<lt>erik.ostlyngen@uninett.noE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2013 by UNINETT Norid AS

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.14.2 or,
at your option, any later version of Perl 5 you may have available.

=cut


text:
var prefix = require("../../../../client/prefix.coffee"),
    print = require("../../../../core/console/print.coffee")
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Creates and styles the search box, if enabled.
//------------------------------------------------------------------------------
module.exports = function ( vars ) {

  if ( vars.dev.value ) print.time("creating search")

  var data = require("./data.js")
    , items = require("./items.coffee")
    , update = require("./update.js")

  vars.container.search = vars.container.selector.selectAll("div.d3plus_drop_search")
    .data(vars.search.enabled ? ["search"] : [])

  function searchStyle(elem) {

    elem
      .style("padding",vars.ui.padding.css)
      .style("display","block")
      .style("background-color",d3.rgb(vars.ui.color.primary.value).darker(0.15).toString())

  }

  function inputStyle(elem) {

    var width = vars.width.secondary - vars.ui.padding.left*2 - vars.ui.padding.right*2 + vars.ui.border*2

    elem
      .style("padding",vars.ui.padding.left/2+vars.ui.padding.right/2+"px")
      .style("width",width+"px")
      .style("border-width","0px")
      .style("font-family",vars.font.secondary.family.value)
      .style("font-size",vars.font.secondary.size+"px")
      .style("font-weight",vars.font.secondary.weight)
      .style("text-align",vars.font.secondary.align)
      .style("outline","none")
      .style(prefix()+"border-radius","0")
      .attr("placeholder",vars.format.value(vars.format.locale.value.method.search))

  }

  if (vars.draw.timing) {

    vars.container.search.transition().duration(vars.draw.timing)
      .call(searchStyle)

    vars.container.search.select("input").transition().duration(vars.draw.timing)
      .call(inputStyle)

  }
  else {

    vars.container.search
      .call(searchStyle)

    vars.container.search.select("input")
      .call(inputStyle)

  }

  vars.container.search.enter()
    .insert("div","#d3plus_drop_list_"+vars.container.id)
      .attr("class","d3plus_drop_search")
      .attr("id","d3plus_drop_search_"+vars.container.id)
      .call(searchStyle)
      .append("input")
        .attr("id","d3plus_drop_input_"+vars.container.id)
        .style("-webkit-appearance","none")
        .call(inputStyle)

  vars.container.search.select("input").on("keyup."+vars.container.id,function(d){
    var term = this.value;
    if (vars.search.term !== term) {
      vars.search.term = term;
      data(vars);
      items(vars);
      update(vars);
    }
  });

  vars.container.search.exit().remove()

  var oldDisplay = vars.container.selector.style("display")
  vars.container.selector.style("display", "block")
  vars.search.height = vars.search.enabled ? vars.container.search.node().offsetHeight ||
                       vars.container.search.node().getBoundingClientRect().height : 0;
  vars.container.selector.style("display", oldDisplay)

  if ( vars.search.enabled ) {
    vars.margin.title += vars.search.height
  }

  if ( vars.dev.value ) print.timeEnd("creating search")

}


text:
Card Sorting / Categorization tool
========


text:
#include <aws/cloudfront/model/EncryptionEntity.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace CloudFront
{
namespace Model
{

EncryptionEntity::EncryptionEntity() :
    m_publicKeyIdHasBeenSet(false),
    m_providerIdHasBeenSet(false),
    m_fieldPatternsHasBeenSet(false)
{
}

EncryptionEntity::EncryptionEntity(const XmlNode& xmlNode) :
    m_publicKeyIdHasBeenSet(false),
    m_providerIdHasBeenSet(false),
    m_fieldPatternsHasBeenSet(false)
{
  *this = xmlNode;
}

EncryptionEntity& EncryptionEntity::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode publicKeyIdNode = resultNode.FirstChild("PublicKeyId");
    if(!publicKeyIdNode.IsNull())
    {
      m_publicKeyId = Aws::Utils::Xml::DecodeEscapedXmlText(publicKeyIdNode.GetText());
      m_publicKeyIdHasBeenSet = true;
    }
    XmlNode providerIdNode = resultNode.FirstChild("ProviderId");
    if(!providerIdNode.IsNull())
    {
      m_providerId = Aws::Utils::Xml::DecodeEscapedXmlText(providerIdNode.GetText());
      m_providerIdHasBeenSet = true;
    }
    XmlNode fieldPatternsNode = resultNode.FirstChild("FieldPatterns");
    if(!fieldPatternsNode.IsNull())
    {
      m_fieldPatterns = fieldPatternsNode;
      m_fieldPatternsHasBeenSet = true;
    }
  }

  return *this;
}

void EncryptionEntity::AddToNode(XmlNode& parentNode) const
{
  Aws::StringStream ss;
  if(m_publicKeyIdHasBeenSet)
  {
   XmlNode publicKeyIdNode = parentNode.CreateChildElement("PublicKeyId");
   publicKeyIdNode.SetText(m_publicKeyId);
  }

  if(m_providerIdHasBeenSet)
  {
   XmlNode providerIdNode = parentNode.CreateChildElement("ProviderId");
   providerIdNode.SetText(m_providerId);
  }

  if(m_fieldPatternsHasBeenSet)
  {
   XmlNode fieldPatternsNode = parentNode.CreateChildElement("FieldPatterns");
   m_fieldPatterns.AddToNode(fieldPatternsNode);
  }

}

} // namespace Model
} // namespace CloudFront
} // namespace Aws


text:
package com.gdn.venice.persistence;

import java.io.Serializable;
import javax.persistence.*;

/**
 * The primary key class for the ven_party_address database table.
 *
 */
@Embeddable
public class VenPartyAddressPK implements Serializable {
	//default serial version id, required for serializable classes.
	private static final long serialVersionUID = 1L;

	@Column(name="party_id", unique=true, nullable=false)
	private Long partyId;

	@Column(name="address_id", unique=true, nullable=false)
	private Long addressId;

	@Column(name="address_type_id", unique=true, nullable=false)
	private Long addressTypeId;

    public VenPartyAddressPK() {
    }
	public Long getPartyId() {
		return this.partyId;
	}
	public void setPartyId(Long partyId) {
		this.partyId = partyId;
	}
	public Long getAddressId() {
		return this.addressId;
	}
	public void setAddressId(Long addressId) {
		this.addressId = addressId;
	}
	public Long getAddressTypeId() {
		return this.addressTypeId;
	}
	public void setAddressTypeId(Long addressTypeId) {
		this.addressTypeId = addressTypeId;
	}

	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (!(other instanceof VenPartyAddressPK)) {
			return false;
		}
		VenPartyAddressPK castOther = (VenPartyAddressPK)other;
		return
			this.partyId.equals(castOther.partyId)
			&& this.addressId.equals(castOther.addressId)
			&& this.addressTypeId.equals(castOther.addressTypeId);

    }

	public int hashCode() {
		final int prime = 31;
		int hash = 17;
		hash = hash * prime + this.partyId.hashCode();
		hash = hash * prime + this.addressId.hashCode();
		hash = hash * prime + this.addressTypeId.hashCode();

		return hash;
    }
}


text:
using ArgParse
s = ArgParseSettings()
@add_arg_table s begin
    "group1"
        help = "One end point of the edge for which to analyze context, where "*
               "| is used to separate mulitple ids. (i.e. ENCFF000ARO|ENCFF000ARK)."
        arg_type = ASCIIString
        required = true
    "group2"
        help = "The other end point of the edge for which to analyze context, where "*
               "| is used to separate mulitple ids. (i.e. ENCFF000ARO|ENCFF000ARK)."
        arg_type = ASCIIString
        required = true
    "data_bundles"
        help = "Location of the ChromNet data bundles (i.e. ENCODE_buildX.ChromNet.jld)"
        arg_type = ASCIIString
        nargs = '+'
        required = true
    "--output", "-o"
        help = "Where to save the edge context BED file"
        default = "-"
    "--load-cor"
        help = "A copy of the raw data correlation matrix"
        metavar = "COR_FILE"
    "--quiet", "-q"
        help = "Don't print anything"
        action = :store_true
end
args = parse_args(s)

using ChromNet
using JSON
using JLD
using SamIO
using ProgressMeter

# open the data bundle and load the metadata
dataBundles = [jldopen(x) for x in args["data_bundles"]]
metadata = Dict()
for bundle in dataBundles
    metadata = merge(metadata, read(bundle, "metadata"))
end
ids = vcat([read(bundle, "ids") for bundle in dataBundles]...)
numBins = round(Int, ceil(sum(ReferenceContigs_hg38.sizes) / 1000))

# find the indexes of the groups this edge is between
group1Inds = map(x->findfirst(ids, x), split(args["group1"], "|"))
group2Inds = map(x->findfirst(ids, x), split(args["group2"], "|"))
@assert all(group1Inds .> 0) "Some ids from group 1 were not found: $(group1Inds[group1Inds .== 0])"
@assert all(group2Inds .> 0) "Some ids from group 2 were not found: $(group2Inds[group2Inds .== 0])"

# compute the joint correlation matrix
C = nothing
if typeof(args["load-cor"]) != Void
    C,header = readdlm(args["load-cor"], header=true)
    @assert all(header .== ids) "Loaded correlation matrix does not match data! Perhaps a different file name ordering?"
else
    C = streaming_cor(dataBundles, quiet=args["quiet"])
end
cov2cor!(C)

# compute the edge impact
edgeScores = streaming_edgeimpact(dataBundles, C, group1Inds, group2Inds, quiet=args["quiet"])
map(close, dataBundles)

# send the data in BED format to the output stream
outStream = STDOUT
if args["output"] != "-"
    outStream = open(args["output"], "w")
end
contigIndex = 1
pos = 1
ctgs = ReferenceContigs_hg38
for i in 1:numBins
    while pos > ctgs.offsets[contigIndex] + ctgs.sizes[contigIndex]
        contigIndex += 1
    end
    println(outStream, ctgs.names[contigIndex], "\t", pos - ctgs.offsets[contigIndex], "\t", pos - ctgs.offsets[contigIndex] + 999, "\t*\t", edgeScores[i])
    pos += 1000
end


text:
package gov.nih.nci.cabig.caaers.service.migrator;

import gov.nih.nci.cabig.caaers.CaaersDbTestCase;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.AdverseEventReport;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.AdverseEventReportingPeriodType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ContactMechanismType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.EthnicityType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.GenderType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.OrganizationAssignedIdentifierType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.OrganizationRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ParticipantType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.PhysicianType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.RaceType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ReducedIdentifierType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ReporterType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudyParticipantAssignmentRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudyRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudySiteRefType;
import gov.nih.nci.cabig.caaers.integration.schema.common.OrganizationType;
import gov.nih.nci.cabig.caaers.integration.schema.common.ParticipantIdentifierType;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class ExpeditedAdverseEventReportConverterTest extends CaaersDbTestCase {

	private ExpeditedAdverseEventReportConverter converter = (ExpeditedAdverseEventReportConverter) getApplicationContext().getBean("eaeConverter");
	private AdverseEventReport aeReport =null;

	protected static final Calendar BIRTH_DATE = new GregorianCalendar(1921, 05, 27);
	protected static final String STUDY_IDENTIFIER = "STUDY-001";
	protected static final String STUDY_SUBJECT_IDENTIFIER = "STU-SUB-001";
	protected static final String SUBJECT_IDENTIFIER = "SUB-001";
	protected static final String ORG_NCI_CODE= "NC010";
	protected static final String ORG_NAME= "Duke University";

	protected XMLGregorianCalendar getXMLDate(Date date) throws DatatypeConfigurationException {
		GregorianCalendar c = new GregorianCalendar();
		c.setTime(date);
		XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
		return date2;
	}

	 protected AdverseEventReport createExpeditedReport() {
		AdverseEventReport report = new AdverseEventReport();
	 	report = new AdverseEventReport();
	 	Date date = new Date();
		try {
			report.setCreatedAt(getXMLDate(date));
		} catch (DatatypeConfigurationException e) {
			e.printStackTrace();
		}
		report.setAdverseEventReportingPeriod(createReportingPeriod());
	 	report.setReporter(createReporter(new ReporterType()));
	 	report.setPhysician(createPhysician(new PhysicianType()));
        report.setExternalId("123456");
        return report;
    }

	 protected AdverseEventReportingPeriodType createReportingPeriod() {
		AdverseEventReportingPeriodType reportingPeriod = new AdverseEventReportingPeriodType();
		reportingPeriod.setCycleNumber(1);
		Date date = new Date();
		try {
			reportingPeriod.setStartDate(getXMLDate(date));
		} catch (DatatypeConfigurationException e) {
			e.printStackTrace();
		}
		reportingPeriod.setStudyParticipantAssignmentRef(createStudyParticipantAssignmentType());
        return reportingPeriod;
	    }

	 protected StudyParticipantAssignmentRefType createStudyParticipantAssignmentType(){
		 StudyParticipantAssignmentRefType studyParticipantAssignmentType = new StudyParticipantAssignmentRefType();
		 studyParticipantAssignmentType.setStudySiteRef(createStudySiteType());

		 studyParticipantAssignmentType.setStudySubjectIdentifier(STUDY_SUBJECT_IDENTIFIER);

		 return studyParticipantAssignmentType;
	 }

	 protected StudySiteRefType createStudySiteType(){
		 StudySiteRefType studySiteType = new StudySiteRefType();
		 studySiteType.setStudyRef(createStudyType());

		 return studySiteType;
	 }

	 protected OrganizationType createOrganizationType(String name, String nciCode ){
		 OrganizationType organizationType = new OrganizationType();
		 organizationType.setName(name);
		 organizationType.setNciInstituteCode(nciCode);

		 return organizationType;
	 }

	 protected StudyRefType createStudyType(){
		 StudyRefType studyType = new StudyRefType();

		 ReducedIdentifierType identifier = new ReducedIdentifierType();
		 identifier.setType(gov.nih.nci.cabig.caaers.integration.schema.common.StudyIdentifierType.PROTOCOL_AUTHORITY_IDENTIFIER);
		 identifier.setValue(STUDY_IDENTIFIER);

		 StudyRefType.Identifiers identifiers = new StudyRefType.Identifiers();
		 identifiers.setIdentifier(identifier);

		 studyType.setIdentifiers(identifiers);

		 return studyType;
	 }

	 protected ParticipantType createParticipantType(){
		 ParticipantType participantType = new ParticipantType();
		 try {
			participantType.setBirthDate(getXMLDate(BIRTH_DATE.getTime()));
		} catch (DatatypeConfigurationException e) {
			e.printStackTrace();
		}

		 participantType.setEthnicity(EthnicityType.NOT_HISPANIC_OR_LATINO);
		 participantType.setFirstName("John");
		 participantType.setLastName("Doe");
		 participantType.setRace(RaceType.NOT_REPORTED);
		 participantType.setGender(GenderType.UNKNOWN);

		 OrganizationAssignedIdentifierType orgId = new OrganizationAssignedIdentifierType();
		 OrganizationRefType orgRefType = new OrganizationRefType();
		 orgRefType.setName(ORG_NAME);
		 orgRefType.setNciInstituteCode(ORG_NCI_CODE);
		 orgId.setOrganizationRef(orgRefType);
		 orgId.setPrimaryIndicator(true);
		 orgId.setType(ParticipantIdentifierType.MRN);
		 orgId.setValue(SUBJECT_IDENTIFIER);

		 List<OrganizationAssignedIdentifierType> orgIds = new ArrayList<OrganizationAssignedIdentifierType>();
		 orgIds.add(orgId);

		 ParticipantType.Identifiers identifiers = new ParticipantType.Identifiers();
		 identifiers.setOrganizationAssignedIdentifier(orgIds);

		 participantType.setIdentifiers(identifiers);

		 return participantType;
	 }

	 protected ReporterType createReporter(final ReporterType person) {
        person.setFirstName("Alfred");
        person.setLastName("Nobel");
        ContactMechanismType cm = new ContactMechanismType();
        cm.setType("e-mail");
        cm.setValue("jmarshall@gmail.ire");
        person.getContactMechanism().add(cm);
        return person;
	    }

	 protected PhysicianType createPhysician(final PhysicianType person) {
        person.setFirstName("Frank");
        person.setLastName("Just Frank");
        ContactMechanismType cm = new ContactMechanismType();
        cm.setType("phone");
        cm.setValue("712-123-9081");
        person.getContactMechanism().add(cm);
        return person;
	    }

	protected void setUp() throws Exception {
		super.setUp();

		aeReport = createExpeditedReport();

	}

	public void testConvertReport() throws Exception{
		ExpeditedAdverseEventReport domainReport = converter.convert(aeReport);

		assertNotNull(domainReport.getReportingPeriod());
		assertNotNull(domainReport.getReporter());
		assertNotNull(domainReport.getPhysician());
		assertNotNull(domainReport.getReportingPeriod().getAssignment());
	//	assertNotNull(domainReport.getReportingPeriod().getAssignment().getParticipant());
		assertNotNull(domainReport.getReportingPeriod().getAssignment().getStudySite());
		assertNotNull(domainReport.getReportingPeriod().getAssignment().getStudySite().getStudy());

        assertTrue(domainReport.getExternalId().equals("123456"));
		assertEquals("wrong physician first name","Frank", domainReport.getPhysician().getFirstName());
		assertEquals("wrong physician phone","712-123-9081", domainReport.getPhysician().getPhoneNumber());
		assertEquals("wrong reporter last name","Nobel", domainReport.getReporter().getLastName());
		assertEquals("wrong reporter email","jmarshall@gmail.ire", domainReport.getReporter().getEmailAddress());

		assertEquals("wrong study identifier",STUDY_IDENTIFIER, domainReport.getReportingPeriod().getAssignment().
				getStudySite().getStudy().getIdentifiers().get(0).getValue());
		assertEquals("wrong study short title","dummy", domainReport.getReportingPeriod().getAssignment().
				getStudySite().getStudy().getShortTitle());
		assertEquals("wrong subject identifier",STUDY_SUBJECT_IDENTIFIER, domainReport.getReportingPeriod().getAssignment()
				.getStudySubjectIdentifier());

	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Boletín de la Academia Nacional de Ciencias de Córdoba 25: 80-81 [no. 151, reprint pages 82-83] (1921)

#### Original name
Gloniella chiliensis Speg.

### Remarks
null


text:
package eu.tankernn.gameEngine.entities;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import org.lwjgl.util.vector.Vector3f;

import eu.tankernn.gameEngine.entities.ai.Behavior;
import eu.tankernn.gameEngine.renderEngine.DisplayManager;
import eu.tankernn.gameEngine.settings.Physics;

public class EntityState implements Serializable {
	/**
	 *
	 */
	private static final long serialVersionUID = -3294516796577777079L;

	protected static final AtomicInteger ID_GEN = new AtomicInteger();

	private int id;
	private int modelId = -1;
	private int systemId = -1;
	private final Vector3f position;
	private final Vector3f rotation;
	private final Vector3f velocity;
	private final Vector3f scale;
	protected boolean dead = false;

	private Set<Behavior> behaviors;

	public EntityState(int id, int modelId, int systemId, Vector3f position, Vector3f rotation, Vector3f velocity,
			Vector3f scale, Behavior... behaviors) {
		this.id = id;
		this.modelId = modelId;
		this.systemId = systemId;
		this.position = new Vector3f(position);
		this.rotation = new Vector3f(rotation);
		this.velocity = new Vector3f(velocity);
		this.scale = new Vector3f(scale);

		this.behaviors = new HashSet<>(Arrays.asList(behaviors));
		this.behaviors.forEach(b -> b.setEntity(this));
	}

	public EntityState(int modelId, int systemId, Vector3f position, Vector3f rotation, Vector3f velocity,
			Vector3f scale, Behavior... behaviors) {
		this(ID_GEN.getAndIncrement(), modelId, systemId, position, rotation, velocity, scale, behaviors);
	}

	public EntityState() {
		this(-1, -1, new Vector3f(0, 0, 0), new Vector3f(0, 0, 0), new Vector3f(0, 0, 0), new Vector3f(1, 1, 1));
	}

	/**
	 * Moves this entity in the direction of its rotation.
	 *
	 * @param speed
	 *            The speed with which to move the entity
	 */
	public void generateVelocity(float speed, float tickTimeSeconds) {
		getVelocity().x = (float) (speed * Math.sin(Math.toRadians(getRotation().y)));
		getVelocity().z = (float) (speed * Math.cos(Math.toRadians(getRotation().y)));
		getVelocity().y += Physics.GRAVITY * DisplayManager.getFrameTimeSeconds();
	}

	public void increaseRotation(Vector3f deltaRotation) {
		Vector3f.add(getRotation(), deltaRotation, getRotation());
	}

	public void update(GameContext ctx) {
		behaviors.forEach(b -> b.update(ctx));

		float terrainHeight = ctx.getTerrainHeight(position.x, position.z);

		if (position.y < terrainHeight) {
			velocity.y = 0;
			position.y = terrainHeight;
		}

		Vector3f.add(position, (Vector3f) new Vector3f(velocity).scale(ctx.getTickLengthSeconds()), position);
	}

	public void addBehavior(Behavior behavior) {
		behaviors.add(behavior);
		behavior.setEntity(this);
	}

	public int getId() {
		return id;
	}

	public int getModelId() {
		return modelId;
	}

	public void setModelId(int modelId) {
		this.modelId = modelId;
	}

	public Vector3f getPosition() {
		return position;
	}

	public Vector3f getRotation() {
		return rotation;
	}

	public Vector3f getVelocity() {
		return velocity;
	}

	public Vector3f getScale() {
		return scale;
	}

	public boolean isDead() {
		return dead;
	}

	public void setDead(boolean dead) {
		this.dead = dead;
	}

	public int getParticleSystemId() {
		return systemId;
	}

	public Set<Behavior> getBehaviors() {
		return behaviors;
	}

	public void setBehaviors(Set<Behavior> behaviors) {
		this.behaviors = behaviors;
	}

	public String toString() {
		return String.format("Entity with id %d, modelId %d and position %s. List of behaviors: %s", id, modelId, position.toString(), behaviors.toString());
	}

	public void resetId() {
		this.id = ID_GEN.getAndIncrement();
	}
}


text:
import sys
import re
import os
import shutil
import commands

"""Copy Special exercise
"""

# +++your code here+++
# Write functions and modify main() to call them

#this function returns the special files in the given directory
def get_files(dir):
  files = os.listdir(dir)
  special_files = []
  for file in files:
    match = re.search(r'__\w+__',file)
    if match:
      special_files.append(file)
  return special_files

def main():
  # This basic command line argument parsing code is provided.
  # Add code to call your functions below.

  # Make a list of command line arguments, omitting the [0] element
  # which is the script itself.
  args = sys.argv[1:]
  if not args:
    print "usage: [--todir dir][--tozip zipfile] dir [dir ...]";
    sys.exit(1)

  # todir and tozip are either set from command line
  # or left as the empty string.
  # The args array is left just containing the dirs.
  todir = ''
  if args[0] == '--todir':
    todir = args[1]
    del args[0:2]

  tozip = ''
  if args[0] == '--tozip':
    tozip = args[1]
    del args[0:2]

  if len(args) == 0:
    print "error: must specify one or more dirs"
    sys.exit(1)

  # +++your code here+++
  # Call your functions
  abstodir = ''
  if todir != '':
    abstodir = os.path.abspath(todir)
    if os.path.exists(abstodir) == False:
      os.mkdir(abstodir)

  for dir in args:
    absdir = os.path.abspath(dir)
    listfiles = get_files(absdir)
    zipcommand = 'zip -j ' + tozip
    for files in listfiles:
      print files
      if todir != '':
        shutil.copy(os.path.join(absdir,files),os.path.join(abstodir,files))
      if tozip != '':
        zipcommand+=' '+os.path.join(absdir,files)
    if tozip != '':
      os.system(zipcommand)

  sys.exit(0)

if __name__ == "__main__":
  main()


text:
class Validation
  include MongoMapper::EmbeddedDocument

  key :type, String
  key :key,  String

  validates_presence_of  :key
  validates_inclusion_of :type, :within => methods.grep(/^validates_/)

  def apply(klass, scope)
    klass.send("validates_#{type}", key)
  end
end


text:
'use strict';

const assert = require('assert');
const app = require('../../../index');

describe('Survey', () => {
    it('should exist', () => {
        assert(app.api.policies.Survey);
    });
});


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression.evaluation;

import com.yahoo.searchlib.rankingexpression.RankingExpression;
import com.yahoo.searchlib.rankingexpression.Reference;
import com.yahoo.tensor.TensorType;

import java.util.Arrays;

/**
 * Creates a context which supports array index based lookup.
 * This instance may be reused indefinitely for evaluations of a single
 * ranking expression, in a single thread at the time.
 *
 * @author bratseth
 */
public class ArrayContext extends AbstractArrayContext implements Cloneable {

    /** The current values set */
    private Value[] values;

    /**
     * Create a fast lookup context for an expression.
     * This instance should be reused indefinitely by a single thread.
     * This will fail if unknown values are attempted added.
     */
    public ArrayContext(RankingExpression expression) {
        this(expression, false);
    }

    public ArrayContext(RankingExpression expression, boolean ignoreUnknownValues) {
        this(expression, ignoreUnknownValues, defaultMissingValue);
    }

    public ArrayContext(RankingExpression expression, Value defaultValue) {
        this(expression, false, defaultValue);
    }

    /**
     * Create a fast lookup context for an expression.
     * This instance should be reused indefinitely by a single thread.
     *
     * @param expression the expression to create a context for
     * @param ignoreUnknownValues whether attempts to put values not present in this expression
     *                            should fail (false - the default), or be ignored (true)
     * @param missingValue the value to return if not set.
     */
    public ArrayContext(RankingExpression expression, boolean ignoreUnknownValues, Value missingValue) {
        super(expression, ignoreUnknownValues, missingValue);
        values = new Value[doubleValues().length];
        Arrays.fill(values, this.missingValue);
    }

    /**
     * Puts a value by name.
     * The value will be frozen if it isn't already.
     *
     * @throws IllegalArgumentException if the name is not present in the ranking expression this was created with, and
     *         ignoredUnknownValues is false
     */
    @Override
    public final void put(String name, Value value) {
        Integer index = nameToIndex().get(name);
        if (index == null) {
            if (ignoreUnknownValues())
                return;
            else
                throw new IllegalArgumentException("Value '" + name + "' is not known to " + this);
        }
        put(index, value);
    }

    /** Same as put(index,DoubleValue.frozen(value)) */
    public final void put(int index, double value) {
        put(index, DoubleValue.frozen(value));
    }

    /**
     * Puts a value by index.
     * The value will be frozen if it isn't already.
     */
    public final void put(int index, Value value) {
        values[index] = value.freeze();
        clearMissing(index);
        try {
            doubleValues()[index] = value.asDouble();
        }
        catch (UnsupportedOperationException e) {
            doubleValues()[index] = Double.NaN; // see getDouble below
        }
    }

    @Override
    public TensorType getType(Reference reference) {
        Integer index = nameToIndex().get(reference.toString());
        if (index == null) return null;
        return values[index].type();
    }

    /** Perform a slow lookup by name */
    @Override
    public Value get(String name) {
        Integer index = nameToIndex().get(name);
        if (index == null) return missingValue;
        return values[index];
    }

    /** Perform a fast lookup by index */
    @Override
    public final Value get(int index) {
        return values[index];
    }

    /** Perform a fast lookup directly of the value as a double. This is faster than get(index).asDouble() */
    @Override
    public final double getDouble(int index) {
        double value = doubleValues()[index];
        if (Double.isNaN(value) && ! isMissing(index))  // NaN is valid as a missing value
            throw new UnsupportedOperationException("Value at " + index + " has no double representation");
        return value;
    }

    /**
     * Creates a clone of this context suitable for evaluating against the same ranking expression
     * in a different thread (i.e, name name to index map, different value set.
     */
    public ArrayContext clone() {
        ArrayContext clone = (ArrayContext)super.clone();
        clone.values = new Value[nameToIndex().size()];
        Arrays.fill(clone.values, missingValue);
        return clone;
    }

}


text:
package com.zeus.visitor;

/**
 * @author xuxingbo
 * @Date 2017/7/4
 */
public class Mouse implements ComputerPart {
    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);
    }
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Fixer\PhpTag;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶2.2.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class NoClosingTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, Tokens $tokens)
    {
        if (count($tokens) < 2 || !$tokens->isMonolithicPhp()) {
            return;
        }

        $closeTags = $tokens->findGivenKind(T_CLOSE_TAG);

        if (empty($closeTags)) {
            return;
        }

        $index = key($closeTags);

        $tokens->removeLeadingWhitespace($index);
        $closeTags[$index]->clear();

        $prevIndex = $tokens->getPrevMeaningfulToken($index);
        if (!$tokens[$prevIndex]->equalsAny(array(';', '}', array(T_OPEN_TAG)))) {
            $tokens->insertAt($prevIndex + 1, new Token(';'));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'The closing `?>` tag MUST be omitted from files containing only PHP.',
            array(new CodeSample("<?php\nclass Sample\n{\n}\n?>"))
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(T_CLOSE_TAG);
    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit6d5f4e40251858cf497adefee93eec0e::getLoader();


text:
#ifndef __LINUX_NETFILTER_CORE_H_
#define __LINUX_NETFILTER_CORE_H_

#include <uapi/linux/netfilter.h>

/* Largest hook number + 1, see uapi/linux/netfilter_decnet.h */
#define NF_MAX_HOOKS 8

#endif


text: kill  `cat ./main.pid`


text:
import React from 'react';
import TextInput from 'ps-react/TextInput';

export default class ExampleError extends React.Component {
  render() {
    return (
      <TextInput
        htmlId="example-optional"
        label="First Name"
        name="firstname"
        required
        error="First name is required"
        onChange={() => {}}
      />
    )
  }
}