text:
Alchemical tools are adventuring items that can prove extremely useful in a variety of situations, including battles, dungeon-delving, or crafting other alchemical items. All of these tools can be made by a character with the [Craft](skills/craft#_craft) (alchemy) skill.

[Alchemical Tools]
| Item | Price | Weight | Craft DC |
| --- | --- | --- | --- |
| Alchemical cement | 5 gp | 2 lbs. | 15 |
| Alchemical glue | 20 gp | 1/2 lb. | 20 |
| Alchemical glue accelerant | 25 gp | — | 25 |
| Alchemical solvent | 20 gp | 1/2 lb. | 20 |
| Armor ointment | 30 gp | 1 lb. | 15 |
| Blackfire clay | 20 gp | 10 lbs. | 20 |
| Bloodblock | 25 gp | — | 25 |
| Buoyant balloon | 10 gp | 1 lb. | 15 |
| Candlerod | 1 gp | 1 lb. | 20 |
| Casting plaster | 5 sp | 5 lbs. | — |
| Chill cream | 15 gp | 1 lb. | 15 |
| Defoliant | 30 gp | — | 25 |
| Embalming fluid | 50 gp | 10 lbs. | 25 |
| Foaming powder | 10 gp | 1 lb. | 20 |
| Glowing ink | 5 gp | — | 15 |
| Impact foam | 25 gp | 1 lb. | 20 |
| Invisible ink (simple) | 2 gp | — | 15 |
| Invisible ink (average) | 10 gp | — | 20 |
| Invisible ink (good) | 25 gp | — | 20 |
| Invisible ink (superior) | 75 gp | — | 25 |
| Light detector | 1 gp | — | 10 |
| Marker dye | 15 gp | 1 lb. | 15 |
| Mending paste | 25 gp | 1/2 lb. | 25 |
| Nushadir | 10 gp | 1 lb. | 20 |
| Rusting powder | 60 gp | — | 30 |
| Scent cloak | 20 gp | 2 lbs. | 20 |
| Smoke pellet | 25 gp | — | 20 |
| Smokestick | 20 gp | 1/2 lb. | 20 |
| Sunrod | 2 gp | 1 lb. | 25 |
| Tindertwig | 1 gp | — | 25 |
| Water purification sponge | 25 gp | 1 lb. | 15 |
| Weapon blanch (adamantine) | 100 gp | 1/2 lb. | 25 |
| Weapon blanch (cold iron) | 20 gp | 1/2 lb. | 20 |
| Weapon blanch (silver) | 5 gp | 1/2 lb. | 20 |

Alchemical Cement

**Price** 5 gp; **Weight** 2 lbs.

You mix this fine gray powder with water and a cubic foot of sand or gravel to form a durable stone-like material. Until it cures, it has the consistency of thick mud, and you must hold it in place (typically with a frame of earth or wood) if you want it to harden in a specific shape. It takes 1d10+10 minutes for the cement to partially cure, gaining hardness 2 and 5 hit points per inch of thickness. After 1d6 hours the cement is fully cured and as hard as true stone.

Alchemical Glue

**Price** 20 gp; **Weight** 1/2 lb.

This glue is stored as two flasks of syrupy liquid. When mixed together and allowed to cure, they form a strong bond. The glue is sufficient to coat 1 square foot of surface, or (because of waste, spills, and inaccurate mixing) up to 20 smaller applications of approximately 2 square inches each. The glue is tacky after 1 minute and fully cured after 1 hour. Pulling apart a large glued surface (at least 1 square foot) requires a DC 20 Strength check for tacky glue or DC 25 for cured glue. Pulling apart a small glued surface (anything less than 1 square foot) is a DC 15 Strength check for tacky glue or DC 20 for cured glue.

Alchemical glue accelerant

**Price** 25 gp; **Weight** —

This tiny dropper contains a liquid that speeds up the cure time of alchemical glue. Applying the accelerant is a standard action. Accelerated glue is tacky after 1 round and fully cured in 1 minute. The dropper contains 20 doses; each dose is sufficient to cure one small application of alchemical glue. The entire dropper must be used to cure a full square foot of glue.

Alchemical Solvent

**Price** 20 gp; **Weight** 1/2 lb.

This bubbling purple gel eats through adhesives. Each vial can cover a single 5-foot square. It destroys most normal adhesives (such as tar, tree sap, or glue) in a single round but takes 1d4+1 rounds to deal with more powerful adhesives (alchemical glue, tanglefoot bags, spider webbing, and so on). It has no affect on fully magical adhesives, such as _ [sovereign glue](magicItems/wondrousItems#_sovereign-glue)_.

Armor Ointment

**Price** 30 gp; **Weight** 1 lb.

This thick lubricant makes the joints of armor move more freely. Applying the ointment takes 1 minute and reduces your armor's armor check penalty by 1 (to a minimum of –1) for 8 hours.

Blackfire Clay

**Price** 20 gp; **Weight** 10 lbs.

This pliant black clay is always pleasantly warm to the touch. Working blackfire clay in your hands for a full round causes the clay to grow much warmer, granting you a +4 alchemical bonus on saving throws made to resist cold weather. You can combine five blocks of clay over the course of a minute to produce a source of warmth equivalent to a small campfire, allowing you to heat a campsite and cook food.

Blackfire clay only produces heat, never light, smoke, or odor. The clay emits warmth for 1 hour before hardening into an unusable lump. A newly created brick of blackfire clay is composed of 10 blocks.

Bloodblock

**Price** 25 gp; **Weight** —

This gooey, pinkish substance helps treat wounds. Using a dose gives you a +5 alchemical bonus on [Heal](skills/heal#_heal) checks for providing first aid, treating wounds made by caltrops or similar objects, or treating deadly wounds. A dose of bloodblock ends a bleed effect as if you had made a DC 15 [Heal](skills/heal#_heal) check. When treating deadly wounds, using a dose of bloodblock counts as one use of a healer's kit (and grants the +5 bonus stated above).

Buoyant Balloon

**Price** 10 gp; **Weight** 1 lb.

This fist-sized alchemically treated animal bladder is tightly sealed around a small wooden grip. By giving the handle a sharp twist you break a tiny glass ampoule just inside the bladder, filling the bag with buoyant gas and causing it to swell into a 3-foot-diameter sphere. Inflating the balloon is a move action. Once filled, the balloon floats upward at a speed of 60 feet per round. The balloon can lift up to 20 pounds of weight as it rises, though carrying more than 10 pounds reduces its speed to 30 feet per round. Multiple balloons attached to a single object add their carrying capacities together when determining how much weight they can lift. If a balloon is not held or bound in place in some manner, it continues to rise until it reaches a height of 600 feet, or until 10 minutes have passed, after which it pops or deflates and is destroyed.

Candlerod

**Price** 1 gp; **Weight** 1 lb.

Similar to but weaker than a sunrod, this stick glows like a candle when struck and lasts for 12 hours.

Casting Plaster

**Price** 5 sp; **Weight** 5 lbs.

This white, dry powder mixes with water to form a paste, which hardens over the course of an hour to create a solid material. It can be used to make casts of footprints or carvings, fill in gaps or cracks in walls, or (if applied over a cloth wrapping) create a cast for a broken bone. Hardened plaster has hardness 1 and 5 hit points per inch of thickness. A 5-pound clay pot of plaster can cover about 5 square feet of flat space to a depth of 1 inch, five Medium forearm or lower-leg casts, two Medium full-arm or full-leg casts, or twice as many casts for a Small creature.

Chill Cream

**Price** 15 gp; **Weight** 1 lb.

This sticky light blue paste grows pleasantly cool to the touch whenever it is exposed to light. Spreading a dose on your face and hands takes a full-round action and grants you a +2 alchemical bonus on saves to resist hot weather. In areas of bright light this bonus increases to +4, while in areas of dim light or darkness it is negated. A dose of chill cream lasts for 1 hour after being applied. A newly crafted bottle of chill cream holds 5 doses.

Defoliant

**Price** 30 gp; **Weight** —

This milky fluid can be mixed with water to quickly kill light and medium vegetation. One flask of defoliant kills light brush and small trees in 50 5-foot squares. Light vegetation (anything but trees) dies within 1 hour and can be cleared at a rate of 10 minutes per 5-foot square (representing uprooting dead plants and breaking stumps into gravel-sized pieces), leaving barren ground. Medium vegetation (anything but massive trees) dies in 2 hours and can be cleared at a rate of 1 hour per 5-foot square. Massive trees can usually survive a single dose of defoliant, and using defoliant doesn't make clearing them any easier. Defoliant can be used as a splash weapon against plant creatures. A direct hit with the undiluted fluid deals 1d6 hit points of damage, 1 point of Strength damage, and 1 point of Constitution damage (Fortitude DC 20 negates the Strength and Constitution damage); plant creatures within 5 feet of the target take 1 hit point of damage.

Embalming Fluid

**Price** 50 gp; **Weight** 10 lbs.

This fluid is used to preserve corpses, whether for later dissection, taxidermy, necromancy, or magic such as _ [raise dead](spells/raiseDead#_raise-dead)_. Embalming fluid is technically a poison, and using it makes a corpse unpalatable to most animals and vermin, though corpse-eating undead don't mind the taste. Treating a corpse with embalming fluid takes 1 hour and a successful DC 25 [Heal](skills/heal#_heal) check. The embalmed corpse decays at half the normal rate (each day dead counts as half a day for the purpose of _ [raise dead](spells/raiseDead#_raise-dead)_).

Foaming Powder

**Price** 10 gp; **Weight** 1 lb.

When you add this 1-pound bag of green powder to a gallon of water, the two combine to form 50 cubic feet of thick green foam. Unless contained, in 1 round the foam fills a 5-foot-square to a depth of 2 feet. When multiple pounds of powder are used, the foam expands at a rate of one 5-foot square per round. Ground covered with the foam is treated as difficult terrain, but is otherwise harmless. After 1 hour, the foam hardens to form a buoyant material roughly the density of honeycomb. The cured foam is easy to cut, with hardness 0 and 5 hit points per foot of thickness. The cured foam breaks down over a few days, and even faster if exposed to water. Casting _ [transmute mud to rock](spells/transmuteMudToRock#_transmute-mud-to-rock)_ on uncured foam converts it into a soft, pumice-like stone (hardness 2, 5 hit points per inch of thickness).

Glowing Ink

**Price** 5 gp; **Weight** —

Often extracted from phosphorescent insects, tiny marine plants, or subterranean fungi, glowing ink emits a faint but steady light (typically red or green) that allows you to read it in normal darkness—this includes darkness created by spells like _ [darkness](spells/darkness#_darkness)_, but not the supernatural darkness created by _ [deeper darkness](spells/deeperDarkness#_deeper-darkness)_. If there is glowing ink on an object, you have a +2 bonus on [Perception](skills/perception#_perception) checks to locate it. Mixing glowing ink with marker dye makes the dye glow in the dark until it fades.

Impact Foam

**Price** 25 gp; **Weight** 1 lb.

This milky white liquid bubbles into a 1-foot-thick semisolid sheet of foam when splashed across the ground. You can spend a minute to apply a flask of impact foam to a 10-foot-radius area, or you can throw the flask as a splash weapon. The foam does not interfere with movement, but reacts strongly to sudden force. A creature that falls onto a sheet of impact foam ignores the first 1d6 points of falling damage and converts the second 1d6 points of falling damage into nonlethal damage. A sheet of impact foam dissolves after 10 minutes or when exposed to at least a gallon of water.

Invisible Ink

| Type | Price | Weight |
| --- | --- | --- |
| Simple | 2 gp | — |
| Average | 10 gp | — |
| Good | 25 gp | — |
| Superior | 75 gp | — |

Invisible ink is a staple of spies, rebels, and secret societies everywhere. Messages written with invisible ink only become visible under specific circumstances. Revealing the secret message with the proper triggering agent is a full-round action per page of text. A successful [Craft](skills/craft#_craft) (alchemy) check reveals the message without the proper trigger and takes 1 hour (the DC varies by ink quality).

_Simple_: This ink is keyed to a single, fairly common trigger, such as heat or vinegar (DC 20 to reveal without the trigger).

_Average_: This ink is keyed to either two common triggers or one uncommon trigger, such as blood or acid (DC 25 to reveal without the trigger).

_Good_: This ink is keyed to either two uncommon triggers or one rare trigger, such as a specific vintage of wine or a specific kind of monster's blood (DC 30 to reveal without the trigger).

_Superior_: This ink is keyed to either two rare triggers or one unique trigger, such as the blood of a specific person (DC 35 to reveal without the trigger).

Light Detector

**Price** 1 gp; **Weight** —

This hand-sized metal plate is covered with a thin layer of light-sensitive transparent paste. If exposed to light, the paste darkens and becomes opaque, depending on the amount of light. Bright light causes it to fully darken in 1 round, normal light in 3 rounds, and dim light in 10 rounds. It is mainly used by creatures with darkvision to determine whether creatures carrying light have recently passed through an area. The plate is sold wrapped in a thick black cloth to prevent accidental light exposure from ruining the plate.

Marker Dye

**Price** 15 gp; **Weight** 1 lb.

This dye (available in several colors) creates an obvious stain wherever it is splashed. Washing has no effect for the first 72 hours (though magic can erase it), but it fades completely after 2 weeks. You can throw it as a splash weapon.

Mending Paste

**Price** 25 gp; **Weight** 1/2 lb.

You can use this smelly, silvery paste to temporarily repair metal objects. It is sold in a sealed flask and reacts with air, turning solid in 1d6+4 minutes. You must make an appropriate DC 20 [Craft](skills/craft#_craft) check to repair a metal item with the broken condition; success means the object loses the broken condition but gains the fragile condition (see page 22). Increase the DC by +5 if the broken object is a magic item or by +5 if it is a firearm (add both modifiers if the item is a magical firearm). If the check fails, the mending paste is consumed but you may try again with another flask or conventional repair methods.

Nushadir

**Price** 10 gp; **Weight** 1 lb.

This reagent is often stored in the form of small, salty pellets in a dry container, though it can also be mixed with a flask of water and carried that way. Nushadir neutralizes acid; a vial of pellets or a flask of nushadir-water is enough to render a cubic foot of acid safe to touch in 1 minute, though this is usually too slow to prevent damage from a thrown vial of acid or the contents of a large monster's gullet. Nushadir vapors are slightly irritating to the eyes, nose, and mouth, causing nausea for 1d4 rounds after close exposure (Fortitude DC 10 negates).

Rusting Powder

**Price** 60 gp; **Weight** —

This flaky brown powder derived from rust monster fluids causes iron and similar metals to corrode and fall apart. If you apply a dose of rusting powder to a metal lock or trap as part of using the [Disable Device](skills/disableDevice#_disable-device) skill, you gain a +5 alchemical bonus to open the lock or disable the trap, but there is a 75% chance that the mechanism is destroyed and cannot be used afterward. If the check fails, the mechanism is destroyed. A destroyed lock cannot be unlocked (but still counts as locked for the purpose opening the locked object). A destroyed trap mechanism immediately triggers the trap. If you fail the DC by 5 or more, the powder also lands on an object in your square (including possibly your armor or weapon), dealing 5 hit points of damage to the object.

Rusting powder is sold in a paper tube; you apply it by tearing the ends off the tube and blowing the flakes into the target device. Rusting powder does not affect gold, silver, copper, bronze, brass, or mithral, but easily affects iron, steel, and adamantine.

Scent Cloak

**Price** 20 gp; **Weight** 2 lbs.

This collection of coarsely ground spices, seeds, musk, and alchemical reagents are meant to be rubbed into your skin and clothes in order to override your scent, increasing the DC of tracking you by scent by +10 for 24 hours. Because you still have a smell, creatures with scent can still detect and pinpoint you if you are cloaked; they just can't identify your smell as something unique. Washing for 1 full round removes the scent cloak.

Smoke Pellet

**Price** 25 gp; **Weight** —

This small clay sphere contains two alchemical substances separated by a thin barrier. When you break the sphere, the substances mingle and fill a 5-foot square with a cloud of foul but harmless yellow smoke. The smoke pellet acts as a smokestick, except the smoke only lasts for 1 round before dispersing. You may throw a smoke pellet as a ranged touch attack with a range increment of 10 feet.

Smokestick

**Price** 20 gp; **Weight** 1/2 lb.

This alchemically treated wooden stick instantly creates thick, opaque smoke when burned. The smoke fills a 10-foot cube (treat the effect as a _ [fog cloud](spells/fogCloud)_ spell, except that a moderate or stronger wind dissipates the smoke in 1 round). The stick is consumed after 1 round, and the smoke dissipates naturally after 1 minute.

Sunrod

**Price** 2 gp; **Weight** 1 lb.

This 1-foot-long, gold-tipped iron rod glows brightly when struck (a standard action). It sheds normal light in a 30-foot radius and increases the light level by one step for an additional 30 feet beyond that area (darkness becomes dim light and dim light becomes normal light). A sunrod does not increase the light level in normal light or bright light. It glows for 6 hours, after which the gold tip is burned out and worthless.

Tindertwig

**Price** 1 gp; **Weight** —

The alchemical substance on the end of this small, wooden stick ignites when struck against a rough surface (a move action). Creating a flame with a tindertwig is much faster than creating a flame with tinder and a flint and steel or magnifying glass. Lighting a torch with a tindertwig is a standard action rather than a full-round action, and lighting any other fire with one is at least a standard action. A tindertwig burns for 1d2 rounds and sheds light as a candle. Tindertwigs are waterproof, but must be dried before you can strike them.

Water Purification sponge

**Price** 25 gp; **Weight** 1 lb.

This fist-sized blue sponge absorbs up to 1 pint of water; squeezing the water out of the sponge filters and purifies it, making it safe for drinking, washing, and similar activities. Filling and emptying the sponge is a full-round action. The filtration is enough to remove mundane impurities and common diseases, but does nothing to protect against poisons, magic, and other exotic threats. Each sponge can cleanse 25 pints of water before deteriorating and becoming useless.

Weapon Blanch

| Type | Price | Weight |
| --- | --- | --- |
| Adamantine | 100 gp | 1/2 lb. |
| Cold iron | 20 gp | 1/2 lb. |
| Silver | 5 gp | 1/2 lb. |

These silver, alchemical powders have a gritty consistency, appearing at first glance to be simple metal shavings. When poured on a weapon and placed over a hot flame for a full round, however, they melt and form a temporary coating on the weapon. The blanching gives the weapon the ability to bypass one kind of material-based damage reduction, such as adamantine, cold iron, or silver. The blanching remains effective until you make a successful attack with the weapon. Each dose of blanching can coat one weapon or up to 10 pieces of ammunition. Only one kind of weapon blanch can be on a weapon at one time, though a weapon made of one special material (such as adamantine) can have a different material blanch (such as silver), and counts as both materials for the first successful hit.


text:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment_flight"
    android:name="net.oldervoll.flightschedule.FlightFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.oldervoll.flightschedule.FlightFragment"
    tools:layout="@android:layout/list_content" />

redpajama_set_name: RedPajamaGithub


text:
/* (c) 2014 Thomas Smits */
/**
 * This script is injected by the extension into the web page to extract data
 * and transfer data back.
 *
 * Due to security restrictions the communication between this script and
 * the extension can only be performed using messages.
 */
$(function() {

    // possible selectors pointing to the form field with the user name;
    // most specific has to be listed first
    var userSelectors = [
        "#Email",
        "#username",
        "#user",
        "#login_field",
        "[name*='email']",
        "[name='login']",
        "[name='login_form[username]']",
        "[name*='login_field']",
        "[name*='username']",
        "[name*='user']"
    ];

    // possible selectors pointing to the form field with the password;
    // most specific has to be listed first
    var passwordSelectors = [
        "[name*='password']",
        "[type='password']"
    ];

    // Retrieve information about the page
    var location = window.location;
    var userField = findElement(userSelectors);
    var passwordField = findElement(passwordSelectors);

    /**
     * Searches a list of selectors to find a specific element.
     *
     * @param selectors selectors to be tested one after the other
     * @returns {jQuery} the found element wrapped as jQuery object
     */
    function findElement(selectors) {
        var i, field;

        for (i = 0; i < selectors.length; i++) {
            field = $(selectors[i]);
            if (field.length) {
                return field;
            }
        }

        // nothing found, return an object with a val() function to
        // mock a jQuery element
        return {
            val: function(x) {
                return "";
            }
        };
    }

    // send data about url and user name to the extension
    chrome.extension.sendMessage(
        {
            url: location,
            user: userField.val()
        }
    );

    // Add a message listener to recieve messages from the extension
    chrome.extension.onMessage.addListener(
        function(request, sender, sendResponse) {
            if (!sender.tab) {
                userField.val(request.user);
                passwordField.val(request.password);
            }
        });
});


text:
package com.netflix.metacat.main.services;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.TableDto;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Table service.
 */
public interface TableService extends MetacatService<TableDto> {
    /**
     * Deletes the table. Returns the table metadata of the table deleted.
     * @param name qualified name of the table to be deleted
     * @param isMView true if this table is created for a mview
     * @return Returns the deleted table
     */
    TableDto deleteAndReturn(QualifiedName name, boolean isMView);

    /**
     * Returns the table with the given name.
     * @param name qualified name of the table
     * @param getTableServiceParameters  get table parameters
     * @return Returns the table with the given name
     */
    Optional<TableDto> get(QualifiedName name, GetTableServiceParameters getTableServiceParameters);

    /**
     * Rename the table from oldName to newName.
     * @param oldName old qualified name of the existing table
     * @param newName new qualified name of the table
     * @param isMView true, if the object is a view
     */
    void rename(QualifiedName oldName, QualifiedName newName, boolean isMView);

    /**
     * Copies the table metadata from source table name to target table targetName.
     * @param name qualified name of the source table
     * @param targetName qualified name of the target table
     * @return Returns the copied table
     */
    TableDto copy(QualifiedName name, QualifiedName targetName);

    /**
     * Copies the table metadata from source table name to target table targetName.
     * @param tableDto source table
     * @param targetName qualified name of the target table
     * @return Returns the copied table
     */
    TableDto copy(TableDto tableDto, QualifiedName targetName);

    /**
     * Saves the user metadata for the given table.
     * @param name qualified name of the table
     * @param definitionMetadata user definition metadata json
     * @param dataMetadata user data metadata json
     */
    void saveMetadata(QualifiedName name, ObjectNode definitionMetadata, ObjectNode dataMetadata);

    /**
     * Returns a list of qualified names of tables that refers to the given uri. If prefixSearch is true,
     * it will consider the uri has a prefix and so it does not do a exact match.
     * @param uri uri/location
     * @param prefixSearch if false, the method looks for exact match for the uri
     * @return list of table names
     */
    List<QualifiedName> getQualifiedNames(String uri, boolean prefixSearch);

    /**
     * Returns a map of list of qualified names of tables that refers to the given uri.
     * If prefixSearch is true, it will consider the uri has a prefix and so it does not do a exact match.
     * @param uris uris/locations
     * @param prefixSearch if false, the method looks for exact match for the uri
     * @return Map of list of table names
     */
    Map<String, List<QualifiedName>> getQualifiedNames(List<String> uris, boolean prefixSearch);

    /**
     * Returns a list of qualified names of tables that matches the given filter.
     * @param name          catalog name
     * @param parameters    parameters used to get the table names
     * @return list of table names
     */
    List<QualifiedName> getQualifiedNames(QualifiedName name, GetTableNamesServiceParameters parameters);
}


text:
require 'net/ssh'

# LXC Version

class Ctnmgr
  attr_accessor :host, :name, :pass
  def initialize(host, name, pass)
    @host = host
    @name = name
    @pass = pass
  end

  def launch_vm(name)
    result = ''
    Net::SSH.start(@host, @name, :password => @pass) do |ssh|
      cmds = [
        "sudo /usr/local/go/bin/go run ./bin/nanda-lxc-clone.go --name ubuntu --newname #{name} --backend dir",
        "sudo /usr/local/go/bin/go run ./bin/nanda-lxc-start.go --name #{name}"
        ]

      ssh.exec!(makecommand(cmds)) do |channel, stream, data|
        result << data if stream == :stdout
        puts data
      end
    end
    { ip: result }
  end

  def start_vm(name)
    Net::SSH.start(@host, @name, :password => @pass) do |ssh|
      ssh.exec makecommand(["sudo lxc-start -n #{name} -d"]) do |ch, stream, data|
        if stream == :stderr
          puts "ERROR: #{data}"
        end
      end
    end
  end

  def stop_vm(name)
    Net::SSH.start(@host, @name, :password => @pass) do |ssh|
      ssh.exec makecommand(["sudo lxc-stop -n #{name}"]) do |ch, stream, data|
        if stream == :stderr
          puts "ERROR: #{data}"
        end
      end
    end
  end

  def destroy_vm(name)
    Net::SSH.start(@host, @name, :password => @pass) do |ssh|
      ssh.exec makecommand(["sudo lxc-destroy -n #{name}"]) do |ch, stream, data|
        if stream == :stderr
          puts "ERROR: #{data}"
        end
      end
    end
  end

  def generate_key()
    key = {}
    result = ""
    filename = ""
    Net::SSH.start(@host, @name, :password => @pass) do |ssh|
      filename = Digest::SHA1.hexdigest ('nandacloud' + Time.now.to_s)
      comment = 'comment'
      cmd = "ssh-keygen -q -t rsa -C '%s' -N '' -f %s >/dev/null && cat #{filename}.pub >> ~/.ssh/authorized_keys && cat #{filename}" %
             [comment, filename]

      ssh.exec cmd do |_ch, stream, data|
        if stream == :stderr
          puts "ERROR: #{data}"
        else
          puts data
          result = data
        end
      end
    end
    key[:result] = result
    key[:name] = filename
    key
  end

  private

  def makecommand(cmds)
    c = []
    c.push 'mkdir -p ~/golib'
    c.push 'export GOROOT=/usr/local/go'
    c.push 'export GOPATH=/home/#{@name}/golib'
    c.push 'export PATH=$PATH:/usr/local/go/bin'

    cmds.each do |cmd|
      c.push cmd
    end
    c.join(' && ')
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. trimest. Soc. mycol. Fr. 96(3): 276 (1980)

#### Original name
Amanita aspera f. lactella E.-J. Gilbert ex Bertault

### Remarks
null


text:
package gov.nasa.ensemble.core.model.plan.temporal.edge.impl;

import gov.nasa.ensemble.emf.transaction.IConsistencyMaintenanceListener;

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

import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.ResourceSetChangeEvent;
import org.eclipse.emf.transaction.TransactionalEditingDomain;

public class TemporalEdgeManagerConsistencyListener implements IConsistencyMaintenanceListener {

	@Override
	public Command createConsistencyMaintenanceCommand(ResourceSetChangeEvent event) {
		final TemporalEdgeManager manager = getTemporalEdgeManager(event);
		if (manager != null) {
			final List<Notification> filtered = new ArrayList<Notification>();
			for (Notification notification : event.getNotifications()) {
				if (manager.isImportant(notification)) {
					filtered.add(notification);
				}
			}
			if (!filtered.isEmpty()) {
				return new TemporalEdgeManagerConsistencyCommand(event.getEditingDomain(), "TemporalEdgeManagerConsistency", manager, filtered);
			}
		}
		return null;
	}

	public TemporalEdgeManager getTemporalEdgeManager(ResourceSetChangeEvent event) {
		for (Resource resource : event.getEditingDomain().getResourceSet().getResources()) {
			for (EObject eObject : resource.getContents()) {
				if (eObject instanceof TemporalEdgeManager) {
					return (TemporalEdgeManager) eObject;
				}
			}
		}
		return null;
	}

	private static final class TemporalEdgeManagerConsistencyCommand extends RecordingCommand {

		private final TemporalEdgeManager manager;
		private final List<Notification> filtered;

		private TemporalEdgeManagerConsistencyCommand(TransactionalEditingDomain domain, String label, TemporalEdgeManager manager, List<Notification> filtered) {
			super(domain, label);
			this.manager = manager;
			this.filtered = filtered;
		}

		@Override
		protected void doExecute() {
			manager.processNotifications(filtered);
		}

	}

}


text:
<?php

namespace Sonata\MediaBundle\Block;

use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Validator\ErrorElement;

use Sonata\PageBundle\Model\BlockInterface;
use Sonata\PageBundle\Model\PageInterface;
use Sonata\PageBundle\Block\BaseBlockService;

use Sonata\MediaBundle\Model\GalleryManagerInterface;
use Sonata\MediaBundle\Model\GalleryInterface;
use Sonata\MediaBundle\Model\MediaInterface;

use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Form;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Sonata\PageBundle\CmsManager\CmsManagerInterface;

/**
 * PageExtension
 *
 * @author     Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class GalleryBlockService extends BaseBlockService
{
    protected $galleryAdmin;

    protected $galleryManager;

    /**
     * @param $name
     * @param \Symfony\Component\Templating\EngineInterface $templating
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     * @param \Sonata\MediaBundle\Model\GalleryManagerInterface $galleryManager
     */
    public function __construct($name, EngineInterface $templating, ContainerInterface $container, GalleryManagerInterface $galleryManager)
    {
        parent::__construct($name, $templating);

        $this->galleryManager = $galleryManager;
        $this->container      = $container;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'Gallery';
    }

    /**
     * @return \Sonata\MediaBundle\Provider\Pool
     */
    public function getMediaPool()
    {
        return $this->container->get('sonata.media.pool');
    }

    /**
     * @return \Sonata\AdminBundle\Admin\AdminInterface
     */
    public function getGalleryAdmin()
    {
        if (!$this->galleryAdmin) {
            $this->galleryAdmin = $this->container->get('sonata.media.admin.gallery');
        }

        return $this->galleryAdmin;
    }

    /**
     * @return array
     */
    public function getDefaultSettings()
    {
        return array(
            'gallery'  => false,
            'title'    => false,
            'context'  => false,
            'format'   => false,
            'pauseTime' => 3000,
            'animSpeed' => 300,
            'startPaused' => false,
            'directionNav' => true,
            'progressBar' => true,
        );
    }

    /**
     * @param \Sonata\PageBundle\CmsManager\CmsManagerInterface $manager
     * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
     * @param \Sonata\PageBundle\Model\BlockInterface $block
     */
    public function buildEditForm(CmsManagerInterface $manager, FormMapper $formMapper, BlockInterface $block)
    {
        $contextChoices = array();

        foreach ($this->getMediaPool()->getContexts() as $name => $context) {
            $contextChoices[$name] = $name;
        }

        $gallery = $block->getSetting('galleryId');

        $formatChoices = array();

        if ($gallery instanceof GalleryInterface) {

            $formats = $this->getMediaPool()->getFormatNamesByContext($gallery->getContext());

            foreach ($formats as $code => $format) {
                $formatChoices[$code] = $code;
            }
        }

        // simulate an association ...
        $fieldDescription = $formMapper->getAdmin()->getModelManager()->getNewFieldDescriptionInstance($this->getGalleryAdmin()->getClass(), 'media' );
        $fieldDescription->setAssociationAdmin($this->getGalleryAdmin());
        $fieldDescription->setAdmin($formMapper->getAdmin());
        $fieldDescription->setOption('edit', 'list');
        $fieldDescription->setAssociationMapping(array('fieldName' => 'gallery', 'type' => \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_ONE));

        $builder = $formMapper->create('galleryId', 'sonata_type_model', array(
            'sonata_field_description' => $fieldDescription,
            'class'             => $this->getGalleryAdmin()->getClass(),
            'model_manager'     => $this->getGalleryAdmin()->getModelManager()
        ));

        $formMapper->add('settings', 'sonata_type_immutable_array', array(
            'keys' => array(
                array('title', 'text', array('required' => false)),
                array('context', 'choice', array('required' => true, 'choices' => $contextChoices)),
                array('format', 'choice', array('required' => count($formatChoices) > 0, 'choices' => $formatChoices)),
                array($builder, null, array()),
                array('pauseTime', 'number', array()),
                array('animSpeed', 'number', array()),
                array('startPaused', 'sonata_type_boolean', array()),
                array('directionNav', 'sonata_type_boolean', array()),
                array('progressBar', 'sonata_type_boolean', array()),
            )
        ));
    }

    /**
     * @param \Sonata\PageBundle\CmsManager\CmsManagerInterface $manager
     * @param \Sonata\AdminBundle\Validator\ErrorElement $errorElement
     * @param \Sonata\PageBundle\Model\BlockInterface $block
     */
    public function validateBlock(CmsManagerInterface $manager, ErrorElement $errorElement, BlockInterface $block)
    {

    }

    /**
     * @param \Sonata\PageBundle\CmsManager\CmsManagerInterface $manager
     * @param \Sonata\PageBundle\Model\BlockInterface $block
     * @param \Sonata\PageBundle\Model\PageInterface $page
     * @param null|\Symfony\Component\HttpFoundation\Response $response
     * @return string
     */
    public function execute(CmsManagerInterface $manager, BlockInterface $block, PageInterface $page, Response $response = null)
    {
        // merge settings
        $settings = array_merge($this->getDefaultSettings(), $block->getSettings());

        $gallery = $settings['galleryId'];

        return $this->renderResponse('SonataMediaBundle:Block:block_gallery.html.twig', array(
            'gallery'   => $gallery,
            'block'     => $block,
            'settings'  => $settings,
            'elements'  => $gallery ? $this->buildElements($gallery) : array(),
        ), $response);
    }

    /**
     * @param \Sonata\PageBundle\CmsManager\CmsManagerInterface $manager
     * @param \Sonata\PageBundle\Model\BlockInterface $block
     */
    public function load(CmsManagerInterface $manager, BlockInterface $block)
    {
        $media = $block->getSetting('galleryId', null);

        if ($media) {
            $media = $this->galleryManager->findOneBy(array('id' => $media));
        }

        $block->setSetting('galleryId', $media);
    }

    /**
     * @param \Sonata\PageBundle\Model\BlockInterface $block
     */
    public function prePersist(BlockInterface $block)
    {
        $block->setSetting('galleryId', is_object($block->getSetting('galleryId')) ? $block->getSetting('galleryId')->getId() : null);
    }

    /**
     * @param \Sonata\PageBundle\Model\BlockInterface $block
     */
    public function preUpdate(BlockInterface $block)
    {
        $block->setSetting('galleryId', is_object($block->getSetting('galleryId')) ? $block->getSetting('galleryId')->getId() : null);
    }

    public function getStylesheets($media)
    {
        return array(
            '/bundles/sonatamedia/nivo-gallery/nivo-gallery.css'
        );
    }

    public function getJavacripts($media)
    {
        return array(
            '/bundles/sonatamedia/nivo-gallery/jquery.nivo.gallery.js'
        );
    }

    /**
     * @param \Sonata\MediaBundle\Model\GalleryInterface $gallery
     * @return array
     */
    private function buildElements(GalleryInterface $gallery)
    {
        $elements = array();
        foreach ($gallery->getGalleryHasMedias() as $galleryHasMedia) {
            if (!$galleryHasMedia->getEnabled()) {
                continue;
            }

            $type = $this->getMediaType($galleryHasMedia->getMedia());

            if (!$type) {
                continue;
            }

            $elements[] = array(
                'title'     => $galleryHasMedia->getMedia()->getName(),
                'caption'   => $galleryHasMedia->getMedia()->getDescription(),
                'type'      => $type,
                'media'     => $galleryHasMedia->getMedia(),
            );
        }

        return $elements;
    }

    /**
     * @param \Sonata\MediaBundle\Model\MediaInterface $media
     */
    private function getMediaType(MediaInterface $media)
    {
        if ($media->getContentType() == 'video/x-flv') {
            return 'video';
        } elseif(substr($media->getContentType(), 0, 5) == 'image') {
            return 'image';
        }

        return false;
    }
}


text:
from google.cloud import translate_v3

async def sample_create_glossary():
    # Create a client
    client = translate_v3.TranslationServiceAsyncClient()

    # Initialize request argument(s)
    glossary = translate_v3.Glossary()
    glossary.name = "name_value"

    request = translate_v3.CreateGlossaryRequest(
        parent="parent_value",
        glossary=glossary,
    )

    # Make the request
    operation = client.create_glossary(request=request)

    print("Waiting for operation to complete...")

    response = await operation.result()

    # Handle the response
    print(response)

# [END translate_generated_translate_v3_TranslationService_CreateGlossary_async]


text:
import proto  # type: ignore

__protobuf__ = proto.module(
    package="google.ads.googleads.v12.enums",
    marshal="google.ads.googleads.v12",
    manifest={"TargetImpressionShareLocationEnum",},
)

class TargetImpressionShareLocationEnum(proto.Message):
    r"""Container for enum describing where on the first search
    results page the automated bidding system should target
    impressions for the TargetImpressionShare bidding strategy.

    """

    class TargetImpressionShareLocation(proto.Enum):
        r"""Enum describing possible goals."""
        UNSPECIFIED = 0
        UNKNOWN = 1
        ANYWHERE_ON_PAGE = 2
        TOP_OF_PAGE = 3
        ABSOLUTE_TOP_OF_PAGE = 4

__all__ = tuple(sorted(__protobuf__.manifest))


text:
// PACKAGES
import React, { Component } from 'react'
import TransitionGroup from 'react-addons-transition-group'
import { TweenMax, Power2, TimelineLite } from "gsap"
//CSS
import "./experience.css"
// COMPONENTS
import ExperienceItem from "./experience-item.js"
import { powerReviewsData, trilogyNWData, devBootcampExpData, cciData } from "./experience-data.js"

let powerReviews = powerReviewsData()
let trilogyNW = trilogyNWData()
let devBootcampExp = devBootcampExpData()
let cci = cciData()

class Experience extends Component {

	componentDidMount(callback) {
		// TweenMax.fromTo(".dbc-drift", 5, {y: -20}, {y: 0})
		TweenMax.fromTo(".pr-drift", 2, {opacity: 0}, {opacity: 1})
		// TweenMax.fromTo(".su-drift", 5, {y: 5}, {y: 0})
		TweenMax.fromTo(".trilogy-drift", 2, {opacity: 0}, {opacity: 1})
		// TweenMax.fromTo(".msu-drift", 5, {y: 20}, {y: 0})
		TweenMax.fromTo(".dev-drift", 2, {opacity: 0}, {opacity: 1})
		TweenMax.fromTo(".cci-drift", 2, {opacity: 0}, {opacity: 1})
	}

    render () {
		return (

					<ExperienceItem {...powerReviews} />

				{/*  */}

					<ExperienceItem {...trilogyNW} />

				{/*  */}

					<ExperienceItem {...devBootcampExp} />

				{/*  */}

					<ExperienceItem {...cci} />

		)
    }
}

export default Experience

// componentWillEnter (callback) {
//   const el = this.container;
//   TweenMax.fromTo(el, 0.8, {y: 300, opacity: 0}, {y: 0, opacity: 1, onComplete: callback});
// }

// componentWillLeave (callback) {
//   const el = this.container;
//   TweenMax.fromTo(el, 0.5, {y: 0, opacity: 1}, {y: 300, opacity: 0, onComplete: callback});
// }

//
 this.container = c}>


text:
ALTER TABLE publicmapping.redistricting_legislativebody ADD COLUMN sort_key integer CHECK (sort_key >= 0);
UPDATE publicmapping.redistricting_legislativebody SET sort_key = id;
ALTER TABLE publicmapping.redistricting_legislativebody ALTER COLUMN sort_key SET NOT NULL;


text:
<resources>
    <string name="app_name">hpb</string>
</resources>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.swin.luchen</groupId>
  <artifactId>ssc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>ssc</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
    	<groupId>org.jgrapht</groupId>
    	<artifactId>jgrapht-core</artifactId>
    	<version>0.9.2</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
        <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.1.1</version>
        <configuration>
             <mainClass>com.swin.luchen.ssc.App</mainClass>
        </configuration>
        </plugin>
    </plugins>
   </build>

</project>


text:
/**
 * Console command loop
 */
package kernel

/**
 * @author ShiZhan
 * Console command loop
 */
object Console {
  import Engine._

  private val usage = """ [Console Usage]
  help        print this message
  status      show program status
  time        show current time
  query       enter SPARQL/read SPARQL file to do query
  update      enter SPARQL/read SPARQL file to do update
  tdbinfo     Jena tdbinfo utility
  tdbloader   Jena tdbloader utility
  tdbquery    Jena tdbquery utility
  tdbupdate   Jena tdbupdate utility
  ! <command> run shell command
  exit        exit console"""
  private val title = "Input Jena command here ..."
  private val prompt = "# "

  def run(): Unit = {
    println(title)
    print(prompt)
    for (line <- io.Source.stdin.getLines) {
      line.split(" ").toList match {
        case "exit" :: Nil => { shutdown; return }
        case "help" :: Nil => println(usage)
        case "status" :: Nil => println(status)
        case "time" :: Nil => println(helper.DateTime.get)
        case "query" :: qArgs => doQuery(qArgs)
        case "update" :: uArgs => doUpdate(uArgs)
        case "tdbinfo" :: Nil => tdbinfo
        case "tdbloader" :: modelFile :: Nil => tdbloader(modelFile)
        case "tdbquery" :: sparqlFile :: Nil => tdbquery(sparqlFile)
        case "tdbupdate" :: sparqlFile :: Nil => tdbupdate(sparqlFile)
        case "!" :: cArgs =>
          import sys.process._
          cArgs.toSeq.lineStream_!.foreach(println)
        case "" :: Nil =>
        case _ => println(s"Unrecognized command: [$line]")
      }
      print(prompt)
    }
  }
}


text:
package net.chocolapod.lwjgfont.packager;

import static net.chocolapod.lwjgfont.packager.TestResources.CLASS_MOSAMOSAFONT_8;
import static net.chocolapod.lwjgfont.packager.TestResources.ENTRY_MOSAMOSAFONT_8;
import static net.chocolapod.lwjgfont.packager.TestResources.IMAGE_MOSAMOSAFONT_8;
import static net.chocolapod.lwjgfont.packager.TestResources.CLASS_MOSAMOSAFONT_9;
import static net.chocolapod.lwjgfont.packager.TestResources.ENTRY_MOSAMOSAFONT_9;
import static net.chocolapod.lwjgfont.packager.TestResources.IMAGE_MOSAMOSAFONT_9;
import static net.chocolapod.lwjgfont.packager.TestResources.CLASS_MOSAMOSAFONT_10;
import static net.chocolapod.lwjgfont.packager.TestResources.ENTRY_MOSAMOSAFONT_10;
import static net.chocolapod.lwjgfont.packager.TestResources.IMAGE_MOSAMOSAFONT_10;
import static net.chocolapod.lwjgfont.packager.TestResources.CLASS_MOSAMOSAFONT_11;
import static net.chocolapod.lwjgfont.packager.TestResources.ENTRY_MOSAMOSAFONT_11;
import static net.chocolapod.lwjgfont.packager.TestResources.IMAGE_MOSAMOSAFONT_11;
import static net.chocolapod.lwjgfont.packager.TestResources.FILE_MOSAMOSAFONT;
import static net.chocolapod.lwjgfont.packager.TestResources.FILE_MOSAMOSAFONT_ALIAS01;
import static net.chocolapod.lwjgfont.packager.TestResources.FILE_MOSAMOSAFONT_ALIAS02;
import static net.chocolapod.lwjgfont.packager.TestResources.TEST_JAR_PATH;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;

import java.awt.FontFormatException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.junit.BeforeClass;
import org.junit.Test;

public class TestLWJGFontFactory_packageMultiFonts {

	@BeforeClass
	public static void prepareJar() throws IOException, FontFormatException, URISyntaxException {
		TestLWJGFontFactory.ceateJar(
			new FontSetting(FILE_MOSAMOSAFONT, 8),
			new FontSetting(FILE_MOSAMOSAFONT, 9),
			new FontSetting(FILE_MOSAMOSAFONT_ALIAS01, 8),
			new FontSetting(FILE_MOSAMOSAFONT_ALIAS01, 10),
			new FontSetting(FILE_MOSAMOSAFONT_ALIAS02, 8),
			new FontSetting(FILE_MOSAMOSAFONT_ALIAS02, 11)
		);
	}

	@Test
	public void loadLWJGFontClass() throws ClassNotFoundException, IOException, FontFormatException {
		URLClassLoader	classLoader = null;

		try {
			classLoader = new URLClassLoader(new URL[] {new File(TEST_JAR_PATH).toURI().toURL()});

			assertNotNull(classLoader.loadClass(CLASS_MOSAMOSAFONT_8));
			assertNotNull(classLoader.loadClass(CLASS_MOSAMOSAFONT_9));
			assertNotNull(classLoader.loadClass(CLASS_MOSAMOSAFONT_10));
			assertNotNull(classLoader.loadClass(CLASS_MOSAMOSAFONT_11));
		} finally {
			if (classLoader != null) {
				try {
					classLoader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	@Test
	public void checkEntries() throws IOException {
		TestLWJGFontFactory_packageDuplicateFonts.assertEntiries(
			ENTRY_MOSAMOSAFONT_8, IMAGE_MOSAMOSAFONT_8,
			ENTRY_MOSAMOSAFONT_9, IMAGE_MOSAMOSAFONT_9,
			ENTRY_MOSAMOSAFONT_10, IMAGE_MOSAMOSAFONT_10,
			ENTRY_MOSAMOSAFONT_11, IMAGE_MOSAMOSAFONT_11
		);
	}

}


text:
package org.camunda.bpm.engine.test.api.history;

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

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.time.DateUtils;
import org.camunda.bpm.engine.CaseService;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.batch.Batch;
import org.camunda.bpm.engine.batch.history.HistoricBatch;
import org.camunda.bpm.engine.impl.batch.history.HistoricBatchEntity;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.metrics.Meter;
import org.camunda.bpm.engine.impl.persistence.entity.HistoricBatchManager;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.api.runtime.migration.MigrationTestRule;
import org.camunda.bpm.engine.test.api.runtime.migration.batch.BatchMigrationHelper;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;

@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_FULL)
public class HistoricInstanceForCleanupQueryTest {

  protected ProvidedProcessEngineRule engineRule = new ProvidedProcessEngineRule();
  public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);
  protected MigrationTestRule migrationRule = new MigrationTestRule(engineRule);
  protected BatchMigrationHelper helper = new BatchMigrationHelper(engineRule, migrationRule);

  @Rule public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(testRule).around(migrationRule);

  private HistoryService historyService;
  private ManagementService managementService;
  private CaseService caseService;
  private ProcessEngineConfigurationImpl processEngineConfiguration;

  @Before
  public void init() {
    historyService = engineRule.getHistoryService();
    managementService = engineRule.getManagementService();
    caseService = engineRule.getCaseService();
    processEngineConfiguration = engineRule.getProcessEngineConfiguration();
  }

  @After
  public void clearDatabase() {
    helper.removeAllRunningAndHistoricBatches();

    clearMetrics();
  }

  protected void clearMetrics() {
    Collection<Meter> meters = processEngineConfiguration.getMetricsRegistry().getDbMeters().values();
    for (Meter meter : meters) {
      meter.getAndClear();
    }
    managementService.deleteMetrics(null);
  }

  @SuppressWarnings("unchecked")
  @Test
  public void testSortHistoricBatchesForCleanup() {
    Date startDate = ClockUtil.getCurrentTime();
    int daysInThePast = -11;
    ClockUtil.setCurrentTime(DateUtils.addDays(startDate, daysInThePast));

    // given
    List<Batch> list = Arrays.asList(helper.migrateProcessInstancesAsync(1), helper.migrateProcessInstancesAsync(1), helper.migrateProcessInstancesAsync(1));

    String batchType = list.get(0).getType();
    final Map<String, Integer> batchOperationsMap = new HashedMap();
    batchOperationsMap.put(batchType, 4);

    for (Batch batch : list) {
      helper.completeSeedJobs(batch);
      helper.executeJobs(batch);

      ClockUtil.setCurrentTime(DateUtils.addDays(startDate, ++daysInThePast));
      helper.executeMonitorJob(batch);
    }

    ClockUtil.setCurrentTime(new Date());
    // when
    List<HistoricBatch> historicList = historyService.createHistoricBatchQuery().list();
    assertEquals(3, historicList.size());

    processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {
      public Void execute(CommandContext commandContext) {

        HistoricBatchManager historicBatchManager = commandContext.getHistoricBatchManager();
        List<String> ids = historicBatchManager.findHistoricBatchIdsForCleanup(7, batchOperationsMap, 0, 59);
        assertEquals(3, ids.size());
        HistoricBatchEntity instance0 = historicBatchManager.findHistoricBatchById(ids.get(0));
        HistoricBatchEntity instance1 = historicBatchManager.findHistoricBatchById(ids.get(1));
        HistoricBatchEntity instance2 = historicBatchManager.findHistoricBatchById(ids.get(2));
        assertTrue(instance0.getEndTime().before(instance1.getEndTime()));
        assertTrue(instance1.getEndTime().before(instance2.getEndTime()));

        return null;
      }
    });
  }

}


text:
<?php

declare(strict_types=1);

namespace atk4\schema;

use atk4\core\Exception;
use atk4\data\Field;
use atk4\data\FieldSqlExpression;
use atk4\Data\Model;
use atk4\data\Persistence;
use atk4\data\Reference\HasOne;
use atk4\dsql\Connection;
use atk4\dsql\Expression;
use Doctrine\DBAL\Platforms;

abstract class Migration extends Expression
{
    public const REF_TYPE_NONE = 0;
    public const REF_TYPE_LINK = 1;
    public const REF_TYPE_PRIMARY = 2;

    /** @var string Expression mode. See. */
    public $mode = 'create';

    /** @var array Expression templates */
    protected $templates = [
        'create' => 'create table {table} ([field])',
        'drop' => 'drop table if exists {table}',
        'alter' => 'alter table {table} [statements]',
        'rename' => 'rename table {old_table} to {table}',
    ];

    /** @var Connection Database connection */
    public $connection;

    /**
     * Field, table and alias name escaping symbol.
     * By SQL Standard it's double quote, but MySQL uses backtick.
     *
     * @var string
     */
    protected $escape_char = '"';

    /** @var string Expression to create primary key */
    public $primary_key_expr = 'primary key autoincrement';

    /** @var array Conversion mapping from Agile Data types to persistence types */
    protected $defaultMapToPersistence = [
        ['varchar', 255], // default
        'boolean' => ['tinyint', 1],
        'integer' => ['bigint'],
        'money' => ['decimal', 12, 2],
        'float' => ['decimal', 16, 6],
        'date' => ['date'],
        'datetime' => ['datetime'],
        'time' => ['varchar', 8],
        'text' => ['text'],
        'array' => ['text'],
        'object' => ['text'],
    ];

    /** @var array use this array in extended classes to overwrite or extend values of default mapping */
    public $mapToPersistence = [];

    /** @var array Conversion mapping from persistence types to Agile Data types */
    protected $defaultMapToAgile = [
        [null], // default
        'tinyint' => ['boolean'],
        'int' => ['integer'],
        'integer' => ['integer'],
        'bigint' => ['integer'],
        'decimal' => ['float'],
        'numeric' => ['float'],
        'date' => ['date'],
        'datetime' => ['datetime'],
        'timestamp' => ['datetime'],
        'text' => ['text'],
    ];

    /** @var array use this array in extended classes to overwrite or extend values of default mapping */
    public $mapToAgile = [];

    /**
     * Stores migrator class to use based on Platform class.
     *
     * Visibility is intentionally set to private.
     * If generic class Migration::of($source) is called, the migrator class will be resolved based on connection's Platform class of $source.
     * When specific migrator class e.g Migration\Mysql::of($source) is called, connection's Platform class will not be resolved (the $registry property is NOT visible).
     * Mysql migrator class will be used explicitly.
     *
     * @var array
     *
     * */
    private static $registry = [
        Platforms\SqlitePlatform::class => Migration\Sqlite::class,
        Platforms\MySqlPlatform::class => Migration\Mysql::class,
        Platforms\PostgreSqlPlatform::class => Migration\Postgresql::class,
        Platforms\OraclePlatform::class => Migration\Oracle::class,
        Platforms\SQLServerPlatform::class => Migration\Mssql::class,
    ];

    /**
     * @deprecated use Migration::of instead
     */
    public static function getMigration($source, $params = []): self
    {
        return self::of($source, $params);
    }

    /**
     * Factory method to get correct Migration subclass object depending on connection given.
     *
     * @param Connection|Persistence|Model $source
     * @param array                        $params
     *
     * @return Migration Subclass
     */
    public static function of($source, $params = []): self
    {
        $connection = static::getConnection($source);

        $migratorClass = null;
        foreach (self::$registry as $platformClass => $class) {
            if ($connection->getDatabasePlatform() instanceof $platformClass) {
                $migratorClass = $class;
            }
        }

        // if used within a subclass Migration method will create migrator of that class
        // if $migrator class is the generic class Migration then migrator was not resolved correctly
        if ($migratorClass === null) {
            throw (new Exception('Not sure which migration class to use for your DSN'))
                ->addMoreInfo('platform', $connection->getDatabasePlatform())
                ->addMoreInfo('source', $source);
        }

        return new $migratorClass($source, $params);
    }

    /**
     * Adds migrator class to the registry for resolving in Migration::of method.
     *
     * Can be used as:
     *
     * Migration::register(new Platforms\MySQLPlatform(), CustomMigration\Mysql), or
     * CustomMigration\Mysql::register('mysql')
     *
     * CustomMigration\Mysql must be descendant of Migration class.
     */
    public static function register(string $platformClass, string $migratorClass = null)
    {
        // forward to generic Migration::register if called with a descendant class e.g Migration\Mysql::register
        if (static::class !== self::class) {
            return (self::class)::register($platformClass, $migratorClass ?: static::class);
        } elseif (!$migratorClass) {
            throw (new Exception('Cannot register generic Migration class'))
                ->addMoreInfo('platform_class', $platformClass);
        }

        if (!is_subclass_of($migratorClass, self::class)) {
            throw (new Exception('Migrator must be descendant to generic Migration class'))
                ->addMoreInfo('migrator_class', $migratorClass);
        }

        self::$registry[$platformClass] = $migratorClass;
    }

    /**
     * Static method to extract Connection from Connection, Persistence or Model.
     *
     * @param Connection|Persistence|Model $source
     */
    public static function getConnection($source): Connection
    {
        if ($source instanceof Connection) {
            return $source;
        } elseif ($source instanceof Persistence\Sql) {
            return $source->connection;
        } elseif (
            $source instanceof Model
            && $source->persistence
            && ($source->persistence instanceof Persistence\Sql)
        ) {
            return $source->persistence->connection;
        }

        throw (new Exception('Source is specified incorrectly. Must be Connection, Persistence or initialized Model'))
            ->addMoreInfo('source', $source);
    }

    /**
     * Create new migration.
     *
     * @param Connection|Persistence|Model $source
     * @param array                        $params
     */
    public function __construct($source, $params = [])
    {
        parent::__construct($params);

        $this->setSource($source);
    }

    /**
     * Sets source of migration.
     *
     * @param Connection|Persistence|Model $source
     */
    public function setSource($source)
    {
        $this->connection = static::getConnection($source);

        if (
            $source instanceof Model
            && $source->persistence
            && ($source->persistence instanceof Persistence\Sql)
        ) {
            $this->setModel($source);
        }
    }

    /**
     * Sets model.
     */
    public function setModel(Model $m): Model
    {
        $this->table($m->table);

        foreach ($m->getFields() as $field) {
            // ignore not persisted model fields
            if ($field->never_persist) {
                continue;
            }

            if ($field instanceof FieldSqlExpression) {
                continue;
            }

            if ($field->short_name === $m->id_field) {
                $ref_type = self::REF_TYPE_PRIMARY;
                $persist_field = $field;
            } else {
                $ref_field = $this->getReferenceField($field);
                $ref_type = $ref_field !== null ? self::REF_TYPE_LINK : $ref_type = self::REF_TYPE_NONE;
                $persist_field = $ref_field ?? $field;
            }

            $options = [
                'type' => $ref_type !== self::REF_TYPE_NONE && empty($persist_field->type) ? 'integer' : $persist_field->type,
                'ref_type' => $ref_type,
                'mandatory' => ($field->mandatory || $field->required) && ($persist_field->mandatory || $persist_field->required),
                // todo add more options here
            ];

            $this->field($field->actual ?: $field->short_name, $options);
        }

        return $m;
    }

    protected function getReferenceField(Field $field): ?Field
    {
        // if the field is a hasOne relation
        // Don't have the right FieldType
        // FieldType is stored in the reference field
        if ($field->reference instanceof HasOne) {
            // @TODO if this can be done better?

            // i don't want to :
            // - change the isolation of relation link
            // - expose the protected property ->their_field
            // i need the type of the field to be used in this table
            $reflection = new \ReflectionClass($field->reference);
            $property = $reflection->getProperty('their_field');
            $property->setAccessible(true);

            /** @var string $reference_their_field get Reflection protected property Reference->their_field */
            $reference_their_field = $property->getValue($field->reference);

            /** @var string $reference_field reference field name */
            $reference_field = $reference_their_field ?? $field->reference->getOwner()->id_field;

            /** @var string $reference_model_class reference class fqcn */
            $reference_model_class = $field->reference->model;

            // @TODO fix, but without the dummy persistence, the following is shown:
            // Uncaught atk4\core\Exception: Element is not found in collection
            // for ID column
            $dummyPersistence = new Persistence\Sql($this->connection);

            return (new $reference_model_class($dummyPersistence))->getField($reference_field);
        }

        return null;
    }

    /**
     * Set SQL expression template.
     *
     * @param string $mode Template name
     *
     * @return $this
     */
    public function mode(string $mode): self
    {
        if (!isset($this->templates[$mode])) {
            throw (new Exception('Structure builder does not have this mode'))
                ->addMoreInfo('mode', $mode);
        }

        $this->mode = $mode;
        $this->template = $this->templates[$mode];

        return $this;
    }

    /**
     * Create new table.
     *
     * @return $this
     */
    public function create(): self
    {
        $this->mode('create')->execute();

        return $this;
    }

    /**
     * Drop table.
     *
     * @return $this
     */
    public function drop(): self
    {
        $this->mode('drop')->execute();

        return $this;
    }

    /**
     * Alter table.
     *
     * @return $this
     */
    public function alter(): self
    {
        $this->mode('alter')->execute();

        return $this;
    }

    /**
     * Rename table.
     *
     * @return $this
     */
    public function rename(): self
    {
        $this->mode('rename')->execute();

        return $this;
    }

    /**
     * @deprecated use Migration::run instead
     */
    public function migrate(): string
    {
        return $this->run();
    }

    /**
     * Will read current schema and consult current 'field' arguments, to see if they are matched.
     * If table does not exist, will invoke ->create. If table does exist, then it will execute
     * methods ->newField(), ->dropField() or ->alterField() as needed, then call ->alter().
     *
     * @return string Returns short textual info for logging purposes
     */
    public function run(): string
    {
        $changes = $added = $altered = $dropped = 0;

        // We use this to read fields from SQL
        $migration2 = new static($this->connection);

        if (!$migration2->importTable($this['table'])) {
            // should probably use custom exception class here
            $this->create();

            return 'created new table';
        }

        $old = $migration2->_getFields();
        $new = $this->_getFields();

        // add new fields or update existing ones
        foreach ($new as $field => $options) {
            // never update ID field (sadly hard-coded field name)
            if ($field === 'id') {
                continue;
            }

            if (isset($old[$field])) {
                // compare options and if needed alter field
                // @todo add more options here like 'len'
                if (array_key_exists('type', $old[$field]) && array_key_exists('type', $options)) {
                    $oldSQLFieldType = $this->getSqlFieldType($old[$field]['type']);
                    $newSQLFieldType = $this->getSqlFieldType($options['type']);
                    if ($oldSQLFieldType !== $newSQLFieldType) {
                        $this->alterField($field, $options);
                        ++$altered;
                        ++$changes;
                    }
                }

                unset($old[$field]);
            } else {
                // new field, so let's just add it
                $this->newField($field, $options);
                ++$added;
                ++$changes;
            }
        }

        // remaining old fields - drop them
        foreach ($old as $field => $options) {
            // never delete ID field (sadly hard-coded field name)
            if ($field === 'id') {
                continue;
            }

            $this->dropField($field);
            ++$dropped;
            ++$changes;
        }

        if ($changes) {
            $this->alter();

            return 'added ' . $added . ' field' . ($added === 1 ? '' : 's') . ', ' .
                'changed ' . $altered . ' field' . ($altered === 1 ? '' : 's') . ' and ' .
                'deleted ' . $dropped . ' field' . ($dropped === 1 ? '' : 's');
        }

        return 'no changes';
    }

    /**
     * Renders statement.
     */
    public function _render_statements(): string
    {
        $result = [];

        if (isset($this->args['dropField'])) {
            foreach ($this->args['dropField'] as $field => $junk) {
                $result[] = 'drop column ' . $this->_escape($field);
            }
        }

        if (isset($this->args['newField'])) {
            foreach ($this->args['newField'] as $field => $option) {
                $result[] = 'add column ' . $this->_render_one_field($field, $option);
            }
        }

        if (isset($this->args['alterField'])) {
            foreach ($this->args['alterField'] as $field => $option) {
                $result[] = 'change column ' . $this->_escape($field) . ' ' . $this->_render_one_field($field, $option);
            }
        }

        return implode(', ', $result);
    }

    /**
     * Create rough model from current set of $this->args['fields']. This is not
     * ideal solution but is designed as a drop-in solution.
     *
     * @param Persistence $persistence
     * @param string      $table
     */
    public function createModel($persistence, $table = null): Model
    {
        $this['table'] = $table ?? $this['table'];

        $m = new Model([$persistence, 'table' => $this['table']]);

        $this->importTable($this['table']);

        foreach ($this->_getFields() as $field => $options) {
            if ($field === 'id') {
                continue;
            }

            if (is_object($options)) {
                continue;
            }

            $defaults = [];

            if ($options['type']) {
                $defaults['type'] = $options['type'];
            }
            $m->addField($field, $defaults);
        }

        return $m;
    }

    /**
     * Sets newField argument.
     *
     * @param string $field
     * @param array  $options
     *
     * @return $this
     */
    public function newField($field, $options = []): self
    {
        $this->_set_args('newField', $field, $options);

        return $this;
    }

    /**
     * Sets alterField argument.
     *
     * @param array $options
     *
     * @return $this
     */
    public function alterField(string $field, $options = []): self
    {
        $this->_set_args('alterField', $field, $options);

        return $this;
    }

    /**
     * Sets dropField argument.
     *
     * @param string $field
     *
     * @return $this
     */
    public function dropField($field): self
    {
        $this->_set_args('dropField', $field, true);

        return $this;
    }

    /**
     * Return database table descriptions.
     * DB engine specific.
     */
    abstract public function describeTable(string $table);

    /**
     * Convert SQL field types to Agile Data field types.
     *
     * @param string $type SQL field type
     */
    public function getModelFieldType(string $type): ?string
    {
        // remove parenthesis and type options
        $type = trim(preg_replace('~(\(| ).*~', '', strtolower($type)));

        $map = array_replace($this->defaultMapToAgile, $this->mapToAgile);
        $a = array_key_exists($type, $map) ? $map[$type] : $map[0];

        return $a[0];
    }

    /**
     * Convert Agile Data field types to SQL field types.
     *
     * @param string|null $type    Agile Data field type
     * @param array       $options More options
     */
    public function getSqlFieldType(?string $type, array $options = []): ?string
    {
        if ($type !== null) {
            $type = strtolower($type);
        }

        $map = array_replace($this->defaultMapToPersistence, $this->mapToPersistence);
        $a = array_key_exists($type, $map) ? $map[$type] : $map[0];

        $res = $a[0];
        if (count($a) > 1) {
            $res .= ' (' . implode(',', array_slice($a, 1)) . ')';
        }

        if (!empty($options['ref_type']) && $options['ref_type'] !== self::REF_TYPE_NONE && $type === 'integer'
            && !($this instanceof Migration\Postgresql)) {
            $res .= ' unsigned';
        }

        if (
            !empty($options['mandatory'])
                || (!empty($options['ref_type']) && $options['ref_type'] === self::REF_TYPE_PRIMARY)
        ) {
            $res .= ' not null';
        }

        if (!empty($options['ref_type']) && $options['ref_type'] === self::REF_TYPE_PRIMARY) {
            $res .= ' ' . $this->primary_key_expr;
        }

        return $res;
    }

    /**
     * Import fields from database into migration field config.
     */
    public function importTable(string $table): bool
    {
        $this->table($table);
        $has_fields = false;
        foreach ($this->describeTable($table) as $row) {
            $has_fields = true;

            $type = $this->getModelFieldType($row['type']);
            $ref_type = $row['pk'] ? self::REF_TYPE_PRIMARY : self::REF_TYPE_NONE;

            $options = [
                'type' => $type,
                'ref_type' => $ref_type,
            ];

            $this->field($row['name'], $options);
        }

        return $has_fields;
    }

    /**
     * Sets table name.
     *
     * @param string $table
     *
     * @return $this
     */
    public function table($table)
    {
        $this['table'] = $table;

        return $this;
    }

    /**
     * Sets old table name.
     *
     * @param string $table
     *
     * @return $this
     */
    public function old_table($old_table)
    {
        $this['old_table'] = $old_table;

        return $this;
    }

    /**
     * Add field in template.
     *
     * @param string $name
     * @param array  $options
     *
     * @return $this
     */
    public function field($name, $options = [])
    {
        // save field in args
        $this->_set_args('field', $name, $options);

        return $this;
    }

    /**
     * Add ID field in template.
     *
     * @param string $name
     *
     * @return $this
     */
    public function id($name = null)
    {
        $options = [
            'type' => 'integer',
            'ref_type' => self::REF_TYPE_PRIMARY,
        ];

        $this->field($name ?? 'id', $options);

        return $this;
    }

    /**
     * Render "field" template.
     *
     * @return string
     */
    public function _render_field()
    {
        $ret = [];

        if (!$this->args['field']) {
            throw new Exception('No fields defined for table');
        }

        foreach ($this->args['field'] as $field => $options) {
            if ($options instanceof Expression) {
                $ret[] = $this->_escape($field) . ' ' . $this->_consume($options);

                continue;
            }

            $ret[] = $this->_render_one_field($field, $options);
        }

        return implode(',', $ret);
    }

    /**
     * Renders one field.
     */
    protected function _render_one_field(string $field, array $options): string
    {
        $name = $options['name'] ?? $field;
        $type = $this->getSqlFieldType($options['type'] ?? null, $options);

        return $this->_escape($name) . ' ' . $type;
    }

    /**
     * Return fields.
     */
    public function _getFields(): array
    {
        return $this->args['field'];
    }

    /**
     * Sets value in args array. Doesn't allow duplicate aliases.
     *
     * @param string $what  Where to set it - table|field
     * @param string $alias Alias name
     * @param mixed  $value Value to set in args array
     */
    protected function _set_args(string $what, string $alias, $value)
    {
        // save value in args
        if ($alias === null) {
            $this->args[$what][] = $value;
        } else {
            // don't allow multiple values with same alias
            if (isset($this->args[$what][$alias])) {
                throw (new Exception(ucfirst($what) . ' alias should be unique'))
                    ->addMoreInfo('alias', $alias);
            }

            $this->args[$what][$alias] = $value;
        }
    }
}


text:
package com.lothrazar.cyclic.item.carrot;

import com.lothrazar.cyclic.ModCyclic;
import com.lothrazar.cyclic.api.IEntityInteractable;
import com.lothrazar.cyclic.item.ItemBaseCyclic;
import com.lothrazar.cyclic.util.UtilChat;
import com.lothrazar.cyclic.util.UtilParticle;
import com.lothrazar.cyclic.util.UtilSound;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.animal.horse.AbstractChestedHorse;
import net.minecraft.world.entity.animal.horse.AbstractHorse;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteract;

public class ItemHorseEnder extends ItemBaseCyclic implements IEntityInteractable {

  public static final String NBT_KEYACTIVE = ModCyclic.MODID + "_carrot_ender";

  public ItemHorseEnder(Properties prop) {
    super(prop);
  }

  public static void onSuccess(LivingEntity liv) {
    UtilSound.playSound(liv, SoundEvents.GENERIC_DRINK);
    UtilParticle.spawnParticle(liv.level, ParticleTypes.CRIT, liv.blockPosition(), 3);
    increment(liv, -1);
    //    int current = ahorse.getPersistentData().getInt(NBT_KEYACTIVE);
    //    UtilChat.addChatMessage(event.getPlayer(), UtilChat.lang("cyclic.carrot_ender.count") + current);
  }

  private static void increment(LivingEntity ahorse, int val) {
    int old = ahorse.getPersistentData().getInt(NBT_KEYACTIVE);
    ahorse.getPersistentData().putInt(NBT_KEYACTIVE, old + val);
  }

  @Override
  public void interactWith(EntityInteract event) {
    if (event.getItemStack().getItem() == this
        && event.getTarget() instanceof AbstractHorse
        && !event.getPlayer().getCooldowns().isOnCooldown(this)) {
      // lets go
      AbstractHorse ahorse = (AbstractHorse) event.getTarget();
      if (event.getTarget() instanceof AbstractChestedHorse
          && ahorse.isTamed()) {
        AbstractChestedHorse ss = (AbstractChestedHorse) event.getTarget();
        ss.setChest(true);
      }
      //do the thing
      increment(ahorse, 1);
      event.setCanceled(true);
      event.setCancellationResult(InteractionResult.SUCCESS);
      event.getPlayer().getCooldowns().addCooldown(this, 1);
      event.getItemStack().shrink(1);
      int current = ahorse.getPersistentData().getInt(NBT_KEYACTIVE);
      UtilChat.addChatMessage(event.getPlayer(), UtilChat.lang("item.cyclic.carrot_ender.count") + current);
      //
      //test
      //      if (ahorse.getType() == EntityType.ZOMBIE_HORSE) {
      //        ahorse.setTamedBy(event.getPlayer());
      //      }
    }
  }
}