text:
<!DOCTYPE html>

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

    <title>Haifeng Jin's Blog</title>

    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <link href="/css/clean-blog.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.5.2/animate.min.css">

            Haifeng Jin's Blog

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                        Home

                        Technology

                        Competitive

                        Chinese

                              Contact

                                Linkedin

                                GitHub

                                Google Scholar

                                E-mail

            <form class="form-inline my-2 my-lg-0">
              <input class="form-control mr-sm-2" type="search" onkeydown="if(event.keyCode==13) googlesearch();" name="search-key-words" placeholder="Search" aria-label="Search">
              <button class="btn btn-outline-success my-2 my-sm-0" onclick="googlesearch()">Search</button>
            </form>

Technology

                        In the Middle of Difficulty Lies Opportunity.

					Title
					Date

				Cube Practice

			 Posted on 05 May 2019

				Working Hours Histogram

			 Posted on 20 Jan 2017

				Get Up Early for 21 Days

			 Posted on 06 May 2016

				Working Hours Heat Map

			 Posted on 28 Nov 2015

				My Daily Routines

			 Posted on 27 Nov 2015

				Jekyll on GitHub Pages

			 Posted on 29 Jun 2015

				Learn Jekyll Really Quick

			 Posted on 26 Jun 2015

«

»

<big>Introduction</big>

Here are some articles and tutorials about technology.


text:
package shapes;

import java.util.Iterator;
import visitor.Visitator;

/**
 * Intersection of two shapes
 *
 * @author Michal Szura
 */
public class Intersection implements Shape, Iterable<Shape> {

    public Shape a;
    public Shape b;

    public Intersection(Shape shape1, Shape shape2) {
        this.a = shape1;
        this.b = shape2;
    }

    @Override
    public boolean contains(float x, float y) {
        if (a.contains(x, y) && b.contains(x, y)) {
            return true;
        }
        return false;
    }

    @Override
    public void accept(Visitator v) {
        v.visit(this);
    }

    @Override
    public String print() {
        if (a instanceof Rectangle || a instanceof Ellipse) {
            return ">Intersection \n" + a.print().replace("|", "") + "\n" + b.print() + "+";
        }
        return ">Intersection \n" + a.print() + "\n" + b.print() + "+";
    }

    @Override
    public Iterator<Shape> iterator() {
        return new ShapeIterator(this);
    }

    @Override
    public String toDebugString() {
        return "Intersection";
    }
}

redpajama_set_name: RedPajamaGithub


text:
#import <Foundation/Foundation.h>
#import "StellaKitExport.h"
#import "SVView.h"

extern NSString *const UIWindowDidBecomeVisibleNotification;
extern NSString *const UIWindowDidBecomeHiddenNotification;
extern NSString *const UIWindowDidBecomeKeyNotification;
extern NSString *const UIWindowDidResignKeyNotification;

extern NSString *const UIKeyboardWillShowNotification;
extern NSString *const UIKeyboardDidShowNotification;
extern NSString *const UIKeyboardWillHideNotification;
extern NSString *const UIKeyboardDidHideNotification;

extern NSString *const UIKeyboardFrameBeginUserInfoKey;
extern NSString *const UIKeyboardFrameEndUserInfoKey;
extern NSString *const UIKeyboardAnimationDurationUserInfoKey;
extern NSString *const UIKeyboardAnimationCurveUserInfoKey;

// deprecated
extern NSString *const UIKeyboardCenterBeginUserInfoKey;
extern NSString *const UIKeyboardCenterEndUserInfoKey;
extern NSString *const UIKeyboardBoundsUserInfoKey;

/* Prototypes */
@interface UIWindow : UIView
{
}

@property(nonatomic, retain) UIScreen             * screen;
@property(nonatomic, retain) UIViewController     * rootViewController;

- (void) makeKeyAndVisible;

- (CGPoint) convertPoint: (CGPoint) point toWindow: (UIWindow *) window;
- (CGPoint) convertPoint: (CGPoint) point fromWindow: (UIWindow *) window;
- (CGRect) convertRect: (CGRect) point toWindow: (UIWindow *) window;
- (CGRect) convertRect: (CGRect) point fromWindow: (UIWindow *) window;

@end


text:
<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

{{ site.description }}

    Home

    {% comment %}
      The code below dynamically generates a sidebar nav of pages with
      `layout: page` in the front-matter. See readme for usage.
    {% endcomment %}

    {% assign pages_list = site.pages %}
    {% for node in pages_list %}
      {% if node.title != null %}
        {% if node.layout == "page" %}
          {{ node.title }}
        {% endif %}
      {% endif %}
    {% endfor %}

      © {{ site.time | date: '%Y' }} David Peterson. All rights reserved.

      Built using Jekyll, Poole and the Lanyon Theme by Mark Otto.

    Hosted on Github Pages.


text:
'use strict';

module.exports = function (t, a) {
	a(t(null), false, "Null");
	a(t("test"), false, "Primitive");
	a(t({}), false, "Any object");

	if (typeof document === 'undefined') return;

	a(t(document.createDocumentFragment()), true, "DocumentFragment");
	a(t(document.createElement('div')), true, "DocumentFragment");
	a(t(document.createTextNode('content')), false, "Text node");
	a(t(document.createComment('content')), false, "Comment node");
	a(t(document), true, "Document node");
	a(t(document.createAttribute('raz')), false, "Attribute");
};


text:
package avrohugger
package input
package parsers

import reflectivecompilation._
import reflectivecompilation.schemagen._

import org.apache.avro.Protocol
import org.apache.avro.Schema
import org.apache.avro.Schema.Parser
import org.apache.avro.SchemaParseException
import org.apache.avro.compiler.idl.Idl
import org.apache.avro.compiler.idl.ParseException
import scala.collection.JavaConverters._
import java.nio.charset.Charset

import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

// tries schema first, then protocol, then idl, then for case class defs
class StringInputParser {

  lazy val schemaParser = new Parser()

  def getSchemas(inputString: String): List[Schema] = {

    def trySchema(str: String) = {
      try {
        List(schemaParser.parse(inputString))}
      catch {
        case notSchema: SchemaParseException => tryProtocol(inputString)
        case unknown: Throwable => sys.error("Unexpected exception: " + unknown)
      }
    }

    def tryProtocol(protocolStr: String): List[Schema] = {
      try {
        Protocol.parse(protocolStr).getTypes().asScala.toList}
      catch {
        case notProtocol: SchemaParseException => tryIDL(inputString)
        case unknown: Throwable => sys.error("Unexpected exception: " + unknown)
      }
    }

    def tryIDL(idlString: String): List[Schema] = {
      try {
        val bytes = idlString.getBytes(Charset.forName("UTF-8"))
        val inStream = new java.io.ByteArrayInputStream(bytes)
        val idlParser = new Idl(inStream)
        val protocol = idlParser.CompilationUnit()
        val types = protocol.getTypes
        types.asScala.toList}
      catch {
        case notIDL: ParseException => tryCaseClass(inputString)
        case unknown: Throwable => sys.error("Unexpected exception: " + unknown)
        }
      }

    def tryCaseClass(codeStr: String): List[Schema] = {
      val compilationUnits = PackageSplitter.getCompilationUnits(codeStr)
      val trees = compilationUnits.map(compUnit => Toolbox.toolBox.parse(compUnit))
      val schemas = trees.flatMap(tree => TreeInputParser.parse(tree))
      TypecheckDependencyStore.knownClasses.clear
      schemas
    }

    // tries schema first, then protocol, then idl, then for case class defs
    val schemas: List[Schema] = trySchema(inputString)
    schemas
  }
}


text:
<oval_definitions xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:oval="http://oval.mitre.org/XMLSchema/oval-common-5" xmlns:ind="http://oval.mitre.org/XMLSchema/oval-definitions-5#independent" xmlns:unix="http://oval.mitre.org/XMLSchema/oval-definitions-5#unix" xmlns:linux="http://oval.mitre.org/XMLSchema/oval-definitions-5#linux" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://oval.mitre.org/XMLSchema/oval-common-5 oval-common-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5 oval-definitions-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5#independent independent-definitions-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5#unix unix-definitions-schema.xsd   http://oval.mitre.org/XMLSchema/oval-definitions-5#linux linux-definitions-schema.xsd">
  <generator>
    <oval:product_name>python</oval:product_name>
    <oval:product_version>2.6.6</oval:product_version>
    <oval:schema_version>5.10</oval:schema_version>
    <oval:timestamp>2011-09-21T13:44:00</oval:timestamp>
  </generator>
  <definitions><definition class="inventory" id="oval:ssg:def:100" version="1">
      <metadata>
        <title>Red Hat Enterprise Linux 6</title>
        <affected family="unix">
          <platform>Red Hat Enterprise Linux 6</platform>
        </affected>
        <reference ref_id="cpe:/o:redhat:enterprise_linux:6" source="CPE"/>
        <description>The operating system installed on the system is
      Red Hat Enterprise Linux 6</description>
      </metadata>
      <criteria>
        <criterion comment="Installed operating system is part of the unix family" test_ref="oval:ssg:tst:101"/>
        <criterion comment="Red Hat Enterprise Linux 6 Workstation is installed" test_ref="oval:ssg:tst:102"/>
        <criterion comment="Red Hat Enterprise Linux 6 Server is installed" test_ref="oval:ssg:tst:103"/>
      </criteria>
    </definition>
    </definitions><tests><ind:family_test check="all" check_existence="at_least_one_exists" comment="installed OS part of unix family" id="oval:ssg:tst:101" version="1">
      <ind:object object_ref="oval:ssg:obj:104"/>
      <ind:state state_ref="oval:ssg:ste:105"/>
    </ind:family_test>
    <linux:rpminfo_test check="all" check_existence="any_exist" comment="redhat-release-workstation is version 6" id="oval:ssg:tst:102" version="1">
      <linux:object object_ref="oval:ssg:obj:106"/>
      <linux:state state_ref="oval:ssg:ste:107"/>
    </linux:rpminfo_test>
    <linux:rpminfo_test check="all" check_existence="any_exist" comment="redhat-release-server is version 6" id="oval:ssg:tst:103" version="1">
      <linux:object object_ref="oval:ssg:obj:108"/>
      <linux:state state_ref="oval:ssg:ste:109"/>
    </linux:rpminfo_test>
    </tests><objects><ind:family_object id="oval:ssg:obj:104" version="1"/>
    <linux:rpminfo_object id="oval:ssg:obj:106" version="1">
      <linux:name>redhat-release-workstation</linux:name>
    </linux:rpminfo_object>
    <linux:rpminfo_object id="oval:ssg:obj:108" version="1">
      <linux:name>redhat-release-server</linux:name>
    </linux:rpminfo_object>
    </objects><states><ind:family_state id="oval:ssg:ste:105" version="1">
      <ind:family>unix</ind:family>
    </ind:family_state>
    <linux:rpminfo_state id="oval:ssg:ste:107" version="1">
      <linux:version operation="pattern match">^6Workstation$</linux:version>
    </linux:rpminfo_state>
    <linux:rpminfo_state id="oval:ssg:ste:109" version="1">
      <linux:version operation="pattern match">^6Server$</linux:version>
    </linux:rpminfo_state>
  </states></oval_definitions>


