text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2013 Christian Seiler <christian@iwakd.de>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_CXX11WORKAROUNDS_H
#define EIGEN_CXX11WORKAROUNDS_H

/* COMPATIBILITY CHECKS
 * (so users of compilers that are too old get some realistic error messages)
 */
#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER < 1310)
#error Intel Compiler only supports required C++ features since version 13.1.
// note that most stuff in principle works with 13.0 but when combining
// some features, at some point 13.0 will just fail with an internal assertion
#elif defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6))
// G++ < 4.6 by default will continue processing the source files - even if we use #error to make
// it error out. For this reason, we use the pragma to make sure G++ aborts at the first error
// it sees. Unfortunately, that is still not our #error directive, but at least the output is
// short enough the user has a chance to see that the compiler version is not sufficient for
// the funky template mojo we use.
#pragma GCC diagnostic error "-Wfatal-errors"
#error GNU C++ Compiler (g++) only supports required C++ features since version 4.6.
#endif

/* Check that the compiler at least claims to support C++11. It might not be sufficient
 * because the compiler may not implement it correctly, but at least we'll know.
 */
#if __cplusplus <= 199711L
#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
#pragma GCC diagnostic error "-Wfatal-errors"
#endif
#error This library needs at least a C++11 compliant compiler. If you use g++/clang, please enable the -std=c++11 compiler flag. (-std=c++0x on older versions.)
#endif

namespace Eigen {

namespace internal {

/* std::get is only constexpr in C++14, not yet in C++11
 */

template<std::size_t I, class T> constexpr inline T&       array_get(std::vector<T>&       a) { return a[I]; }
template<std::size_t I, class T> constexpr inline T&&      array_get(std::vector<T>&&      a) { return a[I]; }
template<std::size_t I, class T> constexpr inline T const& array_get(std::vector<T> const& a) { return a[I]; }

/* Suppose you have a template of the form
 * template<typename T> struct X;
 * And you want to specialize it in such a way:
 *    template<typename S1, typename... SN> struct X<Foo<S1, SN...>> { ::: };
 *    template<>                            struct X<Foo<>>          { ::: };
 * This will work in Intel's compiler 13.0, but only to some extent in g++ 4.6, since
 * g++ can only match templates called with parameter packs if the number of template
 * arguments is not a fixed size (so inside the first specialization, referencing
 * X<Foo<Sn...>> will fail in g++). On the other hand, g++ will accept the following:
 *    template<typename S...> struct X<Foo<S...>> { ::: }:
 * as an additional (!) specialization, which will then only match the empty case.
 * But Intel's compiler 13.0 won't accept that, it will only accept the empty syntax,
 * so we have to create a workaround for this.
 */
#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
#define EIGEN_TPL_PP_SPEC_HACK_DEF(mt, n)    mt... n
#define EIGEN_TPL_PP_SPEC_HACK_DEFC(mt, n)   , EIGEN_TPL_PP_SPEC_HACK_DEF(mt, n)
#define EIGEN_TPL_PP_SPEC_HACK_USE(n)        n...
#define EIGEN_TPL_PP_SPEC_HACK_USEC(n)       , n...
#else
#define EIGEN_TPL_PP_SPEC_HACK_DEF(mt, n)
#define EIGEN_TPL_PP_SPEC_HACK_DEFC(mt, n)
#define EIGEN_TPL_PP_SPEC_HACK_USE(n)
#define EIGEN_TPL_PP_SPEC_HACK_USEC(n)
#endif

} // end namespace internal

} // end namespace Eigen

#endif // EIGEN_CXX11WORKAROUNDS_H

/*
 * kate: space-indent on; indent-width 2; mixedindent off; indent-mode cstyle;
 */


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class T_document_model extends MY_Model
{

    public $table = 't_document';
    public $primary_key = 'id';
    public $label = 'id';
    public $fillable = array(); // If you want, you can set an array with the fields that can be filled by insert/update
    public $protected = array('id'); // ...Or you can set an array with the fields that cannot be filled by insert/update

    function __construct()
    {
        parent::__construct();
        $this->soft_deletes = TRUE;
        $this->has_one['m_customer'] = array('M_customer_model','customer_id','customer_id');
        $this->has_one['m_dokument'] = array('M_dokument_model','document_id','document_id');
    }

    // get total rows
    function get_limit_data($limit, $start) {
        $order            = $this->input->post('order');
        $dataorder = array();
        $where = array();

        $i=1;
        $dataorder[$i++] = 'document_id';
        $dataorder[$i++] = 'customer_id';
        $dataorder[$i++] = 'quantity';
        if(!empty($this->input->post('document_id')))
        {
            $where['document_id'] = $this->input->post('document_id');
        }
        if(!empty($this->input->post('customer_id')))
        {
            $where['customer_id'] = $this->input->post('customer_id');
        }
        if(!empty($this->input->post('quantity')))
        {
            $where['LOWER(quantity) LIKE'] = '%'.strtolower($this->input->post('quantity')).'%';
        }

        $this->where($where);
        $result['total_rows'] = $this->count_rows();

        $this->where($where);
        $this->order_by( $dataorder[$order[0]["column"]],  $order[0]["dir"]);
        $this->limit($start, $limit);
        $result['get_db']=$this
                            ->with_m_customer()
                            ->with_m_dokument()
                            ->get_all();
        return $result;
    }

}

/* End of file T_document_model.php */
/* Location: ./application/models/T_document_model.php */
/* Please DO NOT modify this information : */
/* http://harviacode.com */

redpajama_set_name: RedPajamaGithub


text: A command line program to convert P\-S\-D files to P\-N\-G


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <meta property="og:title" content="Auto-CMS | Template" />
  <meta property="og:site_name" content="Auto CMS Template"/>
  <meta property="og:url" content="http://auto-cms.com/" />
  <meta property="og:description" content="This tool allows you to create a content management system from HTML, CSS, and Javascript, without knowing back end programing." />
  <meta property="og:type" content="website" />
  <meta property="og:image" content="" />

  <title>Auto-CMS | Template</title>

  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

  <link href="/assets/css/common.css" rel="stylesheet">

  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Auto-CMS.com

          Blog

          About Me

Auto CMS Blog

A Blog About Auto CMS's Features

            Man must explore, and this is exploration at its greatest

            Problems look mighty small from 150 miles up

Some date

Copyright © Auto-CMS.com 2015


text:
package jp.kshoji.javax.sound.midi.spi;

import android.support.annotation.NonNull;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import jp.kshoji.javax.sound.midi.Sequence;

/**
 * Abstract class for MIDI File Writer
 *
 * @author K.Shoji
 */
public abstract class MidiFileWriter {

    /**
     * Get the all of the file types ID
     *
     * @return the array of file type
     */
    @NonNull
    public abstract int[] getMidiFileTypes();

    /**
     * Get the all of the file types ID on the specified {@link Sequence}
     *
     * @param sequence the sequence
     * @return the array of file type
     */
    @NonNull
    public abstract int[] getMidiFileTypes(@NonNull Sequence sequence);

    /**
     * Check if the specified file type is supported
     *
     * @param fileType the file type
     * @return true if the specified file type is supported
     */
	public boolean isFileTypeSupported(int fileType) {
		int[] supported = getMidiFileTypes();
		for (int element : supported) {
			if (fileType == element) {
				return true;
			}
		}
		return false;
	}

    /**
     * Check if the specified file type is supported on the specified {@link Sequence}
     *
     * @param fileType the file type
     * @param sequence the sequence
     * @return true if the specified file type is supported on the sequence
     */
	public boolean isFileTypeSupported(int fileType, @NonNull Sequence sequence) {
		int[] supported = getMidiFileTypes(sequence);
		for (int element : supported) {
			if (fileType == element) {
				return true;
			}
		}
		return false;
	}

    /**
     * Write the {@link Sequence} to the {@link File} with the file type
     *
     * @param sequence the sequence
     * @param fileType the file type
     * @param file the file
     * @return the written data length
     * @throws IOException
     */
	public abstract int write(@NonNull Sequence sequence, int fileType, @NonNull File file) throws IOException;

    /**
     * Write the {@link Sequence} to the {@link OutputStream} with the file type
     *
     * @param sequence the sequence
     * @param fileType the file type
     * @param outputStream the OutputStream
     * @return the written data length
     * @throws IOException
     */
	public abstract int write(@NonNull Sequence sequence, int fileType, @NonNull OutputStream outputStream) throws IOException;
}


