text:
namespace StateMachine.Tests.Sync
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Exceptions;
    using Xunit;

    public enum Action
    {
        Assign,
        MarkAsComplete,
        Reject
    }

    public class BasicFunctionality
    {
        public class Draft : IState<object>
        {
            public void OnEnter(object context)
            {
            }

            public void OnExit(object context)
            {
            }
        }

        public class InProgress : IState<object>
        {
            public void OnEnter(object context)
            {
            }

            public void OnExit(object context)
            {
            }
        }

        public class Complete : IState<object>
        {
            public void OnEnter(object context)
            {
            }

            public void OnExit(object context)
            {
            }
        }

        private readonly StateMachine<object, Action>.Builder builder;
        public BasicFunctionality()
        {
            builder = new StateMachine<object, Action>.Builder();

            builder.State<Draft>()
                   .IsInitialState()
                   .On(Action.Assign)
                   .GoesTo<InProgress>();

            builder.State<InProgress>()
                   .On(Action.MarkAsComplete)
                   .GoesTo<Complete>()
                   .On(Action.Reject)
                   .GoesTo<Draft>();
        }

        [Fact]
        public void RegularUseCase()
        {
            var machine = builder.Build();
            var list = new List<Tuple<Type, Type>>();
            machine.TransitionCompleted += (sender, args) => list.Add(Tuple.Create(args.Source, args.Target));
            machine.Trigger(Action.Assign);
            machine.Trigger(Action.Reject);
            machine.Trigger(Action.Assign);
            machine.Trigger(Action.MarkAsComplete);
            Assert.Equal(4, list.Count);
            Assert.True(list.SequenceEqual(new[]
            {
                Tuple.Create(typeof (Draft), typeof (InProgress)),
                Tuple.Create(typeof (InProgress), typeof (Draft)),
                Tuple.Create(typeof (Draft), typeof (InProgress)),
                Tuple.Create(typeof (InProgress), typeof (Complete))
            }));
        }

        [Fact(DisplayName = "Event should be raised when the transition is complete")]
        public void EventIsRaisedWhenTransitionIsComplete()
        {
            bool eventRaised = false;
            var machine = builder.Build();
            machine.TransitionCompleted += (sender, args) => eventRaised = true;
            machine.Trigger(Action.Assign);
            Assert.True(eventRaised);
        }

        [Fact(DisplayName = "If there is no custom handler set for invalid trigger, exception will be thrown.")]
        public void ExceptionIsThrownWhenTheTriggerIsNotValidAndActionIsNotSet()
        {
            var machine = builder.Build();

            Assert.Throws<ExecutionException>(() => machine.Trigger(Action.Reject));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package lang

// Language
type Language int8

const (
	_ Language = iota
	Japanese
	English
	French
	German
	Italian
	Korean
	Spanish
	ChineseSimplified
	ChineseTraditional
	ChineseChina
	ChineseHongKong
	ChineseTaiwan
)

//go:generate stringer -type=Language

func (l Language) LocalName() string {
	switch l {
	case Japanese:
		return "日本語"
	case English:
		return "English"
	case French:
		return "Français"
	case German:
		return "Deutsch"
	case Italian:
		return "Italiano"
	case Korean:
		return "한국어"
	case Spanish:
		return "Español"
	case ChineseSimplified:
		return "简体中文(官方译名)"
	case ChineseTraditional:
		return "繁體中文(官方譯名)"
	case ChineseChina:
		return "简体中文(中国译名)"
	case ChineseHongKong:
		return "繁體中文(香港譯名)"
	case ChineseTaiwan:
		return "繁體中文(台灣譯名)"
	default:
		return ""
	}
}

// Reference:
// http://publications.europa.eu/mdr/resource/authority/multilingual/xml/multilingual.xml

func (l Language) ShortName() string {
	switch l {
	case Japanese:
		return "日"
	case English:
		return "Eng"
	case French:
		return "Fra"
	case German:
		return "Deu"
	case Italian:
		return "Ita"
	case Korean:
		return "한"
	case Spanish:
		return "Spa"
	case ChineseSimplified:
		return "简(官)"
	case ChineseTraditional:
		return "繁(官)"
	case ChineseChina:
		return "简(中)"
	case ChineseHongKong:
		return "繁(港)"
	case ChineseTaiwan:
		return "繁(台)"
	default:
		return ""
	}
}

func (l Language) Id() int {
	return int(l)
}

func (l Language) IsValid() bool {
	return Japanese <= l && l <= ChineseTaiwan
}


text:
'use strict';

var Comparator = require('../../util/comparator');

/**
 * Narayana's algorithm computes the subsequent permutation
 *   in lexicographical order.
 * Complexity: O(n).
 *
 * @param {Array} array
 * @param {function} [compareFn] - Custom compare function.
 * @return {boolean} Boolean flag indicating whether the algorithm succeeded,
 *   true unless the input permutation is lexicographically the last one.
 */
var nextPermutation = function (array, compareFn) {
  if (!array.length) {
    return false;
  }
  var cmp = new Comparator(compareFn);

  // Find pivot and successor indices.
  var pivot = array.length - 1;
  while (pivot && cmp.greaterThanOrEqual(array[pivot - 1], array[pivot])) {
    pivot -= 1;
  }
  if (!pivot) {
    // Permutation is sorted in descending order.
    return false;
  }
  var pivotValue = array[--pivot];
  var successor = array.length - 1;
  while (cmp.lessThanOrEqual(array[successor], pivotValue)) {
    successor -= 1;
  }

  // Swap values.
  array[pivot] = array[successor];
  array[successor] = pivotValue;

  // Reverse the descending part.
  for (var left = pivot, right = array.length; ++left < --right;) {
    var temp = array[left];
    array[left] = array[right];
    array[right] = temp;
  }
  return true;
};

module.exports = nextPermutation;


text:
package io.amient.affinity.kafka

import java.util.Properties

import akka.actor.Actor
import akka.actor.Status.{Failure, Success}
import akka.event.Logging
import com.typesafe.config.Config
import io.amient.affinity.Conf
import io.amient.affinity.core.actor.{TransactionAbort, TransactionBegin, TransactionCommit, TransactionalRecord}
import io.amient.affinity.core.config.CfgStruct
import io.amient.affinity.core.storage.StorageConf
import io.amient.affinity.kafka.KafkaStorage.{KafkaConsumerConf, KafkaProducerConf}
import org.apache.kafka.clients.producer.{Callback, KafkaProducer, ProducerRecord, RecordMetadata}
import org.apache.kafka.common.serialization.ByteArraySerializer

import scala.collection.JavaConverters._

object KafkaConf extends KafkaConf {
  override def apply(config: Config): KafkaConf = new KafkaConf().apply(config)
}

class KafkaConf extends CfgStruct[KafkaConf](classOf[StorageConf]) {
  val BootstrapServers = string("kafka.bootstrap.servers", true).doc("kafka connection string used for consumer and/or producer")
  val Producer = struct("kafka.producer", new KafkaProducerConf, false).doc("any settings that the underlying version of kafka producer client supports")
  val Consumer = struct("kafka.consumer", new KafkaConsumerConf, false).doc("any settings that the underlying version of kafka consumer client supports")
}

class TransactionalProducer extends Actor {

  val logger = Logging.getLogger(context.system, this)

  private[this] var producer: KafkaProducer[Array[Byte], Array[Byte]] = null

  val kafkaConf = KafkaConf(Conf(context.system.settings.config).Affi.Storage)
  val producerConfig = new Properties() {
    if (kafkaConf.Producer.isDefined) {
      val producerConfig = kafkaConf.Producer.toMap()
      if (producerConfig.containsKey("bootstrap.servers")) throw new IllegalArgumentException("bootstrap.servers cannot be overriden for KafkaStroage producer")
      if (producerConfig.containsKey("key.serializer")) throw new IllegalArgumentException("Binary kafka stream cannot use custom key.serializer")
      if (producerConfig.containsKey("value.serializer")) throw new IllegalArgumentException("Binary kafka stream cannot use custom value.serializer")
      producerConfig.entrySet.asScala.filter(_.getValue.isDefined).foreach { case (entry) =>
        put(entry.getKey, entry.getValue.apply.toString)
      }
    }
    put("bootstrap.servers", kafkaConf.BootstrapServers())
    put("value.serializer", classOf[ByteArraySerializer].getName)
    put("key.serializer", classOf[ByteArraySerializer].getName)
  }

  override def receive: Receive = {

    case req@TransactionBegin(transactionalId) => req(sender) ! {
      if (producer == null) {
        producerConfig.put("transactional.id", transactionalId)
        producer = new KafkaProducer[Array[Byte], Array[Byte]](producerConfig)
        logger.debug(s"Transactions.Init(transactional.id = $transactionalId)")
        producer.initTransactions()
      }
      logger.debug("Transactions.Begin()")
      producer.beginTransaction()
    }

    case TransactionalRecord(topic, key, value, timestamp, partition) =>
      val replyto = sender
      val producerRecord = new ProducerRecord(
        topic,
        partition.map(new Integer(_)).getOrElse(null),
        timestamp.map(new java.lang.Long(_)).getOrElse(null),
        key,
        value)
      logger.debug(s"Transactions.Append(topic=$topic)")
      producer.send(producerRecord, new Callback {
        override def onCompletion(metadata: RecordMetadata, exception: Exception): Unit = {
          if (exception != null) {
            replyto ! Failure(exception)
          } else {
            replyto ! Success(metadata.offset())
          }
        }
      })

    case req@TransactionCommit() => req(sender) ! {
      logger.debug("Transactions.Commit()")
      producer.commitTransaction()
    }

    case req@TransactionAbort() => req(sender) ! {
      logger.debug("Transactions.Abort()")
      producer.abortTransaction()
    }
  }
}


text:
<?php

Yii::setPathOfAlias('shop', __DIR__);

require(__DIR__.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'helpers.php');

class ShopModule extends CWebModule {

	public $version = '0.1';

	// Is the Shop in debug Mode?
	public $debug = true;

	// Whether the installer should install some demo data
	public $demo = true;

	// Enable this to use the shop module together with the yii user
	// management module
	public $userModule = false;

	// Names of the tables
	public $categoriesTable = 'categories';
	public $productsTable = 'products';
	public $ordersTable = 'orders';
	public $orderProductsTable = 'order_products';
	public $customersTable = 'customers';
	public $addressesTable = 'addreses';
	public $imagesTable = 'images';
	public $shippingMethodsTable = 'shipping_methods';
	public $paymentMethodsTable = 'payment_methods';
	public $taxesTable = 'taxes';
	public $attributesTable = 'attributes';
	public $variationsTable = 'variations';
	public $currencySymbol = '$';

	public $logoPath = 'logo.jpg';
	public $slipView = '/orders/slip';
	public $invoiceView = '/orders/invoice';
	public $footerView = '/orders/footer';

	public $dateFormat = 'd/m/Y';
	public $publishAssets = false;

	public $thumbWidth = 100;
	public $imageWidth = 200;

	public $adminEmail = null;

	public $termsView = '/order/terms';
	public $orderComplete = ['/shop/orders/success'];
	public $orderFail = ['/shop/orders/failure'];
	public $loginUrl = ['/site/login'];

	// where the uploaded product images are stored its relative to webroot
	public $uploads = 'uploads';

	public $layout = 'shop.views.layouts.main';

	public function init()
	{
		$this->setImport([
			'shop.models.*',
			'shop.components.*',
			'shop.components.cart.*',
		]);
		$this->setComponents([
			'cart' => [
				'class' => 'shop.components.cart.EShoppingCart'
			]
		]);
	}

	public function publishAssets()
	{
		$assets = Yii::getPathOfAlias('application.modules.shop.assets');
		$url = Yii::app()->getAssetManager()->publish($assets);

		if ($this->publishAssets)
		{
			Yii::app()->clientScript
				->registerScriptFile($url.'/js/kube.min.js')
				->registerScriptFile($url.'/js/site.js')
				->registerCssFile($url.'/css/kube.min.css')
				->registerCssFile($url.'/css/site.css')
				->registerCssFile($url.'/css/form.css');
		}

		return $url . '/';
	}

	public function beforeControllerAction($controller, $action)
	{
		if (parent::beforeControllerAction($controller, $action))
			return true;
		else
			return false;
	}

}


text:
package controllers

import javax.inject.{Inject, Singleton}

import actors.{UUIDActor, UserActor}
import akka.actor.{ActorRef, Props}
import akka.pattern.ask
import akka.util.Timeout
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.iteratee.{Concurrent, Iteratee}
import play.api.libs.json.JsValue
import play.api.mvc._
import play.filters.csrf.{CSRFAddToken, CSRFCheck}
import play.libs.Akka
import services.UUIDGenerator

import scala.concurrent.Future
import scala.concurrent.duration._

/**
 * Instead of declaring an object of Application as per the template project, we must declare a class given that
 * the application context is going to be responsible for creating it and wiring it up with the UUID generator service.
 * @param uuidGenerator the UUID generator service we wish to receive.
 */
@Singleton
class Application @Inject() (uuidGenerator: UUIDGenerator) extends Controller {

  implicit val app: play.api.Application = play.api.Play.current

  private final val logger = Logger

  lazy val CacheExpiration =
    app.configuration.getInt("cache.expiration").getOrElse(60 /*seconds*/ * 2 /* minutes */)

  implicit val timeout = Timeout(5 seconds)

  lazy val uuidActor : ActorRef = Akka.system.actorOf(Props(new UUIDActor(uuidGenerator)))

  def index = GetAction { request => {
      val userSession = request.session.get("csrfToken").map(i => i.split("-")(0)).getOrElse("")
      logger.info(s"$userSession")
      logger.info("Serving index page...")
      Ok(views.html.index())
    }
  }

  def randomUUID = Action.async {
    logger.info("calling UUIDGenerator...")
    (uuidActor ? Some) map { case x: String => Ok(x) }
  }

  def ws = WebSocket.using[JsValue] { request =>
    logger.info("User Connected")

    val (out, channel) = Concurrent.broadcast[JsValue]

    val userActor = Akka.system.actorOf(Props(classOf[UserActor], channel))

    val in = Iteratee.foreach[JsValue] { message =>
      logger.info(s"Received message: $message")
      userActor ! message
    }.map { _ =>
      logger.info("User Disconnected")
      Akka.system.stop(userActor)
    }

    (in, out)
  }

  object PostAction extends ActionBuilder[Request] {
    def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
      // authentication code here
      block(request)
    }
    override def composeAction[A](action: Action[A]) = CSRFCheck(action)
  }

  object GetAction extends ActionBuilder[Request] {
    def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
      //val userSession = CSRF.getToken(request).map(_.value).getOrElse("")
      //logger.info(s"GetAction $userSession")
      // authentication code here
      block(request)
    }
    override def composeAction[A](action: Action[A]) = CSRFAddToken(action)
  }

}


