text:
package com.whammich.sstow.block;

import com.whammich.sstow.SoulShardsTOW;
import com.whammich.sstow.api.SoulShardsAPI;
import com.whammich.sstow.tile.TileEntityCage;
import com.whammich.sstow.util.TierHandler;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.BooleanUtils;

public class BlockCage extends Block {

    public BlockCage() {
        super(Material.IRON);
        setUnlocalizedName(SoulShardsTOW.MODID + ".cage");
        setCreativeTab(SoulShardsTOW.TAB_SS);
        setDefaultState(blockState.getBaseState().withProperty(SoulShardsAPI.ACTIVE, false));
        setHardness(3.0F);
        setResistance(3.0F);
    }

    @Override
    protected BlockStateContainer createBlockState() {
        return new BlockStateContainer(this, SoulShardsAPI.ACTIVE);
    }

    @Override
    public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) {
        TileEntity tile = worldIn.getTileEntity(pos);
        return state.withProperty(SoulShardsAPI.ACTIVE, ((TileEntityCage) tile).getActiveState());
    }

    @Override
    public int getMetaFromState(IBlockState state) {
        return state.getValue(SoulShardsAPI.ACTIVE) ? 1 : 0;
    }

    @Override
    public IBlockState getStateFromMeta(int meta) {
        return getDefaultState().withProperty(SoulShardsAPI.ACTIVE, BooleanUtils.toBoolean(MathHelper.clamp(meta, 0, 1)));
    }

    @Override
    public boolean hasComparatorInputOverride(IBlockState state) {
        return true;
    }

    @Override
    public int getComparatorInputOverride(IBlockState state, World world, BlockPos pos) {
        TileEntityCage tile = (TileEntityCage) world.getTileEntity(pos);
        return (int) ((float) tile.getTier() / (float) TierHandler.maxTier) * 15;
    }

    @Override
    public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
        return true;
    }

    @Override
    public void breakBlock(World world, BlockPos blockPos, IBlockState blockState) {
        TileEntityCage tileCage = (TileEntityCage) world.getTileEntity(blockPos);
        if (tileCage != null)
            tileCage.dropItems();

        super.breakBlock(world, blockPos, blockState);
    }

    @Override
    public int damageDropped(IBlockState state) {
        return 0;
    }

    @Override
    @SideOnly(Side.CLIENT)
    public boolean isOpaqueCube(IBlockState state) {
        return false;
    }

    @Override
    @SideOnly(Side.CLIENT)
    public boolean causesSuffocation(IBlockState state) {
        return false;
    }

    @Override
    @SideOnly(Side.CLIENT)
    public BlockRenderLayer getBlockLayer() {
        return BlockRenderLayer.CUTOUT;
    }

    @Override
    public boolean hasTileEntity(IBlockState state) {
        return true;
    }

    @Override
    public TileEntity createTileEntity(World world, IBlockState state) {
        return new TileEntityCage();
    }
}


text:
package com.twu.biblioteca;

import org.junit.Before;
import org.mockito.Mock;

import java.util.List;

/**
 * Created by edytawrobel on 07/06/2017.
 */
public class LibraryTest {

    @Mock
    Book book;

    @Before
    public void setup() {

        Library library = new Library();

        List<Book> books;
        book = new Book("Antoine de Saint-Exupéry", "The Little Prince",1943);
        String sampleOutput = "Antoine de Saint-Exupéry, The Little Prince, 1943";
    }

}

redpajama_set_name: RedPajamaGithub


text:
title: 应用编排与管理 -- DaemonSet
mathjax: false
date: 2021-07-12 09:06:08
categories:
	- Cloud Native
	- Kubernetes
	- Alibaba
tags:
	- Cloud Native
	- Kubernetes
	- Alibaba
---

# 作用

1. 保证集群内每一个或者一些**节点**都运行一组相同的 Pod
2. 跟踪集群节点状态,保证**新加入的节点**自动创建对应的 Pod
3. 跟踪集群节点状态,保证**移除的节点**删除对应的 Pod
4. 跟踪 Pod 状态,保证每个节点 Pod 处于**运行状态**

<!-- more -->

# 实践

## YAML 文件

```yaml ds.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluentd-elasticsearch
  namespace: kube-system
  labels:
    k8s-app: fluentd-logging
spec:
  selector:
    matchLabels:
      name: fluentd-elasticsearch
  template: # Pod Template
    metadata:
      labels:
        name: fluentd-elasticsearch
    spec:
      containers:
        - name: fluentd-elasticsearch
          image: 'fluent/fluentd:v1.4-1'
```

## 查看 Node

```
$ kubectl get nodes
NAME       STATUS   ROLES    AGE   VERSION
minikube   Ready    master   10h   v1.15.5
```

## 查看 DaemonSet

```
$ kubectl apply -f ds.yaml
daemonset.apps/fluentd-elasticsearch created

$ kubectl get ds -n kube-system
NAME                    DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR                 AGE
fluentd-elasticsearch   1         1         1       1            1           <none>                        3m58s
kube-proxy              1         1         1       1            1           beta.kubernetes.io/os=linux   10h

$ kubectl get ds -n kube-system fluentd-elasticsearch -o yaml | head -n 15
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apps/v1","kind":"DaemonSet","metadata":{"annotations":{},"labels":{"k8s-app":"fluentd-logging"},"name":"fluentd-elasticsearch","namespace":"kube-system"},"spec":{"selector":{"matchLabels":{"name":"fluentd-elasticsearch"}},"template":{"metadata":{"labels":{"name":"fluentd-elasticsearch"}},"spec":{"containers":[{"image":"fluent/fluentd:v1.4-1","name":"fluentd-elasticsearch"}]}}}}
  creationTimestamp: "2021-07-12T02:51:12Z"
  generation: 1
  labels:
    k8s-app: fluentd-logging
  name: fluentd-elasticsearch
  namespace: kube-system
  resourceVersion: "8703"
  selfLink: /apis/extensions/v1beta1/namespaces/kube-system/daemonsets/fluentd-elasticsearch
  uid: 4b3c030f-8f45-4f74-87c6-1c21899ebc31
```

| Key           | Value                        |
| ------------- | ---------------------------- |
| DESIRED       | 需要的 Pod 个数              |
| CURRENT       | 当前已存在的 Pod 数          |
| READY         | 就绪的 Pod 数                |
| UP-TO-DATE    | 到达预期版本的 Pod 数        |
| AVAILABLE     | 可用的 Pod 数                |
| NODE SELECTOR | 节点选择标签(筛选部分节点) |

## 查看 Pod

Pod 的 OwnerReference 为 DaemonSet

```
$ kubectl get pods -n kube-system
NAME                               READY   STATUS    RESTARTS   AGE
coredns-6967fb4995-n2pk4           1/1     Running   2          10h
etcd-minikube                      1/1     Running   1          10h
fluentd-elasticsearch-z4b9x        1/1     Running   0          4m25s
kube-apiserver-minikube            1/1     Running   1          10h
kube-controller-manager-minikube   1/1     Running   1          10h
kube-proxy-tjgc7                   1/1     Running   1          10h
kube-scheduler-minikube            1/1     Running   1          10h
storage-provisioner                1/1     Running   2          10h

$ kubectl get pods -n kube-system fluentd-elasticsearch-z4b9x -o yaml | head -n 21
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2021-07-12T02:51:12Z"
  generateName: fluentd-elasticsearch-
  labels:
    controller-revision-hash: 5fd669cccc
    name: fluentd-elasticsearch
    pod-template-generation: "1"
  name: fluentd-elasticsearch-z4b9x
  namespace: kube-system
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: DaemonSet
    name: fluentd-elasticsearch
    uid: 4b3c030f-8f45-4f74-87c6-1c21899ebc31
  resourceVersion: "8702"
  selfLink: /api/v1/namespaces/kube-system/pods/fluentd-elasticsearch-z4b9x
  uid: b2b3ed75-31f9-43f5-b247-92fcb7894741
```

## 更新 DaemonSet

1. **RollingUpdate**(默认):当 DaemonSet 模板更新后,**老 Pod 会先被删除**,然后再去创建新的 Pod,配合健康检查做滚动更新
2. **OnDelete**:当 DaemonSet 模板更新后,只有手动删除某个对应的 Pod,此节点 Pod 才会被更新

```
$ kubectl set image ds/fluentd-elasticsearch fluentd-elasticsearch=fluent/fluentd:v1.4 -n kube-system
daemonset.extensions/fluentd-elasticsearch image updated

$ kubectl describe ds -n kube-system fluentd-elasticsearch
Name:           fluentd-elasticsearch
Selector:       name=fluentd-elasticsearch
Node-Selector:  <none>
Labels:         k8s-app=fluentd-logging
Annotations:    deprecated.daemonset.template.generation: 2
                kubectl.kubernetes.io/last-applied-configuration:
                  {"apiVersion":"apps/v1","kind":"DaemonSet","metadata":{"annotations":{},"labels":{"k8s-app":"fluentd-logging"},"name":"fluentd-elasticsear...
Desired Number of Nodes Scheduled: 1
Current Number of Nodes Scheduled: 1
Number of Nodes Scheduled with Up-to-date Pods: 1
Number of Nodes Scheduled with Available Pods: 1
Number of Nodes Misscheduled: 0
Pods Status:  1 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  name=fluentd-elasticsearch
  Containers:
   fluentd-elasticsearch:
    Image:        fluent/fluentd:v1.4
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age    From                  Message
  ----    ------            ----   ----                  -------
  Normal  SuccessfulCreate  24m    daemonset-controller  Created pod: fluentd-elasticsearch-z4b9x
  Normal  SuccessfulDelete  2m24s  daemonset-controller  Deleted pod: fluentd-elasticsearch-z4b9x
  Normal  SuccessfulCreate  2m12s  daemonset-controller  Created pod: fluentd-elasticsearch-dwmdt

$ kubectl get pods -n kube-system fluentd-elasticsearch-dwmdt -o yaml | head -n 21
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2021-07-12T03:13:27Z"
  generateName: fluentd-elasticsearch-
  labels:
    controller-revision-hash: f86bfc847
    name: fluentd-elasticsearch
    pod-template-generation: "2"
  name: fluentd-elasticsearch-dwmdt
  namespace: kube-system
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: DaemonSet
    name: fluentd-elasticsearch
    uid: 4b3c030f-8f45-4f74-87c6-1c21899ebc31
  resourceVersion: "9692"
  selfLink: /api/v1/namespaces/kube-system/pods/fluentd-elasticsearch-dwmdt
  uid: 8ea753ea-2ed3-4d8a-b950-c31ec6847ecd
```

#  架构设计

## 管理模式

纠正:跟踪 Pod 状态,而非跟踪 Job 状态

