text:
require 'readline'
require 'uri'

module Elasticshell

  class Shell

    Settings.define(:passive_http_verb_format,
                    :description => "Format string for the passive HTTP verb GET.  The string `%v' will be replaced by the verb.",
                    :default     => "\e[34m%v",
                    :internal    => true)

    Settings.define(:active_http_verb_format,
                    :description => "Format string for the active HTTP verbs PUT, POST, and DELETE.  The string `%v' will be replaced by the verb.",
                    :default     => "\e[31m%v",
                    :internal    => true)

    Settings.define(:existing_scope_format,
                    :description => "Format string for an existing scope.  The string `%s' will be replaced by the scope name.",
                    :default     => "\e[32m%s",
                    :internal    => true)

    Settings.define(:missing_scope_format,
                    :description => "Format string for scope which doesn't exist.  The string `%s' will be replaced by the scope name.",
                    :default     => "\e[33m%s",
                    :internal    => true)

    Settings.define(:prompt_format,
                    :description => "Format string for the prompt.  The strings `%v' and `%s' will be replaced by the (already-formatted) HTTP verb and current scope name.",
                    :default     => "\e[1m%v %s$ \e[0m",
                    :internal    => true)

    Settings.define(:pretty_prompt_format,
                    :description => "Format string for the prompt when in pretty-mode.  The strings `%v' and `%s' will be replaced by the (already-formatted) HTTP verb and current scope name.",
                    :default     => "\e[1m%v %s$$ \e[0m",
                    :internal    => true)

    Settings.define(:scope_long_format,
                    :description => "Format string for displaying a scope in a long (`ll') listing.  The string `%s' will be replaced by the scope name.",
                    :default     => "s                          \e[32m%s\e[0m",
                    :internal    => true)

    Settings.define(:index_long_format,
                    :description => "Format string for displaying an index in a long (`ll') listing.  The string `%n' will be replaced by the index name, `%T' with the total number of shards, `%S' with the number of successful shards, `%F' with the number of failed shards, `%s' with the size in bytes, `%h' with the human-readable size",
                    :default     => "d  %S/%F  %h  \e[32m%n\e[0m",
                    :internal    => true)

    Settings.define(:request_long_format,
                    :description => "Format string for displaying a request in a long (`ll') listing.  The string `%r' will be replaced by the request name.",
                    :default     => "-                          %r",
                    :internal    => true)

    Settings.define(:scope_format,
                    :description => "Format string for displaying a scope in a listing.  The string `%s' will be replaced by the scope name.",
                    :default     => "\e[32m%s\e[0m",
                    :internal    => true)

    Settings.define(:request_format,
                    :description => "Format string for displaying a request in a listing.  The string `%r' will be replaced by the request name.",
                    :default     => "%r",
                    :internal    => true)

    include Elasticshell::HasVerb

    attr_accessor :client, :state, :only, :ruby_code, :input, :cache, :output, :line, :input_stream

    attr_reader :scope
    def scope= scope
      @scope = scope
      proc = scope.completion_proc
      Readline.completion_proc = Proc.new do |prefix|
        self.state = :completion
        proc.call(self, prefix)
      end
    end

    def path
      scope.path
    end

    def connected?
      client.connected?
    end

    def initialize options={}
      @interactive = false
      self.state  = :init
      self.client = Client.new(options)
      self.cache  = {}
      @initial_servers = (options[:servers] || [])
      self.verb   = (options[:verb] || 'GET')
      self.scope  = scope_from_path(options[:scope] || '/')
      self.only   = options[:only]
      self.ruby_code = options[:eval]
      self.input_stream  = (options[:input]  || $stdin)
      self.output = (options[:output] || $stdout)
      self.line   = 0
      @log_requests = (options[:log_requests] == false ? false : true)
      pretty! if options[:pretty]
    end

    def scope_from_path path
      if cache[path]
        cache[path]
      else
        cache[path] = Scopes.from_path(path, :client => self.client)
      end
    end

    def prompt
      verb_string  = Elasticshell.format((verb.to_s =~ /^(?:G|H)/i ? :passive_http_verb_format : :active_http_verb_format), "%v", verb.to_s.upcase)
      scope_string = Elasticshell.format((scope.exists? ? :existing_scope_format : :missing_scope_format), "%s", scope.path)
      Elasticshell.format((pretty? ? :pretty_prompt_format : :prompt_format), ["%s", "%v"], [scope_string, verb_string])
    end

    def pretty?
      @pretty
    end

    def pretty!
      @pretty = true
    end

    def not_pretty!
      @pretty = false
    end

    def interactive?
      @interactive
    end

    def setup
      trap("INT") do
        int
      end

      Readline.completer_word_break_characters = " \t\n\"\\'`$><=|&{("

      print <<EOF
Elasticshell v. #{Elasticshell.version}
Type "help" for contextual help.
EOF
      @interactive = true

      self.line = 1
    end

    def run
      setup
      connect
      loop
    end

    def connect
      eval_line("connect #{@initial_servers.join(' ')}")
    end

    def loop
      self.state = :read
      while line = Readline.readline(prompt, true)
        eval_line(line)
      end
      die
    end

    def eval_line line
      begin
        self.state = :eval
        self.input = line.strip
        command.evaluate!
      rescue ::Elasticshell::Error => e
        Elasticshell.error e.message
      end
      self.state = :read
      self.line += 1
      self
    end

    def command
      matching_command_class_name = Commands::PRIORITY.detect do |command_class_name|
        Commands.const_get(command_class_name).matches?(input)
      end

      # We should never hit the following ArgumentError as there
      # exists a catch-all command: Unknown
      raise ArgumentError.new("Could not parse command: '#{input}'") unless matching_command_class_name

      Commands.const_get(matching_command_class_name).new(self, input)
    end

    def print obj, ignore_only=false
      self.output.puts(format_output(obj, ignore_only))
    end

    def format_output obj, ignore_only=false
      case
      when self.only == true && !ignore_only
        format_output(obj, true)
      when self.only && !ignore_only
        format_only_part_of(obj)
      when obj.nil?
        nil
      when obj.is_a?(String) || obj.is_a?(Fixnum)
        obj
      when pretty?
        JSON.pretty_generate(obj)
      else
        obj.to_json
      end
    end

    def format_only_part_of obj
      only_parts = self.only.to_s.split('.')
      obj_to_print = obj
      while obj_to_print && only_parts.size > 0
        this_only = only_parts.shift
        obj_to_print = (obj_to_print || {})[this_only]
      end
      format_output(obj_to_print, true)
    end

    def int
      case self.state
      when :read
        $stdout.write("^C\n#{prompt}")
      else
        $stdout.write("^C...aborted\n#{prompt}")
      end
    end

    def die
      raise ShellError.new("C-d...quitting")
    end

    def log_requests?
      @log_requests
    end

  end
end


text:
package org.rioproject.watch;

import junit.framework.Assert;
import org.junit.Test;

import java.util.*;

/**
 * The class tests the Statistics class against its javadoc
 * specification. The class tests the public constructors, methods, and fields
 * declared in Statistics.
 */
public class StatisticsTest {
    /**
     * Tests the Statistics() constructor.
     */
    @Test
    public void testConstructor1() {
        Statistics stat = new Statistics();
        assertClean(stat);
    }

    /**
     * Tests the Statistics(Vector) constructor.
     */
    @Test
    public void testConstructor2() {

        final int N = 100;
        for (int size = 0; size < N; size++) {
            List<Double> list = new ArrayList<Double>();
            for (int j = 0; j < size; j++) {
                list.add((double) j);
            }
            Statistics stat = new Statistics(list);
            Assert.assertEquals(list, stat.getValues());
            Assert.assertNotSame(list, stat.getValues());
        }

        List<Double> list = new ArrayList<Double>();
        Statistics stat = new Statistics(list);
        Assert.assertEquals(0, stat.count());
        list.add((double) 0);
        Assert.assertEquals(0, stat.count());

        try {
            new Statistics(null);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }
    }

    /**
     * Tests the clearAll() method.
     *
     */
    @Test
    public void testClearAll() {

        Statistics stat = new Statistics();

        for (int i = 0; i < 5; i++) {
            stat.clearAll();
            assertClean(stat);
        }

        List<Double> list = new ArrayList<Double>();
        list.add((double) 0);
        list.add((double) 1);
        list.add((double) 2);
        stat.setValues(list);
        assertCorrect(list, stat);

        for (int i = 0; i < 5; i++) {
            stat.clearAll();
            assertClean(stat);
        }
    }

    /**
     * Tests statistical calculations
     */
    @Test
    public void testStats() {

        Statistics stat = new Statistics();

        for (int i = 0; i < 10; i++) {
            Vector<Double> v = new Vector<Double>();
            int count = (int) (Math.random() * 1000);
            for (int j = 0; j < count; j++) {
                double d = Math.random();
                stat.addValue(d);
                v.add(d);
            }
            assertCorrect(v, stat);
            stat.clearAll();
            assertCorrect(new Vector<Double>(), stat);
        }
    }

    /**
     * Tests the getValues() method.
     */
    @Test
    public void testGetValues() {

        Statistics stat = new Statistics();
        Assert.assertEquals(new Vector(), stat.getValues());

        for (int i = 0; i < 10; i++) {
            Vector<Double> v = new Vector<Double>();
            int count = (int) (Math.random() * 1000);
            for (int j = 0; j < count; j++) {
                double d = Math.random();
                stat.addValue(d);
                v.add(d);
            }
            Assert.assertEquals(v, stat.getValues());
            stat.clearAll();
            Assert.assertEquals(new Vector(), stat.getValues());
        }

        Vector<Double> v = new Vector<Double>();
        stat.setValues(v);
        Assert.assertEquals(v, stat.getValues());
        Assert.assertNotSame(v, stat.getValues());
    }

    /**
     * Tests the addValue(Double) method.
     */
    @Test
    public void testAddValue1() {
        Statistics stat = new Statistics();
        for (int i = 0; i < 10; i++) {
            Vector<Double> v = new Vector<Double>();
            int count = (int) (Math.random() * 100);
            for (int j = 0; j < count; j++) {
                Double d = Math.random();
                stat.addValue(d);
                v.add(d);
                assertCorrect(v, stat);
            }
            stat.clearAll();
        }

        try {
            stat.addValue(null);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }
    }

    /**
     * Tests the addValue(double) method.
     */
    @Test
    public void testAddValue2() {

        Statistics stat = new Statistics();

        for (int i = 0; i < 10; i++) {
            Vector<Double> v = new Vector<Double>();
            int count = (int) (Math.random() * 100);
            for (int j = 0; j < count; j++) {
                double d = Math.random();
                stat.addValue(d);
                v.add(d);
                assertCorrect(v, stat);
            }
            stat.clearAll();
        }
    }

