text:
'use strict';

const _ = require('lodash');
const handlers = require('./handlers');
const Problems = require('../../classes/Dynatrace/Problems');

function groupEvents(problem) {
  return _.groupBy(problem.rankedEvents, e => e.eventType);
}

class ProblemDetails {
  constructor(davis, options) {
    this.davis = davis;
    this.options = options;

    this.intents = {
      problemDetails: {
        skipHelp: true,
        usage: 'Problem details',
        examples: [
          'Tell me about the third problem.',
        ],
        phrases: [

        ],
        lifecycleEvents: [
          'problemDetails',
        ],
        clarification: 'I think you were asking about problem details.',
      },
    };

    this.hooks = {
      'problemDetails:problemDetails': this.problemDetails.bind(this),
    };
  }

  problemDetails(exchange, context) {
    const problems = context.problems;
    let choice = context.choice;
    let idx = -1;

    if (exchange.selected) {
      return this.reply(exchange, exchange.selected, context);
    }

    if (exchange.button) {
      const pid = context.button.value;

      if (pid === 'no') {
        choice = false;
      } else if (pid === 'yes') {
        choice = true;
      } else {
        return this.reply(exchange, pid, context);
      }
    }

    if (_.isNumber(choice)) {
      if (choice < problems.length) {
        idx = choice;
      } else {
        return exchange.response("There weren't that many problems.");
      }
    } else if (_.isBoolean(choice)) {
      if (!choice) {
        return exchange.response('OK, no problem.').end();
      } else if (problems.length === 1) {
        idx = 0;
      } else {
        return exchange.response('Which problem would you like to hear about?').skipFollowUp();
      }
    } else if (_.isString(choice)) {
      if (choice === 'middle') {
        idx = (problems.length / 2).toFixed() - 1;
      } else if (choice === 'last') {
        idx = problems.length - 1;
      }
    }

    if (idx !== -1) {
      const pid = problems[idx].id;
      return this.reply(exchange, pid, context);
    }

    return exchange.response("I'm not sure what problem you were trying to choose.").skipFollowUp();
  }

  reply(exchange, pid, context) {
    const paging = context.paging;
    const VB = this.davis.classes.VB;
    const th = this.davis.textHelpers;

    exchange.addContext({ pid });

    return this.davis.dynatrace.problemDetails(pid) // eslint-disable-line
      .then((problem) => {
        const say = [];
        const show = new VB.Message()
          .addText('Below are the problem details you requested');

        // Create cards for ranked events
        problem.groupedEvents = groupEvents(problem);
        const eventTypes = Object.keys(problem.groupedEvents);
        const roots = problem
          .rankedEvents
          .filter(e => e.isRootCause);

        const rootEventTypes = roots
          .map(e => e.eventType)
          .filter((value, i, self) => self.indexOf(value) === i);

        const impactLevel = problem.impactLevel;
        const titleEvent = _.find(problem.rankedEvents, { impactLevel });
        const eventType = titleEvent.eventType;
        say.push(`There is ${th.friendlyEventFirstAlias(eventType)}`);

        const events = _.map(eventTypes, (e) => {
          const base = handlers.DEFAULT(problem.groupedEvents[e]);
          const handler = _.get(handlers, e);
          if (handler) {
            const out = handler(problem.groupedEvents[e], base);
            out.show.setLink(this.davis.linker.event(problem, problem.groupedEvents[e][0]));
            return out;
          }
          this.davis.logger.debug(`No handler for ${e}. Using default.`);

          base.show.setLink(this.davis.linker.event(problem, problem.groupedEvents[e][0]));

          return base;
        });

        const rootEvents = _.map(rootEventTypes, (e) => {
          const base = handlers.DEFAULT(problem.groupedEvents[e]);
          const handler = _.get(handlers, e);
          if (handler) {
            const out = handler(problem.groupedEvents[e], base);
            out.show.setLink(this.davis.linker.event(problem, problem.groupedEvents[e][0]));
            return out;
          }
          this.davis.logger.debug(`No handler for ${e}. Using default.`);

          base.show.setLink(this.davis.linker.event(problem, problem.groupedEvents[e][0]));

          return base;
        });

        const eventCards = events.map(e => e.show);
        const eventSays = events.map(e => e.say);
        const rootEventSays = rootEvents.map(e => e.say);

        const summaryCard = new VB.Card()
          .setColor(problem.status)
          .addTitle(Problems.title(problem, this.davis))
          .setLink(this.davis.linker.problem(problem))
          .addField('Time Frame', new VB.TimeRange(problem, exchange.user.timezone, true), false);

        const affectedApps = this.affectedApps(problem, context);

        if (affectedApps.length > 0) {
          summaryCard
            .addField(
                'Applications Affected',
                affectedApps.map(e => e.display.visual)
                  .join('\n'),
                false);

          const sayApps = affectedApps.map(e => e.display.audible);
          if (problem.status === 'OPEN') {
            say.push('that is affecting');
          } else {
            say.push('that affected');
          }
          say.push(`${th.humanList(sayApps, 3)}`);
          if (affectedApps.length > 3) {
            say.push(`, and ${affectedApps.length - 3} other event types`);
          }
        }

        say.push(new VB.TimeRange(problem, exchange.user.timezone), '.');

        if (rootEventSays.length === 1) {
          say.push('The root cause was');
          say.push(rootEventSays[0]);

          if (eventSays.length - rootEventSays.length > 0) {
            say.push(', but there were', eventSays.length - rootEventSays.length, 'other event types as well.');
          } else {
            say.push('.');
          }
        } else if (rootEventSays.length > 1) {
          say.push('The root causes were');
          say.push(th.humanList(rootEventSays));

          if (eventSays.length - rootEventSays.length > 0) {
            say.push(', but there were', eventSays.length - rootEventSays.length, 'other event types as well.');
          } else {
            say.push('.');
          }
        }

        show
          .addCard(summaryCard)
          .addCard(eventCards);

        if (exchange.eligibleToPushLink()) {
          exchange.followUp('Would you like me to show you this problem in your browser?')
            .addContext({ targetIntent: 'pushLink' });
        } else if (context.paging) {
          exchange.followUp('Would you like to go back to the list?')
            .addContext({ targetIntent: 'showPage' });
        }

        if (paging && paging.intent === 'problemDetails') {
          const buttons = new VB.ButtonGroup('pageRoute')
            .addAction('Back', 'Back to List', paging.index);

          show.setButtons(buttons);
        }

        //if (roots.length === 0) {
          //exchange
            //.setLinkUrl(this.davis.linker.event(problem, problem.rankedEvents[0]));
        //} else {
        exchange
          .setLinkUrl(this.davis.linker.problem(problem));

        exchange
          .addContext({
            problem,
          })
          .response({ show: show.slack(), say: VB.stringify(say) }).smartEnd();
      });
  }

  affectedApps(problem, context) {
    const impactedEntities = problem.rankedEvents.map(e => e.entityId);
    const impactedApps = context.entities.applications.filter(e =>
        impactedEntities.indexOf(e.entityId) !== -1);
    return impactedApps; // .map(e => e.display.visual);
  }
}

module.exports = ProblemDetails;