text:
local skynet = require "skynet"

local list = {}

local function timeout_check(ti)
	if not next(list) then
		return
	end
	skynet.sleep(ti)	-- sleep 10 sec
	for k,v in pairs(list) do
		skynet.error("timout",ti,k,v)
	end
end

skynet.start(function()
	skynet.error("ping all")
	local list_ret = skynet.call(".launcher", "lua", "LIST")
	for addr, desc in pairs(list_ret) do
		list[addr] = desc
		skynet.fork(function()
			skynet.call(addr,"debug","INFO")
			list[addr] = nil
		end)
	end
	skynet.sleep(0)
	timeout_check(100)
	timeout_check(400)
	timeout_check(500)
	skynet.exit()
end)


text:
<!-- Generated by the JRebel NetBeans plugin -->
<!-- More information http://zeroturnaround.com/software/jrebel/how-to-configure-rebel-xml/ -->
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com"
             xsi:schemaLocation="http://www.zeroturnaround.com http://www.zeroturnaround.com/alderaan/rebel-2_0.xsd">
	<classpath>
		<dir name="C:\Users\RainWhileLoop\Documents\NetBeansProjects\augmentedreality\target\classes"/>

	</classpath>

</application>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;

[RequireComponent(typeof(RaycastController))]
public class CursorManager : MonoBehaviour
{
    public GameObject CursorPrefab;
    public float DefaultDistance = 5.0f;
    public Color HitColor = Color.yellow;
    public Color BaseColor = Color.white;

    private Transform cameraTransform;

    private GameObject cursorGameObject;
    private GameObject hitObject;

    private bool mixedMode = false;
    private Vector3 overridePosition;
    private Vector3 overrideNormal;
    private GameObject overrideObject;

    private void Awake()
    {
        this.cameraTransform = Camera.main.transform;

        if (this.CursorPrefab)
        {
            this.cursorGameObject =
                Instantiate(this.CursorPrefab, this.cameraTransform.position + this.cameraTransform.forward * DefaultDistance,
                    Quaternion.identity) as GameObject;
        }

        if (this.cursorGameObject == null)
        {
            Debug.LogError("Not able to create Cursor");

            return;
        }

        var raycastController = GetComponent<RaycastController>();
        if (raycastController == null)
        {
            Debug.LogError("Not able to find RaycastController in scene.");

            return;
        }
    }

    private void LateUpdate()
    {
        if (this.cameraTransform == null)
        {
            return;
        }

        var raycast = RaycastController.RaycastHit;
        var go = raycast.collider != null ? raycast.collider.gameObject : null;

        // position & normal
        var position = (go != null) ? raycast.point : this.cameraTransform.position + (this.cameraTransform.forward * DefaultDistance);
        var normal = (go != null) ? -raycast.normal : this.cameraTransform.forward;

        var screenPoint = Camera.main.WorldToScreenPoint(position);
        screenPoint.z = Camera.main.nearClipPlane;
        var worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);

        Debug.DrawRay(worldPoint, (position - worldPoint), go != null ? Color.yellow : Color.white);

        // set active hit object
        if (this.mixedMode)
        {
            position = this.overridePosition;
            normal = this.overrideNormal;
            go = this.overrideObject;
        }

        screenPoint = Camera.main.WorldToScreenPoint(position);
        screenPoint.z = Camera.main.nearClipPlane;
        worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);

        Debug.DrawRay(worldPoint, (position - worldPoint), Color.red);

        // update the cusor object properties
        SetActiveObject(go);

        this.cursorGameObject.transform.position = position;
        this.cursorGameObject.transform.forward = normal;
    }

    private void SetActiveObject(GameObject go)
    {
        bool hitChanged = false;

        if (go != null)
        {
            if (this.hitObject != go)
            {
                this.hitObject = go;
                hitChanged = true;
            }
        }
        else
        {
            if (this.hitObject != null)
            {
                this.hitObject = null;
                hitChanged = true;
            }
        }

        if (hitChanged)
        {
            var rend = this.cursorGameObject.GetComponentInChildren<Renderer>();
            if (this.hitObject)
            {
                if (rend != null)
                {
                    rend.material.color = this.HitColor;
                }
            }
            else
            {
                if (rend != null)
                {
                    rend.material.color = this.BaseColor;
                }
            }
        }
    }

    public void SetCursorData(Vector3 position, Vector3 normal, GameObject go)
    {
        mixedMode = true;

        this.overridePosition = position;
        this.overrideNormal = normal;
        this.overrideObject = go;
    }
}


text:
package fishfinger

import (
	"context"
	"fmt"
	"strings"

	"github.com/docker/libcompose/docker"
	"github.com/docker/libcompose/docker/ctx"
	"github.com/docker/libcompose/project"
	"github.com/docker/libcompose/project/options"
)

// -----------------------------------------------------------------------------

// Compose is a structure using `libcompose` to manage a Docker environment
// from a compose-file.
type Compose struct {
	*project.Project
}

// NewCompose returns a new `Compose` or an `error` if something occurs during
// setup. It uses `composeFile` as the path to the compose-file to up.
//
// NOTE: .env files are not currently supported.
func NewCompose(composeFile string) (*Compose, error) {
	p, err := docker.NewProject(
		&ctx.Context{
			Context: project.Context{ComposeFiles: []string{composeFile}},
		}, nil)
	if err != nil {
		return nil, err
	}
	return &Compose{Project: p.(*project.Project)}, nil
}

// -----------------------------------------------------------------------------

// Start launches all `services` specified. If `services` is empty, all services
// described in the compose-file are launched. If something occurs during any
// `services` start, it returns an `error`.
func (c *Compose) Start(services ...string) error {
	return c.Up(context.Background(), options.Up{}, services...)
}

// StartBackoff launches all `services` specified and returns only when
// `backoffFunc` completes. If `services` is empty, all services described in
// the compose-file are launched and `backoffFunc` is used for each of them.
//
// NOTE: This project offers default implementations of `backoffFunc` but user
// should provide an implementation according to the Docker images used.
//
// `backoffFunc` takes as input this `*Compose`, service name and port/protocol:
//
// `backoffFunc(c, "redis", "6379/tcp")`
//
// `services` has format "service:port/protocol", e.g., "redis:6379/tcp".
func (c *Compose) StartBackoff(backoffFunc func(*Compose, string, string) error, services ...string) error {
	for _, service := range services {
		parts := strings.Split(service, ":")
		if len(parts) != 2 {
			return fmt.Errorf("Invalid 'service' parameter %s.  "+
				"Should have format 'service:port/protocol'.", service)
		}
		if err := c.Up(context.Background(), options.Up{}, parts[0]); err != nil {
			return err
		}
		if err := backoffFunc(c, parts[0], parts[1]); err != nil {
			return err
		}
	}
	return nil
}

// Stop removes all `services` specified. If `services` is empty, all services
// described in the compose-file are removed. If something occurs during any
// `services` stop, it returns an `error`.
func (c *Compose) Stop(services ...string) error {
	if err := c.Down(context.Background(), options.Down{}, services...); err != nil {
		return err
	}
	return c.Delete(context.Background(), options.Delete{}, services...)
}

// Status returns `true` if `service` is in running state, `false` otherwise.
// If `service` does not exist, it returns an `error`.
func (c *Compose) Status(service string) (bool, error) {
	serviceObj, err := c.CreateService(service)
	if err != nil {
		return false, err
	}
	ctnrs, err := serviceObj.Containers(context.Background())
	if err != nil || len(ctnrs) == 0 {
		return false, err
	}
	return ctnrs[0].IsRunning(context.Background()), nil
}

// Port returns the host address where `service` is bound to `port`. If
// `service` does not exist or `port` is not bound, it returns an `error`.
//
// NOTE: `port` MUST be of the following form `<portNb>/<protocol>` such as
// `80/tcp`.
func (c *Compose) Port(service, port string) (string, error) {
	s, err := c.CreateService(service)
	if err != nil {
		return "", err
	}
	ctnr, err := s.Containers(context.Background())
	if err != nil {
		return "", err
	} else if len(ctnr) == 0 {
		return "", fmt.Errorf("no container available")
	}
	addr, err := ctnr[0].Port(context.Background(), port)
	if err != nil {
		return "", err
	} else if addr == "" {
		return "", fmt.Errorf("port not bound")
	}
	return addr, nil
}

// Env returns the value of the environment variable `varName` set in container
// `service` by the compose-file. If `service` or `varName` does not exist, It
// returns an `error`.
func (c *Compose) Env(service, varName string) (string, error) {
	s, err := c.CreateService(service)
	if err != nil {
		return "", err
	}
	v, ok := s.Config().Environment.ToMap()[varName]
	if !ok {
		return "", fmt.Errorf("environment var not found")
	}
	return v, nil
}

// Info returns a `project.InfoSet` about a specified `service`.
func (c *Compose) Info(service string) (project.InfoSet, error) {
	serviceObj, err := c.CreateService(service)
	if err != nil {
		return nil, err
	}
	info, err := serviceObj.Info(context.Background())
	if err != nil {
		return nil, err
	}
	return info, nil
}


text:
package io.qameta.allure;

import io.qameta.allure.util.ResultsUtils;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Use this annotation to add some links to results. Usage:
 * <pre>
 * @Link("https://qameta.io")
 * public void myTest() {
 *     ...
 * }
 * </pre>
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@LinkAnnotation
@Repeatable(Links.class)
public @interface Link {

    /**
     * Alias for {@link #name()}.
     *
     * @return the link name.
     */
    String value() default "";

    /**
     * Name for link, by default url.
     *
     * @return the link name.
     */
    String name() default "";

    /**
     * Url for link. By default will search for system property `allure.link.{type}.pattern`, and use it
     * to generate url.
     *
     * @return the link url.
     */
    String url() default "";

    /**
     * This type is used for create an icon for link. Also there is few reserved types such as issue and tms.
     *
     * @return the link type.
     */
    String type() default ResultsUtils.CUSTOM_LINK_TYPE;
}


