text:
package org.broadinstitute.dsde.firecloud.webservice

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import org.broadinstitute.dsde.firecloud.dataaccess.MockThurloeDAO
import org.broadinstitute.dsde.firecloud.model.{BasicProfile, UserInfo}
import org.broadinstitute.dsde.firecloud.service.{BaseServiceSpec, RegisterService, UserService}
import akka.http.scaladsl.model.StatusCodes.{BadRequest, Forbidden, NoContent, NotFound, OK}
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.server.Route.{seal => sealRoute}
import org.broadinstitute.dsde.firecloud.HealthChecks.termsOfServiceUrl
import org.broadinstitute.dsde.firecloud.mock.{MockUtils, SamMockserverUtils}
import org.broadinstitute.dsde.firecloud.model.ModelJsonProtocol.impBasicProfile
import org.mockserver.integration.ClientAndServer
import org.mockserver.integration.ClientAndServer.startClientAndServer
import org.mockserver.model.Header
import org.mockserver.model.HttpRequest._
import org.scalatest.BeforeAndAfterAll
import spray.json.DefaultJsonProtocol

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success

final class RegisterApiServiceSpec extends BaseServiceSpec with RegisterApiService with UserApiService
  with DefaultJsonProtocol with SprayJsonSupport
  with BeforeAndAfterAll with SamMockserverUtils {

  override val executionContext: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global

  // mockserver to return an enabled user from Sam
  var mockSamServer: ClientAndServer = _

  override def afterAll(): Unit = mockSamServer.stop()

  override def beforeAll(): Unit = {
    mockSamServer = startClientAndServer(MockUtils.samServerPort)
    // disabled user
    mockSamServer
      .when(request
        .withMethod("GET")
        .withPath("/register/user/v2/self/info")
        .withHeader(new Header("Authorization", "Bearer disabled")))
      .respond(
        org.mockserver.model.HttpResponse.response()
          .withHeaders(MockUtils.header).withBody(
          """{
            |  "adminEnabled": false,
            |  "enabled": false,
            |  "userEmail": "disabled@nowhere.com",
            |  "userSubjectId": "disabled-id"
            |}""".stripMargin).withStatusCode(OK.intValue)
      )

    // unregistered user
    mockSamServer
      .when(request
        .withMethod("GET")
        .withPath("/register/user/v2/self/info")
        .withHeader(new Header("Authorization", "Bearer unregistered")))
      .respond(
        org.mockserver.model.HttpResponse.response()
          .withHeaders(MockUtils.header).withBody(
          """{
            |  "causes": [],
            |  "message": "Google Id unregistered-id not found in sam",
            |  "source": "sam",
            |  "stackTrace": [],
            |  "statusCode": 404
            |}""".stripMargin).withStatusCode(NotFound.intValue)
      )

    returnEnabledUser(mockSamServer)
  }

  override val registerServiceConstructor:() => RegisterService =
    RegisterService.constructor(app.copy(thurloeDAO = new RegisterApiServiceSpecThurloeDAO))

  override val userServiceConstructor:(UserInfo) => UserService =
    UserService.constructor(app.copy(thurloeDAO = new RegisterApiServiceSpecThurloeDAO))

  "RegisterApiService" - {
    "update-preferences API" - {

      "should succeed with a single notifications key" in {
        val payload = Map(
          "notifications/foo" -> "yes"
        )
        assertPreferencesUpdate(payload, NoContent)
      }

      "should succeed with multiple valid preference keys" in {
        val payload = Map(
          "notifications/foo" -> "yes",
          "notifications/bar" -> "no",
          "notifications/baz" -> "astring",
          "starredWorkspaces" -> "fooId,barId,bazId"
        )
        assertPreferencesUpdate(payload, NoContent)
      }

      "should refuse with a single disallowed key" in {
        val payload = Map(
          "abadkey" -> "astring"
        )
        assertPreferencesUpdate(payload, BadRequest)
      }

      "should refuse with mixed notifications and disallowed keys" in {
        val payload = Map(
          "notifications/foo" -> "yes",
          "notifications/bar" -> "no",
          "secretsomething" -> "astring"
        )
        assertPreferencesUpdate(payload, BadRequest)
      }

      "should refuse with the string 'notifications/' in the middle of a key" in {
        val payload = Map(
          "notifications/foo" -> "yes",
          "notifications/bar" -> "no",
          "substring/notifications/arebad" -> "true"
        )
        assertPreferencesUpdate(payload, BadRequest)
      }

      "should succeed with an empty payload" in {
        val payload = Map.empty[String, String]
        assertPreferencesUpdate(payload, NoContent)
      }

    }

    "register-profile API POST" - {
      "should fail with no terms of service" in {
        val payload = makeBasicProfile(false)
        Post("/register/profile", payload) ~> dummyUserIdHeaders("RegisterApiServiceSpec", "new") ~> sealRoute(registerRoutes) ~> check {
          status should be(Forbidden)
        }
      }

      "should succeed with terms of service" in {
        val payload = makeBasicProfile(true)
        Post("/register/profile", payload) ~> dummyUserIdHeaders("RegisterApiServiceSpec", "new") ~> sealRoute(registerRoutes) ~> check {
          status should be(OK)
        }
      }

      "should succeed user who already exists" in {
        val payload = makeBasicProfile(true)
        Post("/register/profile", payload) ~> dummyUserIdHeaders("RegisterApiServiceSpec") ~> sealRoute(registerRoutes) ~> check {
          status should be(OK)
        }
      }

      def makeBasicProfile(hasTermsOfService: Boolean): BasicProfile = {
        val randomString = MockUtils.randomAlpha()
        BasicProfile(
          firstName = randomString,
          lastName = randomString,
          title = randomString,
          contactEmail = Some("me@abc.com"),
          institute = randomString,
          researchArea = Some(randomString),
          programLocationCity = randomString,
          programLocationState = randomString,
          programLocationCountry = randomString,
          termsOfService = if (hasTermsOfService) Some(termsOfServiceUrl) else None
        )
      }
    }

    "register-profile API GET" - {
      // Because this endpoint is used during the registration process, it
      // should always return info about the user; if it blocked unregistered
      // or disabled users, those users would not be able to proceed.
      //
      // These tests will fail if GET /register/profile is put behind requireEnabledUser().
      List("enabled", "disabled", "unregistered") foreach { testCase =>
        s"should succeed for a(n) $testCase user" in {
          Get("/register/profile") ~> dummyUserIdHeaders(userId = testCase, token = testCase) ~> sealRoute(userServiceRoutes) ~> check {
            withClue(s"with actual response body: ${responseAs[String]}, got error message ->") {
              status should be(OK)
            }
          }
        }
      }
    }
  }

  private def assertPreferencesUpdate(payload: Map[String, String], expectedStatus: StatusCode): Unit = {
    Post("/profile/preferences", payload) ~> dummyUserIdHeaders("RegisterApiServiceSpec") ~> sealRoute(profileRoutes) ~> check {
      status should be(expectedStatus)
    }
  }

  // for purposes of these tests, we treat Thurloe as if it is always successful.
  final class RegisterApiServiceSpecThurloeDAO extends MockThurloeDAO {
    override def saveKeyValues(userInfo: UserInfo, keyValues: Map[String, String])= Future.successful(Success(()))
  }
}

redpajama_set_name: RedPajamaGithub


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

namespace AIFrameWork.CardCompare
{
    public class CompThreeGroupMore : CompareBase
    {
        public override CardCompareResult GetCardCompareResult(int[] cardArray1, int[] cardArray2)
        {
            var q1 = from c1 in cardArray1
                     orderby c1
                     select c1;
            var q2 = from c2 in cardArray2
                     orderby c2
                     select c2;
            if (q1.Last() > q2.Last())
            {
                return CardCompareResult.ParamOneIsBigger;
            }
            else if (q1.Last() < q2.Last())
            {
                return CardCompareResult.ParamOneIsSmaller;
            }
            else
            {
                return CardCompareResult.ParamOneAndTwoEqual;
            }
        }
    }
}


text:
/**
 * @file CSmartFactory.cpp
 * @brief CSmartFactory source file.
 */
// Copyright (c) 2013, Ford Motor Company
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the Ford Motor Company nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "formatters/CSmartFactory.h"

const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_MSG_PARAMS(
    "msg_params");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PARAMS("params");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_FUNCTION_ID(
    "function_id");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_MESSAGE_TYPE(
    "message_type");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_VERSION(
    "protocol_version");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_TYPE(
    "protocol_type");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_CORRELATION_ID(
    "correlation_id");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::kCode("code");
const std::string NsSmartDeviceLink::NsJSONHandler::strings::kMessage(
    "message");


text:
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package caddyhttp

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"testing"

	"github.com/caddyserver/caddy/v2"
)

func TestHostMatcher(t *testing.T) {
	err := os.Setenv("GO_BENCHMARK_DOMAIN", "localhost")
	if err != nil {
		t.Errorf("error while setting up environment: %v", err)
	}

	for i, tc := range []struct {
		match  MatchHost
		input  string
		expect bool
	}{
		{
			match:  MatchHost{},
			input:  "example.com",
			expect: false,
		},
		{
			match:  MatchHost{"example.com"},
			input:  "example.com",
			expect: true,
		},
		{
			match:  MatchHost{"EXAMPLE.COM"},
			input:  "example.com",
			expect: true,
		},
		{
			match:  MatchHost{"example.com"},
			input:  "EXAMPLE.COM",
			expect: true,
		},
		{
			match:  MatchHost{"example.com"},
			input:  "foo.example.com",
			expect: false,
		},
		{
			match:  MatchHost{"example.com"},
			input:  "EXAMPLE.COM",
			expect: true,
		},
		{
			match:  MatchHost{"foo.example.com"},
			input:  "foo.example.com",
			expect: true,
		},
		{
			match:  MatchHost{"foo.example.com"},
			input:  "bar.example.com",
			expect: false,
		},
		{
			match:  MatchHost{"*.example.com"},
			input:  "example.com",
			expect: false,
		},
		{
			match:  MatchHost{"*.example.com"},
			input:  "SUB.EXAMPLE.COM",
			expect: true,
		},
		{
			match:  MatchHost{"*.example.com"},
			input:  "foo.example.com",
			expect: true,
		},
		{
			match:  MatchHost{"*.example.com"},
			input:  "foo.bar.example.com",
			expect: false,
		},
		{
			match:  MatchHost{"*.example.com", "example.net"},
			input:  "example.net",
			expect: true,
		},
		{
			match:  MatchHost{"example.net", "*.example.com"},
			input:  "foo.example.com",
			expect: true,
		},
		{
			match:  MatchHost{"*.example.net", "*.*.example.com"},
			input:  "foo.bar.example.com",
			expect: true,
		},
		{
			match:  MatchHost{"*.example.net", "sub.*.example.com"},
			input:  "sub.foo.example.com",
			expect: true,
		},
		{
			match:  MatchHost{"*.example.net", "sub.*.example.com"},
			input:  "sub.foo.example.net",
			expect: false,
		},
		{
			match:  MatchHost{"www.*.*"},
			input:  "www.example.com",
			expect: true,
		},
		{
			match:  MatchHost{"example.com"},
			input:  "example.com:5555",
			expect: true,
		},
		{
			match:  MatchHost{"{env.GO_BENCHMARK_DOMAIN}"},
			input:  "localhost",
			expect: true,
		},
		{
			match:  MatchHost{"{env.GO_NONEXISTENT}"},
			input:  "localhost",
			expect: false,
		},
	} {
		req := &http.Request{Host: tc.input}
		repl := caddy.NewReplacer()
		ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
		req = req.WithContext(ctx)

		actual := tc.match.Match(req)
		if actual != tc.expect {
			t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input)
			continue
		}
	}
}

