text:
hystrix-codahale-metrics-publisher [![Build Status](https://travis-ci.org/ImmobilienScout24/hystrix-codahale-metrics-publisher.png?branch=master)](https://travis-ci.org/ImmobilienScout24/hystrix-codahale-metrics-publisher)
===================================

This is an implementation of [HystrixMetricsPublisher](http://netflix.github.com/Hystrix/javadoc/index.html?com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisher.html) that publishes metrics using [Coda Hale Yammer Metrics](http://metrics.codahale.com) Version 3.

Usage
-----

```xml
<dependency>
    <groupId>de.is24.hystrix</groupId>
    <artifactId>hystrix-codahale-metrics-publisher</artifactId>
    <version>1.0</version>
</dependency>
```
      HystrixPlugins.getInstance().registerMetricsPublisher(new HystrixCodahaleMetricsPublisher(yourMetricRegistry));

See the Hystrix [Metrics & Monitoring](https://github.com/Netflix/Hystrix/wiki/Metrics-and-Monitoring) Wiki for more information.


text:
package com.google.android.connecteddevice.calendarsync.common;

import com.google.android.connecteddevice.calendarsync.Calendar.TimeRange;
import com.google.android.connecteddevice.calendarsync.Timestamp;
import com.google.common.collect.Range;
import java.time.Instant;

/** Utility methods used for converting time related values used in update.proto */
public final class TimeProtoUtil {

  private TimeProtoUtil() {}

  /** Converts a {@link TimeRange} to a {@link Range<Instant>}. */
  public static Range<Instant> toInstantRange(TimeRange range) {
    return Range.openClosed(toInstant(range.getFrom()), toInstant(range.getTo()));
  }

  /** Converts a {@link Timestamp} to a {@link Instant}. */
  public static Instant toInstant(Timestamp timestamp) {
    return Instant.ofEpochSecond(timestamp.getSeconds());
  }

  /** Converts a {@link Range<Instant>} to a {@link TimeRange}. */
  public static TimeRange toTimeRange(Range<Instant> range) {
    return TimeRange.newBuilder()
        .setFrom(toTimestamp(range.lowerEndpoint()))
        .setTo(toTimestamp(range.upperEndpoint()))
        .build();
  }

  /** Converts a {@link Instant} to a {@link Timestamp}. */
  public static Timestamp toTimestamp(Instant instant) {
    return Timestamp.newBuilder().setSeconds(instant.getEpochSecond()).build();
  }
}

redpajama_set_name: RedPajamaGithub


text:
const DrawCard = require('../../drawcard.js');

class SeptonMeribald extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Stand up to 3 characters',
            cost: ability.costs.kneelSelf(),
            target: {
                mode: 'upTo',
                numCards: 3,
                cardCondition: card => card.location === 'play area' && card.getType() === 'character' &&
                                       card.getPrintedStrength() <= 1 && card.kneeled,
                gameAction: 'stand'
            },
            handler: context => {
                for(let card of context.target) {
                    card.controller.standCard(card);
                }
                this.game.addMessage('{0} kneels {1} to stand {2}', context.player, this, context.target);
            }
        });
    }
}

SeptonMeribald.code = '10040';

module.exports = SeptonMeribald;


text:
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    app.run(debug=True)


text:
package com.guidewire.tools.marathon.client.api

import scalaz._
import dispatch._
import play.api.libs.json._
import scala.concurrent.ExecutionContext

import com.guidewire.tools.marathon.client._

import scala.language.implicitConversions

trait ClientTasks { self: ClientVersion =>
  import Client._

  type VersionSpecificTask <: Task
  type VersionSpecificTaskKill <: TaskKill

  val VersionSpecificTaskFormat: Format[VersionSpecificTask]
  val VersionSpecificTaskApply : Task.Apply[VersionSpecificTask]

  val VersionSpecificTaskKillFormat: Format[VersionSpecificTaskKill]
  val VersionSpecificTaskKillApply : TaskKill.Apply[VersionSpecificTaskKill]

  /** Provides access to a [[play.api.libs.json.Format]] for serializing [[com.guidewire.tools.marathon.client.Task]] instances. */
  lazy implicit val TaskFormat    : Format[Task]       = mapJsonFormat(VersionSpecificTaskFormat)

  /** Composes the URI for querying all tasks. This will end up being similar to `http://<host>:<port>/v1/tasks`. */
  def uriQueryTasks(configuration: Connection): String =
    s"http://${configuration.host}:${configuration.port}/$uriVersionPart/tasks"

  /** Composes the URI for killing tasks. This will end up being similar to `http://<host>:<port>/v1/tasks/kill`. */
  def uriKillTasks(taskKill: TaskKill)(configuration: Connection): String =
    (url(s"http://${configuration.host}:${configuration.port}/$uriVersionPart/tasks/kill") <<? Seq(
        ("appId", taskKill.appId)
      , ("host", taskKill.host)
      , ("id", taskKill.id)
      , ("scale", taskKill.scale.toString.toLowerCase)
    )).url

  /**
   * Makes a call to (effectively) `GET /v1/tasks` and deserializes the payload.
   *
   * @param connection data for constructing the tasks URI
   * @return a [[scalaz.Validation]] that can be composed using normal scalaz methods
   */
  def queryTasks(implicit connection: Connection, executor: ExecutionContext): Future[Validation[Error, Map[String, Traversable[Task]]]] =
    httpGet[Map[String, Traversable[Task]]](connection)(uriQueryTasks)(parseQueryTasksResponse)

  /**
   * Performs the actual parsing and validation of a JSON payload representing the payload from a call
   * to `GET /v1/tasks`.
   *
   * @param response JSON contents to parse and map to a [[scala.collection.Traversable]]
   *                 of [[com.guidewire.tools.marathon.client.Task]]
   * @return a [[scalaz.Validation]] that can be composed using normal scalaz methods
   */
  def parseQueryTasksResponse(statusCode: Int, response: Array[Byte]): Validation[Error, Map[String, Traversable[Task]]] =
    validateify(statusCode, Json.parse(response).validate[Map[String, Seq[Task]]])

  /**
   * Makes a call to (effectively) `POST /v1/tasks/kill` to kill existing tasks and returns the result.
   *
   * @param connection data for constructing the task kill URI
   * @param taskKill app ID, host, id, scale et. al. needed for killing tasks
   * @return a [[scalaz.Validation]] that can be composed using normal scalaz methods
   */
  def killTasks(taskKill: TaskKill)(implicit connection: Connection, executor: ExecutionContext): Future[Validation[Error, Traversable[Task]]] =
    httpPostEmpty[TaskKill, Traversable[Task]](taskKill, connection)(uriKillTasks(taskKill))(parsePostKillTasksResponse)

  /**
   * Performs the actual parsing and validation of a JSON payload representing the payload from a call
   * to `POST /v1/apps/stop`.
   *
   * @param response JSON contents to parse and map to a [[scala.collection.Traversable]] of
   *                 [[com.guidewire.tools.marathon.client.Task]]
   * @return a [[scalaz.Validation]] that can be composed using normal scalaz methods
   */
  def parsePostKillTasksResponse(statusCode: Int, response: Array[Byte]): Validation[Error, Traversable[Task]] =
    validateify(statusCode, Json.parse(response).validate[Seq[Task]])
}