text:
Nailgun extension that generates deployment data based on configuration files published in external git repository
### Requirements
Deployed Fuel 9.0 (Mitaka) Master Node

### Installation
Execute following commands on Fuel Master node
```
# yum install git python-pip
# git clone https://github.com/openstack/fuel-nailgun-extension-iac
# cd fuel-nailgun-extension-iac
# pip install -r requirements.txt
# python setup.py install
# nailgun_syncdb
# systemctl restart nailgun.service
```
Next extension should be enabled. To list all available extensions execute following command
```
# fuel2 extension list
```
Than enable extension for a particular environment
```
# fuel2 env extension enable <env_id> -E fuel_external_git
```

### How to Use

This extension introduces set of additional Fuel CLI commands which help to associate git repo with particular environment and preform CRUD operations this repo. See details [here](../blob/master/doc/cli.md).
```
  gitrepo create
  gitrepo delete
  gitrepo get configs
  gitrepo init
  gitrepo list
  gitrepo update
```
First you need to create repository and configure nailgun to use it.
```
fuel2 gitrepo create --env 1 --name oscnf1 --url git@github.com:dukov/oscnf.git --ref master --key .ssh/id_rsa
```
Next you need to create repository structure. You can do this manually (see Repo structure description below) or extension can automatically generate basic structure for you.
```
fuel2 gitrepo init --repo 11
```
In order to track configuration evolution it is possible to download all configuration files from the environment into **separate** branch of configured Git repository. User configured to access repository must have write permissions to it
```
fuel2 gitrepo get configs --env 1
```
#### Git Repo structure
Here is the example repo structure
```
.
|-- controller_configs
|   `-- glance-api.conf
|-- node_1_configs
|   `-- nova.conf
|-- nova.conf
|-- overrides.yaml
`-- tools
    `-- show-config-for.py
```
There are three levels of configuration: Global, Role, Node. Each level has higher priority in terms of configuration parameters.
* Global - configuration parameters from all configs from this level will be applied to all nodes in environment.
* Role - configuration parameters from all configs from this level will be applied to nodes with particular role. Parameters from this level will override parameters from Global level
* Node - configuration parameters from all configs from this level will be applied to node with particular id. Parameters from this level will override parameters from Global and Role levels