func TestPathMatcher(t *testing.T) {
	for i, tc := range []struct {
		match  MatchPath
		input  string
		expect bool
	}{
		{
			match:  MatchPath{},
			input:  "/",
			expect: false,
		},
		{
			match:  MatchPath{"/"},
			input:  "/",
			expect: true,
		},
		{
			match:  MatchPath{"/foo/bar"},
			input:  "/",
			expect: false,
		},
		{
			match:  MatchPath{"/foo/bar"},
			input:  "/foo/bar",
			expect: true,
		},
		{
			match:  MatchPath{"/foo/bar/"},
			input:  "/foo/bar",
			expect: false,
		},
		{
			match:  MatchPath{"/foo/bar/"},
			input:  "/foo/bar/",
			expect: true,
		},
		{
			match:  MatchPath{"/foo/bar/", "/other"},
			input:  "/other/",
			expect: false,
		},
		{
			match:  MatchPath{"/foo/bar/", "/other"},
			input:  "/other",
			expect: true,
		},
		{
			match:  MatchPath{"*.ext"},
			input:  "/foo/bar.ext",
			expect: true,
		},
		{
			match:  MatchPath{"*.php"},
			input:  "/index.PHP",
			expect: true,
		},
		{
			match:  MatchPath{"*.ext"},
			input:  "/foo/bar.ext",
			expect: true,
		},
		{
			match:  MatchPath{"/foo/*/baz"},
			input:  "/foo/bar/baz",
			expect: true,
		},
		{
			match:  MatchPath{"/foo/*/baz/bam"},
			input:  "/foo/bar/bam",
			expect: false,
		},
		{
			match:  MatchPath{"*substring*"},
			input:  "/foo/substring/bar.txt",
			expect: true,
		},
		{
			match:  MatchPath{"/foo"},
			input:  "/foo/bar",
			expect: false,
		},
		{
			match:  MatchPath{"/foo"},
			input:  "/foo/bar",
			expect: false,
		},
		{
			match:  MatchPath{"/foo"},
			input:  "/FOO",
			expect: true,
		},
		{
			match:  MatchPath{"/foo*"},
			input:  "/FOOOO",
			expect: true,
		},
		{
			match:  MatchPath{"/foo/bar.txt"},
			input:  "/foo/BAR.txt",
			expect: true,
		},
		{
			match:  MatchPath{"*"},
			input:  "/",
			expect: true,
		},
		{
			match:  MatchPath{"*"},
			input:  "/foo/bar",
			expect: true,
		},
		{
			match:  MatchPath{"**"},
			input:  "/",
			expect: true,
		},
		{
			match:  MatchPath{"**"},
			input:  "/foo/bar",
			expect: true,
		},
	} {
		req := &http.Request{URL: &url.URL{Path: tc.input}}
		repl := caddy.NewReplacer()
		ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
		req = req.WithContext(ctx)

		actual := tc.match.Match(req)
		if actual != tc.expect {
			t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input)
			continue
		}
	}
}

func TestPathMatcherWindows(t *testing.T) {
	// only Windows has this bug where it will ignore
	// trailing dots and spaces in a filename, but we
	// test for it on all platforms to be more consistent

	req := &http.Request{URL: &url.URL{Path: "/index.php . . .."}}
	repl := caddy.NewReplacer()
	ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
	req = req.WithContext(ctx)

	match := MatchPath{"*.php"}
	matched := match.Match(req)
	if !matched {
		t.Errorf("Expected to match; should ignore trailing dots and spaces")
	}
}

func TestPathREMatcher(t *testing.T) {
	for i, tc := range []struct {
		match      MatchPathRE
		input      string
		expect     bool
		expectRepl map[string]string
	}{
		{
			match:  MatchPathRE{},
			input:  "/",
			expect: true,
		},
		{
			match:  MatchPathRE{MatchRegexp{Pattern: "/"}},
			input:  "/",
			expect: true,
		},
		{
			match:  MatchPathRE{MatchRegexp{Pattern: "/foo"}},
			input:  "/foo",
			expect: true,
		},
		{
			match:  MatchPathRE{MatchRegexp{Pattern: "/foo"}},
			input:  "/foo/",
			expect: true,
		},
		{
			match:  MatchPathRE{MatchRegexp{Pattern: "/bar"}},
			input:  "/foo/",
			expect: false,
		},
		{
			match:  MatchPathRE{MatchRegexp{Pattern: "^/bar"}},
			input:  "/foo/bar",
			expect: false,
		},
		{
			match:      MatchPathRE{MatchRegexp{Pattern: "^/foo/(.*)/baz$", Name: "name"}},
			input:      "/foo/bar/baz",
			expect:     true,
			expectRepl: map[string]string{"name.1": "bar"},
		},
		{
			match:      MatchPathRE{MatchRegexp{Pattern: "^/foo/(?P<myparam>.*)/baz$", Name: "name"}},
			input:      "/foo/bar/baz",
			expect:     true,
			expectRepl: map[string]string{"name.myparam": "bar"},
		},
	} {
		// compile the regexp and validate its name
		err := tc.match.Provision(caddy.Context{})
		if err != nil {
			t.Errorf("Test %d %v: Provisioning: %v", i, tc.match, err)
			continue
		}
		err = tc.match.Validate()
		if err != nil {
			t.Errorf("Test %d %v: Validating: %v", i, tc.match, err)
			continue
		}

		// set up the fake request and its Replacer
		req := &http.Request{URL: &url.URL{Path: tc.input}}
		repl := caddy.NewReplacer()
		ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
		req = req.WithContext(ctx)
		addHTTPVarsToReplacer(repl, req, httptest.NewRecorder())

		actual := tc.match.Match(req)
		if actual != tc.expect {
			t.Errorf("Test %d [%v]: Expected %t, got %t for input '%s'",
				i, tc.match.Pattern, tc.expect, actual, tc.input)
			continue
		}

		for key, expectVal := range tc.expectRepl {
			placeholder := fmt.Sprintf("{http.regexp.%s}", key)
			actualVal := repl.ReplaceAll(placeholder, "<empty>")
			if actualVal != expectVal {
				t.Errorf("Test %d [%v]: Expected placeholder {http.regexp.%s} to be '%s' but got '%s'",
					i, tc.match.Pattern, key, expectVal, actualVal)
				continue
			}
		}
	}
}

func TestHeaderMatcher(t *testing.T) {
	for i, tc := range []struct {
		match  MatchHeader
		input  http.Header // make sure these are canonical cased (std lib will do that in a real request)
		host   string
		expect bool
	}{
		{
			match:  MatchHeader{"Field": []string{"foo"}},
			input:  http.Header{"Field": []string{"foo"}},
			expect: true,
		},
		{
			match:  MatchHeader{"Field": []string{"foo", "bar"}},
			input:  http.Header{"Field": []string{"bar"}},
			expect: true,
		},
		{
			match:  MatchHeader{"Field": []string{"foo", "bar"}},
			input:  http.Header{"Alakazam": []string{"kapow"}},
			expect: false,
		},
		{
			match:  MatchHeader{"Field": []string{"foo", "bar"}},
			input:  http.Header{"Field": []string{"kapow"}},
			expect: false,
		},
		{
			match:  MatchHeader{"Field": []string{"foo", "bar"}},
			input:  http.Header{"Field": []string{"kapow", "foo"}},
			expect: true,
		},
		{
			match:  MatchHeader{"Field1": []string{"foo"}, "Field2": []string{"bar"}},
			input:  http.Header{"Field1": []string{"foo"}, "Field2": []string{"bar"}},
			expect: true,
		},
		{
			match:  MatchHeader{"field1": []string{"foo"}, "field2": []string{"bar"}},
			input:  http.Header{"Field1": []string{"foo"}, "Field2": []string{"bar"}},
			expect: true,
		},
		{
			match:  MatchHeader{"field1": []string{"foo"}, "field2": []string{"bar"}},
			input:  http.Header{"Field1": []string{"foo"}, "Field2": []string{"kapow"}},
			expect: false,
		},
		{
			match:  MatchHeader{"field1": []string{"*"}},
			input:  http.Header{"Field1": []string{"foo"}},
			expect: true,
		},
		{
			match:  MatchHeader{"field1": []string{"*"}},
			input:  http.Header{"Field2": []string{"foo"}},
			expect: false,
		},
		{
			match:  MatchHeader{"Field1": []string{"foo*"}},
			input:  http.Header{"Field1": []string{"foo"}},
			expect: true,
		},
		{
			match:  MatchHeader{"Field1": []string{"foo*"}},
			input:  http.Header{"Field1": []string{"asdf", "foobar"}},
			expect: true,
		},
		{
			match:  MatchHeader{"Field1": []string{"*bar"}},
			input:  http.Header{"Field1": []string{"asdf", "foobar"}},
			expect: true,
		},
		{
			match:  MatchHeader{"host": []string{"localhost"}},
			input:  http.Header{},
			host:   "localhost",
			expect: true,
		},
		{
			match:  MatchHeader{"host": []string{"localhost"}},
			input:  http.Header{},
			host:   "caddyserver.com",
			expect: false,
		},
		{
			match:  MatchHeader{"Must-Not-Exist": nil},
			input:  http.Header{},
			expect: true,
		},
		{
			match:  MatchHeader{"Must-Not-Exist": nil},
			input:  http.Header{"Must-Not-Exist": []string{"do not match"}},
			expect: false,
		},
	} {
		req := &http.Request{Header: tc.input, Host: tc.host}
		actual := tc.match.Match(req)
		if actual != tc.expect {
			t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input)
			continue
		}
	}
}

func TestQueryMatcher(t *testing.T) {
	for i, tc := range []struct {
		scenario string
		match    MatchQuery
		input    string
		expect   bool
	}{
		{
			scenario: "non match against a specific value",
			match:    MatchQuery{"debug": []string{"1"}},
			input:    "/",
			expect:   false,
		},
		{
			scenario: "match against a specific value",
			match:    MatchQuery{"debug": []string{"1"}},
			input:    "/?debug=1",
			expect:   true,
		},
		{
			scenario: "match against a wildcard",
			match:    MatchQuery{"debug": []string{"*"}},
			input:    "/?debug=something",
			expect:   true,
		},
		{
			scenario: "non match against a wildcarded",
			match:    MatchQuery{"debug": []string{"*"}},
			input:    "/?other=something",
			expect:   false,
		},
		{
			scenario: "match against an empty value",
			match:    MatchQuery{"debug": []string{""}},
			input:    "/?debug",
			expect:   true,
		},
		{
			scenario: "non match against an empty value",
			match:    MatchQuery{"debug": []string{""}},
			input:    "/?someparam",
			expect:   false,
		},
		{
			scenario: "empty matcher value should match empty query",
			match:    MatchQuery{},
			input:    "/?",
			expect:   true,
		},
		{
			scenario: "nil matcher value should NOT match a non-empty query",
			match:    MatchQuery{},
			input:    "/?foo=bar",
			expect:   false,
		},
		{
			scenario: "non-nil matcher should NOT match an empty query",
			match:    MatchQuery{"": nil},
			input:    "/?",
			expect:   false,
		},
		{
			scenario: "match against a placeholder value",
			match:    MatchQuery{"debug": []string{"{http.vars.debug}"}},
			input:    "/?debug=1",
			expect:   true,
		},
		{
			scenario: "match against a placeholder key",
			match:    MatchQuery{"{http.vars.key}": []string{"1"}},
			input:    "/?somekey=1",
			expect:   true,
		},
	} {

		u, _ := url.Parse(tc.input)

		req := &http.Request{URL: u}
		repl := caddy.NewReplacer()
		ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
		repl.Set("http.vars.debug", "1")
		repl.Set("http.vars.key", "somekey")
		req = req.WithContext(ctx)
		actual := tc.match.Match(req)
		if actual != tc.expect {
			t.Errorf("Test %d %v: Expected %t, got %t for '%s'", i, tc.match, tc.expect, actual, tc.input)
			continue
		}
	}
}

