text:
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Schema;
using NUnit.Framework;

namespace Newtonsoft.Json.Tests.Schema
{
  public class JsonSchemaTests : TestFixtureBase
  {
    [Test]
    public void Extends()
    {
      string json;
      JsonSchemaResolver resolver = new JsonSchemaResolver();

      json = @"{
  ""id"":""first"",
  ""type"":""object"",
  ""additionalProperties"":{}
}";

      JsonSchema first = JsonSchema.Parse(json, resolver);

      json =
        @"{
  ""id"":""second"",
  ""type"":""object"",
  ""extends"":{""$ref"":""first""},
  ""additionalProperties"":{""type"":""string""}
}";

      JsonSchema second = JsonSchema.Parse(json, resolver);
      Assert.AreEqual(first, second.Extends);

      json =
        @"{
  ""id"":""third"",
  ""type"":""object"",
  ""extends"":{""$ref"":""second""},
  ""additionalProperties"":false
}";

      JsonSchema third = JsonSchema.Parse(json, resolver);
      Assert.AreEqual(second, third.Extends);
      Assert.AreEqual(first, third.Extends.Extends);

      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      third.WriteTo(jsonWriter, resolver);

      string writtenJson = writer.ToString();
      Assert.AreEqual(@"{
  ""id"": ""third"",
  ""type"": ""object"",
  ""additionalProperties"": false,
  ""extends"": {
    ""$ref"": ""second""
  }
}", writtenJson);

      StringWriter writer1 = new StringWriter();
      JsonTextWriter jsonWriter1 = new JsonTextWriter(writer1);
      jsonWriter1.Formatting = Formatting.Indented;

      third.WriteTo(jsonWriter1);

      writtenJson = writer1.ToString();
      Assert.AreEqual(@"{
  ""id"": ""third"",
  ""type"": ""object"",
  ""additionalProperties"": false,
  ""extends"": {
    ""id"": ""second"",
    ""type"": ""object"",
    ""additionalProperties"": {
      ""type"": ""string""
    },
    ""extends"": {
      ""id"": ""first"",
      ""type"": ""object"",
      ""additionalProperties"": {}
    }
  }
}", writtenJson);
    }
    [Test]
    public void WriteTo_AdditionalProperties()
    {
      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      JsonSchema schema = JsonSchema.Parse(@"{
  ""description"":""AdditionalProperties"",
  ""type"":[""string"", ""integer""],
  ""additionalProperties"":{""type"":[""object"", ""boolean""]}
}");

      schema.WriteTo(jsonWriter);

      string json = writer.ToString();

      Assert.AreEqual(@"{
  ""description"": ""AdditionalProperties"",
  ""type"": [
    ""string"",
    ""integer""
  ],
  ""additionalProperties"": {
    ""type"": [
      ""boolean"",
      ""object""
    ]
  }
}", json);
    }

    [Test]
    public void WriteTo_Properties()
    {
      JsonSchema schema = JsonSchema.Parse(@"{
  ""description"":""A person"",
  ""type"":""object"",
  ""properties"":
  {
    ""name"":{""type"":""string""},
    ""hobbies"":
    {
      ""type"":""array"",
      ""items"": {""type"":""string""}
    }
  }
}");

      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      schema.WriteTo(jsonWriter);

      string json = writer.ToString();

      Assert.AreEqual(@"{
  ""description"": ""A person"",
  ""type"": ""object"",
  ""properties"": {
    ""name"": {
      ""type"": ""string""
    },
    ""hobbies"": {
      ""type"": ""array"",
      ""items"": {
        ""type"": ""string""
      }
    }
  }
}", json);

    }

    [Test]
    public void WriteTo_Enum()
    {
      JsonSchema schema = JsonSchema.Parse(@"{
  ""description"":""Type"",
  ""type"":[""string"",""array""],
  ""items"":{},
  ""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""]
}");

      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      schema.WriteTo(jsonWriter);

      string json = writer.ToString();

      Assert.AreEqual(@"{
  ""description"": ""Type"",
  ""type"": [
    ""string"",
    ""array""
  ],
  ""items"": {},
  ""enum"": [
    ""string"",
    ""object"",
    ""array"",
    ""boolean"",
    ""number"",
    ""integer"",
    ""null"",
    ""any""
  ]
}", json);
    }

    [Test]
    public void WriteTo_CircularReference()
    {
      string json = @"{
  ""id"":""CircularReferenceArray"",
  ""description"":""CircularReference"",
  ""type"":[""array""],
  ""items"":{""$ref"":""CircularReferenceArray""}
}";

      JsonSchema schema = JsonSchema.Parse(json);

      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      schema.WriteTo(jsonWriter);

      string writtenJson = writer.ToString();

      Assert.AreEqual(@"{
  ""id"": ""CircularReferenceArray"",
  ""description"": ""CircularReference"",
  ""type"": ""array"",
  ""items"": {
    ""$ref"": ""CircularReferenceArray""
  }
}", writtenJson);
    }

    [Test]
    public void WriteTo_DisallowMultiple()
    {
      JsonSchema schema = JsonSchema.Parse(@"{
  ""description"":""Type"",
  ""type"":[""string"",""array""],
  ""items"":{},
  ""disallow"":[""string"",""object"",""array""]
}");

      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      schema.WriteTo(jsonWriter);

      string json = writer.ToString();

      Assert.AreEqual(@"{
  ""description"": ""Type"",
  ""type"": [
    ""string"",
    ""array""
  ],
  ""items"": {},
  ""disallow"": [
    ""string"",
    ""object"",
    ""array""
  ]
}", json);
    }

    [Test]
    public void WriteTo_DisallowSingle()
    {
      JsonSchema schema = JsonSchema.Parse(@"{
  ""description"":""Type"",
  ""type"":[""string"",""array""],
  ""items"":{},
  ""disallow"":""any""
}");

      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      schema.WriteTo(jsonWriter);

      string json = writer.ToString();

      Assert.AreEqual(@"{
  ""description"": ""Type"",
  ""type"": [
    ""string"",
    ""array""
  ],
  ""items"": {},
  ""disallow"": ""any""
}", json);
    }

    [Test]
    public void WriteTo_MultipleItems()
    {
      JsonSchema schema = JsonSchema.Parse(@"{
  ""items"":[{},{}]
}");

      StringWriter writer = new StringWriter();
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      jsonWriter.Formatting = Formatting.Indented;

      schema.WriteTo(jsonWriter);

      string json = writer.ToString();

      Assert.AreEqual(@"{
  ""items"": [
    {},
    {}
  ]
}", json);
    }
  }
}


text:
        <canvas id="volunteersByMonth" height="50"></canvas>

             Διαθέσιμοι |
             Υπό ένταξη|
             Ενεργοί |
             Νέοι

@section('footerScripts')

@append

redpajama_set_name: RedPajamaGithub


text:
"""
Tests of io.asciisignalio
"""

from __future__ import division

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from neo.io import AsciiSignalIO
import numpy

from neo.test.io.common_io_test import BaseTestIO

class TestAsciiSignalIO(BaseTestIO, unittest.TestCase, ):
    ioclass = AsciiSignalIO
    files_to_download = [ 'File_asciisignal_1.asc',
                            'File_asciisignal_2.txt',
                            'File_asciisignal_3.txt',
                            ]
    files_to_test = files_to_download

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


text:
<?php
/**
 * ガチャやアイテム販売などに用いる抽選方式クラス
 *
 * @author main
 *
 */
abstract class Component_Lottery_MethodAbstract extends ServiceAbstract
{
  /*
   * 仕様
   *
   * LotteryManagerからlotteryIdが渡されたあとの抽選方式の差を吸収するためのクラス群。
   * といっても結局のところ、基本的にはロットの数量を規定するか否かの違いしかなく、
   *
   * する   …… PackageMethod
   * しない …… NormalMethod
   *
   * である。ただしPackageMethodにもプレイヤー一人の中でのPackageと
   * 全プレイヤー共通でのPackageが存在する。そこで
   *
   * PackageFull
   * PackagePersonal
   *
   * となる。
   *
   * 実はあともう一つ、カードの価値を基準とした簡易版を作ろうと思っていたのだが、
   * 「抽選結果の排出物は必ずgoods_set_idを持ち、またいかなる場合も一度は
   *   player_goodsテーブルを通らなければならない」というルールで実装するにあたって
   * 目的であった手間の省略が困難になったためオミットした。
   *
   * したがって、結論としては、Methodの数は以下
   *
   * ・Normal
   * ・PackagePersonal
   * ・PackageFull
   *
   * の3つである。
   *
   */

  /**
   * 抽選を実行する
   *
   * MEMO: あえてfinalをつけているのは、この処理の流れ自体は共通でやっていこうぜ、くらいの意図があるから。
   */
  final public function castLots($playerId, Entity_Lottery $lottery, $extendedTimes)
  {
    // ガチャ内のロットIDを比重付きですべて取得する
    $weights = $this->getLotInLottery($lottery->lotteryId);

    // 全部で何回引くのか取得。
    $castAmount = $lottery->amount * $extendedTimes;

    // 1段階目、ロットIDをキーとする、引いた数のカウントを格納した配列を作る。
    // packageはamountをそれぞれ制限しながら進めないとだめ。まあ、超えちゃったら
    // けずる、という方式でもいいんだが。
    $lotAmounts = $this->pickUpInLots($playerId, $lottery->lotteryId, $weights, $castAmount);

    // ロットIDをもとにロット内のボーナスリストを取得
    $pickupLotIds = array_keys($lotAmounts);
    $goodsWeightsInLots = $this->getGoodsWeightsInLotsInLotIds($pickupLotIds);

    $playerGoodsList = array();
    // 2段階目、各ロットのボーナスをそれぞれ取得。
    foreach ($lotAmounts as $lotId => $lotAmount) {
      $goodsWeights = $goodsWeightsInLots[$lotId];

      // どのロットでどのボーナスIDを何回引いたのかを取得
      $goodsSetIdCounts = pickUpMany($goodsWeights, $lotAmount);
      foreach($goodsSetIdCounts as $goodsSetId => $goodsAmount) {
        $goods = new Entity_Goods();
        $goods->goodsSetId = $goodsSetId;
        $goods->amount     = $goodsAmount; // Entity_Player_Goodsのcountは回数なので$goodsAmountであっている。

        $goodsList[] = $goods;
      }
    }

    // セットIDを元に具体的なユニットIDやアイテムIDなどを取得してEntity_Player_Goodsに。
    $playerGoodsList = Component_Goods::getInstance()->createPlayerGoodsList($playerId, $goodsList);

    return $playerGoodsList;
  }

  /**
   * どのロットを何回引いたのか取得する
   *
   * @param unknown $weights
   * @param unknown $amount
   * @return Ambigous <multitype:, multitype:number, multitype:, multitype:number >
   */
  protected function pickUpInLots($playerId, $lotteryId, $weights, $amount)
  {
    // packageと違って残数を数えなくていいからすげー楽。
    return pickUpMany($weights, $amount);
  }

  /**
   * あるガチャIDに所属するロットIDを比重付きで返す。
   *
   * MEMO: この後使う関数の都合により、返す配列はロットIDがキー、比重が値となる。
   *
   * @param  integer $lotteryId ガチャID
   * @return array
   */
  protected function getLotInLottery($lotteryId)
  {
    $records = Dao_LotteryLotRelative::getInstance()->selectLots($lotteryId);

    $weights = array();
    foreach($records as $record) {
      $weights[$record['lottery_lot_id']] = $record['weight'];
    }

    return $weights;
  }

