text:
using System.Linq;

namespace NLog.UnitTests.Targets.Wrappers
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using NLog.Common;
    using NLog.Targets;
    using NLog.Targets.Wrappers;
    using Xunit;

    public class SplitGroupTargetTests : NLogTestBase
    {
        [Fact]
        public void SplitGroupSyncTest1()
        {
            SplitGroupSyncTest1inner(false);
        }

        [Fact]
        public void SplitGroupSyncTest1_allEventsAtOnce()
        {
            SplitGroupSyncTest1inner(true);
        }

        private static void SplitGroupSyncTest1inner(bool allEventsAtOnce)
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new SplitGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List<Exception> exceptions = new List<Exception>();

            var inputEvents = new List<LogEventInfo>();
            for (int i = 0; i < 10; ++i)
            {
                inputEvents.Add(LogEventInfo.CreateNullEvent());
            }

            int remaining = inputEvents.Count;
            var allDone = new ManualResetEvent(false);

            // no exceptions

            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (Interlocked.Decrement(ref remaining) == 0)
                    {
                        allDone.Set();
                    }
                }
                      ;
            };

            if (allEventsAtOnce)
            {
                wrapper.WriteAsyncLogEvents(inputEvents.Select(ev => ev.WithContinuation(asyncContinuation)).ToArray());
            }
            else
            {
                for (int i = 0; i < inputEvents.Count; ++i)
                {
                    wrapper.WriteAsyncLogEvent(inputEvents[i].WithContinuation(asyncContinuation));
                }
            }

            allDone.WaitOne();

            Assert.Equal(inputEvents.Count, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.Null(e);
            }

            Assert.Equal(inputEvents.Count, myTarget1.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget2.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget3.WriteCount);

            for (int i = 0; i < inputEvents.Count; ++i)
            {
                Assert.Same(inputEvents[i], myTarget1.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget2.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget3.WrittenEvents[i]);
            }

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex =>
            {
                flushException = ex;
                flushHit.Set();
            });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.True(false, flushException.ToString());
            }

            Assert.Equal(1, myTarget1.FlushCount);
            Assert.Equal(1, myTarget2.FlushCount);
            Assert.Equal(1, myTarget3.FlushCount);
        }

        [Fact]
        public void SplitGroupToStringTest()
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new FileTarget("file1");
            var myTarget3 = new ConsoleTarget("Console2");

            var wrapper = new SplitGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            Assert.Equal("SplitGroup Target[(unnamed)](MyTarget, File Target[file1], Console Target[Console2])", wrapper.ToString());
        }

        [Fact]
        public void SplitGroupSyncTest2()
        {
            var wrapper = new SplitGroupTarget()
            {
                // no targets
            };

            wrapper.Initialize(null);

            List<Exception> exceptions = new List<Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.Equal(10, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.Null(e);
            }

            Exception flushException = new Exception("Flush not hit synchronously.");
            wrapper.Flush(ex => flushException = ex);

            if (flushException != null)
            {
                Assert.True(false, flushException.ToString());
            }
        }

        public class MyAsyncTarget : Target
        {
            public int FlushCount { get; private set; }
            public int WriteCount { get; private set; }

            public MyAsyncTarget() : base()
            {
            }

            public MyAsyncTarget(string name) : this()
            {
                Name = name;
            }

            protected override void Write(LogEventInfo logEvent)
            {
                throw new NotSupportedException();
            }

            protected override void Write(AsyncLogEventInfo logEvent)
            {
                Assert.True(FlushCount <= WriteCount);
                WriteCount++;
                ThreadPool.QueueUserWorkItem(
                    s =>
                        {
                            if (ThrowExceptions)
                            {
                                logEvent.Continuation(new InvalidOperationException("Some problem!"));
                                logEvent.Continuation(new InvalidOperationException("Some problem!"));
                            }
                            else
                            {
                                logEvent.Continuation(null);
                                logEvent.Continuation(null);
                            }
                        });
            }

            protected override void FlushAsync(AsyncContinuation asyncContinuation)
            {
                FlushCount++;
                ThreadPool.QueueUserWorkItem(
                    s => asyncContinuation(null));
            }

            public bool ThrowExceptions { get; set; }
        }

        public class MyTarget : Target
        {
            public MyTarget()
            {
                WrittenEvents = new List<LogEventInfo>();
            }

            public MyTarget(string name) : this()
            {
                Name = name;
            }

            public int FlushCount { get; set; }
            public int WriteCount { get; set; }
            public int FailCounter { get; set; }
            public List<LogEventInfo> WrittenEvents { get; private set; }

            protected override void Write(LogEventInfo logEvent)
            {
                Assert.True(FlushCount <= WriteCount);
                lock (this)
                {
                    WriteCount++;
                    WrittenEvents.Add(logEvent);
                }

                if (FailCounter > 0)
                {
                    FailCounter--;
                    throw new InvalidOperationException("Some failure.");
                }
            }

            protected override void FlushAsync(AsyncContinuation asyncContinuation)
            {
                FlushCount++;
                asyncContinuation(null);
            }
        }
    }
}


text:
from telemetry.core import util
from telemetry.unittest_util import browser_test_case

class TabTestCase(browser_test_case.BrowserTestCase):
  def __init__(self, *args):
    super(TabTestCase, self).__init__(*args)
    self._tab = None

  def setUp(self):
    super(TabTestCase, self).setUp()

    if self._browser.supports_tab_control:
      try:
        self._tab = self._browser.tabs.New()
        while len(self._browser.tabs) > 1:
          self._browser.tabs[0].Close()
      except util.TimeoutException:
        self._RestartBrowser()
    else:
      self._RestartBrowser()
    self._tab.Navigate('about:blank')
    self._tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()

  def Navigate(self, filename, script_to_evaluate_on_commit=None):
    """Navigates |tab| to |filename| in the unittest data directory.

    Also sets up http server to point to the unittest data directory.
    """
    url = self.UrlOfUnittestFile(filename)
    self._tab.Navigate(url, script_to_evaluate_on_commit)
    self._tab.WaitForDocumentReadyStateToBeComplete()

  def _RestartBrowser(self):
    if not self._browser.tabs:
      self.tearDownClass()
      self.setUpClass()
    self._tab = self._browser.tabs[0]

redpajama_set_name: RedPajamaGithub


text:
        <input type="text" class="st-default-search-input pm-form-control pm-white-control" name="search" placeholder="Search documentation" autocomplete="off" autocorrect="off" autocapitalize="off" required="required" />

        {% assign pageurl = page.url | split: '/' %}
        {% assign product_prefix = pageurl[2] %}
        {% assign category_prefix = pageurl[3] %}

        {% for product in site.data.doc_map %}
        {% assign product_index = forloop.index0 %}

                {{product.title}}

                {% for category in product.children %}
                {% assign category_index = forloop.index0 %}

                {% if category.href.size > 0 %}

                        {{category.title}}

                {% else %}

                            {{category.title}}

                            {% for feature in category.children %}
                            {% assign feature_index = forloop.index0 %}
                            {% if feature.href %}

                                    {{feature.title}}

                            {% endif %}
                            {% endfor %}

                {% endif %}
                {% endfor %}

        {% endfor %}


text:
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import React from 'react'

import DateTimePickerWithLabelFormGroup from '../../../../shared/components/input/DateTimePickerWithLabelFormGroup'

describe('date picker with label form group', () => {
  describe('layout', () => {
    it('should render a label', () => {
      const expectedName = 'stardate11111'
      render(
        <DateTimePickerWithLabelFormGroup
          name={expectedName}
          label="stardate11111"
          value={new Date()}
          isEditable
          onChange={jest.fn()}
        />,
      )

      const name = screen.getByText(/stardate/i)
      expect(name).toHaveAttribute('for', `${expectedName}DateTimePicker`)
      expect(name).toHaveTextContent(expectedName)
    })

    it('should render disabled is isDisable disabled is true', () => {
      render(
        <DateTimePickerWithLabelFormGroup
          name="stardate333333"
          label="stardate333333"
          value={new Date()}
          isEditable={false}
          onChange={jest.fn()}
        />,
      )
      expect(screen.getByRole('textbox')).toBeDisabled()
    })

    it('should render the proper value', () => {
      render(
        <DateTimePickerWithLabelFormGroup
          name="stardate4444444"
          label="stardate4444444"
          value={new Date('12/25/2020 2:56 PM')}
          isEditable={false}
          onChange={jest.fn()}
        />,
      )
      const datepickerInput = screen.getByRole('textbox')
      expect(datepickerInput).toBeDisabled()
      expect(datepickerInput).toHaveDisplayValue(/[12/25/2020 2:56 PM]/i)
    })
  })
})

describe('change handler', () => {
  it('should call the change handler on change', () => {
    render(
      <DateTimePickerWithLabelFormGroup
        name="stardate55555555"
        label="stardate55555555"
        value={new Date('1/1/2021 2:56 PM')}
        isEditable
        onChange={jest.fn()}
      />,
    )
    const datepickerInput = screen.getByRole('textbox')

    expect(datepickerInput).toHaveDisplayValue(/[01/01/2021 2:56 PM]/i)
    userEvent.type(datepickerInput, '{selectall}12/25/2020 2:56 PM{enter}')
    expect(datepickerInput).toHaveDisplayValue(/[12/25/2020 2:56 PM]/i)
  })
})


text:
//
//  BaseStepViewController.h
//  LXFrameWork_OC
//
//  Created by 李晓 on 15/7/20.
//  Copyright (c) 2015年 LXFrameWork. All rights reserved.
//

#import "BaseViewController.h"
#import "InterchangeButton.h"
#import "StepNextView.h"

@protocol StepViewDelegate <NSObject>

@required

/**
 *  步骤标题的titleArray
 */
- (NSArray *) titleArrayAtHeadView:(UIView *)StepView;

/**
 *  返回每个步骤标题所对应的View
 */
- (StepNextView *) viewForRowAtFootView :(UIView *)StepView Count:(NSInteger) number;

@end

@interface BaseStepViewController : BaseViewController

/***  StepViewDelegate */
@property (nonatomic,assign) id <StepViewDelegate> delegate;
/***  步骤的头部View */
@property (nonatomic,strong) UIView *stepHeadView;
/***  步骤所对应的底部View */
@property (nonatomic,strong) UIView *stepContentView;
/***  底部的分割线 */
@property (nonatomic,strong) UIView *line;

/**
 *  进入下一个步骤
 */
- (void) nextPage;

/**
 *  跳到某一个页面
 */
- (void) toPage:(NSInteger) pageCount;

/**
 *  刷新数据
 */
- (void) reloadData;

@end


text:
@class NSDictionary, NSURL, NSOrthography;

FOUNDATION_EXPORT NSString *const NSTextCheckingNameKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingJobTitleKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingOrganizationKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingStreetKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingCityKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingStateKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingZIPKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingCountryKey;
FOUNDATION_EXPORT NSString *const NSTextCheckingPhoneKey;

enum {
    NSTextCheckingTypeOrthography = 1ULL << 0,
    NSTextCheckingTypeSpelling = 1ULL << 1,
    NSTextCheckingTypeGrammar = 1ULL << 2,
    NSTextCheckingTypeDate = 1ULL << 3,
    NSTextCheckingTypeAddress = 1ULL << 4,
    NSTextCheckingTypeLink = 1ULL << 5,
    NSTextCheckingTypeQuote = 1ULL << 6,
    NSTextCheckingTypeDash = 1ULL << 7,
    NSTextCheckingTypeReplacement = 1ULL << 8,
    NSTextCheckingTypeCorrection = 1ULL << 9,
};
typedef uint64_t NSTextCheckingType;

enum {
    NSTextCheckingAllSystemTypes = 0xffffffffULL,
    NSTextCheckingAllCustomTypes = 0xffffffffULL << 32,
    NSTextCheckingAllTypes = (NSTextCheckingAllSystemTypes | NSTextCheckingAllCustomTypes),
};
typedef uint64_t NSTextCheckingTypes;

@interface NSTextCheckingResult : NSObject {
    NSTextCheckingType _resultType;
    NSRange _range;
    NSDictionary *_properties;
}

