text:
use std::{sync::mpsc::channel, thread, time::Duration};

use collections::HashMap;
use kvproto::metapb::Region;
use raftstore::coprocessor::{RegionInfoAccessor, RegionInfoProvider};
use test_raftstore::*;
use tikv_util::HandyRwLock;

fn prepare_cluster<T: Simulator>(cluster: &mut Cluster<T>) -> Vec<Region> {
    for i in 0..15 {
        let i = i + b'0';
        let key = vec![b'k', i];
        let value = vec![b'v', i];
        cluster.must_put(&key, &value);
    }

    let end_keys = vec![
        b"k1".to_vec(),
        b"k3".to_vec(),
        b"k5".to_vec(),
        b"k7".to_vec(),
        b"k9".to_vec(),
        b"".to_vec(),
    ];

    let start_keys = vec![
        b"".to_vec(),
        b"k1".to_vec(),
        b"k3".to_vec(),
        b"k5".to_vec(),
        b"k7".to_vec(),
        b"k9".to_vec(),
    ];

    let mut regions = Vec::new();

    for mut key in end_keys.iter().take(end_keys.len() - 1).map(Vec::clone) {
        let region = cluster.get_region(&key);
        cluster.must_split(&region, &key);

        key[1] -= 1;
        let region = cluster.get_region(&key);
        regions.push(region);
    }
    regions.push(cluster.get_region(b"k9"));

    assert_eq!(regions.len(), end_keys.len());
    assert_eq!(regions.len(), start_keys.len());
    for i in 0..regions.len() {
        assert_eq!(regions[i].start_key, start_keys[i]);
        assert_eq!(regions[i].end_key, end_keys[i]);
    }

    // Wait for raftstore to update regions
    thread::sleep(Duration::from_secs(2));
    regions
}

#[test]
fn test_region_collection_seek_region() {
    let mut cluster = new_node_cluster(0, 3);

    let (tx, rx) = channel();
    cluster
        .sim
        .wl()
        .post_create_coprocessor_host(Box::new(move |id, host| {
            let p = RegionInfoAccessor::new(host);
            tx.send((id, p)).unwrap()
        }));

    cluster.run();
    let region_info_providers: HashMap<_, _> = rx.try_iter().collect();
    assert_eq!(region_info_providers.len(), 3);
    let regions = prepare_cluster(&mut cluster);

    for node_id in cluster.get_node_ids() {
        let engine = &region_info_providers[&node_id];

        // Test traverse all regions
        let key = b"".to_vec();
        let (tx, rx) = channel();
        let tx_ = tx.clone();
        engine
            .seek_region(
                &key,
                Box::new(move |infos| {
                    tx_.send(infos.map(|i| i.region.clone()).collect()).unwrap();
                }),
            )
            .unwrap();
        let sought_regions: Vec<_> = rx.recv_timeout(Duration::from_secs(3)).unwrap();
        assert_eq!(sought_regions, regions);

        // Test end_key is exclusive
        let (tx, rx) = channel();
        let tx_ = tx.clone();
        engine
            .seek_region(
                b"k1",
                Box::new(move |infos| tx_.send(infos.next().unwrap().region.clone()).unwrap()),
            )
            .unwrap();
        let region = rx.recv_timeout(Duration::from_secs(3)).unwrap();
        assert_eq!(region, regions[1]);

        // Test seek from non-starting key
        let tx_ = tx.clone();
        engine
            .seek_region(
                b"k6\xff\xff\xff\xff\xff",
                Box::new(move |infos| tx_.send(infos.next().unwrap().region.clone()).unwrap()),
            )
            .unwrap();
        let region = rx.recv_timeout(Duration::from_secs(3)).unwrap();
        assert_eq!(region, regions[3]);
        let tx_ = tx.clone();
        engine
            .seek_region(
                b"\xff\xff\xff\xff\xff\xff\xff\xff",
                Box::new(move |infos| tx_.send(infos.next().unwrap().region.clone()).unwrap()),
            )
            .unwrap();
        let region = rx.recv_timeout(Duration::from_secs(3)).unwrap();
        assert_eq!(region, regions[5]);
    }

    for (_, p) in region_info_providers {
        p.stop();
    }
}

#[test]
fn test_region_collection_get_regions_in_range() {
    let mut cluster = new_node_cluster(0, 3);

    let (tx, rx) = channel();
    cluster
        .sim
        .wl()
        .post_create_coprocessor_host(Box::new(move |id, host| {
            let p = RegionInfoAccessor::new(host);
            tx.send((id, p)).unwrap()
        }));

    cluster.run();
    let region_info_providers: HashMap<_, _> = rx.try_iter().collect();
    assert_eq!(region_info_providers.len(), 3);
    let regions = prepare_cluster(&mut cluster);

    for node_id in cluster.get_node_ids() {
        let engine = &region_info_providers[&node_id];

        let result = engine.get_regions_in_range(b"", b"").unwrap();
        assert_eq!(result, regions);

        let result = engine.get_regions_in_range(b"k1", b"k3").unwrap();
        assert_eq!(&result, &regions[1..3]);

        let result = engine.get_regions_in_range(b"k3", b"k8").unwrap();
        assert_eq!(&result, &regions[2..5]);

        let result = engine.get_regions_in_range(b"k6", b"k8").unwrap();
        assert_eq!(&result, &regions[3..5]);

        let result = engine.get_regions_in_range(b"k7", b"k99").unwrap();
        assert_eq!(&result, &regions[4..6]);

        let result = engine.get_regions_in_range(b"k99", b"").unwrap();
        assert_eq!(&result, &regions[5..6]);
    }

    for (_, p) in region_info_providers {
        p.stop();
    }
}


text:
package com.ociweb.iot.grove.simple_analog;
import com.ociweb.gl.api.Behavior;
import com.ociweb.iot.maker.Port;

/**
 *
 * @author Ray Lo
 *
 */
public interface SimpleAnalogListener extends Behavior{
	public void simpleAnalogEvent(Port port, long time, long durationMillis, int value);
}

redpajama_set_name: RedPajamaGithub


text:
package org.batfish.dataplane;

import static org.batfish.datamodel.Configuration.DEFAULT_VRF_NAME;
import static org.batfish.datamodel.matchers.AbstractRouteDecoratorMatchers.hasPrefix;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.Set;
import org.batfish.datamodel.AbstractRoute;
import org.batfish.datamodel.AnnotatedRoute;
import org.batfish.datamodel.DataPlane;
import org.batfish.datamodel.Edge;
import org.batfish.datamodel.Prefix;
import org.batfish.datamodel.RoutingProtocol;
import org.batfish.datamodel.Topology;
import org.batfish.main.Batfish;
import org.batfish.main.BatfishTestUtils;
import org.batfish.main.TestrigText;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/** End-to-end test of dataplane-dependent static route tracking on NX-OS devices. */
public class TrackTest {
  private static final String SNAPSHOT_FOLDER = "org/batfish/dataplane/testrigs/track";

  @Rule public TemporaryFolder _folder = new TemporaryFolder();

  private Batfish _batfish;

  /*
   * Topology:
   * r1 <============================> r2
   *    Ethernet1/1 GigabitEthernet0/0
   *    .1      192.0.2.0/24        .2
   * - r1 is running HMM on Vlan2, for which Ethernet1/1 is an access switchport
   * - r2 is connected to r1 on GigabitEthernet0/0
   * - r1 main RIB should have HMM route for 192.0.2.2/32 with next-hop Vlan2
   * - r1 should have static routes:
   *   - 10.0.1.0/24, which tracks hmm route 192.0.2.2/32
   *   - 10.0.2.0/24, which tracks route 10.2.0.0/24 from interface Ethernet1/2
   *   - 10.0.3.0/24, which tracks interface Ethernet1/2 line status
   * - r1 should not have static routes:
   *   - 10.0.4.0/24, which tracks missing hmm route 192.0.2.3/32
   *   - 10.0.5.0/24, which tracks missing route 10.3.0.1/24 from shutdown interface Ethernet1/3
   *   - 10.0.6.0/24, which tracks shutdown interface Ethernet1/3
   */
  @Before
  public void setup() throws IOException {
    String r1Filename = "r1";
    String r2Filename = "r2";
    _batfish =
        BatfishTestUtils.getBatfishFromTestrigText(
            TestrigText.builder()
                .setConfigurationFiles(SNAPSHOT_FOLDER, ImmutableSet.of(r1Filename, r2Filename))
                .setLayer1TopologyPrefix(SNAPSHOT_FOLDER)
                .build(),
            _folder);
    _batfish.computeDataPlane(_batfish.getSnapshot());
  }

  @Test
  public void testRoutes() {
    DataPlane dp = _batfish.loadDataPlane(_batfish.getSnapshot());

    // test main RIB routes
    Set<AnnotatedRoute<AbstractRoute>> r1Routes =
        dp.getRibs().get("r1").get(DEFAULT_VRF_NAME).getTypedRoutes();

    assertThat(
        r1Routes.stream()
            .filter(r -> r.getRoute().getProtocol() == RoutingProtocol.STATIC)
            .collect(ImmutableList.toImmutableList()),
        containsInAnyOrder(
            hasPrefix(Prefix.strict("10.0.1.0/24")),
            hasPrefix(Prefix.strict("10.0.2.0/24")),
            hasPrefix(Prefix.strict("10.0.3.0/24"))));
  }

  @Test
  public void testTopology() {
    Topology topology = _batfish.getTopologyProvider().getLayer3Topology(_batfish.getSnapshot());

    assertThat(topology.getEdges(), hasItem(Edge.of("r1", "Vlan2", "r2", "GigabitEthernet0/0")));
  }
}