    /**
     * Tests the setValues method.
     */
    @Test
    public void testSetValues() {

        Statistics stat = new Statistics();

        for (int i = 0; i < 10; i++) {
            Vector<Double> v = new Vector<Double>();
            int count = (int) (Math.random() * 100);
            for (int j = 0; j < count; j++) {
                v.add(Math.random());
                stat.setValues(v);
                Assert.assertEquals(v, stat.getValues());
                Assert.assertNotSame(v, stat.getValues());
            }
        }

        List<Double> v = new ArrayList<Double>();
        stat.setValues(v);
        Assert.assertEquals(0, stat.count());
        v.add((double) 0);
        Assert.assertEquals(0, stat.count());

        try {
            stat.setValues((List<Double>)null);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }
    }

    /**
     * Tests the removeValues(double, boolean) method.
     */
    @Test
    public void testRemoveValues1() {

        List<Double> vTest = asList(new double[]{
            1, 2, 3, 4, 5,
            1, 2, 3, 4, 5, 6,
            1, 2, 3, 4, 5, 6, 7,
            1, 2, 3, 4, 5, 6, 7, 8,
            1, 2, 3, 4, 5, 6, 7, 8, 9,
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10
        });

        {
            Statistics stat = new Statistics(vTest);
            for (int i = 0; i <= 10; i++) {
                stat.removeValues(i, false);
                vTest.remove(new Double(i));
                Assert.assertEquals(vTest, stat.getValues());
            }
        }

        {
            Statistics stat = new Statistics(vTest);
            for (int i = 0; i <= 10; i++) {
                stat.removeValues(i, true);
                vTest.removeAll(asList(new double[]{i}));
                Assert.assertEquals(vTest, stat.getValues());
            }
            assertClean(stat);
        }
    }

    /**
     * Tests the removeValues(Double, boolean) method.
     */
    @Test
    public void testRemoveValues2() {

        List<Double> vTest = asList(new double[]{
            1, 2, 3, 4, 5,
            1, 2, 3, 4, 5, 6,
            1, 2, 3, 4, 5, 6, 7,
            1, 2, 3, 4, 5, 6, 7, 8,
            1, 2, 3, 4, 5, 6, 7, 8, 9,
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10
        });

        {
            Statistics stat = new Statistics(vTest);
            for (int i = 0; i <= 10; i++) {
                stat.removeValues(new Double(i), false);
                vTest.remove(new Double(i));
                Assert.assertEquals(vTest, stat.getValues());
            }
        }

        {
            Statistics stat = new Statistics(vTest);
            for (int i = 0; i <= 10; i++) {
                stat.removeValues(new Double(i), true);
                vTest.removeAll(asList(new double[]{i}));
                Assert.assertEquals(vTest, stat.getValues());
            }
            assertClean(stat);
        }

        try {
            new Statistics().removeValues(null, false);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }

        try {
            new Statistics().removeValues(null, true);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }
    }

    /**
     * Tests the removeValue(int) method.
     */
    @Test
    public void testRemoveValue() {

        List<Double> v = asList(new double[]{
            1, 2, 3, 4, 5,
            1, 2, 3, 4, 5, 6,
            1, 2, 3, 4, 5, 6, 7,
            1, 2, 3, 4, 5, 6, 7, 8,
            1, 2, 3, 4, 5, 6, 7, 8, 9,
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10
        });

        Statistics stat = new Statistics(v);

        while (stat.count() > 0) {
            int i = (int) (Math.random() * stat.count());
            stat.removeValue(i);
            v.remove(i);
            Assert.assertEquals(v, stat.getValues());
        }
        assertClean(stat);

        v = asList(new double[]{1, 2, 3, 4, 5});
        stat.setValues(v);
        stat.removeValue(-1);
        stat.removeValue(5);
        Assert.assertEquals(v, stat.getValues());
    }

    /**
     * Tests the removeValues(Double, Double) method.
     */
    @Test
    public void testRemoveValues3() {

        List<Double> vOrg = asList(new double[]{
            1, 2, 3, 4, 5,
            1, 2, 3, 4, 5, 6,
            1, 2, 3, 4, 5, 6, 7,
            1, 2, 3, 4, 5, 6, 7, 8,
            1, 2, 3, 4, 5, 6, 7, 8, 9,
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10
        });
        Statistics stat = new Statistics(vOrg);

        stat.removeValues(new Double(3.5), new Double(3.6));
        Assert.assertEquals(vOrg, stat.getValues());

        stat.removeValues(new Double(3.6), new Double(3.5));
        Assert.assertEquals(vOrg, stat.getValues());

        stat.removeValues(new Double(100), new Double(-100));
        Assert.assertEquals(vOrg, stat.getValues());

        stat.removeValues(new Double(-100), new Double(100));
        Assert.assertEquals(new Vector(), stat.getValues());

        stat.setValues(vOrg);
        stat.removeValues(new Double(3), new Double(3));
        Assert.assertEquals(asList(new double[]{
            1, 2, 4, 5,
            1, 2, 4, 5, 6,
            1, 2, 4, 5, 6, 7,
            1, 2, 4, 5, 6, 7, 8,
            1, 2, 4, 5, 6, 7, 8, 9,
            1, 2, 4, 5, 6, 7, 8, 9, 10
        }), stat.getValues());

        stat.setValues(vOrg);
        stat.removeValues(new Double(3.5), new Double(4.5));
        Assert.assertEquals(asList(new double[]{
            1, 2, 3, 5,
            1, 2, 3, 5, 6,
            1, 2, 3, 5, 6, 7,
            1, 2, 3, 5, 6, 7, 8,
            1, 2, 3, 5, 6, 7, 8, 9,
            1, 2, 3, 5, 6, 7, 8, 9, 10
        }), stat.getValues());

        stat.setValues(vOrg);
        stat.removeValues(new Double(1.1), new Double(9));
        Assert.assertEquals(asList(new double[]{
            1,
            1,
            1,
            1,
            1,
            1, 10
        }), stat.getValues());

        try {
            stat.removeValues(null, (double) 0);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }

        try {
            stat.removeValues((double) 0, null);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }

        try {
            stat.removeValues(null, null);
            Assert.fail("IllegalArgumentException expected but not thrown");
        } catch (IllegalArgumentException e) {
        }
    }

    /**
     * Tests the removeValues(double, double) method.
     */
    @Test
    public void testRemoveValues4() {

        List<Double> vOrg = asList(new double[]{
            1, 2, 3, 4, 5,
            1, 2, 3, 4, 5, 6,
            1, 2, 3, 4, 5, 6, 7,
            1, 2, 3, 4, 5, 6, 7, 8,
            1, 2, 3, 4, 5, 6, 7, 8, 9,
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10
        });
        Statistics stat = new Statistics(vOrg);

        stat.removeValues(3.5, 3.6);
        Assert.assertEquals(vOrg, stat.getValues());

        stat.removeValues(3.6, 3.5);
        Assert.assertEquals(vOrg, stat.getValues());

        stat.removeValues(100, -100);
        Assert.assertEquals(vOrg, stat.getValues());

        stat.removeValues(-100, 100);
        Assert.assertEquals(new Vector(), stat.getValues());

        stat.setValues(vOrg);
        stat.removeValues(3, 3);
        Assert.assertEquals(asList(new double[]{
            1, 2, 4, 5,
            1, 2, 4, 5, 6,
            1, 2, 4, 5, 6, 7,
            1, 2, 4, 5, 6, 7, 8,
            1, 2, 4, 5, 6, 7, 8, 9,
            1, 2, 4, 5, 6, 7, 8, 9, 10
        }), stat.getValues());

        stat.setValues(vOrg);
        stat.removeValues(3.5, 4.5);
        Assert.assertEquals(asList(new double[]{
            1, 2, 3, 5,
            1, 2, 3, 5, 6,
            1, 2, 3, 5, 6, 7,
            1, 2, 3, 5, 6, 7, 8,
            1, 2, 3, 5, 6, 7, 8, 9,
            1, 2, 3, 5, 6, 7, 8, 9, 10
        }), stat.getValues());

        stat.setValues(vOrg);
        stat.removeValues(1.1, 9);
        Assert.assertEquals(asList(new double[]{
            1,
            1,
            1,
            1,
            1,
            1, 10
        }), stat.getValues());
    }

    /*
     * Asserts that a given Statistics object is clean, that is,
     * contains no values.
     */
    private void assertClean(Statistics stat) {
        Assert.assertEquals(0, stat.count());
        Assert.assertTrue(Double.isNaN(stat.max()));
        Assert.assertTrue(Double.isNaN(stat.min()));
        Assert.assertTrue(Double.isNaN(stat.mean()));
        Assert.assertTrue(Double.isNaN(stat.median()));
        Assert.assertTrue(Double.isNaN(stat.mode()));
        Assert.assertEquals(0, stat.modeOccurrenceCount());
        Assert.assertTrue(Double.isNaN(stat.range()));
        Assert.assertTrue(Double.isNaN(stat.standardDeviation()));
        Assert.assertEquals(0, stat.getValues().size());
        Assert.assertTrue(Double.isNaN(stat.sum()));
    }

    /*
     * Asserts that a given Statistics object produces correct
     * statistical results.
     */
    private void assertCorrect(List<Double> v, Statistics stat) {
        if (v.size() > 0) {
            Assert.assertEquals(count(v), stat.count());
            Assert.assertEquals(max(v), stat.max(), 0);
            Assert.assertEquals(min(v), stat.min(), 0);
            Assert.assertEquals(mean(v), stat.mean(), 0);
            Assert.assertEquals(median(v), stat.median(), 0);
            Assert.assertEquals(mode(v), stat.mode(), 0);
            Assert.assertEquals(modeOccurrenceCount(v),
                                stat.modeOccurrenceCount());
            Assert.assertEquals(range(v), stat.range(), 0);
            Assert.assertEquals(standardDeviation(v),
                                stat.standardDeviation(), 0);
            Assert.assertEquals(v, stat.getValues());
            Assert.assertEquals(sum(v), stat.sum(), 0);
        } else {
            assertClean(stat);
        }
    }

    private int count(List<Double> v) {
        return v.size();
    }

    private double max(List<Double> v) {
        if (v.isEmpty()) return Double.NaN;
        return Collections.max(v);
    }

    private double min(List<Double> v) {
        if (v.isEmpty()) return Double.NaN;
        return Collections.min(v);
    }

    private double mean(List<Double> v) {
        if (v.isEmpty()) return Double.NaN;
        double sum = sum(v);
        return sum / (double) v.size();
    }

    private double median(List<Double> v) {
        if (v.isEmpty())
            return Double.NaN;
        double result;
        List<Double> sortedV = sorted(v);
        Double[] dArray = new Double[v.size()];
        dArray = sortedV.toArray(dArray);

        if (dArray.length % 2 != 0 && dArray.length > 0) {
            // length is odd
            int k = (dArray.length - 1) / 2; // middle index
            result = dArray[k];
        } else { // length is even, take avg of two mid vals
            int k = (dArray.length - 1) / 2; // low middle index
            /* average of low mid val and low mid idx+1 val */
            result =
                (dArray[k] + dArray[k + 1]) / 2D;
        }
        return result;
    }