func TestHeaderREMatcher(t *testing.T) {
	for i, tc := range []struct {
		match      MatchHeaderRE
		input      http.Header // make sure these are canonical cased (std lib will do that in a real request)
		host       string
		expect     bool
		expectRepl map[string]string
	}{
		{
			match:  MatchHeaderRE{"Field": &MatchRegexp{Pattern: "foo"}},
			input:  http.Header{"Field": []string{"foo"}},
			expect: true,
		},
		{
			match:  MatchHeaderRE{"Field": &MatchRegexp{Pattern: "$foo^"}},
			input:  http.Header{"Field": []string{"foobar"}},
			expect: false,
		},
		{
			match:      MatchHeaderRE{"Field": &MatchRegexp{Pattern: "^foo(.*)$", Name: "name"}},
			input:      http.Header{"Field": []string{"foobar"}},
			expect:     true,
			expectRepl: map[string]string{"name.1": "bar"},
		},
		{
			match:  MatchHeaderRE{"Field": &MatchRegexp{Pattern: "^foo.*$", Name: "name"}},
			input:  http.Header{"Field": []string{"barfoo", "foobar"}},
			expect: true,
		},
		{
			match:  MatchHeaderRE{"host": &MatchRegexp{Pattern: "^localhost$", Name: "name"}},
			input:  http.Header{},
			host:   "localhost",
			expect: true,
		},
		{
			match:  MatchHeaderRE{"host": &MatchRegexp{Pattern: "^local$", Name: "name"}},
			input:  http.Header{},
			host:   "localhost",
			expect: false,
		},
	} {
		// compile the regexp and validate its name
		err := tc.match.Provision(caddy.Context{})
		if err != nil {
			t.Errorf("Test %d %v: Provisioning: %v", i, tc.match, err)
			continue
		}
		err = tc.match.Validate()
		if err != nil {
			t.Errorf("Test %d %v: Validating: %v", i, tc.match, err)
			continue
		}

		// set up the fake request and its Replacer
		req := &http.Request{Header: tc.input, URL: new(url.URL), Host: tc.host}
		repl := caddy.NewReplacer()
		ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
		req = req.WithContext(ctx)
		addHTTPVarsToReplacer(repl, req, httptest.NewRecorder())

		actual := tc.match.Match(req)
		if actual != tc.expect {
			t.Errorf("Test %d [%v]: Expected %t, got %t for input '%s'",
				i, tc.match, tc.expect, actual, tc.input)
			continue
		}

		for key, expectVal := range tc.expectRepl {
			placeholder := fmt.Sprintf("{http.regexp.%s}", key)
			actualVal := repl.ReplaceAll(placeholder, "<empty>")
			if actualVal != expectVal {
				t.Errorf("Test %d [%v]: Expected placeholder {http.regexp.%s} to be '%s' but got '%s'",
					i, tc.match, key, expectVal, actualVal)
				continue
			}
		}
	}
}

func TestVarREMatcher(t *testing.T) {
	for i, tc := range []struct {
		desc       string
		match      MatchVarsRE
		input      VarsMiddleware
		expect     bool
		expectRepl map[string]string
	}{
		{
			desc:   "match static value within var set by the VarsMiddleware succeeds",
			match:  MatchVarsRE{"Var1": &MatchRegexp{Pattern: "foo"}},
			input:  VarsMiddleware{"Var1": "here is foo val"},
			expect: true,
		},
		{
			desc:   "value set by VarsMiddleware not satisfying regexp matcher fails to match",
			match:  MatchVarsRE{"Var1": &MatchRegexp{Pattern: "$foo^"}},
			input:  VarsMiddleware{"Var1": "foobar"},
			expect: false,
		},
		{
			desc:       "successfully matched value is captured and its placeholder is added to replacer",
			match:      MatchVarsRE{"Var1": &MatchRegexp{Pattern: "^foo(.*)$", Name: "name"}},
			input:      VarsMiddleware{"Var1": "foobar"},
			expect:     true,
			expectRepl: map[string]string{"name.1": "bar"},
		},
		{
			desc:   "matching against a value of standard variables succeeds",
			match:  MatchVarsRE{"{http.request.method}": &MatchRegexp{Pattern: "^G.[tT]$"}},
			input:  VarsMiddleware{},
			expect: true,
		},
		{
			desc:   "matching against value of var set by the VarsMiddleware and referenced by its placeholder succeeds",
			match:  MatchVarsRE{"{http.vars.Var1}": &MatchRegexp{Pattern: "[vV]ar[0-9]"}},
			input:  VarsMiddleware{"Var1": "var1Value"},
			expect: true,
		},
	} {
		tc := tc // capture range value
		t.Run(tc.desc, func(t *testing.T) {
			t.Parallel()
			// compile the regexp and validate its name
			err := tc.match.Provision(caddy.Context{})
			if err != nil {
				t.Errorf("Test %d %v: Provisioning: %v", i, tc.match, err)
				return
			}
			err = tc.match.Validate()
			if err != nil {
				t.Errorf("Test %d %v: Validating: %v", i, tc.match, err)
				return
			}

			// set up the fake request and its Replacer
			req := &http.Request{URL: new(url.URL), Method: http.MethodGet}
			repl := caddy.NewReplacer()
			ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
			ctx = context.WithValue(ctx, VarsCtxKey, make(map[string]interface{}))
			req = req.WithContext(ctx)

			addHTTPVarsToReplacer(repl, req, httptest.NewRecorder())

			tc.input.ServeHTTP(httptest.NewRecorder(), req, emptyHandler)

			actual := tc.match.Match(req)
			if actual != tc.expect {
				t.Errorf("Test %d [%v]: Expected %t, got %t for input '%s'",
					i, tc.match, tc.expect, actual, tc.input)
				return
			}

			for key, expectVal := range tc.expectRepl {
				placeholder := fmt.Sprintf("{http.regexp.%s}", key)
				actualVal := repl.ReplaceAll(placeholder, "<empty>")
				if actualVal != expectVal {
					t.Errorf("Test %d [%v]: Expected placeholder {http.regexp.%s} to be '%s' but got '%s'",
						i, tc.match, key, expectVal, actualVal)
					return
				}
			}
		})
	}
}

func TestResponseMatcher(t *testing.T) {
	for i, tc := range []struct {
		require ResponseMatcher
		status  int
		hdr     http.Header // make sure these are canonical cased (std lib will do that in a real request)
		expect  bool
	}{
		{
			require: ResponseMatcher{},
			status:  200,
			expect:  true,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{200},
			},
			status: 200,
			expect: true,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{2},
			},
			status: 200,
			expect: true,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{201},
			},
			status: 200,
			expect: false,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{2},
			},
			status: 301,
			expect: false,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{3},
			},
			status: 301,
			expect: true,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{3},
			},
			status: 399,
			expect: true,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{3},
			},
			status: 400,
			expect: false,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{3, 4},
			},
			status: 400,
			expect: true,
		},
		{
			require: ResponseMatcher{
				StatusCode: []int{3, 401},
			},
			status: 401,
			expect: true,
		},
		{
			require: ResponseMatcher{
				Headers: http.Header{
					"Foo": []string{"bar"},
				},
			},
			hdr:    http.Header{"Foo": []string{"bar"}},
			expect: true,
		},
		{
			require: ResponseMatcher{
				Headers: http.Header{
					"Foo2": []string{"bar"},
				},
			},
			hdr:    http.Header{"Foo": []string{"bar"}},
			expect: false,
		},
		{
			require: ResponseMatcher{
				Headers: http.Header{
					"Foo": []string{"bar", "baz"},
				},
			},
			hdr:    http.Header{"Foo": []string{"baz"}},
			expect: true,
		},
		{
			require: ResponseMatcher{
				Headers: http.Header{
					"Foo":  []string{"bar"},
					"Foo2": []string{"baz"},
				},
			},
			hdr:    http.Header{"Foo": []string{"baz"}},
			expect: false,
		},
		{
			require: ResponseMatcher{
				Headers: http.Header{
					"Foo":  []string{"bar"},
					"Foo2": []string{"baz"},
				},
			},
			hdr:    http.Header{"Foo": []string{"bar"}, "Foo2": []string{"baz"}},
			expect: true,
		},
		{
			require: ResponseMatcher{
				Headers: http.Header{
					"Foo": []string{"foo*"},
				},
			},
			hdr:    http.Header{"Foo": []string{"foobar"}},
			expect: true,
		},
		{
			require: ResponseMatcher{
				Headers: http.Header{
					"Foo": []string{"foo*"},
				},
			},
			hdr:    http.Header{"Foo": []string{"foobar"}},
			expect: true,
		},
	} {
		actual := tc.require.Match(tc.status, tc.hdr)
		if actual != tc.expect {
			t.Errorf("Test %d %v: Expected %t, got %t for HTTP %d %v", i, tc.require, tc.expect, actual, tc.status, tc.hdr)
			continue
		}
	}
}

func TestNotMatcher(t *testing.T) {
	for i, tc := range []struct {
		host, path string
		match      MatchNot
		expect     bool
	}{
		{
			host: "example.com", path: "/",
			match:  MatchNot{},
			expect: true,
		},
		{
			host: "example.com", path: "/foo",
			match: MatchNot{
				MatcherSets: []MatcherSet{
					{
						MatchPath{"/foo"},
					},
				},
			},
			expect: false,
		},
		{
			host: "example.com", path: "/bar",
			match: MatchNot{
				MatcherSets: []MatcherSet{
					{
						MatchPath{"/foo"},
					},
				},
			},
			expect: true,
		},
		{
			host: "example.com", path: "/bar",
			match: MatchNot{
				MatcherSets: []MatcherSet{
					{
						MatchPath{"/foo"},
					},
					{
						MatchHost{"example.com"},
					},
				},
			},
			expect: false,
		},
		{
			host: "example.com", path: "/bar",
			match: MatchNot{
				MatcherSets: []MatcherSet{
					{
						MatchPath{"/bar"},
					},
					{
						MatchHost{"example.com"},
					},
				},
			},
			expect: false,
		},
		{
			host: "example.com", path: "/foo",
			match: MatchNot{
				MatcherSets: []MatcherSet{
					{
						MatchPath{"/bar"},
					},
					{
						MatchHost{"sub.example.com"},
					},
				},
			},
			expect: true,
		},
		{
			host: "example.com", path: "/foo",
			match: MatchNot{
				MatcherSets: []MatcherSet{
					{
						MatchPath{"/foo"},
						MatchHost{"example.com"},
					},
				},
			},
			expect: false,
		},
		{
			host: "example.com", path: "/foo",
			match: MatchNot{
				MatcherSets: []MatcherSet{
					{
						MatchPath{"/bar"},
						MatchHost{"example.com"},
					},
				},
			},
			expect: true,
		},
	} {
		req := &http.Request{Host: tc.host, URL: &url.URL{Path: tc.path}}
		repl := caddy.NewReplacer()
		ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
		req = req.WithContext(ctx)

		actual := tc.match.Match(req)
		if actual != tc.expect {
			t.Errorf("Test %d %+v: Expected %t, got %t for: host=%s path=%s'", i, tc.match, tc.expect, actual, tc.host, tc.path)
			continue
		}
	}
}

func BenchmarkHostMatcherWithoutPlaceholder(b *testing.B) {
	req := &http.Request{Host: "localhost"}
	repl := caddy.NewReplacer()
	ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
	req = req.WithContext(ctx)

	match := MatchHost{"localhost"}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		match.Match(req)
	}
}

