text:
using std::string;
using std::vector;

namespace kudu {

const int kMaxWidth = 64;

class TestRle : public KuduTest {};

TEST(BitArray, TestBool) {
  const int len_bytes = 2;
  faststring buffer(len_bytes);

  BitWriter writer(&buffer);

  // Write alternating 0's and 1's
  for (int i = 0; i < 8; ++i) {
    writer.PutValue(i % 2, 1);
  }
  writer.Flush();
  EXPECT_EQ(buffer[0], BOOST_BINARY(1 0 1 0 1 0 1 0));

  // Write 00110011
  for (int i = 0; i < 8; ++i) {
    switch (i) {
      case 0:
      case 1:
      case 4:
      case 5:
        writer.PutValue(0, 1);
        break;
      default:
        writer.PutValue(1, 1);
        break;
    }
  }
  writer.Flush();

  // Validate the exact bit value
  EXPECT_EQ(buffer[0], BOOST_BINARY(1 0 1 0 1 0 1 0));
  EXPECT_EQ(buffer[1], BOOST_BINARY(1 1 0 0 1 1 0 0));

  // Use the reader and validate
  BitReader reader(buffer.data(), buffer.size());
  for (int i = 0; i < 8; ++i) {
    bool val = false;
    bool result = reader.GetValue(1, &val);
    EXPECT_TRUE(result);
    EXPECT_EQ(val, i % 2);
  }

  for (int i = 0; i < 8; ++i) {
    bool val = false;
    bool result = reader.GetValue(1, &val);
    EXPECT_TRUE(result);
    switch (i) {
      case 0:
      case 1:
      case 4:
      case 5:
        EXPECT_EQ(val, false);
        break;
      default:
        EXPECT_EQ(val, true);
        break;
    }
  }
}

// Writes 'num_vals' values with width 'bit_width' and reads them back.
void TestBitArrayValues(int bit_width, int num_vals) {
  const int kTestLen = BitUtil::Ceil(bit_width * num_vals, 8);
  const uint64_t mod = bit_width == 64? 1 : 1LL << bit_width;

  faststring buffer(kTestLen);
  BitWriter writer(&buffer);
  for (int i = 0; i < num_vals; ++i) {
    writer.PutValue(i % mod, bit_width);
  }
  writer.Flush();
  EXPECT_EQ(writer.bytes_written(), kTestLen);

  BitReader reader(buffer.data(), kTestLen);
  for (int i = 0; i < num_vals; ++i) {
    int64_t val = 0;
    bool result = reader.GetValue(bit_width, &val);
    EXPECT_TRUE(result);
    EXPECT_EQ(val, i % mod);
  }
  EXPECT_EQ(reader.bytes_left(), 0);
}

TEST(BitArray, TestValues) {
  for (int width = 1; width <= kMaxWidth; ++width) {
    TestBitArrayValues(width, 1);
    TestBitArrayValues(width, 2);
    // Don't write too many values
    TestBitArrayValues(width, (width < 12) ? (1 << width) : 4096);
    TestBitArrayValues(width, 1024);
  }
}

// Test some mixed values
TEST(BitArray, TestMixed) {
  const int kTestLenBits = 1024;
  faststring buffer(kTestLenBits / 8);
  bool parity = true;

  BitWriter writer(&buffer);
  for (int i = 0; i < kTestLenBits; ++i) {
    if (i % 2 == 0) {
      writer.PutValue(parity, 1);
      parity = !parity;
    } else {
      writer.PutValue(i, 10);
    }
  }
  writer.Flush();

  parity = true;
  BitReader reader(buffer.data(), buffer.size());
  for (int i = 0; i < kTestLenBits; ++i) {
    bool result;
    if (i % 2 == 0) {
      bool val = false;
      result = reader.GetValue(1, &val);
      EXPECT_EQ(val, parity);
      parity = !parity;
    } else {
      int val;
      result = reader.GetValue(10, &val);
      EXPECT_EQ(val, i);
    }
    EXPECT_TRUE(result);
  }
}

// Validates encoding of values by encoding and decoding them.  If
// expected_encoding != NULL, also validates that the encoded buffer is
// exactly 'expected_encoding'.
// if expected_len is not -1, it will validate the encoded size is correct.
template<typename T>
void ValidateRle(const vector<T>& values, int bit_width,
    uint8_t* expected_encoding, int expected_len) {
  faststring buffer;
  RleEncoder<T> encoder(&buffer, bit_width);

  for (const auto& value : values) {
    encoder.Put(value);
  }
  int encoded_len = encoder.Flush();

  if (expected_len != -1) {
    EXPECT_EQ(encoded_len, expected_len);
  }
  if (expected_encoding != nullptr) {
    EXPECT_EQ(memcmp(buffer.data(), expected_encoding, expected_len), 0)
      << "\n"
      << "Expected: " << HexDump(Slice(expected_encoding, expected_len)) << "\n"
      << "Got:      " << HexDump(Slice(buffer));
  }

  // Verify read
  RleDecoder<T> decoder(buffer.data(), encoded_len, bit_width);
  for (const auto& value : values) {
    T val = 0;
    bool result = decoder.Get(&val);
    EXPECT_TRUE(result);
    EXPECT_EQ(value, val);
  }
}

TEST(Rle, SpecificSequences) {
  const int kTestLen = 1024;
  uint8_t expected_buffer[kTestLen];
  vector<uint64_t> values;

  // Test 50 0' followed by 50 1's
  values.resize(100);
  for (int i = 0; i < 50; ++i) {
    values[i] = 0;
  }
  for (int i = 50; i < 100; ++i) {
    values[i] = 1;
  }

  // expected_buffer valid for bit width <= 1 byte
  expected_buffer[0] = (50 << 1);
  expected_buffer[1] = 0;
  expected_buffer[2] = (50 << 1);
  expected_buffer[3] = 1;
  for (int width = 1; width <= 8; ++width) {
    ValidateRle(values, width, expected_buffer, 4);
  }

  for (int width = 9; width <= kMaxWidth; ++width) {
    ValidateRle(values, width, nullptr, 2 * (1 + BitUtil::Ceil(width, 8)));
  }

  // Test 100 0's and 1's alternating
  for (int i = 0; i < 100; ++i) {
    values[i] = i % 2;
  }
  int num_groups = BitUtil::Ceil(100, 8);
  expected_buffer[0] = (num_groups << 1) | 1;
  for (int i = 0; i < 100/8; ++i) {
    expected_buffer[i + 1] = BOOST_BINARY(1 0 1 0 1 0 1 0); // 0xaa
  }
  // Values for the last 4 0 and 1's
  expected_buffer[1 + 100/8] = BOOST_BINARY(0 0 0 0 1 0 1 0); // 0x0a

  // num_groups and expected_buffer only valid for bit width = 1
  ValidateRle(values, 1, expected_buffer, 1 + num_groups);
  for (int width = 2; width <= kMaxWidth; ++width) {
    ValidateRle(values, width, nullptr, 1 + BitUtil::Ceil(width * 100, 8));
  }
}

// ValidateRle on 'num_vals' values with width 'bit_width'. If 'value' != -1, that value
// is used, otherwise alternating values are used.
void TestRleValues(int bit_width, int num_vals, int value = -1) {
  const uint64_t mod = bit_width == 64 ? 1ULL : 1ULL << bit_width;
  vector<uint64_t> values;
  for (uint64_t v = 0; v < num_vals; ++v) {
    values.push_back((value != -1) ? value : (bit_width == 64 ? v : (v % mod)));
  }
  ValidateRle(values, bit_width, nullptr, -1);
}

TEST(Rle, TestValues) {
  for (int width = 1; width <= kMaxWidth; ++width) {
    TestRleValues(width, 1);
    TestRleValues(width, 1024);
    TestRleValues(width, 1024, 0);
    TestRleValues(width, 1024, 1);
  }
}

class BitRle : public KuduTest {
};

// Tests all true/false values
TEST_F(BitRle, AllSame) {
  const int kTestLen = 1024;
  vector<bool> values;

  for (int v = 0; v < 2; ++v) {
    values.clear();
    for (int i = 0; i < kTestLen; ++i) {
      values.push_back(v ? true : false);
    }

    ValidateRle(values, 1, nullptr, 3);
  }
}

// Test that writes out a repeated group and then a literal
// group but flush before finishing.
TEST_F(BitRle, Flush) {
  vector<bool> values;
  for (int i = 0; i < 16; ++i) values.push_back(1);
  values.push_back(false);
  ValidateRle(values, 1, nullptr, -1);
  values.push_back(true);
  ValidateRle(values, 1, nullptr, -1);
  values.push_back(true);
  ValidateRle(values, 1, nullptr, -1);
  values.push_back(true);
  ValidateRle(values, 1, nullptr, -1);
}

// Test some random bool sequences.
TEST_F(BitRle, RandomBools) {
  int iters = 0;
  const int n_iters = AllowSlowTests() ? 1000 : 20;
  while (iters < n_iters) {
    srand(iters++);
    if (iters % 10000 == 0) LOG(ERROR) << "Seed: " << iters;
    vector<uint64_t > values;
    bool parity = 0;
    for (int i = 0; i < 1000; ++i) {
      int group_size = rand() % 20 + 1; // NOLINT(*)
      if (group_size > 16) {
        group_size = 1;
      }
      for (int i = 0; i < group_size; ++i) {
        values.push_back(parity);
      }
      parity = !parity;
    }
    ValidateRle(values, (iters % kMaxWidth) + 1, nullptr, -1);
  }
}

// Test some random 64-bit sequences.
TEST_F(BitRle, Random64Bit) {
  int iters = 0;
  const int n_iters = AllowSlowTests() ? 1000 : 20;
  while (iters < n_iters) {
    srand(iters++);
    if (iters % 10000 == 0) LOG(ERROR) << "Seed: " << iters;
    vector<uint64_t > values;
    for (int i = 0; i < 1000; ++i) {
      int group_size = rand() % 20 + 1; // NOLINT(*)
      uint64_t cur_value = (static_cast<uint64_t>(rand()) << 32) + static_cast<uint64_t>(rand());
      if (group_size > 16) {
        group_size = 1;
      }
      for (int i = 0; i < group_size; ++i) {
        values.push_back(cur_value);
      }

    }
    ValidateRle(values, 64, nullptr, -1);
  }
}

// Test a sequence of 1 0's, 2 1's, 3 0's. etc
// e.g. 011000111100000
TEST_F(BitRle, RepeatedPattern) {
  vector<bool> values;
  const int min_run = 1;
  const int max_run = 32;

  for (int i = min_run; i <= max_run; ++i) {
    int v = i % 2;
    for (int j = 0; j < i; ++j) {
      values.push_back(v);
    }
  }

  // And go back down again
  for (int i = max_run; i >= min_run; --i) {
    int v = i % 2;
    for (int j = 0; j < i; ++j) {
      values.push_back(v);
    }
  }

  ValidateRle(values, 1, nullptr, -1);
}

TEST_F(TestRle, TestBulkPut) {
  size_t run_length;
  bool val = false;

  faststring buffer(1);
  RleEncoder<bool> encoder(&buffer, 1);
  encoder.Put(true, 10);
  encoder.Put(false, 7);
  encoder.Put(true, 5);
  encoder.Put(true, 15);
  encoder.Flush();

  RleDecoder<bool> decoder(buffer.data(), encoder.len(), 1);
  run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
  ASSERT_TRUE(val);
  ASSERT_EQ(10, run_length);

  run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
  ASSERT_FALSE(val);
  ASSERT_EQ(7, run_length);

  run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
  ASSERT_TRUE(val);
  ASSERT_EQ(20, run_length);

  ASSERT_EQ(0, decoder.GetNextRun(&val, MathLimits<size_t>::kMax));
}

TEST_F(TestRle, TestGetNextRun) {
  // Repeat the test with different number of items
  for (int num_items = 7; num_items < 200; num_items += 13) {
    // Test different block patterns
    //    1: 01010101 01010101
    //    2: 00110011 00110011
    //    3: 00011100 01110001
    //    ...
    for (int block = 1; block <= 20; ++block) {
      faststring buffer(1);
      RleEncoder<bool> encoder(&buffer, 1);
      for (int j = 0; j < num_items; ++j) {
        encoder.Put(!!(j & 1), block);
      }
      encoder.Flush();

      RleDecoder<bool> decoder(buffer.data(), encoder.len(), 1);
      size_t count = num_items * block;
      for (int j = 0; j < num_items; ++j) {
        size_t run_length;
        bool val = false;
        DCHECK_GT(count, 0);
        run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
        run_length = std::min(run_length, count);

        ASSERT_EQ(!!(j & 1), val);
        ASSERT_EQ(block, run_length);
        count -= run_length;
      }
      DCHECK_EQ(count, 0);
    }
  }
}

// Generate a random bit string which consists of 'num_runs' runs,
// each with a random length between 1 and 100. Returns the number
// of values encoded (i.e the sum run length).
static size_t GenerateRandomBitString(int num_runs, faststring* enc_buf, string* string_rep) {
  RleEncoder<bool> enc(enc_buf, 1);
  int num_bits = 0;
  for (int i = 0; i < num_runs; i++) {
    int run_length = random() % 100;
    bool value = static_cast<bool>(i & 1);
    enc.Put(value, run_length);
    string_rep->append(run_length, value ? '1' : '0');
    num_bits += run_length;
  }
  enc.Flush();
  return num_bits;
}

TEST_F(TestRle, TestRoundTripRandomSequencesWithRuns) {
  SeedRandom();

  // Test the limiting function of GetNextRun.
  const int kMaxToReadAtOnce = (random() % 20) + 1;

  // Generate a bunch of random bit sequences, and "round-trip" them
  // through the encode/decode sequence.
  for (int rep = 0; rep < 100; rep++) {
    faststring buf;
    string string_rep;
    int num_bits = GenerateRandomBitString(10, &buf, &string_rep);
    RleDecoder<bool> decoder(buf.data(), buf.size(), 1);
    string roundtrip_str;
    int rem_to_read = num_bits;
    size_t run_len;
    bool val;
    while (rem_to_read > 0 &&
           (run_len = decoder.GetNextRun(&val, std::min(kMaxToReadAtOnce, rem_to_read))) != 0) {
      ASSERT_LE(run_len, kMaxToReadAtOnce);
      roundtrip_str.append(run_len, val ? '1' : '0');
      rem_to_read -= run_len;
    }

    ASSERT_EQ(string_rep, roundtrip_str);
  }
}
TEST_F(TestRle, TestSkip) {
  faststring buffer(1);
  RleEncoder<bool> encoder(&buffer, 1);

  // 0101010[1] 01010101 01
  //        "A"
  for (int j = 0; j < 18; ++j) {
    encoder.Put(!!(j & 1));
  }

  // 0011[00] 11001100 11001100 11001100 11001100
  //      "B"
  for (int j = 0; j < 19; ++j) {
    encoder.Put(!!(j & 1), 2);
  }

  // 000000000000 11[1111111111] 000000000000 111111111111
  //                   "C"
  // 000000000000 111111111111 0[00000000000] 111111111111
  //                                  "D"
  // 000000000000 111111111111 000000000000 111111111111
  for (int j = 0; j < 12; ++j) {
    encoder.Put(!!(j & 1), 12);
  }
  encoder.Flush();

  bool val = false;
  size_t run_length;
  RleDecoder<bool> decoder(buffer.data(), encoder.len(), 1);

  // position before "A"
  ASSERT_EQ(3, decoder.Skip(7));
  run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
  ASSERT_TRUE(val);
  ASSERT_EQ(1, run_length);

  // position before "B"
  ASSERT_EQ(7, decoder.Skip(14));
  run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
  ASSERT_FALSE(val);
  ASSERT_EQ(2, run_length);

  // position before "C"
  ASSERT_EQ(18, decoder.Skip(46));
  run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
  ASSERT_TRUE(val);
  ASSERT_EQ(10, run_length);

  // position before "D"
  ASSERT_EQ(24, decoder.Skip(49));
  run_length = decoder.GetNextRun(&val, MathLimits<size_t>::kMax);
  ASSERT_FALSE(val);
  ASSERT_EQ(11, run_length);

  encoder.Flush();
}

// RLE encoding groups values and decides whether to run-length encode or simply bit-pack
// (literal encoding). This test verifies correctness of the RLE decoding when literal
// encoding is used irrespective of the size of the group and the number of values encoded.
template <typename IntType>
class TestRleLiteralGetNextRun : public KuduTest {
 public:
  void RunTest() {
    const auto num_bytes_per_val = sizeof(IntType);
    const auto bit_width = 8 * num_bytes_per_val;

    // Test with number of values that are not necessarily multiple of the group size (8).
    auto max_num_vals = std::min<uint64_t>(1024, std::numeric_limits<IntType>::max());
    for (auto num_vals = 1; num_vals <= max_num_vals; num_vals++) {
      faststring buffer(num_vals * num_bytes_per_val);
      RleEncoder<IntType> encoder(&buffer, bit_width);

      // Use non-repeated pattern of integers so that literal encoding is used.
      for (auto i = 0; i < num_vals; i++) {
        encoder.Put(i, 1);
      }
      encoder.Flush();

      RleDecoder<IntType> decoder(buffer.data(), encoder.len(), bit_width);
      IntType val = 0;
      for (auto i = 0; i < num_vals; i++) {
        size_t len = decoder.GetNextRun(&val, num_vals);
        ASSERT_EQ(1, len);
        ASSERT_EQ(i, val);
      }
      // Read one beyond to verify no value is returned.
      ASSERT_EQ(0, decoder.GetNextRun(&val, num_vals));
    }
  }
};

typedef ::testing::Types<int8_t, int16_t, int32_t, int64_t> IntDataTypes;
TYPED_TEST_CASE(TestRleLiteralGetNextRun, IntDataTypes);

TYPED_TEST(TestRleLiteralGetNextRun, RleGetNextRunIntDataTypes) {
  this->RunTest();
}

} // namespace kudu