    private double mode(List<Double> v) {
        if (v.isEmpty()) return Double.NaN;
        return (Double) mode0(v, true);
    }

    private int modeOccurrenceCount(List<Double> v) {
        if (v.isEmpty())
            return (0);
        return (Integer) mode0(v, false);
    }

    private Object mode0(List<Double> v, boolean returnMode) {
        Map<Object, Integer> hashtable = new HashMap<Object, Integer>(v.size());
        Object obj;
        Integer occurrences = 0;
        Integer cnt;
        int modeCnt = 0;
        Double mode = 0.0D;

        Iterator it = v.iterator();
        while (it.hasNext()) {
            obj = it.next();
            if (hashtable.containsKey(obj)) {
                modeCnt = (hashtable.get(obj)) + 1;
            } else {
                modeCnt = 1;
            }
            hashtable.put(obj, modeCnt);
        }

        it = v.iterator();
        while (it.hasNext()) {
            obj = it.next();
            cnt = hashtable.get(obj);
            if ((cnt) > modeCnt) {
                mode = (Double) obj;
                occurrences = cnt;
            }
        }

        if (returnMode) {
            return mode;
        } else {
            return occurrences;
        }
    }

    private double range(List<Double> v) {
        if (v.isEmpty())
            return Double.NaN;
        else
            return max(v) - min(v);
    }

    private double standardDeviation(List<Double> v) {
        if (v.isEmpty()) {
            return Double.NaN;
        }
        if (v.size() == 1) {
            // Need to return 0 explicitly because otherwise there would
            // be division by zero
            return 0;
        }
        double sum = sum(v);
        double sumOfSquares = 0.0D;

        for (Double aV : v) {
            sumOfSquares += Math.pow(aV, 2D);
        }
        return Math.sqrt((sumOfSquares - Math.pow(sum, 2d) /
                                         (double) v.size()) /
                         (double) (v.size() - 1));

    }

    private double sum(List<Double> v) {
        if (v.isEmpty())
            return Double.NaN;

        double tot = 0.0D;
        for (Double aV : v) {
            tot += aV;
        }
        return tot;
    }

    private List<Double> sorted(List<Double> v) {
        List<Double> cpy = new ArrayList<Double>(v);
        Collections.sort(cpy);
        return cpy;
    }