  /**
   * ロット内のボーナスリストを取得する
   *
   * @param  array $lotIds
   * @return Entity_Goodsが、一意の数値(この場合ロットボーナスID)をキーとして格納された配列が、
   * ロットIDをキーとする配列に格納された、3次元配列
   */
  protected function getGoodsWeightsInLotsInLotIds($lotIds)
  {
    // キャッシュキーのプレフィックス
    $cacheKeyPrefix = __METHOD__.':LotteryLotId:';

    // 渡しているのは無名関数。
    $goodsSetIds = $this->getDataWithCache($lotIds,
                                            $cacheKeyPrefix,
                                            function ($lotIds) {
                                              $records = Dao_LotteryLotGoods::getInstance()->selectByLotIds($lotIds);
                                              $goodsSetIds = array();
                                              foreach($records as $record) {
                                                // 別にロジック上は必要ないんだけどコードが見づらかったから詰め替えた
                                                $lotId   = $record['lottery_lot_id'];
                                                $goodsSetId = $record['goods_id'];
                                                $weight  = $record['weight'];

                                                $goodsSetIds[$lotId][$goodsSetId] = $weight;
                                              }
                                              return $goodsSetIds;
                                            });

    return $goodsSetIds;
  }

  /**
   * 残数制限を付与したpickUpMany()
   *
   * 別に制限は設けてないけどたぶんPackage専用。
   *
   * @param integer $amount  ロットを引く数量
   * @param array   $weights ロットIDをキーとした比重が格納された配列
   * @param array   $remains 各ロットの残数
   * @return array
   */
  protected function pickUpWithRemainLimit($amount, $weights, $remains)
  {
    $counts = array();
    for ($i=1;$i<=$amount;$i++) {
      $lotId = pickUp($weights);
      if(!isset($counts[$lotId])) $counts[$lotId] = 0;
      $counts[$lotId]++;

      // 残数を減らす
      $remains[$lotId]--;

      // 残数がなくなったら比重データそのものから削除してpickUpさせない。
      if ($remains[$lotId] <= 0) {
        unset($weights[$lotId]);
      }
    }
    return $counts;
  }

  /**
   * 保存する
   *
   * @param  integer $playerId  プレイヤーID
   * @param  integer $processId 処理ID
   * @param  integer $playerId
   * @param  integer $processId
   * @param  array $playerGoodsList  Entity_Player_Goodsが格納された配列
   * @param  Entity_Lottery $lottery ガチャインスタンス
   * @param  Entity_Consideration $consideration 対価インスタンス
   * @param  integer $extendedTimes 実行回数。sがついてるけど配列じゃない。
   * @throws Exception
   */
  public function saveResult($playerId, $processId, $playerGoodsList, Entity_Lottery $lottery, Entity_Consideration $consideration, $extendedTimes)
  {

    $conManager = Db_ConnectionManager::getInstance();
    $componentGoods = Component_Goods::getInstance();
    $componentConsideration = Component_Consideration::getInstance();

    $additionList = $this->getPlayerGoodsListInLotteryAddition($lottery->lotteryId, $extendedTimes);

    try {
      $conManager->beginTransaction(__METHOD__);
      // packagePersonalの場合は残数チェックがいるんだけどここでは不要

      // 対価を支払ってもらう
      $componentConsideration->payConsideration($playerId, $consideration, $extendedTimes);

      // 仮置き場にまとめて保存
      $componentGoods->saveGoodsListToDepot($playerId, $processId, $playerGoodsList);

      // 概要をログとして記録
      $this->addLotteryLog($playerId, $processId, $lottery, $playerGoodsList, $extendedTimes);

      // コミット
      $conManager->commit(__METHOD__);

    } catch (Exception $e) {
      $conManager->rollback(__METHOD__);
      throw $e;
    }
  }

  /**
   * ガチャのログを保存する
   *
   * @param integer $playerId
   * @param integer $processId
   * @param Entity_Con $consideration
   * @param unknown $lottery
   */
  public function addLotteryLog($playerId, $processId, $lottery, $playerGoodsList, $extendedTimes)
  {
    // どのガチャを引いたかのログ
    Dao_PlayerLotteryLog::getInstance()->insertOne($lottery->lotteryId, $playerId, $processId, $lottery->amount,
                                                   $lottery->paymentType, $lottery->cost, $extendedTimes);

    // 取得した品物IDのログ
    $goodsSetIdAndAmounts = array();
    foreach ($playerGoodsList as $playerGoods) {
      $goodsSetIdAndAmounts[$playerGoods->goodsSetId] = $playerGoods->count;
    }
    $reasonType = Config::get('goods', 'reason_type_lottery');
    Dao_PlayerGoodsLog::getInstance()->insertMany($playerId, $goodsSetIdAndAmounts, $reasonType, $lottery->lotteryId, $processId);

    // 品物詳細はplayer_goodsに入ったものと全く同じになるのでログはとらない。そちらを見ればOKという認識。
  }

  /**
   * ガチャのおまけを取得する
   *
   * @param  integer $lotteryId
   * @return array Entity_Goodsを格納した配列
   */
  public function getPlayerGoodsListInLotteryAddition($lotteryId, $extendedTimes)
  {
    $records = Dao_LotteryAddition::getInstance()->selectByLotteryId($lotteryId);

    $additionGoodsIds = array_search_values($records, 'goods_id');

    $playerGoodsList = array();
    foreach($additionGoodsIds as $additionGoodsId) {
      $result = new Entity_Player_Goods();
      $result->goodsSetId = $additionGoodsId;
      $result->count   = $extendedTimes;
      $playerGoodsList[] = $result;
    }
    return $playerGoodsList;
  }
}


text:
package org.rioproject.test.utils;

import java.io.*;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

/**
 * Utility to create a JAR.
 */
public class JarUtil {

    public static File createJar(File source,
                                 File target,
                                 String jarName,
                                 Manifest manifest,
                                 File toAdd) throws IOException {
        if (!target.exists())
            if (target.mkdirs())
                System.out.println("Created " + target.getPath());
        JarOutputStream jarOutput = null;
        File jar = new File(target, jarName);
        String strip = replaceSeparators(source.getPath());
        if(!strip.endsWith(File.separator))
            strip = strip+File.separator;
        try {
            jarOutput = new JarOutputStream(new FileOutputStream(jar), manifest);
            if(toAdd!=null)
                addToJar(toAdd, jarOutput, strip);
            addToJar(source, jarOutput, strip);
        } finally {
            if (jarOutput != null)
                jarOutput.close();
        }
        return jar;
    }

    private static void addToJar(File source,
                                 JarOutputStream jarOutput,
                                 String strip) throws IOException {
        BufferedInputStream in = null;
        try {
            if (source.isDirectory()) {
                String name = replaceSeparators(source.getPath());
                if(name.length()>strip.length()) {
                    name = name.substring(strip.length());
                    if (!name.isEmpty()) {
                        if (!name.endsWith("/"))
                            name += "/";
                        JarEntry entry = new JarEntry(name);
                        entry.setTime(source.lastModified());
                        jarOutput.putNextEntry(entry);
                        jarOutput.closeEntry();
                    }
                }
                for (File nestedFile : source.listFiles())
                    addToJar(nestedFile, jarOutput, strip);
                return;
            }
            String name = replaceSeparators(source.getPath()).substring(strip.length());
            JarEntry entry = new JarEntry(name);
            entry.setTime(source.lastModified());
            jarOutput.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                jarOutput.write(buffer, 0, count);
            }
            jarOutput.closeEntry();
        }
        finally {
            if (in != null)
                in.close();
        }
    }

    private static String replaceSeparators(String s) {
        if(System.getProperty("os.name").startsWith("Windows"))
            return s;
        return s.replace("\\", "/");
    }
}


text:
package org.elasticsearch.smoketest;

import com.carrotsearch.randomizedtesting.annotations.Name;
import com.carrotsearch.randomizedtesting.annotations.ParametersFactory;

import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate;
import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase;

import java.util.List;

public class DocsClientYamlTestSuiteIT extends ESClientYamlSuiteTestCase {

    public DocsClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) {
        super(testCandidate);
    }

    @ParametersFactory
    public static Iterable<Object[]> parameters() throws Exception {
        return ESClientYamlSuiteTestCase.createParameters();
    }

    @Override
    protected void afterIfFailed(List<Throwable> errors) {
        super.afterIfFailed(errors);
        String name = getTestName().split("=")[1];
        name = name.substring(0, name.length() - 1);
        name = name.replaceAll("/([^/]+)$", ".asciidoc:$1");
        logger.error("This failing test was generated by documentation starting at {}. It may include many snippets. "
                + "See docs/README.asciidoc for an explanation of test generation.", name);
    }

    @Override
    protected boolean randomizeContentType() {
        return false;
    }
}


text:
local lpeg = require "lpeg"
local core = require "lpeg_patterns.core"
local http_core = require "lpeg_patterns.http.core"
local uri = require "lpeg_patterns.uri"

local C = lpeg.C
local P = lpeg.P

-- discard captures from scheme, host, port and just get whole string
local serialized_origin = C(uri.scheme * P"://" * uri.host * (P":" * uri.port)^-1/function() end)
local origin_list = serialized_origin * (core.SP * serialized_origin)^0
local origin_list_or_null = P"null" + origin_list
local Origin = http_core.OWS * origin_list_or_null * http_core.OWS

return {
	serialized_origin = serialized_origin;
	Origin = Origin;
}


text:
package com.wizzardo.http.framework.template.taglib.g;

import com.wizzardo.http.framework.template.*;
import com.wizzardo.tools.xml.Node;

import java.util.Map;

/**
 * Created by wizzardo on 18.05.15.
 */
public class TextArea extends Tag {

    @Override
    public Tag init(Node node, String offset, String dir, ViewRenderingService viewRenderingService) {
        return init(node.attributes(), new Body(node, "", dir, false, imports), offset);
    }

    public Tag init(Map<String, String> attrs, Body body, String offset) {
        ExpressionHolder name = asExpression(remove(attrs, "name"), true);

        String id = attrs.remove("id");
        String value = attrs.remove("value");

        append(offset);
        append("<textarea name=\"");
        append(model -> {
            RenderResult result = new RenderResult();
            String nameString = String.valueOf(name.getRaw(model));
            result.append(nameString);
            if (id == null)
                result.append("\" id=\"").append(nameString);

            return result;
        });

        if (id != null)
            append("\" id=\"").append(asExpression(id, true));

        append("\"");
        prepareAttrs(attrs);
        append(">");

        if (value != null)
            append(asExpression(value, true));
        else
            append(body::get);

        append("</textarea>\n");
        return this;
    }
}


text:
using System;
using System.Linq;

namespace Microsoft.WindowsAzure.Management.Compute.Models
{
    /// <summary>
    /// The parameters Azure uses to create the operating system disk for the
    /// virtual machine.
    /// </summary>
    public partial class OSVirtualHardDisk
    {
        private string _hostCaching;

        /// <summary>
        /// Optional. Specifies the platform caching behavior of the operating
        /// system disk blob for read/write efficiency.
        /// </summary>
        public string HostCaching
        {
            get { return this._hostCaching; }
            set { this._hostCaching = value; }
        }

        private string _iOType;

        /// <summary>
        /// Optional. Gets or sets the IO type.
        /// </summary>
        public string IOType
        {
            get { return this._iOType; }
            set { this._iOType = value; }
        }

        private string _label;

        /// <summary>
        /// Optional. Specifies the friendly name of an operating system image
        /// in the image repository.
        /// </summary>
        public string Label
        {
            get { return this._label; }
            set { this._label = value; }
        }

        private Uri _mediaLink;

        /// <summary>
        /// Optional. Specifies the location of the operating system disk in
        /// Azure storage.
        /// </summary>
        public Uri MediaLink
        {
            get { return this._mediaLink; }
            set { this._mediaLink = value; }
        }

        private string _name;

