text:
<?php declare(strict_types=1);

namespace Deployer\Task;

use Deployer\Exception\Exception;
use function Deployer\Support\array_flatten;

class ScriptManager
{
    /**
     * @var TaskCollection
     */
    private $tasks;
    /**
     * @var bool
     */
    private $hooksEnabled = true;
    /**
     * @var array
     */
    private $visitedTasks = [];

    public function __construct(TaskCollection $tasks)
    {
        $this->tasks = $tasks;
    }

    /**
     * Return tasks to run.
     *
     * @return Task[]
     */
    public function getTasks(string $name, ?string $startFrom = null, array &$skipped = []): array
    {
        $tasks = [];
        $this->visitedTasks = [];
        $allTasks = $this->doGetTasks($name);

        if ($startFrom === null) {
            $tasks = $allTasks;
        } else {
            $skip = true;
            foreach ($allTasks as $task) {
                if ($skip) {
                    if ($task->getName() === $startFrom) {
                        $skip = false;
                    } else {
                        $skipped[] = $task->getName();
                        continue;
                    }
                }
                $tasks[] = $task;
            }
            if (count($tasks) === 0) {
                throw new Exception('All tasks skipped via --start-from option. Nothing to run.');
            }
        }

        $enabledTasks = [];
        foreach ($tasks as $task) {
            if ($task->isEnabled()) {
                $enabledTasks[] = $task;
            }
        }

        return $enabledTasks;
    }

    /**
     * @return Task[]
     */
    public function doGetTasks(string $name): array
    {
        if (array_key_exists($name, $this->visitedTasks)) {
            if ($this->visitedTasks[$name] >= 100) {
                throw new Exception("Looks like a circular dependency with \"$name\" task.");
            }
            $this->visitedTasks[$name]++;
        } else {
            $this->visitedTasks[$name] = 1;
        }

        $tasks = [];
        $task = $this->tasks->get($name);
        if ($this->hooksEnabled) {
            $tasks = array_merge(array_map([$this, 'doGetTasks'], $task->getBefore()), $tasks);
        }
        if ($task instanceof GroupTask) {
            foreach ($task->getGroup() as $taskName) {
                $subTasks = $this->doGetTasks($taskName);
                foreach ($subTasks as $subTask) {
                    $subTask->addSelector($task->getSelector());
                    if ($task->isOnce()) {
                        $subTask->once();
                    }
                    $tasks[] = $subTask;
                }
            }
        } else {
            $tasks[] = $task;
        }
        if ($this->hooksEnabled) {
            $tasks = array_merge($tasks, array_map([$this, 'doGetTasks'], $task->getAfter()));
        }
        return array_flatten($tasks);
    }

    public function getHooksEnabled(): bool
    {
        return $this->hooksEnabled;
    }

    public function setHooksEnabled(bool $hooksEnabled): void
    {
        $this->hooksEnabled = $hooksEnabled;
    }
}


text:
const router = module.exports = express.Router(); // eslint-disable-line new-cap
const shortid = require("shortid");
const { classify } = require(`${__dirname}/../../../misc/classify.js`);
const validLang = require(`${__dirname}/../../../misc/validLang.js`);

// POST /documents (create document)
router.post("/", app.ratelimit(1, 2.5), async (req, res) => {
	let content = req.body.content;

	if(!content) {
		res.status(400).json({ message: "No content" }).end();
	} else if(content.length >= 250000) {
		res.status(400).json({ message: "Content over 100,000 characters" }).end();
	} else {
		let id = shortid.generate();

		let lang = req.body.language, fulllang;
		if(lang) ({ extension: lang, codemirror: fulllang } = validLang(lang));
		if(!lang) lang = fulllang = classify(content);

		let insertion = { id, content, possibleLanguage: lang };
		console.log(`New paste (${id}) - Language: ${lang} (${fulllang})`);
		await r.table("documents").insert(insertion).run();
		res.status(201).json(insertion).end();
	}
});

// GET /documents/id (get document)
router.get("/:id", app.ratelimit(5, 5), async (req, res) => {
	let id = req.params.id;
	let document = await r.table("documents").get(id).run();
	if(document) {
		res.status(200).json(document).end();
	} else {
		res.status(404).json({ message: "Document not found" }).end();
	}
});

redpajama_set_name: RedPajamaGithub


text:
jest.dontMock('../js/components/Game.react.js');

