text:
'use strict';

/**
 * response.js
 *
 * We handle all potential responses through Actions on Google & Dialogflow here. Specifically, in most cases,
 * we use the built in Response functionality from Dialogflow for easier editability by our writers, replacing
 * and removing pieces on the fly based on conditions.
 */

const fetch = require('node-fetch');

const { logDebug, logError } = require('./logging')
const { makeCard } = require('./sharing-card')

/**
 * Url to our stitching service that creates mp3s for Assistant to play on the fly
 *
 * This service is not part of our OSS release. It used Sox and Rubberband to combine base stems (WAVs) on the fly,
 * using the same json schema we used in our /lookup calls. It ran on a quite beefy flex app engine instance.
 */
const AUDIO_STITCHER_SERVICE = 'your-stitcher-url'

/**
 * Minimum number of 'sessions' we want to go thru before we start showing the card
 * that links out to the website
 */
const NUM_SESSIONS_B4_CARD = 3

/**
 * Combined with above, we'll only show the card every N sessions after we initially allow it
 * so we don't spam users
 */
const SESSIONS_BETWEEN_CARDS = 3

const MIN_SESSION_B4_EXTENDING_OUTRO = 2

const PARAM_INSTRUMENT = '$instrument'

const POST_ROLL_ADD_STUFF_SUGGS = [
    `This is sounding good. Try adding ${PARAM_INSTRUMENT}?`,
    `This is my jam. Try throwing in ${PARAM_INSTRUMENT}.`,
    'This sounds great. Why not try changing the speed?',
    `That sounds tasty. Maybe try adding ${PARAM_INSTRUMENT}?`
]

const POST_ROLL_EXTEND_DURATION_SUGGS = [
    'This is sounding good. Keep it going by saying "play this longer".',
    'This is my jam. Loop longer by saying "keep this going".',
    'This sounds great. Keep it going by saying "play this longer".'
]

const NO_INPUT_RESPONSES = [
    "Did you say something? I don't think I heard you.",
    "If you want to keep jamming, you'll need to say something.",
    "Are you still there? You haven't said anything."
]

const EMPTY_SUGGESTION_RESPONSES = [
    "I'm sorry, I don't think I have anything like that. Please try something different.",
    "I don't think I have that one yet, please try something else.",
    "Checked the library and couldn't find anything for that. Try something else.",
    "Dusted off my records and couldn't find that, why don't you try something else?"
]

const UNKNOWN_ADD_RESPONSES = [
    'I\'m sorry, I don\'t think I have anything like that. Please try something different.',
    'I don\'t think I have that one yet, please try something else.',
    'Checked the library and couldn\'t find anything for that. Try something else.',
    'Dusted off my records and couldn\'t find that, why don\'t you try something else?'
]

const INSTRUMENT_TYPES = ['guitar', 'bass', 'drums', 'keyboard', 'wind', 'strings']
const INSTRUMENT_SUGGS = ['a guitar', 'a bass', 'some drums', 'a keyboard', 'some winds', 'some strings']

/**
 * Service to hit for creating share links to the website, creating a hash of our currentSession object
 * and returning that string.
 */
const HASH_SERVICE = 'https://mixlab-dev.appspot.com/hash'

/**
 * Hopefully you never hear this. If for some reason the stitcher fails or if stem object is broken, the <audio>
 * tag will play this rather than any audio, typically followed by one of the above POST_ROLL suggestions... Whoops.
 */
const WHOOPS_AUDIO_ERROR = "Whoops, there's supposed to be audio playing. Please ignore what I'm about to say."

/**
 * Creates the proper response for when a user adds a new instrument to our current session.
 *
 * On Dialogflow there should be two response objects returned in our RichResponse.items:
 * @item SimpleResponse 	this has all the successful responses, where we append our ssml to play
 * 							NOTE this needs both text and audio for it to autopopulate displayText on return, in most
 * 							cases this is already filled in as $filler, which is ignored and removed with ssml
 *
 * @param app
 * @param currentSession
 */
exports.makeAudioResponse = (app, currentSession) => {
    let sessionCount = currentSession.sessionCount

    // determine when to show our sharing card
    if(app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
        let showCard = sessionCount === NUM_SESSIONS_B4_CARD ||
            (sessionCount > NUM_SESSIONS_B4_CARD &&
                sessionCount % SESSIONS_BETWEEN_CARDS === 0)

        if(showCard) {
            let modifiedSession = Object.assign({}, currentSession)

            // move stems
            modifiedSession['tracks'] = modifiedSession.stems
            delete modifiedSession.stems

            // move sfx
            modifiedSession = moveSfx(modifiedSession)

            // Build rich response with custom sharing card using modified session object
            // to conform with the structure of website (.tracks instead of .stems - oops)
            getHash(modifiedSession)
                .then(hash => {
                    finishAudioResponse(app, currentSession, sessionCount, makeCard(app, hash))
                })
                .catch(error => {
                    logError('getHash error', error)
                    finishAudioResponse(app, currentSession, sessionCount)
                })

        } else {
            // quickly return without calling hash API
            finishAudioResponse(app, currentSession, sessionCount)
        }
    } else {
        // just respond quickly, its on the Home, not a device with a screen
        finishAudioResponse(app, currentSession, sessionCount)
    }
}

/**
 * Used for when we trigger the clear intent.
 *
 * On Dialogflow there should be two response objects returned in our RichResponse.items:
 * @item SimpleResponse 	this has all the successful responses, where we append our ssml to play
 * @item SimpleResponse 	this has responses for when you tried to clear an empty stem array
 *
 * @param app
 * @param wasAlreadyClear	whether or not to use the second SimpleResponse
 */
exports.makeClearResponse = (app, wasAlreadyClear = false) => {
    let richResponse = app.getIncomingRichResponse()

    if(wasAlreadyClear) {
        richResponse.items.splice(0, 1)
    } else {
        richResponse.items.pop()
    }

    return app.ask(richResponse, NO_INPUT_RESPONSES)
}

// TODO(atripaldi) make arrays of potential responses for use on these one-off use-cases or build them to pull from
// Dialogflow responses, which would require removal from intent handling in make audio response

exports.makeCantIncreaseDurationResponse = (app) => {
	return app.ask("How can we increase the duration of literally nothing? Try adding some instruments!", NO_INPUT_RESPONSES)
}

exports.makePlayWhatAgainResponse = (app) => {
    return app.ask("Play what again? There's nothing here! Try adding some instruments!", NO_INPUT_RESPONSES)
}

exports.makeUnknownAddResponse = (app) => {
    return app.ask(getRandomItem(UNKNOWN_ADD_RESPONSES), NO_INPUT_RESPONSES)
}

exports.makeEmptySuggestionsResponse = app => {
    return app.ask(getRandomItem(EMPTY_SUGGESTION_RESPONSES), NO_INPUT_RESPONSES)
}

// ------------------------------------------------------------------------------------------------
// Internal Methods
// ------------------------------------------------------------------------------------------------

const finishAudioResponse = (app, currentSession, sessionCount, card = null) => {
    let richResponse = app.getIncomingRichResponse()
    let url = getAudioURL(currentSession)
    let suggestion = getSuggestionPostRoll(sessionCount, currentSession)

    // hack hack hack since 'speech' or replacing 'textToSpeech' does nothing, need 'ssml' and  to remove 'textToSpeech'
    richResponse.items[0].simpleResponse['ssml'] = getSpeechResponse(url, suggestion)
    delete richResponse.items[0].simpleResponse.textToSpeech

    // add the card if we got one
    if(card) {
        richResponse.addBasicCard(card)
        logDebug('richResponse', card)
    }

    return app.ask(richResponse, NO_INPUT_RESPONSES)
}

const getHash = currentSession => {
    return fetch(
        HASH_SERVICE,
        {
            method: 'POST' ,
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(currentSession)
        }
    ).then(response => response.text())
}

/**
 * hacky workaround #2 for matching schema of webhook with what is being used for sharing in website
 */
const moveSfx = session => {
    let sfx = []

    for(let i = session.tracks.length-1; i >= 0; i--) {
        let item = session.tracks[i]

        if(item.instrumentCategory === 'sfx') {
            sfx = session.tracks.splice(i,1)
            break
        }
    }

    if(sfx.length > 0) {
        session['sfx'] = sfx
    }

    return session
}

const getSuggestionPostRoll = (sessionCount, currentSession) => {
     if(sessionCount >= MIN_SESSION_B4_EXTENDING_OUTRO && sessionCount % 2 === 0) {
        return getRandomItem(POST_ROLL_EXTEND_DURATION_SUGGS)
     } else {
         return getRandomItem(POST_ROLL_ADD_STUFF_SUGGS)
             .replace(PARAM_INSTRUMENT, getInstrumentNotPlaying(currentSession))
    }
}

const getInstrumentNotPlaying = currentSession => {
    let instruments = INSTRUMENT_TYPES.slice()
    let suggestions = INSTRUMENT_SUGGS.slice()

    for(let i = currentSession.stems.length-1; i >= 0; i--) {
        let item = currentSession.stems[i]

        if(instruments.includes(item.instrumentCategory)) {
            instruments.splice(i,1)
            suggestions.splice(i,1)
        }
    }

    logDebug('getInstrumentNotPlaying', instruments, currentSession.stems)

    if(suggestions.length > 1) {
        return getRandomItem(suggestions)
    } else if (suggestions.length === 1) {
        return suggestions[0]
    } else {
        // we've used them all (great!) so why not just pick something random
        return getRandomItem(INSTRUMENT_SUGGS)
    }
}

const getSpeechResponse = (stemsUrl, optionalSuggestion='', optionalPreRoll='') => {
    let prerollBreak = optionalPreRoll !== '' ? '<break time="1s"/>' : ''
    return `<speak>${optionalPreRoll} ${prerollBreak} <audio src="${stemsUrl}">${WHOOPS_AUDIO_ERROR}</audio> ${optionalSuggestion}</speak>`
}

const getAudioURL = currentSession => {
    return AUDIO_STITCHER_SERVICE + `/${encodeURIComponent(JSON.stringify(currentSession.stems))}/${currentSession.duration}`
}

const getRandomItem = array => array[Math.floor(Math.random()*array.length)];


text:
var uniq = require('uniq');

module.exports = function unique_list(str) {
    var str_split = str.split(',');

    return uniq(str_split);
};

redpajama_set_name: RedPajamaGithub


text:
/*! \file DiskMovingPlanR.hpp
 */