text:
class CreateSyncs < ActiveRecord::Migration
  def up
    create_table :syncs do |t|
      t.string    :organization
      t.string    :url
      t.datetime  :last_sync
      t.integer   :calendar_id
      t.timestamps
    end
  end

  def down
    drop_table :syncs
  end
end


text:
const publicationsData = [
  {
    publicationLink: `https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7941666/`,
    publicationDate: `03.03.21`,
    publicationTitle: `Peng J et al.: Estimation of secondary household attack rates for emergent SARS-CoV-2 variants detected by genomic surveillance at a community-based testing site in San Francisco.`,
    publicationSource: `doi:10.1101/2021.03.01.21252705`,
    publicationCompany: `medRxiv`,
  },
  {
    publicationLink: `https://www.nature.com/articles/s41598-021-83642-x`,
    publicationDate: `02.16.21`,
    publicationTitle: `Kim, K.W. et al.: Respiratory viral co-infections among SARS-CoV-2 cases confirmed by virome capture sequencing.`,
    publicationSource: `Sci Rep 11, 3934 (2021).`,
    publicationCompany: `Nature`,
  },
  {
    publicationLink: `https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7217139/`,
    publicationDate: `03.05.20`,
    publicationTitle: `Manning JE et al.: Rapid metagenomic characterization of a case of imported COVID-19 in Cambodia.`,
    publicationSource: `doi:10.1101/2020.03.02.968818`,
    publicationCompany: `bioRxiv`,
  },
];

const newsData = [
  {
    publicationLink: `https://www.nytimes.com/2021/06/03/magazine/metagenomic-sequencing.html`,
    publicationDate: `06.03.21`,
    publicationTitle: `The Disease Detective`,
    publicationCompany: `New York Times`,
  },
  {
    publicationLink: `https://www.nytimes.com/2021/02/16/health/coronavirus-pandemic-cambodia-manning.html?referringSource=articleShare`,
    publicationDate: `02.16.21`,
    publicationTitle: `Piecing Together the Next Pandemic`,
    publicationCompany: `New York Times`,
  },
  {
    publicationLink: `https://southeastasiaglobe.com/covid-19-disease-research/`,
    publicationDate: `04.02.20`,
    publicationTitle: `On the Tail of a Virus`,
    publicationCompany: `Southeast Asia Globe`,
  },
  {
    publicationLink: `https://www.wired.com/story/a-disease-tracker-backed-by-gates-and-zuckerberg-tackles-covid-19/`,
    publicationDate: `03.10.20`,
    publicationTitle: `A Disease Tracker Backed by Gates and Zuckerberg Tackles Covid-19`,
    publicationCompany: `Wired`,
  },
  {
    publicationLink: `https://www.theatlantic.com/science/archive/2018/10/dashboard-disease-detectives/573034/`,
    publicationDate: `10.16.18`,
    publicationTitle: `A Simpler Way to Get to the Bottom of Mysterious Illnesses in Poor Countries`,
    publicationCompany: `Atlantic`,
  },
];

export { publicationsData, newsData };


text:
<resources>
    <string name="app_name">Aula_01</string>
    <string name="hello_round">Hello Round World!</string>
    <string name="hello_square">Hello Square World!</string>
</resources>


text:
We will create release `3.0.2` in this example.

## Start the release

```
git flow release start 3.0.2
```

## Publish a feature

```
git flow release publish 3.0.2
```

## Bump up the version number

Edit the verison in `package.json` to match the release version

```
  "version": "3.0.2",
```

## Finish the release

```
git flow release finish '3.0.2'
```

## Push changes to master

```
git checkout master
git push
```

## Re-Publish NPM (optional)

```
npm publish
```


text:
import {assert} from 'chai';
import domEvents from 'dom-events';
import td from 'testdouble';

import {MDCComponent} from '../../../packages/mdc-base';

class FakeComponent extends MDCComponent {
  get root() {
    return this.root_;
  }

  get foundation() {
    return this.foundation_;
  }

  getDefaultFoundation() {
    const defaultFoundation = td.object({
      isDefaultFoundation: true,
      init: () => {},
    });
    defaultFoundation.rootElementAtTimeOfCall = this.root_;
    return defaultFoundation;
  }

  initialize(...args) {
    this.initializeArgs = args;
    this.initializeComesBeforeFoundation = !this.foundation_;
  }

  initialSyncWithDOM() {
    this.synced = true;
  }
}

suite('MDCComponent');

test('provides a static attachTo() method that returns a basic instance with the specified root', () => {
  const root = document.createElement('div');
  const b = MDCComponent.attachTo(root);
  assert.isOk(b instanceof MDCComponent);
});

test('takes a root node constructor param and assigns it to the "root_" property', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  assert.equal(f.root, root);
});

test('takes an optional foundation constructor param and assigns it to the "foundation_" property', () => {
  const root = document.createElement('div');
  const foundation = {init: () => {}};
  const f = new FakeComponent(root, foundation);
  assert.equal(f.foundation, foundation);
});

test('assigns the result of "getDefaultFoundation()" to "foundation_" by default', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  assert.isOk(f.foundation.isDefaultFoundation);
});

test("calls the foundation's init() method within the constructor", () => {
  const root = document.createElement('div');
  const foundation = td.object({init: () => {}});
  // Testing side effects of constructor
  // eslint-disable-next-line no-new
  new FakeComponent(root, foundation);
  td.verify(foundation.init());
});

test('throws an error if getDefaultFoundation() is not overridden', () => {
  const root = document.createElement('div');
  assert.throws(() => new MDCComponent(root));
});

test('calls initialSyncWithDOM() when initialized', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  assert.isOk(f.synced);
});

test('provides a default initialSyncWithDOM() no-op if none provided by subclass', () => {
  assert.doesNotThrow(MDCComponent.prototype.initialSyncWithDOM.bind({}));
});

test("provides a default destroy() method which calls the foundation's destroy() method", () => {
  const root = document.createElement('div');
  const foundation = td.object({init: () => {}, destroy: () => {}});
  const f = new FakeComponent(root, foundation);
  f.destroy();
  td.verify(foundation.destroy());
});

test('#initialize is called within constructor and passed any additional positional component args', () => {
  const f = new FakeComponent(document.createElement('div'), /* foundation */ undefined, 'foo', 42);
  assert.deepEqual(f.initializeArgs, ['foo', 42]);
});

test('#initialize is called before getDefaultFoundation()', () => {
  const f = new FakeComponent(document.createElement('div'));
  assert.isOk(f.initializeComesBeforeFoundation);
});

test('#listen adds an event listener to the root element', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  const handler = td.func('eventHandler');
  f.listen('FakeComponent:customEvent', handler);
  domEvents.emit(root, 'FakeComponent:customEvent');
  td.verify(handler(td.matchers.anything()));
});

test('#unlisten removes an event listener from the root element', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  const handler = td.func('eventHandler');
  root.addEventListener('FakeComponent:customEvent', handler);
  f.unlisten('FakeComponent:customEvent', handler);
  domEvents.emit(root, 'FakeComponent:customEvent');
  td.verify(handler(td.matchers.anything()), {times: 0});
});

test('#emit dispatches a custom event with the supplied data', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  const handler = td.func('eventHandler');
  let evt = null;
  td.when(handler(td.matchers.isA(Object))).thenDo((evt_) => {
    evt = evt_;
  });
  const data = {evtData: true};
  const type = 'customeventtype';

  root.addEventListener(type, handler);
  f.emit(type, data);
  assert.isOk(evt !== null);
  assert.equal(evt.type, type);
  assert.deepEqual(evt.detail, data);
});

test('#emit dispatches a custom event with the supplied data where custom events aren\'t available', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  const handler = td.func('eventHandler');
  let evt = null;
  td.when(handler(td.matchers.isA(Object))).thenDo((evt_) => {
    evt = evt_;
  });
  const data = {evtData: true};
  const type = 'customeventtype';

  root.addEventListener(type, handler);

  const {CustomEvent} = window;
  window.CustomEvent = undefined;
  try {
    f.emit(type, data);
  } finally {
    window.CustomEvent = CustomEvent;
  }

  assert.isOk(evt !== null);
  assert.equal(evt.type, type);
  assert.deepEqual(evt.detail, data);
});

test('(regression) ensures that this.root_ is available for use within getDefaultFoundation()', () => {
  const root = document.createElement('div');
  const f = new FakeComponent(root);
  assert.equal(f.foundation.rootElementAtTimeOfCall, root);
});


text:
package fpinscala.datastructures

sealed trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]

object Tree {

}


text:
class ListNode:

    def __init__(self, x):
        self.val = x
        self.next = None

    def printList(self):
        head = self
        while head:
            print head,
            head = head.next
        print ''

    def __str__(self):
        return str(self.val)

class Solution:
    # @param head, a ListNode
    # @return nothing

    def reorderList(self, head):
        if head is None or head.next is None:
            return head
        slow = fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        prev = slow.next
        slow.next = None

        # reverse the second part of the list
        cur = prev.next
        prev.next = None
        while cur:
            next = cur.next
            cur.next = prev
            prev = cur
            cur = next

        # merge the two sublist
        root = head
        while prev:
            tmp = prev.next
            prev.next = root.next
            root.next = prev
            root = prev.next
            prev = tmp
        return head

def main():
    import random
    root = ListNode(random.randint(1, 1000))
    head = root
    for x in xrange(9):
        head.next = ListNode(random.randint(1, 1000))
        head = head.next
    root.printList()
    s = Solution()
    root = s.reorderList(root)
    root.printList()

if __name__ == '__main__':
    main()


text:
package org.apache.guacamole.net.auth;

import java.util.Collection;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.form.Form;

/**
 * The context of an active user. The functions of this class enforce all
 * permissions and act only within the rights of the associated user.
 *
 * @author Michael Jumper
 */
public interface UserContext {

    /**
     * Returns the User whose access rights control the operations of this
     * UserContext.
     *
     * @return The User whose access rights control the operations of this
     *         UserContext.
     */
    User self();

    /**
     * Returns the AuthenticationProvider which created this UserContext, which
     * may not be the same AuthenticationProvider that authenticated the user
     * associated with this UserContext.
     *
     * @return
     *     The AuthenticationProvider that created this UserContext.
     */
    AuthenticationProvider getAuthenticationProvider();

    /**
     * Retrieves a Directory which can be used to view and manipulate other
     * users, but only as allowed by the permissions given to the user of this
     * UserContext.
     *
     * @return A Directory whose operations are bound by the restrictions
     *         of this UserContext.
     *
     * @throws GuacamoleException If an error occurs while creating the
     *                            Directory.
     */
    Directory<User> getUserDirectory() throws GuacamoleException;

