text:
{-# LANGUAGE PatternSynonyms #-}
module BundleExport(P(.., A), Q(B)) where

data P = P

data Q = Q

pattern A = P
pattern B = Q


text:
package com.yaconfig.server.message;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class YAServerMessageDecoder extends ByteToMessageDecoder{

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

		int length = in.readInt();
		int version = in.readInt();
		int type = in.readInt();
		int serverStatus = in.readInt();
		long sequenceNum = in.readLong();
		String serverID = readString(in);

		YAServerMessageHeader header = new YAServerMessageHeader();
		header.version = version;
		header.type = type;
		header.serverStatus = serverStatus;
		header.sequenceNum = sequenceNum;
		header.serverID = serverID;

		String key = readString(in);
		byte[] value = readByte(in);

		YAServerMessage yamsg = new YAServerMessage(header,key,value);
		out.add(yamsg);

	}

	protected byte[] readByte(ByteBuf in){
		int length = in.readInt();
		byte[] b = new byte[length];
		in.readBytes(b);

		return b;
	}

	protected String readString(ByteBuf in){
		byte[] b = readByte(in);
		return new String(b);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.scala
package lang
package resolve
package processor

import com.intellij.psi._
import scala.collection.{mutable, Set}
import psi.api.base.patterns.ScBindingPattern
import psi.api.toplevel.typedef.ScTypeDefinition
import psi.ScalaPsiUtil
import caches.CachesUtil
import extensions.toPsiNamedElementExt
import processor.CompletionProcessor.QualifiedName
import psi.types.{PhysicalSignature, Signature, ScType, ScSubstitutor}
import psi.api.statements.{ScTypeAlias, ScFunction}
import psi.api.toplevel.imports.usages.ImportUsed
import completion.ScalaCompletionUtil

object CompletionProcessor {
  case class QualifiedName(name: String, isNamedParameter: Boolean)

  def getQualifiedName(result: ScalaResolveResult): QualifiedName = {
    val name = result.isRenamed match {
      case Some(str) => str
      case None => result.name
    }
    val isNamedParameter = result.isNamedParameter

    QualifiedName(name, isNamedParameter)
  }
}

class CompletionProcessor(override val kinds: Set[ResolveTargets.Value],
                          val place: PsiElement,
                          val collectImplicits: Boolean = false,
                          forName: Option[String] = None,
                          postProcess: ScalaResolveResult => Unit = r => {},
                          val includePrefixImports: Boolean = true) extends BaseProcessor(kinds)
                                                                             with PrecedenceHelper[QualifiedName] {
  protected val precedence: mutable.HashMap[QualifiedName, Int] = new mutable.HashMap[QualifiedName, Int]()

  protected val signatures: mutable.HashMap[Signature, Boolean] = new mutable.HashMap[Signature, Boolean]()

  protected def getPlace: PsiElement = place

  protected def getQualifiedName(result: ScalaResolveResult): QualifiedName = CompletionProcessor.getQualifiedName(result)

  override protected def isCheckForEqualPrecedence = false

  protected def getTopPrecedence(result: ScalaResolveResult): Int = precedence.getOrElse(getQualifiedName(result), 0)

  protected def setTopPrecedence(result: ScalaResolveResult, i: Int) {
    precedence.put(getQualifiedName(result), i)
  }

  override protected def filterNot(p: ScalaResolveResult, n: ScalaResolveResult): Boolean = {
    getQualifiedName(p) == getQualifiedName(n) && super.filterNot(p, n)
  }

  def getSignature(element: PsiNamedElement, substitutor: => ScSubstitutor): Option[Signature] = {
    element match {
      case method: PsiMethod => Some(new PhysicalSignature(method, substitutor))
      case td: ScTypeAlias => None
      case td: PsiClass => None
      case _ => Some(new Signature(element.name, Stream.empty, 0, substitutor, element))
    }
  }

  def execute(_element: PsiElement, state: ResolveState): Boolean = {
    if (!_element.isInstanceOf[PsiElement]) return false
    val element = _element.asInstanceOf[PsiNamedElement]
    forName match {
      case Some(name) if element.name != name => return true
      case _ =>
    }

    lazy val substitutor: ScSubstitutor = Option(state.get(ScSubstitutor.key)).getOrElse(ScSubstitutor.empty)
    lazy val isRenamed: Option[String] = Option(state.get(ResolverEnv.nameKey))
    lazy val implFunction: Option[PsiNamedElement] = Option(state.get(CachesUtil.IMPLICIT_FUNCTION))
    lazy val isNamedParameter: Boolean = Option(state.get(CachesUtil.NAMED_PARAM_KEY)).exists(_.booleanValue())
    val fromType: Option[ScType] = Option(state.get(BaseProcessor.FROM_TYPE_KEY))
    val importsUsed: Set[ImportUsed] = Option(state.get(ImportUsed.key)).getOrElse(Set.empty)
    val prefixCompletion: Boolean = Option(state.get(ScalaCompletionUtil.PREFIX_COMPLETION_KEY)).getOrElse(false)

    def _addResult(result: ScalaResolveResult) {
      val signature: Option[Signature] = getSignature(element, substitutor)
      val forImplicit = implFunction != None
      if (!forImplicit) {
        if (levelSet.contains(result)) {
          if (result.prefixCompletion) {
            levelSet.remove(result)
            addResult(result)
          }
        } else addResult(result)
        signature.foreach(sign => signatures += ((sign, forImplicit)))
      } else {
        signature match {
          case Some(sign) =>
            signatures.get(sign) match {
              case Some(true) =>
                val iterator = levelSet.iterator()
                while (iterator.hasNext) {
                  val next = iterator.next()
                  if (getQualifiedName(next) == getQualifiedName(result) && next.element != result.element &&
                    signature == getSignature(next.element, next.substitutor)) {
                    iterator.remove()
                  }
                }
              case Some(false) => //do nothing
              case None =>
                addResult(result)
                signature.foreach(sign => signatures += ((sign, forImplicit)))
            }
          case _ =>
            if (levelSet.contains(result)) {
              if (result.prefixCompletion) {
                levelSet.remove(result)
                addResult(result)
              }
            } else addResult(result)
        }
      }
    }

    element match {
      case fun: ScFunction if fun.isConstructor => return true //do not add constructor
      case td: ScTypeDefinition =>
        if (kindMatches(td)) {
          val result = new ScalaResolveResult(td, substitutor, nameShadow = isRenamed,
            implicitFunction = implFunction, fromType = fromType, importsUsed = importsUsed, prefixCompletion = prefixCompletion)
          _addResult(result)
        }
        ScalaPsiUtil.getCompanionModule(td) match {
          case Some(td: ScTypeDefinition) if kindMatches(td) =>
            val result = new ScalaResolveResult(td, substitutor,
              nameShadow = isRenamed, implicitFunction = implFunction, fromType = fromType, importsUsed = importsUsed,
              prefixCompletion = prefixCompletion)
            _addResult(result)
          case _ =>
        }
      case named: PsiNamedElement =>
        if (kindMatches(element)) {
          element match {
            case method: PsiMethod =>
              val result = new ScalaResolveResult(named, substitutor, nameShadow = isRenamed,
                implicitFunction = implFunction, isNamedParameter = isNamedParameter, fromType = fromType,
                importsUsed = importsUsed, prefixCompletion = prefixCompletion)
              _addResult(result)
            case bindingPattern: ScBindingPattern =>
              val result = new ScalaResolveResult(named, substitutor, nameShadow = isRenamed,
                implicitFunction = implFunction, isNamedParameter = isNamedParameter, fromType = fromType,
                importsUsed = importsUsed, prefixCompletion = prefixCompletion)
              _addResult(result)
            case _ =>
              val result = new ScalaResolveResult(named, substitutor, nameShadow = isRenamed,
                implicitFunction = implFunction, isNamedParameter = isNamedParameter, fromType = fromType,
                importsUsed = importsUsed, prefixCompletion = prefixCompletion)
              _addResult(result)
          }
        }
    }
    true
  }

  override def changedLevel: Boolean = {
    if (levelSet.isEmpty) return true
    val iterator = levelSet.iterator()
    while (iterator.hasNext) {
      val next = iterator.next()
      postProcess(next)
      candidatesSet += next
    }
    qualifiedNamesSet.addAll(levelQualifiedNamesSet)
    levelSet.clear()
    levelQualifiedNamesSet.clear()
    true
  }

  override def candidatesS: Set[ScalaResolveResult] = {
    val res = candidatesSet
    val iterator = levelSet.iterator()
    while (iterator.hasNext) {
      val next = iterator.next()
      postProcess(next)
      res += next
    }
    res
  }
}


text:
import copy
import datetime
from base64 import b64decode
from uuid import uuid4

from botocore.signers import CloudFrontSigner
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.deconstruct import deconstructible
from django.utils.encoding import filepath_to_uri
from django.utils.text import get_valid_filename
from django.utils.timezone import now
from storages.backends.s3boto3 import S3Boto3Storage

class S3Storage(S3Boto3Storage):
    """
    Wraps the s3 storage class but allows for configurable kwargs per
    backend. The upstream storage class is responsible for setting all
    of the kwargs.
    """

    def __init__(self, *args, config, **kwargs):
        super().__init__(*args, **config, **kwargs)

        # If the attr was not set by the upstream, it's probably wrong
        if not all([hasattr(self, name) for name in config]):
            raise ImproperlyConfigured(
                f"Could not set all kwargs for S3 storage using {config}"
            )

    def copy(self, *, from_name, to_name):
        from_name = self._normalize_name(self._clean_name(from_name))
        to_name = self._normalize_name(self._clean_name(to_name))

        self.connection.meta.client.copy_object(
            Bucket=self.bucket_name,
            CopySource=f"{self.bucket_name}/{from_name}",
            Key=to_name,
        )

@deconstructible
class PrivateS3Storage(S3Storage):
    def __init__(self, *args, **kwargs):
        super().__init__(
            *args, config=settings.PRIVATE_S3_STORAGE_KWARGS, **kwargs
        )

    def url(self, *args, **kwargs):
        """
        Urls for private storage should never be used, as S3Storage will
        generate a signed URL which will allow users to download the file.
        """
        raise NotImplementedError

@deconstructible
class ProtectedS3Storage(S3Storage):
    def __init__(self, *args, internal=False, **kwargs):
        config = copy.deepcopy(settings.PROTECTED_S3_STORAGE_KWARGS)

        # Setting a custom domain will strip the aws headers when using minio.
        # You can get these headers back by setting the custom_domain to None
        if internal:
            config["custom_domain"] = None

        super().__init__(*args, config=config, **kwargs)

    def cloudfront_signed_url(self, *, name, domain=None, expire=None):
        """
        Create a signed url that will be valid until the specific expiry date
        provided using a canned policy.

        Note: This grants the user permission to read the file.

        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#id57
        """
        name = self._normalize_name(self._clean_name(name))

        if domain is None:
            domain = settings.PROTECTED_S3_STORAGE_CLOUDFRONT_DOMAIN

        url = f"https://{domain}/{filepath_to_uri(name)}"

        if expire is None:
            expire = now() + datetime.timedelta(
                seconds=settings.CLOUDFRONT_URL_EXPIRY_SECONDS
            )

        return self._cloudfront_signer.generate_presigned_url(
            url, date_less_than=expire
        )

    @property
    def _cloudfront_signer(self):
        key_bytes = b64decode(
            settings.CLOUDFRONT_PRIVATE_KEY_BASE64.encode("ascii")
        )

        private_key = serialization.load_pem_private_key(
            key_bytes, password=None, backend=default_backend()
        )

        return CloudFrontSigner(
            settings.CLOUDFRONT_KEY_PAIR_ID,
            lambda m: private_key.sign(m, padding.PKCS1v15(), hashes.SHA1()),
        )

@deconstructible
class PublicS3Storage(S3Storage):
    def __init__(self, *args, **kwargs):
        super().__init__(
            *args, config=settings.PUBLIC_S3_STORAGE_KWARGS, **kwargs
        )

private_s3_storage = PrivateS3Storage()
protected_s3_storage = ProtectedS3Storage()
internal_protected_s3_storage = ProtectedS3Storage(internal=True)
public_s3_storage = PublicS3Storage()

storages = [private_s3_storage, protected_s3_storage, public_s3_storage]

if len({s.bucket_name for s in storages}) != len(storages):
    raise ImproperlyConfigured("Storage bucket names are not unique")

def get_logo_path(instance, filename):
    return f"logos/{instance.__class__.__name__.lower()}/{instance.pk}/{get_valid_filename(filename)}"

def get_pdf_path(instance, filename):
    return f"pdfs/{instance.__class__.__name__.lower()}/{instance.pk}/{get_valid_filename(filename)}"

def get_social_image_path(instance, filename):
    return f"social-images/{instance.__class__.__name__.lower()}/{instance.pk}/{get_valid_filename(filename)}"

def get_banner_path(instance, filename):
    return f"b/{instance.pk}/{get_valid_filename(filename)}"

def get_mugshot_path(instance, filename):
    time_prefix = now().strftime("%Y/%m/%d")
    extension = filename.split(".")[-1].lower()
    return f"mugshots/{time_prefix}/{uuid4()}.{extension}"


text:
#ifndef NTL_ZZVec__H
#define NTL_ZZVec__H

#include <NTL/ZZ.h>

NTL_OPEN_NNS

/*****************************************************************

The class ZZVec implements vectors of fixed-length ZZ's.
You can allocate a vector of ZZ's of a specified length, where
the maximum size of each ZZ is also specified.
These parameters can be specified once, either with a constructor,
or with SetSize.
It is an error to try to re-size a vector, or store a ZZ that
doesn't fit.
The space can be released with "kill", and then you are free to
call SetSize again.
If you want more flexible---but less efficient---vectors,
use vec_ZZ.

*****************************************************************/

class ZZVec {

private:
   ZZ* v;
   long len;
   long bsize;

public:
   ZZVec& operator=(const ZZVec&);
   ZZVec(const ZZVec&);

   long length() const { return len; }
   long BaseSize() const { return bsize; }
   void SetSize(long n, long d);
   void kill();

   ZZVec() : v(0), len(0), bsize(0) { }
   ZZVec(long n, long d) : v(0), len(0), bsize(0)  { SetSize(n, d); }
   ~ZZVec() { kill(); };

   ZZ* elts() { return v; }
   const ZZ* elts() const { return v; }

   ZZ& operator[](long i) { return v[i]; }
   const ZZ& operator[](long i) const { return v[i]; }

   void swap(ZZVec& x);

};

inline void swap(ZZVec& x, ZZVec& y) { x.swap(y); }

NTL_CLOSE_NNS

#endif


text:
<?php
/*
 * Default Events List Template
 * This page displays a list of events, called during the em_content() if this is an events list page.
 * You can override the default display settings pages by copying this file to yourthemefolder/plugins/events-manager/templates/ and modifying it however you need.
 * You can display events however you wish, there are a few variables made available to you:
 *
 * $args - the args passed onto EM_Events::output()
 *
 */
$args = apply_filters('em_content_events_args', $args);
//$args['arformat'] = 'foo';
if( get_option('dbem_css_evlist') ) echo "
";

echo EM_Events::output( $args );

if( get_option('dbem_css_evlist') ) echo "
";


text:
images
======

Images folder is for all your images


text:
/**
 * HistoryRow
 *
 * @author zhumeng
 *
 **/

'use strict';

import { Component } from 'react';

import React, {
  StyleSheet,
  Image,
  Text,
  View,
  Platform,
  TouchableHighlight,
  TouchableNativeFeedback,
} from 'react-native';

export default class HistoryRow extends Component {

  // https://facebook.github.io/react/docs/reusable-components.html#es6-classes
  constructor(props) {
    super(props);

    this.state = {
      selected: false
    }

    // Bind callback methods to make `this` the correct context.
    this._onPress = this._onPress.bind(this);
  }

  render () {
    let data = this.props.history.get('data')
    var date = (this.props.history.createdAt).toISOString().replace(/T.+/, '')
    switch (this.props.history.get('type')) {
      case 1 :
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.username}创建{data.tuanname}
            </Text>
          </View>
        );
      case 2 :
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.username}加入{data.tuanname}
            </Text>
          </View>
        );
      case 3 :
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.username}退出{data.tuanname}
            </Text>
          </View>
        );
      case 5 :
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.fromname}团的团名被{data.username}修改为{data.toname}
            </Text>
          </View>
        );
      case 6 :
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.fromname}团的口号被{data.username}修改为{data.toname}
            </Text>
          </View>
        );
      case 10:
        if (this.props.history.get('included')) {
          return (
            <View style={styles.container}>
              <Text style={styles.date}>{date}</Text>
              <Text style={styles.welcome}>
                {data.username}请大家{data.members.length + data.othersnum}人消费了{data.money} 元
              </Text>
            </View>
          );
        } else {
          return (
            <View style={styles.container}>
              <Text style={styles.date}>{date}</Text>
              <Text style={styles.welcome}>
                {data.username}请大家{data.members.length + data.othersnum}人消费了{data.money} 元
                (除我)
              </Text>
            </View>
          );
        }
      case  11:
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.username}请大家{data.members.length}人消费了{data.money}元(已撤销)
            </Text>
          </View>
        );
      case  12:
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.username}发起了一次{data.members.length}人筹款消费
            </Text>
          </View>
        );
      case  13:
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.username}发起的筹款消费已经结束
            </Text>
          </View>
        );
      case  14:
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              {data.username}发起了筹款消费(已撤销)
            </Text>
          </View>
        );
      default :
        return (
          <View style={styles.container}>
            <Text style={styles.date}>{date}</Text>
            <Text style={styles.welcome}>
              默认

            </Text>
          </View>
        );
    }

  }

  _onPress() {
    this.setState({
      selected: !this.state.selected
    });
    this.props.onSelect();
  }
}