text:
namespace monik { namespace AmqpClient { namespace Detail {

bool value_t::operator == (value_t const & v) const
{
    M_STATIC_ASSERT_IS_POD(value_t::union_t);
    MONIK_ASSERT(kind != TableValue::VT_void);
    MONIK_ASSERT(v.kind != TableValue::VT_void);
    if (kind != v.kind) return false;
    switch(kind) {
    case TableValue::VT_bool:      return (variant.boolean == v.variant.boolean);
    case TableValue::VT_int8:      return (variant.i8 == v.variant.i8);
    case TableValue::VT_int16:     return (variant.i16 == v.variant.i16);
    case TableValue::VT_int32:     return (variant.i32 == v.variant.i32);
    case TableValue::VT_int64:     return (variant.i64 == v.variant.i64);
    case TableValue::VT_float:     return (variant.f32 == v.variant.f32);
    case TableValue::VT_double:    return (variant.f64 == v.variant.f64);
    case TableValue::VT_string:    return (string_ == v.string_);
    case TableValue::VT_array:     return (array_ == v.array_);
    case TableValue::VT_table:     return (table_ == v.table_);
    default:
        MONIK_ASSERT(0);
        return false;
    }
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const void_t) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_VOID;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const bool value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_BOOLEAN;
  v.value.boolean = value;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const std::int8_t value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_I8;
  v.value.i8 = value;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const std::int16_t value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_I16;
  v.value.i16 = value;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const std::int32_t value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_I32;
  v.value.i32 = value;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const std::int64_t value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_I64;
  v.value.i64 = value;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const float value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_F32;
  v.value.f32 = value;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const double value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_F64;
  v.value.f64 = value;
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const std::string &value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_UTF8;
  amqp_pool_alloc_bytes(&pool, value.size(), &v.value.bytes);
  memcpy(v.value.bytes.bytes, value.data(), v.value.bytes.len);
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const value_t& value) const
{
    MONIK_ASSERT(value.kind != TableValue::VT_void);
    switch(value.kind) {
    case TableValue::VT_bool:      return operator()(value.variant.boolean);
    case TableValue::VT_int8:      return operator()(value.variant.i8);
    case TableValue::VT_int16:     return operator()(value.variant.i16);
    case TableValue::VT_int32:     return operator()(value.variant.i32);
    case TableValue::VT_int64:     return operator()(value.variant.i64);
    case TableValue::VT_float:     return operator()(value.variant.f32);
    case TableValue::VT_double:    return operator()(value.variant.f64);
    case TableValue::VT_string:    return operator()(value.string_);
    case TableValue::VT_array:     return operator()(value.array_);
    case TableValue::VT_table:     return operator()(value.table_);
    default:
        MONIK_ASSERT(0);
        return{};
    }
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const array_t &value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_ARRAY;
  v.value.array.num_entries = value.size();
  v.value.array.entries = (amqp_field_value_t *)amqp_pool_alloc(
      &pool, sizeof(amqp_field_value_t) * value.size());
  if (NULL == v.value.array.entries) {
    throw std::bad_alloc();
  }

  amqp_field_value_t *output_iterator = v.value.array.entries;
  for (array_t::const_iterator it = value.begin(); it != value.end(); ++it, ++output_iterator) {
    *output_iterator = generate_field_value(pool)(it->m_impl->m_value);
  }
  return v;
}

amqp_field_value_t TableValueImpl::generate_field_value::operator()(
    const Table &value) const {
  amqp_field_value_t v;
  v.kind = AMQP_FIELD_KIND_TABLE;
  v.value.table = CreateAmqpTableInner(value, pool);
  return v;
}

void free_pool(amqp_pool_t *pool) {
  empty_amqp_pool(pool);
  delete pool;
}

amqp_table_t TableValueImpl::CreateAmqpTable(const Table &table,
                                             amqp_pool_ptr_t &pool) {
  if (0 == table.size()) {
    return AMQP_EMPTY_TABLE;
  }

  pool = std::shared_ptr<amqp_pool_t>(new amqp_pool_t, free_pool);
  init_amqp_pool(pool.get(), 1024);

  return CreateAmqpTableInner(table, *pool.get());
}

amqp_table_t TableValueImpl::CreateAmqpTableInner(const Table &table,
                                                  amqp_pool_t &pool) {
  amqp_table_t new_table;

  new_table.num_entries = table.size();

  new_table.entries = (amqp_table_entry_t *)amqp_pool_alloc(
      &pool, sizeof(amqp_table_entry_t) * table.size());

  if (NULL == new_table.entries) {
    throw std::bad_alloc();
  }

  amqp_table_entry_t *output_it = new_table.entries;

  for (Table::const_iterator it = table.begin(); it != table.end();
       ++it, ++output_it) {
    amqp_pool_alloc_bytes(&pool, it->first.size(), &output_it->key);
    if (NULL == output_it->key.bytes) {
      throw std::bad_alloc();
    }

    std::copy(it->first.begin(), it->first.end(), (char *)output_it->key.bytes);
    output_it->value = TableValueImpl::generate_field_value(pool)(it->second.m_impl->m_value);
  }

  return new_table;
}

Table TableValueImpl::CreateTable(const amqp_table_t &table) {
  Table new_table;

  for (int i = 0; i < table.num_entries; ++i) {
    amqp_table_entry_t *entry = &table.entries[i];

    std::string key((char *)entry->key.bytes, entry->key.len);

    new_table.insert(TableEntry(key, CreateTableValue(entry->value)));
  }
  return new_table;
}

TableValue TableValueImpl::CreateTableValue(const amqp_field_value_t &entry) {
  switch (entry.kind) {
    case AMQP_FIELD_KIND_VOID:
      return TableValue();
    case AMQP_FIELD_KIND_BOOLEAN:
      return TableValue((bool)entry.value.boolean);
    case AMQP_FIELD_KIND_I8:
      return TableValue(entry.value.i8);
    case AMQP_FIELD_KIND_I16:
      return TableValue(entry.value.i16);
    case AMQP_FIELD_KIND_I32:
      return TableValue(entry.value.i32);
    case AMQP_FIELD_KIND_I64:
    case AMQP_FIELD_KIND_TIMESTAMP:
      return TableValue(entry.value.i64);
    case AMQP_FIELD_KIND_F32:
      return TableValue(entry.value.f32);
    case AMQP_FIELD_KIND_F64:
      return TableValue(entry.value.f64);
    case AMQP_FIELD_KIND_UTF8:
    case AMQP_FIELD_KIND_BYTES:
      return TableValue(
          std::string((char *)entry.value.bytes.bytes, entry.value.bytes.len));
    case AMQP_FIELD_KIND_ARRAY: {
      amqp_array_t array = entry.value.array;
      Detail::array_t new_array;

      for (int i = 0; i < array.num_entries; ++i) {
        new_array.push_back(CreateTableValue(array.entries[i]));
      }

      return TableValue(new_array);
    }
    case AMQP_FIELD_KIND_TABLE:
      return TableValue(CreateTable(entry.value.table));
    case AMQP_FIELD_KIND_DECIMAL:
    default:
      return TableValue();
  }
}

amqp_table_t TableValueImpl::CopyTable(const amqp_table_t &table,
                                       amqp_pool_ptr_t &pool) {
  if (0 == table.num_entries) {
    return AMQP_EMPTY_TABLE;
  }

  pool = std::shared_ptr<amqp_pool_t>(new amqp_pool_t, free_pool);
  init_amqp_pool(pool.get(), 1024);

  return CopyTableInner(table, *pool.get());
}

amqp_table_t TableValueImpl::CopyTableInner(const amqp_table_t &table,
                                            amqp_pool_t &pool) {
  amqp_table_t new_table;

  new_table.num_entries = table.num_entries;
  new_table.entries = (amqp_table_entry_t *)amqp_pool_alloc(
      &pool, sizeof(amqp_table_entry_t) * table.num_entries);
  if (NULL == new_table.entries) {
    throw std::bad_alloc();
  }

  for (int i = 0; i < table.num_entries; ++i) {
    amqp_table_entry_t *entry = &new_table.entries[i];
    amqp_pool_alloc_bytes(&pool, table.entries[i].key.len, &entry->key);

    if (NULL == entry->key.bytes) {
      throw std::bad_alloc();
    }
    memcpy(entry->key.bytes, table.entries[i].key.bytes, entry->key.len);

    entry->value = CopyValue(table.entries[i].value, pool);
  }

  return new_table;
}

amqp_field_value_t TableValueImpl::CopyValue(const amqp_field_value_t value,
                                             amqp_pool_t &pool) {
  amqp_field_value_t new_value = value;

  switch (value.kind) {
    case AMQP_FIELD_KIND_UTF8:
    case AMQP_FIELD_KIND_BYTES:
      amqp_pool_alloc_bytes(&pool, value.value.bytes.len,
                            &new_value.value.bytes);
      memcpy(new_value.value.bytes.bytes, value.value.bytes.bytes,
             value.value.bytes.len);
      return new_value;
    case AMQP_FIELD_KIND_ARRAY: {
      new_value.value.array.entries = (amqp_field_value_t *)amqp_pool_alloc(
          &pool, sizeof(amqp_field_value_t) * value.value.array.num_entries);
      for (int i = 0; i < value.value.array.num_entries; ++i) {
        new_value.value.array.entries[i] =
            CopyValue(value.value.array.entries[i], pool);
      }
      return new_value;
    }
    case AMQP_FIELD_KIND_TABLE:
      new_value.value.table = CopyTableInner(value.value.table, pool);
      return new_value;
    default:
      return new_value;
  }
}
}
}}  // AmqpClient


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ripple="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:text="Url validation & Ripple effect"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/etValidation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="30dp"
        android:hint="Enter text"
        android:inputType="textUri"
        android:singleLine="true" />

    <com.andexert.library.RippleView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ripple="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        ripple:rv_centered="false">

        <Button
            android:id="@+id/btnEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="#2050aa"
            android:padding="15dp"
            android:text="Url validation"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/white" />
    </com.andexert.library.RippleView>
</LinearLayout>
<!-- From: file:/F:/Workspace/CommonSDK/Multidots/android/utils/src/main/res/layout/activity_url_ripple.xml -->