+ (NSTextCheckingResult *)addressCheckingResultWithRange:(NSRange)range components:(NSDictionary *)components;
+ (NSTextCheckingResult *)correctionCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacement;
+ (NSTextCheckingResult *)dashCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacement;
+ (NSTextCheckingResult *)dateCheckingResultWithRange:(NSRange)range date:(NSDate *)date;
+ (NSTextCheckingResult *)dateCheckingResultWithRange:(NSRange)range date:(NSDate *)date timeZone:(NSTimeZone *)timeZone duration:(NSTimeInterval)duration;
+ (NSTextCheckingResult *)grammarCheckingResultWithRange:(NSRange)range details:(NSArray *)details;
+ (NSTextCheckingResult *)linkCheckingResultWithRange:(NSRange)range URL:(NSURL *)url;
+ (NSTextCheckingResult *)orthographyCheckingResultWithRange:(NSRange)range orthography:(NSOrthography *)orthography;
+ (NSTextCheckingResult *)quoteCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacement;
+ (NSTextCheckingResult *)replacementCheckingResultWithRange:(NSRange)range replacementString:(NSString *)replacement;
+ (NSTextCheckingResult *)spellCheckingResultWithRange:(NSRange)range;

@property(readonly) NSDictionary *addressComponents;
@property(readonly) NSDate *date;
@property(readonly) NSTimeInterval duration;
@property(readonly) NSArray *grammarDetails;
@property(readonly) NSOrthography *orthography;
@property(readonly) NSRange range;
@property(readonly) NSString *replacementString;
@property(readonly) NSTextCheckingType resultType;
@property(readonly) NSTimeZone *timeZone;
@property(readonly) NSURL *URL;

@end


text:
/*
This question is from https://leetcode.com/problems/move-zeroes/
Difficulty: easy

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

Time Complexty = O(n+m)
*/
public class Solution{
	// i = 0 => zeros = 1, currentPosition = 0 [0, 1, 0, 3, 12]
	// i = 1 => zeros = 1, currentPosition = 1 [1, 1, 0, 3, 12]
	// i = 2 => zeros = 2, currentPosition = 1 [1, 1, 0, 3, 12]
	// i = 3 => zeros = 2, currentPosition = 2 [1, 3, 0, 3, 12]
	// i = 4 => zeros = 2, currentPosition = 3 [1, 3, 12, 3, 12]
	public void moveZeroes(int[] nums){
		int currentPosition = 0;
		for(int i = 0 ; i < nums.length; i++){
			if(nums[i] != 0){
				nums[currentPosition] = nums[i];
				currentPosition++;
			}
		}

		for(int i = currentPosition; i < nums.length; i++){
			nums[i] = 0;
		}
		// alternative
		// Arrays.fill(nums, currentPosition, nums.length, 0);
	}
}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('wizard_builder', '0017_remove_unused_models'),
    ]

    operations = [
        migrations.DeleteModel(
            name='MultiLineText',
        ),
    ]


text:
package eu.verdelhan.ta4j.indicators.trackers;

import static eu.verdelhan.ta4j.TATestsUtils.assertDecimalEquals;
import eu.verdelhan.ta4j.Tick;
import eu.verdelhan.ta4j.mocks.MockTick;
import eu.verdelhan.ta4j.mocks.MockTimeSeries;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class ParabolicSarIndicatorTest {

    @Test
    public void trendSwitchTest() {
        List<Tick> ticks = new ArrayList<Tick>();
        ticks.add(new MockTick(0, 10, 13, 8));
        ticks.add(new MockTick(0, 8, 11, 6));
        ticks.add(new MockTick(0, 6, 9, 4));
        ticks.add(new MockTick(0, 11, 15, 9));
        ticks.add(new MockTick(0, 13, 15, 9));
        ParabolicSarIndicator sar = new ParabolicSarIndicator(new MockTimeSeries(ticks), 1);

        assertDecimalEquals(sar.getValue(0), 10);
        assertDecimalEquals(sar.getValue(1), 8);
        assertDecimalEquals(sar.getValue(2), 11);
        assertDecimalEquals(sar.getValue(3), 4);
        assertDecimalEquals(sar.getValue(4), 4);
    }

    @Test
    public void trendSwitchTest2() {
        List<Tick> ticks = new ArrayList<Tick>();
        ticks.add(new MockTick(0, 10, 13, 11));
        ticks.add(new MockTick(0, 10, 15, 13));
        ticks.add(new MockTick(0, 12, 18, 11));
        ticks.add(new MockTick(0, 10, 15, 9));
        ticks.add(new MockTick(0, 9, 15, 9));

        ParabolicSarIndicator sar = new ParabolicSarIndicator(new MockTimeSeries(ticks), 1);

        assertDecimalEquals(sar.getValue(0), 10);
        assertDecimalEquals(sar.getValue(1), 10);
        assertDecimalEquals(sar.getValue(2), 0.04 * (18 - 10) + 10);
        assertDecimalEquals(sar.getValue(3), 18);
        assertDecimalEquals(sar.getValue(4), 18);
    }

    @Test
    public void upTrendTest() {
        List<Tick> ticks = new ArrayList<Tick>();
        ticks.add(new MockTick(0, 10, 13, 11));
        ticks.add(new MockTick(0, 17, 15, 11.38));
        ticks.add(new MockTick(0, 18, 16, 14));
        ticks.add(new MockTick(0, 19, 17, 12));
        ticks.add(new MockTick(0, 20, 18, 9));

        ParabolicSarIndicator sar = new ParabolicSarIndicator(new MockTimeSeries(ticks), 1);

        assertDecimalEquals(sar.getValue(0), 10);
        assertDecimalEquals(sar.getValue(1), 17);
        assertDecimalEquals(sar.getValue(2), 11.38);
        assertDecimalEquals(sar.getValue(3), 11.38);
        assertDecimalEquals(sar.getValue(4), 18);
    }

    @Test
    public void downTrendTest() {
        List<Tick> ticks = new ArrayList<Tick>();
        ticks.add(new MockTick(0, 20, 18, 9));
        ticks.add(new MockTick(0, 19, 17, 12));
        ticks.add(new MockTick(0, 18, 16, 14));
        ticks.add(new MockTick(0, 17, 15, 11.38));
        ticks.add(new MockTick(0, 10, 13, 11));
        ticks.add(new MockTick(0, 10, 30, 11));

        ParabolicSarIndicator sar = new ParabolicSarIndicator(new MockTimeSeries(ticks), 1);

        assertDecimalEquals(sar.getValue(0), 20);
        assertDecimalEquals(sar.getValue(1), 19);
        assertDecimalEquals(sar.getValue(2), 0.04 * (14 - 19) + 19);
        double value = 0.06 * (11.38 - 18.8) + 18.8;
        assertDecimalEquals(sar.getValue(3), value);
        assertDecimalEquals(sar.getValue(4), 0.08 * (11 - value) + value);
        assertDecimalEquals(sar.getValue(5), 11);
    }
}


text:
<?php

namespace Stalker\Lib\StbApi;

interface Horoscope
{
    public function getData();
}


text:
<?php
declare(strict_types=1);

namespace JDWil\Xsd\Event;

/**
 * Class FoundMinInclusiveEvent
 * @package JDWil\Xsd\Event
 */
class FoundMinInclusiveEvent extends AbstractXsdNodeEvent
{

}


text:
// A basic integration test for the service.
// Assumes that there is a pre-existing etcd server running on localhost.
package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"reflect"
	gruntime "runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	kubeletapp "k8s.io/kubernetes/cmd/kubelet/app"
	"k8s.io/kubernetes/pkg/api"
	apierrors "k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/testapi"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/api/v1"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_1"
	"k8s.io/kubernetes/pkg/client/record"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/controller"
	endpointcontroller "k8s.io/kubernetes/pkg/controller/endpoint"
	nodecontroller "k8s.io/kubernetes/pkg/controller/node"
	replicationcontroller "k8s.io/kubernetes/pkg/controller/replication"
	"k8s.io/kubernetes/pkg/kubelet/cadvisor"
	"k8s.io/kubernetes/pkg/kubelet/cm"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
	"k8s.io/kubernetes/pkg/kubelet/dockertools"
	kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/master"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util"
	utilnet "k8s.io/kubernetes/pkg/util/net"
	"k8s.io/kubernetes/pkg/util/sets"
	"k8s.io/kubernetes/pkg/util/wait"
	"k8s.io/kubernetes/pkg/volume/empty_dir"
	"k8s.io/kubernetes/plugin/pkg/scheduler"
	_ "k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider"
	"k8s.io/kubernetes/plugin/pkg/scheduler/factory"
	"k8s.io/kubernetes/test/e2e"
	"k8s.io/kubernetes/test/integration"
	"k8s.io/kubernetes/test/integration/framework"

	etcd "github.com/coreos/etcd/client"
	"github.com/golang/glog"
	"github.com/spf13/pflag"
	"golang.org/x/net/context"
)

var (
	fakeDocker1 = dockertools.NewFakeDockerClient()
	fakeDocker2 = dockertools.NewFakeDockerClient()
	// Limit the number of concurrent tests.
	maxConcurrency int

	longTestTimeout = time.Second * 500

	maxTestTimeout = time.Minute * 15
)

type delegateHandler struct {
	delegate http.Handler
}

func (h *delegateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if h.delegate != nil {
		h.delegate.ServeHTTP(w, req)
		return
	}
	w.WriteHeader(http.StatusNotFound)
}

