text:
#ifndef ARTNET_H
#define ARTNET_H

#include "ofMain.h"
#include "ofxNetwork.h"

// UDP specific
#define ART_NET_PORT 6454
// Opcodes
#define ART_POLL 0x2000
#define ART_DMX 0x5000
// Buffers
#define MAX_BUFFER_ARTNET 530
// Packet
#define ART_NET_ID "Art-Net\0"
#define ART_DMX_START 18

typedef struct {
    char id[8];
    char opcode[2];
    char sequence;
    char universe[2];
    char length[2];
    char data[MAX_BUFFER_ARTNET];
}_artnet_packet;

class ofxArtnetProtocol// : public ofThread
{
public:
    ofxArtnetProtocol();

    void begin();
    void begin(const char* ip);
    uint16_t read();
    void setDmxData(uint8_t* data, uint16_t size);
    void setDmxData(uint16_t index, uint8_t data);
    void send(uint8_t* data, uint16_t universe = 0, uint16_t size = 512);
    void printPacketHeader();
    void printPacketContent();

    // Return a pointer to the start of the DMX data
    inline uint8_t* getDmxFrame(void)
    {
        return artnetPacket + ART_DMX_START;
    }

    inline uint16_t getOpcode(void)
    {
        return opcode;
    }

    inline uint8_t getSequence(void)
    {
        return sequence;
    }

    inline uint16_t getUniverse(void)
    {
        return incomingUniverse;
    }

    inline uint16_t getLength(void)
    {
        return dmxDataLength;
    }

    inline void setArtDmxCallback(void (*fptr)(uint16_t universe, uint16_t length, uint8_t sequence, uint8_t* data))
    {
        artDmxCallback = fptr;
    }

private:

    ofxUDPManager udpConnection;
    _artnet_packet packet;

    uint8_t artnetPacket[MAX_BUFFER_ARTNET];
    uint16_t packetSize;
    uint16_t opcode;
    uint8_t sequence;
    uint16_t incomingUniverse;
    uint16_t dmxDataLength;
    void (*artDmxCallback)(uint16_t universe, uint16_t length, uint8_t sequence, uint8_t* data);

    char artnet_send_packet[MAX_BUFFER_ARTNET];

    bool bConnected;
};

#endif


text:
from typing import List, Set, Tuple

class TreeNode:
    """
    Нода дерева разбора шаблона.
    """
    leaf_chars = "usUS"
    non_leaf_chars = "*?w"

    def __init__(self, parent: 'TreeNode', children: List['TreeNode'], text: str, pattern_pos: int):
        """
        :param parent: родитель ноды.
        :param children: дети ноды.
        :param text: символ, соответствующий ноде.
        :param pattern_pos: позиция символа в шаблоне
        """
        self.parent = parent  # type: TreeNode
        self.children = children  # type: List[TreeNode]
        self.text = text  # type: str
        self.pattern_pos = pattern_pos  # type: int

    def get_level(self) -> int:
        """
        :return: высота ноды в дереве.
        """
        parent = self.parent
        level = 0
        while parent is not None:
            parent = parent.parent
            level += 1
        return level

    def get_next_sibling(self) -> 'TreeNode':
        """
        :return: соседняя нода справа.
        """
        siblings = self.parent.children
        index = siblings.index(self) + 1
        if index < len(siblings):
            return siblings[index]
        return None

    def get_last_child_leaf(self) -> 'TreeNode':
        """
        :return: последняя нода изе детей, которая является листом.
        """
        for child in reversed(self.children):
            if child.is_leaf():
                return child
        return None

    def is_first_leaf(self) -> bool:
        if not self.is_leaf():
            return False
        return [child for child in self.parent.children if child.is_leaf()][0] == self

    def is_last_leaf(self) -> bool:
        if not self.is_leaf():
            return False
        return [child for child in self.parent.children if child.is_leaf()][-1] == self

    def get_most_left_leaf(self) -> 'TreeNode':
        """
        :return: самый левый потомок.
        """
        node = self
        while len(node.children) != 0:
            node = node.children[0]
        assert node.is_leaf()
        return node

    def print_tree(self) -> None:
        """
        Вывод дерева с корнем в этой ноде.
        """
        stack = list()
        stack.append(self)
        while len(stack) != 0:
            current_node = stack.pop()
            print("\t" * current_node.get_level(), current_node)
            stack += current_node.children

    def is_leaf(self) -> bool:
        """
        :return: является ли нода листом дерева.
        """
        return self.text in TreeNode.leaf_chars

    def __str__(self) -> str:
        return self.text + " " + str(self.pattern_pos)

    def __repr__(self) -> str:
        return self.__str__()

    def __hash__(self):
        return hash(self.pattern_pos)

    def __eq__(self, other):
        return self.pattern_pos == other.pattern_pos

class State:
    """
    Состояние разбора.
    """
    def __init__(self, node: TreeNode, string_pos: int, strong_errors: int, weak_errors: int, pattern: str):
        """
        :param node: нода дерева, соответствующая состоянию.
        :param string_pos: позиция в сопоставляемой строке.
        :param strong_errors: количество ошибок в U и S.
        :param weak_errors: количество ошибок в u и s.
        :param pattern: шаблон - путь, до этого состояния.
        """
        self.node = node  # type: TreeNode
        self.string_pos = string_pos  # type: int
        self.strong_errors = strong_errors  # type: int
        self.weak_errors = weak_errors  # type: int
        self.pattern = pattern  # type: str

    def __str__(self) -> str:
        return str(self.node) + " " + str(self.string_pos) + " " + str(self.strong_errors) + " " + str(self.weak_errors)

    def __repr__(self) -> str:
        return self.__str__()

