text:
from __future__ import print_function
import re
import shutil
import unittest
from ruffus.ruffus_utility import RUFFUS_HISTORY_FILE
from ruffus import pipeline_run, pipeline_printout, Pipeline, formatter, output_from
import sys

"""

    test_combinatorics.py

        test product, combine, permute, combine_with_replacement

"""

import os
tempdir = os.path.relpath(os.path.abspath(os.path.splitext(__file__)[0]))
# sub-1s resolution in system?
one_second_per_job = None

# add grandparent to search path for testing
grandparent_dir = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(0, grandparent_dir)

# module name = script name without extension
module_name = os.path.splitext(os.path.basename(__file__))[0]

try:
    from StringIO import StringIO
except:
    from io import StringIO

def touch(outfile):
    with open(outfile, "w"):
        pass

# ___________________________________________________________________________
#
#   generate_initial_files1
# ___________________________________________________________________________
def generate_initial_files1(outfile):
    touch(outfile)

# ___________________________________________________________________________
#
#   generate_initial_files2
# ___________________________________________________________________________

def generate_initial_files2(outfile):
    touch(outfile)

# ___________________________________________________________________________
#
#   generate_initial_files3
# ___________________________________________________________________________

def generate_initial_files3(outfile):
    touch(outfile)

# ___________________________________________________________________________
#
#   check_product_task
# ___________________________________________________________________________

def check_product_task(infiles, outfile,
                       prefices,
                       subpath,
                       subdir):
    with open(outfile, "w") as p:
        p.write(prefices + ",")

# ___________________________________________________________________________
#
#   check_product_merged_task
# ___________________________________________________________________________
def check_product_merged_task(infiles, outfile):
    with open(outfile, "w") as p:
        for infile in sorted(infiles):
            with open(infile) as ii:
                p.write(ii.read())

# ___________________________________________________________________________
#
#   check_product_misspelt_capture_error_task
# ___________________________________________________________________________

def check_product_misspelt_capture_error_task(infiles, outfile):
    """
    FILE_PART mispelt as FILE_PART
    """
    touch(outfile)

# ___________________________________________________________________________
#
#   check_product_out_of_range_formatter_ref_error_task
# ___________________________________________________________________________
def check_product_out_of_range_formatter_ref_error_task(infiles, outfile, ignored_filter):
    """
    {path[2][0]} when len(path) == 1
    """
    touch(outfile)

# ___________________________________________________________________________
#
#   check_product_formatter_ref_index_error_task
# ___________________________________________________________________________

def check_product_formatter_ref_index_error_task(infiles, outfile, ignored_filter):
    """
    {path[0][0][1000} when len of the path string len(path[0][0]) < 1000
    """
    touch(outfile)

# ___________________________________________________________________________
#
#   check_combinations2_task
# ___________________________________________________________________________

def check_combinations2_task(infiles, outfile,
                             prefices,
                             subpath,
                             subdir):
    """
        Test combinations with k-tuple = 2
    """
    with open(outfile, "w") as outf:
        outf.write(prefices + ",")

def check_combinations2_merged_task(infiles, outfile):
    with open(outfile, "w") as p:
        for infile in sorted(infiles):
            with open(infile) as ii:
                p.write(ii.read())

# ___________________________________________________________________________
#
#   check_combinations3_task
# ___________________________________________________________________________

def check_combinations3_task(infiles, outfile,
                             prefices,
                             subpath,
                             subdir):
    """
        Test combinations with k-tuple = 3
    """
    with open(outfile, "w") as outf:
        outf.write(prefices + ",")

def check_combinations3_merged_task(infiles, outfile):
    with open(outfile, "w") as p:
        for infile in sorted(infiles):
            with open(infile) as ii:
                p.write(ii.read())

# ___________________________________________________________________________
#
#   check_permutations2_task
# ___________________________________________________________________________
def check_permutations2_task(infiles, outfile,
                             prefices,
                             subpath,
                             subdir):
    """
        Test permutations with k-tuple = 2
    """
    with open(outfile, "w") as outf:
        outf.write(prefices + ",")

def check_permutations2_merged_task(infiles, outfile):
    with open(outfile, "w") as p:
        for infile in sorted(infiles):
            with open(infile) as ii:
                p.write(ii.read())

# ___________________________________________________________________________
#
#   check_permutations3_task
# ___________________________________________________________________________
def check_permutations3_task(infiles, outfile,
                             prefices,
                             subpath,
                             subdir):
    """
        Test permutations with k-tuple = 3
    """
    with open(outfile, "w") as outf:
        outf.write(prefices + ",")

def check_permutations3_merged_task(infiles, outfile):
    with open(outfile, "w") as p:
        for infile in sorted(infiles):
            with open(infile) as ii:
                p.write(ii.read())

# ___________________________________________________________________________
#
#   check_combinations_with_replacement2_task
# ___________________________________________________________________________
def check_combinations_with_replacement2_task(infiles, outfile,
                                              prefices,
                                              subpath,
                                              subdir):
    """
        Test combinations_with_replacement with k-tuple = 2
    """
    with open(outfile, "w") as outf:
        outf.write(prefices + ",")

def check_combinations_with_replacement2_merged_task(infiles, outfile):
    with open(outfile, "w") as p:
        for infile in sorted(infiles):
            with open(infile) as ii:
                p.write(ii.read())

# ___________________________________________________________________________
#
#   check_combinations_with_replacement3_task
# ___________________________________________________________________________
def check_combinations_with_replacement3_task(infiles, outfile,
                                              prefices,
                                              subpath,
                                              subdir):
    """
        Test combinations_with_replacement with k-tuple = 3
    """
    with open(outfile, "w") as outf:
        outf.write(prefices + ",")

def check_combinations_with_replacement3_merged_task(infiles, outfile):
    with open(outfile, "w") as p:
        for infile in sorted(infiles):
            with open(infile) as ii:
                p.write(ii.read())

def cleanup_tmpdir():
    os.system('rm -f %s %s' %
              (os.path.join(tempdir, '*'), RUFFUS_HISTORY_FILE))

test_pipeline1 = Pipeline("test1")
test_pipeline2 = Pipeline("test2")
gen_task1 = test_pipeline1.originate(task_func=generate_initial_files1,
                                     name="WOWWWEEE",
                                     output=[tempdir + "/" + prefix + "_name.tmp1" for prefix in "abcd"])
test_pipeline1.originate(task_func=generate_initial_files2,
                         output=[tempdir + "/e_name.tmp1", tempdir + "/f_name.tmp1"])
test_pipeline1.originate(task_func=generate_initial_files3,
                         output=[tempdir + "/g_name.tmp1", tempdir + "/h_name.tmp1"])
test_pipeline1.product(task_func=check_product_task,
                       input=[tempdir + "/" + prefix +
                              "_name.tmp1" for prefix in "abcd"],
                       filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                       input2=generate_initial_files2,
                       filter2=formatter(),
                       input3=generate_initial_files3,
                       filter3=formatter(r"tmp1$"),
                       output="{path[0][0]}/{FILE_PART[0][0]}.{basename[1][0]}.{basename[2][0]}.tmp2",
                       extras=["{basename[0][0][0]}{basename[1][0][0]}{basename[2][0][0]}",       # extra: prefices only (abcd etc)
                               # extra: path for 2nd input, 1st file
                               "{subpath[0][0][0]}",
                               "{subdir[0][0][0]}"]).follows("WOWWWEEE").follows(gen_task1).follows(generate_initial_files1).follows("generate_initial_files1")
test_pipeline1.merge(task_func=check_product_merged_task,
                     input=check_product_task,
                     output=tempdir + "/merged.results")
test_pipeline1.product(task_func=check_product_misspelt_capture_error_task,
                       input=gen_task1,
                       filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                       output="{path[0][0]}/{FILEPART[0][0]}.tmp2")
test_pipeline1.product(task_func=check_product_out_of_range_formatter_ref_error_task,
                       input=generate_initial_files1,  #
                       filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                       output="{path[2][0]}/{basename[0][0]}.tmp2",
                       extras=["{FILE_PART[0][0]}"])
test_pipeline1.product(task_func=check_product_formatter_ref_index_error_task,
                       input=output_from("generate_initial_files1"),
                       filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                       output="{path[0][0][1000]}/{basename[0][0]}.tmp2",
                       extras=["{FILE_PART[0][0]}"])
test_pipeline1.combinations(task_func=check_combinations2_task,
                            input=generate_initial_files1,      # gen_task1
                            filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                            tuple_size=2,
                            output="{path[0][0]}/{FILE_PART[0][0]}.{basename[1][0]}.tmp2",
                            extras=["{basename[0][0][0]}{basename[1][0][0]}",       # extra: prefices
                                    # extra: path for 2nd input, 1st file
                                    "{subpath[0][0][0]}",
                                    "{subdir[0][0][0]}"])
test_pipeline1.merge(task_func=check_combinations2_merged_task,
                     input=check_combinations2_task,
                     output=tempdir + "/merged.results")
test_pipeline1.combinations(task_func=check_combinations3_task,
                            input=output_from("WOWWWEEE"),
                            filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                            tuple_size=3,
                            output="{path[0][0]}/{FILE_PART[0][0]}.{basename[1][0]}.{basename[2][0]}.tmp2",
                            extras=["{basename[0][0][0]}{basename[1][0][0]}{basename[2][0][0]}",       # extra: prefices
                                    # extra: path for 2nd input, 1st file
                                    "{subpath[0][0][0]}",
                                    "{subdir[0][0][0]}"])

test_pipeline1.merge(check_combinations3_merged_task,
                     check_combinations3_task, tempdir + "/merged.results")
test_pipeline1.permutations(task_func=check_permutations2_task,
                            input=output_from("WOWWWEEE"),
                            filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                            tuple_size=2,
                            output="{path[0][0]}/{FILE_PART[0][0]}.{basename[1][0]}.tmp2",
                            extras=["{basename[0][0][0]}{basename[1][0][0]}",       # extra: prefices
                                    # extra: path for 2nd input, 1st file
                                    "{subpath[0][0][0]}",
                                    "{subdir[0][0][0]}"])

test_pipeline2.merge(check_permutations2_merged_task,
                     check_permutations2_task, tempdir + "/merged.results")

test_pipeline2.permutations(task_func=check_permutations3_task,
                            input=output_from("WOWWWEEE"),
                            filter=formatter(".*/(?P<FILE_PART>.+).tmp1$"),
                            tuple_size=3,
                            output="{path[0][0]}/{FILE_PART[0][0]}.{basename[1][0]}.{basename[2][0]}.tmp2",
                            extras=["{basename[0][0][0]}{basename[1][0][0]}{basename[2][0][0]}",       # extra: prefices
                                    # extra: path for 2nd input, 1st file
                                    "{subpath[0][0][0]}",
                                    "{subdir[0][0][0]}"])
test_pipeline2.merge(check_permutations3_merged_task,
                     check_permutations3_task, tempdir + "/merged.results")
test_pipeline2.combinations_with_replacement(check_combinations_with_replacement2_task,
                                             input=output_from("WOWWWEEE"),
                                             filter=formatter(
                                                 ".*/(?P<FILE_PART>.+).tmp1$"),
                                             tuple_size=2,
                                             output="{path[0][0]}/{FILE_PART[0][0]}.{basename[1][0]}.tmp2",
                                             extras=["{basename[0][0][0]}{basename[1][0][0]}",       # extra: prefices
                                                     # extra: path for 2nd input, 1st file
                                                     "{subpath[0][0][0]}",
                                                     "{subdir[0][0][0]}"])