text:
namespace accuracy_tips {
namespace features {

const base::FeatureParam<std::string> kSampleUrl{
    &safe_browsing::kAccuracyTipsFeature, "SampleUrl", ""};

const base::FeatureParam<bool> kDisableUi{&safe_browsing::kAccuracyTipsFeature,
                                          "DisableUI", false};

const base::FeatureParam<std::string> kLearnMoreUrl{
    &safe_browsing::kAccuracyTipsFeature, "LearnMoreUrl", ""};

const base::FeatureParam<base::TimeDelta> kTimeBetweenPrompts{
    &safe_browsing::kAccuracyTipsFeature, "TimeBetweenPrompts", base::Days(7)};

extern const base::FeatureParam<int> kNumIgnorePrompts{
    &safe_browsing::kAccuracyTipsFeature, "NumIgnorePrompts", 2};

extern const base::FeatureParam<int> kMaxSiteEngagementScore{
    &safe_browsing::kAccuracyTipsFeature, "MaxSiteEngagementScore", -1};

BASE_FEATURE(kAccuracyTipsSurveyFeature,
             "AccuracyTipsSurvey",
             base::FEATURE_DISABLED_BY_DEFAULT);

const base::FeatureParam<base::TimeDelta> kMinTimeToShowSurvey{
    &kAccuracyTipsSurveyFeature, "MinTimeToShowSurvey", base::Minutes(10)};

const base::FeatureParam<base::TimeDelta> kMaxTimeToShowSurvey{
    &kAccuracyTipsSurveyFeature, "MaxTimeToShowSurvey", base::Minutes(30)};

const base::FeatureParam<int> kMinPromptCountRequiredForSurvey{
    &kAccuracyTipsSurveyFeature, "MinPromptCountRequiredForSurvey", 1};

}  // namespace features
}  // namespace accuracy_tips


text:
{% comment %}
    A 'sequence' is a generalised structure that implements a collection of blocks that can be
    ordered, added and deleted.

    It provides the overall HTML structure, and the logic for updating hidden fields to reflect
    changes to the sequence, but NOT the UI controls for performing those changes: that is the
    responsibility of specific subtypes of 'sequence', such as list and stream.

    DO NOT PUT UI CONTROLS HERE, OR ANYTHING ELSE THAT ASSUMES A SPECIFIC VISUAL RENDERING OF THE LIST.
    (That belongs in templates that extend this one, such as list.html and stream.html.)

{% endcomment %}

{% load wagtailadmin_tags  %}

{% if help_text %}

            {% icon name="help" class_name="default" %}
            {{ help_text }}

{% endif %}

    <input type="hidden" name="{{ prefix }}-count" id="{{ prefix }}-count" value="{{ list_members_html|length }}">

    {% block header %}{% endblock %}

    {% if block_errors %}
        {% for error in block_errors %}

{{ error }}

        {% endfor %}
    {% endif %}

        {% for list_member_html in list_members_html %}
            {{ list_member_html }}
        {% endfor %}

    {% block footer %}{% endblock %}


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

    <title>I-Index</title>
    <meta name="date" content="2017-01-19">
    <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G H I L M N O P R S T U V Y

I

inGoalArea(Position)
            - Method in class model.areas.GoalArea

initialize(URL, ResourceBundle)
            - Method in class controller.ConfigWindowController

initialize(URL, ResourceBundle)
            - Method in class controller.MainController

initialize(URL, ResourceBundle)
            - Method in class controller.StatisticController

initializeAll()
            - Method in class manager.PerimeterManager

create a grid layout from perimeters on the the room

intersects(Circle)
            - Method in class model.areas.GoalArea

stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection

inTriangle(Position, Position, Position, Position)
            - Static method in class model.Position

                http://stackoverflow.com/questions/2049582/how-to-determine-if-a-point-is-in-a-2d-triangle

invert() - Method in class
            model.GVector

isCrossedWith(GVector)
            - Method in class model.GVector

checks if the current and another vector are crossed using the line formula
                E = B-A = ( Bx-Ax, By-Ay ) //this
                F = D-C = ( Dx-Cx, Dy-Cy ) // vector
                P = ( -Ey, Ex )
                h = ( (A-C) * P ) / ( F * P )
                This h number is the key.

isCrossingAnyObstacle(GVector)
            - Method in class manager.areamanagers.ObstacleManager

isEmpty() - Method in
            class model.Position

isInGoal() -
            Method in class model.persons.Person

isInRange(Position) - Method in
            class model.Perimeter

isInRange(Position, double)
            - Method in class model.Position

isJam() - Method in
            class model.Orientation

if the next vertex is in the view area (4x PerimeterSize),
                calculate persons and determine jam based on jam level in properties

isNewPositionAllowed(Position)
            - Method in class model.persons.Person

isSimulationFinished()
            - Method in class factory.SimulationFactory

isVisited(TargetVertex)
            - Method in class model.Vertex

isWeighted() -
            Method in class model.ConfigModel

    A C D E F G H I L M N O P R S T U V Y

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
import re;
import copy;

ENTITY_TRIGGER_TYPES = ['complex',
 'dna',
 'drug',
 'entity',
 'ion',
 'protein',
 'receptor',
 'rna',
 'simple_molecule',
 'simple_chemical',
 'tag',
 'gene',
 'gene_or_gene_product',
 'cellular_component']

EVENT_TRIGGER_TYPES = ['conversion',
 'catabolism',
 'dissociation',
 'inactivation',
 'regulation',
 'gene_expression',
 'catalysis',
 'positive_regulation',
 'pathway',
 'demethylation',
 'localization',
 'activation',
 'degradation',
 'transcription',
 'translation',
 'association',
 'ubiquitination',
 'protein_catabolism',
 'acetylation',
 'phosphorylation',
 'dephosphorylation',
 'methylation',
 'deubiquitination',
 'binding',
 'deacetylation',
 'negative_regulation',
 'transport']

ALL_TRIGGER_TYPES = ENTITY_TRIGGER_TYPES + EVENT_TRIGGER_TYPES

class TextAnnotation:
    id = "";
    type = "";
    type_lower = "";
    start = "";
    end = "";
    text = "";
    def __str__(self):
        return "<trigger {0}, {1}, {2}, {3}, '{4}'>".format( self.id, self.type, self.start, self.end, self.text)

class EntityTrigger(TextAnnotation):
    def get_url():
        return ;

class EventTrigger(TextAnnotation):
    pass;

class Event():
    def __init__(self, ):
        self.id = None;
        self.type = None;
        self.type_lower = None;
        self.trigger = None;
        self.roles = [];

    def get_roles( self, role, ignore_case = True):
        if ignore_case:
            return [r[1] for r in self.roles if r[0].lower() == role.lower()];
        else:
            return [r[1] for r in self.roles if r[0] == role];

    def __str__(self):
        return "<event {0}, {1}, trigger: {2}, roles: [{3}]>".format( self.id, self.type, self.trigger.id, ", ".join([ "{0}: {1}".format( r[0], r[1].id) for r in self.roles]))

class MappingError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr( self.value)

def parse_line( line):
    """Transforms a standoff line into EntityTrigger, EventTrigger, or Event
       Throws a MappingError with information in case of error"""
    entity_trigger = None;
    event_trigger = None;
    event = None;
    equivalence = None

    # handling trigger T[0-1]*
    if line.startswith( "T"):
        # format id \t type start end \t annotation
        split = line.strip().split('\t')
        trigger_type = split[1].split(' ')[0].lower()

         # entity trigger
        if trigger_type in ENTITY_TRIGGER_TYPES:
            # format id \t type start end \t annotation
            split = line.strip().split('\t')
            entity_trigger = EntityTrigger();
            entity_trigger.id = split[0]
            type_start_end = split[1].split(' ')
            entity_trigger.type = type_start_end[0]
            entity_trigger.type_lower = trigger_type
            entity_trigger.start = type_start_end[1]
            entity_trigger.end = type_start_end[2]
            entity_trigger.text = split[2]
            #TRIGGER[entity_trigger.id] =  entity_trigger
            #ENTITY_TRIGGER.append( entity_trigger)
        # event trigger
        elif trigger_type in EVENT_TRIGGER_TYPES:
            event_trigger = EventTrigger();
            event_trigger.id = split[0]
            type_start_end = split[1].split(' ')
            event_trigger.type = type_start_end[0]
            event_trigger.type_lower = trigger_type
            event_trigger.start = type_start_end[1]
            event_trigger.end = type_start_end[2]
            event_trigger.text = split[2]
            #TRIGGER[event_trigger.id] = event_trigger
        else:
            raise MappingError( "unknown trigger in " + line.encode('utf-8'));
    # handling event E[0-1]*
    elif line.startswith("E"):
        # format id \t type role1 role2
        split = line.strip().split('\t')
        event = Event();
        event.id = split[0]

        roles = split[1].split(' ');

        # type
        type_trigger = roles[0].split(':');
        event.type = type_trigger[0]
        event.type_lower = event.type.lower()
        # try if we get the trigger
        try:
            event.trigger = type_trigger[1]
        except:
            pass

        # roles
        for r in range( len(roles) - 1):
            role = roles[r+1];
            role_split = role.split(':')
            role_name = re.sub('[^a-zA-Z]*$','', role_split[0]); # remove trailing numbers from the role
            event.roles.append( (role_name.lower(), role_split[1]))
    elif line.startswith("*"):
        split = line.strip().split('\t')
        if len(split) > 3:
            if split[1] == "Equiv":
                equivalence = ( split[2], split[3])

        # EVENTS[event.id] = event
    return ( entity_trigger, event_trigger, event, equivalence)

