text:
package keyset

import (
	"errors"
	"fmt"

	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/proto"

	"github.com/google/tink/go/core/primitiveset"
	"github.com/google/tink/go/core/registry"
	"github.com/google/tink/go/tink"
	tinkpb "github.com/google/tink/go/proto/tink_go_proto"
)

var errInvalidKeyset = fmt.Errorf("keyset.Handle: invalid keyset")

// Handle provides access to a Keyset protobuf, to limit the exposure of actual protocol
// buffers that hold sensitive key material.
type Handle struct {
	ks          *tinkpb.Keyset
	annotations map[string]string
}

func newWithOptions(ks *tinkpb.Keyset, opts ...Option) (*Handle, error) {
	h := &Handle{ks: ks}
	if err := applyOptions(h, opts...); err != nil {
		return nil, err
	}
	return h, nil
}

// NewHandle creates a keyset handle that contains a single fresh key generated according
// to the given KeyTemplate.
func NewHandle(kt *tinkpb.KeyTemplate) (*Handle, error) {
	ksm := NewManager()
	err := ksm.Rotate(kt)
	if err != nil {
		return nil, fmt.Errorf("keyset.Handle: cannot generate new keyset: %s", err)
	}
	handle, err := ksm.Handle()
	if err != nil {
		return nil, fmt.Errorf("keyset.Handle: cannot get keyset handle: %s", err)
	}
	return handle, nil
}

// NewHandleWithNoSecrets creates a new instance of KeysetHandle using the given keyset which does
// not contain any secret key material.
func NewHandleWithNoSecrets(ks *tinkpb.Keyset) (*Handle, error) {
	if ks == nil {
		return nil, errors.New("keyset.Handle: nil keyset")
	}
	h := &Handle{ks: ks}
	if h.hasSecrets() {
		// If you need to do this, you have to use func insecurecleartextkeyset.Read() instead.
		return nil, errors.New("importing unencrypted secret key material is forbidden")
	}
	return h, nil
}

// Read tries to create a Handle from an encrypted keyset obtained via reader.
func Read(reader Reader, masterKey tink.AEAD) (*Handle, error) {
	return ReadWithAssociatedData(reader, masterKey, []byte{})
}

// ReadWithAssociatedData tries to create a Handle from an encrypted keyset obtained via reader using the provided associated data.
func ReadWithAssociatedData(reader Reader, masterKey tink.AEAD, associatedData []byte) (*Handle, error) {
	encryptedKeyset, err := reader.ReadEncrypted()
	if err != nil {
		return nil, err
	}
	ks, err := decrypt(encryptedKeyset, masterKey, associatedData)
	if err != nil {
		return nil, err
	}
	return &Handle{ks: ks}, nil
}

// ReadWithNoSecrets tries to create a keyset.Handle from a keyset obtained via reader.
func ReadWithNoSecrets(reader Reader) (*Handle, error) {
	ks, err := reader.Read()
	if err != nil {
		return nil, err
	}
	return NewHandleWithNoSecrets(ks)
}

// Public returns a Handle of the public keys if the managed keyset contains private keys.
func (h *Handle) Public() (*Handle, error) {
	privKeys := h.ks.Key
	pubKeys := make([]*tinkpb.Keyset_Key, len(privKeys))

	for i := 0; i < len(privKeys); i++ {
		if privKeys[i] == nil || privKeys[i].KeyData == nil {
			return nil, errInvalidKeyset
		}
		privKeyData := privKeys[i].KeyData
		pubKeyData, err := publicKeyData(privKeyData)
		if err != nil {
			return nil, fmt.Errorf("keyset.Handle: %s", err)
		}
		pubKeys[i] = &tinkpb.Keyset_Key{
			KeyData:          pubKeyData,
			Status:           privKeys[i].Status,
			KeyId:            privKeys[i].KeyId,
			OutputPrefixType: privKeys[i].OutputPrefixType,
		}
	}
	ks := &tinkpb.Keyset{
		PrimaryKeyId: h.ks.PrimaryKeyId,
		Key:          pubKeys,
	}
	return &Handle{ks: ks}, nil
}

// String returns a string representation of the managed keyset.
// The result does not contain any sensitive key material.
func (h *Handle) String() string {
	c, err := prototext.MarshalOptions{}.Marshal(getKeysetInfo(h.ks))
	if err != nil {
		return ""
	}
	return string(c)
}

// KeysetInfo returns KeysetInfo representation of the managed keyset.
// The result does not contain any sensitive key material.
func (h *Handle) KeysetInfo() *tinkpb.KeysetInfo {
	return getKeysetInfo(h.ks)
}

// Write encrypts and writes the enclosing keyset.
func (h *Handle) Write(writer Writer, masterKey tink.AEAD) error {
	return h.WriteWithAssociatedData(writer, masterKey, []byte{})
}

// WriteWithAssociatedData encrypts and writes the enclosing keyset using the provided associated data.
func (h *Handle) WriteWithAssociatedData(writer Writer, masterKey tink.AEAD, associatedData []byte) error {
	encrypted, err := encrypt(h.ks, masterKey, associatedData)
	if err != nil {
		return err
	}
	return writer.WriteEncrypted(encrypted)
}

// WriteWithNoSecrets exports the keyset in h to the given Writer w returning an error if the keyset
// contains secret key material.
func (h *Handle) WriteWithNoSecrets(w Writer) error {
	if h.hasSecrets() {
		return errors.New("exporting unencrypted secret key material is forbidden")
	}

	return w.Write(h.ks)
}

// Primitives creates a set of primitives corresponding to the keys with
// status=ENABLED in the keyset of the given keyset handle, assuming all the
// corresponding key managers are present (keys with status!=ENABLED are skipped).
//
// The returned set is usually later "wrapped" into a class that implements
// the corresponding Primitive-interface.
func (h *Handle) Primitives() (*primitiveset.PrimitiveSet, error) {
	return h.PrimitivesWithKeyManager(nil)
}

// PrimitivesWithKeyManager creates a set of primitives corresponding to
// the keys with status=ENABLED in the keyset of the given keysetHandle, using
// the given key manager (instead of registered key managers) for keys supported
// by it.  Keys not supported by the key manager are handled by matching registered
// key managers (if present), and keys with status!=ENABLED are skipped.
//
// This enables custom treatment of keys, for example providing extra context
// (e.g. credentials for accessing keys managed by a KMS), or gathering custom
// monitoring/profiling information.
//
// The returned set is usually later "wrapped" into a class that implements
// the corresponding Primitive-interface.
func (h *Handle) PrimitivesWithKeyManager(km registry.KeyManager) (*primitiveset.PrimitiveSet, error) {
	if err := Validate(h.ks); err != nil {
		return nil, fmt.Errorf("registry.PrimitivesWithKeyManager: invalid keyset: %s", err)
	}
	primitiveSet := primitiveset.New()
	primitiveSet.Annotations = h.annotations
	for _, key := range h.ks.Key {
		if key.Status != tinkpb.KeyStatusType_ENABLED {
			continue
		}
		var primitive interface{}
		var err error
		if km != nil && km.DoesSupport(key.KeyData.TypeUrl) {
			primitive, err = km.Primitive(key.KeyData.Value)
		} else {
			primitive, err = registry.PrimitiveFromKeyData(key.KeyData)
		}
		if err != nil {
			return nil, fmt.Errorf("registry.PrimitivesWithKeyManager: cannot get primitive from key: %s", err)
		}
		entry, err := primitiveSet.Add(primitive, key)
		if err != nil {
			return nil, fmt.Errorf("registry.PrimitivesWithKeyManager: cannot add primitive: %s", err)
		}
		if key.KeyId == h.ks.PrimaryKeyId {
			primitiveSet.Primary = entry
		}
	}
	return primitiveSet, nil
}

// hasSecrets checks if the keyset handle contains any key material considered secret.
// Both symmetric keys and the private key of an assymmetric crypto system are considered secret keys.
// Also returns true when encountering any errors.
func (h *Handle) hasSecrets() bool {
	for _, k := range h.ks.Key {
		if k == nil || k.KeyData == nil {
			continue
		}
		if k.KeyData.KeyMaterialType == tinkpb.KeyData_UNKNOWN_KEYMATERIAL {
			return true
		}
		if k.KeyData.KeyMaterialType == tinkpb.KeyData_ASYMMETRIC_PRIVATE {
			return true
		}
		if k.KeyData.KeyMaterialType == tinkpb.KeyData_SYMMETRIC {
			return true
		}
	}
	return false
}

func publicKeyData(privKeyData *tinkpb.KeyData) (*tinkpb.KeyData, error) {
	if privKeyData.KeyMaterialType != tinkpb.KeyData_ASYMMETRIC_PRIVATE {
		return nil, fmt.Errorf("keyset.Handle: keyset contains a non-private key")
	}
	km, err := registry.GetKeyManager(privKeyData.TypeUrl)
	if err != nil {
		return nil, err
	}
	pkm, ok := km.(registry.PrivateKeyManager)
	if !ok {
		return nil, fmt.Errorf("keyset.Handle: %s does not belong to a PrivateKeyManager", privKeyData.TypeUrl)
	}
	return pkm.PublicKeyData(privKeyData.Value)
}

func decrypt(encryptedKeyset *tinkpb.EncryptedKeyset, masterKey tink.AEAD, associatedData []byte) (*tinkpb.Keyset, error) {
	if encryptedKeyset == nil || masterKey == nil {
		return nil, fmt.Errorf("keyset.Handle: invalid encrypted keyset")
	}
	decrypted, err := masterKey.Decrypt(encryptedKeyset.EncryptedKeyset, associatedData)
	if err != nil {
		return nil, fmt.Errorf("keyset.Handle: decryption failed: %s", err)
	}
	keyset := new(tinkpb.Keyset)
	if err := proto.Unmarshal(decrypted, keyset); err != nil {
		return nil, errInvalidKeyset
	}
	return keyset, nil
}

func encrypt(keyset *tinkpb.Keyset, masterKey tink.AEAD, associatedData []byte) (*tinkpb.EncryptedKeyset, error) {
	serializedKeyset, err := proto.Marshal(keyset)
	if err != nil {
		return nil, errInvalidKeyset
	}
	encrypted, err := masterKey.Encrypt(serializedKeyset, associatedData)
	if err != nil {
		return nil, fmt.Errorf("keyset.Handle: encrypted failed: %s", err)
	}
	// get keyset info
	encryptedKeyset := &tinkpb.EncryptedKeyset{
		EncryptedKeyset: encrypted,
		KeysetInfo:      getKeysetInfo(keyset),
	}
	return encryptedKeyset, nil
}