    /**
     * Retrieves a Directory which can be used to view and manipulate
     * connections and their configurations, but only as allowed by the
     * permissions given to the user.
     *
     * @return A Directory whose operations are bound by the permissions of
     *         the user.
     *
     * @throws GuacamoleException If an error occurs while creating the
     *                            Directory.
     */
    Directory<Connection> getConnectionDirectory()
            throws GuacamoleException;

    /**
     * Retrieves a Directory which can be used to view and manipulate
     * connection groups and their members, but only as allowed by the
     * permissions given to the user.
     *
     * @return A Directory whose operations are bound by the permissions of
     *         the user.
     *
     * @throws GuacamoleException If an error occurs while creating the
     *                            Directory.
     */
    Directory<ConnectionGroup> getConnectionGroupDirectory()
            throws GuacamoleException;

    /**
     * Retrieves a Directory which can be used to view and manipulate
     * active connections, but only as allowed by the permissions given to the
     * user.
     *
     * @return
     *     A Directory whose operations are bound by the permissions of the
     *     user.
     *
     * @throws GuacamoleException
     *     If an error occurs while creating the Directory.
     */
    Directory<ActiveConnection> getActiveConnectionDirectory()
            throws GuacamoleException;

    /**
     * Retrieves a Directory which can be used to view and manipulate
     * sharing profiles and their configurations, but only as allowed by the
     * permissions given to the user.
     *
     * @return
     *     A Directory whose operations are bound by the permissions of the
     *     user.
     *
     * @throws GuacamoleException
     *     If an error occurs while creating the Directory.
     */
    Directory<SharingProfile> getSharingProfileDirectory()
            throws GuacamoleException;

    /**
     * Retrieves all connection records visible to current user. The resulting
     * set of connection records can be further filtered and ordered using the
     * methods defined on ConnectionRecordSet.
     *
     * @return
     *     A set of all connection records visible to the current user.
     *
     * @throws GuacamoleException
     *     If an error occurs while retrieving the connection records.
     */
    ConnectionRecordSet getConnectionHistory() throws GuacamoleException;

    /**
     * Retrieves a connection group which can be used to view and manipulate
     * connections, but only as allowed by the permissions given to the user of
     * this UserContext.
     *
     * @return A connection group whose operations are bound by the restrictions
     *         of this UserContext.
     *
     * @throws GuacamoleException If an error occurs while creating the
     *                            Directory.
     */
    ConnectionGroup getRootConnectionGroup() throws GuacamoleException;

    /**
     * Retrieves a collection of all attributes applicable to users. This
     * collection will contain only those attributes which the current user has
     * general permission to view or modify. If there are no such attributes,
     * this collection will be empty.
     *
     * @return
     *     A collection of all attributes applicable to users.
     */
    Collection<Form> getUserAttributes();

    /**
     * Retrieves a collection of all attributes applicable to connections. This
     * collection will contain only those attributes which the current user has
     * general permission to view or modify. If there are no such attributes,
     * this collection will be empty.
     *
     * @return
     *     A collection of all attributes applicable to connections.
     */
    Collection<Form> getConnectionAttributes();

    /**
     * Retrieves a collection of all attributes applicable to connection
     * groups. This collection will contain only those attributes which the
     * current user has general permission to view or modify. If there are no
     * such attributes, this collection will be empty.
     *
     * @return
     *     A collection of all attributes applicable to connection groups.
     */
    Collection<Form> getConnectionGroupAttributes();

    /**
     * Retrieves a collection of all attributes applicable to sharing profiles.
     * This collection will contain only those attributes which the current user
     * has general permission to view or modify. If there are no such
     * attributes, this collection will be empty.
     *
     * @return
     *     A collection of all attributes applicable to sharing profile.
     */
    Collection<Form> getSharingProfileAttributes();

}


text:
using Orchard.UI.Resources;

namespace Orchard.Core.Common {
    public class ResourceManifest : IResourceManifestProvider {
        public void BuildManifests(ResourceManifestBuilder builder) {
            var manifest = builder.Add();
            manifest.DefineStyle("DateTimeEditor").SetUrl("datetime-editor.css");
        }
    }
}


text:
from django.contrib import admin
from custom.m4change.models import McctStatus

class McctStatusAdmin(admin.ModelAdmin):
    model = McctStatus
    list_display = ('form_id', 'status', 'domain', 'reason', 'received_on', 'registration_date', 'immunized',
                    'is_booking', 'is_stillbirth', 'modified_on', 'user')
    search_fields = ('form_id',)

admin.site.register(McctStatus, McctStatusAdmin)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Soc. bot. Centre-Ouest, Nouv. sér. , num. spec. 7: 829 (1985)

#### Original name
Usnea cornuta Körb.

### Remarks
null


text:
FOUNDATION_EXPORT double SweetToastsVersionNumber;
FOUNDATION_EXPORT const unsigned char SweetToastsVersionString[];


text:
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

gulp.task('lint', function() {
    return gulp.src(['src/**/*.es6'])
        .pipe(jshint({
            esnext: true
        }))
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jshint.reporter('fail')); // stops the flow if lint task fails
});


text:
package io.transwarp.dfsclient;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;

public class CreateFile {
    public static void main(String[] args) throws IOException {
        // 通过Java API创建文件
        String rootPath = "hdfs://nameservice1";
        Path p = new Path(rootPath + "/tmp/file.txt");
        Configuration conf = new Configuration();
        conf.addResource("core-site.xml");
        conf.addResource("hdfs-site.xml");
        conf.addResource("yarn-site.xml");
        // 没开kerberos,注释下面两行
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromKeytab("hdfs@TDH","E:\\星环\\hdfs.keytab");
        FileSystem fs = p.getFileSystem(conf);
        fs.create(p);
        fs.close();
    }
}


text:
//
//  Controller.m
//  ModalResponderTest
//
//  Created by Paul Kim on 3/6/08.
//  Copyright 2008-2009 Noodlesoft, LLC. All rights reserved.
//

#import "Controller.h"

@implementation Controller

- (IBAction)doModal:sender
{
	NSInteger		returnCode;

	[field setStringValue:@""];

	returnCode = [NSApp runModalForWindow:alert];

	if (returnCode == NSOKButton)
	{
		[field setStringValue:@"OK!"];
	}
	else
	{
		[field setStringValue:@"Cancel"];
	}
}

- (IBAction)doSheet:sender
{
	[field setStringValue:@""];

	[NSApp beginSheet:alert modalForWindow:window modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
	//PENDING
/*
	NSLog(@"ALERT: %@", alert);
	NSLog(@"PARENT: %@", [alert parentWindow]);
	NSLog(@"SHEET: %@", [[alert parentWindow] attachedSheet]);
	NSLog(@"WINDOW: %@", window);
	NSLog(@"CHILD: %@", [window childWindows]);
	NSLog(@"ALERT CHILD: %@", [alert childWindows]);
	NSLog(@"ATTACHED: %@", [window attachedSheet]);
*/
}

- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
	if (returnCode == NSOKButton)
	{
		[field setStringValue:@"OK!"];
	}
	else
	{
		[field setStringValue:@"Cancel"];
	}
}

@end


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

namespace DataBase.Store
{
    class InDetailsStore
    {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <stroke
                android:width="@dimen/auto_dimen2_2"
                android:color="@color/auto_color_ffffff_80" />
            <solid android:color="@color/auto_color_f3f7fb_95" />
            <corners
                android:topLeftRadius="@dimen/auto_dimen2_50"
                android:topRightRadius="@dimen/auto_dimen2_6"
                android:bottomLeftRadius="@dimen/auto_dimen2_6"
                android:bottomRightRadius="@dimen/auto_dimen2_6" />
        </shape>
    </item>
</layer-list>


text:
namespace Apps\Components\Form;

use Cygnite\FormBuilder\Form;
use Cygnite\Foundation\Application;
use Cygnite\Common\UrlManager\Url;

/**
* Sample Form using Cygnite Form Builder
* This file generated by Cygnite CLI Generator.
* You may alter the code to fit your needs
*/

class %controllerName%Form extends Form
{
    //set model object
    private $model;

    public $errors;

    private $segment;

    //set validator object
    public $validation;

    public function __construct($object = null, $segment = null)
    {
        // your model object
        $this->model = $object;
        $this->segment = $segment;
    }

    /**
     *  Build form and return object
     * @return %controllerName%Form
     */
    public function buildForm()
    {
        $id = (isset($this->model->id)) ? $this->model->id : '';

        // Fllowing code is to display validation errors below the input box
        if (is_object($this->validation)) {
            $this->validator = $this->validation;// Errors will displayed below to inputs
            // Set your custom errors
            //$this->validator->setCustomError('column_name_error', 'Custom Error');
        }

        {%formElements%}

        return $this;
    }

    /**
     * Render form
     * @return type
     */
    public function render()
    {
        return $this->getForm();
    }
}


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

<title>edu.cmu.cs.lane.pipeline.datareader.filters Class Hierarchy</title>
<meta name="date" content="2013-10-01">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package edu.cmu.cs.lane.pipeline.datareader.filters

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

edu.cmu.cs.lane.pipeline.datareader.filters.AbstractDataFilter (implements edu.cmu.cs.lane.pipeline.datareader.DataReaderPhaseFileInteractor<T>)

edu.cmu.cs.lane.pipeline.datareader.filters.DefaultDataFilter

edu.cmu.cs.lane.pipeline.datareader.filters.LookUpDataFilter

edu.cmu.cs.lane.pipeline.datareader.filters.MissingDataFilter

edu.cmu.cs.lane.pipeline.datareader.filters.VariabilityDataFilter

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
class AddIndexToStudents < ActiveRecord::Migration
  def self.up
    add_index :students, :id_district
    add_index :students, :id_state
  end