func startComponents(firstManifestURL, secondManifestURL string) (string, string) {
	// Setup
	handler := delegateHandler{}
	apiServer := httptest.NewServer(&handler)

	cfg := etcd.Config{
		Endpoints: []string{"http://127.0.0.1:4001"},
	}
	etcdClient, err := etcd.New(cfg)
	if err != nil {
		glog.Fatalf("Error creating etcd client: %v", err)
	}
	glog.Infof("Creating etcd client pointing to %v", cfg.Endpoints)

	keysAPI := etcd.NewKeysAPI(etcdClient)
	sleep := 4 * time.Second
	ok := false
	for i := 0; i < 3; i++ {
		keys, err := keysAPI.Get(context.TODO(), "/", nil)
		if err != nil {
			glog.Warningf("Unable to list root etcd keys: %v", err)
			if i < 2 {
				time.Sleep(sleep)
				sleep = sleep * sleep
			}
			continue
		}
		for _, node := range keys.Node.Nodes {
			if _, err := keysAPI.Delete(context.TODO(), node.Key, &etcd.DeleteOptions{Recursive: true}); err != nil {
				glog.Fatalf("Unable delete key: %v", err)
			}
		}
		ok = true
		break
	}
	if !ok {
		glog.Fatalf("Failed to connect to etcd")
	}

	cl := client.NewOrDie(&client.Config{Host: apiServer.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}})
	clientset := clientset.NewForConfigOrDie(&client.Config{Host: apiServer.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}})

	// TODO: caesarxuchao: hacky way to specify version of Experimental client.
	// We will fix this by supporting multiple group versions in Config
	cl.ExtensionsClient = client.NewExtensionsOrDie(&client.Config{Host: apiServer.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Extensions.GroupVersion()}})

	// Master
	host, port, err := net.SplitHostPort(strings.TrimLeft(apiServer.URL, "http://"))
	if err != nil {
		glog.Fatalf("Unable to parse URL '%v': %v", apiServer.URL, err)
	}
	portNumber, err := strconv.Atoi(port)
	if err != nil {
		glog.Fatalf("Nonnumeric port? %v", err)
	}

	publicAddress := net.ParseIP(host)
	if publicAddress == nil {
		glog.Fatalf("No public address for %s", host)
	}

	// The caller of master.New should guarantee pulicAddress is properly set
	hostIP, err := utilnet.ChooseBindAddress(publicAddress)
	if err != nil {
		glog.Fatalf("Unable to find suitable network address.error='%v' . "+
			"Fail to get a valid public address for master.", err)
	}

	masterConfig := framework.NewMasterConfig()
	masterConfig.EnableCoreControllers = true
	masterConfig.EnableProfiling = true
	masterConfig.ReadWritePort = portNumber
	masterConfig.PublicAddress = hostIP
	masterConfig.CacheTimeout = 2 * time.Second

	// Create a master and install handlers into mux.
	m := master.New(masterConfig)
	handler.delegate = m.Handler

	// Scheduler
	schedulerConfigFactory := factory.NewConfigFactory(cl, api.DefaultSchedulerName)
	schedulerConfig, err := schedulerConfigFactory.Create()
	if err != nil {
		glog.Fatalf("Couldn't create scheduler config: %v", err)
	}
	eventBroadcaster := record.NewBroadcaster()
	schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: api.DefaultSchedulerName})
	eventBroadcaster.StartLogging(glog.Infof)
	eventBroadcaster.StartRecordingToSink(cl.Events(""))
	scheduler.New(schedulerConfig).Run()

	// ensure the service endpoints are sync'd several times within the window that the integration tests wait
	go endpointcontroller.NewEndpointController(cl, controller.NoResyncPeriodFunc).
		Run(3, util.NeverStop)

	// TODO: Write an integration test for the replication controllers watch.
	go replicationcontroller.NewReplicationManager(clientset, controller.NoResyncPeriodFunc, replicationcontroller.BurstReplicas).
		Run(3, util.NeverStop)

	nodeController := nodecontroller.NewNodeController(nil, cl, 5*time.Minute, util.NewFakeRateLimiter(), util.NewFakeRateLimiter(),
		40*time.Second, 60*time.Second, 5*time.Second, nil, false)
	nodeController.Run(5 * time.Second)
	cadvisorInterface := new(cadvisor.Fake)

	// Kubelet (localhost)
	testRootDir := integration.MakeTempDirOrDie("kubelet_integ_1.", "")
	configFilePath := integration.MakeTempDirOrDie("config", testRootDir)
	glog.Infof("Using %s as root dir for kubelet #1", testRootDir)
	cm := cm.NewStubContainerManager()
	kcfg := kubeletapp.SimpleKubelet(
		cl,
		fakeDocker1,
		"localhost",
		testRootDir,
		firstManifestURL,
		"127.0.0.1",
		10250, /* KubeletPort */
		0,     /* ReadOnlyPort */
		api.NamespaceDefault,
		empty_dir.ProbeVolumePlugins(),
		nil,
		cadvisorInterface,
		configFilePath,
		nil,
		kubecontainer.FakeOS{},
		1*time.Second,  /* FileCheckFrequency */
		1*time.Second,  /* HTTPCheckFrequency */
		10*time.Second, /* MinimumGCAge */
		3*time.Second,  /* NodeStatusUpdateFrequency */
		10*time.Second, /* SyncFrequency */
		10*time.Second, /* OutOfDiskTransitionFrequency */
		40,             /* MaxPods */
		cm, net.ParseIP("127.0.0.1"))

	kubeletapp.RunKubelet(kcfg)
	// Kubelet (machine)
	// Create a second kubelet so that the guestbook example's two redis slaves both
	// have a place they can schedule.
	testRootDir = integration.MakeTempDirOrDie("kubelet_integ_2.", "")
	glog.Infof("Using %s as root dir for kubelet #2", testRootDir)

	kcfg = kubeletapp.SimpleKubelet(
		cl,
		fakeDocker2,
		"127.0.0.1",
		testRootDir,
		secondManifestURL,
		"127.0.0.1",
		10251, /* KubeletPort */
		0,     /* ReadOnlyPort */
		api.NamespaceDefault,
		empty_dir.ProbeVolumePlugins(),
		nil,
		cadvisorInterface,
		"",
		nil,
		kubecontainer.FakeOS{},
		1*time.Second,  /* FileCheckFrequency */
		1*time.Second,  /* HTTPCheckFrequency */
		10*time.Second, /* MinimumGCAge */
		3*time.Second,  /* NodeStatusUpdateFrequency */
		10*time.Second, /* SyncFrequency */
		10*time.Second, /* OutOfDiskTransitionFrequency */

		40, /* MaxPods */
		cm,
		net.ParseIP("127.0.0.1"))

	kubeletapp.RunKubelet(kcfg)
	return apiServer.URL, configFilePath
}

func makeTempDirOrDie(prefix string, baseDir string) string {
	if baseDir == "" {
		baseDir = "/tmp"
	}
	tempDir, err := ioutil.TempDir(baseDir, prefix)
	if err != nil {
		glog.Fatalf("Can't make a temp rootdir: %v", err)
	}
	if err = os.MkdirAll(tempDir, 0750); err != nil {
		glog.Fatalf("Can't mkdir(%q): %v", tempDir, err)
	}
	return tempDir
}

// podsOnNodes returns true when all of the selected pods exist on a node.
func podsOnNodes(c *client.Client, podNamespace string, labelSelector labels.Selector) wait.ConditionFunc {
	// Wait until all pods are running on the node.
	return func() (bool, error) {
		options := api.ListOptions{LabelSelector: labelSelector}
		pods, err := c.Pods(podNamespace).List(options)
		if err != nil {
			glog.Infof("Unable to get pods to list: %v", err)
			return false, nil
		}
		for i := range pods.Items {
			pod := pods.Items[i]
			podString := fmt.Sprintf("%s/%s", pod.Namespace, pod.Name)
			glog.Infof("Check whether pod %q exists on node %q", podString, pod.Spec.NodeName)
			if len(pod.Spec.NodeName) == 0 {
				glog.Infof("Pod %q is not bound to a host yet", podString)
				return false, nil
			}
			if pod.Status.Phase != api.PodRunning {
				glog.Infof("Pod %q is not running, status: %v", podString, pod.Status.Phase)
				return false, nil
			}
		}
		return true, nil
	}
}

func endpointsSet(c *client.Client, serviceNamespace, serviceID string, endpointCount int) wait.ConditionFunc {
	return func() (bool, error) {
		endpoints, err := c.Endpoints(serviceNamespace).Get(serviceID)
		if err != nil {
			glog.Infof("Error getting endpoints: %v", err)
			return false, nil
		}
		count := 0
		for _, ss := range endpoints.Subsets {
			for _, addr := range ss.Addresses {
				for _, port := range ss.Ports {
					count++
					glog.Infof("%s/%s endpoint: %s:%d %#v", serviceNamespace, serviceID, addr.IP, port.Port, addr.TargetRef)
				}
			}
		}
		return count == endpointCount, nil
	}
}

func countEndpoints(eps *api.Endpoints) int {
	count := 0
	for i := range eps.Subsets {
		count += len(eps.Subsets[i].Addresses) * len(eps.Subsets[i].Ports)
	}
	return count
}

func podExists(c *client.Client, podNamespace string, podName string) wait.ConditionFunc {
	return func() (bool, error) {
		_, err := c.Pods(podNamespace).Get(podName)
		return err == nil, nil
	}
}

func podNotFound(c *client.Client, podNamespace string, podName string) wait.ConditionFunc {
	return func() (bool, error) {
		_, err := c.Pods(podNamespace).Get(podName)
		return apierrors.IsNotFound(err), nil
	}
}

func podRunning(c *client.Client, podNamespace string, podName string) wait.ConditionFunc {
	return func() (bool, error) {
		pod, err := c.Pods(podNamespace).Get(podName)
		if apierrors.IsNotFound(err) {
			glog.V(2).Infof("Pod %s/%s was not found", podNamespace, podName)
			return false, nil
		}
		if err != nil {
			// This could be a connection error so we want to retry, but log the error.
			glog.Errorf("Error when reading pod %q: %v", podName, err)
			return false, nil
		}
		if pod.Status.Phase != api.PodRunning {
			glog.V(2).Infof("Pod %s/%s is not running. In phase %q", podNamespace, podName, pod.Status.Phase)
			return false, nil
		}
		return true, nil
	}
}

// runStaticPodTest is disabled until #6651 is resolved.
func runStaticPodTest(c *client.Client, configFilePath string) {
	var testCases = []struct {
		desc         string
		fileContents string
	}{
		{
			desc: "static-pod-from-manifest",
			fileContents: `version: v1beta2
id: static-pod-from-manifest
containers:
  - name: static-container
    image: kubernetes/pause`,
		},
		{
			desc: "static-pod-from-spec",
			fileContents: `{
				"kind": "Pod",
				"apiVersion": "v1",
				"metadata": {
					"name": "static-pod-from-spec"
				},
				"spec": {
					"containers": [{
						"name": "static-container",
						"image": "kubernetes/pause"
					}]
				}
			}`,
		},
	}

	for _, testCase := range testCases {
		func() {
			desc := testCase.desc
			manifestFile, err := ioutil.TempFile(configFilePath, "")
			defer os.Remove(manifestFile.Name())
			ioutil.WriteFile(manifestFile.Name(), []byte(testCase.fileContents), 0600)

			// Wait for the mirror pod to be created.
			podName := fmt.Sprintf("%s-localhost", desc)
			namespace := kubetypes.NamespaceDefault
			if err := wait.Poll(time.Second, longTestTimeout,
				podRunning(c, namespace, podName)); err != nil {
				if pods, err := c.Pods(namespace).List(api.ListOptions{}); err == nil {
					for _, pod := range pods.Items {
						glog.Infof("pod found: %s/%s", namespace, pod.Name)
					}
				}
				glog.Fatalf("%s FAILED: mirror pod has not been created or is not running: %v", desc, err)
			}
			// Delete the mirror pod, and wait for it to be recreated.
			c.Pods(namespace).Delete(podName, nil)
			if err = wait.Poll(time.Second, longTestTimeout,
				podRunning(c, namespace, podName)); err != nil {
				glog.Fatalf("%s FAILED: mirror pod has not been re-created or is not running: %v", desc, err)
			}
			// Remove the manifest file, and wait for the mirror pod to be deleted.
			os.Remove(manifestFile.Name())
			if err = wait.Poll(time.Second, longTestTimeout,
				podNotFound(c, namespace, podName)); err != nil {
				glog.Fatalf("%s FAILED: mirror pod has not been deleted: %v", desc, err)
			}
		}()
	}
}

func runReplicationControllerTest(c *client.Client) {
	t := time.Now()
	clientAPIVersion := c.APIVersion().String()
	data, err := ioutil.ReadFile("cmd/integration/" + clientAPIVersion + "-controller.json")
	if err != nil {
		glog.Fatalf("Unexpected error: %v", err)
	}
	glog.Infof("Done reading config file, took %v", time.Since(t))
	t = time.Now()
	var controller api.ReplicationController
	if err := runtime.DecodeInto(testapi.Default.Codec(), data, &controller); err != nil {
		glog.Fatalf("Unexpected error: %v", err)
	}

	glog.Infof("Creating replication controllers")
	updated, err := c.ReplicationControllers("test").Create(&controller)
	if err != nil {
		glog.Fatalf("Unexpected error: %v", err)
	}
	glog.Infof("Done creating replication controllers, took %v", time.Since(t))
	t = time.Now()

	// In practice the controller doesn't need 60s to create a handful of pods, but network latencies on CI
	// systems have been observed to vary unpredictably, so give the controller enough time to create pods.
	// Our e2e scalability tests will catch controllers that are *actually* slow.
	if err := wait.Poll(time.Second, longTestTimeout, client.ControllerHasDesiredReplicas(c, updated)); err != nil {
		glog.Fatalf("FAILED: pods never created %v", err)
	}
	glog.Infof("Done creating replicas, took %v", time.Since(t))
	t = time.Now()

	// Poll till we can retrieve the status of all pods matching the given label selector from their nodes.
	// This involves 3 operations:
	//	- The scheduler must assign all pods to a node
	//	- The assignment must reflect in a `List` operation against the apiserver, for labels matching the selector
	//  - We need to be able to query the kubelet on that node for information about the pod
	if err := wait.Poll(
		time.Second, longTestTimeout, podsOnNodes(c, "test", labels.Set(updated.Spec.Selector).AsSelector())); err != nil {
		glog.Fatalf("FAILED: pods never started running %v", err)
	}

	glog.Infof("Pods verified on nodes, took %v", time.Since(t))
}

func runAPIVersionsTest(c *client.Client) {
	g, err := c.ServerGroups()
	clientVersion := c.APIVersion().String()
	if err != nil {
		glog.Fatalf("Failed to get api versions: %v", err)
	}
	versions := client.ExtractGroupVersions(g)

	// Verify that the server supports the API version used by the client.
	for _, version := range versions {
		if version == clientVersion {
			glog.Infof("Version test passed")
			return
		}
	}
	glog.Fatalf("Server does not support APIVersion used by client. Server supported APIVersions: '%v', client APIVersion: '%v'", versions, clientVersion)
}