text:
Meteor.startup(function() {
	RocketChat.MessageTypes.registerType({
		id: 'message_pinned',
		system: true,
		message: 'Pinned_a_message',
	});
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharpGL;

namespace PBR.IBLSpecular {
    partial class PBRNode {
        private const string vertexCode = @"#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoords;
layout (location = 2) in vec3 aNormal;

out vec2 TexCoords;
out vec3 WorldPos;
out vec3 Normal;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main()
{
    TexCoords = aTexCoords;
    WorldPos = vec3(model * vec4(aPos, 1.0));
    Normal = mat3(model) * aNormal;

    gl_Position =  projection * view * vec4(WorldPos, 1.0);
}
";

        private const string fragmentCode = @"#version 330 core
out vec4 FragColor;
in vec2 TexCoords;
in vec3 WorldPos;
in vec3 Normal;

// material parameters
uniform vec3 albedo;
uniform float metallic;
uniform float roughness;
uniform float ao;

// IBL
uniform samplerCube irradianceMap;
uniform samplerCube prefilterMap;
uniform sampler2D brdfLUT;

// lights
uniform vec3 lightPositions[4];
uniform vec3 lightColors[4];

uniform vec3 camPos;

const float PI = 3.14159265359;
// ----------------------------------------------------------------------------
float DistributionGGX(vec3 N, vec3 H, float roughness)
{
    float a = roughness*roughness;
    float a2 = a*a;
    float NdotH = max(dot(N, H), 0.0);
    float NdotH2 = NdotH*NdotH;

    float nom   = a2;
    float denom = (NdotH2 * (a2 - 1.0) + 1.0);
    denom = PI * denom * denom;

    return nom / denom;
}
// ----------------------------------------------------------------------------
float GeometrySchlickGGX(float NdotV, float roughness)
{
    float r = (roughness + 1.0);
    float k = (r*r) / 8.0;

    float nom   = NdotV;
    float denom = NdotV * (1.0 - k) + k;

    return nom / denom;
}
// ----------------------------------------------------------------------------
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness)
{
    float NdotV = max(dot(N, V), 0.0);
    float NdotL = max(dot(N, L), 0.0);
    float ggx2 = GeometrySchlickGGX(NdotV, roughness);
    float ggx1 = GeometrySchlickGGX(NdotL, roughness);

    return ggx1 * ggx2;
}
// ----------------------------------------------------------------------------
vec3 fresnelSchlick(float cosTheta, vec3 F0)
{
    return F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0);
}
// ----------------------------------------------------------------------------
vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness)
{
    return F0 + (max(vec3(1.0 - roughness), F0) - F0) * pow(1.0 - cosTheta, 5.0);
}
// ----------------------------------------------------------------------------
void main()
{
    vec3 N = Normal;
    vec3 V = normalize(camPos - WorldPos);
    vec3 R = reflect(-V, N);

    // calculate reflectance at normal incidence; if dia-electric (like plastic) use F0
    // of 0.04 and if it's a metal, use the albedo color as F0 (metallic workflow)
    vec3 F0 = vec3(0.04);
    F0 = mix(F0, albedo, metallic);

    // reflectance equation
    vec3 Lo = vec3(0.0);
    for(int i = 0; i < 4; ++i)
    {
        // calculate per-light radiance
        vec3 L = normalize(lightPositions[i] - WorldPos);
        vec3 H = normalize(V + L);
        float distance = length(lightPositions[i] - WorldPos);
        float attenuation = 1.0 / (distance * distance);
        vec3 radiance = lightColors[i] * attenuation;

        // Cook-Torrance BRDF
        float NDF = DistributionGGX(N, H, roughness);
        float G   = GeometrySmith(N, V, L, roughness);
        vec3 F    = fresnelSchlick(max(dot(H, V), 0.0), F0);

        vec3 nominator    = NDF * G * F;
        float denominator = 4 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0) + 0.001; // 0.001 to prevent divide by zero.
        vec3 specular = nominator / denominator;

         // kS is equal to Fresnel
        vec3 kS = F;
        // for energy conservation, the diffuse and specular light can't
        // be above 1.0 (unless the surface emits light); to preserve this
        // relationship the diffuse component (kD) should equal 1.0 - kS.
        vec3 kD = vec3(1.0) - kS;
        // multiply kD by the inverse metalness such that only non-metals
        // have diffuse lighting, or a linear blend if partly metal (pure metals
        // have no diffuse light).
        kD *= 1.0 - metallic;

        // scale light by NdotL
        float NdotL = max(dot(N, L), 0.0);

        // add to outgoing radiance Lo
        Lo += (kD * albedo / PI + specular) * radiance * NdotL; // note that we already multiplied the BRDF by the Fresnel (kS) so we won't multiply by kS again
    }

    // ambient lighting (we now use IBL as the ambient term)
    vec3 F = fresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);

    vec3 kS = F;
    vec3 kD = 1.0 - kS;
    kD *= 1.0 - metallic;

    vec3 irradiance = texture(irradianceMap, N).rgb;
    vec3 diffuse      = irradiance * albedo;

    // sample both the pre-filter map and the BRDF lut and combine them together as per the Split-Sum approximation to get the IBL specular part.
    const float MAX_REFLECTION_LOD = 4.0;
    vec3 prefilteredColor = textureLod(prefilterMap, R,  roughness * MAX_REFLECTION_LOD).rgb;
    vec2 brdf  = texture(brdfLUT, vec2(max(dot(N, V), 0.0), roughness)).rg;
    vec3 specular = prefilteredColor * (F * brdf.x + brdf.y);

    vec3 ambient = (kD * diffuse + specular) * ao;

    vec3 color = ambient + Lo;

    // HDR tonemapping
    color = color / (color + vec3(1.0));
    // gamma correct
    color = pow(color, vec3(1.0/2.2));

    FragColor = vec4(color , 1.0);
}
";
    }
}


text: @call build\scripts\run_jake -f build\scripts\ci.jakefile.js %*


text:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'paginate'
})
export class PaginatePipe implements PipeTransform {

  transform(input: any[], itemsPerPage: number, currentPage: number): any {
    return input.slice(itemsPerPage * (currentPage - 1), (itemsPerPage * (currentPage - 1)+itemsPerPage));
  }

}


text:
package com.docker.storage.adapters.impl;

import chat.errors.ChatErrorCodes;
import chat.errors.CoreException;
import com.docker.data.SDocker;
import com.docker.storage.DBException;
import com.docker.storage.adapters.SDockersService;
import com.docker.storage.adapters.ServersService;
import com.docker.storage.mongodb.daos.SDockerDAO;
import com.docker.storage.mongodb.daos.ServersDAO;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import org.bson.Document;

import javax.annotation.Resource;

public class SDockersServiceImpl implements SDockersService {
    @Resource
    private SDockerDAO sDockerDAO;

    @Override
    public Document getSDockerConf(String ip, Integer port) throws CoreException {
        try {
            FindIterable<Document> iterable = sDockerDAO.query(new Document().append(SDocker.FIELD_SDOCKER_IP, ip).append(SDocker.FIELD_SDOCKER_PORT, port));
            MongoCursor<Document> cursor = iterable.iterator();
            if(cursor.hasNext())
                return cursor.next();
        } catch (DBException e) {
            e.printStackTrace();
            throw new CoreException(ChatErrorCodes.ERROR_SDOCKER_QUERY_FAILED, "Query SDocker config for " + ip + ":" + port  + " failed, " + e.getMessage());
        }
        return null;

    }
}


text:
package lichen.creeper.core.config;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

/**
 * lichen.creeper core config
 * @author jcai
 */
@XmlRootElement(name="creeper_core")
public class CreeperCoreConfig {

	//日志路径
	@XmlElement(name="log_file")
	public String log_file;

    public static class Database{
        /**
         * 数据库驱动类.
         */
        @XmlElement(name = "driver_class")
        public String driverClassName;
        /**
         * 数据库用户名.
         */
        @XmlElement(name = "user_name")
        public String username;
        /**
         * 数据库用户密码.
         */
        @XmlElement(name = "password")
        public String password;
        /**
         * 数据库url地址.
         */
        @XmlElement(name = "url")
        public String url;
    }

    /**
     * JPA属性配置
     */
    @XmlRootElement(name="property")
    public static class JpaProperty{
    		//属性名称
        @XmlAttribute(name="name")
        public String name;
        //属性的值
        @XmlAttribute(name="value")
        public String value;
    }
    /** 数据库相关配置 **/
    @XmlElement(name="db")
    public Database db = new Database();
    /** JPA相关配置 **/
    @XmlElementWrapper(name="jpa")
    @XmlElement(name="property")
    public List<JpaProperty> jpaProperties = new ArrayList<JpaProperty>();

}


text:
var Promise = require('bluebird');
var blessed = require('blessed');
var _ = require('lodash');
var Point = require('text-buffer/lib/point');

var util = require('slap-util');
var baseWidgetOpts = require('./opts');

function BaseWidget (opts) {
  var self = this;

  if (!(self instanceof blessed.Node)) return new BaseWidget(opts);

  opts = _.merge({}, baseWidgetOpts, opts);
  if (!opts.screen) opts.screen = (opts.parent || {}).screen;
  if (!opts.parent) opts.parent = opts.screen;
  var loggerOpts = opts.logger
    || (opts.parent || {}).options.logger
    || (opts.screen || {}).options.logger;
  if (loggerOpts && !util.logger.stream) util.logger(loggerOpts);
  if (self instanceof BaseWidget) blessed.Box.call(self, opts); // this should not be called if an element inherits from built-in blessed classes
  self.focusable = opts.focusable;

  util.logger.debug(util.typeOf(self), 'init {'+Object.keys(opts).join(',')+'}');
  self.ready = Promise.delay(0)
    .then(function () {
      return typeof self._initHandlers === 'function'
        ? self._initHandlers()
        : BaseWidget.prototype._initHandlers.call(self);
    })
    .return(self)
    .tap(function () { util.logger.debug(util.typeOf(self), 'ready'); });
}
BaseWidget.blessed = blessed;
BaseWidget.prototype.__proto__ = blessed.Box.prototype;