def parse_files( file_pathnames):
    triggers = {} # entities and event triggers
    entity_triggers = [] # entity triggers only
    events = {} # events annotations
    equivalences = []
    for pathname in file_pathnames:
        with open( pathname) as f:
            for i,line in enumerate(f):
                try:
                    entity_trigger, event_trigger, event, equivalence = parse_line( line);
                    if entity_trigger != None:
                        triggers[entity_trigger.id] =  entity_trigger
                        entity_triggers.append( entity_trigger)
                    if event_trigger != None:
                        triggers[event_trigger.id] = event_trigger
                    if event != None:
                        events[event.id] = event
                    if equivalence != None:
                        equivalences.append( equivalence);
                except MappingError as e:
                    print "ERROR " + pathname + ":" + str(i) + ": mapping error:" + e.value
                except:
                    print "ERROR " + pathname + ":" + str(i) + ": parsing line:" + line.encode('utf-8')

    # handle equivalences (add missing triggers and events)
    for equivalence in equivalences:
        t1 = equivalence[0];
        t2 = equivalence[1];
        old = None
        new = None

        if t1 in triggers and not t2 in triggers:
            old = triggers[t1]
        elif t2 in triggers and not t1 in triggers:
            old = triggers[t2]
        if old != None:
            # create a new trigger (copy the id of the old)
            new = copy.copy( old)
            if old.id == t1:
                new.id = t2
            else:
                new.id = t1
            triggers[new.id] = new
            if not old in entity_triggers:
                print "ERROR " + str(file_pathnames) + " equivalence between non-entities cannot be handled (equivalence: " + equivalence + ")"
            else:
                entity_triggers.append( new)

    # replace all event roles with objects, replace trigger id with actual trigger
    for event in events.itervalues():
        try:
            trigger = triggers[event.trigger];
            event.trigger = trigger
        except:
           print "ERROR " + str(file_pathnames) + ": entity trigger '" + event.trigger + "' not found"

        roles = []
        for role_tuple in event.roles:
            role_filler = None;
            try:
                role_filler = events[role_tuple[1]]
            except:
                pass
            try:
                role_filler = triggers[role_tuple[1]]
            except:
                pass
            if role_filler == None:
                print "ERROR " + str(file_pathnames) + " entity/event '" + role_tuple[1] + "' not found"
            else:
                roles.append((role_tuple[0], role_filler))
        event.roles = roles

    return triggers, entity_triggers, events;

def parse_a1_a2( a1_file_path, a2_file_path):
    return parse_files( [ a1_file_path, a2_file_path])

def parse_ann( ann_file_path):
    return parse_files( [ ann_file_path])

##################################################################
##### MAIN
##################################################################

if __name__ == '__main__':
    parse_ann( "test.ann");


text:
from django.contrib import admin
from .models import *

# Register your models here.
admin.site.register(Page)
admin.site.register(Tag)


text:
package org.apache.poi.hpsf;

import java.io.IOException;
import java.io.OutputStream;

/**
 *
Adds writing capability to the {@link Property} class.

 *
 *
Please be aware that this class' functionality will be merged into the
 * {@link Property} class at a later time, so the API will change.

 *
 * @author Rainer Klute <klute@rainer-klute.de>
 */
public class MutableProperty extends Property
{

    /**
     *
Creates an empty property. It must be filled using the set method to
     * be usable.

     */
    public MutableProperty()
    { }

    /**
     *
Creates a MutableProperty as a copy of an existing
     * Property.

     *
     * @param p The property to copy.
     */
    public MutableProperty(final Property p)
    {
        setID(p.getID());
        setType(p.getType());
        setValue(p.getValue());
    }

    /**
     *
Sets the property's ID.

     *
     * @param id the ID
     */
    public void setID(final long id)
    {
        this.id = id;
    }

    /**
     *
Sets the property's type.

     *
     * @param type the property's type
     */
    public void setType(final long type)
    {
        this.type = type;
    }

    /**
     *
Sets the property's value.

     *
     * @param value the property's value
     */
    public void setValue(final Object value)
    {
        this.value = value;
    }

    /**
     *
Writes the property to an output stream.

     *
     * @param out The output stream to write to.
     * @param codepage The codepage to use for writing non-wide strings
     * @return the number of bytes written to the stream
     *
     * @exception IOException if an I/O error occurs
     * @exception WritingNotSupportedException if a variant type is to be
     * written that is not yet supported
     */
    public int write(final OutputStream out, final int codepage)
        throws IOException, WritingNotSupportedException
    {
        int length = 0;
        long variantType = getType();

        /* Ensure that wide strings are written if the codepage is Unicode. */
        if (codepage == Constants.CP_UNICODE && variantType == Variant.VT_LPSTR)
            variantType = Variant.VT_LPWSTR;

        length += TypeWriter.writeUIntToStream(out, variantType);
        length += VariantSupport.write(out, variantType, getValue(), codepage);
        return length;
    }

}


text:
package org.jboss.aerogear.arquillian.junit.rule;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * SecurityActions
 *
 * A set of privileged actions that are not to leak out of this package
 *
 *
 * @author ALR
 *
 * @version $Revision: $
 */
final class SecurityActions {

    // -------------------------------------------------------------------------------||
    // Constructor
    // ------------------------------------------------------------------||
    // -------------------------------------------------------------------------------||

    /**
     * No instantiation
     */
    private SecurityActions() {
        throw new UnsupportedOperationException("No instantiation");
    }

    // -------------------------------------------------------------------------------||
    // Utility Methods
    // --------------------------------------------------------------||
    // -------------------------------------------------------------------------------||

    /**
     * Obtains the Thread Context ClassLoader
     */
    static ClassLoader getThreadContextClassLoader() {
        return AccessController.doPrivileged(GetTcclAction.INSTANCE);
    }

    /**
     * Obtains the Constructor specified from the given Class and argument types
     *
     * @param clazz
     * @param argumentTypes
     * @return
     * @throws NoSuchMethodException
     */
    static Constructor<?> getConstructor(final Class<?> clazz, final Class<?>... argumentTypes) throws NoSuchMethodException {
        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
                public Constructor<?> run() throws NoSuchMethodException {
                    return clazz.getConstructor(argumentTypes);
                }
            });
        }
        // Unwrap
        catch (final PrivilegedActionException pae) {
            final Throwable t = pae.getCause();
            // Rethrow
            if (t instanceof NoSuchMethodException) {
                throw (NoSuchMethodException) t;
            } else {
                // No other checked Exception thrown by Class.getConstructor
                try {
                    throw (RuntimeException) t;
                }
                // Just in case we've really messed up
                catch (final ClassCastException cce) {
                    throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
                }
            }
        }
    }

    /**
     * Create a new instance by finding a constructor that matches the argumentTypes signature using the arguments for
     * instantiation.
     *
     * @param className Full classname of class to create
     * @param argumentTypes The constructor argument types
     * @param arguments The constructor arguments
     * @return a new instance
     * @throws IllegalArgumentException if className, argumentTypes, or arguments are null
     * @throws RuntimeException if any exceptions during creation
     * @author Aslak Knutsen
     * @author ALR
     */
    static <T> T newInstance(final String className, final Class<?>[] argumentTypes, final Object[] arguments,
        final Class<T> expectedType) {
        if (className == null) {
            throw new IllegalArgumentException("ClassName must be specified");
        }
        if (argumentTypes == null) {
            throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
        }
        if (arguments == null) {
            throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
        }
        final Object obj;
        try {
            final ClassLoader tccl = getThreadContextClassLoader();
            final Class<?> implClass = Class.forName(className, false, tccl);
            Constructor<?> constructor = getConstructor(implClass, argumentTypes);
            obj = constructor.newInstance(arguments);
        } catch (Exception e) {
            throw new RuntimeException("Could not create new instance of " + className + ", missing package from classpath?", e);
        }

        // Cast
        try {
            return expectedType.cast(obj);
        } catch (final ClassCastException cce) {
            // Reconstruct so we get some useful information
            throw new ClassCastException("Incorrect expected type, " + expectedType.getName() + ", defined for "
                + obj.getClass().getName());
        }
    }

    static boolean isClassPresent(String name) {
        try {
            ClassLoader classLoader = getThreadContextClassLoader();
            classLoader.loadClass(name);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    static Map<Integer, Annotation[]> getParametersWithAnnotation(final Method method,
        final Class<? extends Annotation> annotationClass) {

        Map<Integer, Annotation[]> declaredParameters = AccessController
            .doPrivileged(new PrivilegedAction<Map<Integer, Annotation[]>>() {

                @Override
                public Map<Integer, Annotation[]> run() {
                    Map<Integer, Annotation[]> foundParameters = new LinkedHashMap<Integer, Annotation[]>();

                    Class<?>[] parameterTypes = method.getParameterTypes();
                    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

                    for (int i = 0; i < parameterTypes.length; i++) {
                        if (isAnnotationPresent(parameterAnnotations[i], annotationClass)) {
                            foundParameters.put(i, parameterAnnotations[i]);
                        }
                    }
                    return foundParameters;
                }

            });
        return declaredParameters;
    }

    static List<Field> getFieldsWithAnnotation(final Class<?> source, final Class<? extends Annotation> annotationClass) {
        List<Field> declaredAccessableFields = AccessController.doPrivileged(new PrivilegedAction<List<Field>>() {
            public List<Field> run() {
                List<Field> foundFields = new ArrayList<Field>();
                Class<?> nextSource = source;
                while (nextSource != Object.class) {
                    for (Field field : nextSource.getDeclaredFields()) {
                        if (field.isAnnotationPresent(annotationClass)) {
                            if (!field.isAccessible()) {
                                field.setAccessible(true);
                            }
                            foundFields.add(field);
                        }
                    }
                    nextSource = nextSource.getSuperclass();
                }
                return foundFields;
            }
        });
        return declaredAccessableFields;
    }

    static boolean isAnnotationPresent(final Annotation[] annotations, final Class<? extends Annotation> needle) {
        for (Annotation a : annotations) {
            if (a.annotationType() == needle) {
                return true;
            }
        }
        return false;
    }

    static Object getFieldValue(final Object instance, final Field field) {
        try {
            Object value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                public Object run() throws IllegalArgumentException, IllegalAccessException {
                    return field.get(instance);
                }
            });
            return value;
        } catch (PrivilegedActionException e) {
            final Throwable t = e.getCause();
            // Rethrow
            if (t instanceof IllegalArgumentException) {
                throw (IllegalArgumentException) t;
            } else if (t instanceof IllegalAccessException) {
                throw new IllegalStateException("Unable to get field value of " + field.getName() + " due to: "
                    + t.getMessage(), t.getCause());
            } else {
                // No other checked Exception thrown by Class.getConstructor
                try {
                    throw (RuntimeException) t;
                }
                // Just in case we've really messed up
                catch (final ClassCastException cce) {
                    throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
                }
            }
        }
    }

    static void setFieldValue(final Object instance, final Field field, final Object value) {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
                public Void run() throws IllegalArgumentException, IllegalAccessException {
                    field.set(instance, value);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            final Throwable t = e.getCause();
            // Rethrow
            if (t instanceof IllegalArgumentException) {
                throw (IllegalArgumentException) t;
            } else if (t instanceof IllegalAccessException) {
                throw new IllegalStateException("Unable to set field value of " + field.getName() + " due to: "
                    + t.getMessage(), t.getCause());
            } else {
                // No other checked Exception thrown by Class.getConstructor
                try {
                    throw (RuntimeException) t;
                }
                // Just in case we've really messed up
                catch (final ClassCastException cce) {
                    throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
                }
            }
        }
    }

    static String getProperty(final String key) {
        try {
            String value = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
                public String run() {
                    return System.getProperty(key);
                }
            });
            return value;
        }
        // Unwrap
        catch (final PrivilegedActionException pae) {
            final Throwable t = pae.getCause();
            // Rethrow
            if (t instanceof SecurityException) {
                throw (SecurityException) t;
            }
            if (t instanceof NullPointerException) {
                throw (NullPointerException) t;
            } else if (t instanceof IllegalArgumentException) {
                throw (IllegalArgumentException) t;
            } else {
                // No other checked Exception thrown by System.getProperty
                try {
                    throw (RuntimeException) t;
                }
                // Just in case we've really messed up
                catch (final ClassCastException cce) {
                    throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
                }
            }
        }
    }

    // -------------------------------------------------------------------------------||
    // Inner Classes
    // ----------------------------------------------------------------||
    // -------------------------------------------------------------------------------||

    /**
     * Single instance to get the TCCL
     */
    private enum GetTcclAction implements PrivilegedAction<ClassLoader> {
        INSTANCE;

        public ClassLoader run() {
            return Thread.currentThread().getContextClassLoader();
        }

    }

}