    private List<Double> asList(double[] doubles) {
        List<Double> v = new ArrayList<Double>();
        for (double aDouble : doubles) {
            v.add(aDouble);
        }
        return v;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//  See http://www.boost.org/libs/config for the most recent version.//
//  Revision $Id: no_char32_t_pass.cpp 79537 2012-07-15 15:59:05Z marshall $
//

// Test file for macro BOOST_NO_CXX11_CHAR32_T
// This file should compile, if it does not then
// BOOST_NO_CXX11_CHAR32_T should be defined.
// See file boost_no_char32_t.ipp for details

// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
#  undef BOOST_ASSERT_CONFIG
#endif

#include <boost/config.hpp>
#include "test.hpp"

#ifndef BOOST_NO_CXX11_CHAR32_T
#include "boost_no_char32_t.ipp"
#else
namespace boost_no_char32_t = empty_boost;
#endif

int main( int, char *[] )
{
   return boost_no_char32_t::test();
}


text:
<!DOCTYPE HTML>

		<title>redports.org</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />

		<link rel="stylesheet" href="assets/css/main.css" type="text/css" media="all" />

Home

<?php if(isset($_SESSION['username'])) { ?>

Repositories

<a href="<?php echo $_SESSION['profile_url']; ?>"><?php echo $_SESSION['name']; ?>

<?php } else { ?>

Features

Login

<?php } ?>


text:
<?php

namespace ZendPdf\Color;

use ZendPdf\InternalType;

/**
 * GrayScale color implementation
 *
 * @category   Zend
 * @package    Zend_PDF
 * @subpackage Zend_PDF_Color
 */
class GrayScale implements ColorInterface
{
    /**
     * GrayLevel.
     * 0.0 (black) - 1.0 (white)
     *
     * @var \ZendPdf\InternalType\NumericObject
     */
    private $_grayLevel;

    /**
     * Object constructor
     *
     * @param float $grayLevel
     */
    public function __construct($grayLevel)
    {
        if ($grayLevel < 0) { $grayLevel = 0; }
        if ($grayLevel > 1) { $grayLevel = 1; }

        $this->_grayLevel = new InternalType\NumericObject($grayLevel);
    }

    /**
     * Instructions, which can be directly inserted into content stream
     * to switch color.
     * Color set instructions differ for stroking and nonstroking operations.
     *
     * @param boolean $stroking
     * @return string
     */
    public function instructions($stroking)
    {
        return $this->_grayLevel->toString() . ($stroking? " G\n" : " g\n");
    }

    /**
     * Get color components (color space dependent)
     *
     * @return array
     */
    public function getComponents()
    {
        return array($this->_grayLevel->value);
    }
}


text:
<?php

namespace webignition\HtmlValidatorOutput\Parser;

use webignition\InternetMediaTypeInterface\InternetMediaTypeInterface;

class HeaderValues
{
    private $contentType;
    private $wasAborted;

    public function __construct(bool $wasAborted, InternetMediaTypeInterface $contentType)
    {
        $this->contentType = $contentType;
        $this->wasAborted = $wasAborted;
    }

    public function getContentType(): InternetMediaTypeInterface
    {
        return $this->contentType;
    }

    public function getWasAborted(): bool
    {
        return $this->wasAborted;
    }
}


text:
// Copyright (C) 2006, 2007, 2008, 2009 Free Software Foundation
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3.  If not see
// <http://www.gnu.org/licenses/>.

// 20.6.6.2 Template class shared_ptr [util.smartptr.shared]

// { dg-do run { target *-*-freebsd* *-*-netbsd* *-*-linux* *-*-solaris* *-*-cygwin *-*-darwin* alpha*-*-osf* mips-sgi-irix6* } }
// { dg-options " -std=gnu++0x -pthread" { target *-*-freebsd* *-*-netbsd* *-*-linux* alpha*-*-osf* mips-sgi-irix6* } }
// { dg-options " -std=gnu++0x -pthreads" { target *-*-solaris* } }
// { dg-options " -std=gnu++0x " { target *-*-cygwin *-*-darwin* } }

#include <memory>
#include <random>
#include <vector>
#include <testsuite_hooks.h>
#include <iostream>
#include <cstdlib>

#include <pthread.h>

#ifdef _GLIBCXX_HAVE_UNISTD_H
#include <unistd.h>	// To test for _POSIX_THREAD_PRIORITY_SCHEDULING
#endif

/* This (brute-force) tests the atomicity and thus thread safety of the
 * shared_ptr <- weak_ptr
 * assignment operation by allocating a test object, retrieving a weak
 * reference to it, and letting a number of threads repeatedly create strong
 * references from the weak reference.
 * Specifically, this tests the function _Sp_counted_base<true>::add_ref_lock()
 */

const unsigned int HAMMER_MAX_THREADS = 10;
const unsigned int POOL_SIZE = 1000;
const unsigned long HAMMER_REPEAT = 100000;
const unsigned long KILL_ONE_IN = 1000;

struct A
  {
    static _Atomic_word counter;
    A()
      {
	__gnu_cxx::__atomic_add(&counter, 1);
      }
    ~A()
      {
	__gnu_cxx::__atomic_add(&counter, -1);
      }
  };

_Atomic_word A::counter = 0;

using std::_S_mutex;

typedef std::__shared_ptr<A, _S_mutex> sp_A_t;
typedef std::__weak_ptr<A, _S_mutex> wp_A_t;

typedef std::vector<sp_A_t> sp_vector_t;
typedef std::vector<wp_A_t> wp_vector_t;

struct shared_and_weak_pools
{
  sp_vector_t& shared_pool;
  wp_vector_t& weak_pool;

  shared_and_weak_pools(sp_vector_t& _shared_pool, wp_vector_t& _weak_pool)
    : shared_pool(_shared_pool), weak_pool(_weak_pool)
    { }
};

void* thread_hammer_and_kill(void* opaque_pools)
{
  shared_and_weak_pools& pools = *static_cast<shared_and_weak_pools*>(opaque_pools);
  // Using the same parameters as in the RNG test cases.
  std::mersenne_twister_engine<
    unsigned long, 32, 624, 397, 31,
    0x9908b0dful, 11,
    0xfffffffful, 7,
    0x9d2c5680ul, 15,
    0xefc60000ul, 18, 1812433253ul> rng;

  sp_vector_t::iterator cur_shared = pools.shared_pool.begin();
  wp_vector_t::iterator cur_weak = pools.weak_pool.begin();

  for (unsigned int i = 0; i < HAMMER_REPEAT; ++i)
    {
      try
      {
        sp_A_t strong(*cur_weak);
      }
      catch (std::bad_weak_ptr& exception)
      {
        ++cur_weak;
        if (cur_weak == pools.weak_pool.end())
          break;
      }

      if (rng() % KILL_ONE_IN == 0)
      {
        cur_shared->reset();
        ++cur_shared;
      }
    }
  return 0;
}

void* thread_hammer(void* opaque_weak)
{
  wp_vector_t& weak_pool = *static_cast<wp_vector_t*>(opaque_weak);
  // Using the same parameters as in the RNG test cases.
  std::mersenne_twister_engine<
    unsigned long, 32, 624, 397, 31,
    0x9908b0dful, 11,
    0xfffffffful, 7,
    0x9d2c5680ul, 15,
    0xefc60000ul, 18, 1812433253ul> rng;

  wp_vector_t::iterator cur_weak = weak_pool.begin();

  for (unsigned int i = 0; i < HAMMER_REPEAT; ++i)
    {
      try
      {
        sp_A_t strong(*cur_weak);
      }
      catch (std::bad_weak_ptr& exception)
      {
        ++cur_weak;
        if (cur_weak == weak_pool.end())
          break;
      }
    }
  return 0;
}

int
test01()
{
  bool test __attribute__((unused)) = true;
  sp_vector_t obj_pool(POOL_SIZE);

  for(sp_vector_t::iterator cur = obj_pool.begin(); cur != obj_pool.end(); ++cur)
  {
    cur->reset(new A);
  }
  // Obtain weak references.
  std::vector<wp_vector_t> weak_pool(HAMMER_MAX_THREADS, wp_vector_t(obj_pool.begin(), obj_pool.end()));

  // Launch threads with pointer to weak reference.
  pthread_t threads[HAMMER_MAX_THREADS];
#if defined(__sun) && defined(__svr4__) && _XOPEN_VERSION >= 500
  pthread_setconcurrency (HAMMER_MAX_THREADS);
#endif

  pthread_attr_t tattr;
  pthread_attr_init(&tattr);

  shared_and_weak_pools pools(obj_pool, weak_pool[0]);
  pthread_create(threads, &tattr, thread_hammer_and_kill, static_cast<void*>(&pools));
  for (unsigned int worker = 1; worker < HAMMER_MAX_THREADS; worker++)
    {
      if (pthread_create(&threads[worker], &tattr,
			 thread_hammer, static_cast<void*>(&weak_pool[worker])))
	std::abort();
    }
  // Wait for threads to complete, then check integrity of reference.
  void* status;
  for (unsigned int worker = 0; worker < HAMMER_MAX_THREADS; worker++)
    {
      if (pthread_join(threads[worker], &status))
	std::abort();
    }
  obj_pool.clear();

  VERIFY( A::counter == 0 );

  return 0;
}

int
main()
{
  test01();
  return 0;
}


text:
yum -y update
yum -y upgrade

# setup systemd to boot to the right runlevel
echo -n "Setting default runlevel to multiuser text mode"
rm -f /etc/systemd/system/default.target
ln -s /lib/systemd/system/multi-user.target /etc/systemd/system/default.target

# If you want to remove rsyslog and just use journald, remove this!
echo -n "Disabling persistent journal"
rmdir /var/log/journal/

# Non-firewalld-firewall
echo -n "Writing static firewall"
cat > /etc/sysconfig/iptables <<'EOF'
# Simple static firewall loaded by iptables.service. Replace
# this with your own custom rules, run lokkit, or switch to
# shorewall or firewalld as your needs dictate.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
EOF

echo -n "Getty fixes"
# although we want console output going to the serial console, we don't
# actually have the opportunity to login there. FIX.
# we don't really need to auto-spawn _any_ gettys.
#sed -i '/^#NAutoVTs=.*/ a\
#NAutoVTs=0' /etc/systemd/logind.conf

echo -n "Network fixes"
# initscripts don't like this file to be missing.
cat > /etc/sysconfig/network << EOF
NETWORKING=yes
NOZEROCONF=yes
EOF

# For cloud images, 'eth0' _is_ the predictable device name, since
# we don't want to be tied to specific virtual (!) hardware
#echo -n > /etc/udev/rules.d/70-persistent-net.rules
#echo -n > /lib/udev/rules.d/75-persistent-net-generator.rules
#ln -s /dev/null /etc/udev/rules.d/80-net-name-slot.rules

# simple eth0 config, again not hard-coded to the build hardware
#cat > /etc/sysconfig/network-scripts/ifcfg-eth0 << EOF
#DEVICE="eth0"
#BOOTPROTO="static"
#ONBOOT="yes"
#TYPE="Ethernet"
#EOF

# generic localhost names
cat > /etc/hosts << EOF
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
EOF

# Because memory is scarce resource in most cloud/virt environments,
# and because this impedes forensics, we are differing from the Fedora
# default of having /tmp on tmpfs.
echo "Disabling tmpfs for /tmp."
systemctl mask tmp.mount

# set some stuff
#echo 'net.ipv4.conf.eth0.arp_notify = 1' >> /etc/sysctl.conf
#echo 'vm.swappiness = 0' >> /etc/sysctl.conf

cat >> /etc/sysctl.conf <<'EOF'
net.ipv4.tcp_rmem = 4096 87380 33554432
net.ipv4.tcp_wmem = 4096 65536 33554432
net.core.rmem_max = 33554432
net.core.wmem_max = 33554432
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_sack = 1
EOF

# disable auto fsck on boot
cat > /etc/sysconfig/autofsck << EOF
AUTOFSCK_DEF_CHECK=yes
PROMPT=no
AUTOFSCK_OPT="-y"
AUTOFSCK_TIMEOUT=10
EOF

# set rackspace mirrors
sed -i 's/mirror.centos.org/mirror.rackspace.com/g' /etc/yum.repos.d/CentOS-Base.repo
sed -i 's%baseurl.*%baseurl=http://mirror.rackspace.com/epel/6/x86_64/%g' /etc/yum.repos.d/epel.repo
sed -i '/baseurl/s/# *//' /etc/yum.repos.d/CentOS-Base.repo
sed -i '/baseurl/s/# *//' /etc/yum.repos.d/epel.repo
sed -i '/mirrorlist/s/^/#/' /etc/yum.repos.d/CentOS-Base.repo
sed -i '/mirrorlist/s/^/#/' /etc/yum.repos.d/epel.repo

# install custom cloud-init and lock version
#wget http://559bf13610f1c068ef67-1f39c9b68192359d629954d9e4642580.r76.cf2.rackcdn.com/cloud-init-0.7.5-14rackspace.x86_64.rpm
wget http://KICK_HOST/cloud-init/cloud-init-0.7.7-el6.rpm
rpm -Uvh --nodeps cloud*.rpm
yum versionlock add cloud-init
pip install pyserial
chkconfig cloud-init on
sed -i '/import sys/a reload(sys)\nsys.setdefaultencoding("Cp1252")' /usr/lib/python2.6/site-packages/configobj.py

# more cloud-init logging
sed -i 's/WARNING/DEBUG/g' /etc/cloud/cloud.cfg.d/05_logging.cfg

# hack for teeth sd* labeling
tune2fs -L / /dev/sda1
cat > /etc/fstab <<'EOF'
LABEL=/ / ext3 errors=remount-ro,noatime 0 1
EOF

# another teeth specific
cat > /etc/sysconfig/modules/onmetal.modules <<'EOF'
#!/bin/sh
exec /sbin/modprobe bonding >/dev/null 2>&1
exec /sbin/modprobe 8021q >/dev/null 2>&1
EOF
chmod +x /etc/sysconfig/modules/onmetal.modules
#
cat > /etc/modprobe.d/blacklist-mei.conf <<'EOF'
blacklist mei_me
EOF
dracut -f

# our cloud-init config
cat > /etc/cloud/cloud.cfg.d/10_rackspace.cfg <<'EOF'
datasource_list: [ ConfigDrive, None ]
disable_root: False
ssh_pwauth: True
ssh_deletekeys: False
resize_rootfs: noblock
manage_etc_hosts: True
growpart:
  mode: auto
  devices: ['/']
system_info:
  distro: rhel
  ssh_svcname: sshd
  default_user:
    name: root
    lock_passwd: True
    gecos: CentOS cloud-init user
    shell: /bin/bash
cloud_config_modules:
 - disk_setup
 - mounts
 - ssh-import-id
 - locale
 - set-passwords
 - package-update-upgrade-install
 - landscape
 - timezone
 - puppet
 - chef
 - salt-minion
 - mcollective
 - disable-ec2-metadata
 - runcmd
 - byobu
EOF

# force grub to use generic disk labels, bootloader above does not do this
#sed -i 's%root=.*%root=LABEL=/ console=ttyS4,115200n8 8250.nr_uarts=5 modprobe.blacklist=mei_me selinux=0%g' /boot/grub/grub.conf
sed -i 's%root=.*%root=LABEL=/ 8250.nr_uarts=5 modprobe.blacklist=mei_me selinux=0%g' /boot/grub/grub.conf
sed -i '/splashimage/d' /boot/grub/grub.conf
sed -i 'g/SELINUX=*/SELINUX=permissive/s' /etc/selinux/config

# log packages
wget http://KICK_HOST/kickstarts/package_postback.sh
bash package_postback.sh CentOS_6_Teeth

# clean up
yum clean all
passwd -d root
passwd -l root
truncate -c -s 0 /var/log/yum.log
rm -f /etc/ssh/ssh_host_*
rm -f /etc/resolv.conf
rm -f /root/.bash_history
rm -f /root/.nano_history
rm -f /root/.lesshst
rm -f /root/.ssh/known_hosts
rm -f /root/anaconda-ks.cfg
rm -rf /tmp/tmp
for k in $(find /tmp -type f); do rm -f $k; done
for k in $(find /root -type f \( ! -iname ".*" \)); do rm -f $k; done
for k in $(find /var/log -type f); do echo > $k; done


text:
<?php

declare(strict_types=1);

namespace StructType;

use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for AddressDelivery_Type StructType
 * Meta information extracted from the WSDL
 * - documentation: The delivery address of the customer. This is a verified address on Location Register.
 * @package Api
 * @subpackage Structs
 * @release 1.1.0
 */
class ApiAddressDelivery_Type extends AbstractStructBase
{
    /**
     * The Street1
     * Meta information extracted from the WSDL
     * - documentation: First line on delivery address
     * - base: string
     * @var string|null
     */
    protected ?string $Street1 = null;
    /**
     * The Street2
     * Meta information extracted from the WSDL
     * - documentation: Second line on delivery address
     * - base: string
     * @var string|null
     */
    protected ?string $Street2 = null;
    /**
     * The Street3
     * Meta information extracted from the WSDL
     * - documentation: Third line on delivery address
     * - base: string
     * @var string|null
     */
    protected ?string $Street3 = null;
    /**
     * The City
     * Meta information extracted from the WSDL
     * - documentation: The delivery city
     * - base: string
     * @var string|null
     */
    protected ?string $City = null;
    /**
     * The PostalCode
     * Meta information extracted from the WSDL
     * - documentation: Postal code for the city
     * - base: string
     * - length: 4
     * @var string|null
     */
    protected ?string $PostalCode = null;
    /**
     * Constructor method for AddressDelivery_Type
     * @uses ApiAddressDelivery_Type::setStreet1()
     * @uses ApiAddressDelivery_Type::setStreet2()
     * @uses ApiAddressDelivery_Type::setStreet3()
     * @uses ApiAddressDelivery_Type::setCity()
     * @uses ApiAddressDelivery_Type::setPostalCode()
     * @param string $street1
     * @param string $street2
     * @param string $street3
     * @param string $city
     * @param string $postalCode
     */
    public function __construct(?string $street1 = null, ?string $street2 = null, ?string $street3 = null, ?string $city = null, ?string $postalCode = null)
    {
        $this
            ->setStreet1($street1)
            ->setStreet2($street2)
            ->setStreet3($street3)
            ->setCity($city)
            ->setPostalCode($postalCode);
    }
    /**
     * Get Street1 value
     * @return string|null
     */
    public function getStreet1(): ?string
    {
        return $this->Street1;
    }
    /**
     * Set Street1 value
     * @param string $street1
     * @return \StructType\ApiAddressDelivery_Type
     */
    public function setStreet1(?string $street1 = null): self
    {
        // validation for constraint: string
        if (!is_null($street1) && !is_string($street1)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($street1, true), gettype($street1)), __LINE__);
        }
        $this->Street1 = $street1;

        return $this;
    }
    /**
     * Get Street2 value
     * @return string|null
     */
    public function getStreet2(): ?string
    {
        return $this->Street2;
    }
    /**
     * Set Street2 value
     * @param string $street2
     * @return \StructType\ApiAddressDelivery_Type
     */
    public function setStreet2(?string $street2 = null): self
    {
        // validation for constraint: string
        if (!is_null($street2) && !is_string($street2)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($street2, true), gettype($street2)), __LINE__);
        }
        $this->Street2 = $street2;

        return $this;
    }
    /**
     * Get Street3 value
     * @return string|null
     */
    public function getStreet3(): ?string
    {
        return $this->Street3;
    }
    /**
     * Set Street3 value
     * @param string $street3
     * @return \StructType\ApiAddressDelivery_Type
     */
    public function setStreet3(?string $street3 = null): self
    {
        // validation for constraint: string
        if (!is_null($street3) && !is_string($street3)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($street3, true), gettype($street3)), __LINE__);
        }
        $this->Street3 = $street3;

        return $this;
    }
    /**
     * Get City value
     * @return string|null
     */
    public function getCity(): ?string
    {
        return $this->City;
    }
    /**
     * Set City value
     * @param string $city
     * @return \StructType\ApiAddressDelivery_Type
     */
    public function setCity(?string $city = null): self
    {
        // validation for constraint: string
        if (!is_null($city) && !is_string($city)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($city, true), gettype($city)), __LINE__);
        }
        $this->City = $city;

        return $this;
    }
    /**
     * Get PostalCode value
     * @return string|null
     */
    public function getPostalCode(): ?string
    {
        return $this->PostalCode;
    }
    /**
     * Set PostalCode value
     * @param string $postalCode
     * @return \StructType\ApiAddressDelivery_Type
     */
    public function setPostalCode(?string $postalCode = null): self
    {
        // validation for constraint: string
        if (!is_null($postalCode) && !is_string($postalCode)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($postalCode, true), gettype($postalCode)), __LINE__);
        }
        // validation for constraint: length(4)
        if (!is_null($postalCode) && mb_strlen((string) $postalCode) !== 4) {
            throw new InvalidArgumentException(sprintf('Invalid length of %s, the number of characters/octets contained by the literal must be equal to 4', mb_strlen((string) $postalCode)), __LINE__);
        }
        $this->PostalCode = $postalCode;

        return $this;
    }
}