test_pipeline2.merge(check_combinations_with_replacement2_merged_task,
                     check_combinations_with_replacement2_task, tempdir + "/merged.results")
test_pipeline2.combinations_with_replacement(task_func=check_combinations_with_replacement3_task,
                                             input=output_from("WOWWWEEE"),
                                             filter=formatter(
                                                 ".*/(?P<FILE_PART>.+).tmp1$"),
                                             tuple_size=3,
                                             output="{path[0][0]}/{FILE_PART[0][0]}.{basename[1][0]}.{basename[2][0]}.tmp2",
                                             extras=["{basename[0][0][0]}{basename[1][0][0]}{basename[2][0][0]}",       # extra: prefices
                                                     # extra: path for 2nd input, 1st file
                                                     "{subpath[0][0][0]}",
                                                     "{subdir[0][0][0]}"])
test_pipeline2.merge(check_combinations_with_replacement3_merged_task,
                     check_combinations_with_replacement3_task, tempdir + "/merged.results")

class TestCombinatorics(unittest.TestCase):
    def setUp(self):
        try:
            os.mkdir(tempdir)
        except OSError:
            pass

    # ___________________________________________________________________________
    #
    #   test product() pipeline_printout and pipeline_run
    # ___________________________________________________________________________
    def test_product_printout(self):
        """Input file exists, output doesn't exist"""
        cleanup_tmpdir()
        s = StringIO()
        test_pipeline2.printout(
            s, [check_product_merged_task], verbose=5, wrap_width=10000)
        self.assertTrue(re.search('Job needs update:.*Missing files.*'
                                  '\[.*{tempdir}/a_name.tmp1, '
                                  '.*{tempdir}/e_name.tmp1, '
                                  '.*{tempdir}/h_name.tmp1, '
                                  '.*{tempdir}/a_name.e_name.h_name.tmp2\]'.format(tempdir=tempdir), s.getvalue(), re.DOTALL))

    def test_product_run(self):
        """Run product"""
        # output is up to date, but function body changed (e.g., source different)
        cleanup_tmpdir()
        test_pipeline2.run([check_product_merged_task], verbose=0,
                           multiprocess=100, one_second_per_job=one_second_per_job)
        with open(tempdir + "/merged.results") as oo:
            self.assertEqual(oo.read(),
                             "aeg,aeh,afg,afh,beg,beh,bfg,bfh,ceg,ceh,cfg,cfh,deg,deh,dfg,dfh,")

    # ___________________________________________________________________________
    #
    #   test product() pipeline_printout diagnostic error messsages
    #
    #       require verbose >= 3 or an empty jobs list
    # ___________________________________________________________________________
    def test_product_misspelt_capture_error(self):
        """Misspelt named capture group
            Requires verbose >= 3 or an empty jobs list
        """
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_product_misspelt_capture_error_task], verbose=3, wrap_width=10000)
        self.assertIn("Warning: Input substitution failed:", s.getvalue())
        self.assertIn("Unmatched field {FILEPART}", s.getvalue())

    def test_product_out_of_range_formatter_ref_error(self):
        """
        {path[2][0]} when len(path) == 1
            Requires verbose >= 3 or an empty jobs list
        """
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_product_out_of_range_formatter_ref_error_task], verbose=3, wrap_width=10000)
        self.assertIn("Warning: Input substitution failed:", s.getvalue())
        self.assertIn("Unmatched field {2}", s.getvalue())

    def test_product_formatter_ref_index_error(self):
        """
        {path[0][0][1000} when len of the path string len(path[0][0]) < 1000
            Requires verbose >= 3 or an empty jobs list
        """
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_product_formatter_ref_index_error_task], verbose=3, wrap_width=10000)
        self.assertIn("Warning: Input substitution failed:", s.getvalue())
        self.assertIn(
            "Unmatched field {string index out of range}", s.getvalue())
        # print s.getvalue()

    # ___________________________________________________________________________
    #
    #   test combinations() pipeline_printout and pipeline_run
    # ___________________________________________________________________________

    def test_combinations2_printout(self):
        """Input file exists, output doesn't exist"""
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline1.printout(
            s, [check_combinations2_merged_task], verbose=5, wrap_width=10000)
        self.assertTrue(re.search('Job needs update:.*Missing files.*'
                                  '\[.*{tempdir}/a_name.tmp1, '
                                  '.*{tempdir}/b_name.tmp1, '
                                  '.*{tempdir}/a_name.b_name.tmp2\]'.format(tempdir=tempdir), s.getvalue(), re.DOTALL))

    def test_combinations2_run(self):
        """Run product"""
        # output is up to date, but function body changed (e.g., source different)
        cleanup_tmpdir()
        test_pipeline2.run([check_combinations2_merged_task], verbose=0,
                           multiprocess=100, one_second_per_job=one_second_per_job)
        with open(tempdir + "/merged.results") as oo:
            self.assertEqual(oo.read(),
                             'ab,ac,ad,bc,bd,cd,')

    # ___________________________________________________________________________
    #
    #   test combinations() pipeline_printout and pipeline_run
    # ___________________________________________________________________________
    def test_combinations3_printout(self):
        """Input file exists, output doesn't exist"""
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_combinations3_merged_task], verbose=5, wrap_width=10000)
        self.assertTrue(re.search(
            '\[.*{tempdir}/a_name.tmp1, '
            '.*{tempdir}/b_name.tmp1, '
            '.*{tempdir}/c_name.tmp1, '
            '.*{tempdir}/a_name.b_name.c_name.tmp2\]'.format(tempdir=tempdir), s.getvalue()))

    def test_combinations3_run(self):
        """Run product"""
        # output is up to date, but function body changed (e.g., source different)
        cleanup_tmpdir()
        test_pipeline2.run([check_combinations3_merged_task], verbose=0,
                           multiprocess=100, one_second_per_job=one_second_per_job)
        with open(tempdir + "/merged.results") as oo:
            self.assertEqual(oo.read(),
                             "abc,abd,acd,bcd,")

    # ___________________________________________________________________________
    #
    #   test permutations() pipeline_printout and pipeline_run
    # ___________________________________________________________________________

    def test_permutations2_printout(self):
        """Input file exists, output doesn't exist"""
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_permutations2_merged_task], verbose=5, wrap_width=10000)
        self.assertTrue(re.search('\[.*{tempdir}/a_name.tmp1, '
                                  '.*{tempdir}/b_name.tmp1, '
                                  '.*{tempdir}/a_name.b_name.tmp2\]'.format(tempdir=tempdir), s.getvalue()))

    def test_permutations2_run(self):
        """Run product"""
        # output is up to date, but function body changed (e.g., source different)
        cleanup_tmpdir()
        test_pipeline2.run([check_permutations2_merged_task], verbose=0,
                           multiprocess=100, one_second_per_job=one_second_per_job)
        with open(tempdir + "/merged.results") as oo:
            self.assertEqual(oo.read(),
                             "ab,ac,ad,ba,bc,bd,ca,cb,cd,da,db,dc,")

    # ___________________________________________________________________________
    #
    #   test permutations() pipeline_printout and pipeline_run
    # ___________________________________________________________________________
    def test_permutations3_printout(self):
        """Input file exists, output doesn't exist"""
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_permutations3_merged_task], verbose=5, wrap_width=10000)
        self.assertTrue(re.search('\[.*{tempdir}/a_name.tmp1, '
                                  '.*{tempdir}/b_name.tmp1, '
                                  '.*{tempdir}/c_name.tmp1, '
                                  '.*{tempdir}/a_name.b_name.c_name.tmp2\]'.format(tempdir=tempdir), s.getvalue()))

    def test_permutations3_run(self):
        """Run product"""
        # output is up to date, but function body changed (e.g., source different)
        cleanup_tmpdir()
        test_pipeline2.run([check_permutations3_merged_task], verbose=0,
                           multiprocess=100, one_second_per_job=one_second_per_job)
        with open(tempdir + "/merged.results") as oo:
            self.assertEqual(oo.read(),
                             'abc,abd,acb,acd,adb,adc,bac,bad,bca,bcd,bda,bdc,cab,cad,cba,cbd,cda,cdb,dab,dac,dba,dbc,dca,dcb,')

    # ___________________________________________________________________________
    #
    #   test combinations_with_replacement() pipeline_printout and pipeline_run
    # ___________________________________________________________________________

    def test_combinations_with_replacement2_printout(self):
        """Input file exists, output doesn't exist"""
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_combinations_with_replacement2_merged_task], verbose=5, wrap_width=10000)
        self.assertTrue(re.search('\[.*{tempdir}/a_name.tmp1, '
                                  '.*{tempdir}/b_name.tmp1, '
                                  '.*{tempdir}/a_name.b_name.tmp2\]'.format(tempdir=tempdir), s.getvalue()))

    def test_combinations_with_replacement2_run(self):
        """Run product"""
        # output is up to date, but function body changed (e.g., source different)
        cleanup_tmpdir()
        test_pipeline2.run([check_combinations_with_replacement2_merged_task],
                           verbose=0, multiprocess=100, one_second_per_job=one_second_per_job)
        with open(tempdir + "/merged.results") as oo:
            self.assertEqual(oo.read(),
                             "aa,ab,ac,ad,bb,bc,bd,cc,cd,dd,")

    # ___________________________________________________________________________
    #
    #   test combinations_with_replacement() pipeline_printout and pipeline_run
    # ___________________________________________________________________________
    def test_combinations_with_replacement3_printout(self):
        """Input file exists, output doesn't exist"""
        cleanup_tmpdir()

        s = StringIO()
        test_pipeline2.printout(
            s, [check_combinations_with_replacement3_merged_task], verbose=5, wrap_width=10000)
        self.assertTrue(re.search('\[.*{tempdir}/a_name.tmp1, '
                                  '.*{tempdir}/b_name.tmp1, '
                                  '.*{tempdir}/c_name.tmp1, '
                                  '.*{tempdir}/a_name.b_name.c_name.tmp2\]'.format(tempdir=tempdir), s.getvalue()))

    def test_combinations_with_replacement3_run(self):
        """Run product"""
        # output is up to date, but function body changed (e.g., source different)
        cleanup_tmpdir()
        test_pipeline2.run([check_combinations_with_replacement3_merged_task],
                           verbose=0, multiprocess=100, one_second_per_job=one_second_per_job)
        with open(tempdir + "/merged.results") as oo:
            self.assertEqual(oo.read(),
                             'aaa,aab,aac,aad,abb,abc,abd,acc,acd,add,bbb,bbc,bbd,bcc,bcd,bdd,ccc,ccd,cdd,ddd,')

    # ___________________________________________________________________________
    #
    #   cleanup
    # ___________________________________________________________________________

    def tearDown(self):
        shutil.rmtree(tempdir)

#
#   Necessary to protect the "entry point" of the program under windows.
#       see: http://docs.python.org/library/multiprocessing.html#multiprocessing-programming
#
if __name__ == '__main__':
    #pipeline_printout(sys.stdout, [check_product_task], verbose = 5)
    unittest.main()


text:
<?php

namespace HotDesign\SimpleAgendaBundle\Entity;