text:
Configs and such. Commands here can be from the repo directory to set stuff up.

  1. Switch to zsh

  ```
  zsh
  chsh -s /bin/zsh
  ```

  2. Clone the repo

  ```
  git clone --recursive https://github.com/lendle/dotfiles.git $HOME/dotfiles
  ```

  3. Setup prezto

  ```
  ln -s $HOME/dotfiles/prezto .zprezto
  ```

  4. Setup configs

  ```
  for rcfile in $HOME/dotfiles/zsh/*; do
    ln -s "$rcfile" "$HOME/.${rcfile:t}"
  done

  touch $HOME/.zprofile.local
  touch $HOME/.zshenv.local
  touch $HOME/.zshrc.local
  ```

  5. Make any machine specific changes to `~/.z*.local`


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// AntProdpaasProductCommonQueryModel Data Structure.
    /// </summary>
    [Serializable]
    public class AntProdpaasProductCommonQueryModel : AopObject
    {
        /// <summary>
        /// 产品码
        /// </summary>
        [XmlElement("product_code")]
        public string ProductCode { get; set; }

        /// <summary>
        /// 产品查询维度,主要分为基础信息,条件信息和产品关联关系信息等
        /// </summary>
        [XmlElement("product_options")]
        public ProductVOOptions ProductOptions { get; set; }

        /// <summary>
        /// 产品版本
        /// </summary>
        [XmlElement("product_version")]
        public string ProductVersion { get; set; }
    }
}


text:
import inspect as _inspect
import sys
from .. import pb as _pb
from ._xabsl import XABSLSymbols

# get all protobuf classes
_proto = {}
for _m in _inspect.getmembers(_pb, _inspect.ismodule):
    for _c in _inspect.getmembers(_m[1], _inspect.isclass):
        if not _c[0].startswith('_'):
            _proto[_c[0]] = _c[1]

class Parser:
    def __init__(self):
        self.nameToType = {}

    def register(self, name, type):
        self.nameToType[name] = type

    def parse(self, name, data):
        message = None

        if name in self.nameToType:
            name = self.nameToType[name]

        if name in _proto:
            message = _proto[name]()

        if message is not None:
            message.ParseFromString(data)

        return message

class BehaviorParser:
    def __init__(self, data=None):

        self.parser = Parser()
        self.symbols = XABSLSymbols()
        self.__options = None
        self.__current_options = None

        self.init(data)

    def init(self, data):
        if data is not None:
            # check given data
            if data == b'unknown representation\n':
                raise Exception('Unknown representation')

            message = self.parser.parse('BehaviorStateComplete', data)

            # initialize options
            self.__options = message.options

            # initialize symbols
            for s in message.inputSymbolList.decimal:
                self.symbols.values[s.name] = s.value
                self.symbols.decimalIdToName[s.id] = s.name

            for s in message.inputSymbolList.boolean:
                self.symbols.values[s.name] = s.value
                self.symbols.booleanIdToName[s.id] = s.name

            for s in message.inputSymbolList.enumerated:
                self.symbols.values[s.name] = s.value
                self.symbols.enumIdToName[s.id] = s.name

            return message

    def __check_initialized(self):
        if self.__options is None:
            # print(" BehaviorParser must be initialized with 'BehaviorStateComplete' data! -> Running Init")
            return False

        return True

    def parse(self, name, data):
        if not self.__check_initialized() and name == "BehaviorStateComplete":
            message = self.init(data)

            return (message, self.__current_options, self.symbols)
        elif name == "BehaviorStateSparse":
            self.__current_options = {}

            message = self.parser.parse("BehaviorStateSparse", data)

            # process active options
            for o in message.activeRootActions:
                self.__parseOption(o)

            # process symbols
            for s in message.inputSymbolList.decimal:
                self.symbols.decimal(s.id, s.value)

            for s in message.inputSymbolList.boolean:
                self.symbols.boolean(s.id, s.value)

            for s in message.inputSymbolList.enumerated:
                self.symbols.enum(s.id, s.value)

            return (message, self.__current_options, self.symbols)
        else:
            return(self.parser.parse(name, data))

    def __parseOption(self, o):
        if o.type == 0:  # Option
            optionComplete = self.__options[o.option.id]
            self.__current_options[optionComplete.name] = {
                'time': o.option.timeOfExecution,
                'state': optionComplete.states[o.option.activeState],
                'stateTime': o.option.stateTime
            }

            for so in o.option.activeSubActions:
                self.__parseOption(so)

    def getActiveOptions(self):
        return list(self.__current_options.keys())

    def isActiveOption(self, option):
        return option in self.__current_options

    def getActiveStates(self):
        return [s['state'].name for s in self.__current_options.values()]

    def getActiveOptionState(self, option):
        if option in self.__current_options:
            return self.__current_options[option]['state'].name

    def __str__(self):
        # TODO: how to represent the options?!
        result = str(self.symbols) + ',\n[\n'
        if self.__current_options:
            for o in self.__current_options:
                result += '\t{} [{} ms] - {} [{} ms]\n'.format(o, self.__current_options[o]['time'],
                                                               self.__current_options[o]['state'].name,
                                                               self.__current_options[o]['stateTime'])
        result += ']'

        return result


text:
using System.Buffers;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Connections;
using Newtonsoft.Json;

namespace ITGlobal.MarkDocs.Tools.Serve.Controllers
{
    public sealed class DevConnectionManager
    {
        private readonly object _connectionsLock = new object();
        private readonly List<ConnectionContext> _connections = new List<ConnectionContext>();

        public void OnConnectedAsync(ConnectionContext connection)
        {
            lock (_connectionsLock)
            {
                _connections.Add(connection);
            }
        }

        public void OnDisconnectedAsync(ConnectionContext connection)
        {
            lock (_connectionsLock)
            {
                _connections.Remove(connection);
            }
        }

        public void Publish<T>(T data)
        {
            lock (_connectionsLock)
            {
                if (_connections.Count == 0)
                {
                    return;
                }

                var buffer = Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(data)
                );

                foreach (var connection in _connections)
                {
                    connection.Transport.Output.Write(buffer);
                    connection.Transport.Output.FlushAsync().GetAwaiter().GetResult();
                }
            }
        }
    }
}


text:
using System;
using NUnit.Framework;

namespace DotSpatial.Projections.Tests
{
    [TestFixture]
    class ReprojectTests
    {
        [Test]
        public void ReprojectPointsWithOtherRanging()
        {
            var geographic = ProjectionInfo.FromProj4String(KnownCoordinateSystems.Geographic.World.WGS1984.ToProj4String());
            var projected = ProjectionInfo.FromProj4String(KnownCoordinateSystems.Projected.World.WebMercator.ToProj4String());
            geographic.Over = true;
            projected.Over = true;
            double[] pointsXY = { -445, 33 };
            double[] pointsXYCopy = { -445, 33 };
            double[] pointsZ = { 0 };
            Reproject.ReprojectPoints(pointsXY, pointsZ, geographic, projected, 0, 1);
            Reproject.ReprojectPoints(pointsXY, pointsZ, projected, geographic, 0, 1);
            Assert.IsTrue(Math.Abs(pointsXY[0] - pointsXYCopy[0]) < 0.00000000001);
            Assert.IsTrue(Math.Abs(pointsXY[1] - pointsXYCopy[1]) < 0.00000000001);
        }

        [Test(Description = "Checks that reprojection for group works the same as reprojection for one point. (https://github.com/DotSpatial/DotSpatial/issues/781)")]
        public void Reprojection_NorthPoleStereographic_ForGroupTheSameAsForOnePoint()
        {
            var wgs = KnownCoordinateSystems.Geographic.World.WGS1984;
            var wgs84Points = new double[] { 10, 10, 45, 45, 80, 80 };

            const double DELTA = double.Epsilon;

            var projectionInfo = KnownCoordinateSystems.Projected.Polar.NorthPoleStereographic;
            var testProjectionPoints = new double[wgs84Points.Length];
            Array.Copy(wgs84Points, testProjectionPoints, testProjectionPoints.Length);
            Reproject.ReprojectPoints(testProjectionPoints, null, wgs, projectionInfo, 0, testProjectionPoints.Length / 2);

            var backWgs84 = new double[testProjectionPoints.Length];
            Array.Copy(testProjectionPoints, backWgs84, backWgs84.Length);

            // Reproject group from projectionInfo to wgs
            Reproject.ReprojectPoints(backWgs84, null, projectionInfo, wgs, 0, backWgs84.Length / 2);

            // Now reproject each point separately and verify that it is same as in group reprojection
            for (int i = 0; i < testProjectionPoints.Length / 2; i++)
            {
                var onePoint = new double[2];
                onePoint[0] = testProjectionPoints[i * 2];
                onePoint[1] = testProjectionPoints[i * 2 + 1];

                Reproject.ReprojectPoints(onePoint, null, projectionInfo, wgs, 0, 1);

                Assert.AreEqual(onePoint[0], backWgs84[i * 2], DELTA);
                Assert.AreEqual(onePoint[1], backWgs84[i * 2 + 1], DELTA);
            }
        }

