text:
package com.opengamma.financial.analytics.model.volatility.local;

import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.financial.analytics.model.volatility.local.PDEPropertyNamesAndValues.PROPERTY_DISCOUNTING_CURVE_NAME;

import java.util.Collections;
import java.util.Set;

import org.threeten.bp.ZonedDateTime;

import com.opengamma.analytics.financial.model.interestrate.curve.ForwardCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.analytics.financial.model.volatility.local.LocalVolatilitySurfaceMoneyness;
import com.opengamma.analytics.financial.model.volatility.local.PDELocalVolatilityCalculator;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.target.ComputationTargetReference;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.analytics.model.curve.forward.ForwardCurveValuePropertyNames;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.util.ArgumentChecker;

/**
 *
 */
public abstract class LocalVolatilityPDEFunction extends AbstractFunction.NonCompiledInvoker {
  /** The name of this local volatility calculation method. */
  public static final String CALCULATION_METHOD = "LocalVolatilityPDE";
  private final String _blackSmileInterpolatorName;

  public LocalVolatilityPDEFunction(final String blackSmileInterpolatorName) {
    ArgumentChecker.notNull(blackSmileInterpolatorName, "Black smile interpolator name");
    _blackSmileInterpolatorName = blackSmileInterpolatorName;
  }

  @Override
  public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
    final ValueProperties properties = getResultProperties();
    return Collections.singleton(new ValueSpecification(getRequirementName(), target.toSpecification(), properties));
  }

  protected abstract String getRequirementName();

  protected abstract ComputationTargetReference getVolatilitySurfaceAndForwardCurveTarget(ComputationTarget target);

  protected abstract ComputationTargetReference getDiscountingCurveTarget(ComputationTarget target);

  protected abstract String getInstrumentType();

  protected abstract EuropeanVanillaOption getOption(FinancialSecurity security, ZonedDateTime date);

  protected abstract ValueProperties getResultProperties();

  protected abstract ValueProperties getResultProperties(ValueRequirement desiredValue);

  protected ValueRequirement getVolatilitySurfaceRequirement(final ComputationTarget target, final ValueRequirement desiredValue) {
    final ValueProperties properties = LocalVolatilitySurfaceUtils
        .addAllDupireLocalVolatilitySurfaceProperties(ValueProperties.builder().get(), getInstrumentType(), _blackSmileInterpolatorName,
            LocalVolatilitySurfacePropertyNamesAndValues.MONEYNESS, desiredValue)
        .get();
    return new ValueRequirement(ValueRequirementNames.LOCAL_VOLATILITY_SURFACE, getVolatilitySurfaceAndForwardCurveTarget(target), properties);
  }

  protected ValueRequirement getForwardCurveRequirement(final ComputationTarget target, final ValueRequirement desiredValue) {
    final String calculationMethod = desiredValue.getConstraint(ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_CALCULATION_METHOD);
    final String forwardCurveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
    final ValueProperties properties = ValueProperties.builder()
        .with(ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_CALCULATION_METHOD, calculationMethod)
        .with(CURVE, forwardCurveName).get();
    return new ValueRequirement(ValueRequirementNames.FORWARD_CURVE, getVolatilitySurfaceAndForwardCurveTarget(target), properties);
  }

  protected ValueRequirement getDiscountingCurveRequirement(final ComputationTarget target, final ValueRequirement desiredValue) {
    final ValueProperties properties = ValueProperties.builder()
        .with(ValuePropertyNames.CURVE, desiredValue.getConstraint(PROPERTY_DISCOUNTING_CURVE_NAME))
        .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG)).get();
    return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, getDiscountingCurveTarget(target), properties);
  }

  protected Object getResult(final PDELocalVolatilityCalculator<?> calculator, final LocalVolatilitySurfaceMoneyness localVolatility,
      final ForwardCurve forwardCurve,
      final EuropeanVanillaOption option, final YieldAndDiscountCurve discountingCurve) {
    return calculator.getResult(localVolatility, forwardCurve, option, discountingCurve);
  }

  protected String getBlackSmileInterpolatorName() {
    return _blackSmileInterpolatorName;
  }
}


text:
require "docile/version"
require "docile/execution"
require "docile/fallback_context_proxy"
require "docile/chaining_fallback_context_proxy"

# Docile keeps your Ruby DSLs tame and well-behaved.
module Docile
  extend Execution

  # Execute a block in the context of an object whose methods represent the
  # commands in a DSL.
  #
  # @note Use with an *imperative* DSL (commands modify the context object)
  #
  # Use this method to execute an *imperative* DSL, which means that:
  #
  #   1. Each command mutates the state of the DSL context object
  #   2. The return value of each command is ignored
  #   3. The final return value is the original context object
  #
  # @example Use a String as a DSL
  #   Docile.dsl_eval("Hello, world!") do
  #     reverse!
  #     upcase!
  #   end
  #   #=> "!DLROW ,OLLEH"
  #
  # @example Use an Array as a DSL
  #   Docile.dsl_eval([]) do
  #     push 1
  #     push 2
  #     pop
  #     push 3
  #   end
  #   #=> [1, 3]
  #
  # @param dsl   [Object] context object whose methods make up the DSL
  # @param args  [Array]  arguments to be passed to the block
  # @yield                the block of DSL commands to be executed against the
  #                         `dsl` context object
  # @return      [Object] the `dsl` context object after executing the block
  def dsl_eval(dsl, *args, &block)
    exec_in_proxy_context(dsl, FallbackContextProxy, *args, &block)
    dsl
  end
  module_function :dsl_eval

  # Execute a block in the context of an immutable object whose methods,
  # and the methods of their return values, represent the commands in a DSL.
  #
  # @note Use with a *functional* DSL (commands return successor
  #       context objects)
  #
  # Use this method to execute a *functional* DSL, which means that:
  #
  #   1. The original DSL context object is never mutated
  #   2. Each command returns the next DSL context object
  #   3. The final return value is the value returned by the last command
  #
  # @example Use a frozen String as a DSL
  #   Docile.dsl_eval_immutable("I'm immutable!".freeze) do
  #     reverse
  #     upcase
  #   end
  #   #=> "!ELBATUMMI M'I"
  #
  # @example Use a Float as a DSL
  #   Docile.dsl_eval_immutable(84.5) do
  #     fdiv(2)
  #     floor
  #   end
  #   #=> 42
  #
  # @param dsl   [Object] immutable context object whose methods make up the
  #                       initial DSL
  # @param args  [Array]  arguments to be passed to the block
  # @yield                the block of DSL commands to be executed against the
  #                         `dsl` context object and successor return values
  # @return      [Object] the return value of the final command in the block
  def dsl_eval_immutable(dsl, *args, &block)
    exec_in_proxy_context(dsl, ChainingFallbackContextProxy, *args, &block)
  end
  module_function :dsl_eval_immutable
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <title>
    WI+RE (Writing Instruction + Research Education) - WI+RE

  </title>

  <meta name="description" content="Quick and practical research and writing tutorials, collaboratively designed by students at UCLA.">

    <meta name="DC.title" content="WI+RE (Writing Instruction + Research Education)" />

    <meta name="DC.source" content="WI+RE - Quick and practical research and writing tutorials, collaboratively designed by students at UCLA." />

                <meta name="DC.creator" content="The WI+RE Team" />

        <meta name="DCterms.abstract" content="WI+RE (Writing Instruction + Research Education)" />

        <meta name="DC.Type" content="home" />

        <meta name="DC.rights" content="Creative Commons Attribution-NonCommercial-ShareAlike" />

  <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

    <link rel="stylesheet" href="/research-tips/assets/vendor/bootstrap/css/bootstrap.min.css">

  <link rel="stylesheet" href="/research-tips/assets/main.css">

    <link rel="stylesheet" href="/research-tips/assets/custom.css">

  <link rel="canonical" href="http://localhost:4000/">
  <link rel="alternate" type="application/rss+xml" title="WI+RE" href="/research-tips/feed.xml">

    WI+RE
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
      Menu

    </button>

          Home

          About

          Workshops

          Tutorials

          Handouts

          Contact

               Search

WI+RE

                  Writing Instruction + Research Education

Quick and practical research and writing tutorials, collaboratively designed by students at UCLA.

                <button class="btn btn-light h-100">

Workshops

Gain a solid foundation in academic research and writing!

                </button>

                <button class="btn btn-light h-100">

Tutorials

Get right to it with quick and practical tutorials.

                </button>

                <button class="btn btn-light h-100">

Handouts

Prefer to work on paper? No problem - we make printable handouts, too.

                </button>

Hi! We're WI+RE.

WI+RE is a learner-led community focused on helping everyone succeed in their writing and research projects.

                    Meet the Creative Team »

                    Visit WI+RE's Sandbox »

                    Our Design Tools and Process »

We share!

As strong believers in open educational resources, all of our work is open source, and our tips can be shared, re-used, and re-mixed under creative commons Attribution-NonCommercial-ShareAlike license.

Want to collaborate? We would too! Check out our code repository and let us know your ideas!

Featured Tutorials

Primary and Secondary Sources

                                    How to tell the difference between primary and secondary sources.

                            Tutorial

                                Handout

Creating Literature Reviews

                                    Demystify the ever mysterious literature review!

                            Tutorial

Expanding Perspectives in Your Search

                                    Move past your initial search to expand your perspectives on your topic.

                            Tutorial

Featured Workshops

Getting Started with Research at UCLA

                                    Looking to get involved with research at UCLA? In this workshop, you'll meet five UCLA Undergraduate students as they explain their unique research journeys. Anyone can do research, and this workshop connects you with resources and opportunities to help you get started today!

                            Start the workshop

Finding Sources with the UCLA Library

                                    Navigate your research with ease and pick out the best sources for your project! In this module, you'll explore the library research guides, learn strategies for finding the information you need, and find out about research consultations.

                            Start the workshop

            All content on this site is Creative Commons Attribution-NonCommercial-ShareAlike by  The WI+RE Team 2020

The WI+RE team is grateful for the ongoing support of UCLA Library.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Schinzia alni Woronin

