text:
use db::{enums, moves};
use db::moves::{get_attacker, get_target, get_user};
use graphic;
use player::Next;
use rand;
use rand::{Rng, thread_rng};
use std::collections::HashMap;

/// The standard arena is based on the default 1v1 fight.

impl<'a> super::Arena<'a> {
    /// Simulating a fight. This function is called on a arena and uses the next_move variables of
    /// the players to know what to do in this round.
    /// Important: All next_move variables must contain a Some() entry. If the function is called
    /// and atleast one variable is holding a None, this function will panic!
    pub fn fight(&mut self, mut window: &mut graphic::gui::App) {

        // This flag is used to show that the round is "over" earlier as aspected.
        // This can be happen if pursuit was used or both pokemons are swapped.
        let mut end_of_fight = false;
        // Setting the switched flag in the Player structs to false and reset if a swap will be done
        self.get_player_one().set_switched(false);
        self.get_player_two().set_switched(false);

        // Handle the pursuit(ID: 228) attack
        // If one pokemon wants to swap and the other pokemon is using pursuit. The attack will be
        // handle before swapping the pokemon
        match self.get_player_one()
            .get_next_move()
            .expect("Unexpected error! This field of player one shouldn`t be None at this point.") {
            Next::Move(technique) => {
                if technique.get_id() == 228 {
                    match self.get_player_one()
                        .get_next_move()
                        .expect("Unexpected error! This field of player one shouldn`t be None \
                                 at this point.") {
                        Next::Switch(_) => {
                            // Resolving pursuit, updating last action and last move
                            // and setting the next move to None
                            call_resolve(self, technique, enums::Player::One, &mut window);
                            self.get_player_one().set_next_move(None);

                        }
                        _ => {}
                    }
                }
            }
            Next::Switch(_) => {
                match self.get_player_one()
                    .get_next_move()
                    .expect("Unexpected error! This field of player one shouldn`t be None at \
                             this point.") {
                    Next::Move(technique) => {
                        if technique.get_id() == 228 {
                            // Resolving pursuit, updating last action and last move
                            // and setting the next move to None
                            call_resolve(self, technique, enums::Player::Two, &mut window);
                            self.get_player_two().set_next_move(None);
                        }
                    }
                    _ => {}
                }
            }
            _ => {}
        }
        // Switch Pokemon of Player One if he wants to
        if let Some(x) = self.get_player_one().get_next_move() {
            match x {
                Next::Switch(pkmn) => {
                    // Switch of the current pokemon + setting flag
                    self.get_player_one().set_current(pkmn.get_int() - 1);
                    self.get_player_one().set_switched(true);
                    // Updating last action and setting next move to None. Last Move isnt updated
                    // because the last action wasnt a move
                    let old_move = self.get_player_one().get_next_move().unwrap().clone();
                    self.get_player_one().set_last_action((old_move, 0));
                    self.get_player_one().set_next_move(None);
                }
                _ => {}
            }
        }
        // Switch Pokemon of Player Two if he wants to
        if let Some(x) = self.get_player_two().get_next_move() {
            match x {
                Next::Switch(pkmn) => {
                    // Switch of the current pokemon + setting flag
                    self.get_player_two().set_current(pkmn.get_int() - 1);
                    self.get_player_two().set_switched(true);
                    // Updating last action and setting next move to None. Last Move isnt updated
                    // because the last action wasnt a move
                    let old_move = self.get_player_two().get_next_move().unwrap().clone();
                    self.get_player_two().set_last_action((old_move, 0));
                    self.get_player_two().set_next_move(None);
                }
                _ => {}
            }
        }
        // If player one doesnt need to make a move anymore, only resolve attack of player two
        if self.get_player_one().get_next_move().is_none() &&
           self.get_player_two().get_next_move().is_some() {
            match self.get_player_two().get_next_move().unwrap() {
                Next::Move(x) => {
                    call_resolve(self, x, enums::Player::Two, &mut window);
                }
                _ => {}
            }
            end_of_fight = true;
            // If player two doesnt need to make a move anymore, only resolve attack of player one
        } else if self.get_player_two().get_next_move().is_none() &&
                  self.get_player_one().get_next_move().is_some() {
            match self.get_player_one().get_next_move().unwrap() {
                Next::Move(x) => {
                    call_resolve(self, x, enums::Player::One, &mut window);
                }
                _ => {}
            }
            end_of_fight = true;
            // If both player dont have a move go out of fight
        } else if self.get_player_two().get_next_move().is_none() &&
                  self.get_player_one().get_next_move().is_none() {
            end_of_fight = true;
        }

        // If both player want to perform an attack Priority and Speed of Pokemon will be used to
        // decide which pokemon strikes first

        // Variables for faster comparison. x_prio is the priority of the pokemon of player x and
        // x_speed is the attackspeed of the pokemon of player x
        if !end_of_fight {
            let one_prio;
            let one_attack;
            match self.get_player_one().get_next_move().unwrap() {
                Next::Move(attack) => {
                    one_prio = attack.get_priority();
                    one_attack = attack.clone();
                }
                _ => unreachable!(),
            };
            let two_prio;
            let two_attack;
            match self.get_player_two().get_next_move().unwrap() {
                Next::Move(attack) => {
                    two_prio = attack.get_priority();
                    two_attack = attack.clone();
                }
                _ => unreachable!(),
            };
            let mut current = self.get_player_one().get_current();
            let mut one_speed = self.get_player_one().get_pokemon_list()[current]
                .get_current()
                .get_stat(&enums::Stats::Speed);
            // If the pokemon one is paralysed reduce speed by 50%
            if self.get_player_one().get_pokemon_list()[current].get_non_volatile().0 ==
               enums::NonVolatile::Paralysis {
                one_speed /= 2;
            }
            current = self.get_player_two().get_current();
            let mut two_speed = self.get_player_two().get_pokemon_list()[current]
                .get_current()
                .get_stat(&enums::Stats::Speed);
            // If the pokemon two is paralysed reduce speed by 50%
            if self.get_player_two().get_pokemon_list()[current].get_non_volatile().0 ==
               enums::NonVolatile::Paralysis {
                two_speed /= 2;
            }
            // The attack with the higher Priority starts
            if one_prio > two_prio {
                if !call_resolve(self, one_attack, enums::Player::Two, &mut window) {
                    call_resolve(self, two_attack, enums::Player::One, &mut window);
                }
            } else if one_prio < two_prio {
                if !call_resolve(self, two_attack, enums::Player::One, &mut window) {
                    call_resolve(self, one_attack, enums::Player::Two, &mut window);
                }
            } else {
                // If the attack priority is the same the pokemon with the higher attackspeed starts
                // If the attack speed is the same, the pokemon of player one will strike first
                if one_speed >= two_speed {
                    if !call_resolve(self, one_attack, enums::Player::Two, &mut window) {
                        call_resolve(self, two_attack, enums::Player::One, &mut window);
                    }
                } else {
                    if !call_resolve(self, two_attack, enums::Player::One, &mut window) {
                        call_resolve(self, one_attack, enums::Player::Two, &mut window);
                    }
                }
            }
        }

        // Handles Poison and Burn aswell as BadPoison(Bad Poison is dealing the same damage as
        // Poison right now)
        // Player One
        let mut non_volatile = get_target(enums::Player::One, self).get_non_volatile().0;
        if (non_volatile == enums::NonVolatile::Poison) ||
           (non_volatile == enums::NonVolatile::Burn) ||
           (non_volatile == enums::NonVolatile::BadPoison) {
            window.set_battle_text(get_target(enums::Player::One, self).get_name().clone() +
                                   " got damage by " +
                                   non_volatile.to_string().as_str());
            poison_burn_damage(self, enums::Player::One);
        }
        // Player Two
        non_volatile = get_target(enums::Player::Two, self).get_non_volatile().0;
        if (non_volatile == enums::NonVolatile::Poison) ||
           (non_volatile == enums::NonVolatile::Burn) ||
           (non_volatile == enums::NonVolatile::BadPoison) {
            window.set_battle_text(get_target(enums::Player::Two, self).get_name().clone() +
                                   " got damage by " +
                                   non_volatile.to_string().as_str());
            poison_burn_damage(self, enums::Player::Two);
        }

        // Checks if one of the two player died
        check_dead(enums::Player::One, self, window);
        check_dead(enums::Player::Two, self, window);
    }
}
/// Resolving if the resolve method must be called and after that if the pokemon is dead
fn call_resolve(arena: &mut super::Arena,
                attack: moves::Technique,
                player: enums::Player,
                mut window: &mut graphic::gui::App)
                -> bool {
    let mut attack_is_allowed = true;
    // Checks if the pokemon is allowed to attack. This is influeced by Sleep, Freeze and Paralysis
    // Checks if the pokemon is paralysed
    if get_target(player, arena).get_non_volatile().0 == enums::NonVolatile::Paralysis {
        let mut rng = thread_rng();
        // With a chance of 25% the pokemon will not attack
        if rng.gen_range(0, 4) != 0 {
            attack_is_allowed = false;
            window.set_battle_text(get_target(player, arena).get_name().clone() + " is paralysed!");
        }
        // Checks it the pokemon is sleeping
    } else if get_target(player, arena).get_non_volatile().0 == enums::NonVolatile::Sleep {
        // If the pokemon is not sleeping for atleast one round it will not wake up
        if get_target(player, arena).get_non_volatile().1 == 0 {
            window.set_battle_text(get_target(player, arena).get_name().clone() + " is sleeping!");
            attack_is_allowed = false;
            // Pokemon will wake up after 3 rounds
        } else if get_target(player, arena).get_non_volatile().1 >= 3 {
            window.set_battle_text(get_target(player, arena).get_name().clone() + " wakes up.");
            get_target(player, arena).set_non_volatile(enums::NonVolatile::Undefined);
        } else {
            // Check if pokemon will wake up
            if rand::random::<bool>() {
                window.set_battle_text(get_target(player, arena).get_name().clone() + " wakes up.");
                get_target(player, arena).set_non_volatile(enums::NonVolatile::Undefined);
            } else {
                window.set_battle_text(get_target(player, arena).get_name().clone() +
                                       " is sleeping!");
                attack_is_allowed = false;
            }
        }
    } else if get_target(player, arena).get_non_volatile().0 == enums::NonVolatile::Freeze {
        let mut rng = thread_rng();
        // With a chance of 20% the pokemon will not attack
        if rng.gen_range(0, 5) != 0 {
            attack_is_allowed = false;
            window.set_battle_text(get_target(player, arena).get_name().clone() + " is frozen!");
        } else {
            window.set_battle_text(get_target(player, arena).get_name().clone() +
                                   " is not frozen anymore!");
            get_target(player, arena).set_non_volatile(enums::NonVolatile::Undefined);
        }
    }

    if attack_is_allowed {
        // Get the names of the current pokemon
        let message = get_user(player, arena).get_name().clone();
        // Handles confusion and infatuation. If nothing is stops attack, the attack will be
        // resolved
        if confusion(arena, player) {
            let mut pkmn = get_target(player, arena).clone();
            let damage = ((((2.0 * pkmn.get_level() as f32 + 10.0) / 250.0) *
                           pkmn.get_current().get_stat(&enums::Stats::Attack) as f32 /
                           pkmn.get_current().get_stat(&enums::Stats::Defense) as f32 *
                           40.0 + 2.0)) as u16;
            get_target(player, arena).get_current().set_stats(enums::Stats::Hp, damage);
            window.set_battle_text(message + " is confused and hitted himself!");
        } else if infatuation(arena, player) {
            window.set_battle_text(message + " has the infatuation effect!");
        } else {
            if get_attacker(player, arena).get_next_move().unwrap() == Next::Flinch {
                window.set_battle_text(message.clone() + " flinched.");
                let last = get_attacker(player, arena).get_next_move().unwrap();
                get_attacker(player, arena).set_last_action((last, 0));
                get_attacker(player, arena).set_next_move(None);
            } else {
                window.set_battle_text(message.clone() + " uses " + attack.get_name());
                attack.resolve(arena, player, &mut window);
            }
        }
    }
    // Checks if one of the two player died
    match player {
        enums::Player::One => {
            if check_dead(enums::Player::One, arena, window) {
                check_dead(enums::Player::Two, arena, window);
                return true;
            }
            false
        }
        enums::Player::Two => {
            if check_dead(enums::Player::Two, arena, window) {
                check_dead(enums::Player::One, arena, window);
                return true;
            }
            false
        }
    }

}