class PatternAnalyzer:
    """
    Сопоставлятель шаблона и строки.
    """
    def __init__(self, pattern: str, error_border: int=8):
        """
        :param error_border: граница по ошибкам.
        :param pattern: шаблон.
        """
        self.pattern = pattern  # type: str
        self.tree = self.__build_tree(pattern)  # type: TreeNode
        self.error_border = error_border

    @staticmethod
    def count_errors(pattern: str, string: str, error_border: int=8) -> Tuple[str, int, int, bool]:
        """
        :param pattern: шаблон.
        :param string: строка.
        :param error_border: граница по ошибкам.
        :return: лучший шаблон, количество сильных ошибок, количество слабых ошибок.
        """
        analyzer = PatternAnalyzer(pattern, error_border)
        return analyzer.__accept(string)

    @staticmethod
    def __build_tree(pattern: str) -> TreeNode:
        """
        Построение дерева шаблона.

        :param pattern: шаблон.
        :return: корень дерева.
        """
        root_node = TreeNode(None, list(), "R", -1)
        current_node = root_node
        for i, ch in enumerate(pattern):
            if ch == "(":
                node = TreeNode(current_node, list(), "()", i)
                current_node.children.append(node)
                current_node = node
            if ch == ")":
                node = current_node
                current_node = current_node.parent
                # Убираем бессмысленные скобки.
                if i + 1 < len(pattern) and pattern[i + 1] not in "*?":
                    current_node.children = current_node.children[:-1] + node.children
                    for child in node.children:
                        child.parent = current_node
            if ch in TreeNode.leaf_chars:
                current_node.children.append(TreeNode(current_node, list(), ch, i))
            # Заменяем скобки на нетерминалы.
            if ch in TreeNode.non_leaf_chars:
                current_node.children[-1].text = ch
                current_node.children[-1].pattern_pos = i
        return root_node

    def __accept(self, string: str) -> Tuple[str, int, int, bool]:
        """
        :param string: строка.
        :return: лучший шаблон, количество сильных ошибок, количество слабых ошибок, были ли ошибки.
        """
        current_states = [State(None, -1, 0, 0, "")]
        current_node = self.tree.get_most_left_leaf()
        for i, ch in enumerate(string):
            new_states = []
            for state in current_states:
                if state.node is not None:
                    current_node = self.__get_next_leaf(state.node)
                variants = self.__get_variants(current_node)

                # Каждый вариант - новое состояние.
                for variant in variants:
                    assert variant.is_leaf()
                    strong_errors = state.strong_errors + int(variant.text.isupper() and variant.text != ch)
                    weak_errors = state.weak_errors + int(variant.text.islower() and variant.text != ch.lower())
                    new_state = State(variant, i, strong_errors, weak_errors, state.pattern+variant.text)
                    if new_state.strong_errors + new_state.weak_errors > self.error_border:
                        continue
                    new_states.append(new_state)

            if len(new_states) == 0:
                # Можем закончить раньше, если по ошибкам порезали ветки, либо если шаблон меньше строки.
                current_states = PatternAnalyzer.__filter_states(current_states, self.tree)
                pattern, strong_errors, weak_errors = self.__get_min_errors_from_states(current_states)
                diff = (len(string) - i)
                return pattern, strong_errors + diff, weak_errors + diff, True

            current_states = new_states
        current_states = PatternAnalyzer.__filter_states(current_states, self.tree)
        return self.__get_min_errors_from_states(current_states) + (False,)

    @staticmethod
    def __get_variants(current_node: TreeNode) -> Set[TreeNode]:
        """
        :param current_node: текущая нода.
        :return: варианты ноды на том же символе строки, возникают из-за * и ? в шаблоне.
        """
        variants = set()
        current_variant = current_node
        while current_variant is not None:
            if current_variant not in variants:
                variants.add(current_variant)
            else:
                current_variant = current_variant.parent
            current_variant = PatternAnalyzer.__get_next_variant(current_variant)
        return variants

    @staticmethod
    def __get_next_variant(node: TreeNode) -> TreeNode:
        """
        Получение следующего варианта из варинатов текущей ноды.

        :param node: текущий вариант.
        :return: следующий вариант.
        """
        assert node.is_leaf()
        while node.parent is not None:
            parent = node.parent
            grandfather = parent.parent
            uncle = parent.get_next_sibling() if grandfather is not None else None
            is_variable = node.is_first_leaf() or not node.is_leaf()
            if is_variable and uncle is not None:
                return uncle.get_most_left_leaf()
            elif grandfather is not None and grandfather.text == "*" and grandfather.children[-1] == parent:
                return grandfather.get_most_left_leaf()
            if is_variable:
                node = parent
            else:
                break
        return None

    @staticmethod
    def __get_next_leaf(node: TreeNode) -> TreeNode:
        """
        Получение следующей ноды.

        :param node: текущая нода.
        :return: следующая нода.
        """
        assert node.is_leaf()
        while node.parent is not None:
            sibling = node.get_next_sibling()
            if sibling is not None:
                return sibling.get_most_left_leaf()
            elif node.parent.text == "*":
                return node.parent.get_most_left_leaf()
            node = node.parent
        return None

    @staticmethod
    def __filter_states(states: List[State], root: TreeNode) -> List[State]:
        """
        Фильтрация по наличию обязательных терминалов.

        :param states: состояния.
        :param root: корень дерева.
        :return: отфильтрованные состояния.
        """
        return [state for state in states if root.get_last_child_leaf() is None or
                state.node.pattern_pos >= root.get_last_child_leaf().pattern_pos]

    @staticmethod
    def __get_min_errors_from_states(states: List[State]) -> Tuple[str, int, int]:
        """
        :param states: состояния.
        :return: лучший шаблон, количество сильных ошибок, количество слабых ошибок.
        """
        if len(states) == 0:
            return "", 0, 0
        return min([(state.pattern, state.strong_errors, state.weak_errors) for i, state in enumerate(states)],
                   key=lambda x: (x[1], x[2], x[0]))

redpajama_set_name: RedPajamaGithub


text:
package org.seqcode.data.io.parsing;

import java.awt.Color;
import java.util.regex.*;

public class BEDLine {

	private String chrom;
	private int chromStart, chromEnd;
	private String name;
	private Double score;
	private Character strand;
	private Integer thickStart, thickEnd;
	private Color itemRgb;
	private int blockCount;
	private int[] blockSizes;
	private int[] blockStarts;

	public String getChrom() { return chrom; }
	public int getChromStart() { return chromStart; }
	public int getChromEnd() { return chromEnd; }
	public String getName() { return name; }
	public Double getScore() { return score; }
	public Character getStrand() { return strand; }
	public Integer getThickStart() { return thickStart; }
	public Integer getThickEnd() { return thickEnd; }
	public Color getItemRgb() { return itemRgb; }
	public int getBlockCount() { return blockCount; }
	public int[] getBlockSizes() { return blockSizes; }
	public int[] getBlockStarts() { return blockStarts; }

    public static Pattern chromPattern = Pattern.compile("chr(.*)");

	public BEDLine(String line) {
		String[] array = line.split("\t");
		chrom = array[0];

        Matcher m = chromPattern.matcher(chrom);
        if(m.matches()) {
            chrom = m.group(1);
        }

		chromStart = Integer.parseInt(array[1]);
		chromEnd = Integer.parseInt(array[2]);

		name = array.length > 3 ? array[3] : null;
		score = array.length > 4 ? (array[4].charAt(0)=='.' ? 0 :Double.parseDouble(array[4])) : null;
		strand = array.length > 5 ? array[5].charAt(0) : null;
		thickStart = array.length > 6 ? Integer.parseInt(array[6]) : null;
		thickEnd = array.length > 7 ? Integer.parseInt(array[7]) : null;

		String[] aa = array.length > 8 ? array[8].split(",") : null;
		if(array.length > 8) {
			int r = Integer.parseInt(aa[0]),
			g = Integer.parseInt(aa[1]),
			b = Integer.parseInt(aa[2]);
			itemRgb = new Color(r, g, b);
		}

		if(array.length>9){
			blockCount = array.length>9 ? Integer.parseInt(array[9]) : null;

			aa = array.length > 10 ? array[10].split(",") : null;
			if(array.length > 10) {
				blockSizes = new int[blockCount];
				for(int i = 0; i < blockCount; i++) {
					blockSizes[i] = Integer.parseInt(aa[i]);
				}
			}

			aa = array.length > 11 ? array[11].split(",") : null;
			if(array.length > 11) {
				blockStarts = new int[blockCount];
				for(int i = 0; i < blockCount; i++) {
					blockStarts[i] = Integer.parseInt(aa[i]);
				}
			}
		}
	}
}


text:
package ast

import (
	"reflect"
)

type Visitor interface {
	EnterScope()
	ExitScope()

	Visit(*Node) bool
	PostVisit(*Node)
}

type ASTVisitor struct {
	Visitor Visitor
}

func NewASTVisitor(visitor Visitor) *ASTVisitor {
	return &ASTVisitor{Visitor: visitor}
}

func (v *ASTVisitor) VisitSubmodule(submodule *Submodule) {
	v.EnterScope()
	submodule.Nodes = v.VisitNodes(submodule.Nodes)
	v.ExitScope()
}

func (v *ASTVisitor) VisitNodes(nodes []Node) []Node {
	res := make([]Node, len(nodes))
	for idx, node := range nodes {
		res[idx] = v.Visit(node)
	}
	return res
}