func BenchmarkHostMatcherWithPlaceholder(b *testing.B) {
	err := os.Setenv("GO_BENCHMARK_DOMAIN", "localhost")
	if err != nil {
		b.Errorf("error while setting up environment: %v", err)
	}

	req := &http.Request{Host: "localhost"}
	repl := caddy.NewReplacer()
	ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
	req = req.WithContext(ctx)
	match := MatchHost{"{env.GO_BENCHMARK_DOMAIN}"}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		match.Match(req)
	}
}


text:
local s = require('say')

s:set_namespace('fr')

-- 'Pending: test.lua @ 12 \n description
s:set('output.pending', 'En attente')
s:set('output.failure', 'Echec')
s:set('output.success', 'Reussite')

s:set('output.pending_plural', 'en attente')
s:set('output.failure_plural', 'echecs')
s:set('output.success_plural', 'reussites')

s:set('output.pending_zero', 'en attente')
s:set('output.failure_zero', 'echec')
s:set('output.success_zero', 'reussite')

s:set('output.pending_single', 'en attente')
s:set('output.failure_single', 'echec')
s:set('output.success_single', 'reussite')

s:set('output.seconds', 'secondes')

s:set('output.no_test_files_match', 'Aucun test n\'est pourrait trouvé qui corresponde au motif de Lua: %s')

-- definitions following are not used within the 'say' namespace
return {
  failure_messages = {
    'Vous avez %d test(s) qui a/ont echoue(s)',
    'Vos tests ont echoue.',
    'Votre code source est mauvais et vous devrez vous sentir mal',
    'Vous avez un code source de Destruction Massive',
    'Jeu plutot etrange game. Le seul moyen de gagner est de ne pas l\'essayer',
    'Meme ma grand-mere ecrivait de meilleurs tests sur un PIII x86',
    'A chaque erreur, prenez une biere',
    'Ca craint, mon pote'
  },
  success_messages = {
    'Oh yeah, tests reussis',
    'Pas grave, y\'a eu du succes',
    'C\'est du bon, mon pote. Que du bon!',
    'Reussi, haut la main!',
    'Test reussi. Un de plus. Offre toi une biere, sur mon compte!',
  }
}


text:
ITK Release 4.10
================

New Features

------------------------------------------------------------------------

-   Wrapping improvements

<!-- -->

-   -   ITK\_USE\_64BITS\_IDS supported on Windows
    -   Faster builds (CastXML calls and build targets reduced by half)
    -   Faster runtime loading and smaller binary size due to hidden
        symbol visibility
    -   Wrapping with BUILD\_SHARED\_LIBS disabled is supported
    -   Do not link to libpython when possible
    -   Filter types do not need to be specified when "Input=inputImage"
        is specified in the constructor
    -   Improved wrapping class coverage
    -   Visual Studio 2015 Update 2 Supported
    -   GCC 6.1 supported

<!-- -->

-   New Remote Module
    -   TwoProjectionRegistration
        -   2D-3D registration designed for radiotherapy
        -   <http://hdl.handle.net/10380/3245>

<!-- -->

-   Core Improvements
    -   Data and build tool downloads now over HTTPS
    -   Extended constexpr usage with ITK\_CONSTEXPR and
        ITKCONSTEXPR\_FUNC macros
    -   ITK\_USE\_64BITS\_IDS, required to process 4GB+ images on
        Windows, now enabled by default
    -   VNL updated and modernized
    -   CMake configuration major modernization
    -   vcl has been removed in favor of the standard libraries
    -   vnl\_math\_ function avoided in favor of std:: and itk::Math
    -   VNL had suppressed integer data conversion warnings on Visual
        Studio (C4257); this suppression has been removed and all
        warnings addressed
    -   Various improvements for building a module externally against an
        ITK build tree
    -   CMAKE\_POSITION\_INDEPENDENT\_CODE is enabled by default
    -   Improved EXERCISE\_BASIC\_OBJECT\_METHODS testing macro

<!-- -->

-   Filtering Improvements
    -   RGB pixel support added to itk::ImageToVTKImageFilter
    -   itk::Box\* filters moved out of the Review module
    -   itk::GaussianDerivativeOperator moved out of the Review module
    -   MaskLabel is deprecated in N4BiasFieldCorrectionFilter in favor
        any non-zero pixel

<!-- -->

-   Registration Improvements
    -   Fixed and moving masks added to the v4 registration methods

<!-- -->

-   Documentation Improvements
    -   Updates to the Software Guide, Doxygen, Wiki and Sphinx Examples
    -   New examples on to convert between ITK and VTK
    -   New example on how to perform vector image registration
    -   The ITK Software Guide describes how to add a third-party
        dependency to a module

<!-- -->

-   Third Party Library Updates
    -   pygccxml updated to v1.7.3
    -   GDCM updated to the release branch latest
    -   VNL updated to latest upstream
    -   MINC updated to the latest upstream
    -   SWIG updated to v3.0.8
    -   PCRE update to v8.38

Changes from v4.10rc02..v4.10.0

------------------------------------------------------------------------

Bradley Lowekamp (3):

`     COMP: Address uninitialized warning of size`\
`     COMP: Devirtualize private methods to prevent instantiation`\
`     COMP: Use well defined ZeroValue for unused initial value.`

Hans Johnson (1):

`     BUG: try_compile needs to have CMAKE_CXX_STANDARD passed`

Hyun Jae Kang (1):

`     COMP: Fix unexpected data-cast results of itkCastImageFilter`

Jon Haitz Legarreta (1):

`     BUG: Fix OpenCV-2.4.9 camera empty image issue.`

Matthew McCormick (13):

`     COMP: Bump CastXML for GCC 6.1 support.`\
`     STYLE: Improvements to HardConnectedComponentsImageFilter.`\
`     ENH: Add baseline for itkHardConnectedComponentImageFilterTest.`\
`     STYLE: Improvements for itkHardConnectedComponentImageFilterTest`\
`     COMP: HardConnectedComponentImageFilter autological constant out of range`\
`     DOC: Sphinx examples update to 2016-05-22.`\
`     DOC: Wiki examples update to 2016-05-22.`\
`     COMP: MSVC result of 32-bit shift implicitly converted to 64 bits`\
`     BUG: Disable building the netlib example.`\
`     ENH: Add FloatAddULP`\
`     BUG: Decrement index in BSplineTransform by ULPs.`\
`     BUG: Adjust index decrement in BSplineTransform`\
`     BUG: Remove VNL README left over from subtree merge.`

Sumedha Singla (1):

`     ENH: WhatModulesITK was not finding modules on Windows`

Changes from v4.10rc01..v4.10rc02

------------------------------------------------------------------------

Davis Vigneault (1):

`     BUG: Improve error checking and testing for ConnectedRegionsMesh`

Hyun Jae Kang (2):

`     BUG: Address the issue of `"`Missing`` ``Delete`"` within SwapZeroCornerToIRP.`\
`     COMP: Fixed Mac OSX wrapping configuration warning`

Matthew McCormick (6):

`     BUG: The ImageFileReader internal pipeline methods should be protected.`\
`     BUG: Use new VNL include directory variables.`\
`     COMP: Add missing NeighborhoodAccessor methods to PhasedArray3D image.`\
`     BUG: Adjust itk.org ExternalData URL.`\
`     COMP: Do not use target_include_directories with CMake 2.8.11.2.`\
`     BUG: Address missing shared_ptr for VS9`

Changes from v4.9.0..v4.10rc01

------------------------------------------------------------------------

Alvaro Sanchez (1):

`     STYLE: moved itkKappaSigmaThresholdImageFilter/Calculator from Nonunit/Review`

Andrey Fedorov (2):

`     BUG: Add missing itk_expat_mangle.h install target`\
`     BUG: fix typo in file name`

Bill Hoffman (2):

`     COMP: fix shared build on Windows when Review is on.`\
`     COMP: work around for VS 2015 optimizer bug causing test failures.`

Bill Lorensen (6):

`     ENH: Bump version for style fixups.`\
`     ENH: Bump wiki examples version, new remote module process`\
`     ENH: Bump wiki examples version, new remote module process`\
`     STYLE: SuperClass should be Superclass`\
`     COMP: Resolve clang linkage issue`\
`     BUG: Valgrind detected an invalid read`

Bradley Lowekamp (21):

`     BUG: Compilation problem with GCC 4.1 and explicit instantiation`\
`     ENH: Update Insight Journal handle links to https`\
`     ENH: Adding const qualifier to results`\
`     BUG: Adding missing const qualifier for GetConfusionMatrix method`\
`     BUG: Use Set/GetMacros, fix const correctness and PrintSelf.`\
`     ENH: added inlined Zero and one values for integer NumericTraits`\
`     ENH: Use constexpr for floating point NumericTraits`\
`     ENH: Make NumericTraits functions constexpr for intrinsic`\
`     BUG: Add definition of static constexpr NumericTrait members`\
`     BUG: Declared static constexpr members need to be defined as constexpr`\
`     ENH: ITK_CONSTEXPR_FUNC implies inline`\
`     BUG: Addressing VS10 and VS11 NumericTraits linkage issue`\
`     BUG: Use LargestPossible region for BSpline domain`\
`     BUG: Remove errant file`\
`     COMP: Address warning about this usage in initializer list`\
`     ENH: Prefer ZeroValue function over variable`\
`     STYLE: Use consistent path for try_compiles binary directory`\
`     BUG: Don't use `"`=`"` in cmake variable name`\
`     ENH: Test address of NumericTraits One and Zero constexpr`\
`     ENH: Use ITK_USE_64BITS_IDS for windows 64 by default`\
`     ENH: Enable run-time dependency on Python library`

Davis Vigneault (4):

`     ENH: Update itkFileTools to allow std::string arguments.`\
`     ENH: Add Floored and Truncated Modulus to VNL`\
`     ENH: Add Ternary Operator Image Filter`\
`     STYLE: Prefer static cast`

Dženan Zukić (1):

`     ENH: CovariantVector's Normalize returns the norm.`

Francois Budin (6):

`     PERF: Simplify itkTemplate New() input type identification.`\
`     ENH: Avoid template type specification for image reader in Python wrapping`\
`     BUG: Missing IOPixelType strings in ImageIOBase`\
`     BUG: Wrapping intermediate files were not automatically updated`\
`     ENH: Reduce number of dependencies for XML files generated for wrapping`\
`     BUG: GCC is limited when calling overloaded base class functions`

GCC-XML Upstream (1):

`     ENH: pygccxml v1.7.3 (reduced)`

GDCM Upstream (1):

`     GDCM 2015-09-02 (1efe9e28)`

Hans Johnson (27):

`     COMP: Static analysis warning`\
`     COMP: Incorrect delete found by static analysis`\
`     PERF:  Avoid temporary std:vector copying.`\
`     COMP: Provide VXL backward compatible includes`\
`     COMP: ITK requires legacy methods`\
`     ENH: Need propagate ITK_LIBRARY_PROPERTIES`\
`     ENH: Added UpdateFromUpstream.sh for VNL`\
`     ENH: Manual copy from vxl/master`\
`     STYLE: vnl_math_[min|max] -> std::[min|max]`\
`     STYLE: Text files should end with a newline`\
`     COMP: Prefer C++11 constexpr when possible`\
`     COMP: Prefer C++11 constexpr when possible`\
`     ENH: Simplify std:: math function definitions`\
`     COMP: Error in constexpr usage`\
`     COMP: Add const to previous const variables`\
`     COMP: SizeValueType can has different definition for itkArray`\
`     ENH: Added utility for modernizing vcl_ to std::`\
`     ENH: Reference vnl_math.h constants directly`\
`     ENH: Avoid using vnl_math_ functions`\
`     COMP: Missing symbol for itkStaticConstMacro`\
`     COMP: Function override missing in BioCell`\
`     ENH: Convert vcl_ to std::`\
`     BUG: Windows vcl_snprintf failures addressed`\
`     COMP: Disabmiguate function calls to SetData`\
`     ENH: Provided static code API for external applications`\
`     COMP: Remove possible type conversion warnings`\
`     ENH: Merge GDCM release branch`