        /// <summary>
        /// Optional. Specifies the name of an operating system image in the
        /// image repository.
        /// </summary>
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        private string _operatingSystem;

        /// <summary>
        /// Optional. The operating system running in the virtual machine.
        /// </summary>
        public string OperatingSystem
        {
            get { return this._operatingSystem; }
            set { this._operatingSystem = value; }
        }

        private Uri _remoteSourceImageLink;

        /// <summary>
        /// Optional. Uri of the source OS image that will be copied to the
        /// customer's storage account of VM creation.If RemoteSourceImageLink
        /// is specified, then MediaLink must also be specified.If
        /// RemoteSourceImageLink is specified, thenSourceIamgeName must not
        /// be specified.
        /// </summary>
        public Uri RemoteSourceImageLink
        {
            get { return this._remoteSourceImageLink; }
            set { this._remoteSourceImageLink = value; }
        }

        private int? _resizedSizeInGB;

        /// <summary>
        /// Optional. When an OS Image or a RemoteSourceImage is used to create
        /// an OSVirtualHardDisk, this parameter can be used to resize the new
        /// OSVirtualHardDisk to a larger size. ResizedSizeInGB must be larger
        /// than the underlying OS Image's LogicalSizeInGB.
        /// </summary>
        public int? ResizedSizeInGB
        {
            get { return this._resizedSizeInGB; }
            set { this._resizedSizeInGB = value; }
        }

        private string _sourceImageName;

        /// <summary>
        /// Optional. Specifies the name of the source image that was used to
        /// provision the virtual machine.
        /// </summary>
        public string SourceImageName
        {
            get { return this._sourceImageName; }
            set { this._sourceImageName = value; }
        }

        /// <summary>
        /// Initializes a new instance of the OSVirtualHardDisk class.
        /// </summary>
        public OSVirtualHardDisk()
        {
        }
    }
}


text:
if( typeof Jetpack == 'undefined' ) {
  Jetpack = {};
}

// Init options:
// options -
// wrapper: defaults to '.tab-wrapper'
// nav: defaults to '.tabs'
// viewport: defaults to '.viewport'
Jetpack.tabs = {
	views: [],
	init: function(options) {
    if(typeof options == 'undefined' ) {
      var options = {};
    }
    if(typeof options.wrapper == 'undefined'){
      options.wrapper = '.tab-wrapper';
    }
    if(typeof options.nav == 'undefined'){
      options.nav = '.tabs';
    }
    if(typeof options.viewport == 'undefined'){
      options.viewport = '.viewport';
    }
    this.bind(options);
	},
	bind: function(options) {
		var self = this;
		$(options.wrapper).each(function(i,el){
			self.views.push(new Jetpack.TabView(el,options));
		});
	}
};

// Pills alias, calls tabs with different default options
// options -
// wrapper: defaults to '.pill-wrapper'
// nav: defaults to '.pills'
// viewport: defaults to '.viewport'
Jetpack.pills = {
	init: function(options) {
    if(typeof options == 'undefined' ) {
      var options = {};
    }
    if(typeof options.wrapper == 'undefined'){
      options.wrapper = '.pill-wrapper';
    }
    if(typeof options.nav == 'undefined'){
      options.nav = '.pills';
    }
    if(typeof options.viewport == 'undefined'){
      options.viewport = '.viewport';
    }
    Jetpack.tabs.bind(options);
	}
};

Jetpack.TabView = function(selector,options) {
	this.$el = $(selector);
	this.$tabs = this.$el.find(options.nav);
	this.$view = this.$el.find(options.viewport);
	this.bind();

	var firstID = this.$tabs.find('a').first().attr('href');
	this.setView(firstID);
};

Jetpack.TabView.prototype = {
	bind: function() {
		var self = this;
		this.$tabs.on('click','a',function(event){
			// Ignore regular links
			var id = $(this).attr('href');
			if( id.charAt(0) == '#' ) {
				event.preventDefault();
				self.setView( id );
			}
		});
	},
	setView: function(id) {
		this.$tabs.find('a').removeClass('active');
		this.$tabs.find('a[href='+id+']').addClass('active');
		this.$view.children().removeClass('active');
		this.$view.find(id).addClass('active');
	}
};


text:
class Profiles::TwoFactorAuthsController < Profiles::ApplicationController
  skip_before_action :check_two_factor_requirement

  def show
    unless current_user.otp_secret
      current_user.otp_secret = User.generate_otp_secret(32)
    end

    unless current_user.otp_grace_period_started_at && two_factor_grace_period
      current_user.otp_grace_period_started_at = Time.current
    end

    Users::UpdateService.new(current_user, user: current_user).execute!

    if two_factor_authentication_required? && !current_user.two_factor_enabled?
      two_factor_authentication_reason(
        global: lambda do
          flash.now[:alert] =
            _('The global settings require you to enable Two-Factor Authentication for your account.')
        end,
        group: lambda do |groups|
          flash.now[:alert] = groups_notification(groups)
        end
      )

      unless two_factor_grace_period_expired?
        grace_period_deadline = current_user.otp_grace_period_started_at + two_factor_grace_period.hours
        flash.now[:alert] = flash.now[:alert] + _(" You need to do this before %{grace_period_deadline}.") % { grace_period_deadline: l(grace_period_deadline) }
      end
    end

    @qr_code = build_qr_code
    @account_string = account_string
    setup_u2f_registration
  end

  def create
    if current_user.validate_and_consume_otp!(params[:pin_code])
      Users::UpdateService.new(current_user, user: current_user, otp_required_for_login: true).execute! do |user|
        @codes = user.generate_otp_backup_codes!
      end

      render 'create'
    else
      @error = _('Invalid pin code')
      @qr_code = build_qr_code
      setup_u2f_registration
      render 'show'
    end
  end

  # A U2F (universal 2nd factor) device's information is stored after successful
  # registration, which is then used while 2FA authentication is taking place.
  def create_u2f
    @u2f_registration = U2fRegistration.register(current_user, u2f_app_id, u2f_registration_params, session[:challenges])

    if @u2f_registration.persisted?
      session.delete(:challenges)
      redirect_to profile_two_factor_auth_path, notice: s_("Your U2F device was registered!")
    else
      @qr_code = build_qr_code
      setup_u2f_registration
      render :show
    end
  end

  def codes
    Users::UpdateService.new(current_user, user: current_user).execute! do |user|
      @codes = user.generate_otp_backup_codes!
    end
  end

  def destroy
    result = TwoFactor::DestroyService.new(current_user, user: current_user).execute

    if result[:status] == :success
      redirect_to profile_account_path, status: :found, notice: s_('Two-factor authentication has been disabled successfully!')
    else
      redirect_to profile_account_path, status: :found, alert: result[:message]
    end
  end

  def skip
    if two_factor_grace_period_expired?
      redirect_to new_profile_two_factor_auth_path, alert: s_('Cannot skip two factor authentication setup')
    else
      session[:skip_two_factor] = current_user.otp_grace_period_started_at + two_factor_grace_period.hours
      redirect_to root_path
    end
  end

  private

  def build_qr_code
    uri = current_user.otp_provisioning_uri(account_string, issuer: issuer_host)
    RQRCode.render_qrcode(uri, :svg, level: :m, unit: 3)
  end

  def account_string
    "#{issuer_host}:#{current_user.email}"
  end

  def issuer_host
    Gitlab.config.gitlab.host
  end

  # Setup in preparation of communication with a U2F (universal 2nd factor) device
  # Actual communication is performed using a Javascript API
  def setup_u2f_registration
    @u2f_registration ||= U2fRegistration.new
    @u2f_registrations = current_user.u2f_registrations
    u2f = U2F::U2F.new(u2f_app_id)

    registration_requests = u2f.registration_requests
    sign_requests = u2f.authentication_requests(@u2f_registrations.map(&:key_handle))
    session[:challenges] = registration_requests.map(&:challenge)

    gon.push(u2f: { challenges: session[:challenges], app_id: u2f_app_id,
                    register_requests: registration_requests,
                    sign_requests: sign_requests })
  end

  def u2f_registration_params
    params.require(:u2f_registration).permit(:device_response, :name)
  end

  def groups_notification(groups)
    group_links = groups.map { |group| view_context.link_to group.full_name, group_path(group) }.to_sentence
    leave_group_links = groups.map { |group| view_context.link_to (s_("leave %{group_name}") % { group_name: group.full_name }), leave_group_members_path(group), remote: false, method: :delete}.to_sentence

    s_(%{The group settings for %{group_links} require you to enable Two-Factor Authentication for your account. You can %{leave_group_links}.})
      .html_safe % { group_links: group_links.html_safe, leave_group_links: leave_group_links.html_safe }
  end
end


text:
#define _GNU_SOURCE
#include <signal.h>
#include <sched.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <numa.h>

#include "pfring.h"
#include "pfring_zc.h"

#include "zutils.c"

//#define USE_RECV_BURST

#define ALARM_SLEEP               1
#define MAX_CARD_SLOTS        32768
#define SWAP_BUFFERS             16
#define QUEUE_LEN              8192
#define SLAVE_BUFFERS            16
#define CACHE_LINE_LEN           64
#define PULSE_TS_PRECISION_NSEC 100

pfring_zc_cluster *zc;
pfring_zc_queue *inzq;
pfring_zc_queue **outzq;
pfring_zc_buffer_pool **pools;
pfring_zc_multi_queue *mq;
pfring_zc_pkt_buff *ph[SWAP_BUFFERS];

u_int32_t num_slaves = 1;
u_int32_t queue_len = QUEUE_LEN;

int bind_core = -1;
int bind_time_pulse_core = -1;

static struct timeval startTime;

struct volatile_globals {
  unsigned long long numPkts;
  unsigned long long numBytes;
  unsigned long long sentPkts;
  int time_pulse;
  int wait_for_packet;
  int pulse_timestamp_precision_nsec;
  volatile u_int8_t do_shutdown;
  volatile u_int64_t *pulse_timestamp_ns;
};

struct volatile_globals *globals;

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

void *time_pulse_thread(void *data) {
  struct volatile_globals *g = globals;
  u_int64_t ns;
  struct timespec tn;
#if 1
  u_int64_t pulse_clone = 0;
#endif

  bind2core(bind_time_pulse_core);

  while (likely(!g->do_shutdown)) {
    /* clock_gettime takes up to 30 nsec to get the time */
    clock_gettime(CLOCK_REALTIME, &tn);

    ns = ((u_int64_t) ((u_int64_t) tn.tv_sec * 1000000000) + (tn.tv_nsec));

#if 1 /* reduce cache thrashing*/
    if(ns >= pulse_clone + g->pulse_timestamp_precision_nsec /* (avoid updating each cycle) */ ) {
#endif
      *g->pulse_timestamp_ns = ((u_int64_t) ((u_int64_t) tn.tv_sec << 32) | tn.tv_nsec);
#if 1
      pulse_clone = ns;
    }
#endif
  }

  return NULL;
}

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

