text:
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Linq.Enumerable;

namespace LASI.Core
{
    /// <summary>
    /// Defines extension methods for sequences of Phrase instances.
    /// </summary>
    /// <seealso cref="Phrase"/>
    public static partial class LexicalEnumerable
    {
        /// <summary>
        /// Returns all Phrases in the document which are in between the provided Phrases. The range
        /// of the resulting sequence is neither upper nor lower inclusive.
        /// </summary>
        /// <param name="after">The exclusive lower bound of the range to aggregate.</param>
        /// <param name="before">The exclusive upper bound of the range to aggregate.</param>
        /// <returns>
        /// All Phrases in the document which are in between the provided Phrases. The range of the
        /// resulting sequence is neither upper nor lower inclusive. If the Phrases are improperly
        /// ordered, are in different documents or if the given phrases are adjacent, an empty
        /// sequence will be returned.
        /// </returns>
        public static IEnumerable<Phrase> Between(this Phrase after, Phrase before) => after.Between(phrase => phrase == before);

        /// <summary>
        /// Returns all Phrases in the document which are in between the provided starting Phrase
        /// and the first phrase which matches the provided selector function. The range of the
        /// resulting sequence is neither upper nor lower inclusive.
        /// </summary>
        /// <param name="after">The exclusive lower bound of the range to aggregate.</param>
        /// <param name="endSelector">
        /// The function which is used to test each subsequent phrase returning true when a match
        /// verbalSelector is found.
        /// </param>
        /// <returns>
        /// All Phrases in the document which are in between the provided start Phrase and the first
        /// Phrase for which the provided predicate function returns true. The range of the
        /// resulting sequence is neither upper nor lower inclusive. If no matching phrase exists
        /// after the starting phrase or the given start Phrase is immediately followed by a Phrase
        /// matching the end selector function, an empty sequence will be returned.an empty sequence
        /// is returned is returned.
        /// </returns>
        public static IEnumerable<Phrase> Between(this Phrase after, Func<Phrase, bool> endSelector) => after.Document.Phrases.Any(endSelector) ?
               after.Document.Phrases.SkipWhile(p => p != after).Skip(1).TakeWhile(p => !endSelector(p)) :
               Empty<Phrase>();

        #region Sequential Implementations

        /// <summary>
        /// Returns all AdjectivePhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All AdjectivePhrases in the sequence</returns>
        public static IEnumerable<AdjectivePhrase> OfAdjectivePhrase(this IEnumerable<Phrase> phrases) => phrases.OfType<AdjectivePhrase>();

        /// <summary>
        /// Returns all AdverbPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All AdverbPhrases in the sequence</returns>
        public static IEnumerable<AdverbPhrase> OfAdverbPhrase(this IEnumerable<Phrase> phrases) => phrases.OfType<AdverbPhrase>();

        /// <summary>
        /// Returns all ConjunctionPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All ConjunctionPhrases in the sequence</returns>
        public static IEnumerable<ConjunctionPhrase> OfConjunctionPhrase(this IEnumerable<Phrase> phrases) => phrases.OfType<ConjunctionPhrase>();

        /// <summary>
        /// Returns all NounPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All NounPhrases in the sequence</returns>
        public static IEnumerable<NounPhrase> OfNounPhrase(this IEnumerable<Phrase> phrases) => phrases.OfType<NounPhrase>();

        /// <summary>
        /// Returns all PrepositionalPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All PrepositionalPhrases in the sequence</returns>
        public static IEnumerable<PrepositionalPhrase> OfPrepositionalPhrase(this IEnumerable<Phrase> phrases) => phrases.OfType<PrepositionalPhrase>();

        /// <summary>
        /// Returns all PronounPhrase in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All PronounPhrase in the sequence</returns>
        public static IEnumerable<PronounPhrase> OfPronounPhrase(this IEnumerable<Phrase> phrases) => phrases.OfType<PronounPhrase>();

        /// <summary>
        /// Returns all VerbPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter.</param>
        /// <returns>All VerbPhrases in the sequence</returns>
        public static IEnumerable<VerbPhrase> OfVerbPhrase(this IEnumerable<Phrase> phrases) => phrases.OfType<VerbPhrase>();

        /// <summary>
        /// Returns a new sequence containing all of the Phrases which follow the given Phrase in
        /// the source sequence.
        /// </summary>
        /// <param name="phrases">The source sequence of Phrases.</param>
        /// <param name="after">The exclusive lower bound of the desired subset of Phrases.</param>
        /// <returns>
        /// A new sequence containing all of the Phrases which follow the given Phrase in the source sequence.
        /// </returns>
        public static IEnumerable<Phrase> PhrasesAfter(this IEnumerable<Phrase> phrases, Phrase after) => phrases.SkipWhile(r => r != after).Skip(1);

        /// <summary>
        /// Returns a new sequence containing all of the Phrases which follow the first Phrase in
        /// the source sequence which matches the provided selector function.
        /// </summary>
        /// <param name="phrases">The source sequence of Phrases.</param>
        /// <param name="startSelector">
        /// The function which will select be used to select the exclusive lower bound of the new sequence.
        /// </param>
        /// <returns>
        /// A new sequence containing all of the Phrases which follow the first Phrase in the source
        /// sequence which matches the provided selector function..
        /// </returns>
        public static IEnumerable<Phrase> PhrasesAfter(this IEnumerable<Phrase> phrases, Func<Phrase, bool> startSelector) => phrases.SkipWhile(r => !startSelector(r)).Skip(1);

        #endregion Sequential Implementations

        #region Parallel Implementations

        /// <summary>
        /// Returns all AdjectivePhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All AdjectivePhrases in the sequence</returns>
        public static ParallelQuery<AdjectivePhrase> OfAdjectivePhrase(this ParallelQuery<Phrase> phrases) => phrases.OfType<AdjectivePhrase>();

        /// <summary>
        /// Returns all AdverbPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All AdverbPhrases in the sequence</returns>
        public static ParallelQuery<AdverbPhrase> OfAdverbPhrase(this ParallelQuery<Phrase> phrases) => phrases.OfType<AdverbPhrase>();

        /// <summary>
        /// Returns all ConjunctionPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All ConjunctionPhrases in the sequence</returns>
        public static ParallelQuery<ConjunctionPhrase> OfConjunctionPhrase(this ParallelQuery<Phrase> phrases) => phrases.OfType<ConjunctionPhrase>();

        /// <summary>
        /// Returns all NounPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All NounPhrases in the sequence</returns>
        public static ParallelQuery<NounPhrase> OfNounPhrase(this ParallelQuery<Phrase> phrases) => phrases.OfType<NounPhrase>();

        /// <summary>
        /// Returns all PrepositionalPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All PrepositionalPhrases in the sequence</returns>
        public static ParallelQuery<PrepositionalPhrase> OfPrepositionalPhrase(this ParallelQuery<Phrase> phrases) => phrases.OfType<PrepositionalPhrase>();

        /// <summary>
        /// Returns all PronounPhrase in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter</param>
        /// <returns>All PronounPhrase in the sequence</returns>
        public static ParallelQuery<PronounPhrase> OfPronounPhrase(this ParallelQuery<Phrase> phrases) => phrases.OfType<PronounPhrase>();

        /// <summary>
        /// Returns all VerbPhrases in the sequence.
        /// </summary>
        /// <param name="phrases">The sequence of componentPhrases to filter.</param>
        /// <returns>All VerbPhrases in the sequence</returns>
        public static ParallelQuery<VerbPhrase> OfVerbPhrase(this ParallelQuery<Phrase> phrases) => phrases.OfType<VerbPhrase>();

        /// <summary>
        /// Returns a new sequence containing all of the Phrases which follow the given Phrase in
        /// the source sequence.
        /// </summary>
        /// <param name="phrases">The source sequence of Phrases.</param>
        /// <param name="after">The exclusive lower bound of the desired subset of Phrases.</param>
        /// <returns>
        /// A new sequence containing all of the Phrases which follow the given Phrase in the source sequence.
        /// </returns>
        public static ParallelQuery<Phrase> PhrasesAfter(this ParallelQuery<Phrase> phrases, Phrase after) => phrases.SkipWhile(r => r != after).Skip(1);

        /// <summary>
        /// Returns a new sequence containing all of the Phrases which follow the first Phrase in
        /// the source sequence which matches the provided selector function.
        /// </summary>
        /// <param name="phrases">The source sequence of Phrases.</param>
        /// <param name="startSelector">
        /// The function which will select be used to select the exclusive lower bound of the new sequence.
        /// </param>
        /// <returns>
        /// A new sequence containing all of the Phrases which follow the first Phrase in the source
        /// sequence which matches the provided selector function..
        /// </returns>
        public static ParallelQuery<Phrase> PhrasesAfter(this ParallelQuery<Phrase> phrases, Func<Phrase, bool> startSelector) => phrases.SkipWhile(r => !startSelector(r)).Skip(1);

        #endregion Parallel Implementations
    }
}


text:
/// @todo Documentation Modules/Legacy/Fields/SetFieldNodes.h

#ifndef MODULES_LEGACY_FIELDS_SETFIELDNODES_H__
#define MODULES_LEGACY_FIELDS_SETFIELDNODES_H__

#include <Dataflow/Network/Module.h>
#include <Modules/Legacy/Fields/share.h>

namespace SCIRun {
  namespace Modules {
    namespace Fields {

      class SCISHARE SetFieldNodes : public Dataflow::Networks::Module,
        public Has2InputPorts<FieldPortTag, MatrixPortTag>,
        public Has1OutputPort<FieldPortTag>
      {
      public:
        SetFieldNodes();

        void execute() override;
        void setStateDefaults() override {}

        INPUT_PORT(0, InputField, Field);
        INPUT_PORT(1, MatrixNodes, Matrix);
        OUTPUT_PORT(0, OutputField, Field);

        MODULE_TRAITS_AND_INFO(ModuleFlags::ModuleHasAlgorithm)
      };

    }
  }
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.xj.scud.client.route;

import io.netty.channel.Channel;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Author: xiajun
 * Date: 2017/01/09 10:44
 */
public abstract class RpcRoute {
    protected Map<String, Channel> serverNodes = new ConcurrentHashMap<>(8);//存放所有服务节点,创建对象时从这里提取
    protected List<Channel> nodes = new CopyOnWriteArrayList<>();//存放所有节点数据

    /**
     * 添加一个服务节点
     *
     * @param node
     */
    public abstract boolean addServerNode(NodeInfo node,Channel channel);

    /**
     * 删除一个服务节点
     *
     * @param path 节点地址
     */
    public abstract Channel removeServerNode(String path);

    /**
     * 获取一个服务节点
     *
     * @return
     */
    public abstract Channel getServer();

    /**
     * 根据指定的key获取服务节点
     *
     * @param key
     * @return
     */
    public Channel getServer(String key) {
        return serverNodes.get(key);
    }

