text:
[![Build Status](https://travis-ci.org/mwerner/spigot.png?branch=master)](https://travis-ci.org/mwerner/spigot "Travis CI")
[![Code Climate](https://codeclimate.com/github/mwerner/spigot.png)](https://codeclimate.com/github/mwerner/spigot "Code Climate")

Spigot is an attempt to bring some sanity to consuming external API data. Without Spigot, you need
to do this manual mapping at creation, such as:

    if params[:data].present?
      data = params[:data]
      record = User.where(external_id: data[:id]).first

      if record.nil?
        url = "https://github.com/#{data[:login]}"

        user = User.new({
          name: data[:first_name],
          email: data[:email_address],
          url: url
        })

        if data[:profile].present?
          user.bio = data[:profile][:text]
        end

        user.save!
      end
    end

This becomes particularly difficult as you start having multiple external sources for the same resource (eg: users from both twitter and facebook).

Spigot produces a map of the raw API data you receive to columns in your database. As a result, you're able to parse their data structure into meaningful attributes in a very concise expression. This turns the previous code block into the following statement:

    User.find_or_create_by_api(params[:data])

Much better.

## Usage

This is an example implementation. Assuming you have a User model in your database and you wish to capture the `id`, `name`, `login`, and `avatar_url` from the API payload.

    require 'open-uri'
    require 'json'

    Spigot.resource :user do
      id          :github_id
      name        :name
      login       :username
      avatar_url :image_url
    end

    data = JSON.parse open('https://api.github.com/users/mwerner').read
    User.spigot.create(data)
    # #<User id: 1, name: "Matthew Werner", github_id: 50568, username: "mwerner", image_url: "https://avatars.githubusercontent.com/u/50568">

## Installation

Add this line to your application's Gemfile:

    gem 'spigot'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install spigot

## Setup

Spigot is configured using simple ruby blocks. You just create an initializer, which evaluates your Spigot definition block to be ready for any data you throw at it.

    # config/initializers/spigot.rb
    Spigot.define do
      service :github do
        resource :pull_request do
          id      :github_id
          number  :number
          created :created_at
        end
      end
    end

This `define` block establishes a `pull_request` resource that is sourced by the `github` service. When you include the Spigot mixin to the `PullRequest` model, the class will gain the ability to parse raw pull request data as received from the Github API.

    class PullRequest < ActiveRecord::Base
      include Spigot::Base
    end

    PullRequest.create_by_api(github: params[:pull_request])

## Services

Services are the source from which you are receiving the data you're consuming. By specifying the service which you are using, you're able to accurately map the same resource from multiple sources (such as a User from Twitter and Facebook's API data formats).

Inside your service block you must further define a `resource`. Any API data that you map can only be attributed to a resource in your app.

It is not required to specify a service. You only need to do so if you need to parse the same resource data from multiple services. If you are not parsing multiple services, you can instead define your spigot map with only the resource definition:

    Spigot.define do
      resource :pull_request do
        id      :github_id
        number  :number
        created :created_at
      end
    end

Then, when invoking the methods on the model, you do not need to specify a service when passing in the data.

    class PullRequest < ActiveRecord::Base
      include Spigot::Base
    end

    PullRequest.create_by_api(params[:pull_request])

## Resources

A resource is a model in your app that will receive the parsed data provided by spigot. These resources are defined using a ruby block:

    Spigot.define do
      resource :user do
        login   :username
        name    :full_name
        created :created_at
      end
    end

The method you are calling within the block corresponds to the API data key you are attempting to access. The symbol you specify, or pass to the function, corresponds to your database table attribute to which the value will be assigned.

A good way to remember which is which is to say (from the above example) "Their `login` is my `username`. Their `name` is my `full_name`".

## Parsing Data

When Spigot parses data, it will read the resource definition present in your Spigot map. It will format the raw API data which passed in, and return a hash of data in the format the calling model can understand.

Looking at an example:

    Spigot.resource(:pull_request) do
      id      :github_id
      metadata do
        number  :number do |attr|
          "##{attr}"
        end
      end
      author  User
      created :created_at
    end

There are several things happening in this definition, let's look at each one.

**Nested block**

If you have a nested block, Spigot will dig down into the API data, to retreive the keys specified inside the block.

    data = params[:pull_request]
    if data[:metadata].present?
      number = data[:metadata][:number]
    end

**Attribute block**

When you pass a block to an attribute mapping, that block will be executed on the value found at that location in the API data. You can use this to manipulate and massage the data into exactly what you'd like to assign to your attribute. In this case we're prepending a hashtag before the pull request number.

    number = data[:metadata][:number]
    pr.number = "##{number}"

**Nested Resource**

If the API data you are receiving has an associated resource which you would also like to capture, you can pass a class inside the resource block. Spigot will recognize that `User` has a defined Spigot map and will use it to create a user. Once the nested data has been parsed and used to create a user, Spigot will merge a key value pair associating the created user's id to the API data which `PullRequest` will use.

    userdata = data.delete(:author)
    user = User.find_or_create_by_api(userdata)
    data.merge!(user_id: user.id)

**Resulting Data**

With the above example, this is the data which would be parsed:

    # Original
    { id: 123, metadata: {number: 456}, author: { id: 987, login: 'mwerner' }, created: '2000-04-01 00:01:00' }

    # Parsed data, passed to PullRequest
    { github_id: 123, number: '#456', user_id: 1, created_at: '2000-04-01 00:01:00' }

**Passing Arrays of data**

Anytime you are parsing an array of data, Spigot will iterate over each element of the array and run the invoked function on each item. It will then return an array of objects which have been created for each element of the array.

## Abbreviated Setup

If you are only consuming one resource from one service, you can use abbreviated syntax to make your Spigot implementation more concise. The following two code blocks are equivalent:

    Spigot.define do
      resource :user do
        login   :username
        created :created_at
      end
    end

    Spigot.resource :user do
      login   :username
      created :created_at
    end

This method can be used for both `service` and `resource`.

## Alternative Syntax

Every class which you include `Spigot::Base` gains a variety of methods to find or save data. These methods can be accessed by a proxy object included on the class. This provides an object that contains all the parsing logic, as well as a more concise syntax.

    # No service specified
    client = PullRequest.spigot
    client.find_or_create(data)

    # Using the :github service
    github = PullRequest.spigot(:github)
    github.find_or_create(data)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.amazonaws.services.kinesisfirehose.model.transform;

import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.kinesisfirehose.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;

/**
 * ElasticsearchDestinationDescriptionMarshaller
 */
public class ElasticsearchDestinationDescriptionJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(
            ElasticsearchDestinationDescription elasticsearchDestinationDescription,
            StructuredJsonGenerator jsonGenerator) {

        if (elasticsearchDestinationDescription == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (elasticsearchDestinationDescription.getRoleARN() != null) {
                jsonGenerator.writeFieldName("RoleARN").writeValue(
                        elasticsearchDestinationDescription.getRoleARN());
            }
            if (elasticsearchDestinationDescription.getDomainARN() != null) {
                jsonGenerator.writeFieldName("DomainARN").writeValue(
                        elasticsearchDestinationDescription.getDomainARN());
            }
            if (elasticsearchDestinationDescription.getIndexName() != null) {
                jsonGenerator.writeFieldName("IndexName").writeValue(
                        elasticsearchDestinationDescription.getIndexName());
            }
            if (elasticsearchDestinationDescription.getTypeName() != null) {
                jsonGenerator.writeFieldName("TypeName").writeValue(
                        elasticsearchDestinationDescription.getTypeName());
            }
            if (elasticsearchDestinationDescription.getIndexRotationPeriod() != null) {
                jsonGenerator.writeFieldName("IndexRotationPeriod").writeValue(
                        elasticsearchDestinationDescription
                                .getIndexRotationPeriod());
            }
            if (elasticsearchDestinationDescription.getBufferingHints() != null) {
                jsonGenerator.writeFieldName("BufferingHints");
                ElasticsearchBufferingHintsJsonMarshaller
                        .getInstance()
                        .marshall(
                                elasticsearchDestinationDescription
                                        .getBufferingHints(),
                                jsonGenerator);
            }
            if (elasticsearchDestinationDescription.getRetryOptions() != null) {
                jsonGenerator.writeFieldName("RetryOptions");
                ElasticsearchRetryOptionsJsonMarshaller.getInstance().marshall(
                        elasticsearchDestinationDescription.getRetryOptions(),
                        jsonGenerator);
            }
            if (elasticsearchDestinationDescription.getS3BackupMode() != null) {
                jsonGenerator.writeFieldName("S3BackupMode").writeValue(
                        elasticsearchDestinationDescription.getS3BackupMode());
            }
            if (elasticsearchDestinationDescription
                    .getS3DestinationDescription() != null) {
                jsonGenerator.writeFieldName("S3DestinationDescription");
                S3DestinationDescriptionJsonMarshaller
                        .getInstance()
                        .marshall(
                                elasticsearchDestinationDescription
                                        .getS3DestinationDescription(),
                                jsonGenerator);
            }
            if (elasticsearchDestinationDescription
                    .getCloudWatchLoggingOptions() != null) {
                jsonGenerator.writeFieldName("CloudWatchLoggingOptions");
                CloudWatchLoggingOptionsJsonMarshaller
                        .getInstance()
                        .marshall(
                                elasticsearchDestinationDescription
                                        .getCloudWatchLoggingOptions(),
                                jsonGenerator);
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static ElasticsearchDestinationDescriptionJsonMarshaller instance;

    public static ElasticsearchDestinationDescriptionJsonMarshaller getInstance() {
        if (instance == null)
            instance = new ElasticsearchDestinationDescriptionJsonMarshaller();
        return instance;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package dht

import (
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	key "github.com/ipfs/go-ipfs/blocks/key"
	notif "github.com/ipfs/go-ipfs/notifications"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	kb "github.com/ipfs/go-ipfs/routing/kbucket"
	pset "github.com/ipfs/go-ipfs/util/peerset"
)

// Required in order for proper JSON marshaling
func pointerizePeerInfos(pis []peer.PeerInfo) []*peer.PeerInfo {
	out := make([]*peer.PeerInfo, len(pis))
	for i, p := range pis {
		np := p
		out[i] = &np
	}
	return out
}

// Kademlia 'node lookup' operation. Returns a channel of the K closest peers
// to the given key
func (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key key.Key) (<-chan peer.ID, error) {
	e := log.EventBegin(ctx, "getClosestPeers", &key)
	tablepeers := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
	if len(tablepeers) == 0 {
		return nil, kb.ErrLookupFailure
	}

	out := make(chan peer.ID, KValue)
	peerset := pset.NewLimited(KValue)

	for _, p := range tablepeers {
		select {
		case out <- p:
		case <-ctx.Done():
			return nil, ctx.Err()
		}
		peerset.Add(p)
	}

	// since the query doesnt actually pass our context down
	// we have to hack this here. whyrusleeping isnt a huge fan of goprocess
	parent := ctx
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
		// For DHT query command
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
			Type: notif.SendingQuery,
			ID:   p,
		})

		closer, err := dht.closerPeersSingle(ctx, key, p)
		if err != nil {
			log.Debugf("error getting closer peers: %s", err)
			return nil, err
		}

		var filtered []peer.PeerInfo
		for _, clp := range closer {
			if kb.Closer(clp, dht.self, key) && peerset.TryAdd(clp) {
				select {
				case out <- clp:
				case <-ctx.Done():
					return nil, ctx.Err()
				}
				filtered = append(filtered, dht.peerstore.PeerInfo(clp))
			}
		}

		// For DHT query command
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
			Type:      notif.PeerResponse,
			ID:        p,
			Responses: pointerizePeerInfos(filtered),
		})

		return &dhtQueryResult{closerPeers: filtered}, nil
	})

	go func() {
		defer close(out)
		defer e.Done()
		// run it!
		_, err := query.Run(ctx, tablepeers)
		if err != nil {
			log.Debugf("closestPeers query run error: %s", err)
		}
	}()

	return out, nil
}

func (dht *IpfsDHT) closerPeersSingle(ctx context.Context, key key.Key, p peer.ID) ([]peer.ID, error) {
	pmes, err := dht.findPeerSingle(ctx, p, peer.ID(key))
	if err != nil {
		return nil, err
	}

	var out []peer.ID
	for _, pbp := range pmes.GetCloserPeers() {
		pid := peer.ID(pbp.GetId())
		if pid != dht.self { // dont add self
			dht.peerstore.AddAddrs(pid, pbp.Addresses(), peer.TempAddrTTL)
			out = append(out, pid)
		}
	}
	return out, nil
}


text:
package org.example.resource;

import io.github.whiskeysierra.archer.Resource;
import org.example.SomeModel;

@Resource
public final class ModelCallingResource {

    private SomeModel model;

    public void send() {
        model.identify();
    }

}


text:
The repo holds an example gRPC set of applications used to help people learn gRPC.

## Tutorials

* [Deploying with Kubernetes](Tutorials/kubernetes)
* [Building Docker Images](Tutorials/docker)

## Build

See the [build guide](Documentation/build-guide.md).


text:
ASP.NET Core MVC用のカスタムモデルバインダーです。

## Description

標準のMVCモデルバインディングでは、「1,024」といったカンマ区切りの数値をdecimalにバインドすることができません。
このConvertModelBinderを用いると、decimalへの柔軟なバインドを行うことができます。

## Features

- decimal, decimal?, ~~DateTime, DateTime?~~へのバインドの拡張
※入力値をConvert.ToDecimalで変換しているだけです。
※RC2以降ではConvert.ToDateTimeを通さなくても同様にバインドされたため外しました。

## Requirement

- ASP.NET Core MVC 1.0

## Usage

Startup.csのConfigureServicesで次のように設定すると、ConvertModelBinderが有効になります。

```
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                // Add this
                options.AddConvertModelBinder();
            });
        }
```


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="gray">#707070</color>
    <color name="darkGray">#202020</color>
    <color name="black">#000000</color>
    <color name="white">#ffffff</color>
    <color name="clear">#00000000</color>
    <color name="main">#158ea5</color>
    <color name="mainLight">#5DCEC6</color>
    <color name="mainDark">#003a58</color>
    <color name="backgroundLight">#f2f4f5</color>
    <color name="settingsTitleColor">#030303</color>
    <color name="settingsParagraphColor">#808080</color>
    <color name="lastSeenColor">#829fa5</color>
    <color name="inactive">#b3b3b3</color>
    <color name="noTagsColor">#bbbbbb</color>
    <color name="divider">#dddddd</color>
    <color name="href">#6aeae1</color>
    <color name="activeAlarm">#FF5555</color>
</resources>


text:
<?php

/**
 * @namespace
 */
namespace Zend\Code\Reflection;

use ReflectionParameter,
    Zend\Code\Reflection;

/**
 * @uses       ReflectionParameter
 * @uses       \Zend\Code\Reflection\Exception
 * @category   Zend
 * @package    Zend_Reflection
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ParameterReflection extends ReflectionParameter implements Reflection
{
    /**
     * @var bool
     */
    protected $isFromMethod = false;

    /**
     * Get declaring class reflection object
     *
     * @param  string $reflectionClass Reflection class to use
     * @return \Zend\Code\Reflection\ReflectionClass
     */
    public function getDeclaringClass()
    {
        $phpReflection  = parent::getDeclaringClass();
        $zendReflection = new ClassReflection($phpReflection->getName());
        unset($phpReflection);
        return $zendReflection;
    }

    /**
     * Get class reflection object
     *
     * @param  string $reflectionClass Reflection class to use
     * @return \Zend\Code\Reflection\ReflectionClass
     */
    public function getClass()
    {
        $phpReflection  = parent::getClass();
        if ($phpReflection == null) {
            return null;
        }
        $zendReflection = new ClassReflection($phpReflection->getName());
        unset($phpReflection);
        return $zendReflection;
    }

    /**
     * Get declaring function reflection object
     *
     * @param  string $reflectionClass Reflection class to use
     * @return Zend_Reflection_Function|\MethodReflection\Code\Reflection\ReflectionMethod
     */
    public function getDeclaringFunction($reflectionClass = null)
    {
        $phpReflection = parent::getDeclaringFunction();
        if ($phpReflection instanceof \ReflectionMethod) {
            $zendReflection = new MethodReflection($this->getDeclaringClass()->getName(), $phpReflection->getName());
        } else {
            $zendReflection = new FunctionReflection($phpReflection->getName());
        }
        unset($phpReflection);
        return $zendReflection;
    }

    /**
     * Get parameter type
     *
     * @return string
     */
    public function getType()
    {
        if ($docblock = $this->getDeclaringFunction()->getDocBlock()) {
            $params = $docblock->getTags('param');

            if (isset($params[$this->getPosition()])) {
                return $params[$this->getPosition()]->getType();
            }

        }

        return null;
    }

    public function toString()
    {
        return parent::__toString();
    }

    public function __toString()
    {
        return parent::__toString();
    }

}


text:
package com.ziyuan.exceptions;

/**
 * CircuitCongestedException 电路拥挤,ringbuffer满了
 *
 * @author ziyuan
 * @since 2017-03-08
 */
public class CircuitCongestedException extends Exception {

    public CircuitCongestedException() {
        super("Circuit is congested!");
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=Edge" />

  <title>Two - Dendron</title>

  <link
    rel="shortcut icon"
    href="https://11ty.dendron.so/favicon.ico"
    type="image/x-icon"
  />
  <link
    rel="stylesheet"
    href="https://11ty.dendron.so/assets/css/just-the-docs-default.css"
  />

  <link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.22.0/themes/prism.min.css"
  />
  <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css"
    integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X"
    crossorigin="anonymous"
  />

  <meta name="viewport" content="width=device-width, initial-scale=1" />

<meta name="description" content="Dendron is a local-first, markdown based, hierarchical note taking tool. It is meant to help you create, organize, and collaborate on knowledge bases of any size.">
<meta name="author" content="Kevin">

<link rel="canonical" href="https://11ty.dendron.so/notes/dendron-blog-two.html">

<meta property="og:type" content="article">
<meta property="og:url" content="https://11ty.dendron.so/notes/dendron-blog-two.html">
<meta property="og:description" content="Dendron is a local-first, markdown based, hierarchical note taking tool. It is meant to help you create, organize, and collaborate on knowledge bases of any size.">
<meta property="og:image" content="https://11ty.dendron.so/logo.png">

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@kevins8">
<meta name="twitter:url" content="https://11ty.dendron.so/notes/dendron-blog-two.html">
<meta name="twitter:description" content="Dendron is a local-first, markdown based, hierarchical note taking tool. It is meant to help you create, organize, and collaborate on knowledge bases of any size.">
<meta name="twitter:image" content="https://11ty.dendron.so/logo.png">

  <meta property="og:title" content="Two - Dendron" />
  <meta name="twitter:title" content="Two - Dendron" />

    <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
      <symbol id="svg-link" viewBox="0 0 24 24">
        <title>Link</title>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-link">
          <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
        </svg>
      </symbol>
      <symbol id="svg-search" viewBox="0 0 24 24">
        <title>Search</title>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search">
          <circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line>
        </svg>
      </symbol>
      <symbol id="svg-menu" viewBox="0 0 24 24">
        <title>Menu</title>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-menu">
          <line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line>
        </svg>
      </symbol>
      <symbol id="svg-arrow-right" viewBox="0 0 24 24">
        <title>Expand</title>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-right">
          <polyline points="9 18 15 12 9 6"></polyline>
        </svg>
      </symbol>
      <symbol id="svg-doc" viewBox="0 0 24 24">
        <title>Document</title>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
          <path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline>
        </svg>
      </symbol>
    </svg>

          <svg viewBox="0 0 24 24" class="icon"><use xlink:href="#svg-menu"></use></svg>

        🌱 with 💕 using  Dendron 🌲

                <input type="text" id="search-input" class="search-input" tabindex="0" placeholder="Search Dendron" aria-label="Search Dendron" autocomplete="off">
                <svg viewBox="0 0 24 24" class="search-icon"><use xlink:href="#svg-search"></use></svg>

Welcome to dendron

Dendron

Blog

Two

    <meta itemprop="headline" content="Two">

    <meta itemprop="datePublished" content="2020-07-19T07:48:16+00:00">
    <meta itemprop="dateModified" content="2020-12-16T11:37:09+00:00">

<svg aria-hidden="true" viewBox="0 0 16 16"><use xlink:href="#svg-link"></use></svg>Two

<svg aria-hidden="true" viewBox="0 0 16 16"><use xlink:href="#svg-link"></use></svg>Summary

Blog 2 Summary

<svg aria-hidden="true" viewBox="0 0 16 16"><use xlink:href="#svg-link"></use></svg>Chap1

Blog 2 Chap1

                    Edit this page on Github


text:
package see.tree;

/**
 * @author pavlov
 * @since 05.09.11
 */
public interface VarNode<T> extends Node<T> {
    String getName();
}


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

namespace Akka.Event
{
    /// <summary>
    ///     Class Info.
    /// </summary>
    public class Info : LogEvent
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="Info" /> class.
        /// </summary>
        /// <param name="logSource">The log source.</param>
        /// <param name="logClass">The log class.</param>
        /// <param name="message">The message.</param>
        public Info(string logSource, Type logClass, object message)
        {
            LogSource = logSource;
            LogClass = logClass;
            Message = message;
        }

        /// <summary>
        ///     Logs the level.
        /// </summary>
        /// <returns>LogLevel.</returns>
        public override LogLevel LogLevel()
        {
            return Event.LogLevel.InfoLevel;
        }
    }
}


text:
package me.exz.wailanbt.commands;

import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;

public class CommandName extends CommandBase {
    @Override
    public String getCommandName() {
        return "wnn";
    }

    @Override
    public boolean canCommandSenderUseCommand(ICommandSender sender) {
        return true;
    }

    @Override
    public String getCommandUsage(ICommandSender sender) {
        return "/wnn";
    }

    @Override
    public void processCommand(ICommandSender sender, String[] array) {
        EntityPlayer player = (EntityPlayer) sender;
        ItemStack holdItem = player.getHeldItem();
        if (holdItem == null) {
            player.addChatComponentMessage(new ChatComponentTranslation("wailanbt.info.NotHolding"));
            return;
        }
        player.addChatComponentMessage(new ChatComponentText(Item.itemRegistry.getNameForObject(holdItem.getItem())));
    }
}


text:
class CreateAuthentications < ActiveRecord::Migration
  def change
    create_table :authentications do |t|
      t.integer :user_id
      t.string  :uid
      t.string  :provider
      t.string  :access_token

      t.timestamps
    end

    add_index :authentications, :user_id
    add_index :authentications, :uid
    add_index :authentications, :provider
  end
end


text:
namespace Capl.Authorization.Matching
{
    using System.Collections;
    using System.Collections.Generic;

    public class MatchExpressionDictionary : IDictionary<string, MatchExpression>
    {
        public MatchExpressionDictionary()
        {
            this.expressions = new Dictionary<string, MatchExpression>();
        }

        private Dictionary<string, MatchExpression> expressions;

        #region IDictionary<string,MatchExpression> Members

        /// <summary>
        /// Adds a new match expression.
        /// </summary>
        /// <param name="key">The key that identifies the match expression.</param>
        /// <param name="value">The match expression instance.</param>
        public void Add(string key, MatchExpression value)
        {
            expressions.Add(key, value);
        }

        public bool ContainsKey(string key)
        {
            return expressions.ContainsKey(key);
        }

        public ICollection<string> Keys
        {
            get { return expressions.Keys; }
        }

        public bool Remove(string key)
        {
            return expressions.Remove(key);
        }

        public bool TryGetValue(string key, out MatchExpression value)
        {
            return expressions.TryGetValue(key, out value);
        }

        public ICollection<MatchExpression> Values
        {
            get { return expressions.Values; }
        }

        public MatchExpression this[string key]
        {
            get { return expressions[key]; }
            set { expressions[key] = value; }
        }

        #endregion

        #region ICollection<KeyValuePair<string,MatchExpression>> Members

        public void Add(KeyValuePair<string, MatchExpression> item)
        {
            ((ICollection<KeyValuePair<string, MatchExpression>>)expressions).Add(item);
        }

        public void Clear()
        {
            expressions.Clear();
        }

        public bool Contains(KeyValuePair<string, MatchExpression> item)
        {
            return ((ICollection<KeyValuePair<string, MatchExpression>>)expressions).Contains(item);
        }

        public void CopyTo(KeyValuePair<string, MatchExpression>[] array, int arrayIndex)
        {
            ((ICollection<KeyValuePair<string, MatchExpression>>)expressions).CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return expressions.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(KeyValuePair<string, MatchExpression> item)
        {
            return ((ICollection<KeyValuePair<string, MatchExpression>>)expressions).Remove(item);
        }

        #endregion

        #region IEnumerable<KeyValuePair<string,MatchExpression>> Members

        public IEnumerator<KeyValuePair<string, MatchExpression>> GetEnumerator()
        {
            return (IEnumerator<KeyValuePair<string, MatchExpression>>)expressions.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return expressions.GetEnumerator();
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c)2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. 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.
  -->

<sequence xmlns="http://ws.apache.org/ns/synapse" name="jmsInboundEndpointTransactionRequestHandlerSequence" onError="inFault">
    <log category="INFO" level="full" separator=",">
        <property name="test" value="requestHandlerSequence"/>
    </log>
    <property name="OUT_ONLY" value="true"/>
    <callout serviceURL="http://localhost:9000/services/SimpleStockQuoteService">
        <source type="envelope"/>
        <target key="placeOrder"/>
    </callout>
    <log category="INFO" level="custom">
        <property name="Transaction Action" value="Committed"/>
    </log>
</sequence>


text:
package players;
import java.util.Random;

import board.Board;
import rules.Rules;
import board.Case;
import java.io.IOException;
/**
 * Cette classe mod�lise L'IA facile ainsi que son comportement
 * @author Eduardo Dom
 *
 */
public class RandomAI extends AGenericPlayer{
	public static AGenericPlayer joueur2 = Board.getSecondPlayer();
	private boolean isFirstPlayer;
	private Case[][] plateau;

	public RandomAI (boolean FirstPlayer){
		this.isFirstPlayer = FirstPlayer;
		if(FirstPlayer){
			this.x = 0;
			this.y = 4;
		}
		else{
			this.x = 8;
			this.y = 4;
		}
		this.plateau = Board.getTableau();
		walls = 10;
	}

	/**
	 * Permet a l'IA de se deplacer vers une case
	 * @param i ,la ligne sur laquelle se trouve la case
	 * @param j ,la colonne sur laquelle se trouve la case
	 * @return Vrai
	 */
	public boolean move(int i,int j){
		plateau[x][y].setEmpty(true);
		x = i;
		y = j;
		plateau[x][y].setEmpty(false);
		return true;
	}
	/**
	 * Permet a l'IA de jouer
	 */
	public void play()throws IOException{
		Random whatChoice = new Random();
		int WallOrMove = whatChoice.nextInt(2);
		if (WallOrMove == 0 && walls > 0){//on place un mur
			boolean not_done = true;
			while(not_done){
				int wall = whatChoice.nextInt(4);
				int i = whatChoice.nextInt(7)+1;
				int j = whatChoice.nextInt(7)+1;
				if (wall == 0 && Rules.canPutWallUp(plateau[i][j]) && Rules.canReallyPutWallUp(plateau[i][j])){
					putWallUp(plateau[i][j]);
					System.out.println("L'IA facile a pos� un mur au dessus de la case en position ("+i+","+j+")");
					walls--;
					not_done = false;
				}
				if (wall == 1 && Rules.canPutWallDown(plateau[i][j])&& Rules.canReallyPutWallDown(plateau[i][j])){
					putWallDown(plateau[i][j]);
					System.out.println("L'IA facile a pos� un mur en dessous de la case en position ("+i+","+j+")");
					walls--;
					not_done = false;
				}
				if (wall == 2 && Rules.canPutWallRight(plateau[i][j])&& Rules.canReallyPutWallRight(plateau[i][j])){
					putWallRight(plateau[i][j]);
					System.out.println("L'IA facile a pos� un mur � droite de la case en position ("+i+","+j+")");
					walls--;
					not_done = false;
				}
				if (wall == 3 && Rules.canPutWallLeft(plateau[i][j])&& Rules.canReallyPutWallLeft(plateau[i][j])){
					putWallLeft(plateau[i][j]);
					System.out.println("L'IA facile a pos� un mur � gauche de la case en position ("+i+","+j+")");
					walls--;
					not_done = false;
				}
			}
		}
		else{
			boolean not_done = true;
			while(not_done){
				int whatDirection = whatChoice.nextInt(4);
				if (whatDirection == 0 && Rules.canMoveUp(this)){
					moveUp();
					not_done = false;
				}
				if (whatDirection == 1 && Rules.canMoveDown(this)){
					moveDown();
					not_done = false;
				}
				if (whatDirection == 2 && Rules.canMoveLeft(this)){
					moveLeft();
					not_done = false;
				}
				if(whatDirection == 3 && Rules.canMoveRight(this)){
					moveRight();
					not_done = false;
				}
			}
		}
	}
}


text:
require 'features/features_helper'

describe "A meeting detail page, with 3 time slots, each with a topic" do
  include_context "full meeting setup"

  context "When viewed by a Visitor" do
    before { visit meeting_path(meeting) }

    it "has a 'Sign In' link" do
      page.should have_link('Sign In')
    end

    it "has the correct title" do
      page.should have_content("Meetup for")
    end

    it "contains 3 time slots" do
      page.should have_selector(:css, '.time_slot', :count => 3)
    end

    it "contains the third topic" do
      page.should have_selector(:css, "#topic_#{topic3.id}")
    end

    it "should not display graph" do
      page.should_not have_selector("//h2", text: 'Kudos Awarded')
    end

    context "when the meeting is closed" do
      before do
        meeting.update_attributes(state: 'closed')
      end

      it "should display a graph" do
        visit meeting_path(meeting)
        page.should have_selector("//h2", text: 'Kudos Awarded')
      end

    end
  end

  context "When viewed by a non-organizer User" do
    let(:user) { create(:user, :name => "Joe User", :provider => "meetup", :uid => "1234") }

    context "Voting is closed" do
      before do
        meeting.update_attributes(state: 'closed')
        signin_as(user)
        visit meeting_path(meeting)
      end

      it "should not display kudos action" do
        page.should_not have_selector(:css, ".kudos")
      end
    end

    context "when the voting is open and user" do
      before do
        meeting.open_kudos!
        signin_as(user)
      end

      context 'when the user has not voted yet' do
        it "should display kudos action" do
          visit meeting_path(meeting)
          page.should have_selector(:css, ".kudos")
        end
      end

      context 'when the user has voted' do
        before { meeting.give_kudo(meeting.topics[0], user) }
        it 'should not display kudos actions' do
          visit meeting_path(meeting)
          page.should_not have_selector(:css, ".kudos")
        end
      end

    end

  end
end


text:
/*
 * Drum.h
 *
 *  Created on: 6 May 2015
 *      Author: jeremy
 */

#ifndef RASPIDRUMS_SOURCE_DRUMKIT_MODULE_H_
#define RASPIDRUMS_SOURCE_DRUMKIT_MODULE_H_

#include "../../Metronome/Metronome.h"
#include "../../IO/SensorsConfig.h"
#include "../../Sound/Mixer/Mixer.h"
#include "../../Sound/Alsa/AlsaParams.h"
#include "../../Sound/SoundBank/SoundBank.h"
#include "../../Util/SimpleSafeQueue.h"

#include "../Kits/Kit.h"

#include "Recorder.h"

#include <string>
#include <vector>
#include <atomic>
#include <thread>
#include <memory>

namespace DrumKit
{

	class Module
	{

	public:

		Module(std::string dir, const Sound::AlsaParams& alsaParams, std::shared_ptr<Sound::Mixer> mixer, std::shared_ptr<Metronome> metro);
		virtual ~Module();

		// Kit
		void SaveKitConfig(std::size_t id) const;
		std::string GetKitLocation() const;
		bool DeleteKit(const int& id);
		void SelectKit(std::size_t id);
		void ReloadKits();
		std::size_t GetKitId() const noexcept { return kitId; }
		std::size_t GetNumKits() const noexcept { return kits.size(); };
		std::vector<std::string> GetKitsNames() const noexcept;
		std::vector<std::string> GetInstrumentsNames() const;

		// Instrument
		void SetInstrumentVolume(size_t id, float volume);
		float GetInstrumentVolume(int id) const;
		int GetNumInstruments() const { return kits[kitId].GetNumInstruments(); };
		std::vector<int> GetInstrumentTriggersIds(int id) const;

		// Triggers
		void ReloadTriggers();
		void SetTriggerParameters(int triggerId, const TriggerParameters& params) { triggers[triggerId]->SetParameters(params);}
		void SetTriggerSensorValue(int id, char channel, short data) { triggers[id]->SetSensorData(channel, data); }
		std::vector<TriggerParameters> GetTriggersParameters() const { return this->triggersParameters; }
		unsigned long long GetLastTrigTime() const noexcept { return lastTrigTime.load(std::memory_order_acquire); }
		int GetLastTrigValue() const noexcept { return lastTrigValue.load(std::memory_order_acquire); }
		float GetTriggerValue(size_t id) const;

		// Module
		void Start();
		void Stop();
		void EnableRecording(bool record);
		void RecorderExport(const std::string& fileName);
		void RecorderExportPCM(const std::string& fileName);
		void RecorderPurgeTempFile();
		void GetDirectory(std::string& dir) const noexcept;

		// Metronome
		void EnableMetronome(bool enable);
		void ChangeTempo(int tempo);
		void ChangeClickVolume(int volume);
		float GetClickVolume() const noexcept;
		void RestartMetronome();
		double GetClickPosition() const noexcept;
		int64_t GetLastClickTime() const noexcept;

		// Config
		IO::SensorsConfig GetSensorsConfig() const noexcept { return sensorsConfig; }

	private:

		void LoadKits();
		void LoadTriggers();
		void Run();
		void CreateTriggers(const std::vector<TriggerParameters>& trigParams);
		bool IsMetronomeEnabled() const;

		// Module
		std::string directory;
		std::thread playThread;

		// Kits
		KitManager kitManager;
		std::size_t kitId;
		std::vector<Kit> kits;
		std::atomic<bool> isPlay;

		// Triggers
		std::vector<TriggerParameters> triggersParameters;
		std::vector<TriggerPtr> triggers;
		std::atomic<int64_t> lastTrigTime;
		std::atomic<int> lastTrigValue;

		IO::SensorsConfig sensorsConfig;

		// Sound
		std::shared_ptr<Sound::SoundBank> soundBank;
		std::shared_ptr<Sound::Mixer> mixer;
		std::shared_ptr<Metronome> metronome;

		int metronomeSoundId;
		std::atomic<bool> isMetronomeEnabled;

		Recorder recorder;

	};

}

#endif /* RASPIDRUMS_SOURCE_DRUMKIT_MODULE_H_ */


text:
FactoryGirl.define do
  factory :chargeback_rate do
    guid                   { MiqUUID.new_guid }
    sequence(:description) { |n| "Chargeback Rate ##{n}" }
    rate_type              'Compute'
  end

  factory :chargeback_rate_with_details, :parent => :chargeback_rate do
    after(:create) do |chargeback_rate|
      chargeback_rate.chargeback_rate_details << FactoryGirl.create(:chargeback_rate_detail_memory_used_with_tiers)
      chargeback_rate.chargeback_rate_details << FactoryGirl.create(:chargeback_rate_detail_memory_allocated_with_tiers)
    end
  end
end


text:
/**
 * This class is generated by jOOQ
 */
package edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records;

import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.Constraint;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;

/**
 * This class is generated by jOOQ.
 */
@Generated(
	value = {
		"http://www.jooq.org",
		"jOOQ version:3.7.3"
	},
	comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ConstraintRecord extends UpdatableRecordImpl<ConstraintRecord> implements Record3<Integer, String, Integer> {

	private static final long serialVersionUID = 1602347587;

	/**
	 * Setter for crowdcontrol.Constraint.id_constraint.
	 */
	public void setIdConstraint(Integer value) {
		setValue(0, value);
	}

	/**
	 * Getter for crowdcontrol.Constraint.id_constraint.
	 */
	public Integer getIdConstraint() {
		return (Integer) getValue(0);
	}

	/**
	 * Setter for crowdcontrol.Constraint.constraint.
	 */
	public void setConstraint(String value) {
		setValue(1, value);
	}

	/**
	 * Getter for crowdcontrol.Constraint.constraint.
	 */
	public String getConstraint() {
		return (String) getValue(1);
	}

	/**
	 * Setter for crowdcontrol.Constraint.experiment.
	 */
	public void setExperiment(Integer value) {
		setValue(2, value);
	}

	/**
	 * Getter for crowdcontrol.Constraint.experiment.
	 */
	public Integer getExperiment() {
		return (Integer) getValue(2);
	}

	// -------------------------------------------------------------------------
	// Primary key information
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Record1<Integer> key() {
		return (Record1) super.key();
	}

	// -------------------------------------------------------------------------
	// Record3 type implementation
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Row3<Integer, String, Integer> fieldsRow() {
		return (Row3) super.fieldsRow();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Row3<Integer, String, Integer> valuesRow() {
		return (Row3) super.valuesRow();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Field<Integer> field1() {
		return Constraint.CONSTRAINT.ID_CONSTRAINT;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Field<String> field2() {
		return Constraint.CONSTRAINT.CONSTRAINT_;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Field<Integer> field3() {
		return Constraint.CONSTRAINT.EXPERIMENT;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Integer value1() {
		return getIdConstraint();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String value2() {
		return getConstraint();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Integer value3() {
		return getExperiment();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ConstraintRecord value1(Integer value) {
		setIdConstraint(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ConstraintRecord value2(String value) {
		setConstraint(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ConstraintRecord value3(Integer value) {
		setExperiment(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ConstraintRecord values(Integer value1, String value2, Integer value3) {
		value1(value1);
		value2(value2);
		value3(value3);
		return this;
	}

	// -------------------------------------------------------------------------
	// Constructors
	// -------------------------------------------------------------------------

	/**
	 * Create a detached ConstraintRecord
	 */
	public ConstraintRecord() {
		super(Constraint.CONSTRAINT);
	}

	/**
	 * Create a detached, initialised ConstraintRecord
	 */
	public ConstraintRecord(Integer idConstraint, String constraint, Integer experiment) {
		super(Constraint.CONSTRAINT);

		setValue(0, idConstraint);
		setValue(1, constraint);
		setValue(2, experiment);
	}
}


text:
package io.github.flbaue.vs.RESTopoly;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import spark.Request;
import spark.Response;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

import static spark.Spark.get;
import static spark.Spark.post;

/**
 * Created by florian on 24.10.15.
 */
public class JailService {

    private Set<Player> playerSet = new HashSet<>();
    private Gson gson = new Gson();

    public static void main(String[] args) {
        new JailService().run();
    }

    private void run() {
        System.out.println("Jail Service is starting");

        get("/", this::root);
        post("/jail", this::createPlayer);
        get("/jail/:playerId", this::getPlayer);
        post("/jail/:playerId", this::playerRollsDice);
    }

    private Object root(Request request, Response response) throws Exception {
        return "It's Alive!";
    }

    private Object createPlayer(Request request, Response response) throws Exception {
        Player player = null;
        try {
            player = gson.fromJson(request.body(), Player.class);
        } catch (JsonSyntaxException e) {
            //nothing
        }

        if (player == null) {
            response.status(420);
            return gson.toJson(new Player("Player model is not valid"));
        }

        playerSet.add(player);
        response.status(201);
        player.setIsInJail(true);
        return gson.toJson(player);
    }

    private Object getPlayer(Request request, Response response) throws Exception {
        String playerId = request.params(":playerId");
        if (playerId == null || playerId.isEmpty()) {
            response.status(420);
            return gson.toJson(new Player("Player Id is missing"));
        }

        Player player = playerSet
                .stream()
                .filter(p -> p.getPlayerId().equals(playerId))
                .findAny()
                .orElseGet(() -> {
                    response.status(404);
                    return new Player("Not found");
                });

        return gson.toJson(player);
    }

    private Object playerRollsDice(Request request, Response response) throws Exception {
        String playerId = request.params("playerId");

        if(!request.queryMap().toMap().containsKey("pasch")) {
            response.status(420);
            return gson.toJson(new Player("Pasch query param must be set"));
        }
        boolean pasch = Boolean.parseBoolean(request.queryParams("pasch"));

        Player player = null;
        for (Player p : playerSet) {
            if (p.getPlayerId().equals(playerId)) {
                player = p;
            }
        }

        if (player == null) {
            response.status(404);
            return gson.toJson(new Player("not found"));

        } else {

            if (player.getRoundsInJail() == 3) {
                response.status(402);

            } else {
                if (pasch) {
                    playerSet.remove(player);
                    player.setIsInJail(false);

                } else {
                    player.addRound();
                }
            }

            return gson.toJson(player);
        }
    }
}


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:background="@color/dark_grey"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SignupActivity" >

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:orientation="vertical"
        android:paddingBottom="@dimen/medium_margin" >

        <TextView
            android:id="@+id/lblSignUp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="@string/sign_up"
            android:textColor="@color/white"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/lblEmail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/lblSignUp"
            android:text="@string/email_address"
            android:paddingTop="@dimen/form_text_field_padding"
            android:textColor="@color/text_field_header" />

        <LinearLayout
        	android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/lblEmail"
        	android:id="@+id/layoutEmail" >
        	<EditText
	            android:id="@+id/txtEmail"
	            android:layout_width="0dp"
	            android:layout_weight="1"
	            android:padding="8dp"
	            android:layout_height="@dimen/text_field_height"
	            android:background="@drawable/text_field_left_rounded"
	            android:hint="@string/email_address"
	            android:inputType="textEmailAddress"
	            android:textColor="@color/white" >
	            <requestFocus />
	        </EditText>
	        <ImageView
		        android:id="@+id/imageView1"
		        android:layout_width="wrap_content"
		        android:layout_height="@dimen/text_field_height"
		        android:layout_marginLeft="-1dp"
		        android:padding="5dp"
		        android:background="@drawable/text_field_tab" />
   	 	</LinearLayout>

        <TextView
            android:id="@+id/lblPassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/layoutEmail"
            android:text="@string/password"
            android:paddingTop="@dimen/form_text_field_padding"
            android:textColor="@color/text_field_header" />

        <LinearLayout
        	android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/lblPassword"
        	android:id="@+id/layoutPassword" >

	        <EditText
	            android:id="@+id/txtPassword"
	            android:layout_width="0dp"
	            android:layout_weight="1"
	            android:padding="8dp"
	            android:layout_height="@dimen/text_field_height"
	            android:background="@drawable/text_field_left_rounded"
	            android:ems="10"
	            android:hint="@string/password"
	            android:inputType="textPassword"
	            android:textColor="@color/white" />

		        <ImageView
			        android:id="@+id/imageView1"
			        android:layout_width="wrap_content"
			        android:layout_height="@dimen/text_field_height"
			        android:layout_marginLeft="-1dp"
			        android:padding="5dp"
			        android:background="@drawable/text_field_tab" />
        </LinearLayout>

        <TextView
            android:id="@+id/lblBirthday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/layoutPassword"
            android:text="@string/birthday"
            android:paddingTop="@dimen/form_text_field_padding"
            android:textColor="@color/text_field_header"/>

        <LinearLayout
        	android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/lblBirthday"
        	android:id="@+id/layoutBirthday" >

	        <EditText
	            android:id="@+id/txtBirthday"
	            android:layout_width="0dp"
	            android:layout_weight="1"
	            android:padding="8dp"
	            android:layout_height="@dimen/text_field_height"
	            android:background="@drawable/text_field_left_rounded"
	            android:ems="10"
	            android:focusableInTouchMode="false"
	            android:hint="@string/what_is_your_birthday"
	            android:inputType="date"
	            android:textColor="@color/white"/>
        	<ImageView
			        android:id="@+id/imageView1"
			        android:layout_width="wrap_content"
			        android:layout_height="@dimen/text_field_height"
			        android:layout_marginLeft="-1dp"
			        android:padding="5dp"
			        android:background="@drawable/text_field_tab" />
        </LinearLayout>

        <Button
            android:id="@+id/btnNext"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_below="@+id/layoutBirthday"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="@dimen/medium_margin"
            android:background="@drawable/splash_screen_button_inactive"
            android:paddingLeft="@dimen/splash_button_padding"
            android:paddingRight="@dimen/splash_button_padding"
            android:text="@string/done"
            android:textColor="@color/splash_font"
            android:textSize="@dimen/sign_up_button_text_size"
            android:textStyle="bold" />

        <ProgressBar
            android:id="@+id/progressLogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/layoutBirthday"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="@dimen/medium_margin"
            android:visibility="gone" />

    </RelativeLayout>

    <TextView
        android:id="@+id/lblDisclaimer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/relativeLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:gravity="center"
        android:text="@string/set_in_code"
        android:textColor="@color/disclaimer_color" />

</RelativeLayout>


text:
namespace StackExchange.DataExplorer.ViewModel
{
    public class SubHeaderViewData
    {
        private string _name;

        public string Id { get; set; }
        public string Title { get; set; }
        public string Href { get; set; }
        public bool Selected { get; set; }
        public bool Default { get; set; }
        public string Description { get; set; }
        public bool RightAlign { get; set; }

        public string Name
        {
            get { return _name ?? Description; }
            set { _name = value; }
        }
    }
}


text:
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, Eric Swann, et. al.
//
// 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.

using System;

namespace Burrows.Publishing
{
    public interface IPublisher : IDisposable
    {
        void Publish<T>(T message);

        void RepublishStoredMessages();

        IServiceBus ServiceBus { get; }
    }
}


text:
module POEditor
  class UI
    @@enabled = false

    def self.enabled
      @@enabled
    end

    def self.enabled=enabled
      @@enabled = enabled
    end

    def self.puts(*args)
      Kernel.puts args.map { |x| x.to_s }.join(" ") if @@enabled
    end
  end
end


text:
#include "test/core/end2end/end2end_tests.h"

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/host_port.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd.h>
#include <grpc/support/useful.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/http/server/http_server_filter.h"
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/server.h"
#include "test/core/end2end/fixtures/proxy.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"

typedef struct fullstack_fixture_data {
  grpc_end2end_proxy *proxy;
} fullstack_fixture_data;

static grpc_server *create_proxy_server(const char *port,
                                        grpc_channel_args *server_args) {
  grpc_server *s = grpc_server_create(server_args, NULL);
  GPR_ASSERT(grpc_server_add_insecure_http2_port(s, port));
  return s;
}

static grpc_channel *create_proxy_client(const char *target,
                                         grpc_channel_args *client_args) {
  return grpc_insecure_channel_create(target, client_args, NULL);
}

static const grpc_end2end_proxy_def proxy_def = {create_proxy_server,
                                                 create_proxy_client};

static grpc_end2end_test_fixture chttp2_create_fixture_fullstack(
    grpc_channel_args *client_args, grpc_channel_args *server_args) {
  grpc_end2end_test_fixture f;
  fullstack_fixture_data *ffd = gpr_malloc(sizeof(fullstack_fixture_data));
  memset(&f, 0, sizeof(f));

  ffd->proxy = grpc_end2end_proxy_create(&proxy_def, client_args, server_args);

  f.fixture_data = ffd;
  f.cq = grpc_completion_queue_create_for_next(NULL);
  f.shutdown_cq = grpc_completion_queue_create_for_pluck(NULL);

  return f;
}

void chttp2_init_client_fullstack(grpc_end2end_test_fixture *f,
                                  grpc_channel_args *client_args) {
  fullstack_fixture_data *ffd = f->fixture_data;
  f->client = grpc_insecure_channel_create(
      grpc_end2end_proxy_get_client_target(ffd->proxy), client_args, NULL);
  GPR_ASSERT(f->client);
}

void chttp2_init_server_fullstack(grpc_end2end_test_fixture *f,
                                  grpc_channel_args *server_args) {
  fullstack_fixture_data *ffd = f->fixture_data;
  if (f->server) {
    grpc_server_destroy(f->server);
  }
  f->server = grpc_server_create(server_args, NULL);
  grpc_server_register_completion_queue(f->server, f->cq, NULL);
  GPR_ASSERT(grpc_server_add_insecure_http2_port(
      f->server, grpc_end2end_proxy_get_server_port(ffd->proxy)));
  grpc_server_start(f->server);
}

void chttp2_tear_down_fullstack(grpc_end2end_test_fixture *f) {
  fullstack_fixture_data *ffd = f->fixture_data;
  grpc_end2end_proxy_destroy(ffd->proxy);
  gpr_free(ffd);
}

/* All test configurations */
static grpc_end2end_test_config configs[] = {
    {"chttp2/fullstack+proxy", FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION |
                                   FEATURE_MASK_SUPPORTS_REQUEST_PROXYING |
                                   FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL |
                                   FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER,
     chttp2_create_fixture_fullstack, chttp2_init_client_fullstack,
     chttp2_init_server_fullstack, chttp2_tear_down_fullstack},
};

int main(int argc, char **argv) {
  size_t i;

  grpc_test_init(argc, argv);
  grpc_end2end_tests_pre_init();
  grpc_init();

  for (i = 0; i < sizeof(configs) / sizeof(*configs); i++) {
    grpc_end2end_tests(argc, argv, configs[i]);
  }

  grpc_shutdown();

  return 0;
}


text:
nodeunit = (function(){
/*
    http://www.JSON.org/json2.js
    2010-11-17

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or ' '),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then


text:
require 'spec_helper'

RSpec.describe Clusters::Providers::Aws do
  it { is_expected.to belong_to(:cluster) }

  it { is_expected.to validate_length_of(:key_name).is_at_least(1).is_at_most(255) }
  it { is_expected.to validate_length_of(:region).is_at_least(1).is_at_most(255) }
  it { is_expected.to validate_length_of(:instance_type).is_at_least(1).is_at_most(255) }
  it { is_expected.to validate_length_of(:security_group_id).is_at_least(1).is_at_most(255) }
  it { is_expected.to validate_presence_of(:subnet_ids) }

  include_examples 'provider status', :cluster_provider_aws

  describe 'default_value_for' do
    let(:provider) { build(:cluster_provider_aws) }

    it "sets default values" do
      expect(provider.region).to eq('us-east-1')
      expect(provider.num_nodes).to eq(3)
      expect(provider.instance_type).to eq('m5.large')
    end
  end

  describe 'custom validations' do
    subject { provider.valid? }

    context ':num_nodes' do
      let(:provider) { build(:cluster_provider_aws, num_nodes: num_nodes) }

      context 'contains non-digit characters' do
        let(:num_nodes) { 'A3' }

        it { is_expected.to be_falsey }
      end

      context 'is blank' do
        let(:num_nodes) { nil }

        it { is_expected.to be_falsey }
      end

      context 'is less than 1' do
        let(:num_nodes) { 0 }

        it { is_expected.to be_falsey }
      end

      context 'is a positive integer' do
        let(:num_nodes) { 3 }

        it { is_expected.to be_truthy }
      end
    end
  end

  describe '#nullify_credentials' do
    let(:provider) { create(:cluster_provider_aws, :scheduled) }

    subject { provider.nullify_credentials }

    before do
      expect(provider.access_key_id).to be_present
      expect(provider.secret_access_key).to be_present
      expect(provider.session_token).to be_present
    end

    it 'removes access_key_id, secret_access_key and session_token' do
      subject

      expect(provider.access_key_id).to be_nil
      expect(provider.secret_access_key).to be_nil
      expect(provider.session_token).to be_nil
    end
  end

  describe '#api_client' do
    let(:provider) { create(:cluster_provider_aws) }
    let(:credentials) { double }
    let(:client) { double }

    subject { provider.api_client }

    before do
      allow(provider).to receive(:credentials).and_return(credentials)

      expect(Aws::CloudFormation::Client).to receive(:new)
        .with(credentials: credentials, region: provider.region)
        .and_return(client)
    end

    it { is_expected.to eq client }
  end

  describe '#credentials' do
    let(:provider) { create(:cluster_provider_aws) }
    let(:credentials) { double }

    subject { provider.credentials }

    before do
      expect(Aws::Credentials).to receive(:new)
        .with(provider.access_key_id, provider.secret_access_key, provider.session_token)
        .and_return(credentials)
    end

    it { is_expected.to eq credentials }
  end

  describe '#created_by_user' do
    let(:provider) { create(:cluster_provider_aws) }

    subject { provider.created_by_user }

    it { is_expected.to eq provider.cluster.user }
  end

  describe '#has_rbac_enabled?' do
    let(:provider) { create(:cluster_provider_aws) }

    subject { provider.has_rbac_enabled? }

    it { is_expected.to be_truthy }
  end

  describe '#knative_pre_installed?' do
    let(:provider) { create(:cluster_provider_aws) }

    subject { provider.knative_pre_installed? }

    it { is_expected.to be_falsey }
  end
end


text:
layout: post
date: '2016-04-05'
title: "Demetrios Wedding Dress Style 3212 Sleeveless Chapel Train Aline/Princess"
category: Demetrios
tags: [Demetrios,Aline/Princess ,Halter,Chapel Train,Sleeveless]
---
### Demetrios Wedding Dress Style 3212
Just **$309.99**
###   Sleeveless Chapel Train Aline/Princess

BRANDS	Demetrios

Silhouette	Aline/Princess

Neckline	Halter

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/demetrios/17620-demetrios-style-3212.html](https://www.readybrides.com/en/demetrios/17620-demetrios-style-3212.html)


text:
package com.hxxc.user.app.ui.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.hxxc.user.app.Constants;
import com.hxxc.user.app.R;
import com.hxxc.user.app.contract.ProductDetailVertical2V;
import com.hxxc.user.app.widget.MultiSwipeRefreshLayout;
import com.trello.rxlifecycle.components.support.RxFragment;

import butterknife.ButterKnife;

import static com.hxxc.user.app.R.id.swipe_refresh_layout;

/**
 * Created by chenqun on 2016/9/22.
 */

public abstract  class BaseFragment2 extends RxFragment {
    protected Context mContext;

    protected MultiSwipeRefreshLayout mSwipeRefreshLayout;
    protected ProductDetailVertical2V v;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getContentViewID() != 0) {
            return inflater.inflate(getContentViewID(), null);
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this,view);
        mSwipeRefreshLayout = (MultiSwipeRefreshLayout) view.findViewById(swipe_refresh_layout);
        trySetupSwipeRefresh();
        initViewsAndEvents(view);
    }
    void trySetupSwipeRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
                    R.color.colorPrimaryDark, R.color.colorPrimary);
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override public void onRefresh() {
                    BaseFragment2.this.onRefresh();
                }
            });
//            mSwipeRefreshLayout.setAnimateToRefreshDuration(1000);
//            mSwipeRefreshLayout.setAnimateToStartDuration(1000);
//            mSwipeRefreshLayout.setDragDistanceConverter(new IDragDistanceConverter() {
//                @Override
//                public float convert(float scrollDistance, float refreshDistance) {
//                    return scrollDistance * 0.5f;
//                }
//            });
//            mSwipeRefreshLayout.setOnRefreshListener(new RecyclerRefreshLayout.OnRefreshListener() {
//                @Override
//                public void onRefresh() {
//                    BaseFragment2.this.onRefresh();
//                }
//            });
        }
    }
    public void setRefresh(boolean requestDataRefresh) {
        if (mSwipeRefreshLayout == null) {
            return;
        }
        if (!requestDataRefresh) {
            // 防止刷新消失太快,让子弹飞一会儿.
            mSwipeRefreshLayout.postDelayed(new Runnable() {
                @Override public void run() {
                    postReflush(false);
                }

            }, Constants.Delay_Reflush_false);
//            postReflush(false);
        } else {
            mSwipeRefreshLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    postReflush(true);
                }
            },Constants.Delay_Reflush_true);
//            postReflush(false);
        }
    }
    private void postReflush(boolean b) {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(b);
        }
    }
    //子类需要重写
    protected void onRefresh() {

    }

    /**
     * override this method to return content view id of the fragment
     */
    protected abstract int getContentViewID();

    /**
     * override this method to do operation in the fragment
     */
    protected abstract void initViewsAndEvents(View rootView);

    public  boolean isLoading = false;
    public  void initDatas(){
    }

    /**
     * toast
     */
    public void toast(@NonNull CharSequence text) {
        Toast.makeText(getActivity().getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    /**
     * toast
     */
    public void toast(@StringRes int stringRes) {
        Toast.makeText(getActivity().getApplicationContext(), stringRes, Toast.LENGTH_SHORT).show();
    }

    // 设置SwipeRefreshLayout可以滚动的孩子
    protected void setScrollUpChild(){

    }

    public void setV(ProductDetailVertical2V view){
        this.v = view;
    }

    @Override
    public void onDestroy() {
        v = null;
        super.onDestroy();
    }
}


text:
/**
 * Bet.cpp
 *
 *  Created on: Oct 20, 2013
 *      Author: Kyle Despins
 */

#include "Bet.h"

#include <string>
#include <sstream>

using namespace std;

/*
 * Default constructor
 */
Bet::Bet() {
	action = INVALID;
	amount = 0;
}

/*
 * Constructor
 */
Bet::Bet(BetAction betAction, int betAmount) {
	action = betAction;
	amount = betAmount;
}

/*
 * Returns the bet action
 */
BetAction Bet::getAction() {
	return action;
}

/*
 * Returns the amount bet
 */
int Bet::getAmount() {
	return amount;
}

/*
 * Returns a string describing the bet
 */
string Bet::print() {
	stringstream ss;

	switch (action) {
	case FOLD:
		ss << "folded.";
		break;
	case CALL:
		if (amount == 0)
			ss << "checked.";
		else
			ss << "called.";
		break;
	case RAISE:
		ss << "raised " << amount << ".";
		break;
	default:
		ss << "made a bet.";
		break;
	}

	return ss.str();
}


text:
#include "kaa/failover/DefaultFailoverStrategy.hpp"

namespace kaa {

const std::size_t DefaultFailoverStrategy::DEFAULT_BOOTSTRAP_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_OPERATION_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_NO_OPERATION_SERVERS_RETRY_PERIOD;
const std::size_t DefaultFailoverStrategy::DEFAULT_NO_CONNECTIVITY_RETRY_PERIOD;

FailoverStrategyDecision DefaultFailoverStrategy::onFailover(Failover failover)
{
	switch (failover) {
		case Failover::NO_BOOTSTRAP_SERVERS:
			return FailoverStrategyDecision(FailoverStrategyAction::RETRY, bootstrapServersRetryPeriod_);
		case Failover::NO_OPERATION_SERVERS:
			return FailoverStrategyDecision(FailoverStrategyAction::RETRY, noOperationServersRetryPeriod_);
		case Failover::ALL_OPERATION_SERVERS_NA:
			return FailoverStrategyDecision(FailoverStrategyAction::RETRY, operationServersRetryPeriod_);
		case Failover::NO_CONNECTIVITY:
			return FailoverStrategyDecision(FailoverStrategyAction::RETRY, noConnectivityRetryPeriod_);
		default:
			return FailoverStrategyDecision(FailoverStrategyAction::NOOP);
	}
}

}


text:
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">

<!-- =============================================================== -->
<!-- Add a ContextProvider to the deployment manager                 -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- This scans the webapps directory for war files and directories  -->
<!-- to deploy.                                                      -->
<!-- This configuration must be used with jetty-deploy.xml, which    -->
<!-- creates the deployment manager instance                         -->
<!-- =============================================================== -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
        <Ref id="DeploymentManager">
          <Call name="addAppProvider">
            <Arg>
              <New class="org.eclipse.jetty.deploy.providers.ContextProvider">
                <!-- <Set name="monitoredDirName"><Property name="jetty.home" default="." />/contexts</Set> -->
				<Set name="monitoredDirName"><Property name="jetty.home" default="." />/AppInsight</Set>
                <Set name="scanInterval">1</Set>
              </New>
            </Arg>
          </Call>
        </Ref>
</Configure>


text:
import time

from gaiatest import GaiaTestCase

class TestVideoPlayer(GaiaTestCase):

    # Video list/summary view
    _video_items_locator = ('css selector', 'ul#thumbnails li[data-name]')
    _video_name_locator = ('css selector', 'p.name')

    # Video player fullscreen
    _video_frame_locator = ('id', 'videoFrame')
    _video_loaded_locator = ('css selector', 'video[style]')
    _video_title_locator = ('id', 'video-title')
    _elapsed_text_locator = ('id', 'elapsed-text')

    def setUp(self):
        GaiaTestCase.setUp(self)

        # add video to storage
        self.push_resource('VID_0001.3gp', 'DCIM/100MZLLA')

        # launch the Video app
        self.app = self.apps.launch('Video')
        self.wait_for_element_displayed(*self._video_items_locator)

    def test_play_video(self):
        # https://moztrap.mozilla.org/manage/case/2478/

        all_videos = self.marionette.find_elements(*self._video_items_locator)

        # Assert that there are more than one video available
        self.assertGreater(all_videos, 0)

        first_video = all_videos[0]
        first_video_name = first_video.find_element(*self._video_name_locator).text

        # click on the first video
        self.marionette.tap(first_video)

        # Video will play automatically
        self.wait_for_element_displayed(*self._video_frame_locator)
        self.wait_for_element_displayed(*self._video_loaded_locator)

        # Wait for vid to have started playing
        self.assertTrue(self.marionette.execute_script("return window.wrappedJSObject.playing;"))

        # Tap to make toolbar visible
        self.marionette.tap(self.marionette.find_element(*self._video_frame_locator))

        # The elapsed time != 0:00 is the only indication of the toolbar visible
        self.assertNotEqual(self.marionette.find_element(*self._elapsed_text_locator).text, "00:00")

        # Check the name too. This will only work if the toolbar is visible
        self.assertEqual(first_video_name,
                         self.marionette.find_element(*self._video_title_locator).text)


text:
<?php

namespace FSi\Bundle\NewsBundle\Behat\Context\Page;

use SensioLabs\Behat\PageObjectExtension\PageObject\Page;

class NewsArchive extends Page
{
    protected $path = '/news/archive';

    /**
     * @return int
     */
    public function getNewsCount()
    {
        return count($this->findAll('css', 'div#news-archive > div.news'));
    }

    /**
     * @return bool
     */
    public function hasPagination()
    {
        return $this->has('css', 'div.pagination > nav');
    }

    /**
     * @param $text
     * @return Boolean
     */
    public function hasPaginationButton($text)
    {
        return $this->hasLink($text) || $this->has('css', sprintf('span:contains("%s")', $text));
    }

    /**
     * @param $text
     */
    public function pressPaginationButton($text)
    {
        return $this->clickLink($text);
    }

    /**
     * @param $text
     * @return Boolean
     */
    public function isButtonDisabled($text)
    {
        $button = $this->findLink($text);
        if (!isset($button)) {
            $button = $this->find('css', sprintf('span:contains("%s")', $text));
        }
        return $button->hasClass('disabled');
    }

    /**
     * @param $text
     * @return Boolean
     */
    public function isButtonCurrent($text)
    {
        $button = $this->findLink($text);
        if (!isset($button)) {
            $button = $this->find('css', sprintf('span:contains("%s")', $text));
        }

        return $button->hasClass('current');
    }
}


text:
package tests;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class PruebaVentanaVisual extends JFrame {

	private JPanel contentPane;
	private JTable tabla;
	private JLabel mensaje;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					PruebaVentanaVisual frame = new PruebaVentanaVisual();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public PruebaVentanaVisual() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JPanel panelSur = new JPanel();
		contentPane.add(panelSur, BorderLayout.SOUTH);

		JButton btnAceptar = new JButton("Aceptar");
		btnAceptar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.out.println( "Aceptar" );
			}
		});
		panelSur.add(btnAceptar);

		JButton btnCancelar = new JButton("Cancelar");
		panelSur.add(btnCancelar);

		tabla = new JTable();
		contentPane.add(tabla, BorderLayout.CENTER);

		mensaje = new JLabel();
		mensaje.setText("Prueba");
		contentPane.add( mensaje, BorderLayout.NORTH );
	}

}


text:
using Hangfire.Console.Serialization;
using System;

namespace Hangfire.Console.Storage
{
    internal interface IConsoleExpirationTransaction : IDisposable
    {
        /// <summary>
        /// Expire data for console.
        /// </summary>
        /// <param name="consoleId">Console identifier</param>
        /// <param name="expireIn">Expiration time</param>
        void Expire(ConsoleId consoleId, TimeSpan expireIn);

        /// <summary>
        /// Persist data for console.
        /// </summary>
        /// <param name="consoleId">Console identifier</param>
        void Persist(ConsoleId consoleId);
    }
}


text:
layout: remote_event
categories:
  - events
links:
title: "Hacking Imagination: Participatory Futures during a Pandemic"
description: "In 2019, NESTA, a global innovation agency based in the UK, commissioned research on participatory futures approaches. A global team compiled over 400 cases from around the world featuring an arrange of analog, tech-driven, and hybrid approaches, methods, and tools for engaging civil society in thinking about the future. Additionally, core team members developed a game that focuses on how to design more impactful, imaginative, and inclusive participatory futures engagements. Following the Q&A, participants are invited to play the game using Miro, an online whiteboard platform. "
speakers:
 - "Dr. John A. Sweeney Director, Qazaq Research Institute for Futures Studies Foresight Advisor, INTERPOL"
image: /images/events/398-263904128_386514.jpg
image_credit:
date: 2020-05-19T18:00:00-05:00
event_id: 398
youtube_id: wyXX9BZAUPo
agenda:
sponsor: Chi Hack Night Community
asl_provided: false
tags:
 - "participatory futures"
published: true

---

[Chi Hack Nights are now remote!](/blog/2020/03/16/chi-hack-night-going-remote.html) Same time, but now from the comfort of your self-quarantine location!

Tune into our livestream at 6pm CST every Tuesday: **[youtube.com/chihacknight/live](https://youtube.com/chihacknight/live)**

---

In 2019, NESTA, a global innovation agency based in the UK, commissioned research on participatory futures approaches. A [global team](https://actionforesight.net/global-swarm/) compiled over 400 cases from around the world featuring an arrange of analog, tech-driven, and hybrid approaches, methods, and tools for engaging civil society in thinking about the future. As with most projects, a report was produced, although only a small percentage of the content from our scan was included in the [final report](https://www.nesta.org.uk/report/our-futures-people-people/). In order to promote engagement on this topic and also to support further engagement, the team that undertook the original research is currently looking to develop an open-source map that provides an interface for exploring all the cases.

Additionally, core team members developed a game that focuses on how to design more impactful, imaginative, and inclusive participatory futures engagements. This presentation provides a brief introduction to the project, outlines a few of the cases, and concludes with an overview of the game, which is available as an open-source download [here](https://github.com/nestauk/our-futures/tree/master/en_original). Following the Q&A, participants are invited to play the game using Miro, an online whiteboard platform.

---

**ASL** This event will {% unless page.asl_provided %} not {% endunless %}have an American Sign Language interpreter.


text:
package org.apache.tez.dag.app.rm;

import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.event.AbstractEvent;

public class ContainerLauncherEvent extends AbstractEvent<ContainerLauncherEventType> {

  private final ContainerId containerId;
  private final NodeId nodeId;
  private final Token containerToken;
  private final int launcherId;
  private final int schedulerId;
  private final int taskCommId;

  public ContainerLauncherEvent(ContainerId containerId, NodeId nodeId,
                                Token containerToken, ContainerLauncherEventType type,
                                int launcherId,
                                int schedulerId, int taskCommId) {
    super(type);
    this.containerId = containerId;
    this.nodeId = nodeId;
    this.containerToken = containerToken;
    this.launcherId = launcherId;
    this.schedulerId = schedulerId;
    this.taskCommId = taskCommId;
  }

  public ContainerId getContainerId() {
    return this.containerId;
  }

  public NodeId getNodeId() {
    return this.nodeId;
  }

  public Token getContainerToken() {
    return this.containerToken;
  }

  public int getLauncherId() {
    return launcherId;
  }

  public int getSchedulerId() {
    return schedulerId;
  }

  public int getTaskCommId() {
    return taskCommId;
  }

  public String toSrting() {
    return super.toString() + " for container " + containerId + ", nodeId: "
        + nodeId + ", launcherId: " + launcherId + ", schedulerId=" + schedulerId +
        ", taskCommId=" + taskCommId;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
        + ((containerId == null) ? 0 : containerId.hashCode());
    result = prime * result
        + ((containerToken == null) ? 0 : containerToken.hashCode());
    result = prime * result + ((nodeId == null) ? 0 : nodeId.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    ContainerLauncherEvent other = (ContainerLauncherEvent) obj;
    if (containerId == null) {
      if (other.containerId != null)
        return false;
    } else if (!containerId.equals(other.containerId))
      return false;
    if (containerToken == null) {
      if (other.containerToken != null)
        return false;
    } else if (!containerToken.equals(other.containerToken))
      return false;
    if (nodeId == null) {
      if (other.nodeId != null)
        return false;
    } else if (!nodeId.equals(other.nodeId))
      return false;
    return true;
  }
}


text: Java library implementing IRCC service from Sony.


text:
package org.apache.skywalking.apm.collector.analysis.metric.provider.worker.application.mapping;

import org.apache.skywalking.apm.collector.analysis.metric.define.graph.MetricWorkerIdDefine;
import org.apache.skywalking.apm.collector.core.graph.Next;
import org.apache.skywalking.apm.collector.core.graph.NodeProcessor;
import org.apache.skywalking.apm.collector.core.util.Const;
import org.apache.skywalking.apm.collector.core.util.TimeBucketUtils;
import org.apache.skywalking.apm.collector.storage.table.application.ApplicationMapping;

/**
 * @author peng-yongsheng
 */
public class ApplicationMappingDayTransformNode implements NodeProcessor<ApplicationMapping, ApplicationMapping> {

    @Override public int id() {
        return MetricWorkerIdDefine.APPLICATION_MAPPING_DAY_TRANSFORM_NODE_ID;
    }

    @Override
    public void process(ApplicationMapping applicationMapping, Next<ApplicationMapping> next) {
        long timeBucket = TimeBucketUtils.INSTANCE.minuteToDay(applicationMapping.getTimeBucket());

        ApplicationMapping newApplicationMapping = ApplicationMappingCopy.copy(applicationMapping);
        newApplicationMapping.setId(String.valueOf(timeBucket) + Const.ID_SPLIT + applicationMapping.getMetricId());
        newApplicationMapping.setTimeBucket(timeBucket);
        next.execute(newApplicationMapping);
    }
}


text:
package com.example.sampe.installapplist;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.List;

public class InstallAppList extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_install_app_list);

        PackageManager pm = this.getPackageManager();
        final List<ApplicationInfo> appInfoList = pm.getInstalledApplications(0);

        final ArrayAdapter<String> appNameList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

        for(ApplicationInfo app: appInfoList){
            String name = app.loadLabel(pm).toString();
            appNameList.add(name);
        }

        ListView listView = new ListView(this);
        setContentView(listView);
        listView.setAdapter(appNameList);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ApplicationInfo item = appInfoList.get(position);
                Intent intent = new Intent(InstallAppList.this, AppDetailViewActivity.class);
                intent.putExtra("AppInfo", item);
                startActivity(intent);
            }
        });

    }
}


text:
var Q = require('q');
var fs = require('fs');
var sys = require('sys');

var Youtube = function() {};

Youtube.prototype.search = function(track){

    var deferred = Q.defer();
    var songs = [
        {title: track.title, url: "http://youtube.com/"+track.title, id: track.id},
        {title: track.title, url: "http://youtube.com/bb", id: "bb"},
    ];
    deferred.resolve( {songs:songs, track: track});
    return deferred.promise;
};

Youtube.prototype.showPlaylist = function(youtube_songs){
    fs.writeFile("/tmp/youtube.html", this.html_page(youtube_songs), function(err) {
            if(err) {
                sys.puts(err);
            } else {
                var exec = require('child_process').exec;
                var child = exec("firefox /tmp/youtube.html &", function (error, stdout, stderr) {
                        sys.print('stdout: ' + stdout);
                        sys.print('stderr: ' + stderr);
                        if (error !== null) {
                            console.log('exec error: ' + error);
                        }
                    });
            }
        });
};

module.exports = Youtube;


text:
{% extends "base.html" %}

{% block content %}

<form role="form" method="POST">

        Email address
        <input type="email" class="form-control" id="email" name="email" placeholder="Email address" required>

        Password
        <input type="password" class="form-control" id="password" name="password" placeholder="Password" required>

    <button type="submit" class="btn btn-primary btn-md">Submit</button>
</form>

Forget your password? Reset it here.

{% endblock %}


text:
export interface SourceReferenceInputTypeInterface {
    type: string;
    name: string;
}


text:
__stop_admiral() {
  __process_msg "Checking if admiral is running"
  local admiral_container=$(sudo docker ps -a | grep admiral | awk '{print $1}')
  if [ "$admiral_container" != "" ]; then
    __process_msg "Stopping running admiral container: $admiral_container"
    sudo docker stop -t=0 $admiral_container
    sudo docker rm -v $admiral_container
  fi
}

__boot_admiral() {
  __process_msg "Generating admiral ENV variables"
  local envs=" -e DBNAME=$DB_NAME \
    -e DBUSERNAME=$DB_USER \
    -e DBPASSWORD=$DB_PASSWORD \
    -e DBDIALECT=$DB_DIALECT \
    -e DBHOST=$DB_IP \
    -e DBPORT=$DB_PORT \
    -e RUN_MODE=$RUN_MODE \
    -e SSH_USER=$SSH_USER \
    -e LOGIN_TOKEN=$LOGIN_TOKEN \
    -e ADMIRAL_IP=$ADMIRAL_IP \
    -e PRIVATE_IMAGE_REGISTRY=$PRIVATE_IMAGE_REGISTRY \
    -e CONFIG_DIR=$CONFIG_DIR \
    -e RUNTIME_DIR=$RUNTIME_DIR"

  __process_msg "Generating admiral mounts"
  local docker_location=$(which docker)
  local mounts=" -v $CONFIG_DIR:$CONFIG_DIR \
    -v $RUNTIME_DIR:$RUNTIME_DIR \
    -v $docker_location:/usr/bin/docker \
    -v /usr/lib/x86_64-linux-gnu/libapparmor.so.1.1.0:/lib/x86_64-linux-gnu/libapparmor.so.1:rw \
    -v /usr/lib/x86_64-linux-gnu/libltdl.so.7.3.0:/lib/x86_64-linux-gnu/libltdl.so.7:rw \
    -v /var/run/docker.sock:/var/run/docker.sock"

  local admiral_image="$PUBLIC_IMAGE_REGISTRY/admiral:$RELEASE"

  local boot_cmd="sudo docker run -d \
    $envs \
    $mounts \
    --publish 50003:50003 \
    --net=host \
    --privileged=true \
    --name=admiral \
    $admiral_image"

  eval "$boot_cmd"
  __process_msg "Admiral container successfully running"

  __process_success "Go to $ADMIRAL_IP:50003 to access the admin panel"
  __process_success "Login Token: $LOGIN_TOKEN"
}

main() {
  __process_marker "Booting Admiral UI"
  __stop_admiral
  __boot_admiral
}

main


text:
<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 25/09/2015
 * Time: 14:26
 */

namespace Sdz\BlogBundle\Validator;

use Doctrine\ORM\EntityManager;
use Symfony\Component\BrowserKit\Request;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class AntiFloodValidator extends ConstraintValidator
{
    private $request;
    private $em;

    public function __construct(Request $request, EntityManager $em)
    {
        $this->request = $request;
        $this->em = $em;
    }

    public function validate($value, Constraint $constraint)
    {
        $ip = $this->request->getServer()->get('REMOTE_ADDR');

        // Pour l'instant, on considère comme flood tout message de moins de 3 caractères
        if (strlen($value) < 3) {
            // C'est cette ligne qui déclenche l'erreur pour le formulaire, avec en argument le message
            $this->context->buildViolation($constraint->messageSpam)
                ->addViolation();
//            $this->context->addViolation($constraint->messageSpam);
        }
  }
}