For example we have ```nova.conf``` file with ```debug = True``` in Global level and ```nova.conf``` with ```debug = False```  in Role level. Resulting configuration will be:
```
[DEFAULT]
debug = False
```
Configuration files for Global level should be placed in repo root. Role and Node levels should be described in overrides.yaml placed in repo root directory using following format
```
nodes:
  '<node_id>': '<directory_name>'
roles:
  '<role_name>': '<directory_name>'
```
Example overrides.yaml
```
nodes:
  '1': node_1_configs
  '2': node_2_configs
roles:
  'cinder': 'cinder_configs'
  'compute': 'compute_configs'
  'controller': 'controller_configs'
  'primary-controller': 'controller_configs'
```
Configuration files for Role and Node levels should be placed in corresponding directory described in overrides.yaml

### REST API
API documentation can be found [here](../blob/master/doc/api.md)


text:
namespace GPUCA_NAMESPACE
{
namespace gpu
{
struct GPUTPCClusterData {
  int id;
  short row;
  short flags;
  float x;
  float y;
  float z;
  float amp;
#ifdef GPUCA_FULL_CLUSTERDATA
  float pad;
  float time;
  float ampMax;
  float sigmaPad2;
  float sigmaTime2;
#endif
};
} // namespace gpu
} // namespace GPUCA_NAMESPACE