Hyun Jae Kang (25):

`     COMP: Fixed the compiler error of ITKCommon2TestDriver on OSX 10.6`\
`     BUG: Fixed the runtime crash of VideoSourceTest on OSX 10.6`\
`     BUG: Fixed the runtime crash of itkTimeProbeTest2`\
`     BUG: Fixed the runtime crash of ITKFastMarchingTestDriver's tests on OSX 10.6`\
`     BUG: Fixed the runtime crash of ITKReviewTestDriver on OSX 10.6`\
`     COMP: Fixed the data conversion warning messages of itkResourceProbe`\
`     BUG: Fixed the runtime crash of itkLabelOverlapMeasuresImageFilterTest`\
`     BUG: Fixed the runtime crash of ITKStatisticsTestDriver tests on OSX 10.6`\
`     BUG: Fixed the runtime crash of itkMRIBiasFieldCorrectionFilterTest`\
`     BUG: Fixed the runtime crash of itkBinaryShapeOpeningImageFilterTest1`\
`     BUG: Fixed the runtime crash of vnl_test_complex on OSX 10.6`\
`     BUG: Fixed the runtime crash of vnl_test_numeric_traits`\
`     BUG: Fixed the runtime crash of test_pow_log on OSX 10.6`\
`     BUG: Exclude a test code of ITKLabelMapTestDriver on OSX 10.6`\
`     BUG: Fixed the failed test case of itkSTLThreadTest on OS X 10.8`\
`     COMP: Update KWStyle to utilize the latest boost library`\
`     COMP: Fixed the compiler error of ITK on Mingw-w64`\
`     COMP: Temporarily suppress the warning messages of data-conversion on VS14`\
`     COMP: Put back the disappeared option of `"`BUILD`` ``EXAMPLES`"`.`\
`     BUG: Fix segmentation faults on mingw-W64 x86_64.`\
`     BUG: Fix the failed test of itkCastImageFilterTest on mingw-w64 compiler.`\
`     COMP: Fixed the cmake configuration for ITK_WRAP_DOC`\
`     COMP: Fixed the warning messages on VS14.`\
`     COMP: Add a missing head file at itkNumericTraitsStdVector.h`\
`     COMP: Fix the wraning message of data-conversion`

Jean-Christophe Fillion-Robin (4):

`     COMP: ITKExternalModule: Support building module without test directory.`\
`     STYLE: Facilitate maintenance of CastXML generator refactoring CMakeLists`\
`     COMP: Allow use of multiple `"`ITK`` ``external`` ``modules`"` in the same project.`\
`     STYLE: UseITK: Document static registration of ITK IO factories. See #3393`

Jon Haitz Legarreta (7):

`     COMP: Delete unused variable compiler warning.`\
`     ENH: Refactored itkBioCellTest`\
`     ENH: Exercise non-tested itk::Math methods.`\
`     ENH: Improve MersenneTwister class and test.`\
`     ENH: Improve itkFEMLoadPoint coverage.`\
`     ENH: Improve itkVersion class code coverage.`\
`     ENH: Perform class name checks in test macro`

KWSys Robot (1):

`     KWSys 2016-03-09 (36d8666f)`

Lucas Gandel (9):

`     ENH: Implement GetNumberOfParameter() in ImageToSpatialObjectMetric`\
`     COMP: Enable wrapping of multiple `"`ITK`` ``external`` ``modules`"` in the same project`\
`     COMP: Fix CASTXML_EXECUTABLE value for multiple external module`\
`     COMP: Fix external module testing`\
`     COMP: Fix git protocol setup`\
`     ENH: Conditionally add testing for External Modules`\
`     BUG: Fix call to std::max() with different variable types`

Manuel Grizonnet (1):

`     COMP: add ITKCommon_EXPORT to fix link issues with external applications`

Matthew McCormick (73):

`     ENH: Add TwoProjectionRegistration Remote Module.`\
`     ENH: Allow ITKVideoBridgeOpenCV to be built externally.`\
`     COMP: Add export specification for itk::ResourceProbe.`\
`     ENH: Do not force shared libraries when wrapping.`\
`     BUG: BUILD_TESTING should be not advanced.`\
`     ENH: Bump ITK version to 4.10.0.`\
`     DOC: Correct ITKImageNoise description spelling.`\
`     ENH: Wrap FFTNormalizedCorrelationImageFilter.`\
`     BUG: Remove Azure ExternalData resource.`\
`     BUG: ExternalData downloads from midas3.kitware.com only supports https.`\
`     BUG: Update ExternalData resource.`\
`     BUG: slicer.kitware.com/midas3/ ExternalData will not support http.`\
`     ENH: Add ITK_CUSTOM_LIBRARY_SUFFIX variable.`\
`     ENH: Wrap PipelineMonitorImageFilter.`\
`     BUG: Update MIDAS url for https in archive testing data script.`\
`     ENH: Wrap std::vector< itk::ImageRegion >.`\
`     BUG: Fix wrapping build with DEFAULT_MODULES OFF.`\
`     ENH: Add RGB pixel support to ImageToVTKImageFilter.`\
`     ENH: Add RGB and vector pixel type wrapping for ImageToVTKImageFilter.`\
`     STYLE: Use PixelType and ImageType in Python tests.`\
`     ENH: Avoid template type specification in Python wrapping.`\
`     COMP: Do not use has_key in itkTemplate New.`\
`     DOC: Emphasize that push access is not required to contribute patches.`\
`     ENH: Download SWIG and PCRE from midas3.kitware.com.`\
`     COMP: Ignore build warning from KWStyle's boost.`\
`     BUG: Remove Azure ExternalData resource.`\
`     BUG: ExternalData downloads from midas3.kitware.com only supports https.`\
`     BUG: slicer.kitware.com/midas3/ ExternalData will not support http.`\
`     ENH: Update the VNL README-ITK.txt subtree commit revision.`\
`     BUG: Mark VXL internal CMake variables as advanced.`\
`     BUG: Run itk_module_target on itknetlib.`\
`     DOC: Direct patches for VXL upstream to the GitHub repository.`\
`     BUG: Run itk_module_target on itknetlib.`\
`     COMP: Account for removal of vcl_* from upstream VXL.`\
`     COMP: Remove itkTypeMacro from BioCellHelper.`\
`     COMP: Convert itkBioCellTest arguments from double to int.`\
`     COMP: Turn off BUILD_DOCUMENTATION for VNL.`\
`     BUG: Install VXL config files to backwards-compatible locations.`\
`     ENH: Remove vcl_complex from the wrapping.`\
`     BUG: Install vnl_export.h and vnl_algo_export.h to previous locations.`\
`     BUG: midas3.kitware.com only supports the https protocol.`\
`     BUG: ImageIOBase SetDimensions should take SizeValueType.`\
`     ENH: Add wrapping for ImagePCAShapeModelEstimator.`\
`     COMP: Do not specify COMPONENTS with find_package(VTK.`\
`     DOC: Fix FFTW warning grammar.`\
`     COMP: Build against system HDF5 1.8.16.`\
`     ENH: Set a default CMAKE_BUILD_TYPE when building a module externally`\
`     COMP: Make initial HDF5 discovery of 1.8.16 quiet.`\
`     ENH: Use hidden symbol visibility for the CPython extension modules.`\
`     ENH: Turn on CMAKE_POSITION_INDEPENDENT_CODE by default.`\
`     BUG: FEMLoadPoint uninitialized value in the constructor.`\
`     BUG: Fix wrapping of complex types in VNL.`\
`     ENH: Bump CMakeLists.txt version 4.9.1.`\
`     COMP: Address ITKCommon Python submodule order.`\
`     BUG: Extend ExternalData_TIMEOUT_ABSOLUTE to 900 seconds.`\
`     BUG: Do not run KWStyle Git config on a release tarball.`\
`     COMP: Ambiguous RGBPixel access in CustomColormapFunction.`\
`     BUG: Prevent division by zero in PhasedArray3DSpecialCoordinatesImage.`\
`     BUG: Initialize azimuth and elevation to pi/2 in PhasedArray3D.`\
`     BUG: Increase MaskLabel backwards compatibility in N4 bias correction.`\
`     ENH: Deprecate MaskLabel in N4BiasFieldCorrectionImageFilter.`\
`     COMP: Update CastXML to support Visual Studio 2015 Update 2.`\
`     COMP: Do not set wrapping library visibility with static builds.`\
`     COMP: Update CastXML to support Visual Studio 2015 Update 2.`\
`     COMP: Broaden the KWStyle warning exception.`\
`     COMP: Update KWStyle version.`\
`     BUG: Do not use the same output file in N4BiasField Test 2,3.`\
`     COMP: Expand EXERCISE_BASIC_OBJECT_METHODS for other GCC versions.`\
`     ENH: Update Cuberille Remote to 2015-05-01.`\
`     ENH: Enable registration of the IOOpenSlide module through CMake.`\
`     ENH: Update itk.org URL's for HTTPS support.`\
`     BUG: Use CastXML built against LLVM with LLVM_ENABLE_TERMINFO OFF.`\
`     BUG: Fix Python wrapping on Windows when ITK_USE_64BIT_IDS is ON.`

Michka Popoff (12):

`     ENH: Use importlib for python 3.4 instead of imp`\
`     ENH: Update to Swig 3.0.8`\
`     ENH: Update PCRE to version 8.38`\
`     ENH: Wrap RayCastInterpolateImageFunction`\
`     ENH: Wrap RayCastInterpolateImageFunction`\
`     COMP: Remove debug output after vcl_complex removal from wrapping`\
`     ENH: Consolidate .idx file generation with swig .i generation.`\
`     ENH: Update UpdatepygccxmlFromUpstream.sh script`\
`     COMP: Set CastXML path and name for pygccxml 1.7.3`\
`     COMP: Fix RayCastInterpolateImageFunction wrapping for image dim 2`\
`     ENH: Use argparse instead of optparse in igenerator.py`\
`     ENH: Use https URL for OS X castxml binary (for consistency)`

Nick Tustison (2):

`     ENH:  Add fixed/moving masking in reg. methods.`\
`     ENH:  Making the mask usage consistent with ITK.`

Pablo Hernandez-Cerdan (1):

`     COMP: Fix warn in FFTW about delete [].`

Sean McBride (18):

`     COMP: Made script OS X compatible`\
`     COMP: mark GDCM GetSeriesHelper() method as deprecated`\
`     BUG: update script to fetch GDCM from its release-2-4 branch instead of master`\
`     DOC: Updated comment to reflect new GDCM version`\
`     COMP: Fixed recently introduced build error with deprecated GDCM method`\
`     BUG: Fixed invalid memory access found by ASan`\
`     COMP: Fixed clang warning about macro expansion giving defined`\
`     COMP: Fixed minor dashboards warnings and typos.`\
`     COMP: Fixed a bunch of clang -Wunreachable-code-break warnings`\
`     COMP: fixed some dashboard warnings (dead code, false positive)`\
`     BUG: Fixed off-by-1 error found by ASan`\
`     COMP: Fixed clang -Wcomma warning`\
`     COMP: Introduce ITK_FALLTHROUGH, to suppress switch fall through warnings`\
`     COMP: Fixed -Wwritable-strings warnings`\
`     COMP: Fixed remaining -Wcomma warnings`\
`     ENH: switch gdcm to release branch, not release-2-4`\
`     COMP: Hack HDF5 to build under ASan & UBSan`\
`     COMP: fixed clang -Wdeprecated-writable-strings warning`