BaseWidget.prototype.walkDepthFirst = function (direction, after, fn) {
  if (arguments.length === 2) fn = after;
  var children = this.children.slice();
  if (direction === -1) children.reverse();
  if (after) children = children.slice(children.indexOf(after) + 1);
  return children.some(function (child) {
    return fn.apply(child, arguments) || BaseWidget.prototype.walkDepthFirst.call(child, direction, fn);
  });
};
BaseWidget.prototype.focusFirst = function (direction, after) {
  return this.walkDepthFirst(direction, after, function () {
    if (this.visible && this.focusable) {
      this.focus();
      return true;
    }
  });
};
BaseWidget.prototype._focusDirection = function (direction) {
  var self = this;
  var descendantParent;
  var descendant = self.screen.focused;
  while (descendant.hasAncestor(self)) {
    descendantParent = descendant.parent;
    if (BaseWidget.prototype.focusFirst.call(descendantParent, direction, descendant)) return self;
    descendant = descendantParent;
  }
  if (!self.focusFirst(direction)) throw new Error("no focusable descendant");
  return self;
};
BaseWidget.prototype.focusNext = function () {
  return this._focusDirection(1);
};
BaseWidget.prototype.focusPrev = function () {
  return this._focusDirection(-1);
};
BaseWidget.prototype.focus = function () {
  if (!this.hasFocus()) return blessed.Box.prototype.focus.apply(this, arguments);
  return this;
};
BaseWidget.prototype.isAttached = function () {
  return this.hasAncestor(this.screen);
};
BaseWidget.prototype.hasFocus = function (asChild) {
  var self = this;
  var focused = self.screen.focused;
  return focused.visible && (focused === self || focused.hasAncestor(self) || (asChild && self.hasAncestor(focused)));
};

BaseWidget.prototype.pos = function () {
  return new Point(this.atop + this.itop, this.aleft + this.ileft);
};
BaseWidget.prototype.size = function () {
  if (!this.isAttached()) return new Point(0, 0); // hack
  return new Point(this.height - this.iheight, this.width - this.iwidth);
};

BaseWidget.prototype.shrinkWidth = function () { return this.content.length + this.iwidth; };
BaseWidget.prototype.getBindings = function () {
  return this.options.bindings;
};
BaseWidget.prototype.resolveBinding = function (key, source1, source2, etc) {
  return BaseWidget.resolveBinding.apply(this,
    [key, util.callBase(this, BaseWidget, 'getBindings')].concat([].slice.call(arguments, 1))
  );
};
BaseWidget.resolveBinding = function (key, source1, source2, etc) {
  var bindings = _.merge.apply(null, [{}].concat([].slice.call(arguments, 1)));
  for (var name in bindings) {
    if (bindings.hasOwnProperty(name)) {
      var keyBindings = bindings[name];
      if (!keyBindings) continue;
      if (typeof keyBindings === 'string') keyBindings = [keyBindings];
      if (keyBindings.some(function (binding) { return binding === key.full || binding === key.sequence; }))
        return name;
    }
  }
};

BaseWidget.prototype._initHandlers = function () {
  var self = this;
  self.on('focus', function () {
    util.logger.debug('focus', util.typeOf(self));
    if (!self.focusable) self.focusNext();
  });
  self.on('blur', function () { util.logger.debug('blur', util.typeOf(self)); });
  self.on('show', function () { self.setFront(); });
  self.on('element keypress', function (el, ch, key) {
    switch (util.callBase(this, BaseWidget, 'resolveBinding', key)) {
      case 'hide': self.hide(); return false;
      case 'focusNext': self.focusNext(); return false;
      case 'focusPrev': self.focusPrev(); return false;
    }
  });
};

module.exports = BaseWidget;


text:
<?php

namespace Propel\Tests\Runtime\Map;

use Propel\Runtime\Configuration;
use Propel\Runtime\Map\DatabaseMap;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\EntityMap;
use Propel\Tests\TestCase;

/**
 * Test class for RelationMap.
 *
 * @author François Zaninotto
 * @version    $Id$
 */
class RelationMapTest extends TestCase
{
    /**
     * @var DatabaseMap
     */
    protected $databaseMap;

    /**
     * @var string
     */
    protected $relationName;

    /**
     * @var RelationMap
     */
    protected $rmap;

    protected function setUp()
    {
        parent::setUp();
        $this->databaseMap = new DatabaseMap('foodb');
        Configuration::getCurrentConfigurationOrCreate()->registerDatabase($this->databaseMap);
        $this->relationName = 'foo';
        $this->rmap = new RelationMap($this->relationName);
    }

    public function testConstructor()
    {
        $this->assertEquals($this->relationName, $this->rmap->getName(), 'constructor sets the relation name');
    }

    public function testLocalEntity()
    {
        $this->assertNull($this->rmap->getLocalEntity(), 'A new relation has no local table');
        $tmap1 = $this->getMockForAbstractClass(EntityMap::class, ['foo', 'foodb', Configuration::getCurrentConfiguration()]);
        $this->rmap->setLocalEntity($tmap1);
        $this->assertEquals($tmap1, $this->rmap->getLocalEntity(), 'The local table is set by setLocalEntity()');
    }

    public function testForeignEntity()
    {
        $this->assertNull($this->rmap->getForeignEntity(), 'A new relation has no foreign table');
        $tmap2 = $this->getMockForAbstractClass(EntityMap::class, ['bar', 'foodb', Configuration::getCurrentConfiguration()]);
        $this->rmap->setForeignEntity($tmap2);
        $this->assertEquals($tmap2, $this->rmap->getForeignEntity(), 'The foreign table is set by setForeignEntity()');
    }

    public function testProperties()
    {
        $properties = ['type', 'onUpdate', 'onDelete'];
        foreach ($properties as $property) {
            $getter = 'get' . ucfirst($property);
            $setter = 'set' . ucfirst($property);
            $this->assertNull($this->rmap->$getter(), "A new relation has no $property");
            $this->rmap->$setter('foo_value');
            $this->assertEquals('foo_value', $this->rmap->$getter(), "The $property is set by setType()");
        }
    }