func (v *ASTVisitor) VisitExprs(exprs []Expr) []Expr {
	res := make([]Expr, len(exprs))
	for idx, expr := range exprs {
		res[idx] = v.VisitExpr(expr)
	}
	return res
}

func (v *ASTVisitor) VisitBlocks(blocks []*Block) []*Block {
	res := make([]*Block, len(blocks))
	for idx, block := range blocks {
		res[idx] = v.VisitBlock(block)
	}
	return res
}

func (v *ASTVisitor) Visit(n Node) Node {
	if isNil(n) {
		return nil
	}

	if v.Visitor.Visit(&n) {
		v.VisitChildren(n)
		v.Visitor.PostVisit(&n)
	}

	return n
}

func (v *ASTVisitor) VisitExpr(e Expr) Expr {
	if isNil(e) {
		return nil
	}

	n := e.(Node)
	if v.Visitor.Visit(&n) {
		v.VisitChildren(n)
		v.Visitor.PostVisit(&n)
	}

	if n != nil {
		return n.(Expr)
	} else {
		return nil
	}
}

func (v *ASTVisitor) VisitBlock(b *Block) *Block {
	if isNil(b) {
		return nil
	}

	n := Node(b)
	if v.Visitor.Visit(&n) {
		v.VisitChildren(n)
		v.Visitor.PostVisit(&n)
	}

	if n != nil {
		return n.(*Block)
	} else {
		return nil
	}
}

func (v *ASTVisitor) EnterScope() {
	v.Visitor.EnterScope()
}

func (v *ASTVisitor) ExitScope() {
	v.Visitor.ExitScope()
}

func (v *ASTVisitor) VisitChildren(n Node) {
	switch n := n.(type) {
	case *Block:
		if !n.NonScoping {
			v.EnterScope()
		}

		n.Nodes = v.VisitNodes(n.Nodes)

		if !n.NonScoping {
			v.ExitScope()
		}

	case *ReturnStat:
		n.Value = v.VisitExpr(n.Value)

	case *IfStat:
		n.Exprs = v.VisitExprs(n.Exprs)
		n.Bodies = v.VisitBlocks(n.Bodies)
		n.Else = v.VisitBlock(n.Else)

	case *AssignStat:
		n.Assignment = v.VisitExpr(n.Assignment)
		n.Access = v.Visit(n.Access).(AccessExpr)

	case *BinopAssignStat:
		n.Assignment = v.VisitExpr(n.Assignment)
		n.Access = v.Visit(n.Access).(AccessExpr)

	case *DestructAssignStat:
		n.Assignment = v.VisitExpr(n.Assignment)
		for idx, acc := range n.Accesses {
			n.Accesses[idx] = v.Visit(acc).(AccessExpr)
		}

	case *DestructBinopAssignStat:
		n.Assignment = v.VisitExpr(n.Assignment)
		for idx, acc := range n.Accesses {
			n.Accesses[idx] = v.Visit(acc).(AccessExpr)
		}

	case *LoopStat:
		n.Body = v.Visit(n.Body).(*Block)

		switch n.LoopType {
		case LOOP_TYPE_INFINITE:
		case LOOP_TYPE_CONDITIONAL:
			n.Condition = v.VisitExpr(n.Condition)
		default:
			panic("invalid loop type")
		}

	case *MatchStat:
		n.Target = v.VisitExpr(n.Target)

		res := make(map[Expr]Node)
		for pattern, stmt := range n.Branches {
			res[v.VisitExpr(pattern)] = v.Visit(stmt)
		}
		n.Branches = res

	case *BinaryExpr:
		n.Lhand = v.VisitExpr(n.Lhand)
		n.Rhand = v.VisitExpr(n.Rhand)

	case *CallExpr:
		n.Function = v.VisitExpr(n.Function)

		n.Arguments = v.VisitExprs(n.Arguments)
		n.ReceiverAccess = v.VisitExpr(n.ReceiverAccess)

	case *ArrayAccessExpr:
		n.Array = v.Visit(n.Array).(AccessExpr)
		n.Subscript = v.VisitExpr(n.Subscript)

	case *SizeofExpr:
		n.Expr = v.VisitExpr(n.Expr)

	case *ArrayLenExpr:
		n.Expr = v.VisitExpr(n.Expr)

	case *TupleLiteral:
		n.Members = v.VisitExprs(n.Members)

	case *CompositeLiteral:
		n.Values = v.VisitExprs(n.Values)

	case *EnumLiteral:
		n1 := v.Visit(n.TupleLiteral)
		if n1 == nil {
			n.TupleLiteral = nil
		} else {
			n.TupleLiteral = n1.(*TupleLiteral)
		}

		n2 := v.Visit(n.CompositeLiteral)
		if n2 == nil {
			n.CompositeLiteral = nil
		} else {
			n.CompositeLiteral = n2.(*CompositeLiteral)
		}

	case *BlockStat:
		n.Block = v.VisitBlock(n.Block)

	case *CallStat:
		n.Call = v.Visit(n.Call).(*CallExpr)

	case *DeferStat:
		n.Call = v.Visit(n.Call).(*CallExpr)

	case *ReferenceToExpr:
		n.Access = v.VisitExpr(n.Access)

	case *PointerToExpr:
		n.Access = v.VisitExpr(n.Access)

	case *CastExpr:
		n.Expr = v.VisitExpr(n.Expr)

	case *LambdaExpr:
		v.VisitFunction(n.Function)

	case *UnaryExpr:
		n.Expr = v.VisitExpr(n.Expr)

	case *StructAccessExpr:
		n.Struct = v.Visit(n.Struct).(AccessExpr)

	case *DerefAccessExpr:
		n.Expr = v.VisitExpr(n.Expr)

	case *FunctionDecl:
		v.VisitFunction(n.Function)

	case *VariableDecl:
		n.Assignment = v.VisitExpr(n.Assignment)

	case *DestructVarDecl:
		n.Assignment = v.VisitExpr(n.Assignment)

	case *FunctionAccessExpr:
		n.ReceiverAccess = v.VisitExpr(n.ReceiverAccess)

	case *NumericLiteral, *StringLiteral, *BoolLiteral, *RuneLiteral,
		*VariableAccessExpr, *TypeDecl, *UseDirective, *BreakStat, *NextStat,
		*DiscardAccessExpr, *EnumPatternExpr:
		// do nothing

	default:
		panic("Unhandled node: " + reflect.TypeOf(n).String())
	}
}

func (v *ASTVisitor) VisitFunction(fn *Function) {
	v.EnterScope()

	if fn.Type.Receiver != nil {
		fn.Receiver = v.Visit(fn.Receiver).(*VariableDecl)
	}

	for idx, param := range fn.Parameters {
		fn.Parameters[idx] = v.Visit(param).(*VariableDecl)
	}

	if fn.Body != nil {
		fn.Body = v.Visit(fn.Body).(*Block)
	}
	v.ExitScope()
}

// IterNodes allows for looping over all nodes using a for range loop
func (v *Submodule) IterNodes() chan Node {
	cv := &channelingVisitor{
		channel: make(chan Node),
	}
	go cv.run(v)
	return cv.channel
}

type channelingVisitor struct {
	channel chan Node
}

func (v *channelingVisitor) run(submod *Submodule) {
	vis := NewASTVisitor(v)
	vis.VisitSubmodule(submod)
	close(v.channel)
}

func (v *channelingVisitor) Visit(n *Node) bool {
	v.channel <- *n
	return true
}