    /**
     * 获取服务节点数
     *
     * @return
     */
    public abstract int size();
}


text:
<?php

/*
|--------------------------------------------------------------------------
| Register Authorize
|--------------------------------------------------------------------------
|
| Register Authorize as Orchestra Resources.
|
*/

Event::listen('orchestra.started: backend', function ()
{
	$authorize = Orchestra\Resources::make('authorize', array(
		'name'    => 'Authorize',
		'uses'    => 'authorize::home',
		'visible' => function ()
		{
			$acl = Orchestra::acl();

			if ($acl->can('manage acl') or $acl->can('manage roles')) return true;

			return false;
		}
	));

	$authorize->roles = 'authorize::roles';
	$authorize->acls  = 'authorize::acls';
});

/*
|--------------------------------------------------------------------------
| Map Authorize Configuration
|--------------------------------------------------------------------------
|
| Allow Orchestra Extension Configuration page to configure Authorize
| options.
|
*/

Orchestra\Extension\Config::map('authorize', array(
	'default_role' => 'orchestra::orchestra.default_role',
	'member_role'  => 'orchestra::orchestra.member_role',
));

Event::listen('orchestra.form: extension.authorize', function ($config, $form)
{
	Authorize\Presenter\Extension::form($form);
});

Event::listen("orchestra.saved: extension.authorize", function($config)
{
	Config::set('orchestra::orchestra.default_role', (int) $config->default_role);
	Config::set('orchestra::orchestra.member_role', (int) $config->member_role);
	Authorize\Core::sync();
});


text:
#include <aws/rds/model/DescribeDBSnapshotAttributesRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::RDS::Model;
using namespace Aws::Utils;

DescribeDBSnapshotAttributesRequest::DescribeDBSnapshotAttributesRequest() :
    m_dBSnapshotIdentifierHasBeenSet(false)
{
}

Aws::String DescribeDBSnapshotAttributesRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DescribeDBSnapshotAttributes&";
  if(m_dBSnapshotIdentifierHasBeenSet)
  {
    ss << "DBSnapshotIdentifier=" << StringUtils::URLEncode(m_dBSnapshotIdentifier.c_str()) << "&";
  }

  ss << "Version=2014-10-31";
  return ss.str();
}

void  DescribeDBSnapshotAttributesRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>apache-storm-bin</artifactId>
        <groupId>org.apache.storm</groupId>
        <version>2.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>storm-client-bin</artifactId>
    <packaging>pom</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.storm</groupId>
            <artifactId>storm-client</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>client</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <attach>false</attach>
                    <runOnlyAtExecutionRoot>false</runOnlyAtExecutionRoot>
                    <descriptors>
                        <descriptor>${project.basedir}/src/main/assembly/storm-client.xml</descriptor>
                    </descriptors>
                    <appendAssemblyId>false</appendAssemblyId>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package example

import org.scalatest.FunSuite

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

/**
 * This class implements a ScalaTest test suite for the methods in object
 * `Lists` that need to be implemented as part of this assignment. A test
 * suite is simply a collection of individual tests for some specific
 * component of a program.
 *
 * A test suite is created by defining a class which extends the type
 * `org.scalatest.FunSuite`. When running ScalaTest, it will automatically
 * find this class and execute all of its tests.
 *
 * Adding the `@RunWith` annotation enables the test suite to be executed
 * inside eclipse using the built-in JUnit test runner.
 *
 * You have two options for running this test suite:
 *
 * - Start the sbt console and run the "test" command
 * - Right-click this file in eclipse and chose "Run As" - "JUnit Test"
 */
@RunWith(classOf[JUnitRunner])
class ListsSuite extends FunSuite {

  /**
   * Tests are written using the `test` operator which takes two arguments:
   *
   * - A description of the test. This description has to be unique, no two
   *   tests can have the same description.
   * - The test body, a piece of Scala code that implements the test
   *
   * The most common way to implement a test body is using the method `assert`
   * which tests that its argument evaluates to `true`. So one of the simplest
   * successful tests is the following:
   */
  test("one plus one is two")(assert(1 + 1 == 2))

  /**
   * In Scala, it is allowed to pass an argument to a method using the block
   * syntax, i.e. `{ argument }` instead of parentheses `(argument)`.
   *
   * This allows tests to be written in a more readable manner:
   */
  test("one plus one is three?") {
    assert(1 + 1 == 2) // This assertion fails! Go ahead and fix it.
  }

  /**
   * One problem with the previous (failing) test is that ScalaTest will
   * only tell you that a test failed, but it will not tell you what was
   * the reason for the failure. The output looks like this:
   *
   * {{{
   *    [info] - one plus one is three? *** FAILED ***
   * }}}
   *
   * This situation can be improved by using a special equality operator
   * `===` instead of `==` (this is only possible in ScalaTest). So if you
   * run the next test, ScalaTest will show the following output:
   *
   * {{{
   *    [info] - details why one plus one is not three *** FAILED ***
   *    [info]   2 did not equal 3 (ListsSuite.scala:67)
   * }}}
   *
   * We recommend to always use the `===` equality operator when writing tests.
   */
  test("details why one plus one is not three") {
    assert(1 + 1 === 2) // Fix me, please!
  }

  /**
   * In order to test the exceptional behavior of a methods, ScalaTest offers
   * the `intercept` operation.
   *
   * In the following example, we test the fact that the method `intNotZero`
   * throws an `IllegalArgumentException` if its argument is `0`.
   */
  test("intNotZero throws an exception if its argument is 0") {
    intercept[IllegalArgumentException] {
      intNotZero(0)
    }
  }

  def intNotZero(x: Int): Int = {
    if (x == 0) throw new IllegalArgumentException("zero is not allowed")
    else x
  }

  /**
   * Now we finally write some tests for the list functions that have to be
   * implemented for this assignment. We fist import all members of the
   * `List` object.
   */
  import Lists._

  /**
   * We only provide two very basic tests for you. Write more tests to make
   * sure your `sum` and `max` methods work as expected.
   *
   * In particular, write tests for corner cases: negative numbers, zeros,
   * empty lists, lists with repeated elements, etc.
   *
   * It is allowed to have multiple `assert` statements inside one test,
   * however it is recommended to write an individual `test` statement for
   * every tested aspect of a method.
   */
  test("sum of a few numbers") {
    assert(sum(List(1, 2, 0)) === 3)
  }

  test("max of a few numbers") {
    assert(max(List(3, 7, 2)) === 7)
  }
}


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

package policy

import (
	"encoding/json"
	"fmt"

	"github.com/minio/minio/pkg/policy/condition"
)

// Action - policy action.
// Refer https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazons3.html
// for more information about available actions.
type Action string

const (
	// AbortMultipartUploadAction - AbortMultipartUpload Rest API action.
	AbortMultipartUploadAction Action = "s3:AbortMultipartUpload"

	// CreateBucketAction - CreateBucket Rest API action.
	CreateBucketAction = "s3:CreateBucket"

	// DeleteBucketAction - DeleteBucket Rest API action.
	DeleteBucketAction = "s3:DeleteBucket"

	// DeleteBucketPolicyAction - DeleteBucketPolicy Rest API action.
	DeleteBucketPolicyAction = "s3:DeleteBucketPolicy"

	// DeleteObjectAction - DeleteObject Rest API action.
	DeleteObjectAction = "s3:DeleteObject"

	// GetBucketLocationAction - GetBucketLocation Rest API action.
	GetBucketLocationAction = "s3:GetBucketLocation"

	// GetBucketNotificationAction - GetBucketNotification Rest API action.
	GetBucketNotificationAction = "s3:GetBucketNotification"

	// GetBucketPolicyAction - GetBucketPolicy Rest API action.
	GetBucketPolicyAction = "s3:GetBucketPolicy"

	// GetObjectAction - GetObject Rest API action.
	GetObjectAction = "s3:GetObject"

	// HeadBucketAction - HeadBucket Rest API action. This action is unused in minio.
	HeadBucketAction = "s3:HeadBucket"

	// ListAllMyBucketsAction - ListAllMyBuckets (List buckets) Rest API action.
	ListAllMyBucketsAction = "s3:ListAllMyBuckets"

	// ListBucketAction - ListBucket Rest API action.
	ListBucketAction = "s3:ListBucket"

	// ListBucketMultipartUploadsAction - ListMultipartUploads Rest API action.
	ListBucketMultipartUploadsAction = "s3:ListBucketMultipartUploads"

	// ListenBucketNotificationAction - ListenBucketNotification Rest API action.
	// This is Minio extension.
	ListenBucketNotificationAction = "s3:ListenBucketNotification"

	// ListMultipartUploadPartsAction - ListParts Rest API action.
	ListMultipartUploadPartsAction = "s3:ListMultipartUploadParts"

	// PutBucketNotificationAction - PutObjectNotification Rest API action.
	PutBucketNotificationAction = "s3:PutBucketNotification"

	// PutBucketPolicyAction - PutBucketPolicy Rest API action.
	PutBucketPolicyAction = "s3:PutBucketPolicy"

	// PutObjectAction - PutObject Rest API action.
	PutObjectAction = "s3:PutObject"
)

// isObjectAction - returns whether action is object type or not.
func (action Action) isObjectAction() bool {
	switch action {
	case AbortMultipartUploadAction, DeleteObjectAction, GetObjectAction:
		fallthrough
	case ListMultipartUploadPartsAction, PutObjectAction:
		return true
	}

	return false
}

// IsValid - checks if action is valid or not.
func (action Action) IsValid() bool {
	switch action {
	case AbortMultipartUploadAction, CreateBucketAction, DeleteBucketAction:
		fallthrough
	case DeleteBucketPolicyAction, DeleteObjectAction, GetBucketLocationAction:
		fallthrough
	case GetBucketNotificationAction, GetBucketPolicyAction, GetObjectAction:
		fallthrough
	case HeadBucketAction, ListAllMyBucketsAction, ListBucketAction:
		fallthrough
	case ListBucketMultipartUploadsAction, ListenBucketNotificationAction:
		fallthrough
	case ListMultipartUploadPartsAction, PutBucketNotificationAction:
		fallthrough
	case PutBucketPolicyAction, PutObjectAction:
		return true
	}

	return false
}

// MarshalJSON - encodes Action to JSON data.
func (action Action) MarshalJSON() ([]byte, error) {
	if action.IsValid() {
		return json.Marshal(string(action))
	}

	return nil, fmt.Errorf("invalid action '%v'", action)
}

// UnmarshalJSON - decodes JSON data to Action.
func (action *Action) UnmarshalJSON(data []byte) error {
	var s string

	if err := json.Unmarshal(data, &s); err != nil {
		return err
	}

	a := Action(s)
	if !a.IsValid() {
		return fmt.Errorf("invalid action '%v'", s)
	}

	*action = a

	return nil
}

func parseAction(s string) (Action, error) {
	action := Action(s)

	if action.IsValid() {
		return action, nil
	}

	return action, fmt.Errorf("unsupported action '%v'", s)
}