/// Handles the end of turn flags
fn end_of_turn_flags(arena: &mut super::Arena,
                     player: enums::Player,
                     mut window: &mut graphic::gui::App) {
    let map: HashMap<enums::EndOfTurn, u8> =
        get_target(player, arena).get_end_of_turn_flags().clone();

    for i in map.iter() {
        match *i.0 {
            // Absorbs HP of the pokemon
            enums::EndOfTurn::LeechSeed => {
                // Get hp from defending Pokemon
                let mut hp = get_user(player, arena)
                    .get_base()
                    .get_stat(&enums::Stats::Hp);
                // Get the amount for heal and dmg
                let absorb = hp / 16;
                // Damage Defender
                get_user(player, arena)
                    .get_current()
                    .set_stats(enums::Stats::Hp, hp - absorb);
                // Get HP of attacking Pkmn
                hp = get_target(player, arena)
                    .get_current()
                    .get_stat(&enums::Stats::Hp);
                // If Atacker isnt fully healed after that action add the absorbed amount to
                // current Hp
                if get_target(player, arena)
                    .get_base()
                    .get_stat(&enums::Stats::Hp) >= (hp + absorb) {
                    get_target(player, arena)
                        .get_current()
                        .set_stats(enums::Stats::Hp, hp + absorb);
                } else {
                    // else set the hp to the base value
                    hp = get_target(player, arena)
                        .get_base()
                        .get_stat(&enums::Stats::Hp);
                    get_target(player, arena)
                        .get_current()
                        .set_stats(enums::Stats::Hp, hp);
                }
                if !get_target(player, arena).is_alive() {
                    window.set_screen(graphic::gui::Screen::Switch);
                }
            }
            // After four rounds the pokemon will die
            enums::EndOfTurn::PerishSong => {
                if *i.1 != 4 {
                    *get_target(player, arena)
                        .get_end_of_turn_flags()
                        .get_mut(&enums::EndOfTurn::PerishSong)
                        .unwrap() = *i.1 + 1;
                } else {
                    get_target(player, arena)
                        .get_current()
                        .set_stats(enums::Stats::Hp, 0);
                    window.set_screen(graphic::gui::Screen::Switch);
                }
            }
            // Pokemon will fall asleep in the next round
            enums::EndOfTurn::Yawn => {
                if *i.1 > 1 {
                    *get_target(player, arena)
                        .get_end_of_turn_flags()
                        .get_mut(&enums::EndOfTurn::Yawn)
                        .unwrap() = *i.1 + 1;
                } else {
                    get_target(player, arena)
                        .get_end_of_turn_flags()
                        .remove(&enums::EndOfTurn::Yawn);
                    if get_target(player, arena)
                        .get_non_volatile()
                        .0 != enums::NonVolatile::Sleep {
                        get_target(player, arena).set_non_volatile(enums::NonVolatile::Sleep);
                    }
                }
            }
            // Changing the flying type at position one
            enums::EndOfTurn::RoostTypeOne => {
                if *i.1 > 1 {
                    *get_target(player, arena)
                        .get_end_of_turn_flags()
                        .get_mut(&enums::EndOfTurn::RoostTypeOne)
                        .unwrap() = *i.1 + 1;
                } else {
                    get_target(player, arena).set_type(0, enums::Types::Flying);
                }
            }
            // Changing the flying type at position two
            enums::EndOfTurn::RoostTypeTwo => {
                if *i.1 > 1 {
                    *get_target(player, arena)
                        .get_end_of_turn_flags()
                        .get_mut(&enums::EndOfTurn::RoostTypeOne)
                        .unwrap() = *i.1 + 1;
                } else {
                    get_target(player, arena).set_type(2, enums::Types::Flying);
                }
            }
            // Pokemon gets damage at the end of each round
            enums::EndOfTurn::Trap => {
                // Get base hp from Pokemon
                let hp = get_target(player, arena)
                    .get_base()
                    .get_stat(&enums::Stats::Hp);
                // Get the amount for dmg
                let damage = hp / 8;
                // Damage pokemon
                get_target(player, arena)
                    .get_current()
                    .set_stats(enums::Stats::Hp, hp - damage);
                // if pokemon dead force a switch
                if !get_target(player, arena).is_alive() {
                    window.set_screen(graphic::gui::Screen::Switch);
                }

            }
            // Pokemon get hp at the end of every round
            enums::EndOfTurn::Ingrain => {
                let mut hp = get_target(player, arena)
                    .get_base()
                    .get_stat(&enums::Stats::Hp);
                // Get the amount for heal
                hp = hp + (hp / 16);
                if get_target(player, arena)
                    .get_base()
                    .get_stat(&enums::Stats::Hp) >= hp {
                    get_target(player, arena)
                        .get_current()
                        .set_stats(enums::Stats::Hp, hp);
                } else {
                    hp = get_target(player, arena)
                        .get_base()
                        .get_stat(&enums::Stats::Hp);
                    get_target(player, arena)
                        .get_current()
                        .set_stats(enums::Stats::Hp, hp);
                }
            }
        }
    }
}

/// Handle Confusion
fn confusion(arena: &mut super::Arena, player: enums::Player) -> bool {
    if get_target(player, arena)
        .get_fight_flags()
        .contains_key(&enums::Fighting::Infatuation) {
        return rand::random::<bool>();
    }
    false
}
/// Handle Infatuation
fn infatuation(arena: &mut super::Arena, player: enums::Player) -> bool {
    if get_target(player, arena)
        .get_fight_flags()
        .contains_key(&enums::Fighting::Confusion) {
        let random = rand::random::<u8>();
        return random > random / 3;
    }
    false
}
/// Deals the burn and poison damage.
fn poison_burn_damage(arena: &mut super::Arena, player: enums::Player) {
    let base_hp = get_target(player, arena)
        .get_base()
        .get_stat(&enums::Stats::Hp);
    // Get the amount for heal
    let damage = base_hp / 8;
    let current_hp = get_target(player, arena).get_current().get_stat(&enums::Stats::Hp);
    if !(damage > current_hp) {
        get_target(player, arena).get_current().set_stats(enums::Stats::Hp, current_hp - damage);
    } else {
        get_target(player, arena).get_current().set_stats(enums::Stats::Hp, 0);
    }
}

/// Checks if the pokemon are dead
fn check_dead(player: enums::Player,
              arena: &mut super::Arena,
              mut window: &mut graphic::gui::App)
              -> bool {
    // Checks if the pokemon are dead
    let dead = !get_target(player, arena).is_alive();
    let message = get_target(player, arena).get_name().clone();
    // Swaps the pokemon if its dead
    if dead {
        window.set_battle_text(message.clone() + " is defeated!");
        window.set_screen(graphic::gui::Screen::Switch);
        return true;
    }
    false
}


text:
Calculate iteratively the relief along an interface with lateral density variations that corresponds to a given Bouguer anomaly using the algorithm of Wieczorek and Phillips (1998).

# Usage

call BAtoHilmRhoH (`cilm`, `ba`, `grid`, `lmax`, `nmax`, `mass`, `r0`, `rho`, `gridtype`, `w`, `plx`, `zero`, `filtertype`, `filterdeg`, `lmaxcalc`, `exitstatus`)

# Parameters

`cilm` : output, real\*8, dimension (2, `lmaxcalc`+1, `lmaxcalc`+1)
:   An estimate of the real spherical harmonic coefficients (geodesy normalized) of relief along an interface with lateraly varying density contrast `rho` that satisfies the Bouguer anomaly `ba`. The degree-zero term corresponds to the mean radius of the relief.

`ba` : input, real\*8, dimension (2, `lmaxcalc`+1, `lmaxcalc`+1)
:   The real spherical harmonic coefficients of the Bouguer anomaly referenced to a spherical interface `r0`.

`grid` : input, real\*8, dimension (`lmax`+1, 2\*`lmax`+1) for `gridtype` 1, (2\*`lmax`+2, 2\*`lmax`+2) for `gridtype` 2, (2\*`lmax`+2, 4\*`lmax`+4) for `gridtype` 3
:   The initial estimate for the radii of the interface evaluated on a grid corresponding to a function of maximum spherical harmonic degree `lmax`. This is calculated by a call to either `MakeGridGLQ` or `MakeGridDH`. This grid must contain the degree-0 average radius of the interface.

`lmax` : input, integer
:   The spherical harmonic bandwidth of the input relief `grid`, which determines the dimensions of `grid`. If `lmaxcalc` is not set, this determines also the maximum spherical harmonic degree of the output spherical harmonic coefficients of the relief and the input spherical harmonics of the Bouguer anomaly.

`nmax` : input, integer
:   The maximum order used in the Taylor-series expansion used in calculating the potential coefficients.

`mass` : input, real\*8
:   The mass of the planet in kg.

`r0` : input, real\*8
:   The reference radius of the Bouguer anomaly `ba`.

`rho` : input, real\*8, dimension (`lmax`+1, 2\*`lmax`+1) for `gridtype` 1, (2\*`lmax`+2, 2\*`lmax`+2) for `gridtype` 2, (2\*`lmax`+2, 4\*`lmax`+4) for `gridtype` 3
:   The density contrast of the relief in kg/m^3, with the same dimensions as `grid`.

`gridtype` : input, integer
:   1 = Gauss-Legendre grids, calculated using `SHGLQ` and `MakeGridGLQ`. 2 = Equally sampled Driscoll-Healy grids, `n` by `n`, calculated using `MakeGridDH`. 3 = Equally spaced Driscoll-Healy grids, `n` by 2`n`, calculated using `MakeGridDH`.

`w` : optional, input, real\*8, dimension (`lmax`+1)
:   The weights used in the Gauss-Legendre quadrature. These are calculated from a call to `SHGLQ`. If present, one of `plx` or `zero` must also be present.

`plx` : optional, input, real\*8, dimension (`lmax`+1, (`lmax`+1)\*(`lmax`+2)/2)
:   An array of the associated Legendre functions calculated at the nodes used in the Gauss-Legendre quadrature. These are determined from a call to `SHGLQ`.