func (v *channelingVisitor) EnterScope()       {}
func (v *channelingVisitor) ExitScope()        {}
func (v *channelingVisitor) PostVisit(n *Node) {}

func isNil(a interface{}) bool {
	defer func() { recover() }()
	return a == nil || reflect.ValueOf(a).IsNil()
}


text:
<?xml version="1.0" ?>

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
    <class name="Sylius\Component\Product\Model\ProductOptionValue">
        <attribute name="id">
            <group>admin:product_option_value:read</group>
        </attribute>
        <attribute name="value">
            <group>admin:product_option_value:read</group>
        </attribute>
        <attribute name="option">
            <group>admin:product_option_value:read</group>
        </attribute>
        <attribute name="code">
            <group>admin:product_option:create</group>
            <group>admin:product_option:update</group>
            <group>admin:product_option_value:read</group>
            <group>admin:product_option_value:write</group>
        </attribute>
        <attribute name="translations">
            <group>admin:product_option:create</group>
            <group>admin:product_option:update</group>
            <group>admin:product_option_value:read</group>
            <group>admin:product_option_value:write</group>
        </attribute>
    </class>
</serializer>


text:
import threading
from subprocess import Popen, PIPE
import time, datetime
import shlex
import uuid
import json
import collections
import urllib2, urllib
from os.path import expanduser

from reporting.parsers import MatchParser, SplitParser, DummyParser, JsonGrepParser
from reporting.utilities import getLogger, get_hostname, init_object
from reporting.exceptions import PluginInitialisationError, RemoteServerError
from reporting.crontab import CronEvent

log = getLogger(__name__)

class IDataSource(object):
    def get_data(self, **kwargs):
        assert 0, "This method must be defined."

class CommandRunner(IDataSource):
    def __init__(self, cmd):
        self.__cmd=cmd
    def get_data(self, **kwargs):
        log.debug("running cmd %s"%self.__cmd)
        process = Popen(shlex.split(self.__cmd), stdout=PIPE)
        pipe = process.stdout
        output = ''.join(pipe.readlines()).strip()
        process.wait()
        return output

class FileReader(IDataSource):
    def __init__(self, path):
        if path.startswith("~"):
            path = expanduser(path)
        self.__path = path

    def get_data(self, **kwargs):
        log.debug("Reading file %s" % self.__path)
        with open(self.__path) as f:
            content = ''.join(f.readlines()).strip()
        return content

class HTTPReader(IDataSource):
    def __init__(self, url, headers={}, auth=None):
        self.__url=url
        self.__headers=headers
        self.__auth=auth
    def get_data(self, **kwargs):
        try:
            if self.__auth:
                password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
                password_manager.add_password(None, self.__url, self.__auth['username'], self.__auth['password'])

                auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handler
                opener = urllib2.build_opener(auth) # create an opener with the authentication handler
                urllib2.install_opener(opener) # install the opener...

            req = urllib2.Request(self.__url, None, self.__headers)
            handler = urllib2.urlopen(req)
        except urllib2.HTTPError as e:
            log.error('response code %d' % e.code)
            if e.code == 400 or e.code==500:
                raise MessageInvalidError()
            else:
                raise RemoteServerError()
        except urllib2.URLError as e:
            raise Exception("Error accessing URL %s: %s" % (self.__url, e.args))
        else:
            # 200
            response = handler.read()
            log.debug("response %d %s"% (handler.code, response))
            handler.close()
            return response

class Collector(threading.Thread):
    def __init__(self, collector_name, config, output, tailer=None):
        threading.Thread.__init__(self, name=collector_name)
        self.__collector_name=collector_name
        self.__config=config
        self.__sleep_time=self.__config['input'].get('frequency',10)
        self.__cron=self.__config['input'].get('schedule',None)
        self.__schedule=None
        if self.__cron is not None:
            self.__schedule=CronEvent(self.__cron)
            log.debug("job scheduled at %s"%self.__schedule.numerical_tab)
        self.__input=None
        self.__parser=None
        self.__output=output

        if self.__config['input']['type']=='command':
            self.__input=CommandRunner(self.__config['input']['source'])
        elif self.__config['input']['type']=='file':
            self.__input=FileReader(self.__config['input']['path'])
        elif self.__config['input']['type']=='http':
            #log.debug('input %s'%self.__config['input'])
            url=self.__config['input']['url']
            headers=self.__config['input'].get('headers', {})
            #log.debug('headers %s'%headers)
            auth=self.__config['input'].get('auth', None)
            self.__input=HTTPReader(url, headers, auth)
        elif self.__config['input']['type']=='class':
            arguments={}
            if 'arguments' in self.__config['input']:
                arguments=self.__config['input']['arguments']
            self.__input=init_object(self.__config['input']['name'], **arguments)
        elif self.__config['input']['type']=='tailer':
            if tailer is None:
                raise AttributeError("Missing tailer in config file for tailer type input")
            self.__input=tailer

        assert(self.__input)

        if 'parser' in self.__config:
            if self.__config['parser']['type']=='match':
                self.__parser=MatchParser(self.__config['parser']['pattern'].strip(), self.__config['parser']['transform'].strip())
            elif self.__config['parser']['type']=='split':
                self.__parser=SplitParser(self.__config['parser']['delimiter'].strip(), self.__config['parser']['transform'].strip())
            elif self.__config['parser']['type']=='dummy':
                self.__parser=DummyParser()
            elif self.__config['parser']['type']=='json':
                arguments={}
                if 'arguments' in self.__config['parser']:
                    arguments=self.__config['parser']['arguments']
                self.__parser=JsonGrepParser(**arguments)
            elif self.__config['parser']['type']=='class':
                arguments={}
                if 'arguments' in self.__config['parser']:
                    arguments=self.__config['parser']['arguments']
                self.__parser=init_object(self.__config['parser']['name'], **arguments)
        self.__running=True
        self.__session_id=str(uuid.uuid4())
        self.__max_error_count=self.__config['input'].get('max_error_count', -1)
        self.__current_data=None
        self.__number_collected=0
        self.__number_failed=0
        self.__sleep_count=0
        self.__error_count=0
        self.__last_check_minute=-1

    def quit(self):
        self.__running=False

    def info(self):
        col_info={"name":self.__collector_name, "config":self.__config, "sleep_time": self.__sleep_time}
        col_info["session_id"]=self.__session_id
        col_info["is_running"]=self.__running
        col_info["current_data"]=self.__current_data
        col_info["number_collected"]=self.__number_collected
        col_info["number_failed"]=self.__number_failed
        col_info["sleep_count"]=self.__sleep_count
        col_info["error_count"]=self.__error_count
        col_info["max_error_count"]=self.__max_error_count
        if self.__cron is not None:
            col_info["cron"]=self.__cron
        if self.__config['input']['type']=='tailer':
            col_info["tailer"]=self.__input.info(self.__config['input']['path'])
        return col_info

    def match_time(self):
        """Return True if this event should trigger at the specified datetime"""
        if self.__schedule is None:
            return False
        t=datetime.datetime.now()
        if t.minute==self.__last_check_minute:
            return False
        self.__last_check_minute=t.minute
        log.debug("check if cron job can be triggered. %d"%self.__last_check_minute)
        return self.__schedule.check_trigger((t.year,t.month,t.day,t.hour,t.minute))

    def run(self):
        count = self.__sleep_time
        error_count = 0
        log.info("Collector %s has started.", self.__collector_name)
        while self.__running:
            args = {'config': self.__config['input']}
            if (self.__schedule is None and count == self.__sleep_time) or self.match_time():
                log.debug("Starting to collect data.")
                count = 0
                data = None
                no_msgs = 1
                try:
                    data = self.__input.get_data(**args)
                    if isinstance(data, collections.deque) or isinstance(data, list):
                        self.__current_data = [l.decode('ASCII', 'ignore') for l in data]
                        payload = []
                        no_msgs = len(data)
                        for line in data:
                            log.debug("Raw data: %s", line)
                            payload.append(self.generate_payload(str(line.decode('ASCII', 'ignore'))))
                        if len(payload) > 0:
                            self.__output.push(payload)
                        else:
                            continue
                    else:
                        # a block of data: either string to be parsed or dict
                        self.__current_data = data
                        log.debug("Raw data: %s", data)
                        if isinstance(data, str):
                            payload = self.generate_payload(str(data.decode('ASCII', 'ignore')))
                        else:
                            payload = self.generate_payload(data)
                        self.__output.push(payload)
                except:
                    self.__current_data = data
                    log.exception('Unable to get or parse data. data: %s', data)
                    error_count += 1
                    if self.__max_error_count > 0 and error_count >= self.__max_error_count:
                        self.__running = False
                        self.__error_count = error_count
                        break
                    self.__number_failed += no_msgs
                    if self.__config['input']['type'] == 'tailer':
                        self.__input.fail(**args)
                else:
                    error_count = 0
                    self.__number_collected += no_msgs
                    if self.__config['input']['type'] == 'tailer':
                        self.__input.success(**args)
                self.__error_count = error_count
            else:
                time.sleep(1)
                if self.__schedule is None:
                    count += 1

            self.__sleep_count = count

        self.__output.close()
        log.info("Collector %s has stopped.", self.__collector_name)

    def generate_payload(self, data):
        """Parse raw data and package the result in required format"""
        if self.__parser:
            data = self.__parser.parse(data)
            log.debug("Parser %s parsed data %s: ", self.__parser.__class__.__name__, data)

        payload = {"id": str(uuid.uuid4()), "session": self.__session_id}
        payload['data'] = data
        if 'metadata' in self.__config:
            for m in self.__config['metadata']:
                payload[m] = self.__config['metadata'][m]
        log.debug("payload to push: %s", payload)
        return payload