        [Test(Description = "Checks that there is no NANs in output for LAEA projections (https://github.com/DotSpatial/DotSpatial/issues/387)")]
        public void LAEA_Reprojection_NoNANs()
        {
            var source = ProjectionInfo.FromProj4String("proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
            // Any LAEA projection
            var dest = ProjectionInfo.FromProj4String("+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +datum=WGS84");

            double[] vertices = { 13.5, 51.3 };
            Reproject.ReprojectPoints(vertices, null, source, dest, 0, 1);

            Assert.IsTrue(!double.IsNaN(vertices[0]));
            Assert.IsTrue(!double.IsNaN(vertices[1]));
        }

        [Test(Description = "Verifies OSGB36 reprojection. (https://github.com/DotSpatial/DotSpatial/issues/732")]
        public void OSGB36_Reprojection()
        {
            var sourceProjection = ProjectionInfo.FromAuthorityCode("EPSG", 27700);
            var targetProjection = ProjectionInfo.FromAuthorityCode("EPSG", 4326);
            var xy = new double[] { 465000, 170000 };
            Reproject.ReprojectPoints(xy, null, sourceProjection, targetProjection, 0, 1);

            // see http://www.ordnancesurvey.co.uk/gps/transformation
            const double expectedX = -1.066488;
            const double expectedY = 51.425291;
            const double eps = 0.0001;
            Assert.AreEqual(expectedX, xy[0], eps);
            Assert.AreEqual(expectedY, xy[1], eps);
        }

        [TestCase(3021, 3006, new double[] { 1366152.968, 6851307.390 }, new double[] { 408700, 6847800 }, 0.08)] // tolerance 8 cm
        [TestCase(3006, 3021, new double[] { 408700, 6847800 }, new double[] { 1366152.968, 6851307.390 }, 0.08)] // tolerance 8 cm
        [TestCase(3013, 3006, new double[] { 19061.000, 6851822.032 }, new double[] { 408700, 6847800 }, 1E-3)] // tolerance 1 mm
        [TestCase(3022, 3021, new double[] { 1536875.736, 7037950.238 }, new double[] { 1649079.352, 7041217.283 }, 1E-3)] // tolerance 1 mm
        public void Reproject_Swedish_Projections_Using_AuthorityCodes(int fromEpsgCode, int toEpsgCode, double[] xy, double[] expected, double tolerance )
        {
            var sourceProjection = ProjectionInfo.FromAuthorityCode("EPSG", fromEpsgCode);
            var targetProjection = ProjectionInfo.FromAuthorityCode("EPSG", toEpsgCode);
            Reproject.ReprojectPoints(xy, null, sourceProjection, targetProjection, 0, 1);
            Assert.AreEqual(expected[0], xy[0], tolerance);
            Assert.AreEqual(expected[1], xy[1], tolerance);
        }

        [TestCase(3021, 3006, new double[] { 1366152.968, 6851307.390 }, new double[] { 408700, 6847800 }, 0.08)] // tolerance 8 cm
        [TestCase(3006, 3021, new double[] { 408700, 6847800 }, new double[] { 1366152.968, 6851307.390 }, 0.08)] // tolerance 8 cm
        [TestCase(3013, 3006, new double[] { 19061.000, 6851822.032 }, new double[] { 408700, 6847800 }, 1E-3)] // tolerance 1 mm
        [TestCase(3022, 3021, new double[] { 1536875.736, 7037950.238 }, new double[] { 1649079.352, 7041217.283 }, 1E-3)] // tolerance 1 mm
        public void Reproject_Swedish_Projections_Using_KnownCrsNames(int fromEpsgCode, int toEpsgCode, double[] xy, double[] expected, double tolerance)
        {
            var sourceProjection = getProjectionUsingKnownCrsName(fromEpsgCode);
            var targetProjection = getProjectionUsingKnownCrsName(toEpsgCode);
            Reproject.ReprojectPoints(xy, null, sourceProjection, targetProjection, 0, 1);
            Assert.AreEqual(expected[0], xy[0], tolerance);
            Assert.AreEqual(expected[1], xy[1], tolerance);
        }

        [Test]
        public void RT9025gonV_to_WGS84()
        {
            // Test from https://github.com/DotSpatial/DotSpatial/issues/618
            var target = KnownCoordinateSystems.Projected.NationalGridsSweden.RT9025gonV;
            var dest = KnownCoordinateSystems.Geographic.World.WGS1984;

            var xy = new double[] { 1411545, 6910904 };
            Reproject.ReprojectPoints(xy, null, target, dest, 0, 1);

            Assert.AreEqual(xy[0], 14.10000, 1e-3);
            Assert.AreEqual(xy[1], 62.30000, 1e-3);
        }

        private ProjectionInfo getProjectionUsingKnownCrsName(int epsgCode)
        {
            ProjectionInfo proj = null;
            if (epsgCode == 3021)
                proj = KnownCoordinateSystems.Projected.NationalGridsSweden.RT9025gonV;
            else if (epsgCode == 3022)
                proj = KnownCoordinateSystems.Projected.NationalGridsSweden.RT900gon;
            else if (epsgCode == 3013)
                proj = KnownCoordinateSystems.Projected.NationalGridsSweden.SWEREF991545;
            else if (epsgCode == 3006)
                proj = KnownCoordinateSystems.Projected.NationalGridsSweden.SWEREF99TM;
            else
                throw new Exception("Not included in this test");

            Assert.AreEqual(epsgCode,proj.AuthorityCode);
                return proj;

        }

        [Test]
        public void EuropeanDatum1950UTMZone30N_to_WGS84()
        {
            // Test from https://github.com/DotSpatial/DotSpatial/issues/623

            var ed50 = KnownCoordinateSystems.Projected.UtmOther.EuropeanDatum1950UTMZone30N;
            var wgs84 = KnownCoordinateSystems.Geographic.World.WGS1984;
            double[] xy = { 450306.555, 4480448.5634 };

            Reproject.ReprojectPoints(xy, null, ed50, wgs84, 0, 1);

            Assert.AreEqual(xy[0], -3.5875, 1e-3);
            Assert.AreEqual(xy[1], 40.47136, 1e-3);
        }
    }
}


text:
import sys
import difflib

if 'HOST_RESERVED_EXCEPTIONS' not in locals():
    HOST_RESERVED_EXCEPTIONS = []

if 'HOST_LOG' not in locals():
	HOST_LOG = lambda data: sys.stdout.write(data+'\n')

Test_File = 'test.log'
Golden_File = 'Golden.log'

def DoCompare():
	HOST_LOG("Loading test case generated data '%s'..."%Test_File)
	TestLog = [item.strip() for item in open(Test_File, 'r').readlines()]
	HOST_LOG("Loading known good data '%s'..."%Golden_File)
	GoldenLog = [item.strip() for item in open(Golden_File, 'r').readlines()]

	LogDiff = difflib.unified_diff(TestLog, GoldenLog)
	DiffCnt = 0
	for DiffLine in LogDiff:
		DiffCnt += 1
		HOST_LOG(DiffLine)