text:
node['system']['packages']['uninstall'].each do |package|
  package package do
    action :remove
  end
end

node['system']['packages']['uninstall_compile_time'].each do |package|
  p = package package do
    action :remove
  end
  p.run_action(:install)
end


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Oxide.Core.Configuration;
using UnityEngine;
using Oxide.Core;

namespace Oxide.Plugins
{
    [Info("RecycleManager", "redBDGR", "1.0.8", ResourceId = 2391)]
    [Description("Easily change features about the recycler")]

    class RecycleManager : RustPlugin
    {
        private bool changed;

        #region Data

        private DynamicConfigFile OutputData;
        private StoredData storedData;

        private void SaveData()
        {
            storedData.table = ingredientList;
            OutputData.WriteObject(storedData);
        }

        private void LoadData()
        {
            try
            {
                storedData = OutputData.ReadObject<StoredData>();
                ingredientList = storedData.table;
            }
            catch
            {
                Puts("Failed to load data, creating new file");
                storedData = new StoredData();
            }
        }

        private class StoredData
        {
            public Dictionary<string, List<ItemInfo>> table = new Dictionary<string, List<ItemInfo>>();
        }

        #endregion

        private class ItemInfo
        {
            public string itemName;
            public int itemAmount;
        }

        private class IngredientInfo
        {
            public List<ItemInfo> items;
        }

        public float recycleTime = 5.0f;
        private const string permissionNameADMIN = "recyclemanager.admin";
        private int maxItemsPerRecycle = 100;

        private static Dictionary<string, object> Multipliers()
        {
            var at = new Dictionary<string, object> {{"*", 1}, {"metal.refined", 1}};
            return at;
        }

        private static List<object> Blacklist()
        {
            var at = new List<object> {"hemp.seed"};
            return at;
        }

        private static List<object> OutputBlacklist()
        {
            var at = new List<object> {"hemp.seed"};
            return at;
        }

        private List<object> blacklistedItems;
        private List<object> outputBlacklistedItems;
        private Dictionary<string, object> multiplyList;
        private Dictionary<string, List<ItemInfo>> ingredientList = new Dictionary<string, List<ItemInfo>>();

        private void LoadVariables()
        {
            blacklistedItems = (List<object>)GetConfig("Lists", "Input Blacklist", Blacklist());
            recycleTime = Convert.ToSingle(GetConfig("Settings", "Recycle Time", 5.0f));
            multiplyList = (Dictionary<string, object>)GetConfig("Lists", "Recycle Output Multipliers", Multipliers());
            maxItemsPerRecycle = Convert.ToInt32(GetConfig("Settings", "Max Items Per Recycle", 100));
            outputBlacklistedItems = (List<object>)GetConfig("Lists", "Output Blacklist", OutputBlacklist());

            if (!changed) return;
            SaveConfig();
            changed = false;
        }

        protected override void LoadDefaultConfig()
        {
            Config.Clear();
            LoadVariables();
        }

        private void Init()
        {
            LoadVariables();
            permission.RegisterPermission(permissionNameADMIN, this);
            OutputData = Interface.Oxide.DataFileSystem.GetFile("RecycleManager");
            LoadData();
            if (ingredientList.Count == 0)
                RefreshIngredientList();
        }

        private void Loaded()
        {
            lang.RegisterMessages(new Dictionary<string, string>
            {
                //chat
                ["No Permissions"] = "You cannot use this command!",
                ["addrecycler CONSOLE invalid syntax"] = "Invalid syntax! addrecycler <playername/id>",
                ["No Player Found"] = "No player was found or they are offline",
                ["AddRecycler CONSOLE success"] = "A recycler was successfully placed at the players location!",

            }, this);
        }

        [ChatCommand("addrecycler")]
        private void AddRecyclerCMD(BasePlayer player, string command, String[] args)
        {
            if (!permission.UserHasPermission(player.UserIDString, permissionNameADMIN))
            {
                player.ChatMessage(msg("No Permissions", player.UserIDString));
                return;
            }

            BaseEntity ent = GameManager.server.CreateEntity("assets/bundled/prefabs/static/recycler_static.prefab", player.transform.position, player.GetEstimatedWorldRotation(), true);
            ent.Spawn();
            return;
        }

        [ConsoleCommand("addrecycler")]
        private void AddRecyclerCMDConsole(ConsoleSystem.Arg arg)
        {
            if (arg?.Args == null)
            {
                arg.ReplyWith(msg("addrecycler CONSOLE invalid syntax"));
                return;
            }
            if (arg.Connection != null) return;
            if (arg.Args.Length != 1)
            {
                arg.ReplyWith(msg("addrecycler CONSOLE invalid syntax"));
                return;
            }
            BasePlayer target = FindPlayer(arg.Args[0]);
            if (target == null || !target.IsValid())
            {
                arg.ReplyWith(msg("No Player Found"));
                return;
            }
            BaseEntity ent = GameManager.server.CreateEntity("assets/bundled/prefabs/static/recycler_static.prefab", target.transform.position, target.GetEstimatedWorldRotation(), true);
            ent.Spawn();
            arg.ReplyWith(msg("AddRecycler CONSOLE success"));
        }

        [ConsoleCommand("reloadrecyclerdata")]
        private void reloadDataCONSOLECMD(ConsoleSystem.Arg args)
        {
            if (args.Connection != null)
                return;
            OutputData = Interface.Oxide.DataFileSystem.GetFile("RecycleManager");
            LoadData();
            Puts("Recycler output list has successfully been updated!");
        }

        private void OnRecyclerToggle(Recycler recycler, BasePlayer player)
        {
            if (recycler.IsOn()) return;
            recycler.CancelInvoke("RecycleThink");
            timer.Once(0.1f, () => { recycler.Invoke("RecycleThink", recycleTime); });
        }

        private bool CanRecycle(Recycler recycler, Item item)
        {
            return !blacklistedItems.Contains(item.info.shortname) && ingredientList.ContainsKey(item.info.shortname);
        }

        private object OnRecycleItem(Recycler recycler, Item item)
        {
            bool flag = false;
            int usedItems = 1;

            if (item.amount > 1)
                usedItems = item.amount;
            if (usedItems > maxItemsPerRecycle)
                usedItems = maxItemsPerRecycle;

            item.UseItem(usedItems);
            foreach (ItemInfo ingredient in ingredientList[item.info.shortname])
            {
                double multi = 1;
                if (multiplyList.ContainsKey("*"))
                    multi = Convert.ToDouble(multiplyList["*"]);
                if (multiplyList.ContainsKey(ingredient.itemName))
                    multi = Convert.ToDouble(multiplyList[ingredient.itemName]);
                int outputamount = Convert.ToInt32(usedItems * Convert.ToDouble(ingredient.itemAmount) * multi);
                if (outputamount < 1)
                    continue;
                if (!recycler.MoveItemToOutput(ItemManager.CreateByName(ingredient.itemName, outputamount)))
                    flag = true;
            }
            if (flag || !recycler.HasRecyclable())
            {
                recycler.StopRecycling();
                for (int i = 5; i <= 11; i++)
                {
                    Item _item = recycler.inventory.GetSlot(i);
                    if (_item == null) continue;
                    if (_item.IsValid())
                        if (outputBlacklistedItems.Contains(_item.info.shortname))
                        {
                            _item.Remove();
                            _item.RemoveFromContainer();
                        }
                }
            }
            return true;
        }