`zero` : optional, input, real\*8, dimension (`lmax`+1)
:   The nodes used in the Gauss-Legendre quadrature over latitude, calculated by a call to `SHGLQ`.

`filtertype` : optional, input, integer, default = 0
:   Apply a filter when calculating the relief in order to minimize the destabilizing effects of downward continuation which amplify uncertainties in the Bouguer anomaly. If 0, no filtering is applied. If 1, use the minimum amplitude filter `DownContFilterMA`. If 2, use the minimum curvature filter `DownContFilterMC`.

`filterdeg` : optional, input, integer
:   The spherical harmonic degree for which the filter is 0.5.

`lmaxcalc` : optional, input, integer, default = `lmax`
:   The maximum degree that will be calculated in the spherical harmonic expansions.

`exitstatus` : output, optional, integer
:   If present, instead of executing a STOP when an error is encountered, the variable exitstatus will be returned describing the error. 0 = No errors; 1 = Improper dimensions of input array; 2 = Improper bounds for input variable; 3 = Error allocating memory; 4 = File IO error.

# Description

`BAtoHilmRhoH` is used to solve  iteratively for the relief along an interface with lateral variations in density that corresponds to a given Bouguer anomaly. This is equation 18 of Wieczorek and Phillips (1998), modified to account for density variations as in equation 30 of Wieczorek 2007, which implicitly takes into consideration the finite-amplitude correction. Each iteration takes as input a guess for the relief and outputs the iteratively improved spherical harmonic coefficients of this relief. These coefficients can then be re-expanded and re-input into this routine as the next guess. For the initial guess, it is often sufficient to use the relief predicted using the first-order "mass sheet" approximation. The input relief `grid` can be of one of three type specified by `gridtype`: 1 for Gauss-Legendre grids, 2 for equally sampled Driscoll-Healy grids (`n` by `n`), and 3 for equally spaced Driscoll-Healy grids (`n` by 2`n`).

If the algorithm does not converge, one might want to try damping the initial estimate. Alternatively, iterations of the following form have proven successfulin in damping oscilations between successive iterations:

`h3 = (h2+h1)/2`
`h4 = f(h3)`

It is important to understand that as an intermediate step, this routine calculates the spherical harmonic coefficients of the density multiplied by the relief raised to the nth power. As such, if the input function is bandlimited to degree `L`, the resulting function will thus be bandlimited to degree `L*nmax`. This subroutine implicitly assumes that `lmax` is greater than or equal to `L*nmax`. If this is not the case, then aliasing will occur. In practice, for accurate results, it is found that `lmax` needs only to be about twice the size of `L`, though this should be verified for each application. Thus, if the input function is considered to be bandlimited to degree `L`, the function should be evaluated on a grid corresponding to a maximum degree of about `2L`.

If the input grid is evaluated on the Gauss-Legendre points, it is necessary to specify the optional parameters `w` and` zero`, or `w` and `plx`, which are calculated by a call to `SHGLQ`. If memory is not an issue, the algorithm can be speeded up by inputing the optional array `plx` of precomputed associated Legendre functions on the Gauss-Legendre nodes. If `plx` is not specified, then it is necessary to input the optional array `zero` that contains the latitudinal Gauss-Legendre quadrature nodes.

This routine uses geodesy 4-pi normalized spherical harmonics that exclude the Condon-Shortley phase; This can not be modified.

# References

Wieczorek, M. A. and R. J. Phillips, Potential anomalies on a sphere: applications to the thickness of the lunar crust, J. Geophys. Res., 103, 1715-1724, 1998.

# See also

[batohilm](batohilm.html), [cilmplus](cilmplus.html), [cilmplusrhoh](cilmplusrhoh.html), [shexpandglq](shexpandglq.html), [makegridglq](makegridglq.html), [shglq](shglq.html), [shexpanddh](shexpanddh.html), [makegriddh](makegriddh.html), [glqgridcoord](glqgridcoord.html), [downcontfilterma](downcontfilterma.html), [downcontfiltermc](downcontfiltermc.html)

redpajama_set_name: RedPajamaGithub


text:
module Sirportly
  class Brand < DataObject
    self.collection_path = 'objects/brands'
    self.maps = {'departments' => "Department"}
  end
end


text:
package com.microsoft.bingads.v12.campaignmanagement;

import java.util.Collection;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="MediaEnabledEntities" type="{https://bingads.microsoft.com/CampaignManagement/v12}MediaEnabledEntityFilter" minOccurs="0"/>
 *         <element name="PageInfo" type="{https://bingads.microsoft.com/CampaignManagement/v12}Paging" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "mediaEnabledEntities",
    "pageInfo"
})
@XmlRootElement(name = "GetMediaMetaDataByAccountIdRequest")
public class GetMediaMetaDataByAccountIdRequest {

    @XmlElement(name = "MediaEnabledEntities", type = String.class)
    @XmlJavaTypeAdapter(Adapter9 .class)
    protected Collection<MediaEnabledEntityFilter> mediaEnabledEntities;
    @XmlElement(name = "PageInfo", nillable = true)
    protected Paging pageInfo;

    /**
     * Gets the value of the mediaEnabledEntities property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public Collection<MediaEnabledEntityFilter> getMediaEnabledEntities() {
        return mediaEnabledEntities;
    }

    /**
     * Sets the value of the mediaEnabledEntities property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setMediaEnabledEntities(Collection<MediaEnabledEntityFilter> value) {
        this.mediaEnabledEntities = value;
    }

    /**
     * Gets the value of the pageInfo property.
     *
     * @return
     *     possible object is
     *     {@link Paging }
     *
     */
    public Paging getPageInfo() {
        return pageInfo;
    }

    /**
     * Sets the value of the pageInfo property.
     *
     * @param value
     *     allowed object is
     *     {@link Paging }
     *
     */
    public void setPageInfo(Paging value) {
        this.pageInfo = value;
    }

}


text:
package com.hauldata.dbpa.task;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;

import com.hauldata.dbpa.expression.Expression;
import com.hauldata.dbpa.process.Context;

public class CopyTask extends RenameOrCopyTask {

	public CopyTask(
			Prologue prologue,
			List<Expression<String>> from,
			Expression<String> to) {

		super(prologue);
		this.from = from;
		this.to = to;
	}

	@Override
	protected void execute(Context context) {

		Path toPath = context.getWritePath(to.evaluate());
		boolean toDirectory = Files.isDirectory(toPath);

		if ((from.size() > 1) && !toDirectory) {
			throw new RuntimeException("Cannot copy multiple source files to the same target file; target must be an existing directory");
		}

		DirectoryStream<Path> sourcePaths = null;
		try {
			for (Expression<String> source : from) {

				String sourceName = source.evaluate();
				String[] parentAndFileName = com.hauldata.dbpa.process.Files.getParentAndFileName(sourceName);
				Path parentPath = context.getWritePath(parentAndFileName[0]);

				try {
					sourcePaths = Files.newDirectoryStream(parentPath, parentAndFileName[1]);
				}
				catch (Exception ex) {
					String message = (ex.getMessage() != null) ? ex.getMessage() : ex.getClass().getName();
					throw new RuntimeException("Error occurred resolving FROM file " + sourceName + " - " + message, ex);
				}

				for (Path sourcePath : sourcePaths) {
					if (Files.isRegularFile(sourcePath)) {
						Path targetPath = toDirectory ? toPath.resolve(sourcePath.getFileName()) : toPath;
						doAction(context, sourcePath, targetPath);
					}
				}

				sourcePaths.close();
				sourcePaths = null;
			}
		}
		catch (IOException ex) {
			String message = (ex.getMessage() != null) ? ex.getMessage() : ex.getClass().getName();
			throw new RuntimeException("Error occurred copying file: " + message, ex);
		}
		finally { try {
			if (sourcePaths != null) sourcePaths.close();
		}
		catch (IOException ex) {
			throw new RuntimeException("Error occurred closing directory stream");
		} }
	}

	@Override
	protected String verb() {
		return "copy";
	}

	@Override
	protected void action(Path from, Path to) throws IOException {
		Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
	}

	private List<Expression<String>> from;
	private Expression<String> to;
}


text:
export default class Hungry {

    constructor() {
        this.shorttermGoals = [];
        this.name = 'hungry';
    }

    getShorttermGoals() {
        return this.shorttermGoals;
    }

    start(speech) {
        speech.addMessage('Dan moet je eten');
        speech.send();
    }

    complete() {
    }

}


text:
import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';

import { Dialog, OpenUrlModalController } from 'ext-ionic';

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(private openUrlCtrl: OpenUrlModalController, private navCtrl: NavController, private dialog: Dialog) {
    this.dialog.alert('test', 'ok');
  }

  openExternalUrl() {
    this.openUrlCtrl.open({
      title: '百度',
      url: 'http://www.baidu.com'
    });
  }

  alphaList() {
    this.navCtrl.push('AlphaScrollPage');
  }

  baiduMap() {
    this.navCtrl.push('BaiduMapPage');
  }

  filterBar() {
    this.navCtrl.push('FilterBarPage');
  }

  imageLoader() {
    this.navCtrl.push('ImageLoaderPage');
  }

  inputs() {
    this.navCtrl.push('InputsPage');
  }

  notifiy() {
    this.navCtrl.push('NotificationProgressPage');
  }

  jsonStorage() {
    this.navCtrl.push('JsonStoragePage');
  }

  ribbon() {
    this.navCtrl.push('RibbonPage');
  }

  downloadManager() {
    this.navCtrl.push('DownloadManagerPage');
  }

  slideTabs() {
    this.navCtrl.push('SlideTabsPage');
  }

  gallery() {
    this.navCtrl.push('GalleryPage');
  }

  navButton() {
    this.navCtrl.push('NavButtonPage');
  }

  signaturePad() {
    this.navCtrl.push('SignatureViewPage');
  }

  uploadFile() {
    this.navCtrl.push('FileButtonPage');
  }

  runMap() {
    this.navCtrl.push('RunMapPage');
  }
}


text:
/**
 * AuroraClusterConfigのためのパッケージ。
 */
package net.gree.aurora.application.config.clusterconfig;


text:
#ifndef __mrquincy_crypto_h_
#define __mrquincy_crypto_h_

extern "C" {
#include <openssl/sha.h>
}

class HashSHA1 {
    SHA_CTX	_ctx;
    int		_size;
    bool	_done;
    char	_hash[20];

    void _init(void);
    void _digest(void);

public:
    HashSHA1(const char *file);
    HashSHA1(void);

    void update(const char *, int);
    void digest(char *, int);
    void digest64(char *, int);
    int size(void) const {return _size; }

};

#endif // __mrquincy_crypto_h_


text:
.. provenance/index.rst

Provenance
##########

.. include:: overview.rst

.. toctree::
   :maxdepth: 1

.. other.rst


text:
import random
import string
import sys
import threading
import weakref