	HOST_LOG("Generated %d lines of differences"%DiffCnt)
	return DiffCnt == 0

if __name__ == "__main__":
	try:
		RESULT = DoCompare()
	except HOST_RESERVED_EXCEPTIONS:
		raise
	except Exception,e:
		HOST_EXCEPT("Failed to compare result - %s"%e)
		RESULT = False


text:
import * as React from 'react';
import { compose, mapProps, withProps, withState, shouldUpdate, lifecycle } from 'recompose';
import { Element as ScrollElement } from 'react-scroll';
import styled from 'styled-components';
import { isEqual, get } from 'lodash';
import { hash } from 'ssUtil';
import { withNotation } from 'enhancers';
import { Score as ScoreService } from 'services';
import {
  ScoreController, CaretController, LoopCaretController,
  ScoreScroller, ScoreLine, ScoreTitle
} from 'components';

const enhance = compose(
  mapProps(props => ({
    width: props.width,
    measuresPerLine: props.measuresPerLine || ScoreService.getMeasuresPerLine(props.width),
    caret: Boolean(props.caret),
    scroller: Boolean(props.scroller),
    hideScroll: Boolean(props.hideScroll),
  })),
  withNotation,
  // The purpose of the score prop is solely to trigger rerenders
  // in consuming components.
  withState('score', 'setScore', null),
  withProps(props => ({
    maybeCreateScore: nextProps => {
      const shouldCreateScore = (
        !nextProps.score ||
        nextProps.score.vextabString !== nextProps.notation.state.vextabString ||
        nextProps.score.width !== nextProps.width
      );

      if (shouldCreateScore) {
        const { maestro } = window.ss;
        try {
          maestro.errors = [];
          const score = new ScoreService(
            nextProps.notation.state.vextabString, nextProps.width, nextProps.measuresPerLine
          );
          maestro.score = score;
          nextProps.setScore(score);
        } catch (error) {
          maestro.errors.push(error);
        }
      }
    }
  })),
  lifecycle({
    componentWillReceiveProps(nextProps): void {
      nextProps.maybeCreateScore(nextProps);
    },
    componentWillUnmount(): void {
      window.ss.maestro.score = null;
      this.props.setScore(null);
    }
  }),
  shouldUpdate((props, nextProps) => props.score !== nextProps.score)
);

const Head = styled.div`
  display: none;
`;
const Body = (styled.div as any)`
  background: white;
  max-height: 1040px;
  overflow-x: hidden;
  overflow-y: ${props => props.hideScroll ? 'hidden' : 'auto'};
  -webkit-overflow-scrolling: touch;
`;
const Spacer = styled.div`
  height: 800px;
  width: 100%;
  background: white;
`;

const ScoreLines = ({ score, caret }) => {
  const vextabString = get(score, 'vextabString');

  if (!vextabString) {
    return null;
  } else {
    const vextabStringHash = hash(`${vextabString}${score.width}`);
    return (
      score.lines.map(line => (
        <ScoreLine
          key={`score-line-${line.number}-${vextabStringHash}`}
          line={line}
          caret={caret}
        />
      )
    ));
  }
};

const Score = ({ width, caret, scroller, notation, score, hideScroll }) =>(
  <div>
    <Head>
      <ScoreController width={width} caret={caret} score={score} />
      {caret ? <CaretController /> : null}
      {caret ? <LoopCaretController /> : null}
      {scroller ? <ScoreScroller /> : null}
    </Head>
    <Body id="Score" hideScroll={hideScroll}>
      <ScoreTitle
        songName={notation.state.songName}
        artistName={notation.state.artistName}
        transcriberName={notation.state.transcriber.username}
      />
      <ScoreLines score={score} caret={caret} />
      <Spacer />
    </Body>
  </div>
);

export default enhance(Score);


text:
package breeze.optimize

import breeze.math.{InnerProductSpace, MutableInnerProductSpace, MutableCoordinateSpace}
import breeze.linalg._
import com.typesafe.scalalogging.slf4j.Logging
import breeze.linalg.operators.{OpMulMatrix, BinaryOp}

/**
 * Port of LBFGS to Scala.
 *
 * Special note for LBFGS:
 *  If you use it in published work, you must cite one of:
 *     * J. Nocedal. Updating  Quasi-Newton  Matrices  with  Limited  Storage
 *    (1980), Mathematics of Computation 35, pp. 773-782.
 *  * D.C. Liu and J. Nocedal. On the  Limited  mem  Method  for  Large
 *    Scale  Optimization  (1989),  Mathematical  Programming  B,  45,  3,
 *    pp. 503-528.
 *  *
 *
 * @param maxIter: maximum number of iterations, or <= 0 for unlimited
 * @param m: The memory of the search. 3 to 7 is usually sufficient.
 */
class LBFGS[T](maxIter: Int = -1, m: Int=10, tolerance: Double=1E-9)
              (implicit space: MutableInnerProductSpace[T, Double]) extends FirstOrderMinimizer[T,DiffFunction[T]](maxIter, tolerance) with Logging {

  import space._
  require(m > 0)

  type History = LBFGS.ApproximateInverseHessian[T]

  protected def takeStep(state: State, dir: T, stepSize: Double) = state.x + dir * stepSize
  protected def initialHistory(f: DiffFunction[T], x: T):History = new LBFGS.ApproximateInverseHessian(m)
  protected def chooseDescentDirection(state: State, fn: DiffFunction[T]):T = {
    state.history * state.grad
  }

  protected def updateHistory(newX: T, newGrad: T, newVal: Double,  f: DiffFunction[T], oldState: State): History = {
    oldState.history.updated(newX - oldState.x, newGrad :- oldState.grad)
  }

  /**
   * Given a direction, perform a line search to find
   * a direction to descend. At the moment, this just executes
   * backtracking, so it does not fulfill the wolfe conditions.
   *
   * @param state the current state
   * @param f The objective
   * @param dir The step direction
   * @return stepSize
   */
  protected def determineStepSize(state: State, f: DiffFunction[T], dir: T) = {
    val x = state.x
    val grad = state.grad

    val ff = LineSearch.functionFromSearchDirection(f, x, dir)
    val search = new StrongWolfeLineSearch(maxZoomIter = 10, maxLineSearchIter = 10) // TODO: Need good default values here.
    val alpha = search.minimize(ff, if(state.iter == 0.0) 1.0/norm(dir) else 1.0)

    if(alpha * norm(grad) < 1E-10)
      throw new StepSizeUnderflow
    alpha
  }

}

object LBFGS {
  case class ApproximateInverseHessian[T](m: Int,
                                          private[LBFGS] val memStep: IndexedSeq[T] = IndexedSeq.empty,
                                          private[LBFGS] val memGradDelta: IndexedSeq[T] = IndexedSeq.empty)
                                         (implicit vspace: MutableInnerProductSpace[T, Double]) extends NumericOps[ApproximateInverseHessian[T]] {

    import vspace._

    def repr: ApproximateInverseHessian[T] = this

    def updated(step: T, gradDelta: T) = {
      val memStep = (step +: this.memStep) take m
      val memGradDelta = (gradDelta +: this.memGradDelta) take m

      new ApproximateInverseHessian(m, memStep,memGradDelta)
    }

    def historyLength = memStep.length

    def *(grad: T) = {
     val diag = if(historyLength > 0) {
       val prevStep = memStep.head
       val prevGradStep = memGradDelta.head
       val sy = prevStep dot prevGradStep
       val yy = prevGradStep dot prevGradStep
       if(sy < 0 || sy.isNaN) throw new NaNHistory
       sy/yy
     } else {
       1.0
     }

     val dir = vspace.copy(grad)
     val as = new Array[Double](m)
     val rho = new Array[Double](m)

     for(i <- 0 until historyLength) {
       rho(i) = (memStep(i) dot memGradDelta(i))
       as(i) = (memStep(i) dot dir)/rho(i)
       if(as(i).isNaN) {
         throw new NaNHistory
       }
       axpy(-as(i), memGradDelta(i), dir)
     }

     dir *= diag

     for(i <- (historyLength - 1) to 0 by (-1)) {
       val beta = (memGradDelta(i) dot dir)/rho(i)
       axpy(as(i) - beta, memStep(i), dir)
     }

     dir *= -1.0
     dir
    }
  }

  implicit def multiplyInverseHessian[T](implicit vspace: MutableInnerProductSpace[T, Double]):BinaryOp[ApproximateInverseHessian[T], T, OpMulMatrix, T] = {
    new BinaryOp[ApproximateInverseHessian[T], T, OpMulMatrix, T] {
      def apply(a: ApproximateInverseHessian[T], b: T): T = a * b
    }

  }
}


text:
Project template for CodeCakeBuilder.

Currently use Code.Cake v0.1.0-beta.
Release for this project is manual (VSIX).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace Microsoft.DwayneNeed.Threading
{
    public class UIThreadPoolDataGridTemplateColumn : DataGridTemplateColumn
    {
        public string PropertyName {get;set;}

        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            // Get the cell template and make sure it is sealed because we need
            // to inflate it on the worker thread.
            DataTemplate cellTemplate = CellTemplate;
            if (!cellTemplate.IsSealed)
            {
                cellTemplate.Seal();
            }

            UIThreadPoolRoot root = new UIThreadPoolRoot();
            root.DataContext = dataItem;
            root.Content = cellTemplate;
            root.PropertyName = PropertyName;

            return root;
        }
    }
}


text:
package rest

import (
	"encoding/json"
	"fmt"
	"github.com/ghodss/yaml"
	"github.com/onsi/gomega/types"
	"k8s.io/client-go/pkg/api/errors"
	"k8s.io/client-go/rest"
	rest2 "kubevirt.io/kubevirt/pkg/rest"
	"reflect"
)

func RepresentMimeType(expected interface{}) types.GomegaMatcher {
	return &representMimeTypeMatcher{
		expected: expected,
	}
}

type representMimeTypeMatcher struct {
	expected interface{}
	body     []byte
}

func (matcher *representMimeTypeMatcher) Match(actual interface{}) (success bool, err error) {
	result, ok := actual.(rest.Result)
	if !ok {
		return false, fmt.Errorf("RepresentMimeType matcher expects a kubernetes rest client Result")
	}

	//Ignore the error here, since receiving data when the return code is not 200 is valid
	matcher.body, _ = result.Raw()

	mimeType, ok := matcher.expected.(string)
	if !ok {
		return false, fmt.Errorf("Expected mime type needs to be a string")
	}

	switch mimeType {
	case rest2.MIME_JSON:
		var obj interface{}
		if err := json.Unmarshal(matcher.body, &obj); err != nil {
			return false, nil
		}
	case rest2.MIME_YAML:
		var obj interface{}
		// yaml.Unmarshal also accepts JSON, so let's check if it is JSON first
		if err := json.Unmarshal(matcher.body, &obj); err == nil {
			return false, nil
		}
		if err := yaml.Unmarshal(matcher.body, &obj); err != nil {
			return false, nil
		}
	default:
		return false, fmt.Errorf("Provided MIME-Type is not supported")
	}

	return true, nil
}

func (matcher *representMimeTypeMatcher) FailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected\n\t%#v\nto to be of type\n\t%#v", string(matcher.body), matcher.expected)
}

func (matcher *representMimeTypeMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected\n\t%#v\nnot to be of type\n\t%#v", string(matcher.body), matcher.expected)
}

func HaveBodyEqualTo(expected interface{}) types.GomegaMatcher {
	return &haveBodyEqualToMatcher{
		expected: expected,
	}
}

type haveBodyEqualToMatcher struct {
	expected interface{}
	obj      interface{}
	err      error
}

func (matcher *haveBodyEqualToMatcher) Match(actual interface{}) (success bool, err error) {
	result, ok := actual.(rest.Result)
	if !ok {
		return false, fmt.Errorf("RepresentMimeType matcher expects a kubernetes rest client Result")
	}

	// Ignoring error here since failed requests can still contain a body
	matcher.obj, matcher.err = result.Get()

	if matcher.err != nil {
		return false, nil
	}

	if reflect.TypeOf(matcher.expected).Kind() != reflect.Ptr {
		matcher.expected = &matcher.expected
	}

	if matcher.obj != nil && reflect.TypeOf(matcher.obj).Kind() != reflect.Ptr {
		matcher.obj = &matcher.obj
	}

	return reflect.DeepEqual(matcher.expected, matcher.obj), nil
}

func (matcher *haveBodyEqualToMatcher) FailureMessage(actual interface{}) (message string) {
	if matcher.err != nil {
		return fmt.Sprintf("Deserializing the runtime object failed with %v", matcher.err)
	} else {
		return fmt.Sprintf("Expected\n\t%#v\nto to be equal to\n\t%#v", matcher.obj, matcher.expected)
	}
}

func (matcher *haveBodyEqualToMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	if matcher.err != nil {
		return fmt.Sprintf("Deserializing the runtime object failed with %v", matcher.err)
	} else {
		return fmt.Sprintf("Expected\n\t%#v\nnot to be equal to\n\t%#v", matcher.obj, matcher.expected)
	}
}