func runSelfLinkTestOnNamespace(c *client.Client, namespace string) {
	svcBody := api.Service{
		ObjectMeta: api.ObjectMeta{
			Name:      "selflinktest",
			Namespace: namespace,
			Labels: map[string]string{
				"name": "selflinktest",
			},
		},
		Spec: api.ServiceSpec{
			// This is here because validation requires it.
			Selector: map[string]string{
				"foo": "bar",
			},
			Ports: []api.ServicePort{{
				Port:     12345,
				Protocol: "TCP",
			}},
			SessionAffinity: "None",
		},
	}
	services := c.Services(namespace)
	svc, err := services.Create(&svcBody)
	if err != nil {
		glog.Fatalf("Failed creating selflinktest service: %v", err)
	}
	err = c.Get().RequestURI(svc.SelfLink).Do().Into(svc)
	if err != nil {
		glog.Fatalf("Failed listing service with supplied self link '%v': %v", svc.SelfLink, err)
	}

	svcList, err := services.List(api.ListOptions{})
	if err != nil {
		glog.Fatalf("Failed listing services: %v", err)
	}

	err = c.Get().RequestURI(svcList.SelfLink).Do().Into(svcList)
	if err != nil {
		glog.Fatalf("Failed listing services with supplied self link '%v': %v", svcList.SelfLink, err)
	}

	found := false
	for i := range svcList.Items {
		item := &svcList.Items[i]
		if item.Name != "selflinktest" {
			continue
		}
		found = true
		err = c.Get().RequestURI(item.SelfLink).Do().Into(svc)
		if err != nil {
			glog.Fatalf("Failed listing service with supplied self link '%v': %v", item.SelfLink, err)
		}
		break
	}
	if !found {
		glog.Fatalf("never found selflinktest service in namespace %s", namespace)
	}
	glog.Infof("Self link test passed in namespace %s", namespace)

	// TODO: Should test PUT at some point, too.
}

func runAtomicPutTest(c *client.Client) {
	svcBody := api.Service{
		TypeMeta: unversioned.TypeMeta{
			APIVersion: c.APIVersion().String(),
		},
		ObjectMeta: api.ObjectMeta{
			Name: "atomicservice",
			Labels: map[string]string{
				"name": "atomicService",
			},
		},
		Spec: api.ServiceSpec{
			// This is here because validation requires it.
			Selector: map[string]string{
				"foo": "bar",
			},
			Ports: []api.ServicePort{{
				Port:     12345,
				Protocol: "TCP",
			}},
			SessionAffinity: "None",
		},
	}
	services := c.Services(api.NamespaceDefault)
	svc, err := services.Create(&svcBody)
	if err != nil {
		glog.Fatalf("Failed creating atomicService: %v", err)
	}
	glog.Info("Created atomicService")
	testLabels := labels.Set{
		"foo": "bar",
	}
	for i := 0; i < 5; i++ {
		// a: z, b: y, etc...
		testLabels[string([]byte{byte('a' + i)})] = string([]byte{byte('z' - i)})
	}
	var wg sync.WaitGroup
	wg.Add(len(testLabels))
	for label, value := range testLabels {
		go func(l, v string) {
			for {
				glog.Infof("Starting to update (%s, %s)", l, v)
				tmpSvc, err := services.Get(svc.Name)
				if err != nil {
					glog.Errorf("Error getting atomicService: %v", err)
					continue
				}
				if tmpSvc.Spec.Selector == nil {
					tmpSvc.Spec.Selector = map[string]string{l: v}
				} else {
					tmpSvc.Spec.Selector[l] = v
				}
				glog.Infof("Posting update (%s, %s)", l, v)
				tmpSvc, err = services.Update(tmpSvc)
				if err != nil {
					if apierrors.IsConflict(err) {
						glog.Infof("Conflict: (%s, %s)", l, v)
						// This is what we expect.
						continue
					}
					glog.Errorf("Unexpected error putting atomicService: %v", err)
					continue
				}
				break
			}
			glog.Infof("Done update (%s, %s)", l, v)
			wg.Done()
		}(label, value)
	}
	wg.Wait()
	svc, err = services.Get(svc.Name)
	if err != nil {
		glog.Fatalf("Failed getting atomicService after writers are complete: %v", err)
	}
	if !reflect.DeepEqual(testLabels, labels.Set(svc.Spec.Selector)) {
		glog.Fatalf("Selector PUTs were not atomic: wanted %v, got %v", testLabels, svc.Spec.Selector)
	}
	glog.Info("Atomic PUTs work.")
}

func runPatchTest(c *client.Client) {
	name := "patchservice"
	resource := "services"
	svcBody := api.Service{
		TypeMeta: unversioned.TypeMeta{
			APIVersion: c.APIVersion().String(),
		},
		ObjectMeta: api.ObjectMeta{
			Name:   name,
			Labels: map[string]string{},
		},
		Spec: api.ServiceSpec{
			// This is here because validation requires it.
			Selector: map[string]string{
				"foo": "bar",
			},
			Ports: []api.ServicePort{{
				Port:     12345,
				Protocol: "TCP",
			}},
			SessionAffinity: "None",
		},
	}
	services := c.Services(api.NamespaceDefault)
	svc, err := services.Create(&svcBody)
	if err != nil {
		glog.Fatalf("Failed creating patchservice: %v", err)
	}

	patchBodies := map[unversioned.GroupVersion]map[api.PatchType]struct {
		AddLabelBody        []byte
		RemoveLabelBody     []byte
		RemoveAllLabelsBody []byte
	}{
		v1.SchemeGroupVersion: {
			api.JSONPatchType: {
				[]byte(`[{"op":"add","path":"/metadata/labels","value":{"foo":"bar","baz":"qux"}}]`),
				[]byte(`[{"op":"remove","path":"/metadata/labels/foo"}]`),
				[]byte(`[{"op":"remove","path":"/metadata/labels"}]`),
			},
			api.MergePatchType: {
				[]byte(`{"metadata":{"labels":{"foo":"bar","baz":"qux"}}}`),
				[]byte(`{"metadata":{"labels":{"foo":null}}}`),
				[]byte(`{"metadata":{"labels":null}}`),
			},
			api.StrategicMergePatchType: {
				[]byte(`{"metadata":{"labels":{"foo":"bar","baz":"qux"}}}`),
				[]byte(`{"metadata":{"labels":{"foo":null}}}`),
				[]byte(`{"metadata":{"labels":{"$patch":"replace"}}}`),
			},
		},
	}

	pb := patchBodies[c.APIVersion()]

	execPatch := func(pt api.PatchType, body []byte) error {
		return c.Patch(pt).
			Resource(resource).
			Namespace(api.NamespaceDefault).
			Name(name).
			Body(body).
			Do().
			Error()
	}
	for k, v := range pb {
		// add label
		err := execPatch(k, v.AddLabelBody)
		if err != nil {
			glog.Fatalf("Failed updating patchservice with patch type %s: %v", k, err)
		}
		svc, err = services.Get(name)
		if err != nil {
			glog.Fatalf("Failed getting patchservice: %v", err)
		}
		if len(svc.Labels) != 2 || svc.Labels["foo"] != "bar" || svc.Labels["baz"] != "qux" {
			glog.Fatalf("Failed updating patchservice with patch type %s: labels are: %v", k, svc.Labels)
		}

		// remove one label
		err = execPatch(k, v.RemoveLabelBody)
		if err != nil {
			glog.Fatalf("Failed updating patchservice with patch type %s: %v", k, err)
		}
		svc, err = services.Get(name)
		if err != nil {
			glog.Fatalf("Failed getting patchservice: %v", err)
		}
		if len(svc.Labels) != 1 || svc.Labels["baz"] != "qux" {
			glog.Fatalf("Failed updating patchservice with patch type %s: labels are: %v", k, svc.Labels)
		}

		// remove all labels
		err = execPatch(k, v.RemoveAllLabelsBody)
		if err != nil {
			glog.Fatalf("Failed updating patchservice with patch type %s: %v", k, err)
		}
		svc, err = services.Get(name)
		if err != nil {
			glog.Fatalf("Failed getting patchservice: %v", err)
		}
		if svc.Labels != nil {
			glog.Fatalf("Failed remove all labels from patchservice with patch type %s: %v", k, svc.Labels)
		}
	}

	glog.Info("PATCHs work.")
}

func runMasterServiceTest(client *client.Client) {
	time.Sleep(12 * time.Second)
	svcList, err := client.Services(api.NamespaceDefault).List(api.ListOptions{})
	if err != nil {
		glog.Fatalf("Unexpected error listing services: %v", err)
	}
	var foundRW bool
	found := sets.String{}
	for i := range svcList.Items {
		found.Insert(svcList.Items[i].Name)
		if svcList.Items[i].Name == "kubernetes" {
			foundRW = true
		}
	}
	if foundRW {
		ep, err := client.Endpoints(api.NamespaceDefault).Get("kubernetes")
		if err != nil {
			glog.Fatalf("Unexpected error listing endpoints for kubernetes service: %v", err)
		}
		if countEndpoints(ep) == 0 {
			glog.Fatalf("No endpoints for kubernetes service: %v", ep)
		}
	} else {
		glog.Errorf("No RW service found: %v", found)
		glog.Fatal("Kubernetes service test failed")
	}
	glog.Infof("Master service test passed.")
}

func runServiceTest(client *client.Client) {
	pod := &api.Pod{
		ObjectMeta: api.ObjectMeta{
			Name: "foo",
			Labels: map[string]string{
				"name": "thisisalonglabel",
			},
		},
		Spec: api.PodSpec{
			Containers: []api.Container{
				{
					Name:  "c1",
					Image: "foo",
					Ports: []api.ContainerPort{
						{ContainerPort: 1234},
					},
					ImagePullPolicy: api.PullIfNotPresent,
				},
			},
			RestartPolicy: api.RestartPolicyAlways,
			DNSPolicy:     api.DNSClusterFirst,
		},
		Status: api.PodStatus{
			PodIP: "1.2.3.4",
		},
	}
	pod, err := client.Pods(api.NamespaceDefault).Create(pod)
	if err != nil {
		glog.Fatalf("Failed to create pod: %v, %v", pod, err)
	}
	if err := wait.Poll(time.Second, longTestTimeout, podExists(client, pod.Namespace, pod.Name)); err != nil {
		glog.Fatalf("FAILED: pod never started running %v", err)
	}
	svc1 := &api.Service{
		ObjectMeta: api.ObjectMeta{Name: "service1"},
		Spec: api.ServiceSpec{
			Selector: map[string]string{
				"name": "thisisalonglabel",
			},
			Ports: []api.ServicePort{{
				Port:     8080,
				Protocol: "TCP",
			}},
			SessionAffinity: "None",
		},
	}
	svc1, err = client.Services(api.NamespaceDefault).Create(svc1)
	if err != nil {
		glog.Fatalf("Failed to create service: %v, %v", svc1, err)
	}

	// create an identical service in the non-default namespace
	svc3 := &api.Service{
		ObjectMeta: api.ObjectMeta{Name: "service1"},
		Spec: api.ServiceSpec{
			Selector: map[string]string{
				"name": "thisisalonglabel",
			},
			Ports: []api.ServicePort{{
				Port:     8080,
				Protocol: "TCP",
			}},
			SessionAffinity: "None",
		},
	}
	svc3, err = client.Services("other").Create(svc3)
	if err != nil {
		glog.Fatalf("Failed to create service: %v, %v", svc3, err)
	}

	// TODO Reduce the timeouts in this test when endpoints controller is sped up. See #6045.
	if err := wait.Poll(time.Second, longTestTimeout, endpointsSet(client, svc1.Namespace, svc1.Name, 1)); err != nil {
		glog.Fatalf("FAILED: unexpected endpoints: %v", err)
	}
	// A second service with the same port.
	svc2 := &api.Service{
		ObjectMeta: api.ObjectMeta{Name: "service2"},
		Spec: api.ServiceSpec{
			Selector: map[string]string{
				"name": "thisisalonglabel",
			},
			Ports: []api.ServicePort{{
				Port:     8080,
				Protocol: "TCP",
			}},
			SessionAffinity: "None",
		},
	}
	svc2, err = client.Services(api.NamespaceDefault).Create(svc2)
	if err != nil {
		glog.Fatalf("Failed to create service: %v, %v", svc2, err)
	}
	if err := wait.Poll(time.Second, longTestTimeout, endpointsSet(client, svc2.Namespace, svc2.Name, 1)); err != nil {
		glog.Fatalf("FAILED: unexpected endpoints: %v", err)
	}

	if err := wait.Poll(time.Second, longTestTimeout, endpointsSet(client, svc3.Namespace, svc3.Name, 0)); err != nil {
		glog.Fatalf("FAILED: service in other namespace should have no endpoints: %v", err)
	}

	svcList, err := client.Services(api.NamespaceAll).List(api.ListOptions{})
	if err != nil {
		glog.Fatalf("Failed to list services across namespaces: %v", err)
	}
	names := sets.NewString()
	for _, svc := range svcList.Items {
		names.Insert(fmt.Sprintf("%s/%s", svc.Namespace, svc.Name))
	}
	if !names.HasAll("default/kubernetes", "default/service1", "default/service2", "other/service1") {
		glog.Fatalf("Unexpected service list: %#v", names)
	}

	glog.Info("Service test passed.")
}