text:
module ES6ModuleMapper
  class Processor
    VERSION = '1'

    def self.call(input)
      key = [VERSION, input[:data]]
      input[:cache].fetch(key) do
        new(input).transform
      end
    end

    def initialize(input)
      @environment  = input[:environment]
      @load_path    = input[:load_path]
      @name         = input[:name]
      @dirname      = File.dirname(input[:filename])
      @content_type = input[:content_type]

      @logger = @environment.logger

      @input_data = input[:data]

      @required = Set.new(input[:metadata][:required])
    end

    def transform
      @logger.info "Parsing #{@name}"
      {
        data: @input_data,
        required: @required,
        import_mapping: parse_imports,
      }
    rescue => e
      @logger.debug "Failed to parse #{@name}"
      raise e
    end

    private

    def parse_imports
      @input_data.scan(/^import .*$/).inject({}) do |imports, line|
        lookup_name = line.match(/from[^'"]+(['"])([^\1]+)\1/)[2]
        uri, _ = resolve(lookup_name, accept: @content_type, pipeline: "self", compat: false)
        if uri.nil?
          raise "Failed to parse #{@name}: #{lookup_name} not found"
        end
        @required << uri
        name = @environment.load(uri).to_hash[:name]
        imports[lookup_name] = name
        imports
      end
    end

    def resolve(path, options = {})
      if @environment.absolute_path?(path)
        raise Sprockets::FileOutsidePaths, "can't require absolute file: #{path}"
      elsif @environment.relative_path?(path)
        path = expand_relative_path(path)
        if logical_path = @environment.split_subpath(@load_path, path)
          if filename = @environment.resolve(logical_path, options.merge(load_paths: [@load_path]))
            filename
          else
            accept = options[:accept]
            message = "couldn't find file '#{logical_path}' under '#{@load_path}'"
            message << " with type '#{accept}'" if accept
            raise Sprockets::FileNotFound, message
          end
        else
          raise Sprockets::FileOutsidePaths, "#{path} isn't under path: #{@load_path}"
        end
      else
        filename = @environment.resolve(path, options)
      end

      if filename
        filename
      else
        accept = options[:accept]
        message = "couldn't find file '#{path}'"
        message << " with type '#{accept}'" if accept
        raise Sprockets::FileNotFound, message
      end
    end

    def expand_relative_path(path)
      File.expand_path(path, @dirname)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*
Package ring implements a simple ring CRDT.
*/
package ring

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"math/rand"
	"sort"
	"time"

	"github.com/weaveworks/mesh"

	"github.com/weaveworks/weave/common"
	"github.com/weaveworks/weave/net/address"
)

// Ring represents the ring itself
type Ring struct {
	Start, End address.Address // [min, max) tokens in this ring.  Due to wrapping, min == max (effectively)
	Peer       mesh.PeerName   // name of peer owning this ring instance
	Entries    entries         // list of entries sorted by token
	Seeds      []mesh.PeerName // peers with which the ring was seeded
}

func (r *Ring) assertInvariants() {
	err := r.checkInvariants()
	if err != nil {
		panic(err.Error())
	}
}

// Errors returned by Merge
var (
	ErrNotSorted       = errors.New("Ring not sorted")
	ErrTokenRepeated   = errors.New("Token appears twice in ring")
	ErrTokenOutOfRange = errors.New("Token is out of range")
	ErrDifferentSeeds  = errors.New("Received ring was seeded differently from ours!")
	ErrDifferentRange  = errors.New("Received range differs from ours!")
	ErrNotFound        = errors.New("No entries for peer found")
)

func errInconsistentEntry(mine, theirs *entry) error {
	return fmt.Errorf("Inconsistent entries for %s: owned by %s but incoming message says %s", mine.Token, mine.Peer, theirs.Peer)
}
func errEntryInMyRange(theirs *entry) error {
	return fmt.Errorf("Peer %s says it owns the IP range from %s, which I think I own", theirs.Peer, theirs.Token)
}
func errNewerVersion(mine, theirs *entry) error {
	return fmt.Errorf("Received update for IP range I own at %s v%d: incoming message says owner %s v%d", mine.Token, mine.Version, theirs.Peer, theirs.Version)
}

func (r *Ring) checkInvariants() error {
	if !sort.IsSorted(r.Entries) {
		return ErrNotSorted
	}

	// Check no token appears twice
	// We know it's sorted...
	for i := 1; i < len(r.Entries); i++ {
		if r.Entries[i-1].Token == r.Entries[i].Token {
			return ErrTokenRepeated
		}
	}

	if len(r.Entries) == 0 {
		return nil
	}

	// Check tokens are in range
	if r.Entries.entry(0).Token < r.Start {
		return ErrTokenOutOfRange
	}
	if r.Entries.entry(-1).Token >= r.End {
		return ErrTokenOutOfRange
	}

	// Check all the freespaces are in range
	for i, entry := range r.Entries {
		next := r.Entries.entry(i + 1)
		distance := r.distance(entry.Token, next.Token)

		if entry.Free > distance {
			return fmt.Errorf("Entry %s-%s reporting too much free space: %d > %d", entry.Token, next.Token, entry.Free, distance)
		}
	}

	return nil
}

// New creates an empty ring belonging to peer.
func New(start, end address.Address, peer mesh.PeerName) *Ring {
	common.Assert(start < end)

	ring := &Ring{Start: start, End: end, Peer: peer, Entries: make([]*entry, 0)}
	ring.updateExportedVariables()
	return ring
}

func (r *Ring) Range() address.Range {
	return address.Range{Start: r.Start, End: r.End}
}

// Returns the distance between two tokens on this ring, dealing
// with ranges which cross the origin
func (r *Ring) distance(start, end address.Address) address.Offset {
	if end > start {
		return address.Offset(end - start)
	}

	return address.Offset((r.End - start) + (end - r.Start))
}

// GrantRangeToHost modifies the ring such that range [start, end)
// is assigned to peer.  This may insert up to two new tokens.
// Preconditions:
// - start < end
// - [start, end) must be owned by the calling peer
func (r *Ring) GrantRangeToHost(start, end address.Address, peer mesh.PeerName) {
	//fmt.Printf("%s GrantRangeToHost [%v,%v) -> %s\n", r.Peer, start, end, peer)

	r.assertInvariants()
	defer r.assertInvariants()
	defer r.updateExportedVariables()

	// ----------------- Start of Checks -----------------

	common.Assert(start < end)
	common.Assert(r.Start <= start && start < r.End)
	common.Assert(r.Start < end && end <= r.End)
	common.Assert(len(r.Entries) > 0)

	// Look for the left-most entry greater than start, then go one previous
	// to get the right-most entry less than or equal to start
	preceedingPos := sort.Search(len(r.Entries), func(j int) bool {
		return r.Entries[j].Token > start
	})
	preceedingPos--

	// Check all tokens up to end are owned by us
	for pos := preceedingPos; pos < len(r.Entries) && r.Entries.entry(pos).Token < end; pos++ {
		common.Assert(r.Entries.entry(pos).Peer == r.Peer)
	}

	// ----------------- End of Checks -----------------

	// Free space at start is max(length of range, distance to next token)
	startFree := r.distance(start, r.Entries.entry(preceedingPos+1).Token)
	if length := r.distance(start, end); startFree > length {
		startFree = length
	}
	// Is there already a token at start, update it
	if previousEntry := r.Entries.entry(preceedingPos); previousEntry.Token == start {
		previousEntry.update(peer, startFree)
	} else {
		// Otherwise, these isn't a token here, insert a new one.
		r.Entries.insert(entry{Token: start, Peer: peer, Free: startFree})
		preceedingPos++
		// Reset free space on previous entry, which we own.
		previousEntry.update(r.Peer, r.distance(previousEntry.Token, start))
	}

	// Give all intervening tokens to the other peer
	pos := preceedingPos + 1
	for ; pos < len(r.Entries) && r.Entries.entry(pos).Token < end; pos++ {
		entry := r.Entries.entry(pos)
		entry.update(peer, address.Min(entry.Free, r.distance(entry.Token, end)))
	}

	// There is never an entry with a token of r.End, as the end of
	// the ring is exclusive.
	if end == r.End {
		end = r.Start
	}

	//  If there is a token equal to the end of the range, we don't need to do anything further
	if _, found := r.Entries.get(end); found {
		return
	}

	// If not, we need to insert a token such that we claim this bit on the end.
	endFree := r.distance(end, r.Entries.entry(pos).Token)
	r.Entries.insert(entry{Token: end, Peer: r.Peer, Free: endFree})
}

// Merge the given ring into this ring and return any new ranges added
func (r *Ring) Merge(gossip Ring) error {
	r.assertInvariants()
	defer r.assertInvariants()
	defer r.updateExportedVariables()

	// Don't panic when checking the gossiped in ring.
	// In this case just return any error found.
	if err := gossip.checkInvariants(); err != nil {
		return err
	}

	if len(gossip.Seeds) > 0 && len(r.Seeds) > 0 {
		if len(gossip.Seeds) != len(r.Seeds) {
			return ErrDifferentSeeds
		}
		for i, seed := range gossip.Seeds {
			if seed != r.Seeds[i] {
				return ErrDifferentSeeds
			}
		}
	}

	if r.Start != gossip.Start || r.End != gossip.End {
		return ErrDifferentRange
	}

	// Now merge their ring with yours, in a temporary ring.
	var result entries
	addToResult := func(e entry) { result = append(result, &e) }

	var mine, theirs *entry
	var previousOwner *mesh.PeerName
	// i is index into r.Entries; j is index into gossip.Entries
	var i, j int
	for i < len(r.Entries) && j < len(gossip.Entries) {
		mine, theirs = r.Entries[i], gossip.Entries[j]
		switch {
		case mine.Token < theirs.Token:
			addToResult(*mine)
			previousOwner = &mine.Peer
			i++
		case mine.Token > theirs.Token:
			// insert, checking that a range owned by us hasn't been split
			if previousOwner != nil && *previousOwner == r.Peer && theirs.Peer != r.Peer {
				return errEntryInMyRange(theirs)
			}
			addToResult(*theirs)
			previousOwner = nil
			j++
		case mine.Token == theirs.Token:
			// merge
			switch {
			case mine.Version >= theirs.Version:
				if mine.Version == theirs.Version && !mine.Equal(theirs) {
					return errInconsistentEntry(mine, theirs)
				}
				addToResult(*mine)
				previousOwner = &mine.Peer
			case mine.Version < theirs.Version:
				if mine.Peer == r.Peer { // We shouldn't receive updates to our own tokens
					return errNewerVersion(mine, theirs)
				}
				addToResult(*theirs)
				previousOwner = nil
			}
			i++
			j++
		}
	}

	// At this point, either i is at the end of r or j is at the end
	// of gossip, so copy over the remaining entries.

	for ; i < len(r.Entries); i++ {
		mine = r.Entries[i]
		addToResult(*mine)
	}

	for ; j < len(gossip.Entries); j++ {
		theirs = gossip.Entries[j]
		if previousOwner != nil && *previousOwner == r.Peer && theirs.Peer != r.Peer {
			return errEntryInMyRange(theirs)
		}
		addToResult(*theirs)
		previousOwner = nil
	}

	if len(r.Seeds) == 0 {
		r.Seeds = gossip.Seeds
	}
	r.Entries = result
	return nil
}

// Empty returns true if the ring has no entries
func (r *Ring) Empty() bool {
	return len(r.Entries) == 0
}

// Given a slice of ranges which are all in the right order except
// possibly the last one spans zero, fix that up and return the slice
func (r *Ring) splitRangesOverZero(ranges []address.Range) []address.Range {
	if len(ranges) == 0 {
		return ranges
	}
	lastRange := ranges[len(ranges)-1]
	// if end token == start (ie last) entry on ring, we want to actually use r.End
	if lastRange.End == r.Start {
		ranges[len(ranges)-1].End = r.End
	} else if lastRange.End <= lastRange.Start {
		// We wrapped; want to split around 0
		// First shuffle everything up as we want results to be sorted
		ranges = append(ranges, address.Range{})
		copy(ranges[1:], ranges[:len(ranges)-1])
		ranges[0] = address.Range{Start: r.Start, End: lastRange.End}
		ranges[len(ranges)-1].End = r.End
	}
	return ranges
}

// OwnedRanges returns slice of Ranges, ordered by IP, indicating which
// ranges are owned by this peer.  Will split ranges which
// span 0 in the ring.
func (r *Ring) OwnedRanges() (result []address.Range) {
	r.assertInvariants()

	for i, entry := range r.Entries {
		if entry.Peer == r.Peer {
			nextEntry := r.Entries.entry(i + 1)
			result = append(result, address.Range{Start: entry.Token, End: nextEntry.Token})
		}
	}

	return r.splitRangesOverZero(result)
}

// For printing status
type RangeInfo struct {
	Peer mesh.PeerName
	address.Range
	Version uint32
}

func (r *Ring) AllRangeInfo() (result []RangeInfo) {
	for i, entry := range r.Entries {
		nextEntry := r.Entries.entry(i + 1)
		ranges := []address.Range{{Start: entry.Token, End: nextEntry.Token}}
		ranges = r.splitRangesOverZero(ranges)
		for _, r := range ranges {
			result = append(result, RangeInfo{entry.Peer, r, entry.Version})
		}
	}
	return
}

// ClaimForPeers claims the entire ring for the array of peers passed
// in.  Only works for empty rings.
func (r *Ring) ClaimForPeers(peers []mesh.PeerName) {
	common.Assert(r.Empty())
	defer r.assertInvariants()
	defer r.updateExportedVariables()

	totalSize := r.distance(r.Start, r.End)
	share := totalSize/address.Offset(len(peers)) + 1
	remainder := totalSize % address.Offset(len(peers))
	pos := r.Start

	for i, peer := range peers {
		if address.Offset(i) == remainder {
			share--
			if share == 0 {
				break
			}
		}

		r.Entries.insert(entry{Token: pos, Peer: peer, Free: share})
		pos += address.Address(share)
	}

	common.Assert(pos == r.End)

	r.Seeds = peers
}

func (r *Ring) FprintWithNicknames(w io.Writer, m map[mesh.PeerName]string) {
	for _, entry := range r.Entries {
		nickname, found := m[entry.Peer]
		if found {
			nickname = fmt.Sprintf(" (%s)", nickname)
		}

		fmt.Fprintf(w, "\n  %s -> %s%s (v%d)", entry.Token,
			entry.Peer, nickname, entry.Version)
	}
}

func (r *Ring) String() string {
	var buffer bytes.Buffer
	fmt.Fprintf(&buffer, "Ring [%s, %s)", r.Start, r.End)
	r.FprintWithNicknames(&buffer, make(map[mesh.PeerName]string))
	return buffer.String()
}

// ReportFree is used by the allocator to tell the ring how many free
// ips are in a given range, so that ChoosePeersToAskForSpace can make
// more intelligent decisions.
func (r *Ring) ReportFree(freespace map[address.Address]address.Offset) {
	r.assertInvariants()
	defer r.assertInvariants()
	defer r.updateExportedVariables()

	common.Assert(!r.Empty())
	entries := r.Entries

	// As OwnedRanges splits around the origin, we need to
	// detect that here and fix up freespace
	if free, found := freespace[r.Start]; found && entries.entry(0).Token != r.Start {
		lastToken := entries.entry(-1).Token
		prevFree, found := freespace[lastToken]
		common.Assert(found)
		freespace[lastToken] = prevFree + free
		delete(freespace, r.Start)
	}

	for start, free := range freespace {
		// Look for entry
		i := sort.Search(len(entries), func(j int) bool {
			return entries[j].Token >= start
		})

		// Are you trying to report free on space I don't own?
		common.Assert(i < len(entries) && entries[i].Token == start && entries[i].Peer == r.Peer)

		// Check we're not reporting more space than the range
		entry, next := entries.entry(i), entries.entry(i+1)
		maxSize := r.distance(entry.Token, next.Token)
		common.Assert(free <= maxSize)

		if entries[i].Free == free {
			return
		}

		entries[i].Free = free
		entries[i].Version++
	}
}

type weightedPeer struct {
	weight   float64
	peername mesh.PeerName
}
type weightedPeers []weightedPeer

// Note Less is using > so that bigger weights sort earlier
func (ws weightedPeers) Less(i, j int) bool { return ws[i].weight > ws[j].weight }
func (ws weightedPeers) Len() int           { return len(ws) }
func (ws weightedPeers) Swap(i, j int)      { ws[i], ws[j] = ws[j], ws[i] }

// ChoosePeersToAskForSpace returns all peers we can ask for space in
// the range [start, end), in weighted-random order.  Assumes start<end.
func (r *Ring) ChoosePeersToAskForSpace(start, end address.Address) []mesh.PeerName {
	totalSpacePerPeer := make(map[mesh.PeerName]address.Offset)

	// iterate through tokens
	for i, entry := range r.Entries {
		// Ignore entries that don't span the range we want
		if i+1 < len(r.Entries) && r.Entries.entry(i+1).Token-1 < start {
			continue
		}
		if entry.Token >= end {
			break
		}
		// Ignore ranges with no free space
		if entry.Free <= 0 {
			continue
		}

		// Don't talk to yourself
		if entry.Peer == r.Peer {
			continue
		}

		totalSpacePerPeer[entry.Peer] += entry.Free
	}

	// Compute weighted random numbers, then sort.
	// This isn't perfect, e.g. an item with weight 2 will get chosen more than
	// twice as often as an item with weight 1, but it's good enough for our purposes.
	ws := make(weightedPeers, 0, len(totalSpacePerPeer))
	for peername, space := range totalSpacePerPeer {
		ws = append(ws, weightedPeer{weight: float64(space) * rand.Float64(), peername: peername})
	}
	sort.Sort(ws)
	result := make([]mesh.PeerName, len(ws))
	for i, wp := range ws {
		result[i] = wp.peername
	}
	return result
}

func (r *Ring) PickPeerForTransfer(isValid func(mesh.PeerName) bool) mesh.PeerName {
	for _, entry := range r.Entries {
		if entry.Peer != r.Peer && isValid(entry.Peer) {
			return entry.Peer
		}
	}
	return mesh.UnknownPeerName
}

// Transfer will mark all entries associated with 'from' peer as owned by 'to' peer
// and return ranges indicating the new space we picked up
func (r *Ring) Transfer(from, to mesh.PeerName) ([]address.Range, error) {
	r.assertInvariants()
	defer r.assertInvariants()
	defer r.updateExportedVariables()

	var newRanges []address.Range
	found := false

	for i, entry := range r.Entries {
		if entry.Peer == from {
			found = true
			entry.Peer = to
			entry.Version++
			newRanges = append(newRanges, address.Range{Start: entry.Token, End: r.Entries.entry(i + 1).Token})
		}
	}

	if !found {
		return nil, ErrNotFound
	}

	return r.splitRangesOverZero(newRanges), nil
}

// Contains returns true if addr is in this ring
func (r *Ring) Contains(addr address.Address) bool {
	return addr >= r.Start && addr < r.End
}

// Owner returns the peername which owns the range containing addr
func (r *Ring) Owner(token address.Address) mesh.PeerName {
	common.Assert(r.Start <= token && token < r.End)

	r.assertInvariants()
	// There can be no owners on an empty ring
	if r.Empty() {
		return mesh.UnknownPeerName
	}

	// Look for the right-most entry, less than or equal to token
	preceedingEntry := sort.Search(len(r.Entries), func(j int) bool {
		return r.Entries[j].Token > token
	})
	preceedingEntry--
	entry := r.Entries.entry(preceedingEntry)
	return entry.Peer
}

// Get the set of PeerNames mentioned in the ring
func (r *Ring) PeerNames() map[mesh.PeerName]struct{} {
	res := make(map[mesh.PeerName]struct{})

	for _, entry := range r.Entries {
		res[entry.Peer] = struct{}{}
	}

	return res
}

func init() {
	rand.Seed(time.Now().UTC().UnixNano())
}


text:
require "gerencianet"
require_relative "../../credentials"

options = {
  client_id: CREDENTIALS::CLIENT_ID,
  client_secret: CREDENTIALS::CLIENT_SECRET,
  sandbox: CREDENTIALS::SANDBOX
}

params = {
  id: 1004
}

body = {
  notification_url: "http://yourdomain.com",
  custom_id: "my_new_id"
}

gerencianet = Gerencianet.new(options)
puts gerencianet.update_carnet_metadata(params: params, body: body)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
	<meta content="2013-12-25 10:18:47 -0700" http-equiv="change-date" />
	<title>IS 13</title>

	<link rel="stylesheet" href='../css/bpi.css' >

Isaías 13

1Oráculo acerca de Babilônia, que Isaías, filho de Amoz, recebeu numa visão.

2Alçai uma bandeira sobre o monte escalvado; levantai a voz para eles; acenai-lhes com a mão, para que entrem pelas portas dos príncipes.

3Eu dei ordens aos meus consagrados; sim, já chamei os meus valentes para executarem a minha ira, os que exultam arrogantemente.

4Eis um tumulto sobre os montes, como o de grande multidão! Eis um tumulto de reinos, de nações congregadas! O Senhor dos exércitos passa em revista o exército para a guerra.

5Vêm duma terra de longe, desde a extremidade do céu, o Senhor e os instrumentos da sua indignação, para destruir toda aquela terra.

6Uivai, porque o dia do Senhor está perto; virá do Todo-Poderoso como assolação.

7Pelo que todas as mãos se debilitarão, e se derreterá o coração de todos os homens.

8E ficarão desanimados; e deles se apoderarão dores e ais; e se angustiarão, como a mulher que está de parto; olharão atônitos uns para os outros; os seus rostos serão rostos flamejantes.

9Eis que o dia do Senhor vem, horrendo, com furor e ira ardente; para pôr a terra em assolação e para destruir do meio dela os seus pecadores.

10Pois as estrelas do céu e as suas constelações não deixarão brilhar a sua luz; o sol se escurecerá ao nascer, e a lua não fará resplandecer a sua luz.

11E visitarei sobre o mundo a sua maldade, e sobre os ímpios a sua iniqüidade; e farei cessar a arrogância dos atrevidos, e abaterei a soberba dos cruéis.

12Farei que os homens sejam mais raros do que o ouro puro, sim mais raros do que o ouro fino de Ofir.

13Pelo que farei estremecer o céu, e a terra se movera do seu lugar, por causa do furor do Senhor dos exércitos, e por causa do dia da sua ardente ira.

14E como a corça quando é perseguida, e como a ovelha que ninguém recolhe, assim cada um voltará para o seu povo, e cada um fugirá para a sua terra.

15Todo o que for achado será traspassado; e todo o que for apanhado, cairá à espada.

16E suas crianças serão despedaçadas perante os seus olhos; as suas casas serão saqueadas, e as suas mulheres violadas.

17Eis que suscitarei contra eles os medos, que não farão caso da prata, nem tampouco no ouro terão prazer.

18E os seus arcos despedaçarão aos mancebos; e não se compadecerão do fruto do ventre; os seus olhos não pouparão as crianças.

19E Babilônia, a glória dos reinos, o esplendor e o orgulho dos caldeus, será como Sodoma e Gomorra, quando Deus as transtornou.

20Nunca mais será habitada, nem nela morará alguém de geração em geração; nem o árabe armará ali a sua tenda; nem tampouco os pastores ali farão deitar os seus rebanhos.

21Mas as feras do deserto repousarão ali, e as suas casas se encherão de horríveis animais; e ali habitarão as avestruzes, e os sátiros pularão ali.

22As hienas uivarão nos seus castelos, e os chacais nos seus palácios de prazer; bem perto está o seu tempo, e os seus dias não se prolongarão.

Almeida Revista e Atualizada© Copyright © 1993 Sociedade Bíblica do Brasil. Todos os direitos reservados. Texto bíblico utilizado com autorização. Saiba mais sobre a Sociedade Bíblica do Brasil. A Sociedade Bíblica do Brasil trabalha para que a Bíblia esteja, efetivamente, ao alcance de todos e seja lida por todos. A SBB é uma entidade sem fins lucrativos, dedicada a promover o desenvolvimento integral do ser humano.


text:
// The MIT License (MIT)
// Copyright © 2013 Mechanobiology Institute, National University of Singapore.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * @fileoverview Recent page.
 *
 * @author mbikt@nus.edu.sg (Kyaw Tun)
 */

goog.provide('mbi.ui.SubpageInfoBox');
goog.require('mbi.data.SiteMap');
goog.require('mbi.data.storage');
goog.require('ydn.gdata.site.Page');

/**
 * Recent page.
 * @constructor
 */
mbi.ui.SubpageInfoBox = function() {
  /**
   * @type {Element}
   */
  this.root = null;
};

/**
 * Render.
 * @param {Element} root
 */
mbi.ui.SubpageInfoBox.prototype.render = function(root) {
  this.root = root;
};

/**
 * @define {boolean} global enable flag.
 */
mbi.ui.SubpageInfoBox.ENABLED = true;

/**
 * @define {boolean} flag.
 */
mbi.ui.SubpageInfoBox.ONLY_TOPIC = true;

/**
 * @param {ydn.gdata.site.Page} page
 */
mbi.ui.SubpageInfoBox.prototype.setModel = function(page) {
  if (!mbi.ui.SubpageInfoBox.ENABLED || !this.root) {
    return;
  }
  if (mbi.ui.SubpageInfoBox.ONLY_TOPIC) {
    var parent = page.getData()['sites$parent'];
    if (!parent) {
      return;
    }
    var m = parent.match(/\d+$/);
    if (!m || m[0] != mbi.app.base.TOPICS_PAGE_ID) {
      return;
    }
  }
  var ancenters = [];
  var map = mbi.app.shared.site_map.walk(page.getUrl(), ancenters);
  if (map) {
    var ids = map.getSubPageIds();
    var arr = [];
    for (var i = 0; i < map.count(); i++) {
      var child = map.child(i);
      var relative_url = child.url.replace(/https?:\/\/[^\/]+\/a\/[^\/]+\/[^\/]+/, '');
      arr.push({
        url: relative_url,
        title: child.getLabel()
      });
    }
    var opt = {
      rows: arr
    };
    goog.soy.renderElement(this.root, templ.mbi.app.subpagesPanel, opt);
    goog.style.setElementShown(this.root, arr.length > 0);
  }
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>23.0</apiVersion>
    <label>salesforce special scripts</label>
</ApexPage>


text:
next: true
sort: 3
title: Basic Operation
---

# Basic Operation

Once urbit is installed, if you have an invitation, it's a planet
like `~fintud-macrep` and a ticket like
`~fortyv-tombyt-tabsen-sonres`.  Run

    bin/urbit -w fintud-macrep -t fortyv-tombyt-tabsen-sonres

(You can leave the `~` on, but it annoys some Unix shells.)

If you don't have an invitation, pick a nickname for your comet,
like `mycomet`.  Urbit will randomly generate a 128-bit plot:

    bin/urbit -c mycomet

Either way, creating your urbit will take some time.  Some of
this time involves generating keys; some of it involves
downloading code over Urbit itself.

If you turn off your pier at any time (either "nicely" with `^D`
from talk or the dojo or by power-failure, oom-killer, or other
calamity), then you can start it up again with the path to your
pier directory (your planet name if you have an invitation,
otherwise the name you chose after `-c`):

    bin/urbit fintud-macrep

or

    bin/urbit mycomet

## Basic operation

Out of the box, your urbit is running two default appliances,
`:dojo` (a shell or REPL) and `:talk`.  Switch between them with
`^X`.  Note that all apps share an output log, but `^X` switches
the prompt.

`^D` from either default appliance exits the urbit process.

If your plot is `~fintud-macrep`, the dojo prompt is

    ~fintud-macrep:dojo>

Type any Hoon expression at the command line and see the result:

    ~fintud-macrep:dojo> (add 2 2)

You'll see:

    > (add 2 2)
    4
    ~fintud-macrep:dojo>

While there are some tools for interacting with urbit's
filesystem direclty, often it's useful to edit urbit files from
Unix.  Use `|mount` to set up a Dropbox-style sync directory in
your pier directory:

    ~fintud-macrep:dojo> |mount %
    >=
    ~fintud-macrep:dojo> |unmount %
    >=

Look inside your pier directory to find your files, and edit them
with your favorite Unix text editor.

Sometimes you want to get files from another urbit.  There's two
main commands to do this.

    ~fintud-macrep:dojo> |merge %examples ~wactex-ribmex %examples
    >=
    ; ~wactex-ribmex is your neighbor
    ; ~wactex-ribmex is your neighbor
    [time passes...]
    merged with strategy %init

This pulls a bunch of examples from `~wactex-ribmex`'s `%examples`
desk and puts them in our `%examples` desk.  A desk is a
branch (in the git branch sense) of our filesystem.

You can, of course, merge the examples into your `%home`
(default) desk if you wish.  Merging into a new desk creates it,
while merging into an existing desk does an intelligent git-style
merge, with conflict resolution and stuff.

    ~fintud-macrep:dojo> |sync %examples ~wactex-ribmex %examples
    >=
    activated sync from %examples on ~wactex-ribmex to %examples
    sync succeeded from %examples on ~wactex-ribmex to %examples
    ~fintud-macrep:dojo> |unsync %examples ~wactex-ribmex %examples
    ended autosync from %examples on ~wactex-ribmex to %examples

`|sync` does an initial `|merge`, then listens for changes on the
foreign desk and runs `|merge` automatically whenever it changes.
By default your `%home` desk is synced to your parent's `%kids`
desk, so the entire network is upgraded at once.  You may, of
course, unsync it, but this voids your warranty.

You can change which desk is your current working directory with:

    ~fintud-macrep:dojo> =dir /=examples=

> `dir` is a special dojo variable, but you can also create your
> own variables with the same syntax.  `=my-var (add 2 3)` allows
> you to use `my-var` for `5` anywhere later on.

When you change your desk all commands will use the files from
that desk.  Unfortunately, changing your working directory to
anywhere but the top directory is currently
[broken](http://github.com/urbit/urbit/issues/565).  If this is
fixed when you're reading this, please submit a pull request for
this document explaining how to do it!

The last command we'll discuss in this quickstart is `+moon`,
which only works on planets.

    ~fintud-macrep:dojo> +moon
    "moon: ~ramnec-rossug-fintud-macrep; ticket: ~holtyl-mognyl-dostyp-moslud"

This generates a random moon and ticket.  A moon is a subidentity
of your planet, so it's a separate urbit that's associated with
your planet.  If your planet is off, then your moon won't
function very well over the network (it'll work just fine
locally, of coures).

You can start up your moon with `bin/urbit -w moon-name -t
ticket`.  We recommend doing this for development because there
are still some instabilities that have the potential to explode
your planet if you develop on it.  If this happens, then your
planet will be unusable until the next continuity breach.  If you
tell us how you exploded your planet, we may give you a
replacement, but it's still a hassle for you.

Don't worry too much about exploding your moons -- you have four
billion of them, and they get replenished after every continuity
breach.  Still do file a bug, though.


text:
from unittest import TestCase
import doctest

class DocTestCase(TestCase):

    def __new__(self, test):
        return getattr(self, test)()

    @classmethod
    def test_account(cls):
        return doctest.DocTestSuite("ezjailremote.utils")


text:
module ApplicationHelper
  def hide_login_menu?(current_page)
    current_page.in?(['/users/sign_in', '/users/password/edit'])
  end

  def parse_amount_to_pay(amount_to_pay)
    return unless amount_to_pay
    (amount_to_pay % 1).zero? ? amount_to_pay.to_i : amount_to_pay
  end

  def amount_to_refund(application)
    amount_to_pay = application.evidence_check ? application.evidence_check.amount_to_pay : application.amount_to_pay
    application.detail.fee - amount_to_pay
  end

  def amount_to_pay(application)
    application.evidence_check ? application.evidence_check.amount_to_pay : application.amount_to_pay
  end

  def amount_value(value)
    return value.to_i if value.to_i.positive?
    nil
  end
end


text:
package com.galaxyvictor.net;

public interface ConectionStatusListener {

	public void onStatusChanged(int previousStatus, int status);

}


text:
/* Includes *******************************************************************/
#include "uart.h"

#include "globals.h"
#include "debug.h"
#include "stm32f3xx_hal.h"
#include "FreeRTOS.h"
#include "portmacro.h"
#include "semphr.h"

/* Private definitions ********************************************************/
#define UART_DEV    USART3

#define UART_DIV_SAMPLING16(__PCLK__, __BAUD__)  (((__PCLK__) + ((__BAUD__)/2U)) / (__BAUD__))

#define BUF_SIZE    256
#define BUF_MASK    (BUF_SIZE-1)
#define BUF_IDX(x)  ((x) & BUF_MASK)

/* Private variables **********************************************************/
static SemaphoreHandle_t mutex;
static SemaphoreHandle_t rxActSem;

static char   rxBuf[BUF_SIZE];
static size_t rxBufReadPtr  = 0;
static size_t rxBufWritePtr = 0;

/* Private function prototypes ************************************************/

/* Private function definitions ***********************************************/

/* Public function definitions ************************************************/
void USART3_IRQHandler(void)
{
    BaseType_t task_woken = pdFALSE;
    uint32_t   isr_flags;
    uint32_t   data;

    /* Read interrupt flags */
    isr_flags = READ_REG(UART_DEV->ISR);

    /* RX interrupt */
    if(isr_flags & USART_ISR_RXNE)
    {
        data = (char) READ_REG(UART_DEV->RDR);

        if((rxBufWritePtr - rxBufReadPtr) < BUF_SIZE)
        {
            rxBuf[BUF_IDX(rxBufWritePtr)] = data;
            rxBufWritePtr++;
        }

        xSemaphoreGiveFromISR(rxActSem, &task_woken);
    }

    /* Acknowledge interrupts */
    WRITE_REG(UART_DEV->ICR, isr_flags);

    portYIELD_FROM_ISR(task_woken);

    return;
}

void uart_init(void)
{
    mutex = xSemaphoreCreateMutex();
    debug_assert(mutex);

    rxActSem = xSemaphoreCreateBinary();
    debug_assert(rxActSem);

    /* Peripheral clock enable */
    __HAL_RCC_USART3_CLK_ENABLE();

    /* Peripheral interrupt init */
    HAL_NVIC_SetPriority(USART3_IRQn, USART3_IRQ_PRIORITY, 0);
    HAL_NVIC_EnableIRQ(USART3_IRQn);

    /* UART configuration */
    WRITE_REG(UART_DEV->CR1, USART_CR1_TE | USART_CR1_RE);

    WRITE_REG(UART_DEV->CR2, 0);

    WRITE_REG(UART_DEV->BRR, UART_DIV_SAMPLING16(HAL_RCC_GetPCLK1Freq(), 9600));

    /* Enable UART peripheral */
    SET_BIT(UART_DEV->CR1, USART_CR1_UE);

    /* Enable RX interrupt */
    SET_BIT(UART_DEV->CR1, USART_CR1_RXNEIE);

    return;
}

char * uart_gets(char * str, size_t maxlen)
{
    size_t read = 0;

    if(str == NULL || maxlen == 0)
    {
        return NULL;
    }

    xSemaphoreTake(mutex, portMAX_DELAY);

    while(read < (maxlen - 1)) /* -1 for NULL char */
    {
        while(rxBufReadPtr == rxBufWritePtr)
        {
            xSemaphoreTake(rxActSem, portMAX_DELAY);
        }

        str[read] = rxBuf[BUF_IDX(rxBufReadPtr)];
        rxBufReadPtr++;

        if(read == 0 && isspace((int)str[read]) != 0)
        {
            /* Skip leading whitespace */
            continue;
        }
        else if(str[read] == '\n')
        {
            /* Reached end of line */
            read++;
            break;
        }

        read++;
    }

    xSemaphoreGive(mutex);

    /* Null terminate the string */
    str[read] = '\0';

    return str;
}


text:
# Example

```
/** @jsx createElement */
import {createElement, createParser} from 'elliptical'
import request from 'request'
import Observable from 'zen-observable'

function CountrySource () {
  const url = 'http://services.groupkt.com/country/get/all'
  return new Observable(observer => {
    observer.next([])

    request(url, (err, response, body) => {
      if (err) {
        observer.error(err)
      } else {
        observer.next(body)
      }
    })
  })
})

const Country = {
  observe () {
    return <CountrySource />
  },
  describe ({data}) {
    const countryItems = data.map(country => {
      return {text: country.name, value: country.alpha2_code}
    })

    return (
      <label text='Country'>
        <list items={countryItems} fuzzy />
      </label>
    )
  }
}

const grammar = (
  <sequence>
    <literal text='flights ' />
    <choice id='direction'>
      <literal text=' from ' value='from' />
      <literal text=' to ' value='to' />
    </choice>
    <Country id='country' />
  </sequence>
)

const parser = createParser(grammar)

document.getElementById('parse-input').onclick = () => {
  const query = document.getElementById('elliptical-input').value
  const outputs = parser.parse(query)
  console.log(outputs)
}

/*
For input 'flights to irela':

  [{ // direct match
    words: [
      {text: 'flights', input: true},
      {text: ' to ', input: true},
      {text: 'Irela', input: true, argument: 'Country'},
      {text: 'nd', input: false, argument: 'Country'}
    ]},
    results: {
      direction: 'to',
      country: 'IE'
    },
    score: 1
  }, { // mid-string match
    words: [
      {text: 'flights', input: true},
      {text: ' to ', input: true},
      {text: 'United Kingdom of Great Britain and Northern ', input: false, argument: 'Country'},
      {text: 'Ireland', input: true, argument: 'Country'}
    ]},
    results: {
      direction: 'to',
      country: 'GB'
    },
    score: 0.75
  }, { // fuzzy match
    words: [
      {text: 'flights', input: true},
      {text: ' to ', input: true},
      {text: 'Macedon', input: false, argument: 'Country'},
      {text: 'i', input: true, argument: 'Country'},
      {text: 'a (the fo', input: false, argument: 'Country'},
      {text: 'r', input: true, argument: 'Country'},
      {text: 'm', input: false, argument: 'Country'},
      {text: 'e', input: true, argument: 'Country'},
      {text: 'r Yugos', input: false, argument: 'Country'},
      {text: 'la', input: true, argument: 'Country'},
      {text: 'v Republic of)', input: false, argument: 'Country'}
    ]},
    results: {
      direction: 'to',
      country: 'MK'
    },
    score: 0.5
  }]
*/
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Signifly_Interview.Models
{
    public class Team
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<TeamMember> TeamMembers { get; set; }
        public List<SkillAmt> Skills { get; set; }
    }

    public class SkillAmt
    {
        public string Name { get; set; }
        public int Amt { get; set; }
    }
}


text:
package com.ibm.icu.dev.test.format;

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Iterator;

import com.ibm.icu.dev.test.ModuleTest;
import com.ibm.icu.dev.test.TestDataModule;
import com.ibm.icu.dev.test.TestDataModule.DataMap;
import com.ibm.icu.dev.test.util.CalendarFieldsSet;
import com.ibm.icu.dev.test.util.DateTimeStyleSet;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.ULocale;

/**
 * @author srl
 *
 */
public class DataDrivenFormatTest extends ModuleTest {

    /**
     * @param baseName
     * @param locName
     */
    public DataDrivenFormatTest() {
        super("com/ibm/icu/dev/data/testdata/", "format");
    }

    /* (non-Javadoc)
     * @see com.ibm.icu.dev.test.ModuleTest#processModules()
     */
    public void processModules() {
        //String testName = t.getName().toString();

        for (Iterator siter = t.getSettingsIterator(); siter.hasNext();) {
            // Iterate through and get each of the test case to process
            DataMap settings = (DataMap) siter.next();

            String type = settings.getString("Type");

            if(type.equals("date_format")) {
                testConvertDate(t, settings, true);
            } else if(type.equals("date_parse")) {
                testConvertDate(t, settings, false);
            } else {
                errln("Unknown type: " + type);
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
         new DataDrivenFormatTest().run(args);
    }

    private static final String kPATTERN = "PATTERN=";
    private static final String kMILLIS = "MILLIS=";
    private static final String kRELATIVE_MILLIS = "RELATIVE_MILLIS=";
    private static final String kRELATIVE_ADD = "RELATIVE_ADD:";

    private void testConvertDate(TestDataModule.TestData testData, DataMap  settings, boolean fmt) {
        DateFormat basicFmt = new SimpleDateFormat("EEE MMM dd yyyy / YYYY'-W'ww-ee");

        int n = 0;
        for (Iterator iter = testData.getDataIterator(); iter.hasNext();) {
            ++n;
            long now = System.currentTimeMillis();
            DataMap currentCase = (DataMap) iter.next();
            String caseString = "["+testData.getName()+"#"+n+(fmt?"format":"parse")+"]";

            String locale = currentCase.getString("locale");
            String spec = currentCase.getString("spec");
            String date = currentCase.getString("date");
            String str = currentCase.getString("str");

            Date fromDate = null;
            boolean useDate = false;

            ULocale loc = new ULocale(locale);
            String pattern = null;
//            boolean usePattern = false;
            DateFormat format = null;
            DateTimeStyleSet styleSet;
            CalendarFieldsSet fromSet = null;

            // parse 'spec'  - either 'PATTERN=yy mm dd' or 'DATE=x,TIME=y'
            if(spec.startsWith(kPATTERN)) {
                pattern = spec.substring(kPATTERN.length());
//                usePattern = true;
                format = new SimpleDateFormat(pattern, loc);
            } else {
                styleSet = new DateTimeStyleSet();
                styleSet.parseFrom(spec);
                format = DateFormat.getDateTimeInstance(styleSet.getDateStyle(), styleSet.getTimeStyle(), loc);
            }

            Calendar cal = Calendar.getInstance(loc);

            // parse 'date' - either 'MILLIS=12345' or  a CalendarFieldsSet
            if(date.startsWith(kMILLIS)) {
                useDate = true;
                fromDate = new Date(Long.parseLong(date.substring(kMILLIS.length())));
            } else if(date.startsWith(kRELATIVE_MILLIS)) {
                useDate = true;
                fromDate = new Date(now+Long.parseLong(date.substring(kRELATIVE_MILLIS.length())));
            } else if(date.startsWith(kRELATIVE_ADD)) {
                String add = date.substring(kRELATIVE_ADD.length()); // "add" is a string indicating which fields to add
                CalendarFieldsSet addSet = new CalendarFieldsSet();
                addSet.parseFrom(add);
                useDate = true;
                cal.clear();
                cal.setTimeInMillis(now);

                /// perform op on 'to calendar'
                for (int q=0; q<addSet.fieldCount(); q++) {
                    if (addSet.isSet(q)) {
                         cal.add(q,addSet.get(q));
                    }
                }

                fromDate = cal.getTime();
            } else {
                fromSet = new CalendarFieldsSet();
                fromSet.parseFrom(date);
            }

            // run the test
            if(fmt) {
                StringBuffer output = new StringBuffer();
                cal.clear();
                FieldPosition pos = new FieldPosition(0);
                if(useDate) {
                    output = format.format(fromDate, output, pos);
                } else {
                    fromSet.setOnCalendar(cal);
                    format.format(cal, output, pos);
                }

                if(output.toString().equals(str)) {
                    logln(caseString + " Success - strings match: " + output);
                } else {
                    errln(caseString + " FAIL: got " + output + " expected " + str);
                }
            } else { // parse
                cal.clear();
                ParsePosition pos = new ParsePosition(0);
                format.parse(str, cal, pos);
                if(useDate) {
                    Date gotDate = cal.getTime();
                    if(gotDate.equals(fromDate)) {
                        logln(caseString + " SUCCESS: got=parse="+str);
                    } else {
                        errln(caseString + " FAIL: parsed " + str + " but got " +
                                basicFmt.format(gotDate) + " - " + gotDate + "  expected " +
                                basicFmt.format(fromDate));
                    }
                } else  {
                    CalendarFieldsSet diffSet = new CalendarFieldsSet();
                    if(!fromSet.matches(cal, diffSet)) {
                        String diffs = diffSet.diffFrom(fromSet);
                        errln(caseString + " FAIL:  differences: " + diffs);
                    } else {
                        logln(caseString + " SUCCESS: got=parse: " + str + " - " + fromSet.toString());
                    }
                }
            }
        }
    }
}


text:
<evaluation>
	<parameter name="Metric">
		<value>LAS</value>
		<value>UAS</value>
		<value>LA</value>
	</parameter>
	<parameter name="GroupBy">
		<value format="all|counter-">Cpostag</value>
	</parameter>
	<formatting argument="pattern" format="0%"/>
</evaluation>


text:
#ifndef MESSAGE_ATTRIBUTE_DECODED_HPP
#define MESSAGE_ATTRIBUTE_DECODED_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <message/detail/config.hpp>

#include <cstdint>
#include <message/detail/attribute_header.hpp>
#include <message/detail/traits.hpp>

#include <message/detail/push_options.hpp>

namespace stun {
namespace attribute {

class decoded {
  typedef detail::attribute_header attribute_header;
 public:
  decoded(const uint8_t* message_header, const uint8_t* attribute_start)
    : message_header_(message_header), attribute_start_(attribute_start) {}

  uint16_t type() const {
    return attribute_header::decoder(attribute_start_).type();
  }

  decoded next() const {
    size_t attribute_size =
        (attribute_header::decoder(attribute_start_).length()+3) & (~3);
    return decoded(message_header_, attribute_start_
        + attribute_header::size + attribute_size);
  }

  template<uint16_t T>
  typename detail::traits<T>::decoding_type to() {
    using stun::detail::traits;
    using stun::detail::attribute_header;
    attribute_header::decoder adec(attribute_start_);
    return traits<T>::decode(message_header_,
        attribute_start_ + attribute_header::size, adec.length());
  }

  bool operator==(const decoded &rhs) const {
    return attribute_start_ == rhs.attribute_start_;
  }

  bool operator!=(const decoded &rhs) const {
    return attribute_start_ != rhs.attribute_start_;
  }

 private:
  const uint8_t* message_header_;
  const uint8_t* attribute_start_;
};

} // namespace attribute
} // namespace stun

#include <message/detail/pop_options.hpp>

#endif // MESSAGE_ATTRIBUTE_DECODED_HPP


text:
import socket

class SocketHandler():
    socket = None
    connection = None
    control_length = 5
    test_other_try = 0

    def __init__(self, port, control_length=5):
        if self.test_other_try:  # why I did it? J_0
            raise Exception('some bullshit happened')
        self.socket = socket.socket()
        self.socket.bind(('', port))
        self.socket.settimeout(0.1)
        self.control_length = control_length
        self.socket.listen(1)
        self.test_other_try = 1

    def get_data_from_socket(self):
        try: # avoid timeout errors to allow looping
            self.connection, address = self.socket.accept()
            self.connection.settimeout(1)
            req = self.connection.recv(5)
            req_len = int(req)
        except socket.timeout:
            req_len = 0
        if req_len:
            return self.connection.recv(req_len).decode('utf-8')
        else:
            return None

    def send_response(self, response):
        length = str(len(response)).zfill(5)
        self.connection.send(length+response)

    def close(self):
        self.socket.close()


text:
@interface PayWayViewController : UIViewController
@property(nonatomic,strong)Order* order;
@end


text:
package es.caib.zkib.jxpath;

/**
 * The  {@link JXPathContext#createPath JXPathContext.createPath()} method of
 * JXPathContext can create missing objects as it traverses an XPath; it
 * utilizes an AbstractFactory for that purpose. Install a factory on
 * JXPathContext by calling {@link JXPathContext#setFactory JXPathContext.
 * setFactory()}.
 *

 * All  methods of this class return false.  Override any of them to return true
 * to indicate that the factory has successfully created the described object.
 *
 * @author Dmitri Plotnikov
 * @version $Revision: 1.1 $ $Date: 2009-04-03 08:13:14 $
 */
public abstract class AbstractFactory {

    /**
     * The  parameters may describe a collection element or an individual
     * object. It is up to the factory to infer which one it is. If it is a
     * collection, the factory should check if the collection exists.  If not,
     * it should create the collection. Then it should create the index'th
     * element of the collection and return true.
     *

     *
     * @param context can be used to evaluate other XPaths, get to variables
     * etc.
     * @param pointer describes the location of the node to be created
     * @param parent is the object that will serve as a parent of the new
     * object
     * @param name is the name of the child of the parent that needs to be
     * created. In the case of DOM may be qualified.
     * @param index is used if the pointer represents a collection element. You
     * may need to expand or even create the collection to accommodate the new
     * element.
     *
     * @return true if the object was successfully created
     */
    public boolean createObject(JXPathContext context, Pointer pointer,
                                Object parent, String name, int index) {
        return false;
    }

    /**
     * Declare the specified variable
     *
     * @param context hosts variable pools. See
     * {@link JXPathContext#getVariables() JXPathContext.getVariables()}
     * @param name is the name of the variable without the "$" sign
     *
     * @return true if the variable was successfully defined
     */
    public boolean declareVariable(JXPathContext context, String name) {
        return false;
    }
}


text:
"""Problem 45 of https://projecteuler.net"""

from projecteuler.generators import triangle_numbers
from projecteuler.inspectors import is_pentagonal, is_hexagonal

def problem_45():
    """Solution to problem 45."""
    count = 0
    triangle_generator = triangle_numbers()
    while True:
        number = next(triangle_generator)
        if not is_hexagonal(number):
            continue
        if not is_pentagonal(number):
            continue
        count += 1
        if count == 3:
            return number


text:
namespace ContosoUniversity.Features.Course
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using AutoMapper;
    using DAL;
    using MediatR;
    using Models;

    public class Index
    {
        public class Query : IAsyncRequest<Result>
        {
            public Department SelectedDepartment { get; set; }
        }

        public class Result
        {
            public Department SelectedDepartment { get; set; }
            public List<Course> Courses { get; set; }

            public class Course
            {
                public int CourseID { get; set; }
                public string Title { get; set; }
                public int Credits { get; set; }
                public string DepartmentName { get; set; }
            }
        }

        public class Handler : IAsyncRequestHandler<Query, Result>
        {
            private readonly SchoolContext _db;

            public Handler(SchoolContext db)
            {
                _db = db;
            }

            public async Task<Result> Handle(Query message)
            {
                int? departmentID = message.SelectedDepartment == null
                    ? (int?)null
                    : message.SelectedDepartment.DepartmentID;

                var courses = await _db.Courses
                    .Where(c => !departmentID.HasValue || c.DepartmentID == departmentID)
                    .OrderBy(d => d.CourseID)
                    .ProjectToListAsync<Result.Course>();

                return new Result
                {
                    Courses = courses,
                    SelectedDepartment = message.SelectedDepartment
                };
            }
        }
    }
}


text:
import { transformWithMarked } from './texttransform.js';

var lightningLocation = 'gus.lightning.force';

var investigationEditLightningID = 'investigationEdit:j_id0:workSds:storyWorkForm:dstpInput:inputComponent:inputFieldWithContainer:textAreaDelegate_Details_And_Steps_To_Reproduce__c_rta_body';

var bugEditLightningID = 'bugEdit:j_id0:workSds:storyWorkForm:dstpInput:inputComponent:inputFieldWithContainer:textAreaDelegate_Details_And_Steps_To_Reproduce__c_rta_body'; // eslint-disable-line no-unused-vars
var bugEditLightningID2 = 'userStoryEdit:j_id0:workSds:storyWorkForm:dstpInput:inputComponent:inputFieldWithContainer:textAreaDelegate_Details_And_Steps_To_Reproduce__c_rta_body';
var bugEditLightningIDDest = 'div.slds-col.slds-col--padded.slds-p-bottom--medium.slds-size--1-of-1.slds-medium-size--1-of-1.slds-large-size--1-of-1';
var bugEditLightningCss = {
    classes: {
        mdPreview: 'bugedit-lightning-mdpreview',
        titleDiv: 'bugedit-lightning-titlediv',
        title: 'slds-form-element__label'
    }
};

var userStoryEditLightningID = 'userStoryEdit:j_id0:workSds:storyWorkForm:descriptionInput:inputComponent:inputFieldWithContainer'; // eslint-disable-line no-unused-vars
var userStoryEditLightningCss = {
    classes: {
        mdPreview: 'userstoryedit-lightning-mdpreview',
        titleDiv: 'userstoryedit-lightning-titlediv',
        title: 'slds-form-element__label'
    }
};

var bugEditClassicLocation = '/apex/adm_bugedit';
var bugEditClassicID = 'bugWorkPage:bugWorkForm:richDetailsInput:textAreaDelegate_Details_and_Steps_to_Reproduce__c_rta_body';
var bugEditClassicDestID = 'richDetailsWrapper';
var bugEditClassicCss = {
    classes: {
        mdPreview: 'inlineEditWrite bugedit-classic-mdpreview',
        titleDiv: 'gusFormFieldLeft bugedit-classic-titlediv',
        title: ''
    }
};

var investigationEditClassicLocation = '/apex/adm_investigationedit';
var investigationEditClassicID = 'investigationWorkPage:investigationForm:richDetailsInput:textAreaDelegate_Details_and_Steps_to_Reproduce__c_rta_body';
var investigationEditClassicDestID = 'gusForm1Column';
var investigationEditClassicCss = {
    classes: {
        mdPreview: 'inlineEditWrite bugedit-classic-mdpreview',
        titleDiv: 'gusFormFieldLeft bugedit-classic-titlediv',
        title: ''
    }
};

var userStoryEditClassicLocation = '/apex/adm_userstoryedit';
var userStoryEditClassicID = 'userStoryWorkPage:storyWorkForm:detailsInput:formRow:input';
var userStoryEditClassicCss = {
    classes: {
        mdPreview: 'userstoryedit-classic-mdpreview',
        titleDiv: 'gusFormFieldLeft userstoryedit-classic-titlediv',
        title: ''
    }
};
var userStoryDetailClassicLocation = '/apex/adm_userstorydetail';
var userStoryDetailClassicID = 'userStoryDetailPage_userStoryWorkForm_detailsInput_inputComponent_outputStandalone_ileinner';

var bugDetailClassicLocation = '/apex/adm_bugdetail';
var bugDetailClassicID = 'bugDetailPage:bugWorkForm:j_id89bugDetailPage:bugWorkForm:j_id89_00NB0000000FiIs_div';

var investigationDetailClassicLocation = '/apex/adm_investigationdetail';
var investigationDetailClassicID = 'investigationDetailPage:investigationWorkForm:j_id88investigationDetailPage:investigationWorkForm:j_id88_00NB0000000FiIs_div';

var lightningBugOrInvestigationEdit;
var iframeContext = false;
window.gusMarkdownRun = true;
var originalHTML = '';
var originalHTMLFromBackground = {};
var validLocationRegex = /sObject\/\w{18}\/view|one.app#\w{488}|one.app.*?#\/sObject\/ADM_Work__c\/new/g;

/**
 * First check we run before any attempt to run the extension logic. Makes sure we are on a page that the extension would run on.
 * @return {boolean} Whether or not the current location is valid
 */
function checkValidLocation () {
    // If the url contains alohaRedirect, the page is basically in the process of loading, so we tell the background page. The
    // background page will continually respond to this message, telling this script to run initialize again. Eventually, the url
    // won't contain alohaRedirect and we will know if the page is valid or invalid
    if (location.href.indexOf('alohaRedirect') > -1) {
        setTimeout(function () {
            initialize();
        }, 200);
        return false;
    } else if (location.href.indexOf('https://gus.my.salesforce.com/apex/adm_') > -1) {  // if we are in classic mode
        return true;
    } else if (location.href.indexOf(lightningLocation) && location.href.match(validLocationRegex) !== null) { // if we are in lightning mode
        return true;
    } else {
        return false;
    }
}

/*
Lightning mode bug edit (and investigation edit) is a special case because it loads two iframes inside the main page, both of which are from a different domain
than the main page. This gives us CORS errors because we need to access the innermost frame. To get around this, we set up the chrome
extension to run this script inside the top frame as well as the middle frame. So, the script running inside the middle frame has
access to the script in the innermost frame. This function allows us to set variables so that we know which script we are in, the outermost
one or the middle one. If we are in the middle one, we do everything as normal, if we are in the outermost one we don't want to change any
of the page's DOM. However, the outermost script is still set up to listen to messages because when, for example, a different bug or user
story is clicked on, the outermost script will still be running but the middle script will be discarded upon navigation away from the page.
The outermost script will run for the entirety of the time that the user is in lightning mode, since chrome extension url matching for
content scripts doesn't provide the specificity necessary for running on only the individual lightning mode pages we want.
 */
function checkForlightningBugOrInvestigationEdit () {
    if (location.href.indexOf(lightningLocation) > -1 && location.href.indexOf('view') === -1 && document.querySelector('#userStoryEdit\\:j_id0\\:workSds\\:storyWorkForm\\:descriptionInput\\:inputComponent\\:inputFieldWithContainer') === null) {
        lightningBugOrInvestigationEdit = true;
        //if this exists, do stuff from iframe context
        if (document.querySelector('body.desktop') === null) {
            iframeContext = true;
        }
    } else {
        lightningBugOrInvestigationEdit = false;
        iframeContext = false;
    }
}

/*
This is where the script receives its instructions from the background page. The script always
sends back if it is currently running or not (green or white circle on icon).
 */
window.chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (location.href !== 'https://gus.lightning.force.com/one/one.app#/n/Work_Manager') {
        var responseObj = {received: true};
        // Background page stores original html for every bug or user story that is visited.
        // Each one has a specific url associated to it, so we store them this way so we can
        // be sure that the script can always inject the correct original html into the correct
        // location.
        if (request.originalHTML) {
            originalHTMLFromBackground[location.href] = request.originalHTML;
        }
        // Request.changeRun is set when the chrome extension icon is clicked. The background page
        // gets notified of that event and tells the script to switch what it was doing and run
        // the opposite way (i.e. view vs reset, edit vs reset)
        if (request.changeRun) {
            window.gusMarkdownRun = !window.gusMarkdownRun;
            initialize();
        }
        // This only happens in lightning mode, since navigation to a different story or bug does
        // not cause a new content script to be injected. When this event happens, we want the
        // script to re-initialize
        if (request.init) {
            initialize();
        }
        // This actually always happens, but it fits into the layout nicely
        if (request.getCurrentRunState) {
            responseObj.runState = window.gusMarkdownRun;
        }

        // Here, we send back the script's run state to the background page, so the chrome extension
        // icon can be set accordingly
        sendResponse(responseObj);
    }
});

/**
 * Changes a user story, investigation, or bug's description to be rendered in Markdown
 * @param  {Element} descriptionBoxEl   the element that contains the text in the description
 */
function viewingPage (descriptionBoxEl) {
    var descriptionBoxHTML = '';
    if (descriptionBoxEl) {
        if (location.href.indexOf(lightningLocation) > -1) {
            if (!descriptionBoxEl.classList.contains('customPre')) {
                descriptionBoxEl.classList.add('customPre');
            }
        }
        descriptionBoxHTML = descriptionBoxEl.innerHTML;
        originalHTML = descriptionBoxEl.innerHTML;
        // Here we send the original html on the page to the background page. This happens as many
        // times as the chrome extension icon is clicked divided by two, but it is only important
        // the first time, because the first time is when we can be sure that the original html
        // is what it is supposed to be
        window.chrome.runtime.sendMessage({originalHTML: originalHTML});
    }
    if (descriptionBoxHTML.length > 0) {
        // Here is where we set the bug or user story description to be the rendered markdown
        // If it's the first time on this bug or user story, the script will not have yet
        // received the original HTML from the background. Any other time, it will have
        // received that so it will use it.
        if (originalHTMLFromBackground[location.href] !== undefined) {
            descriptionBoxEl.innerHTML = transformWithMarked(originalHTMLFromBackground[location.href]);
        } else {
            descriptionBoxEl.innerHTML = transformWithMarked(descriptionBoxHTML);
        }
    }
}

/**
 * Sets the user story or bug's (or investigation's) description back to what it was pre-Markdown
 * @param  {Element} descriptionBoxEl   the element that contains the text in the description
 */
function viewingReset (descriptionBoxEl) {
    if (originalHTMLFromBackground[location.href]) {
        descriptionBoxEl.innerHTML = originalHTMLFromBackground[location.href];
    }
}

/**
 * Sets the markdown preview's inner HTML to whatever the markdown would be
 * after being passed through the textTransform function
 * @param  {Event} event The event that is fired by the bug or user story (or investigation) edit box
 */
function previewEditor (event) {
    var text = event.target.value || event.target.innerHTML;
    // Event.target is the edit box, event.target.prev is the markdown preview box
    event.target.prev.innerHTML = transformWithMarked(text);
}

/**
 * Scrolling event handler for bug (or investigation) edits that scrolls the markdown preview as the edit scrolls,
 * keeping the two in sync
 * @param  {Event} event The event that is fired by the bug (or investigation) edit box
 */
function bugScroll (event) {
    document.querySelector('#markdown-preview').scrollTop = event.target.scrollingElement.scrollTop;
}

/**
 * Scrolling event handler for user story edits that scrolls the markdown preview as the edit scrolls,
 * keeping the two in sync
 * @param  {Event} event The event that is fired by the user story edit box
 */
function userstoryScroll (event) {
    document.querySelector('#markdown-preview').scrollTop = event.target.scrollTop;
}

/**
 * Sets the markdown preview based on user entered text on editing pages.
 * @param  {object} elem                This is an already selected element on the page to be the markdown source
 * @param  {object} destinationElement  This is an already selected element on the page for the html to be injected
 * @param {object} css                  Object that contains class names to be applied to different elements
 */
function editingPage (elem, destinationElement, css) {
    var td = document.querySelector('#title-div');
    var mdp = document.querySelector('#markdown-preview');
    var mdpt = document.querySelector('#markdown-preview-title');
    var titleDiv;
    var markdownPreview;
    var markdownPreviewTitle;
    // If we have already called this method once, the elements will already exist.
    // They will just be hidden, so we have to show them by setting display to block.
    // Otherwise, we have to create them from scratch
    if (td) {
        titleDiv = td;
        titleDiv.style.display = 'block';
    } else {
        titleDiv = document.createElement('div');
        titleDiv.id = 'title-div';
        titleDiv.className = css.classes.titleDiv;
    }
    if (mdp) {
        markdownPreview = mdp;
        markdownPreview.style.display = 'block';
    } else {
        markdownPreview = document.createElement('div');
        markdownPreview.id = 'markdown-preview';
        markdownPreview.className = css.classes.mdPreview;
    }
    if (mdpt) {
        markdownPreviewTitle = mdpt;
        markdownPreviewTitle.style.display = 'block';
    } else {
        markdownPreviewTitle = document.createElement('label');
        markdownPreviewTitle.id = 'markdown-preview-title';
        markdownPreviewTitle.innerHTML = 'Markdown Preview';
        markdownPreviewTitle.className = css.classes.title;
        titleDiv.appendChild(markdownPreviewTitle);
        destinationElement.appendChild(titleDiv);
        destinationElement.appendChild(markdownPreview);
        elem.prev = markdownPreview;
    }

    // Tell the editing box to listen to keyup events, so that rendered
    // markdown can be displayed live as the user types
    var initialKeyup = new CustomEvent('keyup');
    elem.addEventListener('keyup', previewEditor);
    // We have to do an initial keyup so that when the page loads the user
    // will see the preview immediately
    elem.dispatchEvent(initialKeyup);

}

/**
 * Makes the markdown preview invisible on bug or user story edits, happens
 * when the user clicks the chrome extension icon every other time. Also removes
 * the event listener for the live preview
 * @param  {Element} elem The element that has the event listener
 */
function editingReset (elem) {
    elem.removeEventListener('keyup', previewEditor);
    document.querySelector('#title-div').style.display = 'none';
    document.querySelector('#markdown-preview').style.display = 'none';
    document.querySelector('#markdown-preview-title').style.display = 'none';
}

/**
 * Returns an iframe from the document
 * @param  {number} iframeNum   The index containing the desired iframe
 * @return {Element}            Returns the iframe
 */
function getIframe (iframeNum) {
    return document.querySelectorAll('iframe')[iframeNum];
}

/**
 * Utility function that calls the correct editing or viewing function
 * based on parameters
 * @param  {Element} elem           Element that contains bug or user story or investigation description
 * @param  {Boolean} edit           True if the user is editing, false if they are viewing
 * @param  {Element} destElem       Element that the markdown preview is appended to
 * @param  {Object} css             Contains all of the css classes to match the page's css
 */
function showOrHideMarkdown (elem, edit, destElem, css) {
    if (edit == true) {
        if (window.gusMarkdownRun) {
            editingPage(elem, destElem, css);
        } else {
            editingReset(elem);
        }
    } else {
        if (window.gusMarkdownRun) {
            viewingPage(elem);
        } else {
            viewingReset(elem);
        }
    }
}

/**
 * Adds or removes an event listener with a given event type and handler function,
 * based on if the extension is being run or not
 * @param  {Element} element    The element that has or will have the event
 * @param  {string} eventType   The type of event, i.e. "scroll"
 * @param  {function} func      The event handler
 */
function addOrRemoveEventListener (element, eventType, func) {
    if (window.gusMarkdownRun) {
        element.addEventListener(eventType, func);
    } else {
        element.removeEventListener(eventType, func);
    }
}

/**
 * Helper function that is repeated a lot in the initialize function. Looks for an
 * element that the page is actually using, because sometimes there are duplicates
 * on the page that aren't being used currently and actually contain old information
 * to throw us off.
 * @param  {Element[]} elements     List of possible elements found by document.querySelectorAll
 * @param  {string} description     Logged to the console if we find the element
 * @param  {Interval} interval      This interval is cleared if we find the element
 * @return {Boolean}                True if an element was found, false if it wasn't
 */
function lightningDetailFindCorrectElement (elements, description, interval) {
    for (var i = 0; i < elements.length; i++) {
        let element = elements[i];
        if (element.offsetParent !== null) {
            console.log(description); // eslint-disable-line no-console
            showOrHideMarkdown(element, false);
            clearInterval(interval);
            return true;
        }
    }
    return false;
}

/**
 * Helper function called to initialize either a bug or investigation edit in lightning,
 * they are essentially the same
 * @param  {element} element        contains the work description
 * @param  {iframe} iframe          contains the element
 */
function editInit (element, iframe) {
    if (element === null) {
        // Even though the iframe is defined, it hasn't been fully loaded yet, so
        // we have to wait for this to happen before we can access its elements
        iframe.onload = function () {
            element = iframe.contentDocument.getElementById(bugEditLightningID) || iframe.contentDocument.getElementById(bugEditLightningID2);
            var destElement = document.querySelectorAll(bugEditLightningIDDest)[1];
            showOrHideMarkdown(element, true, destElement, bugEditLightningCss);
            addOrRemoveEventListener(element.ownerDocument, 'scroll', bugScroll);
        };
    } else {
        var destElement = document.querySelectorAll(bugEditLightningIDDest)[1];
        showOrHideMarkdown(element, true, destElement, bugEditLightningCss);
        addOrRemoveEventListener(element.ownerDocument, 'scroll', bugScroll);
    }
}

/**
 * Function that controls everything. It's run when the page loads. Figures out what kind of page we are on (bugedit classic,
 * userstorydetail lightning, etc.) and sets the rest of the event handlers and variables accordingly.
 */
function initialize () {
    // Always update these variables every time we run this function, because we don't want the outermost script in bugedit lightning
    // to do anything in here
    var validLocation = checkValidLocation();
    if (validLocation === true) {
        checkForlightningBugOrInvestigationEdit();
        var element;
        var destinationElement;
        var iframe;
        var checkIframeExistence;
        if (!lightningBugOrInvestigationEdit || (iframeContext && lightningBugOrInvestigationEdit)) {
            if (location.href.indexOf(lightningLocation) > -1 && location.href.indexOf('view') == -1) {
                if (document.querySelector('#userStoryEdit\\:j_id0\\:workSds\\:storyWorkForm\\:descriptionInput\\:inputComponent\\:inputFieldWithContainer') !== null) {
                    console.log('userstoryedit lightning'); // eslint-disable-line no-console
                    element = document.getElementById(userStoryEditLightningID);
                    destinationElement = element.parentElement;
                    addOrRemoveEventListener(element, 'scroll', userstoryScroll);
                    showOrHideMarkdown(element, true, destinationElement, userStoryEditLightningCss);
                } else {
                    // If it is not a user story edit, must be an investigation or bug edit. In that case, we have to wait for the innermost iframe to be
                    // defined before we can access it
                    checkIframeExistence = setInterval(function () {
                        if (typeof(iframe) == 'undefined') {
                            var querySelectorAllIndex = 0;
                            iframe = getIframe(querySelectorAllIndex);
                        } else {
                            clearInterval(checkIframeExistence);
                            if (location.href.indexOf('adm_investigationedit') > -1) {
                                console.log('investigationedit lightning'); // eslint-disable-line no-console
                                element = iframe.contentDocument.getElementById(investigationEditLightningID);
                                editInit(element, iframe);
                            } else {
                                console.log('bugedit lightning'); // eslint-disable-line no-console
                                element = iframe.contentDocument.getElementById(bugEditLightningID) || iframe.contentDocument.getElementById(bugEditLightningID2);
                                editInit(element, iframe);
                            }
                        }
                    }, 200);
                }
            } else if (location.href.indexOf(bugEditClassicLocation) > -1 && location.href.indexOf(lightningLocation) == -1) {
                console.log('bugedit classic'); // eslint-disable-line no-console
                // Wait for the iframe to be defined
                checkIframeExistence = setInterval(function () {
                    if (typeof(iframe) == 'undefined') {
                        var querySelectorAllIndex = 1;
                        iframe = getIframe(querySelectorAllIndex);
                    } else {
                        clearInterval(checkIframeExistence);
                        element = iframe.contentDocument.getElementById(bugEditClassicID);
                        destinationElement = document.getElementById(bugEditClassicDestID);
                        //In this case, the iframe has not yet loaded, so we wait for it to load
                        //Otherwise, we just go right ahead and use the elements
                        if (element === null) {
                            iframe.onload = function () {
                                element = iframe.contentWindow.document.getElementById(bugEditClassicID);
                                destinationElement = document.getElementById(bugEditClassicDestID);
                                showOrHideMarkdown(element, true, destinationElement, bugEditClassicCss);
                                addOrRemoveEventListener(element.ownerDocument, 'scroll', bugScroll);
                            };
                        } else {
                            showOrHideMarkdown(element, true, destinationElement, bugEditClassicCss);
                            addOrRemoveEventListener(element.ownerDocument, 'scroll', bugScroll);
                        }
                    }
                }, 200);

            } else if (location.href.indexOf(investigationEditClassicLocation) > -1 && location.href.indexOf(lightningLocation) == -1) {
                console.log('investigationedit classic'); // eslint-disable-line no-console
                // Wait for the iframe to be defined
                checkIframeExistence = setInterval(function () {
                    if (typeof(iframe) == 'undefined') {
                        var querySelectorAllIndex = 1;
                        iframe = getIframe(querySelectorAllIndex);
                    } else {
                        clearInterval(checkIframeExistence);
                        element = iframe.contentDocument.getElementById(investigationEditClassicID);
                        destinationElement = document.querySelector('.' + investigationEditClassicDestID);
                        //In this case, the iframe has not yet loaded, so we wait for it to load
                        //Otherwise, we just go right ahead and use the elements
                        if (element === null) {
                            iframe.onload = function () {
                                element = iframe.contentWindow.document.getElementById(investigationEditClassicID);
                                destinationElement = document.querySelector('.' + investigationEditClassicDestID);
                                showOrHideMarkdown(element, true, destinationElement, investigationEditClassicCss);
                                addOrRemoveEventListener(element.ownerDocument, 'scroll', bugScroll);
                            };
                        } else {
                            showOrHideMarkdown(element, true, destinationElement, investigationEditClassicCss);
                            addOrRemoveEventListener(element.ownerDocument, 'scroll', bugScroll);
                        }
                    }
                }, 200);

            } else if (location.href.indexOf(userStoryEditClassicLocation) > -1 && location.href.indexOf(lightningLocation) == -1) {
                console.log('userstoryedit classic'); // eslint-disable-line no-console
                element = document.getElementById(userStoryEditClassicID);
                destinationElement = element.parentElement;
                showOrHideMarkdown(element, true, destinationElement, userStoryEditClassicCss);
                addOrRemoveEventListener(element, 'scroll', userstoryScroll);

            } else if (location.href.indexOf(lightningLocation) > -1 && location.href.indexOf('view') > -1) {
                let interval = setInterval(function () {
                    let elements = document.querySelectorAll('div.slds-rich-text-editor__output.uiOutputRichText.forceOutputRichText');
                    if (elements.length > 0) {
                        var found = lightningDetailFindCorrectElement(elements, 'bugorinvestigationdetail lightning', interval);
                        if (found === false) {
                            elements = document.querySelectorAll('span.uiOutputTextArea');
                            if (elements.length > 0) {
                                lightningDetailFindCorrectElement(elements, 'userstorydetail lightning', interval);
                            }
                        }
                    } else {
                        elements = document.querySelectorAll('span.uiOutputTextArea');
                        if (elements.length > 0) {
                            lightningDetailFindCorrectElement(elements, 'userstorydetail lightning', interval);
                        }
                    }
                }, 500);

            } else if (location.href.indexOf(userStoryDetailClassicLocation) > -1 && location.href.indexOf(lightningLocation) == -1) {
                console.log('userstorydetail classic'); // eslint-disable-line no-console
                let element = document.getElementById(userStoryDetailClassicID);
                showOrHideMarkdown(element, false);

            } else if (location.href.indexOf(bugDetailClassicLocation) > -1 && location.href.indexOf(lightningLocation) == -1) {
                console.log('bugdetail classic'); // eslint-disable-line no-console
                let element = document.getElementById(bugDetailClassicID);
                showOrHideMarkdown(element, false);

            } else if (location.href.indexOf(investigationDetailClassicLocation) > -1 && location.href.indexOf(lightningLocation) == -1) {
                console.log('investigationdetail classic'); // eslint-disable-line no-console
                let element = document.getElementById(investigationDetailClassicID);
                showOrHideMarkdown(element, false);

            } else {
                window.gusMarkdownRun = false;
                console.log('not found'); // eslint-disable-line no-console
            }
        }
    }
}

// We run this when the script first fires up
initialize();


text:
import DS from 'ember-data';

export default DS.RESTAdapter.extend( {
  coalesceFindRequests: true,   // these blueprints support coalescing (reduces the amount of requests)
  namespace: '/',               // same as API prefix in Sails config
  host: 'http://localhost:8081' // Sails server
});


text:
package org.apache.nifi.components;

import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.context.PropertyContext;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.controller.ControllerServiceLookup;
import org.apache.nifi.expression.ExpressionLanguageCompiler;

import java.util.Collection;
import java.util.Map;
import java.util.function.Function;

public interface ValidationContext extends PropertyContext {

    /**
     * @return the {@link ControllerServiceLookup} which can be used to obtain
     * Controller Services
     */
    ControllerServiceLookup getControllerServiceLookup();

    /**
     * @param controllerService to lookup the validation context of
     * @return a ValidationContext that is appropriate for validating the given
     * {@link ControllerService}
     */
    ValidationContext getControllerServiceValidationContext(ControllerService controllerService);

    /**
     * @return a new {@link ExpressionLanguageCompiler} that can be used to
     * compile & evaluate Attribute Expressions
     */
    ExpressionLanguageCompiler newExpressionLanguageCompiler();

    /**
     * @param value to make a PropertyValue object for
     * @return a PropertyValue that represents the given value
     */
    PropertyValue newPropertyValue(String value);

    /**
     * @return a Map of all configured Properties
     */
    Map<PropertyDescriptor, String> getProperties();

    /**
     * @return the currently configured Annotation Data
     */
    String getAnnotationData();

    /**
     * There are times when the framework needs to consider a component valid,
     * even if it references an invalid ControllerService. This method will
     * return false if the component is to be considered valid even
     * if the given Controller Service is referenced and is invalid.
     *
     * @param service to check if validation is required
     * @return false if the component is to be considered valid
     * even if the given Controller Service is referenced and is invalid
     */
    boolean isValidationRequired(ControllerService service);

    /**
     * @param value to test whether expression language is present
     * @return true if the given value contains a NiFi Expression
     * Language expression, false if it does not
     */
    boolean isExpressionLanguagePresent(String value);

    /**
     * @param propertyName to test whether expression language is supported
     * @return true if the property with the given name supports
     * the NiFi Expression Language, false if the property does not
     * support the Expression Language or is not a valid property name
     */
    boolean isExpressionLanguageSupported(String propertyName);

    /**
     * Returns the identifier of the ProcessGroup that the component being validated lives in
     *
     * @return the identifier of the ProcessGroup that the component being validated lives in
     */
    String getProcessGroupIdentifier();

    /**
     * Returns a Collection containing the names of all Parameters that are referenced by the property with the given name
     * @return  a Collection containing the names of all Parameters that are referenced by the property with the given name
     */
    Collection<String> getReferencedParameters(String propertyName);

    /**
     * @param parameterName the name of the Parameter
     * @return true if a Parameter with the given name is defined in the currently selected Parameter Context
     */
    boolean isParameterDefined(String parameterName);

    /**
     * Returns true if a Parameter with the given name is defined and has a non-null value, false if either the Parameter
     * is not defined or the Parameter is defined but has a value of null.
     * @param parameterName the name of the parameter
     * @return true if the Parameter is defined and has a non-null value, false otherwise
     */
    boolean isParameterSet(String parameterName);

    /**
     * Determines whether or not the dependencies of the given Property Descriptor are satisfied.
     * If the given Property Descriptor has no dependency on another property, then the dependency is satisfied.
     * If there is at least one dependency, then all dependencies must be satisfied.
     * In order for a dependency to be considered satisfied, all of the following must be true:
     *

     *
The property that is depended upon has all of its dependencies satisfied.

     *
If the given Property Descriptor depends on a given AllowableValue, then the property that is depended upon has a value that falls within the given range of Allowable Values for
     *     the dependency.

     *

     *
     * @param propertyDescriptor the property descriptor
     * @param propertyDescriptorLookup a lookup for converting from a property name to the property descriptor with that name
     * @return true if all dependencies of the given property descriptor are satisfied, false otherwise
     */
    boolean isDependencySatisfied(PropertyDescriptor propertyDescriptor, Function<String, PropertyDescriptor> propertyDescriptorLookup);

    /**
     * Determines whether or not incoming and outgoing connections should be validated.
     * If true, then the validation should verify that all Relationships either have one or more connections that include the Relationship,
     * or that the Relationship is auto-terminated.
     * Additionally, if true, then any Processor with an {@link InputRequirement} of {@link InputRequirement.Requirement#INPUT_REQUIRED}
     * should be invalid unless it has an incoming (non-looping) connection, and any Processor with an {@link InputRequirement} of {@link InputRequirement.Requirement#INPUT_FORBIDDEN}
     * should be invalid if it does have any incoming connection.
     *
     * @return true if Connections should be validated, false if Connections should be ignored
     */
    default boolean isValidateConnections() {
        return true;
    }
}


text:
module PrepaidfactoryApi
  module Responses
    # Base class for Responses
    class Base < PrepaidfactoryApi::Base
      include Enumerable

      attr_reader :entities

      def initialize(response)
        @entities ||= []
        parse response
      end

      def parse(response)
        raise PrepaidfactoryApi::NotImplemented, 'This response object uses the default parse method but it should implement it\'s own'
      end

      def each(&block)
        @entities.each(&block)
      end

      def <<(val)
        @entities << val
      end
    end
  end
end


text:
<?php
namespace CLMVC\ViewEngines\WordPress;

use CLMVC\Events\Filter;
use CLMVC\Events\Hook;
use CLMVC\Events\View;
use CLMVC\Views\Shortcode;

/**
 * Class WpActionOverrides
 * @package CLMVC\ViewEngines\WordPress
 */
class WpActionOverrides {
    private $hooks = array('init', 'admin_init', 'admin_menu', 'set_plugin_has_updates' => 'update_option__transient_update_plugins', 'template_redirect');
    private $view_sections = array('print_styles' => 'wp_print_styles', 'print_scripts' => 'wp_print_scripts', 'admin_print_scripts', 'admin_print_styles', 'footer' => 'wp_footer', 'head' => 'wp_head', 'admin_head', 'admin_footer', 'wp_print_scripts', 'wp_footer', 'wp_print_styles', 'enqueue_scripts' => 'wp_enqueue_scripts');
    private $filters = array('query_vars', 'http_request_args', 'rewrite_rules_array', 'list_pages', 'rewrite_rules_array', 'rewrite_rules_array', 'set_plugin_has_updates' => 'pre_set_site_transient_update_plugins', 'template_include', 'after_plugin_row','document_title_parts', 'wp_title', 'status_header', 'pre_handle_404', 'do_parse_request', 'posts_request');

    public function init() {
        Shortcode::registerHandler('add_shortcode');
        $this->actions();
        $this->viewSections();
        $this->filters();
        add_action('wp_register_scripts', function () {
            Hook::run('scripts-register');
        });
        add_action('wp_register_style', function () {
            Hook::run('style-register');
        });

    }

    private function actions() {
        foreach ($this->hooks as $key => $hook) {
            if (is_numeric($key)) {
                Hook::registerHandler($hook, [$this, 'wp_hook_handler']);
            } else {
                Hook::registerHandler($key, [$this, 'wp_hook_handler']);
            }
        }
    }

    private function viewSections() {
        foreach ($this->view_sections as $key => $section) {
            if (is_numeric($key)) {
                View::registerHandler($section, [$this, 'wp_section_handler']);
            } else {
                View::registerHandler($key, [$this, 'wp_section_handler']);
            }
        }
    }

    private function filters() {
        foreach ($this->filters as $key => $filter) {
            if (is_numeric($key)) {
                Filter::registerHandler($filter, [$this, 'wp_filter_handler']);
            } else {
                Filter::registerHandler($key, [$this, 'wp_filter_handler']);
            }
        }
    }

    public function wp_hook_handler($hook, $callback, $priority = 100, $params = 1) {
        $new_hook = array_key_exists_v($hook, $this->hooks);
        if ($new_hook) {
            add_action($new_hook, $callback, $priority, $params);
        } else {
            add_action($hook, $callback, $priority, $params);
        }
    }

    public function wp_filter_handler($filter, $callback, $priority = 100, $params = 1) {
        $new_filter = array_key_exists_v($filter, $this->filters);
        if ($new_filter) {
            add_action($new_filter, $callback, $priority, $params);
        } else {
            add_action($filter, $callback, $priority, $params);
        }
    }

    public function wp_section_handler($section, $callback, $priority = 100, $params = 1) {
        $new_section = array_key_exists_v($section, $this->view_sections);
        if ($new_section) {
            add_action($new_section, $callback, $priority, $params);
        } else {
            add_action($section, $callback, $priority, $params);
        }
    }

    public function wp_section_handler_run($section, $params = array()) {
        $section = (array_key_exists_v($section, $this->view_sections)) ? : $section;
        if (!empty($params)) {
            call_user_func_array('do_action', array($section, $params));
        } else {
            call_user_func_array('do_action', array($section));
        }
    }
}