/** \class DiskMovingPlanR
 *  \brief disk - moving plan relation - Inherits from LagrangianRheonomousR
 */

#ifndef DiskMovingPlanR_h
#define DiskMovingPlanR_h

#include "MechanicsFwd.hpp"
#include "LagrangianRheonomousR.hpp"
#include "PluggedObject.hpp"

typedef double(*FTime)(double);

#define COMPUTE(X) \
  { if (_##X##Function->fPtr) _##X=((FTime)(_##X##Function->fPtr))(t); else _##X=0.; }

class DiskMovingPlanR : public LagrangianRheonomousR,
  public std::enable_shared_from_this<DiskMovingPlanR>
{
private:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(DiskMovingPlanR);

  double _time, _A, _B, _C, _ADot, _BDot, _CDot, _sqrA2pB2, _r, _AADot, _BBDot, _cubsqrA2pB2;

  SP::PluggedObject _AFunction;
  SP::PluggedObject _BFunction;
  SP::PluggedObject _CFunction;

  SP::PluggedObject _ADotFunction;
  SP::PluggedObject _BDotFunction;
  SP::PluggedObject _CDotFunction;

  DiskMovingPlanR() : LagrangianRheonomousR() {};

public:

  DiskMovingPlanR(FTime, FTime, FTime, FTime, FTime, FTime, double);

  void init(double);

  using LagrangianRheonomousR::computeh;
  /** to compute the output y = h(t,q,z) of the Relation
      \param time current time value
      \param q coordinates of the dynamical systems involved in the relation
      \param z user defined parameters (optional)
      \param y the resulting vector
  */
  void computeh(double time, const BlockVector& q, BlockVector& z, SiconosVector& y);

  /** to compute the jacobian of h(...). Set attribute _jachq (access: jacqhq())
      \param time current time value
      \param q coordinates of the dynamical systems involved in the relation
      \param z user defined parameters (optional)
  */
  void computeJachq(double time, const BlockVector& q, BlockVector& z);

  using LagrangianRheonomousR::computehDot;
  /** to compute the time-derivative of the output y = h(t,q,z), saved in attribute _hDot (access: hDot())
      \param time current time value
      \param q coordinates of the dynamical systems involved in the relation
      \param z user defined parameters (optional)
  */
  void computehDot(double time, const BlockVector& q, BlockVector& z);

  double distance(double, double, double);

  void setComputeAFunction(FTime f)
  {
    _AFunction.reset(new PluggedObject());
    _AFunction->setComputeFunction((void*) f);
  }

  void setComputeBFunction(FTime f)
  {
    _BFunction.reset(new PluggedObject());
    _BFunction->setComputeFunction((void*) f);
  }

  void setComputeCFunction(FTime f)
  {
    _CFunction.reset(new PluggedObject());
    _CFunction->setComputeFunction((void*) f);
  }

  void setComputeADotFunction(FTime f)
  {
    _ADotFunction.reset(new PluggedObject());
    _ADotFunction->setComputeFunction((void*) f);
  }

  void setComputeBDotFunction(FTime f)
  {
    _BDotFunction.reset(new PluggedObject());
    _BDotFunction->setComputeFunction((void*) f);
  }

  void setComputeCDotFunction(FTime f)
  {
    _CDotFunction.reset(new PluggedObject());
    _CDotFunction->setComputeFunction((void*) f);
  }

  bool equal(FTime, FTime, FTime, double) const;

  /** compute A
      \param t the time
  */
  void computeA(double t)
  COMPUTE(A)

  /** compute B
      \param t the time
  */
  void computeB(double t)
  COMPUTE(B)

  /** compute C
      \param t the time
  */
  void computeC(double t)
  COMPUTE(C)

  /** compute ADot
    \param t the time
  */
  inline void computeADot(double t)
  COMPUTE(ADot)

  /** compute BDot
      \param t the time
  */
  inline void computeBDot(double t)
  COMPUTE(BDot)

  /** compute CDot
      \param t the time
  */
  inline void computeCDot(double t)
  COMPUTE(CDot)

  /** visitor hooks
   */
  ACCEPT_VISITORS();

  ~DiskMovingPlanR() {};

};
#undef COMPUTE

#endif /* DiskMovingPlanR */


text:
import {expectType} from 'tsd';
import getEmails from './index.js';

expectType<Set<string>>(
	getEmails(
		'Lorem ipsum dolor, sindresorhus@gmail.com consectetuer unicorn@rainbow.cake elit.',
	),
);


text:
require "react/redux/rails/version"

module React
  module Redux
    module Rails
      class Engine < ::Rails::Engine
      end

    end
  end
end


text:
/*
 * SPYGLASS DRAWS CIRCLE TO VIEW HIDDEN LAYER.
 */

// get the pixel position with every move
var mousePosition = null;
map.on('pointermove', function (event) {
  mousePosition = event.pixel;
  map.render();
});

var chosen;
//console.log("chosen je na zacatku: " + chosen);
function onRadioChange(event) {
  if (chosen) {
    chosen.un('precompose', onPreCompose);
    chosen.un('postcompose', onPostCompose);
    chosen.setVisible(false);
  }
  //console.log("VYPISUJI clipped u chosen: " + clipped[event.target.value]);
  chosen = clipped[event.target.value];
  if (chosen === undefined || chosen === 'undefined') {
    return;
  }
  chosen.on('precompose', onPreCompose);
  chosen.on('postcompose', onPostCompose);
  chosen.setVisible(true);
}

// before rendering the layer, do some clipping
function onPreCompose(event) {
  var ctx = event.context;
  var pixelRatio = event.frameState.pixelRatio;
  ctx.save();
  ctx.beginPath();
  if (mousePosition) {
    // only show a circle around the mouse
    ctx.arc(mousePosition[0] * pixelRatio, mousePosition[1] * pixelRatio,
            radius * pixelRatio, 0, 2 * Math.PI);
    ctx.lineWidth = 10 * pixelRatio;
    ctx.strokeStyle = 'rgba(0,175,211,0.5)';
    ctx.stroke();
  }
  ;
  ctx.clip();
}

// after rendering the layer, restore the canvas context
function onPostCompose(event) {
  var ctx = event.context;
  ctx.restore();
}

var inputs = document.querySelectorAll('input[type="radio"]');
for (var i = 0, ii = inputs.length; i < ii; ++i) {
  inputs[i].addEventListener('change', onRadioChange);
}
onRadioChange({target: document.querySelector('input[type="radio"]:checked')});

var radius = 150;
$(document).keydown(function (evt) {
  if (evt.which === 38) {
    radius = Math.min(radius + 5, 500);
    map.render();
  } else if (evt.which === 40) {
    radius = Math.max(radius - 5, 25);
    map.render();
  }
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NadekoBot.Core.Services.Database.Models;
using NadekoBot.Modules.Pokemon.Common;
using NadekoBot.Modules.Pokemon.Extentions;
using NadekoBot.Modules.Pokemon.Services;

namespace NadekoBot.Modules.Pokemon.Common
{
    class PokemonAttack
    {
        public PokemonSprite Attacker;
        public PokemonSprite Defender;
        public PokemonSpecies AttackSpecies;
        public PokemonSpecies DefendSpecies;
        public List<PokemonType> AttackerTypes { get; set; }
        public List<PokemonType> DefenseTypes { get; set; }
        public int Damage { get; }
        public string StatusApplied { get; }
        public int StatusTurns { get; }
        public int StatusDamage { get; }
        private bool Thawed { get; }
        private bool FullyParalyzed { get; }
        public PokemonMove Move { get; }
        Random Rng { get; set; } = new Random();
        public bool IsCritical { get; set; } = false;
        public bool MoveHits { get; }
        /// <summary>
        /// How effective the move is;
        /// 1: somewhat effective,
        /// less than 1: not effective
        /// more than 1: super effective
        /// </summary>
        public double Effectiveness { get; set; } = 1;
        public PokemonAttack(PokemonSprite attacker, PokemonSprite defender, PokemonMove move)
        {
            Attacker = attacker;
            Defender = defender;
            AttackSpecies = attacker.GetSpecies();
            DefendSpecies = defender.GetSpecies();
            AttackerTypes = AttackSpecies.GetPokemonTypes();
            DefenseTypes = DefendSpecies.GetPokemonTypes();
            if (Attacker.StatusTurns == 0 && (Attacker.StatusEffect == "sleep" || Attacker.StatusEffect == "freeze" || Attacker.StatusEffect == "poison"))
                Attacker.StatusEffect = "none";
            if (Attacker.StatusTurns > 0)
                Attacker.StatusTurns--;
            this.Move = move;
            Thawed = DidItThaw();
            FullyParalyzed = IsFullyParalyzed();
            MoveHits = DoesItHit();
            Damage = MoveHits ? CalculateDamage() : 0;
            StatusApplied = MoveHits ? CalculateStatus() : "none";
            StatusTurns = MoveHits ? CalcStatusTurns() : 0;
            StatusDamage = CalculateStatusDamage();
        }
        public void Commit()
        {
            if (MoveHits)
            {
                Defender.HP -= Damage;
                if (StatusApplied != "none")
                {
                    Defender.StatusEffect = StatusApplied;
                    Defender.StatusTurns = (int)StatusTurns;
                }
            }
            Attacker.HP -= StatusDamage;
            if (Thawed)
                Attacker.StatusEffect = "none";

            Attacker.Update();
            Defender.Update();
        }

        private string CalculateStatus()
        {
            if (Defender.StatusEffect == null)
                Defender.StatusEffect = "none";
            if (Defender.StatusEffect != "none")
                return "none";
            var ME = Move.MoveEffects;
            if (ME.Ailment != "none")
            {
                if (ME.AilmentChance == 0 || (Rng.Next(0, 100) < ME.AilmentChance))
                {
                    return ME.Ailment;
                }
            }
            return "none";
        }

        private int CalcStatusTurns()
        {
            if (Move.MoveEffects.MaxTurns != null)
                return Rng.Next(1,(int)Move.MoveEffects.MaxTurns);
            return 0;
        }

        private int CalculateStatusDamage()
        {
            switch (Attacker.StatusEffect)
            {
                case "burn":
                    return Attacker.HP / 16+1;

                case "poison":
                    return Attacker.HP / 16+1;

                default:
                    return 0;

            }
        }

        private int CalculateDamage()
        {
            if (!MoveHits)
                return 0;
            if (Move.DamageType == "status")
                return 0;
            //use formula in http://bulbapedia.bulbagarden.net/wiki/Damage
            double attack;
            double defense;
            if (Move.Type == "physical")
            {
                attack = Attacker.Attack;
                defense = Defender.SpecialDefense;
            }
            else
            {
                attack = Attacker.SpecialAttack;
                defense = Defender.Defense;
            }
            double toReturn = (((((2 * (double)Attacker.Level)/5) + 2) *Move.Power * (attack / defense))/50) + 2;
            toReturn = toReturn * GetModifier();
            return (int)Math.Floor(toReturn);
        }

        private double GetModifier()
        {
            var stablist = AttackerTypes.Where(x => x.Name == Move.Type);
            double stab = 1;
            if (stablist.Any())
                stab = 1.5;
            var typeEffectiveness = SetEffectiveness();
            double critical = 1;
            if (Rng.Next(0, 100) < 6.25)
            {
                IsCritical = true;
                critical = 1.5;
            }
            double other = /*rng.NextDouble() * 2*/1;
            double random = (double)Rng.Next(85, 100) / 100;
            double mod = stab * typeEffectiveness * critical * other * random;
            return mod;
        }

        private bool DoesItHit()
        {
            if (Attacker.StatusEffect == "sleep")
                return false;
            if (FullyParalyzed)
                return false;
            if(Attacker.StatusEffect == "freeze" && Thawed==false)
            {
                return false;
            }
            if (Move.Accuracy == 0)
                return true;
            else
                return Rng.Next(1, 100) <= Move.Accuracy;
        }

        private double SetEffectiveness()
        {

            var moveTypeString = Move.Type.ToUpperInvariant();
            var moveType = moveTypeString.StringToPokemonType();
            var dTypeStrings = DefenseTypes.Select(x => x.Name);
            var mpliers = moveType.Multipliers.Where(x => dTypeStrings.Contains(x.Type));
            foreach (var mplier in mpliers)
            {
                Effectiveness = Effectiveness * mplier.Multiplication;
            }
            return Effectiveness;
        }

        private bool IsFullyParalyzed()
        {
            if (Attacker.StatusEffect == "paralysis") {
                var rand = Rng.Next(1, 5);
                if (rand == 2)
                    return true;
            }

            return false;
        }

        private bool DidItThaw()
        {
            if (Attacker.StatusEffect == "freeze" && Rng.Next(0, 100) < 20)
            {
                return true;
            }
            return false;
        }

        public string AttackString()
        {
            string str = "";
            if (Attacker.StatusEffect == "paralysis")
                str += $"**{Attacker.NickName}** is paralyzed!\n";
            if (FullyParalyzed)
            {
                str += $"It can't move!\n";
                return str;
            }
            if (Attacker.StatusEffect == "freeze")
            {
                    str += $"**{Attacker.NickName}** is frozen solid!\n";
                    return str;
            }
            if (Thawed)
                str += $"**{Attacker.NickName}** has thawed out!\n";
            if (Attacker.StatusEffect == "sleep")
            {
                str += $"💤 **{Attacker.NickName}** is fast asleep!\n";
                return str;
            }
            str += $"**{Attacker.NickName}** attacked **{Defender.NickName}** with **{Move.Name}**\n";
            if (!MoveHits)
            {
                str += "But it missed!\n";
                return str;
            }
            if (Damage > 0)
                str += $"**{Defender.NickName}** received {Damage} damage!\n";
            if (IsCritical)
            {
                str += "It's a critical hit!\n";
            }
            if (Effectiveness > 1)
            {
                str += "It's super effective!\n";
            }
            else if (Effectiveness < 1)
            {
                str += "It's not very effective...\n";
            }
            switch (StatusApplied)
            {
                case "burn":
                    str += $"The opponent's {Defender.NickName} it burned! 🔥\n";
                    break;

                case "paralysis":
                    str += $"The opponent's {Defender.NickName} is paralyzed. It can't attack!\n";
                    break;

                case "poison":
                    str += $"The opponent's {Defender.NickName} has been poisoned!\n";
                    break;

                case "sleep":
                    str += $"The opponent's {Defender.NickName} fell asleep! 💤\n";
                    break;

                case "freeze":
                    str += $"The opponent's {Defender.NickName} was forzen solid! 🌬\n";
                    break;

                default:
                    break;
            }
            if (Attacker.StatusEffect == "burn" || Attacker.StatusEffect == "poison")
            {
                str += $"**{Attacker.NickName}** took {StatusDamage} damage from it's {Attacker.StatusEffect}\n";
            }
            str += $"{Defender.NickName} has {Defender.HP} HP left!";
            return str;
        }
    }
}


text:
name: cljs.test/try-expr
see also:
---

## Summary

## Details

## Examples


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2016 Braden Farmer

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:id="@+id/main_activity_layout"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:clipToPadding="true"
              android:fitsSystemWindows="true"
              android:orientation="vertical"
              android:background="?attr/tb_main_activity_background" >

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        <include layout="@layout/tb_switch_layout" />

    </androidx.appcompat.widget.Toolbar>

    <LinearLayout
        android:id="@+id/fragmentContainer"
        android:orientation="vertical"
        android:layout_width="@dimen/tb_max_width"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:background="?attr/tb_start_menu_background" />

</LinearLayout>


text:
@import url("toolbar.css");

.currenttoolbar .toolbarbutton,
.availabletoolbar .toolbarbutton,
.currenttoolbar .toolbarbutton *,
.availabletoolbar .toolbarbutton *
{
	float: right;
}
.button_placeholder
{
	float: right;
}

.toolbaractions .toolbaractionbutton
{
	float: left;
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

001package org.maltparser.parser.history.container;
002
003import org.maltparser.core.exception.MaltChainedException;
004import org.maltparser.core.symbol.Table;
005/**
006*
007* @author Johan Hall
008**/
009public class TableContainer {
010        public enum RelationToNextDecision { COMBINED, SEQUANTIAL, BRANCHED, SWITCHED, NONE }
011        protected int cachedCode;
012        protected final StringBuilder cachedSymbol;
013        protected Table table;
014        protected String name;
015        private final RelationToNextDecision relationToNextDecision;
016
017        public TableContainer(Table _table, String _name, char _decisionSeparator) {
018                this.table = _table;
019                this.name = _name;
020                switch (_decisionSeparator) {
021                case '+':
022                        this.relationToNextDecision = RelationToNextDecision.COMBINED;
023                        break;
024                case ',':
025                        this.relationToNextDecision = RelationToNextDecision.SEQUANTIAL;
026                        break;
027                case ';':
028                        this.relationToNextDecision = RelationToNextDecision.BRANCHED;
029                        break;
030                case '#':
031                        this.relationToNextDecision = RelationToNextDecision.BRANCHED;
032                        break;
033                case '?':
034                        this.relationToNextDecision = RelationToNextDecision.SWITCHED;
035                        break;
036                default:
037                        this.relationToNextDecision = RelationToNextDecision.NONE;
038                }
039                cachedSymbol = new StringBuilder();
040                cachedCode = -1;
041        }
042
043
044        public void clearCache() {
045                cachedCode = -1;
046                cachedSymbol.setLength(0);
047        }
048
049        public String getSymbol(int code) throws MaltChainedException {
050                if (code < 0 && !containCode(code)) {
051                        clearCache();
052                        return null;
053                }
054                if (cachedCode != code) {
055                        clearCache();
056                        cachedCode = code;
057                        cachedSymbol.append(table.getSymbolCodeToString(cachedCode));
058                }
059                return cachedSymbol.toString();
060        }
061
062        public int getCode(String symbol) throws MaltChainedException {
063                if (cachedSymbol == null || !cachedSymbol.equals(symbol)) {
064                        clearCache();
065                        cachedSymbol.append(symbol);
066                        cachedCode = table.getSymbolStringToCode(symbol);
067                }
068                return cachedCode;
069        }
070
071        public boolean containCode(int code) throws MaltChainedException {
072                if (cachedCode != code) {
073                        clearCache();
074                        cachedSymbol.append(table.getSymbolCodeToString(code));
075                        if (cachedSymbol == null) {
076                                return false;
077                        }
078                        cachedCode = code;
079                }
080                return true;
081        }
082
083        public boolean containSymbol(String symbol) throws MaltChainedException {
084                if (cachedSymbol == null || !cachedSymbol.equals(symbol)) {
085                        clearCache();
086                        cachedCode = table.getSymbolStringToCode(symbol);
087                        if (cachedCode < 0) {
088                                return false;
089                        }
090                        cachedSymbol.append(symbol);
091                }
092                return true;
093        }
094
095        public boolean continueWithNextDecision(int code) throws MaltChainedException {
096                if (table instanceof DecisionPropertyTable) {
097                        return ((DecisionPropertyTable)table).continueWithNextDecision(code);
098                }
099                return true;
100        }
101
102        public boolean continueWithNextDecision(String symbol) throws MaltChainedException {
103                if (table instanceof DecisionPropertyTable) {
104                        return ((DecisionPropertyTable)table).continueWithNextDecision(symbol);
105                }
106                return true;
107        }
108
109        public Table getTable() {
110                return table;
111        }
112
113        public String getTableName() {
114                return table != null?table.getName():null;
115        }
116
117        public String getTableContainerName() {
118                return name;
119        }
120
121        public RelationToNextDecision getRelationToNextDecision() {
122                return relationToNextDecision;
123        }
124
125        protected void setTable(Table table) {
126                this.table = table;
127        }
128
129        protected void setName(String name) {
130                this.name = name;
131        }
132
133        public int size() {
134                return table.size();
135        }
136
137        public String toString() {
138                final StringBuilder sb = new StringBuilder();
139                sb.append(name);
140                sb.append(" -> " );
141                sb.append(cachedSymbol);
142                sb.append(" = ");
143                sb.append(cachedCode);
144                return sb.toString();
145        }
146}


text:
namespace blink {

CueTimeline::CueTimeline(HTMLMediaElement& media_element)
    : media_element_(&media_element),
      last_update_time_(-1),
      ignore_update_(0) {}

void CueTimeline::AddCues(TextTrack* track, const TextTrackCueList* cues) {
  DCHECK_NE(track->mode(), TextTrack::DisabledKeyword());
  for (wtf_size_t i = 0; i < cues->length(); ++i)
    AddCueInternal(cues->AnonymousIndexedGetter(i));
  UpdateActiveCues(MediaElement().currentTime());
}

void CueTimeline::AddCue(TextTrack* track, TextTrackCue* cue) {
  DCHECK_NE(track->mode(), TextTrack::DisabledKeyword());
  AddCueInternal(cue);
  UpdateActiveCues(MediaElement().currentTime());
}

void CueTimeline::AddCueInternal(TextTrackCue* cue) {
  // Negative duration cues need be treated in the interval tree as
  // zero-length cues.
  double end_time = std::max(cue->startTime(), cue->endTime());

  CueInterval interval =
      cue_tree_.CreateInterval(cue->startTime(), end_time, cue);
  if (!cue_tree_.Contains(interval))
    cue_tree_.Add(interval);
}

void CueTimeline::RemoveCues(TextTrack*, const TextTrackCueList* cues) {
  for (wtf_size_t i = 0; i < cues->length(); ++i)
    RemoveCueInternal(cues->AnonymousIndexedGetter(i));
  UpdateActiveCues(MediaElement().currentTime());
}

void CueTimeline::RemoveCue(TextTrack*, TextTrackCue* cue) {
  RemoveCueInternal(cue);
  UpdateActiveCues(MediaElement().currentTime());
}

void CueTimeline::RemoveCueInternal(TextTrackCue* cue) {
  // Negative duration cues need to be treated in the interval tree as
  // zero-length cues.
  double end_time = std::max(cue->startTime(), cue->endTime());

  CueInterval interval =
      cue_tree_.CreateInterval(cue->startTime(), end_time, cue);
  cue_tree_.Remove(interval);

  wtf_size_t index = currently_active_cues_.Find(interval);
  if (index != kNotFound) {
    DCHECK(cue->IsActive());
    currently_active_cues_.EraseAt(index);
    cue->SetIsActive(false);
    // Since the cue will be removed from the media element and likely the
    // TextTrack might also be destructed, notifying the region of the cue
    // removal shouldn't be done.
    cue->RemoveDisplayTree(TextTrackCue::kDontNotifyRegion);
  }
}

void CueTimeline::HideCues(TextTrack*, const TextTrackCueList* cues) {
  for (wtf_size_t i = 0; i < cues->length(); ++i)
    cues->AnonymousIndexedGetter(i)->RemoveDisplayTree();
}

static bool TrackIndexCompare(TextTrack* a, TextTrack* b) {
  return a->TrackIndex() - b->TrackIndex() < 0;
}

static bool EventTimeCueCompare(const std::pair<double, TextTrackCue*>& a,
                                const std::pair<double, TextTrackCue*>& b) {
  // 12 - Sort the tasks in events in ascending time order (tasks with earlier
  // times first).
  if (a.first != b.first)
    return a.first - b.first < 0;

  // If the cues belong to different text tracks, it doesn't make sense to
  // compare the two tracks by the relative cue order, so return the relative
  // track order.
  if (a.second->track() != b.second->track())
    return TrackIndexCompare(a.second->track(), b.second->track());

  // 12 - Further sort tasks in events that have the same time by the
  // relative text track cue order of the text track cues associated
  // with these tasks.
  return a.second->CueIndex() < b.second->CueIndex();
}

static Event* CreateEventWithTarget(const AtomicString& event_name,
                                    EventTarget* event_target) {
  Event* event = Event::Create(event_name);
  event->SetTarget(event_target);
  return event;
}

void CueTimeline::UpdateActiveCues(double movie_time) {
  // 4.8.10.8 Playing the media resource

  //  If the current playback position changes while the steps are running,
  //  then the user agent must wait for the steps to complete, and then must
  //  immediately rerun the steps.
  if (IgnoreUpdateRequests())
    return;

  HTMLMediaElement& media_element = MediaElement();

  // Don't run the "time marches on" algorithm if the document has been
  // detached. This primarily guards against dispatch of events w/
  // HTMLTrackElement targets.
  if (media_element.GetDocument().IsDetached())
    return;

  // https://html.spec.whatwg.org/C/#time-marches-on

  // 1 - Let current cues be a list of cues, initialized to contain all the
  // cues of all the hidden, showing, or showing by default text tracks of the
  // media element (not the disabled ones) whose start times are less than or
  // equal to the current playback position and whose end times are greater
  // than the current playback position.
  CueList current_cues;

  // The user agent must synchronously unset [the text track cue active] flag
  // whenever ... the media element's readyState is changed back to
  // kHaveNothing.
  if (media_element.getReadyState() != HTMLMediaElement::kHaveNothing &&
      media_element.GetWebMediaPlayer()) {
    current_cues =
        cue_tree_.AllOverlaps(cue_tree_.CreateInterval(movie_time, movie_time));
  }

  CueList previous_cues;
  CueList missed_cues;

  // 2 - Let other cues be a list of cues, initialized to contain all the cues
  // of hidden, showing, and showing by default text tracks of the media
  // element that are not present in current cues.
  previous_cues = currently_active_cues_;

  // 3 - Let last time be the current playback position at the time this
  // algorithm was last run for this media element, if this is not the first
  // time it has run.
  double last_time = last_update_time_;
  double last_seek_time = media_element.LastSeekTime();

  // 4 - If the current playback position has, since the last time this
  // algorithm was run, only changed through its usual monotonic increase
  // during normal playback, then let missed cues be the list of cues in other
  // cues whose start times are greater than or equal to last time and whose
  // end times are less than or equal to the current playback position.
  // Otherwise, let missed cues be an empty list.
  if (last_time >= 0 && last_seek_time < movie_time) {
    CueList potentially_skipped_cues =
        cue_tree_.AllOverlaps(cue_tree_.CreateInterval(last_time, movie_time));

    for (CueInterval cue : potentially_skipped_cues) {
      // Consider cues that may have been missed since the last seek time.
      if (cue.Low() > std::max(last_seek_time, last_time) &&
          cue.High() < movie_time)
        missed_cues.push_back(cue);
    }
  }

  last_update_time_ = movie_time;

  // 5 - If the time was reached through the usual monotonic increase of the
  // current playback position during normal playback, and if the user agent
  // has not fired a timeupdate event at the element in the past 15 to 250ms...
  // NOTE: periodic 'timeupdate' scheduling is handled by HTMLMediaElement in
  // PlaybackProgressTimerFired().

  // Explicitly cache vector sizes, as their content is constant from here.
  wtf_size_t missed_cues_size = missed_cues.size();
  wtf_size_t previous_cues_size = previous_cues.size();

  // 6 - If all of the cues in current cues have their text track cue active
  // flag set, none of the cues in other cues have their text track cue active
  // flag set, and missed cues is empty, then abort these steps.
  bool active_set_changed = missed_cues_size;

  for (wtf_size_t i = 0; !active_set_changed && i < previous_cues_size; ++i) {
    if (!current_cues.Contains(previous_cues[i]) &&
        previous_cues[i].Data()->IsActive())
      active_set_changed = true;
  }

  for (CueInterval current_cue : current_cues) {
    // Notify any cues that are already active of the current time to mark
    // past and future nodes. Any inactive cues have an empty display state;
    // they will be notified of the current time when the display state is
    // updated.
    if (current_cue.Data()->IsActive())
      current_cue.Data()->UpdatePastAndFutureNodes(movie_time);
    else
      active_set_changed = true;
  }

  if (!active_set_changed)
    return;

  // 7 - If the time was reached through the usual monotonic increase of the
  // current playback position during normal playback, and there are cues in
  // other cues that have their text track cue pause-on-exi flag set and that
  // either have their text track cue active flag set or are also in missed
  // cues, then immediately pause the media element.
  for (wtf_size_t i = 0; !media_element.paused() && i < previous_cues_size;
       ++i) {
    if (previous_cues[i].Data()->pauseOnExit() &&
        previous_cues[i].Data()->IsActive() &&
        !current_cues.Contains(previous_cues[i]))
      media_element.pause();
  }

  for (wtf_size_t i = 0; !media_element.paused() && i < missed_cues_size; ++i) {
    if (missed_cues[i].Data()->pauseOnExit())
      media_element.pause();
  }

  // 8 - Let events be a list of tasks, initially empty. Each task in this
  // list will be associated with a text track, a text track cue, and a time,
  // which are used to sort the list before the tasks are queued.
  HeapVector<std::pair<double, Member<TextTrackCue>>> event_tasks;

  // 8 - Let affected tracks be a list of text tracks, initially empty.
  HeapVector<Member<TextTrack>> affected_tracks;

  for (const auto& missed_cue : missed_cues) {
    // 9 - For each text track cue in missed cues, prepare an event named enter
    // for the TextTrackCue object with the text track cue start time.
    event_tasks.push_back(
        std::make_pair(missed_cue.Data()->startTime(), missed_cue.Data()));

    // 10 - For each text track [...] in missed cues, prepare an event
    // named exit for the TextTrackCue object with the  with the later of
    // the text track cue end time and the text track cue start time.

    // Note: An explicit task is added only if the cue is NOT a zero or
    // negative length cue. Otherwise, the need for an exit event is
    // checked when these tasks are actually queued below. This doesn't
    // affect sorting events before dispatch either, because the exit
    // event has the same time as the enter event.
    if (missed_cue.Data()->startTime() < missed_cue.Data()->endTime()) {
      event_tasks.push_back(
          std::make_pair(missed_cue.Data()->endTime(), missed_cue.Data()));
    }
  }

  for (const auto& previous_cue : previous_cues) {
    // 10 - For each text track cue in other cues that has its text
    // track cue active flag set prepare an event named exit for the
    // TextTrackCue object with the text track cue end time.
    if (!current_cues.Contains(previous_cue)) {
      event_tasks.push_back(
          std::make_pair(previous_cue.Data()->endTime(), previous_cue.Data()));
    }
  }

  for (const auto& current_cue : current_cues) {
    // 11 - For each text track cue in current cues that does not have its
    // text track cue active flag set, prepare an event named enter for the
    // TextTrackCue object with the text track cue start time.
    if (!previous_cues.Contains(current_cue)) {
      event_tasks.push_back(
          std::make_pair(current_cue.Data()->startTime(), current_cue.Data()));
    }
  }

  // 12 - Sort the tasks in events in ascending time order (tasks with earlier
  // times first).
  std::sort(event_tasks.begin(), event_tasks.end(), EventTimeCueCompare);

  for (const auto& task : event_tasks) {
    if (!affected_tracks.Contains(task.second->track()))
      affected_tracks.push_back(task.second->track());

    // 13 - Queue each task in events, in list order.

    // Each event in eventTasks may be either an enterEvent or an exitEvent,
    // depending on the time that is associated with the event. This
    // correctly identifies the type of the event, if the startTime is
    // less than the endTime in the cue.
    if (task.second->startTime() >= task.second->endTime()) {
      media_element.ScheduleEvent(
          CreateEventWithTarget(event_type_names::kEnter, task.second.Get()));
      media_element.ScheduleEvent(
          CreateEventWithTarget(event_type_names::kExit, task.second.Get()));
    } else {
      bool is_enter_event = task.first == task.second->startTime();
      AtomicString event_name =
          is_enter_event ? event_type_names::kEnter : event_type_names::kExit;
      media_element.ScheduleEvent(
          CreateEventWithTarget(event_name, task.second.Get()));
    }
  }

  // 14 - Sort affected tracks in the same order as the text tracks appear in
  // the media element's list of text tracks, and remove duplicates.
  std::sort(affected_tracks.begin(), affected_tracks.end(), TrackIndexCompare);

  // 15 - For each text track in affected tracks, in the list order, queue a
  // task to fire a simple event named cuechange at the TextTrack object, and,
  // ...
  for (const auto& track : affected_tracks) {
    media_element.ScheduleEvent(
        CreateEventWithTarget(event_type_names::kCuechange, track.Get()));

    // ... if the text track has a corresponding track element, to then fire a
    // simple event named cuechange at the track element as well.
    if (auto* loadable_text_track = DynamicTo<LoadableTextTrack>(track.Get())) {
      HTMLTrackElement* track_element = loadable_text_track->TrackElement();
      DCHECK(track_element);
      media_element.ScheduleEvent(
          CreateEventWithTarget(event_type_names::kCuechange, track_element));
    }
  }

  // 16 - Set the text track cue active flag of all the cues in the current
  // cues, and unset the text track cue active flag of all the cues in the
  // other cues.
  for (const auto& cue : current_cues)
    cue.Data()->SetIsActive(true);

  for (const auto& previous_cue : previous_cues) {
    if (!current_cues.Contains(previous_cue)) {
      TextTrackCue* cue = previous_cue.Data();
      cue->SetIsActive(false);
      cue->RemoveDisplayTree();
    }
  }

  // Update the current active cues.
  currently_active_cues_ = current_cues;
  media_element.UpdateTextTrackDisplay();
}

void CueTimeline::BeginIgnoringUpdateRequests() {
  ++ignore_update_;
}

void CueTimeline::EndIgnoringUpdateRequests() {
  DCHECK(ignore_update_);
  --ignore_update_;
  if (!ignore_update_)
    UpdateActiveCues(MediaElement().currentTime());
}

void CueTimeline::Trace(Visitor* visitor) {
  visitor->Trace(media_element_);
}

}  // namespace blink


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Pitch Page</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/style.css">

    -
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Leckerli+One" />
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Federant" />
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Yellowtail" />

Resume

Portfolio

Contact

Samantha Zgak

Designer | Artist | Photographer

My name is Samantha Zgak, and I am a senior studying Visual Communication Design at Eastern Washington University. My passions include art, design, and photography. I have been dabbling with all different mediums so I can create visually appealing pieces. Some include digital programs, acrilic paint, watercolor, ceramics, and many more.

“What is design? It's where you stand with a foot in two worlds - the world of technology and the world of people and human purposes - and you try to bring the two together.”

Mitchell Kapor


text:
import psutil
import signal
import sys
import time

from threading import Thread

def interruptHandler(signal, frame):
    sys.exit(0)

def dataNetwork():
    netdata = psutil.net_io_counters()
    return netdata.packets_sent + netdata.packets_recv

def dataNetworkHandler():
    idDevice = "IoT101Device"
    while True:
        packets = dataNetwork()
        message = idDevice + " " + str(packets)
        print "dataNetworkHandler " + message
        time.sleep(1)

if __name__ == '__main__':

    signal.signal(signal.SIGINT, interruptHandler)

    threadx = Thread(target=dataNetworkHandler)
    threadx.start()

    while True:
        print "Hello Internet of Things 101"
        time.sleep(5)

# End of File


text:
<link rel="import" href="packages/polymer/polymer.html">

<polymer-element name="profiteer-item-info">
  <template>

      {{model.name}} {{model.typeLine}}

  </template>

</polymer-element>


text:
/* jshint expr: true */

'use strict';

var PeckerBuilder = require('./../../index').Builder;
var peckerExpect = require('./../support/expect');
var testUtils = require('./../support/test-utils');
var expectManifestContainAsset = peckerExpect.expectManifestContainAsset;
var expectManifestNotToContainAsset = peckerExpect.expectManifestNotToContainAsset;
var expectAssetExists = peckerExpect.expectAssetExists;
var cleanBuildFiles = testUtils.cleanBuildFiles;

var peckerBuilder;
var baseOptions = {
  name: 'testPecker',
  env: 'production',
  silent: true,
  skip: ['skip.js'],
  baseDir: __dirname,
  destDir: './build',
  baseUrl: '/static-assets',
  assets: []
};

describe('Unit: PeckerBuilder.buildFileAsset', function () {
  beforeEach(function () {
    peckerBuilder = new PeckerBuilder(baseOptions);
  });

  it('should successfully build a simple CSS "file" asset', function (done) {
    var assetOptions = {
      type: 'file',
      name: 'site.css',
      files: [
        '../support/src/css/site.css'
      ]
    };
    peckerBuilder.buildFileAsset(assetOptions, function () {
      expectManifestContainAsset(peckerBuilder, assetOptions);
      expectAssetExists(peckerBuilder, assetOptions);
      done();
    });
  });
  it('should successfully build and concatenate two (2) CSS "file" assets into a single CSS file', function (done) {

    var assetOptions = {
      type: 'file',
      name: 'all.css',
      files: [
        '../support/src/css/site.css',
        '../support/src/css/app.css'
      ]
    };

    peckerBuilder.buildFileAsset(assetOptions, function () {
      expectManifestContainAsset(peckerBuilder, assetOptions);
      expectAssetExists(peckerBuilder, assetOptions);
      done();
    });
  });
  it('should fail to build a "file" asset that does not exists', function (done) {

    var assetOptions = {
      type: 'file',
      name: 'missing.css',
      files: [
        '../support/src/css/file-does-not-exists.css'
      ],
      transform: [
        'sass',
        'concat',
        'autoprefixer',
        'clean-css'
      ]
    };
    peckerBuilder.buildFileAsset(assetOptions, function () {
      expectManifestNotToContainAsset(peckerBuilder, assetOptions);
      done();
    });
  });

  it('should successfully build but not concatenate if asset name has a file extension in skipConcat list (only one file will be referenced in manifest.json) ', function (done) {

    var assetOptions = {
      type: 'file',
      name: 'h6k3jaH.jpg',
      files: [
        '../support/src/images/*.jpg'
      ],
      transform: [
        {
          fn: 'imagemin',
          args: {
            progressive: true
          }
        }
      ]
    };
    peckerBuilder.buildFileAsset(assetOptions, function () {
      expectManifestContainAsset(peckerBuilder, assetOptions);
      expectAssetExists(peckerBuilder, assetOptions);
      done();
    });
  });

  it('should successfully build a simple CSS "file" asset without hash if skipHash = true', function (done) {
    var assetOptions = {
      type: 'file',
      name: 'site.css',
      files: [
        '../support/src/css/site.css'
      ],
      skipHash: true
    };
    peckerBuilder.buildFileAsset(assetOptions, function () {
      expectManifestContainAsset(peckerBuilder, assetOptions);
      expectAssetExists(peckerBuilder, assetOptions);
      done();
    });
  });

  describe('Built-in transforms', function () {

    it('should successfully perform built-in transforms (sass, autoprefixer, clean-css, concat) on a simple SASS "file" asset', function (done) {

      var assetOptions = {
        type: 'file',
        name: 'transformed-site.css',
        files: [
          '../support/src/css/sass-simple.scss'
        ],
        transform: [
          'sass',
          'concat',
          'autoprefixer',
          'clean-css'
        ]
      };
      peckerBuilder.buildFileAsset(assetOptions, function () {
        expectManifestContainAsset(peckerBuilder, assetOptions);
        expectAssetExists(peckerBuilder, assetOptions);
        done();
      });
    });
    it('should successfully perform built-in transforms (sass, autoprefixer, clean-css, concat) on an SASS "file" asset with `@import` directive', function (done) {

      var assetOptions = {
        type: 'file',
        name: 'transformed-site.css',
        files: [
          '../support/src/css/sass-site.scss'
        ],
        transform: [
          {
            fn: 'sass',
            args: {
              includePaths: [ __dirname + '/../support/src/css']
            }
          },
          'concat',
          'autoprefixer',
          'clean-css'
        ]
      };
      peckerBuilder.buildFileAsset(assetOptions, function () {
        expectManifestContainAsset(peckerBuilder, assetOptions);
        expectAssetExists(peckerBuilder, assetOptions);
        done();
      });
    });
    it('should successfully perform built-in transforms (sass) on an SASS "file" asset with `@import` directive in a different directory', function (done) {

      var assetOptions = {
        type: 'file',
        name: 'transformed-site.css',
        files: [
          '../support/src/css/import-flat-ui.scss'
        ],
        transform: [
          {
            fn: 'sass',
            args: {
              includePaths: [
                './../support/src/flat-ui-sass/stylesheets/',
                './../support/src/bourbon/'
              ]
            }
          }
        ]
      };
      peckerBuilder.buildFileAsset(assetOptions, function () {
        expectManifestContainAsset(peckerBuilder, assetOptions);
        expectAssetExists(peckerBuilder, assetOptions);
        done();
      });
    });
    it('should successfully perform built-in transforms (uglify) on a JavaScript "file" asset', function (done) {

      var assetOptions = {
        type: 'file',
        name: 'simple-log.min.js',
        files: [
          '../support/src/js/simple-log.js'
        ],
        transform: [
          'uglify'
        ]
      };
      peckerBuilder.buildFileAsset(assetOptions, function () {
        expectManifestContainAsset(peckerBuilder, assetOptions);
        expectAssetExists(peckerBuilder, assetOptions);
        done();
      });
    });
    it('should successfully perform built-in transforms (imagemin) on a JPG/JPEG "file" asset', function (done) {

      var assetOptions = {
        type: 'file',
        name: 'h6k3jaH.jpg',
        files: [
          '../support/src/images/h6k3jaH.jpg'
        ],
        transform: [
          'imagemin'
        ]
      };
      peckerBuilder.buildFileAsset(assetOptions, function () {
        expectManifestContainAsset(peckerBuilder, assetOptions);
        expectAssetExists(peckerBuilder, assetOptions);
        done();
      });
    });
    it('should successfully perform built-in transforms (imagemin) on a JPG/JPEG "file" asset with options', function (done) {

      var assetOptions = {
        type: 'file',
        name: 'h6k3jaH.jpg',
        files: [
          '../support/src/images/h6k3jaH.jpg'
        ],
        transform: [
          {
            fn: 'imagemin',
            args: {
              progressive: true
            }
          }
        ]
      };
      peckerBuilder.buildFileAsset(assetOptions, function () {
        expectManifestContainAsset(peckerBuilder, assetOptions);
        expectAssetExists(peckerBuilder, assetOptions);
        done();
      });
    });
  });

  afterEach(function () {
    cleanBuildFiles(peckerBuilder);
  });
});


text:
// Copyright © 2015 Mikko Ronkainen <firstname@mikkoronkainen.com>
// License: MIT, see the LICENSE file.

#include "stdafx.h"

#include "Raytracing/Tracers/PathTracer.h"
#include "Raytracing/Scene.h"
#include "Raytracing/Ray.h"
#include "Raytracing/Intersection.h"

using namespace Raycer;

Color PathTracer::trace(const Scene& scene, const Ray& ray, std::mt19937& generator, const std::atomic<bool>& interrupted)
{
	assert(scene.general.pathSampleCount >= 1);

	Color sampledPixelColor;

	for (uint64_t i = 0; i < scene.general.pathSampleCount; ++i)
		sampledPixelColor += traceRecursive(scene, ray, 0, generator, interrupted);

	return sampledPixelColor / double(scene.general.pathSampleCount);
}

Color PathTracer::traceRecursive(const Scene& scene, const Ray& ray, uint64_t iteration, std::mt19937& generator, const std::atomic<bool>& interrupted)
{
	if (interrupted)
		return Color::BLACK;

	if (iteration >= scene.general.maxPathLength)
		return Color::BLACK;

	Intersection intersection;
	std::vector<Intersection> intersections;

	for (Primitive* primitive : scene.primitives.visible)
	{
		intersections.clear();
		primitive->intersect(ray, intersection, intersections);
	}

	if (!intersection.wasFound)
		return Color::BLACK;

	Material* material = intersection.primitive->material;

	if (material->isEmissive)
	{
		Color emittance = material->emittance;

		if (material->emittanceMapTexture != nullptr)
			emittance = material->emittanceMapTexture->getColor(intersection.texcoord, intersection.position) * material->emittanceMapTexture->intensity;

		return emittance;
	}

	Sampler* sampler = samplers[SamplerType::RANDOM].get();
	Vector3 newDirection = sampler->getHemisphereSample(intersection.onb, 1.0, 0, 0, 1, 1, 0, generator);

	Ray newRay;
	newRay.origin = intersection.position + newDirection * scene.general.rayStartOffset;
	newRay.direction = newDirection;
	newRay.precalculate();

	Color reflectance = material->diffuseReflectance;

	if (material->diffuseMapTexture != nullptr)
		reflectance = material->diffuseMapTexture->getColor(intersection.texcoord, intersection.position) * material->diffuseMapTexture->intensity;

	double alpha = std::abs(newDirection.dot(intersection.normal));
	Color brdf = 2.0 * reflectance * alpha;
	Color reflected = traceRecursive(scene, newRay, iteration + 1, generator, interrupted);

	return brdf * reflected;
}


text:
/*
 * Created by IntelliJ IDEA.
 * User: max
 * Date: Nov 4, 2001
 * Time: 5:19:35 PM
 */
package com.intellij.codeInspection.ui;

import com.intellij.codeInspection.CommonProblemDescriptor;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ex.DescriptorProviderInspection;
import com.intellij.codeInspection.ex.InspectionTool;
import com.intellij.codeInspection.reference.RefElement;
import com.intellij.codeInspection.reference.RefEntity;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.profile.codeInspection.ui.InspectionsConfigTreeComparator;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.TreeToolTipHandler;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;

public class InspectionTree extends Tree {
  private final HashSet<Object> myExpandedUserObjects;
  private SelectionPath mySelectionPath;
  private static final RefEntity[] EMPTY_ELEMENTS_ARRAY = new RefEntity[0];
  private static final ProblemDescriptor[] EMPTY_DESCRIPTORS = new ProblemDescriptor[0];

  public InspectionTree(final Project project) {
    super(new InspectionRootNode(project));

    setCellRenderer(new CellRenderer());//project));
    setShowsRootHandles(true);
    UIUtil.setLineStyleAngled(this);
    addTreeWillExpandListener(new ExpandListener());

    myExpandedUserObjects = new HashSet<Object>();
    myExpandedUserObjects.add(project);

    TreeToolTipHandler.install(this);
    TreeUtil.installActions(this);
    new TreeSpeedSearch(this, new Convertor<TreePath, String>() {
      public String convert(TreePath o) {
        return InspectionsConfigTreeComparator.getDisplayTextToSort(o.getLastPathComponent().toString());
      }
    });

    addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent e) {
        TreePath newSelection = e.getNewLeadSelectionPath();
        if (newSelection != null) {
          mySelectionPath = new SelectionPath(newSelection);
        }
      }
    });
  }

  public void removeAllNodes() {
    getRoot().removeAllChildren();
    nodeStructureChanged(getRoot());
  }

  public InspectionTreeNode getRoot() {
    return (InspectionTreeNode)getModel().getRoot();
  }

  @Nullable
  public InspectionTool getSelectedTool() {
    final TreePath[] paths = getSelectionPaths();
    if (paths == null) return null;
    InspectionTool tool = null;
    for (TreePath path : paths) {
      Object[] nodes = path.getPath();
      for (int j = nodes.length - 1; j >= 0; j--) {
        Object node = nodes[j];
        if (node instanceof InspectionNode) {
          if (tool == null) {
            tool = ((InspectionNode)node).getTool();
          }
          else if (tool != ((InspectionNode)node).getTool()) {
            return null;
          }
          break;
        }
      }
    }

    return tool;
  }

  @NotNull
  public RefEntity[] getSelectedElements() {
    TreePath[] selectionPaths = getSelectionPaths();
    if (selectionPaths != null) {
      final InspectionTool selectedTool = getSelectedTool();
      if (selectedTool == null) return EMPTY_ELEMENTS_ARRAY;

      List<RefEntity> result = new ArrayList<RefEntity>();
      for (TreePath selectionPath : selectionPaths) {
        final InspectionTreeNode node = (InspectionTreeNode)selectionPath.getLastPathComponent();
        addElementsInNode(node, result);
      }
      return result.toArray(new RefEntity[result.size()]);
    }
    return EMPTY_ELEMENTS_ARRAY;
  }

  private static void addElementsInNode(InspectionTreeNode node, List<RefEntity> out) {
    if (!node.isValid()) return;
    if (node instanceof RefElementNode) {
      final RefEntity element = ((RefElementNode)node).getElement();
      if (!out.contains(element)) {
        out.add(0, element);
      }
    }
    if (node instanceof ProblemDescriptionNode) {
      final RefEntity element = ((ProblemDescriptionNode)node).getElement();
      if (!out.contains(element)) {
        out.add(0, element);
      }
    }
    final Enumeration children = node.children();
    while (children.hasMoreElements()) {
      InspectionTreeNode child = (InspectionTreeNode)children.nextElement();
      addElementsInNode(child, out);
    }
  }

  public CommonProblemDescriptor[] getSelectedDescriptors() {
    final InspectionTool tool = getSelectedTool();
    if (getSelectionCount() == 0 || !(tool instanceof DescriptorProviderInspection)) return EMPTY_DESCRIPTORS;
    final TreePath[] paths = getSelectionPaths();
    final List<CommonProblemDescriptor> descriptors = new ArrayList<CommonProblemDescriptor>();
    for (TreePath path : paths) {
      Object node = path.getLastPathComponent();
      traverseDescriptors((InspectionTreeNode)node, descriptors);
    }
    return descriptors.toArray(new CommonProblemDescriptor[descriptors.size()]);
  }

  private static void traverseDescriptors(InspectionTreeNode node, List<CommonProblemDescriptor> descriptors){
    if (node instanceof ProblemDescriptionNode) {
      descriptors.add(((ProblemDescriptionNode)node).getDescriptor());
    }
    for(int i = node.getChildCount() - 1; i >= 0; i--){
      traverseDescriptors((InspectionTreeNode)node.getChildAt(i), descriptors);
    }
  }

  private void nodeStructureChanged(InspectionTreeNode node) {
    ((DefaultTreeModel)getModel()).nodeStructureChanged(node);
  }

  private class ExpandListener implements TreeWillExpandListener {
    public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
      final InspectionTreeNode node = (InspectionTreeNode)event.getPath().getLastPathComponent();
      myExpandedUserObjects.add(node.getUserObject());
      if (node instanceof RefElementNode && !node.children().hasMoreElements()) {
        sortChildren(node);
      }

      // Smart expand
      if (node.getChildCount() == 1) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          public void run() {
            expandPath(new TreePath(node.getPath()));
          }
        });
      }
    }

    public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
      InspectionTreeNode node = (InspectionTreeNode)event.getPath().getLastPathComponent();
      myExpandedUserObjects.remove(node.getUserObject());
    }
  }

  public void restoreExpantionAndSelection() {
    restoreExpantion();
    if (mySelectionPath != null) {
      mySelectionPath.restore();
    }
  }

  private void restoreExpantion() {
    restoreExpantionStatus((InspectionTreeNode)getModel().getRoot());
  }

  private void restoreExpantionStatus(InspectionTreeNode node) {
    if (myExpandedUserObjects.contains(node.getUserObject())) {
      TreeNode[] pathToNode = node.getPath();
      expandPath(new TreePath(pathToNode));
      Enumeration children = node.children();
      while (children.hasMoreElements()) {
        InspectionTreeNode childNode = (InspectionTreeNode)children.nextElement();
        restoreExpantionStatus(childNode);
      }
    }
  }

  private static class CellRenderer extends ColoredTreeCellRenderer {
    /*  private Project myProject;
      InspectionManagerEx myManager;
      public CellRenderer(Project project) {
        myProject = project;
        myManager = (InspectionManagerEx)InspectionManager.getInstance(myProject);
      }*/

    public void customizeCellRenderer(JTree tree,
                                      Object value,
                                      boolean selected,
                                      boolean expanded,
                                      boolean leaf,
                                      int row,
                                      boolean hasFocus) {
      InspectionTreeNode node = (InspectionTreeNode)value;

      append(node.toString(),
             patchAttr(node, appearsBold(node) ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : getMainForegroundAttributes(node)));

      int problemCount = node.getProblemCount();
      if (!leaf) {
        append(" " + InspectionsBundle.message("inspection.problem.descriptor.count", problemCount), patchAttr(node, SimpleTextAttributes.GRAYED_ATTRIBUTES));
      }

      if (!node.isValid()) {
        append(" " + InspectionsBundle.message("inspection.invalid.node.text"), patchAttr(node, SimpleTextAttributes.ERROR_ATTRIBUTES));
      } else {
        setIcon(node.getIcon(expanded));
      }
    }

    public static SimpleTextAttributes patchAttr(InspectionTreeNode node, SimpleTextAttributes attributes) {
      if (node.isResolved()) {
        return new SimpleTextAttributes(attributes.getBgColor(), attributes.getFgColor(), attributes.getWaveColor(), attributes.getStyle() | SimpleTextAttributes.STYLE_STRIKEOUT);
      }
      return attributes;
    }

    private static SimpleTextAttributes getMainForegroundAttributes(InspectionTreeNode node) {
      SimpleTextAttributes foreground = SimpleTextAttributes.REGULAR_ATTRIBUTES;
      if (node instanceof RefElementNode) {
        RefEntity refElement = ((RefElementNode)node).getElement();

        if (refElement instanceof RefElement) {
          refElement = ((RefElement)refElement).getContainingEntry();
          if (((RefElement)refElement).isEntry() && ((RefElement)refElement).isPermanentEntry()) {
            foreground = new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, Color.blue);
          }
        }

      }
      final FileStatus nodeStatus = node.getNodeStatus();
      if (nodeStatus != FileStatus.NOT_CHANGED){
        foreground = new SimpleTextAttributes(foreground.getBgColor(), nodeStatus.getColor(), foreground.getWaveColor(), foreground.getStyle());
      }
      return foreground;
    }

    private static boolean appearsBold(Object node) {
      return ((InspectionTreeNode)node).appearsBold();
    }
  }

  public void sort() {
    sortChildren(getRoot());
  }

  private static void sortChildren(InspectionTreeNode node) {
    TreeUtil.sort(node, InspectionResultsViewComparator.getInstance());
  }

  private class SelectionPath {
    private final Object[] myPath;
    private final int[] myIndicies;

    public SelectionPath(TreePath path) {
      myPath = path.getPath();
      myIndicies = new int[myPath.length];
      for (int i = 0; i < myPath.length - 1; i++) {
        InspectionTreeNode node = (InspectionTreeNode)myPath[i];
        myIndicies[i + 1] = getChildIndex(node, (InspectionTreeNode)myPath[i + 1]);
      }
    }

    private int getChildIndex(InspectionTreeNode node, InspectionTreeNode child) {
      int idx = 0;
      Enumeration children = node.children();
      while (children.hasMoreElements()) {
        InspectionTreeNode ch = (InspectionTreeNode)children.nextElement();
        if (ch == child) break;
        idx++;
      }
      return idx;
    }

    public void restore() {
      getSelectionModel().removeSelectionPaths(getSelectionModel().getSelectionPaths());
      TreeUtil.selectPath(InspectionTree.this, restorePath());
    }

    private TreePath restorePath() {
      ArrayList<Object> newPath = new ArrayList<Object>();

      newPath.add(getModel().getRoot());
      restorePath(newPath, 1);

      return new TreePath(newPath.toArray(new InspectionTreeNode[newPath.size()]));
    }

    private void restorePath(ArrayList<Object> newPath, int idx) {
      if (idx >= myPath.length) return;
      InspectionTreeNode oldNode = (InspectionTreeNode)myPath[idx];

      InspectionTreeNode newRoot = (InspectionTreeNode)newPath.get(idx - 1);

      InspectionResultsViewComparator comparator = InspectionResultsViewComparator.getInstance();
      Enumeration children = newRoot.children();
      while (children.hasMoreElements()) {
        InspectionTreeNode child = (InspectionTreeNode)children.nextElement();
        if (comparator.compare(child, oldNode) == 0) {
          newPath.add(child);
          restorePath(newPath, idx + 1);
          return;
        }
      }

      // Exactly same element not found. Trying to select somewhat near.
      int count = newRoot.getChildCount();
      if (count > 0) {
        if (myIndicies[idx] < count) {
          newPath.add(newRoot.getChildAt(myIndicies[idx]));
        }
        else {
          newPath.add(newRoot.getChildAt(count - 1));
        }
      }
    }
  }
}