func runSchedulerNoPhantomPodsTest(client *client.Client) {
	pod := &api.Pod{
		Spec: api.PodSpec{
			Containers: []api.Container{
				{
					Name:  "c1",
					Image: "kubernetes/pause",
					Ports: []api.ContainerPort{
						{ContainerPort: 1234, HostPort: 9999},
					},
					ImagePullPolicy: api.PullIfNotPresent,
				},
			},
		},
	}

	// Assuming we only have two kublets, the third pod here won't schedule
	// if the scheduler doesn't correctly handle the delete for the second
	// pod.
	pod.ObjectMeta.Name = "phantom.foo"
	foo, err := client.Pods(api.NamespaceDefault).Create(pod)
	if err != nil {
		glog.Fatalf("Failed to create pod: %v, %v", pod, err)
	}
	if err := wait.Poll(time.Second, longTestTimeout, podRunning(client, foo.Namespace, foo.Name)); err != nil {
		glog.Fatalf("FAILED: pod never started running %v", err)
	}

	pod.ObjectMeta.Name = "phantom.bar"
	bar, err := client.Pods(api.NamespaceDefault).Create(pod)
	if err != nil {
		glog.Fatalf("Failed to create pod: %v, %v", pod, err)
	}
	if err := wait.Poll(time.Second, longTestTimeout, podRunning(client, bar.Namespace, bar.Name)); err != nil {
		glog.Fatalf("FAILED: pod never started running %v", err)
	}

	// Delete a pod to free up room.
	glog.Infof("Deleting pod %v", bar.Name)
	err = client.Pods(api.NamespaceDefault).Delete(bar.Name, api.NewDeleteOptions(0))
	if err != nil {
		glog.Fatalf("FAILED: couldn't delete pod %q: %v", bar.Name, err)
	}

	pod.ObjectMeta.Name = "phantom.baz"
	baz, err := client.Pods(api.NamespaceDefault).Create(pod)
	if err != nil {
		glog.Fatalf("Failed to create pod: %v, %v", pod, err)
	}
	if err := wait.Poll(time.Second, longTestTimeout, podRunning(client, baz.Namespace, baz.Name)); err != nil {
		if pod, perr := client.Pods(api.NamespaceDefault).Get("phantom.bar"); perr == nil {
			glog.Fatalf("FAILED: 'phantom.bar' was never deleted: %#v, err: %v", pod, err)
		} else {
			glog.Fatalf("FAILED: (Scheduler probably didn't process deletion of 'phantom.bar') Pod never started running: err: %v, perr: %v", err, perr)
		}
	}

	glog.Info("Scheduler doesn't make phantom pods: test passed.")
}

type testFunc func(*client.Client)

func addFlags(fs *pflag.FlagSet) {
	fs.IntVar(
		&maxConcurrency, "max-concurrency", -1, "Maximum number of tests to be run simultaneously. Unlimited if set to negative.")
}

func main() {
	gruntime.GOMAXPROCS(gruntime.NumCPU())
	addFlags(pflag.CommandLine)

	util.InitFlags()
	util.ReallyCrash = true
	util.InitLogs()
	defer util.FlushLogs()

	go func() {
		defer util.FlushLogs()
		time.Sleep(maxTestTimeout)
		glog.Fatalf("This test has timed out.")
	}()

	glog.Infof("Running tests for APIVersion: %s", os.Getenv("KUBE_TEST_API"))

	firstManifestURL := ServeCachedManifestFile(testPodSpecFile)
	secondManifestURL := ServeCachedManifestFile(testPodSpecFile)
	apiServerURL, _ := startComponents(firstManifestURL, secondManifestURL)

	// Ok. we're good to go.
	glog.Infof("API Server started on %s", apiServerURL)
	// Wait for the synchronization threads to come up.
	time.Sleep(time.Second * 10)

	kubeClient := client.NewOrDie(&client.Config{Host: apiServerURL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}})
	// TODO: caesarxuchao: hacky way to specify version of Experimental client.
	// We will fix this by supporting multiple group versions in Config
	kubeClient.ExtensionsClient = client.NewExtensionsOrDie(&client.Config{Host: apiServerURL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Extensions.GroupVersion()}})

	// Run tests in parallel
	testFuncs := []testFunc{
		runReplicationControllerTest,
		runAtomicPutTest,
		runPatchTest,
		runServiceTest,
		runAPIVersionsTest,
		runMasterServiceTest,
		func(c *client.Client) {
			runSelfLinkTestOnNamespace(c, api.NamespaceDefault)
			runSelfLinkTestOnNamespace(c, "other")
		},
	}

	// Only run at most maxConcurrency tests in parallel.
	if maxConcurrency <= 0 {
		maxConcurrency = len(testFuncs)
	}
	glog.Infof("Running %d tests in parallel.", maxConcurrency)
	ch := make(chan struct{}, maxConcurrency)

	var wg sync.WaitGroup
	wg.Add(len(testFuncs))
	for i := range testFuncs {
		f := testFuncs[i]
		go func() {
			ch <- struct{}{}
			f(kubeClient)
			<-ch
			wg.Done()
		}()
	}
	wg.Wait()
	close(ch)

	// Check that kubelet tried to make the containers.
	// Using a set to list unique creation attempts. Our fake is
	// really stupid, so kubelet tries to create these multiple times.
	createdConts := sets.String{}
	for _, p := range fakeDocker1.Created {
		// The last 8 characters are random, so slice them off.
		if n := len(p); n > 8 {
			createdConts.Insert(p[:n-8])
		}
	}
	for _, p := range fakeDocker2.Created {
		// The last 8 characters are random, so slice them off.
		if n := len(p); n > 8 {
			createdConts.Insert(p[:n-8])
		}
	}
	// We expect 9: 2 pod infra containers + 2 containers from the replication controller +
	//              1 pod infra container + 2 containers from the URL on first Kubelet +
	//              1 pod infra container + 2 containers from the URL on second Kubelet +
	//              1 pod infra container + 1 container from the service test.
	// The total number of container created is 9

	if len(createdConts) != 12 {
		glog.Fatalf("Expected 12 containers; got %v\n\nlist of created containers:\n\n%#v\n\nDocker 1 Created:\n\n%#v\n\nDocker 2 Created:\n\n%#v\n\n", len(createdConts), createdConts.List(), fakeDocker1.Created, fakeDocker2.Created)
	}
	glog.Infof("OK - found created containers: %#v", createdConts.List())

	// This test doesn't run with the others because it can't run in
	// parallel and also it schedules extra pods which would change the
	// above pod counting logic.
	runSchedulerNoPhantomPodsTest(kubeClient)

	glog.Infof("\n\nLogging high latency metrics from the 10250 kubelet")
	e2e.HighLatencyKubeletOperations(nil, 1*time.Second, "localhost:10250")
	glog.Infof("\n\nLogging high latency metrics from the 10251 kubelet")
	e2e.HighLatencyKubeletOperations(nil, 1*time.Second, "localhost:10251")
}

// ServeCachedManifestFile serves a file for kubelet to read.
func ServeCachedManifestFile(contents string) (servingAddress string) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/manifest" {
			w.Write([]byte(contents))
			return
		}
		glog.Fatalf("Got request: %#v\n", r)
		http.NotFound(w, r)
	}))
	return server.URL + "/manifest"
}

const (
	testPodSpecFile = `{
		"kind": "Pod",
		"apiVersion": "v1",
		"metadata": {
			"name": "container-vm-guestbook-pod-spec"
		},
		"spec": {
			"containers": [
				{
					"name": "redis",
					"image": "redis",
					"volumeMounts": [{
						"name": "redis-data",
						"mountPath": "/data"
					}]
				},
				{
					"name": "guestbook",
					"image": "google/guestbook-python-redis",
					"ports": [{
						"name": "www",
						"hostPort": 80,
						"containerPort": 80
					}]
				}],
			"volumes": [{	"name": "redis-data" }]
		}
	}`
)


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

#include "azure_c_shared_utility/gballoc.h"

#include "dataserializer.h"
#include "azure_c_shared_utility/xlogging.h"

DEFINE_ENUM_STRINGS(DATA_SERIALIZER_RESULT, DATA_SERIALIZER_RESULT_VALUES);

BUFFER_HANDLE DataSerializer_Encode(MULTITREE_HANDLE multiTreeHandle, DATA_SERIALIZER_MULTITREE_TYPE dataType, DATA_SERIALIZER_ENCODE_FUNC encodeFunc)
{
    BUFFER_HANDLE pBuffer;

    /* Codes_SRS_DATA_SERIALIZER_07_003: [NULL shall be returned when an invalid parameter is supplied.] */
    if (multiTreeHandle == NULL || encodeFunc == NULL)
    {
        pBuffer = NULL;
        LogError("(Error code: %s)", ENUM_TO_STRING(DATA_SERIALIZER_RESULT, DATA_SERIALIZER_INVALID_ARG) );
    }
    else
    {
        /* Codes_SRS_DATA_SERIALIZER_07_009: [DataSerializer_Encode function shall call into the given DATA_SERIALIZER_ENCODE_FUNC callback with a valid BUFFER object and valid MULTITREE_HANDLE object.] */
        pBuffer = encodeFunc(multiTreeHandle, dataType);
        if (pBuffer == NULL)
        {
            /* Codes_SRS_DATA_SERIALIZER_07_010: [Upon a DATA_SERIALIZER_ENCODE_FUNC failure the DataSerializer_Encode function shall return NULL.] */
            LogError("(Error code: %s)", ENUM_TO_STRING(DATA_SERIALIZER_RESULT, DATA_SERIALIZER_ERROR) );
        }
    }
    /* Codes_SRS_DATA_SERIALIZER_07_002: [DataSerializer_Encode shall return a valid BUFFER_HANDLE when the function executes successfully.] */
    return pBuffer;
}

MULTITREE_HANDLE DataSerializer_Decode(BUFFER_HANDLE data, DATA_SERIALIZER_DECODE_FUNC decodeFunc)
{
    MULTITREE_HANDLE multiTreeHandle;

    /* Codes_SRS_DATA_SERIALIZER_07_007: [NULL shall be returned when an invalid parameter is supplied.] */
    if (data == NULL || decodeFunc == NULL)
    {
        multiTreeHandle = NULL;
        LogError("(Error code: %s)", ENUM_TO_STRING(DATA_SERIALIZER_RESULT, DATA_SERIALIZER_INVALID_ARG) );
    }
    else
    {
        /* Codes_SRS_DATA_SERIALIZER_07_012: [DataSerializer_Decode function shall call into the given DATA_SERIALIZER_DECODE_FUNC callback with a valid BUFFER object and valid MULTITREE_HANDLE object.] */
        multiTreeHandle = decodeFunc(data);
        if (multiTreeHandle == NULL)
        {
            /* Codes_SRS_DATA_SERIALIZER_07_013: [Upon a DATA_SERIALIZER_DECODE_FUNC callback failure the DataSerializer_Encode function Shall return NULL.] */
            LogError("(Error code: %s)", ENUM_TO_STRING(DATA_SERIALIZER_RESULT, DATA_SERIALIZER_ERROR) );
        }
    }

    /* Codes_SRS_DATA_SERIALIZER_07_006: [DataSerializer_Decode shall return a valid MULTITREE_HANDLE when the function executes successfully.] */
    return multiTreeHandle;
}