![image-20210712111948819](https://cloud-native-alibaba-1253868755.cos.ap-guangzhou.myqcloud.com/kubernetes/image-20210712111948819.png)

## DaemonSet Controller

1. 纠正:不是 Job Controller,而是 DaemonSet Controller
2. DaemonSet Controller 需要 Watch 节点状态(通过 API Server 传递到 Etcd)
3. 当节点状态发生变化时,会通过一个内存 MQ 传递消息,DaemonSet Controller 会 Watch 到这一状态
4. DaemonSet Controller 会查看各个节点上是否都有对应的 Pod,没有则创建,有则对比版本

![image-20210712112415859](https://cloud-native-alibaba-1253868755.cos.ap-guangzhou.myqcloud.com/kubernetes/image-20210712112415859.png)

# 参考资料

1. [CNCF × Alibaba 云原生技术公开课](https://edu.aliyun.com/course/1651)


text:
"""
This example demonstrates the following:
    - Creation of a custom resource definition (CRD) using dynamic-client
    - Creation of namespaced custom resources (CR) using the above CRD
    - List, patch (update), delete the custom resources
    - Delete the custom resource definition (CRD)
"""

from kubernetes import config, dynamic
from kubernetes import client as k8s_client
from kubernetes.dynamic.exceptions import ResourceNotFoundError
from kubernetes.client import api_client
import time

def list_ingressroute_for_all_namespaces(group, version, plural):
    custom_object_api = k8s_client.CustomObjectsApi()

    list_of_ingress_routes = custom_object_api.list_cluster_custom_object(
        group, version, plural
    )
    print(
        "%s\t\t\t%s\t\t\t%s\t\t%s\t\t\t\t%s"
        % ("NAME", "NAMESPACE", "FQDN", "TLS", "STRATEGY")
    )
    for item in list_of_ingress_routes["items"]:
        print(
            "%s\t%s\t\t%s\t%s\t%s"
            % (
                item["metadata"]["name"],
                item["metadata"]["namespace"],
                item["spec"]["virtualhost"]["fqdn"],
                item["spec"]["virtualhost"]["tls"],
                item["spec"]["strategy"]
            )
        )

def create_namespace(namespace_api, name):
    namespace_manifest = {
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {"name": name, "resourceversion": "v1"},
    }
    namespace_api.create(body=namespace_manifest)

def delete_namespace(namespace_api, name):
    namespace_api.delete(name=name)

def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config())
    )

    # fetching the custom resource definition (CRD) api
    crd_api = client.resources.get(
        api_version="apiextensions.k8s.io/v1", kind="CustomResourceDefinition"
    )

    namespace_api = client.resources.get(api_version="v1", kind="Namespace")

    # Creating a Namespaced CRD named "ingressroutes.apps.example.com"
    name = "ingressroutes.apps.example.com"

    crd_manifest = {
        "apiVersion": "apiextensions.k8s.io/v1",
        "kind": "CustomResourceDefinition",
        "metadata": {"name": name, "namespace": "default"},
        "spec": {
            "group": "apps.example.com",
            "versions": [
                {
                    "name": "v1",
                    "schema": {
                        "openAPIV3Schema": {
                            "properties": {
                                "spec": {
                                    "properties": {
                                        "strategy": {"type": "string"},
                                        "virtualhost": {
                                            "properties": {
                                                "fqdn": {"type": "string"},
                                                "tls": {
                                                    "properties": {
                                                        "secretName": {"type": "string"}
                                                    },
                                                    "type": "object",
                                                },
                                            },
                                            "type": "object",
                                        },
                                    },
                                    "type": "object",
                                }
                            },
                            "type": "object",
                        }
                    },
                    "served": True,
                    "storage": True,
                }
            ],
            "scope": "Namespaced",
            "names": {
                "plural": "ingressroutes",
                "listKind": "IngressRouteList",
                "singular": "ingressroute",
                "kind": "IngressRoute",
                "shortNames": ["ir"],
            },
        },
    }

    crd_creation_response = crd_api.create(crd_manifest)
    print(
        "\n[INFO] custom resource definition `ingressroutes.apps.example.com` created\n"
    )
    print("%s\t\t%s" % ("SCOPE", "NAME"))
    print(
        "%s\t%s\n"
        % (crd_creation_response.spec.scope, crd_creation_response.metadata.name)
    )

    # Fetching the "ingressroutes" CRD api

    try:
        ingressroute_api = client.resources.get(
            api_version="apps.example.com/v1", kind="IngressRoute"
        )
    except ResourceNotFoundError:
        # Need to wait a sec for the discovery layer to get updated
        time.sleep(2)

    ingressroute_api = client.resources.get(
        api_version="apps.example.com/v1", kind="IngressRoute"
    )

    # Creating a custom resource (CR) `ingress-route-*`, using the above CRD `ingressroutes.apps.example.com`

    namespace_first = "test-namespace-first"
    namespace_second = "test-namespace-second"

    create_namespace(namespace_api, namespace_first)
    create_namespace(namespace_api, namespace_second)

    ingressroute_manifest_first = {
        "apiVersion": "apps.example.com/v1",
        "kind": "IngressRoute",
        "metadata": {
            "name": "ingress-route-first",
            "namespace": namespace_first,
        },
        "spec": {
            "virtualhost": {
                "fqdn": "www.google.com",
                "tls": {"secretName": "google-tls"},
            },
            "strategy": "RoundRobin",
        },
    }

    ingressroute_manifest_second = {
        "apiVersion": "apps.example.com/v1",
        "kind": "IngressRoute",
        "metadata": {
            "name": "ingress-route-second",
            "namespace": namespace_second,
        },
        "spec": {
            "virtualhost": {
                "fqdn": "www.yahoo.com",
                "tls": {"secretName": "yahoo-tls"},
            },
            "strategy": "RoundRobin",
        },
    }

    ingressroute_api.create(body=ingressroute_manifest_first, namespace=namespace_first)
    ingressroute_api.create(body=ingressroute_manifest_second, namespace=namespace_second)
    print("\n[INFO] custom resources `ingress-route-*` created\n")

    # Listing the `ingress-route-*` custom resources

    list_ingressroute_for_all_namespaces(
        group="apps.example.com", version="v1", plural="ingressroutes"
    )

    # Patching the ingressroutes custom resources

    ingressroute_manifest_first["spec"]["strategy"] = "Random"
    ingressroute_manifest_second["spec"]["strategy"] = "WeightedLeastRequest"

    patch_ingressroute_first = ingressroute_api.patch(
        body=ingressroute_manifest_first, content_type="application/merge-patch+json"
    )
    patch_ingressroute_second = ingressroute_api.patch(
        body=ingressroute_manifest_second, content_type="application/merge-patch+json"
    )

    print(
        "\n[INFO] custom resources `ingress-route-*` patched to update the strategy\n"
    )
    list_ingressroute_for_all_namespaces(
        group="apps.example.com", version="v1", plural="ingressroutes"
    )

    # Deleting the ingressroutes custom resources

    delete_ingressroute_first = ingressroute_api.delete(
        name="ingress-route-first", namespace=namespace_first
    )
    delete_ingressroute_second = ingressroute_api.delete(
        name="ingress-route-second", namespace=namespace_second
    )

    print("\n[INFO] custom resources `ingress-route-*` deleted")

    # Deleting the namespaces

    delete_namespace(namespace_api, namespace_first)
    time.sleep(4)
    delete_namespace(namespace_api, namespace_second)
    time.sleep(4)

    print("\n[INFO] test namespaces deleted")

    # Deleting the ingressroutes.apps.example.com custom resource definition

    crd_api.delete(name=name)
    print(
        "\n[INFO] custom resource definition `ingressroutes.apps.example.com` deleted"
    )

if __name__ == "__main__":
    main()


text:
package io.subutai.common.security.crypto.key;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KeyManager
{

    private static final Logger LOG = LoggerFactory.getLogger( KeyManager.class.getName() );

    private KeyPairGenerator keyPairGen;
    private KeyPair keyPair;
    private PrivateKey privateKey;
    private PublicKey publicKey;
    private KeyGenerator keyGen;
    private SecretKey secretKey;
    private Signature signature;

    /**
     * *************************************************************************
     * **********************************
     */
    public KeyPairGenerator prepareKeyPairGeneration( KeyPairType keyPairType, int keySize )
    {

        try
        {
            keyPairGen = KeyPairGenerator.getInstance( keyPairType.jce() );
            keyPairGen.initialize( keySize );
        }
        catch ( Exception e )
        {
            LOG.error( "Error preparing KeyPair generator", e );
        }

        return keyPairGen;
    }

    /**
     * *************************************************************************
     * **********************************
     */
    public KeyPair generateKeyPair( KeyPairGenerator keyPairGen )
    {
        try
        {
            keyPair = keyPairGen.genKeyPair();
            privateKey = keyPair.getPrivate();
            publicKey = keyPair.getPublic();
        }
        catch ( Exception e )
        {
            LOG.error( "Error generating KeyPair", e );
        }

        return keyPair;
    }

    /**
     * *************************************************************************
     * **********************************
     */
    public PrivateKey generatePrivateKeyPair( KeyPair keyPair )
    {
        try
        {
            privateKey = keyPair.getPrivate();
        }
        catch ( Exception e )
        {
            LOG.error( "Error generating Private Key", e );
        }

        return privateKey;
    }

    /**
     * *************************************************************************
     * **********************************
     */
    public PublicKey generatePublicKeyPair( KeyPair keyPair )
    {
        try
        {
            publicKey = keyPair.getPublic();
        }
        catch ( Exception e )
        {
            LOG.error( "Error Public Key", e );
        }

        return publicKey;
    }

    /**
     * *************************************************************************
     * **********************************
     */
    public byte[] generatePrivateKeyPairBytes()
    {
        byte[] privateKeyBytes = null;

        try
        {
            privateKeyBytes = privateKey.getEncoded();
        }
        catch ( Exception e )
        {
            LOG.error( "Error converting private Key to bytes", e );
        }

        return privateKeyBytes;
    }

    /**
     * *************************************************************************
     * **********************************
     */
    public byte[] generatePublicKeyPairBytes()
    {
        byte[] publicKeyBytes = null;

        try
        {
            publicKeyBytes = publicKey.getEncoded();
        }
        catch ( Exception e )
        {
            LOG.error( "Error converting public Key to bytes", e );
        }

        return publicKeyBytes;
    }

    /**
     * *************************************************************************
     * **********************************
     */
    public void prepareSecretKeyGeneration( SecretKeyType secretKeyType )
    {
        try
        {
            keyGen = KeyGenerator.getInstance( secretKeyType.jce() );
        }
        catch ( NoSuchAlgorithmException e )
        {
            LOG.error( "Error preparing Secret Key generator", e );
        }
    }

    /**
     * *************************************************************************
     * **********************************
     */
    public SecretKey generateSecretKey( KeyGenerator keyGen )
    {
        try
        {
            this.keyGen = keyGen;
            secretKey = this.keyGen.generateKey();
        }
        catch ( Exception e )
        {
            LOG.error( "Error generating Secret Key", e );
        }

        return secretKey;
    }

    /**
     * ** Getter Setter Methods ***********************************************************************
     * **********************************
     */
    public KeyPairGenerator getKeyGen()
    {
        return keyPairGen;
    }

    public void setKeyGen( KeyPairGenerator keyPairGen )
    {
        this.keyPairGen = keyPairGen;
    }

    public PrivateKey getPrivateKey()
    {
        return privateKey;
    }

    public void setPrivateKey( PrivateKey privateKey )
    {
        this.privateKey = privateKey;
    }

    public PublicKey getPublicKey()
    {
        return publicKey;
    }

    public void setPublicKey( PublicKey publicKey )
    {
        this.publicKey = publicKey;
    }

    public KeyPairGenerator getKeyPairGen()
    {
        return keyPairGen;
    }

    public void setKeyPairGen( KeyPairGenerator keyPairGen )
    {
        this.keyPairGen = keyPairGen;
    }

    public KeyPair getKeyPair()
    {
        return keyPair;
    }

    public void setKeyPair( KeyPair keyPair )
    {
        this.keyPair = keyPair;
    }

    public SecretKey getSecretKey()
    {
        return secretKey;
    }

    public void setSecretKey( SecretKey secretKey )
    {
        this.secretKey = secretKey;
    }

    public void setKeyGen( KeyGenerator keyGen )
    {
        this.keyGen = keyGen;
    }

    public Signature getSignature()
    {
        return signature;
    }

    public void setSignature( Signature signature )
    {
        this.signature = signature;
    }
}


text:
//
//  TWTRNotificationConstants.h
//  TwitterKit
//
//  Copyright © 2016 Twitter. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

/**
 *  Constants for notifications that are posted from TwitterKit. These are posted on the default notification center.
 */

#pragma mark - Tweet Action Notifications

/**
 *  Notification indicating a Tweet was selected.
 */
FOUNDATION_EXPORT NSString * const TWTRDidSelectTweetNotification;

/**
 *  Notification indicating the Tweet detail view was shown for a given Tweet.
 */
FOUNDATION_EXPORT NSString * const TWTRDidShowTweetDetailNotification;

/**
 *  Notification indicating the user has selected to share Tweet.
 */
FOUNDATION_EXPORT NSString * const TWTRWillShareTweetNotification;

/**
 *  Notification indicating the Tweet was shared.
 */
FOUNDATION_EXPORT NSString * const TWTRDidShareTweetNotification;

/**
 *  Notification indicating the user has cancelled sharing of the Tweet.
 */
FOUNDATION_EXPORT NSString * const TWTRCancelledShareTweetNotification;

/**
 *  Notification indicating the user has liked a Tweet.
 */
FOUNDATION_EXPORT NSString * const TWTRDidLikeTweetNotification;

/**
 *  Notification indicating the user has unliked a Tweet.
 */
FOUNDATION_EXPORT NSString * const TWTRDidUnlikeTweetNotification;

#pragma mark - Media Notifications

/**
 *  Notification indicating the the playback state of a video
 *  has changed.
 *
 *  object: The UIView emitting these notifications
 *  userInfo: {TWTRVideoPlaybackStateKey: TWTRVideoStateValuePlaying}
 *            {TWTRVideoPlaybackStateKey: TWTRVideoStateValuePaused}
 *            {TWTRVideoPlaybackStateKey: TWTRVideoStateValueCompleted}
 */
FOUNDATION_EXPORT NSString * const TWTRVideoPlaybackStateChangedNotification;

/**
 *  User info key for the state of video playback.
 */
FOUNDATION_EXPORT NSString * const TWTRVideoPlaybackStateKey;

/**
 *  User info values for the state of video playback.
 */
FOUNDATION_EXPORT NSString * const TWTRVideoStateValuePlaying;
FOUNDATION_EXPORT NSString * const TWTRVideoStateValuePaused;
FOUNDATION_EXPORT NSString * const TWTRVideoStateValueCompleted;

#pragma mark - Presentation Notifications

/**
 *  Notification indicating that the video view controller will
 *  be presented.
 *
 *  object: The UIViewController hosting the video view
 *  userInfo: {TWTRVideoTypeKey: TWTRVideoTypeGIF}
 *            {TWTRVideoTypeKey: TWTRVideoTypeStandard}
 *            {TWTRVideoTypeKey: TWTRVideoTypeVine}
 */
FOUNDATION_EXPORT NSString * const TWTRWillPresentVideoNotification;

/**
 *  Notification indicating that the video view controller has
 *  been dismissed.
 *
 *  object: The UIViewController hosting the video view
 */
FOUNDATION_EXPORT NSString * const TWTRDidDismissVideoNotification;

/**
 *  The key to fetch the type of video being displayed in a
 *  TWTRVideoViewController.
 */
FOUNDATION_EXPORT NSString * const TWTRVideoTypeKey;

/**
 *  User info values for the type of video being displayed
 *  in a TWTRVideoViewController.
 */
FOUNDATION_EXPORT NSString * const TWTRVideoTypeGIF;
FOUNDATION_EXPORT NSString * const TWTRVideoTypeStandard;
FOUNDATION_EXPORT NSString * const TWTRVideoTypeVine;

#pragma mark - Notification User Info

/**
 *  User info key to fetch the associated Tweet in the notification.
 */
FOUNDATION_EXPORT NSString * const TWTRNotificationInfoTweet;

/**
 * A notification which is posted when a user logs out of Twitter.
 * The notification will contain a user dictionary which contains
 * the user id which is being logged out. Note, this notification may
 * be posted as a result of starting the Twitter object.
 */
FOUNDATION_EXPORT NSString * const TWTRUserDidLogOutNotification;
FOUNDATION_EXPORT NSString * const TWTRLoggedOutUserIDKey;

/**
 * A notification which is posted when a user logs in to Twitter.
 * The notification will contain a user dictionary which contains
 * the user id which is being logged in. Note, this notification may
 * be posted as a result of starting the Twitter object.
 */
FOUNDATION_EXPORT NSString * const TWTRUserDidLogInNotification;
FOUNDATION_EXPORT NSString * const TWTRLoggedInUserIDKey;

NS_ASSUME_NONNULL_END


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>fm.last</groupId>
    <artifactId>lastfm-oss-parent</artifactId>
    <version>1.1.0</version>
  </parent>

  <artifactId>moji</artifactId>
  <version>3.0.1-SNAPSHOT</version>
  <name>Moji</name>
  <description>A File-like MogileFS client</description>
  <inceptionYear>2012</inceptionYear>

  <url>https://github.com/mogilefs-moji/moji/</url>

  <scm>
    <connection>scm:git:git@github.com:mogilefs-moji/${project.artifactId}.git</connection>
    <developerConnection>scm:git:git@github.com:mogilefs-moji/${project.artifactId}.git</developerConnection>
    <url>https://github.com/mogilefs-moji/${project.artifactId}</url>
    <tag>HEAD</tag>
  </scm>

  <properties>
    <license.maven.plugin.version>3.0</license.maven.plugin.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>javax.annotation-api</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.7</version>
    </dependency>
    <dependency>
      <groupId>commons-pool</groupId>
      <artifactId>commons-pool</artifactId>
      <version>1.6</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.1</version>
    </dependency>
    <dependency>
      <groupId>fm.last.commons</groupId>
      <artifactId>lastcommons-lang</artifactId>
      <version>3.0.0</version>
    </dependency>

    <dependency>
      <groupId>fm.last.commons</groupId>
      <artifactId>lastcommons-test</artifactId>
      <version>5.1.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.8.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.6</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.sonatype.plugins</groupId>
        <artifactId>nexus-staging-maven-plugin</artifactId>
        <version>1.6.3</version>
        <extensions>true</extensions>
        <configuration>
          <serverId>sonatype-nexus-staging</serverId>
          <nexusUrl>https://oss.sonatype.org/</nexusUrl>
          <autoReleaseAfterClose>true</autoReleaseAfterClose>
        </configuration>
      </plugin>

      <plugin>
        <groupId>com.mycila</groupId>
        <artifactId>license-maven-plugin</artifactId>
        <version>${license.maven.plugin.version}</version>
        <dependencies>
          <dependency>
            <groupId>com.mycila</groupId>
            <artifactId>license-maven-plugin-git</artifactId>
            <version>${license.maven.plugin.version}</version>
          </dependency>
        </dependencies>
        <configuration>
          <header>src/main/license/mycila/APACHE-2.txt</header>
          <properties>
            <owner>Last.fm & The "mogilefs-moji" committers</owner>
          </properties>
          <includes>
            <include>src/main/java/**</include>
            <include>src/test/java/**</include>
          </includes>
        </configuration>
        <executions>
          <execution>
            <phase>validate</phase>
            <goals>
              <goal>format</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.3.1</version>
        <configuration>
          <archive>
            <manifestEntries>
              <Automatic-Module-Name>fm.last.moji</Automatic-Module-Name>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
Dokku-Alt Server Setup
======================

This is a set of `Ansible <http://docs.ansible.com/>`_ playbooks to provision a
`Dokku <https://github.com/progrium/dokku>`_ server running for my
own personal PAAS.

These won't work out of the box for provisioning your own server but you
are welcome to fork and adapt them to your own needs under the BSD License. See the
`LICENSE <https://github.com/mlavin/dokku-playbooks/blob/master/LICENSE>`_ file for more details.

Example Usage
---------------------

To get started you must install the requirements::

    $ mkvirtualenv -p /usr/bin/python2.7 dokku-playbooks
    (dokku-playbooks) $ pip install -r requirements.txt

The original bootstraping of a fresh server involves only creating a non-root
user with password-less sudo associated with my SSH key::

    (dokku-playbooks) $ ansible-playbook bootstrap.yml -i hosts.ini -u root --ask-pass

Once that initial user is created you will no longer need to connect as root. In fact
once you have run the playbook for the first time you will not longer be allowed
to connect as root::

    (dokku-playbooks) $ ansible-playbook -i hosts.ini site.yml

This will install and configure a few base packages as well as finally Docker
and Dokku-Alt. To add an admin user for Dokku you need to send the SSH key to
the ``dokku access:add`` command::

    (dokku-playbooks) $ cat ~/.ssh/id_rsa.pub | ssh <ip> "sudo sshcommand acl-add dokku [description]"

The tasks are tagged so that only parts of the deployment can be run such as::

    (dokku-playbooks) $ ansible-playbook -i hosts.ini site.yml --tags "packages,security"

To see the list of available tags you'll have to read through the playbooks.


text:
// #region License
//
//
//
// #endregion

using System;
using System.Runtime.Serialization;

namespace Pickles.UserInterface.Settings
{
    [DataContract(Name = "pickles", Namespace = "")]
    public class MainModel
    {
        [DataMember(Name = "featureDirectory")]
        public string FeatureDirectory { get; set; }

        [DataMember(Name = "outputDirectory")]
        public string OutputDirectory { get; set; }

        [DataMember(Name = "projectName")]
        public string ProjectName { get; set; }

        [DataMember(Name = "projectVersion")]
        public string ProjectVersion { get; set; }

        [DataMember(Name = "includeTestResults")]
        public bool IncludeTestResults { get; set; }

        [DataMember(Name = "testResultsFile")]
        public string TestResultsFile { get; set; }

        [DataMember(Name = "testResultsFormat")]
        public TestResultsFormat TestResultsFormat { get; set; }

        [DataMember(Name = "documentationFormats")]
        public DocumentationFormat[] DocumentationFormats { get; set; }

        [DataMember(Name = "selectedLanguageLcid")]
        public int SelectedLanguageLcid { get; set; }
    }
}


text:
<link href="../../../../admin_assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

          <?php
			 $lock_amt = $this->users->get_locking_amount();
			//  print_r($lock_amt);
			   $wallet_amount = $this->users->get_wallet_amount($this->session->userdata('user_id'),$this->session->userdata('role_id'));
			   if( $this->session->userdata('role_id') == 6 )
			   {
				   $netamt = $wallet_amount - $lock_amt["agent"];
			   }
			   else if( $this->session->userdata('role_id') == 2 )
			   {
				   $netamt = $wallet_amount - $lock_amt["channel_partner"];
			   }
			   else if( $this->session->userdata('role_id') == 5 )
			   {
				   $netamt = $wallet_amount - $lock_amt["smd"];
			   }
			   $netamt1 = number_format($netamt,2);

			   $user_id=$this->session->userdata('user_id');
$role_id=$this->session->userdata('role_id');
$userlist = $this->users->get_users_list($user_id);
$wallet_amount = $this->users->get_wallet_amount($user_id,$role_id);

			   if( $this->session->userdata('rcAmount') >  $netamt && true )
			   {
				?>

				Please Pay pending amount INR . <?php echo abs($wallet_amount);?> to avail the services.
				</div
				<?php
			   }
			   else
			   {
		  echo form_open('Recharge/paymenttype','method="post"')?>

            <input type="hidden" value="<?=$this->session->userdata('recharge_session_key')?>" name="recharge_proceed" />
            <input type="hidden"  name="mobile_no" value="<?=$this->session->userdata('mobile_no')?>" />
            <input type="hidden"  name="operator" value="<?=$this->session->userdata('operator')?>" />
            <input type="hidden"  name="operator_circle" value="<?=$this->session->userdata('operator_circle')?>" />
            <input type="hidden"  name="rcAmount" value="<?=$this->session->userdata('rcAmount')?>" />
            <input type="hidden"  name="recharge_type" value="<?=$this->session->userdata('recharge_type')?>" />
            <input type="hidden"  name="operator_name" value="<?=$this->session->userdata('operator_name')?>" />
            <input type="hidden"  name="mark_credit" value="<?=$this->session->userdata('mark_credit')?>" />
            <input type="hidden"  name="mark_credit_text" value="<?=$this->session->userdata('mark_credit_text')?>" />

Recharge of
              <?=$this->session->userdata('operator_name')?>

              <?=$this->session->userdata('recharge_type')?>
              mobile
              <?=$this->session->userdata('mobile_no')?>
               for RS.
              <?=$this->session->userdata('rcAmount');

			  //print_r($this->session->userdata());
			  ?>

              <input type="text" class="form-control" name="couponCode" placeholder="Have a Promo code">

Apply

            	<button type="submit" class="btn btn-info" id="proceed">Proceed to pay Rs. <?=$this->session->userdata('rcAmount')?></button>

          </form>
			   <?php }
			   ?>


text:
<?php
/**
 * User: Joe Linn
 * Date: 3/24/2014
 * Time: 12:10 PM
 */

namespace Stripe\Tests\Api;

use Stripe\Request\ListRequest;
use Stripe\Api\Customers;
use Stripe\Request\Customers\CreateCustomerRequest;
use Stripe\Request\Customers\UpdateCustomerRequest;
use Stripe\Tests\StripeTestCase;

class CustomersTest extends StripeTestCase
{
    /**
     * @var Customers
     */
    protected $customers;

    protected function setUp()
    {
        parent::setUp();
        $this->customers = new Customers($this->client);
    }

    public function testCreateCustomer()
    {
        $balance = -500;
        $description = "testing";
        //$taxRate = 12.3;
        $request = new CreateCustomerRequest();
        $request->setAccountBalance($balance)->setDescription($description);
            //->setTaxPercent($taxRate);
        $response = $this->customers->createCustomer($request);

        $this->assertInstanceOf(Customers::CUSTOMER_RESPONSE_CLASS, $response);
        $this->assertEquals($balance, $response->getAccountBalance());
        $this->assertEquals($description, $request->getDescription());
        //$this->assertEquals($taxRate, $request->getTaxPercent());

        $this->client->delete('customers/' . $response->getId());
    }

    public function testGetCustomer()
    {
        $createResponse = $this->customers->createCustomer();
        $getResponse = $this->customers->getCustomer($createResponse->getId());

        $this->assertInstanceOf(Customers::CUSTOMER_RESPONSE_CLASS, $getResponse);
        $this->assertEquals($createResponse->getId(), $getResponse->getId());

        $this->client->delete('customers/' . $getResponse->getId());
    }

    public function testUpdateCustomer()
    {
        $createResponse = $this->customers->createCustomer();

        $email = "foo@bar.com";
        $description = "a test client";
        $request = new UpdateCustomerRequest();
        $request->setEmail($email)->setDescription($description);
        $updateResponse = $this->customers->updateCustomer($createResponse->getId(), $request);

        $this->assertInstanceOf(Customers::CUSTOMER_RESPONSE_CLASS, $updateResponse);
        $this->assertEquals($email, $updateResponse->getEmail());
        $this->assertEquals($description, $updateResponse->getDescription());

        $this->client->delete('customers/' . $updateResponse->getId());
    }

    public function testDeleteCustomer()
    {
        $createResponse = $this->customers->createCustomer();
        $deleteResponse = $this->customers->deleteCustomer($createResponse->getId());

        $this->assertInstanceOf(Customers::DELETE_RESPONSE_CLASS, $deleteResponse);
        $this->assertTrue($deleteResponse->getDeleted());
        $this->assertEquals($createResponse->getId(), $deleteResponse->getId());
    }

    public function testListCustomers()
    {
        $customer1 = $this->customers->createCustomer();
        $customer2 = $this->customers->createCustomer();
        $this->customers->createCustomer();
        $this->customers->createCustomer();

        $request = new ListRequest();
        $request->setLimit(2);
        $list = $this->customers->listCustomers($request);

        $this->assertInstanceOf(Customers::LIST_CUSTOMERS_RESPONSE_CLASS, $list);
        $this->assertEquals(2, sizeof($list->getData()));

        $this->customers->deleteCustomer($customer1->getId());
        $this->customers->deleteCustomer($customer2->getId());
    }
}


text:
<?php

namespace PUGX\Badge\Model;

class Badge
{
    CONST DEFAULT_FORMAT = 'svg';
    private $subject;
    private $status;
    private $color;
    private $format;

    public function __construct($subject, $status, $color, $format = self::DEFAULT_FORMAT)
    {
        $this->subject = $this->escapeValue($subject);
        $this->status  = $this->escapeValue($status);
        $this->format  = $this->escapeValue($format);
        $this->color   = $color;

        if (!$this->isValidColorHex($this->color)) {
            throw new \InvalidArgumentException(sprintf('Color not valid %s', $this->color));
        }
    }

    /**
     * @return string the Hexadecimal #FFFFFF.
     */
    public function getHexColor()
    {
        return '#'.$this->color;
    }

    /**
     * @return string the format of the image eg. `svg`.
     */
    public function getFormat()
    {
        return $this->format;
    }

    /**
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @return string
     */
    public function getSubject()
    {
        return $this->subject;
    }

    public function __toString()
    {
        return sprintf("%s-%s-%s.%s",
            $this->subject,
            $this->status,
            $this->color,
            $this->format
        );
    }

    private function escapeValue($value)
    {
        $pattern = array(
            // '/([^_])_([^_])/g', // damn it global doesn't work in PHP
            '/([^_])_$/',
            '/^_([^_])/',
            '/__/',
            '/--+/',
        );
        $replacement = array(
            //'$1 $2',
            '$1 ',
            ' $1',
            '°§*¼',
            '-',
        );
        $ret = preg_replace($pattern, $replacement, $value);
        $ret = str_replace('_', ' ', $ret);    // this fix the php pgrep_replace is not global :(
        $ret = str_replace('°§*¼', '_', $ret); // this fix the php pgrep_replace is not global :(

        return $ret;
    }

    private function isValidColorHex($color)
    {
        $color = ltrim($color, "#");
        $regex = '/^[0-9a-fA-F]{6}$/';

        return preg_match($regex, $color);
    }
}


text:
layout: post
title: Hot German Mom Teaches Boy
titleinfo: pornvd
desc: Watch Hot German Mom Teaches Boy. Pornhub is the ultimate xxx porn and sex site.
---

Hot German Mom Teaches Boy

Watch Hot German Mom Teaches Boy. Pornhub is the ultimate xxx porn and sex site.


text:
import pandas as pd
import matplotlib.pyplot as plt
import sys
import numpy as np

def tradeBracket(price,entryBar,upper=None, lower=None, timeout=None):
    '''
    trade a  bracket on price series, return price delta and exit bar #
    Input
    ------
        price : numpy array of price values
        entryBar: entry bar number, *determines entry price*
        upper : high stop
        lower : low stop
        timeout : max number of periods to hold

    Returns exit price  and number of bars held

    '''
    assert isinstance(price, np.ndarray) , 'price must be a numpy array'

    # create list of exit indices and add max trade duration. Exits are relative to entry bar
    if timeout: # set trade length to timeout or series length
        exits = [min(timeout,len(price)-entryBar-1)]
    else:
        exits = [len(price)-entryBar-1]

    p = price[entryBar:entryBar+exits[0]+1] # subseries of price

    # extend exits list with conditional exits
    # check upper bracket
    if upper:
        assert upper>p[0] , 'Upper bracket must be higher than entry price '
        idx = np.where(p>upper)[0] # find where price is higher than the upper bracket
        if idx.any():
            exits.append(idx[0]) # append first occurence
    # same for lower bracket
    if lower:
        assert lower<p[0] , 'Lower bracket must be lower than entry price '
        idx = np.where(p<lower)[0]
        if idx.any():
            exits.append(idx[0])

    exitBar = min(exits) # choose first exit

    return p[exitBar], exitBar

class Backtest(object):
    """
    Backtest class, simple vectorized one. Works with pandas objects.
    """

    def __init__(self,price, signal, signalType='capital', initialCash = 0, roundShares=True):
        """
        Arguments:

        *price*  Series with instrument price.
        *signal* Series with capital to invest (long+,short-) or number of shares.
        *sitnalType* capital to bet or number of shares 'capital' mode is default.
        *initialCash* starting cash.
        *roundShares* round off number of shares to integers

        """

        #TODO: add auto rebalancing

        # check for correct input
        signal_choices = ['capital','shares', "orders"]
        assert signalType in signal_choices, "Wrong signal type provided, must be %s" %' or '.join(signal_choices)

        #save internal settings to a dict
        self.settings = {'signalType':signalType}

        # first thing to do is to clean up the signal, removing nans and duplicate entries or exits
        self.signal = signal.ffill().fillna(0)

        # now find dates with a trade
        if signalType in ('shares', 'capital'):
            self.trades = self.signal.diff().fillna(0)
            tradeIdx = self.trades != 0 # days with trades are set to True
            if signalType == 'capital':
                self.trades = (self.signal[tradeIdx]/price[tradeIdx]).reindex(self.data.index).ffill().fillna(0)
            if roundShares:
                self.trades = self.trades.round()
        elif signalType == 'orders':
            self.trades = self.signal

        # now create internal data structure
        self.data = pd.DataFrame(index=price.index , columns = ['trades','price','shares','value','cash','total','pnl'])
        self.data['price'] = price
        self.data['trades'] = self.trades
        self.data['shares'] = self.trades.cumsum()
        self.data['value'] = self.data['shares'] * self.data['price']

        delta = self.data['shares'].diff() # shares bought sold

        self.data['cash'] = (-delta*self.data['price']).fillna(0).cumsum()+initialCash
        self.data['pnl'] = self.data['cash']+self.data['value']-initialCash
        self.data['total'] = self.data['cash']+self.data['value']

    @property
    def sharpe(self):
        ''' return annualized sharpe ratio of the pnl '''
        pnl = (self.data['pnl'].diff()).shift(-1)[self.data['shares']!=0] # use only days with position.
        return sharpe(pnl)  # need the diff here as sharpe works on daily returns.

    @property
    def pnl(self):
        '''easy access to pnl data column '''
        return self.data['pnl']

    def plotTrades(self, name=''):
        """
        visualise trades on the price chart
            long entry : green triangle up
            short entry : red triangle down
            exit : black circle
        """
        l = ['price']

        p = self.data['price']
        p.plot(style='x-')

        # ---plot markers
        # this works, but I rather prefer colored markers for each day of position rather than entry-exit signals
#         indices = {'g^': self.trades[self.trades > 0].index ,
#                    'ko':self.trades[self.trades == 0].index,
#                    'rv':self.trades[self.trades < 0].index}
#
#
#         for style, idx in indices.iteritems():
#             if len(idx) > 0:
#                 p[idx].plot(style=style)

        # --- plot trades
        #colored line for long positions
        idx = (self.data['shares'] > 0) | (self.data['shares'] > 0).shift(1)
        if idx.any():
            p[idx].plot(style='go')
            l.append('long')

        #colored line for short positions
        idx = (self.data['shares'] < 0) | (self.data['shares'] < 0).shift(1)
        if idx.any():
            p[idx].plot(style='ro')
            l.append('short')

        plt.xlim([p.index[0],p.index[-1]]) # show full axis

        plt.legend(l,loc='best')
        plt.title('trades for %s' %name)

class ProgressBar:
    def __init__(self, iterations):
        self.iterations = iterations
        self.prog_bar = '[]'
        self.fill_char = '*'
        self.width = 50
        self.__update_amount(0)

    def animate(self, iteration):
        print '\r',self,
        sys.stdout.flush()
        self.update_iteration(iteration + 1)

    def update_iteration(self, elapsed_iter):
        self.__update_amount((elapsed_iter / float(self.iterations)) * 100.0)
        self.prog_bar += '  %d of %s complete' % (elapsed_iter, self.iterations)

    def __update_amount(self, new_amount):
        percent_done = int(round((new_amount / 100.0) * 100.0))
        all_full = self.width - 2
        num_hashes = int(round((percent_done / 100.0) * all_full))
        self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
        pct_place = (len(self.prog_bar) // 2) - len(str(percent_done))
        pct_string = '%d%%' % percent_done
        self.prog_bar = self.prog_bar[0:pct_place] + \
            (pct_string + self.prog_bar[pct_place + len(pct_string):])
    def __str__(self):
        return str(self.prog_bar)

def sharpe(pnl):
    return  np.sqrt(250)*pnl.mean()/pnl.std()


text:
layout: default
category: producers
title: "IBM Data Server Gateway for OData"
link: "https://www.ibm.com/developerworks/community/blogs/96960515-2ea1-4391-8170-b0515d08e4da/entry/IBM_Data_Server_Gateway_for_OData_Version_1_0_0"
---
IBM Data Server Gateway for OData enables you to quickly create OData RESTful services to query and update data in IBM DB2 LUW.


text:
@class NSData, NSURL;

@interface _IDELocalizationWriteStringsContext : IDELocalizationWorkContext <IDELocalizationWorkWriteData>
{
    NSURL *IDELocalizationWork_url;
    NSData *IDELocalizationWork_data;
}

@property(retain) NSData *IDELocalizationWork_data; // @synthesize IDELocalizationWork_data;
@property(retain) NSURL *IDELocalizationWork_url; // @synthesize IDELocalizationWork_url;
- (void).cxx_destruct;

@end


text:
Troubleshooting
===============

This section is about some of the problems you may encounter and
how to solve these problems.

Docker
------

Pillow
~~~~~~

If you want to install ``Pillow`` that you should
add this to dockerfile and rebuild image:

- ``RUN apk add jpeg-dev zlib-dev``
- ``LIBRARY_PATH=/lib:/usr/lib /bin/sh -c "poetry install ..."``

See `<https://github.com/python-pillow/Pillow/issues/1763>`_

Root owns build artifacts
~~~~~~~~~~~~~~~~~~~~~~~~~

This happens on some systems.
It happens because build happens in ``docker`` as the ``root`` user.
The fix is to pass current ``UID`` to ``docker``.
See `<https://github.com/wemake-services/wemake-django-template/issues/345>`_.

MacOS performance
~~~~~~~~~~~~~~~~~

If you use the MacOS you
know that you have problems with disk performance.
Starting and restarting an application is slower than with Linux
(it's very noticeable for project with large codebase).
For particular solve this problem add ``:delegated`` to each
your volumes in ``docker-compose.yml`` file.

.. code:: yaml

  volumes:
    - pgdata:/var/lib/postgresql/data:delegated

For more information, you can look at the
`docker documents <https://docs.docker.com/docker-for-mac/osxfs-caching/>`_
and a good `article <https://medium.com/@TomKeur/how-get-better-disk-performance-in-docker-for-mac-2ba1244b5b70>`_.


text:
package tetrismina.client.ui.game;

import java.util.Random;

public class BlockFactory {
	private BlockFactory() {

	}

	public static final Block getNextBlock() {
		Block[] blocks = Block.values();
		int total = blocks.length;
		int index = new Random().nextInt(total);
		return blocks[index];
	}
}


text:
/*!
	\file InstructionTraceGenerator.cpp
	\author Andrew Kerr <arkerr@gatech.edu>
	\date date Jan 5, 2010
	\brief captures static and dynamic instruction counts
*/

// C++ stdlib includes
#include <fstream>

// Ocelot includes
#include <ocelot/executive/interface/ExecutableKernel.h>
#include <ocelot/ir/interface/Module.h>
#include <ocelot/executive/interface/EmulatedKernel.h>
#include <ocelot/trace/interface/TraceEvent.h>
#include <traces/interface/InstructionTraceGenerator.h>

// Hydrazine includes
#include <hydrazine/interface/Exception.h>
#include <hydrazine/interface/debug.h>
#include <hydrazine/interface/macros.h>

// Boost includes
#include <boost/filesystem.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#ifdef REPORT_BASE
#undef REPORT_BASE
#endif

#define REPORT_BASE 1

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::InstructionTraceGenerator::InstructionCounter::InstructionCounter():
	dynamic_count(0), static_count(0), activity(0) {
}

void trace::InstructionTraceGenerator::InstructionCounter::count(
	const ir::PTXInstruction &instr, size_t active) {

	++dynamic_count;
	activity += (double)active;
}

trace::InstructionTraceGenerator::InstructionCounter &
	trace::InstructionTraceGenerator::InstructionCounter::operator+=( const InstructionCounter &counter) {

	dynamic_count += counter.dynamic_count;
	static_count += counter.static_count;
	activity += counter.activity;

	return *this;
}

//////////////////////////////////////////////////////////////////////////////////////////////////

const char * trace::InstructionTraceGenerator::toString(FunctionalUnit fu) {
	switch (fu) {
		case Integer_arithmetic:	//! integer arithmetic
			return "Integer_arithmetic";
		case Integer_logical:		//! itneger logical
			return "Integer_logical";
		case Integer_comparison:	//! comparison
			return "Integer_comparison";
		case Float_single:				//! floating-point single-precision
			return "Float_single";
		case Float_double:				//! floating-point, double-precision
			return "Float_double";
		case Float_comparison:		//! floating-point comparison
			return "Float_comparison";
		case Memory_offchip:			//! off-chip: {global, local}
			return "Memory_offchip";
		case Memory_onchip:			//! cached or scratchpad: {texture, shared, constant}
			return "Memory_onchip";
		case Control:						//! control-flow instructions
			return "Control";
		case Parallelism:				//! parallelism: sync, reduction, vote
			return "Parallelism";
		case Special:						//! transcendental and special functions
			return "Special";
		case Other:							//! not categorized
			return "Other";
		default:
			return "FunctionalUnit_invalid";
	}
}

/*!
	\brief gets the functional unit associated with a particular PTXInstruction
	\param instr PTXInstruction instance
	\return functional unit
*/
trace::InstructionTraceGenerator::FunctionalUnit trace::InstructionTraceGenerator::getFunctionalUnit(
	const ir::PTXInstruction &instr) {

	// switch warning: many fall-through cases follow - code blocks not listed in braces are suspect
	switch (instr.opcode) {

	// Arithmetic
	case ir::PTXInstruction::Abs:
	case ir::PTXInstruction::Add:
	case ir::PTXInstruction::AddC:
	case ir::PTXInstruction::Cvt:
	case ir::PTXInstruction::Cvta:
	case ir::PTXInstruction::Div:
	case ir::PTXInstruction::Fma:
	case ir::PTXInstruction::Mad24:
	case ir::PTXInstruction::Mad:
	case ir::PTXInstruction::Max:
	case ir::PTXInstruction::Min:
	case ir::PTXInstruction::Mov:
	case ir::PTXInstruction::Mul24:
	case ir::PTXInstruction::Mul:
	case ir::PTXInstruction::Neg:
	case ir::PTXInstruction::Rcp:
	case ir::PTXInstruction::Rem:
	case ir::PTXInstruction::Sad:
	case ir::PTXInstruction::Sub:
		{
			switch (instr.type) {
				case ir::PTXOperand::b8:
				case ir::PTXOperand::b16:
				case ir::PTXOperand::b32:
				case ir::PTXOperand::b64:
				case ir::PTXOperand::s8:
				case ir::PTXOperand::s16:
				case ir::PTXOperand::s32:
				case ir::PTXOperand::s64:
				case ir::PTXOperand::u8:
				case ir::PTXOperand::u16:
				case ir::PTXOperand::u32:
				case ir::PTXOperand::u64:
					{
						return Integer_arithmetic;
					}
				case ir::PTXOperand::f32:
					{
						return Float_single;
					}
				case ir::PTXOperand::f64:
					{
						return Float_double;
					}
				default:
					return FunctionalUnit_invalid;
			}
		}
		break;

	// Logical
	case ir::PTXInstruction::And:
	case ir::PTXInstruction::CNot:
	case ir::PTXInstruction::Not:
	case ir::PTXInstruction::Or:
	case ir::PTXInstruction::Shl:
	case ir::PTXInstruction::Shr:
	case ir::PTXInstruction::Xor:
		{
			switch (instr.type) {
				case ir::PTXOperand::b8:
				case ir::PTXOperand::b16:
				case ir::PTXOperand::b32:
				case ir::PTXOperand::b64:
				case ir::PTXOperand::s8:
				case ir::PTXOperand::s16:
				case ir::PTXOperand::s32:
				case ir::PTXOperand::s64:
				case ir::PTXOperand::u8:
				case ir::PTXOperand::u16:
				case ir::PTXOperand::u32:
				case ir::PTXOperand::u64:
					{
						return Integer_logical;
					}
				default:
					return FunctionalUnit_invalid;
			}
		}
		break;

	// Comparison
	case ir::PTXInstruction::SetP:
	case ir::PTXInstruction::Set:
	case ir::PTXInstruction::SlCt:
	case ir::PTXInstruction::SelP:
		{
			switch (instr.type) {
				case ir::PTXOperand::f32:
				case ir::PTXOperand::f64:
					{
						return Float_comparison;
					}

				case ir::PTXOperand::b8:
				case ir::PTXOperand::b16:
				case ir::PTXOperand::b32:
				case ir::PTXOperand::b64:
				case ir::PTXOperand::s8:
				case ir::PTXOperand::s16:
				case ir::PTXOperand::s32:
				case ir::PTXOperand::s64:
				case ir::PTXOperand::u8:
				case ir::PTXOperand::u16:
				case ir::PTXOperand::u32:
				case ir::PTXOperand::u64:
					{
						return Integer_comparison;
					}
				default:
					break;
			}
		}
		break;

	// Transcendental and other special
	case ir::PTXInstruction::Cos:
	case ir::PTXInstruction::Ex2:
	case ir::PTXInstruction::Lg2:
	case ir::PTXInstruction::Rsqrt:
	case ir::PTXInstruction::Sqrt:
	case ir::PTXInstruction::Sin:
		{
			switch (instr.type) {
				case ir::PTXOperand::f32:
				case ir::PTXOperand::f64:
					{
						return Special;
					}
				default:
					return FunctionalUnit_invalid;
			}
		}
		break;

	// Memory
	case ir::PTXInstruction::Atom:
	case ir::PTXInstruction::Ld:
	case ir::PTXInstruction::Ldu:
	case ir::PTXInstruction::Membar:
	case ir::PTXInstruction::Tex:
	case ir::PTXInstruction::St:
		{
			switch (instr.addressSpace) {
				case ir::PTXInstruction::Global:
				case ir::PTXInstruction::Local:
				{
					return Memory_offchip;
				}

				default:
				{
					return Memory_onchip;
				}
			}
		}
		break;

	// Parallelism
	case ir::PTXInstruction::Bar:
	case ir::PTXInstruction::Red:
	case ir::PTXInstruction::Vote:
		{
			return Parallelism;
		}
		break;

	// Control flow
	case ir::PTXInstruction::Bra:
	case ir::PTXInstruction::Call:
	case ir::PTXInstruction::Exit:
	case ir::PTXInstruction::Reconverge:
	case ir::PTXInstruction::Ret:
		{
			return Control;
		}
		break;

	// this should be an exhaustive list!
	default:
		break;
	}

	std::stringstream ss;
	ss << "InstructionTraceGenerator - PTX instruction not supported: "
		<< ir::PTXInstruction::toString(instr.opcode);
	throw hydrazine::Exception(ss.str());
}

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::InstructionTraceGenerator::Header::Header():
	format(trace::TraceGenerator::InstructionTraceFormat), total_dynamic(0), total_static(0) {

}

//////////////////////////////////////////////////////////////////////////////////////////////////

unsigned int trace::InstructionTraceGenerator::_counter = 0;

/*!
	default constructor
*/
trace::InstructionTraceGenerator::InstructionTraceGenerator() {

}

/*!
	\brief destructs instruction trace generator
*/
trace::InstructionTraceGenerator::~InstructionTraceGenerator() {

}

/*!
	\brief called when a traced kernel is launched to retrieve some
		parameters from the kernel
*/
void trace::InstructionTraceGenerator::initialize(
	const executive::ExecutableKernel& kernel) {
	//
	// initialize kernel entry
	//
	_entry.name = kernel.name;
	_entry.module = kernel.module->path();
	_entry.format = InstructionTraceFormat;

	std::string name = kernel.name;

	if( name.size() > 20 ) name.resize( 20 );

	std::stringstream stream;
	stream << _entry.format << "_" << _counter++;

	boost::filesystem::path path( database );

	path = path.parent_path();
	path /= _entry.program + "_" + name + "_" + stream.str() + ".header";
	path = boost::filesystem::system_complete( path );

	_entry.header = path.string();

	_header.format = InstructionTraceFormat;

	// static counts
	const executive::EmulatedKernel &emuKernel =
		static_cast<const executive::EmulatedKernel &>(kernel);

	_header.blockDim = emuKernel.blockDim();
	_header.gridDim = emuKernel.gridDim();

	threadCount = _header.blockDim.x * _header.blockDim.y * _header.blockDim.z;

	instructionCounter.clear();
	for (executive::EmulatedKernel::PTXInstructionVector::const_iterator instr_it =
		emuKernel.instructions.begin();
		instr_it != emuKernel.instructions.end(); ++instr_it ) {

		const ir::PTXInstruction & instr = *instr_it;

		FunctionalUnit fu = getFunctionalUnit(instr);
		if (instructionCounter.find(fu) == instructionCounter.end()) {
			OpcodeCountMap opMap;
			instructionCounter[fu] = opMap;
		}
		if (instructionCounter[fu].find(instr.opcode) == instructionCounter[fu].end()) {
			InstructionCounter counter;
			instructionCounter[fu][instr.opcode] = counter;
		}

		++instructionCounter[fu][instr.opcode].static_count;
	}
}

/*!
	\brief Called whenever an event takes place.

	Note, the const reference 'event' is only valid until event()
	returns
*/
void trace::InstructionTraceGenerator::event(const TraceEvent & event) {
	// every instruction we encounter is guaranteed to be mapped to in the instructionCounter
	// data structure
	FunctionalUnit fu = getFunctionalUnit(*event.instruction);
	instructionCounter[fu][event.instruction->opcode].count(*event.instruction,
		event.active.count());
}

/*!
	\brief Called when a kernel is finished. There will be no more
		events for this kernel.
*/
void trace::InstructionTraceGenerator::finish() {
	//
	// stream to file
	//
	_entry.updateDatabase( database );

	std::ofstream hfile( _entry.header.c_str() );
	boost::archive::text_oarchive harchive( hfile );

	if(!hfile.is_open()) {

		throw hydrazine::Exception(
			"Failed to open InstructionTraceGenerator header file "
			+ _entry.header );
	}

	// visit every instruction counter and divide activity by thread count
	if (threadCount) {
		for (FunctionalUnitCountMap::iterator fu_it = instructionCounter.begin();
			fu_it != instructionCounter.end(); ++fu_it) {

			for (OpcodeCountMap::iterator oc_it = fu_it->second.begin(); oc_it != fu_it->second.end();
				++oc_it) {

	//			if (threadCount != 0 && oc_it->second.dynamic_count != 0) {
	//				oc_it->second.activity /= (double)threadCount * (double)oc_it->second.dynamic_count;
	//			}
	//			else {
	//				oc_it->second.activity = 0;
	//			}
				oc_it->second.dynamic_count *= threadCount;
			}
		}
	}

	harchive << _header;
	harchive << instructionCounter;

	hfile.close();
}

//////////////////////////////////////////////////////////////////////////////////////////////////


text:
		<title>PxTriangleMeshGeometry.h File Reference</title>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<LINK HREF="NVIDIA.css" REL="stylesheet" TYPE="text/css">

				Main Page
				Class Hierarchy
				Compound List
				Compound Members

Include

geometry

Classes |
Typedefs

PxTriangleMeshGeometry.h File Reference

#include "geometry/PxGeometry.h"

#include "geometry/PxMeshScale.h"

#include "common/PxCoreUtilityTypes.h"

This graph shows which files directly or indirectly include this file:

<map name="PxTriangleMeshGeometry_8hdep" id="PxTriangleMeshGeometry_8hdep">
</map>

Go to the source code of this file.

Classes

struct  	PxMeshGeometryFlag

 	Some flags to control the simulated behavior of the mesh geometry.  More...

class  	PxTriangleMeshGeometry

 	Triangle mesh geometry class.  More...

Typedefs

typedef PxFlags

< PxMeshGeometryFlag::Enum,

PxU8 > 	PxMeshGeometryFlags

 	collection of set bits defined in PxMeshGeometryFlag.  More...

Copyright © 2008-2015 NVIDIA Corporation, 2701 San Tomas Expressway, Santa Clara, CA 95050 U.S.A. All rights reserved. www.nvidia.com


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Dynamics;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Core.Models.PublishedContent
{
    /// <summary>
    /// Represents an <see cref="IPublishedProperty"/> type.
    /// </summary>
    /// <remarks>Instances of the <see cref="PublishedPropertyType"/> class are immutable, ie
    /// if the property type changes, then a new class needs to be created.</remarks>
    public class PublishedPropertyType
    {
        public PublishedPropertyType(PublishedContentType contentType, PropertyType propertyType)
        {
            // PropertyEditor [1:n] DataTypeDefinition [1:n] PropertyType

            ContentType = contentType;
            PropertyTypeAlias = propertyType.Alias;

            DataTypeId = propertyType.DataTypeDefinitionId;
            PropertyEditorAlias = propertyType.PropertyEditorAlias;

            InitializeConverters();
        }

        // for unit tests
        internal PublishedPropertyType(string propertyTypeAlias, int dataTypeDefinitionId, string propertyEditorAlias)
        {
            // ContentType to be set by PublishedContentType when creating it
            PropertyTypeAlias = propertyTypeAlias;

            DataTypeId = dataTypeDefinitionId;
            PropertyEditorAlias = propertyEditorAlias;

            InitializeConverters();
        }

        #region Property type

        /// <summary>
        /// Gets or sets the published content type containing the property type.
        /// </summary>
        // internally set by PublishedContentType constructor
        public PublishedContentType ContentType { get; internal set; }

        /// <summary>
        /// Gets or sets the alias uniquely identifying the property type.
        /// </summary>
        public string PropertyTypeAlias { get; private set; }

        /// <summary>
        /// Gets or sets the identifier uniquely identifying the data type supporting the property type.
        /// </summary>
        public int DataTypeId { get; private set; }

        /// <summary>
        /// Gets or sets the alias uniquely identifying the property editor for the property type.
        /// </summary>
        public string PropertyEditorAlias { get; private set; }

        #endregion

        #region Converters

        private IPropertyValueConverter _converter;

        private PropertyCacheLevel _sourceCacheLevel;
        private PropertyCacheLevel _objectCacheLevel;
        private PropertyCacheLevel _xpathCacheLevel;

        private Type _clrType = typeof (object);

        private void InitializeConverters()
        {
            var converters = PropertyValueConvertersResolver.Current.Converters.ToArray();
            var defaultConvertersWithAttributes = PropertyValueConvertersResolver.Current.DefaultConverters;

            _converter = null;

            //get all converters for this property type
            // todo: remove Union() once we drop IPropertyEditorValueConverter support.
            var foundConverters = converters.Union(GetCompatConverters()).Where(x => x.IsConverter(this)).ToArray();
            if (foundConverters.Length == 1)
            {
                _converter = foundConverters[0];
            }
            else if (foundConverters.Length > 1)
            {
                //more than one was found, we need to first figure out if one of these is an Umbraco default value type converter
                //get the non-default and see if we have one
                var nonDefault = foundConverters.Except(defaultConvertersWithAttributes.Select(x => x.Item1)).ToArray();
                if (nonDefault.Length == 1)
                {
                    //there's only 1 custom converter registered that so use it
                    _converter = nonDefault[0];
                }
                else if (nonDefault.Length > 1)
                {
                    //this is not allowed, there cannot be more than 1 custom converter
                    throw new InvalidOperationException(
                        string.Format("Type '{2}' cannot be an IPropertyValueConverter"
                                      + " for property '{1}' of content type '{0}' because type '{3}' has already been detected as a converter"
                                      + " for that property, and only one converter can exist for a property.",
                                      ContentType.Alias, PropertyTypeAlias,
                                      nonDefault[1].GetType().FullName, nonDefault[0].GetType().FullName));
                }
                else
                {
                    //we need to remove any converters that have been shadowed by another converter
                    var foundDefaultConvertersWithAttributes = defaultConvertersWithAttributes.Where(x => foundConverters.Contains(x.Item1));
                    var shadowedTypes = foundDefaultConvertersWithAttributes.SelectMany(x => x.Item2.DefaultConvertersToShadow);
                    var shadowedDefaultConverters = foundConverters.Where(x => shadowedTypes.Contains(x.GetType()));
                    var nonShadowedDefaultConverters = foundConverters.Except(shadowedDefaultConverters).ToArray();

                    if (nonShadowedDefaultConverters.Length == 1)
                    {
                        //assign to the single default converter
                        _converter = nonShadowedDefaultConverters[0];
                    }
                    else if (nonShadowedDefaultConverters.Length > 1)
                    {
                        //this is not allowed, there cannot be more than 1 custom converter
                        throw new InvalidOperationException(
                            string.Format("Type '{2}' cannot be an IPropertyValueConverter"
                                          + " for property '{1}' of content type '{0}' because type '{3}' has already been detected as a converter"
                                          + " for that property, and only one converter can exist for a property.",
                                          ContentType.Alias, PropertyTypeAlias,
                                          nonShadowedDefaultConverters[1].GetType().FullName, nonShadowedDefaultConverters[0].GetType().FullName));
                    }
                }

            }

            // get the cache levels, quietely fixing the inconsistencies (no need to throw, really)
            _sourceCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Source);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Object);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.XPath);
            if (_objectCacheLevel < _sourceCacheLevel) _objectCacheLevel = _sourceCacheLevel;
            if (_xpathCacheLevel < _sourceCacheLevel) _xpathCacheLevel = _sourceCacheLevel;

            if (_converter != null)
            {
                var attr = _converter.GetType().GetCustomAttribute<PropertyValueTypeAttribute>(false);
                if (attr != null)
                    _clrType = attr.Type;
            }
        }

        static PropertyCacheLevel GetCacheLevel(IPropertyValueConverter converter, PropertyCacheValue value)
        {
            if (converter == null)
                return PropertyCacheLevel.Request;

            var attr = converter.GetType().GetCustomAttributes<PropertyValueCacheAttribute>(false)
                .FirstOrDefault(x => x.Value == value || x.Value == PropertyCacheValue.All);

            return attr == null ? PropertyCacheLevel.Request : attr.Level;
        }

        // converts the raw value into the source value
        // uses converters, else falls back to dark (& performance-wise expensive) magic
        // source: the property raw value
        // preview: whether we are previewing or not
        public object ConvertDataToSource(object source, bool preview)
        {
            // use the converter else use dark (& performance-wise expensive) magic
            return _converter != null
                ? _converter.ConvertDataToSource(this, source, preview)
                : ConvertUsingDarkMagic(source);
        }

        // gets the source cache level
        public PropertyCacheLevel SourceCacheLevel { get { return _sourceCacheLevel; } }

        // converts the source value into the clr value
        // uses converters, else returns the source value
        // source: the property source value
        // preview: whether we are previewing or not
        public object ConvertSourceToObject(object source, bool preview)
        {
            // use the converter if any
            // else just return the source value
            return _converter != null
                ? _converter.ConvertSourceToObject(this, source, preview)
                : source;
        }

        // gets the value cache level
        public PropertyCacheLevel ObjectCacheLevel { get { return _objectCacheLevel; } }

        // converts the source value into the xpath value
        // uses the converter else returns the source value as a string
        // if successful, returns either a string or an XPathNavigator
        // source: the property source value
        // preview: whether we are previewing or not
        public object ConvertSourceToXPath(object source, bool preview)
        {
            // use the converter if any
            if (_converter != null)
                return _converter.ConvertSourceToXPath(this, source, preview);

            // else just return the source value as a string or an XPathNavigator
            if (source == null) return null;
            var xElement = source as XElement;
            if (xElement != null)
                return xElement.CreateNavigator();
            return source.ToString().Trim();
        }

        // gets the xpath cache level
        public PropertyCacheLevel XPathCacheLevel { get { return _xpathCacheLevel; } }

        internal static object ConvertUsingDarkMagic(object source)
        {
            // convert to string
            var stringSource = source as string;
            if (stringSource == null) return source; // not a string => return the object
            stringSource = stringSource.Trim();
            if (stringSource.Length == 0) return null; // empty string => return null

            // try numbers and booleans
            // make sure we use the invariant culture ie a dot decimal point, comma is for csv
            // NOTE far from perfect: "01a" is returned as a string but "012" is returned as an integer...
            int i;
            if (int.TryParse(stringSource, NumberStyles.Integer, CultureInfo.InvariantCulture, out i))
                return i;
            float f;
            if (float.TryParse(stringSource, NumberStyles.Float, CultureInfo.InvariantCulture, out f))
                return f;
            bool b;
            if (bool.TryParse(stringSource, out b))
                return b;

            //TODO: We can change this just like we do for the JSON converter - but to maintain compatibility might mean this still has to remain here

            // try xml - that is expensive, performance-wise
            XElement elt;
            if (XmlHelper.TryCreateXElementFromPropertyValue(stringSource, out elt))
                return new DynamicXml(elt); // xml => return DynamicXml for compatiblity's sake

            return source;
        }

        // gets the property CLR type
        public Type ClrType { get { return _clrType; } }

        #endregion

        #region Compat

        // backward-compatibility: support IPropertyEditorValueConverter while we have to
        // todo: remove once we drop IPropertyEditorValueConverter support.

        IEnumerable<IPropertyValueConverter> GetCompatConverters()
        {
            var propertyEditorGuid = LegacyPropertyEditorIdToAliasConverter.GetLegacyIdFromAlias(PropertyEditorAlias, LegacyPropertyEditorIdToAliasConverter.NotFoundLegacyIdResponseBehavior.ReturnNull);
            return PropertyEditorValueConvertersResolver.HasCurrent && propertyEditorGuid.HasValue
                ? PropertyEditorValueConvertersResolver.Current.Converters
                    .Where(x => x.IsConverterFor(propertyEditorGuid.Value, ContentType.Alias, PropertyTypeAlias))
                    .Select(x => new CompatConverter(x))
                : Enumerable.Empty<IPropertyValueConverter>();
        }

        private class CompatConverter : PropertyValueConverterBase
        {
            private readonly IPropertyEditorValueConverter _converter;

            public CompatConverter(IPropertyEditorValueConverter converter)
            {
                _converter = converter;
            }

            public override bool IsConverter(PublishedPropertyType propertyType)
            {
                return true;
            }

            public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
            {
                // NOTE: ignore preview, because IPropertyEditorValueConverter does not support it
                return _converter.ConvertPropertyValue(source).Result;
            }
        }

        #endregion
    }
}


text:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
#ifndef PXPVDSDK_PXPVDERRORCODES_H
#define PXPVDSDK_PXPVDERRORCODES_H

/** \addtogroup pvd
@{
*/

#include "foundation/Px.h"

#if !PX_DOXYGEN
namespace physx
{
namespace pvdsdk
{
#endif

struct PvdErrorType
{
	enum Enum
	{
		Success = 0,
		NetworkError,
		ArgumentError,
		Disconnect,
		InternalProblem
	};
};

typedef PvdErrorType::Enum PvdError;

#if !PX_DOXYGEN
}
}
#endif
/** @} */
#endif // PXPVDSDK_PXPVDERRORCODES_H


text:
'use strict';
const request  = require('request');
const crypto   = require('crypto');
const debug    = require('debug')('gc:load-balancer');
const bluebird = require('bluebird')
const Tools    = require('./lib/tools.js');
const defaults = require('./constants.js');

/**
 * Load balancer
 * @constructor
 */
const LoadBalancer = function(opts) {
  this._rri = 0;
  this.processing_tasks = {};
  this.stats_tasks = {};
};

function processResponse(err, data, peer) {
  if (err) {
    if (!data) data = {};
    data.err = err;
    // Will be catched by Promise.catch
    throw err;
  }

  if (typeof(data) == 'string') {
    try {
      data = JSON.parse(data);
    } catch(e) {
    }
    data.server = peer.identity;
  }
  else if (typeof(data) == 'object')
    data.server = peer.identity;
  return data;
}