text:
namespace chromecast {

CastContentWindow::CastContentWindow(mojom::CastWebViewParamsPtr params)
    : params_(std::move(params)) {
  RegisterBackGestureRouter(gesture_router());
}

CastContentWindow::~CastContentWindow() = default;

void CastContentWindow::SetCastWebContents(CastWebContents* cast_web_contents) {
  cast_web_contents_ = cast_web_contents;
  // Must provide binder callbacks with WeakPtr since CastContentWindow + these
  // interface implementations are destroyed before CastWebContents.
  cast_web_contents_->local_interfaces()->AddBinder(base::BindRepeating(
      &CastContentWindow::BindReceiver, weak_factory_.GetWeakPtr()));
  cast_web_contents_->local_interfaces()->AddBinder(base::BindRepeating(
      &CastContentWindow::BindActivityWindow, weak_factory_.GetWeakPtr()));
  cast_web_contents_->local_interfaces()->AddBinder(
      gesture_router()->GetBinder());
}

void CastContentWindow::AddObserver(Observer* observer) {
  DCHECK(observer);
  sync_observers_.AddObserver(observer);
}

void CastContentWindow::RemoveObserver(CastContentWindow::Observer* observer) {
  DCHECK(observer);
  sync_observers_.RemoveObserver(observer);
}

void CastContentWindow::AddObserver(
    mojo::PendingRemote<mojom::CastContentWindowObserver> observer) {
  observers_.Add(std::move(observer));
}

void CastContentWindow::BindReceiver(
    mojo::PendingReceiver<mojom::CastContentWindow> receiver) {
  receiver_.Bind(std::move(receiver));
}

void CastContentWindow::BindActivityWindow(
    mojo::PendingReceiver<mojom::ActivityWindow> receiver) {
  activity_window_receiver_.Bind(std::move(receiver));
}

void CastContentWindow::Show() {
  RequestVisibility(VisibilityPriority::STICKY_ACTIVITY);
}

void CastContentWindow::Hide() {}

void CastContentWindow::NotifyVisibilityChange(VisibilityType visibility_type) {
  for (auto& observer : observers_) {
    observer->OnVisibilityChange(visibility_type);
  }
  for (Observer& observer : sync_observers_) {
    observer.OnVisibilityChange(visibility_type);
  }
}

}  // namespace chromecast

redpajama_set_name: RedPajamaGithub


text:
package com.br.pgmobil.dto;

import java.io.Serializable;

public class PedidoDTO implements Serializable{

	private static final long serialVersionUID = 1L;