describe('Game', function() {

  var React = require('react/addons');
  var TestUtils = React.addons.TestUtils;
  var Game;

  beforeEach(function() {
    Game = require('../js/components/Game.react');
  });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd "
	default-lazy-init="false">

	<description>缓存管理 redis session集群实现</description>
	<!-- redis Start -->
	<!-- 对象池配置: -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="-1" />
		<property name="maxIdle" value="200" />
		<property name="maxWaitMillis" value="3000" />
		<property name="testOnBorrow" value="true" />
		<property name="testOnReturn" value="true" />
	</bean>

	<!-- redis 连接配置Start  (集群和单机只能有一个实现) -->
	<!--  sentinel 集群配置Start -->
	<!--<import resource="classpath:shiro/redis/redis-sentinel.xml"/>-->
	<!--  sentinel 集群配置End -->

	<!-- redis 单机配置Start -->
	<import resource="classpath:shiro/redis/redis.xml"/>
	<!-- redis 单机配置End -->
	<!-- redis 连接配置End -->

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
	</bean>

	<!-- 缓存管理器 -->
	<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" >
		<constructor-arg ref="redisTemplate"/>
	</bean>

	<bean id="cacheImpl" class="com.yang.spinach.common.utils.redis.cache.RedisCache">
		<property name="redisTemplate" ref="redisTemplate" />
		<property name="expire" value="86400" />
	</bean>

	<bean id="cacheManager" class="com.yang.spinach.common.shiro.ShiroRedisCacheManager">
		<property name="cache" ref="cacheImpl" />
	</bean>
	<bean id="sessionDAO" class="com.yang.spinach.common.shiro.ShiroSessionDao">
		<property name="sessionIdGenerator" ref="sessionIdGenerator" />
		<property name="cache" ref="cacheImpl"></property>
		<property name="expire" value="1800"></property>
	</bean>

	<!-- 凭证匹配器 -->
	<bean id="credentialsMatcher" class="com.yang.spinach.common.shiro.RedisLoginMatcher">
		<property name="cache" ref="cacheImpl"></property>
		<property name="hashAlgorithmName" value="md5" />
		<property name="hashIterations" value="2" />
		<property name="storedCredentialsHexEncoded" value="true" />
	</bean>
</beans>


text:
using Citicon.Data;
using Citicon.DataManager;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Citicon.Payables
{
    public partial class ChequeIssuanceForm : Form
    {
        private PayableManager payableManager;
        private BankManager bankManager;
        private BankAccountManager bankAccountManager;
        private CompanyManager CompanyManager;
        private Supplier payee;
        private Payable[] payables;
        private Bank[] banks;
        private BankAccount[] bankAccounts;
        private string[] checkVoucherNumbers;
        private List<Bank> tempBanks;
        private List<BankAccount> tempBankAccounts;
        private decimal grandTotalAmount;
        private BankAccount selectedBankAccount;
        private List<Supplier> MultiSuppliers;

        string checkVoucherNumber;
        public ChequeIssuanceForm()
        {
            InitializeComponent();
            MultiSuppliers = new List<Supplier>();

            payableManager = new PayableManager();
            payableManager.ExceptionCatched += ExceptionCatched;
            //payableManager.NewChequeVoucherNumber += PayableManager_NewChequeVoucherNumber;
            payableManager.NewItemByChequeVoucherNumber += PayableManager_NewItemByChequeVoucherNumber;
            payableManager.Updated += PayableManager_Updated;

            bankManager = new BankManager();
            bankManager.ExceptionCatched += ExceptionCatched;
            bankManager.NewItemGenerated += BankManager_NewItemGenerated;

            bankAccountManager = new BankAccountManager();
            bankAccountManager.ExceptionCatched += ExceptionCatched;
            bankAccountManager.NewItemGenerated += BankAccountManager_NewItemGenerated;

            CompanyManager = new CompanyManager();
        }

        private void PayableManager_Updated(Payable e)
        {
            tbxCheckVoucherNumber.AutoCompleteCustomSource.Remove(e.ChequeVoucherNumber);

            //if (e.Description != ConfigurationManager.AppSettings["Payable.Description.InputTax"])
            //{
            //    grandTotalAmount += e.Debit;
            //}

            if (e.Expense == Expense.CashInBank)
            {
                grandTotalAmount += e.Value;
            }
        }

        private void BankAccountManager_NewItemGenerated(BankAccount e)
        {
            tempBankAccounts.Add(e);
        }

        private void BankManager_NewItemGenerated(Bank e)
        {
            if (e != null)
            {
                tempBanks.Add(e);
                Invoke(new Action(() => cmbxBanks.Items.Add(e)));
            }
        }

        private async Task LoadBanks()
        {
            tempBanks.Clear();
            banks = await bankManager.GetListAsync();
            cmbxBanks.Items.Add(banks);
        }

        private async Task LoadBankAccounts()
        {
            tempBankAccounts.Clear();
            bankAccounts = await bankAccountManager.GetListAsync();
        }

        private void PayableManager_NewItemByChequeVoucherNumber(Payable e)
        {
            Invoke(new Action(() =>
            {
                if (payee == null) payee = e.Supplier;
                if (!MultiSuppliers.Contains(e.Supplier))
                {
                    MultiSuppliers.Add(e.Supplier);
                }
                dgvPayables.Rows.Add(e, e.Company, e.Branch, e.Value.ToString("#,##0.00"));
            }));
        }

        private void PayableManager_NewChequeVoucherNumber(string e)
        {
            //Invoke(new Action(() => tbxCheckVoucherNumber.AutoCompleteCustomSource.Add(e)));
        }

        private void ExceptionCatched(Exception ex)
        {
            if (Supports.DebugMode) MessageBox.Show(ex.Message);
        }

        private async void ChequeIssuanceForm_Load(object sender, EventArgs e)
        {
            tempBanks = new List<Bank>();
            tempBankAccounts = new List<BankAccount>();
            await LoadCheckVoucherNumbers();
            await LoadBanks();
            await LoadBankAccounts();
            await LoadCompanies();
        }

        private async Task LoadCheckVoucherNumbers()
        {
            tbxCheckVoucherNumber.AutoCompleteCustomSource.Clear();
            checkVoucherNumbers = await payableManager.GetChequeVoucherNumberAsync(false);

            if (checkVoucherNumbers != null)
            {
                tbxCheckVoucherNumber.AutoCompleteCustomSource.AddRange(checkVoucherNumbers);
            }
        }

        private async Task LoadCompanies()
        {
            ChequeCompanyComboBox.Items.Clear();

            try
            {
                var companies = await CompanyManager.GetListAsync();

                if (companies != null && companies.Any())
                {
                    ChequeCompanyComboBox.Items.AddRange(companies);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async Task SetCheckVoucherNumberAsync()
        {
            var x = tbxCheckVoucherNumber.Text.Trim();
            Color backColor = Color.White;
            Color foreColor = Color.Black;
            if (checkVoucherNumbers.Contains(x))
            {
                backColor = Color.FromArgb(50, 50, 50);
                foreColor = Color.FromArgb(255, 192, 192);
                if (x != checkVoucherNumber)
                {
                    payee = null;
                    MultiSuppliers.Clear();
                    checkVoucherNumber = x;
                    dgvPayables.Rows.Clear();
                    payables = await payableManager.GetListByChequeVoucherNumberAsync(x);
                    grandTotalAmount = 0;

                    foreach (DataGridViewRow row in dgvPayables.Rows)
                    {
                        var payable = (Payable)row.Cells[colPayable.Name].Value;

                        if (payable.Expense == Expense.CashInBank)
                        {
                            grandTotalAmount += payable.Value;
                        }
                    }
                    tbxGrandTotal.Text = Math.Abs(grandTotalAmount).ToString("#,##0.00");
                    tbxPayee.Text = payee.Description;
                }
            }
            tbxCheckVoucherNumber.BackColor = backColor;
            tbxCheckVoucherNumber.ForeColor = foreColor;
            tbxPayee.BackColor = backColor;
            tbxPayee.ForeColor = foreColor;

            if (MultiSuppliers.Count > 1)
            {
                MessageBox.Show("Multiple suppliers found.");
                ClearCheckVoucherNumber();
                return;
            }
        }

        private void ClearCheckVoucherNumber()
        {
            Color backColor = Color.White;
            Color foreColor = Color.Black;
            tbxCheckVoucherNumber.Text = string.Empty;
            tbxPayee.Text = string.Empty;
            tbxCheckVoucherNumber.BackColor = backColor;
            tbxCheckVoucherNumber.ForeColor = foreColor;
            tbxPayee.BackColor = backColor;
            tbxPayee.ForeColor = foreColor;
            payee = null;
            dgvPayables.Rows.Clear();
        }

        private void lblChangeCheckVoucherNumber_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ClearCheckVoucherNumber();
        }

        private async void tbxCheckVoucherNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) await SetCheckVoucherNumberAsync();
        }

        private void tbxCheckVoucherNumber_Leave(object sender, EventArgs e)
        {
            //await setCheckVoucherNumber();
        }

        private void cmbxBanks_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbxBankAccounts.Items.Clear();
            cmbxBankAccounts.Items.AddRange(tempBankAccounts.Where(x => x.Bank == (Bank)cmbxBanks.SelectedItem)?.ToArray());
            tbxBank.Text = (cmbxBanks.SelectedItem as Bank)?.ToString();
        }

        private void tbxPayee_TextChanged(object sender, EventArgs e)
        {

        }

        private void cmbxBankAccounts_SelectedIndexChanged(object sender, EventArgs e)
        {
            var bankAccount = (BankAccount)cmbxBankAccounts.SelectedItem;
            if (bankAccount.ChequeNumberEnd >= bankAccount.ChequeNumber)
            {
                tbxCheckNumber.Text = bankAccount.ChequeNumber.ToString("0000000");
            }
            else
            {
                tbxCheckNumber.Text = "0000000";
                MessageBox.Show("Insufficient cheque number!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            tbxBankAccount.Text = bankAccount?.ToString();
        }

        private async void btnExportCheque_Click(object sender, EventArgs e)
        {
            if (selectedBankAccount != null)
            {
                if (dgvPayables.Rows.Count > 0)
                {
                    grandTotalAmount = 0;
                    var rawChequeNumber = tbxCheckNumber.Text.Trim();
                    var chequeNumber = uint.Parse(rawChequeNumber);
                    var chequeCompany = ChequeCompanyComboBox.SelectedItem as Company;
                    if (chequeNumber <= 0)
                    {
                        MessageBox.Show("Insufficient cheque number!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (await ChequeManager.IsCancelledAsync(rawChequeNumber, cmbxBankAccounts.SelectedItem as BankAccount))
                    {
                        MessageBox.Show("Cheque is cancelled.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (await payableManager.ChequeNumberExistsAsync(chequeNumber))
                    {
                        MessageBox.Show("Cheque No. already exists.");
                        return;
                    }

                    foreach (DataGridViewRow row in dgvPayables.Rows)
                    {
                        var payable = (Payable)row.Cells[colPayable.Name].Value;
                        payable.ChequeNumber = rawChequeNumber;
                        payable.ChequeDate = dtpChequeDate.Value;
                        payable.BankAccount = selectedBankAccount;
                        payable.TransactionDate = Supports.SystemDate;
                        payable.ChequeCompany = chequeCompany;
                        payableManager.Update(payable);
                    }

                    payableManager.ExportCheque(grandTotalAmount, payee, dtpChequeDate.Value);
                    selectedBankAccount.ChequeNumber++;
                    bankAccountManager.Update(selectedBankAccount);
                    await LoadCheckVoucherNumbers();
                    dgvPayables.Rows.Clear();
                    tbxCheckNumber.Text = "0000000";
                    tbxCheckVoucherNumber.Text = string.Empty;
                    tbxPayee.Text = string.Empty;
                    ChequeCompanyComboBox.SelectedItem = null;
                    payee = null;
                    tbxGrandTotal.Text = "0.00";
                    ClearCheckVoucherNumber();
                    MessageBox.Show("Done!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else MessageBox.Show("No Payables in the list!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else MessageBox.Show("Please verify all details!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void tbxCheckVoucherNumber_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnRange_Click(object sender, EventArgs e)
        {
            var form = new ChequeNumberRangeForm(cmbxBankAccounts.SelectedItem as BankAccount);
            form.ShowDialog();

            selectedBankAccount = form.CurrentBankAccount;

            if (selectedBankAccount != null)
            {
                cmbxBanks.SelectedItem = selectedBankAccount.Bank;
                cmbxBankAccounts.SelectedItem = selectedBankAccount;
                tbxBank.Text = selectedBankAccount.Bank?.Description;
                tbxBankAccount.Text = selectedBankAccount.Description;
                tbxCheckNumber.Text = selectedBankAccount.ChequeNumber.ToString("0000000");
            }
        }
    }
}


text:
package com.charles.coolweather.util;

/**
 * 接口,回调服务返回的结果
 */
public interface HttpCallbackListener {
    void onFinish(String response);

    void onError(Exception e);
}


text:
require File.expand_path('../../../../../spec_helper', __FILE__)
require 'net/http'
require File.expand_path('../fixtures/http_server', __FILE__)

describe "Net::HTTP#finish" do
  before :each do
    NetHTTPSpecs.start_server
    @http = Net::HTTP.new("localhost", 3333)
  end

  after :each do
    @http.finish if @http.started?
    NetHTTPSpecs.stop_server
  end

  describe "when self has been started" do
    it "closes the tcp connection" do
      @http.start
      @http.finish
      @http.started?.should be_false
    end
  end

  describe "when self has not been started yet" do
    it "raises an IOError" do
      lambda { @http.finish }.should raise_error(IOError)
    end
  end
end


text:
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
import logging

from tornado.options import define, options

define('port', default=8000, type=int)
logging.basicConfig(level=logging.INFO)

class IndexHander(tornado.web.RequestHandler):
    def get(self):
        arg = self.get_argument('q', 'Hello')
        logging.info('type in ' + arg)
        self.write(arg + ' world!')

settings = {'debug': True}  # 开启debug 的参数
if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r'/', IndexHander)], **settings)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
    logging.info('server started...')


text:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
    <style name="AppTheme.CircularProgress">
        <item name="circularProgressBarStyle">@style/FamilyLink.CircularProgressBarLight</item>
    </style>

    <style name="TextAppearance.AppTheme" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/default_text_color</item>
    </style>
    <style name="TextAppearance.AppTheme.ListItem" parent="@android:style/TextAppearance.Large">
    </style>

    <style name="FamilyLink.CircularProgressBarLight" parent="@style/CircularProgressBarLight">
        <item name="progress_color">@android:color/holo_red_light</item>
    </style>

</resources>


text:
<?php namespace Modules\Media\Entities;

use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Modules\Media\Image\Facade\Imagy;
use Modules\Media\ValueObjects\MediaPath;

/**
 * Class File
 * @package Modules\Media\Entities
 * @property \Modules\Media\ValueObjects\MediaPath path
 */
class File extends Model
{
    use Translatable;
    /**
     * All the different images types where thumbnails should be created
     * @var array
     */
    private $imageExtensions = ['jpg', 'png', 'jpeg', 'gif'];

    protected $table = 'media__files';
    public $translatedAttributes = ['description', 'alt_attribute', 'keywords'];
    protected $fillable = [
        'description',
        'alt_attribute',
        'keywords',
        'filename',
        'path',
        'extension',
        'mimetype',
        'width',
        'height',
        'filesize',
        'folder_id',
    ];
    protected $appends = ['path_string'];

    public function getPathAttribute($value)
    {
        return new MediaPath($value);
    }

    public function getPathStringAttribute()
    {
        return (string) $this->path;
    }

    public function isImage()
    {
        return in_array(pathinfo($this->path, PATHINFO_EXTENSION), $this->imageExtensions);
    }

    public function getThumbnail($type)
    {
        if ($this->isImage() && $this->getKey()) {
            return Imagy::getThumbnail($this->path, $type);
        }

        return false;
    }
}


text:
module.exports = handler

var debug = require('debug')('qpm_faucet:home')
var fs    = require('fs')
var wc    = require('webcredits')
var wc_db = require('wc_db')

function handler(req, res) {

  var origin = req.headers.origin
  if (origin) {
    res.setHeader('Access-Control-Allow-Origin', origin)
  }

  if (!req.session.userId) {
    res.send('Must be authenticated via WebID.  Get a webid NOW!')
    return
  }

  var config = res.locals.config

  res.status(200)
  res.header('Content-Type', 'text/html');

  res.render('pages/home', { ui : config.ui })

/*
  res.write('Welcome to HTTP 402 test.  Options:')
  res.write('
\n')
  res.write('See your balance ')
  res.write('
\n')
  res.write('Visit the faucet if you dont have enough credits')
  res.write('
\n')
*/

}


text: Adenine - Framework using React, Redux, ...


text:
@interface CustomCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UILabel *subTitleLabel;

@property (weak, nonatomic) IBOutlet UIImageView *myImageView;

@end


text:
package com.gshakhn.privatewiki.client.components

import com.gshakhn.privatewiki.client.components.testutil.{PrivateWikiBaseSpec, PageInteractions}
import PageInteractions._
import org.scalajs.jquery._
import org.scalatest.path

class BinderLoaderButtonSpec extends PrivateWikiBaseSpec {

  override def newInstance: path.FunSpecLike = new BinderLoaderButtonSpec

  describe("A PrivateWiki with a BinderLoader component") {
    implicit val client = new TestClient
    render

    describe("with no binder name") {
      enterBinderName("")

      describe("and no password") {
        enterBinderPassword("")

        it("should disable the button") {
          jQuery("#binder-button") should haveClass("disabled")
        }
      }

      describe("and a password") {
        enterBinderPassword("secure")

        it("should disable the button") {
          jQuery("#binder-button") should haveClass("disabled")
        }
      }
    }

    describe("with a binder name") {
      enterBinderName("new binder")

      describe("and no password") {
        enterBinderPassword("")

        it("should disable the button") {
          jQuery("#binder-button") should haveClass("disabled")
        }
      }

      describe("and a password") {
        enterBinderPassword("secure")

        it("should enable the button") {
          jQuery("#binder-button") shouldNot haveClass("disabled")
        }
      }
    }
  }

  tearDown()
}


text:
package example;

import java.io.File;

import libs.BaseTest;

import org.openqa.selenium.By;

public class CalcExample extends BaseTest{

	public CalcExample(){
	}

	public CalcExample(int deviceNum) {
		super(deviceNum);
	}

	public void performOperations() {

		try
		{
			driver.findElement(By.id("com.android2.calculator3:id/cling_dismiss")).click();
			driver.findElement(By.id("com.android2.calculator3:id/digit5")).click();
			driver.findElement(By.id("com.android2.calculator3:id/plus")).click();
			driver.findElement(By.id("com.android2.calculator3:id/digit9")).click();
			driver.findElement(By.id("com.android2.calculator3:id/equal")).click();
			String num = driver.findElement(By.xpath("//android.widget.EditText[@index=0]")).getText();
			System.out.println("Result : "+num);
			driver.closeApp();
	    }
	    catch(Exception e)
	    {
	    	e.printStackTrace();
	    }
	}

	public void run(){
		File app = new File("src/example/AndroidCalculator.apk");
		String appPath = app.getAbsolutePath();
		createDriver(appPath); // create devices
		performOperations(); // user function
	}

	public static void main(String[] args) {
		// Create object
		CalcExample calc = new CalcExample();
		calc.execute();
	}
}


text:
	.carousel-fade .carousel-inner .item {
		opacity: 0;
		-webkit-transition-property: opacity;
		transition-property: opacity;
		-webkit-transition-duration: .2s;
		transition-duration: .2s;
	}

	.carousel-fade .carousel-inner .active {
		opacity: 1;
		-moz-transition: opacity ease-in-out .2s;
		-o-transition: opacity ease-in-out .2s;
		-webkit-transition: opacity ease-in-out .2s;
		transition: opacity ease-in-out .2s;
	}

	.carousel-inner,
	.carousel,
	html,
	body,
	.carousel-inner .item {
		height: 100%;
	}

	.carousel.carousel-fade .item {
		opacity: 0.4;
	}

	.carousel.carousel-fade .active.item {
		opacity: 1;
	}


text:
#include "linux/config.h"
#include "linux/kernel.h"
#include "linux/netdevice.h"
#include "linux/rtnetlink.h"
#include "linux/skbuff.h"
#include "linux/socket.h"
#include "linux/spinlock.h"
#include "linux/module.h"
#include "linux/init.h"
#include "linux/etherdevice.h"
#include "linux/list.h"
#include "linux/inetdevice.h"
#include "linux/ctype.h"
#include "linux/bootmem.h"
#include "linux/ethtool.h"
#include "linux/platform_device.h"
#include "asm/uaccess.h"
#include "user_util.h"
#include "kern_util.h"
#include "net_kern.h"
#include "net_user.h"
#include "mconsole_kern.h"
#include "init.h"
#include "irq_user.h"
#include "irq_kern.h"

#define DRIVER_NAME "uml-netdev"

static DEFINE_SPINLOCK(opened_lock);
static LIST_HEAD(opened);

static int uml_net_rx(struct net_device *dev)
{
	struct uml_net_private *lp = dev->priv;
	int pkt_len;
	struct sk_buff *skb;

	/* If we can't allocate memory, try again next round. */
	skb = dev_alloc_skb(dev->mtu);
	if (skb == NULL) {
		lp->stats.rx_dropped++;
		return 0;
	}

	skb->dev = dev;
	skb_put(skb, dev->mtu);
	skb->mac.raw = skb->data;
	pkt_len = (*lp->read)(lp->fd, &skb, lp);

	if (pkt_len > 0) {
		skb_trim(skb, pkt_len);
		skb->protocol = (*lp->protocol)(skb);
		netif_rx(skb);

		lp->stats.rx_bytes += skb->len;
		lp->stats.rx_packets++;
		return pkt_len;
	}

	kfree_skb(skb);
	return pkt_len;
}

static void uml_dev_close(void* dev)
{
	dev_close( (struct net_device *) dev);
}

irqreturn_t uml_net_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
	struct net_device *dev = dev_id;
	struct uml_net_private *lp = dev->priv;
	int err;

	if(!netif_running(dev))
		return(IRQ_NONE);

	spin_lock(&lp->lock);
	while((err = uml_net_rx(dev)) > 0) ;
	if(err < 0) {
		DECLARE_WORK(close_work, uml_dev_close, dev);
		printk(KERN_ERR
		       "Device '%s' read returned %d, shutting it down\n",
		       dev->name, err);
		/* dev_close can't be called in interrupt context, and takes
		 * again lp->lock.
		 * And dev_close() can be safely called multiple times on the
		 * same device, since it tests for (dev->flags & IFF_UP). So
		 * there's no harm in delaying the device shutdown. */
		schedule_work(&close_work);
		goto out;
	}
	reactivate_fd(lp->fd, UM_ETH_IRQ);

out:
	spin_unlock(&lp->lock);
	return(IRQ_HANDLED);
}

static int uml_net_open(struct net_device *dev)
{
	struct uml_net_private *lp = dev->priv;
	int err;

	spin_lock(&lp->lock);

	if(lp->fd >= 0){
		err = -ENXIO;
		goto out;
	}

	if(!lp->have_mac){
 		dev_ip_addr(dev, &lp->mac[2]);
 		set_ether_mac(dev, lp->mac);
	}

	lp->fd = (*lp->open)(&lp->user);
	if(lp->fd < 0){
		err = lp->fd;
		goto out;
	}

	err = um_request_irq(dev->irq, lp->fd, IRQ_READ, uml_net_interrupt,
			     SA_INTERRUPT | SA_SHIRQ, dev->name, dev);
	if(err != 0){
		printk(KERN_ERR "uml_net_open: failed to get irq(%d)\n", err);
		err = -ENETUNREACH;
		goto out_close;
	}

	lp->tl.data = (unsigned long) &lp->user;
	netif_start_queue(dev);

	/* clear buffer - it can happen that the host side of the interface
	 * is full when we get here.  In this case, new data is never queued,
	 * SIGIOs never arrive, and the net never works.
	 */
	while((err = uml_net_rx(dev)) > 0) ;

	spin_unlock(&lp->lock);

	spin_lock(&opened_lock);
	list_add(&lp->list, &opened);
	spin_unlock(&opened_lock);

	return 0;
out_close:
	if(lp->close != NULL) (*lp->close)(lp->fd, &lp->user);
	lp->fd = -1;
out:
	spin_unlock(&lp->lock);
	return err;
}

static int uml_net_close(struct net_device *dev)
{
	struct uml_net_private *lp = dev->priv;

	netif_stop_queue(dev);
	spin_lock(&lp->lock);

	free_irq(dev->irq, dev);
	if(lp->close != NULL)
		(*lp->close)(lp->fd, &lp->user);
	lp->fd = -1;

	spin_unlock(&lp->lock);

	spin_lock(&opened_lock);
	list_del(&lp->list);
	spin_unlock(&opened_lock);

	return 0;
}

static int uml_net_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
	struct uml_net_private *lp = dev->priv;
	unsigned long flags;
	int len;

	netif_stop_queue(dev);

	spin_lock_irqsave(&lp->lock, flags);

	len = (*lp->write)(lp->fd, &skb, lp);

	if(len == skb->len) {
		lp->stats.tx_packets++;
		lp->stats.tx_bytes += skb->len;
		dev->trans_start = jiffies;
		netif_start_queue(dev);

		/* this is normally done in the interrupt when tx finishes */
		netif_wake_queue(dev);
	}
	else if(len == 0){
		netif_start_queue(dev);
		lp->stats.tx_dropped++;
	}
	else {
		netif_start_queue(dev);
		printk(KERN_ERR "uml_net_start_xmit: failed(%d)\n", len);
	}

	spin_unlock_irqrestore(&lp->lock, flags);

	dev_kfree_skb(skb);

	return 0;
}

static struct net_device_stats *uml_net_get_stats(struct net_device *dev)
{
	struct uml_net_private *lp = dev->priv;
	return &lp->stats;
}

static void uml_net_set_multicast_list(struct net_device *dev)
{
	if (dev->flags & IFF_PROMISC) return;
	else if (dev->mc_count)	dev->flags |= IFF_ALLMULTI;
	else dev->flags &= ~IFF_ALLMULTI;
}

static void uml_net_tx_timeout(struct net_device *dev)
{
	dev->trans_start = jiffies;
	netif_wake_queue(dev);
}

static int uml_net_set_mac(struct net_device *dev, void *addr)
{
	struct uml_net_private *lp = dev->priv;
	struct sockaddr *hwaddr = addr;

	spin_lock(&lp->lock);
	memcpy(dev->dev_addr, hwaddr->sa_data, ETH_ALEN);
	spin_unlock(&lp->lock);

	return(0);
}

static int uml_net_change_mtu(struct net_device *dev, int new_mtu)
{
	struct uml_net_private *lp = dev->priv;
	int err = 0;

	spin_lock(&lp->lock);

	new_mtu = (*lp->set_mtu)(new_mtu, &lp->user);
	if(new_mtu < 0){
		err = new_mtu;
		goto out;
	}

	dev->mtu = new_mtu;

 out:
	spin_unlock(&lp->lock);
	return err;
}

static void uml_net_get_drvinfo(struct net_device *dev,
				struct ethtool_drvinfo *info)
{
	strcpy(info->driver, DRIVER_NAME);
	strcpy(info->version, "42");
}

static struct ethtool_ops uml_net_ethtool_ops = {
	.get_drvinfo	= uml_net_get_drvinfo,
	.get_link	= ethtool_op_get_link,
};

void uml_net_user_timer_expire(unsigned long _conn)
{
#ifdef undef
	struct connection *conn = (struct connection *)_conn;

	dprintk(KERN_INFO "uml_net_user_timer_expire [%p]\n", conn);
	do_connect(conn);
#endif
}

static DEFINE_SPINLOCK(devices_lock);
static LIST_HEAD(devices);

static struct platform_driver uml_net_driver = {
	.driver = {
		.name  = DRIVER_NAME,
	},
};
static int driver_registered;

static int eth_configure(int n, void *init, char *mac,
			 struct transport *transport)
{
	struct uml_net *device;
	struct net_device *dev;
	struct uml_net_private *lp;
	int save, err, size;

	size = transport->private_size + sizeof(struct uml_net_private) +
		sizeof(((struct uml_net_private *) 0)->user);

	device = kmalloc(sizeof(*device), GFP_KERNEL);
	if (device == NULL) {
		printk(KERN_ERR "eth_configure failed to allocate uml_net\n");
		return(1);
	}

	memset(device, 0, sizeof(*device));
	INIT_LIST_HEAD(&device->list);
	device->index = n;

	spin_lock(&devices_lock);
	list_add(&device->list, &devices);
	spin_unlock(&devices_lock);

	if (setup_etheraddr(mac, device->mac))
		device->have_mac = 1;

	printk(KERN_INFO "Netdevice %d ", n);
	if (device->have_mac)
		printk("(%02x:%02x:%02x:%02x:%02x:%02x) ",
		       device->mac[0], device->mac[1],
		       device->mac[2], device->mac[3],
		       device->mac[4], device->mac[5]);
	printk(": ");
	dev = alloc_etherdev(size);
	if (dev == NULL) {
		printk(KERN_ERR "eth_configure: failed to allocate device\n");
		return 1;
	}

	lp = dev->priv;
	/* This points to the transport private data. It's still clear, but we
	 * must memset it to 0 *now*. Let's help the drivers. */
	memset(lp, 0, size);

	/* sysfs register */
	if (!driver_registered) {
		platform_driver_register(&uml_net_driver);
		driver_registered = 1;
	}
	device->pdev.id = n;
	device->pdev.name = DRIVER_NAME;
	platform_device_register(&device->pdev);
	SET_NETDEV_DEV(dev,&device->pdev.dev);

	/* If this name ends up conflicting with an existing registered
	 * netdevice, that is OK, register_netdev{,ice}() will notice this
	 * and fail.
	 */
	snprintf(dev->name, sizeof(dev->name), "eth%d", n);
	device->dev = dev;

	(*transport->kern->init)(dev, init);

	dev->mtu = transport->user->max_packet;
	dev->open = uml_net_open;
	dev->hard_start_xmit = uml_net_start_xmit;
	dev->stop = uml_net_close;
	dev->get_stats = uml_net_get_stats;
	dev->set_multicast_list = uml_net_set_multicast_list;
	dev->tx_timeout = uml_net_tx_timeout;
	dev->set_mac_address = uml_net_set_mac;
	dev->change_mtu = uml_net_change_mtu;
	dev->ethtool_ops = &uml_net_ethtool_ops;
	dev->watchdog_timeo = (HZ >> 1);
	dev->irq = UM_ETH_IRQ;

	rtnl_lock();
	err = register_netdevice(dev);
	rtnl_unlock();
	if (err) {
		device->dev = NULL;
		/* XXX: should we call ->remove() here? */
		free_netdev(dev);
		return 1;
	}

	/* lp.user is the first four bytes of the transport data, which
	 * has already been initialized.  This structure assignment will
	 * overwrite that, so we make sure that .user gets overwritten with
	 * what it already has.
	 */
	save = lp->user[0];
	*lp = ((struct uml_net_private)
		{ .list  		= LIST_HEAD_INIT(lp->list),
		  .dev 			= dev,
		  .fd 			= -1,
		  .mac 			= { 0xfe, 0xfd, 0x0, 0x0, 0x0, 0x0},
		  .have_mac 		= device->have_mac,
		  .protocol 		= transport->kern->protocol,
		  .open 		= transport->user->open,
		  .close 		= transport->user->close,
		  .remove 		= transport->user->remove,
		  .read 		= transport->kern->read,
		  .write 		= transport->kern->write,
		  .add_address 		= transport->user->add_address,
		  .delete_address  	= transport->user->delete_address,
		  .set_mtu 		= transport->user->set_mtu,
		  .user  		= { save } });

	init_timer(&lp->tl);
	spin_lock_init(&lp->lock);
	lp->tl.function = uml_net_user_timer_expire;
	if (lp->have_mac)
		memcpy(lp->mac, device->mac, sizeof(lp->mac));

	if (transport->user->init)
		(*transport->user->init)(&lp->user, dev);

	if (device->have_mac)
		set_ether_mac(dev, device->mac);

	return 0;
}

static struct uml_net *find_device(int n)
{
	struct uml_net *device;
	struct list_head *ele;

	spin_lock(&devices_lock);
	list_for_each(ele, &devices){
		device = list_entry(ele, struct uml_net, list);
		if(device->index == n)
			goto out;
	}
	device = NULL;
 out:
	spin_unlock(&devices_lock);
	return(device);
}

static int eth_parse(char *str, int *index_out, char **str_out)
{
	char *end;
	int n;

	n = simple_strtoul(str, &end, 0);
	if(end == str){
		printk(KERN_ERR "eth_setup: Failed to parse '%s'\n", str);
		return(1);
	}
	if(n < 0){
		printk(KERN_ERR "eth_setup: device %d is negative\n", n);
		return(1);
	}
	str = end;
	if(*str != '='){
		printk(KERN_ERR
		       "eth_setup: expected '=' after device number\n");
		return(1);
	}
	str++;
	if(find_device(n)){
		printk(KERN_ERR "eth_setup: Device %d already configured\n",
		       n);
		return(1);
	}
	if(index_out) *index_out = n;
	*str_out = str;
	return(0);
}

struct eth_init {
	struct list_head list;
	char *init;
	int index;
};

/* Filled in at boot time.  Will need locking if the transports become
 * modular.
 */
struct list_head transports = LIST_HEAD_INIT(transports);

/* Filled in during early boot */
struct list_head eth_cmd_line = LIST_HEAD_INIT(eth_cmd_line);

static int check_transport(struct transport *transport, char *eth, int n,
			   void **init_out, char **mac_out)
{
	int len;

	len = strlen(transport->name);
	if(strncmp(eth, transport->name, len))
		return(0);

	eth += len;
	if(*eth == ',')
		eth++;
	else if(*eth != '\0')
		return(0);

	*init_out = kmalloc(transport->setup_size, GFP_KERNEL);
	if(*init_out == NULL)
		return(1);

	if(!transport->setup(eth, mac_out, *init_out)){
		kfree(*init_out);
		*init_out = NULL;
	}
	return(1);
}

void register_transport(struct transport *new)
{
	struct list_head *ele, *next;
	struct eth_init *eth;
	void *init;
	char *mac = NULL;
	int match;

	list_add(&new->list, &transports);

	list_for_each_safe(ele, next, &eth_cmd_line){
		eth = list_entry(ele, struct eth_init, list);
		match = check_transport(new, eth->init, eth->index, &init,
					&mac);
		if(!match)
			continue;
		else if(init != NULL){
			eth_configure(eth->index, init, mac, new);
			kfree(init);
		}
		list_del(&eth->list);
	}
}

static int eth_setup_common(char *str, int index)
{
	struct list_head *ele;
	struct transport *transport;
	void *init;
	char *mac = NULL;

	list_for_each(ele, &transports){
		transport = list_entry(ele, struct transport, list);
	        if(!check_transport(transport, str, index, &init, &mac))
			continue;
		if(init != NULL){
			eth_configure(index, init, mac, transport);
			kfree(init);
		}
		return(1);
	}
	return(0);
}

static int eth_setup(char *str)
{
	struct eth_init *new;
	int n, err;

	err = eth_parse(str, &n, &str);
	if(err) return(1);

	new = alloc_bootmem(sizeof(new));
	if (new == NULL){
		printk("eth_init : alloc_bootmem failed\n");
		return(1);
	}

	INIT_LIST_HEAD(&new->list);
	new->index = n;
	new->init = str;

	list_add_tail(&new->list, &eth_cmd_line);
	return(1);
}

__setup("eth", eth_setup);
__uml_help(eth_setup,
"eth[0-9]+=<transport>,<options>\n"
"    Configure a network device.\n\n"
);

#if 0
static int eth_init(void)
{
	struct list_head *ele, *next;
	struct eth_init *eth;

	list_for_each_safe(ele, next, &eth_cmd_line){
		eth = list_entry(ele, struct eth_init, list);

		if(eth_setup_common(eth->init, eth->index))
			list_del(&eth->list);
	}

	return(1);
}
__initcall(eth_init);
#endif

static int net_config(char *str)
{
	int n, err;

	err = eth_parse(str, &n, &str);
	if(err) return(err);

	str = kstrdup(str, GFP_KERNEL);
	if(str == NULL){
		printk(KERN_ERR "net_config failed to strdup string\n");
		return(-1);
	}
	err = !eth_setup_common(str, n);
	if(err)
		kfree(str);
	return(err);
}

static int net_id(char **str, int *start_out, int *end_out)
{
        char *end;
        int n;

	n = simple_strtoul(*str, &end, 0);
	if((*end != '\0') || (end == *str))
		return -1;

        *start_out = n;
        *end_out = n;
        *str = end;
        return n;
}

static int net_remove(int n)
{
	struct uml_net *device;
	struct net_device *dev;
	struct uml_net_private *lp;

	device = find_device(n);
	if(device == NULL)
		return -ENODEV;

	dev = device->dev;
	lp = dev->priv;
	if(lp->fd > 0)
                return -EBUSY;
	if(lp->remove != NULL) (*lp->remove)(&lp->user);
	unregister_netdev(dev);
	platform_device_unregister(&device->pdev);

	list_del(&device->list);
	kfree(device);
	free_netdev(dev);
	return 0;
}

static struct mc_device net_mc = {
	.name		= "eth",
	.config		= net_config,
	.get_config	= NULL,
        .id		= net_id,
	.remove		= net_remove,
};

static int uml_inetaddr_event(struct notifier_block *this, unsigned long event,
			      void *ptr)
{
	struct in_ifaddr *ifa = ptr;
	struct net_device *dev = ifa->ifa_dev->dev;
	struct uml_net_private *lp;
	void (*proc)(unsigned char *, unsigned char *, void *);
	unsigned char addr_buf[4], netmask_buf[4];

	if(dev->open != uml_net_open) return(NOTIFY_DONE);

	lp = dev->priv;

	proc = NULL;
	switch (event){
	case NETDEV_UP:
		proc = lp->add_address;
		break;
	case NETDEV_DOWN:
		proc = lp->delete_address;
		break;
	}
	if(proc != NULL){
		memcpy(addr_buf, &ifa->ifa_address, sizeof(addr_buf));
		memcpy(netmask_buf, &ifa->ifa_mask, sizeof(netmask_buf));
		(*proc)(addr_buf, netmask_buf, &lp->user);
	}
	return(NOTIFY_DONE);
}

struct notifier_block uml_inetaddr_notifier = {
	.notifier_call		= uml_inetaddr_event,
};

static int uml_net_init(void)
{
	struct list_head *ele;
	struct uml_net_private *lp;
	struct in_device *ip;
	struct in_ifaddr *in;

	mconsole_register_dev(&net_mc);
	register_inetaddr_notifier(&uml_inetaddr_notifier);

	/* Devices may have been opened already, so the uml_inetaddr_notifier
	 * didn't get a chance to run for them.  This fakes it so that
	 * addresses which have already been set up get handled properly.
	 */
	list_for_each(ele, &opened){
		lp = list_entry(ele, struct uml_net_private, list);
		ip = lp->dev->ip_ptr;
		if(ip == NULL) continue;
		in = ip->ifa_list;
		while(in != NULL){
			uml_inetaddr_event(NULL, NETDEV_UP, in);
			in = in->ifa_next;
		}
	}

	return(0);
}

__initcall(uml_net_init);

static void close_devices(void)
{
	struct list_head *ele;
	struct uml_net_private *lp;

	list_for_each(ele, &opened){
		lp = list_entry(ele, struct uml_net_private, list);
		free_irq(lp->dev->irq, lp->dev);
		if((lp->close != NULL) && (lp->fd >= 0))
			(*lp->close)(lp->fd, &lp->user);
		if(lp->remove != NULL) (*lp->remove)(&lp->user);
	}
}

__uml_exitcall(close_devices);

int setup_etheraddr(char *str, unsigned char *addr)
{
	char *end;
	int i;

	if(str == NULL)
		return(0);
	for(i=0;i<6;i++){
		addr[i] = simple_strtoul(str, &end, 16);
		if((end == str) ||
		   ((*end != ':') && (*end != ',') && (*end != '\0'))){
			printk(KERN_ERR
			       "setup_etheraddr: failed to parse '%s' "
			       "as an ethernet address\n", str);
			return(0);
		}
		str = end + 1;
	}
	if(addr[0] & 1){
		printk(KERN_ERR
		       "Attempt to assign a broadcast ethernet address to a "
		       "device disallowed\n");
		return(0);
	}
	return(1);
}

void dev_ip_addr(void *d, unsigned char *bin_buf)
{
	struct net_device *dev = d;
	struct in_device *ip = dev->ip_ptr;
	struct in_ifaddr *in;

	if((ip == NULL) || ((in = ip->ifa_list) == NULL)){
		printk(KERN_WARNING "dev_ip_addr - device not assigned an "
		       "IP address\n");
		return;
	}
	memcpy(bin_buf, &in->ifa_address, sizeof(in->ifa_address));
}

void set_ether_mac(void *d, unsigned char *addr)
{
	struct net_device *dev = d;

	memcpy(dev->dev_addr, addr, ETH_ALEN);
}

struct sk_buff *ether_adjust_skb(struct sk_buff *skb, int extra)
{
	if((skb != NULL) && (skb_tailroom(skb) < extra)){
	  	struct sk_buff *skb2;

		skb2 = skb_copy_expand(skb, 0, extra, GFP_ATOMIC);
		dev_kfree_skb(skb);
		skb = skb2;
	}
	if(skb != NULL) skb_put(skb, extra);
	return(skb);
}

void iter_addresses(void *d, void (*cb)(unsigned char *, unsigned char *,
					void *),
		    void *arg)
{
	struct net_device *dev = d;
	struct in_device *ip = dev->ip_ptr;
	struct in_ifaddr *in;
	unsigned char address[4], netmask[4];

	if(ip == NULL) return;
	in = ip->ifa_list;
	while(in != NULL){
		memcpy(address, &in->ifa_address, sizeof(address));
		memcpy(netmask, &in->ifa_mask, sizeof(netmask));
		(*cb)(address, netmask, arg);
		in = in->ifa_next;
	}
}

int dev_netmask(void *d, void *m)
{
	struct net_device *dev = d;
	struct in_device *ip = dev->ip_ptr;
	struct in_ifaddr *in;
	__u32 *mask_out = m;

	if(ip == NULL)
		return(1);

	in = ip->ifa_list;
	if(in == NULL)
		return(1);

	*mask_out = in->ifa_mask;
	return(0);
}

void *get_output_buffer(int *len_out)
{
	void *ret;

	ret = (void *) __get_free_pages(GFP_KERNEL, 0);
	if(ret) *len_out = PAGE_SIZE;
	else *len_out = 0;
	return(ret);
}

void free_output_buffer(void *buffer)
{
	free_pages((unsigned long) buffer, 0);
}

int tap_setup_common(char *str, char *type, char **dev_name, char **mac_out,
		     char **gate_addr)
{
	char *remain;

	remain = split_if_spec(str, dev_name, mac_out, gate_addr, NULL);
	if(remain != NULL){
		printk("tap_setup_common - Extra garbage on specification : "
		       "'%s'\n", remain);
		return(1);
	}

	return(0);
}

unsigned short eth_protocol(struct sk_buff *skb)
{
	return(eth_type_trans(skb, skb->dev));
}

/*
 * Overrides for Emacs so that we follow Linus's tabbing style.
 * Emacs will notice this stuff at the end of the file and automatically
 * adjust the settings for this buffer only.  This must remain at the end
 * of the file.
 * ---------------------------------------------------------------------------
 * Local variables:
 * c-file-style: "linux"
 * End:
 */


text:
/* eslint-disable no-template-curly-in-string */
export default {
  participants: {
    address: 'Address',
    alreadyRegistered: 'I am already registered',
    backHome: 'Back to overview',
    contact: 'Contact',
    dateOfBirth: 'Date of birth',
    dateOfBirthHelp: 'Minimum age is 18 years old. Please read the festival rules.',
    details: 'Personal information',
    email: 'E-mail',
    emailHelp: 'We will communicate news related to your signup using this e-mail. You definitely want to put a real e-mail here.',
    entry: 'Enter the system',
    failedLogin: 'Unknown e-mail and password combination.',
    festivalTerms: 'Festival rules',
    forgottenPassword: 'Forgotten password',
    forgottenPasswordHelp: 'Enter the e-mail you use to login. We will send you steps to recover your password.',
    fullName: 'Your full name',
    fullNameHelp: 'First Name, Middle Name, Last name and every other name given to you by parents',
    home: 'My Improtřesk',
    changeDetails: 'Edit',
    changeIdentification: 'Set identity',
    changePassword: 'Change Password',
    changePasswordHelp: 'Enter your old password, enter your new password and repeat.',
    changePasswordSuccess: 'Your password was changed successfully. You may login with it now.',
    changePersonalInformation: 'Personal information',
    identificationSettings: 'Identification settings',
    identityFinished: 'It is done! Thank you.',
    identityFormHelp: 'We consider this information highly confidential. Rest assured that we will use them only to arrange your accomodation. We never give these to third parties without asking you first.',
    idNumber: 'ID Number',
    improvAge: 'Improtřesk age',
    login: 'Login',
    logout: 'Logout',
    lunchRegistrationHeading: 'Lunch',
    lunchRegistrationProcess: 'We will send you the festival menu later by e-mail. It always contains at least one option for vegetarians.',
    mightHaveAccountHelp: 'It is possible you have account from last year. Save some time by reusing it.',
    mustBeOlderThan18: 'You must at least 18 years old',
    name: 'Name',
    newPassword: 'New Password',
    newPasswordHelp: 'Enter your new password and save it to be able to login again.',
    newPasswordCheck: 'New Password check',
    newsletter: 'I want to receive news about Improliga',
    newUserHelp: 'Register with this festival to get access to signup form. This step is free.',
    oldPassword: 'Old Password',
    password: 'Password',
    passwordChangeEmailSent: 'We sent instructions to change your password to e-mail address you provided.',
    passwordCheck: 'Check password',
    passwordsDoNotMatch: 'New password and password check do not match',
    paymentHeading: 'Payment and e-mail confirmation',
    paymentProcess: 'You can pay for the signup only using account transfer.',
    phoneNumber: 'Phone number',
    phoneNumberHelp: 'If we find anything worng with your signup, we will first try to contact you on phone, secondly on e-mail. If you do not provide us with your phone number, you take responsibility into your hands.',
    qrCheckin: 'Download QR Ticket',
    register: 'Register',
    registration: 'Registration',
    resetPassword: 'Reset password',
    saveChanges: 'Save changes',
    signupDateUnsure: 'We do not have signup open date for this year yet. Watch news and our Facebook page.',
    signupHowtoHeading: 'How to...?',
    signupHowtoProcess: 'We will send you confirmation e-mail about everything that is related to your signup and payment. Later, we will prompt you to choose lunch',
    signupIntro: 'First we need to get you into the system.  There is just a few simple personal questions we need you to answer. It should not take longer than five minutes. You can choose Workshop, Food and Accomodation <b>in the second step</b>.',
    signupOpenDateExact: 'Signups will open exactly on ${date}. Until then, you can check your account from previous years.',
    signupRegistrationHeading: 'Registration',
    signupRegistrationInfo: 'We need all the information for accounting purposes. We never provide them to third parties. It is your responsibility to fill all the information correctly. We reserve the right to cancel any signup with incorrect information without returning your money back.',
    signupsAlreadyClosed: 'Signups are already closed',
    signupsAlreadyFull: 'All workshops are full',
    signupsNotOpenYet: 'Signups are not open yet',
    signupSuccess: 'Signup was successful. Now you can log in.',
    signupsWillOpen: 'Signups will open',
    signupToFestival: 'Signup to Improtřesk',
    signupTooLate: 'It is too late for signups now, we do not accept any more.',
    team: 'Your improv group',
    teamHelp: 'We use this for statistics and assigning safe sleeping space.',
    workshopRegistrationHeading: 'Workshop registration',
    workshopRegistrationNecessary: 'Wait for the confirmation e-mail before you tell your friends that you are on the workshop. If you are not sure, please write us an e-mail.',
    workshopRegistrationProcess: 'You can reserve a spot only at workshops that are not full. We will give you payment ID after the reservation, which we keep open for 7 days. If you do not pay in time, your spot will be offered to other participants. It may happen that open workshop spots will go temporarily up and down, it is not a mistake.'
  }
}


text:
#include "Buffer.h"
#include "CommandDescriptorScsi.h"
#include "ScsiCommandExtensions.h"

void cScsiCommandExtensions_GetScsiCommandExtensions(std::unique_ptr<vtStor::IScsiCommandExtensions>& ScsiCommandExtensions)
{
    ScsiCommandExtensions = std::unique_ptr<vtStor::IScsiCommandExtensions>(new vtStor::Scsi::cScsiCommandExtensions());
}

namespace vtStor
{
    namespace Scsi
    {
        cScsiCommandExtensions::cScsiCommandExtensions()
        {
        }

        cScsiCommandExtensions::~cScsiCommandExtensions()
        {
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_Inquiry(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.Command6.OpCode = SCSI_COMMAND_INQUIRY;
            commandInputFields.Command6.Length = 36;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::COMMAND_6;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::READ_FROM_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_Read16(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data, U32 Lba, U16 Count)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.Command16.OpCode = SCSI_COMMAND_READ16;
            commandInputFields.Command16.Lba = Lba;
            commandInputFields.Command16.Length = Count;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::COMMAND_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::READ_FROM_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = Count * StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_Read10(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data, U32 Lba, U16 Count)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.Command10.OpCode = SCSI_COMMAND_READ10;
            commandInputFields.Command10.Lba = Lba;
            commandInputFields.Command10.Length = Count;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::COMMAND_10;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::READ_FROM_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = Count * StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_Write16(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data, U32 Lba, U16 Count)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.Command16.OpCode = SCSI_COMMAND_WRITE16;
            commandInputFields.Command16.Lba = Lba;
            commandInputFields.Command16.Length = Count;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::COMMAND_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::WRITE_TO_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = Count * StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_Write10(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data, U32 Lba, U16 Count)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.Command10.OpCode = SCSI_COMMAND_WRITE10;
            commandInputFields.Command10.Lba = Lba;
            commandInputFields.Command10.Length = Count;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::COMMAND_10;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::WRITE_TO_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = Count * StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_AtaIdentifyDevice(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            commandDescriptor->Memset(0);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.AtaPassThrough16.OpCode = SCSI_COMMAND_ATA_PASS_THROUGH;
            commandInputFields.AtaPassThrough16.Command = ATA_SUBCOMMAND_IDENTIFY_DEVICE;
            commandInputFields.AtaPassThrough16.Protocol = 0x04;            // PIO Data In
            commandInputFields.AtaPassThrough16.TDir = 0x01;                // Device to host
            commandInputFields.AtaPassThrough16.TLength = 0x03;             // Transfer length is specified in STPSIU

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::ATAPASSTHROUGH_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::READ_FROM_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_AtaReadDma(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data, U32 Lba, U16 Count)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            commandDescriptor->Memset(0);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.AtaPassThrough16.OpCode = SCSI_COMMAND_ATA_PASS_THROUGH;
            commandInputFields.AtaPassThrough16.Command = ATA_SUBCOMMAND_READ_DMA;
            commandInputFields.AtaPassThrough16.Protocol = 0x06;            // DMA
            commandInputFields.AtaPassThrough16.TDir = 0x01;                // Device to host
            commandInputFields.AtaPassThrough16.TLength = 0x03;             // Transfer length is specified in STPSIU
            commandInputFields.AtaPassThrough16.Features = 0x00;
            commandInputFields.AtaPassThrough16.Lba = Lba;
            commandInputFields.AtaPassThrough16.SectorCount = Count;
            commandInputFields.AtaPassThrough16.Device = 0x40;
            commandInputFields.AtaPassThrough16.Control = 0x00;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::ATAPASSTHROUGH_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::READ_FROM_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = Count * StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_AtaWriteDma(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data, U32 Lba, U16 Count)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            commandDescriptor->Memset(0);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.AtaPassThrough16.OpCode = SCSI_COMMAND_ATA_PASS_THROUGH;
            commandInputFields.AtaPassThrough16.Command = ATA_SUBCOMMAND_WRITE_DMA;
            commandInputFields.AtaPassThrough16.Protocol = 0x06;            // DMA
            commandInputFields.AtaPassThrough16.TDir = 0x00;                // Host to Device
            commandInputFields.AtaPassThrough16.TLength = 0x03;             // Transfer length is specified in STPSIU
            commandInputFields.AtaPassThrough16.Features = 0x00;
            commandInputFields.AtaPassThrough16.Lba = Lba;
            commandInputFields.AtaPassThrough16.SectorCount = Count;
            commandInputFields.AtaPassThrough16.Device = 0x40;
            commandInputFields.AtaPassThrough16.Control = 0x00;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::ATAPASSTHROUGH_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::WRITE_TO_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = Count * StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_AtaReadBuffer(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            commandDescriptor->Memset(0);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.AtaPassThrough16.OpCode = SCSI_COMMAND_ATA_PASS_THROUGH;
            commandInputFields.AtaPassThrough16.Command = ATA_SUBCOMMAND_READ_BUFFER;
            commandInputFields.AtaPassThrough16.Protocol = 0x04;            // PIO Data In
            commandInputFields.AtaPassThrough16.TDir = 0x01;                // Device to host
            commandInputFields.AtaPassThrough16.TLength = 0x03;             // Transfer length is specified in STPSIU

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::ATAPASSTHROUGH_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::READ_FROM_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_AtaWriteBuffer(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            commandDescriptor->Memset(0);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.AtaPassThrough16.OpCode = SCSI_COMMAND_ATA_PASS_THROUGH;
            commandInputFields.AtaPassThrough16.Command = ATA_SUBCOMMAND_WRITE_BUFFER;
            commandInputFields.AtaPassThrough16.Protocol = 0x05;            // PIO Data Out
            commandInputFields.AtaPassThrough16.TDir = 0x00;                // Host to device
            commandInputFields.AtaPassThrough16.TLength = 0x03;             // Transfer length is specified in STPSIU

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::ATAPASSTHROUGH_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::WRITE_TO_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }

        eErrorCode cScsiCommandExtensions::IssueCommand_AtaSmart(std::shared_ptr<IDrive> Drive, U32 CommandType, std::shared_ptr<IBuffer> Data, U8 SubCommand)
        {
            std::shared_ptr<IBuffer> commandDescriptor = std::make_shared<cBuffer>(cCommandDescriptorScsi::SIZE_IN_BYTES);
            commandDescriptor->Memset(0);
            cCommandDescriptorScsi commandDescriptorScsi = cCommandDescriptorScsi::Writer(commandDescriptor);

            StorageUtility::Scsi::uCommandInputFields& commandInputFields = commandDescriptorScsi.GetCommandInputFields();
            commandInputFields.AtaPassThrough16.OpCode = SCSI_COMMAND_ATA_PASS_THROUGH;
            commandInputFields.AtaPassThrough16.Command = ATA_SUBCOMMAND_SMART;
            commandInputFields.AtaPassThrough16.Protocol = 0x04;            // PIO Data In
            commandInputFields.AtaPassThrough16.TDir = 0x01;                // Device to host
            commandInputFields.AtaPassThrough16.TLength = 0x03;             // Transfer length is specified in STPSIU
            commandInputFields.AtaPassThrough16.Features = SubCommand;
            commandInputFields.AtaPassThrough16.Lba = ATA_SUBSMART_IDENTIFIER;

            StorageUtility::Scsi::sCommandCharacteristics& commandCharacteristics = commandDescriptorScsi.GetCommandCharacteristics();
            commandCharacteristics.FieldFormatting = StorageUtility::Scsi::eFieldFormatting::ATAPASSTHROUGH_16;
            commandCharacteristics.DataAccess = StorageUtility::Scsi::eDataAccess::READ_FROM_DEVICE;
            commandCharacteristics.DataTransferLengthInBytes = StorageUtility::Scsi::SCSI_SECTOR_SIZE_IN_BYTES;

            return(Drive->IssueCommand(CommandType, commandDescriptor, Data));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;

namespace Light2D
{
    /// <summary>
    /// Sprite with dual color support. Grabs sprite from GameSpriteRenderer field.
    /// </summary>
    [ExecuteInEditMode]
    public class LightObstacleSprite : CustomSprite
    {
        /// <summary>
        /// Renderer from which sprite will be used.
        /// </summary>
        public Renderer GameSpriteRenderer;

        /// <summary>
        /// Color is packed in mesh UV1.
        /// </summary>
        public Color AdditiveColor;
        private Color _oldSecondaryColor;
        private Renderer _oldGameSpriteRenderer;
        private SpriteRenderer _oldUnitySprite;
        private CustomSprite _oldCustomSprite;

        protected override void OnEnable()
        {
#if UNITY_EDITOR
            if (Material == null)
            {
                Material = (Material)AssetDatabase.LoadAssetAtPath("Assets/Light2D/Materials/DualColor.mat", typeof(Material));
            }
#endif

            base.OnEnable();

            if (GameSpriteRenderer == null && transform.parent != null)
                GameSpriteRenderer = transform.parent.gameObject.GetComponent<Renderer>();

            gameObject.layer = LightingSystem.Instance.LightObstaclesLayer;

            UpdateMeshData(true);
        }

        private void UpdateSecondaryColor()
        {
            var uv1 = new Vector2(
                Util.DecodeFloatRGBA((Vector4)AdditiveColor),
                Util.DecodeFloatRGBA(new Vector4(AdditiveColor.a, 0, 0)));
            for (int i = 0; i < _uv1.Length; i++)
            {
                _uv1[i] = uv1;
            }
        }

        protected override void UpdateMeshData(bool forceUpdate = false)
        {
            if (_meshRenderer == null || _meshFilter == null || IsPartOfStaticBatch)
                return;

            if (GameSpriteRenderer != null && (GameSpriteRenderer != _oldGameSpriteRenderer || forceUpdate ||
                (_oldUnitySprite != null && _oldUnitySprite.sprite != null && _oldUnitySprite.sprite != Sprite) ||
                (_oldCustomSprite != null && _oldCustomSprite.Sprite != null && _oldCustomSprite.Sprite != Sprite)))
            {
                _oldGameSpriteRenderer = GameSpriteRenderer;

                _oldCustomSprite = GameSpriteRenderer.GetComponent<CustomSprite>();
                if (_oldCustomSprite != null)
                {
                    Sprite = _oldCustomSprite.Sprite;
                }
                else
                {
                    _oldUnitySprite = GameSpriteRenderer.GetComponent<SpriteRenderer>();
                    if (_oldUnitySprite != null)
                        Sprite = _oldUnitySprite.sprite;
                }

                Material.EnableKeyword("NORMAL_TEXCOORD");
            }

            if (_oldSecondaryColor != AdditiveColor || forceUpdate)
            {
                UpdateSecondaryColor();
                _isMeshDirty = true;
                _oldSecondaryColor = AdditiveColor;
            }

            base.UpdateMeshData(forceUpdate);
        }
    }
}


text:
package image

import (
	"golang.org/x/net/context"

	"github.com/docker/docker/cli"
	"github.com/docker/docker/cli/command"
	"github.com/spf13/cobra"
)

type tagOptions struct {
	image string
	name  string
}

// NewTagCommand creates a new `docker tag` command
func NewTagCommand(dockerCli command.Cli) *cobra.Command {
	var opts tagOptions

	cmd := &cobra.Command{
		Use:   "tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]",
		Short: "Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE",
		Args:  cli.ExactArgs(2),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.image = args[0]
			opts.name = args[1]
			return runTag(dockerCli, opts)
		},
	}

	flags := cmd.Flags()
	flags.SetInterspersed(false)

	return cmd
}

func runTag(dockerCli command.Cli, opts tagOptions) error {
	ctx := context.Background()

	return dockerCli.Client().ImageTag(ctx, opts.image, opts.name)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaerophorus australis f. subteres Zahlbr. ex H. Magn.

### Remarks
null


text:
package com.albedinsky.android.device.examples.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.albedinsky.android.device.examples.R;
import com.albedinsky.android.device.examples.model.BatteryInfo;
import com.albedinsky.android.ui.widget.adapter.SimpleAdapter;
import com.albedinsky.android.ui.widget.adapter.ViewHolder;

import java.util.ArrayList;

/**
 * @author Martin Albedinsky
 */
public final class BatteryInfoAdapter extends SimpleAdapter<BatteryInfo, ViewHolder> {

	@SuppressWarnings("unused")
	private static final String TAG = "BatteryInfoAdapter";

	private static final int VIEW_TYPE_COUNT = 2;
	private static final int VIEW_TYPE_INFO = 0x00;
	private static final int VIEW_TYPE_CHANGE = 0x01;

	public BatteryInfoAdapter(@NonNull Context context) {
		super(context, new ArrayList<BatteryInfo>(0));
	}

	@SuppressWarnings("ConstantConditions")
	public void dispatchNewInfo(BatteryInfo info) {
		// Add latest info always at the top of the list.
		getItems().add(0, info);
		notifyDataSetChanged();
	}

	@Override
	public int getViewTypeCount() {
		return VIEW_TYPE_COUNT;
	}

	@Override
	public int getItemViewType(int position) {
		final BatteryInfo info = getItem(position);
		return info.hasInfo ? VIEW_TYPE_INFO : VIEW_TYPE_CHANGE;
	}

	@NonNull
	@Override
	protected View onCreateView(@NonNull ViewGroup parent, int position) {
		switch (currentViewType()) {
			case VIEW_TYPE_CHANGE:
				return inflate(R.layout.item_list_battery_change, parent);
		}
		return inflate(R.layout.item_list_battery_info, parent);
	}

	@Nullable
	@Override
	protected ViewHolder onCreateViewHolder(@NonNull View itemView, int position) {
		switch (currentViewType()) {
			case VIEW_TYPE_INFO:
				return new InfoHolder(itemView);
			case VIEW_TYPE_CHANGE:
				return new ChangeHolder(itemView);
		}
		return null;
	}

	@Override
	protected void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
		final BatteryInfo info = getItem(position);
		switch (currentViewType()) {
			case VIEW_TYPE_INFO:
				final InfoHolder infoHolder = (InfoHolder) viewHolder;
				infoHolder.setTime(info.time);
				infoHolder.setHealth(info.getHealthName());
				infoHolder.setStrength(info.strength);
				infoHolder.setPluggedState(info.getPluggedStateName());
				infoHolder.setStatus(info.getStatusName());
				break;
			case VIEW_TYPE_CHANGE:
				final ChangeHolder changeHolder = (ChangeHolder) viewHolder;
				changeHolder.setTime(info.time);
				changeHolder.setChange(info.change);
				break;
		}
	}

	private static final class ChangeHolder extends ViewHolder {

		final TextView time, change;

		public ChangeHolder(View itemView) {
			super(itemView);
			this.time = (TextView) itemView.findViewById(R.id.item_list_battery_change_text_view_time);
			this.change = (TextView) itemView.findViewById(R.id.item_list_battery_change_text_view_change);
		}

		void setTime(String time) {
			this.time.setText(time);
		}

		void setChange(String change) {
			this.change.setText(change);
		}
	}

	private static final class InfoHolder extends ViewHolder {

		final TextView time, health, strength, pluggedState, status;

		public InfoHolder(View itemView) {
			super(itemView);
			this.time = (TextView) itemView.findViewById(R.id.item_list_battery_info_text_view_time);
			this.health = (TextView) itemView.findViewById(R.id.item_list_battery_info_text_view_health);
			this.strength = (TextView) itemView.findViewById(R.id.item_list_battery_info_text_view_strength);
			this.status = (TextView) itemView.findViewById(R.id.item_list_battery_info_text_view_status);
			this.pluggedState = (TextView) itemView.findViewById(R.id.item_list_battery_info_text_view_plugged_state);
		}

		void setTime(String time) {
			this.time.setText(time);
		}

		void setHealth(String health) {
			this.health.setText(health);
		}

		void setStrength(int strength) {
			this.strength.setText(strength >= 0 ? Integer.toString(strength) : "???");
		}

		void setPluggedState(String state) {
			pluggedState.setText(state);
		}

		void setStatus(String status) {
			this.status.setText(status);
		}
	}
}


text:
import React, { Element, PureComponent } from 'react';
import PropTypes from 'prop-types';
import type { Comment } from '../redux/store';

import CommentContainer from './CommentContainer.react';

import '../css/Comment.css';

class CommentListContainer extends PureComponent {
  render(): Element<any> {
    const { comments, ...props } = this.props;
    if (!comments) {
      return <div {...props}>No comments</div>;
    }

    return(
      <div {...props}>
        {comments.map(
          (comment: Comment) => <CommentContainer
            className="Comment-Container"
            key={"comment:" + comment.postId + ":" + comment.id}
            comment={comment}
          />
        )}
      </div>
    );
  }
}

CommentListContainer.propTypes = {
  ...PureComponent.propTypes,
  comments: PropTypes.array,
}

export default CommentListContainer


text:
@implementation OrgApacheLuceneAnalysisPayloadsPayloadHelper

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

+ (IOSByteArray *)encodeFloatWithFloat:(jfloat)payload {
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeFloatWithFloat_(payload);
}

+ (IOSByteArray *)encodeFloatWithFloat:(jfloat)payload
                         withByteArray:(IOSByteArray *)data
                               withInt:(jint)offset {
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeFloatWithFloat_withByteArray_withInt_(payload, data, offset);
}

+ (IOSByteArray *)encodeIntWithInt:(jint)payload {
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeIntWithInt_(payload);
}

+ (IOSByteArray *)encodeIntWithInt:(jint)payload
                     withByteArray:(IOSByteArray *)data
                           withInt:(jint)offset {
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeIntWithInt_withByteArray_withInt_(payload, data, offset);
}

+ (jfloat)decodeFloatWithByteArray:(IOSByteArray *)bytes {
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeFloatWithByteArray_(bytes);
}

+ (jfloat)decodeFloatWithByteArray:(IOSByteArray *)bytes
                           withInt:(jint)offset {
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeFloatWithByteArray_withInt_(bytes, offset);
}

+ (jint)decodeIntWithByteArray:(IOSByteArray *)bytes
                       withInt:(jint)offset {
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeIntWithByteArray_withInt_(bytes, offset);
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, "[B", 0x9, 0, 1, -1, -1, -1, -1 },
    { NULL, "[B", 0x9, 0, 2, -1, -1, -1, -1 },
    { NULL, "[B", 0x9, 3, 4, -1, -1, -1, -1 },
    { NULL, "[B", 0x9, 3, 5, -1, -1, -1, -1 },
    { NULL, "F", 0x9, 6, 7, -1, -1, -1, -1 },
    { NULL, "F", 0x19, 6, 8, -1, -1, -1, -1 },
    { NULL, "I", 0x19, 9, 8, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(encodeFloatWithFloat:);
  methods[2].selector = @selector(encodeFloatWithFloat:withByteArray:withInt:);
  methods[3].selector = @selector(encodeIntWithInt:);
  methods[4].selector = @selector(encodeIntWithInt:withByteArray:withInt:);
  methods[5].selector = @selector(decodeFloatWithByteArray:);
  methods[6].selector = @selector(decodeFloatWithByteArray:withInt:);
  methods[7].selector = @selector(decodeIntWithByteArray:withInt:);
  #pragma clang diagnostic pop
  static const void *ptrTable[] = { "encodeFloat", "F", "F[BI", "encodeInt", "I", "I[BI", "decodeFloat", "[B", "[BI", "decodeInt" };
  static const J2ObjcClassInfo _OrgApacheLuceneAnalysisPayloadsPayloadHelper = { "PayloadHelper", "org.apache.lucene.analysis.payloads", ptrTable, methods, NULL, 7, 0x1, 8, 0, -1, -1, -1, -1, -1 };
  return &_OrgApacheLuceneAnalysisPayloadsPayloadHelper;
}

@end

void OrgApacheLuceneAnalysisPayloadsPayloadHelper_init(OrgApacheLuceneAnalysisPayloadsPayloadHelper *self) {
  NSObject_init(self);
}

OrgApacheLuceneAnalysisPayloadsPayloadHelper *new_OrgApacheLuceneAnalysisPayloadsPayloadHelper_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneAnalysisPayloadsPayloadHelper, init)
}

OrgApacheLuceneAnalysisPayloadsPayloadHelper *create_OrgApacheLuceneAnalysisPayloadsPayloadHelper_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneAnalysisPayloadsPayloadHelper, init)
}

IOSByteArray *OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeFloatWithFloat_(jfloat payload) {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_initialize();
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeFloatWithFloat_withByteArray_withInt_(payload, [IOSByteArray arrayWithLength:4], 0);
}

IOSByteArray *OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeFloatWithFloat_withByteArray_withInt_(jfloat payload, IOSByteArray *data, jint offset) {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_initialize();
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeIntWithInt_withByteArray_withInt_(JavaLangFloat_floatToIntBitsWithFloat_(payload), data, offset);
}

IOSByteArray *OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeIntWithInt_(jint payload) {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_initialize();
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeIntWithInt_withByteArray_withInt_(payload, [IOSByteArray arrayWithLength:4], 0);
}

IOSByteArray *OrgApacheLuceneAnalysisPayloadsPayloadHelper_encodeIntWithInt_withByteArray_withInt_(jint payload, IOSByteArray *data, jint offset) {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_initialize();
  *IOSByteArray_GetRef(nil_chk(data), offset) = (jbyte) (JreRShift32(payload, 24));
  *IOSByteArray_GetRef(data, offset + 1) = (jbyte) (JreRShift32(payload, 16));
  *IOSByteArray_GetRef(data, offset + 2) = (jbyte) (JreRShift32(payload, 8));
  *IOSByteArray_GetRef(data, offset + 3) = (jbyte) payload;
  return data;
}

jfloat OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeFloatWithByteArray_(IOSByteArray *bytes) {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_initialize();
  return OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeFloatWithByteArray_withInt_(bytes, 0);
}

jfloat OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeFloatWithByteArray_withInt_(IOSByteArray *bytes, jint offset) {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_initialize();
  return JavaLangFloat_intBitsToFloatWithInt_(OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeIntWithByteArray_withInt_(bytes, offset));
}

jint OrgApacheLuceneAnalysisPayloadsPayloadHelper_decodeIntWithByteArray_withInt_(IOSByteArray *bytes, jint offset) {
  OrgApacheLuceneAnalysisPayloadsPayloadHelper_initialize();
  return (JreLShift32((IOSByteArray_Get(nil_chk(bytes), offset) & (jint) 0xFF), 24)) | (JreLShift32((IOSByteArray_Get(bytes, offset + 1) & (jint) 0xFF), 16)) | (JreLShift32((IOSByteArray_Get(bytes, offset + 2) & (jint) 0xFF), 8)) | (IOSByteArray_Get(bytes, offset + 3) & (jint) 0xFF);
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneAnalysisPayloadsPayloadHelper)


text:
<?php

namespace Choccybiccy\HumanApi\Endpoint;

use Choccybiccy\HumanApi\Endpoint;
use Choccybiccy\HumanApi\Exception\UnsupportedEndpointMethodException;

/**
 * Class SimpleEndpoint
 * @package Choccybiccy\HumanApi\Endpoint
 */
abstract class SimpleEndpoint extends Endpoint
{

    /**
     * @var bool
     */
    protected $listReturnsArray = false;

    /**
     * {@inheritDoc}
     */
    protected function buildListUrl()
    {
        return $this->buildUrlParts(array(
            $this->type,
        ));
    }

    /**
     * {@inheritDoc}
     */
    protected function buildSpecificEntryUrl($id)
    {
        throw new UnsupportedEndpointMethodException("This endpoint does not support specific entries");
    }

    /**
     * {@inheritDoc}
     */
    public function buildRecentUrl()
    {
        throw new UnsupportedEndpointMethodException("This endpoint does not support recent entries");
    }
}


text:
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""

from __future__ import print_function, unicode_literals
import os
import json

from atomic_reactor.plugins.input_osv3 import OSv3InputPlugin

import pytest
from flexmock import flexmock

@pytest.mark.parametrize('prebuild_json,expected_json', [
    ([],
     [{ 'name': 'pull_base_image' }]
    ),
    ([{ 'name': 'pull_base_image' }],
     [{ 'name': 'pull_base_image' }]
    ),
    ([{ 'name': 'pull_base_image', 'args': { 'a': 'b' }}],
     [{ 'name': 'pull_base_image', 'args': { 'a': 'b' }}]
    ),
    ([{ 'name': 'change_source_registry' }],
     [{ 'name': 'pull_base_image' }]
    ),
    ([{ 'name': 'change_source_registry',
        'args': { 'registry_uri': 'localhost:666', 'insecure_registry': True }}],
     [{ 'name': 'pull_base_image',
        'args': { 'parent_registry': 'localhost:666', 'parent_registry_insecure': True }}]
    ),
    ([{ 'name': 'change_source_registry' }, { 'name': 'pull_base_image', 'args': { 'a': 'b' }}],
     [{ 'name': 'pull_base_image', 'args': { 'a': 'b' }}]
    ),
])
def test_prebuild_plugins_rewrite(prebuild_json, expected_json):
    plugins_json = {
        'prebuild_plugins': prebuild_json,
    }

    mock_env = {
        'BUILD': '{}',
        'SOURCE_URI': 'https://github.com/foo/bar.git',
        'SOURCE_REF': 'master',
        'OUTPUT_IMAGE': 'asdf:fdsa',
        'OUTPUT_REGISTRY': 'localhost:5000',
        'DOCK_PLUGINS': json.dumps(plugins_json),
    }
    flexmock(os, environ=mock_env)

    plugin = OSv3InputPlugin()
    assert plugin.run()['prebuild_plugins'] == expected_json

def test_doesnt_fail_if_no_plugins():
    mock_env = {
        'BUILD': '{}',
        'SOURCE_URI': 'https://github.com/foo/bar.git',
        'SOURCE_REF': 'master',
        'OUTPUT_IMAGE': 'asdf:fdsa',
        'OUTPUT_REGISTRY': 'localhost:5000',
        'DOCK_PLUGINS': '{}',
    }
    flexmock(os, environ=mock_env)

    plugin = OSv3InputPlugin()
    assert plugin.run()['prebuild_plugins'] == [{'name': 'pull_base_image'}]

@pytest.mark.parametrize('build, expected', [
    ('{"metadata": {"selfLink": "/foo/bar"}}', '/foo/bar'),
    ('{"metadata": {}}', None),
    ('{}', None),
])
def test_sets_selflink(build, expected):
    mock_env = {
        'BUILD': build,
        'SOURCE_URI': 'https://github.com/foo/bar.git',
        'SOURCE_REF': 'master',
        'OUTPUT_IMAGE': 'asdf:fdsa',
        'OUTPUT_REGISTRY': 'localhost:5000',
        'DOCK_PLUGINS': '{}',
    }
    flexmock(os, environ=mock_env)

    plugin = OSv3InputPlugin()
    assert plugin.run()['openshift_build_selflink'] == expected


text:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@class AppDelegate;
@class CocosScene;
@class InspectorController;

@interface CCBGLView : CCGLView {

    NSTrackingRectTag trackingTag;

    IBOutlet __weak AppDelegate* appDelegate;
}

@property (nonatomic, weak) IBOutlet InspectorController *inspectorController;

@end


text:
namespace gfx {
class Rect;
class Vector2d;
}  // namespace gfx

namespace viz {

class ContextProvider;

// A convenience wrapper around GLScaler that also reformats the scaler's output
// from interleaved RGBA to NV12 planes. The NV12 format consists of two
// planes of image data: the Y (luma) plane at full size, plus interleaved UV
// (chroma) plane at half-width and half-height. There are two possible modes of
// operation (auto-detected at runtime):
//
// The faster, multiple rendering target (MRT) path: If the platform supports
// MRTs (most of the GPUs in use today), scaling and conversion is a two step
// process:
//
//   Step 1: Produce NV61 format output, a luma plane and a UV-interleaved
//   image. The luma plane is the same as the desired NV12 luma plane. Note,
//   that the UV image is of half-width but not yet half-height.
//
//               (interleaved quads)
//     RGBA RGBA RGBA RGBA RGBA RGBA RGBA RGBA
//     RGBA RGBA RGBA RGBA RGBA RGBA RGBA RGBA
//     RGBA RGBA RGBA RGBA RGBA RGBA RGBA RGBA
//     RGBA RGBA RGBA RGBA RGBA RGBA RGBA RGBA
//       |
//       |     (luma plane)  (chroma, interleaved)
//       |       YYYY YYYY      UVUV UVUV
//       +---> { YYYY YYYY  +   UVUV UVUV }
//               YYYY YYYY      UVUV UVUV
//               YYYY YYYY      UVUV UVUV
//
//   Step 2: Downscales the chroma plane.
//
//     (chroma, interleaved)     (chroma, interleaved)
//           UVUV UVUV
//           UVUV UVUV     -->   UVUV UVUV
//           UVUV UVUV           UVUV UVUV
//           UVUV UVUV
//
// The non-MRT path: For platforms that can only render to a single target at a
// time. This first scales the source to its final size and color-converts,
// transforming an RGBA input into a YUVx output. Then, it scans the YUVA image
// two times to generate each of the Y+UV planes.
//
// Texture packing: OpenGLES2 treats all of the input and output textures as
// RGBA format. See comments for the Convert() method, which explains how the
// planar image data is packed into GL_RGBA textures, how the output textures
// should be sized, and why there are alignment requirements when specifying the
// output rect.
class VIZ_COMMON_EXPORT GLNV12Converter final : public ContextLostObserver {
 public:
  // GLNV12Converter uses the exact same parameters as GLScaler.
  using Parameters = GLScaler::Parameters;

  explicit GLNV12Converter(ContextProvider* context_provider);
  ~GLNV12Converter() final;

  // Returns true if the GL context provides the necessary support for enabling
  // precise color management (see Parameters::enable_precise_color_management).
  bool SupportsPreciseColorManagement() const {
    return step1_.SupportsPreciseColorManagement();
  }

  // [Re]Configure the converter with the given |new_params|. Returns true on
  // success, or false on failure. If |new_params| does not specify an
  // |output_color_space|, it will be default to REC709.
  bool Configure(const Parameters& new_params) WARN_UNUSED_RESULT;

  // Returns the currently-configured and resolved Parameters. Results are
  // undefined if Configure() has never been called successfully.
  const Parameters& params() const { return params_; }

  // Scales a portion of |src_texture|, then format-converts it to two NV12
  // planes, placing the results into |yuv_textures| at offset (0, 0). Returns
  // true to indicate success, or false if this GLNV12Converter is not valid.
  //
  // |src_texture_size| is the full, allocated size of the |src_texture|. This
  // is required for computing texture coordinate transforms (and only because
  // the OpenGL ES 2.0 API lacks the ability to query this info).
  //
  // |src_offset| is the offset in the source texture corresponding to point
  // (0,0) in the source/output coordinate spaces. This prevents the need for
  // extra texture copies just to re-position the source coordinate system.
  //
  // |aligned_output_rect| selects the region to draw (in the scaled, not the
  // source, coordinate space). This is used to save work in cases where only a
  // portion needs to be re-scaled. Because of the way the planar image data is
  // packed in the output textures, the output rect's coordinates must be
  // aligned (see ToAlignedRect() below).
  //
  // The |yuv_textures| are packed with planar data. Depending on the plane,
  // the packing is as follows:
  // - for Y plane, each RGBA quad contains four pixel values: R is pixel 0,
  //   G is pixel 1, and so on.
  // - for UV plane, each RGBA quad contains 2 pixel values: RG are UV values
  //   for pixel 0, BA are UV values for pixel 1, and so on.
  // This makes it trivial to read-back the textures from a pixel buffer as a
  // sequence of unsigned bytes. Thus, the output texture for the Y plane should
  // be defined as GL_RGBA and be at least 1/4 the width of that specified in
  // |aligned_output_rect|. Similarly, the output texture for the UV plane
  // should be defined as GL_RGBA and have at least 1/4 the width [1]
  // and 1/2 the height [2] of |aligned_output_rect|.
  //
  // [1] 1/4 width  = 1/4     // we pack 4 values per pixel
  //                * 1/2     // chroma planes are subsampled
  //                * 2       // we pack 2 chroma planes
  //                * width
  // [2] 1/2 height = 1/2     // chroma planes are subsampled
  //                * height
  //
  // WARNING: The output will always be placed at (0, 0) in the output textures,
  // and not at |aligned_output_rect.origin()|.
  //
  // Note that the |src_texture| will have the min/mag filter set to GL_LINEAR
  // and wrap_s/t set to CLAMP_TO_EDGE in this call.
  bool Convert(GLuint src_texture,
               const gfx::Size& src_texture_size,
               const gfx::Vector2d& src_offset,
               const gfx::Rect& aligned_output_rect,
               const GLuint yuv_textures[2]);

  // Returns the smallest Rect that encloses |rect| and lays on aligned
  // boundaries, as required by the |aligned_output_rect| argument passed to
  // Convert(). The horizontal coordinates will always be a multiple of 4, and
  // the vertical coordinates a multiple of 2.
  static gfx::Rect ToAlignedRect(const gfx::Rect& rect);

  // Returns true if configuring a GLNV12Converter with either |a| or |b| will
  // produce identical behaviors and results.
  static bool ParametersAreEquivalent(const Parameters& a, const Parameters& b);

  static std::unique_ptr<GLNV12Converter> CreateConverterForTest(
      ContextProvider* context_provider,
      bool allow_mrt_path);

 private:
  GLNV12Converter(ContextProvider* context_provider, bool allow_mrt_path);

  bool is_using_mrt_path() const { return !step3_; }

  // Creates or re-defines the intermediate texture, to ensure a texture of the
  // given |required| size is defined.
  void EnsureIntermediateTextureDefined(const gfx::Size& required);

  // ContextLostObserver implementation.
  void OnContextLost() final;

  // The provider of the GL context. This is non-null while the GL context is
  // valid and GLNV12Converter is observing for context loss.
  raw_ptr<ContextProvider> context_provider_;

  // Scales the source content and produces either:
  //   * MRT path: NV61-format output in two textures.
  //   * Non-MRT path: YUVA interleaved output in one texture.
  GLScaler step1_;

  // Holds the results from executing the first-stage |scaler_|, and is read by
  // the other scalers:
  //   * MRT path: This holds the UV-interleaved data (2nd rendering target).
  //   * Non-MRT path: The scaled YUVA interleaved data.
  GLuint intermediate_texture_ = 0;
  gfx::Size intermediate_texture_size_;

  // Step 2 operation using the |intermediate_texture_| as input:
  //   * MRT path: Scales the height by half.
  //   * Non-MRT path: Extracts the luma plane.
  GLScaler step2_;

  // Steps 3 is used by the non-MRT path only, to extract the interleaved chroma
  // planes from |intermediate_texture_|.
  std::unique_ptr<GLScaler> step3_;

  // The Parameters that were provided to the last successful Configure() call.
  Parameters params_;
};

}  // namespace viz

#endif  // COMPONENTS_VIZ_COMMON_GL_NV12_CONVERTER_H_


text:
require 'stringio'

module Packable
  module Extensions #:nodoc:
    module Array #:nodoc:
      def self.included(base)
        base.class_eval do
          alias_method_chain :pack, :long_form
          include Packable
          extend ClassMethods
        end
      end

      def pack_with_long_form(*arg)
        return pack_without_long_form(*arg) if arg.first.is_a? String
        pio = StringIO.new.packed
        write_packed(pio, *arg)
        pio.string
      end

      def write_packed(io, *how)
        return io << self.original_pack(*how) if how.first.is_a? String
        how = [:repeat => :all] if how.empty?
        current = -1
        how.each do |options|
          repeat = options.is_a?(Hash) ? options.delete(:repeat) || 1 : 1
          repeat = length - 1 - current if repeat == :all
          repeat.times do
            io.write(self[current+=1],options)
          end
        end
      end

      module ClassMethods #:nodoc:
        def read_packed(io, *how)
          raise "Can't support builtin format for arrays" if (how.length == 1) && (how.first.is_a? String)
          how.inject [] do |r, options|
            repeat = options.is_a? Hash ? options.delete(:repeat) || 1 : 1
            (0...repeat).inject r do
              r << io.read(options)
            end
          end
        end
      end
    end
  end
end