text: export { default as default } from './src/axis-chart';


text:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string description="Accessibility description for a control that allows the user to close the current screen          and go back to the previous one." name="close_and_go_back">关闭并返回</string>

    <string description="Accessibility for the links to the G+ or Twitter pages for speakers. For example: Go to the Twitter page for Sally Sample." name="speaker_social_page">转至%2$s的%1$s页面</string>

    <string description="Accessibility description for the GPlus icon in the '#io15' box." name="social_io15_gplus_content_description">转到含有io15井号标签的Google Plus页面</string>

    <string description="Accessibility description for the Twitter icon in the '#io15' box." name="social_io15_twitter_content_description">转到含有io15井号标签的Twitter页面</string>

    <string description="Accessibility description for link to the 'Google Developers' GPlus page." name="social_gplus_devs_content_description">转到Google Developers的Google Plus页面</string>

    <string description="Accessibility description for link to the 'Google Developers' Twitter page." name="social_twitter_devs_content_description">转到Google Developers的Twitter页面</string>

    <string description="Accessibility description for the GPlus icon in the '#io15 extended' box." name="social_extended_gplus_content_description">转到含有远程井号标签的Google Plus页面</string>

    <string description="Accessibility description for the Twitter icon in the '#io15 extended' box." name="social_extended_twitter_content_description">转到含有远程井号标签的Twitter页面</string>

    <string descripton="Accessibility description for the GPlus icon in the '#io15 request' box." name="social_request_gplus_content_description">转到含有请求井号标签的Google Plus页面</string>

    <string description="Accessibility description for the Twitter icon in the '#io15 extended' box." name="social_request_twitter_content_description">转到含有请求伸井号标签的Twitter页面</string>

    <string description="Accessibility description for the IO15 logo that is not a link." name="io15_logo_not_clickable">IO15标志不可点击</string>

    <string description="Accessibility description for the IO15 extended logo that is not a link." name="io15_extended_logo_not_clickable">IO15远程标志不可点击</string>

    <string description="Accessibility description for the IO15 request logo that is not a link." name="io15_request_logo_not_clickable">IO15请求标志不可点击</string>

    <string description="Accessibility description for the I/O logo that is not a link." name="io_logo_not_clickable">IO标志不可点击</string>

    <string description="Accessibility description for viewing more sessions/videos." name="more_items_button_desc_a11y">点击可显示更多内容。</string>

    <string name="pref_conf_message_cards_enabled_description"
            description="Description in the Settings screen for the setting that enables display of
            cards with conference information in the explore screen.">在"探索"界面显示会议信息。此信息即时显示,并可能包含来自合作伙伴的商业推广。</string>

    <string descripton="Text of a card shown in the Explore I/O screen that asks the user if they want to configure          the conference WiFi. 'Not now' and 'Yes, please' are options show on the card" name="question_setup_wifi_card_text"><b>大会Wi-Fi</b><br/>您想设置设备以使用大会Wi-Fi吗?</string>

    <string description="A session feedback section label asking the user to rate the session overall" name="session_rating_label_text">环节评级:</string>

    <string descripton="Session feedback section title" name="session_feedback_content_label_text">根据描述/我的期望,内容是:</string>

    <string description="A negative relevance session feedback option" name="session_feedback_not_at_all_relevant">一点也不</string>

    <string description="A negative relevance session feedback option" name="session_feedback_extremely_relevant">非常不好</string>

    <string description="Text for a button which allows the user to enable the feature" name="welcome_enable">启用</string>

    <string description="Text for a button which allows the user to reject the feature" name="welcome_no_thanks">不,谢谢</string>

    <string description="Medium-length welcome text indicating the subsequent text is important legal information " name="welcome_text">在我们开始之前,这里提供与您使用这款应用程序有关的一些重要法律资料。只需要一分钟!</string>

    <string description="Short text asking if they're interested in what's around them" name="welcome_around">您周围</string>

    <string description="Short text asking them to select an account" name="welcome_select_account">选择一个帐户</string>

    <string description="Medium text asking to choose an account from a list" name="welcome_select_accoun_text">请选择要使用的帐户:</string>

    <string name="explore_sessions_show_day_hour_and_room"
            description="Sub-title for a session in ExploreSessionsActivity that shows the day, time and room name for a given session. Example: Day 1 / 9:00AM - 11:00AM / Room 1" ><xliff:g example="Day 1" id="day">%1$s</xliff:g> / <xliff:g example="2:00PM" id="start_time">%2$s</xliff:g> - <xliff:g example="3:00PM" id="end_time">%3$s</xliff:g> / <xliff:g id="room">%4$s</xliff:g></string>

    <string description="Show the Day 1 or Day 2 as part of either the ExploreSessionsActivity title or          in the session details." name="explore_sessions_show_day_n">第%d天</string>

    <string description="Show Day and start time of a session as the title when viewing browsing sessions          (ExploreSessionActivity) from MySchedule." name="explore_sessions_time_slot_title">
    <xliff:g example="Day 1" id="day">%1$s</xliff:g>,<xliff:g example="2:30PM" id="start_time">%2$s</xliff:g>
  </string>

    <string name="explore_io_msgcards_ask_opt_in"
            description="This message is displayed on the Explore I/O screen to ask users whether
            they would like to opt in to receive messages regarding the conference."><![CDATA[
        会议提示消息

        您是否愿意收到有关会议的重要提示消息?此消息即时推送,并可能包含来自合作伙伴的商业推广。]]></string>

    <string name="explore_io_msgcards_conf_creds_card"><b>大会证件</b>
        <br>今年,每名与会者将收到一条不可转让的NFC功能腕带。您凭借腕带和I/O徽章即可参加主题演讲、会议、沙盒和会后聚会。请记住,请随时佩戴。</string>

    <string description="A message card displayed in the Explore I/O page that asks users to opt into a                          feature." name="explore_io_msgcards_after_hours_card"><b>会后聚会</b><br></br>这是你不想错过的一次聚会!欢迎与会者在5月28日晚上前往享受美食、饮品、音乐游戏以及其他更多内容。与会者需佩戴大会徽章和NFC腕带方可进入。</string>

    <string description="This string is presented to users when they attempt to click something that indicates they          can watch a video but it turns out we can't show the video." name="explore_io_video_id_not_valid">很抱歉,视频网址似乎有问题。</string>

    <string description="Generic error message used for errors that should never happen. This explains to the user          that we can't execute the request when they click a button or touch a part of the screen          that should normally be touchable." name="unknown_error">哎呦,我们无法处理该请求。</string>

    <string description="Label of filter option that allow to display all elements" name="all">全部</string>

    <string description="Indicates the item is actionable and the user can tap on it" name="talkback_button">%1$S按钮</string>

    <string description="Indicates the item does nothing when tapped" name="talkback_not_clickable">%1$S不可点击</string>

    <string description="Indicates the item is an image" name="talkback_image">%1$S图像</string>

    <string description="Indicates the item is a link (and actionable)" name="talkback_link">%1$S链接</string>

    <string descripton="Indicates the item is currently selected" name="talkback_selected">%1$S已选</string>

    <string description="Indicates the item is currently not selected" name="talkback_not_selected">%1$S未选</string>

    <string description="Indicates what happens when the user taps on an item" name="talkback_tapfor">点击即可%1$S</string>

    <string descripton="This string is the title of a notification shown to the user when Google Play         services can't connect." name="app_data_notification_resolution_title">I/O应用程序需要权限</string>

    <string description="This string is the message of the notification shown to the user when Google Play services          can't connect from a background sync." name="app_data_notification_resolution_content">I/O应用程序需要完成后台同步。</string>

    <string description="Shown as the titles of the tabs for the user's schedule" name="day_n">第%d天</string>

    <string description="Session feedback section title" name="session_feedback_content">内容为:</string>

    <string description="A positive overall session feedback option" name="session_feedback_great">很好</string>

    <string description="A negative overall session feedback option" name="session_feedback_notgreat">不好</string>

    <string description="A negative relevance session feedback option" name="session_feedback_notrel">不相关</string>

    <string description="A session feedback section label asking for any other feedback. It indicates the user should not add personal information" name="session_feedback_other">还有什么想告诉我们吗?\n(请不要在您的评论中添加任何个人信息。)</string>

    <string description="A positive speaker quality session feedback option" name="session_feedback_outstanding">优秀</string>

    <string description="A negative speaker quality session feedback option" name="session_feedback_poor">很差</string>

    <string description="A positive relevance session feedback option" name="session_feedback_rel">相关</string>

    <string description="Hint for adding other session feedback" name="session_feedback_tell_us">请告诉我们!</string>

     <string name="session_live_streamed">直播流</string>

     <string name="session_watch_live">观看直播</string>

     <string name="session_watch">观看</string>

     <string name="session_replay">重播</string>

     <string name="keynote_group_title">主题演讲</string>

     <string name="more_items_button">更多</string>

     <string name="my_schedule_rate_this_session">评价本环节</string>

     <string name="my_schedule_watch_live_now">立即观看直播</string>

     <string name="navdrawer_description_a11y">用于切换应用程序主要功能的导航菜单</string>

     <string name="navdrawer_item_io_live">I/O直播</string>
     <string name="navdrawer_item_video_library">视频</string>

     <string name="navdrawer_item_debug">调试</string>

     <string name="new_videos_title">
    <xliff:g id="year">%1$d</xliff:g>年度视频</string>

     <string name="pref_conf_message_cards_enabled_title">显示会议提示消息</string>

     <string name="schedule_session_subtitle">
    <xliff:g id="speakers">%1$s</xliff:g>\n<xliff:g id="room">%2$s</xliff:g>
  </string>
     <string name="title_video_library">视频</string>

     <string name="welcome_conduct_title">I/O社区最佳实践</string>

     <string name="welcome_attending">亲临现场?</string>

     <string name="welcome_attending_text">你是远程参与I/O还是亲临旧金山大会现场?</string>

     <string name="title_topic_filtered_video_library">有关<xliff:g id="topic">%1$s</xliff:g>的视频</string>

     <string name="title_year_filtered_video_library">
    <xliff:g id="year">%1$d</xliff:g>年的视频</string>

     <string name="title_year_and_topic_filtered_video_library">
    <xliff:g id="year">%1$d</xliff:g>年的视频,主题为<xliff:g id="topic">%2$s</xliff:g>
  </string>

     <string name="description_filter">筛选</string>

     <string name="title_video_library_filter">筛选</string>

     <string name="year_filter_section_label">年</string>

     <string name="topic_filter_section_label">主题</string>

     <string name="title_activity_new_social">社交</string>

     <string name="title_explore_sessions_filter">筛选</string>

     <string name="explore_io_msgcards_answer_yes">当然,我们开始吧!</string>

     <string name="explore_io_msgcards_answer_no">不,谢谢。</string>

    <plurals name="schedule_block_subtitle">
    <item quantity="other">
      <xliff:g id="number_of_sessions">%1$d</xliff:g>可供参与的会议</item>
  </plurals>

    <plurals name="session_notification_text">
    <item quantity="other">同时,其余<xliff:g id="num_sessions">%2$d</xliff:g>在<xliff:g id="remaining_time">%1$d</xliff:g>分钟后开始。</item>
  </plurals>

    <plurals name="session_notification_ticker">
    <item quantity="other">%d会议即将开始。</item>
  </plurals>

    <plurals name="session_notification_title">
    <item quantity="other">
      <xliff:g id="num_sessions">%2$d</xliff:g>会议在<xliff:g id="remaining_time">%1$d</xliff:g>分钟后开始。</item>
  </plurals>

    <string name="about_body"><b>Google  I/O 2015 </b><br>版本%s <br><br>
        <a href=http://m.google.com/utos> 服务条款</a><br><br> <a href=http://www.google.com/policies/privacy/>隐私政策</ a></string>

    <string name="about_eula">最终用户许可协议</string>

    <string name="about_licenses">开源许可证</string>

    <string name="accept">接受</string>

    <string name="add_account">添加帐户</string>

    <string name="add_to_schedule">添加到日程表</string>

    <string name="add_to_schedule_desc">用于添加会议到你的日程表的按钮</string>

    <string name="all_sessions">所有会议</string>

    <string name="all_themes">所有主题</string>

    <string name="all_topics">所有标题</string>

    <string name="all_types">所有类型</string>

    <string name="all_years">所有年份</string>

    <string name="app_name">JJ Camera</string>

    <string name="attending_in_person">亲自</string>

    <string name="attending_remotely">远程地</string>

    <string name="browse_events">浏览活动</string>

    <string name="browse_sessions">浏览会议...</string>

    <string name="calltoaction_wifi_configure"><br><br>点选"新增Wi-Fi网络"以继续。</string>

    <string name="calltoaction_wifi_settings"><br><br>点击\'打开Wi-Fi设置"以启用Wi-Fi。</string>

    <string name="close_detail_pane">关闭详情页面</string>

    <string name="cancel">取消</string>

    <string name="data_stale_warning">你正在看的数据可能已过时。</string>

    <string name="day_title_today">今天</string>

    <string name="day_title_tomorrow">明天</string>

    <string name="day_title_yesterday">昨天</string>

    <string name="decline">拒绝</string>

    <string name="description_about">关于</string>

    <string name="description_add_schedule">添加到日程表</string>

    <string name="description_app_feedback">应用程序反馈</string>

    <string name="description_app_feedback_old">反馈</string>

    <string name="description_captions">字幕</string>

    <string name="description_configure_wifi">配置Wi-Fi</string>

    <string name="description_i_o_extended"> I/O Extended</string>

    <string name="description_map">地图</string>

    <string name="description_presentation">切换屏幕输出</string>

    <string name="description_refresh">刷新</string>

    <string name="description_remove_schedule">从日程表中删除</string>

    <string name="description_search">搜索</string>

    <string name="description_settings">设置</string>

    <string name="description_setup_wifi_body">既然你在会议现场,我们可以设置这台设备访问会议的(5Ghz)Wi-Fi网络。通过配置设备连接到此无线网络,会有效缓解网络阻塞</string>

    <string name="description_share">共享</string>

    <string name="description_social_stream">查看Google+的数据流</string>

    <string name="drawer_close">已关闭导航视图</string>

    <string name="drawer_open">已开启导航视图</string>

    <string name="empty_captions">没有找到本视频的字幕。</string>

    <string name="empty_session_detail">没有找到会议详情。</string>

    <string name="empty_sessions">没有找到会议。</string>

    <string name="empty_waiting_for_sync">等待同步...</string>

    <string name="empty_widget_text">没有更多即将举行的会议。\n明年见!</string>

    <string name="empty_widget_text_signed_out">点击上方的JJ Camera的图标,开始使用该应用程序。</string>

    <string name="ended_sessions">会议结束</string>

    <string name="give_feedback">是</string>

    <string name="google_account_required_message">要使用此应用程序,在您的设备上至少拥有一个Google帐户。</string>

    <string name="google_account_required_title">需要Google帐户</string>

    <string name="google_i_o_year">I/O <xliff:g id="year">%1$d</xliff:g>
  </string>

    <string name="got_it">知道了</string>

    <string name="live_available">现场直播</string>

    <string name="live_now">现场直播中</string>

    <string name="loading">加载中...</string>

    <string name="login_failed_text">由于一些问题,我们暂时无法加载你选择的演讲。</string>

    <string name="login_failed_text_retry">重试</string>

    <string name="mandatory_update_error">你的应用程序已过期。你必须升级以继续使用它。</string>

    <string name="update_available">Google Play上有这个应用程序的最新版本。</string>

    <string name="map_at">在%1$s:<br><b>%2$s</b></string>

    <string name="map_now_playing">现在播放:<br><b>%1$s</b></string>

    <string name="map_touch_to_see_session">点击屏幕即可看到会议</string>

    <string name="more_sessions">更多会议</string>

    <string name="my_schedule_tab_desc_a11y">点选以显示您为<xliff:g id="day">%1$s</xliff:g>的日程安排。</string>

    <string name="my_schedule_page_desc_a11y">现在显示你的<xliff:g id="day">%1$s</xliff:g>日的日程安排</string>

    <string name="navdrawer_item_explore">我的照相机</string>

    <string name="navdrawer_item_explore_a11y">探索Google I/O</string>

    <string name="navdrawer_item_map">地图</string>

    <string name="navdrawer_item_monitor">实况监视器</string>

    <string name="navdrawer_item_my_schedule">我的视频记录</string>

    <string name="navdrawer_item_settings">设置</string>

    <string name="navdrawer_item_sign_in">登录</string>

    <string name="navdrawer_item_social">社交</string>

    <string name="navdrawer_status_attending_in_person">亲自参加I/O</string>

    <string name="navdrawer_status_attending_remotely">远程参加I/O</string>

    <string name="no_connection_cant_login">无法登录,请检查您的网络连接。</string>

    <string name="no_matching_sessions">没有匹配的演讲。</string>

    <string name="no_matching_sessions_in_interval">在这个时段没有可参与的演讲。</string>

    <string name="no_matching_videos">没有匹配的视频。</string>

    <string name="no_thanks">不 , 谢谢,</string>

    <string name="not_now">现在不能</string>

    <string name="number_1">1</string>

    <string name="number_2">2</string>

    <string name="number_3">3</string>

    <string name="number_4">4</string>

    <string name="number_5">5</string>

    <string name="ok">确定</string>

    <string name="others">其它</string>

    <string name="permission_write">修改Google I/O 日程数据</string>

    <string name="plus_one_description_standard">点击屏幕以加一。</string>

    <string name="pref_analytics_enabled_title">发送匿名的统计信息</string>

    <string name="pref_analytics_enabled_description">如果选中,匿名的统计信息将被发送到Google。</string>

    <string name="pref_attendee_at_venue_description">如果勾选,所有的会议和现场活动将被显示。否则,只显示现场直播会议。</string>

    <string name="pref_attendee_at_venue_title">我会在Google I/O 大会!</string>

    <string name="pref_local_times_description">如果勾选,您的设备会显示设备所属地的本地时间。如果没有勾选,您的设备会显示PDT时间,也就是会议所在地的本地时间。</string>

    <string name="pref_local_times_title">显示本地时间</string>

    <string name="pref_notify_feedback_description">如果勾选,该应用程序会弹出通知,要求你对参加的会议进行评价。</string>

    <string name="pref_notify_feedback_title">请提醒我对我参加的会议进行评价</string>

    <string name="pref_notify_starred_sessions_description">如果勾选,当你选择的会议即将开始时,应用程序将显示一个通知。</string>

    <string name="pref_notify_starred_sessions_title">请通知我参加会议</string>

    <string name="pref_sync_with_calendar_description">如果勾选,你选择的会议将被自动同步到你的Google日历。</string>

    <string name="pref_sync_with_calendar_title">与Google日历同步</string>

    <string name="question_i_o_extended">你想知道更多关于在你的位置附近发生的 I/O Extended活动?</string>

    <string name="question_local_or_remote">你会远程或亲自在旧金山参加I/O吗?</string>

    <string name="related_videos">相关视频</string>

    <string name="remove_from_schedule">在日程表</string>

    <string name="remove_from_schedule_desc">点击按钮以从你的日程表中删除会议。</string>

    <string name="retry">重试</string>

    <string name="schedule_conflict_with_previous">(冲突)</string>

    <string name="schedule_end_time">至<xliff:g id="endTime">%1$s</xliff:g>
  </string>

    <string name="search_hint">搜索会议</string>

    <string name="search_label">Google I/O 会议</string>

    <string name="session_calendar_suffix"> - 由Google I/O 的Android应用程序附加</string>

    <string name="session_details_a11y_session_added">会议添加到你的日程</string>

    <string name="session_details_a11y_session_removed">会议从你的日程安排中删除</string>

    <string name="session_feedback_advanced">太早期</string>

    <string name="session_feedback_basic">太基础</string>

    <string name="session_feedback_notification_text">提供反馈,%1$s</string>

    <string name="session_feedback_notification_ticker">提供会议反馈</string>

    <string name="session_feedback_relevance">这个会议和你的项目多有关?</string>

    <string name="session_feedback_speaker_quality">发言人的质量:</string>

    <string name="session_feedback_submitlink">提交反馈</string>

    <string name="session_finished">已经结束</string>

    <string name="session_give_feedback_message">你觉得今天的演讲怎样?你想发送反馈吗?</string>

    <string name="session_link_livestream">观看直播</string>

    <string name="session_link_moderator">主持人</string>

    <string name="session_link_notes">官方备注</string>

    <string name="session_link_pdf">幻灯片</string>

    <string name="session_link_youtube">YouTube视频</string>

    <string name="session_links">更多</string>

    <string name="session_live_now_message">I/O正在直播!你想观看现场直播吗?</string>

    <string name="session_livestream_block">现场直播!</string>

    <string name="session_livestream_captions">字幕</string>

    <string name="session_livestream_error_init">对不起,初始化YouTube播放器(%1$s)时出现了错误</string>

    <string name="session_livestream_error_playback">对不起,加载现场直播时出现了错误,请稍后再试</string>

    <string name="session_livestream_info">信息</string>

    <string name="session_livestream_play_pause">播放/暂停</string>

    <string name="session_livestream_title"> I/O 现场直播</string>

    <string name="session_notification_text_1">在<xliff:g id="remaining_time">%1$d</xliff:g>分钟后开始。</string>

    <string name="session_now">现在</string>

    <string name="session_requirements">要求</string>

    <string name="session_speakers">演讲者</string>

    <string name="session_subtitle">
    <xliff:g id="time">%1$s</xliff:g>在<xliff:g id="room">%2$s</xliff:g>
  </string>

    <string name="session_subtitle_short">
    <xliff:g id="time">%1$s</xliff:g>
  </string>

    <string name="setup_wifi_yes">是</string>

    <string name="share_livestream_template">看I/O现场直播:\'<xliff:g id="title">%1$s</xliff:g>\'在<xliff:g id="hashtags">%2$s</xliff:g> <xliff:g id="url">%3$s</xliff:g>
  </string>

    <string name="share_template">检查在<xliff:g id="hashtags">%2$s</xliff:g>
    <xliff:g id="url">%3$s</xliff:g>的 \'<xliff:g id="title">%1$s</xliff:g>\'</string>

    <string name="snooze_x_min">小睡<xliff:g id="remaining_time">%1$d</xliff:g>分钟。</string>

    <string name="social_intro">点击标签关注在Google+上的讨论</string>

    <string name="speaker_googleplus_profile">Google+个人资料:<xliff:g id="speakername">%1$s</xliff:g>
  </string>

    <string name="themes">主题</string>

    <string name="time_hint_about_to_start_min">这个会议将在<xliff:g id="minutes">%1$d</xliff:g>分钟后开始。</string>

    <string name="time_hint_about_to_start_shortly">这个会议即将开始(少于1分钟)。</string>

    <string name="time_hint_session_ended">这个会议已经结束。</string>

    <string name="time_hint_started_just">这个会议现在正在进行! (刚开始)</string>

    <string name="time_hint_started_min">本次会议现在正在进行! (在<xliff:g id="minutes">%1$d</xliff:g>分钟前开始)</string>

    <string name="times_shown_in_tz">以<xliff:g id="timezone">%1$s</xliff:g>显示所有时间</string>

    <string name="title_about">关于</string>

    <string name="title_explore">我的照相机</string>

    <string name="title_map">实况监视器</string>

    <string name="title_my_schedule">我的视频记录</string>

    <string name="title_office_hours">办公时间</string>

    <string name="title_sandbox_detail">公司信息</string>

    <string name="title_search">搜索</string>

    <string name="title_session_detail">会议信息</string>

    <string name="title_session_feedback">会议反馈</string>

    <string name="title_settings">设置</string>

    <string name="title_share">分享正在使用的</string>

    <string name="topics">主题</string>

    <string name="types">类型</string>

    <string name="unknown_room">(未指定的房间)</string>

    <string name="update_app">更新应用程序</string>

    <string name="watch_now">现在观看!</string>

    <string name="welcome_to_google_i_o_app">欢迎来到Google I/O 应用程序!</string>

    <string name="wifi_dialog_button_configure">新增WiFi网络</string>

    <string name="wifi_dialog_button_settings">开启WiFi设置</string>

    <string name="wifi_install_error_message">很抱歉,无法更新WiFi配置</string>

    <string name="explore_attending_in_person_toast">亲临I/O现场(您可在设置中修改)</string>
    <string name="explore_attending_remotely_toast">远程参加I/O (您可在设置中修改)</string>
    <string name="go_to_settings">转到设置</string>
    <string name="more_information">更多信息</string>