text:
<?php namespace Anomaly\PagesModule\Page\Command;

use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\PagesModule\Page\Contract\PageRepositoryInterface;

/**
 * Class UnsetHome
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 */
class UnsetHome
{

    /**
     * The page instance.
     *
     * @var PageInterface
     */
    protected $page;

    /**
     * Create a new UnsetHome instance.
     *
     * @param PageInterface $page
     */
    public function __construct(PageInterface $page)
    {
        $this->page = $page;
    }

    /**
     * Handle the command.
     *
     * @param PageRepositoryInterface $pages
     */
    public function handle(PageRepositoryInterface $pages)
    {
        if ($this->page->isHome()) {
            $pages->unsetHomePages();
        }
    }
}


text:
using System;
using Mono.Addins;
using Mono.Addins.Description;

[assembly:Addin ("TypeScript",
	Namespace = "MonoDevelop",
	Version = MonoDevelop.BuildInfo.Version,
	Category = "Language bindings")]

[assembly:AddinName ("TypeScript Language Binding")]
[assembly:AddinDescription ("Adds TypeScript support.")]

[assembly:AddinDependency ("Core", MonoDevelop.BuildInfo.Version)]
[assembly:AddinDependency ("Ide", MonoDevelop.BuildInfo.Version)]
[assembly:AddinDependency ("Refactoring", MonoDevelop.BuildInfo.Version)]
[assembly:AddinDependency ("SourceEditor2", MonoDevelop.BuildInfo.Version)]


text:
@interface MockWriteableDb : NSObject<ESWritableDbWrapper>

-(NSArray*)queriesLog;

@end


text:
import React, { Component } from 'react';
import './App.css';

import ndarray from 'ndarray';
import ops from 'ndarray-ops';

import { food101topK } from './utils';

const loadImage = window.loadImage;

const mapProb = (prob) => {
  if (prob * 100 < 2) {
    return '2%';
  } else {
    return (prob * 100 + '%');
  }
}

const Predictions = ({topK}) => {
  return (

        Prediction
        Probability

      { topK.map((pred, i) =>

          {pred.name}

            {(pred.probability*100).toFixed(5)}%

      )}

  );
}

class App extends Component {

  constructor() {
    super();

    let hasWebgl = false;
    const canvas = document.createElement('canvas');
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    // Report the result.
    if (gl && gl instanceof WebGLRenderingContext) {
      hasWebgl = true;
    } else {
      hasWebgl = false;
    }
    console.log('WebGL enabled:', hasWebgl);

    this.urlInput = null;
    this.state = {
      model: null,
      modelLoaded: false,
      modelLoading: false,
      modelRunning: false,
      imageLoadingError: false,
      loadingPercent: 0,
      classifyPercent: 0,
      topK: null,
      hasWebgl,
      url: 'http://www.rawtillwhenever.com/wp-content/uploads/2015/09/vegan-tempura-sushi-2.png'
    };
  }

  loadModel = () => {
    console.log('Loading Model');
    const model = new window.KerasJS.Model({
      filepaths: {
        model: 'model.json' ,
        weights: 'https://s3.amazonaws.com/stratospark/food-101/model4b.10-0.68_weights.buf',
        metadata: 'model4b.10-0.68_metadata.json'
      },
      gpu: this.state.hasWebgl,
      layerCallPauses: true
    });

    let interval = setInterval(() => {
      const percent = model.getLoadingProgress();
      console.log('Progress', percent, model.xhrProgress);
      this.setState({
        loadingPercent: percent
      });
    }, 100);

    const waitTillReady = model.ready();

    waitTillReady.then(() => {
      clearInterval(interval);
      console.log('Model ready');
      this.setState({
        loadingPercent: 100,
        modelLoading: false,
        modelLoaded: true
      });

      setTimeout(() => this.loadImageToCanvas(this.state.url), 100);
    })
    .catch(err => {
      clearInterval(interval);
      console.log('err', err);
    });

    this.setState({
      modelLoading: true,
      model
    });
  }

  loadImageToCanvas = (url) => {
    console.log('Loading Image');
    if (!url) {
      return;
    };

    this.setState({
      imageLoadingError: false,
      imageLoading: true,
      loadingPercent: 0,
      classifyPercent: 0,
      topK: null
    });

    loadImage(
      'https://crossorigin.me/' + url,
      img => {
        if (img.type === 'error') {
          console.log('Error loading image');
          this.setState({
            imageLoadingError: true,
            imageLoading: false,
            modelRunning: false,
            url: null
          });

        } else {
          console.log('Image Loaded');
          const ctx = document.getElementById('input-canvas').getContext('2d');
          ctx.drawImage(img, 0, 0);
          this.setState({
            imageLoadingError: false,
            imageLoading: false,
            modelRunning: true
          });
          setTimeout(() => {
            this.runModel();
          }, 1000)
        }
      },
      {
        maxWidth: 299,
        maxHeight: 299,
        cover: true,
        crop: true,
        canvas: true,
        crossOrigin: 'Anonymous'
      }
    );
  }

  runModel = () => {
    console.log('Running Model');

    const ctx = document.getElementById('input-canvas').getContext('2d');
    const imageData = ctx.getImageData(
      0,
      0,
      ctx.canvas.width,
      ctx.canvas.height
    );
    const { data, width, height } = imageData;

    // data processing
    // see https://github.com/fchollet/keras/blob/master/keras/applications/imagenet_utils.py
    // and https://github.com/fchollet/keras/blob/master/keras/applications/inception_v3.py
    let dataTensor = ndarray(new Float32Array(data), [ width, height, 4 ]);
    let dataProcessedTensor = ndarray(new Float32Array(width * height * 3), [
      width,
      height,
      3
    ]);
    ops.divseq(dataTensor, 255);
    ops.subseq(dataTensor, 0.5);
    ops.mulseq(dataTensor, 2);
    ops.assign(
      dataProcessedTensor.pick(null, null, 0),
      dataTensor.pick(null, null, 0)
    );
    ops.assign(
      dataProcessedTensor.pick(null, null, 1),
      dataTensor.pick(null, null, 1)
    );
    ops.assign(
      dataProcessedTensor.pick(null, null, 2),
      dataTensor.pick(null, null, 2)
    );

    const inputData = { input_1: dataProcessedTensor.data };
    const predPromise = this.state.model.predict(inputData);

    const totalLayers = Object.keys(this.state.model.modelDAG).length
    let interval = setInterval(() => {
      const completedLayers = this.state.model.layersWithResults.length;
      this.setState({
        classifyPercent: ((completedLayers / totalLayers) * 100).toFixed(2)
      });
    }, 50);

    predPromise.then(outputData => {
      console.log(outputData);
      clearInterval(interval);
      const preds = outputData['dense_1'];
      const topK = food101topK(preds);
      console.log(topK);
      this.setState({
        topK,
        modelRunning: false
      });
    });
  }

  classifyNewImage = () => {
    const newUrl = this.urlInput.value;
    this.setState({
      url: this.urlInput.value
    });
    console.log('classifying new image', newUrl);
    this.loadImageToCanvas(newUrl);
  }

  render() {
    const {
      loadingPercent,
      modelLoaded,
      modelLoading,
      modelRunning,
      imageLoading,
      imageLoadingError,
      classifyPercent,
      topK
    } = this.state;
    return (

Food Classification Demo with Keras.js!

        { !modelLoaded ?

          To get started, click the Load Model button to download the model that
          we have built and exported using the Python notebook. The file may be
          fairly large for some (85 MB), so keep that in mind if progress seems stuck.

        : ''}

        { !modelLoaded && !modelLoading ? <button onClick={this.loadModel}>Load Model (85 MB)</button> : ''}
        { !modelLoaded && modelLoading ?

LOADING MODEL: {loadingPercent}%

          : ''}
        { modelLoaded && imageLoading ?

LOADING IMAGE

          : ''}
        { modelLoaded && imageLoadingError ?

ERROR LOADING IMAGE.
TRY DIFFERENT URL

          : ''}
        { modelLoaded && modelRunning ?

CLASSIFYING: {classifyPercent}%

          : ''}

          { modelLoaded && !modelRunning && !imageLoading ?

            Food Image URL: <input type='text' ref={(input) => { this.urlInput = input; }}/>

            <button onClick={this.classifyNewImage}>Classify Image</button>

          : '' }
          <canvas id='input-canvas' width='299' height='299'/>
          { topK ? <Predictions topK={topK}/> : ''}

    );
  }
}

export default App;


text:
<meta name="generator" content="groff -Thtml, see www.gnu.org">
<meta name="Content-Style" content="text/css">
<title>TIFF2RGBA</title>