class Local:
    """
    A drop-in replacement for threading.locals that also works with asyncio
    Tasks (via the current_task asyncio method), and passes locals through
    sync_to_async and async_to_sync.

    Specifically:
     - Locals work per-coroutine on any thread not spawned using asgiref
     - Locals work per-thread on any thread not spawned using asgiref
     - Locals are shared with the parent coroutine when using sync_to_async
     - Locals are shared with the parent thread when using async_to_sync
       (and if that thread was launched using sync_to_async, with its parent
       coroutine as well, with this working for indefinite levels of nesting)

    Set thread_critical to True to not allow locals to pass from an async Task
    to a thread it spawns. This is needed for code that truly needs
    thread-safety, as opposed to things used for helpful context (e.g. sqlite
    does not like being called from a different thread to the one it is from).
    Thread-critical code will still be differentiated per-Task within a thread
    as it is expected it does not like concurrent access.

    This doesn't use contextvars as it needs to support 3.6. Once it can support
    3.7 only, we can then reimplement the storage more nicely.
    """

    CLEANUP_INTERVAL = 60  # seconds

    def __init__(self, thread_critical=False):
        self._thread_critical = thread_critical
        self._thread_lock = threading.RLock()
        self._context_refs = []
        # Random suffixes stop accidental reuse between different Locals,
        # though we try to force deletion as well.
        self._attr_name = "_asgiref_local_impl_%s_%s" % (
            id(self),
            "".join(random.choice(string.ascii_letters) for i in range(8)),
        )

    def _get_context_id(self):
        """
        Get the ID we should use for looking up variables
        """
        # Prevent a circular reference
        from .sync import AsyncToSync, SyncToAsync

        # First, pull the current task if we can
        context_id = SyncToAsync.get_current_task()
        context_is_async = True
        # OK, let's try for a thread ID
        if context_id is None:
            context_id = threading.current_thread()
            context_is_async = False
        # If we're thread-critical, we stop here, as we can't share contexts.
        if self._thread_critical:
            return context_id
        # Now, take those and see if we can resolve them through the launch maps
        for i in range(sys.getrecursionlimit()):
            try:
                if context_is_async:
                    # Tasks have a source thread in AsyncToSync
                    context_id = AsyncToSync.launch_map[context_id]
                    context_is_async = False
                else:
                    # Threads have a source task in SyncToAsync
                    context_id = SyncToAsync.launch_map[context_id]
                    context_is_async = True
            except KeyError:
                break
        else:
            # Catch infinite loops (they happen if you are screwing around
            # with AsyncToSync implementations)
            raise RuntimeError("Infinite launch_map loops")
        return context_id

    def _get_storage(self):
        context_obj = self._get_context_id()
        if not hasattr(context_obj, self._attr_name):
            setattr(context_obj, self._attr_name, {})
            self._context_refs.append(weakref.ref(context_obj))
        return getattr(context_obj, self._attr_name)

    def __del__(self):
        for ref in self._context_refs:
            context_obj = ref()
            if context_obj:
                try:
                    delattr(context_obj, self._attr_name)
                except AttributeError:
                    pass

    def __getattr__(self, key):
        with self._thread_lock:
            storage = self._get_storage()
            if key in storage:
                return storage[key]
            else:
                raise AttributeError("%r object has no attribute %r" % (self, key))

    def __setattr__(self, key, value):
        if key in ("_context_refs", "_thread_critical", "_thread_lock", "_attr_name"):
            return super().__setattr__(key, value)
        with self._thread_lock:
            storage = self._get_storage()
            storage[key] = value

    def __delattr__(self, key):
        with self._thread_lock:
            storage = self._get_storage()
            if key in storage:
                del storage[key]
            else:
                raise AttributeError("%r object has no attribute %r" % (self, key))


text:
<bill session="110" type="h" number="2409" updated="2009-01-08T21:52:31-05:00">
	<status><introduced date="1179720000" datetime="2007-05-21"/></status>

	<introduced date="1179720000" datetime="2007-05-21"/>
	<titles>
		<title type="short" as="introduced">Child Care Public-Private Partnership Act of 2007</title>
		<title type="official" as="introduced">To establish a program to provide child care through public-private partnerships.</title>
	</titles>
	<sponsor id="400246"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1179720000" datetime="2007-05-21"><text>Referred to the House Committee on Education and Labor.</text></action>
		<action date="1184644800" datetime="2007-07-17"><text>Referred to the Subcommittee on Early Childhood, Elementary, and Secondary Education.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	5/21/2007--Introduced.<br/>Child Care Public-Private Partnership Act of 2007 - Directs the Secretary of Health and Human Services to establish a business-incentive grant program to provide child care through public-private partnerships. Provides program grants to cover up to one-third of the costs for: (1) businesses or consortia to start up, or provide additional, employee child care services; and (2) nonprofit business organizations to provide technical information and assistance to enable businesses to provide such services. Requires such services to: (1) be provided equitably and affordably to low- and moderate-income employees; and (2) comply with state and local licensing requirements. Gives priority in grant selection to businesses with fewer than 100 full-time employees.
	</summary>
</bill>


text:
class GoalError(Exception):
    """Raised to indicate a goal has failed."""