Shawn Waldon (1):

`     STYLE: move itkGaussianDerivativeOperator`

Sujin Philip (1):

`     STYLE: Move itkBox* Filters`

Sumedha Singla (3):

`     ENH: Issue: ITK#3363 Replaced assignment in SetParameters function.`\
`     ENH: Remove unnecessary const_cast`\
`     BUG: Fixed the test itkHDF5ImageIOTest`

VXL Maintainers (9):

`     VNL 2015-11-22 (ea1d60fb)`\
`     VNL 2016-03-02 (cb31149e)`\
`     VNL 2016-03-13 (ae34f0fc)`\
`     VNL 2016-03-15 (751698ab)`\
`     VNL 2016-03-19 (df10fefa)`\
`     VNL 2016-03-25 (f0040231)`\
`     VNL 2016-03-30 (88f50849)`\
`     VNL 2016-04-22 (0ed18124)`\
`     VNL 2016-04-26 (6b168535)`

Vladimir S. FONOV (3):

`     MINC 2015-12-17 (dcb93a5f)`\
`     MINC 2016-01-30 (783bca38)`\
`     MINC 2016-02-24 (8632513e)`

Ziv Yaniv (1):

`     BUG: Interpretation of the Euler angles ZYX or ZXY was not exported.`

ITK Sphinx Examples Changelog

------------------------------------------------------------------------

Dženan Zukić (1):

`     ENH: Default is current directory. Avoid usage of the class SeriesHelper.`

Matt McCormick (19):

`     BUG: Do not depend on the VTK/OpenCV build when system provided.`\
`     ENH: Add ConvertAnitkImageTovtkImageData example.`\
`     ENH: Bump VTK's superbuild version to 7.0.0.`\
`     STYLE: CMake style updates to AddOffsetToIndex/CMakeLists.txt`\
`     ENH: Updates to CreateNewExample.py.in`\
`     ENH: Add ConvertvtkImageDataToAnitkImage example.`\
`     ENH: Update sphinx-bootstrap-theme to v0.4.8`\
`     ENH: Add Python version of StreamAPipeline.`\
`     ENH: Add ConvertAnRGBitkImageTovtkImageData`\
`     ENH: Add a PACE progress bar.`\
`     ENH: Add more Python content to CreateNewExample.py.`\
`     ENH: Add ConvertRGBvtkImageDataToAnitkImage`\
`     BUG: Disable Create3DVolume Python baseline test.`\
`     ENH: Add PerformRegistrationOnVectorImages.`\
`     ENH: Update itk.org URL's for HTTPS support.`\
`     COMP: Use itk::IndexValueType for subdomain index.`\
`     COMP: Bump OpenCV to 3.1.0.`\
`     BUG: Fix superbuild dependencies.`\
`     ENH: Bump ITK to v4.10.0.`

ITK Software Guide Changelog

------------------------------------------------------------------------

Matt McCormick (6):

`     DOC: Correct spelling in the wrapping description.`\
`     BUG: ExternalData servers now use https.`\
`     ENH: Update itk.org URL's for HTTPS support.`\
`     DOC: Adding wrapper .dll's to PATH on Windows is no longer necessary.`\
`     DOC: Document how to add a third-party dependency to a module.`\
`     ENH: Bump ITK ExternalProject to v4.10.0`


text:
package org.purl.sword.atom;

import org.purl.sword.base.*;

/**
 *
 * @author Neil Taylor (nst@aber.ac.uk)
 */
public class Accept extends BasicStringContentElement
{
    /**
     * The XmlName representation for this element.
     */
    private static final XmlName XML_NAME =
            new XmlName(Namespaces.PREFIX_APP, "accept", Namespaces.NS_APP);

    public Accept()
    {
        super(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace());
    }

    public Accept(String version)
    {
        this();
        setContent(version);
    }

    /**
     * Get the XmlName for this class.
     *
     * @return The prefix, localname and namespace for this element.
     */
    public static XmlName elementName()
    {
        return XML_NAME;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls Sci. Nat. , Bot. , sér. 3 5: 119 (1846)

#### Original name
Lentinus tanghiniae var. tanghiniae

### Remarks
null


text:
@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize viewLogin, imgLoginFrame, imgLoginNothing, lblUserName, lblUserPwd, txtUserName, txtUserPwd, btnLogin;

#pragma mark - view lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

-(void)addcolumn:(NSString *)column_name table_name:(NSString *)table_name colunmType:(NSString *)colunmType columnLength:(NSString *)columnLength
{
    NSString *dbPath = [BaseInfo getDataBasePath];
    FMDatabase *db = [[FMDatabase alloc] initWithPath:dbPath];
    [db open];
    BOOL rtn;
    NSString *strSql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ TYPE %@(%@) ", table_name,column_name,colunmType,columnLength];
    rtn = [db executeUpdate:strSql];
    NSLog(@"%@",strSql);
    if (rtn) {
        NSLog(@"update db success,sql = %@",strSql);
    }
    [db close];
}

-(void)createTable:(NSString *)tablename tableDictionary:(NSDictionary *)tableDictionary
{
    NSLog(@"%@",tableDictionary);
    NSString *dbPath = [BaseInfo getDataBasePath];
    FMDatabase *db = [[FMDatabase alloc] initWithPath:dbPath];
    [db open];
    BOOL rtn;

    NSArray *allkeys=[tableDictionary allKeys];

    NSMutableString *mutableString=[[NSMutableString alloc]init];

    NSString *primarykey=[[NSString alloc]init];

    for (int i = 0; i<allkeys.count; i++) {

        NSArray *columns=[tableDictionary objectForKey:allkeys[i]];

        if ([[[tableDictionary objectForKey:allkeys[i]] objectAtIndex:2] isEqualToString:@"0"])
        {
            NSString *name_type_length=[NSString stringWithFormat:@"%@ %@,",allkeys[i],columns[0]];
            [mutableString appendString:name_type_length];
        }

        else if ([[[tableDictionary objectForKey:allkeys[i]] objectAtIndex:2] isEqualToString:@"1"]) {
            primarykey=[NSString stringWithFormat:@"%@ %@ PRIMARY KEY",allkeys[i],columns[0]];
        }
    }
    NSLog(@"%@",mutableString);

    NSString *commonString=mutableString;

    //验证是否有主键
    NSString *temp = @"PRIMARY KEY";
    NSRange foundObj=[primarykey rangeOfString:temp options:NSCaseInsensitiveSearch];
    if(foundObj.length > 0) {
        NSLog(@"Yes ! PRIMARY KEY found");
    } else {
        NSLog(@"Oops ! No PRIMARY KEY");
        commonString=[commonString substringWithRange:NSMakeRange(0, commonString.length-1)];
    }

    if (!primarykey) {
        primarykey=@"";
    }

    NSString *strSql = [NSString stringWithFormat:@"CREATE TABLE %@ (%@ %@)",tablename,commonString,primarykey];

    NSLog(@"%@",strSql);
    rtn = [db executeUpdate:strSql];
    if (rtn) {
        NSLog(@"create table : %@ success,sql = %@",tablename,strSql);
    }
    [db close];
}

-(void)updateDBstruct
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@",paths[0]);

    NSString *path = [[NSBundle mainBundle] pathForResource:@"update_db_struct" ofType:@"plist"];
    NSDictionary *root = [NSDictionary dictionaryWithContentsOfFile:path];
    NSArray *allTableArray=[root allKeys];

    NSString *dbPath = [BaseInfo getDataBasePath];
    FMDatabase *db = [[FMDatabase alloc] initWithPath:dbPath];
    [db open];

    NSMutableArray *local_columns = [[NSMutableArray alloc] init];

    for (NSString *table_name in allTableArray) {
        NSLog(@"table_name = %@",table_name);

        FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", table_name];
        int count;
        while ([rs next]) {
            count=[rs intForColumn:@"count"];
            NSLog(@"%ld",(long)count);
        }

        //如果表存在则检查表内有无新增字段
        if (count==1) {

            NSString *strSql = [NSString stringWithFormat:@"PRAGMA table_info(%@)", table_name];
            FMResultSet *result = [db executeQuery:strSql];

            NSArray *input_array = [[root objectForKey:table_name]allKeys];
            NSLog(@"columns = %@",input_array);

            while ([result next]) {

                NSString *columename = [result stringForColumn:@"name"];
                [local_columns addObject:columename];
            }
            NSLog(@"%@",local_columns);

            for (int i=0; i<input_array.count; i++) {
                if (![local_columns containsObject:input_array[i]]) {
                    NSLog(@"find modifed column ,table = %@ ,column = %@",table_name,input_array[i]);
                    [self addcolumn:input_array[i] table_name:table_name colunmType:[[[root objectForKey:table_name] objectForKey:input_array[i]] objectAtIndex:0] columnLength:[[[root objectForKey:table_name] objectForKey:input_array[i]] objectAtIndex:1]];
                }
            }

        }
        //表不存在则新建表
        else if(count==0)
        {
            NSLog(@"%@ not exist",table_name);
            [self createTable:table_name tableDictionary:[root objectForKey:table_name]];
        }

    }

    [db close];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@",paths[0]);

//    [self updateDBstruct];//just for test

    //隐藏导航条
    self.navigationController.navigationBarHidden = YES;

    //设置控件位置,主要设置高度以及y轴距离
    self.txtUserPwd.frame = CGRectMake(self.txtUserPwd.frame.origin.x, self.btnLogin.frame.origin.y - (self.txtUserPwd.frame.size.height + 25) - 30, self.txtUserPwd.frame.size.width, self.txtUserPwd.frame.size.height + 25);
    self.txtUserName.frame = CGRectMake(self.txtUserName.frame.origin.x, self.txtUserPwd.frame.origin.y - (self.txtUserName.frame.size.height + 20) - 30, self.txtUserName.frame.size.width, self.txtUserName.frame.size.height + 25);
    self.lblUserPwd.frame = CGRectMake(self.lblUserPwd.frame.origin.x, self.txtUserPwd.frame.origin.y + 5, self.lblUserPwd.frame.size.width, self.lblUserPwd.frame.size.height);
    self.lblUserName.frame = CGRectMake(self.lblUserName.frame.origin.x, self.txtUserName.frame.origin.y + 5, self.lblUserName.frame.size.width, self.lblUserName.frame.size.height);

    //初始化变量
    _loginViewModel = [[LoginViewModel alloc] init];
    _loginService = [[LoginService alloc] initWithViewModel:_loginViewModel];

    //监听实体对象,输出结果
    [_loginViewModel addObserver:self
                      forKeyPath:@"result"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:nil];

    //监听实体对象,下载总量大小
    [_loginViewModel addObserver:self
                      forKeyPath:@"prgSumSize"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:nil];

    //监听实体对象,已经下载总量大小
    [_loginViewModel addObserver:self
                      forKeyPath:@"prgDownloadSize"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:nil];

    //监听实体对象,计算进度条大小
    [_loginViewModel addObserver:self
                      forKeyPath:@"prgValue"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:nil];

    //更新数据库文件
    [BaseInfo updateSqliteDatabase];
}

- (void)viewWillAppear:(BOOL)animated
{
    //即将显示页面,设置最后一次登录用户名
    self.txtUserName.text = @"";
    self.txtUserPwd.text = @"";
    self.txtUserName.text = [ConfigInfo AppLastLoginUserName];

    //设置显示登录页面动画,隐藏页面控件
    imgLoginFrame.hidden = YES;
    lblUserName.hidden = YES;
    lblUserPwd.hidden = YES;
    txtUserName.hidden = YES;
    txtUserPwd.hidden = YES;
    btnLogin.hidden = YES;
    imgLoginNothing.hidden = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    static BOOL isFirstLoad = YES;
    if (isFirstLoad) {

    }
    isFirstLoad = NO;

    //设置动画,显示页面对象
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.5];
    [animation setType:@"fade"];
    [animation setSubtype:kCATransitionFromRight];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [viewLogin.layer addAnimation:animation forKey:nil];