#endif // CLUSTERDATA_H


text:
import tensorflow as tf

from setags.data.input import EMBEDDING_SIZE
from setags.data.utils import BIOTag
from setags.utils import DictWrapper

class Features(DictWrapper):
    def __init__(self):
        self.id = None
        self.title = None
        self.title_length = None
        self.content = None
        self.content_length = None

class Labels(DictWrapper):
    def __init__(self):
        self.title_bio = None
        self.content_bio = None

class Params(DictWrapper):
    def __init__(self):
        self.num_epochs = 70
        self.batch_size = 64
        self.max_word_idx = None
        self.num_title_units = 300
        self.num_content_units = 200
        self.learning_rate = 0.002

BIO_ENCODING_SIZE = sum(1 for _ in BIOTag)

DEFAULT_PARAMS = Params().as_dict()

def model_fn(mode, features, labels, params):
    _params = Params.from_dict(params)
    _features = Features.from_dict(features)

    _labels = None
    if mode != tf.estimator.ModeKeys.PREDICT:
        _labels = Labels.from_dict(labels)

    return build_model(mode, _features, _labels, _params)

def build_model(mode: tf.estimator.ModeKeys,
                features: Features,
                labels: Labels,
                params: Params) -> tf.estimator.EstimatorSpec:

    with tf.device("/cpu:0"):
        embeddings = tf.placeholder(tf.float32, [None, EMBEDDING_SIZE], name='embeddings')

    embedded_title = tf.nn.embedding_lookup(embeddings, tf.nn.relu(features.title))
    embedded_content = tf.nn.embedding_lookup(embeddings, tf.nn.relu(features.content))

    with tf.variable_scope("encoder"):
        with tf.variable_scope("title"):
            title_encoder = RNNLayer(embedded_title, features.title_length, params.num_title_units)
        with tf.variable_scope("content"):
            title_final_state = tf.layers.dense(title_encoder.final_state,
                                                EMBEDDING_SIZE,
                                                use_bias=False)
            title_affected_content = tf.expand_dims(title_final_state, -2) + embedded_content
            content_encoder_outputs = softsign_glu(embedded_content, title_affected_content)

    with tf.variable_scope("output"):
        title_bio_logits = tf.layers.dense(title_encoder.outputs, BIO_ENCODING_SIZE)
        content_bio_logits = tf.layers.dense(content_encoder_outputs, BIO_ENCODING_SIZE)
        title_bio_predictions = tf.argmax(title_bio_logits, -1)
        content_bio_predictions = tf.argmax(content_bio_logits, -1)

    # Assign a default value to the train_op and loss to be passed for modes other than TRAIN
    loss = None
    train_op = None
    eval_metric_ops = None
    # Following part of the network will be constructed only for training
    if mode != tf.estimator.ModeKeys.PREDICT:
        hot_title_bio = tf.one_hot(labels.title_bio, BIO_ENCODING_SIZE)
        hot_content_bio = tf.one_hot(labels.content_bio, BIO_ENCODING_SIZE)
        title_masks = Masks(labels.title_bio, title_bio_predictions, features.title_length)
        content_masks = Masks(labels.content_bio, content_bio_predictions, features.content_length)

        title_bio_precision_loss = tf.losses.softmax_cross_entropy(
            hot_title_bio,
            title_bio_logits,
            title_masks.predicted_tokens)
        content_bio_precision_loss = tf.losses.softmax_cross_entropy(
            hot_content_bio,
            content_bio_logits,
            content_masks.predicted_tokens)

        title_bio_recall_loss = tf.losses.softmax_cross_entropy(
            hot_title_bio,
            title_bio_logits,
            title_masks.annotated_tokens)
        content_bio_recall_loss = tf.losses.softmax_cross_entropy(
            hot_content_bio,
            content_bio_logits,
            content_masks.annotated_tokens)

        loss = tf.losses.get_total_loss()
        tf.summary.scalar('title_precision_loss', title_bio_precision_loss)
        tf.summary.scalar('content_precision_loss', content_bio_precision_loss)
        tf.summary.scalar('title_recall_loss', title_bio_recall_loss)
        tf.summary.scalar('content_recall_loss', content_bio_recall_loss)

        train_op = tf.contrib.layers.optimize_loss(
            loss=loss,
            global_step=tf.contrib.framework.get_global_step(),
            learning_rate=params.learning_rate,
            optimizer="Adam")

        if mode == tf.estimator.ModeKeys.EVAL:
            title_accuracy = tf.metrics.accuracy(
                labels.title_bio,
                title_bio_predictions,
                title_masks.length,
                name='title_accuracy')
            content_accuracy = tf.metrics.accuracy(
                labels.content_bio,
                content_bio_predictions,
                content_masks.length,
                name='content_accuracy')

            title_precision = tf.metrics.accuracy(
                labels.title_bio,
                title_bio_predictions,
                title_masks.predicted_tokens,
                name='title_precision')
            content_precision = tf.metrics.accuracy(
                labels.content_bio,
                content_bio_predictions,
                content_masks.predicted_tokens,
                name='content_precision')

            title_recall = tf.metrics.accuracy(
                labels.title_bio,
                title_bio_predictions,
                title_masks.annotated_tokens,
                name='title_recall')
            content_recall = tf.metrics.accuracy(
                labels.content_bio,
                content_bio_predictions,
                content_masks.annotated_tokens,
                name='content_recall')

            eval_metric_ops = {
                'title_accuracy': title_accuracy,
                'content_accuracy': content_accuracy,
                'title_precision': title_precision,
                'content_precision': content_precision,
                'title_recall': title_recall,
                'content_recall': content_recall
            }

    predictions = {
        'id': features.id,
        'title': features.title,
        'title_length': features.title_length,
        'title_bio': title_bio_predictions,
        'content': features.content,
        'content_length': features.content_length,
        'content_bio': content_bio_predictions
    }

    return tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=predictions,
        loss=loss,
        train_op=train_op,
        eval_metric_ops=eval_metric_ops)