// actionConditionKeyMap - holds mapping of supported condition key for an action.
var actionConditionKeyMap = map[Action]condition.KeySet{
	AbortMultipartUploadAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	CreateBucketAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	DeleteBucketPolicyAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	DeleteObjectAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	GetBucketLocationAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	GetBucketNotificationAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	GetBucketPolicyAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	GetObjectAction: condition.NewKeySet(
		condition.S3XAmzServerSideEncryption,
		condition.S3XAmzServerSideEncryptionAwsKMSKeyID,
		condition.S3XAmzStorageClass,
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	HeadBucketAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	ListAllMyBucketsAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	ListBucketAction: condition.NewKeySet(
		condition.S3Prefix,
		condition.S3Delimiter,
		condition.S3MaxKeys,
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	ListBucketMultipartUploadsAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	ListenBucketNotificationAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	ListMultipartUploadPartsAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	PutBucketNotificationAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	PutBucketPolicyAction: condition.NewKeySet(
		condition.AWSReferer,
		condition.AWSSourceIP,
	),

	PutObjectAction: condition.NewKeySet(
		condition.S3XAmzCopySource,
		condition.S3XAmzServerSideEncryption,
		condition.S3XAmzServerSideEncryptionAwsKMSKeyID,
		condition.S3XAmzMetadataDirective,
		condition.S3XAmzStorageClass,
		condition.AWSReferer,
		condition.AWSSourceIP,
	),
}


text:
namespace Umbraco.Cms.Core.Models.Entities
{
    /// <summary>
    /// Defines an entity that belongs to a tree.
    /// </summary>
    public interface ITreeEntity : IEntity
    {
        /// <summary>
        /// Gets or sets the name of the entity.
        /// </summary>
        string Name { get; set; }

        /// <summary>
        /// Gets or sets the identifier of the user who created this entity.
        /// </summary>
        int CreatorId { get; set; }

        /// <summary>
        /// Gets or sets the identifier of the parent entity.
        /// </summary>
        int ParentId { get; set; }

        /// <summary>
        /// Sets the parent entity.
        /// </summary>
        /// <remarks>Use this method to set the parent entity when the parent entity is known, but has not
        /// been persistent and does not yet have an identity. The parent identifier will be retrieved
        /// from the parent entity when needed. If the parent entity still does not have an entity by that
        /// time, an exception will be thrown by <see cref="ParentId"/> getter.</remarks>
        void SetParent(ITreeEntity parent);

        /// <summary>
        /// Gets or sets the level of the entity.
        /// </summary>
        int Level { get; set; }

        /// <summary>
        /// Gets or sets the path to the entity.
        /// </summary>
        string Path { get; set; }

        /// <summary>
        /// Gets or sets the sort order of the entity.
        /// </summary>
        int SortOrder { get; set; }

        /// <summary>
        /// Gets a value indicating whether this entity is trashed.
        /// </summary>
        /// <remarks>
        /// <para>Trashed entities are located in the recycle bin.</para>
        /// <para>Always false for entities that do not support being trashed.</para>
        /// </remarks>
        bool Trashed { get; }
    }
}


text:
::: tip NOTE

The following text is there on purpose, so the page is scrollable.
This demoes that the chart does not consume the wheel until clicked.

:::

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Fringilla ut morbi tincidunt augue interdum velit euismod. Elit pellentesque habitant morbi tristique senectus et netus. Consectetur adipiscing elit pellentesque habitant morbi. Id faucibus nisl tincidunt eget nullam non nisi est sit. Blandit turpis cursus in hac habitasse. Vulputate eu scelerisque felis imperdiet proin fermentum leo vel. Ornare massa eget egestas purus. A diam sollicitudin tempor id eu nisl nunc. Augue mauris augue neque gravida in fermentum et sollicitudin. Dolor purus non enim praesent elementum facilisis leo vel fringilla. Habitant morbi tristique senectus et netus et malesuada. Nulla pharetra diam sit amet nisl suscipit adipiscing bibendum est. Gravida dictum fusce ut placerat orci nulla pellentesque.

Semper viverra nam libero justo laoreet sit. Pretium vulputate sapien nec sagittis aliquam malesuada bibendum arcu vitae. Risus ultricies tristique nulla aliquet enim tortor at auctor urna. Consequat semper viverra nam libero justo laoreet sit amet. Magna ac placerat vestibulum lectus mauris ultrices eros. Dolor purus non enim praesent elementum facilisis leo vel. Enim eu turpis egestas pretium aenean pharetra. Vitae purus faucibus ornare suspendisse sed nisi lacus. Senectus et netus et malesuada fames. Nec feugiat in fermentum posuere urna nec tincidunt praesent. Accumsan lacus vel facilisis volutpat. Lectus quam id leo in vitae turpis massa. Cras sed felis eget velit aliquet. Volutpat maecenas volutpat blandit aliquam.

Volutpat lacus laoreet non curabitur. Diam donec adipiscing tristique risus. Fusce id velit ut tortor pretium viverra suspendisse. Dui ut ornare lectus sit amet est. Pharetra sit amet aliquam id. Porttitor massa id neque aliquam vestibulum morbi blandit. Viverra adipiscing at in tellus integer feugiat scelerisque varius morbi. Quam elementum pulvinar etiam non quam. Congue quisque egestas diam in arcu cursus euismod quis. Dictum fusce ut placerat orci nulla pellentesque. Ut placerat orci nulla pellentesque dignissim enim sit amet. Sagittis id consectetur purus ut faucibus pulvinar elementum integer. Dui ut ornare lectus sit amet est.

Ut tortor pretium viverra suspendisse potenti nullam ac tortor. Mauris a diam maecenas sed enim. Tellus in hac habitasse platea dictumst vestibulum rhoncus. Cras sed felis eget velit aliquet. Purus viverra accumsan in nisl nisi. Sed risus ultricies tristique nulla aliquet enim tortor at. Integer quis auctor elit sed vulputate mi sit amet mauris. Adipiscing elit duis tristique sollicitudin nibh sit amet commodo. Risus feugiat in ante metus dictum at. Posuere urna nec tincidunt praesent semper. Auctor elit sed vulputate mi sit amet mauris commodo. Senectus et netus et malesuada fames ac turpis egestas integer. Varius morbi enim nunc faucibus a pellentesque. Sed felis eget velit aliquet sagittis id. Ac auctor augue mauris augue neque gravida. Etiam erat velit scelerisque in dictum non consectetur a erat.

Tortor condimentum lacinia quis vel eros donec ac. Phasellus vestibulum lorem sed risus ultricies tristique. Vitae tortor condimentum lacinia quis vel eros donec. Morbi tempus iaculis urna id volutpat lacus laoreet non curabitur. Ut pharetra sit amet aliquam id diam. Eu non diam phasellus vestibulum lorem. Pharetra pharetra massa massa ultricies mi. Donec ultrices tincidunt arcu non. Sagittis orci a scelerisque purus semper eget duis. In iaculis nunc sed augue lacus viverra. Vitae proin sagittis nisl rhoncus mattis rhoncus urna neque. Consequat mauris nunc congue nisi vitae suscipit tellus mauris a. Massa placerat duis ultricies lacus sed turpis tincidunt id. Sit amet tellus cras adipiscing enim eu turpis. Amet porttitor eget dolor morbi non arcu risus quis varius. Potenti nullam ac tortor vitae purus.

```js chart-editor
// <block:data:1>
const DATA_COUNT = 70;
const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100};

const labels = Utils.months({count: DATA_COUNT});
const data = {
  labels: labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: Utils.numbers(NUMBER_CFG),
      borderColor: Utils.randomColor(0.4),
      backgroundColor: Utils.randomColor(0.1),
      stack: 'combined',
      type: 'bar'
    },
    {
      label: 'Dataset 2',
      data: Utils.numbers(NUMBER_CFG),
      borderColor: Utils.randomColor(0.4),
      backgroundColor: Utils.randomColor(0.1),
      pointBorderColor: Utils.randomColor(0.7),
      pointBackgroundColor: Utils.randomColor(0.5),
      stack: 'combined'
    }
  ]
};
// </block:data>

// <block:zoom:0>
const zoomOptions = {
  limits: {
    y: {min: 0, max: 200, minRange: 50}
  },
  pan: {
    enabled: true,
    mode: 'xy',
  },
  zoom: {
    wheel: {
      enabled: false,
    },
    pinch: {
      enabled: false
    },
    mode: 'xy',
  }
};
// </block:zoom>

// <block:border:3>
const borderPlugin = {
  id: 'chartAreaBorder',
  beforeDraw(chart, args, options) {
    const {ctx, chartArea: {left, top, width, height}} = chart;
    if (chart.options.plugins.zoom.zoom.wheel.enabled) {
      ctx.save();
      ctx.strokeStyle = 'red';
      ctx.lineWidth = 1;
      ctx.strokeRect(left, top, width, height);
      ctx.restore();
    }
  }
};
// </block:border>

const zoomStatus = () => 'Zoom: ' + (zoomOptions.zoom.wheel.enabled ? 'enabled' : 'disabled');

// <block:config:1>
const config = {
  type: 'line',
  data: data,
  options: {
    scales: {y: {stacked: true, min: 0}},
    plugins: {
      zoom: zoomOptions,
      title: {
        display: true,
        position: 'bottom',
        text: zoomStatus
      }
    },
    onClick(e) {
      const chart = e.chart;
      chart.options.plugins.zoom.zoom.wheel.enabled = !chart.options.plugins.zoom.zoom.wheel.enabled;
      chart.options.plugins.zoom.zoom.pinch.enabled = !chart.options.plugins.zoom.zoom.pinch.enabled;
      chart.update();
    }
  },
  plugins: [borderPlugin]
};
// </block:config>

const actions = [
  {
    name: 'Randomize',
    handler(chart) {
      chart.data.datasets.forEach(dataset => {
        dataset.data = Utils.numbers(NUMBER_CFG);
      });
      chart.update();
    }
  }, {
    name: 'Toggle zoom',
    handler(chart) {
      zoomOptions.zoom.wheel.enabled = !zoomOptions.zoom.wheel.enabled;
      chart.update();
    }
  }, {
    name: 'Toggle pan',
    handler(chart) {
      zoomOptions.pan.enabled = !zoomOptions.pan.enabled;
      chart.update();
    },
  }, {
    name: 'Reset zoom',
    handler(chart) {
      chart.resetZoom();
    }
  }
];

module.exports = {
  actions,
  config,
};
```

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Fringilla ut morbi tincidunt augue interdum velit euismod. Elit pellentesque habitant morbi tristique senectus et netus. Consectetur adipiscing elit pellentesque habitant morbi. Id faucibus nisl tincidunt eget nullam non nisi est sit. Blandit turpis cursus in hac habitasse. Vulputate eu scelerisque felis imperdiet proin fermentum leo vel. Ornare massa eget egestas purus. A diam sollicitudin tempor id eu nisl nunc. Augue mauris augue neque gravida in fermentum et sollicitudin. Dolor purus non enim praesent elementum facilisis leo vel fringilla. Habitant morbi tristique senectus et netus et malesuada. Nulla pharetra diam sit amet nisl suscipit adipiscing bibendum est. Gravida dictum fusce ut placerat orci nulla pellentesque.

Semper viverra nam libero justo laoreet sit. Pretium vulputate sapien nec sagittis aliquam malesuada bibendum arcu vitae. Risus ultricies tristique nulla aliquet enim tortor at auctor urna. Consequat semper viverra nam libero justo laoreet sit amet. Magna ac placerat vestibulum lectus mauris ultrices eros. Dolor purus non enim praesent elementum facilisis leo vel. Enim eu turpis egestas pretium aenean pharetra. Vitae purus faucibus ornare suspendisse sed nisi lacus. Senectus et netus et malesuada fames. Nec feugiat in fermentum posuere urna nec tincidunt praesent. Accumsan lacus vel facilisis volutpat. Lectus quam id leo in vitae turpis massa. Cras sed felis eget velit aliquet. Volutpat maecenas volutpat blandit aliquam.

Volutpat lacus laoreet non curabitur. Diam donec adipiscing tristique risus. Fusce id velit ut tortor pretium viverra suspendisse. Dui ut ornare lectus sit amet est. Pharetra sit amet aliquam id. Porttitor massa id neque aliquam vestibulum morbi blandit. Viverra adipiscing at in tellus integer feugiat scelerisque varius morbi. Quam elementum pulvinar etiam non quam. Congue quisque egestas diam in arcu cursus euismod quis. Dictum fusce ut placerat orci nulla pellentesque. Ut placerat orci nulla pellentesque dignissim enim sit amet. Sagittis id consectetur purus ut faucibus pulvinar elementum integer. Dui ut ornare lectus sit amet est.

Ut tortor pretium viverra suspendisse potenti nullam ac tortor. Mauris a diam maecenas sed enim. Tellus in hac habitasse platea dictumst vestibulum rhoncus. Cras sed felis eget velit aliquet. Purus viverra accumsan in nisl nisi. Sed risus ultricies tristique nulla aliquet enim tortor at. Integer quis auctor elit sed vulputate mi sit amet mauris. Adipiscing elit duis tristique sollicitudin nibh sit amet commodo. Risus feugiat in ante metus dictum at. Posuere urna nec tincidunt praesent semper. Auctor elit sed vulputate mi sit amet mauris commodo. Senectus et netus et malesuada fames ac turpis egestas integer. Varius morbi enim nunc faucibus a pellentesque. Sed felis eget velit aliquet sagittis id. Ac auctor augue mauris augue neque gravida. Etiam erat velit scelerisque in dictum non consectetur a erat.

Tortor condimentum lacinia quis vel eros donec ac. Phasellus vestibulum lorem sed risus ultricies tristique. Vitae tortor condimentum lacinia quis vel eros donec. Morbi tempus iaculis urna id volutpat lacus laoreet non curabitur. Ut pharetra sit amet aliquam id diam. Eu non diam phasellus vestibulum lorem. Pharetra pharetra massa massa ultricies mi. Donec ultrices tincidunt arcu non. Sagittis orci a scelerisque purus semper eget duis. In iaculis nunc sed augue lacus viverra. Vitae proin sagittis nisl rhoncus mattis rhoncus urna neque. Consequat mauris nunc congue nisi vitae suscipit tellus mauris a. Massa placerat duis ultricies lacus sed turpis tincidunt id. Sit amet tellus cras adipiscing enim eu turpis. Amet porttitor eget dolor morbi non arcu risus quis varius. Potenti nullam ac tortor vitae purus.


text:
This project is no longer maintained or available in the App Store.
###

# Winston-Salem Crime Map
### A [RubyMotion](http://www.rubymotion.com/) application brought to you by [Off The Grid Apps](http://otgapps.io/).

![](https://raw.github.com/OTGApps/WSCrime/master/resources/Icon@2x.png)

This application was originally written in pure Objective-C and submitted to the app store. It went through multiple iterations as an XCode project until I heard about [RubyMotion](http://www.rubymotion.com/) and decided to use it as a chance to not only simplify the codebase for this app, but also to learn Ruby in the meantime.

Since I used this as a learning experience, I also wanted to put the code out there for others to learn from and to improve upon (iOS client only, not the server scraper and API).

This RubyMotion project is open source under the MIT license (see *License* file).

This app is a *universal application* (meaning that it works on both the iPhone and iPad). It has also been updated to work with the new screen size of the iPhone 5.

## Getting it

You can get the app one of two ways:

1. Clone this repos and run it in the siumlator (or on a device if you are a registered Apple Developer). ```git clone --recursive git://github.com/OTGApps/WSCrime.git```
2. Get it from the iTunes App Store:

[![image](http://ax.phobos.apple.com.edgesuite.net/images/web/linkmaker/badge_appstore-lrg.gif)](https://itunes.apple.com/us/app/winston-salem-crime-map/id472546582?mt=8&uo=4&at=10l4yY)

## Running the app

### Prerequisites:

1. XCode 4.5 with iOS 6 SDK.
2. You must have a registered and licensed copy or RubyMotion on your computer. If you do not, you will need to [purchase a license here](http://www.rubymotion.com/). Winston-Salem Crime Map requires at least RubyMotion 1.30 or later.
3. [Cocoapods](http://cocoapods.org/) must be installed.
4. Valid Apple Developer signing certificate (if you want to install on a device).

## Compiling:

1. ```cd``` into the WSCrimeMap directory and run ```bundle update```
2. Run ```rake``` and the application will build and launch the iOS simulator.

## ARKit

I recently introduced augmented reality into the app. I'm using [my own fork](https://github.com/markrickert/iPhone-AR-Toolkit) of [a1phanumeric](https://github.com/a1phanumeric)'s [iPhone AR Toolkit](https://github.com/a1phanumeric/iPhone-AR-Toolkit). The reason I'm using my own fork is because including it as a standard xcode project was crashing upon initialization. So I created a static library to use through XCode. I'll try and keep my fork up to date with the main project repo.

## Screenshots

![](https://raw.github.com/OTGApps/WSCrime/master/Marketing/Screenshots/iPhone-small/1.png)
![](https://raw.github.com/OTGApps/WSCrime/master/Marketing/Screenshots/iPhone-small/2.png)
![](https://raw.github.com/OTGApps/WSCrime/master/Marketing/Screenshots/iPhone-small/3.png)
![](https://raw.github.com/OTGApps/WSCrime/master/Marketing/Screenshots/iPhone-small/4.png)


text:
http://google.co.uk

test http://google.co.uk


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mingguo.avarua</groupId>
    <artifactId>cronhub-schedule-daemon</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>cronhub-schedule-daemon</name>

    <properties>
        <project.environment>dev</project.environment>
    </properties>

    <dependencies>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <classifier>jdk15</classifier>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-exec</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.8.0</version>
        </dependency>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-daemon</groupId>
            <artifactId>commons-daemon</artifactId>
            <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>it.sauronsoftware.cron4j</groupId>
            <artifactId>cron4j</artifactId>
            <version>2.2.5</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
    </dependencies>

</project>


text:
/*
        Leaflet.MapissoBuffer, a plugin for buffering drawn items on a Leaflet map.
        (c) 2015, Muhammet Emre Yildirim
        (c) 2015, mapisso.com and Innotech Software
        https://github.com/mapisso/Leaflet.MapissoBuffer
*/

L.Control.mapissoBuffer = L.Control.extend({
	options: {
	        position: 'topright'
	    },

    onAdd: function () {

    	    var buffer_panel_div = L.DomUtil.create('div', 'info'); // create a div with a class "info"

    	     buffer_panel_div.innerHTML = '
Mapisso Buffer Service
'+'' + 'Buffer Value:' + '

'+ '<input type="text" id="buffersize" value="10" style="width:100%" />'
		    +'

'+'<input id="bufferbutton" type="button" value="Buffer" onclick="buffer(oldlayer)" style="width:100%; height:35px"/>'+
		    '
Note: draw point, line, polygon and then, enter the buffer value, click the buffer button to star buffer operation.
';

    	    return buffer_panel_div;
    }

});

var id="";
function buffer(layer) {

	if (layer != undefined) {
		//console.log(oldlayer.toGeoJSON().geometry);
		try {
			var donen = mapissoBuffer.bufferGet(
							layer.toGeoJSON().geometry,
							document.getElementById('buffersize').value,
							key);

			L.geoJson(donen.response).addTo(map);
			id=donen.id;

		} catch (err) {
			alert(err);
		}
	} else {
		alert("First draw a shape!");
	}
}
function download(){
	if(id!=""&&oldlayer!=undefined){
		mapissoBuffer.getDownload(id);
	}
	else{
		alert("First buffer!");
	}
}


text:
namespace Google.Cloud.ResourceManager.V3.Snippets
{
    // [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]
    using Google.Cloud.ResourceManager.V3;
    using System.Threading.Tasks;

    public sealed partial class GeneratedTagKeysClientSnippets
    {
        /// <summary>Snippet for GetTagKeyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task GetTagKeyRequestObjectAsync()
        {
            // Create client
            TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
            // Initialize request argument(s)
            GetTagKeyRequest request = new GetTagKeyRequest
            {
                TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"),
            };
            // Make the request
            TagKey response = await tagKeysClient.GetTagKeyAsync(request);
        }
    }
    // [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012 Couchbase, Inc
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include "config.h"

#include <string.h>

#include <algorithm>
#include <cctype>
#include <cstdlib>

#include "couch-kvstore/couch-notifier.h"
#include "ep_engine.h"
#include "locks.h"
#define STATWRITER_NAMESPACE couch_notifier
#include "statwriter.h"
#undef STATWRITER_NAMESPACE

#ifdef WIN32
static ssize_t sendmsg(SOCKET s, const struct msghdr *msg, int flags);
#endif

/*
 * The various response handlers
 */
class BinaryPacketHandler {
public:
    BinaryPacketHandler(uint32_t sno) :
        seqno(sno), start(0)
    {
        start = gethrtime();
    }

    virtual ~BinaryPacketHandler() { /* EMPTY */ }

    virtual void request(protocol_binary_request_header *) {
        unsupported();
    }
    virtual void response(protocol_binary_response_header *) {
        unsupported();
    }

    virtual void implicitResponse() {
        // by default we don't use quiet commands..
        abort();
    }

    virtual void connectionReset() {
        abort();
    }

    uint32_t seqno;

    hrtime_t getDelta() {
        return (gethrtime() - start) / 1000;
    }

private:
    void unsupported() {
        LOG(EXTENSION_LOG_WARNING, "Unsupported packet received");
        abort();
    }

protected:
    hrtime_t start;
};

class DelVBucketResponseHandler: public BinaryPacketHandler {
public:
    DelVBucketResponseHandler(uint32_t sno, Callback<bool> &cb) :
        BinaryPacketHandler(sno), callback(cb) {
    }

    virtual void response(protocol_binary_response_header *res) {
        uint16_t rcode = ntohs(res->response.status);
        bool success = true;

        if (rcode != PROTOCOL_BINARY_RESPONSE_SUCCESS) {
            success = false;
        }

        callback.callback(success);
    }

    virtual void connectionReset() {
        bool value = false;
        callback.callback(value);
    }

private:
    Callback<bool> &callback;
};

class FlushResponseHandler: public BinaryPacketHandler {
public:
    FlushResponseHandler(uint32_t sno, Callback<bool> &cb) :
        BinaryPacketHandler(sno), callback(cb) {
    }

    virtual void response(protocol_binary_response_header *res) {
        uint16_t rcode = ntohs(res->response.status);
        bool success = true;

        if (rcode != PROTOCOL_BINARY_RESPONSE_SUCCESS) {
            success = false;
        }

        callback.callback(success);
    }

    virtual void connectionReset() {
        bool value = false;
        callback.callback(value);
    }

private:
    Callback<bool> &callback;
};

class SelectBucketResponseHandler: public BinaryPacketHandler {
public:
    SelectBucketResponseHandler(uint32_t sno) :
        BinaryPacketHandler(sno) {
    }

    virtual void response(protocol_binary_response_header *res) {
        uint16_t rcode = ntohs(res->response.status);

        if (rcode != PROTOCOL_BINARY_RESPONSE_SUCCESS) {
            // This should _NEVER_ happen!!!!
            abort();
        }
    }

    virtual void connectionReset() {
        // ignore
    }
};

class NotifyVbucketUpdateResponseHandler: public BinaryPacketHandler {
public:
    NotifyVbucketUpdateResponseHandler(uint32_t sno, Callback<uint16_t> &cb) :
        BinaryPacketHandler(sno), callback(cb) {
    }

    virtual void response(protocol_binary_response_header *res) {
        uint16_t rcode = ntohs(res->response.status);
        callback.callback(rcode);
    }

    virtual void connectionReset() {
        uint16_t rcode = PROTOCOL_BINARY_RESPONSE_ETMPFAIL;
        callback.callback(rcode);
    }

private:
    Callback<uint16_t> &callback;
};

/*
 * Implementation of the member functions in the CouchNotifier class
 */
CouchNotifier::CouchNotifier(EPStats &st, Configuration &config) :
    sock(INVALID_SOCKET), stats(st), configuration(config),
    configurationError(true), seqno(0),
    currentCommand(0xff), lastSentCommand(0xff), lastReceivedCommand(0xff),
    connected(false), inSelectBucket(false)
{
    memset(&sendMsg, 0, sizeof(sendMsg));
    sendMsg.msg_iov = sendIov;

    // Select the bucket (will be sent immediately when we connect)
    selectBucket();
}

void CouchNotifier::resetConnection() {
    LockHolder lh(mutex);
    LOG(EXTENSION_LOG_WARNING,
        "Resetting connection to mccouch, lastReceivedCommand = %s"
        " lastSentCommand = %s currentCommand =%s\n",
        cmd2str(lastReceivedCommand), cmd2str(lastSentCommand),
        cmd2str(currentCommand));
    lastReceivedCommand = 0xff;
    lastSentCommand = 0xff;
    currentCommand = 0xff;

    EVUTIL_CLOSESOCKET(sock);
    sock = INVALID_SOCKET;
    connected = false;
    input.avail = 0;

    std::list<BinaryPacketHandler*>::iterator iter;
    for (iter = responseHandler.begin(); iter != responseHandler.end(); ++iter) {
        (*iter)->connectionReset();
        delete *iter;
    }

    responseHandler.clear();
    lh.unlock();

    // insert the select vbucket command, if necessary
    if (!inSelectBucket) {
        selectBucket();
    }
}

void CouchNotifier::handleResponse(protocol_binary_response_header *res) {
    LockHolder lh(mutex);
    std::list<BinaryPacketHandler*>::iterator iter;
    for (iter = responseHandler.begin(); iter != responseHandler.end()
            && (*iter)->seqno < res->response.opaque; ++iter) {

        // TROND
        // Buffer *b = (*iter)->getCommandBuffer();
        // commandStats[static_cast<uint8_t>(b->data[1])].numImplicit++;
        (*iter)->implicitResponse();
        delete *iter;
    }

    if (iter == responseHandler.end() || (*iter)->seqno != res->response.opaque) {
        if (iter != responseHandler.begin()) {
            responseHandler.erase(responseHandler.begin(), iter);
        }
        return;
    }

    int cmdId = commandId(res->response.opcode);
    if (ntohs(res->response.status) == PROTOCOL_BINARY_RESPONSE_SUCCESS){
        commandStats[cmdId].numSuccess++;
    } else {
        LOG(EXTENSION_LOG_WARNING,
            "Received error[%X] from mccouch for %s\n",
            ntohs(res->response.status), cmd2str(currentCommand));
        commandStats[cmdId].numError++;
    }
    (*iter)->response(res);
    if (res->response.opcode == PROTOCOL_BINARY_CMD_STAT
            && res->response.bodylen != 0) {
        // a stats command is terminated with an empty packet..
    } else {
        delete *iter;
        ++iter;
    }

    responseHandler.erase(responseHandler.begin(), iter);
}

bool CouchNotifier::connect() {
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags = AI_PASSIVE;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family = AF_UNSPEC;

    size_t port = configuration.getCouchPort();
    std::string host = configuration.getCouchHost();
    const char *hptr = host.c_str();
    if (host.empty()) {
        hptr = NULL;
    }

    std::stringstream ss;
    ss << port;

    struct addrinfo *ainfo = NULL;
    int error = getaddrinfo(hptr, ss.str().c_str(), &hints, &ainfo);
    if (error != 0) {
        std::stringstream msg;
        msg << "Failed to look up address information for: \"";
        if (hptr != NULL) {
            msg << hptr << ":";
        }
        msg << port << "\"";
        LOG(EXTENSION_LOG_WARNING, "%s", msg.str().c_str());
        configurationError = true;
        ainfo = NULL;
        return false;
    }

    struct addrinfo *ai = ainfo;
    while (ai != NULL) {
        sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);

        if (sock != -1) {
            if (::connect(sock, ai->ai_addr, ai->ai_addrlen) != -1 &&
                evutil_make_socket_nonblocking(sock) == 0) {
                break;
            }
            EVUTIL_CLOSESOCKET(sock);
            sock = INVALID_SOCKET;
        }
        ai = ai->ai_next;
    }

    freeaddrinfo(ainfo);
    if (sock == INVALID_SOCKET) {
        std::stringstream msg;
        msg << "Failed to connect to: \"";
        if (hptr != NULL) {
            msg << hptr << ":";
        }
        msg << port << "\"";
        LOG(EXTENSION_LOG_WARNING, "%s\n", msg.str().c_str());
        configurationError = true;
        return false;
    }

    // @fixme
    connected = true;

    return true;
}

void CouchNotifier::ensureConnection()
{
    if (!connected) {
        // I need to connect!!!
        std::stringstream rv;
        rv << "Trying to connect to mccouch: \""
           << configuration.getCouchHost().c_str() << ":"
           << configuration.getCouchPort() << "\"";

        LOG(EXTENSION_LOG_WARNING, "%s\n", rv.str().c_str());
        while (!connect()) {
            if (stats.forceShutdown && stats.shutdown.isShutdown) {
                return ;
            }

            if (configuration.isAllowDataLossDuringShutdown() && getppid() == 1) {
                LOG(EXTENSION_LOG_WARNING,
                    "Parent process is gone and you allow data loss during"
                    "shutdown. Terminating without without syncing all data.");
                _exit(1);
            }
            if (configurationError) {
                rv.str(std::string());
                rv << "Failed to connect to: \""
                   << configuration.getCouchHost().c_str() << ":"
                   << configuration.getCouchPort() << "\"";
                LOG(EXTENSION_LOG_WARNING, "%s", rv.str().c_str());

                usleep(5000);
                // we might have new configuration parameters...
                configurationError = false;
            } else {
                rv.str(std::string());
                rv << "Connection refused: \""
                   << configuration.getCouchHost().c_str() << ":"
                   << configuration.getCouchPort() << "\"";
                LOG(EXTENSION_LOG_WARNING, "%s", rv.str().c_str());
                usleep(configuration.getCouchReconnectSleeptime());
            }
        }
        rv.str(std::string());
        rv << "Connected to mccouch: \""
           << configuration.getCouchHost().c_str() << ":"
           << configuration.getCouchPort() << "\"";
        LOG(EXTENSION_LOG_WARNING, "%s", rv.str().c_str());
    }
}

bool CouchNotifier::waitForWritable()
{
    size_t timeout = 1000;
    size_t waitTime = 0;

    while (connected) {
        struct pollfd fds;
        fds.fd = sock;
        fds.events = POLLIN | POLLOUT;
        fds.revents = 0;

        // @todo do not block forever.. but allow shutdown..
        int ret = poll(&fds, 1, timeout);
        if (ret > 0) {
            if (fds.revents & POLLIN) {
                maybeProcessInput();
            }

            if (fds.revents & POLLOUT) {
                return true;
            }
        } else if (ret < 0) {
            LOG(EXTENSION_LOG_WARNING, "poll() failed: \"%s\"",
                strerror(errno));
            resetConnection();
        }  else if ((waitTime += timeout) >= configuration.getCouchResponseTimeout()) {
            // Poll failed due to timeouts multiple times and is above timeout threshold.
            LOG(EXTENSION_LOG_WARNING,
                "No response for mccouch in %ld seconds. Resetting connection.",
                waitTime);
            resetConnection();
        }
    }

    return false;
}

void CouchNotifier::sendSingleChunk(const char *ptr, size_t nb)
{
    while (nb > 0) {
        ssize_t nw = send(sock, ptr, nb, 0);
        if (nw == -1) {
            switch (errno) {
            case EINTR:
                // retry
                break;

            case EWOULDBLOCK:
                if (!waitForWritable()) {
                    return;
                }
                break;

            default:
                LOG(EXTENSION_LOG_WARNING,
                    "Failed to send data to mccouch: \"%s\"", strerror(errno));
                abort();
                return ;
            }
        } else {
            ptr += (size_t)nw;
            nb -= nw;
            if (nb != 0) {
                // We failed to send all of the data... we should take a
                // short break to let the receiving side get a chance
                // to drain the buffer..
                LOG(EXTENSION_LOG_WARNING,
                    "Failed to send all data. Wait a while until mccouch "
                    "is ready to receive more data, reamins = %ld\n", nb);
                usleep(10);
            }
        }
    }
}

void CouchNotifier::sendCommand(BinaryPacketHandler *rh)
{
    currentCommand = reinterpret_cast<uint8_t*>(sendIov[0].iov_base)[1];
    int cmdId = commandId(currentCommand);
    ensureConnection();
    responseHandler.push_back(rh);
    maybeProcessInput();
    if (!connected) {
        // we might have been disconnected
        LOG(EXTENSION_LOG_WARNING,
            "Failed to send data for %s: connection to mccouch is "
            "not established successfully", cmd2str(currentCommand));
        commandStats[cmdId].numError++;
        return;
    }

    do {
        sendMsg.msg_iovlen = numiovec;
        ssize_t nw = sendmsg(sock, &sendMsg, 0);
        if (nw == -1) {
            switch (errno) {
            case EMSGSIZE:
                // Too big.. try to use send instead..
                for (int ii = 0; ii < numiovec; ++ii) {
                    sendSingleChunk((const char*)(sendIov[ii].iov_base), sendIov[ii].iov_len);
                }
                break;

            case EINTR:
                // retry
                LOG(EXTENSION_LOG_WARNING,
                    "Failed to send data to mccouch for %s: \"%s\" "
                    "will retry immediately\n",
                    cmd2str(currentCommand), strerror(errno));
                break;

            case EWOULDBLOCK:
                if (!waitForWritable()) {
                    return;
                }
                break;
            default:
                LOG(EXTENSION_LOG_WARNING,
                    "Failed to send data to mccouch for %s: \"%s\"",
                    cmd2str(currentCommand), strerror(errno));
                resetConnection();
                return;
            }
        } else {
            size_t towrite = 0;
            for (int ii = 0; ii < numiovec; ++ii) {
                towrite += sendIov[ii].iov_len;
            }

            if (towrite == static_cast<size_t>(nw)) {
                // Everything successfully sent!
                lastSentCommand = currentCommand;
                commandStats[cmdId].numSent++;
                currentCommand = static_cast<uint8_t>(0xff);
                return;
            } else {
                // We failed to send all of the data... we should take a
                // short break to let the receiving side get a chance
                // to drain the buffer..
                size_t rms = static_cast<size_t>(nw) - towrite;
                LOG(EXTENSION_LOG_WARNING,
                    "Failed to send all data. Wait a while until mccouch "
                    "is ready to receive more data, remains = %ld\n", rms);
                usleep(10);

                // Figure out how much we sent, and repack the stuff
                for (int ii = 0; ii < numiovec && nw > 0; ++ii) {
                    if (sendIov[ii].iov_len <= (size_t)nw) {
                        nw -= sendIov[ii].iov_len;
                        sendIov[ii].iov_len = 0;
                    } else {
                        // only parts of this iovector was sent..
                        sendIov[ii].iov_base = static_cast<char*>(sendIov[ii].iov_base) + nw;
                        sendIov[ii].iov_len -= nw;
                        nw = 0;
                    }
                }

                // Do I need to fix the iovector...
                int index = 0;
                for (int ii = 0; ii < numiovec; ++ii) {
                    if (sendIov[ii].iov_len != 0) {
                        if (index == ii) {
                            index = numiovec;
                            break;
                        }
                        sendIov[index].iov_len = sendIov[ii].iov_len;
                        sendIov[index].iov_base = sendIov[ii].iov_base;
                        ++index;
                    }
                }
                numiovec = index;
            }
        }
    } while (true);
}

void CouchNotifier::maybeProcessInput()
{
    struct pollfd fds;
    fds.fd = sock;
    fds.events = POLLIN;
    fds.revents = 0;

    // @todo check for the #msg sent to avoid a shitload
    // extra syscalls
    int ret= poll(&fds, 1, 0);
    if (ret > 0 && (fds.revents & POLLIN) == POLLIN) {
        processInput();
    }
}

bool CouchNotifier::processInput() {
    // we don't want to block unless there is a message there..
    // this will unfortunately increase the overhead..
    assert(sock != INVALID_SOCKET);

    size_t processed;
    protocol_binary_response_header *res;

    input.grow(8192);
    res = (protocol_binary_response_header *)input.data;

    do {
        ssize_t nr;
        while (input.avail >= sizeof(*res) && input.avail >= (ntohl(
                res->response.bodylen) + sizeof(*res))) {

            lastReceivedCommand = res->response.opcode;
            switch (res->response.magic) {
            case PROTOCOL_BINARY_RES:
                handleResponse(res);
                break;
            default:
                LOG(EXTENSION_LOG_WARNING,
                    "Rubbish received on the backend stream. closing it");
                resetConnection();
                return false;
            }

            processed = ntohl(res->response.bodylen) + sizeof(*res);
            memmove(input.data, input.data + processed, input.avail - processed);
            input.avail -= processed;
        }

        if (input.size - input.avail == 0) {
            input.grow();
        }

        nr = recv(sock, input.data + input.avail, input.size - input.avail, 0);
        if (nr == -1) {
            switch (errno) {
            case EINTR:
                LOG(EXTENSION_LOG_WARNING,
                    "Failed to receive data from mccouch for %s: \"%s\" "
                    "will retry immediately\n",
                    cmd2str(currentCommand), strerror(errno));
                break;
            case EWOULDBLOCK:
                return true;
            default:
                LOG(EXTENSION_LOG_WARNING,
                    "Failed to read from mccouch: \"%s\"", strerror(errno));
                resetConnection();
                return false;
            }
        } else if (nr == 0) {
            LOG(EXTENSION_LOG_WARNING, "Connection closed by mccouch");
            resetConnection();
            return false;
        } else {
            input.avail += (size_t)nr;
        }
    } while (true);

    return true;
}

bool CouchNotifier::waitForReadable(bool tryOnce)
{
    size_t timeout = 1000;
    size_t waitTime = 0;

    while (connected) {
        bool reconnect = false;
        struct pollfd fds;
        fds.fd = sock;
        fds.events = POLLIN;
        fds.revents = 0;

        // @todo do not block forever.. but allow shutdown..
        int ret = poll(&fds, 1, timeout);
        if (ret > 0) {
            if (fds.revents & POLLIN) {
                return true;
            }
        } else if (ret < 0) {
            LOG(EXTENSION_LOG_WARNING,
                             "poll() failed: \"%s\"",
                             strerror(errno));
            reconnect = true;
        } else if ((waitTime += timeout) >= configuration.getCouchResponseTimeout()) {
            // Poll failed due to timeouts multiple times and is above timeout threshold.
            LOG(EXTENSION_LOG_WARNING,
                "No response for mccouch in %ld seconds. Resetting connection.",
                waitTime);
            reconnect = true;
        }

        if (reconnect) {
            resetConnection();
            if (tryOnce) {
                return false;
            }
        }
    }

    return false;
}

void CouchNotifier::wait()
{
    std::list<BinaryPacketHandler*> *handler = &responseHandler;

    while (!handler->empty() && waitForReadable()) {
        // We don't want to busy-loop, so wait until there is something
        // there...
        processInput();
    }
}

bool CouchNotifier::waitOnce()
{
    std::list<BinaryPacketHandler*> *handler = &responseHandler;

    bool succeed = false;
    while (!handler->empty() && (succeed = waitForReadable(true))) {
        succeed = processInput();
    }
    return succeed;
}

void CouchNotifier::delVBucket(uint16_t vb, Callback<bool> &cb) {
    protocol_binary_request_del_vbucket req;
    // delete vbucket must wait for a response
    do {
        memset(req.bytes, 0, sizeof(req.bytes));
        req.message.header.request.magic = PROTOCOL_BINARY_REQ;
        req.message.header.request.opcode = PROTOCOL_BINARY_CMD_DEL_VBUCKET;
        req.message.header.request.vbucket = ntohs(vb);
        req.message.header.request.datatype = PROTOCOL_BINARY_RAW_BYTES;
        req.message.header.request.opaque = seqno;

        sendIov[0].iov_base = (char*)req.bytes;
        sendIov[0].iov_len = sizeof(req.bytes);
        numiovec = 1;

        sendCommand(new DelVBucketResponseHandler(seqno++, cb));
    } while (!waitOnce());
}

void CouchNotifier::flush(Callback<bool> &cb) {
    protocol_binary_request_flush req;
    // flush must wait for a response
    do {
        memset(req.bytes, 0, sizeof(req.bytes));
        req.message.header.request.magic = PROTOCOL_BINARY_REQ;
        req.message.header.request.opcode = PROTOCOL_BINARY_CMD_FLUSH;
        req.message.header.request.datatype = PROTOCOL_BINARY_RAW_BYTES;
        req.message.header.request.extlen = 4;
        req.message.header.request.bodylen = ntohl(4);
        req.message.header.request.opaque = seqno;
        sendIov[0].iov_base = (char*)req.bytes;
        sendIov[0].iov_len = sizeof(req.bytes);
        numiovec = 1;

        sendCommand(new FlushResponseHandler(seqno++, cb));
    } while (!waitOnce());
}

void CouchNotifier::selectBucket() {
    std::string name = configuration.getCouchBucket();
    protocol_binary_request_no_extras req;

    // select bucket must succeed
    do {
        memset(req.bytes, 0, sizeof(req.bytes));
        req.message.header.request.magic = PROTOCOL_BINARY_REQ;
        req.message.header.request.opcode = 0x89;
        req.message.header.request.datatype = PROTOCOL_BINARY_RAW_BYTES;
        req.message.header.request.opaque = seqno;
        req.message.header.request.keylen = ntohs((uint16_t)name.length());
        req.message.header.request.bodylen = ntohl((uint32_t)name.length());

        sendIov[0].iov_base = (char*)req.bytes;
        sendIov[0].iov_len = sizeof(req.bytes);
        sendIov[1].iov_base = const_cast<char*>(name.c_str());
        sendIov[1].iov_len = name.length();
        numiovec = 2;

        inSelectBucket = true;
        sendCommand(new SelectBucketResponseHandler(seqno++));
    } while (!waitOnce());

    inSelectBucket = false;
}

void CouchNotifier::notify_update(const VBStateNotification &vbs,
                                  uint64_t file_version,
                                  uint64_t header_offset,
                                  Callback<uint16_t> &cb)
{
    protocol_binary_request_notify_vbucket_update req;
    // notify_bucket must wait for a response
    do {
        memset(req.bytes, 0, sizeof(req.bytes));
        req.message.header.request.magic = PROTOCOL_BINARY_REQ;
        req.message.header.request.opcode = CMD_NOTIFY_VBUCKET_UPDATE;
        req.message.header.request.datatype = PROTOCOL_BINARY_RAW_BYTES;
        req.message.header.request.vbucket = ntohs(vbs.vbucket);
        req.message.header.request.opaque = seqno;
        req.message.header.request.bodylen = ntohl(32);

        req.message.body.file_version = ntohll(file_version);
        req.message.body.header_offset = ntohll(header_offset);
        req.message.body.vbucket_state_updated = ntohl(vbs.updateType);
        req.message.body.state = ntohl(vbs.state);
        req.message.body.checkpoint = ntohll(vbs.checkpoint);

        sendIov[0].iov_base = (char*)req.bytes;
        sendIov[0].iov_len = sizeof(req.bytes);
        numiovec = 1;

        sendCommand(new NotifyVbucketUpdateResponseHandler(seqno++, cb));
    } while(!waitOnce());
}

void CouchNotifier::addStats(const std::string &prefix,
                             ADD_STAT add_stat,
                             const void *c)
{
    for (uint8_t ii = 0; ii < MAX_NUM_NOTIFIER_CMD; ++ii) {
        commandStats[ii].addStats(prefix, cmdId2str(ii), add_stat, c);
    }
    add_prefixed_stat(prefix, "current_command", cmd2str(currentCommand), add_stat, c);
    add_prefixed_stat(prefix, "last_sent_command", cmd2str(lastSentCommand), add_stat, c);
    add_prefixed_stat(prefix, "last_received_command", cmd2str(lastReceivedCommand),
            add_stat, c);
}

const char *CouchNotifier::cmd2str(uint8_t cmd)
{
    switch(cmd) {
    case PROTOCOL_BINARY_CMD_DEL_VBUCKET:
        return "del_vbucket";
    case PROTOCOL_BINARY_CMD_FLUSH:
        return "flush";
    case CMD_NOTIFY_VBUCKET_UPDATE:
        return "notify_vbucket_update";
    case 0x89 :
        return "select_bucket";
    default:
        return "unknown";
    }
}

int CouchNotifier::commandId(uint8_t opcode) {
    switch(opcode) {
    case PROTOCOL_BINARY_CMD_DEL_VBUCKET:
        return del_vbucket_cmd;
    case PROTOCOL_BINARY_CMD_FLUSH:
        return flush_vbucket_cmd;
    case CMD_NOTIFY_VBUCKET_UPDATE:
        return update_vbucket_cmd;
    case 0x89 :
        return select_bucket_cmd;
    default:
        return unknown_cmd;
    }
}

const char *CouchNotifier::cmdId2str(int id) {
    switch(id) {
    case del_vbucket_cmd:
        return cmd2str(PROTOCOL_BINARY_CMD_DEL_VBUCKET);
    case flush_vbucket_cmd:
        return cmd2str(PROTOCOL_BINARY_CMD_FLUSH);
    case update_vbucket_cmd:
        return cmd2str(CMD_NOTIFY_VBUCKET_UPDATE);
    case select_bucket_cmd:
        return cmd2str(0x89);
     default:
        return "unknown";
    }
}


text:
from django.contrib import admin

from .models import Club

class ClubAdmin(admin.ModelAdmin):
  list_display = ('name_short', 'name_long', 'site')

admin.site.register(Club, ClubAdmin)


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment">

    <TextView
        android:id="@+id/timerDisplay"
        android:text="@string/timerDisplay"
        android:textAlignment="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:layout_centerInParent="true"
        android:textSize="32dp"
        android:textIsSelectable="false" />

</RelativeLayout>


text:
<?php

namespace Welinkeo\UtilisateurBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Lignecommande
 *
 * @ORM\Table(name="lignecommande", indexes={@ORM\Index(name="fk_ligneCommande_commande1_idx", columns={"commande_numeroCommande"})})
 * @ORM\Entity
 */
class Lignecommande
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="qauntiteCommandee", type="integer", nullable=false)
     */
    private $qauntitecommandee;

    /**
     * @var float
     *
     * @ORM\Column(name="montantTotal", type="float", precision=10, scale=0, nullable=false)
     */
    private $montanttotal;

    /**
     * @var integer
     *
     * @ORM\Column(name="referenceProduit", type="integer", nullable=false)
     */
    private $referenceproduit;

    /**
     * @var string
     *
     * @ORM\Column(name="descriptionProduit", type="text", nullable=false)
     */
    private $descriptionproduit;

    /**
     * @var float
     *
     * @ORM\Column(name="PrixProduit", type="float", precision=10, scale=0, nullable=false)
     */
    private $prixproduit;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateDisponiblite", type="date", nullable=true)
     */
    private $datedisponiblite;

    /**
     * @var \Commande
     *
     * @ORM\ManyToOne(targetEntity="Commande")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="commande_numeroCommande", referencedColumnName="numeroCommande")
     * })
     */
    private $commandeNumerocommande;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set qauntitecommandee
     *
     * @param integer $qauntitecommandee
     *
     * @return Lignecommande
     */
    public function setQauntitecommandee($qauntitecommandee)
    {
        $this->qauntitecommandee = $qauntitecommandee;

        return $this;
    }

    /**
     * Get qauntitecommandee
     *
     * @return integer
     */
    public function getQauntitecommandee()
    {
        return $this->qauntitecommandee;
    }

    /**
     * Set montanttotal
     *
     * @param float $montanttotal
     *
     * @return Lignecommande
     */
    public function setMontanttotal($montanttotal)
    {
        $this->montanttotal = $montanttotal;

        return $this;
    }

    /**
     * Get montanttotal
     *
     * @return float
     */
    public function getMontanttotal()
    {
        return $this->montanttotal;
    }

    /**
     * Set referenceproduit
     *
     * @param integer $referenceproduit
     *
     * @return Lignecommande
     */
    public function setReferenceproduit($referenceproduit)
    {
        $this->referenceproduit = $referenceproduit;

        return $this;
    }

    /**
     * Get referenceproduit
     *
     * @return integer
     */
    public function getReferenceproduit()
    {
        return $this->referenceproduit;
    }

    /**
     * Set descriptionproduit
     *
     * @param string $descriptionproduit
     *
     * @return Lignecommande
     */
    public function setDescriptionproduit($descriptionproduit)
    {
        $this->descriptionproduit = $descriptionproduit;

        return $this;
    }

    /**
     * Get descriptionproduit
     *
     * @return string
     */
    public function getDescriptionproduit()
    {
        return $this->descriptionproduit;
    }

    /**
     * Set prixproduit
     *
     * @param float $prixproduit
     *
     * @return Lignecommande
     */
    public function setPrixproduit($prixproduit)
    {
        $this->prixproduit = $prixproduit;

        return $this;
    }

    /**
     * Get prixproduit
     *
     * @return float
     */
    public function getPrixproduit()
    {
        return $this->prixproduit;
    }

    /**
     * Set datedisponiblite
     *
     * @param \DateTime $datedisponiblite
     *
     * @return Lignecommande
     */
    public function setDatedisponiblite($datedisponiblite)
    {
        $this->datedisponiblite = $datedisponiblite;

        return $this;
    }

    /**
     * Get datedisponiblite
     *
     * @return \DateTime
     */
    public function getDatedisponiblite()
    {
        return $this->datedisponiblite;
    }

    /**
     * Set commandeNumerocommande
     *
     * @param \Welinkeo\UtilisateurBundle\Entity\Commande $commandeNumerocommande
     *
     * @return Lignecommande
     */
    public function setCommandeNumerocommande(\Welinkeo\UtilisateurBundle\Entity\Commande $commandeNumerocommande = null)
    {
        $this->commandeNumerocommande = $commandeNumerocommande;

        return $this;
    }

    /**
     * Get commandeNumerocommande
     *
     * @return \Welinkeo\UtilisateurBundle\Entity\Commande
     */
    public function getCommandeNumerocommande()
    {
        return $this->commandeNumerocommande;
    }
}


text:
package agent

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"reflect"
	"testing"
	"time"

	"github.com/hashicorp/consul/consul/structs"
	"github.com/hashicorp/consul/testutil"
	"github.com/hashicorp/serf/coordinate"
)

func TestHealthChecksInState(t *testing.T) {
	httpTest(t, func(srv *HTTPServer) {
		req, err := http.NewRequest("GET", "/v1/health/state/warning?dc=dc1", nil)
		if err != nil {
			t.Fatalf("err: %v", err)
		}

		testutil.WaitForResult(func() (bool, error) {
			resp := httptest.NewRecorder()
			obj, err := srv.HealthChecksInState(resp, req)
			if err != nil {
				return false, err
			}
			if err := checkIndex(resp); err != nil {
				return false, err
			}

			// Should be a non-nil empty list
			nodes := obj.(structs.HealthChecks)
			if nodes == nil || len(nodes) != 0 {
				return false, fmt.Errorf("bad: %v", obj)
			}
			return true, nil
		}, func(err error) { t.Fatalf("err: %v", err) })
	})

	httpTest(t, func(srv *HTTPServer) {
		req, err := http.NewRequest("GET", "/v1/health/state/passing?dc=dc1", nil)
		if err != nil {
			t.Fatalf("err: %v", err)
		}

		testutil.WaitForResult(func() (bool, error) {
			resp := httptest.NewRecorder()
			obj, err := srv.HealthChecksInState(resp, req)
			if err != nil {
				return false, err
			}
			if err := checkIndex(resp); err != nil {
				return false, err
			}

			// Should be 1 health check for the server
			nodes := obj.(structs.HealthChecks)
			if len(nodes) != 1 {
				return false, fmt.Errorf("bad: %v", obj)
			}
			return true, nil
		}, func(err error) { t.Fatalf("err: %v", err) })
	})
}

func TestHealthChecksInState_DistanceSort(t *testing.T) {
	dir, srv := makeHTTPServer(t)
	defer os.RemoveAll(dir)
	defer srv.Shutdown()
	defer srv.agent.Shutdown()

	testutil.WaitForLeader(t, srv.agent.RPC, "dc1")

	args := &structs.RegisterRequest{
		Datacenter: "dc1",
		Node:       "bar",
		Address:    "127.0.0.1",
		Check: &structs.HealthCheck{
			Node:   "bar",
			Name:   "node check",
			Status: structs.HealthCritical,
		},
	}

	var out struct{}
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	args.Node, args.Check.Node = "foo", "foo"
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	req, err := http.NewRequest("GET", "/v1/health/state/critical?dc=dc1&near=foo", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp := httptest.NewRecorder()
	obj, err := srv.HealthChecksInState(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)
	nodes := obj.(structs.HealthChecks)
	if len(nodes) != 2 {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[0].Node != "bar" {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[1].Node != "foo" {
		t.Fatalf("bad: %v", nodes)
	}

	// Send an update for the node and wait for it to get applied.
	arg := structs.CoordinateUpdateRequest{
		Datacenter: "dc1",
		Node:       "foo",
		Coord:      coordinate.NewCoordinate(coordinate.DefaultConfig()),
	}
	if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
		t.Fatalf("err: %v", err)
	}
	time.Sleep(300 * time.Millisecond)

	// Query again and now foo should have moved to the front of the line.
	resp = httptest.NewRecorder()
	obj, err = srv.HealthChecksInState(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)
	nodes = obj.(structs.HealthChecks)
	if len(nodes) != 2 {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[0].Node != "foo" {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[1].Node != "bar" {
		t.Fatalf("bad: %v", nodes)
	}
}

func TestHealthNodeChecks(t *testing.T) {
	dir, srv := makeHTTPServer(t)
	defer os.RemoveAll(dir)
	defer srv.Shutdown()
	defer srv.agent.Shutdown()

	testutil.WaitForLeader(t, srv.agent.RPC, "dc1")

	req, err := http.NewRequest("GET", "/v1/health/node/nope?dc=dc1", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp := httptest.NewRecorder()
	obj, err := srv.HealthNodeChecks(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)

	// Should be a non-nil empty list
	nodes := obj.(structs.HealthChecks)
	if nodes == nil || len(nodes) != 0 {
		t.Fatalf("bad: %v", obj)
	}

	req, err = http.NewRequest("GET",
		fmt.Sprintf("/v1/health/node/%s?dc=dc1", srv.agent.config.NodeName), nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp = httptest.NewRecorder()
	obj, err = srv.HealthNodeChecks(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)

	// Should be 1 health check for the server
	nodes = obj.(structs.HealthChecks)
	if len(nodes) != 1 {
		t.Fatalf("bad: %v", obj)
	}
}

func TestHealthServiceChecks(t *testing.T) {
	dir, srv := makeHTTPServer(t)
	defer os.RemoveAll(dir)
	defer srv.Shutdown()
	defer srv.agent.Shutdown()

	testutil.WaitForLeader(t, srv.agent.RPC, "dc1")

	req, err := http.NewRequest("GET", "/v1/health/checks/consul?dc=dc1", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp := httptest.NewRecorder()
	obj, err := srv.HealthServiceChecks(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)

	// Should be a non-nil empty list
	nodes := obj.(structs.HealthChecks)
	if nodes == nil || len(nodes) != 0 {
		t.Fatalf("bad: %v", obj)
	}

	// Create a service check
	args := &structs.RegisterRequest{
		Datacenter: "dc1",
		Node:       srv.agent.config.NodeName,
		Address:    "127.0.0.1",
		Check: &structs.HealthCheck{
			Node:      srv.agent.config.NodeName,
			Name:      "consul check",
			ServiceID: "consul",
		},
	}

	var out struct{}
	if err = srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	req, err = http.NewRequest("GET", "/v1/health/checks/consul?dc=dc1", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp = httptest.NewRecorder()
	obj, err = srv.HealthServiceChecks(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)

	// Should be 1 health check for consul
	nodes = obj.(structs.HealthChecks)
	if len(nodes) != 1 {
		t.Fatalf("bad: %v", obj)
	}
}

func TestHealthServiceChecks_DistanceSort(t *testing.T) {
	dir, srv := makeHTTPServer(t)
	defer os.RemoveAll(dir)
	defer srv.Shutdown()
	defer srv.agent.Shutdown()

	testutil.WaitForLeader(t, srv.agent.RPC, "dc1")

	// Create a service check
	args := &structs.RegisterRequest{
		Datacenter: "dc1",
		Node:       "bar",
		Address:    "127.0.0.1",
		Service: &structs.NodeService{
			ID:      "test",
			Service: "test",
		},
		Check: &structs.HealthCheck{
			Node:      "bar",
			Name:      "test check",
			ServiceID: "test",
		},
	}

	var out struct{}
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	args.Node, args.Check.Node = "foo", "foo"
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	req, err := http.NewRequest("GET", "/v1/health/checks/test?dc=dc1&near=foo", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp := httptest.NewRecorder()
	obj, err := srv.HealthServiceChecks(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)
	nodes := obj.(structs.HealthChecks)
	if len(nodes) != 2 {
		t.Fatalf("bad: %v", obj)
	}
	if nodes[0].Node != "bar" {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[1].Node != "foo" {
		t.Fatalf("bad: %v", nodes)
	}

	// Send an update for the node and wait for it to get applied.
	arg := structs.CoordinateUpdateRequest{
		Datacenter: "dc1",
		Node:       "foo",
		Coord:      coordinate.NewCoordinate(coordinate.DefaultConfig()),
	}
	if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
		t.Fatalf("err: %v", err)
	}
	time.Sleep(300 * time.Millisecond)

	// Query again and now foo should have moved to the front of the line.
	resp = httptest.NewRecorder()
	obj, err = srv.HealthServiceChecks(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)
	nodes = obj.(structs.HealthChecks)
	if len(nodes) != 2 {
		t.Fatalf("bad: %v", obj)
	}
	if nodes[0].Node != "foo" {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[1].Node != "bar" {
		t.Fatalf("bad: %v", nodes)
	}
}

func TestHealthServiceNodes(t *testing.T) {
	dir, srv := makeHTTPServer(t)
	defer os.RemoveAll(dir)
	defer srv.Shutdown()
	defer srv.agent.Shutdown()

	testutil.WaitForLeader(t, srv.agent.RPC, "dc1")

	req, err := http.NewRequest("GET", "/v1/health/service/consul?dc=dc1", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp := httptest.NewRecorder()
	obj, err := srv.HealthServiceNodes(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	assertIndex(t, resp)

	// Should be 1 health check for consul
	nodes := obj.(structs.CheckServiceNodes)
	if len(nodes) != 1 {
		t.Fatalf("bad: %v", obj)
	}

	req, err = http.NewRequest("GET", "/v1/health/service/nope?dc=dc1", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp = httptest.NewRecorder()
	obj, err = srv.HealthServiceNodes(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	assertIndex(t, resp)

	// Should be a non-nil empty list
	nodes = obj.(structs.CheckServiceNodes)
	if nodes == nil || len(nodes) != 0 {
		t.Fatalf("bad: %v", obj)
	}

	args := &structs.RegisterRequest{
		Datacenter: "dc1",
		Node:       "bar",
		Address:    "127.0.0.1",
		Service: &structs.NodeService{
			ID:      "test",
			Service: "test",
		},
	}

	var out struct{}
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	req, err = http.NewRequest("GET", "/v1/health/service/test?dc=dc1", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp = httptest.NewRecorder()
	obj, err = srv.HealthServiceNodes(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	assertIndex(t, resp)

	// Should be a non-nil empty list for checks
	nodes = obj.(structs.CheckServiceNodes)
	if len(nodes) != 1 || nodes[0].Checks == nil || len(nodes[0].Checks) != 0 {
		t.Fatalf("bad: %v", obj)
	}
}

func TestHealthServiceNodes_DistanceSort(t *testing.T) {
	dir, srv := makeHTTPServer(t)
	defer os.RemoveAll(dir)
	defer srv.Shutdown()
	defer srv.agent.Shutdown()

	testutil.WaitForLeader(t, srv.agent.RPC, "dc1")

	// Create a service check
	args := &structs.RegisterRequest{
		Datacenter: "dc1",
		Node:       "bar",
		Address:    "127.0.0.1",
		Service: &structs.NodeService{
			ID:      "test",
			Service: "test",
		},
		Check: &structs.HealthCheck{
			Node:      "bar",
			Name:      "test check",
			ServiceID: "test",
		},
	}

	var out struct{}
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	args.Node, args.Check.Node = "foo", "foo"
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	req, err := http.NewRequest("GET", "/v1/health/service/test?dc=dc1&near=foo", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp := httptest.NewRecorder()
	obj, err := srv.HealthServiceNodes(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)
	nodes := obj.(structs.CheckServiceNodes)
	if len(nodes) != 2 {
		t.Fatalf("bad: %v", obj)
	}
	if nodes[0].Node.Node != "bar" {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[1].Node.Node != "foo" {
		t.Fatalf("bad: %v", nodes)
	}

	// Send an update for the node and wait for it to get applied.
	arg := structs.CoordinateUpdateRequest{
		Datacenter: "dc1",
		Node:       "foo",
		Coord:      coordinate.NewCoordinate(coordinate.DefaultConfig()),
	}
	if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
		t.Fatalf("err: %v", err)
	}
	time.Sleep(300 * time.Millisecond)

	// Query again and now foo should have moved to the front of the line.
	resp = httptest.NewRecorder()
	obj, err = srv.HealthServiceNodes(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	assertIndex(t, resp)
	nodes = obj.(structs.CheckServiceNodes)
	if len(nodes) != 2 {
		t.Fatalf("bad: %v", obj)
	}
	if nodes[0].Node.Node != "foo" {
		t.Fatalf("bad: %v", nodes)
	}
	if nodes[1].Node.Node != "bar" {
		t.Fatalf("bad: %v", nodes)
	}
}

func TestHealthServiceNodes_PassingFilter(t *testing.T) {
	dir, srv := makeHTTPServer(t)
	defer os.RemoveAll(dir)
	defer srv.Shutdown()
	defer srv.agent.Shutdown()

	testutil.WaitForLeader(t, srv.agent.RPC, "dc1")

	// Create a failing service check
	args := &structs.RegisterRequest{
		Datacenter: "dc1",
		Node:       srv.agent.config.NodeName,
		Address:    "127.0.0.1",
		Check: &structs.HealthCheck{
			Node:      srv.agent.config.NodeName,
			Name:      "consul check",
			ServiceID: "consul",
			Status:    structs.HealthCritical,
		},
	}

	var out struct{}
	if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
		t.Fatalf("err: %v", err)
	}

	req, err := http.NewRequest("GET", "/v1/health/service/consul?passing", nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	resp := httptest.NewRecorder()
	obj, err := srv.HealthServiceNodes(resp, req)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	assertIndex(t, resp)

	// Should be 0 health check for consul
	nodes := obj.(structs.CheckServiceNodes)
	if len(nodes) != 0 {
		t.Fatalf("bad: %v", obj)
	}
}

func TestFilterNonPassing(t *testing.T) {
	nodes := structs.CheckServiceNodes{
		structs.CheckServiceNode{
			Checks: structs.HealthChecks{
				&structs.HealthCheck{
					Status: structs.HealthCritical,
				},
				&structs.HealthCheck{
					Status: structs.HealthCritical,
				},
			},
		},
		structs.CheckServiceNode{
			Checks: structs.HealthChecks{
				&structs.HealthCheck{
					Status: structs.HealthCritical,
				},
				&structs.HealthCheck{
					Status: structs.HealthCritical,
				},
			},
		},
		structs.CheckServiceNode{
			Checks: structs.HealthChecks{
				&structs.HealthCheck{
					Status: structs.HealthPassing,
				},
			},
		},
	}
	out := filterNonPassing(nodes)
	if len(out) != 1 && reflect.DeepEqual(out[0], nodes[2]) {
		t.Fatalf("bad: %v", out)
	}
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?colorPrimary"
                android:minHeight="?actionBarSize"
                app:contentInsetStart="@dimen/second_keyline"
                app:layout_scrollFlags="scroll|enterAlways" />

            <ViewStub
                android:id="@+id/cab_stub"
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize" />
        </FrameLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabStrip"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="horizontal"
            app:layout_scrollFlags="scroll|enterAlways"
            app:tabGravity="fill"
            app:tabMode="scrollable" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</LinearLayout>


text:
app.controller('CustomerSearchController', ['$scope', '$stateParams', 'customers', 'Customers',
  function($scope, $stateParams, customers, Customers) {
    $scope.page = $stateParams.page || 1;
    $scope.keywords = $stateParams.q || '';

    $scope.customers = customers;
    $scope.hasNextPage = customers.hasNextPage;
    $scope.hasPreviousPage = customers.hasPreviousPage;

    $scope.search = function(searchTerm) {
      if (searchTerm.length !== 0 && searchTerm.length < 3) {
        return;
      }

      $scope.loading = true;

      Customers.getList({ 'keywords': $scope.keywords, 'page': $scope.page })
        .then(function (customers) {
          $scope.hasNextPage = customers.hasNextPage;
          $scope.hasPreviousPage = customers.hasPreviousPage;

          $scope.customers = customers;
          $scope.loading = false;
        });
    }

    $scope.previousPage = function() {
      if ($scope.hasPreviousPage) {
        $scope.page -= 1;
        $scope.search($scope.keywords);
      }
    }

    $scope.nextPage = function() {
      if ($scope.hasNextPage) {
        $scope.page += 1;
        $scope.search($scope.keywords);
      }
    }
  }
]);