</resources>


text:
package com.hazelcast.spi.discovery.multicast.impl;

import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.spi.discovery.DiscoveryNode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastDiscoverySender implements Runnable {

    private static final int SLEEP_DURATION = 2000;
    private MulticastSocket multicastSocket;
    private MulticastMemberInfo multicastMemberInfo;
    private DatagramPacket datagramPacket;
    private ILogger logger;
    private String group;
    private int port;
    private volatile boolean stop;

    public MulticastDiscoverySender(DiscoveryNode discoveryNode, MulticastSocket multicastSocket,
                                    ILogger logger, String group, int port)
            throws IOException {
        this.multicastSocket = multicastSocket;
        this.logger = logger;
        this.group = group;
        this.port = port;
        if (discoveryNode != null) {
            Address address = discoveryNode.getPublicAddress();
            multicastMemberInfo = new MulticastMemberInfo(address.getHost(), address.getPort());
        }
        initDatagramPacket();
    }

    private void initDatagramPacket() throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out;
        out = new ObjectOutputStream(bos);
        out.writeObject(multicastMemberInfo);
        byte[] yourBytes = bos.toByteArray();
        datagramPacket = new DatagramPacket(yourBytes, yourBytes.length,
                InetAddress.getByName(group), port);
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                Thread.sleep(SLEEP_DURATION);
            } catch (InterruptedException e) {
                logger.finest("Thread sleeping interrupted. This may due to graceful shutdown.");
            }
            try {
                send();
            } catch (IOException e) {
                logger.finest(e.getMessage());
            }
        }
    }

    void send() throws IOException {
        multicastSocket.send(datagramPacket);
    }

    public void stop() {
        stop = true;
    }
}