class Masks:
    def __init__(self, tokens_bio: tf.Tensor, bio_predictions: tf.Tensor, length: tf.Tensor):
        self.length = tf.sequence_mask(length, tf.reduce_max(length), tf.float32)
        self.annotated_tokens = tf.cast(tf.greater(tokens_bio, 0), tf.float32)
        self.predicted_tokens = tf.cast(tf.greater(bio_predictions, 0), tf.float32)

class RNNLayer:
    def __init__(self, inputs: tf.Tensor, inputs_lengths: tf.Tensor, num_hidden: int, initial_states: tuple = None):
        fw_cell = tf.nn.rnn_cell.GRUCell(num_hidden, activation=tf.nn.tanh)
        bw_cell = tf.nn.rnn_cell.GRUCell(num_hidden, activation=tf.nn.tanh)
        if initial_states is not None:
            fw_initial_state, bw_initial_state = initial_states
        else:
            fw_initial_state, bw_initial_state = None, None

        self.outputs_tuple, self.final_states_tuple = tf.nn.bidirectional_dynamic_rnn(
            fw_cell, bw_cell, inputs, inputs_lengths,
            initial_state_fw=fw_initial_state,
            initial_state_bw=bw_initial_state,
            dtype=tf.float32)

    @property
    def outputs(self):
        return tf.reduce_sum(self.outputs_tuple, axis=0)

    @property
    def final_state(self):
        return tf.reduce_sum(self.final_states_tuple, axis=0)