/**
 * Clase estática que se encarga de hacer un manejo de las monedas
 *
 */
class StaticCompany {

    const PERSONAL = 0;
    const CLARO = 1;
    const MOVISTAR = 2;

    //Arreglo de monedas Disponibles....
    //
    // array(NOMBRE_MONEDA, SIMBOLO, INDICE PARA LLEVAR A DOLAR)

    private static $companies = array(
        self::PERSONAL => array(
            'label' => 'Personal'
        ),
        self::CLARO => array(
            'label' => 'Claro'
        ),
        self::MOVISTAR => array(
            'label' => 'Movistar',
        ),
    );
    private static $id_default = self::PERSONAL;

    public static function getChoices() {
        $output = array();
        foreach (self::$companies as $k => $c)
            $output[$k] = $c['label'];
        return $output;
    }

    public static function getCompanyName($id) {
        if (isset(self::$companies[$id]['label'])) {
            return self::$companies[$id]['label'];
        }
        return false;
    }

    public static function getDefaultCompany() {
        return self::$id_default;
    }

    public static function getIdDefault() {
        return self::$id_default;
    }

};

redpajama_set_name: RedPajamaGithub


text:
.field-textbox .options-list {
	border-top: 1px solid #ccccbb;
	display: -moz-box;
	display: -webkit-box;
	list-style: none;
	margin: 0;
	padding: 1.75em 0;
	width: 100%;
}
.field-textbox .options-list > * {
	padding-right: 1.75em;
}
.field-textbox .options-list > *:last-child {
	padding-right: 0;
}
.field-textbox .options-list label {
	margin-bottom: 0;
}


text:
require 'json'

module Reeltalk
  class Client
    include Celluloid::IO
    include Celluloid::Logger
    include Celluloid::Notifications

    attr_reader :socket

    def initialize(socket)
      @socket = socket
      @nickname = nil

      subscribe 'chat', :handle_chat
      async.run
    end

    def run
      while message = JSON.parse(@socket.read)
        dispatch message
      end
    rescue EOFError
      event "left"
      terminate
    end

    def dispatch(message)
      debug "Dispatching #{message.inspect}"

      case message['action']
      when 'join'
        @nickname = message['user']
        event 'joined'
      when 'message'
        publish 'chat', message.merge('user' => nickname)
      else
        warn "unknown command '#{action}'"
      end
    end

    def handle_chat(_, message)
      @socket << JSON.generate(message)
    end

    def nickname
      @nickname || "unregistered user"
    end

    def event(message)
      info "#{nickname} #{message}"
      publish 'chat', {'action' => 'control', 'user' => nickname, 'message' => message}
    end
  end
end


text:
package com.google.schemaorg.core;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.schemaorg.SchemaOrgType;
import com.google.schemaorg.SchemaOrgTypeImpl;
import com.google.schemaorg.ValueType;
import com.google.schemaorg.core.datatype.Text;
import com.google.schemaorg.core.datatype.URL;
import com.google.schemaorg.goog.GoogConstants;
import com.google.schemaorg.goog.PopularityScoreSpecification;

/** Implementation of {@link Thing}. */
public class ThingImpl extends SchemaOrgTypeImpl implements Thing {
  private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet();

  private static ImmutableSet<String> initializePropertySet() {
    ImmutableSet.Builder<String> builder = ImmutableSet.builder();

    builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE);

    builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME);

    builder.add(CoreConstants.PROPERTY_DESCRIPTION);

    builder.add(CoreConstants.PROPERTY_IMAGE);

    builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE);

    builder.add(CoreConstants.PROPERTY_NAME);

    builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION);

    builder.add(CoreConstants.PROPERTY_SAME_AS);

    builder.add(CoreConstants.PROPERTY_URL);

    builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION);

    builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE);

    return builder.build();
  }

  static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<Thing.Builder>
      implements Thing.Builder {

    @Override
    public Thing.Builder addAdditionalType(URL value) {
      return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value);
    }

    @Override
    public Thing.Builder addAdditionalType(String value) {
      return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value));
    }

    @Override
    public Thing.Builder addAlternateName(Text value) {
      return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value);
    }

    @Override
    public Thing.Builder addAlternateName(String value) {
      return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value));
    }

    @Override
    public Thing.Builder addDescription(Text value) {
      return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value);
    }

    @Override
    public Thing.Builder addDescription(String value) {
      return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value));
    }

    @Override
    public Thing.Builder addImage(ImageObject value) {
      return addProperty(CoreConstants.PROPERTY_IMAGE, value);
    }

    @Override
    public Thing.Builder addImage(ImageObject.Builder value) {
      return addProperty(CoreConstants.PROPERTY_IMAGE, value.build());
    }

    @Override
    public Thing.Builder addImage(URL value) {
      return addProperty(CoreConstants.PROPERTY_IMAGE, value);
    }

    @Override
    public Thing.Builder addImage(String value) {
      return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value));
    }

    @Override
    public Thing.Builder addMainEntityOfPage(CreativeWork value) {
      return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value);
    }

    @Override
    public Thing.Builder addMainEntityOfPage(CreativeWork.Builder value) {
      return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build());
    }

    @Override
    public Thing.Builder addMainEntityOfPage(URL value) {
      return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value);
    }

    @Override
    public Thing.Builder addMainEntityOfPage(String value) {
      return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value));
    }

    @Override
    public Thing.Builder addName(Text value) {
      return addProperty(CoreConstants.PROPERTY_NAME, value);
    }

    @Override
    public Thing.Builder addName(String value) {
      return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value));
    }

    @Override
    public Thing.Builder addPotentialAction(Action value) {
      return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value);
    }

    @Override
    public Thing.Builder addPotentialAction(Action.Builder value) {
      return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build());
    }

    @Override
    public Thing.Builder addPotentialAction(String value) {
      return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value));
    }

    @Override
    public Thing.Builder addSameAs(URL value) {
      return addProperty(CoreConstants.PROPERTY_SAME_AS, value);
    }

    @Override
    public Thing.Builder addSameAs(String value) {
      return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value));
    }

    @Override
    public Thing.Builder addUrl(URL value) {
      return addProperty(CoreConstants.PROPERTY_URL, value);
    }

    @Override
    public Thing.Builder addUrl(String value) {
      return addProperty(CoreConstants.PROPERTY_URL, Text.of(value));
    }

    @Override
    public Thing.Builder addDetailedDescription(Article value) {
      return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value);
    }

    @Override
    public Thing.Builder addDetailedDescription(Article.Builder value) {
      return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build());
    }

    @Override
    public Thing.Builder addDetailedDescription(String value) {
      return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value));
    }

    @Override
    public Thing.Builder addPopularityScore(PopularityScoreSpecification value) {
      return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value);
    }

    @Override
    public Thing.Builder addPopularityScore(PopularityScoreSpecification.Builder value) {
      return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build());
    }

    @Override
    public Thing.Builder addPopularityScore(String value) {
      return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value));
    }

    @Override
    public Thing build() {
      return new ThingImpl(properties, reverseMap);
    }
  }

  public ThingImpl(Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) {
    super(properties, reverseMap);
  }

  @Override
  public String getFullTypeName() {
    return CoreConstants.TYPE_THING;
  }

  @Override
  public boolean includesProperty(String property) {
    return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property)
        || PROPERTY_SET.contains(GoogConstants.NAMESPACE + property)
        || PROPERTY_SET.contains(property);
  }

  @Override
  public ImmutableList<SchemaOrgType> getAdditionalTypeList() {
    return getProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE);
  }

  @Override
  public ImmutableList<SchemaOrgType> getAlternateNameList() {
    return getProperty(CoreConstants.PROPERTY_ALTERNATE_NAME);
  }

  @Override
  public ImmutableList<SchemaOrgType> getDescriptionList() {
    return getProperty(CoreConstants.PROPERTY_DESCRIPTION);
  }

  @Override
  public ImmutableList<SchemaOrgType> getImageList() {
    return getProperty(CoreConstants.PROPERTY_IMAGE);
  }

  @Override
  public ImmutableList<SchemaOrgType> getMainEntityOfPageList() {
    return getProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE);
  }

  @Override
  public ImmutableList<SchemaOrgType> getNameList() {
    return getProperty(CoreConstants.PROPERTY_NAME);
  }

  @Override
  public ImmutableList<SchemaOrgType> getPotentialActionList() {
    return getProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION);
  }

  @Override
  public ImmutableList<SchemaOrgType> getSameAsList() {
    return getProperty(CoreConstants.PROPERTY_SAME_AS);
  }

  @Override
  public ImmutableList<SchemaOrgType> getUrlList() {
    return getProperty(CoreConstants.PROPERTY_URL);
  }

  @Override
  public ImmutableList<SchemaOrgType> getDetailedDescriptionList() {
    return getProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION);
  }

  @Override
  public ImmutableList<SchemaOrgType> getPopularityScoreList() {
    return getProperty(GoogConstants.PROPERTY_POPULARITY_SCORE);
  }
}


text:
<?php

namespace yiiunit\framework\log;

use yii\log\Dispatcher;
use yii\log\Logger;
use yii\log\Target;
use yiiunit\TestCase;

/**
 * @group log
 */
class TargetTest extends TestCase
{
    public static $messages;

