text:
package io.github.binaryfoo.tlv;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;

public class BerTlvTest {

  @Test
  public void testNewInstanceWithByteFlagThatIsTooBig() {
    try {
      BerTlv.newInstance(Tag.fromHex("9A"), 256);
      fail();
    } catch (IllegalArgumentException ignored) {
    }
  }

  @Test
  public void testNewInstanceWithByteFlag255() {
    BerTlvUtils.assertEquals("9A01FF", BerTlv.newInstance(Tag.fromHex("9A"), 255).toBinary());
  }

  @Test
  public void testNewInstanceWithHexString05() {
    BerTlvUtils.assertEquals("9A0105", BerTlv.newInstance(Tag.fromHex("9A"), "05").toBinary());
  }

  @Test
  public void testToBinary_ValueLengthLessThan127() {
    Tag tag = new Tag(new byte[]{(byte) 0x9F, (byte) 0x1A}, true);
    BerTlv tlv = BerTlv.newInstance(tag, new byte[]{0x01, 0x02, 0x03, 0x04});
    BerTlvUtils.assertEquals("9F1A0401020304", tlv.toBinary());
  }

  @Test
  public void testToBinary_ValueLength128() {
    Tag tag = new Tag(new byte[]{(byte) 0x9F, (byte) 0x1A}, true);
    BerTlv tlv = BerTlv.newInstance(tag, new byte[128]);
    BerTlvUtils.assertEquals("9F1A8180" + StringUtils.repeat("00", 128), tlv.toBinary());
  }

  @Test
  public void testToBinary_2Primitives() {
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("9A"), new byte[]{(byte) 1});
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("9F1A"), new byte[]{(byte) 3});
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("EF"), Arrays.asList(tlv1, tlv2));

    byte[] tlv1Bytes = tlv1.toBinary();
    byte[] tlv2Bytes = tlv2.toBinary();

    BerTlvUtils.assertEquals("EF" + "07" + ISOUtil.hexString(tlv1Bytes) + ISOUtil.hexString(tlv2Bytes), tlv.toBinary());
  }

  @Test
  public void testToBinary_1PrimitiveAnd1Constructed() {
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("9A"), new byte[]{(byte) 1});
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("EF"), Arrays.asList(BerTlv.newInstance(Tag.fromHex("9F1A"), new byte[]{(byte) 3})));
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("E0"), Arrays.asList(tlv1, tlv2));

    byte[] tlv1Bytes = tlv1.toBinary();
    byte[] tlv2Bytes = tlv2.toBinary();

    BerTlvUtils.assertEquals("E0" + "09" + ISOUtil.hexString(tlv1Bytes) + ISOUtil.hexString(tlv2Bytes), tlv.toBinary());
  }

  @Test
  public void testToHexString_Primitive() {
    assertEquals("E1021234", BerTlv.newInstance(Tag.fromHex("E1"), "1234").toHexString());
  }

  @Test
  public void testGetChildrenPrimitive() {
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("E1"), "1234");
    assertEquals(0, tlv.getChildren().size());
  }

  @Test
  public void testFindTlvConstructed() {
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("9A"), 1);
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("9F1A"), 3);
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("EF"), Arrays.asList(tlv1, tlv2));
    assertSame(tlv1, tlv.findTlv(Tag.fromHex("9A")));
    assertSame(tlv2, tlv.findTlv(Tag.fromHex("9F1A")));
    assertNull(tlv.findTlv(Tag.fromHex("00")));
  }

  @Test
  public void testGetChildrenConstructed() {
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("9A"), 1);
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("9F1A"), 3);
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("EF"), Arrays.asList(tlv1, tlv2));
    List<BerTlv> children = tlv.getChildren();
    assertEquals(2, children.size());
    assertEquals(tlv1, children.get(0));
    assertEquals(tlv2, children.get(1));
  }

  @Test
  public void testFindTlvsConstructed() {
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("9A"), 1);
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("9A"), 3);
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("01"), Arrays.asList(tlv1, tlv2));
    List<BerTlv> matches = tlv.findTlvs(Tag.fromHex("9A"));
    assertEquals(2, matches.size());
    assertSame(tlv1, matches.get(0));
    assertSame(tlv2, matches.get(1));
    assertTrue(tlv.findTlvs(Tag.fromHex("00")).isEmpty());
  }

  @Test
  public void testFindTlvPrimitive() {
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("9A"), 1);
    assertNull(tlv.findTlv(Tag.fromHex("9A")));
  }

  @Test
  public void testParsePrimitive() {
    Tag tag = new Tag(new byte[]{(byte) 0x9F, (byte) 0x1A}, true);
    BerTlv expectedTlv = BerTlv.newInstance(tag, new byte[]{0x01, 0x02, 0x03, 0x04});
    BerTlv actualTlv = BerTlv.parse(ISOUtil.hex2byte("9F1A0401020304"));
    BerTlvUtils.assertEquals(expectedTlv.toBinary(), actualTlv.toBinary());
  }

  @Test
  public void testParsePrimitive_Length128() {
    Tag tag = new Tag(new byte[]{(byte) 0x9F, (byte) 0x1A}, true);
    BerTlv expectedTlv = BerTlv.newInstance(tag, new byte[128]);
    BerTlv actualTlv = BerTlv.parse(ISOUtil.hex2byte("9F1A8180" + StringUtils.repeat("00", 128)));
    BerTlvUtils.assertEquals(expectedTlv.toBinary(), actualTlv.toBinary());
  }

  @Test
  public void testParsePrimitive_Length255() {
    Tag tag = new Tag(new byte[]{(byte) 0x9F, (byte) 0x1A}, true);
    BerTlv expectedTlv = BerTlv.newInstance(tag, new byte[255]);
    BerTlv actualTlv = BerTlv.parse(ISOUtil.hex2byte("9F1A81FF" + StringUtils.repeat("00", 255)));
    BerTlvUtils.assertEquals(expectedTlv.toBinary(), actualTlv.toBinary());
  }

  @Test
  public void testParsePrimitive_Length314() {
    Tag tag = new Tag(new byte[]{(byte) 0x9F, (byte) 0x1A}, true);
    BerTlv expectedTlv = BerTlv.newInstance(tag, new byte[314]);
    BerTlv actualTlv = BerTlv.parse(ISOUtil.hex2byte("9F1A82013A" + StringUtils.repeat("00", 314)));
    BerTlvUtils.assertEquals(expectedTlv.toBinary(), actualTlv.toBinary());
  }

  @Test
  public void testParseConstructed_2Primitives() {
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("9A"), 1);
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("9F1A"), 3);
    BerTlv expectedTlv = BerTlv.newInstance(Tag.fromHex("EF"), tlv1, tlv2);

    BerTlv actualTlv = BerTlv.parse(ISOUtil.hex2byte("EF" + "07" + "9A0101" + "9F1A0103"));
    BerTlvUtils.assertEquals(expectedTlv.toBinary(), actualTlv.toBinary());

    BerTlvUtils.assertEquals(tlv1.toBinary(), actualTlv.findTlv(Tag.fromHex("9A")).toBinary());
  }

  @Test
  public void testParseConstructed_1PrimitiveAnd2Constructed() {
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("9A"), 1);
    BerTlv nestedTag1 = BerTlv.newInstance(Tag.fromHex("9F1A"), 3);
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("EF"), Arrays.asList(nestedTag1));
    BerTlv nestedTag2 = BerTlv.newInstance(Tag.fromHex("8A"), "CC");
    BerTlv tlv3 = BerTlv.newInstance(Tag.fromHex("EF"), Arrays.asList(nestedTag2));
    BerTlv expectedTlv = BerTlv.newInstance(Tag.fromHex("E0"), Arrays.asList(tlv1, tlv2, tlv3));

    BerTlv actualTlv = BerTlv.parse(ISOUtil.hex2byte("E0" + "0E" + "9A0101" + "EF049F1A0103" + "EF038A01CC"));
    BerTlvUtils.assertEquals(expectedTlv.toBinary(), actualTlv.toBinary());
    List<BerTlv> actualEFTlvs = actualTlv.findTlvs(Tag.fromHex("EF"));
    assertEquals(2, actualEFTlvs.size());
    BerTlv actualEFTlv1 = actualEFTlvs.get(0);
    BerTlv actualEFTlv2 = actualEFTlvs.get(1);
    BerTlvUtils.assertEquals(tlv2.toBinary(), actualEFTlv1.toBinary());
    BerTlvUtils.assertEquals(nestedTag1.toBinary(), actualEFTlv1.findTlv(Tag.fromHex("9F1A")).toBinary());
    BerTlvUtils.assertEquals(tlv3.toBinary(), actualEFTlv2.toBinary());
    BerTlvUtils.assertEquals(nestedTag2.toBinary(), actualEFTlv2.findTlv(Tag.fromHex("8A")).toBinary());
  }

  @Test
  public void testParseConstructed_1ConstructedAnd1Primitive() {
    BerTlv nestedTag = BerTlv.newInstance(Tag.fromHex("9F1A"), 3);
    BerTlv tlv1 = BerTlv.newInstance(Tag.fromHex("EF"), Arrays.asList(nestedTag));
    BerTlv tlv2 = BerTlv.newInstance(Tag.fromHex("9A"), 1);
    BerTlv expectedTlv = BerTlv.newInstance(Tag.fromHex("E0"), Arrays.asList(tlv1, tlv2));

    BerTlv actualTlv = BerTlv.parse(ISOUtil.hex2byte("E0" + "09" + "EF049F1A0103" + "9A0101"));
    BerTlvUtils.assertEquals(expectedTlv.toBinary(), actualTlv.toBinary());
    List<BerTlv> actualEFTlvs = actualTlv.findTlvs(Tag.fromHex("EF"));
    assertEquals(1, actualEFTlvs.size());
    BerTlv actualEFTlv = actualTlv.findTlv(Tag.fromHex("EF"));
    BerTlvUtils.assertEquals(tlv1.toBinary(), actualEFTlv.toBinary());
    BerTlvUtils.assertEquals(nestedTag.toBinary(), actualEFTlv.findTlv(Tag.fromHex("9F1A")).toBinary());

    BerTlv actual9ATlv = actualTlv.findTlv(Tag.fromHex("9A"));
    BerTlvUtils.assertEquals(tlv2.toBinary(), actual9ATlv.toBinary());
  }

  @Test
  public void testParseAsPrimitive() {
    BerTlv tlv = BerTlv.parseAsPrimitiveTag(ISOUtil.hex2byte("E181039F5301"));
    assertEquals(Tag.fromHex("E1"), tlv.getTag());
    assertEquals("9F5301", tlv.getValueAsHexString());
    assertTrue(tlv instanceof PrimitiveBerTlv);
  }

  @Test
  public void testGetValueAsHexString() {
    BerTlv tlv = BerTlv.newInstance(Tag.fromHex("9A"), new byte[]{1, 2, (byte) 0xFF});
    assertEquals("0102FF", tlv.getValueAsHexString());
  }

  @Test
  public void testGetLengthInBytesOfEncodedLength() {
    assertEquals(1, BerTlv.newInstance(Tag.fromHex("9A"), "FF").getLengthInBytesOfEncodedLength());
    assertEquals(2, BerTlv.newInstance(Tag.fromHex("9A"), StringUtils.repeat("A", 400)).getLengthInBytesOfEncodedLength());
    assertEquals(3, BerTlv.newInstance(Tag.fromHex("9A"), StringUtils.repeat("A", 4000)).getLengthInBytesOfEncodedLength());
  }

  @Test
  public void testGetStartIndexOfValue() {
    assertEquals(2, BerTlv.newInstance(Tag.fromHex("9A"), "FF").getStartIndexOfValue());
    assertEquals(3, BerTlv.newInstance(Tag.fromHex("9A"), StringUtils.repeat("A", 400)).getStartIndexOfValue());
    assertEquals(5, BerTlv.newInstance(Tag.fromHex("9F1B"), StringUtils.repeat("A", 4000)).getStartIndexOfValue());
  }

  @Test
  public void testHandlesZeroPadding() {
    String crap = "910A93D60A0F3CC53834303072459F180400004000860E04DA9F5809004B360CA0FF728F689F180400004000860E04DA9F580904B50F23328A5C788500000000000000000000000000000000000000000000";

    List<BerTlv> tlv = BerTlv.parseList(ISOUtil.hex2byte(crap), true);
    assertThat(tlv.get(1).getChildren().size(), is(4));
  }

  @Test
  public void detailInExceptionForInsufficientBytes() {
    try {
      BerTlv.parse(ISOUtil.hex2byte("918211"));
      fail();
    } catch (TlvParseException e) {
      assertThat(e.getMessage(), is("Failed parsing TLV with tag 91: Bad length: expected to read 2 (0x82) bytes. Only have 1."));
    }
  }

  @Test
  public void withNonStandardTag() {
    List<BerTlv> parsed = BerTlv.parseList(ISOUtil.hex2byte("9F84101C9291EA7DB1EA276A8C96999DF512A6"), true, new QuirkListTagMode(Collections.singleton("9F84")));
    assertThat(parsed.get(0).getTag().getHexString(), is("9F84"));
    assertThat(parsed.get(0).getValueAsHexString(), is("1C9291EA7DB1EA276A8C96999DF512A6"));
  }

  @Test
  public void lengthWith0x80EncodedInSingleByte() {
    String example = "709157134761739001010119D22122011143804400000F5F201A5541542041544D2F5465737420436172642030352020202020205F300202019F1F183131343338303434303030303030303030303030303030309F080200969F4401028C159F02069F03069F1A0295055F2A029A039C019F37048D178A029F02069F03069F1A0295055F2A029A039C019F37049F49039F3704";
    List<BerTlv> tlvs = BerTlv.parseList(ISOUtil.hex2byte(example), true);
    assertEquals(1, tlvs.size());
    assertEquals(9, tlvs.get(0).getChildren().size());
  }
}