def softsign_glu(values: tf.Tensor, gate_values: tf.Tensor):
    with tf.name_scope("softsign_glu"):
        return tf.nn.softsign(gate_values) * values


text:
Available DASH Updates

        <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
        {{error}}

 {{loadingMessage}}

Available Updates

The following table lists all of the updates that may be applied to your DASH server.

Select the link associated with the desired version to being the update process.

The current DASH version is: {{availableUpdates.currentVersion}}.

            No updates are currently available!

                    Version
                    Severity
                    Description

                        <button type="button" class="btn btn-link" ng-disabled="updateInProgress" data-ng-click="applyUpdate(update)">
                            Apply Update
                        </button>

                    {{update.versionString}}
                    {{update.severity}}


text:
# overwrite cache variable macro
macro(ow_cache variable value type text)
    if ("${text}" STREQUAL "")
        message(FATAL_ERROR "ow_cache(overwrite_cache) macro NEEDS a 'text' paramter")
    else()
        set(${variable} ${value} CACHE ${type} ${text} FORCE)
    endif()
endmacro()

# set opencv paramers
ow_cache(BUILD_opencv_apps      OFF BOOL    "Build utility applications (used for example to train classifiers)")
ow_cache(BUILD_ANDROID_EXAMPLES OFF BOOL    "Build examples for Android platform")
ow_cache(BUILD_DOCS             OFF BOOL    "Create build rules for OpenCV Documentation")
ow_cache(BUILD_EXAMPLES         OFF BOOL    "Build all examples")
ow_cache(BUILD_PACKAGE          OFF BOOL    "Enables 'make package_source' command")
ow_cache(BUILD_PERF_TESTS       OFF BOOL    "Build performance tests")
ow_cache(BUILD_TESTS            OFF BOOL    "Build accuracy & regression tests")
ow_cache(BUILD_WITH_DEBUG_INFO  ON  BOOL    "Include debug info into debug libs (not MSCV only)")
ow_cache(WITH_GTK_2_X           ON  BOOL    "Use GTK version 2")
ow_cache(WITH_LIBV4L            ON  BOOL    "Use libv4l for Video 4 Linux support")
ow_cache(BUILD_opencv_ts        ON  BOOL    "Build opencv_ts")
ow_cache(BUILD_opencv_python    OFF  BOOL   "Build opencv_python")
ow_cache(BUILD_opencv_python2   OFF  BOOL   "Build opencv_python2")
ow_cache(BUILD_opencv_python3   OFF  BOOL   "Build opencv_python3")
ow_cache(WITH_GSTREAMER_0_10    ON   BOOL   "Build with gstreamer")

# include opencv
add_subdirectory(opencv)

# find opencv module headers and include them
macro(find_opencv_headers return_list)
    file(GLOB new_list ${PROJECT_SOURCE_DIR}/opencv/modules/**/*)
    get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
    set(dir_list "")
    FOREACH(file_path ${new_list})
        GET_FILENAME_COMPONENT(dir_path ${file_path} PATH)
        SET(dir_list ${dir_list} ${dir_path}/include)
    ENDFOREACH()
    list(REMOVE_DUPLICATES dir_list)
    set(${return_list} ${dir_list})