	private Long valor;
	private String dataHora;
	private String descricao;
	private String nsu;
	private String numeroCartao;
	private String codigoAutorizacao;
	private String status;
	private String statusCancelamento;

	public PedidoDTO(Long valor, String dataHora, String descricao,String nsu, String numeroCartao, String codigoAutorizacao,String status, String statusCancelamento) {
		super();
		this.valor = valor;
		this.dataHora = dataHora;
		this.descricao = descricao;
		this.nsu = nsu;
		this.numeroCartao = numeroCartao;
		this.codigoAutorizacao = codigoAutorizacao;
		this.status = status;
		this.statusCancelamento = statusCancelamento;
	}

	public PedidoDTO(){

	}

	public Long getValor() {
		return valor;
	}

	public void setValor(Long valor) {
		this.valor = valor;
	}

	public String getDataHora() {
		return dataHora;
	}
	public void setDataHora(String dataHora) {
		this.dataHora = dataHora;
	}
	public String getDescricao() {
		return descricao;
	}
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	public String getNsu() {
		return nsu;
	}
	public void setNsu(String nsu) {
		this.nsu = nsu;
	}
	public String getCodigoAutorizacao() {
		return codigoAutorizacao;
	}
	public void setCodigoAutorizacao(String codigoAutorizacao) {
		this.codigoAutorizacao = codigoAutorizacao;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}

	public String getNumeroCartao() {
		return numeroCartao;
	}

	public void setNumeroCartao(String numeroCartao) {
		this.numeroCartao = numeroCartao;
	}

	public String getStatusCancelamento() {
		return statusCancelamento;
	}

	public void setStatusCancelamento(String statusCancelamento) {
		this.statusCancelamento = statusCancelamento;
	}

}


text:
<?php

include 'Vehicle.php';

$myVehicle = new Vehicle(2, 'Orange');
print_r($myVehicle);
echo "\n";

$myVehicle->setColor('Blue');
print_r($myVehicle);