text:
<?php

namespace Kendo\Dataviz\UI;

class StockChartCategoryAxisItemNotesLabelBorder extends \Kendo\SerializableObject {
//>> Properties

    /**
    * The color of the border. Accepts a valid CSS color string, including hex and rgb.
    * @param string $value
    * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemNotesLabelBorder
    */
    public function color($value) {
        return $this->setProperty('color', $value);
    }

    /**
    * The dash type of the border.The following dash types are supported:
    * @param string $value
    * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemNotesLabelBorder
    */
    public function dashType($value) {
        return $this->setProperty('dashType', $value);
    }

    /**
    * The width of the border in pixels. By default the border width is set to zero which means that the border will not appear.
    * @param float $value
    * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemNotesLabelBorder
    */
    public function width($value) {
        return $this->setProperty('width', $value);
    }

//<< Properties
}

?>


text:
package cgeo.geocaching.apps.cachelist;

import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.apps.AbstractLocusApp;
import cgeo.geocaching.models.Geocache;

import org.apache.commons.collections4.CollectionUtils;
import android.support.annotation.NonNull;

import android.app.Activity;
import android.content.Intent;

import java.util.List;

abstract class AbstractLocusCacheListApp extends AbstractLocusApp implements CacheListApp {

    private final boolean export;

    AbstractLocusCacheListApp(final boolean export) {
        super(getString(export ? R.string.caches_map_locus_export : R.string.caches_map_locus), Intent.ACTION_VIEW);
        this.export = export;
    }

    /**
     * show caches in Locus
     *
     * @see AbstractLocusApp#showInLocus
     */
    @Override
    public boolean invoke(@NonNull final List<Geocache> cacheList, @NonNull final Activity activity, @NonNull final SearchResult search) {
        if (CollectionUtils.isEmpty(cacheList)) {
            return false;
        }

        showInLocus(cacheList, false, export, activity);

        return true;
    }

}


text:
/** @file
    @brief Test Implementation

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>

*/

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

// Internal Includes
#include <osvr/Common/PathTreeFull.h>
#include <osvr/Common/PathElementTypes.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/RoutingExceptions.h>
#include "IsType.h"

// Library/third-party includes
#include "gtest/gtest.h"

// Standard includes
// - none

using std::string;
using namespace osvr::common;
TEST(PathTree, create) { ASSERT_NO_THROW(PathTree()); }

TEST(PathTree, getPathRoot) {
    PathTree tree;
    PathNode *result = nullptr;
    ASSERT_NO_THROW(result = &tree.getNodeByPath("/")) << "Get the root.";
    ASSERT_TRUE(result->isRoot());
    ASSERT_EQ(result->getParent(), nullptr);
}

TEST(PathTree, getPathBadInput) {
    PathTree tree;
    ASSERT_THROW(tree.getNodeByPath(""), exceptions::EmptyPath)
        << "Empty string not acceptable as path";
    ASSERT_THROW(tree.getNodeByPath("test"), exceptions::PathNotAbsolute)
        << "Missing leading slash not acceptable";
    ASSERT_THROW(tree.getNodeByPath("//test"), exceptions::EmptyPathComponent)
        << "Empty component not OK!";
    ASSERT_THROW(tree.getNodeByPath("/asdf//test"),
                 exceptions::EmptyPathComponent)
        << "Empty component not OK!";
    ASSERT_THROW(tree.getNodeByPath("/asdf//"), exceptions::EmptyPathComponent)
        << "Empty component not OK!";
}

TEST(PathTree, getPathSingleLevel) {
    PathTree tree;
    PathNode *result = nullptr;
    ASSERT_NO_THROW(result = &tree.getNodeByPath("/test"))
        << "Get a new node just a single level in";
    ASSERT_TRUE(isNodeType<elements::NullElement>(*result))
        << "Check the type of the new node.";
    ASSERT_EQ(result->getName(), "test") << "Check the name of the new node";

    ASSERT_NO_THROW(tree.getNodeByPath("/test")) << "Get the same node again.";
    ASSERT_EQ(tree.getNodeByPath("/test"), *result)
        << "Ensure we're actually getting the same identity.";
    ASSERT_EQ(tree.getNodeByPath("/test/"), *result)
        << "Ensure trailing slashes don't matter.";
}

TEST(PathTree, getPathTwoLevel) {
    PathTree tree;
    PathNode *test2 = nullptr;
    ASSERT_NO_THROW(test2 = &tree.getNodeByPath("/test1/test2"))
        << "Get a node two new levels in";
    // Check test2
    ASSERT_EQ(test2->getName(), "test2");
    ASSERT_FALSE(test2->hasChildren()) << "Make sure it has no children.";
    ASSERT_TRUE(isNodeType<elements::NullElement>(*test2)) << "Check type";
    ASSERT_NE(test2->getParent(), nullptr) << "Make sure it has a parent.";

    // Check test1
    auto test1 = test2->getParent();
    ASSERT_EQ(test1->getName(), "test1");
    ASSERT_TRUE(isNodeType<elements::NullElement>(*test1));
    ASSERT_NE(test1->getParent(), nullptr) << "Make sure it has a parent.";
    auto root = test1->getParent();

    ASSERT_TRUE(root->isRoot());
    ASSERT_EQ(tree.getNodeByPath("/"), *root)
        << "Root identity should be preserved";
    ASSERT_EQ(tree.getNodeByPath("/test1/test2"), *test2)
        << "Identity should be preserved";
}