var styles = StyleSheet.create({
  container : {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderColor: '#eee',
    paddingVertical : 10
  },
  date: {
    fontSize: 15,
    color: 'black',
    marginRight:5
  },
  welcome: {
    width: 210,
    fontSize: 15,
    color: 'black',
    flexDirection: 'row',
    flexWrap: 'wrap'
  }
});


text:
package io.dropwizard.jackson;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;

import java.sql.ClientInfoStatus;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;

public class FuzzyEnumModuleTest {
    private final ObjectMapper mapper = new ObjectMapper();

    private enum EnumWithLowercase {lower_case_enum, mixedCaseEnum}

    private enum EnumWithCreator {
        TEST;

        @JsonCreator
        public static EnumWithCreator fromString(String value) {
            return EnumWithCreator.TEST;
        }
    }

    private enum CurrencyCode {
        USD("United States dollar"),
        AUD("a_u_d"),
        CAD("c-a-d"),
        BLA("b.l.a"),
        EUR("Euro"),
        GBP("Pound sterling");

        private final String description;

        CurrencyCode(String name) {
            this.description = name;
        }

        @Override
        public String toString() {
            return description;
        }
    }

    @Before
    public void setUp() throws Exception {
        mapper.registerModule(new FuzzyEnumModule());
    }

    @Test
    public void mapsUpperCaseEnums() throws Exception {
        assertThat(mapper.readValue("\"SECONDS\"", TimeUnit.class))
                .isEqualTo(TimeUnit.SECONDS);
    }

    @Test
    public void mapsLowerCaseEnums() throws Exception {
        assertThat(mapper.readValue("\"milliseconds\"", TimeUnit.class))
                .isEqualTo(TimeUnit.MILLISECONDS);
    }