/**
 * Method to find suitable peer
 * for now it only checks if peer is SYNCHRONIZED + TASKS have been started
 * @param req {object} Express req object
 */
LoadBalancer.prototype.findSuitablePeer = function(req) {
  let promise = (retry) => {
    if (retry++ > defaults.FIND_SUITABLE_PEER_RETRY) {
      return Promise.reject(new Error('Too many retries on route request while searching for a suitable peer')) ;
    }

    let peer_list = req.net_manager.getPeerList();

    if (peer_list.length === 0) {
      debug('Not any peers is synced (and local compute is not activated)');
      return bluebird.delay(500).then(() => promise(retry));
    }

    let target = peer_list[this._rri++ % peer_list.length];

    //@todo take monitoring data into account
    if (target.identity.synchronized == false) {
      return bluebird.delay(250).then(() => promise(retry));
    }

    return Promise.resolve(target)
  }

  return promise(0)
};

LoadBalancer.prototype.bumpStatTask = function(task_id) {
  // Stats about task
  if (!this.stats_tasks[task_id])
    this.stats_tasks[task_id] = {
      invokations : 1,
      success     : 0,
      errors      : 0,
      remote_invok: 0
    }
  else
    this.stats_tasks[task_id].invokations++;
};

/**
 * Find all Synchronized Peers for broadcast action
 */