    public function testFields()
    {
        $this->assertEquals([], $this->rmap->getLocalFields(), 'A new relation has no local columns');
        $this->assertEquals([], $this->rmap->getForeignFields(), 'A new relation has no foreign columns');
        $tmap1 = $this->getMockForAbstractClass(EntityMap::class, ['foo', 'foodb', Configuration::getCurrentConfiguration()]);
        $col1 = $tmap1->addField('FOO1', 'INTEGER');

        $tmap2 = $this->getMockForAbstractClass(EntityMap::class, ['bar', 'foodb', Configuration::getCurrentConfiguration()]);
        $col2 = $tmap2->addField('BAR1', 'INTEGER');

        $this->rmap->addFieldMapping($col1, $col2);
        $this->assertEquals([$col1], $this->rmap->getLocalFields(), 'addFieldMapping() adds a local table');
        $this->assertEquals([$col2], $this->rmap->getForeignFields(), 'addFieldMapping() adds a foreign table');

        $expected = ['foo.FOO1' => 'bar.BAR1'];
        $this->assertEquals($expected, $this->rmap->getFieldMappings(), 'getFieldMappings() returns an associative array of column mappings');

        $col3 = $tmap1->addField('FOOFOO', 'INTEGER');
        $col4 = $tmap2->addField('BARBAR', 'INTEGER');
        $this->rmap->addFieldMapping($col3, $col4);
        $this->assertEquals(
            [$col1, $col3],
            $this->rmap->getLocalFields(),
            'addFieldMapping() adds a local table'
        );
        $this->assertEquals(
            [$col2, $col4],
            $this->rmap->getForeignFields(),
            'addFieldMapping() adds a foreign table'
        );
        $expected = ['foo.FOO1' => 'bar.BAR1', 'foo.FOOFOO' => 'bar.BARBAR'];
        $this->assertEquals(
            $expected,
            $this->rmap->getFieldMappings(),
            'getFieldMappings() returns an associative array of column mappings'
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.ComponentModel;

using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.ServiceModel.DsspServiceBase;

using sicklrf = Microsoft.Robotics.Services.Sensors.SickLRF.Proxy;

using TrackRoamer.Robotics.Utility.LibSystem;
using TrackRoamer.Robotics.LibMapping;
using TrackRoamer.Robotics.LibBehavior;

namespace TrackRoamer.Robotics.Services.TrackRoamerBehaviors
{
    partial class TrackRoamerBehaviorsService : DsspServiceBase
    {
#if OBSOLETE_PLANANDAVOID_LOGIC

        private const double TurningWaitInterval = 1.0d;              // wait for so many seconds after a turn before accepting a laser frame (should be close to full sweep cycle of the laser)

        #region PlanAndAvoid tactics

        private void TacticsPlanAndAvoid()
        {
            if (_currentRoutePlan.isGoodPlan)
            {
                // we have a good plan, try executing it:
                string sTurn = "no turn";

                double? bestHeadingRelative = _currentRoutePlan.bestHeading - _mapperVicinity.robotDirection.heading;

                if (bestHeadingRelative.HasValue && bestHeadingRelative != 0.0d)
                {
                    sTurn = "turn " + (bestHeadingRelative > 0.0d ? "right " : "left ") + bestHeadingRelative + " degrees";
                }

                if (_currentRoutePlan.legMeters.HasValue)
                {
                    sPlan = "plan: " + sTurn + " and go up to " + Math.Round((double)_currentRoutePlan.legMeters, 2) + " meters (obstacle at " + Math.Round((double)_currentRoutePlan.closestObstacleAlongBestPathMeters, 2) + " meters";
                }
                else
                {
                    sPlan = "plan: steep " + sTurn + " only (obstacle at " + Math.Round((double)_currentRoutePlan.closestObstacleAlongBestPathMeters, 2) + " meters)";
                }

                Tracer.Trace(sPlan);

                // AvoidCollision and EnterOpenSpace have precedence over
                // all other state transitions and are thus handled first.
                bool canMove = PerformAvoidCollision(_currentRoutePlan);   // may result in state set to MovingState.Unable

                // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
                // we must use them while executing the plan.

                // good place to analyze the plan against constraints and set MovingState.Unable
                RoutePlan bestPlan = critiquePlanChain(_currentRoutePlan);

                if (bestPlan == null)
                {
                    _state.MovingState = MovingState.Unable;    // no good plan in the chain
                }

                if (_state.MovingState != MovingState.Unknown && _state.MovingState != MovingState.Unable)
                {
                    if (!_currentRoutePlan.legMeters.HasValue)
                    {
                        // plan requires a steep turn towards the goal:
                        TurnToGoal(_currentRoutePlan);
                    }
                    else
                    {
                        // plan suggests moving and adjusting heading and speed:
                        EnterOpenSpace(_currentRoutePlan);

                        UpdateMovingState(_currentRoutePlan);
                    }
                }
                else
                {
                    // state - Unknown or Unable; will likely start mapping
                    UpdateMovingState(_currentRoutePlan);
                }
            }
            else
            {
                // the plan is no good. Just avoid collision for now:
                Tracer.Trace(sPlan);
                bool canMove = PerformAvoidCollision(null);   // may result in state set to MovingState.Unable (if mustStop)
            }
        }

        #endregion // PlanAndAvoid tactics

        #region Decision Making Elements

        /// <summary>
        /// just turn where the plan wants you to; we are calling with good plan (heading) and no legMeters.
        /// </summary>
        /// <param name="plan"></param>
        private void TurnToGoal(RoutePlan plan)
        {
            // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
            // we must use them while executing the plan.

            _state.NewHeading = (int)Math.Round((double)plan.bestHeadingRelative(_mapperVicinity));

            setMovingStateDetail("TurnToGoal to NewHeading=" + _state.NewHeading);

            AdjustHeading();
        }

        /// <summary>
        /// If the robot is mapping and there is sufficient open space directly ahead, enter this space.
        /// </summary>
        /// <param name="distance"></param>
        private void EnterOpenSpace(RoutePlan plan)
        {
            if (_state.IsMapping && plan != null && plan.isGoodPlan)
            {
                // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
                // we must use them while executing the plan.

                int? distance = (int)((double)plan.closestObstacleAlongBestPathMeters * 1000.0d);

                if (distance > SafeDistanceMm)
                {
                    // We are mapping but can see plenty of free space ahead.
                    // The robot should go into this space.

                    LogInfo("TrackRoamerBehaviorsService: EnterOpenSpace() - while mapping, distance greater than SafeDistance=" + SafeDistanceMm);

                    string message = "open space."; // "while mapping - detected open space; entering...";

                    Talker.Say(5, message);
                    LogHistory(5, message);
                    setMovingStateDetail(message);

                    StopTurning();
                    _state.MovingState = MovingState.FreeForwards;
                    _state.Countdown = 4;
                }
            }
        }

        /// <summary>
        /// Transitions to the most appropriate state.
        /// </summary>
        /// <param name="distance">closest obstacle in corridor ahead</param>
        private void UpdateMovingState(RoutePlan plan)
        {
            LogInfo("TrackRoamerBehaviorsService:UpdateMovingState()   Countdown=" + _state.Countdown + "   MovingState=" + _state.MovingState);

            // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
            // we must use them while executing the plan.

            //if (_state.Countdown > 0)
            //{
            //    _state.Countdown--;
            //    //_state.Countdown = 0;
            //}
            //else

            // based on MetaState, go to the MetaState...() method - which may change the MovingState appropriately
            if (_state.IsUnknown || _state.MovingState == MovingState.Unable)
            {
                MetaStateStartMapping(plan);
            }
            else if (_state.IsMoving)
            {
                MetaStateMove(plan);
            }
            else if (_state.IsMapping)
            {
                MetaStateMap(plan);
            }
        }

        /// <summary>
        /// Implements the "Moving" meta state, basically any transition and not in-place sequence.
        /// </summary>
        /// <param name="distance">closest obstacle in corridor ahead</param>
        private void MetaStateMove(RoutePlan plan)
        {
            LogInfo("TrackRoamerBehaviorsService: MetaStateMove()");

            Talker.Say(4, "Move - " + _state.MovingState);

            // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
            // we must use them while executing the plan.

            switch (_state.MovingState)
            {
                case MovingState.AdjustHeading:
                    setMovingStateDetail("MetaStateMove - AdjustHeading to NewHeading=" + _state.NewHeading);
                    AdjustHeading();
                    break;
                case MovingState.FreeForwards:
                    setMovingStateDetail("MetaStateMove - FreeForwards");
                    AdjustDirectionAndVelocity(plan);
                    break;
                case MovingState.InTransition:
                case MovingState.Unknown:
                    // inTransition means "while executing TurnAndMoveForward() command" (see base).
                    // TurnAndMoveForward() may for a moment leave the state in "Unknown", do not treat it as termination.
                    // this allows current transition to complete, without exiting the "Moving" metastate
                    break;
                case MovingState.BumpedBackingUp:
                    setMovingStateDetail("MetaStateMove - BumpedBackingUp");
                    break;
                default:
                    LogError("TrackRoamerBehaviorsService:MetaStateMove() called in illegal state - " + _state.MovingState);
                    break;
            }
        }

        /// <summary>
        /// Implements the "Mapping" meta state.
        /// </summary>
        /// <param name="distance">closest obstacle in corridor ahead</param>
        private void MetaStateMap(RoutePlan plan)
        {
            LogInfo("TrackRoamerBehaviorsService: MetaStateMap()  MovingState=" + _state.MovingState);

            // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
            // we must use them while executing the plan.

            switch (_state.MovingState)
            {
                case MovingState.RandomTurn:
                    LogInfo("MovingState.RandomTurn");
                    setMovingStateDetail("MetaStateMap - performing RandomTurn");
                    RandomTurn();
                    break;

                case MovingState.Recovering:
                    LogInfo("MovingState.Recovering");
                    setMovingStateDetail("MetaStateMap - Recovering");
                    Recover();
                    break;

                /*
				case MovingState.MapSurroundings:
					_state.Mapped = true;
                    LogInfo("MovingState.MapSurroundings:  Turning 180 deg to map");

                    setMovingStateDetail("MetaStateMap - turning 180 deg to map");

                    SpawnIterator<TurnAndMoveParameters, Handler>(
                        new TurnAndMoveParameters() {
                            speed = (int)Math.Round(MaximumBackwardVelocity),
                            rotatePower = ModerateTurnPower,
                            rotateAngle = 180,
                            desiredMovingState = MovingState.MapSouth
                        },
                        delegate() {
                            _state.Countdown = 15;
                        },
                        TurnAndMoveForward);

					break;

				case MovingState.MapSouth:
                    LogInfo("MovingState.MapSouth:  mapping the View South");

                    Talker.Say(5, "mapping South");

                    setMovingStateDetail("MetaStateMap - mapping South");

                    // _state.South = _laserData;   // needed for FindBestComposite()

                    SpawnIterator<TurnAndMoveParameters, Handler>(
                        new TurnAndMoveParameters() {
                            speed = (int)Math.Round(MaximumBackwardVelocity),
                            rotatePower = ModerateTurnPower,
                            rotateAngle = 180,
                            desiredMovingState = MovingState.MapNorth
                        },
                        delegate() {
                            _state.Countdown = 15;
                        },
                        TurnAndMoveForward);

                        break;

				case MovingState.MapNorth:
                    LogInfo("MovingState.MapNorth:  mapping the View North");

                    Talker.Say(5, "mapping North");

                    //_state.NewHeading = FindBestComposite(_state.South, _laserData);

                    _state.NewHeading = (int)plan.bestHeadingRelative(_mapperVicinity);

                    LogInfo("Composite Map suggests turn to heading: " + _state.NewHeading);

                    setMovingStateDetail("MetaStateMap - mapping North - Composite Map suggests turn: " + _state.NewHeading);

					_state.South = null;
                    _state.MovingState = MovingState.AdjustHeading;
					break;
                */

                case MovingState.InTransition:
                    break;

                default:
                    LogError("TrackRoamerBehaviorsService:MetaStateMap() called in illegal state  - " + _state.MovingState);
                    break;
            }
        }

        /// <summary>
        /// Adjusts the velocity based on environment.
        /// </summary>
        /// <param name="distance">closest obstacle in corridor ahead</param>
        private void AdjustDirectionAndVelocity(RoutePlan plan)
        {
            LogInfo("TrackRoamerBehaviorsService: AdjustDirectionAndVelocity()");

            // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
            // we must use them while executing the plan.

            int legDistanceMm = _state.collisionState.canMoveForwardDistanceMm;

            if (plan.legMeters.HasValue)
            {
                legDistanceMm = Math.Min(legDistanceMm, (int)((double)plan.legMeters * 1000.0d));
            }

            // we come here when _state.MovingState == MovingState.FreeForwards

            _state.Mapped = false;

            //int bestHeading = FindBestHeading(_laserData, 0, (int)Math.Round(_state.Velocity * 1000.0d / 10.0d), CorridorWidthMoving, "FreeForwards - Adjust");

            _state.NewHeading = (int)plan.bestHeadingRelative(_mapperVicinity);    // right - positive, left - negative

            LogInfo("     bestHeading=" + _state.NewHeading + currentCompass);

            if (legDistanceMm > FreeDistanceMm)
            {
                SpawnIterator<TurnAndMoveParameters, Handler>(
                    new TurnAndMoveParameters()
                    {
                        rotateAngle = (int)(((double)_state.NewHeading) * turnHeadingFactor),
                        rotatePower = MaximumTurnPower,
                        speed = (int)Math.Round(Math.Min(_state.collisionState.canMoveForwardSpeedMms, MaximumForwardVelocityMmSec)),
                        desiredMovingState = MovingState.FreeForwards
                    },
                    delegate()
                    {
                    },
                    TurnAndMoveForward);
            }
            else if (legDistanceMm > AwareOfObstacleDistanceMm)
            {
                SpawnIterator<TurnAndMoveParameters, Handler>(
                    new TurnAndMoveParameters()
                    {
                        rotateAngle = (int)(((double)_state.NewHeading) * turnHeadingFactor),
                        rotatePower = ModerateTurnPower,
                        speed = (int)Math.Round(Math.Min(_state.collisionState.canMoveForwardSpeedMms, ModerateForwardVelocityMmSec)),
                        desiredMovingState = MovingState.FreeForwards
                    },
                    delegate()
                    {
                    },
                    TurnAndMoveForward);
            }
            else
            {
                SpawnIterator<TurnAndMoveParameters, Handler>(
                    new TurnAndMoveParameters()
                    {
                        rotateAngle = (int)(((double)_state.NewHeading) * turnHeadingFactor),
                        rotatePower = MinimumTurnPower,
                        speed = (int)Math.Round(Math.Min(_state.collisionState.canMoveForwardSpeedMms, MinimumForwardVelocityMmSec)),
                        desiredMovingState = MovingState.FreeForwards
                    },
                    delegate()
                    {
                        _state.Countdown = Math.Abs(_state.NewHeading / 10);
                    },
                    TurnAndMoveForward);
            }

            LogInfo("     new Countdown=" + _state.Countdown);
        }

        /// <summary>
        /// Implements the "AdjustHeading" state. We are moving already, just need to adjust heading and keep moving.
        /// </summary>
        private void AdjustHeading()
        {
            LogInfo("TrackRoamerBehaviorsService: AdjustHeading()     turning to NewHeading=" + _state.NewHeading + currentCompass);

            _state.MovingState = MovingState.InTransition;
            lastInTransitionStarted = DateTime.Now;

            SpawnIterator<TurnAndMoveParameters, Handler>(
                new TurnAndMoveParameters()
                {
                    rotateAngle = (int)(((double)_state.NewHeading) * turnHeadingFactor),
                    rotatePower = ModerateTurnPower,
                    speed = (int)Math.Round(ModerateForwardVelocityMmSec),
                    desiredMovingState = MovingState.FreeForwards
                },
                delegate()
                {
                    _state.Countdown = Math.Abs(_state.NewHeading / 10);
                },
                TurnAndMoveForward);
        }

        /// <summary>
        /// Implements the "RandomTurn" state.
        /// </summary>
        private void RandomTurn()
        {
            LogInfo("TrackRoamerBehaviorsService: RandomTurn()");

            _state.NewHeading = new Random().Next(-115, 115);
            LogInfo("     start turning (random) to NewHeading=" + _state.NewHeading + currentCompass);

            SpawnIterator<TurnAndMoveParameters, Handler>(
                new TurnAndMoveParameters()
                {
                    rotateAngle = _state.NewHeading,
                    rotatePower = ModerateTurnPower,
                    desiredMovingState = MovingState.Unknown
                },
                delegate()
                {
                    _state.Countdown = 2 + Math.Abs(_state.NewHeading / 10);
                },
                TurnAndMoveForward);
        }

        /// <summary>
        /// Transitions to "Mapping" meta state or "AdjustHeading" state depending on
        /// environment.
        /// </summary>
        /// <param name="distance">closest obstacle in corridor ahead</param>
        private void MetaStateStartMapping(RoutePlan plan)
        {
            int distance = 0;

            if (plan.legMeters.HasValue)
            {
                distance = (int)((double)plan.legMeters * 1000.0d);
            }

            LogInfo("TrackRoamerBehaviorsService: MetaStateStartMapping(distance=" + distance + ")   ObstacleDistance=" + ObstacleDistanceMm);

            Talker.Say(5, "Mapping");

            markNorthBitmap("Start Mapping");

            StopMoving();

            // at this point constraints and allowable speeds and distances are known and stored in _state.collisionState
            // we must use them while executing the plan.

            if (distance < ObstacleDistanceMm)
            {
                LogInfo("    distance < ObstacleDistance (not finding exit)   _state.Mapped=" + _state.Mapped);

                _state.MovingState = MovingState.Recovering;
                LogInfo("    MovingState Recovering (not finding exit)");
                //Talker.Say(5, "Recovering");
                setMovingStateDetail("Recovering (not finding exit)");

                /*
				if (_state.Mapped)
				{
					// We have been mapping before but do not seem to
					// have found anything.
                    _state.MovingState = MovingState.RandomTurn;
                    LogInfo("    requesting RandomTurn");
                    Talker.Say(5, "random turn");
                    setMovingStateDetail("Start Mapping (not finding exit) - requesting RandomTurn");
                }
				else
				{
                    _state.MovingState = MovingState.MapSurroundings;
                    LogInfo("    requesting MapSurroundings");
                    Talker.Say(5, "map surroundings");
                    setMovingStateDetail("Start Mapping (not finding exit) - requesting MapSurroundings");
                }
                 * */
            }
            else
            {
                LogInfo("    distance > ObstacleDistance (exit route found)   CorridorWidthMapping=" + CorridorWidthMappingMm);
                //Talker.Say(5, "exit route found");

                int legMm = Math.Min(ObstacleDistanceMm, distance);

                _state.NewHeading = (int)plan.bestHeadingRelative(_mapperVicinity);      // right - positive, left - negative

                LogInfo("Leg: " + legMm + " mm   NewHeading=" + _state.NewHeading);

                setMovingStateDetail("Start Mapping (exit route found) NewHeading=" + _state.NewHeading + "Leg: " + legMm + " mm");

                _state.MovingState = MovingState.AdjustHeading;
                _state.Countdown = legMm / 50 + Math.Abs(_state.NewHeading / 10);

                LogInfo("     new Countdown=" + _state.Countdown);
            }
        }
        #endregion // Decision Making Elements
#endif // OBSOLETE_PLANANDAVOID_LOGIC

#if OBSOLETE_LASER_LOGIC

        #region Laser Specific decision helpers

        /// <summary>
		/// Respresent a laser range finder reading
		/// </summary>
		internal class RangeData
		{
			/// <summary>
			/// Creates a new instance.
			/// </summary>
			/// <param name="distance">measured distance, mm</param>
			/// <param name="heading">heading in degrees</param>
			public RangeData(int distance, double heading)
			{
                _distance = distance;
				_heading = heading;
			}

			int _distance;
			double _heading;

            // computed values:
			public int DistanceAdjusted { get; set; }     // mm; taking into consideration the Corridor - basically how far we can go in this direction given our width
            public double Weight { get; set; }            // some product of distanceAdjusted and angle between current robot heading and this heading, and may be more

            // measured values:

			/// <summary>
			/// Gets the distance in milimeters.
			/// </summary>
			public int Distance
			{
				get { return _distance; }
			}

			/// <summary>
			/// Gets the heading in degrees.
			/// </summary>
			public double Heading
			{
				get { return _heading; }
			}

			/// <summary>
			/// Comparer to sort instances by distance in a list.
			/// </summary>
			/// <param name="first">first reading</param>
			/// <param name="second">second reading</param>
			/// <returns>a value les than 0 if  <paramref name="first"/> is closer than <paramref name="second"/>, 0 if both have the same distance, a value greater 0 otherwise</returns>
			static public int ByDistance(RangeData first, RangeData second)
			{
				return first._distance.CompareTo(second._distance);
			}

            static public int ByHeading(RangeData first, RangeData second)
            {
                // we compare both values based on how far they are from "straight ahead" course
                double dFirst = Math.Abs(first.Heading);
                double dSecond = Math.Abs(second.Heading);
                return dFirst.CompareTo(dSecond);
            }

            static public int ByWeight(RangeData first, RangeData second)
            {
                return first.Weight.CompareTo(second.Weight);
            }
        }

		/// <summary>
		/// Finds the best free corridor (maximum free space ahead) in a 360 degree scan.
		/// </summary>
		/// <param name="south">the backward half of the scan</param>
		/// <param name="north">the forward half of the scan</param>
		/// <returns>best heading in degrees (right turn - positive, left turn - negative)</returns>
		private int FindBestComposite(sicklrf.State south, sicklrf.State north)
		{
            try
            {
                // sanity check:
                LogInfo("FindBestComposite() south: " + south.DistanceMeasurements.Length + " points,  north: " + north.DistanceMeasurements.Length + " points");

                if (south.DistanceMeasurements.Length + north.DistanceMeasurements.Length < 360)
                {
                    LogError("FindBestComposite() - bad laser measurement");
                    return 0;
                }

                sicklrf.State composite = new sicklrf.State();

                composite.DistanceMeasurements = new int[361];

                for (int i = 0; i < composite.DistanceMeasurements.Length; i++)
                {
                    // the trick is to have halves of the South scan become sides of the full North scan,
                    // so that a 360 degrees composite has heading 0 in the middle.

                    if (i < 90)
                    {
                        composite.DistanceMeasurements[i] = south.DistanceMeasurements[i + 90];
                    }
                    else if (i < 270)
                    {
                        composite.DistanceMeasurements[i] = north.DistanceMeasurements[i - 90];
                    }
                    else // 270...359
                    {
                        composite.DistanceMeasurements[i] = south.DistanceMeasurements[i - 270];
                    }
                }

                composite.AngularResolution = 1.0;
                composite.AngularRange = 360;
                composite.Units = north.Units;

                return FindBestHeading(composite, 0, 0, CorridorWidthMoving, "Best Composite");
            }
            catch (Exception exc)
            {
                LogError(exc);
                return 0;
            }
		}

		/// <summary>
		/// Finds the best heading in a 180 degree laser scan
		/// </summary>
		/// <param name="dx">horizontal offset (always 0 here)</param>
		/// <param name="dy">vertical offset (based on velocity)</param>
        /// <param name="width">corridorWidth of corridor that must be free</param>
		/// <returns>best heading in degrees (right turn - positive, left turn - negative)</returns>
        private int FindBestHeading(int dx, int dy, int corridorWidth, string comment)
        {
            LogInfo("FindBestHeading()   dx=" + dx + " dy=" + dy + " width=" + corridorWidth);

            int count = _laserData.DistanceMeasurements.Length;   // can be 181 for laser scan, or 361 for north-south composite
            double span = toRadians(_laserData.AngularRange);     // radians

            bool isComposite = count > 200; // regular is 181, composite is 361

            List<RangeData> ranges = new List<RangeData>();
            int bestHeadingInt = 0;

            // draw as we need to display decision making process. We may get a composite (north-south scan, with robot front in the middle):
            Bitmap bmp = isComposite ? currentStatusGraphics.compositeBmp : currentStatusGraphics.northBmp;
            lock (bmp)
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    // massage the data - create a bubble of ranges, corrected for forward speed:
                    for (int i = 0; i < count; i++)
                    {
                        int range = _laserData.DistanceMeasurements[i];

                        double angle = span * i / count - span / 2.0d;     // radians; angle from the center

                        double x = range * Math.Sin(angle) - dx;
                        double y = range * Math.Cos(angle) - dy;    // account for some speed, make forward distance shorter

                        angle = Math.Atan2(-x, y);
                        range = (int)Math.Sqrt(x * x + y * y);

                        // with the "dy" speed correction the bubble in front of us is a bit thinner than on the sides.
                        // we don't care about objects too far away, and that also removes the speed-induced distortion on the open.
                        range = Math.Min(range, (int)(FreeDistance * 1.01d));

                        if (i % 10 == 0)
                        {
                            // keep in mind that for rayLine the negative is for the right:
                            rayLine(null, g, range, toDegrees(angle), Pens.Yellow, Brushes.Black);
                        }

                        ranges.Add(new RangeData(range, angle));
                    }

                    // compute distanceAdjusted for each range, so that we know where we can fit with our width:
                    for (int i = 0; i < ranges.Count; i++)
                    {
                        RangeData curr = ranges[i];

                        // for every range see how the robot size fits in that distance spot (with a given robot width):
                        double delta = Math.Atan2(corridorWidth, curr.Distance);
                        double currHeading = curr.Heading;
                        double low = currHeading - delta;
                        double high = currHeading + delta;
                        int distanceAdjusted = curr.Distance;

                        // all rays within our corridor - find minimum:
                        for (int j = 0; j < ranges.Count; j++)
                        {
                            if (i != j && ranges[j].Heading > low && ranges[j].Heading < high)
                            {
                                distanceAdjusted = Math.Min(distanceAdjusted, ranges[j].Distance);
                            }
                        }

                        curr.DistanceAdjusted = distanceAdjusted;

                        curr.Weight = (distanceAdjusted - SafeDistance) * Math.Abs(currHeading > 0 ? Math.PI / 2.0d - currHeading : currHeading + Math.PI / 2.0d);

                        if (i % 10 == 0)
                        {
                            // keep in mind that for rayLine the negative is for the right:
                            rayLine("" + Math.Round(curr.Weight / 100.0d), g, curr.DistanceAdjusted, toDegrees(currHeading), Pens.OrangeRed, Brushes.Black);
                        }
                    }

                    ranges.Sort(RangeData.ByWeight);
                    ranges.Reverse();

                    //// display all candidates left for the final choice (usually just 2-5 rays):
                    //for (int i = 0; i < ranges.Count; i++)
                    //{
                    //    RangeData range = ranges[i];

                    //    // keep in mind that for rayLine the negative is for the right:
                    //    rayLine(null, g, range.Distance, -toDegrees(range.Heading), Pens.OrangeRed, Brushes.Black);
                    //}

                    int bestDistance = ranges[0].DistanceAdjusted;
                    double bestHeading = ranges[0].Heading;
                    double bestHeadingDistance = bestDistance;

                    /*
                    Random rand = new Random();

                    bool byBestDistance = false;

                    if (ranges.Count > 1)
                    {
                        for (int i = 1; i < ranges.Count; i++)
                        {
                            if (ranges[i].Distance < bestDistance)
                            {
                                byBestDistance = true;  // we have a true winner
                                bestHeading = ranges[i-1].Heading;
                                bestHeadingDistance = ranges[i-1].Distance;
                                break;
                            }
                        }

                        if (!byBestDistance)
                        {
                            // Could not choose by best distance - we are on the open at least on one side; get creative.
                            // How about just keeping it the closest to the straight course?
                            ranges.Sort(RangeData.ByHeading);

                            bestHeading = ranges[0].Heading;
                            bestHeadingDistance = ranges[0].Distance;

                            //for (int i = 0; i < ranges.Count; i++)
                            //{
                            //    if (rand.Next(i + 1) == 0)
                            //    {
                            //        bestHeading = ranges[i].Heading;
                            //        bestHeadingDistance = ranges[i].Distance;
                            //    }
                            //}
                        }
                    }
                    */

                    // right turn - positive, left turn - negative, expressed in degrees:
                    bestHeadingInt = (int)Math.Round(toDegrees(bestHeading));

                    // now draw our decision; keep in mind that for rayLine the negative is for the right:

                    using (Pen dirPen = new Pen(Color.LimeGreen, 5.0f))
                    {
                        dirPen.EndCap = LineCap.ArrowAnchor;
                        rayLine("" + bestHeadingInt, g, bestHeadingDistance*1.1d, (double)bestHeadingInt, dirPen, Brushes.Green);
                    }

                    int xLbl = 10;
                    int yLbl = bmp.Height - 40;

                    g.DrawString(comment, StatusGraphics.fontBmpL, Brushes.Green, xLbl, yLbl);
                }
            }
            // end of drawing

            string bestHeadingSay = "straight";

            if (bestHeadingInt < 0)
            {
                bestHeadingSay = "left " + (-bestHeadingInt);
            }
            else if (bestHeadingInt > 0)
            {
                bestHeadingSay = "right " + bestHeadingInt;
            }

            Talker.Say(5, "best heading - " + bestHeadingSay);

            LogInfo("FindBestHeading() found best heading = " + bestHeadingInt + " degrees (" + bestHeadingSay + ")");

            return bestHeadingInt;
        }

        /// <summary>
		/// Finds closest obstacle in a corridor.
		/// </summary>
		/// <param name="width">corridor width</param>
		/// <param name="fov">field of view in degrees, on each side</param>
		/// <returns>distance to the closest obstacle</returns>
		private int FindNearestObstacleInCorridor(int width, int fieldOfView)
		{
			int index;
			int best = 8192;
			int count = _laserData.DistanceMeasurements.Length;
			double rangeLow = -_laserData.AngularRange / 2.0;
			double rangeHigh = _laserData.AngularRange / 2.0;
			double span = _laserData.AngularRange;

			for (index = 0; index < count; index++)
			{
				double angle = rangeLow + (span * index) / count;
				if (Math.Abs(angle) <= fieldOfView)
				{
					angle = angle * Math.PI / 180;

					int range = _laserData.DistanceMeasurements[index];
					int x = (int)(range * Math.Sin(angle));
					int y = (int)(range * Math.Cos(angle));

					if (Math.Abs(x) < width)
					{
						if (range < best)
						{
							best = range;
						}
					}
				}
			}

			return best;
		}
        #endregion

#endif // OBSOLETE_LASER_LOGIC

    }
}


text:
namespace CostaLibrary.ExtensionMethods.UnitTests
{
    using System;
    using System.Xml;
    using Xunit;