    @Test
    public void mapsPaddedEnums() throws Exception {
        assertThat(mapper.readValue("\"   MINUTES \"", TimeUnit.class))
                .isEqualTo(TimeUnit.MINUTES);
    }

    @Test
    public void mapsSpacedEnums() throws Exception {
        assertThat(mapper.readValue("\"   MILLI SECONDS \"", TimeUnit.class))
                .isEqualTo(TimeUnit.MILLISECONDS);
    }

    @Test
    public void mapsDashedEnums() throws Exception {
        assertThat(mapper.readValue("\"REASON-UNKNOWN\"", ClientInfoStatus.class))
                .isEqualTo(ClientInfoStatus.REASON_UNKNOWN);
    }

    @Test
    public void mapsDottedEnums() throws Exception {
        assertThat(mapper.readValue("\"REASON.UNKNOWN\"", ClientInfoStatus.class))
                .isEqualTo(ClientInfoStatus.REASON_UNKNOWN);
    }

    @Test
    public void mapsWhenEnumHasCreator() throws Exception {
        assertThat(mapper.readValue("\"BLA\"", EnumWithCreator.class))
                .isEqualTo(EnumWithCreator.TEST);
    }

    @Test
    public void failsOnIncorrectValue() throws Exception {
        try {
            mapper.readValue("\"wrong\"", TimeUnit.class);
            failBecauseExceptionWasNotThrown(JsonMappingException.class);
        } catch (JsonMappingException e) {
            assertThat(e.getOriginalMessage())
                    .isEqualTo("wrong was not one of [NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS]");
        }
    }

    @Test
    public void mapsToLowerCaseEnums() throws Exception {
        assertThat(mapper.readValue("\"lower_case_enum\"", EnumWithLowercase.class))
                .isEqualTo(EnumWithLowercase.lower_case_enum);
    }

    @Test
    public void mapsMixedCaseEnums() throws Exception {
        assertThat(mapper.readValue("\"mixedCaseEnum\"", EnumWithLowercase.class))
                .isEqualTo(EnumWithLowercase.mixedCaseEnum);
    }

    @Test
    public void readsEnumsUsingToString() throws Exception {
        final ObjectMapper toStringEnumsMapper = mapper.copy()
                .configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
        assertThat(toStringEnumsMapper.readValue("\"Pound sterling\"", CurrencyCode.class)).isEqualTo(CurrencyCode.GBP);
    }

    @Test
    public void readsEnumsUsingToStringWithDeserializationFeatureOff() throws Exception {
        assertThat(mapper.readValue("\"Pound sterling\"", CurrencyCode.class)).isEqualTo(CurrencyCode.GBP);
        assertThat(mapper.readValue("\"a_u_d\"", CurrencyCode.class)).isEqualTo(CurrencyCode.AUD);
        assertThat(mapper.readValue("\"c-a-d\"", CurrencyCode.class)).isEqualTo(CurrencyCode.CAD);
        assertThat(mapper.readValue("\"b.l.a\"", CurrencyCode.class)).isEqualTo(CurrencyCode.BLA);
    }
}


text:
"""
Google Web App gateway tests.

@since: 0.3.1
"""

import unittest

from StringIO import StringIO

from google.appengine.ext import webapp

import pyamf
from pyamf import remoting
from pyamf.remoting.gateway import google as _google

class WebAppGatewayTestCase(unittest.TestCase):
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.gw = _google.WebAppGateway()

        self.environ = {
            'wsgi.input': StringIO(),
            'wsgi.output': StringIO()
        }

        self.request = webapp.Request(self.environ)
        self.response = webapp.Response()

        self.gw.initialize(self.request, self.response)

    def test_get(self):
        self.gw.get()

        self.assertEquals(self.response.__dict__['_Response__status'][0], 405)

    def test_bad_request(self):
        self.environ['wsgi.input'].write('Bad request')
        self.environ['wsgi.input'].seek(0, 0)

        self.gw.post()
        self.assertEquals(self.response.__dict__['_Response__status'][0], 400)

    def test_unknown_request(self):
        self.environ['wsgi.input'].write(
            '\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1\x00\x00\x00'
            '\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01\x61\x02\x00'
            '\x01\x61\x00\x00\x09')
        self.environ['wsgi.input'].seek(0, 0)

        self.gw.post()

        self.assertEquals(self.response.__dict__['_Response__status'][0], 200)

        envelope = remoting.decode(self.response.out.getvalue())
        message = envelope['/1']

        self.assertEquals(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEquals(body.code, 'Service.ResourceNotFound')

    def test_expose_request(self):
        self.executed = False

        def test(request):
            self.assertEquals(self.request, request)
            self.assertTrue(hasattr(self.request, 'amf_request'))

            self.executed = True

        self.gw.expose_request = True
        self.gw.addService(test, 'test.test')

        self.environ['wsgi.input'].write('\x00\x00\x00\x00\x00\x01\x00\x09'
            'test.test\x00\x02/1\x00\x00\x00\x05\x0a\x00\x00\x00\x00')
        self.environ['wsgi.input'].seek(0, 0)

        self.gw.post()

        self.assertTrue(self.executed)

    def test_timezone(self):
        import datetime

        self.executed = False

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEquals(d, now + td)
            self.executed = True

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        msg = remoting.Envelope(amfVersion=pyamf.AMF0, clientType=0)
        msg['/1'] = remoting.Request(target='echo', body=[now])

        stream = remoting.encode(msg)
        self.environ['wsgi.input'] = stream
        self.gw.post()

        envelope = remoting.decode(self.response.out.getvalue())
        message = envelope['/1']

        self.assertEquals(message.body, now)
        self.assertTrue(self.executed)

def suite():
    suite = unittest.TestSuite()

    suite.addTest(unittest.makeSuite(WebAppGatewayTestCase))

    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')


text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

View/Helper/TinySrc.php

Global

                      Classes

\Zend_View_Helper_TinySrc

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to license@zend.com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_View

subpackage

Helper

\Zend_View_Helper_TinySrc
jump to top

Helper for generating urls and/or image tags for use with tinysrc.net

tinysrc.net provides an API for generating scaled, browser device-specific
images. In essence, you pass the API the URL to an image on your own server,
and tinysrc.net then provides the appropriate image based on the device that
accesses it.

Additionally, tinysrc.net allows you to specify additional configuration via
the API:

image size. You may define this as:

explicit size

subtractive size (size of screen minus specified number of pixels)

percentage size (percentage of screen size))

image format. This will convert the image to the given format; allowed
values are "png" or "jpeg". By default, gif images are converted to png.

This helper allows you to specify all configuration options, as well as:

whether or not to generate the full image tag (or just the URL)

base url to images (which should include the protocol, server, and
optionally port and base path)

Extends from

\Zend_View_Helper_HtmlElement

see

\http://tinysrc.net/

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_View

subpackage

Helper

Constants

                TINYSRC_BASE
                = 'http://i.tinysrc.mobi'

Properties

string
                 $_baseUrl= ''

Base URL for images

Details

Type

string

bool
                 $_createTagFlag= 'true'

Whether or not to create an image tag

Default valuetrueDetails

Type

bool

array
                 $_defaultOptions= 'array'

Default options

Used when determining what options were passed, and needing to merge
them with default options.

Default valuearrayDetails

Type

array

string
                 $_dimensions= ''

Default width and height

Details

Type

string

string
                 $_format= ''

Default image format to use

Details

Type

string

Methods

_htmlAttribs(
          array $attribs
          )

        :
          string

Converts an associative array to a string of tag attributes.

Inherited from:
                    \Zend_View_Helper_HtmlElement::_htmlAttribs()

Parameters

Name
Type
Description

$attribs
array

From this array, each key-value pair is converted to an attribute name and value.

Returns

Type
Description

string
The XHTML for the attributes.

Details

access

public

_isStrictDoctype(

          )

        :
          boolean

Is doctype strict?

Inherited from:
                    \Zend_View_Helper_HtmlElement::_isStrictDoctype()

Returns

Type
Description

boolean

_isXhtml(

          )

        :
          boolean

Is doctype XHTML?

Inherited from:
                    \Zend_View_Helper_HtmlElement::_isXhtml()

Returns

Type
Description

boolean

_mergeBaseUrl(
          array $options
          )

        :
          string

Determine whether to use default base URL, or base URL from options

Parameters

Name
Type
Description

$options
array

Returns

Type
Description

string

_mergeDimensions(
          array $options
          )

        :
          string

Determine whether to use default dimensions, or those passed in options.

Parameters

Name
Type
Description

$options
array

Returns

Type
Description

string

_mergeFormat(
          array $options
          )

        :
          string

Determine whether to use default format or format provided in options.

Parameters

Name
Type
Description

$options
array

Returns

Type
Description

string

_normalizeId(
          string $value
          )

        :
          string

Normalize an ID

Inherited from:
                    \Zend_View_Helper_HtmlElement::_normalizeId()

Parameters

Name
Type
Description

$value
string

Returns

Type
Description

string

_validateDimension(
          string $dim
          )

        :
          bool

Validate a dimension

Dimensions may be integers, optionally preceded by '-' or 'x'.

Parameters

Name
Type
Description

$dim
string

Returns

Type
Description

bool

createTag(

          )

        :
          bool

Should the helper create an image tag?

Returns

Type
Description

bool

direct(

          )

        :
          void

Strategy pattern: currently unutilized

Inherited from:
                    \Zend_View_Helper_Abstract::direct()

getBaseUrl(

          )

        :
          string

Get base URL for images

If none already set, uses the ServerUrl and BaseUrl view helpers to
determine the base URL to images.

Returns

Type
Description

string

getClosingBracket(

          )

        :
          string

Get the tag closing bracket

Inherited from:
                    \Zend_View_Helper_HtmlElement::getClosingBracket()

Returns

Type
Description

string

setBaseUrl(
          string $url
          )

        :
          \Zend_View_Helper_TinySrc

Set base URL for images

Parameters

Name
Type
Description

$url
string

Returns