LoadBalancer.prototype.findSynchronizedPeers = function(req) {
  let promise = (retry) => {
    if (retry++ > defaults.FIND_SUITABLE_PEER_RETRY) {
      return Promise.reject(new Error('Too many retries on route request while searching for a suitable peer')) ;
    }

    let peer_list  = req.net_manager.getPeerList();
    let peer_ready = [];
    if (peer_list.length === 0) {
      debug('Not any peers is synced (and local compute is not activated)');
      return bluebird.delay(500).then(() => promise(retry));
    }

    peer_list.forEach((peer) => {
      if (peer.identity.synchronized == true && !peer.local) {
        peer_ready.push(peer)
      }
    });

    //@todo take monitoring data into account
    if (peer_ready.length == 0) {
      return bluebird.delay(100).then(() => promise(retry));
    }

    return Promise.resolve(peer_ready)
  }

  return promise(0)
};

/**
 * Main function to route a one-to-one action
 * exposed on api.js as:
 * http://127.0.0.1:10000/tasks/lb_trigger_single
 *
 * @param req.body.task_id = task id (script.handler)
 * @param req.body.data    = data to be passed to the task
 * @param req.body.opts    = extra options like 'timeout'
 */
LoadBalancer.prototype.route = function(req, res, next) {
  let task_id   = req.body.task_id;
  let task_data = req.body.data || null;
  let task_opts = req.body.opts || {};
  let uuid      = crypto.randomBytes(32).toString('hex');
  let self      = this;

  // Avoid integer overflow
  if (Number.isSafeInteger(this._rri) === false) {
    this._rri = 0;
  }

  this.bumpStatTask(task_id);

  this.findSuitablePeer(req)
    .then((peer) => {

      if (req.task_manager.taskExists(task_id) == false) {
        return res.send({
          err : Tools.safeClone(new Error('Task file ' + task_id + ' does not exists'))
        });
      }

      this.processing_tasks[uuid] = {
        started_at : new Date(),
        peer_info  : peer.identity,
        task_id    : task_id
      };

      /**
       * Local Task
       */
      if (peer.local) {
        console.log('status=routing task=%s target=localhost', task_id);
        return req.task_manager.triggerTask({
          task_id  : task_id,
          task_data: task_data,
          task_opts: task_opts
        })
          .then((data) => {
            this.stats_tasks[task_id].success++;
            delete this.processing_tasks[uuid];
            data.server = req.net_manager.getLocalIdentity();
            res.send(data);
          })
          .catch((err) => {
            this.stats_tasks[task_id].errors++;
            delete this.processing_tasks[uuid];
            res.send({err: err});
          });
      }

      /**
       * Remote Task
       */
      debug('status=routing task=%s target=%s port=%s',
            task_id,
            peer.identity.public_ip,
            peer.identity.api_port);

      this.stats_tasks[task_id].remote_invok++;

      peer.send('trigger', {
        task_id   : task_id,
        task_data : task_data,
        task_opts : task_opts
      }, (err, data) => {
        delete this.processing_tasks[uuid];

        data = processResponse(err, data, peer);
        this.stats_tasks[task_id].success++;

        res.send(data);
        // @todo configure timeout for remote request
      }).timeout(defaults.REMOTE_REQUEST_TIMEOUT);
    })
    .catch(err => {
      this.stats_tasks[task_id].errors++;
      console.error(err.message || err);
      return res.send(Tools.safeClone({ err : err }));
    })
};