// getKeysetInfo returns a KeysetInfo from a Keyset protobuf.
func getKeysetInfo(keyset *tinkpb.Keyset) *tinkpb.KeysetInfo {
	if keyset == nil {
		panic("keyset.Handle: keyset must be non nil")
	}
	nKey := len(keyset.Key)
	keyInfos := make([]*tinkpb.KeysetInfo_KeyInfo, nKey)
	for i, key := range keyset.Key {
		keyInfos[i] = getKeyInfo(key)
	}
	return &tinkpb.KeysetInfo{
		PrimaryKeyId: keyset.PrimaryKeyId,
		KeyInfo:      keyInfos,
	}
}

// getKeyInfo returns a KeyInfo from a Key protobuf.
func getKeyInfo(key *tinkpb.Keyset_Key) *tinkpb.KeysetInfo_KeyInfo {
	return &tinkpb.KeysetInfo_KeyInfo{
		TypeUrl:          key.KeyData.TypeUrl,
		Status:           key.Status,
		KeyId:            key.KeyId,
		OutputPrefixType: key.OutputPrefixType,
	}
}


text:
<?php
if(isset($this->message) && $this->message!='')
{
    if($this->message_type=='err')
        echo '
'.$this->message.'
';
    if($this->message_type=='succ')
        echo '
'.$this->message.'
';
}
?>

redpajama_set_name: RedPajamaGithub


text:
package cusanalytic_sc_online

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DescribeActionData invokes the cusanalytic_sc_online.DescribeActionData API synchronously
// api document: https://help.aliyun.com/api/cusanalytic_sc_online/describeactiondata.html
func (client *Client) DescribeActionData(request *DescribeActionDataRequest) (response *DescribeActionDataResponse, err error) {
	response = CreateDescribeActionDataResponse()
	err = client.DoAction(request, response)
	return
}