Type
Description

\Zend_View_Helper_TinySrc

setCreateTag(
          bool $flag
          )

        :
          \Zend_View_Helper_TinySrc

Set state of "create tag" flag

Parameters

Name
Type
Description

$flag
bool

Returns

Type
Description

\Zend_View_Helper_TinySrc

setDefaultDimensions(
          null|int|string $width
              =
              null, null|int|string $height
              =
              null
          )

        :
          \Zend_View_Helper_TinySrc

Set default dimensions

If null is specified for width, default dimensions will be cleared. If
only width is specified, only width will be used. If either dimension
fails validation, an exception is raised.

Parameters

Name
Type
Description

$width
null|int|string

$height
null|int|string

Returns

Type
Description

\Zend_View_Helper_TinySrc

Throws

Exception
Description

\Zend_View_Exception

setDefaultFormat(
          null|string $format
              =
              null
          )

        :
          \Zend_View_Helper_TinySrc

Set default image format

If set, this will set the default format to use on all images.

Parameters

Name
Type
Description

$format
null|string

Returns

Type
Description

\Zend_View_Helper_TinySrc

Throws

Exception
Description

\Zend_View_Exception

setView(
          \Zend_View_Interface $view
          )

        :
          \Zend_View_Helper_Abstract

Set the View object

Inherited from:
                    \Zend_View_Helper_Abstract::setView()

Parameters

Name
Type
Description

$view
\Zend_View_Interface

Returns

Type
Description

\Zend_View_Helper_Abstract

tinySrc(
          mixed $image
              =
              null, array $options
              =
              array
          )

        :
          void

Generate a link or image tag pointing to tinysrc.net

Parameters

Name
Type
Description

$image
mixed

$options
array

Documentation was generated by DocBlox 0.13.3.


text:
namespace {

// Number of samples to average the most recent capture and encode time
// over.
const int kStatisticsWindow = 3;

// The hard limit is 30fps or 33ms per recording cycle.
const int64_t kDefaultMinimumIntervalMs = 33;

// Controls how much CPU time we can use for encode and capture.
// Range of this value is between 0 to 1. 0 means using 0% of of all CPUs
// available while 1 means using 100% of all CPUs available.
const double kRecordingCpuConsumption = 0.5;

// Maximum number of captured frames in the encoding queue. Currently capturer
// implementations do not allow to keep more than 2 DesktopFrame objects.
static const int kMaxFramesInEncodingQueue = 2;

// Maximum number of unacknowledged frames. Ignored if the client doesn't
// support ACKs. This value was chosen experimentally, using synthetic
// performance tests (see ProtocolPerfTest), to maximize frame rate, while
// keeping round-trip latency low.
static const int kMaxUnacknowledgedFrames = 4;

}  // namespace

namespace remoting {
namespace protocol {

// We assume that the number of available cores is constant.
CaptureScheduler::CaptureScheduler(const base::Closure& capture_closure)
    : capture_closure_(capture_closure),
      tick_clock_(new base::DefaultTickClock()),
      capture_timer_(new base::Timer(false, false)),
      minimum_interval_(
          base::TimeDelta::FromMilliseconds(kDefaultMinimumIntervalMs)),
      num_of_processors_(base::SysInfo::NumberOfProcessors()),
      capture_time_(kStatisticsWindow),
      encode_time_(kStatisticsWindow),
      num_encoding_frames_(0),
      num_unacknowledged_frames_(0),
      capture_pending_(false),
      is_paused_(false),
      next_frame_id_(0) {
  DCHECK(num_of_processors_);
}

CaptureScheduler::~CaptureScheduler() {
}

void CaptureScheduler::Start() {
  DCHECK(thread_checker_.CalledOnValidThread());

  ScheduleNextCapture();
}

void CaptureScheduler::Pause(bool pause) {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (is_paused_ != pause) {
    is_paused_ = pause;

    if (is_paused_) {
      capture_timer_->Stop();
    } else {
      ScheduleNextCapture();
    }
  }
}

void CaptureScheduler::OnCaptureCompleted() {
  DCHECK(thread_checker_.CalledOnValidThread());

  capture_pending_ = false;
  capture_time_.Record(
      (tick_clock_->NowTicks() - last_capture_started_time_).InMilliseconds());

  ++num_encoding_frames_;

  ScheduleNextCapture();
}

void CaptureScheduler::OnFrameEncoded(VideoPacket* packet) {
  DCHECK(thread_checker_.CalledOnValidThread());

  // Set packet_id for the outgoing packet.
  packet->set_frame_id(next_frame_id_);
  ++next_frame_id_;

  // Update internal stats.
  encode_time_.Record(packet->encode_time_ms());

  --num_encoding_frames_;
  ++num_unacknowledged_frames_;

  ScheduleNextCapture();
}

void CaptureScheduler::OnFrameSent() {
  DCHECK(thread_checker_.CalledOnValidThread());

  ScheduleNextCapture();
}

void CaptureScheduler::ProcessVideoAck(scoped_ptr<VideoAck> video_ack) {
  DCHECK(thread_checker_.CalledOnValidThread());

  --num_unacknowledged_frames_;
  DCHECK_GE(num_unacknowledged_frames_, 0);

  ScheduleNextCapture();
}

void CaptureScheduler::SetTickClockForTest(
    scoped_ptr<base::TickClock> tick_clock) {
  tick_clock_ = std::move(tick_clock);
}

void CaptureScheduler::SetTimerForTest(scoped_ptr<base::Timer> timer) {
  capture_timer_ = std::move(timer);
}

void CaptureScheduler::SetNumOfProcessorsForTest(int num_of_processors) {
  num_of_processors_ = num_of_processors;
}

void CaptureScheduler::ScheduleNextCapture() {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (is_paused_ || capture_pending_ ||
      num_encoding_frames_ >= kMaxFramesInEncodingQueue) {
    return;
  }

  if (num_encoding_frames_ + num_unacknowledged_frames_ >=
      kMaxUnacknowledgedFrames) {
    return;
  }

  // Delay by an amount chosen such that if capture and encode times
  // continue to follow the averages, then we'll consume the target
  // fraction of CPU across all cores.
  base::TimeDelta delay =
      std::max(minimum_interval_,
               base::TimeDelta::FromMilliseconds(
                   (capture_time_.Average() + encode_time_.Average()) /
                   (kRecordingCpuConsumption * num_of_processors_)));

  // Account for the time that has passed since the last capture.
  delay = std::max(base::TimeDelta(), delay - (tick_clock_->NowTicks() -
                                               last_capture_started_time_));

  capture_timer_->Start(
      FROM_HERE, delay,
      base::Bind(&CaptureScheduler::CaptureNextFrame, base::Unretained(this)));
}

void CaptureScheduler::CaptureNextFrame() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!is_paused_);
  DCHECK(!capture_pending_);

  capture_pending_ = true;
  last_capture_started_time_ = tick_clock_->NowTicks();
  capture_closure_.Run();
}

}  // namespace protocol
}  // namespace remoting


