text:
<?php

require_once 'Zend/Controller/Action.php';

/**
 * AtomController
 *
 */
class AtomController extends AbstractController
{
    /**
     * Pre-dispatch routines
     *
     * Makes sure that configured actions are protected by wsse.
     *
     * @return void
     */
    public function preDispatch()
    {
        $config = Zend_Registry::get('atom-config');

        if (false == in_array($this->_request->getActionName(), $config->securedActions->toArray())
            || $config->authenticationDisabled) {
            return; // found public action or authentication is disabled
        }

        $adapter = new Yag_Auth_Adapter_Http_Wsse($config->wsse->toArray());
        $adapter->setRequest($this->_request);
        $adapter->setResponse($this->_response);

        $result = $adapter->authenticate();
        if (false == $result->isValid()) {
            $this->view->errorMessages = $result->getMessages();
            $this->_forward('error');
        }
    }

    /**
     * Init
     *
     * Disables layout and sets common Content-Type.
     */
    public function init()
    {
        $layout = $this->_helper->getHelper('layout');
        $layout->direct()->disableLayout();
        $this->_response->setHeader('Content-Type', 'application/x.atom+xml', true);
        // Atom 1.0 preparation...
        //$this->_response->setHeader('Content-Type', 'application/atom+xml;type=entry', true);
    }

    /**
     * Index action
     */
    public function indexAction()
    {
        $this->view->url = 'http://' . $this->_request->getHttpHost() . $this->_request->getBaseUrl();
        // TODO: This is for atom 1.0
        //$this->_response->setHeader('Content-Type', 'application/atomsvc+xml', true);
    }

    /**
     * Error action.
     *
     */
    public function errorAction()
    {
        $this->_response->setHeader('Content-Type', 'text/plain', true);
    }

    /**
     * Upload action
     *
     * Handles atom file uploading, not pretty but gets the work done for now.
     *
     * @return void
     */
    public function uploadAction()
    {
        try {
            $this->_helper->viewRenderer->setNoRender();
            $feed = Zend_Feed::importString($this->_request->getRawBody());
        } catch (Exception $e) {
            $this->_response->setHttpResponseCode(400); // 415 unsuported media?
            $this->_response->setHeader('Status', '400 Unable to read feed', true);
            $this->view->errorMessages = array('Unable to read feed');
            return $this->_forward('error');
        }

        $photoModel = $this->_getPhotoModel();
        $id = null;

        foreach ($feed as $entry) {
            //
            // Entry is related to another entry
            //
            if (isset($entry->link)) {
                // Set description
                if ('' != $entry->content() && $entry->content->offsetGet('mode') == 'xml') {
                    $description = (string) $entry->content;
                }
                // Set tags
                if ('' != ($tags = $entry->{"dc:subject"})) {
                     $tags = implode(',', explode(' ', $tags));
                }

                $entryData = array();

                if (!is_array($entry->link)) {
                    $id = $entry->link('related');
                    $photo = $photoModel->fetchEntry($id);
                    $entryData = $photo->toArray();
                    $entryData['description'] = $description;
                    $entryData['tags'] = $tags;
                    $photoModel->update($entryData, $id);
                } else {
                    foreach ($entry->link as $link) {
                        $id = $link->getDom()->getAttribute('href');
                        try {
                            $photo = $photoModel->fetchEntry($id);
                            $entryData = $photo->toArray();
                            $entryData['description'] = $description;
                            $entryData['tags'] = $tags;
                            $photoModel->update($entryData, $id);
                        } catch (Exception $e) {
                            ; // TODO: Log....
                        }
                    }
                }
            //
            // A new entry is uploaded
            //
            } else if ('' != $entry->content()) {
	            $file = $this->_createTmpFile(base64_decode($entry->content()));
	            $entryData = array();
	            $entryData['title']       = $entry->title;
	            $entryData['created_on']  = date('Y-m-d H:i:s', strtotime($entry->issued));

	            $id = $photoModel->add($entryData, $file);
            } else {
                continue;
            }

            $url = 'http://' . $this->_request->getHttpHost() . $this->_request->getBaseUrl();

            $this->_response->setHttpResponseCode(201);
            $this->_response->setHeader('Status', '201 Created');
            $this->_response->setHeader('Location', $url . $this->_helper->url('show', 'photo', null, array('id' => $id)));

            $this->view->url   = $url;
            $this->view->photo = $photoModel->fetchEntry($id);

            $this->render('upload');
        }
    }

    /**
     * Feed action
     *
     * @return void
     */
    public function feedAction()
    {
        $this->_forward('list', 'photo', null, array('format' => 'atom'));
    }

    /**
     * Creates a temporary file.
     *
     * @param mixed $data
     * @return string
     */
    private function _createTmpFile($data)
    {
        //$size = getimagesize($data);
        // TODO: Get correct extension
        // TODO: fixed tmp path
        $filename = APPLICATION_PATH . '/../upload/app-' . date('Ymhis', time()) . '.jpg';
        file_put_contents($filename, $data);
        return $filename;
    }
}


text:
package com.feetao.web.model;

import java.io.Serializable;
import java.util.Date;

