text:
{include file="public/header" /}

 添加团购商品信息

	<form class="form form-horizontal" id="form-article-add" method="post" action="{:url('deal/add')}">
	基本信息:

			*团购名称:

				<input type="text" class="input-text" value="" placeholder="" id="" name="name">

			*所属城市:

				<select name="city_id" class="select cityId">
					<option value="0">--请选择--</option>

					<option value=""></option>

				</select>

				<select name="city_id" class="select se_city_id">
					<option value="0">--请选择--</option>
				</select>

			*所属分类:

				<select name="category_id" class="select categoryId">
					<option value="0">--请选择--</option>

					<option value=""></option>

				</select>

			所属子类:

			支持门店:

				<input name="location_ids[]" type="checkbox" id="checkbox" value=""/>

              缩略图:

                <input id="file_upload"  type="file" multiple="true" >

                <input id="file_upload_image" name="image" type="hidden" multiple="true" value="">

			团购开始时间:

				<input type="text" name="start_time" class="input-text" id="countTimestart" onfocus="selecttime(1)" value=""  >

			团购结束时间:

				<input type="text" name="end_time" class="input-text" id="countTimestart" onfocus="selecttime(1)" value=""  >

			库存数:

				<input type="text" class="input-text" value="" placeholder="" id="" name="total_count">

			原价:

				<input type="text" class="input-text" value="" placeholder="" id="" name="origin_price">

			团购价:

				<input type="text" class="input-text" value="" placeholder="" id="" name="current_price">

			消费券生效时间:

				<input type="text" name="coupons_begin_time" class="input-text" id="countTimestart" onfocus="selecttime(1)" value=""  >

			消费券结束时间:

				<input type="text" name="coupons_end_time" class="input-text" id="countTimestart" onfocus="selecttime(1)" value=""  >

			团购描述:

			购买须知:

				<button onClick="article_save_submit();" class="btn btn-primary radius" type="submit"> 申请</button>

	</form>

{include file="public/footer" /}


text:
package com.opengamma.analytics.financial.interestrate.capletstripping;

import com.opengamma.analytics.math.matrix.DoubleMatrix1D;

/**
 * interface for a set of model that perform <i>caplet stripping</i> - that is take a set of market values for interest rate
 * caps or floors and infer the values (as a Black volatilities) of the underlying caplets (or floorlets)
 */
public interface CapletStripper {

  /**
   * Solve directly for the market values - these are either cap prices or cap (implied) volatilities.
   * The chi-square will be the sum of squared differences between (calibrated) model and market values.
   * If used with prices, this can weight the solution towards the more expensive caps (i.e. in-the-money & long dated).
   * @param marketValues Quoted market values (prices or implied volatilities) of the cap/floors
   * @param type Are the market values prices or volatilities
   * @return The result of the stripping routine
   */
  CapletStrippingResult solve(double[] marketValues, MarketDataType type);

  /**
   * Solve for weighted market values - these are either cap prices or cap (implied) volatilities.
   * The chi-square will be the sum of squared differences between (calibrated) model and market values, divided by the error;
   * if the error is set to something meaningful (like the bid-offer), the chi-square value has some meaning (rather than
   * just being a metric that is minimised.
   * @param marketValues Quoted market values (prices or implied volatilities)
  * @param type Are the market values prices or volatilities
   * @param errors The expected difference between model and market values
   * @return The result of the stripping routine
   */
  CapletStrippingResult solve(double[] marketValues, MarketDataType type, double[] errors);

  /**
   * Solve directly for the market values - these are either cap prices or cap (implied) volatilities.
   * The chi-square will be the sum of squared differences between (calibrated) model and market values.
   * If used with prices, this can weight the solution towards the more expensive caps (i.e. in-the-money & long dated).
   * @param marketValues Quoted market values (prices or implied volatilities) of the cap/floors
   * @param type Are the market values prices or volatilities
   * @param guess Starting values of the model parameters used by the optimiser
   * @return  The result of the stripping routine
   */
  CapletStrippingResult solve(double[] marketValues, MarketDataType type, DoubleMatrix1D guess);

  /**
   * Solve for weighted market values - these are either cap prices or cap (implied) volatilities.
   * The chi-square will be the sum of squared differences between (calibrated) model and market values, divided by the error;
   * if the error is set to something meaningful (like the bid-offer), the chi-square value has some meaning (rather than
   * just being a metric that is minimised.
   * @param marketValues Quoted market values (prices or implied volatilities)
   * @param type Are the market values prices or volatilities
   * @param errors The expected difference between model and market values
   * @param guess Starting values of the model parameters used by the optimiser
   * @return The result of the stripping routine
   */
  CapletStrippingResult solve(double[] marketValues, MarketDataType type, double[] errors, DoubleMatrix1D guess);

}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * This is the template for generating CRUD search class of the specified model.
 *
 * @var yii\web\View $this
 * @var maxmirazh33\gii\generators\crud\Generator $generator
 */

use yii\helpers\StringHelper;
use yii\helpers\ArrayHelper;
use yii\helpers\Inflector;

$modelClass = StringHelper::basename($generator->modelClass);
$searchModelClass = StringHelper::basename($generator->searchModelClass);
$searchRules = $generator->generateSearchRules();
$searchConditions = $generator->generateSearchConditions();
$relations = $generator->generateRelations();

echo "<?php\n";
?>
namespace <?= StringHelper::dirname(ltrim($generator->searchModelClass, '\\')) ?>;

use yii\data\ActiveDataProvider;
<?php if (count($relations) > 0): ?>
use yii\helpers\ArrayHelper;
<?php endif; ?>
<?php foreach ($relations as $rel): ?>
use common\models\<?=$rel['className'] ?>;
<?php endforeach; ?>

class <?= $searchModelClass ?> extends \<?= ltrim($generator->modelClass, '\\') . "\n" ?>
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            <?= implode(",\n            ", $searchRules) ?>,
        ];
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search($params)
    {
<?php
    $join = '';
    if ($relations > 0) {
        $join = '->joinWith([';
        $relByClass = ArrayHelper::getColumn($relations, 'className');
        foreach ($relByClass as &$rel) {
            $rel = "'" . mb_strtolower($rel) . "'";
        }
        $join .= implode(', ', $relByClass);
        $join .= '])';
    }
?>
        $query = static::find()<?= $join ?>;

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
<?php foreach ($relations as $rel): ?>

        $dataProvider->sort->attributes['<?= $rel['foreignKey'] ?>'] = [
            'asc' => ['<?= mb_strtolower($rel['className']) ?>.<?= $rel['titleAttr'] ?>' => SORT_ASC],
            'desc' => ['<?= mb_strtolower($rel['className']) ?>.<?= $rel['titleAttr'] ?>' => SORT_DESC],
        ];
<?php endforeach; ?>

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        <?= implode("\n        ", $searchConditions) ?>

        return $dataProvider;
    }
<?php foreach ($generator->getTableSchema()->columns as $column): ?>
<?php if (is_array($column->enumValues) && count($column->enumValues) > 0): ?>

    /**
     * @return array enum values for <?= $column->name ?> attribute
     */
    public function get<?= Inflector::humanize(Inflector::variablize($column->name)) ?>Enums()
    {
        $enums = static::getTableSchema()->getColumn('<?= $column->name ?>')->enumValues;
        return array_combine($enums, $enums);
    }
<?php endif; ?>
<?php endforeach; ?>
<?php foreach ($relations as $rel): ?>

    /**
     * @return array as <?= $rel['idAttr'] ?> => <?= $rel['titleAttr'] ?> for <?= $rel['className'] ?> relation models
     */
    public static function get<?= $rel['relationName'] ?>ForDropdown()
    {
        return ArrayHelper::map(<?= $rel['className'] ?>::find()->all(), '<?= $rel['idAttr'] ?>', '<?= $rel['titleAttr'] ?>');
    }
<?php endforeach; ?>
}


text:
using Android.Widget;
using Cirrious.CrossCore.Droid.Platform;
using HeaderedGridView.Core.Services;

namespace HeaderedGridView.Droid.Services
{
    public class MessageService : IMessageService
    {
        private readonly IMvxAndroidCurrentTopActivity _currentActivity;

        public MessageService(IMvxAndroidCurrentTopActivity currentActivity)
        {
            _currentActivity = currentActivity;
        }

        public void Show(string message)
        {
            var toast = Toast.MakeText(_currentActivity.Activity, message, ToastLength.Short);
            toast.Show();
        }
    }
}


text:
You can clone the repository wherever you want. (I like to keep it in `~/Projects/dotfiles`, with `~/dotfiles` as a symlink.) The bootstrapper script will pull in the latest version and copy the files to your home folder.

```bash
git clone git@github.com:colinperuno/dotfiles.git && cd dotfiles && source bootstrap.sh
```

To update, `cd` into your local `dotfiles` repository and then:

```bash
source bootstrap.sh
```

Alternatively, to update while avoiding the confirmation prompt:

```bash
set -- -f; source bootstrap.sh
```

To update later on, just run that command again.

### Sensible OS X defaults

When setting up a new Mac, you may want to set some sensible OS X defaults:

```bash
./.osx
```

### Install Homebrew formulae