void print_stats() {
  static u_int8_t print_all = 0;
  static struct timeval lastTime;
  static u_int64_t lastPkts = 0, lastBytes = 0, lastDrops = 0, lastSlavePkts = 0, lastSlaveDrops = 0;
  unsigned long long nBytes = 0, nPkts = 0, nDrops = 0, nSlavePkts = 0, nSlaveDrops = 0;
  struct timeval endTime;
  char buf1[64], buf2[64], buf3[64], buf4[64], buf5[64];
  pfring_zc_stat stats;
  int i;

  if(startTime.tv_sec == 0)
    gettimeofday(&startTime, NULL);
  else
    print_all = 1;

  gettimeofday(&endTime, NULL);

  nPkts  = globals->numPkts;
  nBytes = globals->numBytes;
  if (pfring_zc_stats(inzq, &stats) == 0)
    nDrops = stats.drop;
  nSlavePkts  = globals->sentPkts;
  for (i = 0; i < num_slaves; i++)
    if (pfring_zc_stats(outzq[i], &stats) == 0)
      nSlaveDrops += stats.drop;

  fprintf(stderr, "=========================\n"
	  "Absolute Stats: Recv %s pkts (%s drops) %s bytes - Forwarded %s pkts (%s drops)\n",
	  pfring_format_numbers((double)nPkts, buf1, sizeof(buf1), 0),
	  pfring_format_numbers((double)nDrops, buf2, sizeof(buf2), 0),
	  pfring_format_numbers((double)nBytes, buf3, sizeof(buf3), 0),
	  pfring_format_numbers((double)nSlavePkts, buf4, sizeof(buf4), 0),
	  pfring_format_numbers((double)nSlaveDrops, buf5, sizeof(buf5), 0));

  if(print_all && lastTime.tv_sec > 0) {
    double deltaMillisec = delta_time(&endTime, &lastTime);
    double bytesDiff = ((double) (nBytes - lastBytes) * 8) / (1000*1000*1000);
    unsigned long long pktsDiff = nPkts-lastPkts;
    unsigned long long dropsDiff = nDrops - lastDrops;
    unsigned long long slavePktsDiff = nSlavePkts - lastSlavePkts;
    unsigned long long slaveDropsDiff = nSlaveDrops - lastSlaveDrops;

    fprintf(stderr,
	     "Actual Stats: Recv %s pps (%s drops) %s Gbps - Forwarded %s pps (%s drops)\n",
	     pfring_format_numbers(((double)pktsDiff/(double)(deltaMillisec/1000)), buf1, sizeof(buf1), 1),
	     pfring_format_numbers(((double)dropsDiff/(double)(deltaMillisec/1000)), buf2, sizeof(buf2), 1),
	     pfring_format_numbers(((double)bytesDiff/(double)(deltaMillisec/1000)), buf3, sizeof(buf3), 1),
	     pfring_format_numbers(((double)slavePktsDiff/(double)(deltaMillisec/1000)), buf4, sizeof(buf4), 1),
	     pfring_format_numbers(((double)slaveDropsDiff/(double)(deltaMillisec/1000)), buf5, sizeof(buf5), 1));
  }

  fprintf(stderr, "=========================\n\n");

  lastPkts = nPkts, lastBytes = nBytes, lastDrops = nDrops;
  lastSlavePkts = nSlavePkts, lastSlaveDrops = nSlaveDrops;
  lastTime.tv_sec = endTime.tv_sec, lastTime.tv_usec = endTime.tv_usec;
}

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

void sigproc(int sig) {
  static int called = 0;
  fprintf(stderr, "Leaving...\n");
  if(called) return; else called = 1;

  globals->do_shutdown = 1;

  print_stats();

  pfring_zc_queue_breakloop(inzq);
}

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

void printHelp(void) {
  printf("zfanout_ipc - (C) 2014 ntop.org\n");
  printf("Using PFRING_ZC v.%s\n", pfring_zc_version());
  printf("A master process sending all ingress packets to all the consumer processes (e.g. zcount_ipc -c <cluster id> -i <consumer id>).\n");
  printf("Note: this is an alternative to zbalance -m 2\n\n");
  printf("Usage: zfanout_ipc -i <device> -c <cluster id> -n <num inst>\n"
	 "                [-h] [-q <len>] [-S <core id>] [-g <core id>] [-a]\n\n");
  printf("-h              Print this help\n");
  printf("-i <device>     Device name\n");
  printf("-c <cluster id> Cluster id\n");
  printf("-n <num inst>   Number of application instances\n");
  printf("-q <len>        Number of slots in each queue (default: %u)\n", QUEUE_LEN);
  printf("-S <core id>    Enable Time Pulse thread and bind it to a core\n");
  printf("-g <core id>    Bind this app to a core\n");
  printf("-a              Active packet wait\n");
  exit(-1);
}

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

void *packet_consumer_thread(void *_id) {
  struct volatile_globals *g = globals;
  pfring_zc_queue *_inzq = inzq;
  pfring_zc_queue **_outzq = outzq;
  pfring_zc_multi_queue *_mq = mq;
  pfring_zc_pkt_buff **_ph = ph;
  u_int32_t _num_slaves = num_slaves;
  int i, ns, flush_tx = 0, toprocess = 0;
#ifdef USE_RECV_BURST
  int nr;
#endif

  bind2core(bind_core);

  while(!g->do_shutdown) {

#ifdef USE_RECV_BURST
    if ((nr = pfring_zc_recv_pkt_burst(_inzq, _ph, SWAP_BUFFERS, 0 /* g->wait_for_packet */)) > 0)
#else
    if (pfring_zc_recv_pkt(_inzq, _ph, 0 /* g->wait_for_packet */) > 0)
#endif
    {

#ifdef USE_RECV_BURST
      toprocess = 0;
      while (toprocess < nr) {
#endif
        pfring_zc_pkt_buff **buff_p = &_ph[toprocess];
        pfring_zc_pkt_buff *buff = *buff_p;

        if (g->time_pulse) {
          u_int64_t pulse_timestamp_ns = *g->pulse_timestamp_ns;
          buff->ts.tv_sec = pulse_timestamp_ns >> 32;
          buff->ts.tv_nsec = pulse_timestamp_ns & 0xffffffff;
        }

        g->numPkts++;
        g->numBytes += buff->len + 24; /* 8 Preamble + 4 CRC + 12 IFG */

        ns = pfring_zc_send_pkt_multi(_mq, buff_p, 0xffffffff, 0);

	//drop += _num_slaves - ns;
        g->sentPkts += ns;

#ifdef USE_RECV_BURST
        toprocess++;
      }
#endif
      flush_tx = 1;

    } else {
      if (flush_tx) {
        for (i = 0; i < _num_slaves; i++)
          pfring_zc_sync_queue(_outzq[i], tx_only);
        flush_tx = 0;
      }

      if (g->wait_for_packet)
        usleep(1);
    }

  }

  pfring_zc_sync_queue(_inzq, rx_only);
  for (i = 0; i < _num_slaves; i++)
    pfring_zc_sync_queue(_outzq[i], tx_only);

  return NULL;
}

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

int main(int argc, char* argv[]) {
  char *device = NULL, c;
  long i;
  int cluster_id = -1;
  pthread_t my_thread, time_thread;
  int wait_for_packet = 1, time_pulse = 0;
  int pulse_timestamp_precision_nsec = PULSE_TS_PRECISION_NSEC;

  startTime.tv_sec = 0;

  while((c = getopt(argc,argv,"ac:g:hi:n:S:q:P:")) != '?') {
    if((c == 255) || (c == -1)) break;

    switch(c) {
    case 'h':
      printHelp();
      break;
    case 'a':
      wait_for_packet = 0;
      break;
    case 'c':
      cluster_id = atoi(optarg);
      break;
    case 'n':
      num_slaves = atoi(optarg);
      break;
    case 'q':
      queue_len = atoi(optarg);
      break;
    case 'i':
      device = strdup(optarg);
      break;
    case 'g':
      bind_core = atoi(optarg);
      break;
    case 'S':
      time_pulse = 1;
      bind_time_pulse_core = atoi(optarg);
      break;
    case 'P':
      pulse_timestamp_precision_nsec = atoi(optarg);
      break;
    }
  }

  if (device == NULL) printHelp();
  if (cluster_id < 0) printHelp();
  if (num_slaves < 1) printHelp();

  bind2node(bind_core);

  /* volatile global variables initialization */
  globals = calloc(1, sizeof(*globals));
  globals->wait_for_packet = wait_for_packet;
  globals->numPkts = 0;
  globals->numBytes = 0;
  globals->sentPkts = 0;
  globals->time_pulse = time_pulse;
  globals->do_shutdown = 0;
  globals->pulse_timestamp_precision_nsec = pulse_timestamp_precision_nsec;

  zc = pfring_zc_create_cluster(
    cluster_id,
    max_packet_len(device),
    0,
    MAX_CARD_SLOTS + (num_slaves * (queue_len + SLAVE_BUFFERS)) + SWAP_BUFFERS,
    numa_node_of_cpu(bind_core),
    NULL /* auto hugetlb mountpoint */
  );

  if(zc == NULL) {
    fprintf(stderr, "pfring_zc_create_cluster error [%s] Please check your hugetlb configuration\n",
	    strerror(errno));
    return -1;
  }

  outzq = calloc(num_slaves,  sizeof(pfring_zc_queue *));
  pools = calloc(num_slaves,  sizeof(pfring_zc_buffer_pool *));

  for (i = 0; i < SWAP_BUFFERS; i++) {
    ph[i] = pfring_zc_get_packet_handle(zc);

    if (ph[i] == NULL) {
      fprintf(stderr, "pfring_zc_get_packet_handle error\n");
      return -1;
    }
  }

  inzq = pfring_zc_open_device(zc, device, rx_only, 0);

  if(inzq == NULL) {
    fprintf(stderr, "pfring_zc_open_device error [%s] Please check that %s is up and not already used\n",
            strerror(errno), device);
    return -1;
  }

  for (i = 0; i < num_slaves; i++) {
    outzq[i] = pfring_zc_create_queue(zc, queue_len);

    if(outzq[i] == NULL) {
      fprintf(stderr, "pfring_zc_create_queue error [%s]\n", strerror(errno));
      return -1;
    }
  }

  for (i = 0; i < num_slaves; i++) {
    pools[i] = pfring_zc_create_buffer_pool(zc, SLAVE_BUFFERS);

    if (pools[i] == NULL) {
      fprintf(stderr, "pfring_zc_create_buffer_pool error\n");
      return -1;
    }
  }

  signal(SIGINT,  sigproc);
  signal(SIGTERM, sigproc);
  signal(SIGINT,  sigproc);

  if (globals->time_pulse) {
    globals->pulse_timestamp_ns = calloc(CACHE_LINE_LEN/sizeof(u_int64_t), sizeof(u_int64_t));
    pthread_create(&time_thread, NULL, time_pulse_thread, NULL);
    while (!*globals->pulse_timestamp_ns && !globals->do_shutdown); /* wait for ts */
  }

  printf("Starting fanout for %d slave applications..\n", num_slaves);

  mq = pfring_zc_create_multi_queue(outzq, num_slaves);

  if(mq == NULL) {
    fprintf(stderr, "pfring_zc_create_multi_queue error [%s]\n", strerror(errno));
    return -1;
  }

  pthread_create(&my_thread, NULL, packet_consumer_thread, (void*) NULL);

  while (!globals->do_shutdown) {
    sleep(ALARM_SLEEP);
    print_stats();
  }

  pthread_join(my_thread, NULL);

  if (globals->time_pulse)
    pthread_join(time_thread, NULL);

  sleep(1);

  pfring_zc_destroy_cluster(zc);

  return 0;
}


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

package net.adoptopenjdk.bumblebench.examples;

import net.adoptopenjdk.bumblebench.core.MiniBench;

public final class MathASinBench extends MiniBench {
	protected int maxIterationsPerLoop(){ return 10000007; }

	protected long doBatch(long numLoops, int numIterationsPerLoop) throws InterruptedException {
		startTimer();
		//MathUtils.initialize();
		double argument = Math.asin(0.1);
		pauseTimer();
		double shrink = 1.99 / numIterationsPerLoop;
		for (long i = 0; i < numLoops; i++) {
			for (int j = 0; j < numIterationsPerLoop; j++) {
				startTimer();
				argument += Math.asin(j * shrink - 1);
				pauseTimer();
			}
		}
		return numLoops * numIterationsPerLoop;
	}
}


text:
package storage