    public class DateTimeExtensionsTests
    {
        [Fact]
        public void ToLelacyFormat_C20()
        {
            var date = new DateTime(1920, 12, 31);
            var result = date.ToLegacyFormat();

            Assert.Equal("0201231", result);
        }

        [Fact]
        public void ToLelacyFormat_C21()
        {
            var date = new DateTime(2013, 10, 31);
            var result = date.ToLegacyFormat();

            Assert.Equal("1131031", result);
        }

        [Fact]
        public void ToXmlDateTime()
        {
            var date = new DateTime(2013, 10, 24, 13, 10, 15, 951);
            var result = date.ToXmlDateTime();
            var result2 = date.ToXmlDateTime(XmlDateTimeSerializationMode.Local);

            Assert.Equal("2013-10-24T13:10:15.951Z", result);
            Assert.Equal("2013-10-24T13:10:15.951+02:00", result2);

        }
    }
}


text:
package com.willoughby.goalie.db.generated;

import java.util.List;

import de.greenrobot.dao.DaoException;

// THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS

// KEEP INCLUDES - put your custom includes here
// KEEP INCLUDES END
/**
 * Entity mapped to table REMINDER.
 */
public class Reminder {

    private Long id;
    private java.util.Date fireDate;
    private java.util.Date fireTime;
    private Boolean isSpecificDate;
    private Integer repeatsOnDayOfTheWeek;
    private long habitualGoalId;