public class BoardMsgDO implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 主键ID
	 */
	private Long id;

	/**
	 * 用户ID
	 */
	private Long userId;

	/**
	 * 关注者唯一ID
	 */
	private String openId;

	/**
	 * 留言内容
	 */
	private String content;

	/**
	 * 状态
	 */
	private Byte status;

	/**
	 * 创建时间
	 */
	private Date gmtCreate;

	/**
	 * 更新时间
	 */
	private Date gmtModified;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public String getOpenId() {
		return openId;
	}

	public void setOpenId(String openId) {
		this.openId = openId;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Byte getStatus() {
		return status;
	}

	public void setStatus(Byte status) {
		this.status = status;
	}

	public Date getGmtCreate() {
		return gmtCreate;
	}

	public void setGmtCreate(Date gmtCreate) {
		this.gmtCreate = gmtCreate;
	}

	public Date getGmtModified() {
		return gmtModified;
	}

	public void setGmtModified(Date gmtModified) {
		this.gmtModified = gmtModified;
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

abstract class NuanceItemType
  extends Phobject {

  private $viewer;

  public function setViewer(PhabricatorUser $viewer) {
    $this->viewer = $viewer;
    return $this;
  }

  public function getViewer() {
    return $this->viewer;
  }

  public function canUpdateItems() {
    return false;
  }

  final public function buildItemView(NuanceItem $item) {
    return $this->newItemView($item);
  }

  protected function newItemView() {
    return null;
  }

  public function getItemTypeDisplayIcon() {
    return null;
  }

  abstract public function getItemTypeDisplayName();
  abstract public function getItemDisplayName(NuanceItem $item);

  final public function updateItem(NuanceItem $item) {
    if (!$this->canUpdateItems()) {
      throw new Exception(
        pht(
          'This item type ("%s", of class "%s") can not update items.',
          $this->getItemTypeConstant(),
          get_class($this)));
    }

    $this->updateItemFromSource($item);
  }

  protected function updateItemFromSource(NuanceItem $item) {
    throw new PhutilMethodNotImplementedException();
  }

  final public function getItemTypeConstant() {
    return $this->getPhobjectClassConstant('ITEMTYPE', 64);
  }

  final public static function getAllItemTypes() {
    return id(new PhutilClassMapQuery())
      ->setAncestorClass(__CLASS__)
      ->setUniqueMethod('getItemTypeConstant')
      ->execute();
  }

}


text:
RLlib Models, Preprocessors, and Action Distributions
=====================================================

The following diagram provides a conceptual overview of data flow between different components in RLlib. We start with an ``Environment``, which given an action produces an observation. The observation is preprocessed by a ``Preprocessor`` and ``Filter`` (e.g. for running mean normalization) before being sent to a neural network ``Model``. The model output is in turn interpreted by an ``ActionDistribution`` to determine the next action.

.. image:: rllib-components.svg

The components highlighted in green can be replaced with custom user-defined implementations, as described in the next sections. The purple components are RLlib internal, which means they can only be modified by changing the algorithm source code.

Default Behaviours
------------------

Built-in Models and Preprocessors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

RLlib picks default models based on a simple heuristic: a `vision network <https://github.com/ray-project/ray/blob/master/rllib/models/tf/visionnet_v1.py>`__ for image observations, and a `fully connected network <https://github.com/ray-project/ray/blob/master/rllib/models/tf/fcnet_v1.py>`__ for everything else. These models can be configured via the ``model`` config key, documented in the model `catalog <https://github.com/ray-project/ray/blob/master/rllib/models/catalog.py>`__. Note that you'll probably have to configure ``conv_filters`` if your environment observations have custom sizes, e.g., ``"model": {"dim": 42, "conv_filters": [[16, [4, 4], 2], [32, [4, 4], 2], [512, [11, 11], 1]]}`` for 42x42 observations.

In addition, if you set ``"model": {"use_lstm": true}``, then the model output will be further processed by a `LSTM cell <https://github.com/ray-project/ray/blob/master/rllib/models/tf/lstm_v1.py>`__. More generally, RLlib supports the use of recurrent models for its policy gradient algorithms (A3C, PPO, PG, IMPALA), and RNN support is built into its policy evaluation utilities.

For preprocessors, RLlib tries to pick one of its built-in preprocessor based on the environment's observation space. Discrete observations are one-hot encoded, Atari observations downscaled, and Tuple and Dict observations flattened (these are unflattened and accessible via the ``input_dict`` parameter in custom models). Note that for Atari, RLlib defaults to using the `DeepMind preprocessors <https://github.com/ray-project/ray/blob/master/rllib/env/atari_wrappers.py>`__, which are also used by the OpenAI baselines library.

Built-in Model Parameters
~~~~~~~~~~~~~~~~~~~~~~~~~

The following is a list of the built-in model hyperparameters:

.. literalinclude:: ../../rllib/models/catalog.py
   :language: python
   :start-after: __sphinx_doc_begin__
   :end-before: __sphinx_doc_end__

TensorFlow Models
-----------------

.. note::

    TFModelV2 replaces the previous ``rllib.models.Model`` class, which did not support Keras-style reuse of variables. The ``rllib.models.Model`` class is deprecated and should not be used.

Custom TF models should subclass `TFModelV2 <https://github.com/ray-project/ray/blob/master/rllib/models/tf/tf_modelv2.py>`__ to implement the ``__init__()`` and ``forward()`` methods. Forward takes in a dict of tensor inputs (the observation ``obs``, ``prev_action``, and ``prev_reward``, ``is_training``), optional RNN state, and returns the model output of size ``num_outputs`` and the new state. You can also override extra methods of the model such as ``value_function`` to implement a custom value branch. Additional supervised / self-supervised losses can be added via the ``custom_loss`` method:

.. autoclass:: ray.rllib.models.tf.tf_modelv2.TFModelV2

    .. automethod:: __init__
    .. automethod:: forward
    .. automethod:: value_function
    .. automethod:: custom_loss
    .. automethod:: metrics
    .. automethod:: update_ops
    .. automethod:: register_variables
    .. automethod:: variables
    .. automethod:: trainable_variables

Once implemented, the model can then be registered and used in place of a built-in model:

.. code-block:: python

    import ray
    import ray.rllib.agents.ppo as ppo
    from ray.rllib.models import ModelCatalog
    from ray.rllib.models.tf.tf_modelv2 import TFModelV2

    class MyModelClass(TFModelV2):
        def __init__(self, obs_space, action_space, num_outputs, model_config, name): ...
        def forward(self, input_dict, state, seq_lens): ...
        def value_function(self): ...

    ModelCatalog.register_custom_model("my_model", MyModelClass)

    ray.init()
    trainer = ppo.PPOTrainer(env="CartPole-v0", config={
        "model": {
            "custom_model": "my_model",
            "custom_options": {},  # extra options to pass to your model
        },
    })

For a full example of a custom model in code, see the `keras model example <https://github.com/ray-project/ray/blob/master/rllib/examples/custom_keras_model.py>`__. You can also reference the `unit tests <https://github.com/ray-project/ray/blob/master/rllib/tests/test_nested_spaces.py>`__ for Tuple and Dict spaces, which show how to access nested observation fields.

Recurrent Models
~~~~~~~~~~~~~~~~

Instead of using the ``use_lstm: True`` option, it can be preferable use a custom recurrent model. This provides more control over postprocessing of the LSTM output and can also allow the use of multiple LSTM cells to process different portions of the input. For a RNN model it is preferred to subclass ``RecurrentTFModelV2`` to implement ``__init__()``, ``get_initial_state()``, and ``forward_rnn()``. You can check out the `custom_keras_rnn_model.py <https://github.com/ray-project/ray/blob/master/rllib/examples/custom_keras_rnn_model.py>`__ model as an example to implement your own model:

.. autoclass:: ray.rllib.models.tf.recurrent_tf_modelv2.RecurrentTFModelV2

    .. automethod:: __init__
    .. automethod:: forward_rnn
    .. automethod:: get_initial_state

Batch Normalization
~~~~~~~~~~~~~~~~~~~

You can use ``tf.layers.batch_normalization(x, training=input_dict["is_training"])`` to add batch norm layers to your custom model: `code example <https://github.com/ray-project/ray/blob/master/rllib/examples/batch_norm_model.py>`__. RLlib will automatically run the update ops for the batch norm layers during optimization (see `tf_policy.py <https://github.com/ray-project/ray/blob/master/rllib/policy/tf_policy.py>`__ and `multi_gpu_impl.py <https://github.com/ray-project/ray/blob/master/rllib/optimizers/multi_gpu_impl.py>`__ for the exact handling of these updates).

In case RLlib does not properly detect the update ops for your custom model, you can override the ``update_ops()`` method to return the list of ops to run for updates.

PyTorch Models
--------------

Similarly, you can create and register custom PyTorch models for use with PyTorch-based algorithms (e.g., A2C, PG, QMIX). See these examples of `fully connected <https://github.com/ray-project/ray/blob/master/rllib/models/torch/fcnet.py>`__, `convolutional <https://github.com/ray-project/ray/blob/master/rllib/models/torch/visionnet.py>`__, and `recurrent <https://github.com/ray-project/ray/blob/master/rllib/agents/qmix/model.py>`__ torch models.

.. autoclass:: ray.rllib.models.torch.torch_modelv2.TorchModelV2

    .. automethod:: __init__
    .. automethod:: forward
    .. automethod:: value_function
    .. automethod:: custom_loss
    .. automethod:: metrics
    .. automethod:: get_initial_state

Once implemented, the model can then be registered and used in place of a built-in model:

.. code-block:: python

    import torch.nn as nn

    import ray
    from ray.rllib.agents import a3c
    from ray.rllib.models import ModelCatalog
    from ray.rllib.models.torch.torch_modelv2 import TorchModelV2

    class CustomTorchModel(nn.Module, TorchModelV2):
        def __init__(self, obs_space, action_space, num_outputs, model_config, name): ...
        def forward(self, input_dict, state, seq_lens): ...
        def value_function(self): ...

    ModelCatalog.register_custom_model("my_model", CustomTorchModel)

    ray.init()
    trainer = a3c.A2CTrainer(env="CartPole-v0", config={
        "use_pytorch": True,
        "model": {
            "custom_model": "my_model",
            "custom_options": {},  # extra options to pass to your model
        },
    })

Custom Preprocessors
--------------------

Custom preprocessors should subclass the RLlib `preprocessor class <https://github.com/ray-project/ray/blob/master/rllib/models/preprocessors.py>`__ and be registered in the model catalog. Note that you can alternatively use `gym wrapper classes <https://github.com/openai/gym/tree/master/gym/wrappers>`__ around your environment instead of preprocessors.

.. code-block:: python

    import ray
    import ray.rllib.agents.ppo as ppo
    from ray.rllib.models import ModelCatalog
    from ray.rllib.models.preprocessors import Preprocessor

    class MyPreprocessorClass(Preprocessor):
        def _init_shape(self, obs_space, options):
            return new_shape  # can vary depending on inputs

        def transform(self, observation):
            return ...  # return the preprocessed observation

    ModelCatalog.register_custom_preprocessor("my_prep", MyPreprocessorClass)

    ray.init()
    trainer = ppo.PPOTrainer(env="CartPole-v0", config={
        "model": {
            "custom_preprocessor": "my_prep",
            "custom_options": {},  # extra options to pass to your preprocessor
        },
    })

Custom Action Distributions
---------------------------

Similar to custom models and preprocessors, you can also specify a custom action distribution class as follows. The action dist class is passed a reference to the ``model``, which you can use to access ``model.model_config`` or other attributes of the model. This is commonly used to implement `autoregressive action outputs <#autoregressive-action-distributions>`__.

.. code-block:: python

    import ray
    import ray.rllib.agents.ppo as ppo
    from ray.rllib.models import ModelCatalog
    from ray.rllib.models.preprocessors import Preprocessor

    class MyActionDist(ActionDistribution):
        @staticmethod
        def required_model_output_shape(action_space, model_config):
            return 7  # controls model output feature vector size

        def __init__(self, inputs, model):
            super(MyActionDist, self).__init__(inputs, model)
            assert model.num_outputs == 7

        def sample(self): ...
        def logp(self, actions): ...
        def entropy(self): ...

    ModelCatalog.register_custom_action_dist("my_dist", MyActionDist)

    ray.init()
    trainer = ppo.PPOTrainer(env="CartPole-v0", config={
        "model": {
            "custom_action_dist": "my_dist",
        },
    })

Supervised Model Losses
-----------------------

You can mix supervised losses into any RLlib algorithm through custom models. For example, you can add an imitation learning loss on expert experiences, or a self-supervised autoencoder loss within the model. These losses can be defined over either policy evaluation inputs, or data read from `offline storage <rllib-offline.html#input-pipeline-for-supervised-losses>`__.

**TensorFlow**: To add a supervised loss to a custom TF model, you need to override the ``custom_loss()`` method. This method takes in the existing policy loss for the algorithm, which you can add your own supervised loss to before returning. For debugging, you can also return a dictionary of scalar tensors in the ``metrics()`` method. Here is a `runnable example <https://github.com/ray-project/ray/blob/master/rllib/examples/custom_loss.py>`__ of adding an imitation loss to CartPole training that is defined over a `offline dataset <rllib-offline.html#input-pipeline-for-supervised-losses>`__.

**PyTorch**: There is no explicit API for adding losses to custom torch models. However, you can modify the loss in the policy definition directly. Like for TF models, offline datasets can be incorporated by creating an input reader and calling ``reader.next()`` in the loss forward pass.

Variable-length / Parametric Action Spaces
------------------------------------------

Custom models can be used to work with environments where (1) the set of valid actions `varies per step <https://neuro.cs.ut.ee/the-use-of-embeddings-in-openai-five>`__, and/or (2) the number of valid actions is `very large <https://arxiv.org/abs/1811.00260>`__. The general idea is that the meaning of actions can be completely conditioned on the observation, i.e., the ``a`` in ``Q(s, a)`` becomes just a token in ``[0, MAX_AVAIL_ACTIONS)`` that only has meaning in the context of ``s``. This works with algorithms in the `DQN and policy-gradient families <rllib-env.html>`__ and can be implemented as follows:

1. The environment should return a mask and/or list of valid action embeddings as part of the observation for each step. To enable batching, the number of actions can be allowed to vary from 1 to some max number:

.. code-block:: python

   class MyParamActionEnv(gym.Env):
       def __init__(self, max_avail_actions):
           self.action_space = Discrete(max_avail_actions)
           self.observation_space = Dict({
               "action_mask": Box(0, 1, shape=(max_avail_actions, )),
               "avail_actions": Box(-1, 1, shape=(max_avail_actions, action_embedding_sz)),
               "real_obs": ...,
           })

2. A custom model can be defined that can interpret the ``action_mask`` and ``avail_actions`` portions of the observation. Here the model computes the action logits via the dot product of some network output and each action embedding. Invalid actions can be masked out of the softmax by scaling the probability to zero:

.. code-block:: python

    class ParametricActionsModel(TFModelV2):
        def __init__(self,
                     obs_space,
                     action_space,
                     num_outputs,
                     model_config,
                     name,
                     true_obs_shape=(4,),
                     action_embed_size=2):
            super(ParametricActionsModel, self).__init__(
                obs_space, action_space, num_outputs, model_config, name)
            self.action_embed_model = FullyConnectedNetwork(...)

        def forward(self, input_dict, state, seq_lens):
            # Extract the available actions tensor from the observation.
            avail_actions = input_dict["obs"]["avail_actions"]
            action_mask = input_dict["obs"]["action_mask"]

            # Compute the predicted action embedding
            action_embed, _ = self.action_embed_model({
                "obs": input_dict["obs"]["cart"]
            })

            # Expand the model output to [BATCH, 1, EMBED_SIZE]. Note that the
            # avail actions tensor is of shape [BATCH, MAX_ACTIONS, EMBED_SIZE].
            intent_vector = tf.expand_dims(action_embed, 1)

            # Batch dot product => shape of logits is [BATCH, MAX_ACTIONS].
            action_logits = tf.reduce_sum(avail_actions * intent_vector, axis=2)

            # Mask out invalid actions (use tf.float32.min for stability)
            inf_mask = tf.maximum(tf.log(action_mask), tf.float32.min)
            return action_logits + inf_mask, state

Depending on your use case it may make sense to use just the masking, just action embeddings, or both. For a runnable example of this in code, check out `parametric_action_cartpole.py <https://github.com/ray-project/ray/blob/master/rllib/examples/parametric_action_cartpole.py>`__. Note that since masking introduces ``tf.float32.min`` values into the model output, this technique might not work with all algorithm options. For example, algorithms might crash if they incorrectly process the ``tf.float32.min`` values. The cartpole example has working configurations for DQN (must set ``hiddens=[]``), PPO (must disable running mean and set ``vf_share_layers=True``), and several other algorithms. Not all algorithms support parametric actions; see the `feature compatibility matrix <rllib-env.html#feature-compatibility-matrix>`__.

Autoregressive Action Distributions
-----------------------------------

In an action space with multiple components (e.g., ``Tuple(a1, a2)``), you might want ``a2`` to be conditioned on the sampled value of ``a1``, i.e., ``a2_sampled ~ P(a2 | a1_sampled, obs)``. Normally, ``a1`` and ``a2`` would be sampled independently, reducing the expressivity of the policy.

To do this, you need both a custom model that implements the autoregressive pattern, and a custom action distribution class that leverages that model. The `autoregressive_action_dist.py <https://github.com/ray-project/ray/blob/master/rllib/examples/autoregressive_action_dist.py>`__ example shows how this can be implemented for a simple binary action space. For a more complex space, a more efficient architecture such as a `MADE <https://arxiv.org/abs/1502.03509>`__ is recommended. Note that sampling a `N-part` action requires `N` forward passes through the model, however computing the log probability of an action can be done in one pass:

.. code-block:: python

    class BinaryAutoregressiveOutput(ActionDistribution):
        """Action distribution P(a1, a2) = P(a1) * P(a2 | a1)"""

        @staticmethod
        def required_model_output_shape(self, model_config):
            return 16  # controls model output feature vector size

        def sample(self):
            # first, sample a1
            a1_dist = self._a1_distribution()
            a1 = a1_dist.sample()

            # sample a2 conditioned on a1
            a2_dist = self._a2_distribution(a1)
            a2 = a2_dist.sample()

            # return the action tuple
            return TupleActions([a1, a2])

        def logp(self, actions):
            a1, a2 = actions[:, 0], actions[:, 1]
            a1_vec = tf.expand_dims(tf.cast(a1, tf.float32), 1)
            a1_logits, a2_logits = self.model.action_model([self.inputs, a1_vec])
            return (Categorical(a1_logits, None).logp(a1) + Categorical(
                a2_logits, None).logp(a2))

        def _a1_distribution(self):
            BATCH = tf.shape(self.inputs)[0]
            a1_logits, _ = self.model.action_model(
                [self.inputs, tf.zeros((BATCH, 1))])
            a1_dist = Categorical(a1_logits, None)
            return a1_dist

        def _a2_distribution(self, a1):
            a1_vec = tf.expand_dims(tf.cast(a1, tf.float32), 1)
            _, a2_logits = self.model.action_model([self.inputs, a1_vec])
            a2_dist = Categorical(a2_logits, None)
            return a2_dist

    class AutoregressiveActionsModel(TFModelV2):
        """Implements the `.action_model` branch required above."""

        def __init__(self, obs_space, action_space, num_outputs, model_config,
                     name):
            super(AutoregressiveActionsModel, self).__init__(
                obs_space, action_space, num_outputs, model_config, name)
            if action_space != Tuple([Discrete(2), Discrete(2)]):
                raise ValueError(
                    "This model only supports the [2, 2] action space")

            # Inputs
            obs_input = tf.keras.layers.Input(
                shape=obs_space.shape, name="obs_input")
            a1_input = tf.keras.layers.Input(shape=(1, ), name="a1_input")
            ctx_input = tf.keras.layers.Input(
                shape=(num_outputs, ), name="ctx_input")

            # Output of the model (normally 'logits', but for an autoregressive
            # dist this is more like a context/feature layer encoding the obs)
            context = tf.keras.layers.Dense(
                num_outputs,
                name="hidden",
                activation=tf.nn.tanh,
                kernel_initializer=normc_initializer(1.0))(obs_input)

            # P(a1 | obs)
            a1_logits = tf.keras.layers.Dense(
                2,
                name="a1_logits",
                activation=None,
                kernel_initializer=normc_initializer(0.01))(ctx_input)

            # P(a2 | a1)
            # --note: typically you'd want to implement P(a2 | a1, obs) as follows:
            # a2_context = tf.keras.layers.Concatenate(axis=1)(
            #     [ctx_input, a1_input])
            a2_context = a1_input
            a2_hidden = tf.keras.layers.Dense(
                16,
                name="a2_hidden",
                activation=tf.nn.tanh,
                kernel_initializer=normc_initializer(1.0))(a2_context)
            a2_logits = tf.keras.layers.Dense(
                2,
                name="a2_logits",
                activation=None,
                kernel_initializer=normc_initializer(0.01))(a2_hidden)

            # Base layers
            self.base_model = tf.keras.Model(obs_input, context)
            self.register_variables(self.base_model.variables)
            self.base_model.summary()

            # Autoregressive action sampler
            self.action_model = tf.keras.Model([ctx_input, a1_input],
                                               [a1_logits, a2_logits])
            self.action_model.summary()
            self.register_variables(self.action_model.variables)

.. note::

   Not all algorithms support autoregressive action distributions; see the `feature compatibility matrix <rllib-env.html#feature-compatibility-matrix>`__.


text:
<!doctype html>

    <title>Code coverage report for ./app/js/services/httpbackendmock.js</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="../prettify.css">

Code coverage report for ./app/js/services/httpbackendmock.js

        Statements: 52.17% (24 / 46)

        Branches: 20% (2 / 10)

        Functions: 54.55% (6 / 11)

        Lines: 52.17% (24 / 46)

        Ignored: none

All files » ./app/js/services\ » httpbackendmock.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

1
1
16

1
1
1
1

1
1
1

16

1

16

1
16

16

16

16

16
16

1

1

1

1

'use strict';

(function (module, angular) {
    module.factory("interceptor", function ($timeout, $rootScope) {
        return {
            "request": function (config) {
                Eif (config.method === 'GET'  ) {
                    var requestUrl = config.url.toString();
                    var n = requestUrl.lastIndexOf('/');
                    requestUrl=  requestUrl.substring(n + 1);

                    Eif(requestUrl.match(/[0-9]+/)){
                        $rootScope.isLoadingRequest = false;
                        return config;
                    }
                }
                $rootScope.isLoadingRequest = true;
                return $timeout(function () {
                    $rootScope.isLoadingRequest = false;
                    return config;
                }, 500);
            }
        };
    })
        .config(function ($httpProvider) {
            $httpProvider.interceptors.push("interceptor");
        });

    module.factory('getCcuFromResource', ['$resource',
        function ($resource, $rootScope) {
            return $resource('testdata/:ccuId.json', {}, {
                get: {method: 'GET', params: {ccuId: 'ccuId'},
                    isArray: false }
            })
        }]);

    module.run(function ($httpBackend, getCcuFromResource) {
        var eventsRegEx = /\/events\/[0-9]+/,
            ccuRegEx = /\/ccu\/[0-9]+/;

        $httpBackend.whenPOST('/events').respond(function (method, url, data) {
            var newEvent = angular.fromJson(data);
            events.push(newEvent);
            return [201, newEvent, {}];
        });

        $httpBackend.whenGET(eventsRegEx).respond(function (method, url) {
            var ccuId = getCcuIdFromURL(url),
                returnList = [];

            for (var event in events) {
                if (events[event].ccuId == ccuId) {
                    returnList.push(events[event]);
                }
            }
            if (returnList.length == 0) {
                return [404, "Not Found!", {}];
            }

            return [200, returnList, {}];
        });

        $httpBackend.whenGET(ccuRegEx).respond(function (method, url) {

            var ccuId = getCcuIdFromURL(url);

            for (var ccu in ccus) {
                if (ccus[ccu].ccuId == ccuId) {
                    return [200,ccus[ccu],{}];
                }
            }
            return [404, "Not Found!", {}];
        });

        $httpBackend.whenGET(/.*/).passThrough();
        $httpBackend.whenPOST(/.*/).passThrough();

        function getCcuIdFromURL(url) {
            var returnList = [];
            var n = url.lastIndexOf('/');
            return url.substring(n + 1);
        }
    });

    var events = [
        {
            "eventId": 1111234232,
            "timestamp": "2014-02-06T13:21:00Z",
            "ccuId": 141705,
            "eventType": "arriving",
            "eventReadPoint": "geo:60.809846,5.031910;crs=wgs84;u=5",
            "eventLocation": 5555548887979
        },
        {
            "eventId": 2222234232,
            "timestamp": "2014-03-12T08:21:00Z",
            "ccuId": 763851,
            "eventType": "inspecting",
            "eventReadPoint": "geo:60.809846,5.031910;crs=wgs84;u=5",
            "eventLocation": 1222267890123
        },
        {
            "eventId": 3333234232,
            "timestamp": "2012-03-13T11:11:00Z",
            "ccuId": 141705,
            "eventType": "departing",
            "eventReadPoint": "geo:60.809846,5.031910;crs=wgs84;u=5",
            "eventLocation": 1111117890123
        },
        {
            "eventId": 5555534232,
            "timestamp": "2012-03-12T08:21:00Z",
            "ccuId": 365891,
            "eventType": "packing",
            "eventReadPoint": "geo:60.809846,5.031910;crs=wgs84;u=5",
            "eventLocation": 8888867890123
        },{
            "eventId": 1111234232,
            "timestamp": "2014-02-06T13:21:00Z",
            "ccuId": 141705,
            "eventType": "arriving",
            "eventReadPoint": "geo:60.809846,5.031910;crs=wgs84;u=5",
            "eventLocation": 5555548887979
        },
        {
            "eventId": 3333234232,
            "timestamp": "2012-03-13T11:11:00Z",
            "ccuId": 763851,
            "eventType": "departing",
            "eventReadPoint": "geo:60.809846,5.031910;crs=wgs84;u=5",
            "eventLocation": 1111117890123
        },
        {
            "eventId": 5555534232,
            "timestamp": "2012-03-12T08:21:00Z",
            "ccuId": 365891,
            "eventType": "packing",
            "eventReadPoint": "geo:60.809846,5.031910;crs=wgs84;u=5",
            "eventLocation": 8888867890123
        }
    ];
    var ccus = [
        {
            "ccuId": 141705,
            "orgNo": 123456789,
            "gln": 1234567890123,
            "ccuClass": "Basket",
            "ccuSubClass": "Half High Basket",
            "ccuOwnerId": 133428,
            "payload": 4300,
            "tareWeight": 1700,
            "maxGrossWeight": 6000,
            "length": 4,
            "width": 4,
            "height": 2.8,

            "r002Compliance": true,
            "certificate": {
                "certificateNumber": 133609,
                "expiryDate": "2015-05-30T09:30:10Z"
            },
            "imoCertificate": {
                "certificateNumber": 133643,
                "expiryDate": "2002-05-30T09:30:10Z"
            },
            "link": {
                "href": "events.json",
                "method": "get",
                "rel": "Events",
                "type": "application/pdf"
            }
        },
        {
            "ccuId": 365891,
            "orgNo": 123456789,
            "gln": 1234567890123,
            "ccuClass": "Basket",
            "ccuSubClass": "Chemical Basket",
            "ccuOwnerId": 133428,
            "payload": 4300,
            "tareWeight": 1700,
            "maxGrossWeight": 6000,
            "length": 4,
            "width": 4,
            "height": 2.8,

            "r002Compliance": true,
            "certificate": {
                "certificateNumber": 133609,
                "expiryDate": "2015-02-03"
            },
            "imoCertificate": {
                "certificateNumber": 133643,
                "expiryDate": "2014-08-03"
            },
            "link": {
                "href": "events.json",
                "method": "get",
                "rel": "Events",
                "type": "application/pdf"
            }
        },
        {
            "ccuId": 763851,
            "orgNo": 123456789,
            "gln": 1234567890123,
            "ccuClass": "Container",
            "ccuSubClass": "Nuclear Container",
            "ccuOwnerId": 133428,
            "payload": 4300,
            "tareWeight": 1700,
            "maxGrossWeight": 6000,
            "length": 4,
            "width": 4,
            "height": 2.8,

            "r002Compliance": true,
            "certificate": {
                "certificateNumber": 133609,
                "expiryDate": "2015-02-03"
            },
            "imoCertificate": {
                "certificateNumber": 133643,
                "expiryDate": "2014-08-03"
            },
            "link": {
                "href": "events.json",
                "method": "get",
                "rel": "Events",
                "type":"application/pdf"
            }
        }
    ];

    angular.module('ELHApp').requires.push('ELHAppMockDev');

}(angular.module('ELHAppMockDev', ['ELHApp', 'ngMockE2E']), angular));

Generated by istanbul at Mon Jul 21 2014 16:07:23 GMT+0200 (W. Europe Daylight Time)


text:
namespace ClrPlus.Windows.PeBinary.Utility {
    using System.Xml.Linq;

    public class InvalidManifestElement : ManifestException {
        public XElement Element;

        public InvalidManifestElement(string message, XElement element) : base(message) {
            Element = element;
        }
    }
}


text:
<?php

namespace Brickoo\Tests\Component\Error\Messaging\Listener;

use Brickoo\Component\Error\Messaging\Messages;
use Brickoo\Component\Error\Messaging\Listener\ExceptionLogMessageListener;
use PHPUnit_Framework_TestCase;

/**
 * ExceptionLogMessageListenerTest
 *
 * Test suite for the ExceptionLogMessageListener class.
 * @see Brickoo\Component\Error\Messaging\Listener\ExceptionLogMessageListener
 * @author Celestino Diaz <celestino.diaz@gmx.de>
 */
class ExceptionLogMessageListenerTest extends PHPUnit_Framework_TestCase {

    /** @covers Brickoo\Component\Error\Messaging\Listener\ExceptionLogMessageListener::getMessageName */
    public function testGetMessageName() {
        $exceptionLogListener = new ExceptionLogMessageListener();
        $this->assertEquals(Messages::EXCEPTION, $exceptionLogListener->getMessageName());
    }

    /** @covers Brickoo\Component\Error\Messaging\Listener\ExceptionLogMessageListener::getPriority */
    public function testGetPriority() {
        $exceptionLogListener = new ExceptionLogMessageListener();
        $this->assertInternalType("integer", $exceptionLogListener->getPriority());
    }

    /**
     * @covers Brickoo\Component\Error\Messaging\Listener\ExceptionLogMessageListener::handleMessage
     * @covers Brickoo\Component\Error\Messaging\Listener\ExceptionLogMessageListener::getExceptionMessage
     * @covers Brickoo\Component\Error\Messaging\Listener\ExceptionLogMessageListener::generateLogMessage
     */
    public function testHandleMessageCallsMessageManager() {
        $previousException = new \Exception();
        $exception = new \Exception("Some exception message", 0, $previousException);

        $message = $this->getMockBuilder("\\Brickoo\\Component\\Error\\Messaging\\Message\\ExceptionMessage")
            ->disableOriginalConstructor()
            ->getMock();
        $message->expects($this->once())
              ->method("getException")
              ->will($this->returnValue($exception));

        $messageDispatcher = $this->getMessageDispatcherStub();
        $messageDispatcher->expects($this->once())
                     ->method("dispatch")
                     ->with($this->isInstanceOf("\\Brickoo\\Component\\Log\\Messaging\\Message\\LogMessage"))
                     ->will($this->returnValue($messageDispatcher));

        $exceptionLogListener = new ExceptionLogMessageListener();
        $this->assertNull($exceptionLogListener->handleMessage($message, $messageDispatcher));
    }

    /**
     * Returns an message dispatcher stub.
     * @return \Brickoo\Component\Messaging\MessageDispatcher
     */
    private function getMessageDispatcherStub() {
        return $this->getMockBuilder("\\Brickoo\\Component\\Messaging\\MessageDispatcher")
            ->disableOriginalConstructor()
            ->getMock();
    }

}


text:
package org.apache.cassandra.tools.nodetool;

import io.airlift.airline.Command;
import io.airlift.airline.Option;
import org.apache.cassandra.tools.NodeProbe;
import org.apache.cassandra.tools.NodeTool.NodeToolCmd;

@Command(name = "enablefullquerylog", description = "Enable full query logging, defaults for the options are configured in cassandra.yaml")
public class EnableFullQueryLog extends NodeToolCmd
{
    @Option(title = "roll_cycle", name = {"--roll-cycle"}, description = "How often to roll the log file (MINUTELY, HOURLY, DAILY).")
    private String rollCycle = null;

    @Option(title = "blocking", name = {"--blocking"}, description = "If the queue is full whether to block producers or drop samples [true|false].")
    private String blocking = null;

    @Option(title = "max_queue_weight", name = {"--max-queue-weight"}, description = "Maximum number of bytes of query data to queue to disk before blocking or dropping samples.")
    private int maxQueueWeight = Integer.MIN_VALUE;

    @Option(title = "max_log_size", name = {"--max-log-size"}, description = "How many bytes of log data to store before dropping segments. Might not be respected if a log file hasn't rolled so it can be deleted.")
    private long maxLogSize = Long.MIN_VALUE;

    @Option(title = "path", name = {"--path"}, description = "Path to store the full query log at. Will have it's contents recursively deleted.")
    private String path = null;

    @Option(title = "archive_command", name = {"--archive-command"}, description = "Command that will handle archiving rolled full query log files." +
                                                                                " Format is \"/path/to/script.sh %path\" where %path will be replaced with the file to archive")
    private String archiveCommand = null;

    @Option(title = "archive_retries", name = {"--max-archive-retries"}, description = "Max number of archive retries.")
    private int archiveRetries = Integer.MIN_VALUE;

    @Override
    public void execute(NodeProbe probe)
    {
        Boolean bblocking = null;
        if (blocking != null)
        {
            if (!blocking.equalsIgnoreCase("TRUE") && !blocking.equalsIgnoreCase("FALSE"))
                throw new IllegalArgumentException("Invalid [" + blocking + "]. Blocking only accepts 'true' or 'false'.");
            else
                bblocking = Boolean.parseBoolean(blocking);
        }
        probe.enableFullQueryLogger(path, rollCycle, bblocking, maxQueueWeight, maxLogSize, archiveCommand, archiveRetries);
    }
}


text:
namespace YAF.Dialogs;

using System.Text;

using YAF.Types.Models;

/// <summary>
/// The Admin Banned IP Add/Edit Dialog.
/// </summary>
public partial class BannedIpEdit : BaseUserControl
{
    /// <summary>
    /// Gets or sets the banned identifier.
    /// </summary>
    /// <value>
    /// The banned identifier.
    /// </value>
    public int? BannedId
    {
        get => this.ViewState["BannedId"].ToType<int?>();

        set => this.ViewState["BannedId"] = value;
    }

    /// <summary>
    /// Binds the data.
    /// </summary>
    /// <param name="bannedId">The banned identifier.</param>
    public void BindData(int? bannedId)
    {
        this.BannedId = bannedId;

        this.Title.LocalizedPage = "ADMIN_BANNEDIP_EDIT";
        this.Save.TextLocalizedPage = "ADMIN_BANNEDIP";

        if (this.BannedId.HasValue)
        {
            // Edit
            var banned = this.GetRepository<BannedIP>().GetById(this.BannedId.Value);

            if (banned != null)
            {
                this.mask.Text = banned.Mask;
                this.BanReason.Text = banned.Reason;
            }

            this.Title.LocalizedTag = "TITLE_EDIT";
            this.Save.TextLocalizedTag = "SAVE";
        }
        else
        {
            // Add
            this.mask.Text = string.Empty;
            this.BanReason.Text = string.Empty;

            this.Title.LocalizedTag = "TITLE";
            this.Save.TextLocalizedTag = "ADD_IP";
        }
    }

    /// <summary>
    /// The page_ load.
    /// </summary>
    /// <param name="sender">
    /// The sender.
    /// </param>
    /// <param name="e">
    /// The e.
    /// </param>
    protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
    {
        if (!this.IsPostBack)
        {
            return;
        }

        this.PageBoardContext.PageElements.RegisterJsBlockStartup(
            "loadValidatorFormJs",
            JavaScriptBlocks.FormValidatorJs(this.Save.ClientID));
    }

    /// <summary>
    /// Handles the Click event of the Add control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    protected void Save_OnClick([NotNull] object sender, [NotNull] EventArgs e)
    {
        if (!this.Page.IsValid)
        {
            return;
        }

        var ipParts = this.mask.Text.Trim().Split('.');

        // do some validation...
        var ipError = new StringBuilder();

        if (ipParts.Length != 4)
        {
            ipError.AppendLine(this.GetText("ADMIN_BANNEDIP_EDIT", "INVALID_ADRESS"));
        }

        foreach (var ip in ipParts)
        {
            // see if they are numbers...
            if (!ulong.TryParse(ip, out var number))
            {
                if (ip.Trim() == "*")
                {
                    continue;
                }

                if (ip.Trim().Length != 0)
                {
                    ipError.AppendFormat(this.GetText("ADMIN_BANNEDIP_EDIT", "INVALID_SECTION"), ip);
                }
                else
                {
                    ipError.AppendLine(this.GetText("ADMIN_BANNEDIP_EDIT", "INVALID_VALUE"));
                }

                break;
            }

            // try parse succeeded... verify number amount...
            if (number > 255)
            {
                ipError.AppendFormat(this.GetText("ADMIN_BANNEDIP_EDIT", "INVALID_LESS"), ip);
            }
        }

        // show error(s) if not valid...
        if (ipError.Length > 0)
        {
            this.PageBoardContext.Notify(ipError.ToString(), MessageTypes.warning);
            return;
        }

        if (!this.GetRepository<BannedIP>().Save(
                this.BannedId,
                this.mask.Text.Trim(),
                this.BanReason.Text.Trim(),
                this.PageBoardContext.PageUserID))
        {
            this.PageBoardContext.LoadMessage.AddSession(
                this.GetText("ADMIN_BANNEDIP", "MSG_EXIST"),
                MessageTypes.warning);
        }
        else
        {
            if (this.PageBoardContext.BoardSettings.LogBannedIP)
            {
                this.Logger.Log(
                    $"IP or mask {this.mask.Text.Trim()} was saved by {this.PageBoardContext.PageUser.DisplayOrUserName()}.",
                    EventLogTypes.IpBanSet);
            }
        }

        // go back to banned IPs administration page
        this.Get<LinkBuilder>().Redirect(ForumPages.Admin_BannedIps);
    }
}


text:
function [t, x] = rk4( FUNC, tspan, x0, N, varargin)

%RK4       approximate the solution of the initial value problem
%
%                       x'(t) = FUNC( t, x ),    x(t0) = x0
%
%          using the classical fourth-order Runge-Kutta method - this
%          routine will work for a system of first-order equations as
%          well as for a single equation
%
%     calling sequences:
%             [x, t] = rk4 ( RHS, t0, x0, tf, N )
%             rk4 ( RHS, t0, x0, tf, N )
%
%     inputs:
%             FUNC    string containing name of m-file defining the
%                     right-hand side of the differential equation;  the
%                     m-file must take two inputs - first, the value of
%                     the independent variable; second, the value of the
%                     dependent variable
%             tspan   [to tf] of indepent variable from which to integrate
%                     over
%             x0      initial value of the dependent variable(s)
%                     if solving a system of equations, this should be a
%                     row vector containing all initial values
%             N       number of uniformly sized time steps to be taken to
%                     advance the solution from t = t0 to t = tf
%
%     output:
%             wi      vector / matrix containing values of the approximate
%                     solution to the differential equation
%             ti      vector containing the values of the independent
%                     variable at which an approximate solution has been
%                     obtained
%

% Number of equations:
neqn = length ( x0 );

% Create indepenent variable vector:
t0 = tspan(1); tf = tspan(2);
t = linspace( t0, tf, N+1 )';

% Create dependent variable vector:
x = zeros( N+1, neqn );

% Set innitial value:
x( 1, 1:neqn) = x0';

% Define step size:
h = ( tf - t0 ) / N;

% Loop over all integration steps:
for i = 1:N
    % Solve for k-values:
    k1 = h * feval ( FUNC, t0, x0, varargin{:} );
	k2 = h * feval ( FUNC, t0 + h/2, x0 + k1/2, varargin{:} );
	k3 = h * feval ( FUNC, t0 + h/2, x0 + k2/2, varargin{:} );
	k4 = h * feval ( FUNC, t0 + h, x0 + k3, varargin{:} );

    % Solve for new state:
    x0 = x0 + ( k1 + 2*k2 + 2*k3 + k4 ) / 6;
	t0 = t0 + h;

    % Store new state:
    x( i+1, 1:neqn ) = x0';
end

end


text:
package com.klisly.bookbox.alarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.klisly.bookbox.BookBoxApplication;

public class MagzineAlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        String msg = intent.getStringExtra("msg");
        long intervalMillis = intent.getLongExtra("intervalMillis", 0);
        if (intervalMillis != 0) {
            AlarmManagerUtil.setAlarmTime(context, System.currentTimeMillis() + intervalMillis,
                    intent);
        }
        BookBoxApplication.getInstance().showMomentNotifi("朝花夕拾", msg);
    }

}