### Remarks
null


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddOccupati extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('anagrafiche', function($table)
		{
			$table->boolean('interventoOccupato')->default('0');
		});
		Schema::table('antenne', function($table)
		{
			$table->boolean('interventoOccupato')->default('0');
		});
		Schema::table('routers', function($table)
		{
			$table->boolean('interventoOccupato')->default('0');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		//
	}

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Internal;

namespace Mapster.EFCore
{
    class MapsterQueryable : IQueryable
    {
        private readonly IQueryable _queryable;
        public MapsterQueryable(IQueryable queryable, IAdapterBuilder builder)
        {
            _queryable = queryable;
            this.Provider = new MapsterQueryableProvider(queryable.Provider, builder);
        }

        IEnumerator IEnumerable.GetEnumerator() => this.Provider.Execute<IEnumerable>(this.Expression).GetEnumerator();

        public Type ElementType => _queryable.ElementType;
        public Expression Expression => _queryable.Expression;
        public IQueryProvider Provider { get; }
    }
    class MapsterQueryable<T> : MapsterQueryable, IQueryable<T>, IAsyncEnumerable<T>
    {
        public MapsterQueryable(IQueryable<T> queryable, IAdapterBuilder builder) :
            base(queryable, builder) { }
        public IEnumerator<T> GetEnumerator() => this.Provider.Execute<IEnumerable<T>>(this.Expression).GetEnumerator();

        public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
        {
            var enumerable = this.Provider is MapsterQueryableProvider mp
                ? mp.ExecuteEnumerableAsync<T>(this.Expression, cancellationToken)
                : ((IAsyncQueryProvider) this.Provider)
                    .ExecuteAsync<IAsyncEnumerable<T>>(this.Expression, cancellationToken);
            return enumerable.GetAsyncEnumerator(cancellationToken);
        }
    }

    class MapsterQueryableProvider : IAsyncQueryProvider
    {
        private readonly IQueryProvider _provider;
        private readonly IAdapterBuilder _builder;

        public MapsterQueryableProvider(IQueryProvider provider, IAdapterBuilder builder)
        {
            _provider = provider;
            _builder = builder;
        }

        public IQueryable CreateQuery(Expression expression)
        {
            return new MapsterQueryable(_provider.CreateQuery(expression), _builder);
        }

        public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
        {
            return new MapsterQueryable<TElement>(_provider.CreateQuery<TElement>(expression), _builder);
        }

        public object Execute(Expression expression)
        {
            using (_builder.CreateMapContextScope())
            {
                return _provider.Execute(expression);
            }
        }

        public TResult Execute<TResult>(Expression expression)
        {
            using (_builder.CreateMapContextScope())
            {
                return _provider.Execute<TResult>(expression);
            }
        }

        public TResult ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken = default)
        {
            var enumerable = ((IAsyncQueryProvider)_provider).ExecuteAsync<TResult>(expression, cancellationToken);
            var enumerableType = typeof(TResult);
            var elementType = enumerableType.GetGenericArguments()[0];
            var wrapType = typeof(MapsterAsyncEnumerable<>).MakeGenericType(elementType);
            return (TResult) Activator.CreateInstance(wrapType, enumerable, _builder);
        }

        public IAsyncEnumerable<TResult> ExecuteEnumerableAsync<TResult>(Expression expression, CancellationToken cancellationToken = default)
        {
            var enumerable = ((IAsyncQueryProvider)_provider).ExecuteAsync<IAsyncEnumerable<TResult>>(expression, cancellationToken);
            return new MapsterAsyncEnumerable<TResult>(enumerable, _builder);
        }

        //public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression)
        //{
        //    var enumerable = ((IAsyncQueryProvider) _provider).ExecuteAsync<IAsyncEnumerable<TResult>>(expression);
        //    return new MapsterAsyncEnumerable<TResult>(enumerable, _builder);
        //}

        //public async Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken)
        //{
        //    using (_builder.CreateMapContextScope())
        //    {
        //        return await ((IAsyncQueryProvider) _provider).ExecuteAsync<TResult>(expression, cancellationToken);
        //    }
        //}
    }

    class MapsterAsyncEnumerable<T> : IAsyncEnumerable<T>
    {
        private readonly IAsyncEnumerable<T> _enumerable;
        private readonly IAdapterBuilder _builder;
        public MapsterAsyncEnumerable(IAsyncEnumerable<T> enumerable, IAdapterBuilder builder)
        {
            _enumerable = enumerable;
            _builder = builder;
        }

        public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
        {
            return new MapsterAsyncEnumerator<T>(_enumerable.GetAsyncEnumerator(cancellationToken), _builder);
        }
    }

    class MapsterAsyncEnumerator<T> : IAsyncEnumerator<T>
    {
        private readonly IAsyncEnumerator<T> _enumerator;
        private readonly MapContextScope _scope;
        public MapsterAsyncEnumerator(IAsyncEnumerator<T> enumerator, IAdapterBuilder builder)
        {
            _enumerator = enumerator;
            _scope = builder.CreateMapContextScope();
        }

        public ValueTask<bool> MoveNextAsync()
        {
            return _enumerator.MoveNextAsync();
        }

        public T Current => _enumerator.Current;
        public ValueTask DisposeAsync()
        {
            _scope.Dispose();
            return _enumerator.DisposeAsync();
        }
    }
}


text:
status: publish
tags:
- real life
published: true
title: Entstoibert
type: post
meta:
  tags: wahl05 stoiber
layout: post
---
Ich bin ja erschüttert, förmlich. Da hat es sich ausgestoibert im Merkelschen Kompetenzteam.

Ich meine, eine illustre Truppe, die sie sich da zusammengestellt hat. (Vor allem, dass das Finanzressort wirklich einer übernehmen soll, der rechnen kann, ist für "Schattenkabinette" eher ungewöhnlich... Aber Darth Beckstein und däumchen drehende Küchenhilfen stellen das Gleichgewicht dann wieder her ;) ) Also ganz rund eigentlich, die Mannschaft im schwarzen Trikot. Nur der - nie um einen unpassenden Kommentar verlegene - MittelstürmerFast-Superminister Edmund fehlt. Dabei hat der doch jüngst so überaus kompetent über die Vorlieben ostdeutscher Wähler philosophiert.

Ob man den Bundestag auch nicht wählen darf, wenn man sich die Unterlagen von West nach Ost schicken lässt, hat der gute Edmund aber offen gelassen. Wie nachlässig. Ich bin mir sicher, die Exilwessis sind jetzt tierisch verunsichert.

Jaja: Sic transit gloria edmundi.


text:
<?php

namespace DesignPatterns\Behavioral\Specification;

interface SpecificationInterface
{
    public function isSatisfiedBy(Item $item): bool;
}


text:
package eu.inn.samza.mesos.mapping

import eu.inn.samza.mesos.MesosTask
import org.apache.mesos.Protos.Offer

import scala.collection.JavaConversions._

object TaskOfferMapper {
  implicit def Offer2ResourceHolder(offer: Offer) = new ResourceHolder {

    override def getResourceList: Map[String, Double] =
      offer.getResourcesList.map(r => (r.getName, r.getScalar.getValue)).toMap

    override def getAttributeList: Map[String, String] =
      offer.getAttributesList.map(r => (r.getName, r.getText.getValue)).toMap
  }
}

class TaskOfferMapper(strategy: ResourceMappingStrategy) {

  import TaskOfferMapper.Offer2ResourceHolder

  private val constraints = new ResourceConstraints

  def addCpuConstraint(cores: Double): TaskOfferMapper = {
    constraints.requireResource("cpus", cores)
    this
  }

  def addMemConstraint(sizeMb: Double): TaskOfferMapper = {
    constraints.requireResource("mem", sizeMb)
    this
  }

  def addDiskConstraint(sizeMb: Double): TaskOfferMapper = {
    constraints.requireResource("disk", sizeMb)
    this
  }

  def addAttributeConstraint(attributes: (String, String)*): TaskOfferMapper = {
    for (attr <- attributes) constraints.requireSupport(attr._1, attr._2)
    this
  }

  def mapResources(offers: Iterable[Offer], tasks: Set[MesosTask]): Map[Offer, Set[MesosTask]] = {
    strategy.mapResources(offers, tasks, constraints)
  }
}


text:
#ifndef TENSORFLOW_COMPILER_JIT_LEGACY_FLAGS_PARALLEL_CHECK_OP_FLAGS_H_
#define TENSORFLOW_COMPILER_JIT_LEGACY_FLAGS_PARALLEL_CHECK_OP_FLAGS_H_

// Legacy flags for the XLA bridge's parallel_check_op module.

#include <vector>

#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/command_line_flags.h"

namespace tensorflow {
namespace legacy_flags {

// Append to *flag_list flag definitions associated with the XLA bridge's
// parallel_check_op module.
void AppendParallelCheckOpFlags(std::vector<tensorflow::Flag>* flag_list);

// The values of flags associated with the XLA bridge's
// parallel_check_op module.
typedef struct {
  bool parallel_check_failfast;  // Fail immediately on first parallel-check
                                 // comparison error.
  string parallel_check_atol;    // Absolute error tolerance for parallel-check
                                 // comparison.
  string parallel_check_rtol;    // Relative error tolerance for parallel-check
                                 // comparison.
} ParallelCheckOpFlags;

// Return a pointer to the ParallelCheckOpFlags struct;
// repeated calls return the same pointer.
// This should be called only after Flags::Parse() has returned.
ParallelCheckOpFlags* GetParallelCheckOpFlags();

}  // namespace legacy_flags
}  // namespace tensorflow

#endif  // TENSORFLOW_COMPILER_JIT_LEGACY_FLAGS_PARALLEL_CHECK_OP_FLAGS_H_