TIFF2RGBA

NAME

SYNOPSIS

DESCRIPTION

OPTIONS

SEE ALSO

NAME

tiff2rgba − convert a TIFF image to
RGBA color space

SYNOPSIS

tiff2rgba [ options ] input.tif
output.tif

DESCRIPTION

Tiff2rgba converts a wide variety of TIFF images
into an RGBA TIFF image. This includes the ability to
translate different color spaces and photometric
interpretation into RGBA, support for alpha blending, and
translation of many different bit depths into a 32bit RGBA
image.

Internally this program is implemented using the
TIFFReadRGBAImage() function, and it suffers any
limitations of that image. This includes limited support for
> 8 BitsPerSample images, and flaws with some esoteric
combinations of BitsPerSample, photometric interpretation,
block organization and planar configuration.

The generated images are stripped images with four
samples per pixel (red, green, blue and alpha) or if the -n
flag is used, three samples per pixel (red, green, and
blue). The resulting images are always planar configuration
contiguous. For this reason, this program is a useful
utility for transform exotic TIFF files into a form
ingestable by almost any TIFF supporting software.

OPTIONS

−c

Specify a compression scheme to use when writing image
data: −c none for no compression (the default),
-c packbits for the PackBits compression algorithm,
-c zip for the Deflate compression algorithm, -c
jpeg for the JPEG compression algorithm, and −c
lzw for Lempel-Ziv & Welch.

−r

Write data with a specified number of rows per strip; by
default the number of rows/strip is selected so that each
strip is approximately 8 kilobytes.

−b

Process the image one block (strip/tile) at a time
instead of by reading the whole image into memory at once.
This may be necessary for very large images on systems with
limited RAM.

−n

Drop the alpha component from the output file, producing
a pure RGB file. Currently this does not work if the -b flag
is also in effect.

SEE ALSO

tiff2bw(1), TIFFReadRGBAImage(3t),
libtiff(3)


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

/**
 * @fileoverview A helper object used by the dice web signin intercept bubble to
 * interact with the browser.
 */
import {sendWithPromise} from 'chrome://resources/js/cr.m.js';

/** Account information sent from C++. */
export interface AccountInfo {
  isManaged: boolean;
  pictureUrl: string;
}

export interface InterceptionParameters {
  headerText: string;
  bodyTitle: string;
  bodyText: string;
  confirmButtonLabel: string;
  cancelButtonLabel: string;
  managedDisclaimerText: string;
  headerTextColor: string;
  interceptedProfileColor: string;
  primaryProfileColor: string;
  interceptedAccount: AccountInfo;
  primaryAccount: AccountInfo;
  showGuestOption: boolean;
  useV2Design: boolean;
  showManagedDisclaimer: boolean;
}

export interface DiceWebSigninInterceptBrowserProxy {
  // Called when the user accepts the interception bubble.
  accept(): void;

  // Called when the user cancels the interception.
  cancel(): void;

  // Called when user selects Guest mode.
  guest(): void;

  // Called when the page is loaded.
  pageLoaded(): Promise<InterceptionParameters>;
}

export class DiceWebSigninInterceptBrowserProxyImpl implements
    DiceWebSigninInterceptBrowserProxy {
  accept() {
    chrome.send('accept');
  }

  cancel() {
    chrome.send('cancel');
  }

  guest() {
    chrome.send('guest');
  }

  pageLoaded() {
    return sendWithPromise('pageLoaded');
  }

  static getInstance(): DiceWebSigninInterceptBrowserProxy {
    return instance ||
        (instance = new DiceWebSigninInterceptBrowserProxyImpl());
  }

  static setInstance(obj: DiceWebSigninInterceptBrowserProxy) {
    instance = obj;
  }
}

let instance: DiceWebSigninInterceptBrowserProxy|null = null;


text:
package io.openkit.user;

import io.openkit.OKLog;
import io.openkit.OKUser;
import io.openkit.asynchttp.AsyncHttpClient;
import io.openkit.asynchttp.OKJsonHttpResponseHandler;
import io.openkit.asynchttp.RequestParams;
import io.openkit.user.OKUserUtilities;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.common.GooglePlayServicesUtil;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;

public class GoogleUtils {

	public static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1002;

	public static String[] getGoogleAccountNames(Context ctx)
	{
		Account[] accounts = getGoogleAccounts(ctx);
		String[] names = new String[accounts.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = accounts[i].name;
		}
		return names;
	}

	public static Account[] getGoogleAccounts(Context ctx)
	{
		AccountManager manager  = AccountManager.get(ctx);
		return manager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
	}

	public static void showGooglePlayServicesErrorDialog(final Activity activityToShowFrom, final int code) {
		activityToShowFrom.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Dialog d = GooglePlayServicesUtil.getErrorDialog(
						code,
						activityToShowFrom,
						REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
				d.show();
			}
		});
	}

	public static abstract class GetGoogleUserInfoRequestHandler {
		public abstract void onSuccess(JSONObject userinfo);
		public abstract void onFailure();
	}

	public static void getGoogleUserInfo(String authToken, final GetGoogleUserInfoRequestHandler googleRequestHandler)
	{
		AsyncHttpClient client = new AsyncHttpClient();
		client.addHeader("Content-Type", "application/json");
		client.addHeader("Accept", "application/json");

		RequestParams params =  new RequestParams();
		params.put("access_token", authToken);

		client.get("https://www.googleapis.com/oauth2/v1/userinfo", params, new OKJsonHttpResponseHandler() {

			@Override
			public void onSuccess(JSONObject object) {
				googleRequestHandler.onSuccess(object);
				OKLog.v("Successfully got Google user info");
			}

			@Override
			public void onSuccess(JSONArray array) {
				// Not expecting an Array object
				OKLog.v("Got a JSON Array when expecting a JSON object while getting Google user info");
				googleRequestHandler.onFailure();
			}

			@Override
			public void onFailure(Throwable error, String content) {
				googleRequestHandler.onFailure();
				OKLog.v( "Error getting Google user info: " + error + "content: " + content);
			}

			@Override
			public void onFailure(Throwable e, JSONArray errorResponse) {
				googleRequestHandler.onFailure();
				OKLog.v( "Error getting Google user info: " + e);
			}

			@Override
			public void onFailure(Throwable e, JSONObject errorResponse) {
				googleRequestHandler.onFailure();
				OKLog.v( "Error getting Google user info: " + e);
			}
		});
	}

	public static void createOrUpdateOKUserFromGoogle(final Context ctx, final String googleAuthToken, final CreateOrUpdateOKUserRequestHandler requestHandler)
	{
		getGoogleUserInfo(googleAuthToken, new GetGoogleUserInfoRequestHandler() {

			@Override
			public void onSuccess(JSONObject userinfo) {

				String googleID, userNick;
				// Parse the user info and then create the OKUser
				try {
					//If the google account doesn't return an ID then we fail
					googleID = userinfo.getString("id");
				} catch (JSONException e) {
					requestHandler.onFail(new Error("Google user info request did not return a user ID"));
					return;
				}

				try {
					userNick = userinfo.getString("name");
				} catch (JSONException e) {
					//If the google account doesn't return a name we just give them a nickname
					userNick = "Me";
				}

				OKUser currentUser = OKUser.getCurrentUser();

				if(currentUser != null) {
					if(currentUser.getGoogleID() != null && currentUser.getGoogleID().equalsIgnoreCase(googleID)) {
						requestHandler.onSuccess(currentUser);
					} else {
						currentUser.setGoogleID(googleID);
						OKUserUtilities.updateOKUser(currentUser, requestHandler);
					}

				} else {
					OKUserUtilities.createOKUser(OKUserIDType.GoogleID, googleID, userNick, requestHandler);
				}
			}

			@Override
			public void onFailure() {
				//If the user info requests fails, let's invalidate the Google auth token
				GoogleAuthUtil.invalidateToken(ctx, googleAuthToken);
				OKLog.v("Invalidated Google auth token");
				requestHandler.onFail(new Error("Getting Google user info failed"));
			}
		});
	}

}


text:
//The MIT License(MIT)

//copyright(c) 2016 Alberto Rodriguez