text:
package org.apache.jackrabbit.core.state;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Test suite that includes all testcases for the State module.
 */
public class TestAll extends TestCase {

    /**
     * Returns a Test suite that executes all tests inside this
     * package.
     *
     * @return a Test suite that executes all tests inside this
     *         package.
     */
    public static Test suite() {
        TestSuite suite = new TestSuite("State tests");

        suite.addTestSuite(ChangeLogTest.class);
        suite.addTestSuite(DefaultISMLockingTest.class);
        suite.addTestSuite(DefaultISMLockingDeadlockTest.class);
        suite.addTestSuite(FineGrainedISMLockingTest.class);
        suite.addTestSuite(NameSetTest.class);
        suite.addTestSuite(NodeStateMergerTest.class);

        return suite;
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JiraSimpleTimeTracker
{
    public partial class PreferencesForm : Form
    {
        public PreferencesForm()
        {
            InitializeComponent();
        }

        private void PreferencesForm_Load(object sender, EventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (checkConnection())
            {
                Properties.Settings.Default.login = tbLogin.Text;
                Properties.Settings.Default.password = tbPassword.Text;
                Properties.Settings.Default.JiraUrl = tbJiraUrl.Text;
                Properties.Settings.Default.LastConnectionSuccessful = true;
                Properties.Settings.Default.Save();
            }
        }

        private bool checkConnection()
        {
            String login = tbLogin.Text;
            String password = tbPassword.Text;
            String jiraUrl = tbJiraUrl.Text;
            PreferencesForm.ActiveForm.Cursor = Cursors.WaitCursor;

            try
            {
                JiraRequest req = new JiraRequest(jiraUrl, login, password);
                String res = req.create("mypermissions"/*"search?jql=filter=-2"*/).getResponse();

                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show("Connection error: " + e.Message, "",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                return false;
            }
            finally
            {
                PreferencesForm.ActiveForm.Cursor = Cursors.Arrow;
            }
        }

        private void checkConnection(object sender, EventArgs e)
        {
            if(checkConnection())
                MessageBox.Show( "Connection successful!","",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
        }

        private void PreferencesForm_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                MainForm.ReleaseCapture();
                MainForm.SendMessage(Handle, MainForm.WM_NCLBUTTONDOWN, MainForm.HT_CAPTION, 0);
            }
        }
    }
}


text:
<?php namespace Pare\Repository\Eloquent;

use Pare\Repository\Contracts\CriteriaInterface;
use Pare\Repository\Criteria\Criteria;
use Pare\Repository\Exceptions\RepositoryException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Container\Container as App;
use Illuminate\Support\Collection;

/**
 * Basic Repository methods like setting up the model
 * @package Pare\Repository\Contracts
 */
abstract class BaseRepository implements CriteriaInterface
{
    /**
     * @var App
     */
    private $app;

    /**
     * @var
     */
    protected $model;

    /**
     * @var Collection
     */
    protected $criteria;

    /**
     * @var bool
     */
    protected $skipCriteria = false;

    /**
     * @param App $app
     * @throws \Pare\Repository\Exceptions\RepositoryException
     */
    public function __construct(App $app, Collection $collection)
    {
        $this->app      = $app;
        $this->criteria = $collection;

        $this->resetScope();
        $this->makeModel();
    }

    /**
     * Specify Model class name
     *
     * @return mixed
     */
    abstract public function model();

    /**
     * @return \Illuminate\Database\Eloquent\Builder
     * @throws \Pare\Repository\Exceptions\RepositoryException
     */
    public function makeModel()
    {
        $model = $this->app->make($this->model());

        if (!$model instanceof Model) {
            throw new RepositoryException(
                "Class {$this->model()} must be an instance of Illuminate\\Database\\Eloquent\\Model"
            );
        }

        return $this->model = $model->newQuery();
    }

    /**
     * @return $this
     */
    public function resetScope()
    {
        $this->skipCriteria(false);
        return $this;
    }

    /**
     * @param bool $status
     * @return $this
     */
    public function skipCriteria($status = null)
    {
        $this->skipCriteria = $status;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCriteria()
    {
        return $this->criteria;
    }

    /**
     * @param Criteria $criteria
     * @return $this
     */
    public function getByCriteria(Criteria $criteria)
    {
        $this->model = $criteria->apply($this->model, $this);
        return $this;
    }

    /**
     * @param Criteria $criteria
     * @return $this
     */
    public function pushCriteria(Criteria $criteria)
    {
        $this->criteria->push($criteria);
        return $this;
    }

    /**
     * @return $this
     */
    public function applyCriteria()
    {
        // skip criteria
        if ($this->skipCriteria === true) {
            return $this;
        }

        // apply criteria
        foreach ($this->getCriteria() as $criteria) {
            if ($criteria instanceof Criteria) {
                $this->model = $criteria->apply($this->model, $this);
            }
        }

        return $this;
    }
}


text:
<!DOCTYPE html>

		<meta http-equiv="refresh" content="0;url=https://www.webrtc-experiment.com/docs/">
        <title>404 Not found</title>

        Access denied. Redirecting to: https://www.webrtc-experiment.com/docs/


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Xml.Serialization;

namespace ExtensionMinder.CommonExt
{
    public static class EnumExtensions
    {
        public static T ParseAsEnumByDescriptionAttribute<T>(this string description) // where T : enum
        {
            if (string.IsNullOrEmpty(description))
                throw new ArgumentNullException(description, @"Cannot parse an empty description");

            var enumType = typeof(T);
            if (!enumType.IsEnum) throw new InvalidOperationException($"Invalid Enum type{typeof(T)}");

            foreach (T item in Enum.GetValues(typeof(T)))
            {
                var attributes =
                    (DescriptionAttribute[])
                    item.GetType()
                        .GetField(item.ToString())
                        .GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0 && attributes[0].Description.ToUpper() == description.ToUpper()) return item;
            }

            throw new InvalidOperationException(
                $"Couldn't find enum of type {typeof(T)} with attribute of '{description}'");
        }

        public static string GetXmlEnumAttribute(this Enum enumerationValue)
        {
            var attributes =
                (XmlEnumAttribute[])
                enumerationValue.GetType()
                    .GetField(enumerationValue.ToString())
                    .GetCustomAttributes(typeof(XmlEnumAttribute), false);
            return attributes.Length > 0 ? attributes[0].Name : enumerationValue.ToString();
        }

        public static T GetEnumAttribute<T>(this Enum enumerationValue) where T : Attribute
        {
            return
                ((T[])
                    enumerationValue.GetType()
                        .GetField(enumerationValue.ToString())
                        .GetCustomAttributes(typeof(T), false))
                .FirstOrDefault();
        }

        ///
        ///     Gets all items for an enum value.
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static IEnumerable<T> GetAllItems<T>(this Enum value)
        {
            return from object item in Enum.GetValues(typeof(T)) select (T) item;
        }

        ///
        ///     Gets all items for an enum type.
        ///
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> GetAllItems<T>() where T : struct
        {
            return Enum.GetValues(typeof(T)).Cast<T>();
        }

        ///
        ///     Gets all combined items from an enum value.
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        /// <example>
        ///     Displays ValueA and ValueB.
        ///
        /// EnumExample dummy = EnumExample.Combi;
        /// foreach (var item in dummy.GetAllSelectedItems<EnumExample />())
        /// {
        ///    Console.WriteLine(item);
        /// }
        ///
        /// </example>
        public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
        {
            var valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

            return from object item in Enum.GetValues(typeof(T))
                let itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture)
                where itemAsInt == (valueAsInt & itemAsInt)
                select (T) item;
        }

        ///
        ///     Determines whether the enum value contains a specific value.
        ///
        /// <param name="value">The value.</param>
        /// <param name="request">The request.</param>
        /// <returns>
        ///     <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
        /// </returns>
        /// <example>
        ///
        /// EnumExample dummy = EnumExample.Combi;
        /// if (dummy.Contains<EnumExample />(EnumExample.ValueA))
        /// {
        ///     Console.WriteLine("dummy contains EnumExample.ValueA");
        /// }
        ///
        /// </example>
        public static bool Contains<T>(this Enum value, T request)
        {
            var valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
            var requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);

            if (requestAsInt == (valueAsInt & requestAsInt)) return true;

            return false;
        }

        public static T? TryParseEnum<T>(this string enumerationString) where T : struct
        {
            if (GetAllItems<T>().Any(e => e.ToString() == enumerationString)) return enumerationString.ToEnum<T>();

            return null;
        }

        public static T ToEnum<T>(this string enumerationString)
        {
            if (string.IsNullOrWhiteSpace(enumerationString))
                return default(T);

            return (T) Enum.Parse(typeof(T), enumerationString);
        }

        public static string GetDescription(this Enum enumerationValue)
        {
            if (enumerationValue == null)
                return null;
            var attributes =
                (DescriptionAttribute[])
                enumerationValue.GetType()
                    .GetField(enumerationValue.ToString())
                    .GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : enumerationValue.ToString();
        }
    }
}


text:
Library for generating UUID (universally unique identifier) version 4 strings.

The library will use [window.crypto](https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto) to
generate random numbers if it detects that it is available, else it will fallback to use
[Math.random](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random).

## Usage

```Typescript
let uuid: string = UUIDv4.generateUUID();
```

Sample Angular Karma test

```Typescript
import { TestBed, inject } from '@angular/core/testing';
import { UUIDv4 } from 'uuid-version4';

describe('sample test', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: []
    });
  });

  it('it should generate UUID version 4 string', inject([], () => {
    let uuid: string = UUIDv4.generateUUID();
    expect(uuid).toBeTruthy();
    expect(uuid.length).toBe(36);
    expect(uuid[14]).toBe('4');
  }));
});
```

## Main source

The main source file is [index.ts](https://github.com/pfrandsen/UUIDv4/blob/master/src/index.ts).

## References

* Wikipedia: [Universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier)
* Specification: [RFC 4122](https://www.ietf.org/rfc/rfc4122.txt)