        private void RefreshIngredientList()
        {
            foreach (ItemDefinition itemInfo in ItemManager.itemList)
            {
                if (itemInfo.Blueprint == null)
                    continue;
                if (itemInfo.Blueprint.ingredients?.Count == 0)
                    continue;
                List<ItemInfo> x = itemInfo.Blueprint.ingredients?.Select(entry => new ItemInfo {itemAmount = (int) entry.amount / 2, itemName = entry.itemDef.shortname}).ToList();
                ingredientList.Add(itemInfo.shortname, x);
            }
            SaveData();
        }

        private object GetConfig(string menu, string datavalue, object defaultValue)
        {
            var data = Config[menu] as Dictionary<string, object>;
            if (data == null)
            {
                data = new Dictionary<string, object>();
                Config[menu] = data;
                changed = true;
            }
            object value;
            if (data.TryGetValue(datavalue, out value)) return value;
            value = defaultValue;
            data[datavalue] = value;
            changed = true;
            return value;
        }

        private static BasePlayer FindPlayer(string nameOrId)
        {
            foreach (var activePlayer in BasePlayer.activePlayerList)
            {
                if (activePlayer.UserIDString == nameOrId)
                    return activePlayer;
                if (activePlayer.displayName.Contains(nameOrId, CompareOptions.OrdinalIgnoreCase))
                    return activePlayer;
                if (activePlayer.net?.connection != null && activePlayer.net.connection.ipaddress == nameOrId)
                    return activePlayer;
            }
            return null;
        }

        string msg(string key, string id = null) => lang.GetMessage(key, this, id);
    }
}


text:
var Compound = require('../').Compound;
var should = require('should');

describe('Compound', function() {

    it('could be created with no app', function() {
        (function() {
            new Compound;
        }).should.not.throw;
    });

    it('should have ability to run tools when instantiated with no app', function () {
        var c = new Compound;
        c.generators.init(c);
        c.generators.list().should.equal('app');
    });

    it('should allow to find model by name', function() {
        var c = new Compound;
        c.models = {Model: function Model() {}, ModelTwo: true};
        should.exist(c.model('Model'));
        should.exist(c.model('model'));
        should.not.exist(c.model('model', true));
        should.exist(c.model('ModelTwo'), true);

        // add model as named fn
        should.not.exist(c.model('ModelThree'));
        c.model(function ModelThree(){});
        should.exist(c.model('ModelThree'));

        // add model as jugglingdb model
        var model = function(){};
        model.modelName = 'HelloJuggling';
        c.model(model);
        should.exist(c.model('HelloJuggling'));

        // throws when model is not named
        (function() {
            c.model(function() {});
        }).should.throw('Named function or jugglingdb model required');

    });

});


text:
permalink: /en/bitcoin-priceBitcoin
redirect: /en/bitcoin-price/
layout: redirect
sitemap: false
---


text:
<?php
/**
 * Configuration file generated by ZFTool
 * The previous configuration file is stored in application.config.old
 *
 * @see https://github.com/zendframework/ZFTool
 */
return array(
    'modules' => array(
        'Application',
        'Users',
        'WebinoImageThumb',
        'HTML5',
        'Contact',
        'Album',
        'Huser',
        'HBase',
        'SampleModule',
        'Restful',
        'DAO',
        'ZendDeveloperTools',
        'Authentication'
        ),
    'module_listener_options' => array(
        'module_paths' => array(
            './module',
            './vendor'
            ),
        'config_glob_paths' => array('config/autoload/{,*.}{global,local}.php'),
//        'config_cache_enabled'=>true,
//        'config_cache_key'=>'configuration',
//        'cache_dir'=>'data/cache/'
        )
    );


text:
@protocol IBRemoteView <NSObject>
@optional

@end

@interface IBRemoteView : NSView <IBRemoteView>

@end


text:
using NUnit.Framework;
using Sharpen;
using Tup.Cobar.Server.Parser;