    /** Used to resolve relations */
    private transient DaoSession daoSession;

    /** Used for active entity operations. */
    private transient ReminderDao myDao;

    private HabitualGoal habitualGoal;
    private Long habitualGoal__resolvedKey;

    private List<RepeatDay> repeatDays;

    // KEEP FIELDS - put your custom fields here
    // KEEP FIELDS END

    public Reminder() {
    }

    public Reminder(Long id) {
        this.id = id;
    }

    public Reminder(Long id, java.util.Date fireDate, java.util.Date fireTime, Boolean isSpecificDate, Integer repeatsOnDayOfTheWeek, long habitualGoalId) {
        this.id = id;
        this.fireDate = fireDate;
        this.fireTime = fireTime;
        this.isSpecificDate = isSpecificDate;
        this.repeatsOnDayOfTheWeek = repeatsOnDayOfTheWeek;
        this.habitualGoalId = habitualGoalId;
    }

    /** called by internal mechanisms, do not call yourself. */
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getReminderDao() : null;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public java.util.Date getFireDate() {
        return fireDate;
    }

    public void setFireDate(java.util.Date fireDate) {
        this.fireDate = fireDate;
    }

    public java.util.Date getFireTime() {
        return fireTime;
    }

    public void setFireTime(java.util.Date fireTime) {
        this.fireTime = fireTime;
    }