import (
	"flag"
	"fmt"
	"os"
	"testing"

	"github.com/Sirupsen/logrus"
	. "github.com/onsi/ginkgo"
	"github.com/onsi/ginkgo/reporters"
	. "github.com/onsi/gomega"
)

func TestStorage(t *testing.T) {
	RegisterFailHandler(Fail)
	junitReporter := reporters.NewJUnitReporter("../test-reports/storage.xml")
	RunSpecsWithDefaultAndCustomReporters(t, "Storage suite", []Reporter{junitReporter})
}

func TestMain(m *testing.M) {
	logrus.SetLevel(logrus.ErrorLevel)
	flag.Parse()
	ret := m.Run()
	if largeDB != nil {
		fmt.Printf("Deleting %s\n", largeDBDir)
		largeDB.Close()
		largeDB.Delete()
	}
	if cleanDB != nil {
		fmt.Printf("Deleting %s\n", cleanDBDir)
		cleanDB.Close()
		cleanDB.Delete()
	}
	os.Exit(ret)
}


text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.us.Common;

namespace OpenADK.Library.us.Instr{

/// <summary>Field for non-numeric types of grading and evaluation such as "narrative."</summary>
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 1.5r1</para>
/// </remarks>
[Serializable]
public class Evaluation : SifKeyedElement
{
	/// <summary>
	/// Creates an instance of an Evaluation
	/// </summary>
	public Evaluation() : base ( InstrDTD.EVALUATION ){}

	/// <summary>
	/// Constructor that accepts values for all mandatory fields
	/// </summary>
	///<param name="evaluationType">A qualifer for what type of evaluation this is.  Valid values are "Inline" and "RefId".  Inline values are contained in the optional Description element, RefIds are contained in the AssessmentRefId element.</param>
	///
	public Evaluation( EvaluationType evaluationType ) : base( InstrDTD.EVALUATION )
	{
		this.SetEvaluationType( evaluationType );
	}