// DescribeActionDataWithChan invokes the cusanalytic_sc_online.DescribeActionData API asynchronously
// api document: https://help.aliyun.com/api/cusanalytic_sc_online/describeactiondata.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeActionDataWithChan(request *DescribeActionDataRequest) (<-chan *DescribeActionDataResponse, <-chan error) {
	responseChan := make(chan *DescribeActionDataResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DescribeActionData(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DescribeActionDataWithCallback invokes the cusanalytic_sc_online.DescribeActionData API asynchronously
// api document: https://help.aliyun.com/api/cusanalytic_sc_online/describeactiondata.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeActionDataWithCallback(request *DescribeActionDataRequest, callback func(response *DescribeActionDataResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DescribeActionDataResponse
		var err error
		defer close(result)
		response, err = client.DescribeActionData(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DescribeActionDataRequest is the request struct for api DescribeActionData
type DescribeActionDataRequest struct {
	*requests.RpcRequest
	TsEnd     requests.Integer `position:"Body" name:"TsEnd"`
	StoreId   string           `position:"Body" name:"StoreId"`
	PageLimit requests.Integer `position:"Body" name:"PageLimit"`
	PageNo    requests.Integer `position:"Body" name:"PageNo"`
	TsStart   requests.Integer `position:"Body" name:"TsStart"`
}

// DescribeActionDataResponse is the response struct for api DescribeActionData
type DescribeActionDataResponse struct {
	*responses.BaseResponse
	PageNo                      int             `json:"PageNo" xml:"PageNo"`
	TsStart                     int64           `json:"TsStart" xml:"TsStart"`
	PageLimit                   int             `json:"PageLimit" xml:"PageLimit"`
	PageCount                   int             `json:"PageCount" xml:"PageCount"`
	DescribeActionDataIsSuccess bool            `json:"IsSuccess" xml:"IsSuccess"`
	ErrorMsg                    string          `json:"ErrorMsg" xml:"ErrorMsg"`
	StoreId                     string          `json:"StoreId" xml:"StoreId"`
	TsEnd                       int64           `json:"TsEnd" xml:"TsEnd"`
	ActionsMsgItems             ActionsMsgItems `json:"ActionsMsgItems" xml:"ActionsMsgItems"`
}

// CreateDescribeActionDataRequest creates a request to invoke DescribeActionData API
func CreateDescribeActionDataRequest() (request *DescribeActionDataRequest) {
	request = &DescribeActionDataRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("cusanalytic_sc_online", "2019-05-24", "DescribeActionData", "", "")
	return
}

// CreateDescribeActionDataResponse creates a response to parse from DescribeActionData response
func CreateDescribeActionDataResponse() (response *DescribeActionDataResponse) {
	response = &DescribeActionDataResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
package elastic

import (
	"encoding/json"
	"testing"
)

func TestFiltersAggregationFilters(t *testing.T) {
	f1 := NewRangeQuery("stock").Gt(0)
	f2 := NewTermQuery("symbol", "GOOG")
	agg := NewFiltersAggregation().Filters(f1, f2)
	src, err := agg.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"filters":{"filters":[{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},{"term":{"symbol":"GOOG"}}]}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestFiltersAggregationFilterWithName(t *testing.T) {
	f1 := NewRangeQuery("stock").Gt(0)
	f2 := NewTermQuery("symbol", "GOOG")
	agg := NewFiltersAggregation().
		FilterWithName("f1", f1).
		FilterWithName("f2", f2)
	src, err := agg.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"filters":{"filters":{"f1":{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},"f2":{"term":{"symbol":"GOOG"}}}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestFiltersAggregationWithKeyedAndNonKeyedFilters(t *testing.T) {
	agg := NewFiltersAggregation().
		Filter(NewTermQuery("symbol", "MSFT")).               // unnamed
		FilterWithName("one", NewTermQuery("symbol", "GOOG")) // named filter
	_, err := agg.Source()
	if err == nil {
		t.Fatal("expected error, got nil")
	}
}

func TestFiltersAggregationWithSubAggregation(t *testing.T) {
	avgPriceAgg := NewAvgAggregation().Field("price")
	f1 := NewRangeQuery("stock").Gt(0)
	f2 := NewTermQuery("symbol", "GOOG")
	agg := NewFiltersAggregation().Filters(f1, f2).SubAggregation("avg_price", avgPriceAgg)
	src, err := agg.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"aggregations":{"avg_price":{"avg":{"field":"price"}}},"filters":{"filters":[{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},{"term":{"symbol":"GOOG"}}]}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestFiltersAggregationWithMetaData(t *testing.T) {
	f1 := NewRangeQuery("stock").Gt(0)
	f2 := NewTermQuery("symbol", "GOOG")
	agg := NewFiltersAggregation().Filters(f1, f2).Meta(map[string]interface{}{"name": "Oliver"})
	src, err := agg.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"filters":{"filters":[{"range":{"stock":{"from":0,"include_lower":false,"include_upper":true,"to":null}}},{"term":{"symbol":"GOOG"}}]},"meta":{"name":"Oliver"}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}


text:
layout: page
sidebar: right
subheadline: Notebook
title:  "Introduction to Atmospheric Ozone"
teaser: "Own notes about Ozone"
breadcrumb: true
tags: [Atmospheric Chemistry, Atmospheric Physics, Ozone, Stratosphere]
categories:
    - science-blog
header:
    title: Atmospheric Chemistry of Ozone
    pattern: pattern_jquery-dark-grey-tile.png
---

> Still under construction...

#### Table of Contents
{:.no_toc }
*  TOC
{:toc}

### Theory of Chapman

It is one of the first, but still useful, theories developed with the objective of explain the production and removing of Ozone on the atmosphere. It proposes a set of chemical reations:

- Photochemical formation

   $$ O_{3}+h\nu \longrightarrow O+O$$

   $$ O_{2}+O+M \longrightarrow  O_{3} + M$$

   Here M is a kind of mediator/catalitic of the chemical reaction, for example $$N_{2}$$. And the light involved belongs to the UV should have a wavelenght  $$ \lambda  \leq 242 nm $$

- Destruction

   $$ O_{3}+h\nu\longrightarrow  O_{2}+O, \qquad \text{with} \qquad \lambda  \leq 850 nm $$

   $$ O_{2}+h\nu \longrightarrow  O_{2}+O(D), \qquad \text{with} \qquad \lambda \leq 320 nm $$

- Producing Oxigen molecule O2

   $$ O_{3}+O \longrightarrow  2O_{2}$$

   $$ O+O+M   \longrightarrow  O_{2}+M$$

   Here M is also kind of mediator/catalitic of the chemical reaction, for example $$N_{2}$$.

The balance between all these equations gives us the estimation of the concentrations.

> According with this theory the formation on O3 is larger on those latitudes with higher incoming UV radiation from the sun, and also un the upper-half part of the atmosphere. However also daily and seasonal variations of incoming radiance will have a direct impact on the formation of Ozone.

Illustration of the Theory of Chapman, from E. Generalic, http://www.periodni.com/ozone_layer_is_not_a_shield.html).

### Ozone Depletion

The Theory of Chapman describes the production of Ozone on the stratosphere but it fails to full describe the ozone depletion that happened mainly during the 70's and 80's. Whence, the original proposal was complemented by chemical reactions involving the now commontly named: ozone depleting substances (ODS) in oposition to for example, ozone precursors. Two families of ODS are named chlorine and bromine compounds. In the case of the chlorine (for examples CFCs) it is possible to have now reactions like:

   $$ CFCl_{3}+h\nu \longrightarrow Cl +\, others$$

and

   $$ Cl+O_{3} \longrightarrow ClO +O_{2}, \qquad \text{with} \qquad \lambda  \leq 230 nm $$

And we can realize that the previous theory of Chapman is now incomplete. Also similar reactions involving Br, $$NO_{x}$$ or $$HO_{x}$$ compounds are possible. Obviusly the process is more complex, and for example Cl can react with $$CH_{4}$$. Finally note that these chain-reactions are conditioned by the atmospheric transport on the trosposphere and stratosphere, and also scavening processes on the troposphere.

### Transport of Ozone

#### Large-scale diabatic circulation

It is known as **Brewer-Dobson circulation**, and it consist on two cells, on each hemisphere ascendent on the tropics, descedent on highlatitudes, which a wave driven transport on the extratropics. Accelerations and decelerations of the Brewer-Dobson circulation is nowdays an active field of research.

A direct consquence of the large-scale circulation is a lower total concentration of Ozone in the tropics and higher on mid to high latitudes but with a strong seasonal component. As a consequence, on highlatitudes we expect higher concentrations on Spring on the Northern Hemisphere but the higher concentrations on Souther Hemisphere are found mostly in November to December. This lower total concentration of ozone on the tropics is due to transport as most of the production of Ozone by UV radiance incidence is happing on these regions.

Illustration of Brewer-Dobson circulation, from http://www.centrometeolombardo.com).

#### Polar Vortex

However, there is another large scale feature named Polar Vortex which can refers to the tropospheric polar vortex or to the stratospheric polar vortex. Here we are mainly focused on the stratospheric polar vortex which has less extension in terms of latitude. The presence of the stratospheric polar vortex has also a seasonal cycle being stronger in Summer-Autumn on the Southern Hemisphere, for example. In this situation the air masses from the tropics rich in ozone can not penetrate on the polar vortex and ozone depletion is larger with the contribution of the polar stratospheric clouds.

Illustration of Polar Vortex. Credits: Darryn W. Waugh research group webpage).

#### Definitions

**Half-Life**: it is the time that a species need to decrease its concentration to half of its initial value.

[Up to table of contents](#toc)
{: .text-right }


text:
import { TestSuite, Test, BeforeAll, AfterAll, Async } from "jec-juta";
import { expect, assert } from "chai";
import { ConfigLoaderBaseImpl } from "../../../../../../utils/test-utils/classes/ConfigLoaderBaseImpl";
import { MappedPathUtil } from "../../../../../../src/com/onsoft/glasscat/util/paths/MappedPathUtil";
import { GlassCatError } from "../../../../../../src/com/onsoft/glasscat/exceptions/GlassCatError";
import { GlassCatErrorCode } from "../../../../../../src/com/onsoft/glasscat/exceptions/GlassCatErrorCode";

import * as utils from "../../../../../../utils/test-utils/utilities/ConfigLoaderBaseTestUtils";

@TestSuite({
  description: "Test the ConfigLoaderBase class template methods"
})
export class ConfigLoaderBaseTest {

  private loader:ConfigLoaderBaseImpl = null;

  @BeforeAll()
  public initTest():void {
    this.loader = new ConfigLoaderBaseImpl();
    MappedPathUtil.getInstance().init(process.cwd());
  }

  @AfterAll()
  public resetTest():void {
    this.loader = null;
    MappedPathUtil.getInstance().init(null);
  }

  @Test({
    description: "should load and return a valid JavaScript Object that contains domains information"
  })
  public loadConfigSyncTest():void {
    const result:any = this.loader.loadConfigSyncImpl(utils.VALID_CONFIG_PATH);
    expect(result.domains).to.have.lengthOf(1);
  }

  @Test({
    description: "should throw an error when the path to the congiguration file is not valid"
  })
  public loadConfigSyncInvalidPathTest():void {
    const loadInvalidDomain:Function = function():void {
      this.loader.loadConfigSyncImpl(utils.INVALID_PATH);
    };
    expect(loadInvalidDomain.bind(this)).to.throw(GlassCatError);
  }

  @Test({
    description: "should throw an error of the type of 'GlassCatErrorCode.CONFIG_LOADING_FAILURE'"
  })
  public loadConfigSyncInvalidPathErrorTest():void {
    try {
      this.loader.loadConfigSyncImpl(utils.INVALID_PATH);
    } catch(e) {
      expect(e.getCode()).to.equal(GlassCatErrorCode.CONFIG_LOADING_FAILURE);
    }
  }

  @Test({
    description: "should throw an error when the congiguration file does not contain a valid object"
  })
  public loadConfigSyncInvalidFileTest():void {
    const loadInvalidDomain:Function = function():void {
      this.loader.loadConfigSyncImpl(utils.INVALID_CONFIG_PATH);
    };
    expect(loadInvalidDomain.bind(this)).to.throw(GlassCatError);
  }

  @Test({
    description: "should throw an error of the type of 'GlassCatErrorCode.CONFIG_LOADING_FAILURE'"
  })
  public loadConfigSyncInvalidFileErrorTest():void {
    try {
      this.loader.loadConfigSyncImpl(utils.INVALID_CONFIG_PATH);
    } catch(e) {
      expect(e.getCode()).to.equal(GlassCatErrorCode.CONFIG_LOADING_FAILURE);
    }
  }

  @Test({
    description: "should load and return a valid JavaScript Object that contains domains information"
  })
  public loadConfigTest(@Async done:Function):void {
    this.loader.loadConfigImpl(utils.VALID_CONFIG_PATH,
      (data:any)=> {
        expect(data.domains).to.have.lengthOf(1);
        done();
      },
      (error:GlassCatError)=> {
        assert.fail(null, error, "Exception should not be thrown");
      }
    );
  }

  @Test({
    description: "should invoke the error callback when the path to the congiguration file is not valid"
  })
  public loadConfigInvalidPathTest(@Async done:Function):void {
    this.loader.loadConfigImpl(utils.INVALID_PATH,
      (data:any)=> {
        assert.fail(null, data, "Test should fail");
      },
      (error:GlassCatError)=> {
        expect(error).not.to.be.null;
        done();
      }
    );
  }

  @Test({
    description: "should pass an error of the type of 'GlassCatErrorCode.CONFIG_LOADING_FAILURE'"
  })
  public loadConfigInvalidPathErrorTest(@Async done:Function):void {
    this.loader.loadConfigImpl(utils.INVALID_PATH,
      (data:any)=> {
        assert.fail(null, data, "Test should fail");
      },
      (error:GlassCatError)=> {
        expect(error.getCode()).to
                               .equal(GlassCatErrorCode.CONFIG_LOADING_FAILURE);
        done();
      }
    );
  }

  @Test({
    description: "should invoke the error callback when the congiguration file does not contain a valid object"
  })
  public loadConfigInvalidFileTest(@Async done:Function):void {
    this.loader.loadConfigImpl(utils.INVALID_CONFIG_PATH,
      (data:any)=> {
        assert.fail(null, data, "Test should fail");
      },
      (error:GlassCatError)=> {
        expect(error).not.to.be.null;
        done();
      }
    );
  }

  @Test({
    description: "should pass an error of the type of 'GlassCatErrorCode.CONFIG_LOADING_FAILURE'"
  })
  public loadConfigInvalidFileErrorTest(@Async done:Function):void {
    this.loader.loadConfigImpl(utils.INVALID_CONFIG_PATH,
      (data:any)=> {
        assert.fail(null, data, "Test should fail");
      },
      (error:GlassCatError)=> {
        expect(error.getCode()).to
                               .equal(GlassCatErrorCode.CONFIG_LOADING_FAILURE);
        done();
      }
    );
  }
}


text:
<link rel="import" href="../../../bower_components/polymer/polymer.html">

<link rel="import" href="../../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../../bower_components/paper-icon-button/paper-icon-button.html">

<link rel="import" href="../social-post/social-post.html">

<dom-module id="social-feed">

  <template>

      <iron-ajax auto url="[[source]]" handle-as="json" last-response="{{_posts}}"></iron-ajax>

Quoi de neuf #{$ hashtag $}

        Tweets sur #devfesttoulouse

Social

Pour nous suivre, nous liker, nous ajouter à vos cercles, c'est ici que ça se passe

          {% for name, item in social %}

            <paper-icon-button icon="icons:{$ name $}"></paper-icon-button>

          {% endfor %}

  </template>

</dom-module>


text:
import redis
import logging
import sys
import time
import re
import pickle
import traceback
import json
import requests

from settings import (REDIS_HOST, REDIS_PORT, KAFKA_HOSTS, KAFKA_TOPIC_PREFIX)

from kafka import KafkaClient, SimpleProducer

class RedisMonitor:

    def __init__(self):
        self.setup()

    def setup(self):
        '''
        Connection stuff here so we can mock it
        '''
        self.redis_conn = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)

        # set up kafka
        self.kafka_conn = KafkaClient(KAFKA_HOSTS)
        self.producer = SimpleProducer(self.kafka_conn)
        self.topic_prefix = KAFKA_TOPIC_PREFIX

    def run(self):
        '''
        The external main run loop
        '''
        self._main_loop()

    def _main_loop(self):
        '''
        The internal while true main loop for the redis monitor
        '''
        while True:
            self._do_info()
            self._do_expire()
            self._do_stop()

            time.sleep(0.1)

    def _do_info(self):
        '''
        Processes info action requests
        '''
        for key in self.redis_conn.scan_iter(match="info:*:*"):
            # the master dict to return
            master = {}
            master['uuid'] = self.redis_conn.get(key)
            master['total_pending'] = 0
            master['server_time'] = int(time.time())

            # break down key
            elements = key.split(":")
            dict = {}
            dict['spiderid'] = elements[1]
            dict['appid'] = elements[2]

            if len(elements) == 4:
                dict['crawlid'] = elements[3]

            # generate the information requested
            if 'crawlid' in dict:
                master = self._build_crawlid_info(master, dict)
            else:
                master = self._build_appid_info(master, dict)

            self.redis_conn.delete(key)

            if self._send_to_kafka(master):
                pass
                #print 'Sent info to kafka'
            else:
                print 'Failed to send info to kafka'

    def _send_to_kafka(self, master):
        '''
        Sends the message back to Kafka
        @param master: the final dict to send
        @log_extras: the extras to append to the log output
        @returns: True if successfully sent to kafka
        '''
        appid_topic = "{prefix}.outbound_{appid}".format(
                                                    prefix=self.topic_prefix,
                                                    appid=master['appid'])
        firehose_topic = "{prefix}.outbound_firehose".format(
                                                    prefix=self.topic_prefix)
        try:
            self.kafka_conn.ensure_topic_exists(appid_topic)
            self.kafka_conn.ensure_topic_exists(firehose_topic)
            # dont want logger in outbound kafka message
            dump = json.dumps(master)
            self.producer.send_messages(appid_topic, dump)
            self.producer.send_messages(firehose_topic, dump)

            return True
        except Exception as ex:
            print traceback.format_exc()
            pass

        return False

    def _build_appid_info(self, master, dict):
        '''
        Builds the appid info object

        @param master: the master dict
        @param dict: the dict object received
        @return: the appid info object
        '''
        master['total_crawlids'] = 0
        master['total_pending'] = 0
        master['total_domains'] = 0
        master['crawlids'] = {}
        master['appid'] = dict['appid']

        match_string = '{sid}:queue'.format(sid=dict['spiderid'])

        sortedDict = self._get_bin(match_string)

        # now iterate through binned dict
        for score in sortedDict:
            for item in sortedDict[score]:
                if 'meta' in item:
                    item = item['meta']
                if item['appid'] == dict['appid']:
                    crawlid = item['crawlid']

                    # add new crawlid to master dict
                    if crawlid not in master['crawlids']:
                        master['crawlids'][crawlid] = {}
                        master['crawlids'][crawlid]['total'] = 0
                        master['crawlids'][crawlid]['high_priority'] = -9999
                        master['crawlids'][crawlid]['low_priority'] = 9999

                        timeout_key = 'timeout:{sid}:{aid}:{cid}'.format(
                                    sid=dict['spiderid'],
                                    aid=dict['appid'],
                                    cid=crawlid)
                        if self.redis_conn.exists(timeout_key):
                            master['crawlids'][crawlid]['expires'] = self.redis_conn.get(timeout_key)

                        master['total_crawlids'] = master['total_crawlids'] + 1

                    if item['priority'] > master['crawlids'][crawlid]['high_priority']:
                        master['crawlids'][crawlid]['high_priority'] = item['priority']

                    if item['priority'] < master['crawlids'][crawlid]['low_priority']:
                        master['crawlids'][crawlid]['low_priority'] = item['priority']

                    master['crawlids'][crawlid]['total'] = master['crawlids'][crawlid]['total'] + 1
                    master['total_pending'] = master['total_pending'] + 1

        return master

    def _get_bin(self, key):
        '''
        Returns a binned dictionary based on redis zscore

        @return: The sorted dict
        '''
        # keys based on score
        sortedDict = {}
        # this doesnt return them in order, need to bin first
        for item in self.redis_conn.zscan_iter(key):
            my_item = pickle.loads(item[0])
            # score is negated in redis
            my_score = -item[1]

            if my_score not in sortedDict:
                sortedDict[my_score] = []

            sortedDict[my_score].append(my_item)

        return sortedDict

    def _build_crawlid_info(self,master, dict):
        '''
        Builds the crawlid info object

        @param master: the master dict
        @param dict: the dict object received
        @return: the crawlid info object
        '''
        master['total_pending'] = 0
        master['appid'] = dict['appid']
        master['crawlid'] = dict['crawlid']

        timeout_key = 'timeout:{sid}:{aid}:{cid}'.format(sid=dict['spiderid'],
                                                        aid=dict['appid'],
                                                        cid=dict['crawlid'])
        if self.redis_conn.exists(timeout_key):
            master['expires'] = self.redis_conn.get(timeout_key)

        # get all domain queues
        match_string = '{sid}:queue'.format(sid=dict['spiderid'])
        sortedDict = self._get_bin(match_string)

        # now iterate through binned dict
        for score in sortedDict:
            for item in sortedDict[score]:
                if 'meta' in item:
                    item = item['meta']
                if item['appid'] == dict['appid'] and \
                                item['crawlid'] == dict['crawlid']:

                    if 'high_priority' not in master:
                        master['high_priority'] = -99999

                    if 'low_priority' not in master:
                        master['low_priority'] = 99999

                    if item['priority'] > master['high_priority']:
                        master['high_priority'] = item['priority']

                    if item['priority'] < master['low_priority']:
                        master['low_priority'] = item['priority']

                    master['total_pending'] = master['total_pending'] + 1

        return master

    def _do_expire(self):
        '''
        Processes expire requests
        Very similar to _do_stop()
        '''
        for key in self.redis_conn.scan_iter(match="timeout:*:*:*"):
            timeout = float(self.redis_conn.get(key))
            curr_time = time.time()
            if curr_time > timeout:
                # break down key
                elements = key.split(":")
                spiderid = elements[1]
                appid = elements[2]
                crawlid = elements[3]

                # add crawl to blacklist so it doesnt propagate
                redis_key = spiderid + ":blacklist"
                value = '{appid}||{crawlid}'.format(appid=appid,
                                                crawlid=crawlid)
                # add this to the blacklist set
                self.redis_conn.sadd(redis_key, value)

                # everything stored in the queue is now expired
                result = self._purge_crawl(spiderid, appid, crawlid)

                # item to send to kafka
                extras = {}
                extras['action'] = "expire"
                extras['spiderid'] = spiderid
                extras['appid'] = appid
                extras['crawlid'] = crawlid
                extras['total_expired'] = result

                self.redis_conn.delete(key)

                if self._send_to_kafka(extras):
                    #print 'Sent expired ack to kafka'
                    pass
                else:
                    print 'Failed to send expired ack to kafka'

    def _do_stop(self):
        '''
        Processes stop action requests
        '''
        for key in self.redis_conn.scan_iter(match="stop:*:*:*"):
            # break down key
            elements = key.split(":")
            spiderid = elements[1]
            appid = elements[2]
            crawlid = elements[3]
            uuid = self.redis_conn.get(key)

            redis_key = spiderid + ":blacklist"
            value = '{appid}||{crawlid}'.format(appid=appid,
                                                crawlid=crawlid)

            # add this to the blacklist set
            self.redis_conn.sadd(redis_key, value)

            # purge crawlid from current set
            result = self._purge_crawl(spiderid, appid, crawlid)

            # item to send to kafka
            extras = {}
            extras['action'] = "stop"
            extras['spiderid'] = spiderid
            extras['appid'] = appid
            extras['crawlid'] = crawlid
            extras['total_purged'] = result

            self.redis_conn.delete(key)

            if self._send_to_kafka(extras):
                # delete timeout for crawl (if needed) since stopped
                timeout_key = 'timeout:{sid}:{aid}:{cid}'.format(
                                        sid=spiderid,
                                        aid=appid,
                                        cid=crawlid)
                self.redis_conn.delete(timeout_key)
                #print 'Sent stop ack to kafka'
            else:
                print 'Failed to send stop ack to kafka'

    def _purge_crawl(self, spiderid, appid, crawlid):
        '''
        Wrapper for purging the crawlid from the queues

        @param spiderid: the spider id
        @param appid: the app id
        @param crawlid: the crawl id
        @return: The number of requests purged
        '''
        # purge three times to try to make sure everything is cleaned
        total = self._mini_purge(spiderid, appid, crawlid)
        total = total + self._mini_purge(spiderid, appid, crawlid)
        total = total + self._mini_purge(spiderid, appid, crawlid)

        return total

    def _mini_purge(self, spiderid, appid, crawlid):
        '''
        Actually purges the crawlid from the queue

        @param spiderid: the spider id
        @param appid: the app id
        @param crawlid: the crawl id
        @return: The number of requests purged
        '''
        total_purged = 0

        match_string = '{sid}:queue'.format(sid=spiderid)
        # using scan for speed vs keys
        for item in self.redis_conn.zscan_iter(match_string):
            item_key = item[0]
            item = pickle.loads(item_key)
            if 'meta' in item:
                item = item['meta']

            if item['appid'] == appid and item['crawlid'] == crawlid:
                self.redis_conn.zrem(match_string, item_key)
                total_purged = total_purged + 1

        return total_purged

def main():
    redis_monitor = RedisMonitor()
    redis_monitor.run()

if __name__ == "__main__":
    sys.exit(main())


text:
'use strict';

const _ = require('lodash');
const service = require('../patientService');
const serviceTestUtils = require('../tests/serviceTestUtils');

describe('lookup patient died on date specs', () => {
    let context;
    beforeAll(() => {
        context = serviceTestUtils.beforeAllScript(service).context;
    });

    it('Should return empty array for the active patient', (done) => {
        service.getPatientDiedOn('urn:vista:999:2:19', context, (err, res) => {
            if (err) {
                return serviceTestUtils.handleError(err);
            }
            expect(res.dateOfDeath).toBeUndefined();
            done();
        });
    });

    it('Should return died date for an expired patient', (done) => { // no such test data yet
        service.getPatientDiedOn('urn:vista:999:2:20', context, (err, res) => {
            if (err) {
                return serviceTestUtils.handleError(err);
            }
            if (res.dateOfDeath) {
                expect(res.dateOfDeath).toEqual(jasmine.any(String));
            } else {
                expect(res.dateOfDeath).toBeUndefined();
            }
            done();
        });
    });

    it('Should return empty array for a non existent patient', (done) => {
        service.getPatientDiedOn('2-499', context, (err, res) => {
            if (err) {
                return serviceTestUtils.handleError(err);
            }
            expect(_.isEmpty(res)).toBeTruthy();
            done();
        });
    });
});


text:
Imports MySql.Data.MySqlClient
Public Class formViewInventory
    Dim con As New connection 'Mysql Connection used through the Form
    Dim tableFont, titlefont, headfont As Font 'Used in Printing the Summary

    'Handles Enter Pressed on Item ID tb
    'If not Blank, fills datagrid up only for That Item
    'Else for all items
    Private Sub ITEM_ID_keydown(sender As Object, e As KeyEventArgs) Handles ITEM_ID.KeyDown
        If e.KeyCode = Keys.Enter Then
            If ITEM_ID.Text <> "" Then
                Try
                    con.connect()
                    Dim query As String = "SELECT ITEM.NAME, MESS_STORE.ITEM_ID, MESS_STORE.QTY FROM(ITEM, MESS_STORE) WHERE ITEM.ITEM_ID = MESS_STORE.ITEM_ID and mess_store.Item_id = '" + ITEM_ID.Text.ToString + "'"
                    Dim comm As New MySqlCommand(query, con.conn)
                    Dim dr As MySqlDataReader
                    dr = comm.ExecuteReader
                    Dim dt1 As New DataTable
                    dt1.Load(dr)
                    DataGridView1.DataSource = dt1
                    dr.Close()
                    ITEM_ID.Text = ""
                    ITEM_ID.Focus()
                Catch ex As Exception
                    MsgBox("Error Occured !! Please Try Again")
                    MsgBox(ex.Message.ToString)
                    ITEM_ID.Focus()
                    ITEM_ID.Text = ""
                End Try
            Else
                fill()
            End If
        End If
    End Sub

    'Fills the DataGrid with all the Items and its Current Quantity
    Private Sub fill()
        Try
            con.connect()
            Dim query As String = "SELECT ITEM.NAME, MESS_STORE.ITEM_ID, MESS_STORE.QTY FROM(ITEM, MESS_STORE) WHERE ITEM.ITEM_ID=MESS_STORE.ITEM_ID"
            Dim comm As New MySqlCommand(query, con.conn)
            Dim dr As MySqlDataReader
            dr = comm.ExecuteReader
            Dim dt As New DataTable
            dt.Load(dr)
            DataGridView1.DataSource = dt
            ITEM_ID.Focus()
            For n As Integer = 0 To 2
                Dim column As DataGridViewColumn = DataGridView1.Columns(n)
                column.Width = 111
            Next
        Catch ex As Exception
            MsgBox("Error Occured ! Please Try Again!")
            MsgBox(ex.Message.ToString)
            Controls.Clear()
            InitializeComponent()
            ITEM_ID.Focus()
        End Try
    End Sub

    'Handles various Keypresses on the Form
    Private Sub formViewInventory_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Escape Then
            Me.Close()
        ElseIf e.KeyCode = Keys.F12 Then
            fill()
        End If
    End Sub

    'On Form Load
    Private Sub formViewInventory_Load(sender As Object, e As EventArgs) Handles Me.Load
        fill()
        ITEM_ID.Focus()
        Me.KeyPreview = True
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        PrintDocument1.Print()
    End Sub

    Private Sub print_bill(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Try
            headfont = New Font("Courier New", 12, FontStyle.Bold)
            tableFont = New Font("Courier New", 10, FontStyle.Bold)
            Dim Datefont = New Font("Courier New", 7.5, FontStyle.Bold)
            e.Graphics.DrawString("INVENTORY STORE SUMMARY", headfont, Brushes.Black, 40, 0)
            e.Graphics.DrawString("************************", headfont, Brushes.Black, 40, 15)
            e.Graphics.DrawString(My.Settings.messName.ToString, tableFont, Brushes.Black, 55, 35)
            e.Graphics.DrawString(DateTime.Now.ToString, headfont, Brushes.Black, 55, 50)

            e.Graphics.DrawString("--------------------------------------", tableFont, Brushes.Black, -20, 65)
            e.Graphics.DrawString("--------------------------------------", tableFont, Brushes.Black, -20, 70)

            e.Graphics.DrawString("Item ID", tableFont, Brushes.Black, 0, 90)
            e.Graphics.DrawString("Item Name", tableFont, Brushes.Black, 80, 90)
            e.Graphics.DrawString("Qty", tableFont, Brushes.Black, 230, 90)

            For n As Integer = 0 To DataGridView1.Rows.Count - 1

                e.Graphics.DrawString(CStr(DataGridView1.Rows(n).Cells(1).Value), tableFont, Brushes.Black, 10, 110 + 20 * n)
                Dim item_name As String
                If CStr(DataGridView1.Rows(n).Cells(0).Value).Length > 12 Then
                    item_name = CStr(DataGridView1.Rows(n).Cells(0).Value).Substring(0, 3) + "..." + CStr(DataGridView1.Rows(n).Cells(0).Value).Substring(CStr(DataGridView1.Rows(n).Cells(0).Value).Length - 6, 6)
                Else
                    item_name = DataGridView1.Rows(n).Cells(0).Value
                End If
                e.Graphics.DrawString(item_name, tableFont, Brushes.Black, 80, 110 + 20 * n)
                e.Graphics.DrawString(CStr(DataGridView1.Rows(n).Cells(2).Value), tableFont, Brushes.Black, 240, 110 + 20 * n)
                'e.Graphics.DrawString(CStr(DataGridView1.Rows(n).Cells(4).Value), tableFont, Brushes.Black, 240, 110 + 20 * n)
            Next

        Catch ex As Exception
            MsgBox("Error Occured! Please Try Again!")
            MsgBox(ex.Message.ToString)

        End Try
    End Sub

End Class


text:
$(".reveal").mousedown(function() {
    $(".pwd").replaceWith($('.pwd').clone().attr('type', 'text'));
})
.mouseup(function() {
	$(".pwd").replaceWith($('.pwd').clone().attr('type', 'password'));
})
.mouseout(function() {
	$(".pwd").replaceWith($('.pwd').clone().attr('type', 'password'));
});


text:
using FBCore.Common.References;
using System;

namespace ImagePipeline.Memory
{
    /// <summary>
    /// Provides custom implementation for <see cref="IResourceReleaser{T}"/>.
    /// </summary>
    public class ResourceReleaserImpl<T> : IResourceReleaser<T>
    {
        private readonly Action<T> _func;

        /// <summary>
        /// Instantiates the <see cref="ResourceReleaserImpl{T}"/>.
        /// </summary>
        /// <param name="func">Delegate function.</param>
        public ResourceReleaserImpl(Action<T> func)
        {
            _func = func;
        }

        /// <summary>
        /// Invokes the Release method of the pool.
        /// </summary>
        /// <param name="value">T.</param>
        public void Release(T value)
        {
            _func(value);
        }
    }
}


text:
define([
        'constants/AGGREGATED_LIST_TYPE'
    ],

    function(AGGREGATED_LIST_TYPE) {

        function AggregatedData(type, maxItems) {

            this.id = _.guid();
            this.type = type || AGGREGATED_LIST_TYPE.FIFO;
            this.maxItems = maxItems || 0;

            this._freezed = false;
            this._queuedData = [];
            this._data = [];
        }

        AggregatedData.prototype.each = function(callback) {
            var i, len;

            for(i = 0, len = this._data.length; i < len; i++) {
                callback(this._data[i], i, false);
            }

            for(i = 0, len = this._queuedData.length; i < len; i++) {
                callback(this._queuedData[i], i, true);
            }
        };

        AggregatedData.prototype.add = function(item) {

            if(this._freezed) {

                this._queuedData.push(item);

            } else {

                this._data.push(item);

                if(this.maxItems > 0 && this.count() > this.maxItems) {
                    return this._automatedRemove();
                }

            }

        };

        AggregatedData.prototype.remove = function(index) {

            this._data.splice(index, 1);

        };

        AggregatedData.prototype.get = function(index) {

            return this._data[index];

        };

        AggregatedData.prototype.getAll = function() {

            return this._data;

        };

        AggregatedData.prototype.clear = function() {

            this._data.length = 0;

        };

        AggregatedData.prototype.toggleFreeze = function() {

            if(this._freezed) {

                this.unfreeze();

            } else {

                this.freeze();

            }

        };

        AggregatedData.prototype.freeze = function() {
            if(!this._freezed) {

                this._freezed = true;

            }
        };

        AggregatedData.prototype.unfreeze = function() {
            if(this._freezed) {

                this._freezed = false;

                _.pushAll(this._data, this._queuedData);

                this._queuedData.length = 0;
            }
        };

        AggregatedData.prototype.count = function() {

            return this._data.length;

        };

        AggregatedData.prototype.getLast = function() {
            return this.get(this.count() - 1);
        };

        AggregatedData.prototype._automatedRemove = function() {
            switch(this.type) {
                case AGGREGATED_LIST_TYPE.FIFO:
                    this.remove(0);
                    break;
                case AGGREGATED_LIST_TYPE.LIFO:
                    this.remove(this.count() - 1);
                    break;
            }
        };

        return AggregatedData;

    });


text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <title>A Scatter chart with the crosshairs snap option</title>

    <meta name="robots" content="noindex,nofollow" />
    <meta name="description" content="A Scatter chart which is using crosshairs and the snap option" />

A Scatter chart demonstrating  the crosshairs snap option

        This Scatter chart demonstrates how you can extract the Scatter charts dataset and index from the variables set on the canvas tag
        by RGraph.

    <canvas id="cvs" width="600" height="400">[No canvas support]</canvas>

    Dataset:

    <input id="dataset" type="text" />

    Point:

    <input id="point" type="text" />

    This goes in the documents header (or you could place it just above the jQuery ready event code):

<script src="/mps/libs/jquery-1.11.3/jquery-1.11.3.js"></script>
<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.dynamic.js"></script>
<script src="RGraph.scatter.js"></script>

    Put this where you want the chart to show up:

<canvas id="cvs" width="600" height="400">
    [No canvas support]
</canvas>

    This is the code that generates the chart. Because it's using the jQuery ready event you can put this at the
    bottom of the document:

<script>
    $(document).ready(function ()
    {
        var scatter = new RGraph.Scatter({
            id:'cvs',
            data: [
                [[0,0,'red'],[5,5,'red'],[10,10,'red'],[15,15,'red'],[20,20,'red'],[25,25,'red'],[30,30,'red'],[35,35,'red'],[40,40,'red'],[45,45,'red'],[50,50,'red']],
                [[0,0,'green'],[5,1,'green'],[10,2,'green'],[15,3,'green'],[20,4,'green'],[25,5,'green'],[30,6,'green'],[35,7,'green'],[40,8,'green'],[45,9,'green'],[50,10,'green']]
            ],
            options: {
                xmax: 100,
                crosshairs: true,
                crosshairsSnap: true,
                gutterLeft: 50,
                line: true,
                lineColors: ['red','green'],
                labels: ['Q1','Q2','Q3','Q4']
            }
        }).draw();

        scatter.oncrosshairs = function (obj)
        {
            document.getElementById("dataset").value =  obj.canvas.__crosshairs_snap_dataset__;
            document.getElementById("point").value =  obj.canvas.__crosshairs_snap_point__;
        }
    });
</script>

        « Back


text:
<!DOCTYPE html>

  	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  	<title>Introduction to Puppet — Documentation — Puppet Labs</title>
  	<link rel="alternate" type="application/atom+xml" title="Puppet Labs Documentation Updates" href="https://github.com/puppetlabs/puppet-docs/commits/master.atom" />
    <link rel="alternate" type="application/atom+xml" title="Puppet Labs Blog Feed" href="http://puppetlabs.com/feed/atom/" />
    <link rel="index" title="Puppet Labs Documentation" href="http://docs.puppetlabs.com" />
    <link rel="icon" href="./../favicon.ico" />

  <meta name="description" content="Introduction to PuppetWhy PuppetAs system administrators acquire more and more systems to manage, automationof mundane tasks is increasingly import..." />

    <meta name="keywords" content="Puppet, puppet labs, reductive labs, open source, system administrator, ruby, data center, automation, support" />

    <link rel="canonical" href="http://docs.puppetlabs.com/guides/introduction.html" />

    <link rel="stylesheet" type="text/css" href="./../files/stylesheets/style_legacy.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="./../files/stylesheets/syntax.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="./../files/stylesheets/adbanner.css" media="screen" />

Puppet Labs

        Skip navigation

              Products

                   What is Puppet?

                   Puppet Enterprise

                   What's New in 2.5

                   Puppet Open Source

                   Enterprise vs. Open Source

                  Puppet Forge

                  Components & Requirements

                  FAQ

                  How to Buy

              Solutions

Configuration Management

Virtualization Management

Cloud Management

IT Compliance

DevOps

OS X Desktops

              Services

Overview

Customer Support

Support Plans

On-Site Education

Professional Services

Events & Workshops

Partners

              Resources

Overview

Documentation

Downloads

Puppet Forge

White Papers

Wiki

Upcoming Webinars

Newsletter

Tech Notes

Webinars

              Customers

                  Companies

                  Case Studies

                  Product Testimonials

                  Service Testimonials

              Community

                  Overview

                  Blog

                  Puppet Camp

                  Puppet User Groups & DevOps Groups

                  Presentations

                  Videos

              Company

Overview

News

Press Releases

Media Kit

Careers

Management

Board and Advisors

Investors

Contact Us

Awards

Security

Documentation

Support

Bug Tracker

Contact Us

Download

			<form action="http://www.google.com/cse" id="cse-search-box">

				<input type="hidden" name="cx" value="017668764424496204839:ubligvgbenm" />
				<input type="hidden" name="ie" value="UTF-8" />
				<input type="text" name="q" class="gsc-input" size="31" />
				<input type="submit" name="sa" class="searchbtn" value="Search" />

			</form>

Docs: Introduction to Puppet

Docs Home

                Quick Nav

Puppet Documentation

Puppet 3 Reference Manual

Puppet 2.7 Reference Manual

Puppet Enterprise User's Guide

Learning Puppet

Resource Types

Functions

Configuration

Developer

Glossary of Puppet Terms

Older References

Facter

Core Facts Reference

PuppetDB

PuppetDB 1 Manual

MCollective

Index

References

Writing Plugins

Release Notes

Contribute

Introduction to Puppet

Why Puppet

As system administrators acquire more and more systems to manage, automation
of mundane tasks is increasingly important.  Rather than develop in-house
scripts, it is desirable to share a system that everyone can use, and invest
in tools that can be used regardless of one’s employer.  Certainly doing
things manually doesn’t scale.

Puppet has been developed to help the sysadmin community move to
building and sharing mature tools that avoid the duplication of
everyone solving the same problem. It does so in two ways:

It provides a powerful framework to simplify the majority of
the technical tasks that sysadmins need to perform

The sysadmin work is written as code in Puppet’s custom
language which is shareable just like any other code.

This means that your work as a sysadmin can get done much faster,
because you can have Puppet handle most or all of the details, and
you can download code from other sysadmins to help you get done
even faster. The majority of Puppet implementations use at least
one or two modules developed by someone else, and there are already
hundreds of modules developed and shared by the community.

Learning Recommendations

We’re glad you want to learn Puppet.  You’re free to browse around the documentation as you like, though we generally recommend trying out Puppet locally first (without the
daemon and client/server setup), so you
can understand the basic concepts.  From there, move on to
centrally managed server infrastructure.   Ralsh
is also a great way to get your feet wet exploring the Puppet model,
after you have read some of the basic information — you can quickly see how
the declarative model works for simple things like users, services, and file permissions.

Once you’ve learned the basics, make sure you understand classes and modules,
then move on to the advanced sections and read more about the features
that are useful to you.  Learning all at once is definitely not required.
If you find something confusing, file a ticket or email us at faq@puppetlabs.com to let us know.

System Components

Puppet is typically (but not always) used in a client/server formation, with all
of your clients talking to one or more central servers. Each client
contacts the server periodically (every half hour, by default),
downloads the latest configuration, and makes sure it is in sync with
that configuration.  Once done, the client can send a report back to the
server indicating if anything needed to change. This diagram shows
the data flow in a regular Puppet implementation:

Puppet’s functionality is built as a stack of separate layers, each
responsible for a fixed aspect of the system, with tight controls
on how information passes between layers:

See also Configuring Puppet.  For more information about components (puppetmasterd, puppetd, puppet, and so on), see the Tools section.

Features of the System

Idempotency

One big difference between Puppet and most other tools is
that Puppet configurations are idempotent, meaning they can safely
be run multiple times. Once you develop your configuration, your
machines will apply the configuration often — by default, every 30
minutes — and Puppet will only make any changes to the system if
the system state does not match the configured state.

If you tell the system to operate in no-op (“aka
dry-run”), mode, using the --noop argument to one of the Puppet
tools, puppet will guarantee that no work happens on
your system. Similarly, if any changes do happen when running
without that flag, puppet will ensure those changes are logged.

Because of this, you can use Puppet to manage a machine throughout its
lifecycle — from initial installation, to ongoing upgrades, and
finally to end-of-life, where you move services elsewhere. Unlike
system install tools like Sun’s Jumpstart or Red Hat’s Kickstart,
Puppet configurations can keep machines up to date for years,
rather than just building them correctly only the first time
and then neccessitating a rebuild.  Puppet users usually do just enough with
their host install tools to boostrap Puppet, then they use
Puppet to do everything else.

Cross Platform

Puppet’s Resource Abstraction Layer (RAL) allows you to focus on the parts of the system
you care about, ignoring implementation details like command
names, arguments, and file formats — your tools should treat all
users the same, whether the user is stored in NetInfo or
/etc/passwd.  We call these system entities
resources.

Ralsh, listed in the Tools section is a fun way to
try out the RAL before you get too deep into Puppet language.

Model & Graph Based

Resource Types

The concept of each resource (like service, file, user, group, etc) is modelled as a “type”.
Puppet decouples the definition from how
that implementation is fulfilled on a particular operating system,
for instance, a Linux user versus an OS X user can be talked about in the same way
but are implemented differently inside of Puppet.

See the types reference for a list of managed types
and information about how to use them.

Providers

Providers are the fulfillment of a resource.  For instance, for
the package type, both ‘yum’ and ‘apt’ are valid ways to manage
packages.  Sometimes more than one provider will be available
on a particular platform, though each platform always has
a default provider.  There are currently 17 providers
for the package type.

Modifying the System

Puppet resource providers are what are responsible for directly managing the
bits on disk. You do not directly modify a system from Puppet language
— you use the language to specify a resource, which then
modifies the system.   This way puppet language behaves exactly the same
way in a centrally managed server setup as it does locally without a server.
Rather than tacking a couple of lines onto
the end of your fstab, you use the mount type to create a new
resource that knows how to modify the fstab, or NetInfo, or
wherever mount information is kept.

Resources have attributes called ‘properties’ which change
the way a resource is managed.  For instance, users have an
attribute that specifies whether the home directory should
be created.

‘Metaparams’ are another special kind of attribute, those exist on
all resources.  This include things like
the log level for the resource, whether the resource should be in
noop mode so it never modifies the system, and the relationships
between resources.

Resource Relationships

Puppet has a system of modelling relationships between resources
— what resources should be evaluated before or after one another.
They also are used to determine whether a resource needs to respond to changes in
another resource (such as if a service needs to restart if the configuration
file for the service has changed).  This ordering reduces unneccessary commands,
such as avoiding restarting a service
if the configuration has not changed.

Because the system is graph based, it’s actually possible to generate a diagram
(from Puppet) of the relationships between all of your resources.

Learning The Language

Seeing a few examples in action will greatly help in learning the system.

For information about the Puppet language, see the latest
Puppet language reference

↑ Back to top

Contents

Why Puppet

Learning Recommendations

System Components

Features of the System

Idempotency

Cross Platform

Model & Graph Based

Learning The Language

Download the Docs

Download Puppet Enterprise

Puppet Labs is Hiring

Engineers, developers & consultants

Newsletter

Stay up to date on all things puppet

				<form class="lpeRegForm formNotEmpty" method="post" enctype="application/x-www-form-urlencoded" action="http://info.puppetlabs.com/index.php/leadCapture/save" id="mktForm_1013" name="mktForm_1013">

				Email Address:<input class="mktFormText mktFormEmail" name="Email" id="Email" type="text" value="" maxlength="255" />

				<input id="mktFrmSubmit" type="submit" class="btn" style="width: auto; overflow: visible; padding-left: .25em; padding-right: .25em;" value="Subscribe" name="submitButton" onclick="formSubmit(document.getElementById("mktForm_1013")); return false;" />

				<input style="display: none;" id="mktFrmReset" type="reset" value="Clear" name="resetButton" onclick="formReset(document.getElementById("mktForm_1013")); return false;" />

				<input type="text" name="_marketo_comments" value="" />
				<input type="hidden" name="lpId" value="-1" />
				<input type="hidden" name="subId" value="100" />

				<input type="hidden" name="kw" value="" />
				<input type="hidden" name="cr" value="" />

				<input type="hidden" name="searchstr" value="" />
				<input type="hidden" name="lpurl" value="http://info.puppetlabs.com/testsubscription.html?cr={creative}&kw={keyword}" />
				<input type="hidden" name="formid" value="1013" />
				<input type="hidden" name="returnURL" value="http://www.puppetlabs.com/misc/subscription-thank-you/" />
				<input type="hidden" name="retURL" value="http://www.puppetlabs.com/misc/subscription-thank-you/" />
				<input type="hidden" name="_mkt_disp" value="return" />
				<input type="hidden" name="_mkt_trk" value="" />

				</form>

Try Puppet Enterprise FREE

Get Involved

Chat with us on IRC

Join the Puppet Developer List

Join the Puppet User List

Join the Puppet Users LinkedIn group

Follow us…

Get the book!

James Turnbull and Jeff McCune's book Pro Puppet is a comprehensive and up-to-date look at Puppet and MCollective.

        © 2011 Puppet Labs

         info@puppetlabs.com

           926 NW 13th Avenue #210
           /
           Portland,
           OR
           97209

         1-877-575-9775


text:
<!DOCTYPE html>
<!--
    @license
    Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
    This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
    The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
    The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
    Code distributed by Google as part of the polymer project is also
    subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html>
  <head>
    <title>HTML Imports Dynamic</title>
    <script src="../../node_modules/@webcomponents/html-imports/html-imports.min.js"></script>
    <script>
      WCT = {
        waitFor: function (callback) {
          HTMLImports.whenReady(callback);
        },
      };
    </script>
    <script src="../../node_modules/wct-browser-legacy/browser.js"></script>
  </head>

  <body>
    <script>
      test('dynamic imports', function (done) {
        var loadSpy = sinon.stub();
        var whenReadySpy = sinon.stub();

        var div = document.createElement('div');
        div.innerHTML =
          '<link rel="import" href="imports/load-1.html">' +
          '<link rel="import" href="imports/load-2.html">';
        for (var i = 0, l = div.children.length; i < l; i++) {
          div.children[i].addEventListener('load', loadSpy);
        }
        document.head.appendChild(div);

        HTMLImports.whenReady(whenReadySpy);
        assert.isFalse(
          whenReadySpy.called,
          'captured elements dynamically added'
        );

        HTMLImports.whenReady(function () {
          assert.equal(whenReadySpy.callCount, 1, 'called previous whenReady');
          assert.equal(loadSpy.callCount, 2, 'load count ok');
          done();
        });
      });

      test('concurrent loads', function (done) {
        var loadSpy = sinon.stub();
        var errorSpy = sinon.stub();

        var link = document.createElement('link');
        link.setAttribute('rel', 'import');
        link.setAttribute('href', 'imports/load-a.html');
        link.addEventListener('load', loadSpy);
        link.addEventListener('error', errorSpy);

        // Add also a <style> to have multiple mutations.
        // HTMLImports should wait for link to load.
        document.head.appendChild(document.createElement('style'));
        document.head.appendChild(link);

        HTMLImports.whenReady(function () {
          assert.equal(errorSpy.callCount, 0, 'error not called');
          assert.equal(loadSpy.callCount, 1, 'load ok');
          assert.isOk(link.import, 'import ok');
          done();
        });
      });
    </script>
  </body>
</html>


text:
package com.flj.latte.ec.main.sort.list;

import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;

import com.flj.latte.ec.R;
import com.flj.latte.ec.main.sort.SortDelegate;
import com.flj.latte.ec.main.sort.content.ContentDelegate;
import com.imooc.core.delegates.LatteDelegate;
import com.latte.ui.recycler.ItemType;
import com.latte.ui.recycler.MultipleFields;
import com.latte.ui.recycler.MultipleItemEntity;
import com.latte.ui.recycler.MultipleRecyclerAdapter;
import com.latte.ui.recycler.MultipleViewHolder;

import java.util.List;

import me.yokeyword.fragmentation.SupportHelper;

/**
 * 商品类别(左边)适配器
 * Created by Administrator on 2017/9/19 0019.
 */

public class SortRecyclerAdapter extends MultipleRecyclerAdapter {

    private final SortDelegate DELEGATE;
    private int mPrePosition =0;

    public SortRecyclerAdapter(List<MultipleItemEntity> data,SortDelegate delegate) {
        super(data);
        this.DELEGATE = delegate;

        //添加垂直菜单布局
        addItemType(ItemType.VERTICAL_MENU_LIST, R.layout.item_vertical_menu_list);

    }

    @Override
    protected void convert(final MultipleViewHolder holder, final MultipleItemEntity entity) {
        super.convert(holder, entity);

        switch (holder.getItemViewType()){
            case ItemType.VERTICAL_MENU_LIST:

                final String text = entity.getField(MultipleFields.TEXT);
                final boolean isClicked = entity.getField(MultipleFields.TAG);
                final AppCompatTextView name = holder.getView(R.id.tv_vertical_item_name);
                final View line = holder.getView(R.id.view_line);
                final View itemView = holder.itemView;

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        final int currentPosition = holder.getAdapterPosition();
                        if (mPrePosition !=currentPosition){ //如果不是选择第一个分类
                            //还原上一个
                            getData().get(mPrePosition).setField(MultipleFields.TAG,false); //设置第一个分类没有被选中
                            notifyItemChanged(mPrePosition);

                            //更新选中的item
                            entity.setField(MultipleFields.TAG,true);
                            notifyItemChanged(currentPosition);
                            mPrePosition = currentPosition;

                            final int contentId = getData().get(currentPosition).getField(MultipleFields.ID);//获取到选中的分类商品id

                            //显示分类对应id的Fragment内容
                            showContent(contentId);

                        }

                    }
                });

                if (!isClicked){ //没有选中的商品分类
                    line.setVisibility(View.INVISIBLE);
                    name.setTextColor(ContextCompat.getColor(mContext,R.color.we_chat_black));
                    itemView.setBackgroundColor(ContextCompat.getColor(mContext,R.color.item_background));

                }else { //选中的商品分类
                    line.setVisibility(View.VISIBLE);
                    name.setTextColor(ContextCompat.getColor(mContext,R.color.app_main));
                    line.setBackgroundColor(ContextCompat.getColor(mContext,R.color.app_main));
                    itemView.setBackgroundColor(Color.WHITE);

                }

                holder.setText(R.id.tv_vertical_item_name,text);
                break;
            default:
                break;
        }

    }

    private void showContent(int contentId){

        final ContentDelegate delegate = ContentDelegate.newInstance(contentId); //分类对应的商品Fragment(右边)
        switchContent(delegate);

    }

    //显示分类对应的Fragment内容
    private void switchContent(ContentDelegate delegate){

        final LatteDelegate contentDelegate =
                SupportHelper.findFragment(DELEGATE.getChildFragmentManager(),ContentDelegate.class);

        if (contentDelegate !=null){

            contentDelegate.getSupportDelegate().replaceFragment(delegate,false);
        }

    }

}


text:
<meta charset="utf-8">
(#) Unsupported Chrome OS Hardware Feature

!!! ERROR: Unsupported Chrome OS Hardware Feature
   This is an error.

Id
:   `UnsupportedChromeOsHardware`
Summary
:   Unsupported Chrome OS Hardware Feature
Note
:   **This issue is disabled by default**; use `--enable UnsupportedChromeOsHardware`
Severity
:   Error
Category
:   Correctness: Chrome OS
Platform
:   Android
Vendor
:   Android Open Source Project
Feedback
:   https://issuetracker.google.com/issues/new?component=192708
Affects
:   Manifest files
Editing
:   This check runs on the fly in the IDE editor
See
:   https://developer.android.com/topic/arc/manifest.html#incompat-entries
Implementation
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/ChromeOsDetector.java)
Tests
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/ChromeOsDetectorTest.java)
Copyright Year
:   2016

The `<uses-feature>` element should not require this unsupported Chrome
OS hardware feature. Any uses-feature not explicitly marked with
`required="false"` is necessary on the device to be installed on. Ensure
that any features that might prevent it from being installed on a Chrome
OS device are reviewed and marked as not required in the manifest.

!!! Tip
   This lint check has an associated quickfix available in the IDE.

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
AndroidManifest.xml:5:Error: Expecting android:required="false" for this
hardware feature that may not be supported by all Chrome OS devices
[UnsupportedChromeOsHardware]

    android:name="android.hardware.touchscreen" android:required="true"/>
                                                -----------------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the source file referenced above:

`AndroidManifest.xml`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~xml linenumbers
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-feature
        android:name="android.hardware.touchscreen" android:required="true"/>

</manifest>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/ChromeOsDetectorTest.java)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `ChromeOsDetector.testInvalidUnsupportedHardware`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=192708.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Adding the suppression attribute
  `tools:ignore="UnsupportedChromeOsHardware"` on the problematic XML
  element (or one of its enclosing elements). You may also need to add
  the following namespace declaration on the root element in the XML
  file if it's not already there:
  `xmlns:tools="http://schemas.android.com/tools"`.

  ```xml
  <?xml version="1.0" encoding="UTF-8"?>
  <manifest xmlns:tools="http://schemas.android.com/tools">
      ...
      <uses-feature tools:ignore="UnsupportedChromeOsHardware" .../>
    ...
  </manifest>
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  <?xml version="1.0" encoding="UTF-8"?>
  <lint>
      <issue id="UnsupportedChromeOsHardware" severity="ignore" />
  </lint>
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'UnsupportedChromeOsHardware'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore UnsupportedChromeOsHardware ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>


text:
app.directive('vpOpen', [function () {
    return {
        link: function postLink(scope, element, attrs) {
            element.on('click', function () {
                var className = 'selected';
                $('.' + className).removeClass(className);
                element.addClass(className);
            });
        }
    };
}]);


text:
exports.migration = {
  run: function(fn) {
    var self = this
    this.queue.push(function() {
      return fn.call(self.store)
    })

    return this
  }
}


text:
package spki

import (
	"github.com/eadmund/sexprs"
)

type AuthCert struct {
	Expr sexprs.Sexp // the originally-parsed S-expression, for hashing
	Issuer Name
	Subject Subject
	Delegate bool
	Valid *Valid
	Tag sexprs.Sexp
}

func (a AuthCert) Certificate() sexprs.Sexp {
	return a.Sexp()
}

func (a AuthCert) Sexp() sexprs.Sexp {
	switch {
	case a.Expr != nil:
		return a.Expr
	}
	var ds, vs sexprs.Sexp
	var s sexprs.List
	if a.Delegate {
		ds = sexprs.List{sexprs.Atom{Value: []byte("delegate")}}
	}
	if a.Valid != nil {
		vs = a.Valid.Sexp()
	}
	s = sexprs.List{sexprs.Atom{Value: []byte("cert")},
		sexprs.List{sexprs.Atom{Value: []byte("issuer")}, a.Issuer.Sexp()},
		sexprs.List{sexprs.Atom{Value: []byte("subject")}, a.Subject.Subject()}}
	if ds != nil {
		s = append(s, ds)
	}
	s = append(s, a.Tag)
	if vs != nil {
		s = append(s, vs)
	}
	return s
}

func (a AuthCert) String() string {
	return a.Sexp().String()
}


text:
I fell in love with the text inputs effects in [this article](http://tympanus.net/codrops/2015/01/08/inspiration-text-input-effects/). As an exercise I decided to recreate as many of them as I can using Swift *(some of them have a personal touch)*.

Currently it features the following effects from the article:

- [x] Kaede
- [x] Hoshi
- [x] Jiro
- [x] Isao
- [x] Minoru
- [x] Yoko
- [x] Madoka
- [x] Akira
- [x] Yoshiko

## How they look

### Kaede

### Hoshi

### Jiro

### Isao

### Minoru

### Yoko

### Madoka

### Akira

### Yoshiko

## Installation

- Looking for Swift 2.3 support? Check out the [1.2.0](https://github.com/raulriera/TextFieldEffects/releases/tag/1.2.0) tag.
- Looking for Swift 2.1 support? Check out the [1.1.1](https://github.com/raulriera/TextFieldEffects/releases/tag/1.1.1) tag.
- Looking for Swift 1.2 support? Check out the `swift-1.2` branch.

### Manual

The easiest way to install this framework is to drag and drop the `TextFieldEffects/TextFieldEffects` folder into your project. This also prevents the `frameworks` [problem in iOS](http://www.openradar.me/21258097) where the IBInspectable and IBDesignable are stripped out.

### CocoaPods

Add the following to your Podfile:

``` ruby
use_frameworks!
pod 'TextFieldEffects'
```

### Carthage

Add the following to your Cartfile:

``` ruby
github 'raulriera/TextFieldEffects'
```

## How to use them

Every effect is properly documented in the source code, this is the best way to both understand and see what they do. There is also an example project included with all the effects and their settings.

### Interface Builder

The library is a simple drop-in, as soon as you set your subclass to one of the effects and your module to `TextFieldEffects` you will be able to see all the IBDesignable settings in the storyboard.

### Code

If you like to get your hands dirty, you can use them just like you would normally use any `UITextField`

``` swift
let textField = KaedeTextField(frame: textFieldFrame)
textField.placeholderColor = .darkGrayColor()
textField.foregroundColor = .lightGrayColor()

view.addSubView(textField)
```

Is that simple.

## Created by
Raul Riera, [@raulriera](http://twitter.com/raulriera)


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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.

=cut

# POD documentation - main docs before the code

=pod

=head1 NAME

Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::GeneStoreNCMembers

=cut

=head1 SYNOPSIS

my $db      = Bio::EnsEMBL::Compara::DBAdaptor->new($locator);
my $g_load_members = Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::GeneStoreNCMembers->new (
                                                    -db      => $db,
                                                    -input_id   => $input_id
                                                    -analysis   => $analysis );
$g_load_members->fetch_input(); #reads from DB
$g_load_members->run();
$g_load_members->write_output(); #writes to DB

=cut

=head1 DESCRIPTION

Create members from a given ncRNA gene (both ncRNA members and gene member).

=cut

=head1 CONTACT

Describe contact details here

=cut

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _

=cut

package Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::GeneStoreNCMembers;

use strict;

use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');

sub param_defaults {
    return {
        'store_genes'  => 1,    # whether genes are also stored as members
    };
}

=head2 fetch_input

    Read the parameters and set up all necessary objects.

=cut

sub fetch_input {
    my $self = shift @_;

    my $genome_db_id = $self->param_required('genome_db_id');
    my $stable_id = $self->param_required('stable_id');

        # fetch the Compara::GenomeDB object for the genome_db_id
    my $genome_db = $self->compara_dba->get_GenomeDBAdaptor->fetch_by_dbID($genome_db_id) or die "Could not fetch genome_db with id=$genome_db_id";
    $self->param('genome_db', $genome_db);

        # using genome_db_id connect to external core database
    my $core_db = $genome_db->db_adaptor() or die "Can't connect to genome database for id=$genome_db_id";
    $self->param('core_db', $core_db);

}

=head2 run

    Fetch a particular gene and create members from its' non-coding transcript(s?) and the gene itself

=cut

sub run {
    my $self = shift @_;

    my $core_db     = $self->param('core_db');
    my $stable_id   = $self->param('stable_id');

    $self->compara_dba->dbc->disconnect_when_inactive(0);
    $core_db->dbc->disconnect_when_inactive(0);

    my $gene_adaptor = $core_db->get_GeneAdaptor or die "Could not create the core GeneAdaptor";

    my $gene = $gene_adaptor->fetch_by_stable_id( $stable_id ) or die "Could not fetch gene with stable_id '$stable_id'";

        # Store gene:
    $self->store_ncrna_gene($gene);

    $self->compara_dba->dbc->disconnect_when_inactive(1);
    $core_db->dbc->disconnect_when_inactive(1);
}

######################################
#
# subroutines
#
#####################################

sub store_ncrna_gene {
    my ($self, $gene) = @_;

    my $longest_ncrna_member;
    my $max_ncrna_length = 0;
    my $gene_member;
    my $gene_member_not_stored = 1;

    my $gene_member_adaptor = $self->compara_dba->get_GeneMemberAdaptor();
    my $seq_member_adaptor = $self->compara_dba->get_SeqMemberAdaptor();

    my $pseudo_stableID_prefix = $self->param('pseudo_stableID_prefix');

    if($pseudo_stableID_prefix) {
        $gene->stable_id($pseudo_stableID_prefix ."G_". $gene->dbID);
    }

    TRANSCRIPT: foreach my $transcript (@{$gene->get_all_Transcripts}) {
        if (defined $transcript->translation) {
            warn("Translation exists for ncRNA transcript ", $transcript->stable_id, "(dbID=",$transcript->dbID.")\n");
            next;
        }

        if($pseudo_stableID_prefix) {
            $transcript->stable_id($pseudo_stableID_prefix ."T_". $transcript->dbID);
        }

        print("     transcript " . $transcript->stable_id ) if($self->debug);

        my $fasta_description = $self->fasta_description($gene, $transcript) or next TRANSCRIPT;

        my $ncrna_member = Bio::EnsEMBL::Compara::SeqMember->new_from_transcript(
            -transcript  => $transcript,
            -genome_db   => $self->param('genome_db'),
            -translate   => 'ncrna',
            -description => $fasta_description,
        );

        print(" => member " . $ncrna_member->stable_id) if($self->debug);

        my $transcript_spliced_seq = $transcript->spliced_seq;

            # store gene_member here only if at least one ncRNA is to be loaded for the gene.
        if($self->param('store_genes') and $gene_member_not_stored) {
            print("     gene       " . $gene->stable_id ) if($self->debug);

            $gene_member = Bio::EnsEMBL::Compara::GeneMember->new_from_gene(
                -gene      => $gene,
                -genome_db => $self->param('genome_db'),
            );
            print(" => member " . $gene_member->stable_id) if($self->debug);

            eval {
                $gene_member_adaptor->store($gene_member);
                print(" : stored") if($self->debug);
            };

            print("\n") if($self->debug);
            $gene_member_not_stored = 0;
        }

        $ncrna_member->gene_member_id($gene_member->dbID);
        $seq_member_adaptor->store($ncrna_member);
        print(" : stored\n") if($self->debug);

        if(length($transcript_spliced_seq) > $max_ncrna_length) {
            $max_ncrna_length     = length($transcript_spliced_seq);
            $longest_ncrna_member = $ncrna_member;
        }
    }

    if($longest_ncrna_member) {
        $seq_member_adaptor->_set_member_as_canonical($longest_ncrna_member);
    }
}

sub fasta_description {
    my ($self, $gene, $transcript) = @_;
    my $acc = 'NULL'; my $biotype = undef;
    $DB::single=1;1;
    eval { $acc = $transcript->display_xref->primary_id;};

    unless ($acc =~ /RF00/) {
        $biotype = $transcript->biotype;
        if ($biotype =~ /miRNA/) {
            my @exons = @{$transcript->get_all_Exons};
            $self->throw("unexpected miRNA with more than one exon") if (1 < scalar @exons);
            my $exon = $exons[0];
            my @supporting_features = @{$exon->get_all_supporting_features};
            if (scalar(@supporting_features)!=1) {
                warn "unexpected miRNA supporting features";
                next;
            }
            my $supporting_feature = $supporting_features[0];
            eval { $acc = $supporting_feature->hseqname; };
        } elsif ($biotype =~ /snoRNA/) {
            eval { $acc = $transcript->external_name; };
        } elsif ($biotype =~ /Mt_rRNA/) {
            # $acc = $biotype;
        } else {
            # Let's try with the gene
            eval { $acc = $gene->get_all_xrefs('RFAM')->[0]->primary_id(); };
        }
    }
    my $description = "Transcript:" . $transcript->stable_id .
                      " Gene:" .      $gene->stable_id .
                      " Chr:" .       $gene->seq_region_name .
                      " Start:" .     $gene->seq_region_start .
                      " End:" .       $gene->seq_region_end.
                      " Acc:" .       $acc;
    print STDERR "Description... $description\n" if ($self->debug);
    return $description;
}

1;


text:
using System;
using Xunit;
using Should;

namespace AutoMapper.UnitTests
{
	namespace DynamicMapping
	{
		public class When_mapping_two_non_configured_types : NonValidatingSpecBase
		{
			private Destination _resultWithGenerics;
			private Destination _resultWithoutGenerics;

			public class Source
			{
				public int Value { get; set; }
			}

			public class Destination
			{
				public int Value { get; set; }
			}

            protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);

            [Fact]
			public void Should_dynamically_map_the_two_types()
			{
				_resultWithGenerics = Mapper.Map<Source, Destination>(new Source {Value = 5});
				_resultWithoutGenerics = (Destination) Mapper.Map(new Source {Value = 5}, typeof(Source), typeof(Destination));
				_resultWithGenerics.Value.ShouldEqual(5);
				_resultWithoutGenerics.Value.ShouldEqual(5);
			}
		}

        public class When_mapping_two_non_configured_types_with_nesting : NonValidatingSpecBase
        {
            private Destination _resultWithGenerics;

            public class Source
            {
                public int Value { get; set; }
                public ChildSource Child { get; set; }
            }

            public class ChildSource
            {
                public string Value2 { get; set; }
            }

            public class Destination
            {
                public int Value { get; set; }
                public ChildDestination Child { get; set; }
            }

            public class ChildDestination
            {
                public string Value2 { get; set; }
            }

            protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);

            public When_mapping_two_non_configured_types_with_nesting()
            {
                var source = new Source
                {
                    Value = 5,
                    Child = new ChildSource
                    {
                        Value2 = "foo"
                    }
                };
                _resultWithGenerics = Mapper.Map<Source, Destination>(source);
            }

            [Fact]
            public void Should_dynamically_map_the_two_types()
            {
                _resultWithGenerics.Value.ShouldEqual(5);
            }

            [Fact]
            public void Should_dynamically_map_the_children()
            {
                _resultWithGenerics.Child.Value2.ShouldEqual("foo");
            }
        }

		public class When_mapping_two_non_configured_types_that_do_not_match : NonValidatingSpecBase
		{
			public class Source
			{
				public int Value { get; set; }
			}

			public class Destination
			{
				public int Valuefff { get; set; }
			}

            protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);

            [Fact]
			public void Should_ignore_any_members_that_do_not_match()
			{
				var destination = Mapper.Map<Source, Destination>(new Source {Value = 5});

				destination.Valuefff.ShouldEqual(0);
			}

			[Fact]
			public void Should_not_throw_any_configuration_errors()
			{
				typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.Map<Source, Destination>(new Source { Value = 5 }));
			}
		}

		public class When_mapping_to_an_existing_destination_object : NonValidatingSpecBase
		{
			private Destination _destination;

			public class Source
			{
				public int Value { get; set; }
				public int Value2 { get; set; }
			}

			public class Destination
			{
				public int Valuefff { get; set; }
				public int Value2 { get; set; }
			}

            protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);

            public When_mapping_to_an_existing_destination_object()
		    {
				_destination = new Destination { Valuefff = 7};
				Mapper.Map(new Source { Value = 5, Value2 = 3}, _destination);
			}

			[Fact]
			public void Should_preserve_existing_values()
			{
				_destination.Valuefff.ShouldEqual(7);
			}

			[Fact]
			public void Should_map_new_values()
			{
				_destination.Value2.ShouldEqual(3);
			}
		}

#if !PORTABLE
        public class When_mapping_from_an_anonymous_type_to_an_interface : NonValidatingSpecBase
		{
			private IDestination _result;

			public interface IDestination
			{
				int Value { get; set; }
			}

			protected override void Because_of()
			{
				_result = Mapper.Map<IDestination>(new {Value = 5});
			}

			[Fact]
			public void Should_allow_dynamic_mapping()
			{
				_result.Value.ShouldEqual(5);
			}

            protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
		}
#endif
    }
}


text:
import { ServiceScope } from '@microsoft/sp-core-library';
import { WebPartContext } from "@microsoft/sp-webpart-base";

export interface IAdaptiveCardsImageGalleryProps {
  context: WebPartContext;
  serviceScope: ServiceScope;
  imageGalleryName: string;
  imagesToDisplay: number;
}


text:
@interface ___FILEBASENAMEASIDENTIFIER___ : NSObject

@end


text:
package org.jabsorb.ng;

import java.io.Serializable;

/**
 * Used to transform the exception to some object in JSONRPCResults
 */
public interface ExceptionTransformer extends Serializable {

    /**
     * Transform the exception to the format desired for transport to the
     * client. This method should not itself throw an exception.
     *
     * @param t
     *            The exception to be transformed
     * @return one of the JSON-compatible types (JSONObject, String, Boolean
     *         etc.), or a Throwable
     */
    Object transform(Throwable t);
}


text:
title: Функции ограничения
sidebar: flexberry-orm_sidebar
keywords: Flexberry ORM, Ограничения
summary: Определение и предназначение построителей ограничений
toc: true
permalink: ru/fo_limit-function.html
lang: ru
---

Функции ограничения позволяют осуществлять фильтрацию и ограничения выборки данных и представляют собой специальный расширяемый язык ограничений, разработанный для [Flexberry ORM](fo_flexberry-orm.html).

Данный механизм лежит в основе функционирования [LINQProvider](fo_linq-provider.html), таким образом, [данные механизмы наложения ограничений тесно связаны](fo_limitation.html).

Существует [возможность сериализовать функцию ограничения](fo_limit-function-serialization.html).

## "Построители" функций ограничений

[SQLWhereLanguageDef](fo_function-list.html) - класс-построитель функций для наложения ограничений на вычитываемые объекты.

[ExternalLangDef](fo_external-lang-def.html) - расширение языка ограничений для задания ограничений на зависимые объекты (детейлы).

[FunctionBuilder](fo_function-builder.html) - класс-обертка над ExternalLangDef с менее многословным синтаксисом для построения функций ограничений на вычитываемые объекты.

[FunctionBuilder примеры](fo_function-builder-examples.html) - более детальные примеры по рефактору `LangDef.GetFunction`.

Существует [возможность расширить реализованные языки ограничений](fo_using-languagedef.html).

## Применение функций ограничения

Работа с функциями ограничений часто связана с вычиткой данных. При вычитке данных функция ограничений указывается в структуре [LoadingCustomizationStruct](fo_loading-customization-struct.html).