text:
<head>
  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>
    {% if page.title == "Home" %}
      {{ site.title }} · {{ site.tagline }}
    {% else %}
      {{ page.title }} · {{ site.title }}
    {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="{{ "/" | relative_url }}public/css/poole.css">
  <link rel="stylesheet" href="{{ "/" | relative_url }}public/css/syntax.css">
  <link rel="stylesheet" href="{{ "/" | relative_url }}public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ "/" | relative_url }}public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="{{ "/" | relative_url }}public/favicon.ico">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

</head>


text:
<title>
Watching over Harlem
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

VIEWS AND VOICES

Police tower moves in along with the gentrifiers

Watching over Harlem

December 15, 2006 | Page 12

A SKY Watch surveillance tower has been placed at the intersection of 129th Street and Malcolm X Boulevard in Harlem by the New York Police Department (NYPD).

This mobile surveillance unit, which gives a cop a line of sight from 20 feet up, is equipped with four cameras, a high-powered spotlight and various sensors. The digital cameras continue recording when the booth is unstaffed and save the video to a computer hard drive. The tower resembles those used as guard watchtowers in prisons.

Sky Watch towers cost from $40,000 to $100,000 apiece. The NYPD is currently leasing one or two--one was erected at the intersection of Carroll Street and Troy Avenue in the Crown Heights section of Brooklyn. The NYPD hopes to eventually have five of the towers in place around the city.

Sky Watch is a product of New Heights Manufacturing in Ellaville, Ga. It is currently being used by the U.S. military in Iraq and the U.S. Border Patrol. In a 2004 article in Quickstart (the newsletter of the Georgia Department of Technical and Adult Education), Sky Watch was said to be a powerful crime deterrent, due to its bulletproof windows, infrared cameras, high-powered spotlights and M-16 ready gun ports.

The prototype for Sky Watch was called "Huntmaster" and was developed as a hunting blind. The manufacturer soon realized that developing this technology for the security industry would propel them into the world market. They began selling the product to the U.S. government in 1998.

The article in Quickstart ends by praising New Heights Manufacturing for "developing additional security and surveillance devices that serve as 'force multipliers,' tools that allow a small number of personnel to pack a bigger punch, defending America on the front lines of the war against terror."

It is interesting to think that such a device would be necessary in Harlem, when all statistics say that the crime rate in the area and the city as a whole has gone down 25 percent in the last five years. The NYPD says the tower was placed in Harlem to combat a surge in murders. It was difficult to find any documentation of a rise in murder rates in Harlem to correspond with the police department's justification for placing Sky Watch in the neighborhood.

The only stories I could find about crime rates in Harlem were about how they have fallen, making it a "hot" new time to invest in real estate development.

The Sky Watch tower was installed on the same intersection as two new luxury condo complexes, the Lenox and the Lenox Grand. Many Harlem residents feel that this is the real reason for the use of the Sky Watch tower. Lloyd Estridge an electrician who worked on the Lenox told the New York Post, "They wait until multimillion-dollar apartments go up, and then they want to watch over Harlem."

I went to 129 Street and Lenox Avenue to check out the tower for myself, but it was no longer there. I decided to go into a local copy center and ask if anyone had noticed the tower and if anyone knew where the Sky Watch tower had been relocated. A couple of residents responded immediately, "I saw that thing, I don't know why they put it in this area."

One man said that the police had been moving it all over the neighborhood. He asked police officers why they would place the tower in his neighborhood, but the officers refused to give him a reason. He said, "I take issue with that thing showing up on my block."

Dawning Greenstreet, New York City

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
/*
 * Live view for the KXPA100 amplifier as standalone instrument
 *
 * Our model is the settings object.
 *
 * @author Edouard Lafargue, ed@lafargue.name
 */

define(function (require) {
    "use strict";

    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        utils = require('app/utils'),
        template = require('js/tpl/instruments/elecraft/KXPA100-standalone.js');

    return Backbone.View.extend({

        initialize: function (options) {
            this.deviceinitdone = false;
            linkManager.on('status', this.updateStatus, this);
        },

        render: function () {
            var self = this;
            console.log('Main render of KXPA100 Standalone main view');
            this.$el.html(template());

            require(['app/instruments/elecraft/display_kxpa100'], function(view) {
               self.KXPA100 = new view();
               $('#kxpa100', self.el).append(self.KXPA100.el);
               self.KXPA100.render();
            });

            return this;
        },

        onClose: function () {
            this.KXPA100.onClose();
            linkManager.off('status', this.updatestatus, this);
        },

        updateStatus: function (data) {
            if (data.portopen && !this.deviceinitdone) {
                this.KXPA100.shown(true);
                this.deviceinitdone = true;

                linkManager.driver.getRequestedPower();
            } else if (!data.portopen) {
                this.deviceinitdone = false;
                this.KXPA100.shown(false);
            }
        },

    });
});


text:
package com.pratamawijaya.retrofit20.model;

/**
 * Created by : pratama - set.mnemonix@gmail.com
 * Date : 9/11/15
 * Project : Retrofit20
 */
public class Contributor {
  private String login;
  private int contributions;

  public String getLogin() {
    return login;
  }

  public void setLogin(String login) {
    this.login = login;
  }

  public int getContributions() {
    return contributions;
  }

  public void setContributions(int contributions) {
    this.contributions = contributions;
  }
}


text:
var fs = Npm.require('fs');
var path = Npm.require('path');

Package.describe({
  "summary": "a way to render the initial page super fast!"
});

Npm.depends({
  "connect": "2.13.0"
});

Package.on_use(function(api) {
  api.use(['minimongo', 'livedata', 'mongo-livedata', 'ejson', 'underscore', 'webapp', 'routepolicy', 'accounts-base'], ['server']);
  api.use(['underscore', 'deps', 'ejson'], ['client']);

  // This is needed due to Meteor Issue #1358
  //   https://github.com/meteor/meteor/issues/1358
  // The 'weak' flag doesn't support non-core (ie. atmosphere) packages yet.
  if(isIronRouterExists()) {
    api.use(['iron-router'], ['client', 'server'], {weak: true});
  }

  //a hack to detect if IR has been added or removed from the app
  //  if IR was not there on the app and added later, FR cannot detect it,
  //  since Meteor caches packages. this is how we force FR to invalidate the cache.
  api.add_files('../../.meteor/packages', ['client', 'server']);

  api.add_files([
    'lib/server/inject_data.html',
    'lib/server/inject_config.html',
  ], 'server', {isAsset: true});

  api.add_files([
    'lib/utils.js'
  ], ['client', 'server']);

  api.add_files([
    'lib/server/utils.js',
    'lib/server/fast_render.js',
    'lib/server/publish_context.js',
    'lib/server/context.js',
    'lib/server/inject.js',
    'lib/server/iron_router_support.js',
  ], 'server');

  api.add_files([
    'lib/vendor/cookies.js',
    'lib/vendor/deepExtend.js',
    'lib/client/log.js',
    'lib/client/fast_render.js',
    'lib/client/ddp_update.js',
    'lib/client/data_handler.js',
    'lib/client/iron_router_support.js',
    'lib/client/auth.js'
  ], 'client');

  api.export('FastRender', ['client', 'server']);
  api.export('__init_fast_render', ['client']);
});

function isAppDir(filepath) {
  try {
    return fs.statSync(path.join(filepath, '.meteor', 'packages')).isFile();
  } catch (e) {
    return false;
  }
}

function meteorRoot() {
  var currentDir = process.cwd();
  while (currentDir) {
    var newDir = path.dirname(currentDir);

    if (isAppDir(currentDir)) {
      break;
    } else if (newDir === currentDir) {
      return null;
    } else {
      currentDir = newDir;
    }
  }

  return currentDir;
}

function isIronRouterExists() {
  var meteorPackages = fs.readFileSync(path.join(meteorRoot(), '.meteor', 'packages'), 'utf8');
  return !!meteorPackages.match(/iron-router/);
}


text:
<?php

namespace Sydes;

class Cache
{

    /**
     * The file cache directory.
     *
     * @var string
     */
    protected $directory;

    /**
     * Create a new file cache instance.
     *
     * @param string $directory
     */
    public function __construct($directory)
    {
        $this->directory = $directory;
    }

    /**
     * Store an item in the cache indefinitely.
     *
     * @param string $key
     * @param mixed  $value
     */
    public function forever($key, $value)
    {
        $this->put($key, $value, 0);
    }

    /**
     * Store an item in the cache for a given number of seconds.
     *
     * @param string $key
     * @param mixed  $value
     * @param int    $seconds
     */
    public function put($key, $value, $seconds = 2678400)
    {
        $value = $this->expiration($seconds).serialize($value);

        $path = $this->path($key);

        file_put_contents($path, $value, LOCK_EX);
    }

    /**
     * Get the expiration time based on the given seconds.
     *
     * @param int $seconds
     * @return int
     */
    protected function expiration($seconds)
    {
        if ($seconds === 0) {
            return 9999999999;
        }
        return time() + $seconds;
    }

    /**
     * Get the full path for the given cache key.
     *
     * @param string $key
     * @return string
     */
    protected function path($key)
    {
        return $this->directory.'/'.md5($key).'.cache';
    }

    /**
     * Remove all items from the cache.
     */
    public function flush()
    {
        if (file_exists($this->directory)) {
            foreach (glob($this->directory.'/*') as $file) {
                unlink($file);
            }
        }
    }

    /**
     * Get an item from the cache, or store the default value.
     *
     * @param string   $key
     * @param int      $seconds
     * @param \Closure $callback
     * @return mixed
     */
    public function remember($key, \Closure $callback, $seconds = 2678400)
    {
        if (!is_null($value = $this->get($key))) {
            return $value;
        }

        $this->put($key, $value = $callback(), $seconds);

        return $value;
    }

    /**
     * Retrieve an item from the cache by key.
     *
     * @param string $key
     * @param mixed  $default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        $path = $this->path($key);

        if (!file_exists($path)) {
            return $default;
        }

        $contents = file_get_contents($path);
        $expire = substr($contents, 0, 10);

        if ($expire < time()) {
            $this->forget($key);
            return $default;
        }

        return unserialize(substr($contents, 10));
    }

    /**
     * Remove an item from the cache.
     *
     * @param string $key
     * @return bool
     */
    public function forget($key)
    {
        $file = $this->path($key);
        if (file_exists($file)) {
            return unlink($file);
        }
        return false;
    }

}


text:
"use strict"

var supervision_strategy = require("../utilities/supervision/supervision-strategy.js");
var faultInfo = require("../utilities/fault-line.js");
var services = require("../db/services.js");
var receiver = require("./receiver.js");
var system_message_handler = require("./system-message-handler.js");
var forward_message_handler = require("./forward-message-handler.js");
var logger = require('../utilities/logger.js').systemLogger;
var Context = require('../utilities/context.js');

class Actor {
	/**
	 * [takes a generator and returns an actor instance]
	 * @param  {Generator} fn      	[generator]
	 * @param  {[object]}  context  [description]
	 * @param  {[object]}  strategy [optional - strategy object]
	 * @return {[Actor]}            [Actor instance]
	 */
	constructor(fn, context, strategy) {
		//the context object stores all the metadata of the actor
		this.context = context;

		//startegy object maintains the failure recovery guidelines
		//that parent actor can send to the children
		//in case children complain "something has gone wrong!!!"
		this.strategy = strategy;

		this.generator = fn;

		//if strategy is not applied then the actor deafults to AllForOneStrategy
		//as if one/more children fail we revert all the children
		if (!this.strategy) {
			let maxRetries = 3;
			let duration = 500;
			this.strategy = new supervision_strategy.OneForOneStrategy(maxRetries, duration);
		}

		//collection of incoming mails to handle backpressure
		//queue-like implementation
		//except the case of system messages
		//system messages are shoved into the front of the collection rather than the back
		this._mailbox = [];

		//rougue messages - its trouble
		//<rogueMailId> : <mail>
		this.rogueMessages = {};

		//prep the actor to receive incoming messages
		this._preStart();
	}

	//preparing the mailbox after initailizing the statestore and the receiver.
	//To get value into a generator for processing we need it in suspended state

	//pre start takes care of creating the statestore
	//initiating the receiver
	_preStart() {

		//flag to indicate if actor is currently processing any message
		this._actor_running = false;

		//processes any message sent to it
		//and maintains the state of the actor
		this._stateStore = this.generator.call(this, this._peek.bind(this));

		//receives messages
		this._receiver = receiver.call(this);

		//initializes the actor to recieve messages
		//_stateStore is an instance of the generator

		//initializing _stateStore - sending empty message
		this._stateStore.next();

		//initializing _receiver - sending empty message
		this._receiver.next();

		//subscribe to the cluster event for reacting to any node failure if any child exists on that node
		//if node fails then the actor consults the actor map in the db to restart all the dead children
		//with the same id so that the children can be restored to the previous state and resume
		faultInfo.subscribe(function (data) {
			// var ip = machine.node;
			// var port = machine.port;

			debugger;

			var self = this;
			var machine = {
				'node': data.node,
				'port': data.port
			};

			services.retrieveActorMap(self.context.id, machine).then(function (childCollection) {
				childCollection.map(function (actorMap) {
					return actorMap.id;
				}).forEach(function (childId) {
					if (self.context.ifExists(childId)) {
						var msg = {
							action: "system",
							subaction: "recover",
							failedNode: machine,
							failureTime: data.failureTime
						};
						console.log('recovery of ~ ', childId);
						var child_context = new Context(childId, self._child_type, self.context.id);
						self.context.send(childId, msg, child_context);
					}
				});
			}, function (err) {
				//log error
			})
		}.bind(this));
	}

	//recover the actor if the actor has crashed
	//will restore the actor to the previously held state at the time of failure
	recover(startTime, node) {
		//call preRestart
		var endTime = this._preRecover();
		var childToRecover = [];
		var self = this;

		services.retrieveChildActorMap(self.context.id).then(function (children) {
				var childrenIds = children.map(function (child) {
					if (child.node.node == node.node && child.node.port == node.port) {
						childToRecover.push(child.id);
					}
					return child.id;
				});
				self.supervisedChildren = new Set(childrenIds);

				var msg = {
					action: "system",
					subaction: "recover",
					failedNode: node,
					failureTime: startTime
				};

				childToRecover.forEach(function (childId) {
					var child_context = new Context(childId, self._child_type, self.context.id);
					self.context.send(childId, msg, child_context);
				});

				return services.retrieveJournal(startTime, endTime, self.context.id)
			})
			//get all the messages from the journal between the startTime and endTime
			//add it to the primary mailbox

		.then(function (journal_msgs) {
				self._mailbox = journal_msgs;
				//retrive all the rogue messages from the rogue store using the actor id
				return services.retrieveRogueMessages(self.context.id)
			})
			.then(function (rogue_messages) {
				self.rogueMessages = rogue_messages;
				self._postRecover();
			})
			.catch(function (err) {
				logger.log('Recover error ' + err);
			});
	}

	//create auxiliary storage
	//refresh the mail
	//route all the mails to an auxiliary mailbox - _mailbox=aux_mailbox
	_preRecover() {
		this._aux_mailbox = [];
		this._switch_to_auxiliary_mailbox = true;
		return Date.now();
	}

	//add auxiliary message box to the to the end of primary mailbox
	//switch primary mailbox to recieve mails
	_postRecover() {
		this._mailbox = this._mailbox.concat(this._aux_mailbox);
		this._aux_mailbox = [];
		this._switch_to_auxiliary_mailbox = false;
		console.log(this.context.id + " mails after recovery ~ " + this._mailbox);
		//peek into the mailbox after it has been restored
		this._peek();
	}

	//restart the actor
	restart() {
		this._preRestart(function () {
			var restart_msg = {
				action: "system",
				subaction: "restart"
			}

			//send restart message to each children
			for (let child of this.context.supervisedChildren) {
				this.context.send(child, restart_msg);
			}

			this._postRestart();

		}.bind(this));
	}

	_preRestart(cb) {
		this._suspend_mailbox = true;
	}

	_postRestart() {
		this._preStart();
		this._peek();
	}

	stop() {
		//suspend the mailbox
		this._suspend_mailbox = true;

		//check if supervisedChildren set it empty then directly call _postStop
		//as actor doesn't need the children to successfully shutdown
		if (!this.context.supervisedChildren.size) {
			//call _postStop
			this._postStop();
		} else {
			this._watch_children_callback = function () {
				this._postStop();

				//dump mailbox into system deadletters

				//clear up any other resources if necessary

				//remove actor from current node's actorMap

			}.bind(this);
		}

		//create terminate message
		var terminate_msg = {
			action: "system",
			subaction: "terminate"
		};

		//send termination message to each children
		for (let child of this.context.supervisedChildren) {
			this.context.send(child, terminate_msg);
		}

	}

	registerChildTermination(childId) {
		if (this._watch_children_callback) {
			if (!this.terminated_set) {
				this.terminated_set = new Set();
			}

			this.terminated_set.add(childId);

			if (eqSet(this.terminated_set, this.context.supervisedChildren)) {
				this._watch_children_callback();
			}
		}

		function eqSet(as, bs) {
			if (as.size !== bs.size) return false;
			for (var a of as)
				if (!bs.has(a)) return false;
			return true;
		}
	}

	//send terminated message to parent
	_postStop() {

		//send "terminated" message to the parent
		var msg = {
			action: "system",
			subaction: "terminated"
		};
		this.context.send(this.context.parentSupervisorId, msg);
	}

	//peek into the mailbox to look for messages
	//take one mail at a time to process it
	_peek() {
		if (!this._suspend_mailbox) {
			let msg = this._mailbox.shift();

			//if we get no message from the mailbox we mark the actor as not running
			//i.e. the actor is not processing any messages so that when it recives any new message
			//it can restart processing the message by again calling peek
			if (msg) {
				this._actor_running = true;
				setImmediate(function () {
					this._stateStore.next(msg);
				}.bind(this));
			} else {
				this._actor_running = false;
			}
		}
	}

	//takes message and sends it to the receiver
	//if auxiliary mailbox is activated
	//then store all the incoming messages in the auxiliary mailbox
	receive(msg) {
		if (this._switch_to_auxiliary_mailbox) {
			this._aux_mailbox.push(msg);
		} else {
			this._receiver.next(msg);
		}
	}

	//add a message to the rogueMessages object
	markRogue(msg) {
		this.rogueMessages[msg.msgId] = msg;
	}

	//remove message from the rogueMessages list
	//it removes and returns the message stored in the object
	unmarkRogue(msgId) {
		var msg = this.rogueMessages[msgId];
		delete this.rogueMessages[msgId];
		return msg;
	}

	//retry the message from the rogue messages list
	retry(msgId) {
		//get rogue message from the rogue list of messages
		var msg = this.unmarkRogue(msgId);

		//push the message into the mailbox - to be retrired
		this.receive(msg);
	}

	//apply parent provided directive to handle a particular exception
	applyDirective(directive, msgId) {
		//unmark message from the rogue list
		var msg = this.unmarkRogue(msgId);

		//apply directive
	}

	//handle forwarded messages
	/*	forwarded messages are the one which are not processed by the actor
		rather forwarded to a particular child in its hierarchy*/
	handleForwardedMessages(mail) {
		forward_message_handler.call(this, mail);
	}

	//handle system messages
	//perform actions based on the subactions specified in the  messages
	handleSystemMessages(mail) {
		system_message_handler.call(this, mail);

	}

	/**
 	[handleException wrap the exception into a system message
	and send it to the parent for processing]
	 * @param  {[object]} exp  [exception]
	 * @param  {[object]} mail [mail which caused the exception]
	 */
	handleException(exp, mail) {
		//mark the mail as rogue
		this.markRogue(mail);

		//write the rogue message collection to the database
		//if the collection doesn't exist for the actor then create
		//or replace the existing collection to keep the rougue message collection fresh
		//to help in recovery of the actor during failures or enforced restarts
		services.saveRogueMessages(this.context.id, this.rogueMessages).then(function (d) {
			//log
			//logger.log("Rogue messages saved for actor", this.context.id, "successfully");
		}, function (err) {
			//log
			//logger.log("Cannot save rogue messages for actor", this.context.id);
		});

		//wrap the exception in a system message
		var msg = {
			action: "system",
			subaction: "exception",
			payload: exp,
			rogueMailId: mail.msgId
		};

		//send it to the parent for processing
		this.context.send(this.context.parentSupervisorId, msg);
	}
}

module.exports = Actor;


text:
require 'progressbar'

class EijiroDictionary
  class SqlProcessor
    COMMON_TOKENS = %w(i ll  mr ok a about after all also an and any are as at back be because been before but by can can t come could day did didn do don down even first for from get give go going good got great had has have he he her here hey him his how if in into is it its just know like little look made make man may me mean men more most much must my new no not now of oh okay on one only or other our out over person really right said say see she should so some something such take tell than that that the their them then there these they think this time to two up upon us use very want was way we well were what when which who why will with work would yeah year yes you you re your)

    class SqlFile
      def initialize
        @num = "001"
        @path = File.join(Rails.root, "db")
      end

      def current_file
        File.join(@path, "eijiro#{@num}.sql")
      end

      def open
        File.open(current_file, "w") do |f|
          f.write "BEGIN TRANSACTION;\n"
        end
      end

      def close
        File.open(current_file, "a") do |f|
          f.write "\nEND TRANSACTION;\n"
        end
        @num = @num.succ
      end
    end

    def initialize
      @flush_limit = 10_0000
      @sqlfile = SqlFile.new
      @sqlfile.open
      @sql = []
    end

    def generate(id, entry, body)
      @sql << "INSERT INTO items (entry, body) VALUES (#{sqlstr(entry)}, #{sqlstr(body)});"
      tokenize(entry).each do |token|
        @sql << "INSERT INTO inverts (token, item_id) VALUES (#{sqlstr(token)}, #{id});"
      end
      if id % @flush_limit == 0
        flush
        @sqlfile.open
      end
    end

    def flush
      File.open(@sqlfile.current_file, "a") do |f|
        f.write @sql.join("\n")
      end
      @sql = []
      @sqlfile.close
    end

    def finish
      flush
      # execute the generated sqls
      database = File.join(Rails.root, %w(db development.sqlite3))
      n = %x{ ls -1 #{File.join(Rails.root, "db", "eijiro*")} |wc -l }.chomp.strip.to_i
      pbar = ProgressBar.new("Executing SQL commands...", n)
      Dir.foreach(File.join(Rails.root, "db")) do |file|
        if file =~ /eijiro.+\.sql/
          pbar.inc
          file = File.join(Rails.root, "db", file)
          system("sqlite3 #{database} \".read #{file}\"")
          system("rm #{file}")
        end
      end
      pbar.finish
    end

    def tokenize(str)
      str.split(/[ \-\.\'\%\"\/\,]/)
        .map(&:downcase)
        .reject {|s| s.size <= 1 || COMMON_TOKENS.include?(s)}
    end

    def sqlstr(str)
      "'#{str.gsub(/'/,"''")}'"
    end
  end
end


text:
@interface ZFAuthenticateVisitorHttpGetIn : FLModelObject {
@private
    NSString* _visitorKey;
}

@property (readwrite, strong, nonatomic) NSString* visitorKey;

+ (ZFAuthenticateVisitorHttpGetIn*) authenticateVisitorHttpGetIn;

@end


text:
/*
 Memory mapping with a red black tree
*/

#ifndef __LIBLOGDB_RBTREE_H__
#define __LIBLOGDB_RBTREE_H__

#include <btc/buffer.h>
#include <btc/cstr.h>

#include <logdb/logdb_base.h>
#include <logdb/logdb_rec.h>
#include <logdb/logdb_core.h>
#include <logdb/red_black_tree.h>

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>
#include <stddef.h>

typedef struct logdb_rbtree_db_ {
    struct rb_red_blk_tree *tree;
} logdb_rbtree_db;

logdb_rbtree_db* logdb_rbtree_db_new();
void logdb_rbtree_free(void *ctx);

/** appends record to the rbtree */
LIBLOGDB_API void logdb_rbtree_init(logdb_log_db* db);

/** appends record to the rbtree */
LIBLOGDB_API void logdb_rbtree_append(void* ctx, logdb_bool load_phase, logdb_record *rec);

/** find a record by key */
LIBLOGDB_API cstring * logdb_rbtree_find(logdb_log_db* db, struct buffer *key);

/** count all red black tree nodes */
LIBLOGDB_API size_t logdb_rbtree_size(logdb_log_db* db);

/* static interface */
static logdb_memmapper logdb_rbtree_mapper = {
    logdb_rbtree_append,
    logdb_rbtree_init,
    logdb_rbtree_free,
    logdb_rbtree_find,
    logdb_rbtree_size
};

#ifdef __cplusplus
}
#endif

#endif /* __LIBLOGDB_RBTREE_H__ */


text:
<?php

namespace MD2\Front\TaskBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\ManyToMany;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping\OneToMany;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity
 */
class User implements UserInterface {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=80, nullable=false)
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=40, nullable=false)
     */
    private $password;

    /**
     *
     * @var array
     *
     * @ORM\Column(name="roles", type="array", nullable=true)
     */
    private $roles;

    private $tasks = null;

    /**
     * @OneToMany(targetEntity="UserTask", mappedBy="user")
     */
    private $userTasks;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return User
     */
    public function setUsername($username) {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername() {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password) {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword() {
        return $this->password;
    }

    public function eraseCredentials() {
        $this->roles = array();
        return $this;
    }

    public function getRoles() {
        return $this->roles;
    }

    public function getSalt() {
        return null;
    }

    public function addUserTask(UserTask $userTask){
        $this->userTasks[] = $userTask;
    }

    public function addTask(Task $task) {
        $userTask = new UserTask();
        $userTask->setTask($task);
        $userTask->setUser($this);
        $this->addUserTask($userTask);
    }

    public function getTasks() {
        if(is_null($this->tasks))
        {
            $this->tasks = array();
            foreach($this->getUserTasks() as $userTask)
            {
                $this->tasks[] = $userTask->getTask();
            }
        }
        return $this->tasks;
    }

    public function getUserTasks() {
        return $this->userTasks;
    }

}


text:
# This is used to create the _rtmixer extension module (see setup.py).

from cffi import FFI
import pa_ringbuffer

RINGBUFFER_CDEF = pa_ringbuffer.cdef()

ffibuilder = FFI()
ffibuilder.cdef(RINGBUFFER_CDEF)
ffibuilder.cdef("""

/* From limits.h: */

#define ULONG_MAX ...

""")
ffibuilder.cdef(open('src/rtmixer.h').read())
ffibuilder.set_source(
    '_rtmixer',
    RINGBUFFER_CDEF + open('src/rtmixer.c').read(),
    include_dirs=['src', 'portaudio/include'],
    sources=['portaudio/src/common/pa_ringbuffer.c'],
    extra_compile_args=[
        '--std=c99',
        # '-Wconversion',
    ],
    # TODO: release mode by default, option for using debug mode
    undef_macros=[
        # 'NDEBUG'
    ],
)

if __name__ == '__main__':
    ffibuilder.compile(verbose=True)


text:
<?php
    /*
    function removeWhitespace($buffer)
    {
        return preg_replace('/\s+/', ' ', $buffer);
    }
    ob_start('removeWhitespace');
    */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link rel="icon" href="<?php echo base_url('public/images/it_spkt.png') ?>" type="image/x-icon" />
  <link rel="shortcut icon" href="<?php echo base_url('public/images/it_spkt.png') ?>"/>
  <title>::. <?php echo $heading ?> .::</title>
  <link rel="stylesheet" media="all" type="text/css" href="<?php echo base_url('public/bootstrap/css/bootstrap.min.css') ?>" />
  <link rel="stylesheet" media="all" type="text/css" href="<?php echo base_url('public/css/style.css') ?>" />
  <link rel="stylesheet" media="all" type="text/css" href="<?php echo base_url('public/css/footable.core.css') ?>" />
  <link rel="stylesheet" media="all" type="text/css" href="<?php echo base_url('public/css/footable.standalone.css') ?>" />
  <link rel="stylesheet" media="all" type="text/css" href="<?php echo base_url('public/font-awesome/css/font-awesome.min.css') ?>"/>

    <?php $this->load->view('includes/left-sidebar-mobile') ?>

        <?php $this->load->view('includes/mobile-bar') ?>

        <?php $this->load->view('includes/main_nav') ?>

                        <?php $this->load->view('includes/left-sidebar') ?>

                    <?php
                        $this->load->view('includes/breadcrum');
                        $this->load->view('includes/time_bar')
                    ?>

<?php echo @$heading ?>

                            <?php
                                foreach ($path as $view)
                                {
                                    $this->load->view($view);
                                }
                            ?>

                    <?php
                        $this->load->view('includes/breadcrum')
                    ?>
                    <?php $this->load->view('includes/right_thongke') ?>

Khoa Công nghệ Thông tin - Đại học Sư phạm Kỹ thuật TP. Hồ Chí Minh

Số 1, Võ Văn Ngân, Thủ Đức, TP. Hồ Chí Minh

    Đang tải ...

<?php //$output = ob_get_flush();?>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Asciidoctor in JavaScript powered by Opal</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
    <link rel="stylesheet" href="../asciidoctor.css">


text:
var Joi = require('joi');
var ObjectAssign = require('object-assign');
var BaseModel = require('hapi-mongo-models').BaseModel;

var NoteEntry = BaseModel.extend({
  constructor: function (attrs) {

    ObjectAssign(this, attrs);
  }
});

NoteEntry.schema = Joi.object().keys({
  data: Joi.string().required(),
  timeCreated: Joi.date().required(),
  userCreated: Joi.object().keys({
    id: Joi.string().required(),
    name: Joi.string().lowercase().required()
  }).required()
});

module.exports = NoteEntry;


text:
from django.conf.urls import url
from kvtags import views

urlpatterns = [
    url(r'^import-tags/$', views.import_tags, name='kvtags_import_tags'),
]


text:
using System;
using System.Diagnostics;
using System.IO;

namespace Nerdle.Ensure
{
    [DebuggerStepThrough]
    public static class DirectoryExistsExtensions
    {
        public static Ensurable<string> DirectoryExists(this Ensurable<string> ensurable, string exceptionMessage = null)
        {
            return ensurable.Satisfies(Directory.Exists, exceptionMessage ?? string.Format("Directory '{0}' does not exist.", ensurable));
        }

        public static Ensurable<string> DirectoryExists(this Ensurable<string> ensurable, Func<Ensurable<string>, Exception> exceptionFactory)
        {
            return ensurable.Satisfies(Directory.Exists, exceptionFactory);
        }
    }
}


text:
from robot.errors import (ExecutionFailed, ReturnFromKeyword, ExecutionPassed,
                          UserKeywordExecutionFailed, DataError, VariableError,
                          ExecutionSkipped,SkipExecution,PassExecution)
from robot.result import Keyword as KeywordResult
from robot.utils import DotDict, prepr, split_tags_from_doc
from robot.variables import is_list_var, VariableAssignment

from .arguments import DefaultValue
from .statusreporter import StatusReporter
from .steprunner import StepRunner
from .timeouts import KeywordTimeout

class UserKeywordRunner(object):

    def __init__(self, handler, name=None):
        self._handler = handler
        self.name = name or handler.name

    @property
    def longname(self):
        libname = self._handler.libname
        return '%s.%s' % (libname, self.name) if libname else self.name

    @property
    def libname(self):
        return self._handler.libname

    @property
    def arguments(self):
        return self._handler.arguments

    def run(self, kw, context):
        assignment = VariableAssignment(kw.assign)
        result = self._get_result(kw, assignment, context.variables)
        with StatusReporter(context, result):
            with assignment.assigner(context) as assigner:
                return_value = self._run(context, kw.args, result)
                assigner.assign(return_value)
                return return_value

    def _get_result(self, kw, assignment, variables):
        handler = self._handler
        doc = variables.replace_string(handler.doc, ignore_errors=True)
        doc, tags = split_tags_from_doc(doc)
        tags = variables.replace_list(handler.tags, ignore_errors=True) + tags
        return KeywordResult(kwname=self.name,
                             libname=handler.libname,
                             doc=doc.splitlines()[0] if doc else '',
                             args=kw.args,
                             assign=tuple(assignment),
                             tags=tags,
                             type=kw.type)

    def _run(self, context, args, result):
        variables = context.variables
        args = self._resolve_arguments(args, variables)
        with context.user_keyword:
            self._set_arguments(args, context)
            timeout = self._get_timeout(variables)
            if timeout is not None:
                result.timeout = str(timeout)
            with context.timeout(timeout):
                error, return_ = self._execute(context)
                if error and not error.can_continue(context.in_teardown):
                    raise error
                return_value = self._get_return_value(variables, return_)
                if error:
                    error.return_value = return_value
                    raise error
                return return_value

    def _get_timeout(self, variables=None):
        timeout = self._handler.timeout
        if not timeout:
            return None
        timeout = KeywordTimeout(timeout.value, timeout.message, variables)
        return timeout

    def _resolve_arguments(self, arguments, variables=None):
        return self.arguments.resolve(arguments, variables)

    def _set_arguments(self, arguments, context):
        positional, named = arguments
        variables = context.variables
        args, kwargs = self.arguments.map(positional, named,
                                          replace_defaults=False)
        self._set_variables(args, kwargs, variables)
        context.output.trace(lambda: self._trace_log_args_message(variables))

    def _set_variables(self, positional, kwargs, variables):
        before_varargs, varargs = self._split_args_and_varargs(positional)
        for name, value in zip(self.arguments.positional, before_varargs):
            if isinstance(value, DefaultValue):
                value = value.resolve(variables)
            variables['${%s}' % name] = value
        if self.arguments.varargs:
            variables['@{%s}' % self.arguments.varargs] = varargs
        if self.arguments.kwargs:
            variables['&{%s}' % self.arguments.kwargs] = DotDict(kwargs)

    def _split_args_and_varargs(self, args):
        if not self.arguments.varargs:
            return args, []
        positional = len(self.arguments.positional)
        return args[:positional], args[positional:]

    def _trace_log_args_message(self, variables):
        args = ['${%s}' % arg for arg in self.arguments.positional]
        if self.arguments.varargs:
            args.append('@{%s}' % self.arguments.varargs)
        if self.arguments.kwargs:
            args.append('&{%s}' % self.arguments.kwargs)
        return self._format_trace_log_args_message(args, variables)

    def _format_trace_log_args_message(self, args, variables):
        args = ['%s=%s' % (name, prepr(variables[name])) for name in args]
        return 'Arguments: [ %s ]' % ' | '.join(args)

    def _execute(self, context):
        if not (self._handler.keywords or self._handler.return_value):
            raise DataError("User keyword '%s' contains no keywords." % self.name)
        error = return_ = pass_ = None
        try:
            StepRunner(context).run_steps(self._handler.keywords)
        except ReturnFromKeyword as exception:
            return_ = exception
            error = exception.earlier_failures
        except ExecutionPassed as exception:
            pass_ = exception
            error = exception.earlier_failures
        except ExecutionSkipped as exception:
            pass_ = exception
            error = exception.earlier_failures
        except ExecutionFailed as exception:
            error = exception
        with context.keyword_teardown(error):
            td_error = self._run_teardown(context)
        if error or td_error:
            error = UserKeywordExecutionFailed(error, td_error)
        return error or pass_, return_

    def _get_return_value(self, variables, return_):
        ret = self._handler.return_value if not return_ else return_.return_value
        if not ret:
            return None
        contains_list_var = any(is_list_var(item) for item in ret)
        try:
            ret = variables.replace_list(ret)
        except DataError as err:
            raise VariableError('Replacing variables from keyword return value '
                                'failed: %s' % err.message)
        if len(ret) != 1 or contains_list_var:
            return ret
        return ret[0]

    def _run_teardown(self, context):
        if not self._handler.teardown:
            return None
        try:
            name = context.variables.replace_string(self._handler.teardown.name)
        except DataError as err:
            return ExecutionFailed(err.message, syntax=True)
        if name.upper() in ('', 'NONE'):
            return None
        try:
            StepRunner(context).run_step(self._handler.teardown, name)
        except PassExecution:
            return None
        except ExecutionFailed as err:
            return err
        return None

    def dry_run(self, kw, context):
        assignment = VariableAssignment(kw.assign)
        result = self._get_result(kw, assignment, context.variables)
        with StatusReporter(context, result):
            assignment.validate_assignment()
            self._dry_run(context, kw.args, result)

    def _dry_run(self, context, args, result):
        self._resolve_arguments(args)
        with context.user_keyword:
            timeout = self._get_timeout()
            if timeout:
                result.timeout = str(timeout)
            error, _ = self._execute(context)
            if error:
                raise error

class EmbeddedArgumentsRunner(UserKeywordRunner):

    def __init__(self, handler, name):
        UserKeywordRunner.__init__(self, handler, name)
        match = handler.embedded_name.match(name)
        if not match:
            raise ValueError('Does not match given name')
        self.embedded_args = list(zip(handler.embedded_args, match.groups()))

    def _resolve_arguments(self, args, variables=None):
        # Validates that no arguments given.
        self.arguments.resolve(args, variables)
        if not variables:
            return []
        return [(n, variables.replace_scalar(v)) for n, v in self.embedded_args]

    def _set_arguments(self, embedded_args, context):
        variables = context.variables
        for name, value in embedded_args:
            variables['${%s}' % name] = value
        context.output.trace(lambda: self._trace_log_args_message(variables))

    def _trace_log_args_message(self, variables):
        args = ['${%s}' % arg for arg, _ in self.embedded_args]
        return self._format_trace_log_args_message(args, variables)


text:
package com.github.jgonian.ipmath;

import static junit.framework.Assert.*;
import java.util.Comparator;

import org.junit.Test;

public class StartAndSizeComparatorTest {

    private static final Asn _10 = Asn.of(10l);
    private static final Asn _9 = _10.previous();
    private static final Asn _11 = _10.next();
    private static final Asn _100 = Asn.of(100l);
    private static final Asn _99 = _100.previous();
    private static final Asn _101 = _100.next();

    private Comparator<AsnRange> comparator = StartAndSizeComparator.<Asn, AsnRange>get();

    @Test
    public void testSingletonFactoryMethod() {
        assertSame(comparator, StartAndSizeComparator.<Asn, AsnRange>get());
    }

    @Test
    public void testCompare() {
        // range      |----------|   [10, 100]
        // other      .|--------|.   [11, 99]
        // other      .|---------|   [11, 100]
        // other      .|----------|  [11, 101]
        // other     |----------|.   [9, 99]
        // other     |-----------|   [9, 100]
        // other     |------------|  [9, 101]
        // other      |---------|.   [10, 99]
        // other      |----------|   [10, 100]
        // other      |-----------|  [10, 101]
        AsnRange range = AsnRange.from(_10).to(_100);
        assertLessThan(range, AsnRange.from(_11).to(_99));
        assertLessThan(range, AsnRange.from(_11).to(_100));
        assertLessThan(range, AsnRange.from(_11).to(_101));
        assertGreaterThan(range, AsnRange.from(_9).to(_99));
        assertGreaterThan(range, AsnRange.from(_9).to(_100));
        assertGreaterThan(range, AsnRange.from(_9).to(_101));
        assertGreaterThan(range, AsnRange.from(_10).to(_99));
        assertEqual(range, AsnRange.from(_10).to(_100));
        assertLessThan(range, AsnRange.from(_10).to(_101));
    }

    private void assertLessThan(AsnRange range, AsnRange other) {
        assertTrue(comparator.compare(range, other) < 0);
    }

    private void assertGreaterThan(AsnRange range, AsnRange other) {
        assertTrue(comparator.compare(range, other) > 0);
    }

    private void assertEqual(AsnRange range, AsnRange other) {
        assertTrue(comparator.compare(range, other) == 0);
    }
}