text:
const HINTS_LIST = `Make sure there's clear space to get to your chairs!
There's no point in a bed you can't get into!
Paintings are pretty!
A chair is a table's best friend!
Check out all the pages of items!
Make sure there's a door to get in!
Press the green button in the bottom left to hide these messages
Wide objects come in two parts!
What home doesn't need an anvil?`.split('\n');

class Hints {
    hintText: Phaser.Text;
    removeTimer: number = 0;
    makeTimer: number = 0;
    enabled: boolean = true;

    constructor(private game: Phaser.Game) {
        this.makeTimer = setTimeout(this.makeHint.bind(this), 15000)
    }

    makeHint() {
        let text = HINTS_LIST[Math.floor(Math.random() * HINTS_LIST.length)];
        this.hintText = this.game.add.text(0, 0, text, HINT_TEXT_STYLE);
        this.hintText.setTextBounds(0, 0, 160, 160);
        this.removeTimer = setTimeout(this.removeHint.bind(this), 5000);
        this.makeTimer = setTimeout(this.makeHint.bind(this), 45000);
    }

    removeHint() {
        this.hintText.destroy();
    }

    toggle() {
        if (this.enabled) {
            if (this.hintText) this.hintText.destroy();
            clearTimeout(this.makeTimer);
            clearInterval(this.removeTimer);
            this.enabled = false;
            let text = "Hints disabled!";
            this.hintText = this.game.add.text(0, 0, text, HINT_TEXT_STYLE);
            this.hintText.setTextBounds(0, 0, 160, 160);
            this.removeTimer = setTimeout(this.removeHint.bind(this), 3000);

        } else {
            if (this.hintText) this.hintText.destroy();
            clearTimeout(this.makeTimer);
            clearInterval(this.removeTimer);
            this.makeHint();
            this.enabled = true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

$lang['required'] 			= "El campo %s es obligatorio.";
$lang['isset']				= "El campo %s debe contener un valor.";
$lang['valid_email']		= "El campo %s debe contener una dirección de email válida.";
$lang['valid_emails'] 		= "El campo %s debe contener todas las direcciones de email válidas.";
$lang['valid_url'] 			= "El campo %s debe contener una URL válida.";
$lang['valid_ip'] 			= "El campo %s debe contener una IP válida.";
$lang['min_length']			= "El campo %s debe tener al menos %s caracteres de longitud.";
$lang['max_length']			= "El campo %s no puede exceder los %s caracteres de longitud.";
$lang['exact_length']		= "El campo %s debe tener exactamente %s caracteres de longitud.";
$lang['alpha']				= "El campo %s debe contener sólo caracteres alfabéticos.";
$lang['alpha_numeric']		= "El campo %s debe contener sólo caracteres alfa-numéricos.";
$lang['alpha_dash']			= "El campo %s debe contener sólo caracteres alfa-numéricos, guiones bajos y guiones.";
$lang['numeric']			= "El campo %s debe contener sólo números.";
$lang['is_numeric']			= "El campo %s debe contener sólo caracteres numéricos.";
$lang['integer']			= "El campo %s debe contener un número entero.";
$lang['matches']			= "El campo %s no coincide con el campo %s.";
$lang['is_natural']			= "El campo %s debe contener sólo múmeros positivos.";
$lang['is_natural_no_zero']	= "El campo %s debe contener un número mayor que cero.";
$lang['is_unique'] 			= "El %s ya se encuentra registrado. Escoja otro.";
$lang['decimal']			= "El campo %s debe contener un número decimal.";
$lang['less_than']			= "El campo %s debe contener un número menor que %s.";
$lang['greater_than']		= "El campo %s debe contener un número mayor que %s.";
$lang['is_string']			= "El campo %s debe estar en formato de texto.";
$lang['is_array']			= "El campo %s debe estar en formato múltiple.";
$lang['existe_pk']			= "%s inválido.";
$lang['existe_fk']			= "El item seleccionado en %s no existe.";
$lang['valida_array_media']	= "El campo %s debe contener un valor.";
$lang['valida_files_media']	= "El campo %s debe contener un archivo seleccionado.";
$lang['existe_slug']		= "El campo %s debe ser único";
$lang['esRut']		= "El %s ingresado no es válido";
$lang['valida_cadena'] ="El campo %s debe contener sólo texto";
$lang['valida_url'] ="El campo %s debe contener una URL válida. Debe tener el formato http://www.tudominio.com";
$lang['validaSelect'] ="Debe seleccionar una opción en el campo %s";

/* End of file form_validation_lang.php */
/* Location: ./system/language/spanish/form_validation_lang.php */


text:
package VC6ProjectCreator;

# ************************************************************
# Description   : A VC6 Project Creator
# Author        : Chad Elliott
# Create Date   : 3/14/2002
# $Id: VC6ProjectCreator.pm 2035 2011-10-06 15:05:21Z johnnyw $
# ************************************************************

# ************************************************************
# Pragmas
# ************************************************************

use strict;

use ProjectCreator;
use VCProjectBase;

use vars qw(@ISA);
@ISA = qw(VCProjectBase ProjectCreator);

# ************************************************************
# Subroutine Section
# ************************************************************

sub project_file_extension {
  #my $self = shift;
  return '.dsp';
}

sub override_valid_component_extensions {
  my($self, $comp) = @_;

  ## Visual C++ 6.0 doesn't understand all of the extensions that MPC
  ## supports.
  if ($comp eq 'source_files' && $self->languageIs(Creator::cplusplus)) {
    return ["\\.cpp", "\\.cxx", "\\.c"];
  }

  return undef;
}

sub override_exclude_component_extensions {
  my($self, $comp) = @_;

  ## Visual C++ 6.0 doesn't understand all of the extensions that MPC
  ## supports.
  if ($comp eq 'source_files' && $self->languageIs(Creator::cplusplus)) {
    return ["_T\\.cpp", "_T\\.cxx"];
  }

  return undef;
}

sub get_dll_exe_template_input_file {
  #my $self = shift;
  return 'vc6dspdllexe';
}

sub get_lib_exe_template_input_file {
  #my $self = shift;
  return 'vc6dsplibexe';
}

sub get_lib_template_input_file {
  #my $self = shift;
  return 'vc6dsplib';
}

sub get_dll_template_input_file {
  #my $self = shift;
  return 'vc6dspdll';
}

1;


text:
package org.helianto.task.def;

/**
 * Define authority types.
 *
 * @author Mauricio Fernandes de Castro
 */
public enum AuthorityType {

    INTERNAL('I'),
    GOVERNAMENTAL('G'),
    NORMATIVE('N'),
    CERTIFICATION('C'),
    PRIVATE('P');

    private char value;

    private AuthorityType(char value) {
        this.value = value;
    }

    public char getValue() {
        return value;
    }

}


text:
/**
 * The LoadMoreComponent lets you load more documents through a button.
 *
 * @type {LoadMoreComponent}
 */
EasySearch.LoadMoreComponent = class LoadMoreComponent extends SingleIndexComponent {
  /**
   * Load more documents.
   */
  loadMore() {
    this.index
      .getComponentMethods(this.name)
      .loadMore(this.options.count)
    ;
  }

  /**
   * Content of the component.
   *
   * @returns string
   */
  content() {
    return this.options.content;
  }

  /**
   * Attributes of the component.
   *
   * @returns string
   */
  attributes() {
    return this.getData().attributes || {};
  }

  /**
   * Return true if there are more documents to load.
   *
   * @returns {Boolean}
   */
  moreDocuments() {
    return this.index.getComponentMethods(this.name).hasMoreDocuments();
  }

  /**
   * Event map.
   *
   * @returns {Object}
   */
  events() {
    return [{
      'click button' : function () {
        this.loadMore();
      }
    }];
  }

  /**
   * Return the default options.
   *
   * @returns {Object}
   */
  get defaultOptions() {
    return {
      content: 'Load more',
      count: 10
    };
  }
};

EasySearch.LoadMoreComponent.register('EasySearch.LoadMore');


text:
require "json"
require "rspec/core"

class RSpec::Core::ExampleGroup
  def self.generate_fixture(file_path, hash={}, &block)
    describe "JSON fixture generation", hash.merge(:fixture => true) do
      it "generates a fixture for #{file_path}" do
        instance_exec(&block)
        save_fixture file_path
      end
    end
  end

  def save_fixture(filename, content = JSON.parse(response.body))
    path = Rails.root + "spec/javascripts/fixtures/backbone/" + filename
    path.dirname.mkpath unless path.dirname.directory?

    File.open(path, 'w') do |f|
      f.write JSON.pretty_generate(content.as_json)
    end
  end
end


text:
namespace {
int kUserDataKey;  // The value is not important, the address is a key.
}

// static
TabDialogs* TabDialogs::FromWebContents(content::WebContents* contents) {
  DCHECK(contents);
  return static_cast<TabDialogs*>(contents->GetUserData(UserDataKey()));
}

// static
const void* TabDialogs::UserDataKey() {
  return &kUserDataKey;
}


text:
namespace chrono {
namespace vehicle {

/// @addtogroup vehicle_driver
/// @{

/// Driver inputs from data file.
/// A driver model based on user inputs provided as time series. If provided as a
/// text file, each line in the file must contain 4 values:
///   time steering throttle braking
/// It is assumed that the time values are unique.
/// If the time values are not sorted, this must be specified at construction.
/// Driver inputs at intermediate times are obtained through linear interpolation.
class CH_VEHICLE_API ChDataDriver : public ChDriver {
  public:
    /// Definition of driver inputs at a given time.
    struct Entry {
        Entry() {}
        Entry(double time, double steering, double throttle, double braking)
            : m_time(time), m_steering(steering), m_throttle(throttle), m_braking(braking) {}
        double m_time;
        double m_steering;
        double m_throttle;
        double m_braking;
    };

    /// Construct using data from the specified file.
    ChDataDriver(ChVehicle& vehicle,           ///< associated vehicle
                 const std::string& filename,  ///< name of data file
                 bool sorted = true            ///< indicate whether entries are sorted by time stamps
                 );

    /// Construct using data from the specified data entries.
    ChDataDriver(ChVehicle& vehicle,              ///< associated vehicle
                 const std::vector<Entry>& data,  ///< vector of data entries
                 bool sorted = true               ///< indicate whether entries are sorted by time stamps
                 );

    ~ChDataDriver() {}

    /// Update the driver system at the specified time.
    /// The driver inputs are obtained through linear interpolation between the
    /// provided data points.
    virtual void Synchronize(double time) override;

  private:
    static bool compare(const Entry& a, const Entry& b) { return a.m_time < b.m_time; }

    std::vector<Entry> m_data;
};

/// @} vehicle_driver

}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
package com.queues;

import junit.framework.TestCase;

public class RandomizedQueueTest extends TestCase {

	public void testRandomQueue() {

		//test empty queue
		RandomizedQueue<Integer> rq = new RandomizedQueue<Integer>();
		assertEquals(0, rq.size());
		assertEquals(true, rq.isEmpty());

		// test enqueue operation
		rq.enqueue(10);
		rq.enqueue(5);
		rq.enqueue(100);
		rq.enqueue(2);
		assertEquals(false, rq.isEmpty());
		assertEquals(4, rq.size());

		//test dequeue
		rq.dequeue();
		rq.dequeue();
		assertEquals(2, rq.size());

		// test sample
		rq.sample();
		rq.sample();
		assertEquals(2, rq.size());

		//test dequeue
		rq.dequeue();
		rq.dequeue();
		assertEquals(0, rq.size());
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>sentinel-cluster</artifactId>
        <groupId>com.alibaba.csp</groupId>
        <version>2.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sentinel-cluster-server-envoy-rls</artifactId>

    <properties>
        <java.source.version>1.8</java.source.version>
        <java.target.version>1.8</java.target.version>

        <protobuf.version>3.10.0</protobuf.version>
        <grpc.version>1.30.2</grpc.version>

        <maven.shade.version>3.2.1</maven.shade.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-cluster-server-default</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-extension</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>${javax.annotation-api.version}</version>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty</artifactId>
            <version>${grpc.version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>${grpc.version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>${grpc.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>${protobuf.version}</version>
        </dependency>

        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.32</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
                    </protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
                    </pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>${maven.pmd.version}</version>
                <configuration>
                    <excludeRoots>
                        <excludeRoot>target/generated-sources</excludeRoot>
                    </excludeRoots>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>prod</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-shade-plugin</artifactId>
                        <version>${maven.shade.version}</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>shade</goal>
                                </goals>
                                <configuration>
                                    <finalName>sentinel-envoy-rls-token-server</finalName>
                                    <transformers>
                                        <transformer
                                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                            <mainClass>
                                                com.alibaba.csp.sentinel.cluster.server.envoy.rls.SentinelEnvoyRlsServer
                                            </mainClass>
                                        </transformer>
                                        <transformer
                                                implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                    </transformers>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
package ca.etsmtl.applets.etsmobile.model;

import ca.etsmtl.applets.etsmobile2.R;

/**
 * Created by Phil on 17/11/13.
 */
public class MyMenuItem {

	private boolean requiresLogin;
	public String title = "";
	public int resId = R.drawable.ic_launcher;
	public Class mClass = null;

	public MyMenuItem(String title, Class mClass) {
		this.title = title;
		this.mClass = mClass;
	}

	public MyMenuItem(String title, Class mClass, int resId, boolean requiresLogin) {
		this.title = title;
		this.mClass = mClass;
		this.resId = resId;
		this.requiresLogin = requiresLogin;
	}

	public boolean hasToBeLoggedOn() {
		return requiresLogin;
	}
}


text:
require.config({
    paths: {
        'jquery': '../../bower_components/jquery/dist/jquery',
        'text': '../../bower_components/requirejs-text/text',
        'require-css': '../../bower_components/require-css',
        'require-less': '../../bower_components/require-less',
        'base': '../../bower_components/larsthorup-base',
        'feed': '../assets'
    },
    map: {
        '*': {
            'css': 'require-css/css',
            'less': 'require-less/less'
        }
    },
    less: {
        logLevel: 1 // Note: only show errors
    }
});
require(['jquery', 'feed/js/feed'], function ($, feed) {
    feed.render($('#feed-container'));
});


text:
package brut.androlib.aapt1;

import brut.androlib.Androlib;
import brut.androlib.ApkDecoder;
import brut.androlib.ApkOptions;
import brut.androlib.TestUtils;
import brut.directory.ExtFile;
import brut.common.BrutException;
import brut.util.OS;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.File;
import java.util.logging.Logger;

import static org.junit.Assert.assertTrue;

/**
 * @author Connor Tumbleson <connor.tumbleson@gmail.com>
 */
public class EmptyResourcesArscTest {
    @BeforeClass
    public static void beforeClass() throws Exception {
        TestUtils.cleanFrameworkFile();
        sTmpDir = new ExtFile(OS.createTempDirectory());
        sTestOrigDir = new ExtFile(sTmpDir, "issue1730-orig");
        sTestNewDir = new ExtFile(sTmpDir, "issue1730-new");
        LOGGER.info("Unpacking issue1730.apk...");
        TestUtils.copyResourceDir(EmptyResourcesArscTest.class, "aapt1/issue1730", sTestOrigDir);

        File testApk = new File(sTestOrigDir, "issue1730.apk");

        LOGGER.info("Decoding issue1730.apk...");
        ApkDecoder apkDecoder = new ApkDecoder(testApk);
        apkDecoder.setOutDir(sTestNewDir);
        apkDecoder.decode();

        LOGGER.info("Building issue1730.apk...");
        ApkOptions apkOptions = new ApkOptions();
        new Androlib(apkOptions).build(sTestNewDir, testApk);
    }

    @AfterClass
    public static void afterClass() throws BrutException {
        OS.rmdir(sTmpDir);
    }

    @Test
    public void buildAndDecodeTest() {
        assertTrue(sTestNewDir.isDirectory());
        assertTrue(sTestOrigDir.isDirectory());
    }

    private static ExtFile sTmpDir;
    private static ExtFile sTestOrigDir;
    private static ExtFile sTestNewDir;

    private final static Logger LOGGER = Logger.getLogger(EmptyResourcesArscTest.class.getName());
}


text:
namespace baidu {
namespace squirrel {
namespace db {

class IndexDB {
public:
  virtual ~IndexDB() {}
  virtual StatusCode Put(const std::string& key, const std::string& value) = 0;
  virtual StatusCode Get(const std::string& key, std::string* value) = 0;
  virtual StatusCode Delete(const std::string& key) = 0;
};

} // namespace db
} // namespace squirrel
} // namespace baidu

#endif // SQUIRREL_INDEX_DB_H_


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Build.OverwriteDocuments
{
    using Markdig.Syntax;

    public interface IOverwriteBlockRule
    {
        string TokenName{ get; }

        bool Parse(Block block, out string value);
    }
}


text:
Wedeto (WEb DEvelopment TOolkit)

Application is the part of Wedeto that ties it al together. The Application
class will be the main component of a Wedeto web application, and it provides
access and management of database access, mail, internationalization, request
dispatching and response building.

# Requirements:

php >= 7.0

# License

Wedeto\Application is covered by the MIT license.


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Clark F. E. 1993. Rhaptohelenina papuanensis, a new genus and species of benthic foraminifer from the Recent of the Papuan Plateau and Alexa Bank. Journal of Paleontology 67(5): 899-901.

#### Original name
null

### Remarks
null


text:
package adv;

import java.io.IOException;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;

import simple.FastaReducer;

public class FastaAdvReducer extends Reducer<Text, Text, Text, Text> {

	private static Log LOG = LogFactory.getLog(FastaReducer.class);

	private static final String RESULTS_NAME = "/results";

	private MultipleOutputs<Text, Text> out;
	private FileSystem fs = null;

	@Override
	protected void cleanup(Context context) throws IOException,
			InterruptedException {
		super.cleanup(context);
		out.close();

	}

	@Override
	protected void setup(Context context) throws IOException,
			InterruptedException {
		super.setup(context);
		out = new MultipleOutputs<Text, Text>(context);
		fs = FileSystem.get(context.getConfiguration());
	}

	public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException
	{
		Configuration cfg = context.getConfiguration();
		String refName = cfg.get(FastaAdvancedJob.WORKING_FILE_NAME);
		String alignmentDir = FastaAdvancedJob.ALIGNMENTS_DIR + refName;
		Path path = new Path(alignmentDir + RESULTS_NAME);

		{
			FSDataOutputStream outStream = (!fs.exists(path)) ? fs.create(path, true) : fs.append(path);

			Iterator<Text> it = values.iterator();
			while (it.hasNext())
			{
				it.next().write(outStream);
			}

			outStream.close();
		}

		out.write(new Text(refName), new Text(path.toString()), cfg.get(FastaAdvancedJob.TARGET_CHECKSUM));
	}

}


text:
#include <boost/program_options.hpp>
#include "modules/perception/tool/benchmark/lidar/detection_evaluation.h"

int main(int argc, char** argv) {
  boost::program_options::options_description boost_desc("Allowed options");
  boost_desc.add_options()("help", "produce help message")(
      "cloud", boost::program_options::value<std::string>(),
      "provide the point cloud folder or list")(
      "result", boost::program_options::value<std::string>(),
      "provide the result folder or list")(
      "groundtruth", boost::program_options::value<std::string>(),
      "provide the groundtruth folder or list")(
      "is_folder", boost::program_options::value<bool>(),
      "provide folder or list")(
      "loading_thread_num",
      boost::program_options::value<unsigned int>()->default_value(4),
      "thread number for loading data")(
      "evaluation_thread_num",
      boost::program_options::value<unsigned int>()->default_value(4),
      "thread number for evaluation")(
      "parallel_processing_num",
      boost::program_options::value<unsigned int>()->default_value(4),
      "parallel processing number for each time")(
      "reserve",
      boost::program_options::value<std::string>()->default_value(""));

  boost::program_options::variables_map boost_args;
  boost::program_options::store(
      boost::program_options::parse_command_line(argc, argv, boost_desc),
      boost_args);
  boost::program_options::notify(boost_args);

  if (boost_args.count("help") || !boost_args.count("cloud") ||
      !boost_args.count("result") || !boost_args.count("groundtruth") ||
      !boost_args.count("is_folder")) {
    std::cout << boost_desc << std::endl;
    return 0;
  }

  const std::string cloud = boost_args["cloud"].as<std::string>();
  const std::string result = boost_args["result"].as<std::string>();
  const std::string groundtruth = boost_args["groundtruth"].as<std::string>();
  bool is_folder = boost_args["is_folder"].as<bool>();
  unsigned int loading_thread_num =
      boost_args["loading_thread_num"].as<unsigned int>();
  unsigned int evaluation_thread_num =
      boost_args["evaluation_thread_num"].as<unsigned int>();
  unsigned int parallel_processing_num =
      boost_args["parallel_processing_num"].as<unsigned int>();
  const std::string reserve = boost_args["reserve"].as<std::string>();

  apollo::perception::benchmark::DetectionEvaluation evaluator;
  evaluator.init(cloud, result, groundtruth, is_folder, loading_thread_num,
                 evaluation_thread_num, parallel_processing_num, reserve);

  evaluator.run_evaluation();

  std::cerr << evaluator << std::endl;

  return 0;
}


text:
package com.espirit.moddev.fstesttools.mocking;

import de.espirit.firstspirit.access.UserService;
import de.espirit.firstspirit.access.project.Project;
import de.espirit.firstspirit.access.schedule.ScheduleContext;
import de.espirit.firstspirit.access.schedule.ScheduleTask;

import java.io.Closeable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * The type Mocking schedule context.
 */
public class MockingScheduleContext extends MockingScriptContext implements ScheduleContext {

    private Map<String, Serializable> variables = new HashMap<>();
    private final UserService userService = getMock(UserService.class);
    private final Project project = getMock(Project.class);
    private boolean stateSuccess;
    private String comment;
    private Date startTime;
    private String path;
    private List<ScheduleTask> tasks = new ArrayList<>();
    private int taskIndex;
    private int fatalErrorCount;
    private int errorCount;
    private int warningCount;

    /**
     * Instantiates a new Mocking schedule context.
     *
     * @param supportedEnvironments the supported environments
     */
    public MockingScheduleContext(final Env... supportedEnvironments) {
        super(supportedEnvironments);
    }

    /**
     * Instantiates a new Mocking schedule context.
     *
     * @param locale                the locale
     * @param supportedEnvironments the supported environments
     */
    public MockingScheduleContext(final Locale locale, final Env... supportedEnvironments) {
        super(locale, supportedEnvironments);
    }

    /**
     * Instantiates a new Mocking schedule context.
     *
     * @param testLocale              the test locale
     * @param enableServiceBrokerFake the enable service broker fake
     * @param environment             the environment
     */
    public MockingScheduleContext(final Locale testLocale, final boolean enableServiceBrokerFake, final Env environment) {
        super(testLocale, enableServiceBrokerFake, environment);
    }

    @Override
    public ScheduleTask getTask() {
        return tasks.get(taskIndex);
    }

    @Override
    public int getTaskIndex() {
        return taskIndex;
    }

    @Override
    public List<? extends ScheduleTask> getTasks() {
        return Collections.unmodifiableList(tasks);
    }

    @Override
    public Project getProject() {
        return project;
    }

    @Override
    public UserService getUserService() {
        return userService;
    }

    @Override
    public String getPath() {
        return path;
    }

    @Override
    public Set<String> getVariableNames() {
        return variables.keySet();
    }

    @Override
    public Object getVariable(final String s) {
        return variables.get(s);
    }

    @Override
    public void setVariable(final String s, final Serializable serializable) {
        variables.put(s, serializable);
    }

    @Override
    public void removeVariable(final String s) {
        variables.remove(s);
    }

    @Override
    public int getFatalErrorCount() {
        return fatalErrorCount;
    }

    @Override
    public int getErrorCount() {
        return errorCount;
    }

    @Override
    public int getWarningCount() {
        return warningCount;
    }

    @Override
    public void setComment(final String s) {
        this.comment = s;
    }

    @Override
    public String getComment() {
        return comment;
    }

    @Override
    public void setStateToFailed() {
        stateSuccess = false;
    }

    @Override
    public void setStateToSuccess() {
        stateSuccess = true;
    }

    @Override
    public boolean isStateFailed() {
        return false;
    }

    @Override
    public boolean isStateSuccess() {
        return stateSuccess;
    }

    @Override
    public Date getStartTime() {
        return new Date(startTime.getTime());
    }

    @Override
    public void setStartTime(final Date date) {
        this.startTime = new Date(date.getTime());
    }

    @Override
    public void addCloseable(final Closeable closeable) {
        //keine ahnung was man hier implementieren soll...
    }

    /**
     * Sets warning count.
     *
     * @param warningCount the warning count
     */
    public void setWarningCount(final int warningCount) {
        this.warningCount = warningCount;
    }

    /**
     * Sets error count.
     *
     * @param errorCount the error count
     */
    public void setErrorCount(final int errorCount) {
        this.errorCount = errorCount;
    }

    /**
     * Sets fatal error count.
     *
     * @param fatalErrorCount the fatal error count
     */
    public void setFatalErrorCount(final int fatalErrorCount) {
        this.fatalErrorCount = fatalErrorCount;
    }

    /**
     * Sets task index.
     *
     * @param taskIndex the task index
     */
    public void setTaskIndex(final int taskIndex) {
        this.taskIndex = taskIndex;
    }

    /**
     * Sets path.
     *
     * @param path the path
     */
    public void setPath(final String path) {
        this.path = path;
    }

    /**
     * Add all tasks.
     *
     * @param scheduleTasks the scheduleTasks
     * @return the boolean
     */
    public boolean addAllTasks(final Collection<ScheduleTask> scheduleTasks) {
        return tasks.addAll(scheduleTasks);
    }

    /**
     * Add task.
     *
     * @param task the task
     * @return the boolean
     */
    public boolean addTask(final ScheduleTask task) {
        return tasks.add(task);
    }

    /**
     * Remove task.
     *
     * @param task the task
     * @return the boolean
     */
    public boolean removeTask(final ScheduleTask task) {
        return tasks.remove(task);
    }

    /**
     * Remove all tasks.
     *
     * @param scheduleTasks the scheduleTasks
     * @return the boolean
     */
    public boolean removeAllTasks(final Collection<ScheduleTask> scheduleTasks) {
        return tasks.removeAll(scheduleTasks);
    }
}


text:
package org.apache.sling.testing.junit.rules.category;

/**
 * Marker interface for the tests that fail independently of the Java version or other environment settings
 */
public interface FailingTest {
}


text:
package com.salesforce.dva.argus.service.tsdb;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.salesforce.dva.argus.service.metric.transform.Transform;
import com.salesforce.dva.argus.service.metric.transform.TransformFactory;
import com.salesforce.dva.argus.system.SystemAssert;
import com.salesforce.dva.argus.system.SystemException;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Encapsulates parameters used to drive a query of metric data.
 *
 * @author  Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com)
 */
@JsonInclude(Include.NON_NULL)
public class MetricQuery extends AnnotationQuery {

	//~ Instance fields ******************************************************************************************************************************

	private String _namespace;
	private Aggregator _aggregator;
	private Aggregator _downsampler;
	private Long _downsamplingPeriod;
	private MetricQueryContext _metricQueryContext;

	//~ Constructors *********************************************************************************************************************************

	/**
	 * Creates a new MetricQuery object by performing a shallow copy of the given MetricQuery object.
	 *
	 * @param  clone  The MetricQuery object to clone. Cannot be null.
	 */
	public MetricQuery(MetricQuery clone) {
		SystemAssert.requireArgument(clone != null, "The object to clone cannot be null.");
		_scope = clone.getScope();
		_metric = clone.getMetric();
		setTags(clone.getTags());
		setStartTimestamp(clone.getStartTimestamp());
		setEndTimestamp(clone.getEndTimestamp());
		setNamespace(clone.getNamespace());
		setAggregator(clone.getAggregator());
		setDownsampler(clone.getDownsampler());
		setDownsamplingPeriod(clone.getDownsamplingPeriod());
		setMetricQueryContext(clone.getMetricQueryContext());
	}

	/**
	 * Creates a new Metric Query object.
	 *
	 * @param  scope           The scope of the metric. Cannot be null or empty.
	 * @param  metric          The name of the metric. Cannot be null or empty.
	 * @param  tags            The tags associated with the metric. Can be null or empty.
	 * @param  startTimestamp  The start time stamp for the query. Cannot be null.
	 * @param  endTimestamp    The end time for the query. If null, defaults to the current system time.
	 */
	public MetricQuery(String scope, String metric, Map<String, String> tags, Long startTimestamp, Long endTimestamp) {
		super(scope, metric, tags, startTimestamp, endTimestamp);
		SystemAssert.requireArgument(metric != null, "Metric cannot be null");
	}

	/** Creates a new Metric object. */
	protected MetricQuery() {
		super();
	}

	//~ Methods **************************************************************************************************************************************

	/**
	 * Returns the namespace of the query.
	 *
	 * @return  The query namespace.  Can be null.
	 */
	public String getNamespace() {
		return _namespace;
	}

	/**
	 * Sets the query namespace.
	 *
	 * @param  namespace  The namespace.  May be null.
	 */
	public void setNamespace(String namespace) {
		_namespace = namespace;
	}

	/**
	 * Returns the method used to aggregate query results.
	 *
	 * @return  The aggregator method used.
	 */
	public Aggregator getAggregator() {
		return _aggregator;
	}

	/**
	 * Sets the method used to aggregate query results.
	 *
	 * @param  aggregator  The aggregator method to use.
	 */
	public void setAggregator(Aggregator aggregator) {
		_aggregator = aggregator;
	}

	/**
	 * Returns the method used to downsample query results.
	 *
	 * @return  The method used to downsample the query results.
	 */
	public Aggregator getDownsampler() {
		return _downsampler;
	}

	/**
	 * Sets the method used to downsample the query results.
	 *
	 * @param  downsampler  The method used to downsample the query results.
	 */
	public void setDownsampler(Aggregator downsampler) {
		_downsampler = downsampler;
	}

	/**
	 * Returns the time interval in milliseconds used to downsample the query results.
	 *
	 * @return  The downsample interval.
	 */
	public Long getDownsamplingPeriod() {
		return _downsamplingPeriod;
	}

	/**
	 * Sets the time interval in milliseconds used to downsample the query results.
	 *
	 * @param  downsamplingPeriod  The downsample interval.
	 */
	public void setDownsamplingPeriod(Long downsamplingPeriod) {
		_downsamplingPeriod = downsamplingPeriod;
	}

	/**
	 * Returns the context for this query
	 *
	 * @return  The context for query
	 */
	public MetricQueryContext getMetricQueryContext() {
		return _metricQueryContext;
	}

	/**
	 * Sets any extra context for this query
	 *
	 * @param  readEndPoint  The context for query
	 */
	public void setMetricQueryContext(MetricQueryContext metricQueryContext) {
		_metricQueryContext = metricQueryContext;
	}

	/**
	 * Returns the TSDB metric name.
	 *
	 * @return  The TSDB metric name.
	 */
	@JsonIgnore
	public String getTSDBMetricName() {
		StringBuilder sb = new StringBuilder();

		sb.append(getMetric()).append(DefaultTSDBService.DELIMITER).append(getScope());

		if (_namespace != null && !_namespace.isEmpty()) {
			sb.append(DefaultTSDBService.DELIMITER).append(getNamespace());
		}
		return sb.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();

		result = prime * result + ((_aggregator == null) ? 0 : _aggregator.hashCode());
		result = prime * result + ((_downsampler == null) ? 0 : _downsampler.hashCode());
		result = prime * result + ((_downsamplingPeriod == null) ? 0 : _downsamplingPeriod.hashCode());
		result = prime * result + ((_namespace == null) ? 0 : _namespace.hashCode());
		result = prime * result + ((_metricQueryContext == null) ? 0 : _metricQueryContext.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}

		MetricQuery other = (MetricQuery) obj;

		if (_aggregator != other._aggregator) {
			return false;
		}
		if (_downsampler != other._downsampler) {
			return false;
		}
		if (_downsamplingPeriod == null) {
			if (other._downsamplingPeriod != null) {
				return false;
			}
		} else if (!_downsamplingPeriod.equals(other._downsamplingPeriod)) {
			return false;
		}
		if (_namespace == null) {
			if (other._namespace != null) {
				return false;
			}
		} else if (!_namespace.equals(other._namespace)) {
			return false;
		} else if (!_metricQueryContext.equals(other._metricQueryContext)) {
			return false;
		}
		return true;
	}

	/**
	 * Returns the TSDB formatted representation of the query.
	 * @todo This is implementation specific and needs to be moved to the service interface.
	 *
	 * @return  The TSDB formatted representation of the query.
	 *
	 * @throws  SystemException  If UTF-8 encoding is not supported on the system.
	 */
	@Override
	public String toString() {
		String pattern = "start={0,number,#}&end={1,number,#}&m={2}{3}&ms=true&show_tsuids=true";
		long start = Math.max(0, getStartTimestamp() - 1);
		long end = Math.max(start, getEndTimestamp() + 1);
		StringBuilder sb = new StringBuilder();

		sb.append(getAggregator() == null ? "avg" : getAggregator().getDescription()).append(":");
		if (getDownsampler() != null) {
			sb.append(getDownsamplingPeriod()).append("ms").append("-").append(getDownsampler().getDescription()).append(":");
		}
		sb.append(getTSDBMetricName());

		Map<String, String> tags = new HashMap<>(getTags());

		try {
			return MessageFormat.format(pattern, start, end, sb.toString(), toTagParameterArray(tags));
		} catch (UnsupportedEncodingException ex) {
			throw new SystemException(ex);
		}
	}

	//~ Enums ****************************************************************************************************************************************

	/**
	 * The supported methods for aggregation and downsampling.
	 *
	 * @author  Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com)
	 */
	public enum Aggregator {

		MIN("min"),
		MAX("max"),
		SUM("sum"),
		AVG("avg"),
		DEV("dev"),
		ZIMSUM("zimsum"),
		COUNT("count"),
		MIMMIN("mimmin"),
		MIMMAX("mimmax"),
		NONE("none");

		private final String _description;

		private Aggregator(String description) {
			_description = description;
		}

		/**
		 * Returns the element corresponding to the given name.
		 *
		 * @param   name  The aggregator name.
		 *
		 * @return  The corresponding aggregator element.
		 */
		public static Aggregator fromString(String name) {
			if (name != null && !name.isEmpty()) {
				for (Aggregator aggregator : Aggregator.values()) {
					if (name.equalsIgnoreCase(aggregator.name())) {
						return aggregator;
					}
				}
			}
			return null;
		}

		/**
		 * Returns the short hand description of the method.
		 *
		 * @return  The method description.
		 */
		public String getDescription() {
			return _description;
		}

	    public static Transform correspondingTransform(Aggregator agg, TransformFactory factory) {

	    	Transform transform;
			switch(agg) {
				case MIN:
					transform = factory.getTransform(TransformFactory.Function.MIN.getName());
					break;
				case MAX:
					transform = factory.getTransform(TransformFactory.Function.MAX.getName());
					break;
				case SUM:
					transform = factory.getTransform(TransformFactory.Function.ZEROIFMISSINGSUM.getName());
					break;
				case AVG:
					transform = factory.getTransform(TransformFactory.Function.AVERAGE.getName());
					break;
				case DEV:
					transform = factory.getTransform(TransformFactory.Function.DEVIATION.getName());
					break;
				case ZIMSUM:
					transform = factory.getTransform(TransformFactory.Function.ZEROIFMISSINGSUM.getName());
					break;
				case COUNT:
					transform = factory.getTransform(TransformFactory.Function.COUNT.getName());
					break;
				case MIMMIN:
					transform = factory.getTransform(TransformFactory.Function.MIN.getName());
					break;
				case MIMMAX:
					transform = factory.getTransform(TransformFactory.Function.MAX.getName());
					break;
				case NONE:
					transform = factory.getTransform(TransformFactory.Function.IDENTITY.getName());
					break;
				default:
					throw new IllegalArgumentException("Aggregator not legal: " + agg);
			}

			return transform;
	    }
	}

	/**
	 * Encapsulates parameters used to provide additional context to a metric query if needed
	 *
	 * @author  Dilip Devaraj(ddevaraj@salesforce.com)
	 */
	class MetricQueryContext {
		private String _readEndPoint;

		/**
		 * Returns the endpoint for this query
		 *
		 * @return  The endpoint for query
		 */
		public String getReadEndPoint() {
			return _readEndPoint;
		}

		/**
		 * Sets the endpoint for this query
		 *
		 * @param  readEndPoint  The endpoint for query
		 */
		public void setReadEndPoint(String readEndPoint) {
			_readEndPoint = readEndPoint;
		}

		@Override
		public String toString() {
			return "MetricQueryContext [_readEndPoint=" + _readEndPoint + "]";
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((_readEndPoint == null) ? 0 : _readEndPoint.hashCode());
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			MetricQueryContext other = (MetricQueryContext) obj;
			if (_readEndPoint == null) {
				if (other._readEndPoint != null)
					return false;
			} else if (!_readEndPoint.equals(other._readEndPoint))
				return false;
			return true;
		}
	}
}
/* Copyright (c) 2016, Salesforce.com, Inc.  All rights reserved. */


text:
cask "webpquicklook" do
  version :latest
  sha256 :no_check

  # raw.githubusercontent.com/emin/WebPQuickLook/ was verified as official when first introduced to the cask
  url "https://raw.githubusercontent.com/emin/WebPQuickLook/master/WebpQuickLook.tar.gz"
  name "WebPQuickLook"
  homepage "https://github.com/emin/WebPQuickLook"

  qlplugin "WebpQuickLook.qlgenerator"
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You under the Apache License, Version 2.0
  ~ (the "License"); you may not use this file except in compliance with
  ~ the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:sharding="http://shardingsphere.apache.org/schema/shardingsphere/sharding"
       xmlns:spi="http://shardingsphere.apache.org/schema/shardingsphere/spi"
       xmlns:bean="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://shardingsphere.apache.org/schema/shardingsphere/sharding
                        http://shardingsphere.apache.org/schema/shardingsphere/sharding/sharding.xsd
                        http://shardingsphere.apache.org/schema/shardingsphere/spi
                        http://shardingsphere.apache.org/schema/shardingsphere/spi/spi.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <context:annotation-config />
    <context:component-scan base-package="org.apache.shardingsphere.example.core.jpa"/>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="shardingDataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:database="MYSQL" />
        </property>
        <property name="packagesToScan" value="org.apache.shardingsphere.example.core.jpa.entity" />
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory" />
    <tx:annotation-driven />

    <bean id="demo_ds" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo_ds?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
    </bean>

    <sharding:inline-strategy id="orderTableStrategy" sharding-column="order_id" algorithm-expression="t_order_${order_id % 2}" />
    <sharding:inline-strategy id="orderItemTableStrategy" sharding-column="order_id" algorithm-expression="t_order_item_${order_id % 2}" />

    <bean:properties id="properties">
        <prop key="worker.id">123</prop>
    </bean:properties>

    <spi:key-generate-algorithm id="snowflakeAlgorithm" type="SNOWFLAKE" props-ref="properties"/>

    <sharding:key-generator id="orderKeyGenerator" column="order_id" algorithm-ref="snowflakeAlgorithm" />
    <sharding:key-generator id="itemKeyGenerator" column="order_item_id" algorithm-ref="snowflakeAlgorithm" />

    <sharding:data-source id="shardingDataSource">
        <sharding:sharding-rule data-source-names="demo_ds">
            <sharding:table-rules>
                <sharding:table-rule logic-table="t_order" actual-data-nodes="demo_ds.t_order_${0..1}" table-strategy-ref="orderTableStrategy" key-generator-ref="orderKeyGenerator" />
                <sharding:table-rule logic-table="t_order_item" actual-data-nodes="demo_ds.t_order_item_${0..1}" table-strategy-ref="orderItemTableStrategy" key-generator-ref="itemKeyGenerator" />
            </sharding:table-rules>
            <sharding:binding-table-rules>
                <sharding:binding-table-rule logic-tables="t_order,t_order_item"/>
            </sharding:binding-table-rules>
            <sharding:broadcast-table-rules>
                <sharding:broadcast-table-rule table="t_address"/>
            </sharding:broadcast-table-rules>
        </sharding:sharding-rule>
    </sharding:data-source>
</beans>


text:
BOOL APIENTRY DllMain(HMODULE hModule,
	DWORD  ul_reason_for_call,
	LPVOID lpReserved
)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
		SGlobalSharedDataInst.hInst = hModule;
		break;
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}


text:
<?php

namespace TFE\LibrairieBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * Edition
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="TFE\LibrairieBundle\Entity\EditionRepository")
 *
 * @UniqueEntity(fields="nomEdition", message="Cette maison d'édition est déjà enregistrée !")
 */
class Edition
{
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->livres = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nomEdition", type="string", length=30, unique=true)
     *
     * @Assert\notBlank(message = "Veuillez remplir ce champ")
     * @Assert\Length(
     *      max = "30",
     *      maxMessage = "Max. {{ limit }} caractères"
     * )
     */
    private $nomEdition;

    /**
     * @var string
     *
     * @ORM\Column(name="urlEdition", type="string", length=255, nullable=true)
     *
     * @Assert\Length(
     *      max = "255",
     *      maxMessage = "Max. {{ limit }} caractères"
     * )
     */
    private $urlEdition;

    /**
     * @var Livre
     *
     * @ORM\OneToMany(targetEntity="TFE\LibrairieBundle\Entity\Livre", mappedBy="edition")
     *
     * @Assert\Valid
     */
    private $livres;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nomEdition
     *
     * @param string $nomEdition
     * @return Edition
     */
    public function setNomEdition($nomEdition)
    {
        $this->nomEdition = $nomEdition;

        return $this;
    }

    /**
     * Get nomEdition
     *
     * @return string
     */
    public function getNomEdition()
    {
        return $this->nomEdition;
    }

    /**
     * Set urlEdition
     *
     * @param string $urlEdition
     * @return Edition
     */
    public function setUrlEdition($urlEdition)
    {
        $this->urlEdition = $urlEdition;

        return $this;
    }

    /**
     * Get urlEdition
     *
     * @return string
     */
    public function getUrlEdition()
    {
        return $this->urlEdition;
    }

    /**
     * Add livres
     *
     * @param \TFE\LibrairieBundle\Entity\Livre $livres
     * @return Edition
     */
    public function addLivre(\TFE\LibrairieBundle\Entity\Livre $livres)
    {
        $this->livres[] = $livres;

        return $this;
    }

    /**
     * Remove livres
     *
     * @param \TFE\LibrairieBundle\Entity\Livre $livres
     */
    public function removeLivre(\TFE\LibrairieBundle\Entity\Livre $livres)
    {
        $this->livres->removeElement($livres);
    }

    /**
     * Get livres
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getLivres()
    {
        return $this->livres;
    }
}


text:
You can define your own Router component.

This might be useful if you like to have a more traditional routing approach in
where you define routes as component's class attribute:

    routes: {
      '/': MainPage,
      ...
    }

Another case for this is to have more control how routers render its children,
you can define your own `render()` and do what you want.

We are going to implement custom router as a mixin:

    var React = require('react')
    var Router = require('react-router-component')

    var MyRouterMixin = {
      mixins: [Router.RouterMixin, Router.RouteRenderingMixin],

      getRoutes: function(props) {
        var routes = []
        for (var path in this.routes)
          routes.push({path: path, handler: this.routes[path]})
        return routes
      },

      setRoutingState: function(state) {
        // contains match, matchProps, handler, prefix, navigation;
        // see RouterMixin
        this.setState(state);
      }
    }

There are two things you need to notice.

First, `Router.RouterMixin` implements routing machinery and triggers router's
update when something changes (hash, pathname or something else, depending on
the environment router works in).

This mixin expects that you would implement `getRoutes` method which should
return a list of route descriptions in form of `{path: ..., handler: ...}`.

`RouterMixin` also supports intercepting its use of `setState` via `setRoutingState`.

Second, `Router.RouteRenderingMixin` is a strategy which specifies how
handler is rendered. It provides a method `renderRouteHandler()`.

We can now define our custom routers like this:

    var CreateReactClass = require('create-react-class');

    var Application = CreateReactClass({
      mixins: [MyRouterMixin],

      routes: {
        '/': MainPage,
        '/users/:username': UserPage,

        null: NotFoundPage
      },

      render: function() {
        return this.transferPropsTo(this.renderRouteHandler());
      }
    });


text:
define('app/components/pourcast/viewModel', ['ko'], function (ko) {

    function Pourcast(model) {
        var self = this;

        self.taps = ko.computed(function() {
            return ko.unwrap(model.taps);
        });
    };

    return {
        viewModel: Pourcast,
        template: { element: 'pourcast-template' }
    };
});


text:
function [argStruct] = pargs(args, defArgStruct, flagParamNames)
% Helper function for parsing varargin.
%
% INPUT:
% args = 'varargin' 1xN cell array
% defArgStruct = struct with argument names and corresponding default
%                values.
% flagParamNames = 1xM cell array with names of parameters that don't
%                  require a value. If they appear in 'args', their value
%                  will be set to 1. (Optional)
%
% OUTPUT:
% argStruct = struct with parsed arguments/values. Flags are guaranteed to
%             get assigned either a true/false value by pargs.
%
% EXAMPLES:
% argStruct = pargs(varargin, struct('param1', 0.1, 'otherParam', 'test'));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initialization

if nargin < 3
    flagParamNames = {};
end

if ~(isscalar(defArgStruct) && isstruct(defArgStruct))
    error('PARGS:InvalidDefArgStruct', 'Invalid default parameter specification: should be a single struct');
end

% Create matrix of accepted parameter names
validParamNames = fieldnames(defArgStruct);

for i = 1:length(flagParamNames)
    if ~isValidParamName(flagParamNames{i}, validParamNames)
        error('PARGS:InvalidFlagParamName', 'Invalid flag parameter name "%s"', flagParamNames{i});
    end
end

argStruct = defArgStruct;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Parse!

parseStates = struct('paramName', 1, 'paramValue', 2);
curParseState = parseStates.paramName;
curParamName = '';
curArgIdx = 1;

while curArgIdx <= length(args)
    if curParseState == parseStates.paramName
        curParamName = parseParamName(args{curArgIdx}, validParamNames);
        if isempty(curParamName)
            error('PARGS:InvalidArgument', 'Invalid argument "%s"', args{curArgIdx});
        end
        if isFlagParam(curParamName, flagParamNames)
            % Flag parameter!
            % Value might be explicitly specified...
            if length(args) > curArgIdx
                if islogical(args{curArgIdx+1}) || isnumeric(args{curArgIdx+1})
                    % Flag value is explicitly specified
                    if args{curArgIdx+1}
                        argStruct.(curParamName) = true;    % make sure we explicitly assign true/false
                    else
                        argStruct.(curParamName) = false;
                    end

                    % --> paramName (skip 1 arg)
                    curArgIdx = curArgIdx + 2;
                    curParseState = parseStates.paramName;
%^^^
                    continue;
                end
            end

            % Apparently, value was not explicitly specified: turn it on
            argStruct.(curParamName) = true;

            % --> paramName
            curArgIdx = curArgIdx + 1;
            curParseState = parseStates.paramName;
%^^^
            continue;
        else
            % Not a flag parameter
            % --> paramValue
            curArgIdx = curArgIdx + 1;
            curParseState = parseStates.paramValue;
%^^^
            continue;
        end
    elseif curParseState == parseStates.paramValue
        % Save parameter value
        argStruct.(curParamName) = args{curArgIdx};

        % --> paramName
        curArgIdx = curArgIdx + 1;
        curParseState = parseStates.paramName;
%^^^
        continue;
    else
        error('Invalid parse state in pargs!');
    end
end % while

% Are we missing anything?
if curParseState == parseStates.paramValue
    error('PARGS:MissingArgumentValue', 'Missing value for argument "%s"', curParamName);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    function [valid] = isValidParamName(paramName, validParamNames)
        valid = ~isempty(parseParamName(paramName, validParamNames));
    end

    function [parsedParamName] = parseParamName(paramName, validParamNames)
        parsedParamName = '';
        for j = 1:length(validParamNames)
            if strcmpi(paramName, validParamNames{j})
                parsedParamName = validParamNames{j};
                return
            end
        end
    end

    function [isFlag] = isFlagParam(paramName, flagParamNames)
        isFlag = false;
        for j = 1:length(flagParamNames)
            if strcmpi(paramName, flagParamNames{j})
                isFlag = true;
                return
            end
        end
    end

end