  def self.down
    remove_index :students, :column => :id_state
    remove_index :students, :column => :id_district
  end
end


text:
@implementation DEMOAppDelegate

@end


text:
<?php
App::uses('AppController', 'Controller');
/**
 * Issues Controller
 *
 * @property Issue $Issue
 * @property PaginatorComponent $Paginator
 */
class IssuesController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator');

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Issue->recursive = 0;
		$this->set('issues', $this->Paginator->paginate());
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Issue->exists($id)) {
			throw new NotFoundException(__('Invalid issue'));
		}
		$options = array('conditions' => array('Issue.' . $this->Issue->primaryKey => $id));
		$this->set('issue', $this->Issue->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add($task_id) {
		if ($this->request->is('post')) {
			$n = $this->Issue->find('count',
					array('conditions' => array('Issue.task_id' => $task_id)));
			$n = $n+1;
			$this->Issue->create();
			$this->request->data['Issue']['name'] = $task_name.' Issue #'.$n;
			$this->request->data['Issue']['task_id'] = $task_id;
			if ($this->Issue->save($this->request->data)) {
				$this->Session->setFlash(__('The issue has been saved.'));
				return $this->redirect(array('controller' => 'tasks', 'action' => 'my_tasks'));
			} else {
				$this->Session->setFlash(__('The issue could not be saved. Please, try again.'));
			}
		}
		$task_name = $this->Issue->Task->find('first', array('conditions' => array('Task.id' => $task_id),
				'fields' => array('Task.name'), 'contain' => array()));
		$issueTypes = $this->Issue->IssueType->find('list');
		$this->set(compact('issueTypes'));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Issue->exists($id)) {
			throw new NotFoundException(__('Invalid issue'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->Issue->save($this->request->data)) {
				$this->Session->setFlash(__('The issue has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The issue could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Issue.' . $this->Issue->primaryKey => $id));
			$this->request->data = $this->Issue->find('first', $options);
		}
		$tasks = $this->Issue->Task->find('list');
		$issueTypes = $this->Issue->IssueType->find('list');
		$this->set(compact('tasks', 'issueTypes'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Issue->id = $id;
		if (!$this->Issue->exists()) {
			throw new NotFoundException(__('Invalid issue'));
		}
		$this->request->allowMethod('post', 'delete');
		if ($this->Issue->delete()) {
			$this->Session->setFlash(__('The issue has been deleted.'));
		} else {
			$this->Session->setFlash(__('The issue could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}
}


text:
import React from 'react';
import connect from 'react-redux/lib/components/connect';
import { bindActionCreators } from 'redux';
import appActions from './Actions';
import Alert from 'react-s-alert';
import { Navbar, Button } from 'react-bootstrap';
import AppPropTypes from './PropTypes';
import type IApp from './IApp';
import Menu from 'react-burger-menu/lib/menus/stack';
import DocumentTitle from 'react-document-title';
import ToggleDisplay from 'react-toggle-display';
import { Form, ValidatedInput } from '../../components/ValidatedInput';

type IProps = {
  app: IApp,
  loadAppAsync: Function,
  showAuth: Function,
  logOut: Function,
  authenticateAsAdmin: Function,
  redirectToHome: Function,
  redirectToProducts: Function,
  redirectToContactUs: Function,
  children: any
}

export class App extends React.Component {
  static propTypes = {
    app: React.PropTypes.shape(AppPropTypes),
    loadAppAsync: React.PropTypes.func.isRequired,
    redirectToHome: React.PropTypes.func.isRequired,
    redirectToProducts: React.PropTypes.func.isRequired,
    redirectToContactUs: React.PropTypes.func.isRequired,
    showAuth: React.PropTypes.func.isRequired,
    logOut: React.PropTypes.func.isRequired,
    authenticateAsAdmin: React.PropTypes.func.isRequired,
    children: React.PropTypes.element.isRequired
  };

  constructor (props: IProps) {
    super(props);

    this.state = {
      expanded: false
    };

    this.hideAuth = this.hideAuth.bind(this);
    this.logIn = this.logIn.bind(this);
    this.logOut = this.logOut.bind(this);
    this.generateRedirect = this.generateRedirect.bind(this);
    this.onMenuStateChange = this.onMenuStateChange.bind(this);
    this.onValidAuth = this.onValidAuth.bind(this);
    this.renderHeader = this.renderHeader.bind(this);
  }

  onValidAuth (values) {
    this.props.authenticateAsAdmin(values.password)
      .then(() => {
        this.hideAuth();
      })
      .catch(() => {
        Alert.error('Authentication Failed');
      });
  }

  onMenuStateChange (state) {
    this.setState({
      expanded: state.isOpen
    });
  }

  generateRedirect (fn: Function) {
    return () => {
      this.setState({
        expanded: false
      }, () => { fn(); });
    };
  }

  hideAuth () {
    this.props.showAuth(false);
  }

  logIn () {
    this.setState({
      expanded: false
    }, () => { this.props.showAuth(true); });
  }

  logOut () {
    this.setState({
      expanded: false
    }, () => { this.props.logOut(false); });
  }

  componentWillMount () {
  }

  componentWillUnmount () {
  };

  componentDidMount () {
    this.props.loadAppAsync();
  };

  componentWillReceiveProps (nextProps) {
  }

  shouldComponentUpdate (nextProps, nextState) {
    return nextProps.app.isReady;
  }

  componentWillUpdate (nextProps, nextState) {
  }

  componentDidUpdate (prevProps, prevState) {
  }

  renderHeader (docTitle : string) {
    let logOutButton = (this.props.app.isAdmin === true)
      ? (
LogOut
)
      : (
);
    let logInButton = (this.props.app.isAdmin === false)
      ? (.)
      : `${(this.props.app.isAdmin) ? '(Admin)' : ''}`;
    let title = docTitle;
    let brand = (
{title} {logInButton}
);

    if (this.props.app.showHeader) {
      var bmTop = 50 + ((this.props.app.isAdmin) ? this.props.app.bmOffset : 0);
      var bmStyles = {
        bmOverlay: {
          top: `${bmTop}px`
        },
        bmMenuWrap: {
          top: `${bmTop}px`
        }
      };

      return (

          <Menu right isOpen={this.state.expanded} onStateChange={this.onMenuStateChange} styles={bmStyles}>

Home

Products

Contact Us

            {logOutButton}
          </Menu>
          <Navbar fixedTop>
            <Navbar.Header>
              <Navbar.Brand>
                {brand}
              </Navbar.Brand>
              <ToggleDisplay show={this.props.app.showAuth}>
                <Form onValidSubmit={this.onValidAuth}>
                  <ValidatedInput
                    name="password"
                    type="password"
                    label="Password"
                    validate="required"
                    errorHelp={{
                      required: 'Please specify a password'
                    }}
                  />
                  <Button type="submit" bsStyle="primary">Submit</Button>
                  <Button onClick={this.hideAuth}>Cancel</Button>
                </Form>
              </ToggleDisplay>
            </Navbar.Header>
          </Navbar>

      );
    } else {
      return null;
    }
  }

  render () {
    let docTitle = 'Phillip J Buttrose Pty Ltd';

    return (this.props.app.isReady)
    ? (
      <DocumentTitle title={docTitle}>

          {this.renderHeader(docTitle)}

              {this.props.children}

          <Alert stack={{limit: 5}} timeout={5000} position="bottom" spacing={50} offset={50} effect="slide" html />

      </DocumentTitle>
    )
    : null;
  }
}

const mapStateToProps = (state) => ({
  app: state.app
});

const mapDispatchToProps = (dispatch: Function) => {
  return bindActionCreators({
    loadAppAsync: appActions.loadAppAsync,
    redirectToHome: appActions.redirectToHome,
    redirectToProducts: appActions.redirectToProducts,
    redirectToContactUs: appActions.redirectToContactUs,
    showAuth: appActions.showAuth,
    logOut: appActions.logOut,
    authenticateAsAdmin: appActions.authenticateAsAdmin
  }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(App);


text:
http://www.lintcode.com/en/problem/sort-colors-ii/

Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.

*Notice*

You are not suppose to use the library's sort function for this problem.

**Example**

Given colors=```[3, 2, 2, 1, 4]```, ```k=4```, your code should sort colors in-place to ```[1, 2, 2, 3, 4]```.

## Thoughts

- A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory.
  - Two-pass algorithm: first pass, count the number of each color
  - Second pass, place the color according to their counts

- Another method is using the similar method as in Sort Color for three colors.

## My Solution

```python
    def sortColors2(self, colors, k):
        # write your code here
        count = 0
        start = 0
        end = len(colors) - 1
        remain = list(colors)
        while count < k:
            if not remain:
                break
            minColor = min(remain)
            maxColor = max(remain)
            pColor1, pColor2 = self.sortColors(colors, minColor, maxColor, start, end)
            start = pColor1
            end = pColor2
            count += 2
            remain = colors[start:end+1] #start和end都应该包含在下一次里面
        return colors

    def sortColors(self, colors, color1, color2, start, end):
        # left和right表示的是两个颜色'下一个'的位置'
        left = start
        right = end
        index = start
        while index <= right:
            if colors[index] == color1:
                colors = self.swap(colors, left, index)
                left += 1
                index += 1
            elif colors[index] == color2:
                colors = self.swap(colors, right, index)
                right -= 1
            else:
                index += 1

        return left, right

    def swap(self, nums, i, j):
        tmp = nums[j]
        nums[j] = nums[i]
        nums[i] = tmp
        return nums
```

## Reference

- https://lefttree.gitbooks.io/leetcode-categories/content/quickSelect/sortColors2.html
- http://www.cnblogs.com/yuzhangcmu/p/4177326.html


text:
export * from './ui.module';
export * from './panel';
export * from './forms';


text:
package org.openkilda.messaging.info.stats;

import org.openkilda.messaging.info.InfoData;
import org.openkilda.model.SwitchId;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Value;

import java.util.List;

@Value
@Builder
@EqualsAndHashCode(callSuper = false)
@JsonNaming(value = SnakeCaseStrategy.class)
public class SwitchTableStatsData extends InfoData {
    SwitchId switchId;
    List<TableStatsEntry> tableStatsEntries;
}


text:
package de.domisum.exziff.world.block;

public enum Axis implements BlockAttributeType
{

	X,
	Y,
	Z,
	NONE

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>SslSocketConnector xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1   // ========================================================================
2   // Copyright 2000-2005 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // Licensed under the Apache License, Version 2.0 (the "License");
5   // you may not use this file except in compliance with the License.
6   // You may obtain a copy of the License at
7   // http://www.apache.org/licenses/LICENSE-2.0
8   // Unless required by applicable law or agreed to in writing, software
9   // distributed under the License is distributed on an "AS IS" BASIS,
10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  // See the License for the specific language governing permissions and
12  // limitations under the License.
13  // ========================================================================
14
15  package org.mortbay.jetty.security;
16
17  import java.io.ByteArrayInputStream;
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.net.InetAddress;
22  import java.net.ServerSocket;
23  import java.net.Socket;
24  import java.net.SocketAddress;
25  import java.security.KeyStore;
26  import java.security.SecureRandom;
27  import java.security.Security;
28  import java.security.cert.X509Certificate;
29  import java.util.ArrayList;
30  import java.util.Arrays;
31  import java.util.Iterator;
32  import java.util.List;
33
34  import javax.net.ssl.HandshakeCompletedEvent;
35  import javax.net.ssl.HandshakeCompletedListener;
36  import javax.net.ssl.KeyManager;
37  import javax.net.ssl.KeyManagerFactory;
38  import javax.net.ssl.SSLContext;
39  import javax.net.ssl.SSLException;
40  import javax.net.ssl.SSLPeerUnverifiedException;
41  import javax.net.ssl.SSLServerSocket;
42  import javax.net.ssl.SSLServerSocketFactory;
43  import javax.net.ssl.SSLSession;
44  import javax.net.ssl.SSLSocket;
45  import javax.net.ssl.TrustManager;
46  import javax.net.ssl.TrustManagerFactory;
47
48  import org.mortbay.io.EndPoint;
49  import org.mortbay.io.bio.SocketEndPoint;
50  import org.mortbay.jetty.HttpSchemes;
51  import org.mortbay.jetty.Request;
52  import org.mortbay.jetty.bio.SocketConnector;
53  import org.mortbay.log.Log;
54  import org.mortbay.resource.Resource;
55
56  /* ------------------------------------------------------------ */
57  /**
58   * JSSE Socket Listener.
59   *
60   * This specialization of HttpListener is an abstract listener that can be used as the basis for a
61   * specific JSSE listener.
62   *
63   * This is heavily based on the work from Court Demas, which in turn is based on the work from Forge
64   * Research.
65   *
66   * @author Greg Wilkins (gregw@mortbay.com)
67   * @author Court Demas (court@kiwiconsulting.com)
68   * @author Forge Research Pty Ltd ACN 003 491 576
69   * @author Jan Hlavat�
70   */
71  public class SslSocketConnector extends SocketConnector
72  {
73      /**
74       * The name of the SSLSession attribute that will contain any cached information.
75       */
76      static final String CACHED_INFO_ATTR = CachedInfo.class.getName();
77
78      /** Default value for the keystore location path. */
79      public static final String DEFAULT_KEYSTORE = System.getProperty("user.home") + File.separator
80              + ".keystore";
81
82      /** String name of key password property. */
83      public static final String KEYPASSWORD_PROPERTY = "jetty.ssl.keypassword";
84
85      /** String name of keystore password property. */
86      public static final String PASSWORD_PROPERTY = "jetty.ssl.password";
87
88      /**
89       * Return the chain of X509 certificates used to negotiate the SSL Session.
90       * <p>
91       * Note: in order to do this we must convert a javax.security.cert.X509Certificate[], as used by
92       * JSSE to a java.security.cert.X509Certificate[],as required by the Servlet specs.
93       *
94       * @param sslSession the javax.net.ssl.SSLSession to use as the source of the cert chain.
95       * @return the chain of java.security.cert.X509Certificates used to negotiate the SSL
96       *         connection. <br>
97       *         Will be null if the chain is missing or empty.
98       */
99      private static X509Certificate[] getCertChain(SSLSession sslSession)
100     {
101         try
102         {
103             javax.security.cert.X509Certificate javaxCerts[] = sslSession.getPeerCertificateChain();
104             if (javaxCerts == null || javaxCerts.length == 0)
105                 return null;
106
107             int length = javaxCerts.length;
108             X509Certificate[] javaCerts = new X509Certificate[length];
109
110             java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
111             for (int i = 0; i < length; i++)
112             {
113                 byte bytes[] = javaxCerts[i].getEncoded();
114                 ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
115                 javaCerts[i] = (X509Certificate) cf.generateCertificate(stream);
116             }
117
118             return javaCerts;
119         }
120         catch (SSLPeerUnverifiedException pue)
121         {
122             return null;
123         }
124         catch (Exception e)
125         {
126             Log.warn(Log.EXCEPTION, e);
127             return null;
128         }
129     }
130
131
132     /** Default value for the cipher Suites. */
133     private String _excludeCipherSuites[] = null;
134
135     /** Default value for the keystore location path. */
136     private String _keystore=DEFAULT_KEYSTORE ;
137     private String _keystoreType = "JKS"; // type of the key store
138
139     /** Set to true if we require client certificate authentication. */
140     private boolean _needClientAuth = false;
141     private transient Password _password;
142     private transient Password _keyPassword;
143     private transient Password _trustPassword;
144     private String _protocol= "TLS";
145     private String _provider;
146     private String _secureRandomAlgorithm; // cert algorithm
147     private String _sslKeyManagerFactoryAlgorithm = (Security.getProperty("ssl.KeyManagerFactory.algorithm")==null?"SunX509":Security.getProperty("ssl.KeyManagerFactory.algorithm")); // cert algorithm
148     private String _sslTrustManagerFactoryAlgorithm = (Security.getProperty("ssl.TrustManagerFactory.algorithm")==null?"SunX509":Security.getProperty("ssl.TrustManagerFactory.algorithm")); // cert algorithm
149
150     private String _truststore;
151     private String _truststoreType = "JKS"; // type of the key store
152
153     /** Set to true if we would like client certificate authentication. */
154     private boolean _wantClientAuth = false;
155     private int _handshakeTimeout = 0; //0 means use maxIdleTime
156
157     private boolean _allowRenegotiate =false;
158
159     /* ------------------------------------------------------------ */
160     /**
161      * Constructor.
162      */
163     public SslSocketConnector()
164     {
165         super();
166     }
167
168
169     /* ------------------------------------------------------------ */
170     /**
171      * @return True if SSL re-negotiation is allowed (default false)
172      */
173     public boolean isAllowRenegotiate()
174     {
175         return _allowRenegotiate;
176     }
177
178     /* ------------------------------------------------------------ */
179     /**
180      * Set if SSL re-negotiation is allowed. CVE-2009-3555 discovered
181      * a vulnerability in SSL/TLS with re-negotiation.  If your JVM
182      * does not have CVE-2009-3555 fixed, then re-negotiation should
183      * not be allowed.
184      * @param allowRenegotiate true if re-negotiation is allowed (default false)
185      */
186     public void setAllowRenegotiate(boolean allowRenegotiate)
187     {
188         _allowRenegotiate = allowRenegotiate;
189     }
190
191     /* ------------------------------------------------------------ */
192     public void accept(int acceptorID)
193         throws IOException, InterruptedException
194     {
195         try
196         {
197             Socket socket = _serverSocket.accept();
198             configure(socket);
199
200             Connection connection=new SslConnection(socket);
201             connection.dispatch();
202         }
203         catch(SSLException e)
204         {
205             Log.warn(e);
206             try
207             {
208                 stop();
209             }
210             catch(Exception e2)
211             {
212                 Log.warn(e2);
213                 throw new IllegalStateException(e2.getMessage());
214             }
215         }
216     }
217
218     /* ------------------------------------------------------------ */
219     protected void configure(Socket socket)
220         throws IOException
221     {
222         super.configure(socket);
223     }
224
225     /* ------------------------------------------------------------ */
226     protected SSLServerSocketFactory createFactory()
227         throws Exception
228     {
229         if (_truststore==null)
230         {
231             _truststore=_keystore;
232             _truststoreType=_keystoreType;
233         }
234
235         KeyManager[] keyManagers = null;
236         InputStream keystoreInputStream = null;
237         if (_keystore != null)
238         	keystoreInputStream = Resource.newResource(_keystore).getInputStream();
239         KeyStore keyStore = KeyStore.getInstance(_keystoreType);
240         keyStore.load(keystoreInputStream, _password==null?null:_password.toString().toCharArray());
241
242         KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_sslKeyManagerFactoryAlgorithm);
243         keyManagerFactory.init(keyStore,_keyPassword==null?null:_keyPassword.toString().toCharArray());
244         keyManagers = keyManagerFactory.getKeyManagers();
245
246         TrustManager[] trustManagers = null;
247         InputStream truststoreInputStream = null;
248         if (_truststore != null)
249         	truststoreInputStream = Resource.newResource(_truststore).getInputStream();
250         KeyStore trustStore = KeyStore.getInstance(_truststoreType);
251         trustStore.load(truststoreInputStream,_trustPassword==null?null:_trustPassword.toString().toCharArray());
252
253         TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(_sslTrustManagerFactoryAlgorithm);
254         trustManagerFactory.init(trustStore);
255         trustManagers = trustManagerFactory.getTrustManagers();
256
257
258         SecureRandom secureRandom = _secureRandomAlgorithm==null?null:SecureRandom.getInstance(_secureRandomAlgorithm);
259
260         SSLContext context = _provider==null?SSLContext.getInstance(_protocol):SSLContext.getInstance(_protocol, _provider);
261
262         context.init(keyManagers, trustManagers, secureRandom);
263
264         return context.getServerSocketFactory();
265     }
266
267     /* ------------------------------------------------------------ */
268     /**
269      * Allow the Listener a chance to customise the request. before the server does its stuff. <br>
270      * This allows the required attributes to be set for SSL requests. <br>
271      * The requirements of the Servlet specs are:
272      * <ul>
273      * <li> an attribute named "javax.servlet.request.cipher_suite" of type String.</li>
274      * <li> an attribute named "javax.servlet.request.key_size" of type Integer.</li>
275      * <li> an attribute named "javax.servlet.request.X509Certificate" of type
276      * java.security.cert.X509Certificate[]. This is an array of objects of type X509Certificate,
277      * the order of this array is defined as being in ascending order of trust. The first
278      * certificate in the chain is the one set by the client, the next is the one used to
279      * authenticate the first, and so on. </li>
280      * </ul>
281      *
282      * @param endpoint The Socket the request arrived on.
283      *        This should be a {@link SocketEndPoint} wrapping a {@link SSLSocket}.
284      * @param request HttpRequest to be customised.
285      */
286     public void customize(EndPoint endpoint, Request request)
287         throws IOException
288     {
289         super.customize(endpoint, request);
290         request.setScheme(HttpSchemes.HTTPS);
291
292         SocketEndPoint socket_end_point = (SocketEndPoint)endpoint;
293         SSLSocket sslSocket = (SSLSocket)socket_end_point.getTransport();
294
295         try
296         {
297             SSLSession sslSession = sslSocket.getSession();
298             String cipherSuite = sslSession.getCipherSuite();
299             Integer keySize;
300             X509Certificate[] certs;
301
302             CachedInfo cachedInfo = (CachedInfo) sslSession.getValue(CACHED_INFO_ATTR);
303             if (cachedInfo != null)
304             {
305                 keySize = cachedInfo.getKeySize();
306                 certs = cachedInfo.getCerts();
307             }
308             else
309             {
310                 keySize = new Integer(ServletSSL.deduceKeyLength(cipherSuite));
311                 certs = getCertChain(sslSession);
312                 cachedInfo = new CachedInfo(keySize, certs);
313                 sslSession.putValue(CACHED_INFO_ATTR, cachedInfo);
314             }
315
316             if (certs != null)
317                 request.setAttribute("javax.servlet.request.X509Certificate", certs);
318             else if (_needClientAuth) // Sanity check
319                 throw new IllegalStateException("no client auth");
320
321             request.setAttribute("javax.servlet.request.cipher_suite", cipherSuite);
322             request.setAttribute("javax.servlet.request.key_size", keySize);
323         }
324         catch (Exception e)
325         {
326             Log.warn(Log.EXCEPTION, e);
327         }
328     }
329
330     /* ------------------------------------------------------------ */
331     public String[] getExcludeCipherSuites() {
332         return _excludeCipherSuites;
333     }
334
335     /* ------------------------------------------------------------ */
336     public String getKeystore()
337     {
338         return _keystore;
339     }
340
341     /* ------------------------------------------------------------ */
342     public String getKeystoreType()
343     {
344         return (_keystoreType);
345     }
346
347     /* ------------------------------------------------------------ */
348     public boolean getNeedClientAuth()
349     {
350         return _needClientAuth;
351     }
352
353     /* ------------------------------------------------------------ */
354     public String getProtocol()
355     {
356         return _protocol;
357     }
358
359     /* ------------------------------------------------------------ */
360     public String getProvider() {
361 	return _provider;
362     }
363
364     /* ------------------------------------------------------------ */
365     public String getSecureRandomAlgorithm()
366     {
367         return (this._secureRandomAlgorithm);
368     }
369
370     /* ------------------------------------------------------------ */
371     public String getSslKeyManagerFactoryAlgorithm()
372     {
373         return (this._sslKeyManagerFactoryAlgorithm);
374     }
375
376     /* ------------------------------------------------------------ */
377     public String getSslTrustManagerFactoryAlgorithm()
378     {
379         return (this._sslTrustManagerFactoryAlgorithm);
380     }
381
382     /* ------------------------------------------------------------ */
383     public String getTruststore()
384     {
385         return _truststore;
386     }
387
388     /* ------------------------------------------------------------ */
389     public String getTruststoreType()
390     {
391         return _truststoreType;
392     }
393
394     /* ------------------------------------------------------------ */
395     public boolean getWantClientAuth()
396     {
397         return _wantClientAuth;
398     }
399
400     /* ------------------------------------------------------------ */
401     /**
402      * By default, we're confidential, given we speak SSL. But, if we've been told about an
403      * confidential port, and said port is not our port, then we're not. This allows separation of
404      * listeners providing INTEGRAL versus CONFIDENTIAL constraints, such as one SSL listener
405      * configured to require client certs providing CONFIDENTIAL, whereas another SSL listener not
406      * requiring client certs providing mere INTEGRAL constraints.
407      */
408     public boolean isConfidential(Request request)
409     {
410         final int confidentialPort = getConfidentialPort();
411         return confidentialPort == 0 || confidentialPort == request.getServerPort();
412     }
413
414     /* ------------------------------------------------------------ */
415     /**
416      * By default, we're integral, given we speak SSL. But, if we've been told about an integral
417      * port, and said port is not our port, then we're not. This allows separation of listeners
418      * providing INTEGRAL versus CONFIDENTIAL constraints, such as one SSL listener configured to
419      * require client certs providing CONFIDENTIAL, whereas another SSL listener not requiring
420      * client certs providing mere INTEGRAL constraints.
421      */
422     public boolean isIntegral(Request request)
423     {
424         final int integralPort = getIntegralPort();
425         return integralPort == 0 || integralPort == request.getServerPort();
426     }
427
428     /* ------------------------------------------------------------ */
429     /**
430      * @param addr The {@link SocketAddress address} that this server should listen on
431      * @param backlog See {@link ServerSocket#bind(java.net.SocketAddress, int)}
432      * @return A new {@link ServerSocket socket object} bound to the supplied address with all other
433      * settings as per the current configuration of this connector.
434      * @see #setWantClientAuth
435      * @see #setNeedClientAuth
436      * @see #setCipherSuites
437      * @exception IOException
438      */
439
440     /* ------------------------------------------------------------ */
441     protected ServerSocket newServerSocket(String host, int port,int backlog) throws IOException
442     {
443         SSLServerSocketFactory factory = null;
444         SSLServerSocket socket = null;
445
446         try
447         {
448             factory = createFactory();
449
450             socket = (SSLServerSocket) (host==null?
451                             factory.createServerSocket(port,backlog):
452                             factory.createServerSocket(port,backlog,InetAddress.getByName(host)));
453
454             if (_wantClientAuth)
455                 socket.setWantClientAuth(_wantClientAuth);
456             if (_needClientAuth)
457                 socket.setNeedClientAuth(_needClientAuth);
458
459             if (_excludeCipherSuites != null && _excludeCipherSuites.length >0)
460             {
461                 List excludedCSList = Arrays.asList(_excludeCipherSuites);
462                 String[] enabledCipherSuites = socket.getEnabledCipherSuites();
463             	List enabledCSList = new ArrayList(Arrays.asList(enabledCipherSuites));
464             	Iterator exIter = excludedCSList.iterator();
465
466                 while (exIter.hasNext())
467             	{
468             	    String cipherName = (String)exIter.next();
469                     if (enabledCSList.contains(cipherName))
470                     {
471                         enabledCSList.remove(cipherName);
472                     }
473             	}
474                 enabledCipherSuites = (String[])enabledCSList.toArray(new String[enabledCSList.size()]);
475
476                 socket.setEnabledCipherSuites(enabledCipherSuites);
477             }
478
479         }
480         catch (IOException e)
481         {
482             throw e;
483         }
484         catch (Exception e)
485         {
486             Log.warn(e.toString());
487             Log.debug(e);
488             throw new IOException("!JsseListener: " + e);
489         }
490         return socket;
491     }
492
493     /* ------------------------------------------------------------ */
494     /**
495      * @author Tony Jiang
496      */
497     public void setExcludeCipherSuites(String[] cipherSuites) {
498         this._excludeCipherSuites = cipherSuites;
499     }
500
501     /* ------------------------------------------------------------ */
502     public void setKeyPassword(String password)
503     {
504         _keyPassword = Password.getPassword(KEYPASSWORD_PROPERTY,password,null);
505     }
506
507     /* ------------------------------------------------------------ */
508     /**
509      * @param keystore The resource path to the keystore, or null for built in keystores.
510      */
511     public void setKeystore(String keystore)
512     {
513         _keystore = keystore;
514     }
515
516     /* ------------------------------------------------------------ */
517     public void setKeystoreType(String keystoreType)
518     {
519         _keystoreType = keystoreType;
520     }
521
522     /* ------------------------------------------------------------ */
523     /**
524      * Set the value of the needClientAuth property
525      *
526      * @param needClientAuth true iff we require client certificate authentication.
527      */
528     public void setNeedClientAuth(boolean needClientAuth)
529     {
530         _needClientAuth = needClientAuth;
531     }
532
533     /* ------------------------------------------------------------ */
534     public void setPassword(String password)
535     {
536         _password = Password.getPassword(PASSWORD_PROPERTY,password,null);
537     }
538
539     /* ------------------------------------------------------------ */
540     public void setTrustPassword(String password)
541     {
542         _trustPassword = Password.getPassword(PASSWORD_PROPERTY,password,null);
543     }
544
545     /* ------------------------------------------------------------ */
546     public void setProtocol(String protocol)
547     {
548         _protocol = protocol;
549     }
550
551     /* ------------------------------------------------------------ */
552     public void setProvider(String _provider) {
553 	this._provider = _provider;
554     }
555
556     /* ------------------------------------------------------------ */
557     public void setSecureRandomAlgorithm(String algorithm)
558     {
559         this._secureRandomAlgorithm = algorithm;
560     }
561
562     /* ------------------------------------------------------------ */
563     public void setSslKeyManagerFactoryAlgorithm(String algorithm)
564     {
565         this._sslKeyManagerFactoryAlgorithm = algorithm;
566     }
567
568     /* ------------------------------------------------------------ */
569     public void setSslTrustManagerFactoryAlgorithm(String algorithm)
570     {
571         this._sslTrustManagerFactoryAlgorithm = algorithm;
572     }
573
574
575     public void setTruststore(String truststore)
576     {
577         _truststore = truststore;
578     }
579
580
581     public void setTruststoreType(String truststoreType)
582     {
583         _truststoreType = truststoreType;
584     }
585
586     /* ------------------------------------------------------------ */
587     /**
588      * Set the value of the _wantClientAuth property. This property is used when
589      * {@link #newServerSocket(SocketAddress, int) opening server sockets}.
590      *
591      * @param wantClientAuth true iff we want client certificate authentication.
592      * @see SSLServerSocket#setWantClientAuth
593      */
594     public void setWantClientAuth(boolean wantClientAuth)
595     {
596         _wantClientAuth = wantClientAuth;
597     }
598
599     /**
600      * Set the time in milliseconds for so_timeout during ssl handshaking
601      * @param msec a non-zero value will be used to set so_timeout during
602      * ssl handshakes. A zero value means the maxIdleTime is used instead.
603      */
604     public void setHandshakeTimeout (int msec)
605     {
606         _handshakeTimeout = msec;
607     }
608
609
610     public int getHandshakeTimeout ()
611     {
612         return _handshakeTimeout;
613     }
614     /**
615      * Simple bundle of information that is cached in the SSLSession. Stores the effective keySize
616      * and the client certificate chain.
617      */
618     private class CachedInfo
619     {
620         private X509Certificate[] _certs;
621         private Integer _keySize;
622
623         CachedInfo(Integer keySize, X509Certificate[] certs)
624         {
625             this._keySize = keySize;
626             this._certs = certs;
627         }
628
629         X509Certificate[] getCerts()
630         {
631             return _certs;
632         }
633
634         Integer getKeySize()
635         {
636             return _keySize;
637         }
638     }
639
640
641     public class SslConnection extends Connection
642     {
643         public SslConnection(Socket socket) throws IOException
644         {
645             super(socket);
646         }
647
648         public void run()
649         {
650             try
651             {
652                 int handshakeTimeout = getHandshakeTimeout();
653                 int oldTimeout = _socket.getSoTimeout();
654                 if (handshakeTimeout > 0)
655                     _socket.setSoTimeout(handshakeTimeout);
656
657                 final SSLSocket ssl=(SSLSocket)_socket;
658                 ssl.addHandshakeCompletedListener(new HandshakeCompletedListener()
659                 {
660                     boolean handshook=false;
661                     public void handshakeCompleted(HandshakeCompletedEvent event)
662                     {
663                         if (handshook)
664                         {
665                             if (!_allowRenegotiate)
666                             {
667                                 Log.warn("SSL renegotiate denied: "+ssl);
668                                 try{ssl.close();}catch(IOException e){Log.warn(e);}
669                             }
670                         }
671                         else
672                             handshook=true;
673                     }
674                 });
675                 ssl.startHandshake();
676
677                 if (handshakeTimeout>0)
678                     _socket.setSoTimeout(oldTimeout);
679
680                 super.run();
681             }
682             catch (SSLException e)
683             {
684                 Log.warn(e);
685                 try{close();}
686                 catch(IOException e2){Log.ignore(e2);}
687             }
688             catch (IOException e)
689             {
690                 Log.debug(e);
691                 try{close();}
692                 catch(IOException e2){Log.ignore(e2);}
693             }
694         }
695     }
696
697 }

This page was automatically generated by Maven


text:
//=============================================================================
/**
 *  @file    DLList_Test.cpp
 *
 *    This test illustrates the use of <ACE_DLList>.
 *
 *  @author James Hu <jxh@cs.wustl.edu> and Douglas C. Schmidt <schmidt@cs.wustl.edu>
 */
//=============================================================================

#include "test_config.h"
#include "ace/Containers.h"
#include "ace/SString.h"
#include "ace/Malloc_T.h"

typedef ACE_TCHAR *ACE_STRING;
typedef ACE_DLList<ACE_STRING> STRLIST;
typedef ACE_DLList_Iterator<ACE_STRING> STRLIST_ITERATOR;
typedef ACE_DLList_Reverse_Iterator<ACE_STRING> STRLIST_REVERSE_ITERATOR;

static ACE_STRING string_table[] =
{
  // Note: all these casts are to appease SC 5.0 which is not pleased
  // with using string literals (i.e. const char *'s) as char
  // *'s. It's ugly, but necessary.
  const_cast<ACE_TCHAR *> (ACE_TEXT ("hello")),
  const_cast<ACE_TCHAR *> (ACE_TEXT ("guten Tag")),
  const_cast<ACE_TCHAR *> (ACE_TEXT ("goodbye")),
  const_cast<ACE_TCHAR *> (ACE_TEXT ("auf wiedersehen")),
  const_cast<ACE_TCHAR *> (ACE_TEXT ("funny")),
  const_cast<ACE_TCHAR *> (ACE_TEXT ("lustig")),
  0
};

static void
run_iterate (STRLIST &list)
{
  ACE_STRING *entry;
  size_t i = 0;

  for (STRLIST_ITERATOR iter (list);
       (entry = iter.next ()) != 0;
       iter.advance (), i++)
    {
      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("iterating (%d): [%s]\n"),
                  i,
                  (ACE_TCHAR *) *entry));
    }
}

static void
run_reverse_iterate (STRLIST &list)
{
  ACE_STRING *entry;
  size_t i = 0;

  for (STRLIST_REVERSE_ITERATOR iter (list);
       iter.next (entry) != 0;
       iter.advance (), i++)
    {
      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("iterating (%d): [%s]\n"),
                  i,
                  (ACE_TCHAR *) *entry));
    }
}

static int
run_test (void)
{
  STRLIST list;

  size_t i;

  for (i = 0; string_table[i] != 0; i++)
    {
      if (ACE_EVEN (i)
          && list.insert_tail ((ACE_STRING *) &string_table[i]) == 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("%p failed for %s\n"),
                           ACE_TEXT ("insert"),
                           string_table[i]),
                          -1);
      else if (list.insert_head ((ACE_STRING *) &string_table[i]) == 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("%p failed for %s\n"),
                           ACE_TEXT ("insert"),
                           string_table[i]),
                          -1);
      run_iterate (list);
      run_reverse_iterate (list);
    }

  run_iterate (list);
  run_reverse_iterate (list);

  list.delete_tail ();
  list.delete_tail ();

  run_iterate (list);
  run_reverse_iterate (list);

  list.delete_head ();
  list.delete_head ();

  run_iterate (list);
  run_reverse_iterate (list);

  return 0;
}

int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("DLList_Test"));

  run_test ();

  ACE_END_TEST;

  return 0;
}


text:
layout: main
title: Hackference 2015 - Sponsor Us
TODO: all of the page plz
---

Sponsorship Packages

Download as a PDF

Hackference is three unique days of learning, collaboration and creating, taking place in two venues across central Birmingham. 250 Conference attendees will be enjoying talks focusing on new technology, creating amazing experiences - watching and participating in workshops, and 150 Hackathon attendees will be part of one of the biggest hackathons in the United Kingdom.

Conference

October 2nd

								{% include conference-map.html %}

Hackathon

October 3rd - October 4th

								{% include hackathon-map.html %}

Who attends Hackference?

We're lucky at Hackference to have a diverse mixture of attendees - previous event's have had plenty of student, startup, corporate and freelance attendees from all over the skill spectrum. Although we love local developers and designers, we are even more lucky to have such a large number of them travel in from across the country.

The majority of our speakers are renowed on a national level - and some, international - and travel to us from all across the world. They are active on social media, and usually have a very large following as they are considered trendsetters, influencers and brand promoters.

Why support Hackference?

Supporting Hackference is a truely amazing way to get your company exposed to highly skilled and motivated developers and designers who are on the leading-edge of technology. In addition to helping us cover the costs of organising such an event - you are also helping us exhibit the brilliant, and sometimes, overlooked Birmingham technology scene. With your support, it mean's we can provide a fantastic event to our attendees.

The Packages

As the bare minimum everyone that sponsors is listed on our sponsors page with logo and a page explaining who you are and why you are supporting Hackference 2015. Also, a thank you will be sent out from our social media accounts and a mention in our periodic e-mail.

											OPPORTUNITY
											Virtual
											Bronze
											Silver
											Gold
											Platinum

											£200
											£500
											£2,000
											£3,500
											£6,000

											Basic Package

											Inclusion on every page

											Be recognised on site

											Dedicated email to members

											Goody bag inserts

											API Partner

											Booklet Advertisement

											*
											*
											*
											*

											Booth Space

											Inclusion on mailshots

											Lanyards

											Workshop Session

											Speakers Bar

											Inclusion on Video

											Power the workshops

											Power the main track

											Power the hackathon

											Afterparty

											Tickets
											0
											1
											2
											3
											4

The Extras

We have plenty of other things that you can sponsor, either adding in or swapping with items in the packages.

Student Tickets

Professionals aren't the only people that get the most out of conferences, students get access to the biggest experts in fields they may not normally have access to. We want to bring in more students and up the diversity of the attendees.

Cost: Contact us

Bean Bags

Sponsor the bean bags at the Hackathon, all the over night hackers will be eternally grateful to you for the more comfortable night's sleep they would have enjoyed.

Cost: £1,000

Hackathon WiFi

Connectivity is always a problem at large tech events, especially community events. Help keep the hackers hacking!

Cost: £3,500

Conference T-shirt

Give all the attendee's a little something unique and special to remember the event and your brand by.

Cost: Contact us

Hackathon Meal - Lunch

First and last meal of Hackference is lunch, help provide that kick to start everyone off.

Cost: £500

Hackathon Meal - Dinner

After most of a working day coding, the hackers deserve a break and something nice to dig into.

Cost: £850

Hackathon Meal - Breakfast

For those hackers that are just waking up, or haven't even attempted sleep, this is a much needed boost to the final hours of hacking.

Cost: £400

Hacker Coffee/Tea

The venue has an on-site coffee shop, why not have it branded and powered by your company.

Cost: Contact us

Hacker Fuel

Cover all the soft drink and energy drinks the hackers will consume over the 30 hours the hackathon is open.

Cost: £500

Hacker Beer

Cover the evening beers, where hackers are trying to relax and dig in for the long haul hacking.

Cost: £500

More Information

If you have any questions, or specific goals or requirements, please don't hesitate to get in contact; we're always open to ideas and will try to accommodate as much as possilbe.

You can contact us via:

										E-mail

										sponsorship@hackference.co.uk

										Twitter

										@hackferencebrum

										Phone

										(+44) 07816961602

					<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Inclusion on the Sponsor page

This is a great way of showing your support to Hackference. This package includes:

Company logo as image on website

Image and Text on the sponsors page

A social media shoutout across all Hackference Social Media to say thank you and who you are!

					<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
class AbsDistributionGenerator {
public:
  virtual std::vector<double> generate()=0;
};

#endif


text:
Affine Registration
===================

The affine transform allows for shearing and scaling in addition to the rotation and translation. This is usually a good choice of transform for initialization of non-rigid transforms like the B-Spline transform. The affine transform is selected using :code:`sitk.GetDefaultParameterMap("affine")`.

Consider the images in Figure 10.

.. _fig10:

    .. image::  _static/BrainProtonDensity.png
       :width: 45%
       :align: left
    .. image::  _static/BrainProtonDensityTranslatedR1013x17yS12.png
       :width: 45%
       :align: left

    .. class:  center

    Figure 10. The original image :code:`fixedImage.nii` (left) and translated and rotated image :code:`movingImage.nii` (right).

The image on the right has been sheared, scaled 1.2x, rotated 10 degrees and translated 13 pixels in the x-direction and 17 pixels in the y-direction. Using the :code:`AdvancedAffineTransform` we may correct for this misalignment.

::

    import SimpleITK as sitk

    elastixImageFilter = sitk.ElastixImageFilter()
    elastixImageFilter.SetFixedImage(sitk.ReadImage("fixedImage.nii")
    elastixImageFilter.SetMovingImage(sitk.ReadImage("movingImage.nii")
    elastixImageFilter.SetParameterMap(sitk.GetDefaultParameterMap("affine"))
    elastixImageFilter.Execute()
    sitk.WriteImage(elastixImageFilter.GetResultImage())

It is clear from the result mean image on right in Fig. 11 that registration was successful.

.. _fig11:

    .. image::  _static/PreAffine.jpeg
       :width: 45%
       :align: left
    .. image::  _static/PostAffine.jpeg
       :width: 45%
       :align: left

    .. class:  center

    Figure 11. Mean image before registration (left) and mean image after registration (right).

Notice that the only difference from the previous example is the requested parameter map. In fact, only the `Transform` parameter seperates the two parameter maps. The following parameter map is equivalent to the one used above:

::

    import SimpleITK as sitk

    parameterMap = sitk.GetDefaultParameterMap("rigid")
    parameterMap["Transform"] = ["AffineTransform"]

You can inspect the default parameter maps in the `elastix repository <https://github.com/SuperElastix/elastix/blob/522843d90ff586be051c480514cd14a88db45dbf/src/Core/Main/elxParameterObject.cxx#L260-L362>`_ to convince yourself.

This demonstrates how easy it is to try out different registration components with SimpleElastix. In the next example we will introduce non-rigid registration and initialize the moving image with an affine transform.