LoadBalancer.prototype.broadcast = function(req, res, next) {
  let task_id   = req.body.task_id;
  let task_data = req.body.data || null;
  let task_opts = req.body.opts || {};
  let uuid      = crypto.randomBytes(32).toString('hex');

  this.findSynchronizedPeers(req)
    .then((peers) => {
      var responses_nb = peers.length;

      if (req.task_manager.taskExists(task_id) == false) {
        return res.send({
          err : Tools.safeClone(new Error('Task file ' + task_id + ' does not exists'))
        }).status(500);
      }

      this.bumpStatTask(task_id);

      var the_end = setInterval(() => {
        if (responses_nb <= 0) {
          clearInterval(the_end);
          res.end();
        }
      }, 100);

      return bluebird.map(peers, (peer) => {

        this.processing_tasks[uuid] = {
          started_at : new Date(),
          peer_info  : peer.identity,
          task_id    : task_id
        };

        this.stats_tasks[task_id].remote_invok++;

        peer.send('trigger', {
          task_id   : task_id,
          task_data : task_data,
          task_opts : task_opts
        }, (err, data) => {
          responses_nb--;
          delete this.processing_tasks[uuid];

          data = processResponse(err, data, peer);
          this.stats_tasks[task_id].success++;

          res.write(JSON.stringify(data));
        }).timeout(defaults.REMOTE_REQUEST_TIMEOUT);
      }, {concurrency: 20});
    })
    .catch((e) => {
      console.error(e);
      res.send(e);
    });
};