    public Boolean getIsSpecificDate() {
        return isSpecificDate;
    }

    public void setIsSpecificDate(Boolean isSpecificDate) {
        this.isSpecificDate = isSpecificDate;
    }

    public Integer getRepeatsOnDayOfTheWeek() {
        return repeatsOnDayOfTheWeek;
    }

    public void setRepeatsOnDayOfTheWeek(Integer repeatsOnDayOfTheWeek) {
        this.repeatsOnDayOfTheWeek = repeatsOnDayOfTheWeek;
    }

    public long getHabitualGoalId() {
        return habitualGoalId;
    }

    public void setHabitualGoalId(long habitualGoalId) {
        this.habitualGoalId = habitualGoalId;
    }

    /** To-one relationship, resolved on first access. */
    public HabitualGoal getHabitualGoal() {
        long __key = this.habitualGoalId;
        if (habitualGoal__resolvedKey == null || !habitualGoal__resolvedKey.equals(__key)) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            HabitualGoalDao targetDao = daoSession.getHabitualGoalDao();
            HabitualGoal habitualGoalNew = targetDao.load(__key);
            synchronized (this) {
                habitualGoal = habitualGoalNew;
            	habitualGoal__resolvedKey = __key;
            }
        }
        return habitualGoal;
    }

    public void setHabitualGoal(HabitualGoal habitualGoal) {
        if (habitualGoal == null) {
            throw new DaoException("To-one property 'habitualGoalId' has not-null constraint; cannot set to-one to null");
        }
        synchronized (this) {
            this.habitualGoal = habitualGoal;
            habitualGoalId = habitualGoal.getId();
            habitualGoal__resolvedKey = habitualGoalId;
        }
    }