endmacro()
find_opencv_headers(open_cv_headers)
set(OpenCV_INCLUDE_DIRS ${open_cv_headers})
include_directories(${OpenCV_INCLUDE_DIRS})

# include generated opencv headers
include_directories(${PROJECT_SOURCE_DIR}/opencv/include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/opencv)
include_directories(${CMAKE_CURRENT_BINARY_DIR})

# set all avaialbe libs to the OpenCV_LIBS variable
SET(OpenCV_LIBS
    opencv_calib3d
    opencv_core
    opencv_features2d
    opencv_flann
    opencv_highgui
    opencv_imgcodecs
    opencv_imgproc
    opencv_ml
    opencv_objdetect
    opencv_photo
    opencv_shape
    opencv_stitching
    opencv_superres
    opencv_ts
    opencv_video
    opencv_videoio
    opencv_videostab
)


text:
'use strict';

var app = require('./config/lib/app');
var server = app.start();


text:
"""Exposes a HTTP API from performing operations on click-tracking ads in DCM.

Supports hosting on GAE Standard.
"""

from datetime import datetime
from datetime import timedelta
import json
import logging
import os
from urlparse import urlparse
from googleapiclient import discovery
from googleapiclient.errors import HttpError
import jinja2
from oauth2client.contrib import appengine
import webapp2
from google.appengine.api import urlfetch

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    autoescape=True,
    extensions=['jinja2.ext.autoescape'])

# Client should download the credentials and deploy them with the code
# We could use KMS or Datastore, but let's keep it simple for now
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')

API_NAME = 'dfareporting'
API_VERSION = 'v2.8'
API_SCOPES = ['https://www.googleapis.com/auth/dfatrafficking']

TIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'

decorator = appengine.oauth2decorator_from_clientsecrets(
    CLIENT_SECRETS, scope=API_SCOPES)

service = discovery.build(API_NAME, API_VERSION)

class MainHandler(webapp2.RequestHandler):

  @decorator.oauth_required
  def get(self):
    credentials = decorator.get_credentials()
    if credentials.access_token_expired:
      credentials.refresh(decorator.http())
    template = JINJA_ENVIRONMENT.get_template('templates/index.html')
    self.response.write(template.render())

class ProfilesHandler(webapp2.RequestHandler):

  @decorator.oauth_required
  def get(self):
    resp = service.userProfiles().list().execute(http=decorator.http())
    self.response.write(json.dumps({'profiles': resp['items']}))

class PlacementsHandler(webapp2.RequestHandler):
  """Handles placement lookup (GET) and click-tracker creation (POST)."""

  @decorator.oauth_required
  def get(self, profile_id, placement_id):
    try:
      http = decorator.http()
      resp = service.placements().get(
          profileId=profile_id, id=placement_id).execute(http=http)
      logging.debug(resp)
      self.response.write(json.dumps({'placement': resp}))
    except HttpError as err:
      upstream_error = json.loads(err.content)['error']
      logging.error(upstream_error)
      resp = {
          'code': upstream_error['code'],
          'message': upstream_error['message']
      }
      self.response.set_status(resp['code'])
      self.response.write(json.dumps(resp))

  @decorator.oauth_required
  def post(self, profile_id, placement_id):
    data = json.loads(self.request.body)
    http = decorator.http()
    placement = service.placements().get(
        profileId=profile_id, id=placement_id).execute(http=http)
    one_year = datetime.now() + timedelta(days=365)
    tracker_urls = {}
    for t in data['trackers']:
      url = urlparse(t['url'])
      ad = service.ads().insert(
          profileId=profile_id,
          body={
              'advertiserId':
                  placement['advertiserId'],
              'campaignId':
                  placement['campaignId'],
              'placementId':
                  placement_id,
              'type':
                  'AD_SERVING_CLICK_TRACKER',
              'clickThroughUrl': {
                  'customClickThroughUrl': url.geturl(),
                  'defaultLandingPage': False
              },
              'name':
                  t['name'],
              'active':
                  True,
              'dynamicClickTracker':
                  True,
              'startTime': (datetime.now() + timedelta(seconds=3))
                           .strftime(TIME_FORMAT),
              'endTime':
                  one_year.strftime(TIME_FORMAT),
              'placementAssignments': [{
                  'placementId': placement_id,
                  'active': True
              }]
          }).execute(http=http)
      tracker_urls[ad['id']] = {'name': t['name']}
    # increase timeout for tag generation
    urlfetch.set_default_fetch_deadline(30)
    tags = service.placements().generatetags(
        profileId=profile_id,
        campaignId=placement['campaignId'],
        placementIds=[placement_id],
        tagFormats=['PLACEMENT_TAG_CLICK_COMMANDS']).execute(http=http)
    for pt in tags['placementTags']:
      if pt['placementId'] == placement_id:
        for td in pt['tagDatas']:
          if td['adId'] in tracker_urls:
            tracker_urls[td['adId']]['clickUrl'] = td['clickTag']
    resp = json.dumps({'uploaded': tracker_urls})
    logging.debug(resp)
    self.response.write(resp)