	/// <summary>
	/// Constructor used by the .Net Serialization formatter
	/// </summary>
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected Evaluation( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	/// <summary>
	/// Gets the metadata fields that make up the key of this object
	/// </summary>
	/// <value>
	/// an array of metadata fields that make up the object's key
	/// </value>
	public override IElementDef[] KeyFields {
		get { return new IElementDef[] { InstrDTD.EVALUATION_EVALUATIONTYPE }; }
	}

	/// <summary>
	/// Gets or sets the value of the <c>EvaluationType</c> attribute.
	/// </summary>
	/// <value> The <c>EvaluationType</c> attribute of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "A qualifer for what type of evaluation this is.  Valid values are "Inline" and "RefId".  Inline values are contained in the optional Description element, RefIds are contained in the AssessmentRefId element."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.5r1</para>
	/// </remarks>
	public string EvaluationType
	{
		get
		{
			return GetFieldValue( InstrDTD.EVALUATION_EVALUATIONTYPE );
		}
		set
		{
			SetField( InstrDTD.EVALUATION_EVALUATIONTYPE, value );
		}
	}

	/// <summary>
	/// Sets the value of the <c>EvaluationType</c> attribute.
	/// </summary>
	/// <param name="val">A EvaluationType object</param>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "A qualifer for what type of evaluation this is.  Valid values are "Inline" and "RefId".  Inline values are contained in the optional Description element, RefIds are contained in the AssessmentRefId element."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.5r1</para>
	/// </remarks>
	public void SetEvaluationType( EvaluationType val )
	{
		SetField( InstrDTD.EVALUATION_EVALUATIONTYPE, val );
	}

	/// <summary>
	/// Gets or sets the value of the <c><Description></c> element.
	/// </summary>
	/// <value> The <c>Description</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "A free text description of the evaluation to be used for this activity"</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 1.5r1</para>
	/// </remarks>
	public string Description
	{
		get
		{
			return (string) GetSifSimpleFieldValue( InstrDTD.EVALUATION_DESCRIPTION ) ;
		}
		set
		{
			SetFieldValue( InstrDTD.EVALUATION_DESCRIPTION, new SifString( value ), value );
		}
	}

}}


text:
[#]: collector: (lujun9972)
[#]: translator: (qfzy1233)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (A beginner's guide to Linux permissions)
[#]: via: (https://opensource.com/article/19/6/understanding-linux-permissions)
[#]: author: (Bryant Son https://opensource.com/users/brson/users/greg-p/users/tj)

A beginner's guide to Linux permissions
======
Linux security permissions designate who can do what with a file or
directory.
![Hand putting a Linux file folder into a drawer][1]

One of the main benefits of Linux systems is that they are known to be less prone to security vulnerabilities and exploits than other systems. Linux definitely gives users more flexibility and granular controls over its file systems' security permissions. This may imply that it's critical for Linux users to understand security permissions. That isn't necessarily true, but it's still wise for beginning users to understand the basics of Linux permissions.

### View Linux security permissions

To start learning about Linux permissions, imagine we have a newly created directory called **PermissionDemo**. Run **cd** inside the directory and use the **ls -l** command to view the Linux security permissions. If you want to sort them by time modified, add the **-t** option.

```
`ls -lt`
```

Since there are no files inside this new directory, this command returns nothing.

![No output from ls -l command][2]

To learn more about the **ls** option, access its man page by entering **man ls** on the command line.

![ls man page][3]

Now, let's create two files: **cat.txt** and **dog.txt** with empty content; this is easy to do using the **touch** command. Let's also create an empty directory called **Pets** with the **mkdir** command. We can use the **ls -l** command again to see the permissions for these new files.

![Creating new files and directory][4]

We need to pay attention to two sections of output from this command.

### Who has permission?

The first thing to examine indicates _who_ has permission to access the file/directory. Note the section highlighted in the red box below. The first column refers to the _user_ who has access, while the second column refers to the _group_ that has access.

![Output from -ls command][5]

There are three main types of users: **user** , **group** ; and **other** (essentially neither a user nor a group). There is one more: **all** , which means practically everyone.

![User types][6]

Because we are using **root** as the user, we can access any file or directory because **root** is the superuser. However, this is generally not the case, and you will probably be restricted to your username. A list of all users is stored in the **/etc/passwd** file.

![/etc/passwd file][7]

Groups are maintained in the **/etc/group** file.

![/etc/passwd file][8]

### What permissions do they have?

The other section of the output from **ls -l** that we need to pay attention to relates to enforcing permissions. Above, we confirmed that the owner and group permissions for the files dog.txt and cat.txt and the directory Pets we created belong to the **root** account. We can use that information about who owns what to enforce permissions for the different user ownership types, as highlighted in the red box below.

![Enforcing permissions for different user ownership types][9]

We can dissect each line into five bits of information. The first part indicates whether it is a file or a directory; files are labeled with a **-** (hyphen), and directories are labeled with **d**. The next three parts refer to permissions for **user** , **group** , and **other** , respectively. The last part is a flag for the [**access-control list**][10] (ACL), a list of permissions for an object.

![Different Linux permissions][11]

Linux permission levels can be identified with letters or numbers. There are three privilege types:

  * **read** : r or 4
  * **write:** w or 2
  * **executable:** e or 1

![Privilege types][12]

The presence of each letter symbol ( **r** , **w** , or **x** ) means that the permission exists, while **-** indicates it does not. In the example below, the file is readable and writeable by the owner, only readable if the user belongs to the group, and readable and executable by anyone else. Converted to numeric notation, this would be 645 (see the image below for an explanation of how this is calculated).

![Permission type example][13]

Here are a few more examples:

![Permission type examples][14]

Test your knowledge by going through the following exercises.

![Permission type examples][15]

--------------------------------------------------------------------------------

via: https://opensource.com/article/19/6/understanding-linux-permissions

作者:[Bryant Son][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/brson/users/greg-p/users/tj
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/yearbook-haff-rx-linux-file-lead_0.png?itok=-i0NNfDC (Hand putting a Linux file folder into a drawer)
[2]: https://opensource.com/sites/default/files/uploads/1_3.jpg (No output from ls -l command)
[3]: https://opensource.com/sites/default/files/uploads/1_man.jpg (ls man page)
[4]: https://opensource.com/sites/default/files/uploads/2_6.jpg (Creating new files and directory)
[5]: https://opensource.com/sites/default/files/uploads/3_2.jpg (Output from -ls command)
[6]: https://opensource.com/sites/default/files/uploads/4_0.jpg (User types)
[7]: https://opensource.com/sites/default/files/uploads/linuxpermissions_4_passwd.jpg (/etc/passwd file)
[8]: https://opensource.com/sites/default/files/uploads/linuxpermissions_4_group.jpg (/etc/passwd file)
[9]: https://opensource.com/sites/default/files/uploads/linuxpermissions_5.jpg (Enforcing permissions for different user ownership types)
[10]: https://en.wikipedia.org/wiki/Access-control_list
[11]: https://opensource.com/sites/default/files/uploads/linuxpermissions_6.jpg (Different Linux permissions)
[12]: https://opensource.com/sites/default/files/uploads/linuxpermissions_7.jpg (Privilege types)
[13]: https://opensource.com/sites/default/files/uploads/linuxpermissions_8.jpg (Permission type example)
[14]: https://opensource.com/sites/default/files/uploads/linuxpermissions_9.jpg (Permission type examples)
[15]: https://opensource.com/sites/default/files/uploads/linuxpermissions_10.jpg (Permission type examples)


text:
The Inference Framework
========================

The diagram below outlines the overall architecture of the inference framework.

.. image:: infer_frmwork.png

The entire process of generating inference codes from model and query specification consists of four stages:

1. The ``@model`` macro will convert a model specification into a model class, of which the internal representation is a factor graph.

2. The ``@query`` macro will reduce the factor graph based on the query. The reduction may involve following steps:

    (a) Simplify factors by absorbing known variables. For example, a second-order factor (i.e. a factor with two arguments) :math:`f(x, y)` can be reduced to a first-order factor if the value of one variable (say :math:`y`) is given.

    (b) Eliminate irrelevant variables and factors: variables and factors that do not influence the conditional distribution of the queried variables can be safely removed. For example, consider a joint distribution :math:`p(x, y, z) = p_1(x | z) p_2(y | z)`. When the value of :math:`y` is given, the variable :math:`y` is conditionally independent from :math:`x`. Therefore, the variable :math:`y` can be ignored in the inference for :math:`x`.

   The macro ``@query`` also generates a high-level description of the inference algorithm.

3. An *inference compiler* will compiles the inference algorithm into low-level Julia codes, taking into account the computational architecture of the target platform (e.g. CPU cores, GPU, cluster, cloud, etc).

4. Finally, the Julia compiler will emit LLVM instructions, which will then be compiled into native codes by the LLVM compiler.

Here, we focus on the first two steps, that is, compilation of model and query specifications into inference algorithms.

Gaussian Mixture Model Revisited
---------------------------------

To illustrate the procedure of model compilation, let's revisit the Gaussian mixture model (GMM). Given a model specification, the ``@model`` macro creates a *factor graph*, which is a hyper-graph with factors connecting between variables. The following diagram is the factor graph that represents a GMM with two components.

.. image:: gmm_facgraph.png
    :scale: 50%
    :align: center

In this graph, each sample is associated with two factors, a ``mixture factor`` that connects between observed samples, components, and component indicator :math:`z_i`, and a factor that specifies the prior of each component indicator. These two factors were directly specified in the model specification. In the *model learning query*, the data ``x`` are given. Therefore the order of each mixture factor is reduced from :math:`2 K + 2` to :math:`2 K + 1`.

The most widely used learning algorithm for this purpose is *Expectation Maximization*, which comprises three updating steps, as outlined below.

* Update the poterior probabilities of :math:`z_i` conditioned on prior :math:`\pi`, component parameters :math:`(\mu_k, \Sigma_k)`, and the corresponding observed sample :math:`x_i`, as

    .. math::

        q_i(k) := p(z_i = k | \pi, \theta, x_i) & \propto \pi(k) \mathcal{N}(x_i; \mu_k, \Sigma_k) \\
        & = \exp \left( \log \pi(k) + \log \mathcal{N}(x_i; \mu_k, \Sigma_k) \right)

 This can be interpreted as an integration of a message from the prior factor (that is, :math:`\log \pi(k)`) and a message from the corresponding mixture factor (that is, :math:`\log \mathcal{N}(x_i; \mu_k, \Sigma_k)`). Here, :math:`\log \mathcal{N}(x_i; \mu_k, \Sigma_k)` denotes the pdf at :math:`x_i` with respect to a Gaussian component.

* Update the maximum likelihood estimation of :math:`\pi`, as

    .. math::

        \pi(k) = \frac{1}{n} \sum_{i=1}^n p(z_i = k) = \frac{1}{n} \sum_{i=1}^n \exp ( \log q_i(k) )

 This can be interpreted as a computational process that combines messages from each of :math:`z_i` (that is, :math:`\log q_i(k)`).

* Update the maximum likelihood estimation of component parameters :math:`\mu_k` and :math:`\Sigma_k`, as

    .. math::

        \mu_k &= \left( \sum_{i=1}^n q_i(k) x_i \right) \left( \sum_{i=1}^n q_i(k) \right)^{-1} \\
        \Sigma_k &= \left( \sum_{i=1}^n q_i(k) (x_i - \mu_k) (x_i - \mu_k)^T \right) \left( \sum_{i=1}^n q_i(k) \right)^{-1}

 Again, this is also a specific way that combines messages from each of the mixture factors associated with them.

The analysis above shows that the E-M algorithm can be viewed as a message-passing scheme that iteratively update the states associated with each variable by exchanging messages between factors and variables. Actually, the message-passing scheme is a very general paradigm. Many widely used inference algorithms, including *mean-field based variational inference*, *belief propagation*, *expectation propagation*, *Gibbs sampling*, and *Hamiltonian Monte Carlo*, can be implemented as certain forms of message passing schemes.

Inference via Message Passing
------------------------------

Generally, a message passing procedure consists of several stages:

1. Initialize the states associated with each variable. Depending on the chosen algorithm, the states associated with a variable can be in differen forms. For example, for a discrete variable, its associated state can be a value (in Gibbs sampling or maximum-likelihood estimation), variational distribution (in variational inference), or a marginal distribution (in belief propagation or expectation propagation).

2. Iteratively invoke the following steps until convergence or other termination criteria are met.

    (a) update the message from a factor to some of its incident variables (based on updated status of other incident variables).
    (b) update variable states based on incoming messages.

3. Compute queried quantities based on variable states. For example, if a Gibbs sampling algorithm is used, the expectation of a variable can be approximated by the sample mean.

It is possible to generate such an inference procedure according to the structure of the factor graph. However, there remains several challenges to be addressed:

1. Some intermediate quantities may be used in the computation of several different messages. For example, :math:`\sum_{i=1}^n q_i(k)` appears in multiple updating formulas for GMM. It is desirable to identify these quantities and avoid unnecessary re-computation of the same value.

2. Each message depends on the states of several variables, while the states of a variable may depend on several messages. A message/variable state only needs to be updated when its depending values have changed. To identify whether a variable/message needs to be updated, a natural idea is to build a dependency graph, where each node corresponds to either a variable state or a message. By time-stamping each node, it is not difficult to see whether a node can be updated by looking at the time-stamps of each neighboring nodes.

3. Updating steps can be scheduled in numerous ways. Poor scheduling may result in slow convergence. Therefore, deriving a reasonable schedule is also important to achieve high efficiency.


text: Python library for accessing ActiveTick data


text:
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'

module Google
  module Apis
    module DatastoreV1beta1
      # Cloud Datastore API
      #
      # Accesses the schemaless NoSQL database to provide fully managed, robust,
      #  scalable storage for your application.
      #
      # @example
      #    require 'google/apis/datastore_v1beta1'
      #
      #    Datastore = Google::Apis::DatastoreV1beta1 # Alias the module
      #    service = Datastore::DatastoreService.new
      #
      # @see https://cloud.google.com/datastore/
      class DatastoreService < Google::Apis::Core::BaseService
        # @return [String]
        #  API key. Your API key identifies your project and provides you with API access,
        #  quota, and reports. Required unless you provide an OAuth 2.0 token.
        attr_accessor :key

        # @return [String]
        #  Available to use for quota purposes for server-side applications. Can be any
        #  arbitrary string assigned to a user, but should not exceed 40 characters.
        attr_accessor :quota_user

        def initialize
          super('https://datastore.googleapis.com/', '',
                client_name: 'google-apis-datastore_v1beta1',
                client_version: Google::Apis::DatastoreV1beta1::GEM_VERSION)
          @batch_path = 'batch'
        end

        # Exports a copy of all or a subset of entities from Google Cloud Datastore to
        # another storage system, such as Google Cloud Storage. Recent updates to
        # entities may not be reflected in the export. The export occurs in the
        # background and its progress can be monitored and managed via the Operation
        # resource that is created. The output of an export may only be used once the
        # associated operation is done. If an export operation is cancelled before
        # completion it may leave partial data behind in Google Cloud Storage.
        # @param [String] project_id
        #   Project ID against which to make the request.
        # @param [Google::Apis::DatastoreV1beta1::GoogleDatastoreAdminV1beta1ExportEntitiesRequest] google_datastore_admin_v1beta1_export_entities_request_object
        # @param [String] fields
        #   Selector specifying which fields to include in a partial response.
        # @param [String] quota_user
        #   Available to use for quota purposes for server-side applications. Can be any
        #   arbitrary string assigned to a user, but should not exceed 40 characters.
        # @param [Google::Apis::RequestOptions] options
        #   Request-specific options
        #
        # @yield [result, err] Result & error if block supplied
        # @yieldparam result [Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation] parsed result object
        # @yieldparam err [StandardError] error object if request failed
        #
        # @return [Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation]
        #
        # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
        # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
        # @raise [Google::Apis::AuthorizationError] Authorization is required
        def export_project(project_id, google_datastore_admin_v1beta1_export_entities_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
          command = make_simple_command(:post, 'v1beta1/projects/{projectId}:export', options)
          command.request_representation = Google::Apis::DatastoreV1beta1::GoogleDatastoreAdminV1beta1ExportEntitiesRequest::Representation
          command.request_object = google_datastore_admin_v1beta1_export_entities_request_object
          command.response_representation = Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation::Representation
          command.response_class = Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation
          command.params['projectId'] = project_id unless project_id.nil?
          command.query['fields'] = fields unless fields.nil?
          command.query['quotaUser'] = quota_user unless quota_user.nil?
          execute_or_queue_command(command, &block)
        end

        # Imports entities into Google Cloud Datastore. Existing entities with the same
        # key are overwritten. The import occurs in the background and its progress can
        # be monitored and managed via the Operation resource that is created. If an
        # ImportEntities operation is cancelled, it is possible that a subset of the
        # data has already been imported to Cloud Datastore.
        # @param [String] project_id
        #   Project ID against which to make the request.
        # @param [Google::Apis::DatastoreV1beta1::GoogleDatastoreAdminV1beta1ImportEntitiesRequest] google_datastore_admin_v1beta1_import_entities_request_object
        # @param [String] fields
        #   Selector specifying which fields to include in a partial response.
        # @param [String] quota_user
        #   Available to use for quota purposes for server-side applications. Can be any
        #   arbitrary string assigned to a user, but should not exceed 40 characters.
        # @param [Google::Apis::RequestOptions] options
        #   Request-specific options
        #
        # @yield [result, err] Result & error if block supplied
        # @yieldparam result [Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation] parsed result object
        # @yieldparam err [StandardError] error object if request failed
        #
        # @return [Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation]
        #
        # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
        # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
        # @raise [Google::Apis::AuthorizationError] Authorization is required
        def import_project(project_id, google_datastore_admin_v1beta1_import_entities_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
          command = make_simple_command(:post, 'v1beta1/projects/{projectId}:import', options)
          command.request_representation = Google::Apis::DatastoreV1beta1::GoogleDatastoreAdminV1beta1ImportEntitiesRequest::Representation
          command.request_object = google_datastore_admin_v1beta1_import_entities_request_object
          command.response_representation = Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation::Representation
          command.response_class = Google::Apis::DatastoreV1beta1::GoogleLongrunningOperation
          command.params['projectId'] = project_id unless project_id.nil?
          command.query['fields'] = fields unless fields.nil?
          command.query['quotaUser'] = quota_user unless quota_user.nil?
          execute_or_queue_command(command, &block)
        end

        protected

        def apply_command_defaults(command)
          command.query['key'] = key unless key.nil?
          command.query['quotaUser'] = quota_user unless quota_user.nil?
        end
      end
    end
  end
end


text:
var NAVTREE =
[
  [ "Lua-API++", "index.html", [
    [ "Lua API++ library", "index.html", null ],
    [ "License", "main_license.html", null ],
    [ "Basic concepts", "basic_concepts.html", [
      [ "Global state", "basic_concepts.html#basic_global_state", null ],
      [ "Lua functions and context", "basic_concepts.html#basic_state", [
        [ "Multiple return values", "basic_concepts.html#basic_state_multiret", [
          [ "Returning multiple values", "basic_concepts.html#basic_state_multiret_return", null ],
          [ "Accepting multiple return values of a call", "basic_concepts.html#basic_state_multiret_call", null ]
        ] ]
      ] ],
      [ "Lua values", "basic_concepts.html#basic_values", [
        [ "Native values", "basic_concepts.html#basic_values_native", null ],
        [ "User values", "basic_concepts.html#basic_values_user", null ],
        [ "Temporary value handling", "basic_concepts.html#basic_values_temporary", null ],
        [ "Valref", "basic_concepts.html#basic_values_valref", null ],
        [ "Anchor value types", "basic_concepts.html#basic_values_anchors", [
          [ "Value", "basic_concepts.html#basic_values_anchors_value", null ],
          [ "Table", "basic_concepts.html#basic_values_anchors_table", null ],
          [ "Valset", "basic_concepts.html#basic_values_anchors_valset", null ]
        ] ]
      ] ]
    ] ],
    [ "Motivational example", "motivational_example.html", null ],
    [ "Automatic stack management", "stack_management.html", [
      [ "Passing values to and returning from functions", "stack_management.html#stack_management_function", [
        [ "References", "stack_management.html#stack_management_function_valref", null ],
        [ "Anchors", "stack_management.html#stack_management_function_anchor", null ]
      ] ]
    ] ],
    [ "Using the library", "usage.html", [
      [ "Using the library with your project", "usage.html#usage_basic", null ],
      [ "Building the tests (for library development)", "usage.html#usage_tests", null ],
      [ "Documentation", "usage.html#Documentation", null ]
    ] ],
    [ "Configuring the library", "configuring.html", [
      [ "Compatibility", "configuring.html#configuring_compatibility", [
        [ "Lua language version", "configuring.html#configuring_compatibility_langver", null ],
        [ "NRVO support", "configuring.html#configuring_compatibility_nrvo", null ]
      ] ],
      [ "Discardability", "configuring.html#configuring_discardability", null ],
      [ "Performance", "configuring.html#configuring_performance", null ],
      [ "Debugging: stack integrity checking", "configuring.html#configuring_stack_watch", null ]
    ] ],
    [ "Performance", "performace.html", null ],
    [ "Compatibility", "compatibility.html", [
      [ "Lua 5.1", "compatibility.html#compatibility_5_1", null ],
      [ "Lua 5.2", "compatibility.html#compatibility_5_2", null ],
      [ "Lua 5.3", "compatibility.html#compatibility_5_3", null ],
      [ "NRVO compiler capability", "compatibility.html#compatibility_nrvo", null ]
    ] ],
    [ "External links", "external_links.html", null ],
    [ "FAQ", "faq.html", [
      [ "Compatibility", "faq.html#faq_compat", [
        [ "Which versions of Lua does this library support?", "faq.html#faq_compat_versions", null ],
        [ "Is this library compatible with LuaJIT?", "faq.html#faq_compat_luajit", null ]
      ] ],
      [ "Programming", "faq.html#faq_programming", [
        [ "Is it possible to use inherited classes with virtual functions as userdata?", "faq.html#faq_programming_polymorphic_userdata", null ]
      ] ],
      [ "Technical issues", "faq.html#faq_known_problems", [
        [ "I compiled the motivational example and it crashes on out-of-bound array access.", "faq.html#faq_known_problems_sjlj", null ]
      ] ]
    ] ],
    [ "Changelog", "changelog.html", [
      [ "2015-02-12-0", "changelog.html#changes_2015_02_12_0", [
        [ "2015-02-12-1", "changelog.html#changes_2015_02_12_1", null ],
        [ "2015-02-12-2", "changelog.html#changes_2015_02_12_2", null ],
        [ "2015-02-12-3", "changelog.html#changes_2015_02_12_3", null ]
      ] ],
      [ "2015-01-21-0", "changelog.html#changes_2015_01_21_0", null ],
      [ "2014-11-24-0", "changelog.html#changes_2014_11_24_0", null ],
      [ "2014-10-29-0", "changelog.html#changes_2014_10_29_0", null ],
      [ "2014-09-22-0", "changelog.html#changes_2014_09_22_0", null ],
      [ "2014-09-18-0", "changelog.html#changes_2014_09_18_0", null ],
      [ "2014-09-09-0", "changelog.html#changes_2014_09_09_0", null ],
      [ "2014-09-01-0", "changelog.html#changes_2014_09_01_0", null ],
      [ "2014-08-29-0", "changelog.html#changes_2014_08_29_0", null ],
      [ "2014-08-28-0", "changelog.html#changes_2014_08_28_0", null ],
      [ "2014-08-18-0", "changelog.html#changes_2014_08_18_0", null ]
    ] ],
    [ "Deprecated List", "deprecated.html", null ],
    [ "Namespace Members", "namespacemembers.html", [
      [ "All", "namespacemembers.html", null ],
      [ "Functions", "namespacemembers_func.html", null ],
      [ "Variables", "namespacemembers_vars.html", null ],
      [ "Typedefs", "namespacemembers_type.html", null ],
      [ "Enumerations", "namespacemembers_enum.html", null ]
    ] ],
    [ "Classes", "annotated.html", [
      [ "Class List", "annotated.html", "annotated_dup" ],
      [ "Class Index", "classes.html", null ],
      [ "Class Hierarchy", "hierarchy.html", "hierarchy" ],
      [ "Class Members", "functions.html", [
        [ "All", "functions.html", null ],
        [ "Functions", "functions_func.html", null ],
        [ "Variables", "functions_vars.html", null ],
        [ "Typedefs", "functions_type.html", null ],
        [ "Enumerations", "functions_enum.html", null ]
      ] ]
    ] ],
    [ "Files", null, [
      [ "File List", "files.html", "files" ],
      [ "File Members", "globals.html", [
        [ "All", "globals.html", null ],
        [ "Macros", "globals_defs.html", null ]
      ] ]
    ] ]
  ] ]
];

var NAVTREEINDEX =
[
"annotated.html",
"namespacemembers_enum.html"
];

var SYNCONMSG = 'click to disable panel synchronisation';
var SYNCOFFMSG = 'click to enable panel synchronisation';


text:
<?php

// need to include the module constant for this test
require_once BASE_PATH.'/modules/batchmake/constant/module.php';
require_once BASE_PATH.'/modules/batchmake/controllers/components/KWBatchmakeComponent.php';
require_once BASE_PATH.'/library/KWUtils.php';

/** helper class used for testing batchmake module */
class BatchmakeControllerTest extends ControllerTestCase
  {

  /**
   * setup function will set test config properties in the Zend_Registry
   */
  public function setup()
    {
    parent::setup();
    $testConfigProps = $this->setupAndGetConfig();
    Zend_Registry::set('batchmake_test_config', $testConfigProps);
    }

  /**
   * helper function to return Midas configured temp directory
   * @return midas temp dir
   */
  protected function getTempDirectory()
    {
    include_once BASE_PATH.'/core/GlobalController.php';
    $controller = new MIDAS_GlobalController($this->request, $this->response);
    return $controller->getTempDirectory();
    }

  /**
   * function will create a temporary batchmake config, copying over test data
   * to the the locations in that config needed for the tests, returning an
   * array of config property names to directory locations.
   * @TODO figure out a way to copy over Batchmake or else mock it
   * @return string
   */
  public function setupAndGetConfig()
    {
    // create a test batchmake setup in the temp dir
    // and initialize test data
    $tmpDir = $this->getTempDirectory() .'/';
    $subDirs = array("batchmake", "tests");
    $testDir = KWUtils::createSubDirectories($tmpDir, $subDirs);
    $configProps = array(MIDAS_BATCHMAKE_TMP_DIR_PROPERTY => $tmpDir.'/batchmake/tests/tmp',
    MIDAS_BATCHMAKE_BIN_DIR_PROPERTY => $tmpDir.'/batchmake/tests/bin',
    MIDAS_BATCHMAKE_SCRIPT_DIR_PROPERTY => $tmpDir.'/batchmake/tests/script',
    MIDAS_BATCHMAKE_APP_DIR_PROPERTY => $tmpDir.'/batchmake/tests/bin',
    MIDAS_BATCHMAKE_DATA_DIR_PROPERTY => $tmpDir.'/batchmake/tests/data',
    MIDAS_BATCHMAKE_CONDOR_BIN_DIR_PROPERTY => $tmpDir.'/batchmake/tests/condorbin');
    // now make sure these dirs exist
    // later can actually add some stuff to these dirs
    foreach($configProps as $prop => $dir)
      {
      if(!file_exists($dir) && !KWUtils::mkDir($dir))
        {
        throw new Zend_Exception("couldn't create dir ".$dir);
        }
      }

    // now copy over the bms files
    $srcDir = BASE_PATH . 'modules/batchmake/tests/testfiles/script';
    $targetDir = $configProps[MIDAS_BATCHMAKE_SCRIPT_DIR_PROPERTY];
    $extension = '.bms';
    $this->symlinkFileset($srcDir, $targetDir, $extension);

    // and now the bmms
    $srcDir = BASE_PATH . 'modules/batchmake/tests/testfiles/bin';
    $targetDir = $configProps[MIDAS_BATCHMAKE_APP_DIR_PROPERTY];
    $extension = '.bmm';
    $this->symlinkFileset($srcDir, $targetDir, $extension);

    // the mock object strategy requires both an interface and for
    // executable files to exist on disk in a particular location,
    // so here we will create symlinks to a known executable
    // ls
    // which should be on most systems

    $params = array('ls');
    $cmd = KWUtils::prepareExeccommand('which', $params);
    // dir doesn't matter, just send in srcDir as it is convenient
    KWUtils::exec($cmd, $output, $srcDir, $returnVal);
    if($returnVal !== 0 || !isset($output) || !isset($output[0]))
      {
      throw new Zend_Exception('Problem finding ls on your system, used for testing');
      }
    $pathToLs = $output[0];

    // get the applications and their path properties from the component that
    // expects them
    $applicationsPaths = Batchmake_KWBatchmakeComponent::getApplicationsPaths();
    foreach($applicationsPaths as $application => $pathProperty)
      {
      // now in the place of each executable, symlink the ls exe
      $link = $configProps[$pathProperty] . '/' . $application;
      if(!file_exists($link) && !symlink($pathToLs, $link))
        {
        throw new Zend_Exception($pathToLs . ' could not be sym-linked to ' . $link);
        }
      }

    return $configProps;
    }

  /**
   * looks in the srcDir, finds all files ending with $extension, and
   * symlinks them to targetDir if there isn't already a file there
   * by that name
   * @param type $srcDir
   * @param type $targetDir
   * @param type $extension
   */
  protected function symlinkFileset($srcDir, $targetDir, $extension)
    {
    // open the directory
    $handle = opendir($srcDir);
    if(!is_readable($srcDir))
      {
      throw new Zend_Exception("can't read ".$srcDir);
      }
    // and scan through the items inside
    while(false !== ($item = readdir($handle)))
      {
      // make sure item matches extendsion
      if((strpos($item, $extension) == strlen($item) - 4))
        {
        // link the file if it isn't already there
        $scriptTarget = $srcDir . '/' . $item;
        $scriptLink = $targetDir . '/' . $item;
        if(!file_exists($scriptLink) && !symlink($scriptTarget, $scriptLink))
          {
          throw new Zend_Exception($scriptTarget . ' could not be sym-linked to ' . $scriptLink);
          }
        }
      }
    closedir($handle);
    }

  }


text:
module.exports = {
  EMPTY: 'empty', //room created but no users joined (default status)
  WAITING: 'waiting', // at least one user in room, waiting for more
  FULL: 'full', // room full: all users joined
  READY: 'ready', // room ready: all users joined and connected
  STARTED: 'started' // room started
};


text:
/**
 * audio_cluster_descriptor_imp.cpp
 *
 * Audio Cluster descriptor implementation
 */

#include <thread>
#include <mutex>

#include "avdecc_error.h"
#include "enumeration.h"
#include "log_imp.h"
#include "end_station_imp.h"
#include "audio_cluster_descriptor_imp.h"

namespace avdecc_lib
{
audio_cluster_descriptor_imp::audio_cluster_descriptor_imp(end_station_imp * end_station_obj, const uint8_t * frame, ssize_t pos, size_t frame_len) : descriptor_base_imp(end_station_obj, frame, frame_len, pos) {}

audio_cluster_descriptor_imp::~audio_cluster_descriptor_imp() {}

audio_cluster_descriptor_response * STDCALL audio_cluster_descriptor_imp::get_audio_cluster_response()
{
    std::lock_guard<std::mutex> guard(base_end_station_imp_ref->locker); //mutex lock end station
    return resp = new audio_cluster_descriptor_response_imp(resp_ref->get_desc_buffer(),
                                                            resp_ref->get_desc_size(), resp_ref->get_desc_pos());
}
}


text:
<?php

namespace Markup\NeedleBundle\Tests\Suggest;

use Markup\NeedleBundle\Suggest\SolrSuggestService;
use Markup\NeedleBundle\Suggest\SuggestServiceInterface;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class SolrSuggestServiceTest extends TestCase
{
    protected function setUp()
    {
        $this->solarium = m::mock('Solarium\Client');
        $this->suggester = new SolrSuggestService($this->solarium);
    }

    protected function tearDown()
    {
        m::close();
    }

    public function testIsSuggestService()
    {
        $this->assertInstanceOf(SuggestServiceInterface::class, $this->suggester);
    }
}


text:
package org.apache.flink.types.parser;

import org.apache.flink.types.StringValue;

public class UnquotedStringValueParserTest extends ParserTestBase<StringValue> {

    @Override
    public String[] getValidTestValues() {
        return new String[] {
                "abcdefgh", "i", "jklmno", "\"abc\"defgh\"", "\"i\"", "Hello9"
        };
    }

    @Override
    public StringValue[] getValidTestResults() {
        return new StringValue[] {
                new StringValue("abcdefgh"), new StringValue("i"), new StringValue("jklmno"),
                new StringValue("\"abc\"defgh\""), new StringValue("\"i\""), new StringValue("Hello9")
        };
    }

    @Override
    public String[] getInvalidTestValues() {
        return new String[] { };
    }

	@Override
	public boolean allowsEmptyField() {
		return true;
	}

    @Override
    public FieldParser<StringValue> getParser() {
        return new StringValueParser();
    }

    @Override
    public Class<StringValue> getTypeClass() {
        return StringValue.class;
    }
}


text:
define(function(require) {
	var modE = require('./mod-e');
	return {};
});


text:
package com.squareup.timessquare;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import com.squareup.timessquare.MonthCellDescriptor.RangeState;

public class CalendarCellView extends TextView {
  private static final int[] STATE_SELECTABLE = {
      R.attr.tsquare_state_selectable
  };
  private static final int[] STATE_CURRENT_MONTH = {
      R.attr.tsquare_state_current_month
  };
  private static final int[] STATE_TODAY = {
      R.attr.tsquare_state_today
  };
  private static final int[] STATE_HIGHLIGHTED = {
      R.attr.tsquare_state_highlighted
  };
  private static final int[] STATE_RANGE_FIRST = {
      R.attr.tsquare_state_range_first
  };
  private static final int[] STATE_RANGE_MIDDLE = {
      R.attr.tsquare_state_range_middle
  };
  private static final int[] STATE_RANGE_LAST = {
      R.attr.tsquare_state_range_last
  };

  private boolean isSelectable = false;
  private boolean isCurrentMonth = false;
  private boolean isToday = false;
  private boolean isHighlighted = false;
  private RangeState rangeState = RangeState.NONE;

  @SuppressWarnings("UnusedDeclaration") //
  public CalendarCellView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public void setSelectable(boolean isSelectable) {
    this.isSelectable = isSelectable;
    refreshDrawableState();
  }

  public void setCurrentMonth(boolean isCurrentMonth) {
    this.isCurrentMonth = isCurrentMonth;
    refreshDrawableState();
  }

  public void setToday(boolean isToday) {
    this.isToday = isToday;
    refreshDrawableState();
  }

  public void setRangeState(MonthCellDescriptor.RangeState rangeState) {
    this.rangeState = rangeState;
    refreshDrawableState();
  }

  public void setHighlighted(boolean highlighted) {
    isHighlighted = highlighted;
    refreshDrawableState();
  }

  public boolean isCurrentMonth() {
    return isCurrentMonth;
  }

  public boolean isToday() {
    return isToday;
  }

  public boolean isSelectable() {
    return isSelectable;
  }

  @Override protected int[] onCreateDrawableState(int extraSpace) {
    final int[] drawableState = super.onCreateDrawableState(extraSpace + 5);

    if (isSelectable) {
      mergeDrawableStates(drawableState, STATE_SELECTABLE);
    }

    if (isCurrentMonth) {
      mergeDrawableStates(drawableState, STATE_CURRENT_MONTH);
    }

    if (isToday) {
      mergeDrawableStates(drawableState, STATE_TODAY);
    }

    if (isHighlighted) {
      mergeDrawableStates(drawableState, STATE_HIGHLIGHTED);
    }

    if (rangeState == MonthCellDescriptor.RangeState.FIRST) {
      mergeDrawableStates(drawableState, STATE_RANGE_FIRST);
    } else if (rangeState == MonthCellDescriptor.RangeState.MIDDLE) {
      mergeDrawableStates(drawableState, STATE_RANGE_MIDDLE);
    } else if (rangeState == RangeState.LAST) {
      mergeDrawableStates(drawableState, STATE_RANGE_LAST);
    }

    return drawableState;
  }
}


text:
require 'benchmark'
require 'inversion_of_array.rb'

array = []
for i in 1..10000
  array << i
end
array.shuffle!

time = Benchmark.measure do
  inversions = InversionOfArray.inversions(BruteForceStrategy.new,array)
  p "Inversions #{inversions}"
end

p time


text:
sap.ui.define("openui5/googlemaps/TravelMode", ['jquery.sap.global'],
    function(jQuery) {
        "use strict";
        var TravelMode = {
            driving: 'DRIVING',
            walking: 'WALKING',
            bicycling: 'BICYCLING',
            transit: 'TRANSIT'
        };
        return TravelMode;

    }, /* bExport= */ true);


text:
namespace DentalSoft.Data.Contracts.Addresses
{
    public class RegionFilter
    {
        public int? Id { get; set; }

        public string Name { get; set; }
    }
}


text:
'use strict';

var morgan = require('morgan'),
	moment = require('moment');

morgan.token('logTime', function(req, res) {
	return moment().format('YYYY-MM-DD h:mm:ss');
});

var format = {
	dev: 'dev',
	manual: '[:logTime] :remote-addr :method :url :status :res[content-length] -:response-time ms'
};

module.exports = function(app) {
	// Showing stack errors
	app.set('showStackError', true);
	app.use(morgan(format.manual));
	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		//app.use(morgan('dev'));
		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

};


text:
import { Accounts } from 'meteor/accounts-base'
import { Meteor } from 'meteor/meteor';
import {
  Migrations,
} from '../imports/collections.js';

// Create Default API User
const defaultAccountExists = Meteor.users.findOne({ username: Meteor.settings.private.username });
const createDefaultUserMigration = Migrations.findOne({ name: 'CreateDefaultUser' });

if (!defaultAccountExists && !createDefaultUserMigration) {
  const userId = Accounts.createUser({
    email: Meteor.settings.private.email,
    username: Meteor.settings.private.username,
    password: Meteor.settings.private.password,
  });
  Accounts.setPassword(userId, Meteor.settings.private.password);
  Migrations.insert({ name: 'CreateDefaultUser' });
}


text:
object PatmatADT {
  abstract sealed class Odd(x: Odd)

  case class Good(x: Odd) extends Odd(x)
  case class Bad(x: Odd) extends Odd(x)

  def foo1a(x: Odd) = x match { // warning: Good(_: Bad), Bad(_: Good)
    case Good(_: Good) => false
    case Bad(_: Bad) => false
  }

  def foo1b(x: Odd) = x match {
    case Good(_: Good) => false
    case Bad(_: Bad) => false
    case Good(_: Bad) => false
    case Bad(_: Good) => false
  }

  def foo2(x: Option[Int]) = x match { // warning: Some(_: Int)
    case Some(_: Double) => true
    case None => true
  }

  def foo3a[T](x: Option[T]) = (x, x) match { // warning: (Some(_), Some(_)), (None, Some(_))
    case (Some(_), None) => true
    case (None, None) => true
  }

  def foo3b[T](x: Option[T]) = (x, x) match { // warning: (Some(_), Some(_)), (None, None)
    case (Some(_), None) => true
    case (None, Some(_)) => true
  }

  sealed trait Base
  case class Foo() extends Base

  def foo4(x: Base) = x match {
    case Foo() =>
  }

  sealed abstract class CL3Literal
  case object IntLit extends CL3Literal
  case object CharLit extends CL3Literal
  case object BooleanLit extends CL3Literal

  sealed abstract class Tree
  case class LetL(value: CL3Literal) extends Tree

  def foo5(tree: Tree) : Any = tree match {
    case LetL(CharLit) =>
  }

  def foo6[T](l: List[T]): Boolean = l match {
    case x::xs => true
    case Nil => false
  }
}


text:
namespace HeroicallyRecipes.Web.Models.Account
{
    using System.ComponentModel.DataAnnotations;
    using HeroicallyRecipes.Common.Validation;

    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [Display(Name = "Nickname")]
        [RegularExpression(ModelConstants.NickNamePattern, ErrorMessage = "Invalid username characters.")]
        [StringLength(ModelConstants.UserNickNameMaxLength, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = ModelConstants.UserNickNameMinLength)]
        public string NickName { get; set; }
    }
}


text:
const config = require('config');
const rethink = require('rethinkdb');

const DATABASE_NAME = config.get('database.name').toString();
const TABLE_NAME = 'jenkins_metrics';
const INDEX_NAME = 'jobName';
const PRIMARY_KEY = 'url';

function connection() {
  return rethink.connect(config.get('database'))
    .then(conn => ensureDatabase(conn)
        .catch(error => {
          connectionDisposer(conn);
          throw error;
        }))
    .disposer(connectionDisposer);
}

function insert(conn, data) {
  return getTable().insert(data)
    .run(conn)
    .then(result => result)
    .catch(err => err);
}

function ensureDatabase(conn) {
  return rethink.dbList()
    .run(conn)
    .then(databases => ((databases.indexOf(DATABASE_NAME) !== -1)
        ? ensureTable(conn)
        : createDatabase(conn)));
}

function createDatabase(conn) {
  return rethink.dbCreate(DATABASE_NAME)
    .run(conn)
    .then(() => ensureTable(conn));
}

function ensureTable(conn) {
  return getDb()
    .tableList()
    .run(conn)
    .then(tables =>
      ((tables.indexOf(TABLE_NAME) !== -1)
          ? ensureIndex(conn)
          : createTable(conn)));
}

function ensureIndex(conn) {
  return getTable()
    .indexList()
    .run(conn)
    .then(indexes => ((indexes.indexOf(INDEX_NAME) !== -1)
        ? waitForIndex(conn)
        : createIndex(conn)));
}

function createTable(conn) {
  return getDb()
    .tableCreate(TABLE_NAME, { primaryKey: PRIMARY_KEY })
      .run(conn)
      .then(() => createIndex(conn));
}

function createIndex(conn) {
  return getDb()
    .table(TABLE_NAME)
    .indexCreate(INDEX_NAME)
    .run(conn)
    .then(() => waitForIndex(conn));
}

function waitForIndex(conn) {
  return getTable()
    .indexWait(INDEX_NAME)
    .run(conn)
    .then(() => conn);
}

function connectionDisposer(conn) {
  if (conn) {
    try {
      conn.close();
    } catch (error) {
      console.error(error);
      process.exit(1);
    }
  }
}

function getTable() {
  return getDb().table(TABLE_NAME);
}

function getDb() {
  return rethink.db(DATABASE_NAME);
}

module.exports = {
  connection,
  insert
};


text:
<?php

namespace Coyote\Http\Grids\Adm\Forum;

use Coyote\Forum;
use Coyote\Services\Grid\Components\CreateButton;
use Coyote\Services\Grid\Grid;
use Boduch\Grid\Components\EditButton;

class ReasonsGrid extends Grid
{
    public function buildGrid()
    {
        $this
            ->addColumn('id', [
                'title' => 'ID'
            ])
            ->addColumn('name', [
                'title' => 'Nazwa',
                'clickable' => function (Forum\Reason $reason) {
                    return link_to_route('adm.forum.reasons.save', $reason->name, [$reason->id]);
                }
            ])
            ->addRowAction(new EditButton(function (Forum\Reason $reason) {
                return route('adm.forum.reasons.save', [$reason->id]);
            }))
            ->addComponent(
                new CreateButton(
                    route('adm.forum.reasons.save'),
                    'Nowa pozycja'
                )
            );
    }
}


text:
  <title>Websheets Demo</title>
  <link rel="stylesheet" href="../src/websheet.css" />


text:
module AppBuild
  module Plugin
    class Auth < Plugin::Base
      def name; "auth"; end

      gem 'ember_auth_rails', :github => "mharris717/ember_auth_rails", :branch => :master
      gem "multiauth", :github => "mharris717/multiauth", :branch => :master

      define_step "migrations" do
        run_cmd "rake multiauth_engine:install:migrations"
        run_cmd "rake ember_auth_rails_engine:install:migrations"
      end

      define_step "add login partial to layout" do
        File.append_after "#{path}/app/views/layouts/application.html.erb","<body>","\n  <%= render :partial => 'layouts/user' %>"
      end
    end
  end
end