module.exports = LoadBalancer;


text:
import diagnostic

class pfitscher_cpu:
    def __init__(self, metric_manager):
        """Form the diagnoser"""
        self.mm = metric_manager
        self.t_inuse_high = 80.0
        self.t_inuse_low = 50.0
        self.t_inuse_saturated = 20.0
        self.t_steal_high = 1.0

    def diagnose(self, interval):
        """Perform the diagnostic and return it"""
        v_inuse_mean = self.mm.get_reduced_metric('cpu',
                                                        'inuse',
                                                        ('mean', ),
                                                        interval)
        v_inuse_over = self.mm.get_reduced_metric('cpu',
                                                        'inuse',
                                                        ('over',95.0),
                                                        interval)
        v_steal_mean = self.mm.get_reduced_metric('cpu',
                                                        'steal',
                                                        ('mean', ),
                                                        interval)

        diag = diagnostic.Diagnostic(diagnoser='pfitscher_cpu',
                                     resource='cpu')

        if v_inuse_mean is None or v_steal_mean is None:
            diag.diagnostic = None
        elif v_steal_mean >= self.t_steal_high \
                or v_inuse_mean >= self.t_inuse_high:
            diag.diagnostic = diagnostic.UNDER
        elif v_inuse_mean < self.t_inuse_low \
                and v_inuse_over <= self.t_inuse_saturated:
            diag.diagnostic = diagnostic.OVER
        else:
            diag.diagnostic = diagnostic.CORRECT

        if diag.diagnostic is not None:
            diag.info = self.make_info(v_inuse_mean, v_inuse_over, v_steal_mean)
        return diag

    def make_info(self, v_inuse_mean, v_inuse_over, v_steal_mean):
        """Generate a info message to the diagnostic"""
        info = '\n    - average utilization: %.2f%%'
        info += '\n    - utilization above 95%%: %.2f%%'
        info += '\n    - average steal: %.2f%%'
        return info % (v_inuse_mean, v_inuse_over, v_steal_mean)


