text:
import com.mongodb.MongoClient;
import com.whatistics.backend.configuration.TypedProperties;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

import java.io.FileReader;
import java.io.IOException;

/**
 * Load configuration for use in tests.
 * @author robert
 */
public class MasterTest {
    protected TypedProperties globalProperties = new TypedProperties();

    protected Datastore ds;

    MasterTest(){
        try {
            this.globalProperties.load(this.getClass().getClassLoader().getResourceAsStream("global.properties"));
            this.globalProperties.load(this.getClass().getClassLoader().getResourceAsStream("password.properties"));
            this.globalProperties.load(this.getClass().getClassLoader().getResourceAsStream("dev.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.ds = new Morphia().createDatastore(new MongoClient(globalProperties.getProperty("mongoClientHostname")), globalProperties.getProperty("dbTestName"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.incode.module.commchannel.integtests.postaladdress;

import java.util.SortedSet;

import javax.inject.Inject;

import com.google.common.eventbus.Subscribe;

import org.junit.Before;
import org.junit.Test;

import org.apache.isis.applib.AbstractSubscriber;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;

import org.incode.module.commchannel.dom.impl.channel.CommunicationChannel;
import org.incode.module.commchannel.dom.impl.postaladdress.T_addPostalAddress;
import org.incode.module.commchannel.dom.impl.postaladdress.PostalAddress;
import org.incode.module.commchannel.dom.impl.type.CommunicationChannelType;
import org.incode.module.commchannel.fixture.dom.CommChannelDemoObject;
import org.incode.module.commchannel.fixture.dom.CommChannelDemoObjectMenu;
import org.incode.module.commchannel.fixture.scripts.teardown.CommChannelDemoObjectsTearDownFixture;
import org.incode.module.commchannel.integtests.CommChannelModuleIntegTest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assume.assumeThat;

public class CommunicationChannelOwner_addPostalAddress_IntegTest extends CommChannelModuleIntegTest {

    @Inject
    CommChannelDemoObjectMenu commChannelDemoObjectMenu;

    CommChannelDemoObject fredDemoOwner;

    @Before
    public void setUpData() throws Exception {
        fixtureScripts.runFixtureScript(new CommChannelDemoObjectsTearDownFixture(), null);

        fredDemoOwner = wrap(commChannelDemoObjectMenu).create("Fred");
    }

    public static class ActionImplementationIntegrationTest extends
            CommunicationChannelOwner_addPostalAddress_IntegTest {

        @Test
        public void can_create_postal_address_without_looking_up_geocode() throws Exception {

            // given
            final SortedSet<CommunicationChannel> channelsBefore = wrap(mixinCommunicationChannels(fredDemoOwner)).$$();
            assertThat(channelsBefore).hasSize(0);

            // when
            wrap(mixinNewPostalAddress(fredDemoOwner)).$$(
                    "Flat 2a", "45 Penny Lane", "Allerton", "Liverpool", "L39 5AA", "UK", "Home", "Fred Smith's home",
                    false);

            // then
            final SortedSet<CommunicationChannel> channelsAfter = wrap(mixinCommunicationChannels(fredDemoOwner)).$$();

            assertThat(channelsAfter).hasSize(1);
            final CommunicationChannel communicationChannel = channelsAfter.first();

            assertThat(communicationChannel.getName()).isEqualTo("Flat 2a, 45 Pe..., L39 5AA, UK");
            assertThat(communicationChannel.getPurpose()).isEqualTo("Home");
            assertThat(communicationChannel.getNotes()).isEqualTo("Fred Smith's home");
            assertThat(communicationChannel.getType()).isEqualTo(CommunicationChannelType.POSTAL_ADDRESS);
            assertThat(communicationChannel.getId()).isNotNull();

            assertThat(communicationChannel.getLocation()).isNull();

            assertThat(communicationChannel).isInstanceOf(PostalAddress.class);
            final PostalAddress postalAddress = (PostalAddress)communicationChannel;
            assertThat(postalAddress.getAddressLine1()).isEqualTo("Flat 2a");
            assertThat(postalAddress.getAddressLine2()).isEqualTo("45 Penny Lane");
            assertThat(postalAddress.getAddressLine3()).isEqualTo("Allerton");
            assertThat(postalAddress.getAddressLine4()).isEqualTo("Liverpool");
            assertThat(postalAddress.getPostalCode()).isEqualTo("L39 5AA");
            assertThat(postalAddress.getCountry()).isEqualTo("UK");
            assertThat(postalAddress.getFormattedAddress()).isNull();
            assertThat(postalAddress.getGeocodeApiResponseAsJson()).isNull();
            assertThat(postalAddress.getLatLng()).isNull();
            assertThat(postalAddress.getPlaceId()).isNull();
            assertThat(postalAddress.getAddressComponents()).isNull();
        }

        @Test
        public void can_create_postal_address_and_also_look_up_geocode() throws Exception {

            assumeThat(isInternetReachable(), is(true));

            // given
            final SortedSet<CommunicationChannel> channelsBefore = wrap(mixinCommunicationChannels(fredDemoOwner)).$$();
            assertThat(channelsBefore).hasSize(0);

            // when
            wrap(mixinNewPostalAddress(fredDemoOwner)).$$(
                    "45", "High Street", "Oxford", "Oxfordshire", "OX1", "UK", "Work", "Fred Smith's work", true);

            // then
            final SortedSet<CommunicationChannel> channelsAfter = wrap(mixinCommunicationChannels(fredDemoOwner)).$$();

            assertThat(channelsAfter).hasSize(1);
            final CommunicationChannel communicationChannel = channelsAfter.first();

            assertThat(communicationChannel.getName()).isEqualTo("45 High St, Oxford OX1, UK");

            assertThat(communicationChannel.getLocation()).isNotNull();

            assertThat(communicationChannel).isInstanceOf(PostalAddress.class);
            final PostalAddress postalAddress = (PostalAddress)communicationChannel;
            assertThat(postalAddress.getFormattedAddress()).isEqualTo("45 High St, Oxford OX1, UK");
            assertThat(postalAddress.getGeocodeApiResponseAsJson()).isNotNull();
            assertThat(postalAddress.getLatLng()).matches("51.752[\\d][\\d][\\d][\\d],-1.250[\\d][\\d][\\d][\\d]");
            assertThat(postalAddress.getPlaceId()).isEqualTo("Eho0NSBIaWdoIFN0LCBPeGZvcmQgT1gxLCBVSw");
            assertThat(postalAddress.getAddressComponents()).isNotNull();
        }
    }

    public static class RaisesEventIntegrationTest extends CommunicationChannelOwner_addPostalAddress_IntegTest {

        @DomainService(nature = NatureOfService.DOMAIN)
        public static class TestSubscriber extends AbstractSubscriber {
            T_addPostalAddress.DomainEvent ev;

            @Subscribe
            public void on(T_addPostalAddress.DomainEvent ev) {
                this.ev = ev;
            }
        }

        @Inject
        TestSubscriber testSubscriber;

        @Test
        public void happy_case() throws Exception {

            wrap(mixinNewPostalAddress(fredDemoOwner)).$$(
                    "Flat 2a", "45 Penny Lane", "Allerton", "Liverpool", "L39 5AA", "UK", "Home", "Fred Smith's home",
                    false);

            assertThat(testSubscriber.ev).isNotNull();
        }

    }

}


text:
import { Hooks } from "sequelize";

declare module "sequelize" {
    export interface Model<TInstance, TAttributes> extends Hooks<TInstance>, Associations {
        /**
         * A hashmap of associations defined for this model.
         * @param {string} key - The name of the association
         * @return {Association} The association definition.
         */
        associations: { [key: string]: Association };
    }

    /**
     * Defines an association between models.
     */
    export interface Association {
        /**
         * The field on the source instance used to access the associated target instance.
         */
        associationAccessor: string;

        /**
         * The type of the association. One of `HasMany`, `BelongsTo`, `HasOne`, `BelongsToMany`
         */
        associationType: string;

        /**
         * The foreign key options specified for this association, if any.
         */
        foreignKey: AssociationForeignKeyOptions;
    }

    /**
     * Defines a BelongsTo association between two models, where the source model as a foreign key to the target.
     */
    export interface BelongsToAssociation extends Association {
        /**
         * The name of the attribute that contains the identifier on the source.
         */
        identifier: string;

        /**
         * The name of the attribute that contains the identifier on the target.
         */
        targetIdentifier: string;
    }
}


text:
<def-group>
  <definition class="compliance" id="dconf_gnome_disable_thumbnailers" version="1">
    <metadata>
      <title>Disable All GNOME3 Thumbnailers</title>
      <affected family="unix">
        <platform>Red Hat Enterprise Linux 7</platform>
        <platform>multi_platform_fedora</platform>
      </affected>
      <description>The system's default desktop environment, GNOME3, uses a
      number of different thumbnailer programs to generate thumbnails for any
      new or modified content in an opened folder. Disable the execution of
      these thumbnail applications within GNOME3.</description>
      <reference source="galford" ref_id="20140824" ref_url="test_attestation" />
    </metadata>
    <criteria operator="OR">
      <extend_definition comment="dconf installed" definition_ref="package_dconf_installed" negate="true" />
      <criteria comment="Disable Gnome3 Thumbnailers and prevent user from enabling" operator="AND">
        <extend_definition comment="dconf user profile exists" definition_ref="enable_dconf_user_profile" />
        <criterion comment="Disable thumbnailers in GNOME3" test_ref="test_gnome_disable_thumbnailers" />
        <criterion comment="prevent user from changing idle delay" test_ref="test_prevent_user_change_gnome_thumbnailers" />
      </criteria>
    </criteria>
  </definition>

  <ind:textfilecontent54_test check="all" check_existence="all_exist"
  comment="Disable thumbnailers in GNOME3"
  id="test_gnome_disable_thumbnailers" version="1">
    <ind:object object_ref="obj_gnome_disable_thumbnailers" />
  </ind:textfilecontent54_test>
  <ind:textfilecontent54_object id="obj_gnome_disable_thumbnailers"
  version="1">
    <ind:path>/etc/dconf/db/local.d/</ind:path>
    <ind:filename operation="pattern match">^.*$</ind:filename>
    <ind:pattern operation="pattern match">^\[org/gnome/desktop/thumbnailers]([^\n]*\n+)+?disable-all=true$</ind:pattern>
    <ind:instance datatype="int">1</ind:instance>
  </ind:textfilecontent54_object>

  <ind:textfilecontent54_test check="all" check_existence="all_exist"
  comment="user cannot enable thumbnailers "
  id="test_prevent_user_change_gnome_thumbnailers" version="1">
    <ind:object object_ref="obj_prevent_user_change_gnome_thumbnailers" />
  </ind:textfilecontent54_test>
  <ind:textfilecontent54_object id="obj_prevent_user_change_gnome_thumbnailers"
  version="1">
    <ind:path>/etc/dconf/db/local.d/locks/</ind:path>
    <ind:filename operation="pattern match">^.*$</ind:filename>
    <ind:pattern operation="pattern match">^/org/gnome/desktop/thumbnailers/disable-all$</ind:pattern>
    <ind:instance datatype="int">1</ind:instance>
  </ind:textfilecontent54_object>
</def-group>


text:
<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */

use app\components\widgets\ActiveForm;
use yii\helpers\Html;

$this->title = 'Request password reset';
$this->params['breadcrumbs'][] = $this->title;
?>

            <?php $form = ActiveForm::begin(['id' => 'request-password-reset-form']); ?>

            <?= $form->field($model, 'email')->textInput(['placeholder' => Yii::t('app','Email')]) ?>
            <?= Html::submitButton(Yii::t('app','Send'), ['class' => 'btn btn-success btn-login']) ?>

                <?= Html::a(Yii::t('app','Login page'), ['login']) ?>

            <?php ActiveForm::end(); ?>


text:
use dfa::Dfa;
use error::Error;
use itertools::Itertools;
use look::Look;
use nfa::{Accept, Nfa, NoLooks, State, StateIdx, StateSet};
use num_traits::PrimInt;
use range_map::{Range, RangeMap, RangeMultiMap};
use std::{char, u8, usize};
use std::cmp::max;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem::swap;
use utf8_ranges::{Utf8Range, Utf8Sequence, Utf8Sequences};

// This provides a more compact way of representing UTF-8 sequences.
//
// A sequence of bytes belongs to this set if its first byte is in `head[0]`, its second byte is
// in `head[1]`, etc., and its last byte belongs to one of the ranges in `last_byte`.
//
// This representation is handy for making NFAs because compared to the representation in
// `Utf8Sequences`, it adds many fewer states. Basically, we are doing some crude minimization
// before creating the states.
struct MergedUtf8Sequences {
    pub head: Vec<Utf8Range>,
    pub last_byte: Vec<Utf8Range>,
}

// Returns this range as a pair of chars, or none if this is an empty range.
fn to_char_pair(r: Range<u32>) -> Option<(char, char)> {
    // Round up self.start to the nearest legal codepoint.
    let start = if r.start > 0xD7FF && r.start < 0xE000 {
        0xE000
    } else {
        r.start
    };

    // Round down self.end.
    let end = if r.end > 0x10FFFF {
        0x10FFFF
    } else if r.end < 0xE000 && r.end > 0xD7FF {
        0xD7FF
    } else {
        r.end
    };

    if start > end {
        None
    } else {
        Some((char::from_u32(start).unwrap(), char::from_u32(end).unwrap()))
    }
}

impl MergedUtf8Sequences {
    // Panics if not all the input sequences have the same leading byte ranges.
    fn merge<I>(iter: I) -> MergedUtf8Sequences where I: Iterator<Item=Utf8Sequence> {
        let mut head = Vec::new();
        let mut last_byte = Vec::new();

        for seq in iter {
            let len = seq.len();
            let h = &seq.as_slice()[..len-1];
            if head.is_empty() {
                head.extend_from_slice(h);
            } else if &head[..] != h {
                panic!("invalid sequences to merge");
            }

            last_byte.push(seq.as_slice()[len-1]);
        }

        MergedUtf8Sequences {
            head: head,
            last_byte: last_byte,
        }
    }

    fn from_sequences<'a, I>(iter: I) -> Box<Iterator<Item=MergedUtf8Sequences> + 'a>
    where I: Iterator<Item=Utf8Sequence> + 'a {
        fn head(u: &Utf8Sequence) -> Vec<Utf8Range> {
            let len = u.len();
            u.as_slice()[..len-1].to_owned()
        }

        Box::new(iter
            .group_by(head)
            .into_iter()
            .map(|(_, seqs)| MergedUtf8Sequences::merge(seqs.into_iter())))
    }

    fn from_ranges<'a, I>(iter: I) -> Box<Iterator<Item=MergedUtf8Sequences> + 'a>
    where I: Iterator<Item=Range<u32>> + 'a {
        MergedUtf8Sequences::from_sequences(
            iter.filter_map(to_char_pair)
                .flat_map(|r| Utf8Sequences::new(r.0, r.1)))
    }

    fn num_bytes(&self) -> u8 {
        (self.head.len() + 1) as u8
    }
}

// Creates a byte-based Dfa that matches all the chars in `look.as_set()`.
fn make_char_dfa(look: Look) -> Dfa<(Look, u8)> {
    let mut nfa: Nfa<u32, NoLooks> = Nfa::with_capacity(2);
    nfa.add_state(Accept::Never);
    nfa.add_look_ahead_state(look, 1, 0);
    // TODO: shouldn't adding both Full and Boundary be redundant?
    nfa.init.push((Look::Full, 0));
    nfa.init.push((Look::Boundary, 0));
    nfa.states[0].consuming
        = RangeMultiMap::from_vec(look.as_set().ranges().map(|x| (x, 1)).collect());

    // These unwraps are OK because the only failures are caused by having too many states.
    nfa.byte_me(usize::MAX).unwrap()
        .determinize(usize::MAX).unwrap()
        .optimize()
}

// Creates a byte-based Dfa that matches backwards all the chars in `look.as_set()`.
fn make_rev_char_dfa(look: Look) -> Dfa<(Look, u8)> {
    let mut nfa: Nfa<u8, NoLooks> = Nfa::with_capacity(0); // TODO: better capacity
    nfa.add_state(Accept::Never);
    nfa.init.push((Look::Full, 0));
    nfa.init.push((Look::Boundary, 0));

    // This is more-or-less C&P from add_utf8_sequence.
    for seq in MergedUtf8Sequences::from_ranges(look.as_set().ranges()) {
        let mut last_state = nfa.add_state(Accept::Never);

        for range in &seq.last_byte {
            nfa.add_transition(0, last_state, Range::new(range.start, range.end));
        }
        for range in seq.head.iter().rev() {
            let cur_state = nfa.add_state(Accept::Never);

            nfa.add_transition(last_state, cur_state, Range::new(range.start, range.end));
            last_state = cur_state;
        }

        nfa.states[last_state].accept = Accept::Always;
        nfa.states[last_state].accept_look = look;
        nfa.states[last_state].accept_state = 0;
        nfa.states[last_state].accept_tokens = seq.num_bytes();
    }

    // This unwrap is OK because the only failures are caused by having too many states.
    nfa.determinize(usize::MAX).unwrap()
        .optimize()
}

// We cache optimized Dfas for the expensive looks. See `Nfa<u8, NoLooks>::add_min_utf8_sequences`
// for an explanation.
lazy_static! {
    static ref WORD_CHAR_DFA: Dfa<(Look, u8)> = make_char_dfa(Look::WordChar);
    static ref NOT_WORD_CHAR_DFA: Dfa<(Look, u8)> = make_char_dfa(Look::NotWordChar);
    static ref REV_WORD_CHAR_DFA: Dfa<(Look, u8)> = make_rev_char_dfa(Look::WordChar);
    static ref REV_NOT_WORD_CHAR_DFA: Dfa<(Look, u8)> = make_rev_char_dfa(Look::NotWordChar);
}

impl<Tok: Debug + PrimInt> Nfa<Tok, NoLooks> {
    // Returns the set of all states that can be reached from some initial state.
    fn reachable_from<I>(&self, states: I) -> HashSet<StateIdx> where I: Iterator<Item=StateIdx> {
        let mut active: HashSet<StateIdx> = states.collect();
        let mut next_active: HashSet<StateIdx> = HashSet::new();
        let mut ret = active.clone();

        while !active.is_empty() {
            for &s in &active {
                for &(_, t) in self.states[s].consuming.ranges_values() {
                    if !ret.contains(&t) {
                        ret.insert(t);
                        next_active.insert(t);
                    }
                }
            }
            swap(&mut active, &mut next_active);
            next_active.clear();
        }
        ret
    }

    // Reverses this Nfa, but only the transitions (i.e. doesn't do anything about initial and
    // final states).
    fn reversed_simple(&self) -> Nfa<Tok, NoLooks> {
        let rev_transitions = self.reversed_transitions();
        let mut ret: Nfa<Tok, NoLooks> = Nfa::with_capacity(self.states.len());

        for trans in rev_transitions {
            let idx = ret.add_state(Accept::Never);
            ret.states[idx].consuming = trans;
        }

        ret
    }

    // Returns the set of all states that can be reached from an initial state and that can reach
    // some accepting state.
    fn reachable_states(&self) -> HashSet<StateIdx> {
        let init_states = self.init.iter().map(|pair| pair.1);
        let final_states = self.states.iter().enumerate()
            .filter(|&(_, state)| state.accept != Accept::Never)
            .map(|(idx, _)| idx);

        let forward = self.reachable_from(init_states);
        let backward = self.reversed_simple().reachable_from(final_states);
        forward.intersection(&backward).cloned().collect()
    }

    /// Optimizes this Nfa by removing all states that cannot be reached from an initial state
    /// and all states that cannot lead to an accepting state.
    pub fn trim_unreachable(&mut self) {
        let reachable = self.reachable_states();

        let mut old_states = Vec::new();
        swap(&mut self.states, &mut old_states);
        let mut old_to_new = vec![None; old_states.len()];

        let (new_to_old, new_states): (Vec<_>, Vec<State<Tok>>) = old_states.into_iter()
            .enumerate()
            .filter(|&(i, _)| reachable.contains(&i))
            .unzip();
        self.states = new_states;

        for (new, &old) in new_to_old.iter().enumerate() {
            old_to_new[old] = Some(new);
        }

        self.map_states(|s| old_to_new[s]);
    }

    // Returns an `Accept` that will accept whenever anything in `states` would accept.
    fn accept_union(&self, states: &StateSet) -> Accept {
        states.iter().map(|s| self.states[*s].accept).max().unwrap_or(Accept::Never)
    }
}

impl Nfa<u32, NoLooks> {
    /// Converts this `Nfa` into one that consumes the input byte-by-byte.
    pub fn byte_me(self, max_states: usize) -> ::Result<Nfa<u8, NoLooks>> {
        let mut ret = Nfa::<u8, NoLooks> {
            states: self.states.iter().map(|s| State {
                accept: s.accept,
                accept_look: s.accept_look,
                accept_state: s.accept_state,
                accept_tokens: s.accept_tokens,
                consuming: RangeMultiMap::new(),
                looking: Vec::new(),
            }).collect(),
            init: self.init,
            phantom: PhantomData,
        };

        for (i, state) in self.states.into_iter().enumerate() {
            // Group transitions by the target state, and add them in batches. Most of the time, we
            // can merge a bunch of Utf8Sequences before adding them, which saves a bunch of
            // states.
            for (tgt, transitions) in state.consuming.ranges_values().group_by(|x| x.1) {
                try!(ret.add_utf8_sequences(i, transitions.into_iter().map(|x| x.0), tgt, max_states));
            }
        }
        Ok(ret)
    }
}

impl Nfa<u8, NoLooks> {
    /// Converts this `Nfa` into a `Dfa`.
    pub fn determinize(&self, max_states: usize) -> ::Result<Dfa<(Look, u8)>> {
        Determinizer::determinize(self, max_states, MatchChoice::TransitionOrder, self.init.clone())
    }

    /// Converts this `Nfa` into a `Dfa`.
    ///
    /// Whenever this `Nfa` matches some text, the `Dfa` also will. But if this `Nfa` has multiple
    /// possible endpoints for a match then the returned `Dfa` is only guaranteed to match the
    /// longest one.
    pub fn determinize_longest(&self, max_states: usize) -> ::Result<Dfa<(Look, u8)>> {
        Determinizer::determinize(self, max_states, MatchChoice::LongestMatch, self.init.clone())
    }

    /// Returns the reversal of this `Nfa`.
    ///
    /// If `self` matches some string of bytes, then the return value of this method will match
    /// the same strings of bytes reversed.
    ///
    /// Note that this loses information about match priorities.
    pub fn reverse(&self, max_states: usize) -> ::Result<Nfa<u8, NoLooks>> {
        let mut ret = self.reversed_simple();

        // Turn our initial states into ret's accepting states.
        for &(look, i) in &self.init {
            match look {
                Look::Full => {
                    ret.states[i].accept = Accept::Always;
                    ret.states[i].accept_look = Look::Full;
                },
                Look::Boundary => {
                    ret.states[i].accept = max(ret.states[i].accept, Accept::AtEoi);
                    ret.states[i].accept_look = max(ret.states[i].accept_look, Look::Boundary);
                },
                Look::NewLine => {
                    let accept_state = ret.add_look_ahead_state(Look::NewLine, 1, i);
                    ret.add_transition(i, accept_state, Range::new(b'\n', b'\n'));
                    ret.states[i].accept = max(ret.states[i].accept, Accept::AtEoi);
                    ret.states[i].accept_look = max(ret.states[i].accept_look, Look::Boundary);
                },
                Look::WordChar | Look::NotWordChar => {
                    // It would make more sense to put this outside the loop, but having it inside
                    // prevents a deadlock: constructing REV_*_DFA ends up calling reverse(), but
                    // with no look-ahead so it never gets inside this loop.
                    let dfa: &Dfa<_> = if look == Look::WordChar {
                        &REV_WORD_CHAR_DFA
                    } else {
                        ret.states[i].accept = max(ret.states[i].accept, Accept::AtEoi);
                        ret.states[i].accept_look = max(ret.states[i].accept_look, Look::Boundary);
                        &REV_NOT_WORD_CHAR_DFA
                    };
                    let accept_state = ret.add_look_ahead_state(look, 1, i);
                    try!(ret.add_min_utf8_sequences(i, dfa, accept_state, max_states));
                },
                Look::Empty => {
                    panic!("Empty cannot be an init look");
                },
            }
        }

        // Turn our accepting states into ret's initial states.
        ret.init.clear();
        for st in &self.states {
            if st.accept != Accept::Never {
                ret.init.push((st.accept_look, st.accept_state));
            }
        }
        Ok(ret)
    }

    /// Can we accept immediately if the beginning of the input matches `look`?
    fn init_accept(&self, look: Look) -> Accept {
        let set = self.init.iter()
            .filter(|pair| look <= pair.0)
            .map(|pair| pair.1)
            .collect::<Vec<_>>();
        self.accept_union(&set)
    }

    /// This essentially modifies `self` by adding a `^.*` at the beginning.
    ///
    /// The result is actually a little bit different, because `.` matches a whole code point,
    /// whereas the `^.*` that we add works at the byte level.
    pub fn anchor(mut self, max_states: usize) -> ::Result<Nfa<u8, NoLooks>> {
        let loop_accept = self.init_accept(Look::Full);
        let loop_state = self.add_state(loop_accept);
        let init_accept = self.init_accept(Look::Boundary);
        let init_state = self.add_state(init_accept);

        // Swap out init so that we can iterate over it while modifying `self`.
        let mut init = Vec::new();
        swap(&mut init, &mut self.init);

        for &(look, st_idx) in &init {
            if look.allows_eoi() {
                // TODO: shouldn't need to clone here.
                for &(range, target) in self.states[st_idx].consuming.clone().ranges_values() {
                    self.add_transition(init_state, target, range);
                }
            }

            match look {
                Look::Boundary => {},
                Look::Full => {
                    for &(range, target) in self.states[st_idx].consuming.clone().ranges_values() {
                        self.add_transition(loop_state, target, range);
                    }
                },
                Look::NewLine => {
                    self.add_transition(init_state, st_idx, Range::new(b'\n', b'\n'));
                    self.add_transition(loop_state, st_idx, Range::new(b'\n', b'\n'));
                },
                Look::WordChar | Look::NotWordChar => {
                    let dfa: &Dfa<_> =
                        if look == Look::WordChar { &WORD_CHAR_DFA } else { &NOT_WORD_CHAR_DFA };

                    try!(self.add_min_utf8_sequences(loop_state, dfa, st_idx, max_states));
                    try!(self.add_min_utf8_sequences(init_state, dfa, st_idx, max_states));
                },
                Look::Empty => {
                    panic!("Cannot start with an empty look");
                },
            }

            // Once we've found an init state that accepts immediately, don't look for any others
            // (since any matches that we find starting from them are lower priority that the one
            // we've found already). This check is *almost* unnecessary, since similar pruning
            // happens when we turn the NFA into a DFA. The important case that needs to be handled
            // here is the case that a high-priority init state has no transitions out of it. Such
            // a state will be completely removed by this function, and so we need to acknowledge
            // its existence here.
            if self.states[st_idx].accept == Accept::Always {
                break;
            }
        }

        // Wire up the initial and loop states, but only if they aren't accepting. That's because
        // if they are accepting then the accept should take priority over the transition (since
        // making the transition means that we are searching for a match that starts later).
        if init_accept != Accept::Always {
            self.add_transition(init_state, loop_state, Range::full());
        }
        if loop_accept != Accept::Always {
            self.add_transition(loop_state, loop_state, Range::full());
        }

        // The new Nfa is only allowed to start at the beginning of the input, and only at the new
        // initial state.
        self.init.push((Look::Boundary, init_state));
        self.trim_unreachable();
        Ok(self)
    }

    // This does the same thing as add_utf8_sequences, but it gets the transitions from a dfa,
    // which should have zero as its only starting state, and for which every accepting state
    // should be Accept::Always.
    //
    // This is probably used in conjunction with make_char_dfa, which ends up having the same
    // effect as add_utf8_sequences, but adds fewer states.
    fn add_min_utf8_sequences(
        &mut self,
        start_state: StateIdx,
        dfa: &Dfa<(Look, u8)>,
        end_state: StateIdx,
        max_states: usize,
    ) -> ::Result<()> {
        let offset = self.states.len();
        // If end_accept is true, then it isn't actually important that we end in state
        // `end_state`: we can create a new look_ahead state to end in.
        let end_accept = self.states[end_state].accept_tokens > 0;

        if self.states.len() + dfa.num_states() > max_states {
            return Err(Error::TooManyStates);
        }
        for _ in 0..dfa.num_states() {
            self.add_state(Accept::Never);
        }
        for d_idx in 0..dfa.num_states() {
            let n_src = if d_idx == 0 { start_state } else { d_idx + offset };
            for &(range, d_tgt) in dfa.transitions(d_idx).ranges_values() {
                let n_tgt = if dfa.accept(d_tgt) == &Accept::Always && !end_accept {
                    end_state
                } else {
                    let n_tgt = d_tgt + offset;
                    self.states[n_tgt].accept = *dfa.accept(d_tgt);
                    if let Some(&(look, bytes)) = dfa.ret(d_tgt) {
                        self.states[n_tgt].accept_look = look;
                        self.states[n_tgt].accept_state = start_state;
                        self.states[n_tgt].accept_tokens = bytes;
                    }
                    n_tgt
                };
                self.add_transition(n_src, n_tgt, range);
            }
        }

        Ok(())
    }

    // Adds a path from `start_state` to `end_state` for all byte sequences matching `seq`.
    //
    // If `end_state` is a look-ahead state, makes a new accepting state instead (so that we know
    // how many bytes of look-ahead we used).
    fn add_utf8_sequence(
        &mut self,
        start_state: StateIdx,
        mut end_state: StateIdx,
        seq: MergedUtf8Sequences
    ) {
        let mut last_state = start_state;
        for range in &seq.head {
            let cur_state = self.add_state(Accept::Never);

            self.add_transition(last_state, cur_state, Range::new(range.start, range.end));
            last_state = cur_state;
        }

        if self.states[end_state].accept_tokens > 0 {
            let look = self.states[end_state].accept_look;
            let acc_state = self.states[end_state].accept_state;
            end_state = self.add_look_ahead_state(look, seq.num_bytes(), acc_state);
        }
        for range in &seq.last_byte {
            self.add_transition(last_state, end_state, Range::new(range.start, range.end));
        }
    }

    // Adds a byte path from `start_state` to `end_state` for every char in `ranges`.
    fn add_utf8_sequences<I>(
        &mut self,
        start_state: StateIdx,
        ranges: I,
        end_state: StateIdx,
        max_states: usize
    ) -> ::Result<()>
    where I: Iterator<Item=Range<u32>> {
        for m in MergedUtf8Sequences::from_ranges(ranges) {
            self.add_utf8_sequence(start_state, end_state, m);
            if self.states.len() > max_states {
                return Err(Error::TooManyStates);
            }
        }
        Ok(())
    }

    // Finds the transitions out of the given set of states, as a RangeMap.
    fn transition_map(&self, states: &[StateIdx]) -> RangeMap<u8, Vec<usize>> {
        let mut transitions = states.into_iter()
            .flat_map(|s| self.states[*s].consuming.ranges_values().cloned())
            .collect::<RangeMultiMap<u8, StateIdx>>()
            .group();

        // `scratch` is large enough to be indexed by anything in `elts`. It is full of `false`.
        fn uniquify(elts: &mut Vec<StateIdx>, scratch: &mut Vec<bool>) {
            elts.retain(|&e| {
                let ret = !scratch[e];
                scratch[e] = true;
                ret
            });

            // Clean up scratch, so that it is full of `false` again.
            for e in elts {
                scratch[*e] = false;
            }
        }

        let mut scratch = vec![false; self.num_states()];
        for pair in transitions.as_mut_slice() {
            uniquify(&mut pair.1, &mut scratch);
        }

        transitions
    }
}

#[derive(PartialEq)]
enum MatchChoice {
    TransitionOrder,
    LongestMatch,
}

// This contains all the intermediate data structures that we need when turning an `Nfa` into a
// `Dfa`.
struct Determinizer<'a> {
    nfa: &'a Nfa<u8, NoLooks>,
    dfa: Dfa<(Look, u8)>,
    state_map: HashMap<StateSet, StateIdx>,
    active_states: Vec<StateSet>,
    max_states: usize,
    match_choice: MatchChoice,
}

impl<'a> Determinizer<'a> {
    // Turns an Nfa into an almost-equivalent (up to the difference between shortest and longest
    // matches) Dfa.
    //
    // `init` is a vector of length Look::num(). Each entry gives a set of initial states that
    // will be turned into the initial states of the dfa.
    fn determinize(nfa: &Nfa<u8, NoLooks>,
                   max_states: usize,
                   match_choice: MatchChoice,
                   init: Vec<(Look, StateIdx)>) -> ::Result<Dfa<(Look, u8)>> {
        let mut det = Determinizer::new(nfa, max_states, match_choice);
        try!(det.run(init));
        Ok(det.dfa)
    }

    fn new(nfa: &'a Nfa<u8, NoLooks>,
           max_states: usize,
           match_choice: MatchChoice) -> Determinizer<'a> {
        Determinizer {
            nfa: nfa,
            dfa: Dfa::new(),
            state_map: HashMap::new(),
            active_states: Vec::new(),
            max_states: max_states,
            match_choice: match_choice,
        }
    }

    // Checks whether we should accept in the given set of states.
    //
    // Returns a tuple: the first element says when we accept, the second says what look-ahead (if
    // any) led to us accepting, and the third says how many bytes of look-ahead we needed before
    // knowing that we can accept.
    //
    // There is one annoying corner case: there could be two states in the set `s` with different
    // values of `accept_tokens`, where the higher priority state says `Accept::AtEoi` and the
    // lower priority state says `Accept::Always`. In this case, we return `(AtEoi, look, bytes)`
    // where `look` and `bytes` come from the lower priority state. This doesn't lose any
    // information, since if a state says `Accept::AtEoi` then its `accept_look` and
    // `accept_tokens` are guaranteed to be `Boundary` and `0`.
    fn accept(&self, s: &[StateIdx]) -> (Accept, Look, u8) {
        let mut accept_states = s.iter().cloned()
            .filter(|i| self.nfa.states[*i].accept != Accept::Never);
        let mut accept_always_states = s.iter().cloned()
            .filter(|i| self.nfa.states[*i].accept == Accept::Always);

        let (first_accept, other_accept) = if self.match_choice == MatchChoice::TransitionOrder {
            (accept_states.next(), accept_always_states.next())
        } else {
            (accept_states.min_by_key(|i| self.nfa.states[*i].accept_tokens),
                accept_always_states.min_by_key(|i| self.nfa.states[*i].accept_tokens))
        };

        // Returns the intersection of state.accept_look over all states in s that accept
        // unconditionally and have the given number of look-ahead bytes.
        let look_intersection = |toks: u8| {
            s.iter().cloned()
                .filter(|i| self.nfa.states[*i].accept == Accept::Always)
                .filter(|i| self.nfa.states[*i].accept_tokens == toks)
                .fold(Look::Full, |x, y| x.intersection(&self.nfa.states[y].accept_look))
        };

        if let Some(first_accept) = first_accept {
            let st = &self.nfa.states[first_accept];

            if st.accept == Accept::AtEoi {
                // Check if there is a lower-priority Accept::Always.
                if let Some(other_accept) = other_accept {
                    let other_st = &self.nfa.states[other_accept];
                    if other_st.accept_tokens > 0 {
                        let look = look_intersection(other_st.accept_tokens);
                        return (Accept::AtEoi, look, other_st.accept_tokens);
                    }
                }
                (Accept::AtEoi, Look::Boundary, 0)
            } else {
                (Accept::Always, look_intersection(st.accept_tokens), st.accept_tokens)
            }
        } else {
            // There are no accepting states.
            (Accept::Never, Look::Empty, 0)
        }
    }

    // Tries to add a new state to the Dfa.
    //
    // If the state already exists, returns the index of the old one. If there are too many states,
    // returns an error.
    fn add_state(&mut self, mut s: StateSet) -> ::Result<StateIdx> {
        // When we choose our matches by transition order, discard any states that have lower
        // priority than the best match we've found.
        if self.match_choice == MatchChoice::TransitionOrder {
            if let Some(accept_idx) = s.iter().position(|&i| self.nfa.states[i].accept == Accept::Always) {
                s.truncate(accept_idx + 1);
            }
        }

        if self.state_map.contains_key(&s) {
            Ok(*self.state_map.get(&s).unwrap())
        } else if self.dfa.num_states() >= self.max_states {
            Err(Error::TooManyStates)
        } else {
            let (acc, look, bytes_ago) = self.accept(&s);
            let ret = if acc != Accept::Never { Some ((look, bytes_ago)) } else { None };
            let new_state = self.dfa.add_state(acc, ret);

            self.active_states.push(s.clone());
            self.state_map.insert(s, new_state);
            Ok(new_state)
        }
    }

    // Creates a deterministic automaton representing the same language as our `nfa`.
    // Puts the new Dfa in self.dfa.
    fn run(&mut self, init: Vec<(Look, StateIdx)>) -> ::Result<()> {
        if self.nfa.states.is_empty() {
            return Ok(());
        }

        for &look in Look::all() {
            let init_states: StateSet = init.iter().cloned()
                .filter(|&(x, _)| look == x)
                .map(|(_, y)| y)
                .collect();
            if !init_states.is_empty() {
                let new_state_idx = try!(self.add_state(init_states));
                self.dfa.init[look.as_usize()] = Some(new_state_idx);
            }
        }

        while !self.active_states.is_empty() {
            let state = self.active_states.pop().unwrap();
            // This unwrap is ok because anything in active_states must also be in state_map.
            let state_idx = *self.state_map.get(&state).unwrap();
            let trans = self.nfa.transition_map(&state);

            let mut dfa_trans = Vec::new();
            for &(range, ref target) in trans.ranges_values() {
                let target_idx = try!(self.add_state(target.clone()));
                dfa_trans.push((range, target_idx));
            }
            self.dfa.set_transitions(state_idx, dfa_trans.into_iter().collect());
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use look::Look;
    use dfa::Dfa;
    use nfa::{Accept, Nfa, NoLooks};
    use nfa::tests::{re_nfa, trans_nfa, trans_range_nfa};
    use range_map::Range;
    use std::usize;

    fn re_nfa_anchored(re: &str) -> Nfa<u8, NoLooks> {
        re_nfa(re).byte_me(usize::MAX).unwrap().anchor(usize::MAX).unwrap()
    }

    fn re_dfa(re: &str) -> Dfa<(Look, u8)> {
        re_nfa(re).byte_me(usize::MAX).unwrap().determinize(usize::MAX).unwrap()
    }

    #[test]
    fn anchor_simple() {
        let nfa = re_nfa_anchored("a");
        let mut target = trans_range_nfa(3, &[(2, 0, Range::new(b'a', b'a')),
                                              (2, 1, Range::full()),
                                              (1, 0, Range::new(b'a', b'a')),
                                              (1, 1, Range::full())]);
        target.init.push((Look::Boundary, 2));
        target.states[0].accept = Accept::Always;

        assert_eq!(nfa, target);
    }

    #[test]
    fn anchor_nl() {
        let nfa = re_nfa_anchored(r"(?m)^a");
        let mut target = trans_nfa(4, &[(3, 1, 'a'),
                                        (0, 1, 'a'),
                                        (2, 0, '\n'),
                                        (3, 0, '\n')]);
        target.init.push((Look::Boundary, 3));
        target.states[1].accept = Accept::Always;

        let mut target = target.byte_me(usize::MAX).unwrap();
        target.states[2].consuming.insert(Range::full(), 2);
        target.states[3].consuming.insert(Range::full(), 2);

        assert_eq!(nfa, target);
    }

    #[test]
    fn anchor_already_anchored() {
        let nfa = re_nfa_anchored("^a");
        let mut target = trans_nfa(2, &[(1, 0, 'a')]);
        target.init.push((Look::Boundary, 1));
        target.states[0].accept = Accept::Always;

        assert_eq!(nfa, target);
    }

    #[test]
    fn determinize_pruning() {
        assert_eq!(re_dfa("a|aa"), re_dfa("a"));
    }

    macro_rules! check_rev_inits {
        ($name:ident, $re:expr, $inits:expr) => {
            #[test]
            fn $name() {
                let rev = re_nfa($re).byte_me(usize::MAX).unwrap().reverse(usize::MAX).unwrap();
                println!("{:?}", rev.init);
                for &look in Look::all() {
                    println!("checking look {:?}", look);
                    if $inits.contains(&look) {
                        assert!(rev.init.iter().any(|pair| pair.0 == look));
                    } else {
                        assert!(!rev.init.iter().any(|pair| pair.0 == look));
                    }
                }
            }
        };
    }

    check_rev_inits!(rev_init_simple, "abc", [Look::Full]);
    check_rev_inits!(rev_init_boundary, "abc$", [Look::Boundary]);
    check_rev_inits!(rev_init_simple_and_boundary, "(abc$|abc)", [Look::Full, Look::Boundary]);
    check_rev_inits!(rev_init_new_line, "(?m)abc$", [Look::Boundary, Look::NewLine]);
    check_rev_inits!(rev_init_word, r"  \b", [Look::WordChar]);
    check_rev_inits!(rev_init_not_word, r"abc\b", [Look::Boundary, Look::NotWordChar]);
    check_rev_inits!(rev_init_word_or_not_word, r".\b", [Look::Boundary, Look::NotWordChar, Look::WordChar]);
}


text:
package org.onosproject.drivers.lumentum;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.onosproject.net.AnnotationKeys;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.SparseAnnotations;
import org.onosproject.net.device.DefaultDeviceDescription;
import org.onosproject.net.device.DeviceDescription;
import org.onosproject.net.device.DeviceDescriptionDiscovery;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.slf4j.Logger;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.util.TreeEvent;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.net.optical.device.OmsPortHelper.omsPortDescription;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Device description behaviour for Lumentum Snmp devices.
 */
public class LumentumRoadmDiscovery extends AbstractHandlerBehaviour implements DeviceDescriptionDiscovery {

    private final Logger log = getLogger(getClass());

    private static final String CTRL_PORT_STATE = ".1.3.6.1.4.1.46184.1.4.1.1.3.";

    private LumentumSnmpDevice snmp;

    @Override
    public DeviceDescription discoverDeviceDetails() {
        //TODO get device description
        DeviceService deviceService = checkNotNull(handler().get(DeviceService.class));
        DeviceId deviceId = handler().data().deviceId();
        Device device = deviceService.getDevice(deviceId);
        return new DefaultDeviceDescription(device.id().uri(), Device.Type.ROADM,
                                            "Lumentum", "SDN ROADM", "1.0", "v1",
                                            device.chassisId(), (SparseAnnotations) device.annotations());
    }

    @Override
    public List<PortDescription> discoverPortDetails() {
        return ImmutableList.copyOf(this.getPorts());
    }

    private List<PortDescription> getPorts() {
        try {
            snmp = new LumentumSnmpDevice(handler().data().deviceId());
        } catch (IOException e) {
            log.error("Failed to connect to device: ", e);

            return Collections.emptyList();
        }

        List<PortDescription> ports = Lists.newLinkedList();

        OID[] oids = {
                new OID(CTRL_PORT_STATE + "1"),
                new OID(CTRL_PORT_STATE + "2")
        };

        for (OID oid : oids) {

            for (TreeEvent event : snmp.get(oid)) {
                if (event != null) {
                    VariableBinding[] varBindings = event.getVariableBindings();
                    for (VariableBinding varBinding : varBindings) {
                        if (varBinding.getVariable().toInt() == 1) {
                            int portNumber = varBinding.getOid().removeLast();
                            int portDirection = varBinding.getOid().removeLast();
                            SparseAnnotations ann = DefaultAnnotations.builder()
                                    .set(AnnotationKeys.PORT_NAME, portDirection + "-" + portNumber)
                                    .build();
                            PortDescription p = omsPortDescription(
                                    PortNumber.portNumber(ports.size() + 1L),
                                    true,
                                    LumentumSnmpDevice.START_CENTER_FREQ,
                                    LumentumSnmpDevice.END_CENTER_FREQ,
                                    LumentumSnmpDevice.CHANNEL_SPACING.frequency(),
                                    ann);
                            ports.add(p);
                        }
                    }
                }
            }
        }

        // Create LINE IN and LINE OUT ports as these are not reported through SNMP
        SparseAnnotations annLineIn = DefaultAnnotations.builder()
                .set(AnnotationKeys.PORT_NAME, "LINE IN")
                .build();
        ports.add(omsPortDescription(
                PortNumber.portNumber(ports.size() + 1L),
                true,
                LumentumSnmpDevice.START_CENTER_FREQ,
                LumentumSnmpDevice.END_CENTER_FREQ,
                LumentumSnmpDevice.CHANNEL_SPACING.frequency(),
                annLineIn
        ));

        SparseAnnotations annLineOut = DefaultAnnotations.builder()
                .set(AnnotationKeys.PORT_NAME, "LINE OUT")
                .build();
        ports.add(omsPortDescription(
                PortNumber.portNumber(ports.size() + 1L),
                true,
                LumentumSnmpDevice.START_CENTER_FREQ,
                LumentumSnmpDevice.END_CENTER_FREQ,
                LumentumSnmpDevice.CHANNEL_SPACING.frequency(),
                annLineOut
        ));

        return ports;
    }
}


text:
using Bloom.Player.Modules.PlayingModule.Views;
using Prism.Modularity;
using Prism.Regions;

namespace Bloom.Player.Modules.PlayingModule
{
    /// <summary>
    /// Player playing Prism module.
    /// </summary>
    [Module(ModuleName = "PlayingModule")]
    public class PlayingModuleDefinition : IModule
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Bloom.Player.Modules.PlayingModule"/> class.
        /// </summary>
        /// <param name="regionManager">The region manager.</param>
        public PlayingModuleDefinition(IRegionManager regionManager)
        {
            _regionManager = regionManager;
        }
        private readonly IRegionManager _regionManager;

        /// <summary>
        /// Notifies the module that it has be initialized.
        /// </summary>
        public void Initialize()
        {
            _regionManager.RegisterViewWithRegion("PlayingRegion", typeof(PlayingView));
        }
    }
}


text:
module Rester
  class Client
    class Resource
      attr_reader :client
      attr_reader :path

      def initialize(client, path='')
        @client = client
        @path = path
      end

      def get(params={})
        _request(:get, '', params)
      end

      def update(params={})
        _request(:put, '', params)
      end

      def delete(params={})
        _request(:delete, '', params)
      end

      private

      def method_missing(meth, *args, &block)
        meth = meth.to_s
        arg = args.first

        case arg
        when Hash, NilClass
          _handle_search_or_create(meth, arg || {})
        when String, Symbol
          Resource.new(client, _path(meth, arg))
        else
          raise ArgumentError, "invalid argument type #{arg.inspect}"
        end
      end

      def _request(verb, path, params={})
        client.request(verb, _path(path), params)
      end

      def _path(*args)
        Utils.join_paths(path, *args)
      end

      def _handle_search_or_create(name, params)
        verb, name = Utils.extract_method_verb(name)
        _request(verb, name, params)
      end
    end # Resource
  end # Client
end # Rester


text:
package album.data;

import beans.EntityBeanI;

import javax.persistence.*;

@Entity(name = "album_mapping")
public interface EIAlbumMapping extends EntityBeanI {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    Long getAlbumMappingId();

    void setAlbumMappingId(Long albumMappingId);

    @Column(name = "album_id", nullable = false)
    Long getAlbumId();

    void setAlbumId(Long albumId);

    @Column(name = "album_photo_id", nullable = false)
    Long getAlbumPhotoId();

    void setAlbumPhotoId(Long albumPhotoId);

    @Column(name = "disabled", nullable = false)
    Boolean isAlbumMappingDisabled();

    void setAlbumMappingDisabled(Boolean albumMappingDisabled);

}


text:
/** The root of The Core, defined by webpack.DefinePlugin */
declare const CORE_ROOT: string;

/** The environment to run on (production or development) */
declare const NODE_ENV: 'production' | 'development';


text:
package pro.taskana.simplehistory.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pro.taskana.classification.api.ClassificationCustomField;
import pro.taskana.common.api.TimeInterval;
import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.simplehistory.impl.classification.ClassificationHistoryQuery;
import pro.taskana.simplehistory.impl.classification.ClassificationHistoryQueryColumnName;
import pro.taskana.spi.history.api.events.classification.ClassificationHistoryEvent;

public class ClassificationHistoryQueryImpl implements ClassificationHistoryQuery {

  private static final String CLASSIFICATION_PACKAGE_PATH =
      "pro.taskana.simplehistory.impl.classification.";
  private static final String LINK_TO_MAPPER =
      CLASSIFICATION_PACKAGE_PATH + "ClassificationHistoryQueryMapper.queryHistoryEvents";
  private static final String LINK_TO_VALUE_MAPPER =
      CLASSIFICATION_PACKAGE_PATH + "ClassificationHistoryQueryMapper.queryHistoryColumnValues";
  private static final String LINK_TO_COUNTER =
      CLASSIFICATION_PACKAGE_PATH + "ClassificationHistoryQueryMapper.countHistoryEvents";

  private static final Logger LOGGER =
      LoggerFactory.getLogger(ClassificationHistoryQueryImpl.class);

  private static final String SQL_EXCEPTION_MESSAGE =
      "Method openConnection() could not open a connection to the database.";

  private final TaskanaHistoryEngineImpl taskanaHistoryEngine;

  private final List<String> orderBy = new ArrayList<>();
  private final List<String> orderColumns = new ArrayList<>();
  private ClassificationHistoryQueryColumnName columnName;
  private String[] idIn;
  private String[] eventTypeIn;
  private TimeInterval[] createdIn;
  private String[] userIdIn;
  private String[] classificationIdIn;
  private String[] applicationEntryPointIn;
  private String[] categoryIn;
  private String[] domainIn;
  private String[] keyIn;
  private String[] nameIn;
  private String[] parentIdIn;
  private String[] parentKeyIn;
  private int[] priorityIn;
  private String[] serviceLevelIn;
  private String[] typeIn;
  private String[] custom1In;
  private String[] custom2In;
  private String[] custom3In;
  private String[] custom4In;
  private String[] custom5In;
  private String[] custom6In;
  private String[] custom7In;
  private String[] custom8In;
  private String[] eventTypeLike;
  private String[] userIdLike;
  private String[] classificationIdLike;
  private String[] applicationEntryPointLike;
  private String[] categoryLike;
  private String[] domainLike;
  private String[] keyLike;
  private String[] nameLike;
  private String[] parentIdLike;
  private String[] parentKeyLike;
  private String[] serviceLevelLike;
  private String[] typeLike;
  private String[] custom1Like;
  private String[] custom2Like;
  private String[] custom3Like;
  private String[] custom4Like;
  private String[] custom5Like;
  private String[] custom6Like;
  private String[] custom7Like;
  private String[] custom8Like;

  public ClassificationHistoryQueryImpl(TaskanaHistoryEngineImpl internalTaskanaHistoryEngine) {
    this.taskanaHistoryEngine = internalTaskanaHistoryEngine;
  }

  @Override
  public ClassificationHistoryQuery idIn(String... idIn) {
    this.idIn = idIn;
    return this;
  }

  @Override
  public ClassificationHistoryQuery eventTypeIn(String... eventType) {
    this.eventTypeIn = eventType;
    return this;
  }

  @Override
  public ClassificationHistoryQuery createdWithin(TimeInterval... createdWithin) {
    this.createdIn = createdWithin;
    return this;
  }

  @Override
  public ClassificationHistoryQuery userIdIn(String... userId) {
    this.userIdIn = userId;
    return this;
  }

  @Override
  public ClassificationHistoryQuery classificationIdIn(String... classificationId) {
    this.classificationIdIn = classificationId;
    return this;
  }

  @Override
  public ClassificationHistoryQuery applicationEntryPointIn(String... applicationEntryPoint) {
    this.applicationEntryPointIn = applicationEntryPoint;
    return this;
  }

  @Override
  public ClassificationHistoryQuery categoryIn(String... category) {
    this.categoryIn = category;
    return this;
  }

  @Override
  public ClassificationHistoryQuery domainIn(String... domain) {
    this.domainIn = domain;
    return this;
  }

  @Override
  public ClassificationHistoryQuery keyIn(String... key) {
    this.keyIn = key;
    return this;
  }

  @Override
  public ClassificationHistoryQuery nameIn(String... name) {
    this.nameIn = name;
    return this;
  }

  @Override
  public ClassificationHistoryQuery parentIdIn(String... parentId) {
    this.parentIdIn = parentId;
    return this;
  }

  @Override
  public ClassificationHistoryQuery parentKeyIn(String... parentKey) {
    this.parentKeyIn = parentKey;
    return this;
  }

  @Override
  public ClassificationHistoryQuery priorityIn(int... priorities) {
    this.priorityIn = priorities;
    return this;
  }

  @Override
  public ClassificationHistoryQuery serviceLevelIn(String... serviceLevelIn) {
    this.serviceLevelIn = serviceLevelIn;
    return this;
  }

  @Override
  public ClassificationHistoryQuery typeIn(String... type) {
    this.typeIn = type;
    return this;
  }

  @Override
  public ClassificationHistoryQuery customAttributeIn(
      ClassificationCustomField customField, String... searchArguments) {
    switch (customField) {
      case CUSTOM_1:
        custom1In = searchArguments;
        break;
      case CUSTOM_2:
        custom2In = searchArguments;
        break;
      case CUSTOM_3:
        custom3In = searchArguments;
        break;
      case CUSTOM_4:
        custom4In = searchArguments;
        break;
      case CUSTOM_5:
        custom5In = searchArguments;
        break;
      case CUSTOM_6:
        custom6In = searchArguments;
        break;
      case CUSTOM_7:
        custom7In = searchArguments;
        break;
      case CUSTOM_8:
        custom8In = searchArguments;
        break;
      default:
        throw new SystemException("Unknown customField '" + customField + "'");
    }
    return this;
  }

  @Override
  public ClassificationHistoryQuery eventTypeLike(String... eventType) {
    this.eventTypeLike = toLowerCopy(eventType);
    return this;
  }

  @Override
  public ClassificationHistoryQuery userIdLike(String... userId) {
    this.userIdLike = toLowerCopy(userId);
    return this;
  }

  @Override
  public ClassificationHistoryQuery classificationIdLike(String... classificationId) {
    this.classificationIdLike = toLowerCopy(classificationId);
    return this;
  }

  @Override
  public ClassificationHistoryQuery applicationEntryPointLike(String... applicationEntryPointLike) {
    this.applicationEntryPointLike = toLowerCopy(applicationEntryPointLike);
    return this;
  }

  @Override
  public ClassificationHistoryQuery categoryLike(String... category) {
    this.categoryLike = toLowerCopy(category);
    return this;
  }

  @Override
  public ClassificationHistoryQuery domainLike(String... domain) {
    this.domainLike = toLowerCopy(domain);
    return this;
  }

  @Override
  public ClassificationHistoryQuery keyLike(String... key) {
    this.keyLike = toLowerCopy(key);
    return this;
  }

  @Override
  public ClassificationHistoryQuery nameLike(String... name) {
    this.nameLike = toLowerCopy(name);
    return this;
  }

  @Override
  public ClassificationHistoryQuery parentIdLike(String... parentId) {
    this.parentIdLike = toLowerCopy(parentId);
    return this;
  }

  @Override
  public ClassificationHistoryQuery parentKeyLike(String... parentKey) {
    this.parentKeyLike = toLowerCopy(parentKey);
    return this;
  }

  @Override
  public ClassificationHistoryQuery serviceLevelLike(String... serviceLevel) {
    this.serviceLevelLike = toLowerCopy(serviceLevel);
    return this;
  }

  @Override
  public ClassificationHistoryQuery typeLike(String... type) {
    this.typeLike = toLowerCopy(type);
    return this;
  }

  @Override
  public ClassificationHistoryQuery customAttributeLike(
      ClassificationCustomField customField, String... searchArguments) {
    switch (customField) {
      case CUSTOM_1:
        custom1Like = toLowerCopy(searchArguments);
        break;
      case CUSTOM_2:
        custom2Like = toLowerCopy(searchArguments);
        break;
      case CUSTOM_3:
        custom3Like = toLowerCopy(searchArguments);
        break;
      case CUSTOM_4:
        custom4Like = toLowerCopy(searchArguments);
        break;
      case CUSTOM_5:
        custom5Like = toLowerCopy(searchArguments);
        break;
      case CUSTOM_6:
        custom6Like = toLowerCopy(searchArguments);
        break;
      case CUSTOM_7:
        custom7Like = toLowerCopy(searchArguments);
        break;
      case CUSTOM_8:
        custom8Like = toLowerCopy(searchArguments);
        break;
      default:
        throw new SystemException("Unknown customField '" + customField + "'");
    }
    return this;
  }

  @Override
  public ClassificationHistoryQuery orderByEventType(SortDirection sortDirection) {
    return addOrderCriteria("EVENT_TYPE", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByCreated(SortDirection sortDirection) {
    return addOrderCriteria("CREATED", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByUserId(SortDirection sortDirection) {
    return addOrderCriteria("USER_ID", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByClassificationId(SortDirection sortDirection) {
    return addOrderCriteria("CLASSIFICATION_ID", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByApplicationEntryPoint(SortDirection sortDirection) {
    return addOrderCriteria("APPLICATION_ENTRY_POINT", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByCategory(SortDirection sortDirection) {
    return addOrderCriteria("CATEGORY", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByDomain(SortDirection sortDirection) {
    return addOrderCriteria("DOMAIN", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByKey(SortDirection sortDirection) {
    return addOrderCriteria("KEY", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByName(SortDirection sortDirection) {
    return addOrderCriteria("NAME", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByParentId(SortDirection sortDirection) {
    return addOrderCriteria("PARENT_ID", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByParentKey(SortDirection sortDirection) {
    return addOrderCriteria("PARENT_KEY", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByPriority(SortDirection sortDirection) {
    return addOrderCriteria("PRIORITY", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByServiceLevel(SortDirection sortDirection) {
    return addOrderCriteria("SERVICE_LEVEL", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByType(SortDirection sortDirection) {
    return addOrderCriteria("TYPE", sortDirection);
  }

  @Override
  public ClassificationHistoryQuery orderByCustomAttribute(int num, SortDirection sortDirection)
      throws InvalidArgumentException {

    switch (num) {
      case 1:
        return addOrderCriteria("CUSTOM_1", sortDirection);
      case 2:
        return addOrderCriteria("CUSTOM_2", sortDirection);
      case 3:
        return addOrderCriteria("CUSTOM_3", sortDirection);
      case 4:
        return addOrderCriteria("CUSTOM_4", sortDirection);
      case 5:
        return addOrderCriteria("CUSTOM_5", sortDirection);
      case 6:
        return addOrderCriteria("CUSTOM_6", sortDirection);
      case 7:
        return addOrderCriteria("CUSTOM_7", sortDirection);
      case 8:
        return addOrderCriteria("CUSTOM_8", sortDirection);
      default:
        throw new InvalidArgumentException(
            "Custom number has to be between 1 and 8, but this is: " + num);
    }
  }

  @Override
  public List<ClassificationHistoryEvent> list() {
    List<ClassificationHistoryEvent> result = new ArrayList<>();
    try {
      taskanaHistoryEngine.openConnection();
      result = taskanaHistoryEngine.getSqlSession().selectList(LINK_TO_MAPPER, this);
      return result;
    } catch (SQLException e) {
      LOGGER.error(SQL_EXCEPTION_MESSAGE, e.getCause());
      return result;
    } finally {
      taskanaHistoryEngine.returnConnection();
    }
  }

  @Override
  public List<ClassificationHistoryEvent> list(int offset, int limit) {
    List<ClassificationHistoryEvent> result = new ArrayList<>();
    try {
      taskanaHistoryEngine.openConnection();
      RowBounds rowBounds = new RowBounds(offset, limit);
      result = taskanaHistoryEngine.getSqlSession().selectList(LINK_TO_MAPPER, this, rowBounds);
      return result;
    } catch (SQLException e) {
      LOGGER.error(SQL_EXCEPTION_MESSAGE, e.getCause());
      return result;
    } finally {
      taskanaHistoryEngine.returnConnection();
    }
  }

  @Override
  public List<String> listValues(
      ClassificationHistoryQueryColumnName dbColumnName, SortDirection sortDirection) {
    List<String> result = new ArrayList<>();
    this.columnName = dbColumnName;
    List<String> cacheOrderBy = new ArrayList<>(this.orderBy);
    this.orderBy.clear();
    this.addOrderCriteria(columnName.toString(), sortDirection);

    try {
      taskanaHistoryEngine.openConnection();
      result = taskanaHistoryEngine.getSqlSession().selectList(LINK_TO_VALUE_MAPPER, this);
      return result;
    } catch (SQLException e) {
      LOGGER.error(SQL_EXCEPTION_MESSAGE, e.getCause());
      return result;
    } finally {
      this.orderBy.addAll(cacheOrderBy);
      this.columnName = null;
      this.orderColumns.remove(orderColumns.size() - 1);
      taskanaHistoryEngine.returnConnection();
    }
  }

  @Override
  public ClassificationHistoryEvent single() {
    ClassificationHistoryEvent result = null;
    try {

      taskanaHistoryEngine.openConnection();
      result = taskanaHistoryEngine.getSqlSession().selectOne(LINK_TO_MAPPER, this);

      return result;
    } catch (SQLException e) {
      LOGGER.error(SQL_EXCEPTION_MESSAGE, e.getCause());
      return result;
    } finally {
      taskanaHistoryEngine.returnConnection();
    }
  }

  @Override
  public long count() {
    Long rowCount = null;
    try {
      taskanaHistoryEngine.openConnection();
      rowCount = taskanaHistoryEngine.getSqlSession().selectOne(LINK_TO_COUNTER, this);
      return (rowCount == null) ? 0L : rowCount;
    } catch (SQLException e) {
      LOGGER.error(SQL_EXCEPTION_MESSAGE, e.getCause());
      return -1;
    } finally {
      taskanaHistoryEngine.returnConnection();
    }
  }

  public String[] getIdIn() {
    return idIn;
  }

  public String[] getEventTypeIn() {
    return eventTypeIn;
  }

  public TimeInterval[] getCreatedIn() {
    return createdIn;
  }

  public String[] getUserIdIn() {
    return userIdIn;
  }

  public String[] getClassificationIdIn() {
    return classificationIdIn;
  }

  public String[] getApplicationEntryPointIn() {
    return applicationEntryPointIn;
  }

  public String[] getCategoryIn() {
    return categoryIn;
  }

  public String[] getDomainIn() {
    return domainIn;
  }

  public String[] getKeyIn() {
    return keyIn;
  }

  public String[] getNameIn() {
    return nameIn;
  }

  public String[] getParentIdIn() {
    return parentIdIn;
  }

  public String[] getParentKeyIn() {
    return parentKeyIn;
  }

  public int[] getPriorityIn() {
    return priorityIn;
  }

  public String[] getServiceLevelIn() {
    return serviceLevelIn;
  }

  public String[] getTypeIn() {
    return typeIn;
  }

  public String[] getCustom1In() {
    return custom1In;
  }

  public String[] getCustom2In() {
    return custom2In;
  }

  public String[] getCustom3In() {
    return custom3In;
  }

  public String[] getCustom4In() {
    return custom4In;
  }

  public String[] getCustom5In() {
    return custom5In;
  }

  public String[] getCustom6In() {
    return custom6In;
  }

  public String[] getCustom7In() {
    return custom7In;
  }

  public String[] getCustom8In() {
    return custom8In;
  }

  public String[] getEventTypeLike() {
    return eventTypeLike;
  }

  public String[] getUserIdLike() {
    return userIdLike;
  }

  public String[] getClassificationIdLike() {
    return classificationIdLike;
  }

  public String[] getApplicationEntryPointLike() {
    return applicationEntryPointLike;
  }

  public String[] getCategoryLike() {
    return categoryLike;
  }

  public String[] getDomainLike() {
    return domainLike;
  }

  public String[] getKeyLike() {
    return keyLike;
  }

  public String[] getNameLike() {
    return nameLike;
  }

  public String[] getParentIdLike() {
    return parentIdLike;
  }

  public String[] getParentKeyLike() {
    return parentKeyLike;
  }

  public String[] getServiceLevelLike() {
    return serviceLevelLike;
  }

  public String[] getTypeLike() {
    return typeLike;
  }

  public String[] getCustom1Like() {
    return custom1Like;
  }

  public String[] getCustom2Like() {
    return custom2Like;
  }

  public String[] getCustom3Like() {
    return custom3Like;
  }

  public String[] getCustom4Like() {
    return custom4Like;
  }

  public String[] getCustom5Like() {
    return custom5Like;
  }

  public String[] getCustom6Like() {
    return custom6Like;
  }

  public String[] getCustom7Like() {
    return custom7Like;
  }

  public String[] getCustom8Like() {
    return custom8Like;
  }

  public ClassificationHistoryQueryColumnName getColumnName() {
    return columnName;
  }

  public List<String> getOrderBy() {
    return orderBy;
  }

  public List<String> getOrderColumns() {
    return orderColumns;
  }

  private ClassificationHistoryQueryImpl addOrderCriteria(
      String columnName, SortDirection sortDirection) {
    String orderByDirection =
        " " + (sortDirection == null ? SortDirection.ASCENDING : sortDirection);
    orderBy.add(columnName + orderByDirection);
    orderColumns.add(columnName);
    return this;
  }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Pax Logging</title>
</head>
<body>
  Hello World of Logging!
</body>
</html>


text:
layout: post
title: Spring property-override源码解读
categories: [编程, java, spring]
tags: [property, override]
---

> `spring`编码中,我们常常使用`override`的方式改写第三方`jar`包中`bean`的属性值

#### 1. 一个例子
```xml
<context:property-override location="classpath*:conf/dataSource.properties" />

<bean id="dataSource" class="com.xx.DataSource">
        <property name="url" value="url" />
        <property name="username" value="xxx" />
        <property name="password" value="123" />
</bean>
```

#### 2. context命令空间

`context`是`spring-context`中定义的一个命令空间,从`META-INF/spring.handlers`中找到其对应`handler`

```
http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler
```

`ContextNamespaceHandler:`

```java
registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser());
```

`PropertyOverrideBeanDefinitionParser.getBeanClass`

```java
protected Class<?> getBeanClass(Element element) {
    return PropertyOverrideConfigurer.class;
}
```

#### 3. PropertyOverrideConfigurer.processProperties

`PropertyOverrideConfigurer`继承自`PropertyResourceConfigurer`,并重写了`processProperties`方法

```java
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
			throws BeansException {

    for (Enumeration<?> names = props.propertyNames(); names.hasMoreElements();) {
        String key = (String) names.nextElement();
        try {
            processKey(beanFactory, key, props.getProperty(key));
        }
        catch (BeansException ex) {
            String msg = "Could not process key '" + key + "' in PropertyOverrideConfigurer";
            if (!this.ignoreInvalidKeys) {
                throw new BeanInitializationException(msg, ex);
            }
            if (logger.isDebugEnabled()) {
                logger.debug(msg, ex);
            }
        }
    }
}
```

#### 4. PropertyOverrideConfigurer.processKey

```java
protected void processKey(ConfigurableListableBeanFactory factory, String key, String value)
        throws BeansException {

    int separatorIndex = key.indexOf(this.beanNameSeparator);
    if (separatorIndex == -1) {
        throw new BeanInitializationException("Invalid key '" + key +
                "': expected 'beanName" + this.beanNameSeparator + "property'");
    }
    String beanName = key.substring(0, separatorIndex);
    String beanProperty = key.substring(separatorIndex+1);
    this.beanNames.add(beanName);
    applyPropertyValue(factory, beanName, beanProperty, value);
    if (logger.isDebugEnabled()) {
        logger.debug("Property '" + key + "' set to value [" + value + "]");
    }
}
```

> 这里可以看出属性文件的`key`必须是`beanName.property`,并且不支持多级

#### 5. PropertyOverrideConfigurer.applyPropertyValue

`bean`属性替换的逻辑在`PropertyOverrideConfigurer.applyPropertyValue`

```java
protected void applyPropertyValue(
        ConfigurableListableBeanFactory factory, String beanName, String property, String value) {

    BeanDefinition bd = factory.getBeanDefinition(beanName);
    while (bd.getOriginatingBeanDefinition() != null) {
        bd = bd.getOriginatingBeanDefinition();
    }
    PropertyValue pv = new PropertyValue(property, value);
    pv.setOptional(this.ignoreInvalidKeys);
    bd.getPropertyValues().addPropertyValue(pv);
}
```

#### 6. 总结

对比一下`placeholder`和`override`的区别,虽然两者没什么可比性(一个是占位、一个是重写),但他们的应用却有重叠:

* `placeholder`是占位,即一个符号,需要用具体的属性值来替换。`override`是重写,只是提供一个在属性文件中重写`bean`默认属性值的方法。
* `placeholder`需要用`<property name="username" value="${jdbc.username:root}"/>`定义,而`override`直接给定一个默认值`<property name="username" value="root"/>`
* `placeholder`可以用于`beanName,class,property,scope,property`等,而`override`只能用于`property`
* `placeholder`的属性`key`和占位符相同,而`override`的属性`key`是`bean.property`


text:
int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([RaabeAppAppDelegate class]));
    }
}


text:
from cssselect import GenericTranslator as OriginalGenericTranslator
from cssselect import HTMLTranslator as OriginalHTMLTranslator
from cssselect.xpath import XPathExpr as OriginalXPathExpr
from cssselect.xpath import _unicode_safe_getattr, ExpressionError
from cssselect.parser import FunctionalPseudoElement

class XPathExpr(OriginalXPathExpr):

    textnode = False
    attribute = None

    @classmethod
    def from_xpath(cls, xpath, textnode=False, attribute=None):
        x = cls(path=xpath.path, element=xpath.element, condition=xpath.condition)
        x.textnode = textnode
        x.attribute = attribute
        return x

    def __str__(self):
        path = super(XPathExpr, self).__str__()
        if self.textnode:
            if path == '*':
                path = 'text()'
            elif path.endswith('::*/*'):
                path = path[:-3] + 'text()'
            else:
                path += '/text()'

        if self.attribute is not None:
            if path.endswith('::*/*'):
                path = path[:-2]
            path += '/@%s' % self.attribute

        return path

    def join(self, combiner, other):
        super(XPathExpr, self).join(combiner, other)
        self.textnode = other.textnode
        self.attribute = other.attribute
        return self

class TranslatorMixin(object):
    """This mixin adds support to CSS pseudo elements via dynamic dispatch.

    Currently supported pseudo-elements are ``::text`` and ``::attr(ATTR_NAME)``.
    """

    def xpath_element(self, selector):
        xpath = super(TranslatorMixin, self).xpath_element(selector)
        return XPathExpr.from_xpath(xpath)

    def xpath_pseudo_element(self, xpath, pseudo_element):
        """
        Dispatch method that transforms XPath to support pseudo-element
        """
        if isinstance(pseudo_element, FunctionalPseudoElement):
            method = 'xpath_%s_functional_pseudo_element' % (
                pseudo_element.name.replace('-', '_'))
            method = _unicode_safe_getattr(self, method, None)
            if not method:
                raise ExpressionError(
                    "The functional pseudo-element ::%s() is unknown"
                    % pseudo_element.name)
            xpath = method(xpath, pseudo_element)
        else:
            method = 'xpath_%s_simple_pseudo_element' % (
                pseudo_element.replace('-', '_'))
            method = _unicode_safe_getattr(self, method, None)
            if not method:
                raise ExpressionError(
                    "The pseudo-element ::%s is unknown"
                    % pseudo_element)
            xpath = method(xpath)
        return xpath

    def xpath_attr_functional_pseudo_element(self, xpath, function):
        """Support selecting attribute values using ::attr() pseudo-element
        """
        if function.argument_types() not in (['STRING'], ['IDENT']):
            raise ExpressionError(
                "Expected a single string or ident for ::attr(), got %r"
                % function.arguments)
        return XPathExpr.from_xpath(xpath,
                                    attribute=function.arguments[0].value)

    def xpath_text_simple_pseudo_element(self, xpath):
        """Support selecting text nodes using ::text pseudo-element"""
        return XPathExpr.from_xpath(xpath, textnode=True)

class GenericTranslator(TranslatorMixin, OriginalGenericTranslator):
    pass

class HTMLTranslator(TranslatorMixin, OriginalHTMLTranslator):
    pass

_translator = HTMLTranslator()

def css2xpath(query):
    "Return translated XPath version of a given CSS query"
    return _translator.css_to_xpath(query)


text:
<?php

/**
 * Created by PhpStorm.
 * User: kuroro2121
 * Date: 14/10/21
 * Time: 13:24
 */
trait DITestServiceOneTraits
{
    protected $testServiceOne;

    public function setTestServiceOne($service)
    {
        $this->testServiceOne = $service;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.jf.java.web</groupId>
	<artifactId>LinkStore</artifactId>
	<packaging>war</packaging>
	<version>0.1</version>
	<name>LinkStore</name>
	<url>https://github.com/jamesfarrugia/LinkStore</url>

	<properties>
		<jdk.version>1.8</jdk.version>
		<servlet.version>3.0.1</servlet.version>

		<junit.version>4.11</junit.version>
		<mockito.version>1.9.5</mockito.version>
		<testng.version>6.8.7</testng.version>

		<spring.version>4.2.3.RELEASE</spring.version>
		<jackson.version>2.4.3</jackson.version>

		<logback.version>1.0.13</logback.version>
		<jcl-over-slf4j.version>1.7.5</jcl-over-slf4j.version>

		<sqlite.version>3.8.11.2</sqlite.version>
		<jooq.version>3.7.1</jooq.version>
		<cglib.version>3.1</cglib.version>
		<bonecp.version>0.8.0.RELEASE</bonecp.version>

		<lucene.version>5.3.1</lucene.version>

		<commons.http.version>4.4</commons.http.version>
		<commons.io.version>2.2</commons.io.version>
		<jsoup.version>1.8.2</jsoup.version>
	</properties>

	<dependencies>
		<!-- Unit Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>${mockito.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>${testng.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Servlet dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${jcl-over-slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
		</dependency>

		<!-- Jackson for JSON mappings -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<!-- SQLite driver -->
		<dependency>
			<groupId>org.xerial</groupId>
			<artifactId>sqlite-jdbc</artifactId>
			<version>${sqlite.version}</version>
		</dependency>

		<!-- jOOQ -->
		<dependency>
			<groupId>org.jooq</groupId>
			<artifactId>jooq</artifactId>
			<version>${jooq.version}</version>
		</dependency>

		<!-- CGLib -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>${cglib.version}</version>
		</dependency>

		<!-- BonceCP -->
		<dependency>
			<groupId>com.jolbox</groupId>
			<artifactId>bonecp</artifactId>
			<version>${bonecp.version}</version>
		</dependency>

		<!-- Lucene -->
		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-core</artifactId>
			<version>${lucene.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-analyzers-common</artifactId>
			<version>${lucene.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-queryparser</artifactId>
			<version>${lucene.version}</version>
		</dependency>

		<!-- HTTP client -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>${commons.http.version}</version>
		</dependency>

		<!-- IO Utils -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons.io.version}</version>
		</dependency>

		<!-- JSoup for processing HTML -->
		<dependency>
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>${jsoup.version}</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>LinkStore</finalName>
		<plugins>
			<!-- Set JDK Compiler Level -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<organization>
		<name>James Farrugia</name>
		<url>jamesfarrugia.com</url>
	</organization>

	<scm>
		<url>https://github.com/jamesfarrugia/LinkStore</url>
	</scm>
	<issueManagement>
		<url>https://github.com/jamesfarrugia/LinkStore/issues</url>
		<system>GitHub</system>
	</issueManagement>
</project>


text:
<?php
/**
 * @package DRYTemplatingAddon
 */
class addon_dry_templating_admin extends addon_dry_templating_info
{
  public function init_pages ($menuName)
  {
    menu_page::addonAddPage('addon_dry_templating_page_groups','','Page Groups', $this->name);
  }

  public function display_addon_dry_templating_page_groups ()
  {
    $reg = geoAddon::getRegistry($this->name);

    // load existing page group data or submitted data on error
    if ($reg->page_groups_with_error) {
      $page_groups = $reg->page_groups_with_error;
    } elseif ($reg->page_groups) {
      $page_groups = $reg->page_groups;
    }

    // unset page_groups_with_error to avoid loop
    $reg->page_groups_with_error = null;
    $reg->save();

    $tpl_vars = array();
    $tpl_vars['admin_messages'] = geoAdmin::m();

    if ($page_groups) {
      // convert the array of page ids to a comma separated list
      foreach ($page_groups as &$page_group) {
        $page_group['page_ids'] = implode(',', $page_group['page_ids']);
      }
      $tpl_vars['page_groups'] = $page_groups;
    }

    geoView::getInstance()->setBodyTpl('admin/page_groups.tpl', $this->name)->setBodyVar($tpl_vars);
  }

  public function update_addon_dry_templating_page_groups ()
  {
    if (isset($_POST['page_groups'])) {
      $new_page_groups = $_POST['page_groups'];
    } else {
      return false;
    }

    $admin = geoAdmin::getInstance();
    $reg = geoAddon::getRegistry($this->name);

    $page_groups = array();

    // build the new list of page groups
    foreach ($new_page_groups as $key => $page_group) {
      // clean the input and check the input for errors
      $cleaned_result = $this->clean_page_group_input($key, $page_group);
      $page_group = $cleaned_result[0];
      $errors = $cleaned_result[1];

      // if there was an error add each error to the list of admin messages
      if ($errors) {
        $error = true;
        foreach ($errors as $error) {
          $admin->userError($error);
        }
      }

      if (!(is_null($page_group) || $page_group['remove'])) {
        array_push($page_groups, $page_group);
      }
    }

    array_multisort($page_groups);

    // give each group an id field
    foreach ($page_groups as $key => &$page_group) {
      $page_group['id'] = $key;
    }

    if ($error) {
      $admin->userError("Page groups not saved.");
      $reg->page_groups_with_error = $page_groups;
      $reg->save();
      return false;
    } else {
      $reg->page_groups = $page_groups;
      $reg->save();
      $admin->message("Page groups saved.");
      return true;
    }
  }

  private function clean_page_group_input ($id, $input)
  {
    $errors = array();

    // ignore a new group if field is empty
    if ($id == 'new' && (!$input['name'] && !$input['page_ids'])) {
      return array(null, $errors);
    }

    // fail if empty field
    if (!$input['name'] || !$input['page_ids']) {
      array_push($errors, 'Empty field.');
    }

    // strip all whitespace from page ids
    $input['page_ids'] = preg_replace('/\s+/', '', $input['page_ids']);

    // strip all whitespace from name
    $input['name'] = preg_replace('/\s+/', '', $input['name']);

    // only letters and underscores allowed in name
    if (preg_match('/[^A-Za-z_]/', $input['name'])) {
      array_push($errors, 'Invalid charater in group name: ' . $input['name']);
    }

    // only letters, numbers, underscores, and commas allowed in page id list
    if (preg_match('/[^A-Za-z0-9_,]/', $input['page_ids'])) {
      array_push($errors, 'Invalid charater in page id list: ' . $input['page_ids']);
    }

    // make name lowercase
    $input['name'] = strtolower($input['name']);

    // create array from list of page ids
    $input['page_ids'] = explode(',', $input['page_ids']);

    return array($input, $errors);
  }
}


text:
from a10sdk.common.A10BaseClass import A10BaseClass

class Policy(A10BaseClass):

    """Class Description::
    WAF policy File.

    Class policy supports CRUD Operations and inherits from `common/A10BaseClass`.
    This class is the `"PARENT"` class for this module.`

    :param policy: {"description": "WAF policy File", "format": "string", "minLength": 1, "optional": false, "maxLength": 63, "type": "string"}
    :param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
    :param remote_file: {"optional": true, "type": "string", "description": "profile name for remote url", "format": "url"}
    :param use_mgmt_port: {"default": 0, "optional": true, "type": "number", "description": "Use management port as source port", "format": "flag"}
    :param period: {"description": "Specify the period in second", "format": "number", "type": "number", "maximum": 31536000, "minimum": 60, "optional": true}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    URL for this object::
    `https://<Hostname|Ip address>//axapi/v3/import-periodic/policy/{policy}`.

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""
        self.required = [ "policy"]

        self.b_key = "policy"
        self.a10_url="/axapi/v3/import-periodic/policy/{policy}"
        self.DeviceProxy = ""
        self.policy = ""
        self.uuid = ""
        self.remote_file = ""
        self.use_mgmt_port = ""
        self.period = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)


text:
@interface PodsDummy_Pods_LUAutocompleteViewExample : NSObject
@end
@implementation PodsDummy_Pods_LUAutocompleteViewExample
@end


text:
/**
 * WHATWG fetch polyfill for client side.
 */

"use strict";

var _Object$defineProperty = require("babel-runtime/core-js/object/define-property")["default"];

_Object$defineProperty(exports, "__esModule", {
  value: true
});

var fetch;

if (typeof window !== "undefined") {
  if (!window.fetch) {
    require("whatwg-fetch");
  }
  fetch = window.fetch;
}

exports["default"] = fetch;
module.exports = exports["default"];