func HaveStatusCode(expected interface{}) types.GomegaMatcher {
	return &haveStatusCodeMatcher{
		expected: expected,
	}
}

type haveStatusCodeMatcher struct {
	expected   interface{}
	statusCode int
}

func (matcher *haveStatusCodeMatcher) Match(actual interface{}) (success bool, err error) {
	result, ok := actual.(rest.Result)
	if !ok {
		return false, fmt.Errorf("HaveStatusCode matcher expects a kubernetes rest client Result")
	}

	expectedStatusCode, ok := matcher.expected.(int)
	if !ok {
		return false, fmt.Errorf("Expected status code to be of type int")
	}

	result.StatusCode(&matcher.statusCode)

	if result.Error() != nil {
		matcher.statusCode = int(result.Error().(*errors.StatusError).Status().Code)
	}

	return matcher.statusCode == expectedStatusCode, nil
}

func (matcher *haveStatusCodeMatcher) FailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected status code \n\t%#v\nto to be\n\t%#v", matcher.statusCode, matcher.expected)
}

func (matcher *haveStatusCodeMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected status code \n\t%#v\nnot to be\n\t%#v", matcher.statusCode, matcher.expected)
}


text:
package info.boytsov.lucene.parsers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Date;
import java.util.Properties;

import org.apache.lucene.benchmark.byTask.feeds.DocData;
import org.htmlparser.Parser;
import org.htmlparser.util.ParserException;
import org.xml.sax.InputSource;

/**
 * Simple HTML Parser extracting title, meta tags, and body text
 * that is based on org.htmlparser.
 */
public class LeoHTMLParser implements HTMLParser {

  @Override
  public DocData parse(DocData docData,
                       String name,
                       Date date,
                       Reader reader,
                       ContentSourceDateUtil trecSrc) throws IOException {

    return parse(docData, name, date, new InputSource(reader), trecSrc);
  }

  public DocData parse(DocData docData,
                       String name,
                       Date date,
                       InputSource source,
                       ContentSourceDateUtil trecSrc)
                       throws IOException {
    String title = "";
    String bodyText = "";

    String baseHref = "http://fake-domain.com";
    String encoding = "utf8";

    /*
     *
     * This is clearly not the most efficient way to parse,
     * but it is much more stable.
     *
     */
    StringWriter writer = new StringWriter();
    BufferedReader br = new BufferedReader(source.getCharacterStream());

    String line;
    while(null != (line = br.readLine())) {
        writer.append(line);
    }
    br.close();

    String html = writer.toString();

    try {
      Parser HtmlParser = Parser.createParser(html, encoding);

      LeoCleanerUtil res = new LeoCleanerUtil(baseHref);
      HtmlParser.visitAllNodesWith(res);

      title = res.GetTitleText();

      bodyText = title + " " +
                 res.GetDescriptionText() + " " +
                 res.GetKeywordText() + " " +
                 res.GetBodyText();

    } catch (ParserException e) {
      System.err.println(" Parser exception: " + e + " trying simple conversion");
      // Plan B!!!
      Pair<String,String> sres = LeoCleanerUtil.SimpleProc(html);

      title = sres.getFirst();
      bodyText = title + " " + sres.getSecond();
    }

    docData.clear();
    docData.setName(name);
    docData.setTitle(title);
    docData.setBody(bodyText);
    docData.setProps(new Properties());
    docData.setDate(date);

    return docData;
  }

}


text:
(function() {
  var PouchDB, _, dbNameError, methods;

  PouchDB = require('pouchdb');

  _ = require('underscore');

  dbNameError = function() {
    throw new Error('A database name must be specified');
  };

  methods = {
    'create': 'post',
    'update': 'put',
    'patch': 'put',
    'delete': 'remove',
    'read': 'get'
  };

  module.exports = function(defaults) {
    var adapter, db, settings;
    settings = {
      defaults: {
        dbName: null,
        dbOptions: {},
        query: 'allDocs'
      }
    };
    defaults = defaults || {};
    defaults = _.extend(settings.defaults, defaults);
    db = new PouchDB(defaults.dbName, defaults.dbOptions);
    adapter = function(method, model, options) {
      var actions, code;
      options = options || {};
      options = _.extend(defaults, model && model.pouch || {}, options);
      actions = {
        get: function() {
          var design, query;
          if (model._id != null) {
            return db.get(model._id).then(function(resp) {
              return options.success(resp);
            })["catch"](function(err) {
              if ((options != null ? options.error : void 0) != null) {
                return options.error(err);
              } else {
                throw err;
              }
            });
          } else if (options.query === 'allDocs') {
            return db.allDocs({
              include_docs: true
            }).then(function(resp) {
              return options.success(resp);
            })["catch"](function(err) {
              if ((options != null ? options.error : void 0) != null) {
                return options.error(err);
              } else {
                throw err;
              }
            });
          } else {
            query = function(q) {
              return db.query(q, {
                include_docs: true
              }).then(function(resp) {
                return options.success(resp);
              })["catch"](function(err) {
                if ((options != null ? options.error : void 0) != null) {
                  return options.error(err);
                } else {
                  throw err;
                }
              });
            };
            if (options.options != null) {
              design = options.options[options.query];
              if ((typeof design) === 'function') {
                return query(design);
              } else if ((typeof design) === 'object') {
                if (design.fun != null) {
                  return query(design.fun);
                } else {
                  throw Error('Please define a map and reduce function');
                }
              }
            } else {
              return query(options.query);
            }
          }
        },
        post: function() {
          var body;
          body = model.toJSON();
          return db.post(body).then(function(resp) {
            body._id = resp.id;
            body._rev = resp.rev;
            return options.success(body, resp);
          })["catch"](function(err) {
            if ((options != null ? options.error : void 0) != null) {
              return options.error(err);
            } else {
              throw err;
            }
          });
        },
        put: function() {
          var body;
          body = model.toJSON();
          return db.put(body).then(function(resp) {
            body._rev = resp.rev;
            return options.success(body, resp);
          })["catch"](function(err) {
            if ((options != null ? options.error : void 0) != null) {
              return options.error(err);
            } else {
              throw err;
            }
          });
        },
        remove: function() {
          return db.remove(model._id, model._rev).then(function(resp) {
            return options.success();
          })["catch"](function(err) {
            if ((options != null ? options.error : void 0) != null) {
              return options.error(err);
            } else {
              throw err;
            }
          });
        }
      };
      code = methods[method];
      return actions[code]();
    };
    adapter.defaults = defaults;
    adapter.pouchDB = db;
    return adapter;
  };

}).call(this);


text:
.class public interface abstract Landroid/support/v4/animation/AnimatorListenerCompat;
.super Ljava/lang/Object;
.source "AnimatorListenerCompat.java"

# annotations
.annotation build Landroid/support/annotation/RestrictTo;
    value = {
        .enum Landroid/support/annotation/RestrictTo$Scope;->LIBRARY_GROUP:Landroid/support/annotation/RestrictTo$Scope;
    }
.end annotation

# virtual methods
.method public abstract onAnimationCancel(Landroid/support/v4/animation/ValueAnimatorCompat;)V
.end method

.method public abstract onAnimationEnd(Landroid/support/v4/animation/ValueAnimatorCompat;)V
.end method

.method public abstract onAnimationRepeat(Landroid/support/v4/animation/ValueAnimatorCompat;)V
.end method

.method public abstract onAnimationStart(Landroid/support/v4/animation/ValueAnimatorCompat;)V
.end method


text:
This walkthrough introduces Datastore, which lets you store data permanently.

You can return to this walkthrough anytime by running this command:

```bash
teachme ~/software-product-sprint/walkthroughs/week-2-server/step-5-datastore-walkthrough.md
```

Click the **Start** button to begin!

## The Goal

The goal of this project is to use Datastore to permanently store the messages
you implemented in last week's "contact me" project. You'll store the messages
in Datastore, and then create a page that displays them. This will be a lot
more convenient than searching through the logs!

This walkthrough introduces a lot of concepts, but you don't have to use all of
them. Decide what makes sense for your goal.