    /** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */
    public List<RepeatDay> getRepeatDays() {
        if (repeatDays == null) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            RepeatDayDao targetDao = daoSession.getRepeatDayDao();
            List<RepeatDay> repeatDaysNew = targetDao._queryReminder_RepeatDays(id);
            synchronized (this) {
                if(repeatDays == null) {
                    repeatDays = repeatDaysNew;
                }
            }
        }
        return repeatDays;
    }

    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    public synchronized void resetRepeatDays() {
        repeatDays = null;
    }

    /** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

    // KEEP METHODS - put your custom methods here
    // KEEP METHODS END

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.accumulo</groupId>
    <artifactId>accumulo-project</artifactId>
    <version>2.1.0-SNAPSHOT</version>
  </parent>
  <artifactId>accumulo-hadoop-mapreduce</artifactId>
  <name>Apache Accumulo Hadoop MapReduce</name>
  <description>Apache Accumulo MapReduce bindings.</description>
  <dependencies>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client-runtime</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>com.beust</groupId>
      <artifactId>jcommander</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-minicluster</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-server-base</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>net.revelc.code</groupId>
        <artifactId>apilyzer-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>apilyzer</id>
            <goals>
              <goal>analyze</goal>
            </goals>
            <configuration>
              <includes>
                <include>org[.]apache[.]accumulo[.]core[.]client[.]mapred(?:uce)?[.].*</include>
              </includes>
              <excludes>
                <exclude>.*[.]impl[.].*</exclude>
              </excludes>
              <allows>
                <allow>org[.]apache[.]accumulo[.]core[.](?:client|data|security)[.](?!.*(impl|thrift|crypto).*).*</allow>
                <!-- Not public API, but hard to get rid of. Pair is just so useful. -->
                <allow>org[.]apache[.]accumulo[.]core[.]util[.]Pair</allow>
                <!--Types from hadoop used in API. If adding a new type from
                     Hadoop to the Accumulo API ensure its annotated as stable.-->
                <allow>org[.]apache[.]hadoop[.]conf[.]Configuration</allow>
                <allow>org[.]apache[.]hadoop[.]fs[.](FileSystem|Path)</allow>
                <allow>org[.]apache[.]hadoop[.]io[.](Text|Writable|WritableComparable|WritableComparator)</allow>
                <allow>org[.]apache[.]hadoop[.]mapred[.](JobConf|RecordReader|InputSplit|RecordWriter|Reporter)</allow>
                <allow>org[.]apache[.]hadoop[.]mapred[.]FileOutputFormat[$]Counter</allow>
                <allow>org[.]apache[.]hadoop[.]mapreduce[.](Job|JobContext|RecordReader|InputSplit|TaskAttemptContext|RecordWriter|OutputCommitter|TaskInputOutputContext)</allow>
                <allow>org[.]apache[.]hadoop[.]mapreduce[.]lib[.]output[.]FileOutputFormat[$]Counter</allow>
                <allow>org[.]apache[.]hadoop[.]util[.]Progressable</allow>
                <allow>org[.]apache[.]hadoop[.]mapred[.](FileAlreadyExistsException|InvalidJobConfException)</allow>
              </allows>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
@interface CardGameViewController ()
@property (weak, nonatomic) IBOutlet UILabel *flipLable;
@property (nonatomic) int flipCount;

@end

@implementation CardGameViewController
- (void) setFlipCount:(int)flipCount{
    _flipCount = flipCount;

    NSLog(@"flip counts: %d", self.flipCount);
}
- (IBAction)touchCardButton:(UIButton *)sender {
//    UIImage *cardImage = [UIImage imageNamed:@"cardback"];
    if ([sender.currentTitle length] ) {
        [sender setBackgroundImage:[UIImage imageNamed:@"cardback"]
                          forState:UIControlStateNormal];
        [sender setTitle:@"" forState:UIControlStateNormal];
    }else{
        [sender setBackgroundImage:[UIImage imageNamed:@"cardfront"]
                          forState:UIControlStateNormal];
        [sender setTitle:@"A♣" forState:UIControlStateNormal];

    }
    self.flipCount++;
    self.flipLable.text =[NSString stringWithFormat:@"次数: %d", self.flipCount] ;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
<!DOCTYPE html>

    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

transform: rotate(45deg)

transform: rotate(90deg)

transform: rotate(-10deg)

transform: rotate(40grad)

transform: rotate(1.57rad)

transform: rotate(.2turn)


text:
<?php
/**
 * The Base Form Field class.
 *
 * You need to extend it with your custom Form Fields.
 *
 * @author Asier Marqués <asiermarques@gmail.com>
 */

namespace SimpleForm\Field;

use Zend\Validator\AbstractValidator;
use Zend\Validator\NotEmpty;

abstract class AbstractField
{
    protected $_errors     = array();
    protected $_options    = array();
    protected $_validators = array();

    protected $_html_attributes = array();

    protected $_form_name;

    protected $_name;
    protected $_value;

    public function __construct($options=array())
    {

        $this->_options    = $options;

        if(isset($options["validators"]))
        {
            $this->_validators = $options["validators"];
            unset($this->_options["validators"]);
        }
    }

    public function configure($name, $form_name)
    {
        $this->_name       = $name;
        $this->_form_name  = $form_name;

        $this->checkOptionsRequisites();
        $this->configureHTMLAttributes();
    }

    public function reset()
    {
        $this->setValue(null);
    }

    public function getOptions()
    {
        return $this->_options;
    }

    public function getValidators()
    {
        return $this->_validators;
    }

    public function getErrors()
    {
        return $this->_errors;
    }

    /**
     * Override this method in order to check the required options
     * @return bool
     */
    protected function checkOptionsRequisites()
    {
        return true;
    }

    protected function configureHTMLAttributes()
    {

        if (isset($this->_options["required"])) {
            if ($this->_options["required"]) {
                $this->_html_attributes["required"] = "required";
                $this->_validators[] = new NotEmpty();
            }

            unset($this->_options["required"]);
        } else {
            $this->_html_attributes["required"] = "required";
            $this->_validators[] = new NotEmpty();
        }

        $this->_html_attributes["id"]   = $this->_form_name . "_" . $this->_name;
        if($this->_form_name)
        {
            $this->_html_attributes["name"] = $this->_form_name . "[" . $this->_name . "]";
        }else{
            $this->_html_attributes["name"] = $this->_name;
        }

        foreach ($this->_options as $key=>$option) {
            $this->_html_attributes[$key] = $option;
        }
    }

    public function getName()
    {
        return $this->_name;
    }

    public function getAttributesArray()
    {
        return $this->_html_attributes;
    }

    public function getAttributes()
    {
        $html = " ";
        foreach ($this->_html_attributes as $key=>$value) {
            $html .= ' ' .  $key . '="' . $value . '"';
        }

        return $html;
    }

    public function getValue()
    {
        return $this->_value;
    }

    public function setValue($value)
    {
        $this->_value = $value;
    }

    public function bind($value)
    {
        $this->reset();

        $this->setValue($value);

        $this->_errors = array();

        /**
         * @var $validator AbstractValidator
         */
        foreach ($this->_validators as $validator) {
            if (is_array($value)) {
                foreach ($value as $_value) {
                    if (!$validator->isValid($_value)) {
                        foreach ($validator->getMessages() as $i=>$message) {
                            $this->_errors[] = $message;
                        }
                    }
                }
            } else {
                if (!$validator->isValid($value)) {
                    foreach ($validator->getMessages() as $i=>$message) {
                        $this->_errors[] = $message;
                    }
                }
            }
        }

        if (count($this->_errors)) {
            if (!isset($this->_html_attributes["class"])) {
                $this->_html_attributes["class"] = "";
            }

            $this->_html_attributes["class"] .= " error";
        }

        return !count($this->_errors);
    }

    public function __toString()
    {
        return $this->getRow();
    }

    public function getRow($label=null)
    {
        return $this->getLabelTag($label) . $this->getInputTag() . $this->getErrorTag();
    }

    public function getLabelTag($label=null)
    {
        $label = isset($this->_options["label"]) ? $this->_options["label"] : ($label ? $label :$this->_name);
        return '_form_name . '_'. $this->_name .'">' . $label . '';
    }

    public function hasError()
    {
        return count($this->_errors);
    }

    public function getErrorArray()
    {
        return $this->_errors;
    }

    public function getErrorTag()
    {
        if ($this->hasError()) {
            $html = "";
            foreach ($this->getErrorArray() as $key=>$error) {
                $html .= '' . $error . '';
            }
            return $html;
        }

        return null;
    }

    public function getInputTagWithAttributes(array $html_attr)
    {
        foreach($html_attr as $key=>$value)
        {
            $this->_html_attributes[$key] = $value;
        }
        return $this->getInputTag();
    }

    abstract public function getInputTag();
}