text:
===============
Feature Details
===============

.. warning::

   This section a very early draft.

Workflow and Activity Contracts
-------------------------------

Python classes and decorators are used to declare the signatures of workflows
and activities. For example, a workflow type MyWorkflow is defined as a
subclass of :py:class:`~botoflow.workflow_definition.WorkflowDefinition`:

.. code-block:: python

    class MyWorkflow(WorkflowDefinition):

        @execute(version='1.0', execution_start_to_close_timeout=1*MINUTES)
        def start_my_workflow(self, input1, input2):
            self.workflow_state = "Workflow started"

        @signal()
        def signal1(self, input1, input2):
            pass

In the example above, the workflow interface MyWorkflow contains a method,
`start_my_workflow`, for starting a new execution. This method is decorated
with @ :py:func:`~botoflow.decorators.execute`. In a given workflow, at least
one method can be decorated with @ :py:func:`~botoflow.decorators.execute`. This
method is the entry point of the workflow logic, and the framework calls this
method to execute the workflow logic when a decision task is received.

The workflow also defines the signals that may be sent to the workflow. The
signal method gets invoked when a signal with a matching name is received by
the workflow execution. For example, the `MyWorkflow` declares a signal method,
`signal1`, decorated with @ :py:func:`~botoflow.decorators.signal`.

The @ :py:func:`~botoflow.decorators.signal` decorator is required on signal
methods. Signals cannot `return` (if you return a value from a signal, it will
be ignored). A workflow may have zero or more signal methods defined in it.

Methods annotated with @ :py:func:`~botoflow.decorators.execute` and @
:py:func:`~botoflow.decorators.signal` annotations may have any number of
parameters including positional and keyword arguments (`*args, **kwds`).

Additionally, you are also able to report the latest state of a workflow
execution, using a
:py:attr:`~botoflow.workflow_definition.WorkflowDefinition.workflow_state`. This
state is not the entire application state of the workflow. The intended use of
this feature is to allow you to store up to 32KB of data to indicate the
latest status of the execution. For example, in an order processing workflow,
you may store a string which indicates that the order has been received,
processed, or canceled. This method is called by the framework every time a
decision task is completed to get the latest state. The state is stored in
Amazon Simple Workflow Service (SWF) and can be retrieved using SWF APIs. This
allows you to check the latest state of a workflow execution. You can assign
any serializable object, which fits your needs, to this property.

Activities on the other hand can be any `object` with some or all of it's
methods decorated with @ :py:func:`~botoflow.decorators.activity`. In addition,
there's another decorator that can be applied to the class to set some activity
defaults.

.. code-block:: python

    @activities(default_task_schedule_to_start_timeout = 4*MINUTES,
                default_task_start_to_close_timeout = 2*HOURS)
    class MyActivities(object):

        # Overrides values from the @activities decorator
        @activity(default_task_schedule_to_start_timeout = 2*MINUTES)
        def activity1(self):
            """This is sample activity 1"""
            pass

        # the docstring is usually used as the description field, but i'ts also
        # overridable
        @activity(description="My special description")
        def activity2(self, a):
            print a

        # not an activity
        def _some_method(self):
            pass

Workflow and Activity Type Registration
---------------------------------------

Amazon SWF requires activity and workflow types to be registered before they
can be used. The framework automatically registers the workflows and activities
in the implementations you add to the workers. The framework looks for types
that implement workflows and activities and registers them with Amazon SWF. By
default, the framework uses the interface definitions to infer registration
options for workflow and activity types. The workflow worker registers all workflow types
it is configured with that have the @ :py:func:`~botoflow.decorators.execute`
annotation. Similarly, each activity method is required to be annotated with
the @ :py:func:`~botoflow.decorators.activity` decorator and optionally the
class can be decorated with @ :py:func:`~botoflow.decorators.activities`.  The
activity worker registers all activity types that it is configured with the
:py:func:`~botoflow.decorators.activity` decorator. The registration is
performed automatically when you start one of the workers. Workflow and
activity types that have have the `skip_registration` attribute set to `True`
will not be registered with Amazon SWF.

Note that Amazon SWF does not allow you to re-register or modify the type after
it has been registered once. The framework will try to register all types, but
if the type is already registered it will not be re-registered and no error
will be reported. If you need to modify registered settings, you should
register a new version of the type. You can also override registered settings
when starting a new execution or calling an activity using
:py:mod:`botoflow.options` context managers.

The registration requires a type name and some other registration options. The
default implementation determines these as follows:

Workflow Type Name and Version
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The framework determines the name of the workflow type from the workflow
definition and the @execute decorated method. The form of the default workflow
type name is `class.__name__`. The default name of the workflow type in the
above example is: *MyWorkflow*. You can override the default name using the
name parameter of the @ :py:func:`~botoflow.decorators.workflow` decorator. The
name must not be an empty string.

The workflow version is specified using the `version` parameter of the @
:py:func:`~botoflow.decorators.execute`. There is no default for the `version`
and it must be explicitly specified. Version is a free form string and you are
free to use your own versioning scheme.

Signal Name
^^^^^^^^^^^

The name of the signal can be specified using the name parameter of the @
:py:func:`~botoflow.decorators.signal`. If not specified, it is defaulted to
the name of the signal method.

Activity Type Name and Version
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The framework determines the name of the activity type from the activity class name. The form of the default activity type name is {prefix}{name}. The
{prefix} is set to the name of the activity class followed by a '.' and
the {name} is set to the method name. The default {prefix} can be overridden in
the @ :py:func:`~botoflow.decorators.activities` decorator with `activity_name_prefix` parameter. You can also specify
the activity type name using the @ :py:func:`~botoflow.decorators.activity` decorator on the activity
method. Note that when you override the name using @activity, the framework
**will** automatically prepend the prefix to it.

The activity version is specified using the version parameter of the @Activities annotation. This version is used as the default for all activities defined in the interface and can be overridden on a per-activity basis using the @Activity annotation.

Activity Cancellation
^^^^^^^^^^^^^^^^^^^^^

From within an execution, activities can be cancelled with:
"<activity_future>.cancel()".

This will raise a CancelledError exception signifying successful cancellation.
Cancellation will not be successful in any of the following cases:
(1) the activity is not heartbeating
(2) the activity is heartbeating, but chooses to ignore cancel requests
(3) the activity completes before receiving the request

To heartbeat, within an activity simply do: "botoflow.get_context().heartbeat()".
This will raise a CancellationError if a cancel is requested. If this error, a
subclass of, or a CancelledError is raised by the activity, botoflow will
report to SWF that the activity task was cancelled. This exception then gets
assigned to the activity future (see above).

Workflow Cancellation
^^^^^^^^^^^^^^^^^^^^^

Workflow cancellations will send a cancel request to all open activities and cancel
the workflow itself, all in a single decision without waiting for activities to
complete/cancel.

To cancel a workflow from within the executing context itself, either:
(1) raise CancelledError, or
(2) <WorkflowDefinition>self.cancel()

To cancel a workflow from a different execution context, use cancel on the
respective WorkflowDefinition:

.. code-block:: python

    external_wf = WorkflowDefinition(WorkflowExecution('workflow-id', 'run-id'))
    external_wf.cancel()


text:
package org.pmiops.workbench.test;

import static com.google.common.truth.Truth.assertThat;

import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.pmiops.workbench.utils.Comparables;

public class ComparablesTest {