//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.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace LiveCharts.Helpers
{
    public delegate void NoisyCollectionCollectionChanged<in T>(
        IEnumerable<T> oldItems, IEnumerable<T> newItems);

    public interface INoisyCollection : IList
    {
        event NoisyCollectionCollectionChanged<object> CollectionChanged;
    }

    public class NoisyCollection<T> : INoisyCollection, IList<T>
    {
        private readonly List<T> _source;

        #region Contructors

        public NoisyCollection()
        {
            _source = new List<T>();
        }

        public NoisyCollection(IEnumerable<T> collection)
        {
            _source = new List<T>(collection);
        }

        public NoisyCollection(int capacity)
        {
            _source = new List<T>(capacity);
        }

        #endregion

        #region Properties

        public T this[int index]
        {
            get { return _source[index]; }
            set { _source[index] = value; }
        }

        object IList.this[int index]
        {
            get { return _source[index]; }
            set { _source[index] = (T) value; }
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _source.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public int Count
        {
            get { return _source.Count; }
        }

        bool ICollection<T>.IsReadOnly
        {
            get { return ((ICollection<T>) _source).IsReadOnly; }
        }
        bool IList.IsReadOnly
        {
            get { return ((IList) _source).IsReadOnly; }
        }

        public bool IsSynchronized
        {
            get { return ((ICollection) _source).IsSynchronized; }
        }

        public object SyncRoot
        {
            get { return ((ICollection) _source).SyncRoot; }
        }

        public bool IsFixedSize { get { return ((IList) _source).IsFixedSize; } }

        #endregion

        public int Add(object value)
        {
            _source.Add((T)value);
            OnCollectionChanged(null, new[] {(T) value});
            return _source.Count;
        }

        public void Add(T item)
        {
            _source.Add(item);
            OnCollectionChanged(null, new [] {item});
        }

        public void AddRange(IEnumerable<T> items)
        {
            _source.AddRange(items);
            OnCollectionChanged(null, items);
        }

        public void Insert(int index, object value)
        {
            _source.Insert(index, (T) value);
            OnCollectionChanged(null, new[] {(T) value});
        }

        public void Insert(int index, T item)
        {
            _source.Insert(index, item);
            OnCollectionChanged(null, new[] {item});
        }

        public void InsertRange(int index, IEnumerable<T> collection)
        {
            _source.InsertRange(index, collection);
            OnCollectionChanged(null, collection);
        }

        public void Remove(object value)
        {
            _source.Remove((T) value);
            OnCollectionChanged(new[] {(T) value}, null);
        }

        public bool Remove(T item)
        {
            var ans = _source.Remove(item);
            OnCollectionChanged(new[] { item }, null);
            return ans;
        }

        void IList.RemoveAt(int index)
        {
            var i = _source[index];
            _source.RemoveAt(index);
            OnCollectionChanged(new[] { i }, null);
        }

        void IList<T>.RemoveAt(int index)
        {
            var i = _source[index];
            _source.RemoveAt(index);
            OnCollectionChanged(new[] { i }, null);
        }

        public void RemoveAt(int index)
        {
            var i = _source[index];
            _source.RemoveAt(index);
            OnCollectionChanged(new[] { i }, null);
        }

        void IList.Clear()
        {
            var backup = _source.ToArray();
            _source.Clear();
            OnCollectionChanged(backup, null);
        }

        void ICollection<T>.Clear()
        {
            var backup = _source.ToArray();
            _source.Clear();
            OnCollectionChanged(backup, null);
        }

        public void Clear()
        {
            var backup = _source.ToArray();
            _source.Clear();
            OnCollectionChanged(backup, null);
        }

        public bool Contains(object value)
        {
            return _source.Contains((T) value);
        }

        public bool Contains(T item)
        {
            return _source.Contains(item);
        }

        public void CopyTo(Array array, int index)
        {
            _source.CopyTo(array.Cast<T>().ToArray(), index);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _source.CopyTo(array, arrayIndex);
        }

        public int IndexOf(object value)
        {
            return _source.IndexOf((T) value);
        }

        public int IndexOf(T item)
        {
            return _source.IndexOf(item);
        }

        event NoisyCollectionCollectionChanged<object> INoisyCollection.CollectionChanged
        {
            add { CollectionChanged += value as NoisyCollectionCollectionChanged<T>; }
            remove { CollectionChanged -= value as NoisyCollectionCollectionChanged<T>; }
        }
        public event NoisyCollectionCollectionChanged<T> CollectionChanged;

        private void OnCollectionChanged(IEnumerable<T> olditems, IEnumerable<T> newItems)
        {
            if (CollectionChanged != null)
                CollectionChanged.Invoke(olditems, newItems);
        }
    }
}


text:
require('angular');
require('angular-ui-router');

require('./config.js');
require('./controllers');
require('./services');
require('./directives');


text:
var common = require('../common');
var assert = require('assert');
var http = require('http');

var server = http.createServer(function (req, res) {
  res.end('Hello');
});

server.listen(common.PORT, function () {
  var req = http.get({port: common.PROXY_PORT}, function (res) {
    res.on('data', function (data) {
      req.abort();
      server.close();
    });
  });
});


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM;

use Doctrine\ORM\Internal\CommitOrderCalculator;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataBuildingContext;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Reflection\RuntimeReflectionService;
use Doctrine\Tests\OrmTestCase;

/**
 * Tests of the commit order calculation.
 *
 * IMPORTANT: When writing tests here consider that a lot of graph constellations
 * can have many valid orderings, so you may want to build a graph that has only
 * 1 valid order to simplify your tests.
 */
class CommitOrderCalculatorTest extends OrmTestCase
{
    /**
     * @var CommitOrderCalculator
     */
    private $calc;

    /**
     * @var ClassMetadataBuildingContext|\PHPUnit_Framework_MockObject_MockObject
     */
    private $metadataBuildingContext;

    protected function setUp()
    {
        $this->calc                    = new CommitOrderCalculator();
        $this->metadataBuildingContext = new ClassMetadataBuildingContext(
            $this->createMock(ClassMetadataFactory::class),
            new RuntimeReflectionService()
        );
    }

    public function testCommitOrdering1()
    {
        $class1 = new ClassMetadata(NodeClass1::class, $this->metadataBuildingContext);
        $class2 = new ClassMetadata(NodeClass2::class, $this->metadataBuildingContext);
        $class3 = new ClassMetadata(NodeClass3::class, $this->metadataBuildingContext);
        $class4 = new ClassMetadata(NodeClass4::class, $this->metadataBuildingContext);
        $class5 = new ClassMetadata(NodeClass5::class, $this->metadataBuildingContext);

        $this->calc->addNode($class1->getClassName(), $class1);
        $this->calc->addNode($class2->getClassName(), $class2);
        $this->calc->addNode($class3->getClassName(), $class3);
        $this->calc->addNode($class4->getClassName(), $class4);
        $this->calc->addNode($class5->getClassName(), $class5);

        $this->calc->addDependency($class1->getClassName(), $class2->getClassName(), 1);
        $this->calc->addDependency($class2->getClassName(), $class3->getClassName(), 1);
        $this->calc->addDependency($class3->getClassName(), $class4->getClassName(), 1);
        $this->calc->addDependency($class5->getClassName(), $class1->getClassName(), 1);

        $sorted = $this->calc->sort();

        // There is only 1 valid ordering for this constellation
        $correctOrder = [$class5, $class1, $class2, $class3, $class4];

        self::assertSame($correctOrder, $sorted);
    }

    public function testCommitOrdering2()
    {
        $class1 = new ClassMetadata(NodeClass1::class, $this->metadataBuildingContext);
        $class2 = new ClassMetadata(NodeClass2::class, $this->metadataBuildingContext);

        $this->calc->addNode($class1->getClassName(), $class1);
        $this->calc->addNode($class2->getClassName(), $class2);

        $this->calc->addDependency($class1->getClassName(), $class2->getClassName(), 0);
        $this->calc->addDependency($class2->getClassName(), $class1->getClassName(), 1);

        $sorted = $this->calc->sort();

        // There is only 1 valid ordering for this constellation
        $correctOrder = [$class2, $class1];

        self::assertSame($correctOrder, $sorted);
    }
}

class NodeClass1 {}
class NodeClass2 {}
class NodeClass3 {}
class NodeClass4 {}
class NodeClass5 {}


text:
""" Various kinds of markup (static content) widgets.

"""
from __future__ import absolute_import

from ...properties import abstract
from ...properties import Int, String
from .widget import Widget

@abstract
class Markup(Widget):
    """ Base class for HTML markup widget models. """

class Paragraph(Markup):
    """ A block (paragraph) of text.

    """

    text = String(help="""
    The contents of the widget.
    """)

    width = Int(500, help="""
    The width of the block in pixels.
    """)

    height = Int(400, help="""
    The height of the block in pixels.
    """)

class PreText(Paragraph):
    """ A block (paragraph) of pre-formatted text.

    """


text:
package jeffaschenk.commons.frameworks.cnxidx.resiliency.ldap;

/**
 * Web Admin Request Exception Class.
 *
 * @author jeff.schenk
 * @version 4.4 $Revision
 * Developed 2005
 */

class WebAdminRequestException extends Exception {

    public static final WebAdminRequestException INVALID_REQUEST = new WebAdminRequestException(400);
    public static final WebAdminRequestException PAGE_NOT_FOUND = new WebAdminRequestException(404);
    public static final WebAdminRequestException INTERNAL_SERVER_ERROR = new WebAdminRequestException(500);

    private int errorCode;

    public WebAdminRequestException(int errorCode) {
        super();

        this.errorCode = errorCode;
    }

    public int hashCode() {
        return errorCode;
    }

    public boolean equals(Object that) {
        try {
            return this.errorCode == ((WebAdminRequestException) that).errorCode;
        } catch (ClassCastException cce) {
            return false;
        }
    }

    public int getErrorCode() {
        return errorCode;
    }

    public String toString() {
        return "" + errorCode;
    }
} ///:~ End of WebAdminRequestException Class.


text:
using std::cerr;
using std::endl;
using std::string;

namespace tupleware {
class Logging {
public:
    static void debug(string filename, int line, string msg) {
        log("[DEBUG]: ", filename, line, msg);
    }

    static void error(string filename, int line, string msg) {
        log("[ERROR]: ", filename, line, msg);
    }

    static void fatal(string filename, int line, string msg) {
        log("[FATAL]: ", filename, line, msg);
        exit(1);
    }

    static void info(string msg) {
        log("[INFO]:  ", msg);
    }

    static void warn(string msg) {
        log("[WARN]:  ", msg);
    }
private:
    static void log(string type, string filename, int line, string msg) {
        cerr << type << filename << " at " << line << " (" << msg << ")"
             << endl;
    }

    static void log(string type, string msg) {
        cerr << type << msg << endl;
    }
};
}
#endif


text:
package com.braintreegateway.integrationtest;

import com.braintreegateway.Pager;
import com.braintreegateway.ResourceCollection;
import com.braintreegateway.util.NodeWrapper;
import com.braintreegateway.util.NodeWrapperFactory;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class ResourceCollectionIT {
    private String[] values = new String[]{"a", "b", "c", "d", "e"};

    class TestPager implements Pager<String> {
        public List<String> getPage(List<String> ids) {
            List<String> results = new ArrayList<String>();

            for (String id : ids) {
                results.add(values[Integer.parseInt(id)]);
            }
            return results;
        }
    }

    @Test
    public void getFirst() {
        NodeWrapper xml = NodeWrapperFactory.instance.create("<search-results>" +
                "<page-size>2</page-size>" +
                "<ids type=\"array\">" +
                    "<items>0</items>" +
                    "<items>1</items>" +
                    "<items>2</items>" +
                    "<items>3</items>" +
                    "<items>4</items>" +
                "</ids>" +
                "</search-results>"
        );

        ResourceCollection<String> resourceCollection = new ResourceCollection<String>(new TestPager(), xml);

        int index = 0;
        int count = 0;
        for (String string : resourceCollection) {
            assertEquals(values[index], string);
            index++;
            count++;
        }
        assertEquals(values.length, count);
    }
}


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Regulations Governing Personal Information File Security Maintenance Plan and Processing Method for the Human Resources Recruitment Industry</英文法規名稱>
<中文法規名稱>人力仲介業個人資料檔案安全維護計畫及處理辦法</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=N0090045</法規網址>
<最新英文異動日期>20210927</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件>
  <檔案>
    <檔案名稱><![CDATA[Attached Form:Human ResourcesRecruitment Industry Notification Record Form.pdf]]></檔案名稱>
    <下載網址>https://law.moj.gov.tw/Eng/LawClass/LawGetFile.ashx?FileId=0000006945</下載網址>
  </檔案>
</附件>
<沿革內容><![CDATA[1.Full text including 25 articles promulgated on 1 May 2013 by order Lao-Chi-Guan-Zhi No. 1020500788
2.Amended on September 27, 2021]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <編章節>   Chapter I General</編章節>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[These regulations are established in accordance with Paragraph 3, Article 27 of the Personal Information Protection Act (hereinafter the "Act").]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[These regulations are applicable to the human resources recruitment industry, meaning the following institutions:
1.Private employment services institutions with approval of establishment in accordance with Article 34 of the Employment Services Act.
2.Employment service agencies for people with disabilities with approval of establishment in accordance with Paragraph 3, Article 35 of the People with Disabilities Rights Protection Act.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[To implement the security maintenance and administration of personal information files and to protect personal information against theft, alteration, damage, loss or disclosure, the human resources recruitment industry should establish a personal information file security maintenance plan (hereinafter the "Plan").
The Plan shall include a processing method for personal information after termination of any business relationship.
The human resources recruitment industry should regularly review and amend the Plan in accordance with applicable legislation.]]></條文內容>
  </條文>
  <編章節>   Chapter II Personal Information Protection Planning</編章節>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall have dedicated staff or establish a dedicated organization to be responsible for personal information file security maintenance and administration and shall allocate commensurate resources.
The duties of the dedicated person or organization under the previous paragraph are as follows:
1.Establish personal information protection administration principles and make public announcements about the basis and specific purpose of its collection, processing and use of personal information and other protection related matters for the understanding of their staff.
2.Plan, establish, amend and execute the Plan.
3.Regularly provide basic knowledge promotion and professional educational training for their affiliated staff for them to understand the applicable legislations of personal information protection, the scope of responsibilities, administration measures and methods.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[Personal information protection administration principles established by the human resources recruitment industry shall include the following:
1.Compliance with personal information protection related legislation.
2.Reasonable and safe method for the collection, processing and use of personal information within the scope of specific purpose.
3.Techniques of reasonable security standards for the protection of personal information files that are collected, processed and used.
4.Contact the personnel for the exercise of personal information related rights by owners of information or for whom relevant complaints and consultations may be filed.
5.Emergency response procedure for handling events of theft, alteration, damage, loss or disclosure of personal information.
6.Mechanism for the supervision of subcontractors for the collection, processing and use of personal information.
7.Mechanism to ensure the security of personal information files and to maintain the operation of the Plan.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall verify personal information they hold in accordance with personal information protection related legislation, define the scope included in the Plan, establish files and regularly verify whether there are any changes.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall analyze the risks that may arise out of the collection, processing and use in accordance with the scope defined under the previous paragraph and establish proper control measures based on the results of such analysis.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall establish the following mechanisms in response to any event of theft, alteration, damage, loss or disclosure of personal information:
1. Adopt proper response measures to control the damage to the owners of the information created by the event.
2. Verity the situation of the event, inform the owner in a proper manner, including corresponding measures that have been adopted.
3. Review the prevention mechanism to prevent reoccurrence of a similar event.
When the incidents under the preceding paragraph occur, the human resources recruitment industry shall fill up the Notification Record sheet (as attached), and notify the municipal city government(s), or the county/city government(s) where the incident occurred and notify the Central Competent Authority. After the Central Competent Authority or the municipal city government(s), or the county/city government(s) received the notifications, with the power granted in Article 22 to Article 25 of this regulation, the mentioned authority is entitled to take appropriate supervisory and management measures.]]></條文內容>
  </條文>
  <編章節>   Chapter III Personal Information Administration Procedure</編章節>
  <條文>
    <條號>Article 9</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall ensure compliance with applicable legislation before the collection, processing and use of personal information provided under Paragraph 1, Article 6 of the Act.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 10</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall establish the following procedure with regard to the obligation of notification in accordance with Articles 8 and 9 of the Act:
1.Adopt a proper notification method based on the situation of information collection.
2.Confirm the reasons based on which the owner does not need to be notified.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 11</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall establish the following procedure with regard to the collection, processing or use of personal information other than the information provided under Paragraph 1, Article 6:
1.Confirm the specific purpose and legal conditions for the collection and processing of personal information.
2.Ensure that the use of personal information is within the necessary scope of the specific purpose. For any use of personal information outside the specific purpose, verify whether the conditions for use outside the legally defined specific purpose are met.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 12</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall establish the following supervisory procedure if the collection, processing or use of personal information is subcontracted in whole or in part:
1.Confirm the scope, type, specific purpose and period for the subcontracted collection, processing and use of personal information.
2.Ensure that the subcontractor adopts necessary security measures.
3.In case of further subcontracting, verify the identity of the second-level subcontractor.
4.If the subcontractor or its employee breaches any personal information protection legislation or the subcontracting agreement, require the subcontractor to inform the principal of the relevant measures and adopt remedy measures.
5.If the principal has any other instructions to the subcontractors, such instructions must be considered.
6.Upon termination or cancellation of the subcontracting relationship, must request the subcontractor to return the media in which personal information is stored and destroy or delete personal information stored and held by the subcontractor.
7.Ensure that the subcontractor performs the requirements under subparagraphs 1 to 6.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 13</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall establish the following procedure if personal information is used for marketing purposes:
1.Upon the initial marketing, the owners of information shall be provided with a method of refusing the marketing, with the necessary cost paid by the human resources recruitment industry.
2.When the owner refuses to receive marketing, immediately stop using the owner's personal information for marketing purposes and inform the relevant staff.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 14</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall verify whether any restriction is imposed by the central industry competent authority in accordance with Article 21 of the Act before international transmission of personal information.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 15</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall establish the following procedure when the information owner exercises the rights with regard to its personal information under Article 3 of the Act:
1.Verify that the person is the owner of the personal information.
2.Provide the owner with a method to exercise its rights and proceed within the deadline required under Article 13 of the Act.
3.Verify whether there is any reason to refuse the owner's exercise of its rights under Articles 10 and 11 of the Act and inform the owner of such reason.
4.Inform the fees to be charged.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 16</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall establish the following procedure to maintain correct personal information:
1.Verify whether there is any mistake in the collection, processing or use of personal information.
2.Regularly review the information and make correction or supplement if any mistake discovered. If the correction or supplement is not made, inform the persons who have used the information after correction or supplement.
3.In case of any dispute, establish a relevant procedure for the processing and use of disputed information in accordance with Paragraph 2, Article 11 of the Act.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 17</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall regularly verify whether the specific purpose for the personal information it possesses has ceased to exist or whether the period has expired.
If the specific purpose for the personal information has ceased to exist or if the period has expired, Paragraph 3, Article 11 of the Act shall be applicable.]]></條文內容>
  </條文>
  <編章節>   Chapter IV Personal Information Administration Measures</編章節>
  <條文>
    <條號>Article 18</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall adopt the following measures for staff administration:
1.Confirm the persons responsible for all relevant procedures for the collection, processing and use of personal information.
2.Establish an administration mechanism as required by the procedure and assign different authorities to the relevant staff. Regularly verify whether such authorities are proper and necessary.
3.Agree on confidentiality obligations with the affiliated staff.
4.Cancel the identification code of affiliated staff after their departure and take back the access badge (card) and relevant authorizations.
5.If relevant staff possesses personal information, upon departure of the staff, the staff must return the media on which personal information is stored and destroy or delete personal information stored.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 19</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall adopt the following measures with regard to information security administration in the collection, processing or use of personal information:
1. Establish procedure guidelines.
2. In using computerized equipment, establish regulations regarding the use of mobile devices or storage media.
3. If personal information is maintained and must be encrypted or shielding, adopt proper encryption or shielding mechanism.
4. In transmitting personal information, if encryption is required under different transmission methods, adopt a proper encryption mechanism and ensure the correctness of the recipient of information.
5. Evaluate the necessity of backup based on the importance of information maintained and create backups and encryption thereon in the same manner as the originals. Maintain the media in which backup information is stored in a proper manner and regularly perform reverse testing to confirm effectiveness.
6. When the media in which personal information is stored is to be disposed of or used for another purpose, duly destroy or delete the information stored in the media in a physical or other manner.
7. Properly maintain the passcodes used in the administration mechanism and encryption mechanism.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 20</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall adopt the following measures with regard to equipment security administration:
1.Implement necessary access control methods depending on the procedure.
2.Property maintains the media in which personal information is stored.
3.Reinforce protection against natural disaster and other accidents in accordance with different work environments and establish necessary disaster prevention equipment.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 21</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall adopt the following measures in relation to technology administration:
1.Configure a certification mechanism on computers, automatic processing equipment or systems and perform identification and control of authorized staff with access to personal information.
2.The account name and password used under the certification mechanism must have a certain degree of complexity and passwords must be changed regularly.
3.Configure an alarm and relevant response mechanism on computers, automatic processing equipment or systems to react and handle anomalous access properly.
4.The quantity and scope of authority to access personal information shall be determined as required for the procedure. Access authority cannot be shared.
5.Use firewalls or intrusion detection equipment to avoid unauthorized access to the system that stores personal information.
6.In using application programs that access personal information, ensure that the user has authorization to use them.
7.Regularly test the effectiveness of the authority certification mechanism.
8.Regularly inspect configuration of authority to access personal information.
9.Install anti-virus, anti-hacking software in the computer system that processes personal information and regularly update virus codes.
10.Regularly install patches for loopholes in the computer processing system and relevant application programs.
11.File sharing software shall not be installed in any computer or automatic processing equipment with access authority.
12.In testing information systems that process personal information, do not use real personal information. If real personal information is used, specify a procedure of use.
13.In case of any change to the information system that processes personal information, ensure that the level of security is not lowered.
14.Regularly inspect the use status of personal information system and the access to personal information.]]></條文內容>
  </條文>
  <編章節>   Chapter V Personal Information Processing Method after Termination of Business</編章節>
  <條文>
    <條號>Article 22</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall adopt the following measures for the processing of personal information after termination of business:
1.Delete or destroy the information stored in the media in which personal information is stored, record and maintain the method, time, location of deletion or destruction and the method proving the deletion or destruction.
2.The assignee may legally maintain such personal information, record and maintain the reason, method, time and location of assignment.]]></條文內容>
  </條文>
  <編章節>   Chapter VI Record Mechanism</編章節>
  <條文>
    <條號>Article 23</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall maintain the following records in executing the procedures and measures under the Plan:
1.Actions undertaken in response to the occurrence of the event.
2.Requirements of the principal that are executed by the subcontractor.
3.The rights that the information owners are allowed to exercise.
4.Maintenance and correction of personal information.
5.Change of authority of relevant staff.
6.Act of relevant staff in violation of authority.
7.Backup and testing of reversion.
8.Delivery and transmission of personal information.
9.Deletion, destruction or assignment of personal information.
10.System for storage of personal information.
11.Regular inspection on information system that processes personal information.
12.Educational training.
13.Execution of audit on the Plan and improvement measures.]]></條文內容>
  </條文>
  <編章節>   Chapter VII Miscellaneous</編章節>
  <條文>
    <條號>Article 24</條號>
    <條文內容><![CDATA[The human resources recruitment industry shall regularly inspect the execution status of the Plan and establish improvement measures for failure of due execution.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 25</條號>
    <條文內容><![CDATA[These Regulations are implemented from their date of promulgation.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="buttonBg">#CCCCCC</color>
    <color name="buttonTextColor">#000000</color>

    <color name="controller_bg_dark">#66000000</color>
    <color name="controller_bg_light">#00000000</color>

    <color name="edit_base_line_color">#77ffffff</color>

</resources>