text:
"""Extremely random forest graph builder. go/brain-tree."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import math
import random

import tensorflow as tf

from tensorflow.contrib.tensor_forest.python.ops import inference_ops
from tensorflow.contrib.tensor_forest.python.ops import training_ops

# If tree[i][0] equals this value, then i is a leaf node.
LEAF_NODE = -1

# A convenience class for holding random forest hyperparameters.
#
# To just get some good default parameters, use:
#   hparams = ForestHParams(num_classes=2, num_features=40).fill()
#
# Note that num_classes can not be inferred and so must always be specified.
# Also, either num_splits_to_consider or num_features should be set.
#
# To override specific values, pass them to the constructor:
#   hparams = ForestHParams(num_classes=5, num_trees=10, num_features=5).fill()
#
# TODO(thomaswc): Inherit from tf.HParams when that is publicly available.
class ForestHParams(object):
  """A base class for holding hyperparameters and calculating good defaults."""

  def __init__(self, num_trees=100, max_nodes=10000, bagging_fraction=1.0,
               max_depth=0, num_splits_to_consider=0,
               feature_bagging_fraction=1.0,
               max_fertile_nodes=0, split_after_samples=250,
               valid_leaf_threshold=1, **kwargs):
    self.num_trees = num_trees
    self.max_nodes = max_nodes
    self.bagging_fraction = bagging_fraction
    self.feature_bagging_fraction = feature_bagging_fraction
    self.max_depth = max_depth
    self.num_splits_to_consider = num_splits_to_consider
    self.max_fertile_nodes = max_fertile_nodes
    self.split_after_samples = split_after_samples
    self.valid_leaf_threshold = valid_leaf_threshold

    for name, value in kwargs.items():
      setattr(self, name, value)

  def values(self):
    return self.__dict__

  def fill(self):
    """Intelligently sets any non-specific parameters."""
    # Fail fast if num_classes or num_features isn't set.
    _ = getattr(self, 'num_classes')
    _ = getattr(self, 'num_features')

    self.training_library_base_dir = getattr(
        self, 'training_library_base_dir', '')
    self.inference_library_base_dir = getattr(
        self, 'inference_library_base_dir', '')

    self.bagged_num_features = int(self.feature_bagging_fraction *
                                   self.num_features)

    self.bagged_features = None
    if self.feature_bagging_fraction < 1.0:
      self.bagged_features = [random.sample(
          range(self.num_features),
          self.bagged_num_features) for _ in range(self.num_trees)]

    self.regression = getattr(self, 'regression', False)

    # Num_outputs is the actual number of outputs (a single prediction for
    # classification, a N-dimenensional point for regression).
    self.num_outputs = self.num_classes if self.regression else 1

    # Add an extra column to classes for storing counts, which is needed for
    # regression and avoids having to recompute sums for classification.
    self.num_output_columns = self.num_classes + 1

    # Allow each tree to be unbalanced by up to a factor of 2.
    self.max_depth = (self.max_depth or
                      int(2 * math.ceil(math.log(self.max_nodes, 2))))

    # The Random Forest literature recommends sqrt(# features) for
    # classification problems, and p/3 for regression problems.
    # TODO(thomaswc): Consider capping this for large number of features.
    self.num_splits_to_consider = (
        self.num_splits_to_consider or
        max(10, int(math.ceil(math.sqrt(self.num_features)))))

    # max_fertile_nodes doesn't effect performance, only training speed.
    # We therefore set it primarily based upon space considerations.
    # Each fertile node takes up num_splits_to_consider times as much
    # as space as a non-fertile node.  We want the fertile nodes to in
    # total only take up as much space as the non-fertile nodes, so
    num_fertile = int(math.ceil(self.max_nodes / self.num_splits_to_consider))
    # But always use at least 1000 accumulate slots.
    num_fertile = max(num_fertile, 1000)
    self.max_fertile_nodes = self.max_fertile_nodes or num_fertile
    # But it also never needs to be larger than the number of leaves,
    # which is max_nodes / 2.
    self.max_fertile_nodes = min(self.max_fertile_nodes,
                                 int(math.ceil(self.max_nodes / 2.0)))

    # We have num_splits_to_consider slots to fill, and we want to spend
    # approximately split_after_samples samples initializing them.
    num_split_initializiations_per_input = max(1, int(math.floor(
        self.num_splits_to_consider / self.split_after_samples)))
    self.split_initializations_per_input = getattr(
        self, 'split_initializations_per_input',
        num_split_initializiations_per_input)

    # If base_random_seed is 0, the current time will be used to seed the
    # random number generators for each tree.  If non-zero, the i-th tree
    # will be seeded with base_random_seed + i.
    self.base_random_seed = getattr(self, 'base_random_seed', 0)

    return self

# A simple container to hold the training variables for a single tree.
class TreeTrainingVariables(object):
  """Stores tf.Variables for training a single random tree.

  Uses tf.get_variable to get tree-specific names so that this can be used
  with a tf.learn-style implementation (one that trains a model, saves it,
  then relies on restoring that model to evaluate).
  """

  def __init__(self, params, tree_num, training):
    self.tree = tf.get_variable(
        name=self.get_tree_name('tree', tree_num), dtype=tf.int32,
        initializer=tf.constant(
            [[-1, -1]] + [[-2, -1]] * (params.max_nodes - 1)))
    self.tree_thresholds = tf.get_variable(
        name=self.get_tree_name('tree_thresholds', tree_num),
        shape=[params.max_nodes],
        initializer=tf.constant_initializer(-1.0))
    self.tree_depths = tf.get_variable(
        name=self.get_tree_name('tree_depths', tree_num),
        shape=[params.max_nodes],
        dtype=tf.int32,
        initializer=tf.constant_initializer(1))
    self.end_of_tree = tf.get_variable(
        name=self.get_tree_name('end_of_tree', tree_num),
        dtype=tf.int32,
        initializer=tf.constant([1]))

    if training:
      self.non_fertile_leaves = tf.get_variable(
          name=self.get_tree_name('non_fertile_leaves', tree_num),
          dtype=tf.int32,
          initializer=tf.constant([0]))
      self.non_fertile_leaf_scores = tf.get_variable(
          name=self.get_tree_name('non_fertile_leaf_scores', tree_num),
          initializer=tf.constant([1.0]))

      self.node_to_accumulator_map = tf.get_variable(
          name=self.get_tree_name('node_to_accumulator_map', tree_num),
          shape=[params.max_nodes],
          dtype=tf.int32,
          initializer=tf.constant_initializer(-1))

      self.candidate_split_features = tf.get_variable(
          name=self.get_tree_name('candidate_split_features', tree_num),
          shape=[params.max_fertile_nodes, params.num_splits_to_consider],
          dtype=tf.int32,
          initializer=tf.constant_initializer(-1))
      self.candidate_split_thresholds = tf.get_variable(
          name=self.get_tree_name('candidate_split_thresholds', tree_num),
          shape=[params.max_fertile_nodes, params.num_splits_to_consider],
          initializer=tf.constant_initializer(0.0))

    # Statistics shared by classification and regression.
    self.node_sums = tf.get_variable(
        name=self.get_tree_name('node_sums', tree_num),
        shape=[params.max_nodes, params.num_output_columns],
        initializer=tf.constant_initializer(0.0))

    if training:
      self.candidate_split_sums = tf.get_variable(
          name=self.get_tree_name('candidate_split_sums', tree_num),
          shape=[params.max_fertile_nodes, params.num_splits_to_consider,
                 params.num_output_columns],
          initializer=tf.constant_initializer(0.0))
      self.accumulator_sums = tf.get_variable(
          name=self.get_tree_name('accumulator_sums', tree_num),
          shape=[params.max_fertile_nodes, params.num_output_columns],
          initializer=tf.constant_initializer(-1.0))

      # Regression also tracks second order stats.
      if params.regression:
        self.node_squares = tf.get_variable(
            name=self.get_tree_name('node_squares', tree_num),
            shape=[params.max_nodes, params.num_output_columns],
            initializer=tf.constant_initializer(0.0))

        self.candidate_split_squares = tf.get_variable(
            name=self.get_tree_name('candidate_split_squares', tree_num),
            shape=[params.max_fertile_nodes, params.num_splits_to_consider,
                   params.num_output_columns],
            initializer=tf.constant_initializer(0.0))

        self.accumulator_squares = tf.get_variable(
            name=self.get_tree_name('accumulator_squares', tree_num),
            shape=[params.max_fertile_nodes, params.num_output_columns],
            initializer=tf.constant_initializer(-1.0))

      else:
        self.node_squares = tf.constant(
            0.0, name=self.get_tree_name('node_squares', tree_num))

        self.candidate_split_squares = tf.constant(
            0.0, name=self.get_tree_name('candidate_split_squares', tree_num))

        self.accumulator_squares = tf.constant(
            0.0, name=self.get_tree_name('accumulator_squares', tree_num))

  def get_tree_name(self, name, num):
    return '{0}-{1}'.format(name, num)

class ForestStats(object):

  def __init__(self, tree_stats, params):
    """A simple container for stats about a forest."""
    self.tree_stats = tree_stats
    self.params = params

  def get_average(self, thing):
    val = 0.0
    for i in range(self.params.num_trees):
      val += getattr(self.tree_stats[i], thing)

    return val / self.params.num_trees

class TreeStats(object):

  def __init__(self, num_nodes, num_leaves):
    self.num_nodes = num_nodes
    self.num_leaves = num_leaves

class ForestTrainingVariables(object):
  """A container for a forests training data, consisting of multiple trees.

  Instantiates a TreeTrainingVariables object for each tree. We override the
  __getitem__ and __setitem__ function so that usage looks like this:

    forest_variables = ForestTrainingVariables(params)

    ... forest_variables.tree ...
  """

  def __init__(self, params, device_assigner, training=True,
               tree_variable_class=TreeTrainingVariables):
    self.variables = []
    for i in range(params.num_trees):
      with tf.device(device_assigner.get_device(i)):
        self.variables.append(tree_variable_class(params, i, training))

  def __setitem__(self, t, val):
    self.variables[t] = val

  def __getitem__(self, t):
    return self.variables[t]

class RandomForestDeviceAssigner(object):
  """A device assigner that uses the default device.

  Write subclasses that implement get_device for control over how trees
  get assigned to devices.  This assumes that whole trees are assigned
  to a device.
  """

  def __init__(self):
    self.cached = None

  def get_device(self, unused_tree_num):
    if not self.cached:
      dummy = tf.constant(0)
      self.cached = dummy.device

    return self.cached

class RandomForestGraphs(object):
  """Builds TF graphs for random forest training and inference."""

  def __init__(self, params, device_assigner=None, variables=None,
               tree_graphs=None,
               t_ops=training_ops,
               i_ops=inference_ops):
    self.params = params
    self.device_assigner = device_assigner or RandomForestDeviceAssigner()
    tf.logging.info('Constructing forest with params = ')
    tf.logging.info(self.params.__dict__)
    self.variables = variables or ForestTrainingVariables(
        self.params, device_assigner=self.device_assigner)
    tree_graph_class = tree_graphs or RandomTreeGraphs
    self.trees = [
        tree_graph_class(
            self.variables[i], self.params,
            t_ops.Load(self.params.training_library_base_dir),
            i_ops.Load(self.params.inference_library_base_dir), i)
        for i in range(self.params.num_trees)]

  def _bag_features(self, tree_num, input_data):
    split_data = tf.split(1, self.params.num_features, input_data)
    return tf.concat(1, [split_data[ind]
                         for ind in self.params.bagged_features[tree_num]])

  def training_graph(self, input_data, input_labels):
    """Constructs a TF graph for training a random forest.

    Args:
      input_data: A tensor or placeholder for input data.
      input_labels: A tensor or placeholder for labels associated with
        input_data.

    Returns:
      The last op in the random forest training graph.
    """
    tree_graphs = []
    for i in range(self.params.num_trees):
      with tf.device(self.device_assigner.get_device(i)):
        seed = self.params.base_random_seed
        if seed != 0:
          seed += i
        # If using bagging, randomly select some of the input.
        tree_data = input_data
        tree_labels = input_labels
        if self.params.bagging_fraction < 1.0:
          # TODO(thomaswc): This does sampling without replacment.  Consider
          # also allowing sampling with replacement as an option.
          batch_size = tf.slice(tf.shape(input_data), [0], [1])
          r = tf.random_uniform(batch_size, seed=seed)
          mask = tf.less(r, tf.ones_like(r) * self.params.bagging_fraction)
          gather_indices = tf.squeeze(tf.where(mask), squeeze_dims=[1])
          # TODO(thomaswc): Calculate out-of-bag data and labels, and store
          # them for use in calculating statistics later.
          tree_data = tf.gather(input_data, gather_indices)
          tree_labels = tf.gather(input_labels, gather_indices)
        if self.params.bagged_features:
          tree_data = self._bag_features(i, tree_data)

        tree_graphs.append(
            self.trees[i].training_graph(tree_data, tree_labels, seed))
    return tf.group(*tree_graphs)

  def inference_graph(self, input_data):
    """Constructs a TF graph for evaluating a random forest.

    Args:
      input_data: A tensor or placeholder for input data.

    Returns:
      The last op in the random forest inference graph.
    """
    probabilities = []
    for i in range(self.params.num_trees):
      with tf.device(self.device_assigner.get_device(i)):
        tree_data = input_data
        if self.params.bagged_features:
          tree_data = self._bag_features(i, input_data)
        probabilities.append(self.trees[i].inference_graph(tree_data))
    with tf.device(self.device_assigner.get_device(0)):
      all_predict = tf.pack(probabilities)
      return tf.reduce_sum(all_predict, 0) / self.params.num_trees

  def average_size(self):
    """Constructs a TF graph for evaluating the average size of a forest.

    Returns:
      The average number of nodes over the trees.
    """
    sizes = []
    for i in range(self.params.num_trees):
      with tf.device(self.device_assigner.get_device(i)):
        sizes.append(self.trees[i].size())
    return tf.reduce_mean(tf.pack(sizes))

  def average_impurity(self):
    """Constructs a TF graph for evaluating the leaf impurity of a forest.

    Returns:
      The last op in the graph.
    """
    impurities = []
    for i in range(self.params.num_trees):
      with tf.device(self.device_assigner.get_device(i)):
        impurities.append(self.trees[i].average_impurity())
    return tf.reduce_mean(tf.pack(impurities))

  def get_stats(self, session):
    tree_stats = []
    for i in range(self.params.num_trees):
      with tf.device(self.device_assigner.get_device(i)):
        tree_stats.append(self.trees[i].get_stats(session))
    return ForestStats(tree_stats, self.params)

class RandomTreeGraphs(object):
  """Builds TF graphs for random tree training and inference."""

  def __init__(self, variables, params, t_ops, i_ops, tree_num):
    self.training_ops = t_ops
    self.inference_ops = i_ops
    self.variables = variables
    self.params = params
    self.tree_num = tree_num

  def _gini(self, class_counts):
    """Calculate the Gini impurity.

    If c(i) denotes the i-th class count and c = sum_i c(i) then
      score = 1 - sum_i ( c(i) / c )^2

    Args:
      class_counts: A 2-D tensor of per-class counts, usually a slice or
        gather from variables.node_sums.

    Returns:
      A 1-D tensor of the Gini impurities for each row in the input.
    """
    smoothed = 1.0 + tf.slice(class_counts, [0, 1], [-1, -1])
    sums = tf.reduce_sum(smoothed, 1)
    sum_squares = tf.reduce_sum(tf.square(smoothed), 1)

    return 1.0 - sum_squares / (sums * sums)

  def _weighted_gini(self, class_counts):
    """Our split score is the Gini impurity times the number of examples.

    If c(i) denotes the i-th class count and c = sum_i c(i) then
      score = c * (1 - sum_i ( c(i) / c )^2 )
            = c - sum_i c(i)^2 / c
    Args:
      class_counts: A 2-D tensor of per-class counts, usually a slice or
        gather from variables.node_sums.

    Returns:
      A 1-D tensor of the Gini impurities for each row in the input.
    """
    smoothed = 1.0 + tf.slice(class_counts, [0, 1], [-1, -1])
    sums = tf.reduce_sum(smoothed, 1)
    sum_squares = tf.reduce_sum(tf.square(smoothed), 1)

    return sums - sum_squares / sums

  def _variance(self, sums, squares):
    """Calculate the variance for each row of the input tensors.

    Variance is V = E[x^2] - (E[x])^2.

    Args:
      sums: A tensor containing output sums, usually a slice from
        variables.node_sums.  Should contain the number of examples seen
        in index 0 so we can calculate expected value.
      squares: Same as sums, but sums of squares.

    Returns:
      A 1-D tensor of the variances for each row in the input.
    """
    total_count = tf.slice(sums, [0, 0], [-1, 1])
    e_x = sums / total_count
    e_x2 = squares / total_count

    return tf.reduce_sum(e_x2 - tf.square(e_x), 1)

  def training_graph(self, input_data, input_labels, random_seed):
    """Constructs a TF graph for training a random tree.

    Args:
      input_data: A tensor or placeholder for input data.
      input_labels: A tensor or placeholder for labels associated with
        input_data.
      random_seed: The random number generator seed to use for this tree.  0
        means use the current time as the seed.

    Returns:
      The last op in the random tree training graph.
    """
    # Count extremely random stats.
    (node_sums, node_squares, splits_indices, splits_sums,
     splits_squares, totals_indices, totals_sums,
     totals_squares, input_leaves) = (
         self.training_ops.count_extremely_random_stats(
             input_data, input_labels, self.variables.tree,
             self.variables.tree_thresholds,
             self.variables.node_to_accumulator_map,
             self.variables.candidate_split_features,
             self.variables.candidate_split_thresholds,
             num_classes=self.params.num_output_columns,
             regression=self.params.regression))
    node_update_ops = []
    node_update_ops.append(
        tf.assign_add(self.variables.node_sums, node_sums))

    splits_update_ops = []
    splits_update_ops.append(self.training_ops.scatter_add_ndim(
        self.variables.candidate_split_sums,
        splits_indices, splits_sums))
    splits_update_ops.append(self.training_ops.scatter_add_ndim(
        self.variables.accumulator_sums, totals_indices,
        totals_sums))

    if self.params.regression:
      node_update_ops.append(tf.assign_add(self.variables.node_squares,
                                           node_squares))
      splits_update_ops.append(self.training_ops.scatter_add_ndim(
          self.variables.candidate_split_squares,
          splits_indices, splits_squares))
      splits_update_ops.append(self.training_ops.scatter_add_ndim(
          self.variables.accumulator_squares, totals_indices,
          totals_squares))

    # Sample inputs.
    update_indices, feature_updates, threshold_updates = (
        self.training_ops.sample_inputs(
            input_data, self.variables.node_to_accumulator_map,
            input_leaves, self.variables.candidate_split_features,
            self.variables.candidate_split_thresholds,
            split_initializations_per_input=(
                self.params.split_initializations_per_input),
            split_sampling_random_seed=random_seed))
    update_features_op = tf.scatter_update(
        self.variables.candidate_split_features, update_indices,
        feature_updates)
    update_thresholds_op = tf.scatter_update(
        self.variables.candidate_split_thresholds, update_indices,
        threshold_updates)

    # Calculate finished nodes.
    with tf.control_dependencies(splits_update_ops):
      children = tf.squeeze(tf.slice(self.variables.tree, [0, 0], [-1, 1]),
                            squeeze_dims=[1])
      is_leaf = tf.equal(LEAF_NODE, children)
      leaves = tf.to_int32(tf.squeeze(tf.where(is_leaf), squeeze_dims=[1]))
      finished = self.training_ops.finished_nodes(
          leaves, self.variables.node_to_accumulator_map,
          self.variables.accumulator_sums,
          num_split_after_samples=self.params.split_after_samples)

    # Update leaf scores.
    # TODO(gilberth): Optimize this. It currently calculates counts for
    # every non-fertile leaf.
    with tf.control_dependencies(node_update_ops):
      def dont_update_leaf_scores():
        return self.variables.non_fertile_leaf_scores

      def update_leaf_scores_regression():
        sums = tf.gather(self.variables.node_sums,
                         self.variables.non_fertile_leaves)
        squares = tf.gather(self.variables.node_squares,
                            self.variables.non_fertile_leaves)
        new_scores = self._variance(sums, squares)
        return tf.assign(self.variables.non_fertile_leaf_scores, new_scores)

      def update_leaf_scores_classification():
        counts = tf.gather(self.variables.node_sums,
                           self.variables.non_fertile_leaves)
        new_scores = self._weighted_gini(counts)
        return tf.assign(self.variables.non_fertile_leaf_scores, new_scores)

      # Because we can't have tf.self.variables of size 0, we have to put in a
      # garbage value of -1 in there.  Here we check for that so we don't
      # try to index into node_per_class_weights in a tf.gather with a negative
      # number.
      update_nonfertile_leaves_scores_op = tf.cond(
          tf.less(self.variables.non_fertile_leaves[0], 0),
          dont_update_leaf_scores,
          update_leaf_scores_regression if self.params.regression else
          update_leaf_scores_classification)

    # Calculate best splits.
    with tf.control_dependencies(splits_update_ops):
      split_indices = self.training_ops.best_splits(
          finished, self.variables.node_to_accumulator_map,
          self.variables.candidate_split_sums,
          self.variables.candidate_split_squares,
          self.variables.accumulator_sums,
          self.variables.accumulator_squares,
          regression=self.params.regression)

    # Grow tree.
    with tf.control_dependencies([update_features_op, update_thresholds_op]):
      (tree_update_indices, tree_children_updates,
       tree_threshold_updates, tree_depth_updates, new_eot) = (
           self.training_ops.grow_tree(
               self.variables.end_of_tree, self.variables.tree_depths,
               self.variables.node_to_accumulator_map, finished, split_indices,
               self.variables.candidate_split_features,
               self.variables.candidate_split_thresholds))
      tree_update_op = tf.scatter_update(
          self.variables.tree, tree_update_indices, tree_children_updates)
      threhsolds_update_op = tf.scatter_update(
          self.variables.tree_thresholds, tree_update_indices,
          tree_threshold_updates)
      depth_update_op = tf.scatter_update(
          self.variables.tree_depths, tree_update_indices, tree_depth_updates)

    # Update fertile slots.
    with tf.control_dependencies([update_nonfertile_leaves_scores_op,
                                  depth_update_op]):
      (node_map_updates, accumulators_cleared, accumulators_allocated,
       new_nonfertile_leaves, new_nonfertile_leaves_scores) = (
           self.training_ops.update_fertile_slots(
               finished, self.variables.non_fertile_leaves,
               self.variables.non_fertile_leaf_scores,
               self.variables.end_of_tree, self.variables.tree_depths,
               self.variables.accumulator_sums,
               self.variables.node_to_accumulator_map,
               max_depth=self.params.max_depth,
               regression=self.params.regression))

    # Ensure end_of_tree doesn't get updated until UpdateFertileSlots has
    # used it to calculate new leaves.
    gated_new_eot, = tf.tuple([new_eot], control_inputs=[new_nonfertile_leaves])
    eot_update_op = tf.assign(self.variables.end_of_tree, gated_new_eot)

    updates = []
    updates.append(eot_update_op)
    updates.append(tree_update_op)
    updates.append(threhsolds_update_op)
    updates.append(tf.assign(
        self.variables.non_fertile_leaves, new_nonfertile_leaves,
        validate_shape=False))
    updates.append(tf.assign(
        self.variables.non_fertile_leaf_scores,
        new_nonfertile_leaves_scores, validate_shape=False))

    updates.append(tf.scatter_update(
        self.variables.node_to_accumulator_map,
        tf.squeeze(tf.slice(node_map_updates, [0, 0], [1, -1]),
                   squeeze_dims=[0]),
        tf.squeeze(tf.slice(node_map_updates, [1, 0], [1, -1]),
                   squeeze_dims=[0])))

    cleared_and_allocated_accumulators = tf.concat(
        0, [accumulators_cleared, accumulators_allocated])
    # Calculate values to put into scatter update for candidate counts.
    # Candidate split counts are always reset back to 0 for both cleared
    # and allocated accumulators. This means some accumulators might be doubly
    # reset to 0 if the were released and not allocated, then later allocated.
    split_values = tf.tile(
        tf.expand_dims(tf.expand_dims(
            tf.zeros_like(cleared_and_allocated_accumulators, dtype=tf.float32),
            1), 2),
        [1, self.params.num_splits_to_consider, self.params.num_output_columns])
    updates.append(tf.scatter_update(
        self.variables.candidate_split_sums,
        cleared_and_allocated_accumulators, split_values))
    if self.params.regression:
      updates.append(tf.scatter_update(
          self.variables.candidate_split_squares,
          cleared_and_allocated_accumulators, split_values))

    # Calculate values to put into scatter update for total counts.
    total_cleared = tf.tile(
        tf.expand_dims(
            tf.neg(tf.ones_like(accumulators_cleared, dtype=tf.float32)), 1),
        [1, self.params.num_output_columns])
    total_reset = tf.tile(
        tf.expand_dims(
            tf.zeros_like(accumulators_allocated, dtype=tf.float32), 1),
        [1, self.params.num_output_columns])
    accumulator_updates = tf.concat(0, [total_cleared, total_reset])
    updates.append(tf.scatter_update(
        self.variables.accumulator_sums,
        cleared_and_allocated_accumulators, accumulator_updates))
    if self.params.regression:
      updates.append(tf.scatter_update(
          self.variables.accumulator_squares,
          cleared_and_allocated_accumulators, accumulator_updates))

    # Calculate values to put into scatter update for candidate splits.
    split_features_updates = tf.tile(
        tf.expand_dims(
            tf.neg(tf.ones_like(cleared_and_allocated_accumulators)), 1),
        [1, self.params.num_splits_to_consider])
    updates.append(tf.scatter_update(
        self.variables.candidate_split_features,
        cleared_and_allocated_accumulators, split_features_updates))

    return tf.group(*updates)

  def inference_graph(self, input_data):
    """Constructs a TF graph for evaluating a random tree.

    Args:
      input_data: A tensor or placeholder for input data.

    Returns:
      The last op in the random tree inference graph.
    """
    return self.inference_ops.tree_predictions(
        input_data, self.variables.tree, self.variables.tree_thresholds,
        self.variables.node_sums,
        valid_leaf_threshold=self.params.valid_leaf_threshold)

  def average_impurity(self):
    """Constructs a TF graph for evaluating the average leaf impurity of a tree.

    If in regression mode, this is the leaf variance. If in classification mode,
    this is the gini impurity.

    Returns:
      The last op in the graph.
    """
    children = tf.squeeze(tf.slice(self.variables.tree, [0, 0], [-1, 1]),
                          squeeze_dims=[1])
    is_leaf = tf.equal(LEAF_NODE, children)
    leaves = tf.to_int32(tf.squeeze(tf.where(is_leaf), squeeze_dims=[1]))
    counts = tf.gather(self.variables.node_sums, leaves)
    impurity = self._weighted_gini(counts)
    return tf.reduce_sum(impurity) / tf.reduce_sum(counts + 1.0)

  def size(self):
    """Constructs a TF graph for evaluating the current number of nodes.

    Returns:
      The current number of nodes in the tree.
    """
    return self.variables.end_of_tree - 1

  def get_stats(self, session):
    num_nodes = self.variables.end_of_tree.eval(session=session) - 1
    num_leaves = tf.where(
        tf.equal(tf.squeeze(tf.slice(self.variables.tree, [0, 0], [-1, 1])),
                 LEAF_NODE)).eval(session=session).shape[0]
    return TreeStats(num_nodes, num_leaves)


text:
package models.manager.commands

import models.Item
import models.manager.commands.traits.CanStartPlayer

/**
  * Created by rbrowning on 4/26/17.
  *
  * Sent from the endpoints to the manager, this will tell the manager to play the current items.
  *
  * If there's already a playlist this will stop the current player and clear the playlist and start
  * a new item with the new playlist
  */
case class PlayAllItems(items: Seq[Item]) extends CanStartPlayer


text:
import unittest

import GafferOSL
import GafferOSLUI
import GafferUITest

class NodeUITest( GafferUITest.TestCase ) :

	def testLifetimes( self ) :

		self.assertNodeUIsHaveExpectedLifetime( GafferOSL )

if __name__ == "__main__":
	unittest.main()


text:
  #{list items:articles, as:'article'}

${article.title}

        ${article.date.format()}

        ${article.body.markdown().raw()}

read on »

  #{/list}

  #{list items:archives, as:'archive'}
  #{/list}


text:
 You're a mentsh!

Thanks for spreading Messiah's music on the web. (◕‿◕✿)

                Want to help even more? {{vm.donateText}} to amplify and increase Messiah's music.

Chavah Messianic Radio


text:
package ab.asktest.lib;

/**
 * Quick and dirty Input Sanitiser to address basic input - HTML/JS/XSS issues, etc.
 *
 * A real version would be more clever.
 *
 * In a real Question asking tool, we would also probably allow a limited set of HTML - emoticons, EM, etc...
 * and no JS, etc. All we're doing here is stripping all HTML.
 *
 * This tool would also form the first line of spambot defense - if a question is being input, is it garbage or a real sentence?
 * Not an easy question!
 *
 * @author andrewb
 * @version 0.0.1
 * */
public class BasicInputSanitiser {

	public static String cleanInput(String input){
		if(input==null||input.length()<1){
			return null;
		}
		input = input.replaceAll("\\<[^>]*>","");
		return input.trim();
	}
	public static String cleanInput(String input, int maxlen){
		if(input==null||input.length()<1){
			return null;
		}
		input = cleanInput(input);
		return (input.length()>maxlen?input.substring(0, maxlen):input);
	}

}


text:
@import TSTripleSec;

@interface TSTripleSecTest : XCTestCase
@end

@implementation TSTripleSecTest

- (void)test {
  NSData *message = [@"this is a secret message" dataUsingEncoding:NSUTF8StringEncoding];
  NSData *key = [@"toomanysecrets" dataUsingEncoding:NSUTF8StringEncoding];

  NSError *error = nil;
  TSTripleSec *tripleSec = [[TSTripleSec alloc] init];
  NSData *encrypted = [tripleSec encrypt:message key:key error:&error];
  XCTAssertNil(error);

  NSData *decrypted = [tripleSec decrypt:encrypted key:key error:&error];
  XCTAssertNil(error);

  XCTAssertEqualObjects(message, decrypted);
}

- (void)testDecrypt {
  // triplesec --key toomanysecrets enc 'this is a really secret message'
  NSData *encrypted = [@"1c94d7de0000000378ad843339b7328da65be613c4208f8d50b11c689eefac9c9825b40025b0a5ccc4e1d7c13b2997f85163f1d0ae807575a309a4483ed034032bc4a10782b2966f6b0df2eec58ace6a3dae7d9911c024b860139c677c4291b33c6d5a9256e76e2621e24f19cc4035b9c8a90ef859e5c86992b8a3f3f2ead880d1a740671594293ba28b09b7fed06c7df2a15e9bf0a473841da194625aaac9f97fff8e7da973bc5881edc9293a16f55da654aa4caff1465a3a16b58d8d1a86516070559a61fafaf3131f032a692642af37dddfc91580eb5720760536284bab463921ada601212e5f2b510396fb60ff" dataFromHexString];

  NSData *key = [@"toomanysecrets" dataUsingEncoding:NSUTF8StringEncoding];

  NSError *error = nil;
  TSTripleSec *tripleSec = [[TSTripleSec alloc] init];
  NSData *decrypted = [tripleSec decrypt:encrypted key:key error:&error];
  XCTAssertNil(error);

  NSData *message = [@"this is a really secret message" dataUsingEncoding:NSUTF8StringEncoding];
  XCTAssertEqualObjects(message, decrypted);
}

// TODO
- (void)_testVectors {
  NSString *path = [[NSBundle mainBundle] pathForResource:@"vectors" ofType:@"json"];
  NSData *data = [NSData dataWithContentsOfFile:path];
  NSArray *testVectors = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  NSAssert(testVectors, nil);

  for (NSDictionary *test in testVectors) {
    NSData *key = [test[@"key"] dataFromHexString];
    NSData *ciphertext = [test[@"ciphertext"] dataFromHexString];
    NSData *plaintext = [test[@"plaintext"] dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;
    TSTripleSec *tripleSec = [[TSTripleSec alloc] init];
    //NSData *encrypted = [tripleSec encrypt:plaintext key:key error:&error];
    //GHAssertNil(error, nil);
    NSData *decrypted = [tripleSec decrypt:ciphertext key:key error:&error];
    XCTAssertNil(error);
    XCTAssertEqualObjects(plaintext, decrypted);
  }
}

@end


text:
import type { Container } from '../../container';
import { filterMap } from '../../system/array';
import { debug } from '../../system/decorators/log';
import { normalizePath } from '../../system/path';
import { getLines } from '../../system/string';
import {
	GitCommit,
	GitCommitIdentity,
	GitFile,
	GitFileChange,
	GitFileIndexStatus,
	GitStash,
	GitStashCommit,
} from '../models';
import { fileStatusRegex } from './logParser';
// import { Logger } from './logger';

// Using %x00 codes because some shells seem to try to expand things if not
const lb = '%x3c'; // `%x${'<'.charCodeAt(0).toString(16)}`;
const rb = '%x3e'; // `%x${'>'.charCodeAt(0).toString(16)}`;
const sl = '%x2f'; // `%x${'/'.charCodeAt(0).toString(16)}`;
const sp = '%x20'; // `%x${' '.charCodeAt(0).toString(16)}`;

interface StashEntry {
	ref?: string;
	date?: string;
	committedDate?: string;
	fileNames?: string;
	files?: GitFile[];
	summary?: string;
	stashName?: string;
}

export class GitStashParser {
	static defaultFormat = [
		`${lb}${sl}f${rb}`,
		`${lb}r${rb}${sp}%H`, // ref
		`${lb}d${rb}${sp}%at`, // date
		`${lb}c${rb}${sp}%ct`, // committed date
		`${lb}l${rb}${sp}%gd`, // reflog-selector
		`${lb}s${rb}`,
		'%B', // summary
		`${lb}${sl}s${rb}`,
		`${lb}f${rb}`,
	].join('%n');

	@debug({ args: false, singleLine: true })
	static parse(container: Container, data: string, repoPath: string): GitStash | undefined {
		if (!data) return undefined;

		const lines = getLines(`${data}</f>`);
		// Skip the first line since it will always be </f>
		let next = lines.next();
		if (next.done) return undefined;

		if (repoPath !== undefined) {
			repoPath = normalizePath(repoPath);
		}

		const commits = new Map<string, GitStashCommit>();

		let entry: StashEntry = {};
		let line: string | undefined = undefined;
		let token: number;

		let match;
		let renamedFileName;

		while (true) {
			next = lines.next();
			if (next.done) break;

			line = next.value;

			// <<1-char token>> <data>
			// e.g. <r> bd1452a2dc
			token = line.charCodeAt(1);

			switch (token) {
				case 114: // 'r': // ref
					entry = {
						ref: line.substring(4),
					};
					break;

				case 100: // 'd': // author-date
					entry.date = line.substring(4);
					break;

				case 99: // 'c': // committer-date
					entry.committedDate = line.substring(4);
					break;

				case 108: // 'l': // reflog-selector
					entry.stashName = line.substring(4);
					break;

				case 115: // 's': // summary
					while (true) {
						next = lines.next();
						if (next.done) break;

						line = next.value;
						if (line === '</s>') break;

						if (entry.summary === undefined) {
							entry.summary = line;
						} else {
							entry.summary += `\n${line}`;
						}
					}

					// Remove the trailing newline
					if (entry.summary != null && entry.summary.charCodeAt(entry.summary.length - 1) === 10) {
						entry.summary = entry.summary.slice(0, -1);
					}
					break;

				case 102: // 'f': // files
					// Skip the blank line git adds before the files
					next = lines.next();
					if (!next.done && next.value !== '</f>') {
						while (true) {
							next = lines.next();
							if (next.done) break;

							line = next.value;
							if (line === '</f>') break;

							if (line.startsWith('warning:')) continue;

							match = fileStatusRegex.exec(line);
							if (match != null) {
								if (entry.files === undefined) {
									entry.files = [];
								}

								renamedFileName = match[3];
								if (renamedFileName !== undefined) {
									entry.files.push({
										status: match[1] as GitFileIndexStatus,
										path: renamedFileName,
										originalPath: match[2],
									});
								} else {
									entry.files.push({
										status: match[1] as GitFileIndexStatus,
										path: match[2],
									});
								}
							}
						}

						if (entry.files != null) {
							entry.fileNames = filterMap(entry.files, f => (f.path ? f.path : undefined)).join(', ');
						}
					}

					GitStashParser.parseEntry(container, entry, repoPath, commits);
					entry = {};
			}
		}

		const stash: GitStash = {
			repoPath: repoPath,
			commits: commits,
		};
		return stash;
	}

	private static parseEntry(
		container: Container,
		entry: StashEntry,
		repoPath: string,
		commits: Map<string, GitStashCommit>,
	) {
		let commit = commits.get(entry.ref!);
		if (commit == null) {
			commit = new GitCommit(
				container,
				repoPath,
				entry.ref!,
				new GitCommitIdentity('You', undefined, new Date((entry.date! as any) * 1000)),
				new GitCommitIdentity('You', undefined, new Date((entry.committedDate! as any) * 1000)),
				entry.summary?.split('\n', 1)[0] ?? '',
				[],
				entry.summary ?? '',
				entry.files?.map(f => new GitFileChange(repoPath, f.path, f.status, f.originalPath)) ?? [],
				undefined,
				[],
				entry.stashName,
			) as GitStashCommit;
		}

		commits.set(entry.ref!, commit);
	}
}


text:
tags:  hrvatski
title: Testiranje. Kako početi?
---

Sjećam se svojih prvih dana na ovom poslu. Testirao sam istu aplikaciju koju i sad testiram. Srećom, naslijedio sam popriličnu količinu testova (ali na žalost samo za tu aplikaciju).

Posjeli su me za računalo, dali mi stotinjak testova napisanih u Wordu, url aplikacije (na stroju za testiranje, ne url gdje je sve "za pravo"), korisničko ime i lozinku administratora i rekli: "Testiraj".

Nakon nekoliko minuta osjećao sam se kao riba u vodi.

Testove sam poslije prebacio iz Worda u Excel (jako volim Excel), dodao koju kolonu, izbacio pokoju, popravio neke greščice koje sam našao (o da, i testeri rade greške)...

Ovo je jedan od tih testova. Ime mu je Napravi-Korisnika, a prezime Test-Funkcionalnosti. O klanovima testova (prepoznaju se po prezimenu) će biti riječi ovih dana. Test-Funkcionalnosti, naravno, provjerava da li neka funkcionalnost aplikacije radi ono što bi trebala. Svako drugo testiranje odbija, pozivajući se na kolektivni ugovor koji je njegov klan potpisao.

Svi testovi pretpostavljaju da je korisnik prijavljen u aplikaciju i da se nalazi na početnoj stranici (osim naravno testova za prijavu i odjavu).

broj testa: 1

korisnik: administrator

naslov: napravi korisnika

koraci:

klikni link "napravi korisnika"

popuni podatke, samo obavezna polja, označena * (zvjezdicom)

klikni dugme "nastavi"

postavi ovlasti pristupa za pojedine zajednice

klikni dugme "spremi"

ulazni podaci:

titula

ime

prezime

država

e-pošta

korisničko ime

lozinka

ponovi lozinku

ovlasti pristupa za pojedine zajednice

očekivani rezultati

povratna informacija da je korisnik napravljen

korisnik je napravljen


text:
% Copyright (C) 2010 Joao Carreira
%
% This code is part of the extended implementation of the paper:
%
% J. Carreira, C. Sminchisescu, Constrained Parametric Min-Cuts for Automatic Object Segmentation, IEEE CVPR 2010
%

function D = SvmSegm_compute_segm_feats_nofiles(exp_dir, img_name, masks, feat_type)
    assert(iscell(feat_type));

    I = imread([exp_dir '/JPEGImages/' img_name '.jpg']);
    parfor h=1:numel(feat_type)
        if(strcmp(feat_type{h}, 'SimpleSegmentFeatures'))
            f = SimpleSegmentFeatures(I, masks, [exp_dir 'PB/' img_name '_PB']);
        elseif(strcmp(feat_type{h}, 'GestaltSegmentFeatures'))
            f =GestaltSegmentFeatures(I, masks, [exp_dir 'PB/' img_name '_PB']);
        else
            error('no such feature type');
        end

        f = f.compute_all_feats();

        D{h} = f.get_feats();
    end
end


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace EasyWeChat\Tests\OpenPlatform;

use Doctrine\Common\Cache\ArrayCache;
use EasyWeChat\OpenPlatform\VerifyTicket;
use EasyWeChat\Tests\TestCase;

class VerifyTicketTest extends TestCase
{
    /**
     * Get VerifyTicket instance.
     */
    public function getVerifyTicket($appId)
    {
        return new VerifyTicket($appId, new ArrayCache());
    }

    /**
     * Tests that the verify ticket is properly cached.
     */
    public function testTicket()
    {
        $verifyTicket = $this->getVerifyTicket('foobar');

        $this->assertTrue($verifyTicket->setTicket('ticket@foobar'));
        $this->assertEquals('ticket@foobar', $verifyTicket->getTicket());
    }

    /**
     * Test cache key.
     */
    public function testCacheKey()
    {
        $verifyTicket = $this->getVerifyTicket('app-id');

        $this->assertEquals('easywechat.open_platform.component_verify_ticket.app-id', $verifyTicket->getCacheKey());

        $verifyTicket->setCacheKey('cache-key.app-id');

        $this->assertEquals('cache-key.app-id', $verifyTicket->getCacheKey());
    }
}