  private static final Duration SMALL_DURATION = Duration.ofMinutes(3);
  private static final Duration LARGE_DURATION = Duration.ofMinutes(10);

  @Test
  public void testIsLessThan() {
    assertThat(Comparables.isLessThan(SMALL_DURATION, SMALL_DURATION)).isFalse();
    assertThat(Comparables.isLessThan(SMALL_DURATION, LARGE_DURATION)).isTrue();
    assertThat(Comparables.isLessThan(LARGE_DURATION, SMALL_DURATION)).isFalse();
  }

  @Test
  public void testIsLessThanOrEqualTo() {
    assertThat(Comparables.isLessThanOrEqualTo(SMALL_DURATION, SMALL_DURATION)).isTrue();
    assertThat(Comparables.isLessThanOrEqualTo(SMALL_DURATION, LARGE_DURATION)).isTrue();
    assertThat(Comparables.isLessThanOrEqualTo(LARGE_DURATION, SMALL_DURATION)).isFalse();
  }

  @Test
  public void testIsEqualValueTo() {
    assertThat(Comparables.isEqualValueTo(SMALL_DURATION, SMALL_DURATION)).isTrue();
    assertThat(Comparables.isEqualValueTo(SMALL_DURATION, LARGE_DURATION)).isFalse();
    assertThat(Comparables.isEqualValueTo(LARGE_DURATION, SMALL_DURATION)).isFalse();
  }

  @Test
  public void testIsGreaterThan() {
    assertThat(Comparables.isGreaterThan(SMALL_DURATION, SMALL_DURATION)).isFalse();
    assertThat(Comparables.isGreaterThan(SMALL_DURATION, LARGE_DURATION)).isFalse();
    assertThat(Comparables.isGreaterThan(LARGE_DURATION, SMALL_DURATION)).isTrue();
  }

  @Test
  public void testIsGreaterThanOrEqualTo() {
    assertThat(Comparables.isGreaterThanOrEqualTo(SMALL_DURATION, SMALL_DURATION)).isTrue();
    assertThat(Comparables.isGreaterThanOrEqualTo(SMALL_DURATION, LARGE_DURATION)).isFalse();
    assertThat(Comparables.isGreaterThanOrEqualTo(LARGE_DURATION, SMALL_DURATION)).isTrue();
  }
}


text:
from panda3d.core import *
import sys,os
loadPrcFileData("", "prefer-parasite-buffer #f")

import direct.directbase.DirectStart
from direct.interval.IntervalGlobal import *
from direct.gui.DirectGui import OnscreenText
from direct.showbase.DirectObject import DirectObject
from direct.actor import Actor
from random import *
from ObjectMover import *
plane_size = 1000
split_count = 4

class World(DirectObject):
    def __init__(self):
        self.step_x = 0
        self.step_y = 0
        self.suffix =""
#        for x in range (0, split_count):
#            for y in range(0, split_count):
#                cam_pos_x = ((x*2 + 1) - split_count) * (plane_size/(split_count*2))
#                cam_pos_y = ((y*2 + 1) - split_count) * (plane_size/(split_count*2))
#                print `((x, y), (cam_pos_x, cam_pos_y))`
        # creating the offscreen buffer.
        #self.camZ = 690
        #self.camZ = 72000
        #self.far = self.camZ
        #self.near = self.far-60
        winprops = WindowProperties.size(1200,1200)
        props = FrameBufferProperties()
        props.setRgbColor(1)
        props.setAlphaBits(1)
        props.setDepthBits(1)
        LBuffer = base.graphicsEngine.makeOutput(
                 base.pipe, "offscreen buffer", -2,
                 props, winprops,
                 GraphicsPipe.BFRefuseWindow,
                 base.win.getGsg(), base.win)

        if (LBuffer == None):
           self.t=addTitle("Shadow Demo: Video driver cannot create an offscreen buffer.")
           return

        self.depthmap = Texture()
        LBuffer.addRenderTexture(self.depthmap, GraphicsOutput.RTMCopyRam, GraphicsOutput.RTPDepthStencil)
        if (base.win.getGsg().getSupportsShadowFilter()):
            Ldepthmap.setMinfilter(Texture.FTShadow)
            Ldepthmap.setMagfilter(Texture.FTShadow)

        # Adding a color texture is totally unnecessary, but it helps with debugging.
        self.colormap = Texture()
        LBuffer.addRenderTexture(self.colormap, GraphicsOutput.RTMCopyRam, GraphicsOutput.RTPColor)

        self.LCam=base.makeCamera(LBuffer)
        self.LCam.node().setScene(render)
        #self.LCam.node().getLens().setFov(0.2)
        #self.LCam.node().getLens().setAspectRatio(1.6)

#        self.LCam.setPos(0, 0, 150)
#        self.LCam.lookAt(0, 0,0)
        #self.LCam.node().getLens().setNearFar(self.near,self.far)

        lens = OrthographicLens()
        lens.setFilmSize(1200, 1200)
        lens.setFilmOffset(0,0)
        lens.setNearFar(-60, 0)
        self.LCam.node().setLens(lens)

        base.setBackgroundColor(0,0,0.2,1)
        base.cam.node().setLens(lens)
        #base.camLens.setNearFar(1.0,10000)
        #base.camLens.setFov(10)
 #       self.LCam.setPos(0, 0, self.camZ)
 #       self.LCam.lookAt(0, 0,0)
        #self.moveCam()
        base.disableMouse()

        self.environ = loader.loadModel("models/environment/road")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setPos(-600,0, -600)
        self.environ.setP(90)
        self.accept("o", base.oobe)
        self.accept('p',self.write)
        """
        self.accept('s',self.decnear)
        self.accept('x',self.incnear)

        self.accept('d',self.decfar)
        self.accept('c',self.incfar)
        self.objectMover = ObjectMover(self.LCam, 100)
        """

    def moveCam(self):
        if (self.step_y >= split_count):
            sys.exit()
        self.suffix = str(self.step_x)+'_'+str(self.step_y)
        cam_pos_x = ((self.step_x*2 + 1) - split_count) * (plane_size/(split_count*2))
        cam_pos_y = ((self.step_y*2 + 1) - split_count) * (plane_size/(split_count*2))
        print `((self.step_x, self.step_y), (cam_pos_x, cam_pos_y))`
        self.step_x = self.step_x +1;
        if (self.step_x >= split_count):
            self.step_x = 0
            self.step_y = self.step_y +1
        self.LCam.setPos(cam_pos_x, cam_pos_y, self.camZ)
        self.LCam.lookAt(cam_pos_x, cam_pos_y, 0)

    def write(self):
        heightmap = PNMImage()
        self.depthmap.store(heightmap)
        #print `heightmap`
        heightmap.write('heightmap/heightmap'+self.suffix+'.bmp')

        colormap = PNMImage()
        self.colormap.store(colormap)
        #print `colormap`
        colormap.write('heightmap/colormap'+self.suffix+'.bmp')
        #self.moveCam()

    def decnear(self):
        self.near = self.near -1
        self.setNearFar()
    def incnear(self):
        self.near = self.near +1
        self.setNearFar()
    def decfar(self):
        self.far = self.far -1
        self.setNearFar()
    def incfar(self):
        self.far = self.far +1
        self.setNearFar()

    def setNearFar(self):
        print `(self.near, self.far)`
        self.LCam.node().getLens().setNearFar(self.near,self.far)

# end of __init__

World()
run()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta content="IE=Edge" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, height=device-height">
    <title>