text:
package com.laxture.lib.util;

import java.util.HashMap;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;

public class ContactsUtil {

    private static final String[] PROJECTION_CONTACT = {
        Contacts._ID,
        Contacts.DISPLAY_NAME,
    };

    private static final String[] PROJECTION_PHONE = {
        Phone.TYPE,
        Phone.NUMBER
    };

    private ContactsUtil() {}

    public static HashMap<String, String> resolvePhoneNumber(Context context, Uri uri) {
        HashMap<String, String> phoneList = new HashMap<String, String>();
        Cursor cursor = context.getContentResolver().query(uri, PROJECTION_CONTACT, null, null, null);
        if (cursor.moveToFirst()) {
            String contactId = cursor.getString(cursor.getColumnIndexOrThrow(Contacts._ID));
            String contactName = cursor.getString(cursor.getColumnIndexOrThrow(Contacts.DISPLAY_NAME));
            LLog.d("Selected Contact id/name :: %s/%s", contactId, contactName);

            Cursor phoneCursor = context.getContentResolver().query(Phone.CONTENT_URI, PROJECTION_PHONE,
                    Phone.CONTACT_ID+"="+contactId, null, null);
            while (phoneCursor.moveToNext()) {
                int type = phoneCursor.getInt(phoneCursor.getColumnIndexOrThrow(Phone.TYPE));
                String typeLabel = Phone.getTypeLabel(context.getResources(), type, "Unknow").toString();
                phoneList.put(typeLabel, phoneCursor.getString(phoneCursor.getColumnIndexOrThrow(Phone.NUMBER)));
            }
            phoneCursor.close();
        }
        cursor.close();

        return phoneList;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="pluginSchema"
xmlns:gml="http://www.opengis.net/gml"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="pluginSchema /data/capabilities/validate/pluginSchema.xsd">
    <name>Geometry Disjoint Geometry</name>
    <description> A Geometry is disjoint from another Geometry.</description>
    <class>
        org.geotools.validation.spatial.relate.DisjointIntegrity
    </class>
</plugin>


text:
module CSI
  module Plugins
    # This plugin is used for interacting with a SonMicro
    # SM132 USB RFID Reader / Writer (PCB v3)
    module SonMicroRFID
      # Supported Method Parameters::
      # son_micro_rfid_obj = CSI::Plugins::SonMicroRFID.connect(
      #   block_dev: 'optional - serial block device path (defaults to /dev/ttyUSB0)',
      #   baud: 'optional - (defaults to 9600)',
      #   data_bits: 'optional - (defaults to 8)',
      #   stop_bits: 'optional - (defaults to 1)',
      #   parity: 'optional - (defaults to SerialPort::NONE)',
      #   flow_control: 'optional - (defaults to SerialPort::HARD) SerialPort::NONE|SerialPort::SOFT|SerialPort::HARD'
      # )

      public_class_method def self.connect(opts = {})
        # Default Baud Rate for this Device is 19200
        opts[:baud] = 19200 if opts[:baud].nil?
        son_micro_rfid_obj = CSI::Plugins::Serial.connect(opts)
      rescue StandardError => e
        disconnect(son_micro_rfid_obj: son_micro_rfid_obj) unless son_micro_rfid_obj.nil?
        raise e
      end

      # Supported Method Parameters::
      #  cmds = CSI::Plugins::SonMicroRFID.list_cmds
      public_class_method def self.list_cmds
        # Returns an Array of Symbols
        cmds = %i[
          reset
          firmware
          seek_for_tag
          select_tag
          authenticate
          read_block
          write_block
          write_value
          write_four_byte_block
          write_key
          increment
          decrement
          antenna_power
          read_port
          write_port
          halt
          set_baud_rate
          sleep
          poll_buffer
        ]
      rescue StandardError => e
        raise e
      end

      # Supported Method Parameters::
      #  params = CSI::Plugins::SonMicroRFID.list_params(
      #   cmd: 'required - cmd returned from #list_cmds method',
      # )
      public_class_method def self.list_params(opts = {})
        cmd = opts[:cmd].to_s.scrub.strip.chomp

        case cmd.to_sym
        when :reset
          params = %i[no_params_implemented]
        when :firmware
          params = %i[no_params_implemented]
        when :seek_for_tag
          params = %i[no_params_required]
        when :select_tag
          params = %i[no_params_required]
        when :authenticate
          params = %i[no_params_implemented]
        when :read_block
          params = %i[no_params_implemented]
        when :write_block
          params = %i[no_params_implemented]
        when :write_value
          params = %i[no_params_implemented]
        when :write_four_byte_block
          params = %i[no_params_implemented]
        when :write_key
          params = %i[no_params_implemented]
        when :increment
          params = %i[no_params_implemented]
        when :decrement
          params = %i[no_params_implemented]
        when :antenna_power
          params = %i[off on reset]
        when :read_port
          params = %i[no_params_implemented]
        when :write_port
          params = %i[no_params_implemented]
        when :halt
          params = %i[no_params_implemented]
        when :set_baud_rate
          params = %i[no_params_implemented]
        when :sleep
          params = %i[no_params_implemented]
        when :poll_buffer
          params = %i[no_params_implemented]
        else
          raise "Unsupported Command: #{cmd}.  Supported commands are:\n#{list_cmds}\n\n\n"
        end

        params
      rescue StandardError => e
        raise e
      end

      # Supported Method Parameters::
      # cmd_response_arr = get_cmd_responses(
      #   son_micro_rfid_obj: 'required - son_micro_rfid_obj returned from #connect method'
      # )

      public_class_method def self.get_cmd_responses(opts = {})
        son_micro_rfid_obj = opts[:son_micro_rfid_obj]

        raw_byte_arr = CSI::Plugins::Serial.dump_session_data(
          serial_obj: son_micro_rfid_obj
        )

        hex_esc_raw_resp = ''
        raw_byte_arr.each do |byte|
          # this_byte = "\s#{byte.unpack1('H*')}"
          this_byte = byte.unpack1('H*')
          # Needed when #unpack1 returns 2 bytes instead of one
          # e.g."ް" translates to deb0 (that's not a double quote ")
          # instead of de b0
          # this condition is ghetto-hacker-ish.
          if this_byte.length == 4
            byte_one = this_byte[1..2]
            byte_two = this_byte[-2..-1]
            hex_esc_raw_resp = "#{hex_esc_raw_resp}\s#{byte_one}"
            hex_esc_raw_resp = "#{hex_esc_raw_resp}\s#{byte_two}"
          else
            hex_esc_raw_resp = "#{hex_esc_raw_resp}\s#{this_byte}"
          end
        end

        # Return command response array in space-delimited hex
        cmd_response_arr = hex_esc_raw_resp.upcase.strip.split(/(?=FF)/)
        cmd_response_arr.map(&:strip)
      rescue StandardError => e
        # Flush Responses for Next Request
        CSI::Plugins::Serial.flush_session_data(
          serial_obj: son_micro_rfid_obj
        )

        raise e
      end

      # Supported Method Parameters::
      # parsed_cmd_resp_arr = parse_cmd_resp(
      #   cmd_resp: 'required - command response string'
      # )

      private_class_method def self.parse_responses(opts = {})
        son_micro_rfid_obj = opts[:son_micro_rfid_obj]
        cmd = opts[:cmd].to_s.scrub.strip.chomp

        keep_parsing_responses = true
        next_response_detected = false
        all_cmd_responses = []
        a_cmd_r_len = 0
        last_a_cmd_r_len = 0

        parsed_cmd_resp_arr = []
        bytes_in_cmd_resp = 0
        cmd_resp = ''

        # Parse All Responses and add them to parsed_cmd_resp_arr
        while keep_parsing_responses
          until next_response_detected
            print '.'
            all_cmd_responses = get_cmd_responses(
              son_micro_rfid_obj: son_micro_rfid_obj
            )
            cmd_resp = all_cmd_responses.last
            bytes_in_cmd_resp = cmd_resp.split.length if cmd_resp
            a_cmd_r_len = all_cmd_responses.length

            next_response_detected = true if bytes_in_cmd_resp > 3 &&
                                             a_cmd_r_len > last_a_cmd_r_len
          end
          next_response_detected = false
          last_a_cmd_r_len = a_cmd_r_len
          print "\n"

          # Third byte
          expected_cmd_resp_byte_len = cmd_resp.split[2].to_i(16) + 4

          # Fourth byte
          cmd_hex = cmd_resp.split[3]

          while bytes_in_cmd_resp < expected_cmd_resp_byte_len
            all_cmd_responses = get_cmd_responses(
              son_micro_rfid_obj: son_micro_rfid_obj
            )

            cmd_resp = all_cmd_responses.last
            bytes_in_cmd_resp = cmd_resp.split.length
            puts "EXPECTED CMD BYTE LEN: #{expected_cmd_resp_byte_len}"
            puts "LAST CMD BYTE LEN: #{bytes_in_cmd_resp} >>>"
            puts all_cmd_responses
            puts "COMMAND HEX: #{cmd_hex}\n\n\n"
          end

          puts "\nALL CMD RESPS >>>"
          puts "#{all_cmd_responses}\n\n\n"

          parsed_cmd_resp_hash = {}
          parsed_cmd_resp_hash[:hex_resp] = cmd_resp
          parsed_cmd_resp_hash[:cmd_hex] = cmd_hex
          parsed_cmd_resp_hash[:cmd_desc] = cmd.to_sym
          resp_code = '?'

          # TODO: Detect EMV
          case cmd_hex
          when '82', '83'
            resp_code = cmd_resp.split[4]
            parsed_cmd_resp_hash[:resp_code_hex] = resp_code
            case resp_code
            when '01'
              parsed_cmd_resp_hash[:resp_code_desc] = :mifare_ultralight
              parsed_cmd_resp_hash[:tag_id] = cmd_resp.split[5..-2].join(
                ' '
              )
            when '02'
              parsed_cmd_resp_hash[:resp_code_desc] = :mifare_classic_1k
              parsed_cmd_resp_hash[:tag_id] = cmd_resp.split[5..-2].join(
                ' '
              )
            when '03'
              parsed_cmd_resp_hash[:resp_code_desc] = :mifare_classic_4k
              parsed_cmd_resp_hash[:tag_id] = cmd_resp.split[5..-2].join(
                ' '
              )
            when '4C'
              parsed_cmd_resp_hash[:resp_code_desc] = :seeking_tag
              parsed_cmd_resp_hash[:tag_id] = :seeking_tag
            when '4E'
              parsed_cmd_resp_hash[:resp_code_desc] = :no_tag_present
              parsed_cmd_resp_hash[:tag_id] = :not_available
            when '55'
              parsed_cmd_resp_hash[:resp_code_desc] = :antenna_off
              parsed_cmd_resp_hash[:tag_id] = :not_available
            when 'FF'
              parsed_cmd_resp_hash[:resp_code_desc] = :unknown_tag_type
              parsed_cmd_resp_hash[:tag_id] = cmd_resp.split[5..-2].join(
                ' '
              )
            else
              parsed_cmd_resp_hash[:resp_code_desc] = :unknown_resp_code
              parsed_cmd_resp_hash[:tag_id] = :not_available
            end
          else
            parsed_cmd_resp_hash[:cmd_desc] = :not_available
          end

          keep_parsing_responses = false unless resp_code == '4C'

          parsed_cmd_resp_arr.push(parsed_cmd_resp_hash)
        end

        parsed_cmd_resp_arr
      rescue StandardError => e
        raise e
      ensure
        # Flush Responses for Next Request
        CSI::Plugins::Serial.flush_session_data(
          serial_obj: son_micro_rfid_obj
        )
      end

      # Supported Method Parameters::
      #  CSI::Plugins::SonMicroRFID.exec(
      #   son_micro_rfid_obj: 'required - son_micro_rfid_obj returned from #connect method'
      #   cmd: 'required - cmd returned from #list_cmds method',
      #   params: 'optional - parameters for specific command returned from #list_params method'
      # )
      public_class_method def self.exec(opts = {})
        son_micro_rfid_obj = opts[:son_micro_rfid_obj]
        cmd = opts[:cmd].to_s.scrub.strip.chomp
        params = opts[:params].to_s.scrub.strip.chomp

        params_bytes = []

        # Use the Mifare Panel Application to reverse enginner commands.
        case cmd.to_sym
        when :reset
          cmd_bytes = [0xFF, 0x00, 0x01, 0x80, 0x81]
        when :firmware
          cmd_bytes = [0xFF, 0x00, 0x01, 0x81, 0x82]
        when :seek_for_tag
          cmd_bytes = [0xFF, 0x00, 0x01, 0x82, 0x83]
        when :select_tag
          cmd_bytes = [0xFF, 0x00, 0x01, 0x83, 0x84]
        when :authenticate
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :read_block
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :write_block
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :write_value
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :write_four_byte_block
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :write_key
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :increment
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :decrement
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :antenna_power
          cmd_bytes = [0xFF, 0x00, 0x02, 0x90]
          case params.to_sym
          when :off
            params_bytes = [0x00, 0x92]
          when :on
            params_bytes = [0x01, 0x93]
          when :reset
            params_bytes = [0x02, 0x94]
          else
            raise "Unsupported Parameters: #{params} for #{cmd}.  Supported parameters for #{cmd} are:\n#{list_params(cmd: cmd)}\n\n\n"
          end
        when :read_port
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :write_port
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :halt
          cmd_bytes = [0xFF, 0x00, 0x01, 0x93, 0x94]
        when :set_baud_rate
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :sleep
          cmd_bytes = [0xFF, 0x00, 0x01]
        when :poll_buffer
          cmd_bytes = [0xFF, 0x00, 0x01, 0xB0, 0xB1]
        else
          raise "Unsupported Command: #{cmd}.  Supported commands are:\n#{list_cmds}\n\n\n"
        end

        # If parameters to a command are set, append them.
        cmd_bytes += params_bytes unless params_bytes.empty?
        # Execute the command.
        cmd_bytes.each do |byte|
          son_micro_rfid_obj[:serial_conn].putc(byte)
        end

        # Parse commands response(s).
        # Return an array of hashes.
        parse_responses(
          son_micro_rfid_obj: son_micro_rfid_obj,
          cmd: cmd.to_sym
        )
      rescue StandardError => e
        raise e
      ensure
        # Flush Responses for Next Request
        CSI::Plugins::Serial.flush_session_data(
          serial_obj: son_micro_rfid_obj
        )
      end

      # Supported Method Parameters::
      # CSI::Plugins::SonMicroRFID.disconnect(
      #   son_micro_rfid_obj: 'required - son_micro_rfid_obj returned from #connect method'
      # )

      public_class_method def self.disconnect(opts = {})
        CSI::Plugins::Serial.disconnect(
          serial_obj: opts[:son_micro_rfid_obj]
        )
      rescue StandardError => e
        raise e
      end

      # Author(s):: Jacob Hoopes <jake.hoopes@gmail.com>

      public_class_method def self.authors
        "AUTHOR(S):
          Jacob Hoopes <jake.hoopes@gmail.com>
        "
      end

      # Display Usage for this Module

      public_class_method def self.help
        puts "USAGE:
          son_micro_rfid_obj = #{self}.connect(
            block_dev: 'optional serial block device path (defaults to /dev/ttyUSB0)',
            baud: 'optional (defaults to 9600)',
            data_bits: 'optional (defaults to 8)',
            stop_bits: 'optional (defaults to 1)',
            parity: 'optional (defaults to SerialPort::NONE)',
            flow_control: 'optional (defaults to SerialPort::NONE)'
          )

          cmds = #{self}.list_cmds

          params = #{self}.list_params(
            cmd: 'required - cmd returned from #list_cmds method',
          )

          parsed_cmd_resp_arr = #{self}.exec(
            son_micro_rfid_obj: 'required son_micro_rfid_obj returned from #connect method',
            cmd: 'required - cmd returned from #list_cmds method',
            params: 'optional - parameters for specific command returned from #list_params method'
          )

          #{self}.disconnect(
            son_micro_rfid_obj: 'required son_micro_rfid_obj returned from #connect method'
          )

          #{self}.authors
        "
      end
    end
  end
end