namespace Tup.Cobar4Net.Parser
{
	/// <author>xianmao.hexm</author>
	[NUnit.Framework.TestFixture]
	public class ServerParserTest
	{
		[NUnit.Framework.Test]
		public virtual void TestIsBegin()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Begin, ServerParse.Parse("begin"));
			NUnit.Framework.Assert.AreEqual(ServerParse.Begin, ServerParse.Parse("BEGIN"));
			NUnit.Framework.Assert.AreEqual(ServerParse.Begin, ServerParse.Parse("BegIn"));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsCommit()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Commit, ServerParse.Parse("commit"));
			NUnit.Framework.Assert.AreEqual(ServerParse.Commit, ServerParse.Parse("COMMIT"));
			NUnit.Framework.Assert.AreEqual(ServerParse.Commit, ServerParse.Parse("cOmmiT "));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsDelete()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Delete, ServerParse.Parse("delete ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Delete, ServerParse.Parse("DELETE ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Delete, ServerParse.Parse("DeletE ..."
				));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsInsert()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Insert, ServerParse.Parse("insert ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Insert, ServerParse.Parse("INSERT ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Insert, ServerParse.Parse("InserT ..."
				));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsReplace()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Replace, ServerParse.Parse("replace ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Replace, ServerParse.Parse("REPLACE ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Replace, ServerParse.Parse("rEPLACe ..."
				));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsRollback()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Rollback, ServerParse.Parse("rollback"
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Rollback, ServerParse.Parse("ROLLBACK"
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Rollback, ServerParse.Parse("rolLBACK "
				));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSelect()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Select, unchecked((int)(0xff)) & ServerParse
				.Parse("select ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Select, unchecked((int)(0xff)) & ServerParse
				.Parse("SELECT ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Select, unchecked((int)(0xff)) & ServerParse
				.Parse("sELECt ..."));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSet()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Set, unchecked((int)(0xff)) & ServerParse
				.Parse("set ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Set, unchecked((int)(0xff)) & ServerParse
				.Parse("SET ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Set, unchecked((int)(0xff)) & ServerParse
				.Parse("sEt ..."));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsShow()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Show, unchecked((int)(0xff)) & ServerParse
				.Parse("show ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Show, unchecked((int)(0xff)) & ServerParse
				.Parse("SHOW ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Show, unchecked((int)(0xff)) & ServerParse
				.Parse("sHOw ..."));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsStart()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Start, unchecked((int)(0xff)) & ServerParse
				.Parse("start ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Start, unchecked((int)(0xff)) & ServerParse
				.Parse("START ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Start, unchecked((int)(0xff)) & ServerParse
				.Parse("stART ..."));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsUpdate()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Update, ServerParse.Parse("update ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Update, ServerParse.Parse("UPDATE ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Update, ServerParse.Parse("UPDate ..."
				));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsShowDatabases()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Databases, ServerParseShow.Parse(
				"show databases", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Databases, ServerParseShow.Parse(
				"SHOW DATABASES", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Databases, ServerParseShow.Parse(
				"SHOW databases ", 4));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsShowDataSources()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Datasources, ServerParseShow.Parse
				("show datasources", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Datasources, ServerParseShow.Parse
				("SHOW DATASOURCES", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Datasources, ServerParseShow.Parse
				("  SHOW   DATASOURCES  ", 6));
		}

		[NUnit.Framework.Test]
		public virtual void TestShowCobarStatus()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseShow.CobarStatus, ServerParseShow.Parse
				("show cobar_status", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.CobarStatus, ServerParseShow.Parse
				("show cobar_status ", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.CobarStatus, ServerParseShow.Parse
				(" SHOW COBAR_STATUS", " SHOW".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse(" show cobar_statu"
				, " SHOW".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse(" show cobar_status2"
				, " SHOW".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse("Show cobar_status2 "
				, "SHOW".Length));
		}

		[NUnit.Framework.Test]
		public virtual void TestShowCobarCluster()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseShow.CobarCluster, ServerParseShow.Parse
				("show cobar_cluster", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.CobarCluster, ServerParseShow.Parse
				("Show cobar_CLUSTER ", 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.CobarCluster, ServerParseShow.Parse
				(" show  COBAR_cluster", 5));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse(" show cobar_clust"
				, 5));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse(" show cobar_cluster2"
				, 5));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse("Show COBAR_cluster9 "
				, 4));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsShowOther()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse("show ..."
				, 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse("SHOW ..."
				, 4));
			NUnit.Framework.Assert.AreEqual(ServerParseShow.Other, ServerParseShow.Parse("SHOW ... "
				, 4));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSetAutocommitOn()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOn, ServerParseSet.Parse
				("set autocommit=1", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOn, ServerParseSet.Parse
				("set autoCOMMIT = 1", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOn, ServerParseSet.Parse
				("SET AUTOCOMMIT=on", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOn, ServerParseSet.Parse
				("set autoCOMMIT = ON", 3));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSetAutocommitOff()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOff, ServerParseSet.Parse
				("set autocommit=0", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOff, ServerParseSet.Parse
				("SET AUTOCOMMIT= 0", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOff, ServerParseSet.Parse
				("set autoCOMMIT =OFF", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.AutocommitOff, ServerParseSet.Parse
				("set autoCOMMIT = off", 3));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSetNames()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.Names, unchecked((int)(0xff)) & ServerParseSet
				.Parse("set names utf8", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.Names, unchecked((int)(0xff)) & ServerParseSet
				.Parse("SET NAMES UTF8", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.Names, unchecked((int)(0xff)) & ServerParseSet
				.Parse("set NAMES utf8", 3));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsCharacterSetResults()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.CharacterSetResults, unchecked((int
				)(0xff)) & ServerParseSet.Parse("SET character_set_results  = NULL", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.CharacterSetResults, unchecked((int
				)(0xff)) & ServerParseSet.Parse("SET CHARACTER_SET_RESULTS= NULL", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.CharacterSetResults, unchecked((int
				)(0xff)) & ServerParseSet.Parse("Set chARActer_SET_RESults =  NULL", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.CharacterSetConnection, unchecked(
				(int)(0xff)) & ServerParseSet.Parse("Set chARActer_SET_Connection =  NULL", 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.CharacterSetClient, unchecked((int
				)(0xff)) & ServerParseSet.Parse("Set chARActer_SET_client =  NULL", 3));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSetOther()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.Other, ServerParseSet.Parse("set ..."
				, 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.Other, ServerParseSet.Parse("SET ..."
				, 3));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.Other, ServerParseSet.Parse("sEt ..."
				, 3));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsKill()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Kill, unchecked((int)(0xff)) & ServerParse
				.Parse(" kill  ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Kill, unchecked((int)(0xff)) & ServerParse
				.Parse("kill 111111 ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Kill, unchecked((int)(0xff)) & ServerParse
				.Parse("KILL  1335505632"));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsKillQuery()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.KillQuery, unchecked((int)(0xff)) & ServerParse
				.Parse(" kill query ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.KillQuery, unchecked((int)(0xff)) & ServerParse
				.Parse("kill   query 111111 ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.KillQuery, unchecked((int)(0xff)) & ServerParse
				.Parse("KILL QUERY 1335505632"));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSavepoint()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Savepoint, ServerParse.Parse(" savepoint  ..."
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Savepoint, ServerParse.Parse("SAVEPOINT "
				));
			NUnit.Framework.Assert.AreEqual(ServerParse.Savepoint, ServerParse.Parse(" SAVEpoint   a"
				));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsUse()
		{
			NUnit.Framework.Assert.AreEqual(ServerParse.Use, unchecked((int)(0xff)) & ServerParse
				.Parse(" use  ..."));
			NUnit.Framework.Assert.AreEqual(ServerParse.Use, unchecked((int)(0xff)) & ServerParse
				.Parse("USE "));
			NUnit.Framework.Assert.AreEqual(ServerParse.Use, unchecked((int)(0xff)) & ServerParse
				.Parse(" Use   a"));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsStartTransaction()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseStart.Transaction, ServerParseStart.Parse
				(" start transaction  ...", 6));
			NUnit.Framework.Assert.AreEqual(ServerParseStart.Transaction, ServerParseStart.Parse
				("START TRANSACTION", 5));
			NUnit.Framework.Assert.AreEqual(ServerParseStart.Transaction, ServerParseStart.Parse
				(" staRT   TRANSaction  ", 6));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSelectVersionComment()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.VersionComment, ServerParseSelect
				.Parse(" select @@version_comment  ", 7));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.VersionComment, ServerParseSelect
				.Parse("SELECT @@VERSION_COMMENT", 6));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.VersionComment, ServerParseSelect
				.Parse(" selECT    @@VERSION_comment  ", 7));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSelectVersion()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Version, ServerParseSelect.Parse
				(" select version ()  ", 7));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Version, ServerParseSelect.Parse
				("SELECT VERSION(  )", 6));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Version, ServerParseSelect.Parse
				(" selECT    VERSION()  ", 7));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSelectDatabase()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Database, ServerParseSelect.Parse
				(" select database()  ", 7));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Database, ServerParseSelect.Parse
				("SELECT DATABASE()", 6));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Database, ServerParseSelect.Parse
				(" selECT    DATABASE()  ", 7));
		}

		[NUnit.Framework.Test]
		public virtual void TestIsSelectUser()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.User, ServerParseSelect.Parse(" select user()  "
				, 7));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.User, ServerParseSelect.Parse("SELECT USER()"
				, 6));
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.User, ServerParseSelect.Parse(" selECT    USER()  "
				, 7));
		}

		[NUnit.Framework.Test]
		public virtual void TestTxReadUncommitted()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxReadUncommitted, ServerParseSet.
				Parse("  SET SESSION TRANSACTION ISOLATION LEVEL READ  UNCOMMITTED  ", "  SET".Length
				));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxReadUncommitted, ServerParseSet.
				Parse(" set session transaction isolation level read  uncommitted  ", " SET".Length
				));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxReadUncommitted, ServerParseSet.
				Parse(" set session transaCTION ISOLATION LEvel read  uncommitteD ", " SET".Length
				));
		}

		[NUnit.Framework.Test]
		public virtual void TestTxReadCommitted()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxReadCommitted, ServerParseSet.Parse
				("  SET SESSION TRANSACTION ISOLATION LEVEL READ  COMMITTED  ", "  SET".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxReadCommitted, ServerParseSet.Parse
				(" set session transaction isolation level read  committed  ", " SET".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxReadCommitted, ServerParseSet.Parse
				(" set session transaCTION ISOLATION LEVel read  committed ", " SET".Length));
		}

		[NUnit.Framework.Test]
		public virtual void TestTxRepeatedRead()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxRepeatedRead, ServerParseSet.Parse
				("  SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE   READ  ", "  SET".Length
				));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxRepeatedRead, ServerParseSet.Parse
				(" set session transaction isolation level repeatable   read  ", " SET".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxRepeatedRead, ServerParseSet.Parse
				(" set session transaction isOLATION LEVEL REPEatable   read ", " SET".Length));
		}

		[NUnit.Framework.Test]
		public virtual void TestTxSerializable()
		{
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxSerializable, ServerParseSet.Parse
				("  SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE  ", "  SET".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxSerializable, ServerParseSet.Parse
				(" set session transaction   isolation level serializable  ", " SET".Length));
			NUnit.Framework.Assert.AreEqual(ServerParseSet.TxSerializable, ServerParseSet.Parse
				(" set session   transaction  isOLATION LEVEL SERIAlizable ", " SET".Length));
		}

		[NUnit.Framework.Test]
		public virtual void TestIdentity()
		{
			string stmt = "select @@identity";
			int indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterIdentity(stmt, stmt.
				IndexOf('i'));
			NUnit.Framework.Assert.AreEqual(stmt.Length, indexAfterLastInsertIdFunc);
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Identity, ServerParseSelect.Parse
				(stmt, 6));
			stmt = "select  @@identity as id";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Identity, ServerParseSelect.Parse
				(stmt, 6));
			stmt = "select  @@identitY  id";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Identity, ServerParseSelect.Parse
				(stmt, 6));
			stmt = "select  /*foo*/@@identitY  id";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Identity, ServerParseSelect.Parse
				(stmt, 6));
			stmt = "select/*foo*/ @@identitY  id";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Identity, ServerParseSelect.Parse
				(stmt, 6));
			stmt = "select/*foo*/ @@identitY As id";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Identity, ServerParseSelect.Parse
				(stmt, 6));
			stmt = "select  @@identity ,";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select  @@identity as, ";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select  @@identity as id  , ";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select  @@identity ass id   ";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
		}

		[NUnit.Framework.Test]
		public virtual void TestLastInsertId()
		{
			string stmt = " last_insert_iD()";
			int indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt
				, stmt.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.Length, indexAfterLastInsertIdFunc);
			stmt = " last_insert_iD ()";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.Length, indexAfterLastInsertIdFunc);
			stmt = " last_insert_iD ( /**/ )";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.Length, indexAfterLastInsertIdFunc);
			stmt = " last_insert_iD (  )  ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.LastIndexOf(')') + 1, indexAfterLastInsertIdFunc
				);
			stmt = " last_insert_id(  )";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.LastIndexOf(')') + 1, indexAfterLastInsertIdFunc
				);
			stmt = "last_iNsert_id(  ) ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.LastIndexOf(')') + 1, indexAfterLastInsertIdFunc
				);
			stmt = " last_insert_iD";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(-1, indexAfterLastInsertIdFunc);
			stmt = " last_insert_i     ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(-1, indexAfterLastInsertIdFunc);
			stmt = " last_insert_i    d ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(-1, indexAfterLastInsertIdFunc);
			stmt = " last_insert_id (     ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(-1, indexAfterLastInsertIdFunc);
			stmt = " last_insert_id(  d)     ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(-1, indexAfterLastInsertIdFunc);
			stmt = " last_insert_id(  ) d    ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.LastIndexOf(')') + 1, indexAfterLastInsertIdFunc
				);
			stmt = " last_insert_id(d)";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(-1, indexAfterLastInsertIdFunc);
			stmt = " last_insert_id(#\r\nd) ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(-1, indexAfterLastInsertIdFunc);
			stmt = " last_insert_id(#\n\r) ";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.LastIndexOf(')') + 1, indexAfterLastInsertIdFunc
				);
			stmt = " last_insert_id (#\n\r)";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.LastIndexOf(')') + 1, indexAfterLastInsertIdFunc
				);
			stmt = " last_insert_id(#\n\r)";
			indexAfterLastInsertIdFunc = ServerParseSelect.IndexAfterLastInsertIdFunc(stmt, stmt
				.IndexOf('l'));
			NUnit.Framework.Assert.AreEqual(stmt.LastIndexOf(')') + 1, indexAfterLastInsertIdFunc
				);
			stmt = "select last_insert_id(#\n\r)";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r) as id";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r) as `id`";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r) as 'id'";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)  id";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)  `id`";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)  'id'";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r) a";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			// NOTE: this should be invalid, ignore this bug
			stmt = "select last_insert_id(#\n\r) as";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r) asd";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			// NOTE: this should be invalid, ignore this bug
			stmt = "select last_insert_id(#\n\r) as 777";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			// NOTE: this should be invalid, ignore this bug
			stmt = "select last_insert_id(#\n\r)  777";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)as `77``7`";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)ass";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)as 'a'";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)as 'a\\''";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)as 'a'''";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "select last_insert_id(#\n\r)as 'a\"'";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 6));
			stmt = "   select last_insert_id(#\n\r) As 'a\"'";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.LastInsertId, ServerParseSelect
				.Parse(stmt, 9));
			stmt = "select last_insert_id(#\n\r)as 'a\"\\'";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select last_insert_id(#\n\r)as `77``7` ,";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select last_insert_id(#\n\r)as `77`7`";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select last_insert_id(#\n\r) as,";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select last_insert_id(#\n\r) ass a";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
			stmt = "select last_insert_id(#\n\r) as 'a";
			NUnit.Framework.Assert.AreEqual(ServerParseSelect.Other, ServerParseSelect.Parse(
				stmt, 6));
		}
	}
}