app = webapp2.WSGIApplication(
    [
        ('/', MainHandler),
        (r'/profiles', ProfilesHandler),
        (r'/profiles/(\d+)/placements/(\d+)', PlacementsHandler),
        (decorator.callback_path, decorator.callback_handler()),
    ],
    debug=True)


text:
package org.hisp.dhis.analytics.data;

import static com.google.common.collect.Lists.newArrayList;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import org.hisp.dhis.analytics.AnalyticsManager;
import org.hisp.dhis.analytics.AnalyticsSecurityManager;
import org.hisp.dhis.analytics.DataQueryGroups;
import org.hisp.dhis.analytics.DataQueryParams;
import org.hisp.dhis.analytics.DataQueryService;
import org.hisp.dhis.analytics.QueryPlanner;
import org.hisp.dhis.analytics.QueryPlannerParams;
import org.hisp.dhis.analytics.RawAnalyticsManager;
import org.hisp.dhis.analytics.analyze.ExecutionPlanStore;
import org.hisp.dhis.analytics.cache.AnalyticsCache;
import org.hisp.dhis.analytics.cache.AnalyticsCacheSettings;
import org.hisp.dhis.analytics.data.handler.DataAggregator;
import org.hisp.dhis.analytics.data.handler.DataHandler;
import org.hisp.dhis.analytics.data.handler.HeaderHandler;
import org.hisp.dhis.analytics.data.handler.MetadataHandler;
import org.hisp.dhis.analytics.data.handler.SchemaIdResponseMapper;
import org.hisp.dhis.analytics.event.EventAnalyticsService;
import org.hisp.dhis.analytics.resolver.ExpressionResolvers;
import org.hisp.dhis.expression.ExpressionService;
import org.hisp.dhis.external.conf.DhisConfigurationProvider;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;

/**
 * @author Luciano Fiandesio
 */
@MockitoSettings( strictness = Strictness.LENIENT )
@ExtendWith( { MockitoExtension.class } )
abstract class AnalyticsServiceBaseTest
{
    @Mock
    protected AnalyticsManager analyticsManager;

    @Mock
    private RawAnalyticsManager rawAnalyticsManager;

    @Mock
    private AnalyticsSecurityManager securityManager;

    @Mock
    private QueryPlanner queryPlanner;

    @Mock
    private ExpressionService expressionService;

    @Mock
    private OrganisationUnitService organisationUnitService;

    @Mock
    private SystemSettingManager systemSettingManager;

    @Mock
    protected EventAnalyticsService eventAnalyticsService;

    @Mock
    private DataQueryService dataQueryService;

    @Mock
    private SchemaIdResponseMapper schemaIdResponseMapper;

    @Mock
    private DhisConfigurationProvider dhisConfig;

    @Mock
    private AnalyticsCache analyticsCache;

    @Mock
    private AnalyticsCacheSettings analyticsCacheSettings;

    @Mock
    private ExpressionResolvers resolvers;

    @Mock
    private NestedIndicatorCyclicDependencyInspector nestedIndicatorCyclicDependencyInspector;

    @Mock
    private ExecutionPlanStore executionPlanStore;

    DataAggregator target;

    @BeforeEach
    public void baseSetUp()
    {
        DefaultQueryValidator queryValidator = new DefaultQueryValidator( systemSettingManager );

        HeaderHandler headerHandler = new HeaderHandler();
        MetadataHandler metadataHandler = new MetadataHandler( dataQueryService, schemaIdResponseMapper );
        DataHandler dataHandler = new DataHandler( eventAnalyticsService, rawAnalyticsManager,
            resolvers, expressionService, queryPlanner, queryValidator, systemSettingManager, analyticsManager,
            organisationUnitService, executionPlanStore );

        target = new DataAggregator( headerHandler, metadataHandler, dataHandler );
        target.feedHandlers();

        when( systemSettingManager.getBooleanSetting( SettingKey.ANALYTICS_MAINTENANCE_MODE ) )
            .thenReturn( false );
        when( analyticsCacheSettings.fixedExpirationTimeOrDefault() ).thenReturn( 0L );
    }

    void initMock( DataQueryParams params )
    {
        when( securityManager.withDataApprovalConstraints( Mockito.any( DataQueryParams.class ) ) )
            .thenReturn( params );
        when( securityManager.withUserConstraints( any( DataQueryParams.class ) ) ).thenReturn( params );
        when( queryPlanner.planQuery( any( DataQueryParams.class ), any( QueryPlannerParams.class ) ) ).thenReturn(
            DataQueryGroups.newBuilder().withQueries( newArrayList( DataQueryParams.newBuilder().build() ) ).build() );
    }
}