When setting up a new Mac, you may want to install some common [Homebrew](http://brew.sh/) formulae (after installing Homebrew, of course):

```bash
./brew.sh


text:
package com.hazelcast.simulator.probes.xml;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.HdrHistogram.Histogram;

import java.nio.ByteBuffer;

import static org.HdrHistogram.Histogram.decodeFromCompressedByteBuffer;
import static org.apache.commons.codec.binary.Base64.decodeBase64;
import static org.apache.commons.codec.binary.Base64.encodeBase64String;

final class HistogramConverter implements Converter {

    @Override
    public boolean canConvert(Class clazz) {
        return clazz.equals(Histogram.class);
    }

    @Override
    public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
        Histogram histogram = (Histogram) object;
        int size = histogram.getNeededByteBufferCapacity();
        ByteBuffer byteBuffer = ByteBuffer.allocate(size);
        int bytesWritten = histogram.encodeIntoCompressedByteBuffer(byteBuffer);
        byteBuffer.rewind();
        byteBuffer.limit(bytesWritten);
        String encodedHistogram = encodeBase64String(byteBuffer.array());

        writer.setValue(encodedHistogram);
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext unmarshallingContext) {
        String encodedHistogram = reader.getValue();

        try {
            byte[] bytes = decodeBase64(encodedHistogram);
            return decodeFromCompressedByteBuffer(ByteBuffer.wrap(bytes), 0);
        } catch (Exception e) {
            throw new IllegalArgumentException("Could not parse histogram", e);
        }
    }
}


text:
package org.zmpp.tads3

import java.util.regex._
import scala.collection.JavaConversions._

// I really do not want to write my own regex library, the one Java follows
// Perl and is therefore good enough in 99.999999% of all cases.
// Instead, we translate a T3 regex into a Perl regex and let the Java
// regex library handle the rest.
// Angle bracket expressions are replaced with range expressions and using
// POSIX equivalents where possible.
//
// Note that there are some things that do not map to a Perl/Java regext 1:1:
// - flags (case/nocase, min/max, firstbegin/firstend)
// - end-of-word match (the normal word boundary match is used instead)
//
// TODO:
// - group match expressions ('%1', '%2' etc), will be mapped to back references
// - lookahead/non-capturing group (might be already working, looks compatible to Perl)
// - ranges with special characters
//
// Here I wanted to say that I used the cool Scala parser combinator library,
// but I did not, it seems more efficient and simple to just do a straightforward
// implementation
//
// Some dirty facts about T3 regexes:
//
// - regexes recognize the following special characters at the main level
//   of an expression:
//
//     '^' | '$' | '(' | ')' | '|' |  '<' | '%' | '.' | '['
//
//   This means
//
//     '*' | '+' | '?' | '{' | '}'
//
//   can appear at main level and are then recognized as a regular character.
//   These are only recognized in the "postfix" position state of the reference
//   parser.
//   Perl-style regexes might choke on this, because, as in T3, these are
//   special characters, but the parsers will treat them as such even when
//   in postfix position.
//   Since we translate to a Java regex (which is a Perl regex), we need
//   to explicitly escape said special characters when they are in the main
//   position. The closing mustache needs to be escaped when it closes
//   a non-postfix opening mustache.
object RegexTranslator {
  val Punctuation = Set('%', '<', '>' )
  val SymbolMappings = Map("langle"   -> "<",   "rangle"    -> ">",
                           "lsquare"  -> "\\[", "rsquare"   -> "\\]",
                           "lbrace"   -> "{",   "rbrace"    -> "}",
                           "dot"      -> ".",   "period"    -> ".",
                           "vbar"     -> "|",   "caret"     -> "\\^",
                           "squote"   -> "'",   "dquote"    -> "\"",
                           "star"     -> "*",   "plus"      -> "+",
                           "percent"  -> "%",   "question"  -> "?",
                           "dollar"   -> "$",   "backslash" -> "\\\\",
                           "return"   -> "\r",  "linefeed" -> "\n",
                           "tab"      -> "\t",  "nul"      -> "\0",
                           "null"     -> "\0",
                           "alpha"    -> "\\p{Alpha}",
                           "upper"    -> "\\p{Upper}",
                           "lower"    -> "\\p{Lower}",
                           "digit"    -> "\\p{Digit}",
                           "alphanum" -> "\\p{Alnum}",
                           "space"    -> "\\p{Space}",
                           "punct"    -> "\\p{Punct}",
                           "newline"  -> "\r\n\u2028"
                         )
}

class RegexTranslator(str: String) {
  import RegexTranslator._

  private var parsePos    = 0
  private val builder       = new StringBuilder
  private var negate        = false
  private var caseSensitive = true

  def translate = {
    printf("RegexTranslator.translate('%s')\n", str)

    while (parsePos < str.length) {
      if (!handleRangeExpression) {
        val c = str.charAt(parsePos)
        if (isPunctuation(c)) handlePunctuation
        else {
          // this is the "non-postfix exception", escape the characters
          // that are special in postfix position to work around a
          // non-documented feature/bug in the reference implementation
          // which is used in at least one game (AllHope.t3)
          if (isPostfixSpecialChar(c)) builder.append("\\")
          builder.append(c)
          parsePos += 1
        }
      }
      // because of the "non-postfix exception", we have to
      // parse a postfix position in the translation mechanism.
      if (parsePos < str.length) handlePostfix
    }
    (caseSensitive, builder.toString)
  }

  private def handleRangeExpression = {
    if (str.charAt(parsePos) != '[') false
    else {
      var inRangeExpression = true
      while (inRangeExpression && parsePos < str.length) {
        val c = str.charAt(parsePos)
        builder.append(c)
        parsePos += 1
        if (c == ']') inRangeExpression = false
      }
      true
    }
  }

  private def isPunctuation(c: Char) = Punctuation.contains(c)

  private def handlePunctuation {
    val c = str.charAt(parsePos)
    if (c == '%') escapeCharacter
    else if (c == '<') angleExpression
    else {
      throw new UnsupportedOperationException("unsupported punctuation: '%c'\n".format(c))
    }
  }

  // handle the '%' character
  // in the regular case, this will simply replace '%' with '\\'
  // exceptions:
  // - '%<' and '%>' => '\\b' (Java/Perl do not support 'end of word')
  private def escapeCharacter {
    builder.append('\\')
    val nextChar = str.charAt(parsePos + 1)
    if (nextChar == '<' || nextChar == '>') builder.append('b')
    else builder.append(nextChar)
    parsePos += 2
  }

  // This is the part that differs the most from normal (Perl) regular
  // expressions. The rule is:
  // - between the angles comes a list of expressions, separated by '|'
  // - a '^' negates the content
  private def angleExpression {
    parsePos += 1
    negate = if (str.charAt(parsePos) == '^') {
      parsePos += 1
      true
    } else false
    val contentStringBuilder = new StringBuilder
    while (str.charAt(parsePos) != '>') {
      contentStringBuilder.append(str.charAt(parsePos))
      parsePos += 1
    }
    parsePos += 1 // skip the terminator '>'
    val comps = contentStringBuilder.toString.split('|')
    var identifiers = comps.map(comp => if (comp.contains("-")) comp.trim
                                        else comp.trim.toLowerCase)
    // if there is any nocase in here, we set the whole pattern to
    // non-sensitive, default is case sensitive
    if (identifiers.filter(_ == "nocase").length > 0) caseSensitive = false

    // filter out the case modifiers, since there is no text substitution for
    // those
    identifiers = identifiers.filter(id => id != "nocase" && id != "case")
    if (identifiers.length > 0) {
      builder.append("[")
      if (negate) builder.append("^")
      identifiers.foreach(str => {
        if (SymbolMappings.contains(str)) builder.append(SymbolMappings(str))
        else builder.append(str)
      })
      builder.append("]")
    }
  }

  private def handlePostfix = {
    if (str.charAt(parsePos) == '{') {
      var inRepetitionDef = true
      while (inRepetitionDef && parsePos < str.length) {
        val c = str.charAt(parsePos)
        builder.append(c)
        if (c == '}') inRepetitionDef = false
        parsePos += 1
      }
    } else if (isPostfixSpecialCharPos1(str.charAt(parsePos))) {
      builder.append(str.charAt(parsePos))
      parsePos += 1
    }
  }

  // note that we exclude the '}' character here so we only handle
  // it either in non-postfix or ending a postfix expression
  private def isPostfixSpecialCharPos1(c: Char) = {
    c == '*' || c == '+' || c == '?' | c == '{'
  }

  private def isPostfixSpecialChar(c: Char) = {
    isPostfixSpecialCharPos1(c) || c == '}'
  }
}


text:
# gulp-cli

[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url]

Command Line Utility for Gulp

## Usage

```bash
> gulp [flags] <task> <task>...
```

## Custom Metadata

When listing tasks with the `gulp -T` command, gulp-cli displays some custom metadata as defined upon task functions. Currently supported properties:

* `task.description` - String of the description to display.

```js
function clean() { ... }
clean.description = 'Cleans up generated files.';
```

* `task.flags` - Object with key/value pairs being flag/description to display.

```js
function build() { ... }
build.flags = {
  '--prod': 'Builds in production mode.'
};
```

Example Usage:

```js
function build() { ... }
build.description = 'Build entire project.';
build.flags = {
  '--prod': 'Builds in production mode (minification, etc).'
};
// gulp 3.x
gulp.task('build', build);
// gulp 4.x
gulp.task(build);
```

## Tasks

The task(s) listed on the command line will be executed.
If more than one task is listed, Gulp will execute all of them
concurrently, that is, as if they had all been listed as dependencies of
a single task.

Gulp does not serialize tasks listed on the command line. From using
other comparable tools users may expect to execute something like
`gulp clean build`, with tasks named `clean` and `build`. This will not
produce the intended result, as the two tasks will be executed
concurrently.

Just running `gulp` will execute the task `default`. If there is no
`default` task, gulp will error.

## Completion
> Thanks to the grunt team, specifically Tyler Kellen

To enable tasks auto-completion in shell you should add `eval "$(gulp --completion=shell)"` in your `.shellrc` file.

###### Bash:

Add `eval "$(gulp --completion=bash)"` to `~/.bashrc`.

###### Zsh:

Add `eval "$(gulp --completion=zsh)"` to `~/.zshrc`.

###### Powershell:

Add `Invoke-Expression ((gulp --completion=powershell) -join [System.Environment]::NewLine)` to `$PROFILE`.

###### Fish:

Add `gulp --completion=fish | source` to `~/.config/fish/config.fish`.

## Compilers

You can find a list of supported languages at https://github.com/js-cli/js-interpret. If you would like to add support for a new language, send pull requests/open issues on that project.

## Environment

The CLI adds process.env.INIT_CWD which is the original cwd it was launched from.

## Configuration

Configuration is supported through the use of a `.gulp.*` file (e.g. `.gulp.json`, `.gulp.yml`). You can find a list of supported languages at https://github.com/js-cli/js-interpret.

Configuration from the home directory (`~`) and current working directory (`cwd`) are merged with `cwd` taking precedence.

Supported configurations properties:

| Property    | Description |
|-------------|-------------|
| description | Top-level description of the project/gulpfile (Replaces "Tasks for ~/path/of/gulpfile.js") |

## Flags

gulp has very few flags to know about. All other flags are for tasks to use if needed.

__Some flags only work with gulp 4 and will be ignored when invoked against gulp 3.__

      Flag
      Short Flag
      Description

      --help
      -h
      Show this help.

      --version
      -v
      Print the global and local gulp versions.

      --require [path]

      Will require a module before running the gulpfile. This is useful for transpilers but also has other applications.

      --gulpfile [path]

      Manually set path of gulpfile. Useful if you have multiple gulpfiles. This will set the CWD to the gulpfile directory as well.

      --cwd [path]

      Manually set the CWD. The search for the gulpfile, as well as the relativity of all requires will be from here.

      --verify [path (optional)]

      Will verify plugins referenced in project's package.json against the plugins blacklist.

      --tasks
      -T
      Print the task dependency tree for the loaded gulpfile.

      --depth [number]

      Specify the depth of the task dependency tree to print.

      --tasks-simple

      Print a plaintext list of tasks for the loaded gulpfile.

      --tasks-json [path]

      Print the task dependency tree, in JSON format, for the loaded gulpfile. The [path] argument is optional, and if given writes the JSON to the path.

      --color

      Will force gulp and gulp plugins to display colors, even when no color support is detected.

      --no-color

      Will force gulp and gulp plugins to not display colors, even when color support is detected.

      --silent
      -S
      Suppress all gulp logging.

      --continue

      Continue execution of tasks upon failure.

      --log-level
      -L
      Set the loglevel. -L for least verbose and -LLLL for most verbose. -LLL is default.

## License

MIT

[gittip-url]: https://www.gittip.com/WeAreFractal/
[gittip-image]: http://img.shields.io/gittip/WeAreFractal.svg

[downloads-image]: http://img.shields.io/npm/dm/gulp-cli.svg
[npm-url]: https://npmjs.org/package/gulp-cli
[npm-image]: http://img.shields.io/npm/v/gulp-cli.svg

[travis-url]: https://travis-ci.org/gulpjs/gulp-cli
[travis-image]: http://img.shields.io/travis/gulpjs/gulp-cli.svg?label=travis-ci

[appveyor-url]: https://ci.appveyor.com/project/gulpjs/gulp-cli
[appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/gulp-cli.svg?label=appveyor

[coveralls-url]: https://coveralls.io/r/gulpjs/gulp-cli
[coveralls-image]: http://img.shields.io/coveralls/gulpjs/gulp-cli/master.svg

[gitter-url]: https://gitter.im/gulpjs/gulp
[gitter-image]: https://badges.gitter.im/gulpjs/gulp.png


text:
export function pixels(state = {}, action) {
  switch (action.type) {
    /*
     *
     */
    case 'ADD_PIXEL':

      let clone = Object.assign({}, state)
      clone[action.data.row] = Object.assign({}, clone[action.data.row])
      clone[action.data.row][action.data.column] = {
        color: action.data.color
      }

      return clone
    default:
      return state
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<localization>
  <string id="RadEditorStatistics">Statistiques</string>
  <string id="RadEditorNodeInspector">Inspecteur de propriétés</string>
  <string id="RadEditorDomInspector">Inspecteur des balises HTML</string>
  <string id="RadEditorHtmlInspector">Vue HTML immédiate</string>
  <string id="StatisticsWords">Mots :</string>
  <string id="StatisticsCharacters">Caractères :</string>
  <string id="NodeInspectorSelectedElement">L'élément sélectionné est </string>
  <string id="NodeInspectorInvalidValue">Valeur invalide. Veuillez entrer un numéro.</string>
  <string id="className">Nom de classe</string>
  <string id="borderColor">Couleur de bordure</string>
  <string id="bgColor">Couleur du fond</string>
  <string id="width">Largeur</string>
  <string id="height">Hauteur</string>
  <string id="align">Alignement</string>
  <string id="vAlign">Alignement vertical</string>
  <string id="cellSpacing">CellSpacing</string>
  <string id="cellPadding">CellPadding</string>
  <string id="border">Largeur de la bordure</string>
  <string id="noWrap">Pas de retour à la ligne</string>
  <string id="value">Valeur</string>
  <string id="id">Id</string>
  <string id="name">Nom</string>
  <string id="href">URL</string>
  <string id="title">Titre</string>
  <string id="target">Cible</string>
  <string id="alt">ToolTip</string>
  <string id="_blank">Nouvelle fenêtre</string>
  <string id="_self">Même fenêtre</string>
  <string id="_parent">Fenêtre parente</string>
  <string id="_top">Fenêtre du navigateur</string>
  <string id="_search">Panneau de recherche</string>
  <string id="_media">Panneau de media</string>
  <string id="DomInspectorRemoveElement">Supprimer l'élément</string>
  <string id="rows">Lignes</string>
  <string id="cols">Colonnes</string>
</localization>


text:
package com.vaadin.test.cdi;

public class CDIPushStateNavigationIT extends CDINavigationIT {

    protected String getUIPath() {
        return "/subpath";
    }

    @Override
    protected String getViewSeparator() {
        return "/";
    }
}


text:
<!DOCTYPE html>

If you click on the "Hide" button, I will disappear.

<button id="hide">Hide</button>
<button id="show">Show</button>


text:
upload.modules.addmodule({
    name: 'updown',
    init: function () {
        // We do this to try to hide the fragment from the referral in IE
        this.requestframe = document.createElement('iframe')
        this.requestframe.src = 'about:blank'
        this.requestframe.style.visibility = 'hidden'
        document.body.appendChild(this.requestframe)
    },
    downloadfromident: function(seed, progress, done, ident) {
        var xhr = new this.requestframe.contentWindow.XMLHttpRequest()
        xhr.onload = this.downloaded.bind(this, seed, progress, done)
        xhr.open('GET', (upload.config.server ? upload.config.server : '') + 'i/' + ident.ident)
        xhr.responseType = 'blob'
        xhr.onerror = this.onerror.bind(this, progress)
        xhr.addEventListener('progress', progress, false)
        xhr.send()
    },
    onerror: function(progress) {
      progress('error')
    },
    downloaded: function (seed, progress, done, response) {
        if (response.target.status != 200) {
          this.onerror(progress)
        } else {
          this.cache(seed, response.target.response)
          progress('decrypting')
          crypt.decrypt(response.target.response, seed).done(done)
        }
    },
    encrypted: function(progress, done, data) {
        var formdata = new FormData()
        formdata.append('api_key', upload.config.api_key)
        formdata.append('ident', data.ident)
        formdata.append('file', data.encrypted)
        $.ajax({
            url: (upload.config.server ? upload.config.server : '') + 'up',
            data: formdata,
            cache: false,
            processData: false,
            contentType: false,
            dataType: 'json',
            xhr: function () {
                var xhr = new XMLHttpRequest()
                xhr.upload.addEventListener('progress', progress, false)
                return xhr
            },
            type: 'POST'
        }).done(done.bind(undefined, data))
    },
    cache: function(seed, data) {
      this.cached = data
      this.cached_seed = seed
    },
    cacheresult: function(data) {
      this.cache(data.seed, data.encrypted)
    },
    download: function (seed, progress, done) {
        if (this.cached_seed == seed) {
          progress('decrypting')
          crypt.decrypt(this.cached, seed).done(done).progress(progress)
        } else {
          crypt.ident(seed).done(this.downloadfromident.bind(this, seed, progress, done))
        }
    },
    upload: function (blob, progress, done) {
        crypt.encrypt(blob).done(this.encrypted.bind(this, progress, done)).done(this.cacheresult.bind(this)).progress(progress)
    }
})


text:
"""empty message

Revision ID: 37s5rj356547
Revises: j4d9g3scvf4s
Create Date: 2019-02-20 16:45:34.186981

"""

# revision identifiers, used by Alembic.
revision = '37s5rj356547'
down_revision = 'j4d9g3scvf4s'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('group_quota', sa.Float(), nullable=True))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('users', 'group_quota')
    ### end Alembic commands ###


text:
     NAME
	  glIsTexture -	determine if a name corresponds	to a texture

     C SPECIFICATION
	  GLboolean glIsTexture( GLuint	texture	)

     PARAMETERS
	  texture  Specifies a value that may be the name of a
		   texture.

     DESCRIPTION
	  glIsTexture returns GL_TRUE if texture is currently the name
	  of a texture.	 If texture is zero, or	is a non-zero value
	  that is not currently	the name of a texture, or if an	error
	  occurs, glIsTexture returns GL_FALSE.

     NOTES
	  glIsTexture is available only	if the GL version is 1.1 or
	  greater.

     ERRORS
	  GL_INVALID_OPERATION is generated if glIsTexture is executed
	  between the execution	of glBegin and the corresponding
	  execution of glEnd.

     SEE ALSO
	  glBindTexture, glCopyTexImage1D, glCopyTexImage2D,
	  glDeleteTextures, glGenTextures, glGet, glGetTexParameter,
	  glTexImage1D,	glTexImage2D,
	  glTexParameter


text:
class Feature < ActiveRecord::Base
  has_and_belongs_to_many :areas, dependent: :delete_all

  validates :ftype, presence: true
  acts_as_mappable

  scope :with_type,    -> (ftype, subtype=nil) { subtype.present? ? where(ftype: ftype, subtype: subtype) : where(ftype: ftype) }
  scope :in_area,      -> (area) { in_bounds(area.bounds) }

  def self.subtypes_for(ftype)
    where(ftype: ftype).distinct.pluck(:subtype).compact.sort
  end
end


text:
import {PropTypes} from 'react'
import {StyleSheet, css} from 'aphrodite'
import Person from './person'

export default PersonGroup

function PersonGroup({people = [], personClassNames}) {
  const {styles} = PersonGroup
  return (
    <div className={css(styles.group)}>
      {people.map((person, index) => (
        <Person
          key={index}
          {...person}
          personClassNames={personClassNames}
        />
      ))}
    </div>
  )
}

PersonGroup.propTypes = {
  people: PropTypes.array,
  personClassNames: PropTypes.object,
}

PersonGroup.styles = StyleSheet.create({
  group: {
    marginTop: 20,
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'flex-start',
    alignContent: 'space-between',
    justifyContent: 'center',
  },
})


text:
/* Generated By:JJTree: Do not edit this line. ASTId.h Version 7.0 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=MyNode,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
#pragma once

#include "SimpleNode.h"

class SPLParser;

class ASTId : public SimpleNode {
public:
           ASTId(int id);
           ASTId(SPLParser *parser, int id);
  virtual ~ASTId();
  virtual void interpret();
  friend class SPLParser;
  friend class ASTAssignment;

private:
	string name;
};


text:
"""
TOKEN-BASED AUTH MIDDLEWARE

This WSGI component performs multiple jobs:

- it verifies that incoming client requests have valid tokens by verifying
  tokens with the auth service.
- it will reject unauthenticated requests UNLESS it is in 'delay_auth_decision'
  mode, which means the final decision is delegated to the downstream WSGI
  component (usually the OpenStack service)
- it will collect and forward identity information from a valid token
  such as user name, groups, etc...

Refer to: http://wiki.openstack.org/openstack-authn

This WSGI component has been derived from Keystone's auth_token
middleware module. It contains some specialization for Quantum.

HEADERS
=======

Headers starting with ``HTTP_`` is a standard http header
Headers starting with ``HTTP_X`` is an extended http header

Coming in from initial call from client or customer
---------------------------------------------------

HTTP_X_AUTH_TOKEN
    The client token being passed in

HTTP_X_STORAGE_TOKEN
    The client token being passed in (legacy Rackspace use) to support
    cloud files

Used for communication between components
-----------------------------------------

www-Authenticate
    Only used if this component is being used remotely

HTTP_AUTHORIZATION
    Basic auth password used to validate the connection

What we add to the request for use by the OpenStack service
-----------------------------------------------------------

HTTP_X_AUTHORIZATION
    The client identity being passed in

"""

import httplib
import json
import logging
import urllib
from urlparse import urlparse
from webob.exc import HTTPUnauthorized, Request, Response

from keystone.common.bufferedhttp import http_connect_raw as http_connect

PROTOCOL_NAME = "Quantum Token Authentication"
logger = logging.getLogger(__name__)  # pylint: disable=C0103

# pylint: disable=R0902
class AuthProtocol(object):
    """Auth Middleware that handles authenticating client calls"""

    def _init_protocol_common(self, app, conf):
        """ Common initialization code"""
        logger.info("Starting the %s component", PROTOCOL_NAME)

        self.conf = conf
        self.app = app
        #if app is set, then we are in a WSGI pipeline and requests get passed
        # on to app. If it is not set, this component should forward requests

        # where to find the Quantum service (if not in local WSGI chain)
        # these settings are only used if this component is acting as a proxy
        # and the OpenSTack service is running remotely
        if not self.app:
            self.service_protocol = conf.get('quantum_protocol', 'https')
            self.service_host = conf.get('quantum_host')
            self.service_port = int(conf.get('quantum_port'))
            self.service_url = '%s://%s:%s' % (self.service_protocol,
                                           self.service_host,
                                           self.service_port)

        # delay_auth_decision means we still allow unauthenticated requests
        # through and we let the downstream service make the final decision
        self.delay_auth_decision = int(conf.get('delay_auth_decision', 0))

    def _init_protocol(self, _app, conf):
        """ Protocol specific initialization """

        # where to find the auth service (we use this to validate tokens)
        self.auth_host = conf.get('auth_host')
        self.auth_port = int(conf.get('auth_port'))
        self.auth_protocol = conf.get('auth_protocol', 'http')
        self.cert_file = conf.get('certfile', None)
        self.key_file = conf.get('keyfile', None)
        self.auth_timeout = conf.get('auth_timeout', 30)
        self.auth_api_version = conf.get('auth_version', '2.0')
        self.auth_location = "%s://%s:%s" % (self.auth_protocol,
                                             self.auth_host,
                                             self.auth_port)
        self.auth_uri = conf.get('auth_uri', self.auth_location)
        logger.debug("Authentication Service:%s", self.auth_location)
        # Credentials used to verify this component with the Auth service
        # since validating tokens is a privileged call
        self.admin_user = conf.get('admin_user')
        self.admin_password = conf.get('admin_password')
        self.admin_token = conf.get('admin_token')
        # bind to one or more service instances
        service_ids = conf.get('service_ids')
        self.serviceId_qs = ''
        if service_ids:
            self.serviceId_qs = '?HP-IDM-serviceId=%s' % \
                                (urllib.quote(service_ids))

    def _build_token_uri(self, claims=None):
        claim_str = "/%s" % claims if claims else ""
        return "/v%s/tokens%s%s" % (self.auth_api_version, claim_str,
                                    self.serviceId_qs or '')

    def __init__(self, app, conf):
        """ Common initialization code """
        # Defining instance variables here for improving pylint score
        # NOTE(salvatore-orlando): the following vars are assigned values
        # either in init_protocol or init_protocol_common. We should not
        # worry about them being initialized to None
        self.admin_password = None
        self.admin_token = None
        self.admin_user = None
        self.auth_api_version = None
        self.auth_host = None
        self.auth_location = None
        self.auth_uri = None
        self.auth_port = None
        self.auth_protocol = None
        self.auth_timeout = None
        self.cert_file = None
        self.key_file = None
        self.service_host = None
        self.service_port = None
        self.service_protocol = None
        self.service_url = None
        self.proxy_headers = None
        self.start_response = None
        self.app = None
        self.conf = None
        self.env = None
        self.delay_auth_decision = None
        self.expanded = None
        self.claims = None

        self._init_protocol_common(app, conf)  # Applies to all protocols
        self._init_protocol(app, conf)  # Specific to this protocol

    # pylint: disable=R0912
    def __call__(self, env, start_response):
        """ Handle incoming request. Authenticate. And send downstream. """
        logger.debug("entering AuthProtocol.__call__")
        logger.debug("start response:%s", start_response)
        self.start_response = start_response
        self.env = env

        #Prep headers to forward request to local or remote downstream service
        self.proxy_headers = env.copy()
        for header in self.proxy_headers.iterkeys():
            if header[0:5] == 'HTTP_':
                self.proxy_headers[header[5:]] = self.proxy_headers[header]
                del self.proxy_headers[header]

        #Look for authentication claims
        logger.debug("Looking for authentication claims")
        self.claims = self._get_claims(env)
        if not self.claims:
            #No claim(s) provided
            logger.debug("No claims provided")
            if self.delay_auth_decision:
                #Configured to allow downstream service to make final decision.
                #So mark status as Invalid and forward the request downstream
                self._decorate_request("X_IDENTITY_STATUS", "Invalid")
            else:
                #Respond to client as appropriate for this auth protocol
                return self._reject_request()
        else:
            # this request is presenting claims. Let's validate them
            logger.debug("Claims found. Validating.")
            valid = self._validate_claims(self.claims)
            if not valid:
                # Keystone rejected claim
                if self.delay_auth_decision:
                    # Downstream service will receive call still and decide
                    self._decorate_request("X_IDENTITY_STATUS", "Invalid")
                else:
                    #Respond to client as appropriate for this auth protocol
                    return self._reject_claims()
            else:
                self._decorate_request("X_IDENTITY_STATUS", "Confirmed")

            #Collect information about valid claims
            if valid:
                logger.debug("Validation successful")
                claims = self._expound_claims()

                # Store authentication data
                if claims:
                    # TODO(Ziad): add additional details we may need,
                    #             like tenant and group info
                    self._decorate_request('X_AUTHORIZATION', "Proxy %s" %
                        claims['user'])

                    self._decorate_request('X_TENANT_ID',
                                        claims['tenant']['id'],)
                    self._decorate_request('X_TENANT_NAME',
                                        claims['tenant']['name'])

                    self._decorate_request('X_USER_ID',
                                        claims['user']['id'])
                    self._decorate_request('X_USER_NAME',
                                        claims['user']['name'])

                    self._decorate_request('X_TENANT', claims['tenant']['id'])
                    self._decorate_request('X_USER', claims['user']['id'])

                    if 'group' in claims:
                        self._decorate_request('X_GROUP', claims['group'])
                    if 'roles' in claims and len(claims['roles']) > 0:
                        if claims['roles'] is not None:
                            roles = ''
                            for role in claims['roles']:
                                if len(roles) > 0:
                                    roles += ','
                                roles += role
                            self._decorate_request('X_ROLE', roles)

                    # NOTE(todd): unused
                    self.expanded = True
            logger.debug("About to forward request")
            #Send request downstream
            return self._forward_request()

    # NOTE(salvatore-orlando): this function is now used again
    def get_admin_auth_token(self, username, password):
        """
        This function gets an admin auth token to be used by this service to
        validate a user's token. Validate_token is a priviledged call so
        it needs to be authenticated by a service that is calling it
        """
        headers = {
            "Content-type": "application/json",
            "Accept": "application/json"}
        params = {
                  "auth":
                  {
                   "passwordCredentials":
                   {
                    "username": username,
                    "password": password
                    }
                   }
                  }
        if self.auth_protocol == "http":
            conn = httplib.HTTPConnection(self.auth_host, self.auth_port)
        else:
            conn = httplib.HTTPSConnection(self.auth_host, self.auth_port,
                cert_file=self.cert_file)
        conn.request("POST", self._build_token_uri(), json.dumps(params), \
            headers=headers)
        response = conn.getresponse()
        data = response.read()
        return data

    @staticmethod
    def _get_claims(env):
        """Get claims from request"""
        claims = env.get('HTTP_X_AUTH_TOKEN', env.get('HTTP_X_STORAGE_TOKEN'))
        return claims

    def _reject_request(self):
        """Redirect client to auth server"""
        return HTTPUnauthorized("Authentication required",
                    [("WWW-Authenticate",
                      "Keystone uri='%s'" % self.auth_uri)])(self.env,
                                                        self.start_response)

    def _reject_claims(self):
        """Client sent bad claims"""
        return HTTPUnauthorized()(self.env, self.start_response)

    def _validate_claims(self, claims, retry=False):
        """Validate claims, and provide identity information if applicable """

        # Step 1: We need to auth with the keystone service, so get an
        # admin token
        # TODO(ziad): Need to properly implement this, where to store creds
        # for now using token from ini
        # NOTE(salvatore-orlando): Temporarily restoring auth token retrieval,
        # with credentials in configuration file
        if not self.admin_token:
            auth = self.get_admin_auth_token(self.admin_user,
                                             self.admin_password)
            self.admin_token = json.loads(auth)["access"]["token"]["id"]

        # Step 2: validate the user's token with the auth service
        # since this is a priviledged op,m we need to auth ourselves
        # by using an admin token
        headers = {"Content-type": "application/json",
                    "Accept": "application/json",
                    "X-Auth-Token": self.admin_token}
        conn = http_connect(self.auth_host, self.auth_port, 'GET',
                            self._build_token_uri(claims), headers=headers,
                            ssl=(self.auth_protocol == 'https'),
                            key_file=self.key_file, cert_file=self.cert_file,
                            timeout=self.auth_timeout)
        resp = conn.getresponse()
        # pylint: disable=E1103
        conn.close()

        if not str(resp.status).startswith('20'):
            # Keystone rejected claim
            # In case a 404 error it might just be that the token has expired
            # Therefore try and get a new token
            # of course assuming admin credentials have been specified
            # Note(salvatore-orlando): the 404 here is not really
            # what should be returned
            if self.admin_user and self.admin_password and \
               not retry and str(resp.status) == '404':
                logger.warn("Unable to validate token." +
                         "Admin token possibly expired.")
                self.admin_token = None
                return self._validate_claims(claims, True)
            return False
        else:
            #TODO(Ziad): there is an optimization we can do here. We have just
            #received data from Keystone that we can use instead of making
            #another call in _expound_claims
            logger.info("Claims successfully validated")
            return True

    def _expound_claims(self):
        # Valid token. Get user data and put it in to the call
        # so the downstream service can use it
        headers = {"Content-type": "application/json",
                    "Accept": "application/json",
                    "X-Auth-Token": self.admin_token}
        conn = http_connect(self.auth_host, self.auth_port, 'GET',
                            self._build_token_uri(self.claims),
                            headers=headers,
                            ssl=(self.auth_protocol == 'https'),
                            key_file=self.key_file, cert_file=self.cert_file,
                            timeout=self.auth_timeout)
        resp = conn.getresponse()
        data = resp.read()
        # pylint: disable=E1103
        conn.close()

        if not str(resp.status).startswith('20'):
            raise LookupError('Unable to locate claims: %s' % resp.status)

        token_info = json.loads(data)
        #TODO(Ziad): make this more robust
        #first_group = token_info['auth']['user']['groups']['group'][0]
        roles = []
        rolegrants = token_info["access"]["user"]["roles"]
        if rolegrants is not None:
            roles = [rolegrant["id"] for rolegrant in rolegrants]

        token_info = json.loads(data)

        roles = [role['name'] for role in token_info[
            "access"]["user"]["roles"]]

        # in diablo, there were two ways to get tenant data
        tenant = token_info['access']['token'].get('tenant')
        if tenant:
            # post diablo
            tenant_id = tenant['id']
            tenant_name = tenant['name']
        else:
            # diablo only
            tenant_id = token_info['access']['user'].get('tenantId')
            tenant_name = token_info['access']['user'].get('tenantName')

        verified_claims = {
            'user': {
                'id': token_info['access']['user']['id'],
                'name': token_info['access']['user']['name'],
            },
            'tenant': {
                'id': tenant_id,
                'name': tenant_name
            },
            'roles': roles}

        return verified_claims

    def _decorate_request(self, index, value):
        """Add headers to request"""
        self.proxy_headers[index] = value
        self.env["HTTP_%s" % index] = value

    def _forward_request(self):
        """Token/Auth processed & claims added to headers"""
        #now decide how to pass on the call
        if self.app:
            # Pass to downstream WSGI component
            return self.app(self.env, self.start_response)
            #.custom_start_response)
        else:
            # We are forwarding to a remote service (no downstream WSGI app)
            req = Request(self.proxy_headers)
            # pylint: disable=E1101
            parsed = urlparse(req.url)
            conn = http_connect(self.service_host,
                                self.service_port,
                                req.method,
                                parsed.path,
                                self.proxy_headers,
                                ssl=(self.service_protocol == 'https'))
            resp = conn.getresponse()
            data = resp.read()
            return Response(status=resp.status, body=data)(self.proxy_headers,
                                                           self.start_response)

def filter_factory(global_conf, **local_conf):
    """Returns a WSGI filter app for use with paste.deploy."""
    conf = global_conf.copy()
    conf.update(local_conf)

    def auth_filter(application):
        return AuthProtocol(application, conf)
    return auth_filter

def app_factory(global_conf, **local_conf):
    conf = global_conf.copy()
    conf.update(local_conf)
    return AuthProtocol(None, conf)


text:
layout:     post
title:      alex honnold
date:       2019-09-05 15:18:47
summary:
categories: drawing
---
![alex honnold](/images/diary/alex-honnold.png ".")


text:
import Phaser from 'phaser'
import config from '../config'

export default class extends Phaser.Sprite {
	constructor ({ game, x, y, asset }) {
		super(game, x, y, asset)
		this.anchor.setTo(0.5, 1)
		this.game.add.existing(this)

		this.animations.add('walk')
		this.animations.add('dead')
		this.animations.add('jump')

		this.jumpSound = this.game.add.audio('jump')
	}

	/**
	* Setup player physics and animations
	*/
	enable() {
		this.game.physics.arcade.enable(this)
		this.body.gravity.y = config.player.weight
		this.body.velocity.x = config.player.speed
		this.animations.play('walk', 18, true)
	}

	/**
	* Stop moving and change image
	*/
	die() {
		// set to dead (this doesn't affect rendering)
		this.alive = false
		// stop moving
		this.body.velocity.x = 0
		// stop all animations and change sprite image
		this.animations.stop(null, false)
		this.loadTexture('playerDead')
		this.animations.play('dead', 13.5, true)
	}

	/**
	* Speed up x speed
	*/
	speedUp() {
		if(this.body.velocity.x < config.player.maxSpeed) {
			let newSpeed = this.body.velocity.x + config.player.speedBonus
			if(newSpeed > config.player.maxSpeed) {
				newSpeed = config.player.maxSpeed
			}
			this.body.velocity.x = newSpeed
		}
	}

	/**
	* Player jump
	*/
	jump() {
		if (this.body.blocked.down) {
			this.jumpSound.play()
			this.body.velocity.y -= config.player.jump
			// stop walking animation and change sprite image
			this.animations.stop('walk', false)
			this.loadTexture('playerJump')
			this.animations.play('jump', 40, true)
			this.isJumping = true
		}
	}

	/**
	 * Player land
	 */
	maybeLand() {
		if (this.body.blocked.down) {
			this.animations.stop('jump', false)
			this.loadTexture('player')
			this.animations.play('walk', 18, true)
			this.isJumping = false
		}
	}
}


text:
title: Keeping Build Artifacts After CI/CD
shortTitle: Build Artifacts
menus:
  basic/ci:
    title: Artifacts
    weight: 5
tags:
  - cdn
  - artifacts
  - testing
categories:
  - Continuous Integration
  - Caching
redirect_from:
  - /continuous-integration/keep-build-artifacts/
---

* include a table of contents
{:toc}

For security reasons Codeship does not provide persistent storage of files between builds (aside from the build log). If you wish to retain artifacts for troubleshooting purposes, then you will need to implement steps to transfer them to a remote server during the build run.

## Upload artifacts to S3

If you want to upload artifacts to S3 during your test steps, you can use the [AWS CLI]({{ site.baseurl }}{% link _basic/continuous-deployment/deployment-with-awscli.md %}). First add the following environment variables to your project configuration:

```
AWS_DEFAULT_REGION
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
```

Then add the following commands to your setup/test steps:

```shell
pip install awscli
aws s3 cp your_artifact_file.zip s3://mybucket/your_artifact_file.zip
```

{% csnote info %}
For Codeship Pro, our [Codeship AWS container]({{ site.baseurl }}{% link _pro/continuous-deployment/aws.md %}) can be implemented to transfer artifacts to S3 storage.
{% endcsnote %}

For more advanced usage of the S3 CLI, please see Amazon's [S3 documentation](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html).

**Note** that you can simply add another [integrated S3 deployment]({{ site.baseurl }}{% link _basic/continuous-deployment/deployment-to-aws-s3.md %}) after your actual deployment if you only want to keep artifacts for specific branches.

## Upload through SFTP

Each project has its own [SSH public key]({{ site.baseurl }}{% link _general/projects/project-ssh-key.md %}) which you'll find under _Project Settings > General_. You can use this key to grant access to your storage provider for Codeship or [upload files through SFTP]({{ site.baseurl }}{% link _basic/continuous-deployment/deployment-with-ftp-sftp-scp.md %}).


text:
@interface NTAlbumViewController : NTSuperViewController<UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *albums;

@end


text:
package org.hisp.dhis.program;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.AccessLevel;
import org.hisp.dhis.common.AuditType;
import org.hisp.dhis.common.CodeGenerator;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.common.OrganisationUnitSelectionMode;
import org.hisp.dhis.event.EventStatus;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.program.notification.ProgramNotificationEventType;
import org.hisp.dhis.program.notification.ProgramNotificationPublisher;
import org.hisp.dhis.programrule.engine.TrackedEntityInstanceEnrolledEvent;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.trackedentity.TrackedEntityType;
import org.hisp.dhis.trackedentity.TrackedEntityTypeService;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.hisp.dhis.common.OrganisationUnitSelectionMode.ACCESSIBLE;
import static org.hisp.dhis.common.OrganisationUnitSelectionMode.ALL;
import static org.hisp.dhis.common.OrganisationUnitSelectionMode.CHILDREN;

/**
 * @author Abyot Asalefew
 */
@Transactional
public class DefaultProgramInstanceService
    implements ProgramInstanceService
{
    private static final Log log = LogFactory.getLog( DefaultProgramInstanceService.class );

    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    @Autowired
    private ProgramInstanceStore programInstanceStore;

    @Autowired
    private ProgramStageInstanceStore programStageInstanceStore;

    @Autowired
    private ProgramService programService;

    @Autowired
    private CurrentUserService currentUserService;

    @Autowired
    private TrackedEntityInstanceService trackedEntityInstanceService;

    @Autowired
    private OrganisationUnitService organisationUnitService;

    @Autowired
    private TrackedEntityTypeService trackedEntityTypeService;

    @Autowired
    private ProgramNotificationPublisher programNotificationPublisher;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private ProgramInstanceAuditService programInstanceAuditService;

    // -------------------------------------------------------------------------
    // Implementation methods
    // -------------------------------------------------------------------------

    @Override
    public int addProgramInstance( ProgramInstance programInstance )
    {
        programInstanceStore.save( programInstance );
        return programInstance.getId();
    }

    @Override
    public void deleteProgramInstance( ProgramInstance programInstance )
    {
        deleteProgramInstance( programInstance, false );
    }

    @Override
    public void deleteProgramInstance( ProgramInstance programInstance, boolean forceDelete )
    {
        if ( forceDelete )
        {
            programInstanceStore.delete( programInstance );
        }
        else
        {
            programInstance.setDeleted( true );
            programInstance.setStatus( ProgramStatus.CANCELLED );
            programInstanceStore.update( programInstance );
        }
    }

    @Override
    public ProgramInstance getProgramInstance( int id )
    {
        ProgramInstance programInstance = programInstanceStore.get( id );

        User user = currentUserService.getCurrentUser();

        if ( user != null )
        {
            addProgramInstanceAudit( programInstance, user.getUsername() );
        }

        return programInstance;
    }

    @Override
    public ProgramInstance getProgramInstance( String uid )
    {
        ProgramInstance programInstance = programInstanceStore.getByUid( uid );

        User user = currentUserService.getCurrentUser();

        if ( user != null )
        {
            addProgramInstanceAudit( programInstance, user.getUsername() );
        }

        return programInstance;
    }

    @Override
    public boolean programInstanceExists( String uid )
    {
        return programInstanceStore.exists( uid );
    }

    @Override
    public boolean programInstanceExistsIncludingDeleted( String uid )
    {
        return programInstanceStore.existsIncludingDeleted( uid );
    }

    @Override
    public void updateProgramInstance( ProgramInstance programInstance )
    {
        programInstanceStore.update( programInstance );
    }

    @Override
    public ProgramInstanceQueryParams getFromUrl( Set<String> ou, OrganisationUnitSelectionMode ouMode, Date lastUpdated, String program, ProgramStatus programStatus,
        Date programStartDate, Date programEndDate, String trackedEntityType, String trackedEntityInstance, Boolean followUp, Integer page, Integer pageSize,
        boolean totalPages, boolean skipPaging, boolean includeDeleted )
    {
        ProgramInstanceQueryParams params = new ProgramInstanceQueryParams();

        if ( ou != null )
        {
            for ( String orgUnit : ou )
            {
                OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit( orgUnit );

                if ( organisationUnit == null )
                {
                    throw new IllegalQueryException( "Organisation unit does not exist: " + orgUnit );
                }

                params.getOrganisationUnits().add( organisationUnit );
            }
        }

        Program pr = program != null ? programService.getProgram( program ) : null;

        if ( program != null && pr == null )
        {
            throw new IllegalQueryException( "Program does not exist: " + program );
        }

        TrackedEntityType te = trackedEntityType != null ? trackedEntityTypeService.getTrackedEntityType( trackedEntityType ) : null;

        if ( trackedEntityType != null && te == null )
        {
            throw new IllegalQueryException( "Tracked entity does not exist: " + program );
        }

        TrackedEntityInstance tei = trackedEntityInstance != null ? trackedEntityInstanceService.getTrackedEntityInstance( trackedEntityInstance ) : null;

        if ( trackedEntityInstance != null && tei == null )
        {
            throw new IllegalQueryException( "Tracked entity instance does not exist: " + program );
        }

        params.setProgram( pr );
        params.setProgramStatus( programStatus );
        params.setFollowUp( followUp );
        params.setLastUpdated( lastUpdated );
        params.setProgramStartDate( programStartDate );
        params.setProgramEndDate( programEndDate );
        params.setTrackedEntityType( te );
        params.setTrackedEntityInstance( tei );
        params.setOrganisationUnitMode( ouMode );
        params.setPage( page );
        params.setPageSize( pageSize );
        params.setTotalPages( totalPages );
        params.setSkipPaging( skipPaging );
        params.setIncludeDeleted( includeDeleted );

        return params;
    }

    // TODO consider security
    @Override
    public List<ProgramInstance> getProgramInstances( ProgramInstanceQueryParams params )
    {
        decideAccess( params );
        validate( params );

        User user = currentUserService.getCurrentUser();

        if ( user != null && params.isOrganisationUnitMode( OrganisationUnitSelectionMode.ACCESSIBLE ) )
        {
            params.setOrganisationUnits( user.getDataViewOrganisationUnitsWithFallback() );
            params.setOrganisationUnitMode( OrganisationUnitSelectionMode.DESCENDANTS );
        }
        else if ( params.isOrganisationUnitMode( CHILDREN ) )
        {
            Set<OrganisationUnit> organisationUnits = new HashSet<>();
            organisationUnits.addAll( params.getOrganisationUnits() );

            for ( OrganisationUnit organisationUnit : params.getOrganisationUnits() )
            {
                organisationUnits.addAll( organisationUnit.getChildren() );
            }

            params.setOrganisationUnits( organisationUnits );
        }

        if ( !params.isPaging() && !params.isSkipPaging() )
        {
            params.setDefaultPaging();
        }

        List<ProgramInstance> programInstances = programInstanceStore.getProgramInstances( params );

        if ( user != null )
        {
            addProrgamInstanceAudits( programInstances, user.getUsername() );
        }

        return programInstances;
    }

    @Override
    public int countProgramInstances( ProgramInstanceQueryParams params )
    {
        decideAccess( params );
        validate( params );

        User user = currentUserService.getCurrentUser();

        if ( user != null && params.isOrganisationUnitMode( OrganisationUnitSelectionMode.ACCESSIBLE ) )
        {
            params.setOrganisationUnits( user.getDataViewOrganisationUnitsWithFallback() );
            params.setOrganisationUnitMode( OrganisationUnitSelectionMode.DESCENDANTS );
        }
        else if ( params.isOrganisationUnitMode( CHILDREN ) )
        {
            Set<OrganisationUnit> organisationUnits = new HashSet<>();
            organisationUnits.addAll( params.getOrganisationUnits() );

            for ( OrganisationUnit organisationUnit : params.getOrganisationUnits() )
            {
                organisationUnits.addAll( organisationUnit.getChildren() );
            }

            params.setOrganisationUnits( organisationUnits );
        }

        params.setSkipPaging( true );

        return programInstanceStore.countProgramInstances( params );
    }

    @Override
    public void decideAccess( ProgramInstanceQueryParams params )
    {
        // TODO Check access for current user
    }

    @Override
    public void validate( ProgramInstanceQueryParams params ) throws IllegalQueryException
    {
        String violation = null;

        if ( params == null )
        {
            throw new IllegalQueryException( "Params cannot be null" );
        }

        User user = currentUserService.getCurrentUser();

        if ( !params.hasOrganisationUnits() && !(params.isOrganisationUnitMode( ALL ) || params.isOrganisationUnitMode( ACCESSIBLE )) )
        {
            violation = "At least one organisation unit must be specified";
        }

        if ( params.isOrganisationUnitMode( ACCESSIBLE ) && (user == null || !user.hasDataViewOrganisationUnitWithFallback()) )
        {
            violation = "Current user must be associated with at least one organisation unit when selection mode is ACCESSIBLE";
        }

        if ( params.hasProgram() && params.hasTrackedEntityType() )
        {
            violation = "Program and tracked entity cannot be specified simultaneously";
        }

        if ( params.hasProgramStatus() && !params.hasProgram() )
        {
            violation = "Program must be defined when program status is defined";
        }

        if ( params.hasFollowUp() && !params.hasProgram() )
        {
            violation = "Program must be defined when follow up status is defined";
        }

        if ( params.hasProgramStartDate() && !params.hasProgram() )
        {
            violation = "Program must be defined when program start date is specified";
        }

        if ( params.hasProgramEndDate() && !params.hasProgram() )
        {
            violation = "Program must be defined when program end date is specified";
        }

        if ( violation != null )
        {
            log.warn( "Validation failed: " + violation );

            throw new IllegalQueryException( violation );
        }
    }

    @Override
    public List<ProgramInstance> getProgramInstances( Program program )
    {
        return programInstanceStore.get( program );
    }

    @Override
    public List<ProgramInstance> getProgramInstances( Program program, ProgramStatus status )
    {
        return programInstanceStore.get( program, status );
    }

    @Override
    public List<ProgramInstance> getProgramInstances( TrackedEntityInstance entityInstance, Program program, ProgramStatus status )
    {
        return programInstanceStore.get( entityInstance, program, status );
    }

    @Override
    public ProgramInstance enrollTrackedEntityInstance( TrackedEntityInstance trackedEntityInstance, Program program,
        Date enrollmentDate, Date incidentDate, OrganisationUnit organisationUnit )
    {
        return enrollTrackedEntityInstance( trackedEntityInstance, program, enrollmentDate,
            incidentDate, organisationUnit, CodeGenerator.generateUid() );
    }

    @Override
    public ProgramInstance enrollTrackedEntityInstance( TrackedEntityInstance trackedEntityInstance,
        Program program, Date enrollmentDate, Date incidentDate, OrganisationUnit organisationUnit, String uid )
    {
        // ---------------------------------------------------------------------
        // Add program instance
        // ---------------------------------------------------------------------

        if ( program.getTrackedEntityType() != null && !program.getTrackedEntityType().equals( trackedEntityInstance.getTrackedEntityType() ) )
        {
            throw new IllegalQueryException( "Tracked entity instance must have same tracked entity as program: " + program.getUid() );
        }

        ProgramInstance programInstance = new ProgramInstance();
        programInstance.setUid( CodeGenerator.isValidUid( uid ) ? uid : CodeGenerator.generateUid() );
        programInstance.setOrganisationUnit( organisationUnit );
        programInstance.enrollTrackedEntityInstance( trackedEntityInstance, program );

        if ( enrollmentDate != null )
        {
            programInstance.setEnrollmentDate( enrollmentDate );
        }
        else
        {
            programInstance.setEnrollmentDate( new Date() );
        }

        if ( incidentDate != null )
        {
            programInstance.setIncidentDate( incidentDate );
        }
        else
        {
            programInstance.setIncidentDate( new Date() );
        }

        programInstance.setStatus( ProgramStatus.ACTIVE );
        addProgramInstance( programInstance );

        // -----------------------------------------------------------------
        // Send enrollment notifications (if any)
        // -----------------------------------------------------------------

        programNotificationPublisher.publishEnrollment( programInstance, ProgramNotificationEventType.PROGRAM_ENROLLMENT );

        eventPublisher.publishEvent( new TrackedEntityInstanceEnrolledEvent( this, programInstance ) );

        // -----------------------------------------------------------------
        // Update ProgramInstance and TEI
        // -----------------------------------------------------------------

        updateProgramInstance( programInstance );
        trackedEntityInstanceService.updateTrackedEntityInstance( trackedEntityInstance );

        return programInstance;
    }

    @Override
    public boolean canAutoCompleteProgramInstanceStatus( ProgramInstance programInstance )
    {
        Set<ProgramStageInstance> programStageInstances = new HashSet<>( programInstance.getProgramStageInstances() );
        Set<ProgramStage> programStages = new HashSet<>();

        for ( ProgramStageInstance programStageInstance : programStageInstances )
        {
            if ( (!programStageInstance.isCompleted() && programStageInstance.getStatus() != EventStatus.SKIPPED)
                || programStageInstance.getProgramStage().getRepeatable() )
            {
                return false;
            }

            programStages.add( programStageInstance.getProgramStage() );
        }

        return programStages.size() == programInstance.getProgram().getProgramStages().size();
    }

    @Override
    public void completeProgramInstanceStatus( ProgramInstance programInstance )
    {
        // ---------------------------------------------------------------------
        // Send sms-message when to completed the program
        // ---------------------------------------------------------------------

        programNotificationPublisher.publishEnrollment( programInstance, ProgramNotificationEventType.PROGRAM_COMPLETION );

        eventPublisher.publishEvent( new TrackedEntityInstanceEnrolledEvent( this, programInstance ) );

        // -----------------------------------------------------------------
        // Update program-instance
        // -----------------------------------------------------------------

        programInstance.setStatus( ProgramStatus.COMPLETED );
        programInstance.setEndDate( new Date() );
        programInstance.setCompletedBy( currentUserService.getCurrentUsername() );

        updateProgramInstance( programInstance );
    }

    @Override
    public void cancelProgramInstanceStatus( ProgramInstance programInstance )
    {
        // ---------------------------------------------------------------------
        // Set status of the program-instance
        // ---------------------------------------------------------------------

        Calendar today = Calendar.getInstance();
        PeriodType.clearTimeOfDay( today );
        Date currentDate = today.getTime();

        programInstance.setEndDate( currentDate );
        programInstance.setStatus( ProgramStatus.CANCELLED );
        updateProgramInstance( programInstance );

        // ---------------------------------------------------------------------
        // Set statuses of the program-stage-instances
        // ---------------------------------------------------------------------

        for ( ProgramStageInstance programStageInstance : programInstance.getProgramStageInstances() )
        {
            if ( programStageInstance.getExecutionDate() == null )
            {
                // -------------------------------------------------------------
                // Set status as skipped for overdue events, or delete
                // -------------------------------------------------------------

                if ( programStageInstance.getDueDate().before( currentDate ) )
                {
                    programStageInstance.setStatus( EventStatus.SKIPPED );
                    programStageInstanceStore.update( programStageInstance );
                }
                else
                {
                    programStageInstanceStore.delete( programStageInstance );
                }
            }
        }
    }

    @Override
    public void incompleteProgramInstanceStatus( ProgramInstance programInstance )
    {
        Program program = programInstance.getProgram();

        TrackedEntityInstance tei = programInstance.getEntityInstance();

        if ( getProgramInstances( tei, program, ProgramStatus.ACTIVE ).size() > 0 )
        {
            log.warn( "Program has another active enrollment going on. Not possible to incomplete" );

            throw new IllegalQueryException( "Program has another active enrollment going on. Not possible to incomplete" );
        }

        // -----------------------------------------------------------------
        // Update program-instance
        // -----------------------------------------------------------------

        programInstance.setStatus( ProgramStatus.ACTIVE );

        updateProgramInstance( programInstance );
    }

    private void addProgramInstanceAudit( ProgramInstance programInstance, String accessedBy )
    {
        if ( programInstance != null && programInstance.getProgram().getAccessLevel() != null && programInstance.getProgram().getAccessLevel() != AccessLevel.OPEN && accessedBy != null )
        {
            ProgramInstanceAudit programInstanceAudit = new ProgramInstanceAudit( programInstance, accessedBy, AuditType.READ );

            programInstanceAuditService.addProgramInstanceAudit( programInstanceAudit );
        }
    }

    private void addProrgamInstanceAudits( List<ProgramInstance> programInstances, String accessedBy )
    {
        for ( ProgramInstance programInstance : programInstances )
        {
            addProgramInstanceAudit( programInstance, accessedBy );
        }
    }
}


text:
// Guids.cs
// MUST match guids.h
using System;

namespace EgorBo.GradleBindings_VisualStudio
{
    static class GuidList
    {
        public const string guidGradleBindings_VisualStudioPkgString = "94487fc6-72c6-448b-a460-5e52f7ea2b92";
        public const string guidGradleBindings_VisualStudioCmdSetString = "82484a7f-647f-41c1-9f41-29b193185a8d";

        public static readonly Guid guidGradleBindings_VisualStudioCmdSet = new Guid(guidGradleBindings_VisualStudioCmdSetString);
    };
}


text:
package org.wildfly.swarm.container.runtime.cdi;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.enterprise.context.ContextNotActiveException;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Vetoed;
import javax.enterprise.inject.spi.BeanManager;

import org.jboss.shrinkwrap.api.Archive;
import org.wildfly.swarm.spi.runtime.annotations.DeploymentScoped;

/**
 * @author Martin Kouba
 */
@Vetoed
public class DeploymentContextImpl implements DeploymentContext {

    // It's a normal scope so there may be no more than one mapped instance per contextual type per thread
    private final ThreadLocal<Map<Contextual<?>, ContextualInstance<?>>> currentContext = new ThreadLocal<>();

    private final ThreadLocal<Archive> currentArchive = new ThreadLocal<>();

    private final ThreadLocal<String> currentName = new ThreadLocal<>();

    private final ThreadLocal<Boolean> implicitDeployment = new ThreadLocal<>();

    public Class<? extends Annotation> getScope() {
        return DeploymentScoped.class;
    }

    @SuppressWarnings("unchecked")
    public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
        Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

        if (ctx == null) {
            // Thread local not set - context is not active!
            throw new ContextNotActiveException();
        }

        ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

        if (instance == null && creationalContext != null) {
            // Bean instance does not exist - create one if we have CreationalContext
            instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
            ctx.put(contextual, instance);
        }

        return instance != null ? instance.get() : null;
    }

    public <T> T get(Contextual<T> contextual) {
        return get(contextual, null);
    }

    public boolean isActive() {
        return currentContext.get() != null;
    }

    public void destroy(Contextual<?> contextual) {
        Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();
        if (ctx == null) {
            return;
        }
        ctx.remove(contextual);
    }

    public void activate(Archive archive, String asName, boolean implicit) {
        currentContext.set(new HashMap<>());
        currentArchive.set(archive);
        currentName.set(asName);
        implicitDeployment.set(implicit);
    }

    public void deactivate() {
        Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();
        if (ctx == null) {
            return;
        }
        for (ContextualInstance<?> instance : ctx.values()) {
            try {
                instance.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        ctx.clear();
        currentContext.remove();
        currentArchive.set(null);
        currentName.set(null);
    }

    public Archive getCurrentArchive() {
        return currentArchive.get();
    }

    public String getCurrentName() {
        return currentName.get();
    }

    @Override
    public boolean isImplicit() {
        return implicitDeployment.get();
    }

    /**
     * We use this injectable version to detect the original "activator", so that we can skip deactivation during {@link #deactivate()} if needed.
     *
     * @author Martin Kouba
     */
    static final class InjectableDeploymentContext implements DeploymentContext {

        private static final Logger LOGGER = Logger.getLogger(InjectableDeploymentContext.class.getName());

        private final DeploymentContext delegate;

        private final BeanManager beanManager;

        private boolean isActivator;

        /**
         * @param delegate
         * @param beanManager
         */
        InjectableDeploymentContext(DeploymentContext delegate, BeanManager beanManager) {
            this.delegate = delegate;
            this.beanManager = beanManager;
            this.isActivator = false;
        }

        @Override
        public void destroy(Contextual<?> contextual) {
            delegate.destroy(contextual);
        }

        @Override
        public Class<? extends Annotation> getScope() {
            return delegate.getScope();
        }

        @Override
        public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
            return delegate.get(contextual);
        }

        @Override
        public <T> T get(Contextual<T> contextual) {
            return delegate.get(contextual);
        }

        @Override
        public boolean isActive() {
            return delegate.isActive();
        }

        @Override
        public void activate(Archive archive, String asName, boolean implicit) {
            try {
                beanManager.getContext(delegate.getScope());
                LOGGER.info("Command context already active");
            } catch (ContextNotActiveException e) {
                // Only activate the context if not already active
                delegate.activate(archive, asName, implicit);
                isActivator = true;
            }
        }

        @Override
        public void deactivate() {
            if (isActivator) {
                delegate.deactivate();
            } else {
                LOGGER.info("Command context not activated by this bean");
            }
        }

        @Override
        public Archive getCurrentArchive() {
            return this.delegate.getCurrentArchive();
        }

        @Override
        public String getCurrentName() {
            return this.delegate.getCurrentName();
        }

        @Override
        public boolean isImplicit() {
            return this.delegate.isImplicit();
        }
    }

    /**
     * This wrapper allows to create and destroy a bean instance properly.
     *
     * @param <T>
     * @author Martin Kouba
     */
    static final class ContextualInstance<T> {

        private final T value;

        private final CreationalContext<T> creationalContext;

        private final Contextual<T> contextual;

        /**
         * @param instance
         * @param creationalContext
         * @param contextual
         */
        ContextualInstance(T instance, CreationalContext<T> creationalContext, Contextual<T> contextual) {
            this.value = instance;
            this.creationalContext = creationalContext;
            this.contextual = contextual;
        }

        T get() {
            return value;
        }

        Contextual<T> getContextual() {
            return contextual;
        }

        void destroy() {
            contextual.destroy(value, creationalContext);
        }

    }

}


text:
package com.quexten.ravtech.util;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;

public class FileUtil {

	public static Array<FileHandle> getChildrenFiles(FileHandle handle) {
		Array<FileHandle> files = new Array<FileHandle>();
		FileHandle[] children = handle.list();
		for(int i = 0; i < children.length; i++)
			if(children[i].isDirectory())
				files.addAll(getChildrenFiles(children[i]));
			else
				files.add(children[i]);
		return files;
	}

}


text:
"""Turn tasks with DClaw robots.

This is a single rotation of an object from an initial angle to a target angle.
"""

import abc
import collections
from typing import Dict, Optional, Sequence

import numpy as np
from transforms3d.euler import euler2quat

from robel.components.robot.dynamixel_robot import DynamixelRobotState
from robel.dclaw.base_env import BaseDClawObjectEnv
from robel.simulation.randomize import SimRandomizer
from robel.utils.configurable import configurable
from robel.utils.resources import get_asset_path

# The observation keys that are concatenated as the environment observation.
DEFAULT_OBSERVATION_KEYS = (
    'claw_qpos',
    'object_x',
    'object_y',
    'last_action',
    'target_error',
)

# Reset pose for the claw joints.
RESET_POSE = [0, -np.pi / 3, np.pi / 3] * 3

DCLAW3_ASSET_PATH = 'robel/dclaw/assets/dclaw3xh_valve3_v0.xml'

class BaseDClawTurn(BaseDClawObjectEnv, metaclass=abc.ABCMeta):
    """Shared logic for DClaw turn tasks."""

    def __init__(self,
                 asset_path: str = DCLAW3_ASSET_PATH,
                 observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS,
                 frame_skip: int = 40,
                 interactive: bool = False,
                 success_threshold: float = 0.1,
                 **kwargs):
        """Initializes the environment.

        Args:
            asset_path: The XML model file to load.
            observation_keys: The keys in `get_obs_dict` to concatenate as the
                observations returned by `step` and `reset`.
            frame_skip: The number of simulation steps per environment step.
            interactive: If True, allows the hardware guide motor to freely
                rotate and its current angle is used as the goal.
            success_threshold: The difference threshold (in radians) of the
                object position and the goal position within which we consider
                as a sucesss.
        """
        super().__init__(
            sim_model=get_asset_path(asset_path),
            observation_keys=observation_keys,
            frame_skip=frame_skip,
            **kwargs)

        self._interactive = interactive
        self._success_threshold = success_threshold
        self._desired_claw_pos = RESET_POSE

        self._target_bid = self.model.body_name2id('target')

        # The following are modified (possibly every reset) by subclasses.
        self._initial_object_pos = 0
        self._initial_object_vel = 0
        self._set_target_object_pos(0)

    def _reset(self):
        """Resets the environment."""
        self._reset_dclaw_and_object(
            claw_pos=RESET_POSE,
            object_pos=self._initial_object_pos,
            object_vel=self._initial_object_vel,
            guide_pos=self._target_object_pos)

        # Disengage the motor.
        if self._interactive and self.robot.is_hardware:
            self.robot.set_motors_engaged('guide', False)

    def _step(self, action: np.ndarray):
        """Applies an action to the robot."""
        self.robot.step({
            'dclaw': action,
            'guide': np.atleast_1d(self._target_object_pos),
        })

    def get_obs_dict(self) -> Dict[str, np.ndarray]:
        """Returns the current observation of the environment.

        Returns:
            A dictionary of observation values. This should be an ordered
            dictionary if `observation_keys` isn't set.
        """
        claw_state, object_state, guide_state = self.robot.get_state(
            ['dclaw', 'object', 'guide'])

        # If in interactive mode, use the guide motor position as the goal.
        if self._interactive:
            self._set_target_object_pos(guide_state.qpos)

        # Calculate the signed angle difference to the target in [-pi, pi].
        target_error = self._target_object_pos - object_state.qpos
        target_error = np.mod(target_error + np.pi, 2 * np.pi) - np.pi

        obs_dict = collections.OrderedDict((
            ('claw_qpos', claw_state.qpos),
            ('claw_qvel', claw_state.qvel),
            ('object_x', np.cos(object_state.qpos)),
            ('object_y', np.sin(object_state.qpos)),
            ('object_qvel', object_state.qvel),
            ('last_action', self._get_last_action()),
            ('target_error', target_error),
        ))
        # Add hardware-specific state if present.
        if isinstance(claw_state, DynamixelRobotState):
            obs_dict['claw_current'] = claw_state.current

        return obs_dict

    def get_reward_dict(
            self,
            action: np.ndarray,
            obs_dict: Dict[str, np.ndarray],
    ) -> Dict[str, np.ndarray]:
        """Returns the reward for the given action and observation."""
        target_dist = np.abs(obs_dict['target_error'])
        claw_vel = obs_dict['claw_qvel']

        reward_dict = collections.OrderedDict((
            # Penalty for distance away from goal.
            ('target_dist_cost', -5 * target_dist),
            # Penalty for difference with nomimal pose.
            ('pose_diff_cost',
             -1 * np.linalg.norm(obs_dict['claw_qpos'] - self._desired_claw_pos)
            ),
            # Penality for high velocities.
            ('joint_vel_cost',
             -1 * np.linalg.norm(claw_vel[np.abs(claw_vel) >= 0.5])),

            # Reward for close proximity with goal.
            ('bonus_small', 10 * (target_dist < 0.25)),
            ('bonus_big', 50 * (target_dist < 0.10)),
        ))
        return reward_dict

    def get_score_dict(
            self,
            obs_dict: Dict[str, np.ndarray],
            reward_dict: Dict[str, np.ndarray],
    ) -> Dict[str, np.ndarray]:
        """Returns a standardized measure of success for the environment."""
        target_dist = np.abs(obs_dict['target_error'])
        score_dict = collections.OrderedDict((
            ('points', 1.0 - target_dist / np.pi),
            ('success', target_dist < self._success_threshold),
        ))
        score_dict.update(
            self._get_safety_scores(
                pos=obs_dict['claw_qpos'],
                vel=obs_dict['claw_qvel'],
                current=obs_dict.get('claw_current'),
            ))
        return score_dict

    def _set_target_object_pos(self, target_pos: float,
                               unbounded: bool = False):
        """Sets the goal angle to the given position."""
        # Modulo to [-pi, pi].
        if not unbounded:
            target_pos = np.mod(target_pos + np.pi, 2 * np.pi) - np.pi
        self._target_object_pos = np.asarray(target_pos, dtype=np.float32)

        # Mark the target position in sim.
        # WARNING: euler2quat will mutate a passed numpy array.
        self.model.body_quat[self._target_bid] = euler2quat(
            0, 0, float(target_pos))

@configurable(pickleable=True)
class DClawTurnFixed(BaseDClawTurn):
    """Turns the object with a fixed initial and fixed target position."""

    def _reset(self):
        # Turn from 0 degrees to 180 degrees.
        self._initial_object_pos = 0
        self._set_target_object_pos(np.pi)
        super()._reset()

@configurable(pickleable=True)
class DClawTurnRandom(BaseDClawTurn):
    """Turns the object with a random initial and random target position."""

    def _reset(self):
        # Initial position is +/- 60 degrees.
        self._initial_object_pos = self.np_random.uniform(
            low=-np.pi / 3, high=np.pi / 3)
        # Target position is 180 +/- 60 degrees.
        self._set_target_object_pos(
            np.pi + self.np_random.uniform(low=-np.pi / 3, high=np.pi / 3))
        super()._reset()

@configurable(pickleable=True)
class DClawTurnRandomDynamics(DClawTurnRandom):
    """Turns the object with a random initial and random target position.

    The dynamics of the simulation are randomized each episode.
    """

    def __init__(self,
                 *args,
                 sim_observation_noise: Optional[float] = 0.05,
                 **kwargs):
        super().__init__(
            *args, sim_observation_noise=sim_observation_noise, **kwargs)
        self._randomizer = SimRandomizer(self)
        self._dof_indices = (
            self.robot.get_config('dclaw').qvel_indices.tolist() +
            self.robot.get_config('object').qvel_indices.tolist())

    def _reset(self):
        # Randomize joint dynamics.
        self._randomizer.randomize_dofs(
            self._dof_indices,
            damping_range=(0.005, 0.1),
            friction_loss_range=(0.001, 0.005),
        )
        self._randomizer.randomize_actuators(
            all_same=True,
            kp_range=(1, 3),
        )
        # Randomize friction on all geoms in the scene.
        self._randomizer.randomize_geoms(
            all_same=True,
            friction_slide_range=(0.8, 1.2),
            friction_spin_range=(0.003, 0.007),
            friction_roll_range=(0.00005, 0.00015),
        )
        self._randomizer.randomize_bodies(
            ['mount'],
            position_perturb_range=(-0.01, 0.01),
        )
        self._randomizer.randomize_geoms(
            ['mount'],
            color_range=(0.2, 0.9),
        )
        self._randomizer.randomize_geoms(
            parent_body_names=['valve'],
            color_range=(0.2, 0.9),
        )
        super()._reset()