text:
@interface NAViewController ()

@property (strong, nonatomic) NAArrowView *arrowView;
@property (strong, nonatomic) UIImagePickerController *picker;

@property (weak, nonatomic) IBOutlet UIView *controlsView;
@property (weak, nonatomic) IBOutlet UIView *statusBarView;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;

@end

@implementation NAViewController

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setTranslatesAutoresizingMaskIntoConstraints:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.picker.showsCameraControls = NO;
    self.picker.navigationBarHidden = YES;
    self.picker.toolbarHidden = YES;
    self.picker.cameraViewTransform =
    CGAffineTransformScale(self.picker.cameraViewTransform,
                           1.0,
                           (self.view.frame.size.height -
                            self.controlsView.frame.size.height) /
                           self.view.frame.size.width);

    UIView *overlayView =
    [[UIView alloc] initWithFrame:self.view.frame];

    overlayView.opaque = NO;
    overlayView.backgroundColor = [UIColor clearColor];

    [self setupArrowViewInView:overlayView];
    [overlayView addSubview:self.controlsView];
    [overlayView addSubview:self.statusBarView];
    [overlayView addSubview:self.distanceLabel];
    [overlayView addSubview:self.locationLabel];

    self.picker.cameraOverlayView = overlayView;
}

- (void)viewDidAppear:(BOOL)animated
{
    [self presentViewController:self.picker animated:NO completion:nil];
}

#pragma mark - Setup

- (void)setupArrowViewInView:(UIView *)view
{
    CGRect frame = CGRectMake(view.frame.size.width / 6.0,
                              view.frame.size.height / 10.0,
                              4.0 * view.frame.size.width / 6.0,
                              5.5 * view.frame.size.height / 10.0);
    self.arrowView = [[NAArrowView alloc] initWithFrame:frame];
    self.arrowView.delegate = self;
    [view addSubview:self.arrowView];
}

#pragma mark - Button actions

- (IBAction)buttonPressed:(UIButton *)sender
{
    if ([sender.titleLabel.text isEqualToString:@"Featheringill Hall"]) {
        self.arrowView.destination =
        [[CLLocation alloc] initWithLatitude:36.1447809
                                   longitude:-86.8032186];
    } else if ([sender.titleLabel.text isEqualToString:@"Roma"]) {
        self.arrowView.destination =
        [[CLLocation alloc] initWithLatitude:36.1480013
                                   longitude:-86.8083296];
    } else if ([sender.titleLabel.text isEqualToString:@"Ben & Jerry's"]) {
        self.arrowView.destination =
        [[CLLocation alloc] initWithLatitude:36.146143
                                   longitude:-86.7994725];
    } else if ([sender.titleLabel.text isEqualToString:@"Qdoba"]) {
        self.arrowView.destination =
        [[CLLocation alloc] initWithLatitude:36.1504781
                                   longitude:-86.8008202];
    }

    self.locationLabel.text = sender.titleLabel.text;
    self.distanceLabel.text = [self.arrowView.locationManager distanceToLocation:self.arrowView.destination];

    if (!self.arrowView.isPointing) {
        [self.arrowView startPointing];
    }
}

#pragma mark - NAArrowViewDelegate

- (void)locationManager:(CLLocationManager *)manager
	 didUpdateLocations:(NSArray *)locations
{
    self.distanceLabel.text = [manager distanceToLocation:self.arrowView.destination];
}

@end


text:
package se.itello.commandrunner.gui.commandtable;

import javafx.scene.control.TreeItem;
import se.itello.commandrunner.Command;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class CommandTableRowTreeItemListManipulator {
    public static List<TreeItem<CommandTableRow>> getFlatTreeItemList(TreeItem<CommandTableRow> root) {
        List<TreeItem<CommandTableRow>> items = new ArrayList<>();
        TreeItem<CommandTableRow> node = root;

        Deque<TreeItem<CommandTableRow>> rows = new ArrayDeque<>();
        rows.push(node);

        while (!rows.isEmpty()) {
            node = rows.removeFirst();
            node.getChildren().forEach(rows::addLast);
            items.add(node);
        }

        return items;
    }

    public static void addAllCommandRowsForTreeItem(TreeItem<CommandTableRow> item, List<CommandTableCommandRow> commandRows) {
        CommandTableRow row = item.getValue();

        if (row instanceof CommandTableCommandRow) {
            if (commandRows.contains(row)) {
                return;
            }

            CommandTableCommandRow commandRow = (CommandTableCommandRow) row;
            final Command command = commandRow.getCommand();
            commandRows.add(commandRow);

            TreeItem<CommandTableRow> parentItem = item.getParent();
            while (parentItem != null) {
                final String parentCommandDirectory = parentItem.getValue().commandDirectoryProperty().getValue();
                if (!parentCommandDirectory.isEmpty()) {
                    command.setParentCommandDirectory(parentCommandDirectory);
                    break;
                }

                parentItem = parentItem.getParent();
            }
        } else if (row instanceof CommandTableGroupRow) {
            item.getChildren().forEach(child -> addAllCommandRowsForTreeItem(child, commandRows));
        } else {
            throw new UnsupportedOperationException("unidentified row");
        }
    }
}


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>

                    Metrics ({{registry.updateInterval()}} ms)

Last Update {{registry.lastUpdate.format('HH:mm:ss')}}

                                show all
                                &nbsp|
                                hide all

Update every

                            100 milliseconds

                            500 milliseconds

                            1 second

                            5 seconds

                            10 seconds

                            Don't update

Chart size

                            Small

                            Medium

                            Large

Reset Config & Data

                    {{metric.name}}

                                show all
                                 |
                                hide all

                            <form role="form" class="form-inline">

                                        <input type="text" placeholder="Search {{metric.name}}" class="form-control" ng-model="search.name" />

                                            <button type="button" class="btn btn-default form-control" ng-click="search.name = ''">×</button>

                            </form>

                                    <input type="checkbox" ng-checked="chart.isVisible()"
                                           ng-click="chart.toggle()" />{{chart.name}}

                    Health Status ({{healthMonitor.updateInterval() / 1000}} s)

Unhealthy

                            {{line.name}}

Healthy

                            {{line.name}}

Update every

                            1 second

                            5 seconds

                            10 seconds

                            30 seconds

                            60 seconds

                            10 minutes

                            Don't update

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            {{registry.updateError}} retry

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            {{healthMonitor.updateError}} retry

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

{{healthItem.name}}

{{healthItem.text}}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
/**
 * The descriptor for a cells range.
 * For example: `{startRow: 1, startCol: 1, endRow: 2, endColumn: 2}` is a range with four cells.
 * And `{startRow: 1, endRow: 2}` is a range with two rows.
 * - For the cells block, four properties are required.
 * - For the rows, `startRow` and `endRow` are required.
 * - For the columns, `startCol` and `endColumn` are required.
 */
type RangeDescriptor = {
  startRow?: number;
  startColumn?: number;
  endRow?: number;
  endColumn?: number;
};

/**
 * The descriptor for a selection
 * @see SelectionType
 */
type SelectionDescriptor = {
  type: number;
} & RangeDescriptor;

type ContextForSelectionAction = {
  rows?: number;
  columns?: number;
};

type RectangleObject = {
  top: number;
  bottom: number;
  left: number;
  right: number;
};

type ClipboardInterface = {
  setData: (mimeType: string, data: any) => any;
};


text:
package br.com.touchtec.games.web;

import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import br.com.touchtec.games.core.model.ItemPedido;
import br.com.touchtec.games.core.model.Jogo;
import br.com.touchtec.games.core.model.Plataforma;

@Scope("session")
@Component
public class CarrinhoDeCompras implements Serializable {

    private static final long serialVersionUID = 1L;

    // Não queremos repetições e queremos manter a ordem
    private Set<ItemPedido> items = new LinkedHashSet<>();

    public void addItem(Jogo jogo, Integer quantidade, Plataforma plataforma) {
        ItemPedido itemPedido = new ItemPedido();
        itemPedido.setJogo(jogo);
        itemPedido.setQuantidade(quantidade);
        itemPedido.setPlataforma(plataforma);

        this.items.remove(itemPedido);

        this.items.add(itemPedido);
    }

    public void removeItem(Integer index) {
        // como garantimos a ordem do set, é possivel encontrar um item iterando

        int i = 0;
        for (Iterator iterator = this.items.iterator(); iterator.hasNext(); i++) {
            iterator.next();
            if (i == index) {
                iterator.remove();
                break;
            }
        }

    }

    public Set<ItemPedido> getItems() {
        return this.items;
    }

    public void clear() {
        this.getItems().clear();
    }

    public Integer getSize() {
        return this.items.size();
    }

    public Float getTotal() {
        Float total = 0f;
        for (ItemPedido item : this.items) {
            total += item.getValorTotalItem();
        }
        return total;
    }
}


text:
package com.hotels.styx.proxy.backends.file;

import com.fasterxml.jackson.databind.JsonNode;
import com.hotels.styx.StyxConfig;
import com.hotels.styx.api.Environment;
import com.hotels.styx.api.configuration.Configuration;
import com.hotels.styx.api.configuration.ConfigurationException;
import com.hotels.styx.api.extension.service.spi.Registry;
import com.hotels.styx.infrastructure.configuration.yaml.JsonNodeConfig;
import com.hotels.styx.proxy.backends.file.FileChangeMonitor.FileMonitorSettings;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