    public function filters()
    {
        return [
            [[], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']],

            [['levels' => 0], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']],
            [
                ['levels' => Logger::LEVEL_INFO | Logger::LEVEL_WARNING | Logger::LEVEL_ERROR | Logger::LEVEL_TRACE],
                ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
            ],
            [['levels' => ['error']], ['B', 'G', 'H']],
            [['levels' => Logger::LEVEL_ERROR], ['B', 'G', 'H']],
            [['levels' => ['error', 'warning']], ['B', 'C', 'G', 'H']],
            [['levels' => Logger::LEVEL_ERROR | Logger::LEVEL_WARNING], ['B', 'C', 'G', 'H']],

            [['categories' => ['application']], ['A', 'B', 'C', 'D', 'E']],
            [['categories' => ['application*']], ['A', 'B', 'C', 'D', 'E', 'F']],
            [['categories' => ['application.*']], ['F']],
            [['categories' => ['application.components']], []],
            [['categories' => ['application.components.Test']], ['F']],
            [['categories' => ['application.components.*']], ['F']],
            [['categories' => ['application.*', 'yii.db.*']], ['F', 'G', 'H']],
            [['categories' => ['application.*', 'yii.db.*'], 'except' => ['yii.db.Command.*']], ['F', 'G']],

            [['categories' => ['application', 'yii.db.*'], 'levels' => Logger::LEVEL_ERROR], ['B', 'G', 'H']],
            [['categories' => ['application'], 'levels' => Logger::LEVEL_ERROR], ['B']],
            [['categories' => ['application'], 'levels' => Logger::LEVEL_ERROR | Logger::LEVEL_WARNING], ['B', 'C']],
        ];
    }

    /**
     * @dataProvider filters
     * @param array $filter
     * @param array $expected
     */
    public function testFilter($filter, $expected)
    {
        static::$messages = [];

        $logger = new Logger();
        $dispatcher = new Dispatcher([
            'logger' => $logger,
            'targets' => [new TestTarget(array_merge($filter, ['logVars' => []]))],
            'flushInterval' => 1,
        ]);
        $logger->log('testA', Logger::LEVEL_INFO);
        $logger->log('testB', Logger::LEVEL_ERROR);
        $logger->log('testC', Logger::LEVEL_WARNING);
        $logger->log('testD', Logger::LEVEL_TRACE);
        $logger->log('testE', Logger::LEVEL_INFO, 'application');
        $logger->log('testF', Logger::LEVEL_INFO, 'application.components.Test');
        $logger->log('testG', Logger::LEVEL_ERROR, 'yii.db.Command');
        $logger->log('testH', Logger::LEVEL_ERROR, 'yii.db.Command.whatever');

        $this->assertEquals(count($expected), count(static::$messages));
        $i = 0;
        foreach ($expected as $e) {
            $this->assertEquals('test' . $e, static::$messages[$i++][0]);
        }
    }

    public function testGetContextMessage()
    {
        $target = new TestTarget([
            'logVars' => [
                'A', '!A.A_b', 'A.A_d',
                'B.B_a',
                'C', 'C.C_a',
                'D',
            ],
        ]);
        $GLOBALS['A'] = [
            'A_a' => 1,
            'A_b' => 1,
            'A_c' => 1,
        ];
        $GLOBALS['B'] = [
            'B_a' => 1,
            'B_b' => 1,
            'B_c' => 1,
        ];
        $GLOBALS['C'] = [
            'C_a' => 1,
            'C_b' => 1,
            'C_c' => 1,
        ];
        $GLOBALS['E'] = [
            'C_a' => 1,
            'C_b' => 1,
            'C_c' => 1,
        ];
        $context = $target->getContextMessage();
        $this->assertContains('A_a', $context);
        $this->assertNotContains('A_b', $context);
        $this->assertContains('A_c', $context);
        $this->assertContains('B_a', $context);
        $this->assertNotContains('B_b', $context);
        $this->assertNotContains('B_c', $context);
        $this->assertContains('C_a', $context);
        $this->assertContains('C_b', $context);
        $this->assertContains('C_c', $context);
        $this->assertNotContains('D_a', $context);
        $this->assertNotContains('D_b', $context);
        $this->assertNotContains('D_c', $context);
        $this->assertNotContains('E_a', $context);
        $this->assertNotContains('E_b', $context);
        $this->assertNotContains('E_c', $context);
    }

    /**
     * @covers \yii\log\Target::setLevels()
     * @covers \yii\log\Target::getLevels()
     */
    public function testSetupLevelsThroughArray()
    {
        $target = $this->getMockForAbstractClass('yii\\log\\Target');

        $target->setLevels(['info', 'error']);
        $this->assertEquals(Logger::LEVEL_INFO | Logger::LEVEL_ERROR, $target->getLevels());

        $target->setLevels(['trace']);
        $this->assertEquals(Logger::LEVEL_TRACE, $target->getLevels());

        $this->expectException('yii\\base\\InvalidConfigException');
        $this->expectExceptionMessage('Unrecognized level: unknown level');
        $target->setLevels(['info', 'unknown level']);
    }

    /**
     * @covers \yii\log\Target::setLevels()
     * @covers \yii\log\Target::getLevels()
     */
    public function testSetupLevelsThroughBitmap()
    {
        $target = $this->getMockForAbstractClass('yii\\log\\Target');

        $target->setLevels(Logger::LEVEL_INFO | Logger::LEVEL_WARNING);
        $this->assertEquals(Logger::LEVEL_INFO | Logger::LEVEL_WARNING, $target->getLevels());

        $target->setLevels(Logger::LEVEL_TRACE);
        $this->assertEquals(Logger::LEVEL_TRACE, $target->getLevels());

        $this->expectException('yii\\base\\InvalidConfigException');
        $this->expectExceptionMessage('Incorrect 128 value');
        $target->setLevels(128);
    }

    public function testGetEnabled()
    {
        /** @var Target $target */
        $target = $this->getMockForAbstractClass('yii\\log\\Target');

        $target->enabled = true;
        $this->assertTrue($target->enabled);

        $target->enabled = false;
        $this->assertFalse($target->enabled);

        $target->enabled = function ($target) {
            return empty($target->messages);
        };
        $this->assertTrue($target->enabled);
    }

    public function testFormatMessage()
    {
        /** @var Target $target */
        $target = $this->getMockForAbstractClass('yii\\log\\Target');

        $text = 'message';
        $level = Logger::LEVEL_INFO;
        $category = 'application';
        $timestamp = 1508160390.6083;

        $expectedWithoutMicro = '2017-10-16 13:26:30 [info][application] message';
        $formatted = $target->formatMessage([$text, $level, $category, $timestamp]);
        $this->assertSame($expectedWithoutMicro, $formatted);

        $target->microtime = true;

        $expectedWithMicro = '2017-10-16 13:26:30.6083 [info][application] message';
        $formatted = $target->formatMessage([$text, $level, $category, $timestamp]);
        $this->assertSame($expectedWithMicro, $formatted);

        $timestamp = 1508160390;

        $expectedWithoutMicro = '2017-10-16 13:26:30 [info][application] message';
        $formatted = $target->formatMessage([$text, $level, $category, $timestamp]);
        $this->assertSame($expectedWithoutMicro, $formatted);
    }
}

class TestTarget extends Target
{
    public $exportInterval = 1;

    /**
     * Exports log [[messages]] to a specific destination.
     * Child classes must implement this method.
     */
    public function export()
    {
        TargetTest::$messages = array_merge(TargetTest::$messages, $this->messages);
        $this->messages = [];
    }

    /**
     * @inheritdoc
     */
    public function getContextMessage()
    {
        return parent::getContextMessage();
    }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M2.475,22.05 L21.525,3.025V22.05ZM9.825,20.4H19.875V7.025L9.825,17.075Z"/>
</vector>


text:
/* bbflow, buttons for markItUp! */
.markItUp .m_flowmenu a			{ background-image: url(images/flowmenu.png); }

.markItUp .mv_collegehumor a	{ background-image: url(images/v/collegehumor.png); }
.markItUp .mv_dailymotion a		{ background-image: url(images/v/dailymotion.png); }
.markItUp .mv_gamespot a		{ background-image: url(images/v/gamespot.png); }
.markItUp .mv_gametrailers a	{ background-image: url(images/v/gametrailers.png); }
.markItUp .mv_googlevideo a		{ background-image: url(images/v/googlevideo.png); }
.markItUp .mv_metacafe a		{ background-image: url(images/v/metacafe.png); }
.markItUp .mv_rutube a			{ background-image: url(images/v/rutube.png); }
.markItUp .mv_spike a			{ background-image: url(images/v/spike.png); }
.markItUp .mv_veoh a			{ background-image: url(images/v/veoh.png); }
.markItUp .mv_videomailru a		{ background-image: url(images/v/videomailru.png); }
.markItUp .mv_yahoovideo a		{ background-image: url(images/v/yahoovideo.png); }
.markItUp .mv_youtube a			{ background-image: url(images/v/youtube.png); }


text:
cask 'mirador' do
  version '1.3'
  sha256 'bc9e8a6f3de948a8674de3d35b9f9074be15421f24f4bcce5591899dc828a9c2'

  # github.com is the official download host per the vendor homepage
  url "https://github.com/mirador/mirador/releases/download/#{version}/mirador-macosx-#{version}.zip"
  appcast 'https://github.com/mirador/mirador/releases.atom'
  name 'Mirador'
  homepage 'http://fathom.info/mirador/'
  license :gpl

  app 'Mirador.app'
end


text:
#ifndef WINPR_H
#define WINPR_H

#include <winpr/platform.h>

#ifdef WINPR_DLL
#if defined _WIN32 || defined __CYGWIN__
#ifdef WINPR_EXPORTS
#ifdef __GNUC__
#define WINPR_API __attribute__((dllexport))
#else
#define WINPR_API __declspec(dllexport)
#endif
#else
#ifdef __GNUC__
#define WINPR_API __attribute__((dllimport))
#else
#define WINPR_API __declspec(dllimport)
#endif
#endif
#else
#if __GNUC__ >= 4
#define WINPR_API __attribute__((visibility("default")))
#else
#define WINPR_API
#endif
#endif
#else /* WINPR_DLL */
#define WINPR_API
#endif

#if defined(WIN32) && !defined(__CYGWIN__)
#define WINPR_DEPRECATED(obj) __declspec(deprecated) obj
#elif defined(__GNUC__)
#define WINPR_DEPRECATED(obj) obj __attribute__((deprecated))
#else
#define WINPR_DEPRECATED(obj) obj
#endif

/* Thread local storage keyword define */
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define WINPR_TLS __thread
#else
#define WINPR_TLS __declspec(thread)
#endif
#elif !defined(__IOS__)
#define WINPR_TLS __thread
#else
#warning "Target iOS does not support Thread Local Storage!"
#warning "Multi Instance support is disabled!"
#define WINPR_TLS
#endif

#ifdef _WIN32
#define INLINE __inline
#else
#define INLINE inline
#endif

WINPR_API void winpr_get_version(int* major, int* minor, int* revision);
WINPR_API const char* winpr_get_version_string(void);
WINPR_API const char* winpr_get_build_date(void);
WINPR_API const char* winpr_get_build_revision(void);
WINPR_API const char* winpr_get_build_config(void);

#define WINPR_UNUSED(x) (void)(x)

#endif /* WINPR_H */


text:
<?php

namespace PH7;

defined('PH7') or exit('Restricted access');

use PH7\Framework\Layout\Html\Design;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;

class Permission extends PermissionCore
{
    public function __construct()
    {
        parent::__construct();

        if ((UserCore::auth() || AffiliateCore::auth() || AdminCore::auth()) &&
            ($this->registry->action === 'forgot' || $this->registry->action === 'reset')
        ) {
            Header::redirect(
                Uri::get('lost-password', 'main', 'account'),
                $this->alreadyConnectedMsg(),
                Design::ERROR_TYPE
            );
        }
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\Casio;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class DateTimeOriginal extends AbstractTag
{

    protected $Id = 77;

    protected $Name = 'DateTimeOriginal';

    protected $FullName = 'Casio::QVCI';

    protected $GroupName = 'Casio';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'Casio';

    protected $g2 = 'Camera';

    protected $Type = 'string';

    protected $Writable = false;

    protected $Description = 'Date/Time Original';

    protected $local_g2 = 'Time';

    protected $flag_Permanent = true;

    protected $MaxLength = 20;

}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="48"
    android:viewportHeight="48"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M13.15,30.85V17.1H21.65L32.9,5.9V42.1L21.65,30.85Z"/>
</vector>


text:
cask 'font-monoton' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/monoton/Monoton-Regular.ttf'
  name 'Monoton'
  homepage 'https://www.google.com/fonts/specimen/Monoton'

  font 'Monoton-Regular.ttf'
end


text:
namespace PXPAgent {

// Holds a time point reference to a past instant and allows comparing
// it to timestamps in ISO8601 format
class Timestamp {
  public:
    struct Error : public std::runtime_error {
        explicit Error(std::string const& msg) : std::runtime_error(msg) {}
    };

    boost::posix_time::ptime time_point;

    // If the specified time interval is not in the following format,
    // the ctor throws an Error: <integer value><suffix>
    // Possible suffixes (ex. "14d"):
    //      `d`  - days
    //      `h`  - hours
    //      `m`  - minutes
    Timestamp(const std::string& past_duration);

    // Returns a ptime time point for a past instant that is old
    // as specified
    // Throws an Error in case past_duration is not in a valid format,
    // as described mentioned above
    static boost::posix_time::ptime getPastInstant(std::string past_duration);

    // Returns the number of minutes out of the specified duration
    // Throws an Error in case past_duration is not in a valid format,
    // as described mentioned above
    static unsigned int getMinutes(std::string past_duration);

    // Throws an Error in case the specified time string is not in
    // the extended ISO format (refer to boost date_time docs)
    static std::string convertToISO(std::string extended_ISO8601_time);

    // Throws an Error in case it fails to create a time point from
    // the specified extended ISO date time string
    bool isNewerThan(const std::string& extended_ISO8601_time);

    bool isNewerThan(const std::time_t&);
};

}  // namespace PXPAgents

#endif  // SRC_AGENT_TIME_HPP


text:
var co = require('co')
var methods = require('methods')
var slice = Array.prototype.slice

module.exports = function (express) {
  function coexpress () {
    var app = express()
    wrap(app)
    app.use(startMiddleware)
    return app
  }

  coexpress.__proto__ = express

  if (express.Router) {
    coexpress.Router = function () {
      var router = express.Router()
      wrap(router)
      return router
    }
  }

  function startMiddleware (req, res, next) {
    res.render = wrapResponseMethod(res.render)
    res.send = wrapResponseMethod(res.send)
    res.throw = safeThrow
    next()
  }

  coexpress.errorMiddleware = function (opts) {
    opts = opts || {}

    if (opts.log === true) {
      opts.log = console.error.bind(console)
    }

    return function (error, req, res, next) {
      var code = error.code || 500
      var err = error.expose ? error.message : 'Internal Server Error'

      if (opts.log) {
        opts.log(error.stack)
      }

      res.send(code, {
        error: err
      })
    }
  }

  return coexpress
}

function wrap (app) {
  methods.forEach(function (method) {
    app[method] = wrapAppMethod(app[method])
  })

  app.param = wrapParamMethod(app.param)
  app.use = wrapAppMethod(app.use)
  app.all = wrapAppMethod(app.all)
  app.del = app.delete
}

function wrapAppMethod (route) {
  return function () {
    return route.apply(this, slice.call(arguments).map(convertGenerators))
  }
}

function wrapParamMethod (route) {
  return function (name, fn) {
    var cb = fn

    if (isGenerator(fn)) {
      cb = function (req, res, next, id) {
        co(fn).call(this, req, res, id, nextIfAble(req, res, next))
      }
    }

    return route.call(this, name, cb)
  }
}

function convertGenerators (v) {
  return ! isGenerator(v) ? v : function (req, res, next) {
    co(v).call(this, req, res, nextIfAble(req, res, next))
  }
}

function nextIfAble (req, res, next) {
  return function (err) {
    // setImmediate(function () {
      if (err || ! res.sent) next(err)
    // })
  }
}

function isGenerator (v) {
  return typeof v === 'function' && 'GeneratorFunction' === v.constructor.name
}

function wrapResponseMethod (method) {
  return function () {
    this.sent = true
    method.apply(this, arguments)
  }
}

function safeThrow (code, message) {
  var err = new Error(message)
  err.expose = true
  err.code = code
  throw err
}


text:
#include "reader.h"
#include "config.h"
#include "error.h"

#define MODULE_NAME "reader.c"

#ifdef DEBUG_READER
#include "debugging.h"
#else
#include "no_debugging.h"
#endif

/******************************************************************************
 *                              Public Functions
 ******************************************************************************/

struct Reader *newReader(struct Expression *env,
                         struct CharReadStream *stream) {
    struct Reader *reader = SAFE_MALLOC(sizeof(struct Reader));
    assert(env && stream);
    reader->type = EXPR_SYMBOL;
    reader->expr = NULL;
    reader->env = env;
    reader->lookup = SAFE_MALLOC(sizeof(struct ReadMacroLookUp));
    registerStandardReadMacro(reader, rmIdentity);
    reader->lookup->next = 0;
    reader->lookup->sign = 0;
    reader->stream = stream;
    reader->buffer = SAFE_STRING_NEW(READ_BUFFER_SIZE);
    reader->symbolTable = symbolTableCreate(READER_GET_ENVIRONMENT(reader));
    resetReader(reader);
    return reader;
}

void deleteReader(struct Reader *reader) {
    struct ReadMacroLookUp *entry, *nextEntry;

    assert(reader);

    entry = reader->lookup;

    if (reader) {
        if (reader->lookup) {
            while (entry) {
                nextEntry = entry->next;
                free(entry);
                entry = nextEntry;
            };
        };
        if (reader->buffer) free(reader->buffer);
        symbolTableDispose(READER_GET_ENVIRONMENT(reader), reader->symbolTable);
        free(reader);
    };
    reader = 0;
}

void resetReader(struct Reader *reader) {
    assert(reader);
    if (reader->expr) {
        reader->expr = (void *)0;
    };
    reader->type = EXPR_NO_TYPE;
    reader->current = reader->buffer;
}

struct Expression *fuRead(struct Reader *reader) {
    char readChar;
    NativeReadMacro macro;
    struct Expression *expr = 0;

    assert(reader);
    assert(0 == reader->expr);

    while (0 != (readChar = READ_NEXT_CHAR(reader))) {

        DEBUG_PRINT_PARAM(" Got '%c'\n", readChar);

        macro = LOOKUP_READ_MACRO((char)readChar, reader);
        DEBUG_PRINT_NATIVE_FUNC(macro);
        if (macro) {
            macro(reader, readChar);
            /* if the macro returned an expression, we are done  */
            if (reader->expr) {
                DEBUG_PRINT("fuRead() returns expr : \n");
                DEBUG_PRINT_EXPR(READER_GET_ENVIRONMENT(reader), reader->expr);
                expr = reader->expr;
                reader->expr = 0;
                return expr;
            }
            /* Any Read macro should take care to restore the status of the
             * reader lookup to the state when it was invoked */
        } else {
            /* Any char not triggering any macro indicates that the read string
             * is indeed a symbol */
            /* Should never ever be reached !  */
            DEBUG_PRINT("read was unable to deal with readChar!");
        };
    };

    /* if not looked up yet, try to evaluate the input */
    if ((macro = LOOKUP_READ_MACRO(0, reader))) {
        macro(reader, 0);
    } else {
        rmTerminator(reader, 0); /* If none registered, take the standard
                                    terminating macro */
    }

    DEBUG_PRINT(" reached end of function\n");
    DEBUG_PRINT_EXPR(READER_GET_ENVIRONMENT(reader), reader->expr);

    expr = reader->expr;
    reader->expr = 0;

    return expr;

}

NativeReadMacro lookupReadMacro(struct Reader *reader, char c) {
    struct ReadMacroLookUp *entry;

    assert(reader);
    if (!reader->lookup) return 0;
    /* if lookup does not contain any special macros, so give back the standard
       one */
    if (!reader->lookup->next) return reader->lookup->macro;
    entry = reader->lookup->next;
    while (entry->next && entry->sign != c) {
        entry = entry->next;
    }

    /* if none found, return the standard read macro, i.e. the first in the list
     * */
    if (entry->sign != c) entry = reader->lookup;
    return entry->macro;
}

NativeReadMacro registerStandardReadMacro(struct Reader *reader,
                                          NativeReadMacro macro) {
    NativeReadMacro old;
    assert(reader);
    old = reader->lookup->macro;
    reader->lookup->macro = macro;
    return old;
}

NativeReadMacro registerReadMacro(struct Reader *reader, unsigned char c,
                                  NativeReadMacro macro) {
    NativeReadMacro old;
    struct ReadMacroLookUp *before, *entry = reader->lookup;
    assert(reader);

    before = reader->lookup;

    while (entry->next && entry->next->sign != c) {
        before = entry;
        entry = entry->next;
    };

    if (entry->next && entry->next->sign == c) {
        DEBUG_PRINT_PARAM("registerLookup: Searched for '%c'", c);
        DEBUG_PRINT_PARAM("   (%u)  ", (unsigned int)c);
        DEBUG_PRINT_PARAM(" Found '%c'\n", entry->sign);
        if (!macro) {
            DEBUG_PRINT_PARAM("Removed '%c\n' from Read Macro Lookup\n", c);
            before->next->next = entry->next->next;
            old = entry->next->macro;
            free(entry->next);
            return old;
        };
        DEBUG_PRINT_PARAM("Replaced '%c' from Read Macro Lookup\n", c);
        old = entry->next->macro;
        entry->next->macro = macro;
        return old;
    };
    /* Macro entry does not yet exist - create it */
    DEBUG_PRINT_PARAM("Created entry for '%c\n' in Read Macro Lookup\n", c);
    entry->next = SAFE_MALLOC(sizeof(struct ReadMacroLookUp));
    entry = entry->next;
    entry->macro = macro;
    entry->sign = c;
    entry->next = 0;
    return 0;
}

/**
 * Cast the content of reader->buffer to whatever type is given as reader->type
 * and store the expression in reader->expr
 */
void setExprOfReader(struct Reader *reader) {
    float f;

    assert(reader);

    DEBUG_PRINT("setExprOfReader() invoked\n");

    if (reader->buffer == reader->current) {
        reader->expr = NIL;
        return;
    };

    switch (reader->type) {
        case EXPR_SYMBOL:
            *reader->current = 0;
            reader->expr = GET_SYMBOL(reader, reader->buffer);
            DEBUG_PRINT_PARAM("   Created %s\n",
                              EXPRESSION_STRING(reader->expr));
            break;

        case EXPR_CHARACTER:
            reader->expr = CREATE_CHAR_EXPRESSION(
                READER_GET_ENVIRONMENT(reader), *(reader->current - 1));
            DEBUG_PRINT_PARAM("   Created %c\n",
                              EXPRESSION_CHARACTER(reader->expr));
            *reader->current = 0;
            break;

        case EXPR_STRING:
            *reader->current = 0;
            reader->expr = CREATE_STRING_EXPRESSION(
                READER_GET_ENVIRONMENT(reader), reader->buffer);
            DEBUG_PRINT_PARAM("   Created %s\n",
                              EXPRESSION_STRING(reader->expr));
            break;

        case EXPR_INTEGER:
            *reader->current = 0;
            reader->expr = stringToIntExpression(READER_GET_ENVIRONMENT(reader),
                                                 reader->buffer);
            DEBUG_PRINT_PARAM("   Created %i\n",
                              EXPRESSION_INTEGER(reader->expr));
            break;

        case EXPR_FLOAT:
            *reader->current = 0;
            f = atof(reader->buffer);
            reader->expr =
                CREATE_FLOAT_EXPRESSION(READER_GET_ENVIRONMENT(reader), f);
            DEBUG_PRINT_PARAM("   Created %f\n",
                              EXPRESSION_FLOATING(reader->expr));
            break;

        case EXPR_NO_TYPE:
            reader->expr =
                CREATE_INVALID_EXPRESSION(READER_GET_ENVIRONMENT(reader));
            break;

        default:
            ERROR(ERR_UNEXPECTED_VAL,
                  "Could not determine type of read expression");
    };

    *reader->current = 0;
    DEBUG_PRINT_PARAM("   Found  %s\n", reader->buffer);
    DEBUG_PRINT_PARAM("   Expr set: %s\n", (reader->expr) ? "yes" : "no");
    return;
}

void printLookup(struct Reader *reader) {
    struct ReadMacroLookUp *next;

    assert(reader && reader->lookup);

    next = reader->lookup;

    while (next->next) {
        fprintf(stderr, "%c ", next->next->sign);
        next = next->next;
    };

    fprintf(stderr, "\n");
}

void rmIgnore(struct Reader *reader, char sigle) {
    /* well, yes, thats exactly what it does - nothing */
}

void rmIdentity(struct Reader *reader, char sigle) {
    assert(reader);
    PUSH_INTO_BUFFER(sigle, reader);
}

void rmTerminator(struct Reader *reader, char sigle) {
    assert(reader != 0);

    DEBUG_PRINT_PARAM("Read macro rmTerminator called with %c\n", sigle);
    if (reader->buffer != reader->current) {
        setExprOfReader(reader);
    };
}


text:
//---------------------------------------------------------------------------
#ifndef MediaInfo_Ac3H
#define MediaInfo_Ac3H
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/File__Analyze.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Class File_Ac3
//***************************************************************************

class File_Ac3 : public File__Analyze
{
public :
    //In
    int64u Frame_Count_Valid;
    bool   MustParse_dac3;
    bool   MustParse_dec3;
    bool   CalculateDelay;

    //Constructor/Destructor
    File_Ac3();

private :
    //Streams management
    void Streams_Fill();
    void Streams_Finish();

    //Buffer - File header
    bool FileHeader_Begin();

    //Buffer - Synchro
    bool Synchronize();
    void Synched_Init();
    bool Synched_Test();

    //Buffer - Demux
    #if MEDIAINFO_DEMUX
    bool Demux_UnpacketizeContainer_Test();
    #endif //MEDIAINFO_DEMUX

    //Buffer - Global
    void Read_Buffer_Continue ();
    void Read_Buffer_Unsynched();
    #if MEDIAINFO_SEEK
    size_t Read_Buffer_Seek (size_t Method, int64u Value, int64u ID);
    #endif //MEDIAINFO_SEEK

    //Buffer - Per element
    void Header_Parse();
    void Data_Parse();

    //Elements
    void Core();
    void Core_Frame();
    void HD();
    void TimeStamp();
    void dac3();
    void dec3();
    bool FrameSynchPoint_Test();
    bool CRC_Compute(size_t Size);
    size_t Core_Size_Get();
    size_t HD_Size_Get();

    //Buffer
    const int8u* Save_Buffer;
    size_t Save_Buffer_Offset;
    size_t Save_Buffer_Size;

    //Temp
    struct dolby
    {
        int8u  dialnorm;
        int8u  compr;
        int8u  dynrng;  //This is only the first occurence of aufblk
        bool   compre;
        bool   dynrnge;  //This is only the first occurence of aufblk

        dolby()
        {
            dialnorm=0;
            compre=false;
            dynrnge=false;
        }
    };
    dolby  FirstFrame_Dolby;
    dolby  FirstFrame_Dolby2;
    std::vector<int64u> dialnorms;
    std::vector<int64u> dialnorm2s;
    std::vector<int64u> comprs;
    std::vector<int64u> compr2s;
    std::vector<int64u> dynrngs;
    std::vector<int64u> dynrng2s;
    std::map<int8u, int64u> fscods;
    std::map<int8u, int64u> frmsizecods;
    int64u Frame_Count_HD;
    int16u chanmap_Max[8][9];
    int16u frmsizplus1_Max[8][9];
    int16u HD_BitRate_Max;
    int16u HD_Channels2;
    int8u  fscod;
    int8u  fscod2;
    int8u  frmsizecod;
    int8u  bsid;
    int8u  bsid_Max;
    int8u  bsmod_Max[8][9];
    int8u  acmod_Max[8][9];
    int8u  dsurmod_Max[8][9];
    int8u  numblkscod;
    int8u  HD_StreamType;
    int8u  HD_SubStreams_Count;
    int8u  HD_SamplingRate1;
    int8u  HD_SamplingRate2;
    int8u  HD_Channels1;
    int8u  HD_Resolution1;
    int8u  HD_Resolution2;
    int8u  dynrng_Old;
    int8u  substreamid_Independant_Current;
    int8u  substreams_Count;
    bool   lfeon_Max[8][9];
    bool   dxc3_Parsed;
    bool   HD_MajorSync_Parsed;
    bool   HD_NoRestart;
    bool   HD_ExtraParity;
    bool   HD_IsVBR;
    bool   Core_IsPresent;
    bool   HD_IsPresent;
    bool   dynrnge_Exists;
    bool   chanmape_Max[8][9];
    bool   TimeStamp_IsPresent;
    bool   TimeStamp_IsParsing;
    bool   TimeStamp_Parsed;
    bool   TimeStamp_DropFrame_IsValid;
    bool   TimeStamp_DropFrame_Content;
    bool   BigEndian;
    bool   IgnoreCrc_Done;
    bool   IgnoreCrc;
    float64 TimeStamp_Content;
};

} //NameSpace

#endif


text:
package pbutil

import (
	"context"

	"github.com/golang/protobuf/proto"
	"golang.org/x/sync/errgroup"

	pb "go.chromium.org/luci/resultdb/proto/v1"
)

// Query queries for results continuously, sending individual items to
// dest channel until the paging query is exhausted or the context is canceled.
// A request must be *pb.QueryTestResultRequest, pb.QueryTestExonerationsRequest
// or *pb.QueryArtifactsRequest. Messages sent to dest are *pb.TestResult,
// *pb.TestExoneration or *pb.Artifact respectively.
//
// Does not return the next page token because ctx can be canceled in the middle
// of a page.
//
// If there are multiple requests in reqs, then runs them all concurrently and
// sends all of their results to dest.
// This is useful to query items of different types, e.g. test results and
// test exonerations.
// Does not limit concurrency.
func Query(ctx context.Context, dest chan<- proto.Message, client pb.ResultDBClient, reqs ...proto.Message) error {
	eg, ctx := errgroup.WithContext(ctx)
	for _, req := range reqs {
		// Check req type.
		switch req.(type) {
		case *pb.QueryTestResultsRequest:
		case *pb.QueryTestExonerationsRequest:
		case *pb.QueryArtifactsRequest:
		default:
			panic("req must be *QueryTestResultRequest, *QueryTestExonerationRequest or *QueryArtifactsRequest")
		}

		q := &queryResults{
			client: client,
			// Make a copy because we will be modifying it.
			req:  proto.Clone(req),
			dest: dest,
		}
		eg.Go(func() error {
			return q.run(ctx)
		})
	}
	return eg.Wait()
}

// queryResults implements Query for one request.
type queryResults struct {
	client pb.ResultDBClient
	req    proto.Message
	dest   chan<- proto.Message
}

func (q *queryResults) run(ctx context.Context) error {
	// Prepare a channel for responses such that we can make an RPC as soon as we
	// started consuming the response, as opposed to after the response is
	// completely consumed.
	batchC := make(chan []proto.Message)
	errC := make(chan error, 1)
	go func() {
		defer close(batchC)
		errC <- q.queryResponses(ctx, batchC)
	}()

	// Forward items to q.dest.
	for batch := range batchC {
		for _, item := range batch {
			// Note: selecting on errC here would be a race because the batch
			// goroutine might have been already done, but we still did not send all
			// items to the caller.
			select {
			case <-ctx.Done():
				return <-errC
			case q.dest <- item:
			}
		}
	}
	return <-errC
}

// queryResponses pages through query results and sends item batches to batchC.
func (q *queryResults) queryResponses(ctx context.Context, batchC chan<- []proto.Message) error {
	// The initial token is the current token in the base request.
	token := (q.req).(interface{ GetPageToken() string }).GetPageToken()
	for {
		var batch []proto.Message
		var err error
		batch, token, err = q.call(ctx, token)
		if err != nil || len(batch) == 0 {
			if ctx.Err() != nil {
				return ctx.Err()
			}
			return err
		}

		select {
		case batchC <- batch:
		case <-ctx.Done():
			return ctx.Err()
		}

		if token == "" {
			return nil
		}
	}
}

// call makes a request with a given page token.
func (q *queryResults) call(ctx context.Context, pageToken string) (batch []proto.Message, nextPageToken string, err error) {
	// Make a call and convert the response to generic types.
	switch req := q.req.(type) {
	case *pb.QueryTestResultsRequest:
		req.PageToken = pageToken
		var res *pb.QueryTestResultsResponse
		res, err = q.client.QueryTestResults(ctx, req)
		if res != nil {
			batch = make([]proto.Message, len(res.TestResults))
			for i, r := range res.TestResults {
				batch[i] = r
			}
			nextPageToken = res.NextPageToken
		}

	case *pb.QueryTestExonerationsRequest:
		req.PageToken = pageToken
		var res *pb.QueryTestExonerationsResponse
		res, err = q.client.QueryTestExonerations(ctx, req)
		if res != nil {
			batch = make([]proto.Message, len(res.TestExonerations))
			for i, r := range res.TestExonerations {
				batch[i] = r
			}
			nextPageToken = res.NextPageToken
		}

	case *pb.QueryArtifactsRequest:
		req.PageToken = pageToken
		var res *pb.QueryArtifactsResponse
		res, err = q.client.QueryArtifacts(ctx, req)
		if res != nil {
			batch = make([]proto.Message, len(res.Artifacts))
			for i, r := range res.Artifacts {
				batch[i] = r
			}
			nextPageToken = res.NextPageToken
		}

	default:
		panic("impossible")
	}

	return
}


text:
import { FormGroup } from "@angular/forms";

export class EqualValidator{
  public static validate(firstField,secondField){
    return (c:FormGroup) => {
      return (c.controls && c.controls[firstField].value == c.controls[secondField].value) ? null : {
          passwordsEqual:{
            valid:false
          }
        }
    }
}
}


text:
import Form from '../form';

class LoginForm extends Form {
  constructor() {
    super({
      domSelector: '#login-form',
      httpMethod: 'POST',
      uri: '/signin',
      manifest: {
        username: {
          required: true,
          email: true,
        },
        password: {
          required: true,
        },
      },
      alertOnFieldError: false,
    });
  }

  onGetData(data) {
    if (data.username) {
      data.email = data.username;
      delete data.username;
    }
    if (data.password) {
      data.secretword = data.password;
      delete data.password;
    }
    return data;
  }
}

export default LoginForm;


text:
require 'webmock'
require 'webmock/rspec'
require 'rspec/wait'
require 'pry'
require 'rack'
require 'rack/test'
require 'rake'

if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.0')
  require 'sidekiq'
  require 'sidekiq/cli'
end

require 'airbrake'
require 'airbrake/rake/tasks'

# Load integration tests only when they're run through appraisals.
if ENV['APPRAISAL_INITIALIZED']
  # Gems from appraisals that every application uses.
  require 'warden'

  # Load a Rails app or skip.
  begin
    ENV['RAILS_ENV'] = 'test'

    if RUBY_ENGINE == 'jruby'
      require 'activerecord-jdbcsqlite3-adapter'
    else
      require 'sqlite3'
    end

    require 'rails'

    rails_vsn = Gem::Version.new(Rails.version)

    ENV['DATABASE_URL'] = if rails_vsn <= Gem::Version.new('4.2')
                            'sqlite3:///:memory:'
                          else
                            'sqlite3::memory:'
                          end

    require 'action_controller'
    require 'action_view'
    require 'action_view/testing/resolvers'
    require 'active_record/railtie'
    if rails_vsn >= Gem::Version.new('4.2')
      require 'active_job'

      # Silence logger.
      ActiveJob::Base.logger.level = 99
    end

    require 'resque'
    require 'resque_spec'
    require 'airbrake/resque/failure'
    Resque::Failure.backend = Resque::Failure::Airbrake

    require 'delayed_job'
    require 'delayed_job_active_record'
    require 'airbrake/delayed_job/plugin'
    Delayed::Worker.delay_jobs = false

    require 'airbrake/rails/railtie'

    load 'apps/rails/dummy_task.rake'
    require 'apps/rails/dummy_app'
  rescue LoadError
    puts '** Skipped Rails specs'
  end

  # Load a Sinatra app or skip.
  begin
    # Resque depends on Sinatra, so when we launch Rails specs, we also
    # accidentally load Sinatra.
    raise LoadError if defined?(Resque)

    require 'sinatra'
    require 'apps/sinatra/dummy_app'
  rescue LoadError
    puts '** Skipped Sinatra specs'
  end

  # Load a Rack app or skip.
  begin
    require 'apps/rack/dummy_app'
  rescue LoadError
    puts '** Skipped Rack specs'
  end
end

RSpec.configure do |c|
  c.order = 'random'
  c.color = true
  c.disable_monkey_patching!
  c.wait_timeout = 3

  c.include Rack::Test::Methods
end

Airbrake.configure do |c|
  c.project_id = 113743
  c.project_key = 'fd04e13d806a90f96614ad8e529b2822'
  c.logger = Logger.new('/dev/null')
  c.app_version = '1.2.3'
  c.workers = 5
end

# Make sure tests that use async requests fail.
Thread.abort_on_exception = true

AirbrakeTestError = Class.new(StandardError)

# Print header with versions information. This simplifies debugging of build
# failures on CircleCI.
versions = <<EOS
#{'#' * 80}
# RUBY_VERSION: #{RUBY_VERSION}
# RUBY_ENGINE: #{RUBY_ENGINE}
EOS
versions << "# JRUBY_VERSION #{JRUBY_VERSION}\n" if defined?(JRUBY_VERSION)
versions << "# Rails version: #{Rails.version}\n" if defined?(Rails)
versions << "# Sinatra version: #{Sinatra::VERSION}\n" if defined?(Sinatra)
versions << "# Rack release: #{Rack.release}\n"
versions << '#' * 80

puts versions


text: System.import("./lib/main/index").catch(console.error);


text:
# JSON in .NET
## Parsing JSON with .NET'

Databases

Telerik Software Academy

    http://academy.telerik.com

# Table of Contents

*   The JSON data format
    *   Rules and features
    *   Usage
*   JSON.NET Overview
    *   Installation and usage
    *   LINQ-to-JSON
    *   JSON to XML and XML to JSON

#   The JSON Data Format

*   JSON (JavaScript Object Notation) is a lightweight data format
    *   Human and machine-readable
    *   Based on the way to create objects in JS
    *   Platform independent - can be used with any programming language

#   JSON Rules

*   The JSON format follows  the rules of object literals in JS

*   **Strings**, **numbers** and **Booleans** are valid JSON

```javascript
"this is string and is valid JSON"
```

*   **Arrays** are valid JSON

```javascript
[5, 'string', true]
```

*   **Objects** are valid JSON

```javascript
{
  "firstname": "Doncho",
  "lastname": "Minkov",
  "occupation": "Technical trainer"
}

```

#   Built-in JSON Serializers

*   .NET has **built-in JSON serializer**:
    *   The `JavaScriptSerializer` class, contained in `System.Web.Extensions` assembly
*   `JavaScriptSerializer` has parsing from object to JSON string and vice versa:

```cs
var place = new Place(…);
var serializer = new JavaScriptSerializer();

var jsonPlace = serializer.Serialize(place);
var objPlace = serializer.Deserialize<Place>(jsonPlace);
```

##   Demo

#   What is JSON.NET?

*   JSON.NET is a library for parsing JSON in .NET
    *   Has better performance than the `JavaScriptSerializer`
    *   Provides **LINQ-to-JSON**
    *   Has an out-of-the-box support for parsing between JSON and XML

#   Installing JSON.NET

*   To install JSON.NET run in the Package Manager Console:

```bash
$ Install-Package Newtonsoft.Json
```

*   JSON.NET has two primary methods:
    *   Serialize an object:

    ```cs
    var jsonObj = JsonConvert.SerializeObject(obj);
    ```

    *   Deserialize an object:

    ```cs
    var copy = JsonConvert.DeserializeObject<ObjType>(jsonObj);
    ```

##   Demo

#   JSON.NET Features

*   JSON.NET can be configured to:
    *   **Indent** the output JSON string
    *   To convert JSON to **anonymous types**
    *   To control the **casing** and **properties** to parse
    *   To **skip errors**
*   JSON.NET also supports:
    *   **LINQ-to-JSON**
    *   Direct parse between XML and JSON

#   Configuring JSON.NET

*   To indent the output string use `Formattingg.Indented`:

```cs
JsonConvert.SerializeObject(place, Formatting.Indented);
```

*   Deserializing to anonymous types:

```cs
var json = @"{
               ""fname"": ""Doncho"",
               ""lname"": ""Minkov"",
               ""occupation"": ""Technical Trainer""
             }";

var template = new
{ FName  = "", LName = "", Occupation = "" };
var person = JsonConvert.DeserializeAnonymousType(json, template);
```

*   Must provide a template Object

##   Demo

#   JSON.NET Parsing of Objects
*   By default JSON.NET takes **each Property/Field** from the **public interface** of a class and parses it
    *   This can be controlled using attributes:

```cs
public class User
{
  [JsonProperty("user")]
  public string Username { get; set; }

  [JsonIgnore]
  public string Password { get; set; }
}

```

*   `[JsonProperty(...)]` tells the parser that `Username` is `user` in the JSON
*   `[JsonIgnore]` tells the parser to skip the property `Password`

##   Demo

#  LINQ-to-JSON

*   JSON.NET has a support for **LINQ-to-JSON**

```cs
var jsonObj = JObject.Parse(json);
Console.WriteLine("Places in {0}:", jsonObj["name"]);

jsonObj["places"].Select(
   pl =>
       string.Format("{0}) {1} ({2})",
                     index++,
                     pl["name"],
                     string.Join(", ",
                             pl["categories"].Select(
                               cat => cat["name"]))))
                 .Print();
```

##   Demo

#   XML to JSON and JSON to XML

*   Conversions from JSON to XML are done using two methods:
  *   XML to JSON

```cs
string jsonFromXml = JsonConvert.SerializeXNode(doc);
```

  *   JSON to XML

```cs
XDocument xmlFromJson = JsonConvert.DeserializeXNode(json);
```

##   Demo

# JSON in .NET
## Questions


text:
package org.jkiss.dbeaver.ui.preferences;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.IWorkbenchPropertyPage;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.impl.AbstractDescriptor;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.struct.DBSDataContainer;
import org.jkiss.dbeaver.model.struct.DBSEntity;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.model.struct.rdb.DBSTable;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.entity.EntityEditorDescriptor;
import org.jkiss.dbeaver.ui.editors.entity.EntityEditorsRegistry;
import org.jkiss.dbeaver.ui.internal.UINavigatorMessages;
import org.jkiss.dbeaver.ui.navigator.NavigatorPreferences;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/**
 * PrefPageDatabaseNavigator
 */
public class PrefPageDatabaseNavigator extends AbstractPrefPage implements IWorkbenchPreferencePage, IWorkbenchPropertyPage
{
    public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.navigator"; //$NON-NLS-1$

    private Button expandOnConnectCheck;
    private Button restoreFilterCheck;
    private Text restoreStateDepthText;
    private Button sortCaseInsensitiveCheck;
    private Button sortFoldersFirstCheck;
    private Button showConnectionHostCheck;
    private Button showObjectsDescriptionCheck;
    private Button showStatisticsCheck;
    private Button showNodeActionsCheck;
    private Button colorAllNodesCheck;

    private Button showObjectTipsCheck;
    private Button showToolTipsCheck;
    private Button showContentsInToolTipsContents;

    private Button showResourceFolderPlaceholdersCheck;
    private Button groupByDriverCheck;
    private Text longListFetchSizeText;
    private Combo dsDoubleClickBehavior;
    private Combo objDoubleClickBehavior;
    private Combo defaultEditorPageCombo;

    public PrefPageDatabaseNavigator()
    {
        super();
        setPreferenceStore(new PreferenceStoreDelegate(DBWorkbench.getPlatform().getPreferenceStore()));
    }

    @Override
    public void init(IWorkbench workbench)
    {

    }

    @Override
    protected Control createContents(Composite parent)
    {
        Composite composite = UIUtils.createPlaceholder(parent, 2, 5);

        {
            Group navigatorGroup = UIUtils.createControlGroup(composite, UINavigatorMessages.pref_page_database_general_group_navigator, 2, SWT.NONE, 0);
            ((GridData)navigatorGroup.getLayoutData()).verticalSpan = 2;

            showConnectionHostCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_host_name, UINavigatorMessages.pref_page_database_general_label_show_host_name_tip, false, 2);
            showObjectsDescriptionCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_objects_description, UINavigatorMessages.pref_page_database_general_label_show_objects_description_tip, false, 2);
            showStatisticsCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_statistics, UINavigatorMessages.pref_page_database_general_label_show_statistics_tip, false, 2);
            showNodeActionsCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_node_actions, UINavigatorMessages.pref_page_database_general_label_show_node_actions_tip, false, 2);
            showResourceFolderPlaceholdersCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_folder_placeholders, UINavigatorMessages.pref_page_database_general_label_show_folder_placeholders_tip, false, 2);
            sortFoldersFirstCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_folders_first, UINavigatorMessages.pref_page_database_general_label_folders_first_tip, false, 2);
            groupByDriverCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_group_database_by_driver, "", false, 2);
            groupByDriverCheck.setEnabled(false);

            sortCaseInsensitiveCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_order_elements_alphabetically, "", false, 2);

            colorAllNodesCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_color_all_nodes, UINavigatorMessages.pref_page_database_general_label_color_all_nodes_tip, false, 2);

            showObjectTipsCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_tips_in_tree, UINavigatorMessages.pref_page_database_general_label_show_tips_in_tree_tip, false, 2);
            showToolTipsCheck = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_tooltips, UINavigatorMessages.pref_page_database_general_label_show_tooltips_tip, false, 2);
            showContentsInToolTipsContents = UIUtils.createCheckbox(navigatorGroup, UINavigatorMessages.pref_page_database_general_label_show_contents_in_tooltips, UINavigatorMessages.pref_page_database_general_label_show_contents_in_tooltips_tip, false, 2);
        }

        {
            Group behaviorGroup = UIUtils.createControlGroup(composite, UINavigatorMessages.pref_page_database_navigator_group_behavior, 2, GridData.VERTICAL_ALIGN_BEGINNING, 0);

            objDoubleClickBehavior = UIUtils.createLabelCombo(behaviorGroup, UINavigatorMessages.pref_page_database_general_label_double_click_node, SWT.DROP_DOWN | SWT.READ_ONLY);
            objDoubleClickBehavior.add(UINavigatorMessages.pref_page_database_general_label_double_click_node_open_properties, 0);
            objDoubleClickBehavior.add(UINavigatorMessages.pref_page_database_general_label_double_click_node_expand_collapse, 1);

            dsDoubleClickBehavior = UIUtils.createLabelCombo(behaviorGroup, UINavigatorMessages.pref_page_database_general_label_double_click_connection, SWT.DROP_DOWN | SWT.READ_ONLY);
            dsDoubleClickBehavior.add(UINavigatorMessages.pref_page_database_general_label_double_click_connection_open_properties, NavigatorPreferences.DoubleClickBehavior.EDIT.ordinal());
            dsDoubleClickBehavior.add(UINavigatorMessages.pref_page_database_general_label_double_click_connection_conn_disconn, NavigatorPreferences.DoubleClickBehavior.CONNECT.ordinal());
            dsDoubleClickBehavior.add(UINavigatorMessages.pref_page_database_general_label_double_click_connection_open_sqleditor, NavigatorPreferences.DoubleClickBehavior.SQL_EDITOR.ordinal());
            dsDoubleClickBehavior.add(UINavigatorMessages.pref_page_database_general_label_double_click_connection_expand_collapse, NavigatorPreferences.DoubleClickBehavior.EXPAND.ordinal());
            dsDoubleClickBehavior.add(UINavigatorMessages.pref_page_database_general_label_double_click_connection_open_new_sqleditor, NavigatorPreferences.DoubleClickBehavior.SQL_EDITOR_NEW.ordinal());

            defaultEditorPageCombo = UIUtils.createLabelCombo(behaviorGroup, UINavigatorMessages.pref_page_navigator_default_editor_page_label, UINavigatorMessages.pref_page_navigator_default_editor_page_tip, SWT.DROP_DOWN | SWT.READ_ONLY);
        }

        {
            Group miscGroup = UIUtils.createControlGroup(composite, UINavigatorMessages.pref_page_database_navigator_group_misc, 2, GridData.VERTICAL_ALIGN_BEGINNING, 0);

            expandOnConnectCheck = UIUtils.createCheckbox(miscGroup, UINavigatorMessages.pref_page_database_general_label_expand_navigator_tree, "", false, 2);
            restoreFilterCheck = UIUtils.createCheckbox(miscGroup, UINavigatorMessages.pref_page_database_general_label_restore_filter, UINavigatorMessages.pref_page_database_general_label_restore_filter_tip, false, 2);

            longListFetchSizeText = UIUtils.createLabelText(miscGroup, UINavigatorMessages.pref_page_database_general_label_long_list_fetch_size, "", SWT.BORDER);
            longListFetchSizeText.setToolTipText(UINavigatorMessages.pref_page_database_general_label_long_list_fetch_size_tip);
            longListFetchSizeText.addVerifyListener(UIUtils.getIntegerVerifyListener(Locale.getDefault()));

            restoreStateDepthText = UIUtils.createLabelText(miscGroup, UINavigatorMessages.pref_page_database_general_label_restore_state_depth, "", SWT.BORDER);
            restoreStateDepthText.setToolTipText(UINavigatorMessages.pref_page_database_general_label_restore_state_depth_tip);
            restoreStateDepthText.addVerifyListener(UIUtils.getIntegerVerifyListener(Locale.getDefault()));
        }

        performDefaults();

        return composite;
    }

    @Override
    protected void performDefaults()
    {
        DBPPreferenceStore store = DBWorkbench.getPlatform().getPreferenceStore();

        expandOnConnectCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_EXPAND_ON_CONNECT));
        restoreFilterCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_RESTORE_FILTER));
        restoreStateDepthText.setText(store.getString(NavigatorPreferences.NAVIGATOR_RESTORE_STATE_DEPTH));
        showObjectTipsCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_SHOW_OBJECT_TIPS));
        showToolTipsCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_SHOW_TOOLTIPS));
        showContentsInToolTipsContents.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_SHOW_CONTENTS_IN_TOOLTIP));
        sortCaseInsensitiveCheck.setSelection(store.getBoolean(ModelPreferences.NAVIGATOR_SORT_ALPHABETICALLY));
        sortFoldersFirstCheck.setSelection(store.getBoolean(ModelPreferences.NAVIGATOR_SORT_FOLDERS_FIRST));
        showConnectionHostCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_SHOW_CONNECTION_HOST_NAME));
        showObjectsDescriptionCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_SHOW_OBJECTS_DESCRIPTION));
        showStatisticsCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_SHOW_STATISTICS_INFO));
        showNodeActionsCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_SHOW_NODE_ACTIONS));
        colorAllNodesCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_COLOR_ALL_NODES));
        showResourceFolderPlaceholdersCheck.setSelection(store.getBoolean(ModelPreferences.NAVIGATOR_SHOW_FOLDER_PLACEHOLDERS));
        groupByDriverCheck.setSelection(store.getBoolean(NavigatorPreferences.NAVIGATOR_GROUP_BY_DRIVER));
        longListFetchSizeText.setText(store.getString(NavigatorPreferences.NAVIGATOR_LONG_LIST_FETCH_SIZE));
        NavigatorPreferences.DoubleClickBehavior objDCB = CommonUtils.valueOf(NavigatorPreferences.DoubleClickBehavior.class, store.getString(NavigatorPreferences.NAVIGATOR_OBJECT_DOUBLE_CLICK));
        objDoubleClickBehavior.select(objDCB == NavigatorPreferences.DoubleClickBehavior.EXPAND ? 1 : 0);
        dsDoubleClickBehavior.select(
            CommonUtils.valueOf(
                NavigatorPreferences.DoubleClickBehavior.class,
                store.getString(NavigatorPreferences.NAVIGATOR_CONNECTION_DOUBLE_CLICK),
                NavigatorPreferences.DoubleClickBehavior.EDIT)
                .ordinal());

        String defEditorPage = store.getString(NavigatorPreferences.NAVIGATOR_DEFAULT_EDITOR_PAGE);
        List<EntityEditorDescriptor> entityEditors = getAvailableEditorPages();
        defaultEditorPageCombo.removeAll();
        defaultEditorPageCombo.add(UINavigatorMessages.pref_page_navigator_default_editor_page_last);
        defaultEditorPageCombo.select(0);
        for (EntityEditorDescriptor eed : entityEditors) {
            defaultEditorPageCombo.add(eed.getName());
            if (eed.getId().equals(defEditorPage)) {
                defaultEditorPageCombo.select(defaultEditorPageCombo.getItemCount() - 1);
            }
        }
    }

    @Override
    public boolean performOk()
    {
        DBPPreferenceStore store = DBWorkbench.getPlatform().getPreferenceStore();

        store.setValue(NavigatorPreferences.NAVIGATOR_EXPAND_ON_CONNECT, expandOnConnectCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_RESTORE_FILTER, restoreFilterCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_RESTORE_STATE_DEPTH, restoreStateDepthText.getText());
        store.setValue(NavigatorPreferences.NAVIGATOR_SHOW_OBJECT_TIPS, showObjectTipsCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_SHOW_TOOLTIPS, showToolTipsCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_SHOW_CONTENTS_IN_TOOLTIP, showContentsInToolTipsContents.getSelection());
        store.setValue(ModelPreferences.NAVIGATOR_SORT_ALPHABETICALLY, sortCaseInsensitiveCheck.getSelection());
        store.setValue(ModelPreferences.NAVIGATOR_SORT_FOLDERS_FIRST, sortFoldersFirstCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_SHOW_CONNECTION_HOST_NAME, showConnectionHostCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_SHOW_OBJECTS_DESCRIPTION, showObjectsDescriptionCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_SHOW_STATISTICS_INFO, showStatisticsCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_SHOW_NODE_ACTIONS, showNodeActionsCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_COLOR_ALL_NODES, colorAllNodesCheck.getSelection());
        store.setValue(ModelPreferences.NAVIGATOR_SHOW_FOLDER_PLACEHOLDERS, showResourceFolderPlaceholdersCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_GROUP_BY_DRIVER, groupByDriverCheck.getSelection());
        store.setValue(NavigatorPreferences.NAVIGATOR_LONG_LIST_FETCH_SIZE, longListFetchSizeText.getText());
        NavigatorPreferences.DoubleClickBehavior objDCB = NavigatorPreferences.DoubleClickBehavior.EXPAND;
        if (objDoubleClickBehavior.getSelectionIndex() == 0) {
            objDCB = NavigatorPreferences.DoubleClickBehavior.EDIT;
        }
        store.setValue(NavigatorPreferences.NAVIGATOR_OBJECT_DOUBLE_CLICK, objDCB.name());
        store.setValue(NavigatorPreferences.NAVIGATOR_CONNECTION_DOUBLE_CLICK,
            CommonUtils.fromOrdinal(NavigatorPreferences.DoubleClickBehavior.class, dsDoubleClickBehavior.getSelectionIndex()).name());

        List<EntityEditorDescriptor> entityEditors = getAvailableEditorPages();
        int defEditorIndex = defaultEditorPageCombo.getSelectionIndex();
        store.setValue(NavigatorPreferences.NAVIGATOR_DEFAULT_EDITOR_PAGE, defEditorIndex <= 0 ? "" : entityEditors.get(defEditorIndex - 1).getId());

        PrefUtils.savePreferenceStore(store);

        return true;
    }

    private List<EntityEditorDescriptor> getAvailableEditorPages() {
        final EntityEditorsRegistry editorsRegistry = EntityEditorsRegistry.getInstance();
        final List<EntityEditorDescriptor> editors = new ArrayList<>(editorsRegistry.getEntityEditors());
        editors.removeIf(editor -> {
            if (editor.getType() != EntityEditorDescriptor.Type.editor) return true;
            for (AbstractDescriptor.ObjectType ot : editor.getObjectTypes()) {
                if (!DBSDataContainer.class.getName().equals(ot.getImplName()) &&
                    !DBSObjectContainer.class.getName().equals(ot.getImplName()) &&
                    !DBSEntity.class.getName().equals(ot.getImplName()) &&
                    !DBSTable.class.getName().equals(ot.getImplName()))
                {
                    return true;
                }
            }
            return false;
        });
        editors.sort(Comparator.comparing(editor -> {
            switch (editor.getPosition()) {
                case EntityEditorDescriptor.POSITION_PROPS:
                    return -2;
                case EntityEditorDescriptor.POSITION_START:
                    return -1;
                case EntityEditorDescriptor.POSITION_END:
                    return 1;
                default:
                    return 0;
            }
        }));
        editors.add(0, editorsRegistry.getDefaultEditor());
        return editors;
    }

    @Override
    public void applyData(Object data)
    {
        super.applyData(data);
    }

    @Nullable
    @Override
    public IAdaptable getElement()
    {
        return null;
    }

    @Override
    public void setElement(IAdaptable element)
    {
    }

}


text:
module Billimatic
  module Resources
    class Person < Base
      crud :list, :show, :create, :update, :destroy

      def initialize(http)
        @collection_name = 'people'
        super http
      end

      def search(cpf:)
        http.get("#{resource_base_path}/search", params: { cpf: cpf }) do |response|
          respond_with_collection response
        end
      end
    end
  end
end