text:
\documentclass[A4,12pt, utf8]{article}
\usepackage{tikz}
\usepackage[
    backend=biber,
    style=authoryear-icomp,
    sortlocale=de_DE,
    natbib=true,
    url=false,
    doi=true,
    eprint=false
]{biblatex}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{hyperref}
\usepackage{pgf}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
\usepackage{todonotes}
\usepackage{dirtree}
\usepackage{pdflscape}
\usepackage{csquotes}
\MakeOuterQuote{"}

\newcommand{\tinytodo}[2][]
   {\todo[caption={#2}, size=\small, #1]{\renewcommand{\baselinestretch}{0.5}\selectfont#2\par}}

\colorlet{punct}{red!60!black}
\definecolor{background}{HTML}{EEEEEE}
\definecolor{delim}{RGB}{20,105,176}
\colorlet{numb}{magenta!60!black}

\lstdefinelanguage{json}{
    basicstyle=\normalfont\ttfamily,
    % numbers=left,
    % numberstyle=\scriptsize,
    % stepnumber=1,
    % numbersep=8pt,
    showstringspaces=false,
    breaklines=true,
    frame=lines,
    backgroundcolor=\color{background},
    literate=
     *{0}{{{\color{numb}0}}}{1}
      {1}{{{\color{numb}1}}}{1}
      {2}{{{\color{numb}2}}}{1}
      {3}{{{\color{numb}3}}}{1}
      {4}{{{\color{numb}4}}}{1}
      {5}{{{\color{numb}5}}}{1}
      {6}{{{\color{numb}6}}}{1}
      {7}{{{\color{numb}7}}}{1}
      {8}{{{\color{numb}8}}}{1}
      {9}{{{\color{numb}9}}}{1}
      {:}{{{\color{punct}{:}}}}{1}
      {,}{{{\color{punct}{,}}}}{1}
      {\{}{{{\color{delim}{\{}}}}{1}
      {\}}{{{\color{delim}{\}}}}}{1}
      {[}{{{\color{delim}{[}}}}{1}
      {]}{{{\color{delim}{]}}}}{1},
}
% \addbibresource{linked.bib}

\newcounter{treeline}

\newcommand{\treeroot}[1]{% Title
\node[above] at (0,0) {#1};%
\setcounter{treeline}{0}
}

\newcommand{\treeentry}[2]{% Title, Level
\draw[->] (#2-1,-\value{treeline}/2) -- (#2-1,-\value{treeline}/2-0.5) -- (#2+0.5,-\value{treeline}/2-0.5) node[right] {#1};
\stepcounter{treeline}
}

\newcommand{\altentry}[2]{% Title, Level
\draw[->] (#2-1,-\value{treeline}/2) -- (#2-1,-\value{treeline}/2-0.5) -- (#2+0.5,-\value{treeline}/2-0.5) node[right] {#1};
\foreach \x in {1,...,#2}
{   \draw (\x-1,-\value{treeline}/2) -- (\x-1,-\value{treeline}/2-0.5);
}
\stepcounter{treeline}
}

\title{emuLVC - Stucture of the angularjs app}
\author{Raphael Winkelmann}
\date{\today}
\begin{document}
  % \maketitle

\section{Schematic DB file structure on disc}

\begin{tikzpicture}
\treeroot{\textbf{dbRootFolder/}}
\altentry{\textit{global\_DBconfig.json$^{*2}$}}{1}
\altentry{\textbf{0001\_ses/$^{*3}$}}{1}
\altentry{\textbf{0002\_ses/}}{1}
\altentry{\textit{0002\_sesmeta$^{*6}$}}{2}
\altentry{\textbf{bundle1\_bndl/$^{*4}$}}{2}
\altentry{\textbf{bundle2\_bndl/}}{2}
\altentry{\textit{bundle2\_bndlmeta.json$^{*7}$}}{3}
\altentry{\textit{bundle2.wav}}{3}
\altentry{\textit{bundle2\_annot.json$^{*5}$}}{3}
\altentry{\textit{bundle2.fms}}{3}
\altentry{\textit{bundle2.f0}}{3}
\altentry{\dots}{3}
\altentry{\textbf{bundle3\_bndl/}}{2}
\altentry{\dots}{2}
\altentry{\textbf{0003\_ses/}}{1}
\altentry{\dots}{1}
\end{tikzpicture}

\begin{itemize}
  \item $^{*2}$: global config information file (similar to \textit{.tpl} file of old EMU). Specifies things like structure of hierarchy and possible perspectives to look at the DB (relevant for layout of labeler). \textit{\_DBconfig.json} is a fix suffix and the prefix should be the same as the database name field in the file itself.
  \item $^{*3}$: \textit{\_ses} is a fix suffix specifying the folder as being a session folder. Preceding this suffix can be anything as long it is unique on a session level (OS won't let you name two folders the same anyway...). If no session is required a dummy session is used called 0000\_ses.
  \item $^{*4}$: a bundle encapsulates what used to be known as an utterance in a folder. This includes signal files (\textit{wav, SSFF}) and the new annotation file (see $^{*5}$). Unknown file extensions are ignored. \textit{\_bndl} is a fix suffix specifying the folder as being a bundle folder.
  \item $^{*5}$: annotation file containing label and level information as well as hierarchical information (see listing 1). \textit{\_annot.json} is a fix suffix and the prefix should be the same as the bundle name.
  \item $^{*6}$: Optional session meta information file. Simple key-value json of the form \{"key1":"value1", "key2":"value2"\}
  \item $^{*7}$: Optional bundle meta information file. Simple key-value json of the form \{"key1":"value1", "key2":"value2"\}
\end{itemize}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{File structure of json files}

The EMU-webApp supports several JSON file types for which individual schema are available (all of type:
\texttt{http://json-schema.org/draft-04/schema\#})

\section{Schema files}

There are two sets of schema files. The ones being used by the current live version of the web application
(\url{http://ips-lmu.github.io/EMU-webApp/}) and the ones used by the current development version.
The two sets are usually quite similar if not identical as we try to keep the file definitions as
constant as possible.

The schema files used by the current live version are:

\todo[inline]{redo after schema cleanup}

\begin{itemize}
  \item \textbf{DBconfigFileSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/DBconfigFileSchema.json}{GitHub link}
  \item \textbf{annotationFileSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/annotationFileSchema.json}{GitHub link}
  \item \textbf{bundleSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/bundleSchema.json}{GitHub link}
  \item \textbf{bundleListSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/bundleListSchema.json}{GitHub link}
  \item \textbf{emuwebappConfigSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/emuwebappConfigSchema.json}{GitHub link}
  \item \textbf{emuwebappConfigSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/emuwebappConfigSchema.json}{GitHub link}
\end{itemize}

The schema files for the development version are:

\begin{itemize}
  \item \textbf{DBconfigFileSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/DBconfigFileSchema.json}{GitHub link}
  \item \textbf{annotationFileSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/annotationFileSchema.json}{GitHub link}
  \item \textbf{bundleSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/bundleSchema.json}{GitHub link}
  \item \textbf{bundleListSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/bundleListSchema.json}{GitHub link}
  \item \textbf{emuwebappConfigSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/emuwebappConfigSchema.json}{GitHub link}
  \item \textbf{emuwebappConfigSchema}: \href{https://github.com/IPS-LMU/EMU-webApp/blob/master/dist/schemaFiles/emuwebappConfigSchema.json}{GitHub link}
\end{itemize}

Examples of files that validate against these schemas can be found here:

\todo[inline]{List files that validate here}

\begin{lstlisting}[caption=EMU-webApp internal derived signal representation, label=idsr, language=json,firstnumber=1]
{
  "filepath": "/path/to/msajc003.fms",
  "sampleRate" = 200,
  "origFreq" = 20000,
  "startTime" = 0.0025,
  "columns" = [
  {"name": "fm",
    "length": 4,
    "ssffDataType": "SHORT"
    "values" : [[0, 1042, 2072, 3170],
                [0, 1260, 2122, 3118],
                [0, 1339, 2293, 3258],
                ...]},
  {"name": "bw",
    "length": 4,
    "ssffDataType": "SHORT"
    "values" : [[0, 886, 371, 890],
                [0, 724, 567, 826],
                [0, 410, 664, 740],
                ...]}
  ]
}
\end{lstlisting}

\clearpage

\end{document}


text:
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.gui.dnd;

import java.awt.Point;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

import org.pathvisio.core.debug.Logger;
import org.pathvisio.core.gui.PathwayTransferable;
import org.pathvisio.core.model.ConverterException;
import org.pathvisio.core.model.GpmlFormat;
import org.pathvisio.core.model.ObjectType;
import org.pathvisio.core.model.Pathway;
import org.pathvisio.core.model.PathwayElement;
import org.pathvisio.gui.view.VPathwaySwing;

public class PathwayImportHandler extends TransferHandler implements ClipboardOwner {

	static final int NOT_OWNER = -1;
	int timesPasted; //Keeps track of how many times the same data is pasted
	static final double M_PASTE_OFFSET = 10;

	Set<DataFlavor> supportedFlavors;

	public PathwayImportHandler() {
		supportedFlavors = new HashSet<DataFlavor>();
		supportedFlavors.add(PathwayTransferable.GPML_DATA_FLAVOR);
		supportedFlavors.add(DataFlavor.stringFlavor);
	}

	public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
		for(DataFlavor d : transferFlavors) {
			if(supportedFlavors.contains(d)) return true;
		}
		return false;
	}

	public boolean importData(JComponent comp, Transferable t) {
		try {
			String xml = PathwayTransferable.getText(t);
			if(xml != null) {
				Logger.log.trace("Importing from xml: " + xml);
				importGpml(comp, xml, null);
			}

		} catch(Exception e) {
			Logger.log.error("Unable to paste pathway data", e);
		}
		return false;
	}

	public boolean importDataAtCursorPosition(JComponent comp, Transferable t, Point p) {
		try {
			String xml = PathwayTransferable.getText(t);
			if(xml != null) {
				Logger.log.trace("Importing from xml: " + xml);
				importGpml(comp, xml, p);
			}

		} catch(Exception e) {
			Logger.log.error("Unable to paste pathway data", e);
		}
		return false;
	}

	/**
	 * new parameter p is just used for paste with the right click menu
	 */
	private boolean importGpml(JComponent comp, String xml, Point p) throws UnsupportedFlavorException, IOException, ConverterException {
		Pathway pnew = new Pathway();
		GpmlFormat.readFromXml(pnew, new StringReader(xml), true);

		List<PathwayElement> elements = new ArrayList<PathwayElement>();
		for(PathwayElement elm : pnew.getDataObjects()) {
			if(elm.getObjectType() != ObjectType.MAPPINFO) {
				elements.add(elm);
			} else {
				//Only add mappinfo if it's not generated by the transferable
				String source = elm.getMapInfoDataSource();
				if(!PathwayTransferable.INFO_DATASOURCE.equals(source)) {
					elements.add(elm);
				}
			}
		}

		if(p == null) {
			int shift = 0;
			if(timesPasted != NOT_OWNER) shift = ++timesPasted;
			((VPathwaySwing)comp).getChild().paste(elements, shift * M_PASTE_OFFSET, shift * M_PASTE_OFFSET);
		} else {
			Point2D.Double shift = calculateShift(elements, p);
			((VPathwaySwing)comp).getChild().paste(elements, shift.x, shift.y);
		}
		return false;
	}

	public void lostOwnership(Clipboard clipboard, Transferable contents) {
		timesPasted = NOT_OWNER;
	}

	public void obtainedOwnership() {
		timesPasted = 0;
	}

	private Point2D.Double calculateShift(List<PathwayElement> elements, Point cursorPosition) {
		Point2D.Double topLeftCorner = getTopLeftCorner(elements);
		double xShift = cursorPosition.x - topLeftCorner.x;
		double yShift = cursorPosition.y - topLeftCorner.y;
		return new Point2D.Double(xShift, yShift);
	}

	/**
	 * Returns the top left corner of the bounding box around the elements
	 * @param elements = list of PathwayElement objects
	 * @return
	 */
	private Point2D.Double getTopLeftCorner(List<PathwayElement> elements) {

		Rectangle2D vr = null;
		for (PathwayElement o : elements)
		{
			if (o.getObjectType() == ObjectType.INFOBOX) continue;
			if (o.getObjectType() == ObjectType.BIOPAX) continue;
			else {
				if (vr == null) vr = o.getMBounds();
				else vr.add(o.getMBounds());
			}
		}

		return new Point2D.Double(vr.getX(), vr.getY());
	}
}


text:
layout: post
date: '2016-09-14'
title: "Khione Gown"
category: Vintage Wedding Gowns
tags: ["bride","apparel","gown","star","khione"]
image: http://www.starbrideapparel.com/21899-thickbox_default/khione-gown.jpg
---
Khione Gown

On Sales: **$323.394**
<amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/21899-thickbox_default/khione-gown.jpg" alt="Khione Gown 0" />
<amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/21900-thickbox_default/khione-gown.jpg" alt="Khione Gown 1" />
<amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/21901-thickbox_default/khione-gown.jpg" alt="Khione Gown 2" />

Buy it: [Khione Gown](https://www.starbrideapparel.com/vintage-wedding-gowns/8721-khione-gown-1463394481431.html "Khione Gown")

View more: [Vintage Wedding Gowns](https://www.starbrideapparel.com/9-vintage-wedding-gowns "Vintage Wedding Gowns")


text:
/*
 * This is not the original file distributed by the Apache Software Foundation
 * It has been modified by the Hipparchus project
 */

package org.hipparchus.linear;

/**
 * Default implementation of the {@link RealMatrixChangingVisitor} interface.
 * <p>
 * This class is a convenience to create custom visitors without defining all
 * methods. This class provides default implementations that do nothing.
 * </p>
 *
 */
public class DefaultRealMatrixChangingVisitor implements RealMatrixChangingVisitor {
    /** {@inheritDoc} */
    @Override
    public void start(int rows, int columns,
                      int startRow, int endRow, int startColumn, int endColumn) {
    }

    /** {@inheritDoc} */
    @Override
    public double visit(int row, int column, double value) {
        return value;
    }

    /** {@inheritDoc} */
    @Override
    public double end() {
        return 0;
    }
}


text:
class Coffee
	def cost
		2
	end
end

module Milk
	def cost
		super + 0.4
	end
end

module Sugar
	def cost
		super + 0.2
	end
end

coffee = Coffee.new
coffee.extend(Milk)
coffee.extend(Sugar)
p coffee.cost


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\PromotionBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
final class RegisterRuleCheckersPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if (!$container->has('sylius.registry_promotion_rule_checker') || !$container->has('sylius.form_registry.promotion_rule_checker')) {
            return;
        }

        $promotionRuleCheckerRegistry = $container->getDefinition('sylius.registry_promotion_rule_checker');
        $promotionRuleCheckerFormTypeRegistry = $container->getDefinition('sylius.form_registry.promotion_rule_checker');

        $promotionRuleCheckerTypeToLabelMap = [];
        foreach ($container->findTaggedServiceIds('sylius.promotion_rule_checker') as $id => $attributes) {
            if (!isset($attributes[0]['type'], $attributes[0]['label'], $attributes[0]['form_type'])) {
                throw new \InvalidArgumentException('Tagged rule checker `' . $id . '` needs to have `type`, `form_type` and `label` attributes.');
            }

            $promotionRuleCheckerTypeToLabelMap[$attributes[0]['type']] = $attributes[0]['label'];
            $promotionRuleCheckerRegistry->addMethodCall('register', [$attributes[0]['type'], new Reference($id)]);
            $promotionRuleCheckerFormTypeRegistry->addMethodCall('add', [$attributes[0]['type'], 'default', $attributes[0]['form_type']]);
        }

        $container->setParameter('sylius.promotion_rules', $promotionRuleCheckerTypeToLabelMap);
    }
}


text:
.. _openni_grabber:

The OpenNI Grabber Framework in PCL
-----------------------------------

As of PCL 1.0, we offer a new generic grabber interface to provide a smooth and
convenient access to different devices and their drivers, file formats and
other sources of data.

The first driver that we incorporated is the new OpenNI Grabber, which makes it
a breeze to request data streams from OpenNI compatible cameras. This tutorial
presents how to set up and use the grabber, and since it's so simple, we can
keep it short :).

The cameras that we have tested so far are the `Primesense Reference Design <http://www.primesense.com/>`_, `Microsoft Kinect <http://www.xbox.com/kinect/>`_ and `Asus Xtion Pro <http://event.asus.com/wavi/product/WAVI_Pro.aspx>`_ cameras:

.. image:: images/openni_cams.jpg
   :height: 390px

Simple Example
--------------

In *visualization*, there is a very short piece of code which contains all that
is required to set up a *pcl::PointCloud<XYZ>* or *pcl::PointCloud<XYZRGB>*
cloud callback.

Here is a screenshot and a video of the PCL OpenNI Viewer in action, which uses
the OpenNI Grabber.

.. image:: images/pcl_openni_viewer.jpg
   :height: 390px
   :target: _images/pcl_openni_viewer.jpg

.. raw:: html

  <iframe title="PCL OpenNI Viewer example" width="480" height="390" src="http://www.youtube.com/embed/x3SaWQkPsPI?rel=0" frameborder="0" allowfullscreen></iframe>

So let's look at the code. From *visualization/tools/openni_viewer_simple.cpp*

.. code-block:: cpp
   :linenos:

    #include <pcl/io/openni_grabber.h>
    #include <pcl/visualization/cloud_viewer.h>

    class SimpleOpenNIViewer
    {
      public:
        SimpleOpenNIViewer () : viewer ("PCL OpenNI Viewer") {}

        void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &cloud)
        {
          if (!viewer.wasStopped())
            viewer.showCloud (cloud);
        }

        void run ()
        {
          pcl::Grabber* interface = new pcl::OpenNIGrabber();

          std::function<void (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)> f =
            boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);

          interface->registerCallback (f);

          interface->start ();

          while (!viewer.wasStopped())
          {
            boost::this_thread::sleep (boost::posix_time::seconds (1));
          }

          interface->stop ();
        }

        pcl::visualization::CloudViewer viewer;
    };

    int main ()
    {
      SimpleOpenNIViewer v;
      v.run ();
      return 0;
    }

As you can see, the *run ()* function of *SimpleOpenNIViewer* first creates a
new *OpenNIGrabber* interface. The next line might seem a bit intimidating at
first, but it's not that bad. We create a *boost::bind* object with the address
of the callback *cloud_cb_*, we pass a reference to our *SimpleOpenNIViewer*
and the argument place holder *_1*.

The *bind* then gets casted to a *std::function* object which is templated on
the callback function type, in this case *void (const
pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)*. The resulting function object can
the be registered with the *OpenNIGrabber* and subsequently started.  Note that
the *stop ()* method does not necessarily need to be called, as the destructor
takes care of that.

Additional Details
------------------

The *OpenNIGrabber* offers more than one datatype, which is the reason we made
the *Grabber* interface so generic, leading to the relatively complicated
*boost::bind* line. In fact, we can register the following callback types as of
this writing:

* `void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)`

* `void (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)`

* `void (const openni_wrapper::Image::Ptr&)`

  This provides just the RGB image from the built-in camera.

* `void (const openni_wrapper::DepthImage::Ptr&)`

  This provides the depth image, without any color or intensity information

* `void (const openni_wrapper::Image::Ptr&, const openni_wrapper::DepthImage::Ptr&, float constant)`

  When a callback of this type is registered, the grabber sends both RGB
  image and depth image and the constant (*1 / focal length*), which you need
  if you want to do your own disparity conversion.

.. note::
  All callback types that need a depth _and_ image stream have a
  synchronization mechanism enabled which ensures consistent depth and image
  data. This introduces a small lag, since the synchronizer needs to wait at
  least for one more set of images before sending the first ones.

Starting and stopping streams
-----------------------------

The *registerCallback* call returns a *boost::signals2::connection* object,
which we ignore in the above example. However, if you want to interrupt or
cancel one or more of the registered data streams, you can call disconnect the
callback without stopping the whole grabber:

.. code-block:: cpp

   boost::signals2::connection = interface (registerCallback (f));

   // ...

   if (c.connected ())
     c.disconnect ();

Benchmark
---------

The following code snippet will attempt to subscribe to both the *depth* and
*color* streams, and is provided as a way to benchmark your system. If your
computer is too slow, and you might not be able to get ~29Hz+, please contact
us. We might be able to optimize the code even further.

.. literalinclude:: sources/openni_grabber/openni_grabber.cpp
   :language: cpp
   :linenos:

Compiling and running the program
---------------------------------

Add the following lines to your CMakeLists.txt file:

.. literalinclude:: sources/openni_grabber/CMakeLists.txt
   :language: cmake
   :linenos:

Troubleshooting
---------------

Q: I get an error that there's no device connected:

.. note::

  [OpenNIGrabber] No devices connected.
  terminate called after throwing an instance of 'pcl::PCLIOException'
  what():  pcl::OpenNIGrabber::OpenNIGrabber(const std::string&) in openni_grabber.cpp @ 69: Device could not be initialized or no devices found.
  [1]    8709 abort      openni_viewer

A: most probably this is a problem with the XnSensorServer. Do you have the
ps-engine package installed? Is there a old process of XnSensorServer hanging
around, try kill it.

Q: I get an error about a closed network connection:

.. note::

  terminate called after throwing an instance of 'pcl::PCLIOException'
  what():  No matching device found. openni_wrapper::OpenNIDevice::OpenNIDevice(xn::Context&, const xn::NodeInfo&, const xn::NodeInfo&, const xn::NodeInfo&, const xn::NodeInfo&) @ /home/andreas/pcl/pcl/trunk/io/src/openni_camera/openni_device.cpp @ 96 : creating depth generator failed. Reason: The network connection has been closed!

A: This error can occur with newer Linux kernels that include the *gspca_kinect* kernel module. The module claims the usb interface of the kinect and prevents OpenNI from doing so.
You can either remove the kernel module (*rmmod gspca_kinect*) or blacklist it (by executing *echo "blacklist gspca_kinect" > /etc/modprobe.d/blacklist-psengine.conf* as root).
The OpenNI Ubuntu packages provided by PCL already include this fix, but you might need it in other distributions.

Conclusion
----------

The Grabber interface is very powerful and general and makes it a breeze to
connect to OpenNI compatible cameras in your code. We are in the process of
writing a FileGrabber which can be used using the same interface, and can e.g.
load all Point Cloud files from a directory and provide them to the callback at
a certain rate. The only change required is
the allocation of the Grabber Object (*pcl::Grabber *g = new ...;*).

If you have a sensor which you would like to have available within PCL, just
let us know at *pcl-developers@pointclouds.org*, and we will figure something
out.


text:
#ifndef _WX_ACCEL_H_
#define _WX_ACCEL_H_

#include "wx/object.h"
#include "wx/string.h"
#include "wx/event.h"

class WXDLLIMPEXP_CORE wxAcceleratorTable: public wxObject
{
    DECLARE_DYNAMIC_CLASS(wxAcceleratorTable)
public:
    wxAcceleratorTable();
    wxAcceleratorTable(const wxString& resource); // Load from .rc resource
    wxAcceleratorTable(int n, const wxAcceleratorEntry entries[]); // Load from array

    virtual ~wxAcceleratorTable();

    bool Ok() const { return IsOk(); }
    bool IsOk() const;

    // Implementation only
    int GetCount() const;
    wxAcceleratorEntry* GetEntries() const;
};

extern WXDLLIMPEXP_DATA_CORE(wxAcceleratorTable) wxNullAcceleratorTable;

#endif
// _WX_ACCEL_H_


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}

module DigitalOcean.Droplet(
  Droplet(..),
  droplets
                           ) where

import Control.Applicative ()
import Control.Monad (liftM, mzero)
import Control.Monad.IO.Class
import Data.Aeson ((.:),  FromJSON(..), Value(..), decode)
import DigitalOcean.Base

-- $setup
-- >>> import System.Environment
-- >>> import DigitalOcean.Base(Authentication(..))
-- >>> import Data.Maybe(isJust)

data Droplet = Droplet {
  did :: Integer,
  dname :: String,
  dmemory :: Integer,
  dvcpus :: Integer,
  disk :: Integer,
  dlocked :: Bool,
  createdAtv2 :: String,
  dstatus :: String,
  backupIds :: [Integer]
} deriving (Show, Read)

newtype Droplets = Droplets [Droplet]

instance FromJSON Droplets where
  parseJSON (Object v) = Droplets <$> v.: "droplets"
  parseJSON _          = mzero

instance FromJSON Droplet where
  parseJSON (Object v) =
    Droplet <$>
    (v .: "id") <*>
    (v .: "name") <*>
    (v .: "memory") <*>
    (v .: "vcpus") <*>
    (v .: "disk") <*>
    (v .: "locked") <*>
    (v .: "created_at") <*>
    (v .: "status") <*>
    (v .: "backup_ids")
  parseJSON _ = mzero

-- | List all Droplets
--
-- @
-- do
--     tkn <- getEnv "DIGITAL_OCEAN_PERSONAL_ACCESS_TOKEN"
--     maybeDroplets <- droplets $ Authentication tkn
--     print $ show $ isJust maybeDroplets
-- @
--
droplets :: Authentication -> (MonadIO m) => m (Maybe [Droplet])
droplets a = liftM toList $ liftM decode (requestGet "droplets?page=1&per_page=100" a)

toList :: Maybe Droplets -> Maybe [Droplet]
toList = \ds ->  case ds of Just(Droplets l) -> Just l
                            Nothing          -> Nothing


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>About | Mirò</title>
        <meta name="description" content="About Mirò musical services">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="author" content="Diego A. Riveros">

        <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,900" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Dosis:300,400,700,800" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="css/entypo.css">

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/slick.css">
        <link rel="stylesheet" href="css/magnific-popup.css">
        <link rel="stylesheet" href="css/main.css">

        <link rel="apple-touch-icon" href="img/icon.png">
        <link rel="icon" type="image/png" href="img/fav.png">

                    Mirò

 FR

                    Toggle navigation
                    <button class="icon icon-menu burger-menu"></button>

Home

About

Contact

Portfolio

Software

Music

                        <hgroup class="title-group">

About

Mirò musical services

                        </hgroup>

                            <hgroup class="title-group text-center">

Who I am

A few words about Mirò

                            </hgroup>

Mirò, formally known as Diego Riveros, is a young artist from Montréal. He does his own music, software and sounds for his own projects. His interest for technology gave an opening of possibilities for the creation of his music with the integration of musical coding. Now, he wants to share his knowledge with your production.

He has trained as a jazz performer and learned how to compose and make musical arrangements at that time. Afterwards, he on got a degree in digital music from the University of Montreal. There, he learned techniques to sound design, field recording, studio recording and software creation.

                            <hgroup class="title-group text-center">

For all your musical needs

With the latest technology

                            </hgroup>

DSP coding

Video games sound integration, plugins, experimental projects. If you have something clear in mind, I can make it happen.

Composing/Producing

In any genre, style or project with the musical background I've been trough, I will be the future architect of your projects.

Mix/Master

Delivernig the best results possible for all your needs. Radio, iTunes, CD Album. It will sound good on any listening platform.

Voice-over

If you need to do the vocals of a singer, for a video, video game or music video.

Live Sound/Recording

If you need sound equipment for your event, a sound engineer or a recording of your live performance.

Sound design

Need a sound bank for your project, for your video game or else. I will deliver with unique sounds that will give your project a boost in quality.

About

Contact

Portfolio

Software

Music

© <time datetime="2016">2016</time> Mirò, All Rights Reserved, by Diego A. Riveros


text:
from .nameregistry import NameRegistry  # noqa
from .readwrite_lock import ReadWriteMutex  # noqa
from .langhelpers import PluginLoader, memoized_property, \
    coerce_string_conf, to_list, KeyReentrantMutex  # noqa


text:
import typing
import argparse

from ..repo import description
from ..repo import implementation
from ..utils import format
from . import Command

class State(Command):
    """ Checks the state of all repositories, and list all those out-of-date"""
    LOCAL = True
    FILTER = True

    def parse(self, *args: str) -> typing.Any:
        """ Parses arguments given to this Command """
        parser = argparse.ArgumentParser(prog='git-manager state')
        parser.add_argument('pattern', nargs='?')

        group = parser.add_mutually_exclusive_group()
        group.add_argument('--update', dest='update',
                           action='store_true', default=True,
                           help='Update remote references using \'git '
                                'remote update\' before showing status. '
                                'Enabled by default.  ')
        group.add_argument('--no-update', dest='update',
                           action='store_false',
                           help='DO NOT update remote references using '
                                '\'git remote update\' '
                                'before showing status. ')

        targs = parser.parse_args(args)
        if targs.pattern:
            super(State, self).parse(targs.pattern)

        return targs

    def run(self, repo: description.RepositoryDescription) -> bool:

        if not repo.local.exists():
            return False

        status = repo.local.remote_status(self.args.update)

        if status == implementation.RemoteStatus.REMOTE_NEWER:
            self.line.linebreak()
            print(format.Format.yellow('Upstream is ahead of your branch, '
                                       'pull required. '))

        elif status == implementation.RemoteStatus.LOCAL_NEWER:
            self.line.linebreak()
            print(format.Format.green('Your branch is ahead of upstream, '
                                      'push required.'))
        elif status == implementation.RemoteStatus.DIVERGENCE:
            self.line.linebreak()
            print(format.Format.red('Your branch and upstream have diverged, '
                                    'merge or rebase required. '))

        return status == implementation.RemoteStatus.UP_TO_DATE


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class battlesys.RandomEventResult (BattleSys Documentation)
</TITLE>

<META NAME="date" CONTENT="2012-10-27">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

NBattleSys Doc

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
battlesys.RandomEventResult

Packages that use RandomEventResult

battlesys

battlesys.analysis

battlesys.playerCtrl23

Uses of RandomEventResult in battlesys

Methods in battlesys with parameters of type RandomEventResult

protected  CompleteMoveResult
Player.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

          Do a player move.

Constructors in battlesys with parameters of type RandomEventResult

RandomEventResult(RandomEventResult r,
                  java.lang.String resultString)

          Constructor setting up the Random Event Result from a given result, only with result string replaced.

Uses of RandomEventResult in battlesys.analysis

Methods in battlesys.analysis with parameters of type RandomEventResult

protected  CompleteMoveResult
AnalysisPlayer.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

Uses of RandomEventResult in battlesys.playerCtrl23

Methods in battlesys.playerCtrl23 with parameters of type RandomEventResult

 CompleteMoveResult
Coolxo1.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

 CompleteMoveResult
Coolxo2.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

 CompleteMoveResult
Donaldli1.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

 CompleteMoveResult
Donaldli2.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

 CompleteMoveResult
StupidBang1.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

 CompleteMoveResult
StupidBang2.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

 CompleteMoveResult
ZhugePeople1.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

 CompleteMoveResult
ZhugePeople2.move(PlayerList thisPlayers,
     PlayerList opposingPlayers,
     int round,
     int battleNo,
     RandomEventResult reResult,
     java.util.List<SingleMoveResult> mResult)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

NBattleSys Doc

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import Enclosing.constants;

class Enclosing {
  static class constants {
    public static final String CONSTANT =  null;
  }
}

class Test {
  void f() {
      String constants = Enclosing.constants.CONSTANT;
      System.out.println(constants);
  }
}


text:
#ifndef __STDLIB_H__
#define __STDLIB_H__

#include <libcgc.h>
#include "malloc.h"

void bzero( void *buff, size_t len );
char *strchr(const char *s, int c);
void int_to_str( int val, char *buf );

char *strtok(char *str, const char *delim);
char *strdup(char *s);
int isspace( int c );
int isdigit( int c );
int isnan( double val );
int isinf( double val );
int tolower( int c );
int toupper( int c );
double atof(const char *str);
int atoi(const char *str);
int abs( int );

void puts(char *str);
int strcmp( char *str1, char *str2 );
char *strcpy( char *dest, char *src );
char *strncpy( char *dest, const char *src, size_t num );
size_t cgc_strlen( const char *str );
int printf( const char *fmt, ... );
int sprintf( char *str, const char *fmt, ... );
size_t getline( char *buffer, size_t len );
size_t receive_until( char *, char, size_t );

void* cgc_memcpy( void *dest, void *src, size_t numbytes );
void* cgc_memset( void *dest, int value, size_t num );

#endif // __STDLIB_H__


text:
import * as ganache from 'ganache-cli'
import Web3 from 'web3'
import { Contract } from 'web3/types'
import Parameterizer from '../../src/contracts/parameterizer'
import { PARAMETERIZER_ABI, ONE_ETHER, ONE_GWEI } from  '../../src/constants'
import { Return } from '../../src/@types'
import {
  deploy,
  readBytecode,
  call,
  transact,
} from '../../src/helpers'

const provider:any = ganache.provider(),
  w3 = new Web3(provider),
  toBN = w3.utils.toBN,
  marketTokenAddress = '0x931D387731bBbC988B312206c74F77D004D6B84b',
  votingAddress = '0x931D387731bBbC988B312206c74F77D004D6B84b'

const priceFloor = w3.utils.toWei('1', 'szabo')
const spread = 110
const listReward = w3.utils.toWei('250', 'szabo')
const stake = w3.utils.toWei('10', 'finney')
const voteBy = 100
const plurality = 50
const backendPayment = 25
const makerPayment = 25
const costPerByte = w3.utils.toWei('100', 'gwei')

let parameterizer:Parameterizer,
  accounts:string[],
  instantiated:boolean,
  deployedParameterizer:Contract

describe('Parameterizer', () => {
  beforeAll(async () => {
    accounts = await w3.eth.getAccounts()

    // deploy Parameterizer
    const parameterizerBin:string = readBytecode('parameterizer')
    deployedParameterizer = await deploy(w3,
                            accounts[0],
                            PARAMETERIZER_ABI,
                            parameterizerBin,
                            [marketTokenAddress,
                              votingAddress,
                              priceFloor,
                              spread,
                              listReward,
                              stake,
                              voteBy,
                              plurality,
                              backendPayment,
                              makerPayment,
                              costPerByte])
    // now we can instantiate the HOC
    parameterizer = new Parameterizer(accounts[0])
    await parameterizer.at(w3, deployedParameterizer.options.address)
  })

  describe('Class methods for Parameterizer', () => {

    it('calls getBackendPayment correctly', async () => {
      const defaults = await parameterizer.getBackendPayment()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getBackendPayment')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getMakerPayment correctly', async () => {
      const defaults = await parameterizer.getMakerPayment()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getMakerPayment')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getReservePayment correctly', async () => {
      const defaults = await parameterizer.getReservePayment()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getReservePayment')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getCostPerByte correctly', async () => {
      const defaults = await parameterizer.getCostPerByte()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getCostPerByte')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getStake correctly', async () => {
      const defaults = await parameterizer.getStake()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getStake')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getPriceFloor correctly', async () => {
      const defaults = await parameterizer.getPriceFloor()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getPriceFloor')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getHash correctly', async () => {
      const defaults = await parameterizer.getHash(2, 42)
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getHash')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getSpread correctly', async () => {
      const defaults = await parameterizer.getSpread()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getSpread')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getListReward correctly', async () => {
      const defaults = await parameterizer.getListReward()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getListReward')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getPlurality correctly', async () => {
      const defaults = await parameterizer.getPlurality()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getPlurality')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getReparam correctly', async () => {
      const defaults = await parameterizer.getReparam('hash')
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getReparam')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls getVoteBy correctly', async () => {
      const defaults = await parameterizer.getVoteBy()
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('getVoteBy')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls reparameterize correctly', async () => {

      // PLURALITY == 6
      const defaults = await parameterizer.reparameterize(6, 51)
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('reparameterize')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })

    it('calls resolveReparam correctly', async () => {
      const defaults = await parameterizer.resolveReparam('hash')
      let tx = defaults[0]
      let opts = defaults[1]
      let gas = parameterizer.getGas('resolveReparam')
      expect(tx).not.toBeNull(accounts[0])
      expect(opts).not.toBeNull()
      expect(Object.keys(opts).indexOf('gas')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('from')).toBeGreaterThan(-1)
      expect(Object.keys(opts).indexOf('gasPrice')).toBeGreaterThan(-1)
      expect(opts['gas']).toBeGreaterThanOrEqual(gas)
      let from = opts['from']
      expect(from).not.toBeNull()
      expect(from!.trim().length).toBeGreaterThan(0)
      let gasPrice = opts['gasPrice']
      expect(gasPrice).not.toBeNull()
      expect(parseInt(gasPrice)).toBeGreaterThan(0)
    })
  })
})


text:
package rapture.dsl.iqry;

public class NumberWhereValue extends WhereValue {
	public NumberWhereValue(String passed) {
        super(Double.valueOf(passed));
	}
}


text:
package org.wso2.carbon.analytics.dashboard.ui.dto;

/**
 * A bean that represents a tabular data format.
 * Used to respond to widget data requests.
 *
 */
public class TableDTO {
    private String name;
    private Object[] data;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object[] getData() {
        return data;
    }

    public void setData(Object[] data) {
        this.data = data;
    }
}


text:
package com.treasure_data.td_import.writer;

import static org.junit.Assert.assertTrue;

import java.util.Properties;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.treasure_data.td_import.Options;
import com.treasure_data.td_import.Configuration;
import com.treasure_data.td_import.prepare.PrepareConfiguration;
import com.treasure_data.td_import.writer.RecordWriter;

public class TestMsgpackGZIPFileWriter {

    protected Properties props;
    protected Options options;
    protected PrepareConfiguration conf;
    protected RecordWriter writer;

    @Before
    public void createResources() throws Exception {
        // create system properties
        props = System.getProperties();
        props.setProperty(Configuration.BI_PREPARE_PARTS_OUTPUTFORMAT,
                Configuration.BI_PREPARE_PARTS_OUTPUTFORMAT_DEFAULTVALUE); // msgpackgz

        // create options
        options = new Options();
        options.initPrepareOptionParser(props);
        options.setOptions(new String[0]);

        // create configuration
        conf = new PrepareConfiguration();
        conf.configure(props, options);

        // create writer
        writer = conf.getOutputFormat().createFileWriter(conf);

    }

    @After
    public void destroyResources() throws Exception {
    }

    @Test
    public void dummy() throws Exception {
        assertTrue(true);
    }
}


text:
const utils = require('../utils');

const BASE_DIR = './src/selectors';
const TEST_DIR = './src/selectors/test';

function generateSelector(args) {
  if (!args[0]) {
    return utils.printError('Invalid number of arguments. Must specify a name for the selector.');
  }

  if (!utils.checkDirectoryExists(BASE_DIR)) {
    return utils.printError(`Cannot find directory for selectors: ${BASE_DIR}`);
  }

  if (!utils.checkDirectoryExists(TEST_DIR)) {
    return utils.printError(`Cannot find directory for selector tests: ${TEST_DIR}`);
  }

  return utils.createFiles(BASE_DIR, [ `${args[0]}.js`, `test/${args[0]}.js` ]);
}

module.exports = {
  description: 'Creates a new selector.',
  alias: 's',
  examples: ['selector MySelector', 's MySelector'],
  fn: generateSelector,
};


text:
/*
 * Legal Notice
 *
 * This document and associated source code (the "Work") is a part of a
 * benchmark specification maintained by the TPC.
 *
 * The TPC reserves all right, title, and interest to the Work as provided
 * under U.S. and international laws, including without limitation all patent
 * and trademark rights therein.
 *
 * No Warranty
 *
 * 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
 *     CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
 *     AUTHORS AND DEVELOPERS OF THE WORK HEREBY DISCLAIM ALL OTHER
 *     WARRANTIES AND CONDITIONS, EITHER EXPRESS, IMPLIED OR STATUTORY,
 *     INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES,
 *     DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR
 *     PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF
 *     WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE.
 *     ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT,
 *     QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT
 *     WITH REGARD TO THE WORK.
 * 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
 *     ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO THE
 *     COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS
 *     OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT,
 *     INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY,
 *     OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT
 *     RELATING TO THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
 *     ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * Contributors
 * - Sergey Vasilevskiy
 */

#include "../inc/EGenUtilities_stdafx.h"    // Windows-specific error file

using namespace TPCE;

CSystemErr::CSystemErr(Action eAction, char const * szLocation)
    : CBaseErr(szLocation)
    , m_eAction(eAction)
{
#ifdef WIN32
    m_idMsg = GetLastError();   //for Windows
#elif (__unix) || (_AIX)
    m_idMsg = errno;    //for Unix
#else
#error No system error routine defined.
#endif
}

CSystemErr::CSystemErr(int iError, Action eAction, char const * szLocation)
    : CBaseErr(szLocation)
    , m_eAction(eAction)
{
    // This constructor is provided for registry functions where the function return code
    // is the error code.
    m_idMsg = iError;
}

const char * CSystemErr::ErrorText() const
{
    return strerror(m_idMsg);
}

const char *CBaseTxnErr::szMsgs[CBaseTxnErr::Last+1] = {
    "Success",
    //Trade Order errors
    "Unauthorized executor",
    "Transaction rolled back",
    "Bad input data",
    "Error code above the range"
};

const char* CBaseTxnErr::ErrorText(int code)
{
    if (code > CBaseTxnErr::Last)
        return szMsgs[CBaseTxnErr::Last];
    else
        return szMsgs[code];
}


text:
package com.google.api.ads.adwords.jaxws.v201406.video;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for StatsSelector.AllTimeRestrict.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="StatsSelector.AllTimeRestrict">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="NONE"/>
 *     <enumeration value="SINCE_VIDEO_AD_START"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "StatsSelector.AllTimeRestrict")
@XmlEnum
public enum StatsSelectorAllTimeRestrict {

    NONE,
    SINCE_VIDEO_AD_START,

    /**
     *
     *                 Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static StatsSelectorAllTimeRestrict fromValue(String v) {
        return valueOf(v);
    }

}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <title>QUnit Test Suite</title>

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


text:
#ifndef __UNSIGNEDINTPACKING_H__
#define __UNSIGNEDINTPACKING_H__

#include "util/array.h"

namespace Resources
{
	class UnsignedIntPacking
	{
	public:
		UnsignedIntPacking(unsigned int valueCount = 0, unsigned int packingBitsCount = 0);

		unsigned int GetValueCount();
		bool SetValueCount(unsigned int valueCount, bool resizeBuffer);

		unsigned int GetPackingBitsCount();
		bool SetPackingBitsCount(unsigned int packingBitsCount, bool resizeBuffer);

		bool Pack(unsigned int inputUnsignedInt);

		Util::Array<unsigned char>& GetBuffer();
	private:
		unsigned int mValueCount;
		unsigned int mPackingBitsCount;
		unsigned int mByteCount;
		unsigned int mNextBitToWrite;
		Util::Array<unsigned char> mBuffer;
	};
}//namespace Resources
#endif//__UNSIGNEDINTPACKING_H__


text:
Workbench.Views.SensorMetadataView = Backbone.Marionette.LayoutView.extend({
  template: "metadata",

  modelEvents: {
    "sensorLoaded": "loadAttributes"
  },

  ui: {
    description: '.sensor-description',
    owner: '.sensor-owner',
    contact: '.sensor-contact',
    otherSensors: '.other-sensors',
    datastreamCount: '.sensor-datastream-count'
  },

  regions: {
    map: "#map"
  },

  initialize: function() {
    this.renderDeferred = $.Deferred();

    var self = this;
    this.listenTo(this.model.get("datastreams"), "add", function() {
      self.renderDeferred.done(function() {
        self.updateDatastreamCount();
      });
    });

    // The element ID MUST be passed into Leaflet, so we use a custom attachment
    // function for the Marionette region.
    this.map.attachHtml = function(view) {
      this.$el.empty();
      view.setElement(this.$el);
    };
  },

  // Animate out, update content, animate back in
  swapContent: function($element, content) {
    $element.transition({ rotateX: '90deg' }).promise().done(function() {
      this.text(content).transition({ rotateX: '0deg' });
    });
  },

  onRender: function() {
    this.renderDeferred.resolve();
    this.ui.otherSensors.prop('href', Backbone.history.root + "sensors?api_key=" + this.model.get('api_key'));
  },

  loadAttributes: function() {
    var self = this;
    this.renderDeferred.done(function() {
      self.swapContent(self.ui.description, self.model.get("description"));
      self.swapContent(self.ui.owner, self.model.get("contact_name"));
      self.swapContent(self.ui.contact, self.model.get("contact_email"));

      self.updateDatastreamCount();

      self.map.show(new Workbench.Views.SensorMapView({
        model: self.model
      }));
    });
  },

  updateDatastreamCount: function() {
    this.swapContent(this.ui.datastreamCount, this.model.get("datastreams").length);
    return this;
  }
});


text:
package config

import (
	"github.com/ngerakines/tram/util"
	"os"
	"path/filepath"
)

func NewDefaultAppConfig() string {
	return buildDefaultConfig(defaultBasePath)
}

func NewDefaultAppConfigWithBaseDirectory(root string) string {
	return buildDefaultConfig(func(section string) string {
		cacheDirectory := filepath.Join(root, ".cache", section)
		os.MkdirAll(cacheDirectory, 00777)
		return cacheDirectory
	})
}

func buildDefaultConfig(basePathFunc basePath) string {
	return `{
   "listen": ":7040",
   "lruSize": 120000,
   "index": {
     "engine": "local",
     "localBasePath": "` + basePathFunc("index") + `"
   },
   "storage": {
      "engine": "local",
      "basePath": "` + basePathFunc("storage") + `"
   }
}`
}

type basePath func(string) string

func defaultBasePath(section string) string {
	cacheDirectory := filepath.Join(util.Cwd(), ".cache", section)
	os.MkdirAll(cacheDirectory, 00777)
	return cacheDirectory
}


text:
		<!-- Javascripts
		================================================== -->
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

		<script src="{{ asset('assets/js/build/production.min.js') }}"></script>

		<script src="{{ asset('assets/js/vendor/angular/angular.js') }}"></script>
		<script src="{{ asset('assets/js/controllers.js') }}"></script>
	</body>
</html>


text:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    GLFrame = new QGLFrame();      // create our subclassed GLWidget
    xSlider = createSlider();
    ySlider = createSlider();
    zSlider = createSlider();

         connect(xSlider, SIGNAL(valueChanged(int)), GLFrame, SLOT(setXRotation(int)));
         connect(GLFrame, SIGNAL(xRotationChanged(int)), xSlider, SLOT(setValue(int)));
         connect(ySlider, SIGNAL(valueChanged(int)), GLFrame, SLOT(setYRotation(int)));
         connect(GLFrame, SIGNAL(yRotationChanged(int)), ySlider, SLOT(setValue(int)));
         connect(zSlider, SIGNAL(valueChanged(int)), GLFrame, SLOT(setZRotation(int)));
         connect(GLFrame, SIGNAL(zRotationChanged(int)), zSlider, SLOT(setValue(int)));

    xSlider->setValue(0);
    ySlider->setValue(0);
    zSlider->setValue(0);

    QWidget *window = new QWidget();
    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(GLFrame);
    mainLayout->addWidget(xSlider);
    mainLayout->addWidget(ySlider);
    mainLayout->addWidget(zSlider);
    window->setLayout(mainLayout);
    setWindowTitle(tr("GPU GEM"));
    setCentralWidget(window);      // assign it to the central widget of the window
    GLFrame->initRenderThread();    // start rendering

}

MainWindow::~MainWindow()
{
    delete GLFrame;
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *evt)
{
    GLFrame->stopRenderThread();    // stop the thread befor exiting
    QMainWindow::closeEvent(evt);
}

QSlider *MainWindow::createSlider()
{
    QSlider *slider = new QSlider(Qt::Vertical);
    slider->setRange(0, 360);
    slider->setSingleStep(1);
    slider->setPageStep(15);
    slider->setTickInterval(15);
    slider->setTickPosition(QSlider::TicksRight);
    return slider;
}


text:
/*

 2008 José Manuel Menéndez Poo
 *
 * Please give me credit if you use this code. It's all I ask.
 *
 * Contact me for more info: menendezpoo@gmail.com
 *
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel;

namespace System.Windows.Forms
{
    [Designer(typeof(RibbonItemGroupDesigner))]
    public class RibbonItemGroup : RibbonItem,
        IContainsSelectableRibbonItems, IContainsRibbonComponents
    {
        #region Fields
        private RibbonItemGroupItemCollection _items;
        private bool _drawBackground;

        #endregion

        #region Ctor
        public RibbonItemGroup()
        {
            _items = new RibbonItemGroupItemCollection(this);
            _drawBackground = true;
        }

        public RibbonItemGroup(IEnumerable<RibbonItem> items)
            : this()
        {
            _items.AddRange(items);
        }
        #endregion

        #region Props

        /// <summary>
        /// Gets or sets a value indicating if the group should
        /// </summary>
        [DefaultValue(true)]
        [Description("Background drawing should be avoided when group contains only TextBoxes and ComboBoxes")]
        public bool DrawBackground
        {
            get { return _drawBackground; }
            set { _drawBackground = value; }
        }

        /// <summary>
        /// Gets the first item of the group
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonItem FirstItem
        {
            get
            {
                if (Items.Count > 0)
                {
                    return Items[0];
                }

                return null;
            }
        }

        /// <summary>
        /// Gets the last item of the group
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonItem LastItem
        {
            get
            {
                if (Items.Count > 0)
                {
                    return Items[Items.Count - 1];
                }

                return null;
            }
        }

        /// <summary>
        /// Gets the collection of items of this group
        /// </summary>
        [DesignerSerializationVisibility( DesignerSerializationVisibility.Content)]
        public RibbonItemGroupItemCollection Items
        {
            get
            {
                return _items;
            }
        }

        #endregion

        #region Methods

        public override void SetBounds(Rectangle bounds)
        {
            base.SetBounds(bounds);

            int curLeft = bounds.Left;

            foreach (RibbonItem item in Items)
            {
                item.SetBounds(new Rectangle(new Point(curLeft, bounds.Top), item.LastMeasuredSize));

                curLeft = item.Bounds.Right + 1;
            }

        }

        public override void OnPaint(object sender, RibbonElementPaintEventArgs e)
        {
            if (DrawBackground)
            {
                Owner.Renderer.OnRenderRibbonItem(new RibbonItemRenderEventArgs(Owner, e.Graphics, e.Clip, this));
            }

            foreach (RibbonItem item in Items)
            {
                item.OnPaint(this, new RibbonElementPaintEventArgs(item.Bounds, e.Graphics, RibbonElementSizeMode.Compact));
            }

            if (DrawBackground)
            {
                Owner.Renderer.OnRenderRibbonItemBorder(new RibbonItemRenderEventArgs(Owner, e.Graphics, e.Clip, this));
            }
        }

        public override Size MeasureSize(object sender, RibbonElementMeasureSizeEventArgs e)
        {
            ///For RibbonItemGroup, size is always compact, and it's designed to be on an horizontal flow
            ///tab panel.
            ///
            int minWidth = 16;
            int widthSum = 0;
            int maxHeight = 16;

            foreach (RibbonItem item in Items)
            {
                Size s = item.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(e.Graphics, RibbonElementSizeMode.Compact));
                widthSum += s.Width + 1;
                maxHeight = Math.Max(maxHeight, s.Height);
            }

            widthSum -= 1;

            widthSum = Math.Max(widthSum, minWidth);

            if (Site != null && Site.DesignMode)
            {
                widthSum += 10;
            }

            Size result = new Size(widthSum, maxHeight);
            SetLastMeasuredSize(result);
            return result;
        }

        /// <param name="ownerPanel">RibbonPanel where this item is located</param>
        internal override void SetOwnerPanel(System.Windows.Forms.RibbonPanel ownerPanel)
        {
            base.SetOwnerPanel(ownerPanel);

            Items.SetOwnerPanel(ownerPanel);
        }

        /// <param name="owner">Ribbon that owns this item</param>
        internal override void SetOwner(System.Windows.Forms.Ribbon owner)
        {
            base.SetOwner(owner);

            Items.SetOwner(owner);
        }

        /// <param name="ownerTab">RibbonTab where this item is located</param>
        internal override void SetOwnerTab(System.Windows.Forms.RibbonTab ownerTab)
        {
            base.SetOwnerTab(ownerTab);

            Items.SetOwnerTab(ownerTab);
        }

        internal override void SetSizeMode(RibbonElementSizeMode sizeMode)
        {
            base.SetSizeMode(sizeMode);

            foreach (RibbonItem item in Items)
            {
                item.SetSizeMode(RibbonElementSizeMode.Compact);
            }
        }

        public override string ToString()
        {
            return "Group: " + Items.Count + " item(s)";
        }
        #endregion

        #region IContainsRibbonItems Members

        public IEnumerable<RibbonItem> GetItems()
        {
            return Items;
        }

        public Rectangle GetContentBounds()
        {
            return Rectangle.FromLTRB(Bounds.Left + 1, Bounds.Top + 1, Bounds.Right - 1, Bounds.Bottom);
        }

        #endregion

        #region IContainsRibbonComponents Members

        public IEnumerable<Component> GetAllChildComponents()
        {
            return Items.ToArray();
        }

        #endregion
    }
}


text:
社团的网站,采用wordpress制作,萌萌哒
表格的代码在:https://github.com/XJTU-ISTC/xjtuistc-website/blob/master/istc/wp-content/themes/accelerate/page-templates/resume.php


text:
Small repository to benchmark different methods to merge weights in a recursive neural net inside crisbal's docker image of jcjohnson's character-level language neural network.

To run:

git clone https://github.com/mattebaughman/nnMergeBenchmark.git

cd nnMergeBenchmark

bash run-docker.sh

sudo apt update

sudo apt install wget

wget https://raw.githubusercontent.com/mattebaughman/nnMergeBenchmark/master/run4.sh

bash run4.sh

This will print inside the docker the results of the four independent runs as they execute.


text:
package gaming.robocop.universe;

import android.graphics.Canvas;

import android.graphics.Canvas;

public class GameLoopThread extends Thread {

       static final long FPS = 10;

       private GameView view;

       private boolean running = false;

       public GameLoopThread(GameView view) {

             this.view = view;

       }

       public void setRunning(boolean run) {

             running = run;

       }

       @Override

       public void run() {

             long ticksPS = 1000 / FPS;

             long startTime;

             long sleepTime;

             while (running) {

                    Canvas c = null;

                    startTime = System.currentTimeMillis();

                    try {

                           c = view.getHolder().lockCanvas();

                           synchronized (view.getHolder()) {

                                  view.onDraw(c);

                           }

                    } finally {

                           if (c != null) {

                                  view.getHolder().unlockCanvasAndPost(c);

                           }

                    }

                    sleepTime = ticksPS-(System.currentTimeMillis() - startTime);

                    try {

                           if (sleepTime > 0)

                                  sleep(sleepTime);

                           else

                                  sleep(10);

                    } catch (Exception e) {}

             }

       }

}


text:
import unittest
import math
import yodel.filter
import yodel.analysis
import yodel.conversion
import yodel.complex

def frequency_response(response):
    size = len(response)
    freq_response_real = [0] * size
    freq_response_imag = [0] * size
    fft = yodel.analysis.FFT(size)
    fft.forward(response, freq_response_real, freq_response_imag)
    return freq_response_real, freq_response_imag

def amplitude_response(spec_real, spec_imag, db=False):
    size = len(spec_real)
    amp = [0] * size
    for i in range(0, size):
        amp[i] = yodel.complex.modulus(spec_real[i], spec_imag[i])
        if db:
            amp[i] = yodel.conversion.lin2db(amp[i])
    return amp

class TestCustomFilter(unittest.TestCase):

    def setUp(self):
        self.samplerate = 48000
        self.framesize = 512
        self.flt = yodel.filter.Custom(self.samplerate, self.framesize)

    def test_default(self):
        insignal = [math.sin(2.0*math.pi*100.0*i/self.samplerate) for i in range(0, self.framesize)]
        outsignal = [0] * self.framesize

        self.flt.process(insignal, outsignal)

        fr_real, fr_imag = frequency_response(self.flt.ir)
        ampl = amplitude_response(fr_real, fr_imag)

        for i in range(0, len(ampl)):
            self.assertAlmostEqual(1, ampl[i], delta=1e-3)

        for i in range(0, self.flt.latency+1):
            self.assertAlmostEqual(0, outsignal[i])

        for i in range(self.flt.latency+1, self.framesize):
            self.assertAlmostEqual(insignal[i-self.flt.latency-1], outsignal[i], delta=1e-3)

    def test_flat(self):
        insignal = [math.sin(2.0*math.pi*100.0*i/self.samplerate) for i in range(0, self.framesize)]
        outsignal = [0] * self.framesize
        flatresp = [1] * int((self.framesize/2)+1)

        self.flt.design(flatresp, db=False)
        self.flt.process(insignal, outsignal)

        fr_real, fr_imag = frequency_response(self.flt.ir)
        ampl = amplitude_response(fr_real, fr_imag)

        for i in range(0, len(ampl)):
            self.assertAlmostEqual(1, ampl[i], delta=1e-3)

        for i in range(0, self.flt.latency+1):
            self.assertAlmostEqual(0, outsignal[i])

        for i in range(self.flt.latency+1, self.framesize):
            self.assertAlmostEqual(insignal[i-self.flt.latency-1], outsignal[i], delta=1e-3)

    def test_flat_db(self):
        insignal = [math.sin(2.0*math.pi*100.0*i/self.samplerate) for i in range(0, self.framesize)]
        outsignal = [0] * self.framesize
        flatresp = [0] * int((self.framesize/2)+1)

        self.flt.design(flatresp, db=True)
        self.flt.process(insignal, outsignal)

        fr_real, fr_imag = frequency_response(self.flt.ir)
        ampl = amplitude_response(fr_real, fr_imag)

        for i in range(0, len(ampl)):
            self.assertAlmostEqual(1, ampl[i], delta=1e-3)

        for i in range(0, self.flt.latency+1):
            self.assertAlmostEqual(0, outsignal[i])

        for i in range(self.flt.latency+1, self.framesize):
            self.assertAlmostEqual(insignal[i-self.flt.latency-1], outsignal[i], delta=1e-3)

    def test_total_cancellation(self):
        insignal = [math.sin(2.0*math.pi*100.0*i/self.samplerate) for i in range(0, self.framesize)]
        outsignal = [0] * self.framesize
        flatresp = [0] * int((self.framesize/2)+1)

        self.flt.design(flatresp, db=False)
        self.flt.process(insignal, outsignal)

        fr_real, fr_imag = frequency_response(self.flt.ir)
        ampl = amplitude_response(fr_real, fr_imag)

        for i in range(0, len(ampl)):
            self.assertAlmostEqual(0, ampl[i], delta=1e-3)

        for i in range(0, self.framesize):
            self.assertAlmostEqual(0, outsignal[i])

if __name__ == '__main__':
    unittest.main()