text:
"""Tests for tf.contrib.tensor_forest.ops.count_extremely_random_stats."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

from tensorflow.contrib.tensor_forest.python.ops import training_ops

from tensorflow.python.framework import test_util
from tensorflow.python.platform import googletest

class CountExtremelyRandomStatsTest(test_util.TensorFlowTestCase):

  def setUp(self):
    self.input_data = [[-1., 0.], [-1., 2.],  # node 1
                       [1., 0.], [1., -2.]]  # node 2
    self.input_labels = [0, 1, 2, 3]
    self.tree = [[1, 0], [-1, 0], [-1, 0]]
    self.tree_thresholds = [0., 0., 0.]
    self.node_map = [-1, 0, -1]
    self.split_features = [[1], [-1]]
    self.split_thresholds = [[1.], [0.]]
    self.ops = training_ops.Load()

  def testSimple(self):
    with self.test_session():
      (pcw_node, pcw_splits_indices, pcw_splits_delta, pcw_totals_indices,
       pcw_totals_delta, leaves) = (
           self.ops.count_extremely_random_stats(
               self.input_data, self.input_labels, self.tree,
               self.tree_thresholds, self.node_map,
               self.split_features, self.split_thresholds, num_classes=4))

      self.assertAllEqual(
          [[1., 1., 1., 1.], [1., 1., 0., 0.], [0., 0., 1., 1.]],
          pcw_node.eval())
      self.assertAllEqual([[0, 0, 0]], pcw_splits_indices.eval())
      self.assertAllEqual([1.], pcw_splits_delta.eval())
      self.assertAllEqual([[0, 1], [0, 0]], pcw_totals_indices.eval())
      self.assertAllEqual([1., 1.], pcw_totals_delta.eval())
      self.assertAllEqual([1, 1, 2, 2], leaves.eval())

  def testThreaded(self):
    with self.test_session(
        config=tf.ConfigProto(intra_op_parallelism_threads=2)):
      (pcw_node, pcw_splits_indices, pcw_splits_delta, pcw_totals_indices,
       pcw_totals_delta,
       leaves) = (self.ops.count_extremely_random_stats(self.input_data,
                                                        self.input_labels,
                                                        self.tree,
                                                        self.tree_thresholds,
                                                        self.node_map,
                                                        self.split_features,
                                                        self.split_thresholds,
                                                        num_classes=4))

      self.assertAllEqual([[1., 1., 1., 1.], [1., 1., 0., 0.],
                           [0., 0., 1., 1.]],
                          pcw_node.eval())
      self.assertAllEqual([[0, 0, 0]], pcw_splits_indices.eval())
      self.assertAllEqual([1.], pcw_splits_delta.eval())
      self.assertAllEqual([[0, 1], [0, 0]], pcw_totals_indices.eval())
      self.assertAllEqual([1., 1.], pcw_totals_delta.eval())
      self.assertAllEqual([1, 1, 2, 2], leaves.eval())

  def testNoAccumulators(self):
    with self.test_session():
      (pcw_node, pcw_splits_indices, pcw_splits_delta, pcw_totals_indices,
       pcw_totals_delta, leaves) = (
           self.ops.count_extremely_random_stats(
               self.input_data, self.input_labels, self.tree,
               self.tree_thresholds, [-1] * 3,
               self.split_features, self.split_thresholds, num_classes=4))

      self.assertAllEqual([[1., 1., 1., 1.], [1., 1., 0., 0.],
                           [0., 0., 1., 1.]],
                          pcw_node.eval())
      self.assertEquals((0, 3), pcw_splits_indices.eval().shape)
      self.assertAllEqual([], pcw_splits_delta.eval())
      self.assertEquals((0, 2), pcw_totals_indices.eval().shape)
      self.assertAllEqual([], pcw_totals_delta.eval())
      self.assertAllEqual([1, 1, 2, 2], leaves.eval())

  def testBadInput(self):
    del self.node_map[-1]

    with self.test_session():
      with self.assertRaisesOpError(
          'Number of nodes should be the same in '
          'tree, tree_thresholds, and node_to_accumulator'):
        pcw_node, _, _, _, _, _ = (
            self.ops.count_extremely_random_stats(
                self.input_data, self.input_labels, self.tree,
                self.tree_thresholds, self.node_map,
                self.split_features, self.split_thresholds, num_classes=4))

        self.assertAllEqual([], pcw_node.eval())

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


text:
// Generated Source

interface BotExtensionCreationRequest {

    /**
     * Bot name (equals to extension first name)
     */
    name?: string;

    /**
     * Key of a bot application
     */
    applicationKey?: string;

    /**
     * User extension identifier
     */
    creatorId?: string;
}

export default BotExtensionCreationRequest;


text: The perfect app for any sports fan


text:
<?php
/**
 * @package    apostrophePlugin
 * @subpackage    form
 * @author     P'unk Avenue <apostrophe@punkave.com>
 */
class aSmartSlideshowForm extends BaseaSmartSlideshowForm
{
}


text:
/*
 * 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.
 */

#include <cstddef>
#include <fstream>
#include <math.h>
#include <unistd.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <list>

#include "AnsHeap.h"
#include "AnswerTree.h"
#include "Bchart.h"
#include "Bst.h"
#include "ChartBase.h"
#include "ECArgs.h"
#include "ECString.h"
#include "ewDciTokStrm.h"
#include "extraMain.h"
#include "GotIter.h"
#include "InputTree.h"
#include "Link.h"
#include "MeChart.h"
#include "Params.h"
#include "ParseStats.h"
#include "ScoreTree.h"
#include "SentRep.h"
#include "TimeIt.h"
#include "UnitRules.h"
#include "utils.h"
#include "Wrd.h"

extern int sentenceCount;
static const double log600 = log2(600.0);
typedef pair<double,InputTree*> ScoredTree;

class ParserError {
    public:
        ParserError(string msg);
        ParserError(const char *filename, int filelinenum, const char *msg);

        string description;
};

class LabeledSpan {
    public:
        int start;
        int end;
        int termIndex;

        LabeledSpan();
        LabeledSpan(int startIndex, int endIndex, string termName);
        int size();
        bool disrupts(int otherStart, int otherEnd);
        bool operator==(const LabeledSpan& other) const;
        bool operator!=(const LabeledSpan& other) const;
        bool operator<(const LabeledSpan& other) const;
        friend ostream& operator<<(ostream& os, const LabeledSpan& span);
};

class LabeledSpans: public vector<LabeledSpan> {
    public:
        int minSizeForParsing;
        bool sorted;
        LabeledSpans();
        void addConstraint(int start, int end, string term);
        static void spansFromTree(InputTree* tree, LabeledSpans& spans);

        void ensureSorted();
        bool matches(InputTree* tree);
        bool applyToChart(ChartBase* chart, int length);
        bool disrupts(int start, int end);
};

vector<ScoredTree>* parse(SentRep* sent, ExtPos& tagConstraints,
                          LabeledSpans* spanConstraints);
vector<ScoredTree>* parse(SentRep* sent);

ParseStats* getParseStats(InputTree* proposed, InputTree* gold);

double fscore(InputTree* proposed, InputTree* gold);

double treeLogProb(InputTree* tree);

void loadTermsOnly(string modelPath);
void loadHeadInfoOnly(string modelPath);

void setOptions(string language, bool caseInsensitive, int nBest,
        bool smallCorpus, double overparsing, int debug,
        float smoothPosAmount);

SentRep* tokenize(string text, int expectedTokens);
SentRep* tokenize(string text);

InputTree* inputTreeFromString(const char* str);
list<InputTree* >* inputTreesFromString(const char* str);
list<InputTree* >* inputTreesFromFile(const char* filename);
list<SentRep* >* sentRepsFromString(const char* str);
list<SentRep* >* sentRepsFromFile(const char* filename);

string asNBestList(vector<ScoredTree>& scoredTrees, string sentenceId);

string ptbEscape(string word);
string ptbUnescape(string word);


text:
'use strict'

var tap = require('tap')
var setDistance = require('../lib/setDistance')

tap.test('it requires an item object', function (test) {
  var item = false
  var expectedErrorMessage = 'Missing required input: item object'
  setDistance(item, function (error, data) {
    tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
    test.done()
  })
})

tap.test('it requires item.schoolAddresseForMeasurement to exist', function (test) {
  var item = {
    schoolAddresseForMeasurement: false
  }
  var expectedErrorMessage = 'Missing required input: item.schoolAddresseForMeasurement'
  setDistance(item, function (error, data) {
    tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
    test.done()
  })
})

tap.test('it requires item.registeredAddressForMeasurement to exist', function (test) {
  var item = {
    schoolAddresseForMeasurement: true,
    registeredAddressForMeasurement: false
  }
  var expectedErrorMessage = 'Missing required input: item.registeredAddressForMeasurement'
  setDistance(item, function (error, data) {
    tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
    test.done()
  })
})

tap.test('it measures the walking distance from registered address', function (test) {
  var item = require('./data/automatic_yes_distance.json')
  item.schoolAddresseForMeasurement = item.skoleAdresse
  item.registeredAddressForMeasurement = item.folkeregistrertAdresseAdresse
  setDistance(item, function (error, data) {
    if (error) {
      throw error
    }
    tap.equal(data.measuredDistanceRegisteredAddress.distanceValue, item.measuredDistanceRegisteredAddress.distanceValue)
    test.done()
  })
})


text:
TEST(Try, result_is_true) {
  auto a_try = Result(std::string{"result"});
  ASSERT_TRUE(a_try);
  ASSERT_TRUE(a_try.successful());
  ASSERT_FALSE(a_try.failure());
}

TEST(Try, failure_is_false) {
  auto a_try = Failure<std::string>("exploded");
  ASSERT_FALSE(a_try);
  ASSERT_FALSE(a_try.successful());
  ASSERT_TRUE(a_try.failure());
}

TEST(Try, failure_has_reason) {
  auto a_try = Failure<std::string>("exploded");
  ASSERT_EQ(std::string{"exploded"}, a_try.failure_reason());
}

TEST(Try, result_is_shared_ptr) {
  auto a_try = Result(std::string{"result"});
  std::shared_ptr<std::string> ptr = a_try;
  ASSERT_EQ(2, ptr.use_count());
}

TEST(Try, result_derefences) {
  auto a_try = Result(std::string{"result"});
  std::shared_ptr<std::string> ptr = a_try;
  ASSERT_EQ(typeid(std::string), typeid(*a_try));
  ASSERT_EQ(typeid(std::string), typeid(from_result(a_try)));
  ASSERT_EQ(std::string{"result"}, *a_try);
}

TEST(Try, result_from_returning_lambda) {
  auto a_try = TryFrom<std::string>([]() {
    return std::string{"lambda"};
  });
  ASSERT_TRUE(a_try);
  ASSERT_EQ(std::string{"lambda"}, *a_try);
}

TEST(Try, failure_from_throwing_lambda) {
  auto a_try = TryFrom<std::string>([]() {
    throw std::runtime_error{"exploded"};
    return std::string{"lambda"};
  });
  ASSERT_FALSE(a_try);
  ASSERT_EQ(std::string{"exploded"}, a_try.failure_reason());
}


text:
/* global $state, $location */
/* eslint-disable no-unused-expressions */
describe('State: 404', () => {
  beforeEach(module('app.states'))

  describe('route', () => {
    const views = {
      four0four: 'app/states/404/404.html'
    }

    beforeEach(() => {
      bard.inject('$location', '$rootScope', '$state')
    })

    it('should map /404 route to 404 View template', () => {
      expect($state.get('404').templateUrl).to.equal(views.four0four)
    })

    it('should work with $state.go', () => {
      $state.go('404')
      expect($state.is('404'))
    })

    it('should route /invalid to the otherwise (404) route', (done) => {
      $location.path('/invalid')
      done()
      expect($state.current.templateUrl).to.equal(views.four0four)
    })
  })
})


text:
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Runtime.Serialization.Formatters.Binary;

using Microsoft.VisualStudio.DebuggerVisualizers;

using Duality;
using Duality.Drawing;
using Duality.Resources;

[assembly: DebuggerVisualizer(
	typeof(Duality.VisualStudio.BitmapDebuggerVisualizer),
	typeof(Duality.VisualStudio.TextureAtlasDebuggerVisualizerObjectSource),
	Target = typeof(Texture),
	Description = "Texture Atlas Visualizer")]

namespace Duality.VisualStudio
{
	public class TextureAtlasDebuggerVisualizerObjectSource : VisualizerObjectSource
	{
		public override void GetData(object target, Stream outgoingData)
		{
			Texture texture = target as Texture;
			Pixmap.Layer layer = texture.RetrievePixelData();
			Bitmap bitmap = layer.ToBitmap();

			if (texture.BasePixmap.Res != null)
			{
				PixmapAtlasDebuggerVisualizerObjectSource.VisualizeAtlas(bitmap, texture.BasePixmap.Res.Atlas);
			}

			BinaryFormatter formatter = new BinaryFormatter();
			formatter.Serialize(outgoingData, texture.ToString());
			formatter.Serialize(outgoingData, bitmap);
			outgoingData.Flush();
		}
	}
}


text:
import Component from '@ember/component';
// @ts-ignore: Ignore import of compiled template
import layout from '../templates/components/expandable-content';
import { classNames } from '@ember-decorators/component';
import { action } from '@ember/object';

const baseComponentClass = 'expandable-content';

@classNames(`${baseComponentClass}__container`)
export default class ExpandableContent extends Component {
  layout = layout;

  /**
   * Leads to ease of use in the template level
   * @type {string}
   */
  baseComponentClass = baseComponentClass;

  /**
   * The expanded state of this component. When the user clicks on the button trigger, it'll toggle this
   * between expanded and unexpanded. Can optionally be passed in as a parameter, or defaulted to being
   * a local property
   * @type {boolean}
   */
  isExpanded = false;

  /**
   * Toggles the expanded state of this component, which will then reveal the yielded content in an
   * "expanded" window
   */
  @action
  toggleExpanded(): void {
    this.toggleProperty('isExpanded');
  }
}


text:
+++
comments = true
date = 2014-09-24T00:00:00Z
title = "Swift – Object metadata explained"
description = "An in-depth analysis on how the meta data is stores in OpenStack Swift."
+++

![metadata](/assets/metadata.jpg)
Openstack Swift – we all know stores its objects reliably, in a replicated manner. How does swift store the information about the object itself ? i.e. metadata information ?

The answer is  xattrs. a.k.a extended attributes.
**Extended file attributes** is a file system feature that enables users to associate computer files with metadata not interpreted by the file system.  These are properties organized in (name, value) pairs, optionally set to files or directories in order to record information which cannot be stored in the file itself.

Names are null-terminated printable character strings which are up to 256 bytes in length, while their associated values can contain up to 64 KB of binary data in case of XFS.
More on extended file attributes [here](http://en.wikipedia.org/wiki/Extended_file_attributes).

The extended attributes can be accessed by commands getfattr and set using setfattr.
Consider the following example of a file obj-2 uploaded using swift.
{{< highlight bash >}}
# swift -A http://127.0.0.1:8080/auth/v1.0 -U test:tester -K testing upload cont1 obj-2
{{< / highlight >}}

Using swift-get-nodes, we can see the partition for the uploaded object is 859 and hash is d6e5c4cbcdfb4b1f5e786d4e624b24e4
{{< highlight bash >}}
# swift-get-nodes  -a /etc/swift/object.ring.gz AUTH_test/cont1/obj-2

Account  	AUTH_test
Container	cont1
Object   	obj-2

Partition	859
Hash     	d6e5c4cbcdfb4b1f5e786d4e624b24e4
{{< / highlight >}}

Using this partition information, one can lookup to the file on the swift node.
{{< highlight text >}}
|-- 1 -> /mnt/sdb1/1
|   `-- node
|       `-- sdb1
|           |-- objects
|           |   |-- 155
|           |   |   `-- 716
|           |   |       `-- 26ddfcaf7d30709da094d31572a8d716
|           |   |           `-- 1412007292.47349.data
|           |   `-- 859
|           |       `-- 4e4
|           |           `-- d6e5c4cbcdfb4b1f5e786d4e624b24e4
|           |               `-- 1412011351.04987.data
{{< / highlight >}}

Now, lets examine the contents of "1412011351.04987.data" using getfattr.
{{< highlight bash >}}
$ getfattr 1412011351.04987.data
# file: 1412011351.04987.data
user.swift.metadata

$ getfattr -n user.swift.metadata 1412011351.04987.data
# file: 1412011351.04987.data
user.swift.metadata="�}q(UContent-LengthqU13UnameqU/AUTH_test/cont1/obj-2qUX-Object-Meta-MtimeU1412011318.077730qUETagqU 8ddd8be4b179a529afa5f2ffae4b9858qU
                                                                                X-TimestampU1412011351.04987U
                      Content-Typeq	Uapplication/octet-streamq12u."
{{< / highlight >}}

As you can see, swift stores the metadata using extended attributes with the key "user.swift.metadata" and a dictionary as the value.
Lets now uncover the binary value. Following is a python utility program which reads from stdin and unpickles the data. save it as swift-meta.py
{{< highlight python >}}
# swift-meta.py
import pickle

with open("/dev/stdin") as f:
    print pickle.loads(f.read())
{{< / highlight >}}

Now, lets rerun the getfattr on the object with swift-meta.py.(note –only-values, else unpickling will creak)
{{< highlight bash >}}
$ getfattr -d --only-values -n user.swift.metadata 1412011351.04987.data | python swift-meta.py
{'Content-Length': '13', 'name': '/AUTH_test/cont1/obj-2', 'Content-Type': 'application/octet-stream', 'ETag': '8ddd8be4b179a529afa5f2ffae4b9858', 'X-Timestamp': '1412011351.04987', 'X-Object-Meta-Mtime': '1412011318.077730'}
{{< / highlight >}}

This is what we get when we do a stat on an object. As you can see, the same values stored above are stat'ed.
{{< highlight bash >}}
$ swift -A http://127.0.0.1:8080/auth/v1.0 -U test:tester -K testing stat cont1 obj-2
       Account: AUTH_test
     Container: cont1
        Object: obj-2
  Content Type: application/octet-stream
Content Length: 13
 Last Modified: Mon, 29 Sep 2014 17:22:32 GMT
          ETag: 8ddd8be4b179a529afa5f2ffae4b9858
    Meta Mtime: 1412011318.077730
 Accept-Ranges: bytes
    Connection: keep-alive
   X-Timestamp: 1412011351.04987
    X-Trans-Id: tx5c513a3673594d6d9ff16-00542998d9
{{< / highlight >}}

Now, lets add a custom metadata to see what gets stored in xattrs (–meta my_meta_1:orange).
{{< highlight bash >}}
$ swift -A http://127.0.0.1:8080/auth/v1.0 -U test:tester -K testing post cont1 obj-2 --meta my_meta_1:orange

$ getfattr -d --only-values -n user.swift.metadata 1412012477.02665.data | python swift-meta.py
{'Content-Length': '13', 'name': '/AUTH_test/cont1/obj-2', 'ETag': '8ddd8be4b179a529afa5f2ffae4b9858', 'X-Object-Meta-My-Meta-1': 'orange', 'X-Timestamp': '1412012477.02665', 'Content-Type': 'application/octet-stream'}
{{< / highlight >}}

As you can see, the user data gets stored as "Object-Meta-My-Meta-1" with value "orange", along with other set of metadata defined by swift for each object.


text:
/*
* 9. We are given a string containing a list of forbidden words and
* a text containing some of these words. Write a program that replaces the
* forbidden words with asterisks.
*
* Example:
* Microsoft announced its next generation PHP compiler today.
* It is based on .NET Framework 4.0 and is implemented as
* a dynamic language in CLR.
*
* Words: "PHP, CLR, Microsoft"
* The expected result:
* ********* announced its next generation *** compiler today.
* It is based on .NET Framework 4.0 and is implemented as
* a dynamic language in ***.
*/

using System;

namespace _09.ReplaceForbidenWords
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = Console.ReadLine();

            string[] forbidenWords = "PHP, CLR, Microsoft".Split(',');

            for (int i = 0; i < forbidenWords.Length; i++)
            {
                forbidenWords[i] = forbidenWords[i].Trim();
                text = text.Replace(forbidenWords[i], new string('*', forbidenWords[i].Length));
            }

            Console.WriteLine(text);
        }
    }
}


text:
// Copyright 2015 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package test

import (
    "encoding/hex"
    "encoding/binary"
    "os"
    "fmt"
    "bytes"
    "time"
    "strings"
    cp "github.com/FactomProject/FactomCode/controlpanel"
    fct "github.com/FactomProject/factoid"
    "github.com/FactomProject/factoid/state/stateinit"
    "github.com/FactomProject/factoid/state"
    "github.com/FactomProject/factoid/block"
    "github.com/FactomProject/factoid/database"
    "github.com/FactomProject/ed25519"
    "math/rand"
    "testing"
)

var _ = time.Second
var _ = state.FactoidState{}
var _ = hex.EncodeToString
var _ = fmt.Printf
var _ = ed25519.Sign
var _ = rand.New
var _ = binary.Write
var _ = fct.Prtln
var _ = stateinit.GetDatabase
var _ = database.MapDB{}

var fs *Test_state
// sets up teststate.go
func Test_setup_FactoidState (test *testing.T) {
    // Create a Test State
    fs = new(Test_state)
    fs.Init(test)
}

func PrtTrans(t fct.ITransaction){
    fmt.Println("Transaction")
    for _,input    := range t.GetInputs()    {
        fmt.Println("in ", input.GetAddress(), input.GetAmount(), fs.GetBalance(input.GetAddress()))
    }
    for _,output   := range t.GetOutputs()   {
        fmt.Println("out", output.GetAddress(), output.GetAmount(), fs.GetBalance(output.GetAddress()))
    }
    for _,ecoutput := range t.GetECOutputs() {
        fmt.Println("ec ", ecoutput.GetAddress(), ecoutput.GetAmount(), fs.GetECBalance(ecoutput.GetAddress()))
    }
}

// Run a simulation of Transactions and blocks designed to test a pseudo random transaction set.
// If randomize = 0, then we will use the clock to seed the random number generator, and print the
// 64 bit seed used.  If randomize is set to some value, we use that vaule (allowing us to repeat
// tests if we like.
func Test_create_genesis_FactoidState (test *testing.T) {
    randomize       := int64(0)

    numBlocks       := 15

    // Average number of BTC transactions per block is <1000 as of Aug 8, 2015
    // https://blockchain.info/charts/n-transactions-per-block
    numTransactions := 10     // Maximum Transactions

    if testing.Short() {
        fmt.Print("\nDoing Short Tests\n")
        numBlocks       = 5
        numTransactions = 20
    }
    block.UpdateAmount(10000000)
    if randomize == 0 {
        randomize = time.Now().UnixNano()
        rand.Seed(randomize)
        randomize = rand.Int63()
        rand.Seed(randomize)
    }else{
        rand.Seed(randomize)
    }

    fmt.Println("Randomize Seed Used: ",randomize)

    cp.CP.AddUpdate(
        "Test Parms",
        "status",                                                              // Category
        fmt.Sprintf("Number of Blocks %d Max number Transactions %d",
            numBlocks,numTransactions),
        fmt.Sprintf("Randomize Seed: %v",randomize),
        0)

    // Use Bolt DB
    if !testing.Short() {
        fs.SetDB(new(database.MapDB))
        fs.GetDB().Init()
        db := stateinit.GetDatabase("./fct_test.db")
        fs.GetDB().SetPersist(db)
        fs.GetDB().SetBacker(db)

        fs.GetDB().DoNotPersist(fct.DB_F_BALANCES)
        fs.GetDB().DoNotPersist(fct.DB_EC_BALANCES)
        fs.GetDB().DoNotPersist(fct.DB_BUILD_TRANS)
        fs.GetDB().DoNotCache(fct.DB_FACTOID_BLOCKS)
        fs.GetDB().DoNotCache(fct.DB_BAD_TRANS)
        fs.GetDB().DoNotCache(fct.DB_TRANSACTIONS)
    }else{
        fs.SetDB(new(database.MapDB))
        fs.GetDB().Init()
    }

    // Set the price for Factoids
    fs.SetFactoshisPerEC(100000)
    err := fs.LoadState()
    if err != nil {
        fmt.Println("Faid to initialize: ",err)
        os.Exit(1)
    }
    pre := fs.GetTransactionBlock(fs.GetCurrentBlock().GetPrevKeyMR())
    if !bytes.Equal(pre.GetHash().Bytes(), fs.GetCurrentBlock().GetPrevKeyMR().Bytes()) {
        fmt.Printf("Something is ill!")
        test.Fail()
        return
    }

    // Print the Genesis Block.  If we don't know the past, then print it.
    past := fs.GetTransactionBlock(pre.GetPrevKeyMR())
    if past == nil {
    for _,trans := range pre.GetTransactions() {
        PrtTrans(trans)
    }
    }

    if err != nil {
        fct.Prtln("Failed to load:", err)
        test.Fail()
        return
    }

    var max,min,maxblk int
    min = 100000
    // Create a number of blocks (i)
    for i:=0; i<numBlocks; i++ {

        fmt.Println("Block",fs.GetCurrentBlock().GetDBHeight())

        PrtTrans(fs.GetCurrentBlock().GetTransactions()[0])

        thisRunLimit := (rand.Int()%numTransactions)+1

        cp.CP.AddUpdate(
            "This Block",
            "status",                                                              // Category
            fmt.Sprintf("Number of Transactions we are putting in this block: %d",
                        thisRunLimit),
                        "",
                        0)

        var transCnt int
        periodMark := 1
        // Create a new block
        for j:=fs.stats.transactions; fs.stats.transactions < j+thisRunLimit; {      // Execute for some number RECORDED transactions
            transCnt++
            periodvalue := thisRunLimit/10
            delta := thisRunLimit/10/4
            if delta == 0 { delta = 1 }
            if rand.Int()%100 > 50 { delta = -delta }
            periodvalue += delta
            if periodvalue == 0 { periodvalue = 1 }

            if periodMark <=10 && transCnt%(periodvalue)==0 {
                fs.EndOfPeriod(periodMark)
                periodMark++
            }

            tx := fs.newTransaction()

            addtest := true
            flip := rand.Int()%100
            if rand.Int()%100 < 5 { // Mess up the timestamp on 5 percent of the transactions
                addtest = false
                blkts := uint64(fs.GetCurrentBlock().GetCoinbaseTimestamp())
                if flip < 49 {    // Flip a coin
                    tx.SetMilliTimestamp(blkts - uint64(fct.TRANSACTION_PRIOR_LIMIT)-1)
                    fs.stats.errors["trans too early"] += 1
                    fs.stats.full["trans too early"]="trans too early"
                }else{
                    tx.SetMilliTimestamp(blkts + uint64(fct.TRANSACTION_POST_LIMIT)+1)
                    fs.stats.errors["trans too late"] += 1
                    fs.stats.full["trans too late"]="trans too late"
                }
                fs.twallet.SignInputs(tx)
            }

            // Test Marshal/UnMarshal
            m,err := tx.MarshalBinary()
            if err != nil { fmt.Println("\n Failed to Marshal: ",err); test.Fail(); return }
            if len(m) > max {
                max = len(m)
                cp.CP.AddUpdate(
                    "max transaction size",                                              // tag
                    "info",                                                              // Category
                    fmt.Sprintf("Max Transaction Size %d",max),                          // Title
                    fmt.Sprintf("<pre>#inputs = %-3d  #outputs = %-3d  #ecoutputs = %-3d<pre>",
                       len(tx.GetInputs()),len(tx.GetOutputs()),len(tx.GetECOutputs())), // Msg
                    0)                                                                   // Expire
            }
            if len(m) < min {
                min = len(m)
                cp.CP.AddUpdate(
                    "min transaction size",                                              // tag
                    "info",                                                              // Category
                    fmt.Sprintf("Min Transaction Size %d",min),                          // Title
                    fmt.Sprintf("<pre>#inputs = %-3d  #outputs = %-3d  #ecoutputs = %-3d<pre>",
                       len(tx.GetInputs()),len(tx.GetOutputs()),len(tx.GetECOutputs())), // Msg
                    0)                                                                   // Expire
            }

            k := rand.Int()%(len(m)-2)
            k++
            good := true
            flip = rand.Int()%100
            // To simulate bad data, I mess up some of the data here.
            if rand.Int()%100 < 5 { // Mess up 5 percent of the transactions
                good = false
                if flip < 49 {    // Flip a coin
                    m = m[k:]
                    fs.stats.errors["lost start of trans"] += 1
                    fs.stats.full["lost start of trans"]="lost start of trans"
                }else{
                    m = m[:k]
                    fs.stats.errors["lost end of trans"] += 1
                    fs.stats.full["lost end of trans"]="lost end of trans"
                }
            }

            t := new(fct.Transaction)
            err = t.UnmarshalBinary(m)

            if good && tx.IsEqual(t) != nil {
                fmt.Println("Fail valid Unmarshal")
                test.Fail()
                return
            }
            if err == nil {
                if good && err != nil  {
                    fmt.Println("Added a transaction that should have failed to be added")
                    fmt.Println(err)
                    test.Fail();
                    return
                }
                if !good {
                    fmt.Println("Failed to add a transaction that should have added")
                    test.Fail();
                    return
                }
            }

            if good {
                err = fs.AddTransaction(j+1,t)
            }
            if !addtest  && err == nil {
                ts := int64(t.GetMilliTimestamp())
                bts := int64(fs.GetCurrentBlock().GetCoinbaseTimestamp())
                fmt.Println("timestamp failure ", ts, bts, ts-bts, fct.TRANSACTION_POST_LIMIT)
                test.Fail()
                return
            }
            if !addtest && err == nil {
                fmt.Println("failed to catch error")
                test.Fail()
                return
            }

            if addtest && good && err != nil {
                fmt.Println(err)
                fmt.Println("Unmarshal Failed. trans is good",
                            "\nand the error detected: ",err,
                            "\nand k:",k, "and flip:",flip)
                test.Fail()
                return
            }

            if good && addtest {

                PrtTrans(t)
                fs.stats.transactions += 1

                title := fmt.Sprintf("Bad Transactions: %d  Total transaactions %d",
                                     fs.stats.badAddresses,fs.stats.transactions)
                cp.CP.AddUpdate("Bad Transaction","status", title, "", 0)

                time.Sleep(time.Second/100)
            }else{
                fs.stats.badAddresses += 1
            }

        }
        //
        // Serialization deserialization tests for blocks
        //
        blkdata,err := fs.GetCurrentBlock().MarshalBinary()
        if err != nil { test.Fail(); return }
        blk := fs.GetCurrentBlock().GetNewInstance().(block.IFBlock)
        err = blk.UnmarshalBinary(blkdata)
        if err != nil { test.Fail(); return }

        fmt.Println("Block Check")

        // Collect our block pointers, MR Key, and LMR Key before we process the end of block
        blk1     := fs.GetCurrentBlock()
        blk1KMR  := blk1.GetHash()
        blk1LKMR := blk1.GetLedgerKeyMR()

        // Process the end of block.  This simulates what Factomd will do.
        fmt.Println("ProcessEndOfBlock")
        fs.ProcessEndOfBlock()             // Process the block.
        fmt.Println("Check ProcessEndOfBlock")

        // Collect the new block pointer, Previous MR Key and LMR Key after we processed the block.
        blk2      := fs.GetCurrentBlock()
        blk2PKMR  := blk2.GetPrevKeyMR()
        blk2PLKMR := blk2.GetPrevLedgerKeyMR()

        // Check that the Previous MR and LMR match what we had from the previous block.
        if !bytes.Equal(blk1KMR.Bytes(),blk2PKMR.Bytes()) {
            fmt.Println("MR's don't match")
            test.Fail()
            return
        }
        if !bytes.Equal(blk1LKMR.Bytes(),blk2PLKMR.Bytes()) {
            fmt.Println("LKMR's don't match")
            fmt.Println(" block: ",blk1LKMR)
            fmt.Println(" Prev:  ",blk2PLKMR)
            test.Fail()
            return
        }

        // Now we marshal and unmarshal to simulate a reboot, getting our blocks for the DB
        data, err := blk1.MarshalBinary()
        if err != nil {
            fmt.Println("Failed to Marshal")
            test.Fail()
            return
        }
        blk1b := new(block.FBlock)
        err = blk1b.UnmarshalBinary(data)
        if err != nil {
            fmt.Println("Failed to Unmarshal")
            test.Fail()
            return
        }

        // Does the marshal and unmarshal of the block yeild the same MR and LMR?  If so GOOD!
        if !bytes.Equal(blk2PKMR.Bytes(),blk1b.GetKeyMR().Bytes()) {
            fmt.Println("Unmarshaled KeyMR values do not match")
            test.Fail()
            return
        }
        if !bytes.Equal(blk2PLKMR.Bytes(),blk1b.GetLedgerKeyMR().Bytes()) {
            fmt.Println("Unmarshaled LedgerKeyMR values do not match")
            test.Fail()
            return
        }

        /************************************************************
         *                Reporting to the Control Panel
         ************************************************************/
        {
            c := 1
            keys := make([]string, 0, len(fs.stats.errors))
            for k := range fs.stats.errors {
                keys = append(keys, k)
            }
            for i := 0; i<len(keys)-1; i++ {
                for j:=0;j<len(keys)-i-1; j++ {
                    if keys[j]<keys[j+1] {
                        t := keys[j]
                        keys[j] = keys[j+1]
                        keys[j+1]=t
                    }
                }
            }
            var out bytes.Buffer
            for _,key := range keys {
                ecnt := fs.stats.errors[key]
                by  := []byte(fs.stats.full[key])
                prt := string(by)
                if len(prt)>80 { prt = string(by[:80])+"..." }
                prt = strings.Replace(prt,"\n"," ",-1)
                out.WriteString(fmt.Sprintf("%6d %s\n",ecnt,prt))
                c++
            }

            cp.CP.AddUpdate(
                "transerrors",                                    // tag
                "errors",                                         // Category
                "Transaction Info & Errors:",                     // Title
                "<pre>"+string(out.Bytes())+"</pre>",             // Msg
                0)                                                // Expires

        }

        if len(blkdata)>maxblk {
            maxblk = len(blkdata)
            cp.CP.AddUpdate(
                "maxblocksize",                                   // tag
                "info",                                           // Category
                fmt.Sprintf("Max Block Size: %dK",maxblk/1024),   // Title
                "",                                               // Msg
                0)                                                // Expires
        }

         sec1    := fs.stats.TransactionsPerSec()
         sec2    := fs.stats.TotalTransactionsPerSec()

         cp.CP.AddUpdate(
                "transpersec",                                    // tag
                "status",                                         // Category
                fmt.Sprintf("Transactions per second %4.2f, (+ bad) %4.2f",sec1,sec2), // Title
                "",                                               // Msg
                0)                                                // Expires
    }
    fmt.Println("\nDone")
//     // Get the head of the Factoid Chain
//     blk := fs.GetTransactionBlock(fct.FACTOID_CHAINID_HASH)
//     hashes := make([]fct.IHash,0,10)
//     // First run back from the head back to the genesis block, collecting hashes.
//     for {
//         h := blk.GetHash()
//         hashes = append(hashes,h)
//         if bytes.Compare(blk.GetPrevKeyMR().Bytes(),fct.ZERO) == 0 {
//             break
//         }
//         tblk := fs.GetTransactionBlock(blk.GetPrevKeyMR())
//         blk = tblk
//         time.Sleep(time.Second/100)
//     }
//
//     // Now run forward, and build our accounting
//     for i := len(hashes)-1; i>=0; i-- {
//         blk = fs.GetTransactionBlock(hashes[i])
//         fmt.Println("Block",blk.GetDBHeight())
//         for _,trans := range blk.GetTransactions() {
//             PrtTrans(trans)
//         }
//     }
}


text:
package org.apache.drill.test.rowSet;

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

import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
import org.apache.drill.exec.record.MaterializedField;

/**
 * Builder of a row set schema expressed as a list of materialized
 * fields. Optimized for use when creating schemas by hand in tests.
 *

 * Example usage to create the following schema:

 * <tt>(c: INT, a: MAP(b: VARCHAR, d: INT, e: MAP(f: VARCHAR), g: INT), h: BIGINT)</tt>
 *

 * Code:

 *     BatchSchema batchSchema = new SchemaBuilder()
 *        .add("c", MinorType.INT)
 *        .addMap("a")
 *          .addNullable("b", MinorType.VARCHAR)
 *          .add("d", MinorType.INT)
 *          .addMap("e")
 *            .add("f", MinorType.VARCHAR)
 *            .buildMap()
 *          .add("g", MinorType.INT)
 *          .buildMap()
 *        .addArray("h", MinorType.BIGINT)
 *        .build();
 * </code

 */

public class SchemaBuilder {

  /**
   * Build a column schema (AKA "materialized field") based on name and a
   * variety of schema options. Every column needs a name and (minor) type,
   * some may need a mode other than required, may need a width, may
   * need scale and precision, and so on.
   */

  // TODO: Add map methods

  public static class ColumnBuilder {
    private final String name;
    private final MajorType.Builder typeBuilder;

    public ColumnBuilder(String name, MinorType type) {
      this.name = name;
      typeBuilder = MajorType.newBuilder()
          .setMinorType(type)
          .setMode(DataMode.REQUIRED);
    }

    public ColumnBuilder setMode(DataMode mode) {
      typeBuilder.setMode(mode);
      return this;
    }

    public ColumnBuilder setWidth(int width) {
      typeBuilder.setPrecision(width);
      return this;
    }

    public ColumnBuilder setScale(int scale, int precision) {
      typeBuilder.setScale(scale);
      typeBuilder.setPrecision(precision);
      return this;
    }

    public MaterializedField build() {
      return MaterializedField.create(name, typeBuilder.build());
    }
  }

  /**
   * Internal structure for building a map. A map is just a schema,
   * but one that is part of a parent column.
   */

  public static class MapBuilder extends SchemaBuilder {
    private final SchemaBuilder parent;
    private final String memberName;

    public MapBuilder(SchemaBuilder parent, String memberName) {
      this.parent = parent;
      this.memberName = memberName;
    }

    @Override
    public BatchSchema build() {
      throw new IllegalStateException("Cannot build for a nested schema");
    }

    @Override
    public SchemaBuilder buildMap() {
      MaterializedField col = columnSchema(memberName, MinorType.MAP, DataMode.REQUIRED);
      for (MaterializedField childCol : columns) {
        col.addChild(childCol);
      }
      parent.finishMap(col);
      return parent;
    }

    @Override
    public SchemaBuilder withSVMode(SelectionVectorMode svMode) {
      throw new IllegalStateException("Cannot set SVMode for a nested schema");
    }
  }

  protected List<MaterializedField> columns = new ArrayList<>( );
  private SelectionVectorMode svMode = SelectionVectorMode.NONE;

  public SchemaBuilder() { }

  /**
   * Create a new schema starting with the base schema. Allows appending
   * additional columns to an additional schema.
   */

  public SchemaBuilder(BatchSchema baseSchema) {
    for (MaterializedField field : baseSchema) {
      add(field);
    }
  }

  public SchemaBuilder add(String pathName, MajorType type) {
    return add(MaterializedField.create(pathName, type));
  }

  public SchemaBuilder add(MaterializedField col) {
    columns.add(col);
    return this;
  }

  /**
   * Create a column schema using the "basic three" properties of name, type and
   * cardinality (AKA "data mode.") Use the {@link ColumnBuilder} for to set
   * other schema attributes.
   */

  public static MaterializedField columnSchema(String pathName, MinorType type, DataMode mode) {
    return MaterializedField.create(pathName,
        MajorType.newBuilder()
          .setMinorType(type)
          .setMode(mode)
          .build());
  }

  public SchemaBuilder add(String pathName, MinorType type, DataMode mode) {
    return add(columnSchema(pathName, type, mode));
  }

  public SchemaBuilder add(String pathName, MinorType type) {
    return add(pathName, type, DataMode.REQUIRED);
  }

  public SchemaBuilder add(String pathName, MinorType type, int width) {
    MaterializedField field = new SchemaBuilder.ColumnBuilder(pathName, type)
        .setMode(DataMode.REQUIRED)
        .setWidth(width)
        .build();
    return add(field);
  }

  public SchemaBuilder addNullable(String pathName, MinorType type) {
    return add(pathName, type, DataMode.OPTIONAL);
  }

  public SchemaBuilder addNullable(String pathName, MinorType type, int width) {
    MaterializedField field = new SchemaBuilder.ColumnBuilder(pathName, type)
        .setMode(DataMode.OPTIONAL)
        .setWidth(width)
        .build();
    return add(field);
  }

  public SchemaBuilder addArray(String pathName, MinorType type) {
    return add(pathName, type, DataMode.REPEATED);
  }

  /**
   * Add a map column. The returned schema builder is for the nested
   * map. Building that map, using {@link MapBuilder#buildMap()},
   * will return the original schema builder.
   *
   * @param pathName the name of the map column
   * @return a builder for the map
   */

  public MapBuilder addMap(String pathName) {
    return new MapBuilder(this, pathName);
  }

  public SchemaBuilder withSVMode(SelectionVectorMode svMode) {
    this.svMode = svMode;
    return this;
  }

  public BatchSchema build() {
    return new BatchSchema(svMode, columns);
  }

  void finishMap(MaterializedField map) {
    columns.add(map);
  }

  public SchemaBuilder buildMap() {
    throw new IllegalStateException("Cannot build map for a top-level schema");
  }
}


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.0, minimum-scale=0.5, maximum-scale=3.0">
    <link rel="icon" href="https://cdn.xgqfrms.xyz/logo/favicon.ico" type="image/x-icon">
    <link rel="icon" href="https://cdn.xgqfrms.xyz/logo/favicon.png" type="image/png">
    <base href="/">
    <meta name="author" content="xgqfrms, webgeeker">
    <meta name="keywords" content="xgqfrms, webgeeker, github,Tutorials, ES5 ES6 ES7, React 2, Angular 2, Ionic 2">
    <meta name="description" content="xgqfrms's learning website! & xgqfrms, webgeeker, Tutorials, ES5 ES6 ES7, React 2, Angular 2, Ionic 2">
    <meta name="application-name" content="learning.xgqfrms.xyz">
    <meta name="generator" content="Sublime Text 3, Visual Studio Code 1.8, Google Chrome Canary, GitHub, React 2, Angular 2, Ionic 2">
    <link rel="author" type="text/plain" href="https://learning.xgqfrms.xyz/humans.txt" />
    <title>https://learning.xgqfrms.xyz/about</title>

about me

        https://learning.xgqfrms.xyz/about.html


text:
package org.apache.tapestry5.integration.app1.pages;

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

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.OptionGroupModel;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.integration.app1.data.Entity;
import org.apache.tapestry5.integration.app1.data.IncidentData;
import org.apache.tapestry5.internal.OptionGroupModelImpl;
import org.apache.tapestry5.internal.OptionModelImpl;
import org.apache.tapestry5.util.AbstractSelectModel;

public class OptionGroupForm {

    @Property
    @Persist
    private Entity entity;

    private static final List<Entity> entityList = Arrays.asList(new Entity("1", "label1"), new Entity("2", "label2"), new Entity("3", "label3"));

    void onPrepare()
    {
        if (entity == null)
        {
            entity = new Entity();
            entity.setId("1");
            entity.setLabel("label1");
        }
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "form")
    public void onFormSuccess() {
        // It's OK we should come here on form submission
    }

    @OnEvent(value = EventConstants.FAILURE, component = "form")
    public void onFormFailure() throws Exception {
        throw new Exception("The form should have been successfully submitted");
    }

    public SelectModel getModel() {
        return new AbstractSelectModel() {

            private List<OptionGroupModel> groupModels = null;

            public List<OptionModel> getOptions() {
                return null;
            }

            public List<OptionGroupModel> getOptionGroups() {
                if (groupModels == null) {
                    computeModel();
                }
                return groupModels;
            }

            private void computeModel() {
                groupModels = new ArrayList<OptionGroupModel>();
                for (Entity entity : entityList) {
                    List<OptionModel> options = new ArrayList<OptionModel>();
                    options.add(new OptionModelImpl(entity.getLabel(), entity));

                    OptionGroupModel groupModel = new OptionGroupModelImpl(entity.getLabel(), false, options);
                    groupModels.add(groupModel);
                }

            }
        };
    }
}


text:
package logbook.internal.gui;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableColumn.SortType;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TreeItemPropertyValueFactory;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
import logbook.bean.AppConfig;
import logbook.bean.AppViewConfig;
import logbook.bean.AppViewConfig.CreateItemLogConfig;
import logbook.bean.SlotitemEquiptype;
import logbook.bean.SlotitemEquiptypeCollection;
import logbook.bean.SlotitemMst;
import logbook.bean.SlotitemMstCollection;
import logbook.internal.Items;
import logbook.internal.LoggerHolder;
import logbook.internal.Tuple;
import logbook.internal.log.CreateitemLogFormat;
import logbook.internal.log.LogWriter;
import lombok.EqualsAndHashCode;
import lombok.val;

/**
 * 開発ログ
 *
 */
public class CreateItemController extends WindowController {

    @FXML
    private SplitPane splitPane;

    /** 集計 */
    @FXML
    private TreeTableView<CreateItemCollect> collect;

    /** 集計 */
    @FXML
    private TreeTableColumn<CreateItemCollect, String> unit;

    /** 件数 */
    @FXML
    private TreeTableColumn<CreateItemCollect, Integer> count;

    /** 割合 */
    @FXML
    private TreeTableColumn<CreateItemCollect, String> ratio;

    /** トグルボタン */
    @FXML
    private ToggleGroup group;

    /** 装備→投入資材 */
    @FXML
    private ToggleButton buttonItemRecipe;

    /** 投入資材→装備 */
    @FXML
    private ToggleButton buttonRecipeItem;

    /** 明細 */
    @FXML
    private TableView<CreateItem> detail;

    /** 行番号 */
    @FXML
    private TableColumn<BattleLogDetail, Integer> row;

    /** 日付 */
    @FXML
    private TableColumn<CreateItem, String> date;

    /** 装備 */
    @FXML
    private TableColumn<CreateItem, String> item;

    /** 種類 */
    @FXML
    private TableColumn<CreateItem, String> type;

    /** 投入資材 */
    @FXML
    private TableColumn<CreateItem, Recipe> recipe;

    /** 秘書艦 */
    @FXML
    private TableColumn<CreateItem, String> secretary;

    private Map<CreateItemCollect, List<CreateItem>> detailList = new HashMap<>();

    private ObservableList<CreateItem> detailItems = FXCollections.observableArrayList();

    @FXML
    void initialize() {
        try {
            TableTool.setVisible(this.detail, this.getClass() + "#" + "detail");
            // SplitPaneの分割サイズ
            Timeline x = new Timeline();
            x.getKeyFrames().add(new KeyFrame(Duration.millis(1), (e) -> {
                Tools.Controls.setSplitWidth(this.splitPane, this.getClass() + "#" + "splitPane");
            }));
            x.play();
            this.detail.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
            this.detail.setOnKeyPressed(TableTool::defaultOnKeyPressedHandler);
            SortedList<CreateItem> sorted = new SortedList<CreateItem>(this.detailItems);
            this.detail.setItems(sorted);
            sorted.comparatorProperty().bind(this.detail.comparatorProperty());

            Map<String, SlotitemMst> unitToType3 = this.unitToType3();
            this.unit.setCellFactory(p -> new ItemIconCell(unitToType3));
            this.unit.setCellValueFactory(new TreeItemPropertyValueFactory<>("unit"));
            this.count.setCellValueFactory(new TreeItemPropertyValueFactory<>("count"));
            this.ratio.setCellValueFactory(new TreeItemPropertyValueFactory<>("ratio"));

            this.row.setCellFactory(TableTool.getRowCountCellFactory());
            this.date.setCellValueFactory(new PropertyValueFactory<>("date"));
            this.item.setCellValueFactory(new PropertyValueFactory<>("item"));
            this.type.setCellValueFactory(new PropertyValueFactory<>("type"));
            this.recipe.setCellValueFactory(new PropertyValueFactory<>("recipe"));
            this.secretary.setCellValueFactory(new PropertyValueFactory<>("secretary"));

            this.collect.setSortPolicy((param) -> {
                Optional.ofNullable(this.collect.getRoot()).map(TreeItem::getChildren).ifPresent(items -> sortItems(param.getSortOrder(), items));
                return true;
            });
            this.collect.getSelectionModel()
                    .selectedItemProperty()
                    .addListener(this::detail);
            this.group.selectedToggleProperty()
                    .addListener(this::changeType);
            this.setCollect(this.buttonItemRecipe);
            loadConfig();
            TreeTableTool.setVisible(this.collect, this.getClass() + "#" + "collect");
        } catch (Exception e) {
            LoggerHolder.get().error("FXMLの初期化に失敗しました", e);
        }
    }

    private void sortItems(List<TreeTableColumn<CreateItemCollect, ?>> sortOrder, List<TreeItem<CreateItemCollect>> items) {
        items.sort((o1, o2) -> {
            CreateItemCollect c1 = o1.getValue();
            CreateItemCollect c2 = o2.getValue();
            int diff = 0;
            for (TreeTableColumn<CreateItemCollect, ?> order: sortOrder) {
                if (order == this.unit) {
                    diff = c1.getUnit().compareTo(c2.getUnit());
                } else if (order == this.count) {
                    diff = c1.getCount() - c2.getCount();
                } else if (order == this.ratio) {
                    // アイテムごとの列だと空の場合もある
                    if (c1.getRatio() != null && c2.getRatio() != null) {
                        double dd = c1.getRatio() - c2.getRatio();
                        diff = dd > 0.0 ? 1 : (dd < 0.0 ? -1 : 0);
                    }
                }
                if (diff != 0) {
                    int alpha = order.getSortType() == SortType.DESCENDING ? -1 : 1;
                    return alpha * diff;
                }
            }
            // デフォルトは predefined sort order の昇順
            diff = c1.getSortOrder() - c2.getSortOrder();
            if (diff == 0) {
                diff = c1.getUnit().compareTo(c2.getUnit());
            }
            return diff;
        });
        // 子供もソート
        items.forEach(item -> sortItems(sortOrder, item.getChildren()));
    }

    @FXML
    void copyDetail(ActionEvent event) {
        TableTool.selectionCopy(this.detail);
    }

    @FXML
    void selectAllDetail(ActionEvent event) {
        TableTool.selectAll(this.detail);
    }

    @FXML
    void columnVisibleDetail(ActionEvent event) {
        try {
            TableTool.showVisibleSetting(this.detail, this.getClass() + "#" + "detail",
                    this.getWindow());
        } catch (Exception e) {
            LoggerHolder.get().error("FXMLの初期化に失敗しました", e);
        }
    }

    /**
     * 集計単位からアイコンを引くためのMap
     * @return type3
     */
    private Map<String, SlotitemMst> unitToType3() {
        val type2To3 = SlotitemMstCollection.get().getSlotitemMap()
                .values()
                .stream()
                .collect(toMap(item -> item.getType().get(2), Function.identity(), (a, b) -> a));
        Map<String, SlotitemMst> unitToType3 = SlotitemEquiptypeCollection.get()
                .getEquiptypeMap()
                .values()
                .stream()
                .filter(e -> type2To3.containsKey(e.getId()))
                .collect(toMap(SlotitemEquiptype::getName, item -> type2To3.get(item.getId())));
        unitToType3.putAll(
                SlotitemMstCollection.get().getSlotitemMap()
                        .values()
                        .stream()
                        .collect(toMap(SlotitemMst::getName, Function.identity(), (a, b) -> a)));
        return unitToType3;
    }

    /**
     * 集計する
     * @param button 集計タイプ
     */
    private void setCollect(Toggle button) {
        this.detailList.clear();
        Path logFile = Paths.get(AppConfig.get().getReportPath(), new CreateitemLogFormat().fileName());
        try {
            List<CreateItem> logs;
            Map<String, Integer> map = SlotitemEquiptypeCollection.get().getEquiptypeMap().values().stream()
                .collect(Collectors.toMap(SlotitemEquiptype::getName, SlotitemEquiptype::getId));
            try (Stream<String> lines = Files.lines(logFile, LogWriter.DEFAULT_CHARSET)) {
                logs = lines.skip(1)
                        .map(CreateItem::parse)
                        .filter(Objects::nonNull)
                        .map(item -> item.setEquipType(map.getOrDefault(item.getType(), -1)))
                        .collect(toList());
            }

            Map<Recipe, Long> count = logs.stream()
                    .collect(groupingBy(CreateItem::getRecipe, counting()));

            Map<?, ?> grouping = Collections.emptyMap();
            CreateItemCollect rootCollect = new CreateItemCollect();
            if (button == this.buttonItemRecipe) {
                rootCollect.setUnit("全件 (成功のみ)");
                grouping = logs.stream()
                        .filter(item -> !item.getItem().isEmpty())
                        .sorted(Comparator.comparing(CreateItem::getEquipType)
                                .thenComparing(CreateItem::getItem)
                                .thenComparing(CreateItem::getRecipe))
                        .collect(groupingBy((item) -> Tuple.of(item.getEquipType(), item.getType()), LinkedHashMap::new,
                                groupingBy(CreateItem::getItem, LinkedHashMap::new,
                                        groupingBy(CreateItem::getRecipe, LinkedHashMap::new,
                                                toList()))));
            }
            if (button == this.buttonRecipeItem) {
                rootCollect.setUnit("全件 (失敗も含む)");
                grouping = logs.stream()
                        .sorted(Comparator.comparing(CreateItem::getRecipe)
                                .thenComparing(CreateItem::getType)
                                .thenComparing(CreateItem::getItem))
                        .collect(groupingBy(CreateItem::getRecipe, LinkedHashMap::new,
                                groupingBy(CreateItem::getItem, LinkedHashMap::new,
                                        toList())));
            }

            TreeItem<CreateItemCollect> root = this.collect.getRoot();
            if (root == null) {
                root = new TreeItem<>();
                root.setValue(rootCollect);
                root.setExpanded(true);
                this.collect.setRoot(root);
            } else {
                this.collect.getRoot().getChildren().clear();
                this.collect.getRoot().setValue(rootCollect);
            }
            this.collect.setShowRoot(true);
            this.setUnit(root, count, null, grouping);
            setCount(root);
        } catch (Exception e) {
            LoggerHolder.get().warn("開発報告書の読込中に例外", e);
        }
    }

    /**
     * 左ペインに表示するツリーを構築する
     * @param parent
     * @param count
     * @param recipe
     * @param grouping
     */
    @SuppressWarnings("unchecked")
    private void setUnit(TreeItem<CreateItemCollect> parent,
            Map<Recipe, Long> count,
            Recipe recipe,
            Map<?, ?> grouping) {
        for (val entry : grouping.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            Tuple.Pair<Integer, String> pair = null;
            if (key instanceof Recipe) {
                recipe = (Recipe) key;
            } else if (key instanceof Tuple.Pair) {
                pair = (Tuple.Pair<Integer, String>)key;
            }
            CreateItemCollect item = new CreateItemCollect();
            if ("".equals(key)) {
                item.setUnit("(失敗)");
            } else if (pair != null) {
                item.setUnit(pair.getValue());
                item.setSortOrder(pair.getKey());
            } else {
                item.setUnit(key.toString());
            }
            if (recipe != null) {
                List<CreateItem> rows = this.getSubItem(value);
                Collections.sort(rows, Comparator.comparing(CreateItem::getDate));

                int size = rows.size();
                long total = count.get(recipe);
                double ratio = BigDecimal.valueOf(size)
                        .divide(BigDecimal.valueOf(total), 4, RoundingMode.FLOOR)
                        .multiply(BigDecimal.valueOf(100))
                        .setScale(2)
                        .doubleValue();
                item.setCount(size);
                item.setRatio(ratio);

                this.detailList.put(item, rows);
            }

            TreeItem<CreateItemCollect> unitRoot = new TreeItem<>(item);
            parent.getChildren().add(unitRoot);

            if (value instanceof Map) {
                this.setUnit(unitRoot, count, recipe, (Map<?, ?>) value);
            }
            if (recipe == null) {
                setCount(unitRoot);
            }
        }
    }

    private static void setCount(TreeItem<CreateItemCollect> item) {
        item.getValue().setCount(item.getChildren().stream().map(TreeItem::getValue).mapToInt(CreateItemCollect::getCount).sum());
    }

    private List<CreateItem> getSubItem(Object maporlist) {
        List<CreateItem> list = new ArrayList<>();
        if (maporlist instanceof Map) {
            for (Object obj : ((Map<?, ?>) maporlist).values()) {
                list.addAll(this.getSubItem(obj));
            }
        }
        if (maporlist instanceof List) {
            for (Object obj : (List<?>) maporlist) {
                list.add(((CreateItem) obj));
            }
        }
        return list;
    }

    /**
     * 右ペインに詳細表示するリスナー
     *
     * @param observable 値が変更されたObservableValue
     * @param oldValue 古い値
     * @param value 新しい値
     */
    private void detail(ObservableValue<? extends TreeItem<CreateItemCollect>> observable,
            TreeItem<CreateItemCollect> oldValue, TreeItem<CreateItemCollect> value) {
        if (value != null) {
            this.detailItems.clear();
            addItems(this.detailItems, value);
        }
    }

    private void addItems(List<CreateItem> list, TreeItem<CreateItemCollect> value) {
        Optional<List<CreateItem>> v = Optional.ofNullable(this.detailList.get(value.getValue()));
        if (v.isPresent()) {
            list.addAll(v.get());
        } else {
            value.getChildren().forEach(child -> addItems(list, child));
        }
    }

    /**
     * 集計タイプの変更
     *
     * @param observable 値が変更されたObservableValue
     * @param oldValue 古い値
     * @param value 新しい値
     */
    private void changeType(ObservableValue<? extends Toggle> observable,
            Toggle oldValue, Toggle value) {
        this.setCollect(value);
        saveConfig();
    }

    private void loadConfig() {
        Optional.ofNullable(AppViewConfig.get().getCreateItemLogConfig())
            .ifPresent(config -> {
                if (config.getIndex() == 1) {
                    this.group.selectToggle(this.buttonRecipeItem);
                }
            });
    }

    private void saveConfig() {
        CreateItemLogConfig config = AppViewConfig.get().getCreateItemLogConfig();
        if (config == null) {
            config = new CreateItemLogConfig();
        }
        config.setIndex(this.group.getSelectedToggle() == this.buttonItemRecipe ? 0 : 1);
        AppViewConfig.get().setCreateItemLogConfig(config);
    }

    /**
     * 装備アイコンセル
     */
    private static class ItemIconCell extends TreeTableCell<CreateItemCollect, String> {

        private Map<String, SlotitemMst> unitToType3;

        public ItemIconCell(Map<String, SlotitemMst> unitToType3) {
            this.unitToType3 = unitToType3;
        }

        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (!empty) {
                this.setText(item);
                SlotitemMst mst = this.unitToType3.get(item);
                if (mst != null) {
                    ImageView image = new ImageView(Items.itemImage(mst));
                    image.setFitHeight(24);
                    image.setFitWidth(24);
                    this.setGraphic(image);
                } else {
                    this.setGraphic(null);
                }
            } else {
                this.setText(item);
                this.setGraphic(null);
            }
        }
    }

    /**
     * 明細
     */
    public static class CreateItem {

        /** 日付 */
        private StringProperty date = new SimpleStringProperty();

        /** 装備 */
        private StringProperty item = new SimpleStringProperty();

        /** 種類 */
        private StringProperty type = new SimpleStringProperty();

        /** 投入資材 */
        private ObjectProperty<Recipe> recipe = new SimpleObjectProperty<Recipe>();

        /** 秘書艦 */
        private StringProperty secretary = new SimpleStringProperty();

        /** SlotitemEquiptype */
        private int equipType;

        /**
         * 日付を取得します。
         * @return 日付
         */
        public StringProperty dateProperty() {
            return this.date;
        }

        /**
         * 日付を取得します。
         * @return 日付
         */
        public String getDate() {
            return this.date.get();
        }

        /**
         * 日付を設定します。
         * @param date 日付
         */
        public void setDate(String date) {
            this.date.set(date);
        }

        /**
         * 装備を取得します。
         * @return 装備
         */
        public StringProperty itemProperty() {
            return this.item;
        }

        /**
         * 装備を取得します。
         * @return 装備
         */
        public String getItem() {
            return this.item.get();
        }

        /**
         * 装備を設定します。
         * @param item 装備
         */
        public void setItem(String item) {
            this.item.set(item);
        }

        /**
         * 種類を取得します。
         * @return 種類
         */
        public StringProperty typeProperty() {
            return this.type;
        }

        /**
         * 種類を取得します。
         * @return 種類
         */
        public String getType() {
            return this.type.get();
        }

        /**
         * 種類を設定します。
         * @param type 種類
         */
        public void setType(String type) {
            this.type.set(type);
        }

        /**
         * 投入資材を取得します。
         * @return 投入資材
         */
        public ObjectProperty<Recipe> recipeProperty() {
            return this.recipe;
        }

        /**
         * 投入資材を取得します。
         * @return 投入資材
         */
        public Recipe getRecipe() {
            return this.recipe.get();
        }

        /**
         * 投入資材を設定します。
         * @param recipe 投入資材
         */
        public void setRecipe(Recipe recipe) {
            this.recipe.set(recipe);
        }

        /**
         * 秘書艦を取得します。
         * @return 秘書艦
         */
        public StringProperty secretaryProperty() {
            return this.secretary;
        }

        /**
         * 秘書艦を取得します。
         * @return 秘書艦
         */
        public String getSecretary() {
            return this.secretary.get();
        }

        /**
         * 秘書艦を設定します。
         * @param secretary 秘書艦
         */
        public void setSecretary(String secretary) {
            this.secretary.set(secretary);
        }

        public int getEquipType() {
            return this.equipType;
        }

        public CreateItem setEquipType(int equipType) {
            this.equipType = equipType;
            return this;
        }

        @Override
        public String toString() {
            return new StringJoiner("\t")
                    .add(this.date.get())
                    .add(this.item.get())
                    .add(this.type.get())
                    .add(String.valueOf(this.recipe.get()))
                    .add(this.secretary.get())
                    .toString();
        }

        public static CreateItem parse(String line) {
            try {
                String[] columns = line.split(",", -1);
                CreateItem value = new CreateItem();
                value.setDate(columns[0]);
                value.setItem(columns[1]);
                value.setType(columns[2]);
                value.setRecipe(new Recipe(columns[3], columns[4], columns[5], columns[6]));
                value.setSecretary(columns[7]);
                return value;
            } catch (Exception e) {
            }
            return null;
        }
    }

    /**
     * 集計
     */
    public static class CreateItemCollect {

        /** 単位 */
        private StringProperty unit = new SimpleStringProperty();

        /** 回数 */
        private IntegerProperty count = new SimpleIntegerProperty();

        /** 割合 */
        private Double ratio;

        /** ソート順 */
        private int sortOrder;

        /**
         * 単位を取得します。
         * @return 単位
         */
        public StringProperty unitProperty() {
            return this.unit;
        }

        /**
         * 単位を取得します。
         * @return 単位
         */
        public String getUnit() {
            return this.unit.get();
        }

        /**
         * 単位を設定します。
         * @param unit 単位
         */
        public void setUnit(String unit) {
            this.unit.set(unit);
        }

        /**
         * 回数を取得します。
         * @return 回数
         */
        public IntegerProperty countProperty() {
            return this.count;
        }

        /**
         * 回数を取得します。
         * @return 回数
         */
        public int getCount() {
            return this.count.get();
        }

        /**
         * 回数を設定します。
         * @param count 回数
         */
        public void setCount(int count) {
            this.count.set(count);
        }

        /**
         * 割合を取得します。
         * @return 割合
         */
        public StringProperty ratioProperty() {
            return new SimpleStringProperty(this.ratio != null ? this.ratio + "%" : "");
        }

        /**
         * 割合を取得します。
         * @return 割合
         */
        public Double getRatio() {
            return this.ratio;
        }

        /**
         * 割合を設定します。
         * @param ratio 割合
         */
        public void setRatio(Double ratio) {
            this.ratio = ratio;
        }

        /**
         * ソート順を取得します。
         * @return ソート順
         */
        public int getSortOrder() {
            return this.sortOrder;
        }

        /**
         * ソート順を設定します。
         * @param sortOrder ソート順
         */
        public void setSortOrder(int sortOrder) {
            this.sortOrder = sortOrder;
        }
    }

    /**
     * 投入資材
     */
    @EqualsAndHashCode
    private static class Recipe implements Comparable<Recipe> {

        /** 燃料 */
        private final int fuel;

        /** 弾薬 */
        private final int ammo;

        /** 鋼材 */
        private final int metal;

        /** ボーキサイト */
        private int bauxite;

        public Recipe(String fuel, String ammo, String metal, String bauxite) {
            this.fuel = Integer.parseInt(fuel);
            this.ammo = Integer.parseInt(ammo);
            this.metal = Integer.parseInt(metal);
            this.bauxite = Integer.parseInt(bauxite);
        }

        @Override
        public int compareTo(Recipe o) {
            if (this.fuel != o.fuel)
                return Integer.compare(this.fuel, o.fuel);
            if (this.ammo != o.ammo)
                return Integer.compare(this.ammo, o.ammo);
            if (this.metal != o.metal)
                return Integer.compare(this.metal, o.metal);
            if (this.bauxite != o.bauxite)
                return Integer.compare(this.bauxite, o.bauxite);
            return 0;
        }

        @Override
        public String toString() {
            return this.fuel + "/" + this.ammo + "/" + this.metal + "/" + this.bauxite;
        }
    }
}


text:
"""
The MIT License (MIT)
Copyright (c) 2015 Christophe Aubert
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

import dataBase.sqlite3.ProbeData
from dataBase.sqlite3 import ConnectDB

class DbQuery(ConnectDB.ConnectDB):
    def __init__(self, path, name):
        ConnectDB.ConnectDB.__init__(self, path, name)
        self.connect()

    def query(self):
        _data = self.cursor.execute('''SELECT v_probe,
                                              v_date,
                                              v_ozone,
                                              v_temperature,
                                              v_groundHumidity,
                                              v_airHumidity FROM value''')

        _probeData = dataBase.sqlite3.ProbeData.ProbeData()

        for row in _data:

            _probeData.setValue(row['v_probe'],row['v_date'],row['v_ozone'],row['v_temperature'],row['v_groundHumidity'],row['v_airHumidity'])
            #print _probeData.toJson()