text:
import Carousel from '../collection';

Meteor.publish('carousels.all', function() {
  return Carousel.find();
});

Meteor.publish('carousels.one', function(id) {
  return Carousel.find({_id: id});
});


text:
require File.dirname(__FILE__) + '/../test_helper'

class BeneficiaryTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  def test_create_beneficiary
    Beneficiary.create(
      :name_first => "Samantha",
      :name_last => "Smith",
      :statement => "Samantha is saving to open her own framing business.",
      :photo => Photo.create(
        :uploaded_data => fixture_file_upload("../files/WACASH_saver1.jpg", 'image/jpg')
      )
    )
  end
end


text:
if (Meteor.absoluteUrl().indexOf('localhost') !== -1)
  Herald.settings.queueTimer = 1000;

Meteor.startup(function () {

  Herald.collection.deny({
    update: !Users.can.editById,
    remove: !Users.can.editById
  });

  // disable all email notifications when "emailNotifications" is set to false
  Herald.settings.overrides.email = !Settings.get('emailNotifications', true);

});

var commentEmail = function (userToNotify) {
  var notification = this;
  // put in setTimeout so it doesn't hold up the rest of the method
  Meteor.setTimeout(function () {
    notificationEmail = buildEmailNotification(notification);
    Telescope.email.send(Users.getEmail(userToNotify), notificationEmail.subject, notificationEmail.html);
  }, 1);
};

var getCommenterProfileUrl = function (comment) {
  var user = Meteor.users.findOne(comment.userId);
  if (user) {
    return Users.getProfileUrl(user);
  } else {
    return Users.getProfileUrlBySlugOrId(comment.userId);
  }
};

var getAuthor = function (comment) {
  var user = Meteor.users.findOne(comment.userId);
  if (user) {
    return Users.getUserName(user);
  } else {
    return comment.author;
  }
};

// ------------------------------------------------------------------------------------------- //
// -----------------------------------------  Posts ------------------------------------------ //
// ------------------------------------------------------------------------------------------- //

Herald.addCourier('newPost', {
  media: {
    email: {
      emailRunner: function (user) {
        var p = Posts.getProperties(this.data);
        var subject = p.postAuthorName+' has created a new post: '+p.postTitle;
        var html = Telescope.email.buildTemplate(Telescope.email.getTemplate('emailNewPost')(p));
        Telescope.email.send(Users.getEmail(user), subject, html);
      }
    }
  }
  // message: function (user) { return 'email template?' }
});

Herald.addCourier('newPendingPost', {
  media: {
    email: {
      emailRunner: function (user) {
        var p = Posts.getProperties(this.data);
        var subject = p.postAuthorName+' has a new post pending approval: '+p.postTitle;
        var html = Telescope.email.buildTemplate(Telescope.email.getTemplate('emailNewPendingPost')(p));
        Telescope.email.send(Users.getEmail(user), subject, html);
      }
    }
  }
});

Herald.addCourier('postApproved', {
  media: {
    onsite: {},
    email: {
      emailRunner: function (user) {
        var p = Posts.getProperties(this.data);
        var subject = 'Your post "'+p.postTitle+'" has been approved';
        var html = Telescope.email.buildTemplate(Telescope.email.getTemplate('emailPostApproved')(p));
        Telescope.email.send(Users.getEmail(user), subject, html);
      }
    }
  },
  message: {
    default: function () {
      return Blaze.toHTML(Blaze.With(this, function () {
        return Template.notification_post_approved;
      }));
    }
  },
  transform: {
    postUrl: function () {
      var p = Posts.getProperties(this.data);
      return p.postUrl;
    },
    postTitle: function () {
      var p = Posts.getProperties(this.data);
      return p.postTitle;
    }
  }
});

// ------------------------------------------------------------------------------------------- //
// ---------------------------------------- Comments ----------------------------------------- //
// ------------------------------------------------------------------------------------------- //

// specify how to get properties used in template from comment data
var commentCourierTransform = {
  profileUrl: function () {
    return getCommenterProfileUrl(this.data.comment);
  },
  postCommentUrl: function () {
    return Router.path('post_page', {_id: this.data.post._id});
  },
  author: function () {
    return getAuthor(this.data.comment);
  },
  postTitle: function () {
    return this.data.post.title;
  },
  url: function () {
    return Router.path('comment_reply', {_id: this.parentComment._id});
  }
};

Herald.addCourier('newComment', {
  media: {
    onsite: {},
    email: {
      emailRunner: commentEmail
    }
  },
  message: {
    default: function () {
      return Blaze.toHTML(Blaze.With(this, function () {
        return Template.notification_new_comment;
      }));
    }
  },
  transform: commentCourierTransform
});

Herald.addCourier('newReply', {
  media: {
    onsite: {},
    email: {
      emailRunner: commentEmail
    }
  },
  message: {
    default: function () {
      return Blaze.toHTML(Blaze.With(this, function () {
        return Template.notification_new_reply;
      }));
    }
  },
  transform: commentCourierTransform
});

Herald.addCourier('newCommentSubscribed', {
  media: {
    onsite: {},
    email: {
      emailRunner: commentEmail
    }
  },
  message: {
    default: function () {
      return Blaze.toHTML(Blaze.With(this, function () {
        return Template.notification_new_reply;
      }));
    }
  },
  transform: commentCourierTransform
});


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/ease_chatfrom_bg_focused" />
    <item android:drawable="@drawable/ease_chatfrom_bg_normal" />
</selector>


text:
using System;
using System.Net.Http;

namespace Imgur.API.RequestBuilders
{
    internal abstract class RequestBuilderBase
    {
        /// <exception cref="ArgumentNullException"></exception>
        internal HttpRequestMessage CreateRequest(HttpMethod httpMethod, string url)
        {
            if (httpMethod == null)
                throw new ArgumentNullException(nameof(httpMethod));

            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));

            return new HttpRequestMessage(httpMethod, url);
        }
    }
}