Don't be afraid to get creative, but focus on finishing a
[minimum viable product](https://en.wikipedia.org/wiki/Minimum_viable_product)
that proves you have all of the pieces connected, and then come back later and
add extra features if you have time left over.

## Persistent Storage

You might try to use a data structure like an `ArrayList` to store data in a
servlet. But what happens if you have more data than fits in memory? What
happens when your server restarts, or when App Engine automatically scales your
server up or down?

The answer is that your data will be erased. This won't work for data that you
want to store permanently.

The solution to this problem is to use **persistent storage** to store the data
somewhere safer. You might use a database, or file storage.

[Datastore](https://cloud.google.com/appengine/docs/standard/java11/using-cloud-datastore)
is a [NoSQL](https://en.wikipedia.org/wiki/NoSQL) database that lets you store
and load data using Java code.

The next few steps introduce Datastore through an example that stores tasks in a
todo list.

## Example

The `todo-list` directory contains an example project that uses Datastore to
store tasks posted by the user. The next few steps will walk you through this
example project.

## Maven Dependency

To use Datastore, first add the Datastore dependency to your
<walkthrough-editor-open-file
    filePath="software-product-sprint/portfolio/pom.xml">
  pom.xml
</walkthrough-editor-open-file>
file:

```xml
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-datastore</artifactId>
  <version>1.104.0</version>
</dependency>
```

This dependency lets you reference the classes that come with the Google Cloud
Datastore library.

## Datastore

Open the
<walkthrough-editor-open-file
    filePath="software-product-sprint/walkthroughs/week-3-libraries/datastore/examples/todo-list/src/main/java/com/google/sps/servlets/NewTaskServlet.java">
  NewTaskServlet.java
</walkthrough-editor-open-file>
file in the `todo-list` directory to see how it uses Datastore to save a task.

To use Datastore, you first need an instance of the `Datastore` class.
You can call the `DatastoreOptions.getDefaultInstance().getService()` function:

```java
Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
```

Now you can use this `datastore` variable to interact with Datastore.

You can read more about the `Datastore` class
[here](https://googleapis.dev/java/google-cloud-datastore/1.105.3/com/google/cloud/datastore/Datastore.html).

## Entities

Data in Datastore is represented by **entities**. You can think of an entity
similar to how you think about an instance of a class in Java. Each entity has
an associated key.

A key has a **kind**, which is similar to a class name.

Look at the `doPost()` function in the
<walkthrough-editor-open-file
    filePath="software-product-sprint/walkthroughs/week-3-libraries/datastore/examples/todo-list/src/main/java/com/google/sps/servlets/NewTaskServlet.java">
  NewTaskServlet.java
</walkthrough-editor-open-file>
file to see how it creates an key by giving it a *kind* of `Task`:

```java
KeyFactory keyFactory = datastore.newKeyFactory().setKind("Task");
```

This line of code creates an `KeyFactory` with a *kind* of `Task` and stores it in a
`keyFactory` variable.

An entity also has **properties**, similar to how a class can have variables.
Each property is a **key** and a **value**.

To create an entity, you give it  key and then set its properties by calling
the `set()` function:

```java
FullEntity taskEntity =
    Entity.newBuilder(keyFactory.newKey())
        .set("title", title)
        .set("timestamp", timestamp)
        .build();
```

This code adds two properties to the `taskEntity` entity: `title` and
`timestamp`. Property values can be strings, numbers, or timestamps. See
[this guide](https://cloud.google.com/datastore/docs/concepts/entities#datastore-datastore-upsert-java)
to learn more about the types of values you can store in an entity.

### Storing Entities

Now that you have a `datastore` variable and a `taskEntity` variable, you can
store the entity by passing it into the `datastore.put()` function:

```java
datastore.put(taskEntity);
```

This function stores `taskEntity` in Datastore so that you can load it next time
you need it.

## Your Turn

Modify your servlet file to take the data entered by users in your "contact me"
form and store it as an entity in Datastore. Get this working before
you worry about loading the data.

The first time you deploy your application, you may encounter an error like this when
submitting the form:
`com.google.cloud.datastore.DatastoreException: Cloud Datastore API has not been used ...`.
If you do, follow the link in the error message and enable the Cloud Datastore API.

### Admin Page

Datastore includes an admin page that gives you access to its data. This is very
useful for debugging and managing your data.

To view the admin page for your live server, go to
[https://console.cloud.google.com/datastore](https://console.cloud.google.com/datastore).

Use the admin page to confirm that your data is stored correctly. After you get
this step working, create a pull request and send it to your advisor for
review!

## Loading Entities

Now that you have data stored in Datastore, you can load it whenever a user
requests it.

The `todo-list` example contains a
<walkthrough-editor-open-file
    filePath="software-product-sprint/walkthroughs/week-3-libraries/datastore/examples/todo-list/src/main/java/com/google/sps/servlets/ListTasksServlet.java">
  ListTasksServlet.java
</walkthrough-editor-open-file>
file that loads entities from Datastore.

First create a `Query` instance with the kind of entity you want to load, then
pass that `Query` into the `datastore.run()` function, which gives you a
`QueryResults` instance that contains all of the entities in Datastore with
that kind. To loop iterate those entities, call the `hasNext()` and `next()` functions.

```java
Query<Entity> query =
        Query.newEntityQueryBuilder().setKind("Task").setOrderBy(OrderBy.desc("timestamp")).build();
QueryResults<Entity> results = datastore.run(query);

while (results.hasNext()) {
  Entity entity = results.next();
...
```

Then inside this loop, you can use the `entity.get*()` functions to get
the properties that were set on each entity when it was stored in Datastore.

By storing entities when the user creates them and loading them when you need to
use them again, you can use Datastore as persistent storage even when your web
app is shut down or restarted.

## Your Turn

Next, add some code to your servlet class that loads the "contact me" data from
Datastore. You can use Gson to format the data as JSON, and then you can use
JavaScript to fetch that JSON, and parse it to build the HTML of a page that
lists all of the messages you've received.

### Sanitizing User Input

If you're taking user input and showing it as HTML, you need to make sure you're
properly handling cases like users entering HTML tags or JavaScript in their
input. Not handling this can lead to security issues like cross-site scripting
(XSS).

The todo list example uses a library called [jSoup](https://jsoup.org/) to
sanitize user input in the `NewTaskServlet.java` file:

```java
String title = Jsoup.clean(request.getParameter("title"), Whitelist.none());
```

This line of code takes the data entered by the user and removes any HTML or
JavaScript content from it. Now it's safe to show in the content of an HTML
page.

You should also consider hiding personal data like email addresses.

If you use of jSoup, you'll need to added it as a dependency in your
<walkthrough-editor-open-file filePath="software-product-sprint/portfolio/pom.xml">pom.xml
</walkthrough-editor-open-file> file. You can find an example
<walkthrough-editor-open-file filePath="software-product-sprint/walkthroughs/week-3-libraries/datastore/examples/todo-list/pom.xml">here</walkthrough-editor-open-file>.

## Pull Requests

<walkthrough-conclusion-trophy></walkthrough-conclusion-trophy>

Congratulations! Your portfolio page should now support messages that are
permanently stored in Datastore. Make sure your
[MVP](https://en.wikipedia.org/wiki/Minimum_viable_product) works and is
submitted to your GitHub repo by the end of the week.

When you're done, share your live URL in the chat!

To return to the libraries walkthrough, run this command:

```bash
teachme ~/software-product-sprint/walkthroughs/week-3-libraries/libraries-walkthrough.md
```

### Learn More

This tutorial covered the fundamentals of how to use Datastore, but Datastore
also provides more advanced functionality. See these resources for more info:

-   [Datastore documentation](https://cloud.google.com/datastore/docs/)
-   [Entities documentation](https://cloud.google.com/datastore/docs/concepts/entities)
-   [Datastore API](https://googleapis.dev/java/google-cloud-datastore/1.105.3/index.html?com/google/cloud/datastore/Datastore.html)


text:
layout: post
title: "Using Spring Boot as a Proxy for downloading Data from Redshift"
description: ""
category:
tags: ["spring", "redshift", "aws"]
---
{% include JB/setup %}

Suppose you have a redshift db that you want to allow users to download data from. You also want to use spring security to
ensure that users can only download data they are authorised to see and nothing else.

1) Redshift UNLOAD
2) Role base credentials
3) Specifying your select statement
4) Adding Headers
5) Controlling access to S3 by prefix
6) Piping files from S3 to the client.


text:
import frontpage from './components/frontpage';
import createTeam from './components/TeamComponents/createTeam';
import listAllTeams from './components/TeamComponents/listAllTeams';
import editTeam from './components/TeamComponents/editTeam';
import createPlayer from './components/PlayerComponents/createPlayer';
import listAllPlayers from './components/PlayerComponents/listAllPlayers';
import editPlayer from './components/PlayerComponents/editPlayer';

export default [
  {
    path: '/',
    component: frontpage
  },
  {
    path: '/team/create',
    component: createTeam
  },
  {
    path: '/team/overview',
    component: listAllTeams
  },
  {
    path: '/team/overview/edit/:teamId',
    component: editTeam
  },
  {
    path: '/player/create',
    component: createPlayer,
  },
  {
    path: '/player/overview',
    component: listAllPlayers
  },
  {
    path: '/player/overview/edit/:playerId',
    component: editPlayer
  }
];


text:
'use strict';

//Setting up route
angular.module('job-applications').config(['$stateProvider',
	function($stateProvider) {
		// Job applications state routing
		$stateProvider.
		state('employer-job-candidates', {
			url: '/employer-job-candidates/:jobId',
			templateUrl: 'modules/job-applications/views/employer-job-candidates.client.view.html'
		})
		.state('employer-job-candidates.all', {
			url: '/all',
			templateUrl: 'modules/job-applications/views/employer-job-candidates.client.all.view.html'
		})
		.state('employer-job-candidates.interview', {
			url: '/interview',
			templateUrl: 'modules/job-applications/views/employer-job-candidates.interview.client.view.html'
		})
		.state('employer-job-candidates.exam', {
			url: '/exam',
			templateUrl: 'modules/job-applications/views/employer-job-candidates.exam.client.view.html'
		})
		.state('employer-job-candidates.stage', {
			url: '/:stage',
			templateUrl: 'modules/job-applications/views/employer-job-candidates.exam.client.view.html'
		});
	}
]);


text:
<krpano onstart="loadscene(get(scene[0].name), null, MERGE);">

	<!-- webvr.xml - WebVR plugin, enter/exit VR buttons, VR cursor, VR setup -->
	<include url="../plugins/webvr.xml" />

  <!-- add/overwrite some settings from the webvr.xml for this example
		- enable the fake mode
		- add events for portrait usage
	-->
  <plugin name="WebVR"
	        mobilevr_fake_support="true"
	        onentervr="webvr_onentervr(); webvr_act_as_gyro_in_portrait_mode(true);"
	        onexitvr="webvr_onexitvr(); tween(layer[webvr_rotate_to_landscape_request].alpha, 0.0, 0.0);"
	        />

  <!-- re-align the vr button and 'auto-start' the video when pressing the enterVR button -->
  <layer name="webvr_enterbutton"
	       align="bottom" y="10%"
	       ondown="video_auto_start();"
	       />

  <!-- show a 'rotate the device' info when the mobile device is in portrait orientation in VR mode -->
  <layer name="webvr_rotate_to_landscape_request" keep="true" vr="true" devices="mobile"
	       url="rotate_device.png" scale="0.5"
	       align="top" edge="center" y="28%"
	       autoalpha="true" alpha="0.0"
	       enabled="false"
	       />

  <events name="webvr_events" keep="true" devices="html5"
	        onresize.mobile="webvr_act_as_gyro_in_portrait_mode();"
	        />

  <action name="webvr_act_as_gyro_in_portrait_mode">
    if(device.mobile AND webvr.isenabled,
    div(aspect, stagewidth, stageheight);
    if(aspect != lastaspect OR '%1' == 'true',
    copy(lastaspect, aspect);
    if(stagewidth GT stageheight,
    <!-- landscape orientation - use stereo rendering and a direct/fast gyro sensor mode -->
    set(display.stereo, true);
    set(webvr.mobilevr_sensor_mode, 3);
    webvr.update();
    tween(layer[webvr_rotate_to_landscape_request].alpha, 0.0, 0.0);
    ,
    <!-- portrait orientation - use normal rendering and a smoother/slower gyro sensor mode -->
    set(display.stereo, false);
    set(webvr.mobilevr_sensor_mode, 1);
    webvr.update();
    tween(layer[webvr_rotate_to_landscape_request].alpha, 1.0);
    delayedcall(3.0, tween(layer[webvr_rotate_to_landscape_request].alpha, 0.0, 1.0); );
    );
    );
    ,
    set(lastaspect, 0);
    );
  </action>

  <!-- use the dragging control by default -->
	<control mousetype="drag2d" />

	<!-- the intro pano -->
	<view fovtype="VFOV" fov="90" fovmin="40" fovmax="150" />

	<events name="change_scene" keep="true" onclick="click_nextscene_loop();" />

	<!-- hotspots -->
  <style
    name="hotspotstyle"
    url="../images/360-hotspot.png"
    onover="set(url, ../images/360-hotspot-hover.png);"
    distorted="true"
    onclick="goto(get(linkedscene));"
    vr_timeout="1000" />

  <!-- pano changing actions -->
  <action name="goto">
    loadscene(%1, null, NOPREVIEW|MERGE|KEEPVIEW|KEEPMOVING, BLEND(1))
  </action>
<!--
  <action name="nextscene_loop">
    if(xml.scene != null AND scene.count GT 1,
    add(newsceneindex, scene[get(xml.scene)].index, %1);
    sub(lastsceneindex, scene.count, 1);
    if(newsceneindex LT 0, copy(newsceneindex,lastsceneindex));
    if(newsceneindex GT lastsceneindex, set(newsceneindex,0));
    loadscene(get(scene[get(newsceneindex)].name), null, NOPREVIEW|MERGE|KEEPMOVING, COLORBLEND(3.0, 0x000000, easeOutSine));
    );
  </action> -->

  	<action name="nextscene_loop">
		if(xml.scene != null AND scene.count GT 1,
			add(newsceneindex, scene[get(xml.scene)].index, %1);
			sub(lastsceneindex, scene.count, 1);
			if(newsceneindex LT 0, copy(newsceneindex,lastsceneindex));
			if(newsceneindex GT lastsceneindex, set(newsceneindex,0));
			loadscene(get(scene[get(newsceneindex)].name), null, NOPREVIEW|MERGE|KEEPVIEW|KEEPMOVING, BLEND(1));
		);
	</action>

  <action name="click_nextscene_loop">
    <!--CardBoard B-->
    jsget(headset, 'localStorage.getItem("krpano.webvr.1")');
    if (headset == "63.5,0,96,0.6,100,3", nextscene_loop(+1));
  </action>
</krpano>


text:
package com.homework.kubra;

public class Datas {

	private String Planet;

	private String Discoverer;

	public Datas(String a, String b)
	{
		Planet = a;
		Discoverer = b;
	}

	public String getPlanet() {
		return Planet;
	}

	public String getDiscoverer() {
		return Discoverer;
	}
    public void setPlanet(String Planet) {
        this.Planet = Planet;
     }
    public void setDiscoverer(String Discoverer) {
        this.Discoverer = Discoverer;
     }

}


text:
<?php

namespace FOS\RestBundle\Tests\Functional;

/**
 * Test class for serialization errors and exceptions.
 *
 * @author Florian Voutzinos <florian@voutzinos.com>
 */
class SerializerErrorTest extends WebTestCase
{
    /**
     * @dataProvider serializeExceptionJsonProvider
     */
    public function testSerializeExceptionJson($testCase, $expectedContent)
    {
        $this->iniSet('error_log', file_exists('/dev/null') ? '/dev/null' : 'nul');

        $client = $this->createClient(array('test_case' => $testCase));
        $client->request('GET', '/serializer-error/exception.json');

        $this->assertEquals($expectedContent, $client->getResponse()->getContent());
    }

    public function serializeExceptionJsonProvider()
    {
        return array(
            array('Serializer', '{"code":500,"message":"Something bad happened.","errors":null}'),
            array('JMSSerializer', '{"code":500,"message":"Something bad happened."}'),
        );
    }

    /**
     * @dataProvider serializeExceptionXmlProvider
     */
    public function testSerializeExceptionXml($testCase, $expectedContent)
    {
        $this->iniSet('error_log', file_exists('/dev/null') ? '/dev/null' : 'nul');

        $client = $this->createClient(array('test_case' => $testCase));
        $client->request('GET', '/serializer-error/exception.xml');

        $this->assertEquals($expectedContent, $client->getResponse()->getContent());
    }

    public function serializeExceptionXmlProvider()
    {
        $expectedSerializerContent = <<<XML
<?xml version="1.0"?>
<response>500<message>Something bad happened.</message><errors/></response>

XML;

        $expectedJMSContent = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  500
  <message><![CDATA[Something bad happened.]]></message>
  <errors xsi:nil="true"/>
</result>

XML;

        return array(
            array('Serializer', $expectedSerializerContent),
            array('JMSSerializer', $expectedJMSContent),
        );
    }

    /**
     * @dataProvider serializeInvalidFormJsonProvider
     */
    public function testSerializeInvalidFormJson($testCase, $expectedContent)
    {
        $client = $this->createClient(array('test_case' => $testCase));
        $client->request('GET', '/serializer-error/invalid-form.json');

        $this->assertEquals($expectedContent, $client->getResponse()->getContent());
    }

    public function serializeInvalidFormJsonProvider()
    {
        return array(
            array('Serializer', '{"code":400,"message":"Validation Failed","errors":{"children":{"name":{"errors":["This value should not be blank."]}}}}'),
            array('JMSSerializer', '{"code":400,"message":"Validation Failed","errors":{"children":{"name":{"errors":["This value should not be blank."]}}}}'),
        );
    }

    /**
     * @dataProvider serializeInvalidFormXmlProvider
     */
    public function testSerializeInvalidFormXml($testCase, $expectedContent)
    {
        $client = $this->createClient(array('test_case' => $testCase));
        $client->request('GET', '/serializer-error/invalid-form.xml');

        $this->assertEquals($expectedContent, $client->getResponse()->getContent());
    }

    public function serializeInvalidFormXmlProvider()
    {
        $expectedSerializerContent = <<<XML
<?xml version="1.0"?>
<response>400<message>Validation Failed</message><errors><children><name><errors>This value should not be blank.</errors></name></children></errors></response>

XML;

        $expectedJMSContent = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<result>
  400
  <message><![CDATA[Validation Failed]]></message>
  <errors>
    <form name="form">
      <errors/>
      <form name="name">
        <errors>
          <entry><![CDATA[This value should not be blank.]]></entry>
        </errors>
      </form>
    </form>
  </errors>
</result>

XML;

        return array(
            array('Serializer', $expectedSerializerContent),
            array('JMSSerializer', $expectedJMSContent),
        );
    }
}


text:
package com.yqboots.security.core;

import com.yqboots.core.util.DBUtils;
import com.yqboots.security.core.repository.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Permission manager implementation.
 *
 * @author Eric H B Zhan
 * @since 1.1.0
 */
@Service
@Transactional(readOnly = true)
public class PermissionManagerImpl implements PermissionManager {
    @Autowired
    private PermissionRepository permissionRepository;

    /**
     * {@inheritDoc}
     */
    @Override
    public Page<Permission> findPermissions(final String sidFilter, final Pageable pageable) {
        return permissionRepository.findBySecurityIdentityLike(DBUtils.wildcard(sidFilter), pageable);
    }
}


text:
<ion-view view-title="资讯" cache-view="true">
    <ion-nav-buttons side="right">
        <button class="button button-clear" on-tap="showTags()">标签</button>
    </ion-nav-buttons>
    <ion-content class="has-header information" delegate-handle="informations">
        <ion-refresher pulling-text="下拉刷新..." on-refresh="doRefresh()">
        </ion-refresher>

{{info.title}}

{{info.summary}}

发布于:{{info.publish_time *1000 | date:'yyyy-MM-dd HH:mm:ss'}}

        <ion-infinite-scroll ng-if="vm.hasMore" on-infinite="loadMore(false)" icon="ion-loading-c">
        </ion-infinite-scroll>
        <ion-content-empty value="informations" loading="vm.loading" retry="doRefresh()" title="vm.emptyTitle">
        </ion-content-empty>
    </ion-content>
</ion-view>