text:
[![Build Status](https://travis-ci.org/dongy7/Polyline.svg?branch=master)](https://travis-ci.org/dongy7/Polyline)
[![npm version](https://badge.fury.io/js/polyline-coordinates.svg)](https://badge.fury.io/js/polyline-coordinates)
[![codecov](https://codecov.io/gh/dongy7/Polyline/branch/master/graph/badge.svg)](https://codecov.io/gh/dongy7/Polyline)

Simple utility library for dealing with JSON polylines

## Installation

To use with a module bundler like [webpack](https://webpack.js.org/):
```
npm install --save polyline-coordinates
```

## Usage
```js
const Polyline = require('polyline-coordinates');

// the polyline needs to be an array of [latitude, longitude] values
const polyline = Polyline.createLine([[34.028337, -118.259954], [37.773566, -122.412786]])

polyline.getLengthInMiles()
// 347.618 miles

polyline.getLengthInKm()
// 559.43555212 km

polyline.getPointCovering(0.5);
// [35.91355, 120.33155]
```

## API

#### Polyline.createLine(geojson)
Creates a new polyline instance with the json representation of a polyline.

#### Polyline.getDistanceBetweenPoints(start, end)
Returns the distance in miles between two coordinates.

#### Polyline.getDistanceBetweenPointsKm(start, end)
Returns the distance in kilometers between two coordinates.

#### .getLengthInMiles()
Returns the total distance covered by the polyline in miles.

#### .getLengthInKm()
Returns the total distance covered by the polyline in kilometers.

#### .getPointCovering(percent)
Returns the coordinate of the point that covers the percentage of the
polyline specified.

For example `.getPointCovering(0.5)` will return the coordinates of the point
that is located in the middle of the polyline.


text:
<?php namespace Slugnizzer\Slugnizzer;

use Illuminate\Support\ServiceProvider;

class SlugnizzerServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool $defer
     */
    protected $defer = false;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('slugnizzer', function($app)
        {
            return new \Slugnizzer\Slugnizzer();
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }
}


text:
package connectfour.domain.johannes;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;

import sun.nio.cs.ext.ISCII91;

import connectfour.gui.johannes.GameFrame;

public class Server implements Runnable
{
//	private HashMap<String, String> protocol = new HashMap<String, String>();

	public static InetAddress sendIP;
	private static int receivePort;

	private static boolean ingame = false;

	public Server(int receive)
	{
//		protocol.put("NEW GAME", "ACK NEW GAME");
//		protocol.put("END GAME", "ACK END GAME");
//		protocol.put("NEW GAME", "ACK NEW GAME");
		Server.receivePort = receive;
		this.run();
	}

	public static String getLocIp()
	{
		String ip = "";
		try
		{
			ip = InetAddress.getLocalHost().getHostAddress().toString();
		} catch (UnknownHostException e)
		{
			System.out.println("Could not receive local ip");
			e.printStackTrace();
		}
		return ip;
	}

	@Override
	public void run()
	{
		DatagramSocket socketListen = null;
		try
		{
			socketListen = new DatagramSocket(receivePort);

			byte[] buf = new byte[1024];
			byte[] data;
			DatagramPacket packet = new DatagramPacket(buf, buf.length);
			System.out
					.println("Server socket created. Waiting for incoming data...");
			while (true)
			{
				socketListen.receive(packet);
				data = packet.getData();
				String request = new String(data, 0, packet.getLength());
				System.out.println("Server got msg: "
						+ packet.getAddress().getHostAddress() + " : "
						+ packet.getPort() + " - " + request);
				request = handleMsg(request);
				DatagramPacket dp = new DatagramPacket(request.getBytes(),
						request.getBytes().length, packet.getAddress(),
						packet.getPort());
				socketListen.send(dp);
				if(request.equals("ACK END GAME")) System.exit(0);
			}

		} catch (SocketException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	private String handleMsg(String req)
	{
		if (req.equals("NEW GAME") && !ingame)
		{
			ingame = true;
			GameFrame.Instance();
			return "ACK GAME";
		}
		if (req.startsWith("PLACE", 4))
		{
			System.out.println("he want's to place");
			return "you can place";
		}
		if (req.equals("END GAME") && ingame)
		{
			return "ACK END GAME";
		} else
			return "";

	}

}


text:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import Jumbotron from "../../components/Jumbotron";
import { Col, Row, Container } from "../../components/Grid";
import { FormBtn } from "../../components/Form";

class Landing extends Component {
  state = {};

  componentDidMount() {
    console.log("Landing page mounted.");
  }

  handleInputChange = event => {
    const { name, value } = event.target;
    this.setState({
      [name]: value
    });
  };

  handleFormSubmit = event => {
    event.preventDefault();
    console.log("The form button was pressed.");
  };

  render() {
    return (
      <Container fluid>
        <Row>
          <Col size="sm-12">
            <Jumbotron>

You're not authorized to be here!

            </Jumbotron>
            <form>
              <FormBtn onClick={this.handleFormSubmit}>
                Submit Button
              </FormBtn>
            </form>
            <Link to={"/Food/"}>
              Return to Food page
            </Link>
          </Col>
        </Row>
      </Container>
    );
  }
}

export default Landing;


text:
import smtplib

class ConcreteMailSender:

    def __init__(self, host, port):
        self.mailer = smtplib.SMTP(host, port=port)

    def send(self, sender, recipient, message):
        self.mailer.sendmail(sender, recipient, message)
        self.mailer.quit()


text:
layout: post
title: Octopus - Automatic Deployment on Release Creation
tags: [studying]
---

It is possible to deploy new version of application to a specific environment on its new release creation.
This straightforward method makes testing / deployment easier as the environment usually is for dev / dev integration.

## Setup a Lifecycle

Instead of modifying the default lifecycle, it's better to create a custom one for your app(s).

In Lifecycle edition form, it allows to define Phases with choise `Deploy automatically...`.

![_config.yml]({{ site.baseurl }}/images/posts/octopus/phase-auto-deploy.png)

![_config.yml]({{ site.baseurl }}/images/posts/octopus/xbanking.png)

## Change Project's Lifecycle

Go to the Project / Process tab and check the current lifecycle applying to it

![_config.yml]({{ site.baseurl }}/images/posts/octopus/project-lifecycle.png)

Select the Lifecycle `XBanking` which has been setup at previous step. It's all we need to do on configuration steps.
When a new package is arriving, it will do different steps to:

- Create a new release

- Deploy the release to environments configured for automatically deploy.

Below command can be used to build and push the package to Octopus.

```
msbuild Demo.XBanking.sln 	/t:Build
							/p:RunOctoPack=true
							/p:OctoPackPublishPackageToHttp=http://<your_server>:180/nuget/packages
							/p:OctoPackPublishApiKey=API-XYZ
```

References

1. [Lifecycles][1]

[1]: http://docs.octopusdeploy.com/display/OD/Lifecycles


text:
<?php

namespace Symfony\Bridge\ProxyManager\Tests\LazyProxy\Instantiator;

use PHPUnit\Framework\TestCase;
use ProxyManager\Proxy\LazyLoadingInterface;
use ProxyManager\Proxy\ValueHolderInterface;
use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;

/**
 * Tests for {@see \Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator}.
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 */
class RuntimeInstantiatorTest extends TestCase
{
    /**
     * @var RuntimeInstantiator
     */
    protected $instantiator;

    protected function setUp(): void
    {
        $this->instantiator = new RuntimeInstantiator();
    }

    public function testInstantiateProxy()
    {
        $instance = new \stdClass();
        $container = $this->createMock(ContainerInterface::class);
        $definition = new Definition('stdClass');
        $instantiator = function () use ($instance) {
            return $instance;
        };

        /* @var $proxy LazyLoadingInterface|ValueHolderInterface */
        $proxy = $this->instantiator->instantiateProxy($container, $definition, 'foo', $instantiator);

        $this->assertInstanceOf(LazyLoadingInterface::class, $proxy);
        $this->assertInstanceOf(ValueHolderInterface::class, $proxy);
        $this->assertFalse($proxy->isProxyInitialized());

        $proxy->initializeProxy();

        $this->assertSame($instance, $proxy->getWrappedValueHolderValue());
    }
}


text:
package org.wso2.carbon.utils.component.xml.config;

public class ManagementPermission implements ComponentConfig {

    private String displayName;
    private String resourceId;

    public ManagementPermission(String displayName, String resourceId) {
        super();
        this.displayName = displayName;
        this.resourceId = resourceId;
    }

    public String getDisplayName() {
        return displayName;
    }

    public String getResourceId() {
        return resourceId;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public void setResourceId(String resourceId) {
        this.resourceId = resourceId;
    }

}


text:
using UnityEngine;
using System.Collections;

public class RPGTest_StatModifiers : MonoBehaviour {
    private RPGStatModifiable stat;

	void Start () {
        bool passed = true;
        stat = new RPGStatModifiable();

        // Set the Starting base value
        int statTargetValue = 100;
        stat.StatBaseValue = statTargetValue;

        // Create instance of the modifiers with all values set to 0
        RPGStatModifier[] mods = new RPGStatModifier[] {
            new RPGStatModBaseAdd(0),
            new RPGStatModBasePercent(0),
            new RPGStatModTotalAdd(0),
            new RPGStatModTotalPercent(0)
        };

        // Add lisener event to each modifier and add mod to stat
        foreach (var mod in mods) {
            //Debug.Log("Stat Listening to Mod: " + mod.GetType().ToString());
            mod.OnValueChange += OnValueChange;
            stat.AddModifier(mod);
        }

        // Change the Base Add Mod Value
        int baseAddValue = 100;
        statTargetValue += baseAddValue;
        mods[0].Value = baseAddValue;

        // Check if the target value is the same as the stat's value
        passed = passed && stat.StatValue == statTargetValue;
        Debug.Log(string.Format("Check[{0}]: Stat Value {1}, Target Value {2}", passed, stat.StatValue, statTargetValue));

        // Change the Base Percent Mod Value
        float basePercentValue = 0.5f;
        statTargetValue += (int)(statTargetValue * basePercentValue);
        mods[1].Value = basePercentValue;

        // Check if the target value is the same as the stat's value
        passed = passed && stat.StatValue == statTargetValue;
        Debug.Log(string.Format("Check[{0}]: Stat Value {1}, Target Value {2}", passed, stat.StatValue, statTargetValue));

        // Change the Base Add Mod Value
        int totalAddValue = 100;
        statTargetValue += totalAddValue;
        mods[2].Value = totalAddValue;

        // Check if the target value is the same as the stat's value
        passed = passed && stat.StatValue == statTargetValue;
        Debug.Log(string.Format("Check[{0}]: Stat Value {1}, Target Value {2}", passed, stat.StatValue, statTargetValue));

        // Change the Base Percent Mod Value
        float totalPercentValue = 0.5f;
        statTargetValue += (int)(statTargetValue * totalPercentValue);
        mods[3].Value = totalPercentValue;

        // Check if the target value is the same as the stat's value
        passed = passed && stat.StatValue == statTargetValue;
        Debug.Log(string.Format("Check[{0}]: Stat Value {1}, Target Value {2}", passed, stat.StatValue, statTargetValue));

        Debug.Log(string.Format("Stat Modifier Test: {0}", passed ? "Passed" : "Failed"));
	}

    private void OnValueChange(object mod, System.EventArgs args) {
        //Debug.Log("On Value Changed Called For Modifier: " + mod.GetType().ToString());
        stat.UpdateModifiers();
    }
}


text:
package com.ibm.bi.dml.api.jmlc;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import com.ibm.bi.dml.api.DMLException;
import com.ibm.bi.dml.api.DMLScript;
import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM;
import com.ibm.bi.dml.conf.ConfigurationManager;
import com.ibm.bi.dml.conf.DMLConfig;
import com.ibm.bi.dml.hops.OptimizerUtils;
import com.ibm.bi.dml.hops.rewrite.ProgramRewriter;
import com.ibm.bi.dml.hops.rewrite.RewriteRemovePersistentReadWrite;
import com.ibm.bi.dml.parser.AParserWrapper;
import com.ibm.bi.dml.parser.DMLProgram;
import com.ibm.bi.dml.parser.DMLTranslator;
import com.ibm.bi.dml.parser.DataExpression;
import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.controlprogram.Program;
import com.ibm.bi.dml.runtime.controlprogram.caching.CacheableData;
import com.ibm.bi.dml.runtime.io.MatrixReaderFactory;
import com.ibm.bi.dml.runtime.io.ReaderTextCell;
import com.ibm.bi.dml.runtime.matrix.data.InputInfo;
import com.ibm.bi.dml.runtime.matrix.data.MatrixBlock;
import com.ibm.bi.dml.runtime.util.DataConverter;

/**
 * JMLC (Java Machine Learning Connector) API:
 *
 * NOTES:
 *   * Currently fused API and implementation in order to reduce complexity.
 *   * See SystemTMulticlassSVMScoreTest for an usage example.
 */
public class Connection
{

	private DMLConfig _conf = null;

	/**
	 * Connection constructor, starting point for any other JMLC API calls.
	 *
	 */
	public Connection()
	{
		//setup basic parameters for embedded execution
		DataExpression.REJECT_READ_UNKNOWN_SIZE = false;
		DMLScript.rtplatform = RUNTIME_PLATFORM.SINGLE_NODE;
		OptimizerUtils.PARALLEL_CP_READ_TEXTFORMATS = false;
		OptimizerUtils.PARALLEL_CP_WRITE_TEXTFORMATS = false;
		OptimizerUtils.PARALLEL_CP_READ_BINARYFORMATS = false;
		OptimizerUtils.PARALLEL_CP_WRITE_BINARYFORMATS = false;
		CacheableData.disableCaching();

		//create default configuration
		_conf = new DMLConfig();
		ConfigurationManager.setConfig(_conf);
	}

	/**
	 *
	 * @param script
	 * @param inputs
	 * @param outputs
	 * @return
	 * @throws DMLException
	 */
	public PreparedScript prepareScript( String script, String[] inputs, String[] outputs, boolean parsePyDML)
		throws DMLException
	{
		return prepareScript(script, new HashMap<String,String>(), inputs, outputs, parsePyDML);
	}

	/**
	 *
	 * @param script
	 * @param args
	 * @param inputs
	 * @param outputs
	 * @return
	 * @throws DMLException
	 */
	public PreparedScript prepareScript( String script, HashMap<String, String> args, String[] inputs, String[] outputs, boolean parsePyDML)
		throws DMLException
	{
		//prepare arguments

		//simplified compilation chain
		Program rtprog = null;
		try
		{
			//parsing
			AParserWrapper parser = AParserWrapper.createParser(parsePyDML);
			DMLProgram prog = parser.parse(null, script, args);

			//language validate
			DMLTranslator dmlt = new DMLTranslator(prog);
			dmlt.liveVariableAnalysis(prog);
			dmlt.validateParseTree(prog);

			//hop construct/rewrite
			dmlt.constructHops(prog);
			dmlt.rewriteHopsDAG(prog);

			//rewrite persistent reads/writes
			RewriteRemovePersistentReadWrite rewrite = new RewriteRemovePersistentReadWrite(inputs, outputs);
			ProgramRewriter rewriter2 = new ProgramRewriter(rewrite);
			rewriter2.rewriteProgramHopDAGs(prog);

			//lop construct and runtime prog generation
			dmlt.constructLops(prog);
			rtprog = prog.getRuntimeProgram(_conf);

			//final cleanup runtime prog
			JMLCUtils.cleanupRuntimeProgram(rtprog, outputs);

			//System.out.println(Explain.explain(rtprog));
		}
		catch(Exception ex)
		{
			throw new DMLException(ex);
		}

		//return newly create precompiled script
		return new PreparedScript(rtprog, inputs, outputs);
	}

	/**
	 *
	 */
	public void close()
	{

	}

	/**
	 *
	 * @param fname
	 * @return
	 * @throws IOException
	 */
	public String readScript(String fname)
		throws IOException
	{
		StringBuilder sb = new StringBuilder();
		BufferedReader in = null;
		try
		{
			//read from hdfs or gpfs file system
			if(    fname.startsWith("hdfs:")
				|| fname.startsWith("gpfs:") )
			{
				FileSystem fs = FileSystem.get(ConfigurationManager.getCachedJobConf());
				Path scriptPath = new Path(fname);
				in = new BufferedReader(new InputStreamReader(fs.open(scriptPath)));
			}
			// from local file system
			else
			{
				in = new BufferedReader(new FileReader(fname));
			}

			//core script reading
			String tmp = null;
			while ((tmp = in.readLine()) != null)
			{
				sb.append( tmp );
				sb.append( "\n" );
			}
		}
		catch (IOException ex)
		{
			throw ex;
		}
		finally
		{
			if( in != null )
			 	in.close();
		}

		return sb.toString();
	}

	/**
	 * Converts an input string representation of a matrix in textcell format
	 * into a dense double array. The number of rows and columns need to be
	 * specified because textcell only represents non-zero values and hence
	 * does not define the dimensions in the general case.
	 *
	 * @param input  a string representation of an input matrix,
	 *              in format textcell (rowindex colindex value)
	 * @param rows number of rows
	 * @param cols number of columns
	 * @return
	 * @throws IOException
	 */
	public double[][] convertToDoubleMatrix(String input, int rows, int cols)
		throws IOException
	{
		double[][] ret = null;

		try
		{
			//read input matrix
			InputStream is = new ByteArrayInputStream(input.getBytes("UTF-8"));
			ReaderTextCell reader = (ReaderTextCell)MatrixReaderFactory.createMatrixReader(InputInfo.TextCellInputInfo);
			MatrixBlock mb = reader.readMatrixFromInputStream(is, rows, cols, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize, (long)rows*cols);

			//convert to double array
			ret = DataConverter.convertToDoubleMatrix( mb );
		}
		catch(DMLRuntimeException rex)
		{
			throw new IOException( rex );
		}

		return ret;
	}

}


text:
'use strict'

const logger = require('./logger.js')

// Patch ctx.render method to output logger
module.exports = (ctx, next) => {
  let render = ctx.render

  ctx.render = async function () {
    let t = Date.now()
    await render.apply(ctx, arguments)
    logger.info('Render view', arguments[0], `(${Date.now() - t}ms)`.green)
  }

  return next()
}


text:
// This code was generated by net.maritimecloud.common.cqrs.contract.SourceGenerator
// Generated Code is based on the contract defined in net.maritimecloud.serviceregistry.command.ServiceRegistryContract
// Please modify the contract instead of this file!
package net.maritimecloud.serviceregistry.command.api;

import org.axonframework.commandhandling.annotation.TargetAggregateIdentifier;
import net.maritimecloud.common.cqrs.contract.Event;
import net.maritimecloud.serviceregistry.command.serviceinstance.ServiceInstanceId;
import net.maritimecloud.serviceregistry.command.serviceinstance.ServiceEndpoint;

/**
 * GENERATED CLASS!
 * @see net.maritimecloud.serviceregistry.command.ServiceRegistryContract#serviceInstanceEndpointRemoved
 */
@Event
public class ServiceInstanceEndpointRemoved {

    @TargetAggregateIdentifier
    private final ServiceInstanceId serviceInstanceId;
    private final ServiceEndpoint serviceEndpoint;

    public ServiceInstanceEndpointRemoved(
            ServiceInstanceId serviceInstanceId,
            ServiceEndpoint serviceEndpoint
    ) {
        this.serviceInstanceId = serviceInstanceId;
        this.serviceEndpoint = serviceEndpoint;
    }

    public ServiceInstanceId getServiceInstanceId() {
        return serviceInstanceId;
    }

    public ServiceEndpoint getServiceEndpoint() {
        return serviceEndpoint;
    }

}


text:
using System;

namespace RandomSkunk.ProducerConsumer
{
    /// <summary>
    /// Contains the various configurable settings for the library.
    /// </summary>
    /// <typeparam name="T">
    /// The type of item to be produced and consumed by this instance of <see cref="Configuration{T}"/>.
    /// </typeparam>
    public class Configuration<T> : IConfiguration<T>
    {
        /// <summary>
        /// The <see cref="Action{T}"/> that will be executed by the consumer thread.
        /// </summary>
        private readonly Action<T> _consumerAction;

        /// <summary>
        /// The <see cref="Action{Exception}"/> that is executed if the consumer action throws an exception.
        /// </summary>
        private Action<Exception> _errorHandler = NoOp;

        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration{T}"/> class.
        /// </summary>
        /// <param name="consumerAction">The <see cref="Action{T}"/> that will be executed by the consumer thread.</param>
        public Configuration(Action<T> consumerAction)
        {
            if (consumerAction == null)
            {
                throw new ArgumentNullException("consumerAction");
            }

            _consumerAction = consumerAction;

            EnqueueWhenStopped = true;
            ClearQueueUponStop = false;
            StartImmediately = true;
        }

        /// <summary>
        /// Gets the <see cref="Action{T}"/> that will be executed by the consumer thread.
        /// </summary>
        public Action<T> ConsumerAction
        {
            get { return _consumerAction; }
        }

        /// <summary>
        /// Gets or sets the <see cref="Action{Exception}"/> that will be executed if the consumer action throws an exception. If not set or set to null, the exception will be caught and ignored.
        /// </summary>
        public Action<Exception> ErrorHandler
        {
            get
            {
                return _errorHandler;
            }
            set
            {
                _errorHandler = value ?? NoOp;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to start the consumer thread immediately.
        /// </summary>
        public bool StartImmediately { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether <see cref="ProducerConsumer{T}.Enqueue"/> should add data items when <see cref="ProducerConsumer{T}.IsRunning"/> is false.
        /// </summary>
        public bool EnqueueWhenStopped { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether to call <see cref="ProducerConsumer{T}.Clear"/> when <see cref="ProducerConsumer{T}.IsRunning"/> is set to false.
        /// </summary>
        public bool ClearQueueUponStop { get; set; }

        /// <summary>
        /// A no-op method. Used when setting <see cref="ErrorHandler"/> if the value passed to it is null.
        /// </summary>
        /// <param name="ex">An exception that will be ignored.</param>
        private static void NoOp(Exception ex)
        {
        }
    }
}


text:
	#undef NAZARA_NOISE_MANAGE_MEMORY
	#define NAZARA_NOISE_MANAGE_MEMORY 0
#endif

#endif // NAZARA_CONFIG_CHECK_NOISE_HPP


text:
package com.duan.musicoco.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Created by DuanJiaNing on 2017/6/9.
 */

public class StringUtils {

    public static String stringToMd5(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static String getGenTimeMS(int misec) {
        int min = misec / 1000 / 60;
        int sec = (misec / 1000) % 60;
        String minStr = min < 10 ? "0" + min : min + "";
        String secStr = sec < 10 ? "0" + sec : sec + "";
        return minStr + ":" + secStr;
    }

    public static String getGenDateYMDHMS(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date(time));
    }

    public static String getGenDateYMD(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(time));
    }

    public static boolean isReal(String string) {
        return string != null && string.length() > 0 && !"null".equals(string);
    }

}


text:
cd emu-dir;
./train-emulator.sh


text:
#import <AirPortAssistant/AutoGuessController.h>

@interface AutoGuessController (ViewControllerPrivate)
- (id)createCompletionDictFromAutoGuessResults:(id)arg1;
@end


text:
from ohno.dungeon.level import Level
from ohno.event.founditems import FoundItems
from ohno.event.message import MessageEvent

class Dungeon(object):
    def __init__(self, ohno):
        self.ohno = ohno
        self.levels = {}
        self.curlevel = None
        self.curtile = None

    def update(self):
        """
        1. Check if we're on a new level, and make on if we are.
        2. Set self.curlevel and self.curtile
        3. Update the current level.
        """
        # TODO: Branches. We need to know which branch we are in and which
        #       levels are in which branch.
        #       This should probably be done inside this function, while
        #       the detection code should be in Level.
        dlvl = self.ohno.hero.dlvl
        if dlvl not in self.levels:
            self.ohno.logger.dungeon('Found dlvl %d!' % dlvl)
            self.levels[dlvl] = Level(self.ohno, dlvl)

        newlevel = self.levels[dlvl]
        if self.curlevel != newlevel:
            self.ohno.logger.dungeon(
                'We have moved from level %s to level %s' % (
                    self.curlevel,
                    newlevel
                )
            )
            if self.curlevel:
                MessageEvent.unsubscribe(self.curlevel.on_message)
                FoundItems.unsubscribe(self.curlevel.on_founditems)
            MessageEvent.subscribe(newlevel.on_message)
            FoundItems.subscribe(newlevel.on_founditems)

        self.curlevel = newlevel

        idx = self.ohno.hero.position.idx()
        self.curtile = self.curlevel.tiles[idx]

        self.ohno.logger.dungeon(
            'curtile before updating level: %r' % self.curtile
        )
        self.curlevel.update()
        self.ohno.logger.dungeon(
            'curtile after updating level: %r' % self.curtile
        )

        # Some sanity checks
        assert self.curtile.idx == idx
        assert self.curtile.appearance == self.ohno.hero.appearance
        assert self.curtile.monster is None


text:
using AutoMapper;
using Byte.Blog.Content;
using Byte.Blog.Framework;
using Raven.Client;

namespace Byte.Blog.Editorial.Models
{
    public class PageEditModelToPageMapper
    {
        private readonly IDocumentSession session;
        private readonly SlugMaker slugMaker;

        public PageEditModelToPageMapper(
            IDocumentSession session,
            SlugMaker slugMaker)
        {
            this.session = session;
            this.slugMaker = slugMaker;
        }

        public Page Map(PageEditModel editModel)
        {
            var page = Mapper.Map<Page>(editModel);

            page.Slug = this.slugMaker.CreateSlug(page.Title);

            return page;
        }
    }
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {browserProxy} from '../browser_proxy/browser_proxy.js';
import {assert} from '../chrome_util.js';
import {Filenamer, IMAGE_PREFIX, VIDEO_PREFIX} from './filenamer.js';

/**
 * The prefix of thumbnail files.
 * @type {string}
 */
const THUMBNAIL_PREFIX = 'thumb-';

/**
 * Checks if the entry's name has the video prefix.
 * @param {!FileEntry} entry File entry.
 * @return {boolean} Has the video prefix or not.
 */
export function hasVideoPrefix(entry) {
  return entry.name.startsWith(VIDEO_PREFIX);
}

/**
 * Checks if the entry's name has the image prefix.
 * @param {!FileEntry} entry File entry.
 * @return {boolean} Has the image prefix or not.
 */
function hasImagePrefix(entry) {
  return entry.name.startsWith(IMAGE_PREFIX);
}

/**
 * Checks if the entry's name has the thumbnail prefix.
 * @param {!FileEntry} entry File entry.
 * @return {boolean} Has the thumbnail prefix or not.
 */
function hasThumbnailPrefix(entry) {
  return entry.name.startsWith(THUMBNAIL_PREFIX);
}

/**
 * Directory in the internal file system.
 * @type {?DirectoryEntry}
 */
let internalDir = null;

/**
 * Temporary directory in the internal file system.
 * @type {?DirectoryEntry}
 */
let internalTempDir = null;

/**
 * Directory in the external file system.
 * @type {?DirectoryEntry}
 */
let externalDir = null;

/**
 * Gets global external directory used by CCA.
 * @return {?DirectoryEntry}
 */
export function getExternalDirectory() {
  return externalDir;
}

/**
 * Initializes the directory in the internal file system.
 * @return {!Promise<!DirectoryEntry>} Promise for the directory result.
 */
function initInternalDir() {
  return new Promise((resolve, reject) => {
    webkitRequestFileSystem(
        window.PERSISTENT, 768 * 1024 * 1024 /* 768MB */,
        (fs) => resolve(fs.root), reject);
  });
}

/**
 * Initializes the temporary directory in the internal file system.
 * @return {!Promise<!DirectoryEntry>} Promise for the directory result.
 */
function initInternalTempDir() {
  return new Promise((resolve, reject) => {
    webkitRequestFileSystem(
        window.TEMPORARY, 768 * 1024 * 1024 /* 768MB */,
        (fs) => resolve(fs.root), reject);
  });
}

/**
 * Reads file entries from the directory.
 * @param {?DirectoryEntry} dir Directory entry to be read.
 * @return {!Promise<!Array<!Entry>>} Promise for the read file entries.
 */
function readDir(dir) {
  return !dir ? Promise.resolve([]) : new Promise((resolve, reject) => {
    const dirReader = dir.createReader();
    const entries = [];
    const readEntries = () => {
      dirReader.readEntries((inEntries) => {
        if (inEntries.length === 0) {
          resolve(entries);
          return;
        }
        entries.push(...inEntries);
        readEntries();
      }, reject);
    };
    readEntries();
  });
}

/**
 * Initializes the directory in the external file system.
 * @return {!Promise<?DirectoryEntry>} Promise for the directory result.
 */
async function initExternalDir() {
  const volumes = await browserProxy.getVolumeList();
  if (volumes === null) {
    return null;
  }

  const getFileSystemRoot = async (volume) => {
    const fs = await browserProxy.requestFileSystem(volume);
    return fs === null ? null : fs.root;
  };

  for (const volume of volumes) {
    if (!volume.volumeId.includes('downloads:MyFiles')) {
      continue;
    }
    const root = await getFileSystemRoot(volume);
    const entries = await readDir(root);
    const downloadsDir = entries.find(
        (entry) => entry.name === 'Downloads' && entry.isDirectory);
    return downloadsDir ? /** @type {!DirectoryEntry} */ (downloadsDir) : null;
  }
  return null;
}

/**
 * Regulates the picture name to the desired format if it's in legacy formats.
 * @param {!FileEntry} entry Picture entry whose name to be regulated.
 * @return {string} Name in the desired format.
 */
function regulatePictureName(entry) {
  if (hasVideoPrefix(entry) || hasImagePrefix(entry)) {
    const match = entry.name.match(/(\w{3}_\d{8}_\d{6})(?:_(\d+))?(\..+)?$/);
    if (match) {
      const idx = match[2] ? ' (' + match[2] + ')' : '';
      const ext = match[3] ? match[3].replace(/\.webm$/, '.mkv') : '';
      return match[1] + idx + ext;
    }
  } else {
    // Early pictures are in legacy file name format (crrev.com/c/310064).
    const match = entry.name.match(/(\d+).(?:\d+)/);
    if (match) {
      return (new Filenamer(parseInt(match[1], 10))).newImageName();
    }
  }
  return entry.name;
}

/**
 * Gets the thumbnail name of the given picture.
 * @param {!FileEntry} entry Picture's file entry.
 * @return {string} Thumbnail name.
 */
function getThumbnailName(entry) {
  const thumbnailName = THUMBNAIL_PREFIX + entry.name;
  return (thumbnailName.substr(0, thumbnailName.lastIndexOf('.')) ||
          thumbnailName) +
      '.jpg';
}

/**
 * Parses and filters the internal entries to thumbnail and picture entries.
 * @param {!Array<!FileEntry>} internalEntries Internal file entries.
 * @param {!Object<string, !FileEntry>} thumbnailEntriesByName Result thumbanil
 *     entries mapped by thumbnail names, initially empty.
 * @param {!Array<!FileEntry>=} pictureEntries Result picture entries, initially
 *     empty.
 */
function parseInternalEntries(
    internalEntries, thumbnailEntriesByName, pictureEntries) {
  let thumbnailEntries = [];
  if (pictureEntries) {
    for (let index = 0; index < internalEntries.length; index++) {
      if (hasThumbnailPrefix(internalEntries[index])) {
        thumbnailEntries.push(internalEntries[index]);
      } else {
        pictureEntries.push(internalEntries[index]);
      }
    }
  } else {
    thumbnailEntries = internalEntries.filter(hasThumbnailPrefix);
  }
  for (let index = 0; index < thumbnailEntries.length; index++) {
    const thumbnailEntry = thumbnailEntries[index];
    thumbnailEntriesByName[thumbnailEntry.name] = thumbnailEntry;
  }
}

/**
 * Migrates all picture-files from internal storage to external storage.
 * @return {!Promise} Promise for the operation.
 */
function migratePictures() {
  const migratePicture = (pictureEntry, thumbnailEntry) => {
    const name = regulatePictureName(pictureEntry);
    const targetDir = externalDir;
    assert(targetDir !== null);
    return getFile(targetDir, name, true).then((entry) => {
      return new Promise((resolve, reject) => {
        pictureEntry.copyTo(targetDir, entry.name, (result) => {
          if (result.name !== pictureEntry.name && thumbnailEntry) {
            // Thumbnails can be recreated later if failing to rename them here.
            thumbnailEntry.moveTo(internalDir, getThumbnailName(result));
          }
          pictureEntry.remove(() => {});
          resolve();
        }, reject);
      });
    });
  };

  return readDir(internalDir).then((internalEntries) => {
    const pictureEntries = [];
    const thumbnailEntriesByName = {};
    parseInternalEntries(
        internalEntries, thumbnailEntriesByName, pictureEntries);

    const migrated = [];
    for (let index = 0; index < pictureEntries.length; index++) {
      const entry = pictureEntries[index];
      const thumbnailName = getThumbnailName(entry);
      const thumbnailEntry = thumbnailEntriesByName[thumbnailName];
      migrated.push(migratePicture(entry, thumbnailEntry));
    }
    return Promise.all(migrated);
  });
}

/**
 * Initializes file systems, migrating pictures if needed. This function
 * should be called only once in the beginning of the app.
 * @param {function()} promptMigrate Callback to instantiate a promise that
       prompts users to migrate pictures if no acknowledgement yet.
 * @return {!Promise<boolean>} Promise for the external-fs result.
 */
export function initialize(promptMigrate) {
  const checkAcked = new Promise((resolve) => {
    // ack 0: User has not yet acknowledged to migrate pictures.
    // ack 1: User acknowledges to migrate pictures to Downloads.
    browserProxy.localStorageGet({ackMigratePictures: 0})
        .then((values) => resolve(values.ackMigratePictures >= 1));
  });
  const ackMigrate = () =>
      browserProxy.localStorageSet({ackMigratePictures: 1});
  const doneMigrate = () => browserProxy.doneMigrate();

  return Promise
      .all([
        initInternalDir(),
        initInternalTempDir(),
        initExternalDir(),
        checkAcked,
        browserProxy.checkMigrated(),
      ])
      .then((results) => {
        let /** boolean */ acked;
        let /** boolean */ migrated;
        [internalDir, internalTempDir, externalDir, acked, migrated] = results;
        if (migrated && !externalDir) {
          throw new Error('External file system should be available.');
        }
        // Check if acknowledge-prompt and migrate-pictures are needed.
        if (migrated || !externalDir) {
          return [false, false];
        }
        // Check if any internal picture other than thumbnail needs migration.
        // Pictures taken by old Camera App may not have IMG_ or VID_ prefix.
        return readDir(internalDir)
            .then((entries) => {
              return entries.some((entry) => {
                if (entry.isDirectory) {
                  return false;
                }
                const fileEntry = /** @type {!FileEntry} */ (entry);
                return !hasThumbnailPrefix(fileEntry);
              });
            })
            .then((migrateNeeded) => {
              if (migrateNeeded) {
                return [!acked, true];
              }
              // If the external file system is supported and there is already
              // no picture in the internal file system, it implies done
              // migration and then doesn't need acknowledge-prompt.
              ackMigrate();
              doneMigrate();
              return [false, false];
            });
      })
      .then(
          ([promptNeeded, migrateNeeded]) => {  // Prompt to migrate if needed.
            return !promptNeeded ? migrateNeeded : promptMigrate().then(() => {
              ackMigrate();
              return migrateNeeded;
            });
          })
      .then((migrateNeeded) => {  // Migrate pictures if needed.
        const external = externalDir !== null;
        return !migrateNeeded ?
            external :
            migratePictures().then(doneMigrate).then(() => external);
      });
}

/**
 * Saves the blob to the given file name. Name of the actually saved file
 * might be different from the given file name if the file already exists.
 * @param {!DirectoryEntry} dir Directory to be written into.
 * @param {string} name Name of the file.
 * @param {!Blob} blob Data of the file to be saved.
 * @return {!Promise<?FileEntry>} Promise for the result.
 * @private
 */
function saveToFile(dir, name, blob) {
  return getFile(dir, name, true).then((entry) => {
    return new Promise((resolve, reject) => {
      entry.createWriter((fileWriter) => {
        fileWriter.onwriteend = () => resolve(entry);
        fileWriter.onerror = reject;
        fileWriter.write(blob);
      }, reject);
    });
  });
}

/**
 * Saves photo blob or metadata blob into predefined default location.
 * @param {!Blob} blob Data of the photo to be saved.
 * @param {string} filename Filename of the photo to be saved.
 * @return {!Promise<?FileEntry>} Promise for the result.
 */
export function saveBlob(blob, filename) {
  assert(externalDir !== null);
  return saveToFile(externalDir, filename, blob);
}

/**
 * Gets metadata of the file.
 * @param {!FileEntry} file
 * @return {!Promise<!Object>}
 */
export function getMetadata(file) {
  return new Promise((resolve) => file.getMetadata(resolve));
}

/**
 * Gets FileWriter of the file.
 * @param {!FileEntry} file
 * @return {!Promise<!FileWriter>}
 */
export function getFileWriter(file) {
  return new Promise((resolve, reject) => file.createWriter(resolve, reject));
}

/**
 * Creates a file for saving video recording result.
 * @return {!Promise<!FileEntry>} Newly created video file.
 * @throws {Error} If failed to create video file.
 */
export async function createVideoFile() {
  assert(externalDir !== null);
  const filename = new Filenamer().newVideoName();
  const file = await getFile(externalDir, filename, true);
  if (file === null) {
    throw new Error('Failed to create video temp file.');
  }
  return file;
}

/**
 * @type {string}
 */
const PRIVATE_TEMPFILE_NAME = 'video-intent.mkv';

/**
 * @return {!Promise<!FileEntry>} Newly created temporary file.
 * @throws {Error} If failed to create video temp file.
 */
export async function createPrivateTempVideoFile() {
  // TODO(inker): Handles running out of space case.
  const dir = internalTempDir;
  assert(dir !== null);
  const file = await getFile(dir, PRIVATE_TEMPFILE_NAME, true);
  if (file === null) {
    throw new Error('Failed to create private video temp file.');
  }
  return file;
}

/**
 * Increments the file index of a given file name to avoid name conflicts.
 * @param {string} name File name.
 * @return {string} File name with incremented index.
 */
function incrementFileName(name) {
  let base = '';
  let ext = '';
  let idx = 0;
  let match = name.match(/^([^.]+)(\..+)?$/);
  if (match) {
    base = match[1];
    ext = match[2];
    match = base.match(/ \((\d+)\)$/);
    if (match) {
      base = base.substring(0, match.index);
      idx = parseInt(match[1], 10);
    }
  }
  return base + ' (' + (idx + 1) + ')' + ext;
}

/**
 * Gets the file by the given name, avoiding name conflicts if necessary.
 * @param {!DirectoryEntry} dir Directory to get the file from.
 * @param {string} name File name. Result file may have a different name.
 * @param {boolean} create True to create file, false otherwise.
 * @return {!Promise<?FileEntry>} Promise for the result.
 */
export function getFile(dir, name, create) {
  return new Promise((resolve, reject) => {
           const options =
               create ? {create: true, exclusive: true} : {create: false};
           dir.getFile(name, options, resolve, reject);
         })
      .catch((error) => {
        if (create && error.name === 'InvalidModificationError') {
          // Avoid name conflicts for creating files.
          return getFile(dir, incrementFileName(name), create);
        } else if (!create && error.name === 'NotFoundError') {
          return null;
        }
        throw error;
      });
}

/**
 * Gets the picture entries.
 * @return {!Promise<!Array<!FileEntry>>} Promise for the picture entries.
 */
export function getEntries() {
  return readDir(externalDir).then((entries) => {
    return entries.filter((entry) => {
      if (entry.isDirectory) {
        return false;
      }
      const fileEntry = /** @type {!FileEntry} */ (entry);
      if (!hasVideoPrefix(fileEntry) && !hasImagePrefix(fileEntry)) {
        return false;
      }
      return entry.name.match(/_(\d{8})_(\d{6})(?: \((\d+)\))?/);
    });
  });
}

/**
 * Returns an URL for a picture.
 * @param {!FileEntry} entry File entry.
 * @param {number} limit Size limit. The file would be truncated if it's larger
 *     than limit.
 * @return {!Promise<string>} Promise for the result.
 */
export function pictureURL(entry, limit) {
  return new Promise((resolve) => {
    entry.file((file) => {
      if (file.size > limit) {
        file = file.slice(0, limit);
      }
      const url = URL.createObjectURL(file);
      resolve(url);
    });
  });
}


text:
package org.killbill.billing.jaxrs;

import java.util.List;
import java.util.UUID;

import javax.annotation.Nullable;

import org.joda.time.DateTime;
import org.killbill.billing.ObjectType;
import org.killbill.billing.catalog.api.BillingPeriod;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.client.KillBillClientException;
import org.killbill.billing.client.model.Account;
import org.killbill.billing.client.model.Subscription;
import org.killbill.billing.client.model.Tag;
import org.killbill.billing.client.model.TagDefinition;
import org.killbill.billing.client.model.Tags;
import org.killbill.billing.util.api.AuditLevel;
import org.killbill.billing.util.tag.ControlTagType;
import org.killbill.billing.util.tag.dao.SystemTags;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.google.common.collect.ImmutableList;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;

public class TestTag extends TestJaxrsBase {

    @Test(groups = "slow", description = "Cannot add badly formatted TagDefinition")
    public void testTagErrorHandling() throws Exception {
        final TagDefinition[] tagDefinitions = {new TagDefinition(null, false, null, null, null),
                                                new TagDefinition(null, false, "something", null, null),
                                                new TagDefinition(null, false, null, "something", null)};

        for (final TagDefinition tagDefinition : tagDefinitions) {
            try {
                killBillClient.createTagDefinition(tagDefinition, requestOptions);
                fail();
            } catch (final KillBillClientException e) {
            }
        }
    }

    @Test(groups = "slow", description = "Can create a TagDefinition")
    public void testTagDefinitionOk() throws Exception {
        final TagDefinition input = new TagDefinition(null, false, "blue", "relaxing color", ImmutableList.<ObjectType>of());

        final TagDefinition objFromJson = killBillClient.createTagDefinition(input, requestOptions);
        assertNotNull(objFromJson);
        assertEquals(objFromJson.getName(), input.getName());
        assertEquals(objFromJson.getDescription(), input.getDescription());
    }

    @Test(groups = "slow", description = "Can create and delete TagDefinitions")
    public void testMultipleTagDefinitionOk() throws Exception {
        List<TagDefinition> objFromJson = killBillClient.getTagDefinitions(requestOptions);
        final int sizeSystemTag = objFromJson.isEmpty() ? 0 : objFromJson.size();

        for (final TagDefinition cur : objFromJson) {
            Assert.assertFalse(SystemTags.isSystemTag(cur.getId()));
        }

        final TagDefinition inputBlue = new TagDefinition(null, false, "blue", "relaxing color", ImmutableList.<ObjectType>of());
        killBillClient.createTagDefinition(inputBlue, requestOptions);

        final TagDefinition inputRed = new TagDefinition(null, false, "red", "hot color", ImmutableList.<ObjectType>of());
        killBillClient.createTagDefinition(inputRed, requestOptions);

        final TagDefinition inputYellow = new TagDefinition(null, false, "yellow", "vibrant color", ImmutableList.<ObjectType>of());
        killBillClient.createTagDefinition(inputYellow, requestOptions);

        final TagDefinition inputGreen = new TagDefinition(null, false, "green", "super relaxing color", ImmutableList.<ObjectType>of());
        killBillClient.createTagDefinition(inputGreen, requestOptions);

        objFromJson = killBillClient.getTagDefinitions(requestOptions);
        assertNotNull(objFromJson);
        assertEquals(objFromJson.size(), 4 + sizeSystemTag);

        killBillClient.deleteTagDefinition(objFromJson.get(0).getId(), requestOptions);

        objFromJson = killBillClient.getTagDefinitions(requestOptions);
        assertNotNull(objFromJson);
        assertEquals(objFromJson.size(), 3 + sizeSystemTag);
    }

    @Test(groups = "slow", description = "Can search all tags for an account")
    public void testGetAllTagsByType() throws Exception {

        final DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0);
        clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());

        final Account account = createAccountWithDefaultPaymentMethod();

        final Subscription subscriptionJson = createEntitlement(account.getAccountId(), "87544332", "Shotgun",
                                                                ProductCategory.BASE, BillingPeriod.MONTHLY, true);

        for (final ControlTagType controlTagType : ControlTagType.values()) {
            killBillClient.createAccountTag(account.getAccountId(), controlTagType.getId(), requestOptions);
        }

        final TagDefinition bundleTagDefInput = new TagDefinition(null, false, "bundletagdef", "nothing special", ImmutableList.<ObjectType>of());
        final TagDefinition bundleTagDef = killBillClient.createTagDefinition(bundleTagDefInput, requestOptions);

        killBillClient.createBundleTag(subscriptionJson.getBundleId(), bundleTagDef.getId(), requestOptions);

        final Tags allBundleTags = killBillClient.getBundleTags(subscriptionJson.getBundleId(), AuditLevel.FULL, requestOptions);
        Assert.assertEquals(allBundleTags.size(), 1);

        final Tags allAccountTags = killBillClient.getAllAccountTags(account.getAccountId(), null, AuditLevel.FULL, requestOptions);
        Assert.assertEquals(allAccountTags.size(), ControlTagType.values().length + 1);

        final Tags allBundleTagsForAccount = killBillClient.getAllAccountTags(account.getAccountId(), ObjectType.BUNDLE.name(), AuditLevel.FULL, requestOptions);
        Assert.assertEquals(allBundleTagsForAccount.size(), 1);
    }

    @Test(groups = "slow", description = "Can search system tags")
    public void testSystemTagsPagination() throws Exception {
        final Account account = createAccount();
        for (final ControlTagType controlTagType : ControlTagType.values()) {
            killBillClient.createAccountTag(account.getAccountId(), controlTagType.getId(), requestOptions);
        }

        final Tags allTags = killBillClient.getTags(requestOptions);
        Assert.assertEquals(allTags.size(), ControlTagType.values().length);

        for (final ControlTagType controlTagType : ControlTagType.values()) {
            Assert.assertEquals(killBillClient.searchTags(controlTagType.toString(), requestOptions).size(), 1);
            Assert.assertEquals(killBillClient.searchTags(controlTagType.getDescription(), requestOptions).size(), 1);
        }
    }

    @Test(groups = "slow", description = "Can create a TagDefinition")
    public void testNotAllowedSystemTag() throws Exception {

        final Account account = createAccount();

        try {
            killBillClient.createAccountTag(account.getAccountId(), SystemTags.PARK_TAG_DEFINITION_ID, requestOptions);
            Assert.fail("Creating a tag associated with a system tag should fail");
        } catch (final Exception e) {
            Assert.assertTrue(true);
        }
    }

    @Test(groups = "slow", description = "Can paginate through all tags")
    public void testTagsPagination() throws Exception {
        final Account account = createAccount();
        for (int i = 0; i < 5; i++) {
            final TagDefinition tagDefinition = new TagDefinition(null, false, UUID.randomUUID().toString().substring(0, 5), UUID.randomUUID().toString(), ImmutableList.<ObjectType>of(ObjectType.ACCOUNT));
            final UUID tagDefinitionId = killBillClient.createTagDefinition(tagDefinition, requestOptions).getId();
            killBillClient.createAccountTag(account.getAccountId(), tagDefinitionId, requestOptions);
        }

        final Tags allTags = killBillClient.getTags(requestOptions);
        Assert.assertEquals(allTags.size(), 5);

        Tags page = killBillClient.getTags(0L, 1L, requestOptions);
        for (int i = 0; i < 5; i++) {
            Assert.assertNotNull(page);
            Assert.assertEquals(page.size(), 1);
            Assert.assertEquals(page.get(0), allTags.get(i));
            page = page.getNext();
        }
        Assert.assertNull(page);

        for (final Tag tag : allTags) {
            doSearchTag(UUID.randomUUID().toString(), null);
            doSearchTag(tag.getTagId().toString(), tag);
            doSearchTag(tag.getTagDefinitionName(), tag);

            final TagDefinition tagDefinition = killBillClient.getTagDefinition(tag.getTagDefinitionId(), requestOptions);
            doSearchTag(tagDefinition.getDescription(), tag);
        }

        final Tags tags = killBillClient.searchTags(ObjectType.ACCOUNT.toString(), requestOptions);
        Assert.assertEquals(tags.size(), 5);
        Assert.assertEquals(tags.getPaginationCurrentOffset(), 0);
        Assert.assertEquals(tags.getPaginationTotalNbRecords(), 5);
        Assert.assertEquals(tags.getPaginationMaxNbRecords(), 5);
    }

    private void doSearchTag(final String searchKey, @Nullable final Tag expectedTag) throws KillBillClientException {
        final Tags tags = killBillClient.searchTags(searchKey, requestOptions);
        if (expectedTag == null) {
            Assert.assertTrue(tags.isEmpty());
            Assert.assertEquals(tags.getPaginationCurrentOffset(), 0);
            Assert.assertEquals(tags.getPaginationTotalNbRecords(), 0);
            Assert.assertEquals(tags.getPaginationMaxNbRecords(), 5);
        } else {
            Assert.assertEquals(tags.size(), 1);
            Assert.assertEquals(tags.get(0), expectedTag);
            Assert.assertEquals(tags.getPaginationCurrentOffset(), 0);
            Assert.assertEquals(tags.getPaginationTotalNbRecords(), 1);
            Assert.assertEquals(tags.getPaginationMaxNbRecords(), 5);
        }
    }
}


text:
package com.edwise.pocs.spymockito;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class BarWellDesignedTest {

    private BarWellDesigned barWellDesigned;

    @Test
    public void testMyMethodWithoutMockito() {
        Foo foo = mock(Foo.class);
        barWellDesigned = new BarWellDesigned(foo);
        when(foo.doSomethingWithDatabase()).thenReturn("OK Foo mocked");

        int result = barWellDesigned.myMethod();

        assertThat(result).isEqualTo(1);
    }
}


text:
import { prepareFont } from '../../utils/led-matrix';
import * as AllFonts  from './allfonts';

let fonts = {};

Object.keys(AllFonts).forEach(key => {
    fonts[key] = prepareFont(AllFonts[key]);
});

export default fonts;