import static com.google.common.io.Files.createTempDir;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.copy;
import static java.nio.file.Files.delete;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class FileBackedBackendServicesRegistryFactoryTest {

    private File tempDir;
    private Path monitoredFile;
    private Environment environment;

    @BeforeEach
    public void setUp() throws Exception {
        tempDir = createTempDir();
        monitoredFile = Paths.get(tempDir.toString(), "origins.yml");
        write(monitoredFile, "content-v1");
        environment = new com.hotels.styx.Environment.Builder().build();
    }

    @AfterEach
    public void tearDown() throws Exception {
        delete(monitoredFile);
        delete(tempDir.toPath());
    }

    @Test
    public void instantiatesFromYaml() {

        environment = new com.hotels.styx.Environment.Builder()
                .configuration(StyxConfig.fromYaml("config: {originsFile: '${CONFIG_LOCATION:classpath:}/conf/origins/backend-factory-origins.yml'}", false))
                .build();

        JsonNodeConfig factoryConfig = new JsonNodeConfig(environment.configuration().get("config", JsonNode.class).get());

        Registry registry = new FileBackedBackendServicesRegistry.Factory().create(environment, factoryConfig);

        assertThat(registry != null, is(true));
    }

    @Test
    public void requiresOriginsFileToBeSet() {
        Configuration configuration = mockConfiguration(Optional.of(""));

        Exception e = assertThrows(ConfigurationException.class,
                () -> new FileBackedBackendServicesRegistry.Factory().create(environment, configuration));
        assertTrue(e.getMessage()
                .matches("empty .services.registry.factory.config.originsFile. config value for factory class FileBackedBackendServicesRegistry.Factory"));
    }

    @Test
    public void requiresOriginsFileToBeNonEmpty() {
        Configuration configuration = mockConfiguration(Optional.empty());

        Exception e = assertThrows(ConfigurationException.class,
                () -> new FileBackedBackendServicesRegistry.Factory().create(environment, configuration));
        assertTrue(e.getMessage()
                .matches("missing .services.registry.factory.config.originsFile. config value for factory class FileBackedBackendServicesRegistry.Factory"));
    }

    @Test
    public void fileMonitorIsTurnedOffByDefault() {
        Configuration configuration = mockConfiguration(Optional.of("/styx/config/path/origins.yml"), Optional.empty());

        FileBackedBackendServicesRegistry registry = (FileBackedBackendServicesRegistry)new FileBackedBackendServicesRegistry.Factory().create(environment, configuration);
        assertThat(registry.monitor(), is(FileMonitor.DISABLED));
    }

    @Test
    public void createsWithFileChangeMonitor() {
        Configuration configuration = mockConfiguration(Optional.of(monitoredFile.toString()), Optional.of(new FileMonitorSettings(true)));

        FileBackedBackendServicesRegistry registry = (FileBackedBackendServicesRegistry)new FileBackedBackendServicesRegistry.Factory().create(environment, configuration);
        assertThat(registry.monitor(), instanceOf(FileChangeMonitor.class));
    }

    private Configuration mockConfiguration(Optional<String> path) {
        Configuration configuration = mock(Configuration.class);
        when(configuration.get(eq("originsFile"), eq(String.class))).thenReturn(path);
        return configuration;
    }

    private Configuration mockConfiguration(Optional<String> path, Optional<FileMonitorSettings> monitorSettings) {
        Configuration configuration = mock(Configuration.class);
        when(configuration.get(eq("originsFile"), eq(String.class))).thenReturn(path);
        when(configuration.get(eq("monitor"), eq(FileMonitorSettings.class))).thenReturn(monitorSettings);
        return configuration;
    }

    void write(Path path, String text) throws Exception {
        copy(new ByteArrayInputStream(text.getBytes(UTF_8)), path, REPLACE_EXISTING);
    }

}


text:
package org.jboss.elasticsearch.river.jira.mgm;

import java.util.concurrent.atomic.AtomicReferenceArray;

import junit.framework.Assert;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.threadpool.ThreadPool;
import org.jboss.elasticsearch.river.jira.IJiraRiverMgm;
import org.jboss.elasticsearch.river.jira.JiraRiver;
import org.jboss.elasticsearch.river.jira.mgm.lifecycle.JRLifecycleCommand;
import org.jboss.elasticsearch.river.jira.mgm.lifecycle.JRLifecycleRequest;
import org.jboss.elasticsearch.river.jira.mgm.lifecycle.JRLifecycleResponse;
import org.jboss.elasticsearch.river.jira.mgm.lifecycle.NodeJRLifecycleRequest;
import org.jboss.elasticsearch.river.jira.mgm.lifecycle.NodeJRLifecycleResponse;
import org.jboss.elasticsearch.river.jira.mgm.lifecycle.TransportJRLifecycleAction;
import org.jboss.elasticsearch.river.jira.mgm.lifecycle.TransportJRLifecycleActionTest;
import org.junit.Test;
import org.mockito.Mockito;

/**
 * Unit test for {@link TransportJRMgmBaseAction}.
 *
 * @author Vlastimil Elias (velias at redhat dot com)
 */
public class TransportJRMgmBaseActionTest {

	protected static final ClusterName clusterName = TransportJRLifecycleActionTest.clusterName;
	DiscoveryNode dn = new DiscoveryNode("aa", DummyTransportAddress.INSTANCE, Version.CURRENT);
	DiscoveryNode dn2 = new DiscoveryNode("aa2", DummyTransportAddress.INSTANCE, Version.CURRENT);

	@Test
	public void constructor() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);
		Assert.assertNotNull(tested.logger);
		Assert.assertEquals(
				"org.elasticsearch.org.jboss.elasticsearch.river.jira.mgm.lifecycle.TransportJRLifecycleAction",
				tested.logger.getName());
	}

	@Test
	public void newResponse() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);

		{
			AtomicReferenceArray<NodeJRLifecycleResponse> responses = new AtomicReferenceArray<NodeJRLifecycleResponse>(0);
			JRLifecycleResponse res = tested.newResponse(null, responses);
			Assert.assertEquals(clusterName, res.getClusterName());
			Assert.assertEquals(0, res.getNodes().length);
		}

		{
			AtomicReferenceArray<NodeJRLifecycleResponse> responses = new AtomicReferenceArray<NodeJRLifecycleResponse>(
					new NodeJRLifecycleResponse[] { new NodeJRLifecycleResponse(dn), new NodeJRLifecycleResponse(dn2) });
			JRLifecycleResponse res = tested.newResponse(null, responses);
			Assert.assertEquals(clusterName, res.getClusterName());
			Assert.assertEquals(2, res.getNodes().length);
		}

	}

	@Test
	public void executor() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);
		Assert.assertEquals(ThreadPool.Names.MANAGEMENT, tested.executor());
	}

	@Test
	public void accumulateExceptions() {
		TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);
		Assert.assertEquals(false, tested.accumulateExceptions());
	}

	@Test
	public void nodeOperation() {

		String myRiverName = "myRiver";

		IJiraRiverMgm jiraRiverMock = Mockito.mock(IJiraRiverMgm.class);
		RiverName riverName = new RiverName("jira", myRiverName);
		Mockito.when(jiraRiverMock.riverName()).thenReturn(riverName);

		JiraRiver.addRunningInstance(jiraRiverMock);

		try {
			TransportJRLifecycleAction tested = TransportJRLifecycleActionTest.prepareTestedInstance(clusterName);

			Mockito.reset(jiraRiverMock);
			{
				NodeJRLifecycleRequest nodeRequest = new NodeJRLifecycleRequest("ndid", new JRLifecycleRequest("unknownRiver",
						JRLifecycleCommand.STOP));
				NodeJRLifecycleResponse resp = tested.nodeOperation(nodeRequest);
				Assert.assertNotNull(resp);
				Assert.assertFalse(resp.riverFound);
				Mockito.verifyZeroInteractions(jiraRiverMock);
			}

			Mockito.reset(jiraRiverMock);
			{
				NodeJRLifecycleRequest nodeRequest = new NodeJRLifecycleRequest("ndid", new JRLifecycleRequest(myRiverName,
						JRLifecycleCommand.STOP));
				NodeJRLifecycleResponse resp = tested.nodeOperation(nodeRequest);
				Assert.assertNotNull(resp);
				Assert.assertTrue(resp.riverFound);
				Mockito.verify(jiraRiverMock).stop(true);
				Mockito.verifyNoMoreInteractions(jiraRiverMock);
			}

		} finally {
			JiraRiver.removeRunningInstances(myRiverName);
		}
	}

}


text:
"""dv order history fix

Revision ID: b82e99329bf5
Revises: a43f72b7c848
Create Date: 2019-04-22 14:27:02.384999

"""
from alembic import op

# revision identifiers, used by Alembic.
revision = "b82e99329bf5"
down_revision = "a43f72b7c848"
branch_labels = None
depends_on = None

def upgrade(engine_name):
    globals()["upgrade_%s" % engine_name]()

def downgrade(engine_name):
    globals()["downgrade_%s" % engine_name]()

def upgrade_rdr():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute(
        "ALTER TABLE biobank_dv_order_history CHANGE COLUMN `created` `created` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);"
    )
    op.execute(
        "ALTER TABLE biobank_dv_order_history CHANGE COLUMN `modified` `modified` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);"
    )
    # ### end Alembic commands ###

def downgrade_rdr():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

def upgrade_metrics():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

def downgrade_metrics():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###


text:
package org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author Max Medvedev
 */
public class ConditionInstruction extends InstructionImpl implements Instruction {

  private final Set<ConditionInstruction> myDependent;

  public ConditionInstruction(@NotNull PsiElement element, @NotNull Collection<ConditionInstruction> dependent) {
    super(element);
    myDependent = new LinkedHashSet<>(dependent);
    myDependent.add(this);
  }

  @NotNull
  @Override
  protected String getElementPresentation() {
    StringBuilder builder = new StringBuilder();
    builder.append("Condition ").append(getElement());
    if (myDependent.size() > 1) {
      builder.append(", dependent: ");
      builder.append(StringUtil.join(ContainerUtil.filter(myDependent, d -> d != this), i -> String.valueOf(i.num()), ", "));
    }
    return builder.toString();
  }

  public Set<ConditionInstruction> getDependentConditions() {
    return myDependent;
  }
}