    //显示页面控件
    imgLoginFrame.hidden = NO;
    lblUserName.hidden = NO;
    lblUserPwd.hidden = NO;
    txtUserName.hidden = NO;
    txtUserPwd.hidden = NO;
    btnLogin.hidden = NO;
    imgLoginNothing.hidden = YES;

    //self.txtUserPwd.text = @"7zx377";
}

- (void)dealloc
{
    [_loginViewModel removeObserver:self forKeyPath:@"result" context:nil];
    [_loginViewModel removeObserver:self forKeyPath:@"prgSumSize" context:nil];
    [_loginViewModel removeObserver:self forKeyPath:@"prgDownloadSize" context:nil];
    [_loginViewModel removeObserver:self forKeyPath:@"prgValue" context:nil];

    if (_hud) {
        [_hud removeFromSuperview];
        _hud = nil;
    }
    _loginService = nil;
    _loginViewModel = nil;

    [self setViewLogin:nil];
    [self setImgLoginFrame:nil];
    [self setImgLoginNothing:nil];
    [self setLblUserName:nil];
    [self setLblUserPwd:nil];
    [self setTxtUserName:nil];
    [self setTxtUserPwd:nil];
    [self setBtnLogin:nil];
}

- (void)viewDidUnload
{
    [self setViewLogin:nil];
    [self setImgLoginFrame:nil];
    [self setImgLoginNothing:nil];
    [self setLblUserName:nil];
    [self setLblUserPwd:nil];
    [self setTxtUserName:nil];
    [self setTxtUserPwd:nil];
    [self setBtnLogin:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)didReceiveMemoryWarning
{

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return interfaceOrientation == UIInterfaceOrientationLandscapeLeft
    || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

#pragma mark - MBProgressHUDDelegate

- (void)hudWasHidden:(MBProgressHUD *)hud
{
	[_hud removeFromSuperview];
	_hud = nil;
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 101) {
        if (buttonIndex == 0) {
            _hud = [[MBProgressHUD alloc] initWithView:self.view];
            _hud.delegate = self;
            _hud.labelText = @"正在登录";
            //_hud.dimBackground = YES;
            [self.view addSubview:_hud];
            [_hud show:YES];

            //请求登录
            [self performSelector:@selector(login) withObject:nil afterDelay:0.1];
        }
    }
    else if (alertView.tag == 102) {
        if (buttonIndex == 0) {
            [self performSelector:@selector(transformPage) withObject:nil afterDelay:0.1];
        }
    }
}

#pragma mark - user actions

- (void)login
{
    NSString *userName = self.txtUserName.text;
    NSString *userPwd = self.txtUserPwd.text;
    [_loginService requestLogin:userName userPwd:userPwd];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqual:@"result"]) {
        LoginResult loginResult = [[change objectForKey:@"new"] intValue];
        switch (loginResult) {
            case LoginSuccess:
                if ([ConfigInfo AppHasUserData]) {
                    if ([BaseInfo isExistenceNetwork]) {
                        _hud.mode = MBProgressHUDModeIndeterminate;
                        _hud.labelText = @"绑定用户改变或者用户权限改变";
                        _hud.detailsLabelText = @"正在重新更新数据";
                        [_loginService performSelector:@selector(requestUserData:) withObject:[UserInfo sharedUserInfo].userName afterDelay:0.1];
                        return;
                    }
                    else {
                        _hud.customView = [BaseInfo getMsgPrompt];
                        _hud.mode = MBProgressHUDModeCustomView;
                        _hud.labelText = @"绑定用户改变或者用户权限改变";
                        _hud.detailsLabelText = @"请连接网络重新更新数据";
                        [_hud hide:YES afterDelay:5.0];
                    }
                }
                else {
                    [ConfigInfo setConfigValue:[UserInfo sharedUserInfo].userName key:kAppLastLoginUserName];
                    if (_loginViewModel.updateDesc == nil || [_loginViewModel.updateDesc isEqualToString:@""]) {
                        _hud.customView = [BaseInfo getMsgSuccess];
                        _hud.mode = MBProgressHUDModeCustomView;
                        _hud.labelText = @"登录成功";
                        [_hud hide:YES afterDelay:0.5];
                        [self performSelector:@selector(transformPage) withObject:nil afterDelay:0.5];
                    }
                    else {
                        [_hud hide:YES];
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"变更明细"
                                                                            message:_loginViewModel.updateDesc
                                                                           delegate:self
                                                                  cancelButtonTitle:@"确定"
                                                                  otherButtonTitles:nil, nil];
                        alertView.tag = 102;
                        [alertView show];
                        _loginViewModel.updateDesc = @"";
                    }
                }
                break;

            case LoginInitRequest:
                _hud.mode = MBProgressHUDModeIndeterminate;
                _hud.labelText = @"正在请求初始化";
                break;
            case LoginDataDownload:
                _hud.mode = MBProgressHUDModeAnnularDeterminate;
                _hud.labelText = @"正在下载数据包";
                break;
            case LoginInitDownload:
                _hud.mode = MBProgressHUDModeAnnularDeterminate;
                _hud.labelText = @"正在下载数据包";
                break;
            case LoginInitExpandZip:
                _hud.mode = MBProgressHUDModeIndeterminate;
                _hud.labelText = @"正在解压数据包";
                _hud.detailsLabelText = @"";
                break;
            case LoginSystemInfo:
                _hud.mode = MBProgressHUDModeIndeterminate;
                _hud.labelText = @"正在请求系统配置信息";
                _hud.detailsLabelText = @"";
                break;

            case LoginDataModify:
                _hud.mode = MBProgressHUDModeIndeterminate;
                _hud.labelText = @"正在更新数据";
                _hud.detailsLabelText = @"";
                break;

            case LoginErrorInit:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"系统尚未初始化";
                _hud.detailsLabelText = @"请连接网络下载初始化包";
                [_hud hide:YES afterDelay:5.0];
                break;
            case LoginErrorDelete:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"系统已被加入黑名单";
                _hud.detailsLabelText = @"请联系相关人员解除并连接网络登录";
                [_hud hide:YES afterDelay:5.0];
                break;
            case LoginErrorLock:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"系统已被锁定";
                _hud.detailsLabelText = @"请联系相关人员解除并连接网络登录";
                [_hud hide:YES afterDelay:5.0];
                break;
            case LoginErrorNotUser:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"系统暂无该帐号登录纪录";
                [_hud hide:YES afterDelay:2.0];
                break;
            case LoginErrorFailure:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"用户密码已经过期";
                _hud.detailsLabelText = @"请连接网络重新登录";
                [_hud hide:YES afterDelay:2.0];
                break;
            case LoginErrorPassword:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"用户名或密码错误";
                _hud.detailsLabelText = [NSString stringWithFormat:@"剩余允许错误次数%d次", ([ConfigInfo ServerErrorNumber] - [self getLoginErrorNumber])];
                [_hud hide:YES afterDelay:5.0];
                break;
            case LoginErrorNotNet:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"系统网络异常";
                [_hud hide:YES afterDelay:2.0];
                break;
            case LoginErrorLoginKey:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"登录密钥错误";
                [_hud hide:YES afterDelay:2.0];
                break;
            case LoginErrorUserKey:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"当前网络状况暂不稳定";
                _hud.detailsLabelText = @"请稍后再试";
                [_hud hide:YES afterDelay:2.0];
                break;
            case LoginErrorExpandZip:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"数据解压失败";
                [_hud hide:YES afterDelay:2.0];
                break;
            case LoginErroriPadUser:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"请尝试使用绑定用户登录";
                _hud.detailsLabelText = @"系统不存在该用户或者已被其他用户绑定";
                [_hud hide:YES afterDelay:5.0];
                break;
            case LoginErrorDataModify:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"更新数据错误";
                [_hud hide:YES afterDelay:2.0];
                break;
            default:
                _hud.customView = [BaseInfo getMsgPrompt];
                _hud.mode = MBProgressHUDModeCustomView;
                _hud.labelText = @"登录异常";
                [_hud hide:YES afterDelay:2.0];
                break;
        }
    }
    else if ([keyPath isEqual:@"prgSumSize"]) {
        _hud.labelText = [NSString stringWithFormat:@"总计剩余 %.2fMB", [[change objectForKey:@"new"] floatValue]];
    }
    else if ([keyPath isEqual:@"prgDownloadSize"]) {
        _hud.detailsLabelText = [NSString stringWithFormat:@"已下载 %.2fMB", [[change objectForKey:@"new"] floatValue]];
    }
    else if ([keyPath isEqual:@"prgValue"]) {
        _hud.progress = [[change objectForKey:@"new"] floatValue];
    }
}

- (void)transformPage
{
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.5];
    [animation setType:@"fade"];
    [animation setSubtype:kCATransitionFromLeft];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

    if ([self.txtUserName.text isEqualToString:kHigerViseClientOffLine] &&
        [self.txtUserPwd.text isEqualToString:kHigerViseClientOffLine]) {
        IndexViewController *indexViewController = [[IndexViewController alloc] initWithNibName:nil bundle:nil];
        [self.navigationController pushViewController:indexViewController animated:NO];
        [self.navigationController.view.layer addAnimation:animation forKey:nil];
    }
    else {

        //IntentOrderMainViewController *intentOrderMainViewController = [[IntentOrderMainViewController alloc] initWithNibName:@"IntentOrderMainViewController" bundle:nil];
        //[self.navigationController pushViewController:intentOrderMainViewController animated:NO];

        //IndexViewController *indexViewController = [[IndexViewController alloc] initWithNibName:nil bundle:nil];
        //[self.navigationController pushViewController:indexViewController animated:NO];
        //[self.navigationController.view.layer addAnimation:animation forKey:nil];

        if (!_feedbackViewController) {
            _feedbackViewController = [[FeedbackViewController alloc] initWithNibName:nil bundle:nil];
        }

        [self.navigationController pushViewController:_feedbackViewController animated:NO];
        [self.navigationController.view.layer addAnimation:animation forKey:nil];
    }
}