Grow Open Source Project    </title>
    <meta property="og:title" content="Grow Open Source Project – grow.io">
    <meta property="og:site_name" content="grow.io">
    <meta property="og:type" content="website">
    <meta property="og:url" content="http://localhost/project/">
      <meta name="description" content="An open source, Git-based static site generator for rapid, content-driven website management and production.">
      <meta property="og:description" content="An open source, Git-based static site generator for rapid, content-driven website management and production.">
      <link rel="shortcut icon" href="/favicon.ico">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Dosis:300,400,500|Source+Code+Pro" rel="stylesheet">
    <link href="/css/composite/global-815332777827e9f19889b183c4d607cd.min.css" rel="stylesheet">
        <link href="/css/composite/home-067aec70e8e4b53dcfea7a816e58b5b1.min.css" rel="stylesheet">

      Grow

        Start
        Docs
        About
        Search
        Styles

    Grow

    Grow is an open source project.

        code
      GitHub

          Grow's mission is to bring joy to building and launching microsites

              We want Grow to be the canonical way for teams and individuals to build, launch, and
maintain high-quality, content-rich web sites. It's architected to work for humans, to allow
people pair it with their own development tools, to run locally and in the cloud, and to
bring simplicity to web site management.

              Grow (the app) and the stuff you make with it (your sites) are portable. You can run Grow
anywhere, and you can take your content anywhere because your content is stored as flat
files. There will never be lock-in with Grow.

          Get involved

              Grow is open source and you can help shape its future by contributing code, filing issues,
joining the discussion, and making feature requests.

              You can contribute code by sending pull requests to the open source project.

                Source Code

                Issues and Milestones

                Mailing List

                Contributors

                Organization

          Technology

            Grow is written in Python and projects are file-based and backed by Git. Grow is a static site
generator – meaning you can use it to build and deploy sites almost anywhere

          Roadmap

            Interested in seeing what Grow will be adding in the future? Checkout the GitHub issue tracker
to see what is in the works.

                Grow Issues and Milestones

      Grow is released under the MIT License.

      Except otherwise noted, docs are released under CC 3.0 and icons are from Flatties.

      Edit on GitHub


text:
namespace Publisher
{
    /// <summary>
    /// Settings interface for rsync (file/directory copying)
    /// </summary>
    [Bam.Core.SettingsExtensions(typeof(DefaultSettings.DefaultSettingsExtensions))]
    interface IRsyncSettings :
        Bam.Core.ISettingsBase
    {
        /// <summary>
        /// Make the tool output verbose
        /// </summary>
        bool Verbose { get; set; }

        /// <summary>
        /// Recursively copy all files
        /// </summary>
        bool Recursive { get; set; }

        /// <summary>
        /// Preserve all file attributes when copying
        /// </summary>
        bool PreserveAllAttributes { get; set; }

        /// <summary>
        /// Use checksums to avoid copying files again on another run
        /// </summary>
        bool UseChecksums { get; set; }

        /// <summary>
        /// List of excluded file paths
        /// </summary>
        Bam.Core.TokenizedStringArray Exclusions { get; set; }
    }
}


text:
<?php if (!defined('W3TC')) die(); ?>

    <?php _e('Account #:', 'w3-total-cache'); ?>

        <input id="cdn_att_account" class="w3tc-ignore-change" type="text"
           <?php $this->sealing_disabled('cdn') ?> name="cdn.att.account" value="<?php echo htmlspecialchars($this->_config->get_string('cdn.att.account')); ?>" size="60" />

    <?php _e('Token:', 'w3-total-cache'); ?>

        <input id="cdn_att_token" class="w3tc-ignore-change" type="password"
           <?php $this->sealing_disabled('cdn') ?> name="cdn.att.token" value="<?php echo htmlspecialchars($this->_config->get_string('cdn.att.token')); ?>" size="60" />

	<?php _e('<acronym title="Secure Sockets Layer">SSL</acronym> support:', 'w3-total-cache'); ?>

		<select id="cdn_att_ssl" name="cdn.att.ssl" <?php $this->sealing_disabled('cdn') ?>>
			<option value="auto"<?php selected($this->_config->get_string('cdn.att.ssl'), 'auto'); ?>><?php _e('Auto (determine connection type automatically)', 'w3-total-cache'); ?></option>
			<option value="enabled"<?php selected($this->_config->get_string('cdn.att.ssl'), 'enabled'); ?>><?php _e('Enabled (always use SSL)', 'w3-total-cache'); ?></option>
			<option value="disabled"<?php selected($this->_config->get_string('cdn.att.ssl'), 'disabled'); ?>><?php _e('Disabled (always use HTTP)', 'w3-total-cache'); ?></option>
		</select>

<?php _e('Some <acronym>CDN</acronym> providers may or may not support <acronym title="Secure Sockets Layer">SSL</acronym>, contact your vendor for more information.', 'w3-total-cache'); ?>

    <?php _e('Replace site\'s hostname with:', 'w3-total-cache'); ?>

		<?php $cnames = $this->_config->get_array('cdn.att.domain'); include W3TC_INC_DIR . '/options/cdn/common/cnames.php'; ?>

<?php _e('Enter the hostname provided by your <acronym>CDN</acronym> provider, this value will replace your site\'s hostname in the <acronym title="Hypertext Markup Language">HTML</acronym>.', 'w3-total-cache'); ?>

        <input id="cdn_test" class="button {type: 'att', nonce: '<?php echo wp_create_nonce('w3tc'); ?>'}" type="button" value="Test AT&T" />


text:
using System.Collections.Generic;
using Xunit;
using Yaapii.Atoms.Enumerable;

namespace Yaapii.Atoms.Enumerator.Tests
{
    public sealed class DistinctTest
    {
        [Fact]
        public void MergesEntries()
        {
            Assert.True(
                new Enumerable.LengthOf(
                    new ManyOf<string>(
                        new Distinct<string>(
                            new ManyOf<IEnumerator<string>>(
                                new ManyOf<string>("A", "B", "F").GetEnumerator(),
                                new ManyOf<string>("A", "E", "F").GetEnumerator()
                            )
                        )
                    )
                ).Value() == 4);
        }

        [Fact]
        public void Resets()
        {
            var e =
                new Distinct<string>(
                    new ManyOf<IEnumerator<string>>(
                        new ManyOf<string>("A").GetEnumerator(),
                        new ManyOf<string>("A").GetEnumerator()
                    )
                );

            e.MoveNext();
            e.Reset();

            Assert.True(e.MoveNext());
        }

        [Fact]
        public void WorksWithEmpties()
        {
            Assert.True(
                new Enumerable.LengthOf(
                    new ManyOf<string>(
                        new Distinct<string>(
                            new ManyOf<IEnumerator<string>>(
                                new ManyOf<string>().GetEnumerator(),
                                new ManyOf<string>().GetEnumerator()
                            )
                        )
                    )
                ).Value() == 0);
        }
    }
}


text:
<?php
return array (
  'Basic settings' => 'Základní nastavení',
  'Confirm image deleting' => 'Potvrďte smazání obrázku',
  'Cancel' => 'Zrušit',
  'Dashboard' => 'Nástěnka',
  'Delete' => 'Smazat',
  'E.g. http://example.com/humhub' => 'Např. http://example.com/humhub',
  'New users will automatically added to these space(s).' => 'Do těchto prostorů budou automaticky přidání noví uživatelé.',
  'Save' => 'Uložit',
  'You\'re using no logo at the moment. Upload your logo now.' => 'V tuto chvíli se nezobrazuje žádné logo. Můžete nějaké nahrát.',
);