- (IBAction)btnLogin_TouchUpInside:(id)sender
{
    [self.txtUserName resignFirstResponder];
    [self.txtUserPwd resignFirstResponder];

    if ([self.txtUserName.text isEqualToString:@""]) {
        _hud = [[MBProgressHUD alloc] initWithView:self.view];
        _hud.delegate = self;
        _hud.customView = [BaseInfo getMsgPrompt];
        _hud.mode = MBProgressHUDModeCustomView;
        _hud.labelText = @"请填写用户名";
        //_hud.dimBackground = YES;
        [self.view addSubview:_hud];
        [_hud show:YES];
        [_hud hide:YES afterDelay:1.0];
        return;
    }

    if ([self.txtUserPwd.text isEqualToString:@""]) {
        _hud = [[MBProgressHUD alloc] initWithView:self.view];
        _hud.delegate = self;
        _hud.customView = [BaseInfo getMsgPrompt];
        _hud.mode = MBProgressHUDModeCustomView;
        _hud.labelText = @"请填写密码";
        //_hud.dimBackground = YES;
        [self.view addSubview:_hud];
        [_hud show:YES];
        [_hud hide:YES afterDelay:1.0];
        return;
    }

    if ([self.txtUserName.text isEqualToString:kHigerViseClientOffLine] &&
        [self.txtUserPwd.text isEqualToString:kHigerViseClientOffLine]) {
        [UserInfo sharedUserInfo].userName = kHigerViseClientOffLine;
        [UserInfo sharedUserInfo].userPassword = kHigerViseClientOffLine;
        [UserInfo sharedUserInfo].useriPadKey = kHigerViseClientOffLine;
        [UserInfo sharedUserInfo].userRealName = @"数据管理员";
        [UserInfo sharedUserInfo].userLevel = @"1000";
        [UserInfo sharedUserInfo].userArea = @"ALL";

        NSString *dbResourcePath = [[NSBundle mainBundle] pathForResource:kHigerDatabaseOffLine ofType:@""];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsPath = [paths objectAtIndex:0];
        NSString *databasePath = [documentsPath stringByAppendingPathComponent:kHigerDatabaseOffLine];
        if (![[NSFileManager defaultManager] fileExistsAtPath:databasePath]) {
            //[[NSFileManager defaultManager] removeItemAtPath:databasePath error:nil];
            [[NSFileManager defaultManager] copyItemAtPath:dbResourcePath toPath:databasePath error:nil];
        }

        [self performSelector:@selector(transformPage) withObject:nil afterDelay:0.5];

        return;
    }

    if ([ConfigInfo AppStatus] == kAppStatusInit) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"建议WIFI环境\r\n系统需初始化登录?" delegate:self cancelButtonTitle:@"登录并下载" otherButtonTitles:@"取消登录", nil];
        alertView.tag = 101;
        [alertView show];
        return;
    }

    _hud = [[MBProgressHUD alloc] initWithView:self.view];
    _hud.delegate = self;
    _hud.labelText = @"正在登录";
    //_hud.dimBackground = YES;
    [self.view addSubview:_hud];
    [_hud show:YES];

    //请求登录
    [self performSelector:@selector(login) withObject:nil afterDelay:0.1];
}

- (int)getLoginErrorNumber
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *localDate = [dateFormatter stringFromDate:date];
    NSString *where = [NSString stringWithFormat:@"date(login_time, 'unixepoch', 'localtime') = '%@' AND login_result = 0 ORDER BY user_login_id DESC", localDate];
    NSArray *array = [client_user_login_dal getList:where];
    return array.count;
}

@end


text:
package org.uminho.gsd.benchmarks.TPCW_CassandraOM.database_executor;

import org.uminho.gsd.benchmarks.benchmark.BenchmarkExecutor;
import org.uminho.gsd.benchmarks.generic.helpers.NodeKeyGenerator;
import org.uminho.gsd.benchmarks.helpers.TPM_counter;
import org.uminho.gsd.benchmarks.interfaces.KeyGenerator;
import org.uminho.gsd.benchmarks.interfaces.executor.AbstractDatabaseExecutorFactory;
import org.uminho.gsd.benchmarks.interfaces.executor.DatabaseExecutorInterface;

/**
 * TPC-W execution factory  interface for Cassandra
 * It loads the configuration for Cassandra and returns execution clients.
 */
public class TPCWCassandraDatanucleusExecutorFactory extends AbstractDatabaseExecutorFactory {

    KeyGenerator keyGenerator;

    public TPCWCassandraDatanucleusExecutorFactory(BenchmarkExecutor executor, String conf_file) {
        super(executor, conf_file);
        init();
    }

    private void init() {

		initTPMCounting();

    }

    @Override
    public DatabaseExecutorInterface getDatabaseClient() {

        if (keyGenerator == null && nodeID != null) {
            keyGenerator = new NodeKeyGenerator(this.nodeID.getId());
        }

		TPM_counter tpm_counter = new TPM_counter();
		registerCounter(tpm_counter);

        return new TPCWCassandraDataNucleusExecutor(keyGenerator,tpm_counter);

    }
}


text:
def merge(dicta, dictb):
    dicta.update(dictb)
    return dicta

from functools import reduce
from collections import defaultdict
from collections import deque
from itertools import islice

import re

lowalpha=re.compile('[^a-z]')

def normalize(word):
    return re.sub(lowalpha,'',word.lower())

def add(x,y):
    return x+y

def triple_sum(a,b):
    return [a[0]+b[0],a[1]+b[1],a[2]+b[2]]

def double_sum(a,b):
    return [a[0]+b[0],a[1]+b[1]]

def merge_under(operand):
    def _reducer(a,b):
        for key in b:
            if key in a:
                a[key]=operand(a[key],b[key])
            else:
                a[key]=b[key]
        return a
    return _reducer

def groups_of(count, iterable):
    # in_groups_of(3,range(7)) gives:
    # [[0,1,2],[1,2,3],[2,3,4],[3,4,5],[4,5,6]]
    iterable=iter(iterable)# in case a sequence is given
    current=deque(islice(iterable,0,count))
    yield list(current)
    for element in iterable:
        current.popleft()
        current.append(element)
        yield list(current)

def groups_of_with_page(count, iterable):
    for group in groups_of(count, iterable):
        return group[0][0], map(lambda x: x[1], group)


text:
layout: post
microblog: true
audio:
photo: http://microblog.curtclifton.net/uploads/2017/108cadc544.jpg
date: 2017-10-10 14:02:03 -0700
guid: http://curt.micro.blog/2017/10/10/if-the-deranged.html
---
If the deranged coconut trees don't get you…

<img src="http://microblog.curtclifton.net/uploads/2017/108cadc544.jpg" width="599" height="600" />


text:
[![npm version](https://badge.fury.io/js/write-int.svg)](https://badge.fury.io/js/write-int)

Convert integer numbers to their written form.

Inspired by [js-written-number](https://github.com/yamadapc/js-written-number)

## Usage
### Install with npm
```
npm install write-int --save
```

And require it where needed:
```JavaScript
var writeInt = require('write-int');
```

### Reference as script
It also works to simply reference in a `script` tag:
```HTML
<script src="path/to/writeInt.min.js"></script>
```

### English
English is the default language. Numbers supported between -1e66 and 1e66 exclusive (1 followed by 66 zeros or 1 * 10^66).
```JavaScript
writeInt(123);// => 'one hundred and twenty-three'

writeInt(123, {lang: 'en'});// => 'one hundred and twenty-three'
```

### Spanish
Numbers supported between -1e24 and 1e24 (exclusive).
```JavaScript
writeInt(2030, {lang: 'es'});// => 'dos mil treinta'
```

### German
Numbers supported between -1e18 and 1e18 (exclusive).
```JavaScript
writeInt(2000, {lang: 'de'});// => 'zweitausend'
```

### Esperanto
Numbers supported from 0 up through 1e15 - 1.
```JavaScript
writeInt(1234, {lang: 'eo'});// => 'mil ducent tridek kvar'
```

### Lojban
Numbers supported between -1.8e308 and 1.8e308 (exclusive).
```JavaScript
writeInt(11, {lang: 'jb'});// => 'papa'
```

### Specification
`writeInt(number[, options])`

- @param {number|string} number
- @param {object} [options]
- @property {string} [options.lang='en']
- @property {boolean} [options.einhundert=false]
- - whether to include 'ein' for 100 in German
- - 100 is 'einhundert' if true, 'hundert' if false
- @property {boolean} [options.eintausend=false]
- - whether to include 'ein' for 1000 in German
- - 1000 is 'eintausend' if true, 'tausend' if false
- @returns {string|null}

Returns `number` written out if it is representable (within supported range of valid language), else returns `null`. If `number` is type string, it should be a base 10 number.

Example:
```JavaScript
writeInt(11);// => 'eleven'
writeInt("11");// => 'eleven'

writeInt(1e2);// => 'one hundred'
writeInt("1e2");// => 'one hundred'

writeInt(11, {lang: 'es'});// => 'once'

writeInt(100, {lang: 'de'});// => 'hundert'
writeInt(100, {lang: 'de', einhundert: true});// => 'einhundert'

writeInt();// => null
writeInt({});// => null
writeInt("a");// => null
writeInt('foo');// => null
```

---

`writeInt.supported(lang)`

- @param {string} lang
- @returns {boolean}

Returns whether `lang` is a supported language.

Example:
```Javascript
writeInt.supported('en');// => true

writeInt.supported('xy');// => false
```

---

`writeInt.representable(number, lang)`

- @param {number|string} number
- @param {string} lang
- @returns {boolean}

Returns whether `number` is representable (within the supported range) in `lang`. Returns false if `lang` is not supported. If `writeInt()` is called for an unrepresentable number, then `null` is returned.

Example:
```Javascript
writeInt.representable(12, 'en');// => true

writeInt.representable(12, 'xy');// => false

writeInt.representable('a', 'en');// => false
```

## Supported languages
- English `lang: 'en'`
- Spanish `lang: 'es'`
- German `lang: 'de'`
- Esperanto `lang: 'eo'`
- Lojban `lang: 'jb'`

## Contributing
1. Fork the repo
2. Make a new branch
3. Make the changes
4. Run `npm run build` to build to `dist/writeInt.js` and `dist/writeInt.min.js`
4. Run `npm run test` to check that all tests pass
5. Submit a pull request
6. Thanks!

### Adding a language
1. Create a copy of `src/languages/interface.js` and rename it to the [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) code of the language.
2. Implement the functions and properties for the language. Any helper functions and properties can be made as well.
3. Create a test file in `test` with the same file name.

Note: [Lojban](https://en.wikipedia.org/wiki/Lojban) does not have a ISO 639-1 code. "jb", which is unspecified in ISO 639-1, is used for Lojban. (The Lojban code in ISO 639-2 and ISO 639-3 is "jbo").


text:
#include "tensorflow/lite/micro/kernels/svdf.h"

#include <math.h>

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/op_macros.h"
#include "tensorflow/lite/micro/kernels/activation_utils.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"
#include "tensorflow/lite/micro/micro_utils.h"

namespace tflite {
namespace {

void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  return context->AllocatePersistentBuffer(context, sizeof(OpData));
}

TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  auto* params = reinterpret_cast<TfLiteSVDFParams*>(node->builtin_data);
  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData& data = *(static_cast<const OpData*>(node->user_data));

  const TfLiteEvalTensor* input =
      tflite::micro::GetEvalInput(context, node, kSvdfInputTensor);
  const TfLiteEvalTensor* weights_feature =
      tflite::micro::GetEvalInput(context, node, kSvdfWeightsFeatureTensor);
  const TfLiteEvalTensor* weights_time =
      tflite::micro::GetEvalInput(context, node, kSvdfWeightsTimeTensor);
  const TfLiteEvalTensor* bias =
      (NumInputs(node) == 5)
          ? tflite::micro::GetEvalInput(context, node, kSvdfBiasTensor)
          : nullptr;
  TfLiteEvalTensor* activation_state = tflite::micro::GetMutableEvalInput(
      context, node, kSvdfInputActivationStateTensor);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kSvdfOutputTensor);

  switch (weights_feature->type) {
    case kTfLiteFloat32: {
      EvalFloatSvdfReference(
          context, node, input, weights_feature, weights_time, bias, params,
          data.scratch_tensor_index, activation_state, output);
      return kTfLiteOk;
      break;
    }

    case kTfLiteInt8: {
      EvalIntegerSvdfReference(context, node, input, weights_feature,
                               weights_time, bias, params, activation_state,
                               output, data);
      return kTfLiteOk;
      break;
    }

    default:
      TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.",
                         TfLiteTypeGetName(weights_feature->type));
      return kTfLiteError;
  }
  return kTfLiteOk;
}

}  // namespace

TfLiteRegistration Register_SVDF() {
  return {/*init=*/Init,
          /*free=*/nullptr,
          /*prepare=*/PrepareSvdf,
          /*invoke=*/Eval,
          /*profiling_string=*/nullptr,
          /*builtin_code=*/0,
          /*custom_name=*/nullptr,
          /*version=*/0};
}

}  // namespace tflite