text:
This dark-feathered vulture has a bald neck and head, and its long, hooked beak is caked with carrion.

Vulture CR 1/2

XP 200

N Small animal

**Init** +1; **Senses** low-light vision, [scent](monsters/universalMonsterRules#_scent); [Perception](skills/perception#_perception) +9

Defense

**AC** 13, touch 12, flat-footed 12 (+1 Dex, +1 natural, +1 size)

**hp** 6 (1d8+2)

**Fort** +6, **Ref** +3, **Will** +1; +4 vs. [disease](monsters/universalMonsterRules#_disease-(ex-or-su))

Offense

**Speed** 10 ft., fly 50 ft. (average)

**Melee** bite +2 (1d6+1)

Statistics

**Str** 12, **Dex** 13, **Con** 14, **Int** 2, **Wis** 13, **Cha** 7

**Base Atk** +0; **CMB** +0; **CMD** 11

**Feats** [Great Fortitude](feats#_great-fortitude)

**Skills** [Fly](skills/fly#_fly) +7, [Perception](skills/perception#_perception) +9; **Racial Modifiers** +8 [Perception](skills/perception#_perception)

Ecology

**Environment** warm plains or hills

**Organization** solitary, pair, or flock (3–24)

**Treasure** none

Though related to raptors and other birds of prey, vultures mainly feed on carrion they spot or scent from on high. Vultures have weak claws compared to predatory birds, but their sharp and wickedly hooked beaks tear living flesh as readily as the sharpest blade.

Despite dining on carrion, vultures prefer their corpses newly dead rather than rotten. Some even hunt smaller prey when food is scarce.

# Vulture, Giant

A wickedly hooked beak and an immense bald head draw attention from this enormous scavenger's vast wingspan.

Giant Vulture CR 4

XP 1,200

N Large animal

**Init** +2; **Senses** low-light vision, [scent](monsters/universalMonsterRules#_scent); [Perception](skills/perception#_perception) +13

Defense

**AC** 17, touch 11, flat-footed 15 (+2 Dex, +6 natural, –1 size)

**hp** 42 (5d8+20)

**Fort** +10, **Ref** +6, **Will** +3; +4 vs. [disease](monsters/universalMonsterRules#_disease-(ex-or-su))

Offense

**Speed** 10 ft., fly 50 ft. (average)

**Melee** bite +9 (2d6+9 plus [disease](monsters/universalMonsterRules#_disease-(ex-or-su)))

**Space** 10 ft.; **Reach** 5 ft.

Statistics

**Str** 22, **Dex** 15, **Con** 18, **Int** 2, **Wis** 15, **Cha** 7

**Base** Atk +3; **CMB** +10; **CMD** 22

**Feats** [Great Fortitude](feats#_great-fortitude), [Skill Focus](feats#_skill-focus) ( [Perception](skills/perception#_perception)), [Toughness](feats#_toughness), [Weapon Focus](feats#_weapon-focus) (bite)

**Skills** [Fly](skills/fly#_fly) +7, [Perception](skills/perception#_perception) +13; **Racial Modifiers** +4 [Perception](skills/perception#_perception)

**SQ** diseased

Ecology

**Environment** warm plains or hills

**Organization** solitary, pair, or flock (3–8)

**Treasure** none

Special Abilities

**Diseased (Ex)** Due to their filthy eating habits and constant exposure to decaying flesh, giant vultures are harbingers of [disease](monsters/universalMonsterRules#_disease-(ex-or-su))—much more so than the standard vulture. Any creature bitten by a giant vulture has a 10% chance of being exposed to filth fever, blinding sickness, or a similar [disease](monsters/universalMonsterRules#_disease-(ex-or-su)). Once this check is made, a victim can no longer be infected by this particular giant vulture, though attacks by different giant vultures are resolved normally and may result in multiple illnesses. While vultures aren't immune to all diseases, they do gain a +4 racial bonus on all saving throws against such ailments.

Larger even than condors, giant vultures dwell only in regions where carrion is both large and plentiful, such as the primeval wildernesses where megafauna roam. They also flock to regions torn by war, feasting on the dead with no concern for allegiance or race. Giant vultures rarely wait for wounded creatures to finish dying before they feed, and are much braver than most wild animals. A giant vulture, for example, wouldn't think twice about swooping down on a heavily armored column of soldiers just to snatch up a few wounded stragglers from the end of the line.

A giant vulture stands more than 13 feet tall, has a wingspan of over 30 feet, and weighs 500 to 600 pounds.


text:
/* eslint no-console: 0 */

import express from 'express'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'

import config from './webpack/config.development'

const app = express()
const compiler = webpack(config)
const PORT = 3000

const wdm = webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath,
  stats: {
    colors: true
  }
})

app.use(wdm)

app.use(webpackHotMiddleware(compiler))

const server = app.listen(PORT, 'localhost', (err) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(`Listening at http://localhost:${PORT}`)
})

let ran = false

const gracefulExit = () => {
  if (!ran) {
    console.log('Stopping dev server')
    wdm.close()
    server.close(() => {
      process.exit(0)
    })
    ran = true
    process.exit(0)
  }
}

process.on('SIGTERM', gracefulExit)
process.on('exit', gracefulExit)

redpajama_set_name: RedPajamaGithub


text:
import json
import pathlib

import pytest

import salt.states.ansiblegate as ansiblegate
from tests.support.mock import MagicMock, patch
from tests.support.runtests import RUNTIME_VARS

@pytest.fixture
def configure_loader_modules():
    return {ansiblegate: {}}

@pytest.fixture
def playbooks_examples_dir():
    return pathlib.Path(RUNTIME_VARS.TESTS_DIR) / "unit" / "files" / "playbooks"

def test_ansible_playbooks_states_success(playbooks_examples_dir):
    """
    Test ansible.playbooks states executions success.
    """

    success_output = json.loads(
        playbooks_examples_dir.joinpath("success_example.json").read_text()
    )

    with patch.dict(
        ansiblegate.__salt__,
        {"ansible.playbooks": MagicMock(return_value=success_output)},
    ), patch("salt.utils.path.which", return_value=True), patch.dict(
        ansiblegate.__opts__, {"test": False}
    ):
        ret = ansiblegate.playbooks("foobar")
        assert ret["result"] is True
        assert ret["comment"] == "Changes were made by playbook foobar"
        assert ret["changes"] == {
            "py2hosts": {
                "Ansible copy file to remote server": {"centos7-host1.tf.local": {}}
            }
        }

def test_ansible_playbooks_states_success_with_skipped(playbooks_examples_dir):
    """
    Test ansible.playbooks states executions success.
    """

    success_output = json.loads(
        playbooks_examples_dir.joinpath("success_example_with_skipped.json").read_text()
    )

    with patch.dict(
        ansiblegate.__salt__,
        {"ansible.playbooks": MagicMock(return_value=success_output)},
    ), patch("salt.utils.path.which", return_value=True), patch.dict(
        ansiblegate.__opts__, {"test": False}
    ):
        ret = ansiblegate.playbooks("foobar")
        assert ret["result"] is True
        assert ret["comment"] == "No changes to be made from playbook foobar"
        assert ret["changes"] == {
            "all": {
                "install git CentOS": {"uyuni-stable-min-sles15sp3.tf.local": {}},
                "install git SUSE": {"uyuni-stable-min-centos7.tf.local": {}},
                "install git Ubuntu": {
                    "uyuni-stable-min-centos7.tf.local": {},
                    "uyuni-stable-min-sles15sp3.tf.local": {},
                },
            }
        }

def test_ansible_playbooks_states_failed(playbooks_examples_dir):
    """
    Test ansible.playbooks failed states executions.
    :return:
    """
    failed_output = json.loads(
        playbooks_examples_dir.joinpath("failed_example.json").read_text()
    )
    with patch.dict(
        ansiblegate.__salt__,
        {"ansible.playbooks": MagicMock(return_value=failed_output)},
    ), patch("salt.utils.path.which", return_value=True), patch.dict(
        ansiblegate.__opts__, {"test": False}
    ):
        ret = ansiblegate.playbooks("foobar")
        assert ret["result"] is False
        assert ret["comment"] == "There were some issues running the playbook foobar"
        assert ret["changes"] == {
            "py2hosts": {
                "yum": {
                    "centos7-host1.tf.local": [
                        "No package matching 'rsyndc' found available, installed or"
                        " updated"
                    ]
                }
            }
        }


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>collection.trash</groupId>
  <artifactId>landfill</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Land-Based Trash Repository</name>
  <description>This is a sample using trash collection as an example.</description>

  <organization>
    <name>Sanitation Workers of Washington, D.C.</name>
    <url>http://www.trash.gov/</url>
  </organization>

  <dependencies>
    <dependency>
      <groupId>jmock</groupId>
      <artifactId>jmock</artifactId>
      <version>1.0.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.4</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>rpm-maven-plugin</artifactId>
        <!--version>2.1.4</version-->
        <executions>
          <execution>
            <id>generate-rpm</id>
            <goals>
              <goal>rpm</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <license>GPL (c) 2005, SWWDC</license>
          <distribution>Trash 2005</distribution>
          <group>Application/Collectors</group>
          <icon>src/main/resources/icon.gif</icon>
          <packager>SWWDC</packager>
          <prefix>/usr/local</prefix>
          <changelogFile>src/changelog</changelogFile>
          <defineStatements>
            <defineStatement>_unpackaged_files_terminate_build 0</defineStatement>
          </defineStatements>
          <mappings>
            <mapping>
              <directory>/usr/local/bin/landfill</directory>
              <filemode>440</filemode>
              <username>dumper</username>
              <groupname>dumpgroup</groupname>
              <sources>
                <source>
                  <location>target/classes</location>
                </source>
              </sources>
            </mapping>
            <!--mapping>
              <directory>/usr/local/doc/landfill</directory>
              <documentation>true</documentation>
              <filemode>444</filemode>
              <username>dumper</username>
              <groupname>dumpgroup</groupname>
              <sources>
                <source>
                  <location>target/site</location>
                </source>
              </sources>
            </mapping-->
            <mapping>
              <directory>/usr/local/lib</directory>
              <filemode>750</filemode>
              <username>dumper</username>
              <groupname>dumpgroup</groupname>
              <dependency>
                <includes>
                  <include>jmock:jmock</include>
                  <include>javax.servlet:servlet-api:2.4</include>
                </includes>
                <excludes>
                  <exclude>junit:junit</exclude>
                </excludes>
              </dependency>
            </mapping>
            <mapping>
              <directory>/usr/local/bin</directory>
              <filemode>750</filemode>
              <username>dumper</username>
              <groupname>dumpgroup</groupname>
              <sources>
                <source>
                  <location>src/main/bin</location>
                </source>
                <softlinkSource>
                  <location>/usr/local/bin/new.sh</location>
                  <destination>old.sh</destination>
                </softlinkSource>
              </sources>
            </mapping>
            <mapping>
              <directory>/usr/local/oldbin</directory>
              <filemode>750</filemode>
              <username>dumper</username>
              <groupname>dumpgroup</groupname>
              <sources>
                <softlinkSource>
                  <location>/usr/local/bin</location>
                </softlinkSource>
              </sources>
            </mapping>
            <mapping>
              <directory>/usr/local/conf/landfill</directory>
              <configuration>true</configuration>
              <filemode>640</filemode>
              <username>dumper</username>
              <groupname>dumpgroup</groupname>
              <sources>
                <source>
                  <location>src/main/conf</location>
                </source>
              </sources>
            </mapping>
            <mapping>
              <directory>/usr/local/log/landfill</directory>
              <filemode>750</filemode>
              <username>dumper</username>
              <groupname>dumpgroup</groupname>
            </mapping>
          </mappings>
          <preinstallScriptlet>
            <script>echo "installing now"</script>
          </preinstallScriptlet>
          <postinstallScriptlet>
            <scriptFile>src/main/scripts/postinstall</scriptFile>
            <fileEncoding>utf-8</fileEncoding>
          </postinstallScriptlet>
          <preremoveScriptlet>
            <scriptFile>src/main/scripts/preremove</scriptFile>
            <fileEncoding>utf-8</fileEncoding>
          </preremoveScriptlet>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
<?php

namespace Icans\Platforms\CoffeeKittyBundle\Document\Tests;

use Icans\Platforms\CoffeeKittyBundle\Document\Kitty;

/**
 * Tests for the kitty document.
 */
class KittyTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Kitty
     */
    protected $kitty;

    /**
     * Tests the user which should be null first. After setting it to a mock we expect it to be returned again.
     */
    public function testOwner()
    {
        $this->assertNull($this->kitty->getOwner());
        $userMock = $this->getMockBuilder('\Icans\Platforms\UserBundle\Document\User')->getMock();
        $returnedKitty = $this->kitty->setOwner($userMock);
        $this->assertSame($this->kitty, $returnedKitty);
        $this->assertSame($userMock, $this->kitty->getOwner());
    }

    /**
     * Tests the pending status which should be null as default. After setting it false we expect it to be returned
     * again.
     */
    public function testPrice()
    {
        $this->assertNull($this->kitty->getPrice());
        $returnedKitty = $this->kitty->setPrice(13.37);
        $this->assertSame($this->kitty, $returnedKitty);
        $this->assertEquals(13.37, $this->kitty->getPrice());
    }

    /**
     * Tests the pending status which should be true as default. After setting it false we expect it to be returned
     * again.
     */
    public function testPending()
    {
        $this->assertNull($this->kitty->getName());
        $returnedKitty = $this->kitty->setName('Test Kitty');
        $this->assertSame($this->kitty, $returnedKitty);
        $this->assertEquals('Test Kitty', $this->kitty->getName());
    }

    /**
     * Set up for the model to test.
     */
    protected function setUp()
    {
        $this->kitty = new Kitty();
    }
}


text:
<?php
class IndexController extends CommonController
{
    public function action() {
        /*
        $a = $b['ccc'];
        $rtn = PhateHttpRequest::getHeaderParam();
        PhateFluentd::post('debug.test', array('a'=>'b'));
        $this->_renderer->render('ok');
         *
         */
        $filename = PHATE_ROOT_DIR . 'logs/hoge.bin';
        $data = msgpack_pack(PhateHttpRequest::getHeaderParam());
        file_put_contents($filename, $data);
        $this->_renderer->render($filename);
    }

}


text:
package jp.classmethod.testing.examples.verifier;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.classmethod.testing.verifier.ArrayVerifier;
import jp.classmethod.testing.verifier.IterableVerifier;
import jp.classmethod.testing.verifier.MapVerifier;
import jp.classmethod.testing.verifier.ObjectVerifier;

import org.junit.Test;

public class ItemVerifier extends ObjectVerifier<Item> {

	/**
	 * Itemオブジェクトの比較検証を行う。
	 * @param actual
	 * @param expected
	 */
	public static void verify(Item actual, Item expected) throws Exception {
		new ItemVerifier().verifyObject(actual, expected);
	}

	/**
	 * Itemの反復オブジェクトの比較検証を行う。
	 * @param actual
	 * @param expected
	 */
	public static void verify(Iterable<Item> actual, Iterable<Item> expected) throws Exception {
		new IterableVerifier<Item>(new ItemVerifier()).verify(actual, expected);
	}

    /**
     * Itemの配列の比較検証を行う。
     * @param actual
     * @param expected
     */
    public static void verify(Item[] actual, Item[] expected) throws Exception {
        new ArrayVerifier<Item>(new ItemVerifier()).verify(actual, expected);
    }

    /**
     * ItemのMapの比較検証を行う。
     * @param actual
     * @param expected
     */
    public static void verify(Map<?, Item> actual, Map<?, Item> expected) throws Exception {
        new MapVerifier<Item>(new ItemVerifier()).verify(actual, expected);
    }

    @Override
	public void verifyNotNullObject(Item actual, Item expected) throws AssertionError {
		assertThat("id", actual.id, is(expected.id));
		assertThat("name", actual.name, is(expected.name));
		assertThat("price", actual.price, is(expected.price));
		assertThat("description", actual.description, is(expected.description));
	}

	@Test
	public void createdを除外した検証() throws Exception {
		// Setup
        Item expected = newItem(1L, "test", 2000, "説明", null);
        Item actual = newItem(1L, "test", 2000, "説明", new Date());
		// Verify
		verify(actual, expected);
	}

	@Test
	public void Iterableオブジェクトを比較する() throws Exception {
		// Setup
		List<Item> expected = Arrays.asList(
				newItem(1L, "test1", 2000, "説明1", new Date()),
				newItem(2L, "test2", 2001, "説明2", new Date()));
		List<Item> actual = Arrays.asList(
				newItem(1L, "test1", 2000, "説明1", null),
				newItem(2L, "test2", 2001, "説明2", null));
		// Verify
		verify(actual, expected);
	}

    @Test
    public void 配列を比較する() throws Exception {
        // Setup
        Item[] expected = new Item[] {
                null,
                newItem(1L, "test1", 2000, "説明1", new Date()),
                newItem(2L, "test2", 2001, "説明2", new Date()) };
        Item[] actual = new Item[] {
                null,
                newItem(1L, "test1", 2000, "説明1", null),
                newItem(2L, "test2", 2001, "説明", null) };
        // Verify
        verify(actual, expected);
    }

    @Test
    public void Mapを比較する() throws Exception {
        // Setup
        Map<Long, Item> expected = new HashMap<>();
        expected.put(1L, newItem(1L, "test1", 2000, "説明1", new Date()));
        expected.put(2L, newItem(2L, "test2", 2001, "説明2", new Date()));
        Map<Long, Item> actual = new HashMap<>();
        actual.put(1L, newItem(1L, "test1", 2000, "説明1", null));
        actual.put(2L, newItem(2L, "test2", 2001, "説明2", null));
        // Verify
        verify(actual, expected);
    }
    static Item newItem(Long id, String name, Integer price, String desc, Date createdAt) {
        Item obj = new Item();
        obj.id = id;
        obj.name = name;
        obj.price = price;
        obj.description = desc;
        obj.createdAt = createdAt;
        return obj;
    }

}


text:
package net.savantly.sprout.core.domain.tenant;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;

@Repository
@RepositoryRestResource(path="tenants", collectionResourceRel="tenants")
public interface TenantRepository extends PagingAndSortingRepository<TenantEntity, String> {

	Tenant findOneByAliases(String alias);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="horizontal"

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginRight="5dp"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/name"
        android:height="50dp"
        android:textSize="20dp"
        android:layout_weight="0.5"
        android:layout_width="0dp"
        android:layout_marginRight="5dp"
        android:gravity="center_vertical|start"
        android:layout_height="wrap_content"></TextView>

    <TextView
        android:id="@+id/price"
        android:height="50dp"
        android:layout_width="0dp"
        android:layout_weight="0.4"
        android:gravity="center_vertical|end"
        android:layout_height="wrap_content"/>

    <ImageButton
        android:id="@+id/removeFromCart"
        android:src="@drawable/ic_delete_black_24dp"
        android:layout_width="10dp"
        android:layout_height="50dp"
        android:layout_weight="0.1"
        android:gravity="center_vertical|end"/>

</LinearLayout>


text:
#ifndef __REGHELPERS_H__
#define __REGHELPERS_H__

#ifdef __cplusplus
extern "C" {
#endif

#include <windows.h>
#include <shlwapi.h>

HKEY WINAPI RegOpen( HKEY, LPCTSTR, LPCTSTR, BOOL );
BOOL WINAPI RegDelete( HKEY, LPCTSTR, LPCTSTR );
BOOL WINAPI RegSetSZ( HKEY, LPCTSTR, LPCTSTR );
BOOL WINAPI RegSetDW( HKEY, LPCTSTR, DWORD );
BOOL WINAPI RegGetSZ( HKEY, LPCTSTR, LPTSTR, DWORD );
BOOL WINAPI RegGetDW( HKEY, LPCTSTR, LPDWORD );

#ifdef __cplusplus
}
#endif

#endif


text:
<?php
namespace Frozennode\Administrator\Tests\DataTable\Columns;

use Mockery as m;

class ActionFactoryTest extends \PHPUnit_Framework_TestCase {

	/**
	 * The Validator mock
	 *
	 * @var Mockery
	 */
	protected $validator;

	/**
	 * The Config mock
	 *
	 * @var Mockery
	 */
	protected $config;

	/**
	 * The ColumnFactory mock
	 *
	 * @var Mockery
	 */
	protected $factory;

	/**
	 * Set up function
	 */
	public function setUp()
	{
		$this->validator = m::mock('Frozennode\Administrator\Validator');
		$this->config = m::mock('Frozennode\Administrator\Config\Model\Config');
		$this->factory = m::mock('Frozennode\Administrator\Actions\Factory', array($this->validator, $this->config))->makePartial();
	}

	/**
	 * Tear down function
	 */
	public function tearDown()
	{
		m::close();
	}

	public function testMake()
	{
		$this->factory->shouldReceive('parseDefaults')->once()->andReturn(array())
						->shouldReceive('getActionObject')->once()->andReturn('test');
		$this->assertEquals($this->factory->make('action', array()), 'test');
	}

	public function testParseDefaults()
	{
		$this->config->shouldReceive('getDataModel')->once();
		$this->validator->shouldReceive('arrayGet')->twice();
		$output = array('action_name' => 'action', 'has_permission' => true, 'messages' => array());
		$this->assertEquals($this->factory->parseDefaults('action', array()), $output);
	}

	/**
	 * @expectedException InvalidArgumentException
	 */
	public function testParseDefaultsInvalidName()
	{
		$this->config->shouldReceive('getDataModel')->once()
						->shouldReceive('getOption')->once();
		$this->factory->parseDefaults(true, array());
	}

	/**
	 * @expectedException InvalidArgumentException
	 */
	public function testParseDefaultsInvalidOptions()
	{
		$this->config->shouldReceive('getDataModel')->once()
						->shouldReceive('getOption')->once();
		$this->factory->parseDefaults('action', true);
	}

	public function testParseDefaultsPermissionFails()
	{
		$this->config->shouldReceive('getDataModel')->once();
		$this->validator->shouldReceive('arrayGet')->twice()->andReturn(function($model) {return false;});
		$result = $this->factory->parseDefaults('action', array());
		$this->assertEquals($result['has_permission'], false);
	}

	public function testGetByNameSucceeds()
	{
		$action = m::mock('Frozennode\Administrator\Actions\Action');
		$action->shouldReceive('getOption')->once()->andReturn('action');
		$this->factory->shouldReceive('getActions')->once()->andReturn(array($action));
		$this->assertEquals($this->factory->getByName('action'), $action);
	}

	public function testGetByNameFails()
	{
		$action = m::mock('Frozennode\Administrator\Actions\Action');
		$action->shouldReceive('getOption')->once()->andReturn('foo');
		$this->factory->shouldReceive('getActions')->once()->andReturn(array($action));
		$this->assertEquals($this->factory->getByName('action'), false);
	}

	public function testGetByNameGlobalSucceeds()
	{
		$action = m::mock('Frozennode\Administrator\Actions\Action');
		$action->shouldReceive('getOption')->once()->andReturn('action');
		$this->factory->shouldReceive('getGlobalActions')->once()->andReturn(array($action));
		$this->assertEquals($this->factory->getByName('action', true), $action);
	}

	public function testGetByNameGlobalFails()
	{
		$action = m::mock('Frozennode\Administrator\Actions\Action');
		$action->shouldReceive('getOption')->once()->andReturn('foo');
		$this->factory->shouldReceive('getGlobalActions')->once()->andReturn(array($action));
		$this->assertEquals($this->factory->getByName('action', true), false);
	}

	public function testGetActions()
	{
		$this->factory->shouldReceive('make')->times(3)->andReturn(1);
		$this->config->shouldReceive('getOption')->andReturn(array(array(), array(), array()));
		$this->assertEquals($this->factory->getActions(), array(1, 1, 1));
	}

	public function testGetActionsOptions()
	{
		$action = m::mock('Frozennode\Administrator\Actions\Action');
		$action->shouldReceive('getOptions')->times(3)->andReturn(1);
		$this->factory->shouldReceive('getActions')->andReturn(array($action, $action, $action));
		$this->assertEquals($this->factory->getActionsOptions(), array(1, 1, 1));
	}

	public function testGetGlobalActions()
	{
		$this->factory->shouldReceive('make')->times(3)->andReturn(1);
		$this->config->shouldReceive('getOption')->andReturn(array(array(), array(), array()));
		$this->assertEquals($this->factory->getGlobalActions(), array(1, 1, 1));
	}

	public function testGetGlobalActionsOptions()
	{
		$action = m::mock('Frozennode\Administrator\Actions\Action');
		$action->shouldReceive('getOptions')->times(3)->andReturn(1);
		$this->factory->shouldReceive('getGlobalActions')->andReturn(array($action, $action, $action));
		$this->assertEquals($this->factory->getGlobalActionsOptions(), array(1, 1, 1));
	}

	public function testGetActionPermissionsCallback()
	{
		$this->config->shouldReceive('getDataModel')->once()
						->shouldReceive('getOption')->once()->andReturn(array('foo' => function($model) {return false;}));
		$output = array('create' => true, 'view' => true, 'delete' => true, 'update' => true, 'foo' => false);
		$this->assertEquals($this->factory->getActionPermissions(), $output);
	}

	public function testGetActionPermissionsBool()
	{
		$this->config->shouldReceive('getDataModel')->once()
						->shouldReceive('getOption')->once()->andReturn(array('foo' => false));
		$output = array('create' => true, 'view' => true, 'delete' => true, 'update' => true, 'foo' => false);
		$this->assertEquals($this->factory->getActionPermissions(), $output);
	}
}


text:
cd tools; go build release.go; cd ..
./tools/release nias2 > version/version.go
sh build.sh
./tools/release nias2 nias-Mac.zip build/nias-Mac.zip
./tools/release nias2 nias-Win64.zip build/nias-Win64.zip
./tools/release nias2 nias-Linux64.zip build/nias-Linux64.zip


text:
require 'gridpoint'
require 'drawer'

module ColumnDrop
  # The latest gem that needs inserting
  class DropGem
    attr_accessor :column

    def initialize(grid, value, drawer)
      @grid   = grid
      @value  = value
      @gpoint = Grid::Point.new(3, -1)
      @drawer = drawer
    end

    def draw
      @drawer.draw_gem(@gpoint, @value)
    end

    def drop_by_one_row
      new_pos = Grid.down_by_one_line

      return :done if !new_pos

      @gpoint = new_pos
    end
  end
end


text:
copyright:
  years: 2016, 2017
lastupdated: "2017-02-24"

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Definición de políticas
{: #policies}

Las políticas controlan las puertas en un conducto de entrega continua. Si su código no satisface o excede una política instaurada en una puerta concreta, se detiene el despliegue para evitar que se liberen cambios con un riesgo elevado.
{:shortdesc}

Las políticas se definen en {{site.data.keyword.DRA_short}}. Las políticas se crean en la organización (org) de {{site.data.keyword.Bluemix_notm}} que contiene {{site.data.keyword.DRA_short}}. Todas las aplicaciones que se encuentran en la misma organización puede utilizar la política.

Para definir una política:

1. En la navegación izquierda, pulse **Valores**.

2. Pulse **Política**.

3. Pulse **Crear política** y, a continuación, especifique un nombre y una descripción para la nueva política.

4. Pulse **Siguiente**.

4. Añada al menos una regla a la política:
  1. Pulse **Añadir regla a política**.
  2. Seleccione el tipo de regla.
  3. Especifique los detalles y las condiciones de la regla.
  4. Pulse **Guardar**.

5. Cuando haya acabado de añadir reglas a la política, pulse **Completado**.

## Creación de reglas
{: #criteria}

Las reglas definen los criterios que utilizarán las políticas para juzgar el cumplimiento o incumplimiento de la misma. Podría crear una política "Unit Testing and Test Coverage" que contenga una regla de prueba de unidad que requiera al menos un éxito del 80% de la misma y una regla de cobertura que precise el 100% de la cobertura de código. Si añade una puerta que haga referencia a esta regla en un conducto, la puerta impide que las compilaciones que no satisfacen ambas reglas continúen.

Puede exigir una prueba satisfactoria sea como sea marcándola como crítica. Para crear una regla, seleccione una política y, a continuación, pulse **Añadir regla a política**.

### Creación de reglas de prueba de verificación funcional
{: #criteria_fvt}

1. Escriba una descripción y seleccione un formato.

2. Especifique el porcentaje de casos de prueba que deben pasar correctamente para considerarse satisfactorio.

3. Defina los casos de prueba que sean críticos.

4. Para supervisar las regresiones de casos de prueba, marque el recuadro de selección **Supervisar la regresión de casos de prueba**.

5. Pulse **Guardar**.

### Creación de reglas de prueba de unidad
{: #criteria_ut}

1. Escriba una descripción y seleccione un formato.

2. Especifique el porcentaje de casos de prueba que deben pasar correctamente para considerarse satisfactorio.

3. Defina los casos de prueba que sean críticos.

4. Para supervisar las regresiones de casos de prueba, marque el recuadro de selección **Supervisar la regresión de casos de prueba**.

5. Pulse **Guardar**.

### Creación de reglas de cobertura de código
{: #criteria_codecoverage}

1. Escriba una descripción y seleccione un formato.

2. Especifique el porcentaje de cobertura de código que es necesario para considerarse satisfactorio.

3. Para supervisar las regresiones de cobertura de código, marque el recuadro de selección **Supervisar la regresión de casos de prueba**.

4. Pulse **Guardar**.

### Creación de reglas de exploración de seguridad estática
{: #criteria_static}

1. Especifique una descripción.

2. Especifique el número máximo de problemas de seguridad baja, media o elevada que esta regla permite.

3. Pulse **Guardar**.

### Creación de reglas de exploración de seguridad dinámica
{: #criteria_dynamic}

1. Especifique una descripción.

2. Especifique el número máximo de problemas de seguridad baja, media o elevada que esta regla permite.

3. Pulse **Guardar**.

## Herramientas y formatos de resultados de pruebas

{{site.data.keyword.DRA_short}} da soporte a estos tipos de métricas y formatos:

* Prueba de verificación funcional (Mocha, xUnit)
* Prueba de unidad (Mocha, xUnit, Karma/Mocha)
* Cobertura de código (Istanbul como formato de informe de resumen de JSON, Blanket.js)

{{site.data.keyword.DRA_short}} también da soporte a las pruebas de Selenium y Jasmine. Estas pruebas deben estar incluidas dentro de las herramientas soportadas oficialmente como, por ejemplo, xUnit y Mocha. Para obtener más información sobre el uso de {{site.data.keyword.deliverypipeline}}, {{site.data.keyword.DRA_short}} y Selenium conjuntamente, consulte [Running Selenium tests from the command line on a delivery pipeline](https://developer.ibm.com/devops-services/2016/07/21/running-selenium-tests-command-line-delivery-pipeline/).

Para los elementos que tienen casos de prueba, puede especificar casos de prueba críticos, que son pruebas que deben pasar correctamente independientemente del porcentaje aceptable. Los nombres de los casos de prueba críticos deben coincidir con el atributo `full title` (título completo) del caso de prueba.
* Para pruebas de Karma/Mocha, las series de descripción `describe()` e `it()` están enlazadas entre ellas con espacios.
* Para pruebas de xUnit, el nombre de paquete, nombre de clase y nombre de función están enlazados entre ellos con espacios. Esto se muestra en el ejemplo siguiente:
  ```
  <testsuites package="test">
    <testsuite package="otc-api" name="PUT Service Instances - Test Setup" tests="2" failures="0" errors="0">
      <testcase name="#1 Authorization passed for mock user: idsb3t1@us.ibm.com"/>
      <testcase name="#2 Authorization passed for mock user: idsb3t4@us.ibm.com"/>
    </testsuite>
  </testsuite>
  ```
  Este ejemplo genera estos nombres de casos de prueba:
  ```
  test otc-api PUT Service Instances - Test Setup #1 Authorization passed for mock user: idsb3t1@us.ibm.com
  test otc-api PUT Service Instances - Test Setup #2 Authorization passed for mock user: idsb3t1@us.ibm.com
  ```

Puede utilizar Sauce Labs con {{site.data.keyword.DRA_short}} añadiendo la integración de la herramienta Sauce Labs a su conducto. A continuación, incorpore las variables de entorno `SAUCE_USERNAME` y `SAUCE_ACCESS_KEY` en las pruebas de Selenium como credenciales.

Puede ver los títulos completos de todas las pruebas en los registros tras una ejecución.

**Notas:**
* {{site.data.keyword.DRA_short}} no da soporte a las pruebas críticas que contienen un guión en el título completo.
* Si cambia el nombre de su organización, debe recrear las políticas que estaban asociadas al nombre anterior. Perderá el acceso a los informes de decisión que se generaron antes del cambio de nombre.

## Visualización de informes de decisión
{: #DI_decision_reports}

Tras ejecutarse un conducto, {{site.data.keyword.DRA_short}} empieza a recopilar y analizar los resultados de las pruebas para establecer una línea base. Los datos de cada ejecución posterior se recopila y se compara con los resultados anteriores. Las puertas de decisión utilizan estos datos para determinar cuándo se debe detener un despliegue.

Para ver el informe de decisión de una puerta del conducto, siga estos pasos:

   1. En la etapa que contiene la puerta que se debe comprobar, pulse **Ver registros e historial**.

   2. Desde el trabajo que contiene la puerta, pulse el nombre de la puerta.

   3. En la ventana de registros, busque el mensaje `Comprobar aquí informe de {{site.data.keyword.DRA_short}}` y pulse el enlace para abrir el informe.


text:
require 'spec_helper'

require 'puppet/util/watcher'

describe Puppet::Util::Watcher do
  describe "the common file ctime watcher" do
    FakeStat = Struct.new(:ctime)

    def ctime(time)
      FakeStat.new(time)
    end

    let(:filename) { "fake" }

    def after_reading_the_sequence(initial, *results)
      mock_file = mock(filename)
      Puppet::FileSystem::File.expects(:new).with(filename).at_least(1).returns mock_file

      expectation = mock_file.stubs(:stat)
      ([initial] + results).each do |result|
        expectation = if result.is_a? Class
                        expectation.raises(result)
                      else
                        expectation.returns(result)
                      end.then
      end

      watcher = Puppet::Util::Watcher::Common.file_ctime_change_watcher(filename)
      results.size.times { watcher = watcher.next_reading }

      watcher
    end

    it "is intially unchanged" do
      expect(after_reading_the_sequence(ctime(20))).to_not be_changed
    end

    it "has not changed if a section of the file path continues to not exist" do
      expect(after_reading_the_sequence(Errno::ENOTDIR, Errno::ENOTDIR)).to_not be_changed
    end

    it "has not changed if the file continues to not exist" do
      expect(after_reading_the_sequence(Errno::ENOENT, Errno::ENOENT)).to_not be_changed
    end

    it "has changed if the file is created" do
      expect(after_reading_the_sequence(Errno::ENOENT, ctime(20))).to be_changed
    end

    it "is marked as changed if the file is deleted" do
      expect(after_reading_the_sequence(ctime(20), Errno::ENOENT)).to be_changed
    end

    it "is marked as changed if the file modified" do
      expect(after_reading_the_sequence(ctime(20), ctime(21))).to be_changed
    end
  end
end


text:
.class public Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;
.super Lcom/sun/org/apache/xml/internal/security/transforms/TransformSpi;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath$XPathNodeFilter;
    }
.end annotation

# static fields
.field static synthetic class$com$sun$org$apache$xml$internal$security$transforms$implementations$TransformXPath:Ljava/lang/Class; = null

.field public static final implementedTransformURI:Ljava/lang/String; = "http://www.w3.org/TR/1999/REC-xpath-19991116"

.field static log:Ljava/util/logging/Logger;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    sget-object v0, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;->class$com$sun$org$apache$xml$internal$security$transforms$implementations$TransformXPath:Ljava/lang/Class;

    if-eqz v0, :cond_0

    sget-object v0, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;->class$com$sun$org$apache$xml$internal$security$transforms$implementations$TransformXPath:Ljava/lang/Class;

    :goto_0
    invoke-virtual {v0}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Ljava/util/logging/Logger;->getLogger(Ljava/lang/String;)Ljava/util/logging/Logger;

    move-result-object v0

    sput-object v0, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;->log:Ljava/util/logging/Logger;

    return-void

    :cond_0
    const-string/jumbo v0, "com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath"

    invoke-static {v0}, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;->class$(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    sput-object v0, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;->class$com$sun$org$apache$xml$internal$security$transforms$implementations$TransformXPath:Ljava/lang/Class;

    goto :goto_0
.end method

.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Lcom/sun/org/apache/xml/internal/security/transforms/TransformSpi;-><init>()V

    return-void
.end method

.method static synthetic class$(Ljava/lang/String;)Ljava/lang/Class;
    .locals 3

    :try_start_0
    invoke-static {p0}, Ljava/lang/Class;->forName(Ljava/lang/String;)Ljava/lang/Class;
    :try_end_0
    .catch Ljava/lang/ClassNotFoundException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v1

    return-object v1

    :catch_0
    move-exception v0

    new-instance v1, Ljava/lang/NoClassDefFoundError;

    invoke-virtual {v0}, Ljava/lang/Throwable;->getMessage()Ljava/lang/String;

    move-result-object v2

    invoke-direct {v1, v2}, Ljava/lang/NoClassDefFoundError;-><init>(Ljava/lang/String;)V

    throw v1
.end method

.method private needsCircunvent(Ljava/lang/String;)Z
    .locals 1

    const/4 v0, 0x1

    return v0
.end method

# virtual methods
.method protected engineGetURI()Ljava/lang/String;
    .locals 1

    const-string/jumbo v0, "http://www.w3.org/TR/1999/REC-xpath-19991116"

    return-object v0
.end method

.method protected enginePerformTransform(Lcom/sun/org/apache/xml/internal/security/signature/XMLSignatureInput;)Lcom/sun/org/apache/xml/internal/security/signature/XMLSignatureInput;
    .locals 6
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/sun/org/apache/xml/internal/security/transforms/TransformationException;
        }
    .end annotation

    :try_start_0
    iget-object v3, p0, Lcom/sun/org/apache/xml/internal/security/transforms/TransformSpi;->_transformObject:Lcom/sun/org/apache/xml/internal/security/transforms/Transform;

    invoke-virtual {v3}, Lcom/sun/org/apache/xml/internal/security/utils/ElementProxy;->getElement()Lorg/w3c/dom/Element;

    move-result-object v3

    invoke-interface {v3}, Lorg/w3c/dom/Node;->getOwnerDocument()Lorg/w3c/dom/Document;

    move-result-object v3

    invoke-static {v3}, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder;->setDoc(Lorg/w3c/dom/Document;)V

    iget-object v3, p0, Lcom/sun/org/apache/xml/internal/security/transforms/TransformSpi;->_transformObject:Lcom/sun/org/apache/xml/internal/security/transforms/Transform;

    invoke-virtual {v3}, Lcom/sun/org/apache/xml/internal/security/utils/ElementProxy;->getElement()Lorg/w3c/dom/Element;

    move-result-object v3

    invoke-interface {v3}, Lorg/w3c/dom/Node;->getFirstChild()Lorg/w3c/dom/Node;

    move-result-object v3

    const-string/jumbo v4, "XPath"

    const/4 v5, 0x0

    invoke-static {v3, v4, v5}, Lcom/sun/org/apache/xml/internal/security/utils/XMLUtils;->selectDsNode(Lorg/w3c/dom/Node;Ljava/lang/String;I)Lorg/w3c/dom/Element;

    move-result-object v0

    if-eqz v0, :cond_0

    invoke-interface {v0}, Lorg/w3c/dom/Node;->getChildNodes()Lorg/w3c/dom/NodeList;

    move-result-object v3

    const/4 v4, 0x0

    invoke-interface {v3, v4}, Lorg/w3c/dom/NodeList;->item(I)Lorg/w3c/dom/Node;

    move-result-object v1

    invoke-static {v1}, Lcom/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI;->getStrFromNode(Lorg/w3c/dom/Node;)Ljava/lang/String;

    move-result-object v2

    invoke-direct {p0, v2}, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;->needsCircunvent(Ljava/lang/String;)Z

    move-result v3

    invoke-virtual {p1, v3}, Lcom/sun/org/apache/xml/internal/security/signature/XMLSignatureInput;->setNeedsToBeExpanded(Z)V

    if-eqz v1, :cond_1

    new-instance v3, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath$XPathNodeFilter;

    invoke-direct {v3, p0, v0, v1, v2}, Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath$XPathNodeFilter;-><init>(Lcom/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath;Lorg/w3c/dom/Element;Lorg/w3c/dom/Node;Ljava/lang/String;)V

    invoke-virtual {p1, v3}, Lcom/sun/org/apache/xml/internal/security/signature/XMLSignatureInput;->addNodeFilter(Lcom/sun/org/apache/xml/internal/security/signature/NodeFilter;)V

    const/4 v3, 0x1

    invoke-virtual {p1, v3}, Lcom/sun/org/apache/xml/internal/security/signature/XMLSignatureInput;->setNodeSet(Z)V

    return-object p1

    :cond_0
    const/4 v3, 0x2

    new-array v1, v3, [Ljava/lang/Object;

    const-string/jumbo v3, "ds:XPath"

    const/4 v4, 0x0

    aput-object v3, v1, v4

    const-string/jumbo v3, "Transform"

    const/4 v4, 0x1

    aput-object v3, v1, v4

    new-instance v3, Lcom/sun/org/apache/xml/internal/security/transforms/TransformationException;

    const-string/jumbo v4, "xml.WrongContent"

    invoke-direct {v3, v4, v1}, Lcom/sun/org/apache/xml/internal/security/transforms/TransformationException;-><init>(Ljava/lang/String;[Ljava/lang/Object;)V

    throw v3
    :try_end_0
    .catch Lorg/w3c/dom/DOMException; {:try_start_0 .. :try_end_0} :catch_0

    :catch_0
    move-exception v0

    new-instance v3, Lcom/sun/org/apache/xml/internal/security/transforms/TransformationException;

    const-string/jumbo v4, "empty"

    invoke-direct {v3, v4, v0}, Lcom/sun/org/apache/xml/internal/security/transforms/TransformationException;-><init>(Ljava/lang/String;Ljava/lang/Exception;)V

    throw v3

    :cond_1
    :try_start_1
    new-instance v3, Lorg/w3c/dom/DOMException;

    const/4 v4, 0x3

    const-string/jumbo v5, "Text must be in ds:Xpath"

    invoke-direct {v3, v4, v5}, Lorg/w3c/dom/DOMException;-><init>(SLjava/lang/String;)V

    throw v3
    :try_end_1
    .catch Lorg/w3c/dom/DOMException; {:try_start_1 .. :try_end_1} :catch_0
.end method


text:
import { Focus, SugarElement } from '@ephox/sugar';

import * as Touches from '../touch/Touches';
import { Chain } from './Chain';
import { Step } from './Step';
import * as UiFinder from './UiFinder';

const touchStart = Touches.touchstart;
const touchStartAt = (element: SugarElement<Node>, dx: number, dy: number): void => Touches.touchstartAt(dx, dy)(element);
const touchEnd = Touches.touchend;
const touchEndAt = (element: SugarElement<Node>, dx: number, dy: number): void => Touches.touchendAt(dx, dy)(element);
const touchMove = Touches.touchmove;
const touchMoveTo = (element: SugarElement<Node>, dx: number, dy: number): void => Touches.touchmoveTo(dx, dy)(element);

const cTrigger = <T extends Node, U extends Element>(selector: string, action: (ele: SugarElement<U>) => void) =>
  Chain.async<SugarElement<T>, SugarElement<T>>((container, next, die) => {
    UiFinder.findIn<U>(container, selector).fold(
      () => die('Could not find element: ' + selector),
      (ele) => {
        action(ele);
        next(container);
      }
    );
  });

const sTriggerWith = <T, U extends Element>(container: SugarElement<Node>, selector: string, action: (ele: SugarElement<U>) => void) =>
  Chain.asStep<T, SugarElement<Node>>(container, [ cTrigger<Node, U>(selector, action) ]);

const trueTap = (elem: SugarElement<HTMLElement>): void => {
  // The closest event queue to a true tap event
  Focus.focus(elem);
  Touches.touchstart(elem);
  Touches.touchend(elem);
};

const tap = (elem: SugarElement<Node>): void => {
  Touches.touchstart(elem);
  Touches.touchend(elem);
};

const sTap = <T>(element: SugarElement<Node>): Step<T, T> =>
  Step.sync<T>(() => tap(element));

const sTrueTapOn = <T>(container: SugarElement<Node>, selector: string): Step<T, T> =>
  sTriggerWith<T, HTMLElement>(container, selector, trueTap);

const sTapOn = <T>(container: SugarElement<Node>, selector: string): Step<T, T> =>
  sTriggerWith<T, Element>(container, selector, tap);

const cTapOn = <T extends Node>(selector: string): Chain<SugarElement<T>, SugarElement<T>> =>
  cTrigger(selector, tap);

const cTouchStartAt = <T extends Node>(dx: number, dy: number): Chain<SugarElement<T>, SugarElement<T>> =>
  Chain.op<SugarElement<T>>(Touches.touchstartAt(dx, dy));

const cTouchEndAt = <T extends Node>(dx: number, dy: number): Chain<SugarElement<T>, SugarElement<T>> =>
  Chain.op<SugarElement<T>>(Touches.touchendAt(dx, dy));

const cTouchMoveTo = <T extends Node>(dx: number, dy: number): Chain<SugarElement<T>, SugarElement<T>> =>
  Chain.op<SugarElement<T>>(Touches.touchmoveTo(dx, dy));

const point = Touches.point;

const cTrueTap = Chain.op(trueTap);
const cTap = Chain.op(tap);
const cTouchMove = Chain.op(Touches.touchmove);
const cTouchStart = Chain.op(Touches.touchstart);
const cTouchEnd = Chain.op(Touches.touchend);

export {
  point,

  tap,
  trueTap,

  touchStart,
  touchStartAt,
  touchEnd,
  touchEndAt,
  touchMove,
  touchMoveTo,

  sTap,
  sTapOn,
  sTrueTapOn,

  cTap,
  cTapOn,
  cTrueTap,
  cTouchStart,
  cTouchStartAt,
  cTouchMove,
  cTouchMoveTo,
  cTouchEnd,
  cTouchEndAt
};


text:
package gov.hhs.fha.nhinc.connectmgr.persistance.dao;

import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerException;
import gov.hhs.fha.nhinc.properties.PropertyAccessor;

import java.io.File;

import javax.xml.bind.JAXBException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.uddi.api_v3.BusinessDetail;

/**
 *
 * @author kshtabnoy
 *
 *         Implementation of ConnectionManagerDAO that stores connection information in local file
 *
 */
public class UddiConnectionInfoDAOFileImpl extends ConnectionManagerDAOBase implements ConnectionManagerDAO {

    private static UddiConnectionInfoDAOFileImpl instance = null;
    private File file = null;
    private Log log = null;
    private static final String UDDI_XML_FILE_NAME = "uddiConnectionInfo.xml";

    public static UddiConnectionInfoDAOFileImpl getInstance() {
        if (instance == null) {
            instance = new UddiConnectionInfoDAOFileImpl();
        }
        return instance;
    }

    UddiConnectionInfoDAOFileImpl() {
        log = getLogger();

        String fileName = getUddiConnectionFileLocation();
        log.debug("Reading UddiConnectionInfo from file: " + fileName);
        if (fileName != null) {
            file = new File(fileName);
        }
    }

    public String getUddiConnectionFileLocation() {
        if (file == null) {
            String sValue = PropertyAccessor.getInstance().getPropertyFileLocation();
            if (sValue != null && sValue.length() > 0) {
                if (sValue.endsWith(File.separator)) {
                    setFileName(sValue + UDDI_XML_FILE_NAME);
                } else {
                    setFileName(sValue + File.separator + UDDI_XML_FILE_NAME);
                }
            }
        }

        return isFile() ? file.getAbsolutePath() : null;
    }

    private boolean isFile() {
        return file != null && file.exists();
    }
    @Override
    public BusinessDetail loadBusinessDetail() throws Exception {
        if (!isFile()) {
            throw new ConnectionManagerException("Unable to access system variable: nhinc.properties.dir.");
        }

        BusinessDetail resp = null;
        try {
            resp = super.loadBusinessDetail(file);
        } catch (JAXBException ex) {
            getLogger().error("unable to load business entities from " + file.getName(), ex);
            resp = new BusinessDetail();
            throw new Exception("unable to load business entities from " + file.getName(), ex);
        }
        return resp;
    }

    @Override
    public void saveBusinessDetail(BusinessDetail BusinessDetail) {
        super.saveBusinessDetail(BusinessDetail, file);
    }

    public long getLastModified() {
        if (file.exists()) {
            return file.lastModified();
        } else {
            return 0;
        }
    }

    @Override
    protected Log getLogger() {
        if (log == null) {
            setLogger(LogFactory.getLog(this.getClass()));
        }
        return log;
    }

    @Override
    protected void setLogger(Log log) {
        this.log = log;
    }

    public void setFileName(String fileName) {
        file = new File(fileName);
    }
}


text:
package com.palantir.atlasdb.keyvalue.api;

import com.palantir.common.persist.Persistable;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.SafeArg;
import org.immutables.value.Value;

@Value.Immutable
public abstract class TargetedSweepMetadata implements Persistable {
    public abstract boolean conservative();

    public abstract boolean dedicatedRow();

    public abstract int shard();

    public abstract long dedicatedRowNumber();

    @Value.Default
    public boolean nonSweepableTransaction() {
        return false;
    }

    public static final int MAX_SHARDS = 256;
    public static final int MAX_DEDICATED_ROWS = 64;
    private static final int SWEEP_STRATEGY_MASK = 0x80;
    private static final int USE_DEDICATED_ROWS_MASK = 0x40;
    private static final int DEDICATED_ROW_NUMBER_MASK = 0x3F;
    private static final int BYTE_MASK = 0xFF;

    @Value.Check
    void checkShardSize() {
        Preconditions.checkArgument(
                shard() >= 0 && shard() < MAX_SHARDS,
                "Shard number must non-negative and strictly less than the maximum.",
                SafeArg.of("maxShards", MAX_SHARDS),
                SafeArg.of("shards", shard()));
    }

    @Value.Check
    void checkRowNumber() {
        Preconditions.checkArgument(
                dedicatedRowNumber() >= 0 && dedicatedRowNumber() < MAX_DEDICATED_ROWS,
                "Dedicated row number must non-negative and strictly less than the maximum.",
                SafeArg.of("maxDedicatedRows", MAX_DEDICATED_ROWS),
                SafeArg.of("dedicatedRows", dedicatedRowNumber()));
    }

    @Value.Check
    void checkDefaultsForNonSweepableTransaction() {
        if (nonSweepableTransaction()) {
            Preconditions.checkArgument(conservative(), "Non sweepable transactions must set the conservative bit.");
            Preconditions.checkArgument(!dedicatedRow(), "Non sweepable transactions must not use dedicated rows.");
            Preconditions.checkArgument(shard() == 0, "Non sweepable transactions must use only shard 0.");
        }
    }

    public static final Hydrator<TargetedSweepMetadata> BYTES_HYDRATOR =
            input -> ImmutableTargetedSweepMetadata.builder()
                    .conservative((input[0] & SWEEP_STRATEGY_MASK) != 0)
                    .dedicatedRow((input[0] & USE_DEDICATED_ROWS_MASK) != 0)
                    .shard((input[0] << 2 | (input[1] & BYTE_MASK) >> 6) & BYTE_MASK)
                    .dedicatedRowNumber(input[1] & DEDICATED_ROW_NUMBER_MASK)
                    .nonSweepableTransaction((input[2] & SWEEP_STRATEGY_MASK) != 0)
                    .build();

    @Override
    public byte[] persistToBytes() {
        byte[] result = new byte[] {0, 0, 0, 0};
        result[0] |= (shard() & BYTE_MASK) >> 2;
        if (dedicatedRow()) {
            result[0] |= USE_DEDICATED_ROWS_MASK;
        }
        if (conservative()) {
            result[0] |= SWEEP_STRATEGY_MASK;
        }
        result[1] |= dedicatedRowNumber() & DEDICATED_ROW_NUMBER_MASK;
        result[1] |= (shard() << 6) & BYTE_MASK;
        if (nonSweepableTransaction()) {
            result[2] |= SWEEP_STRATEGY_MASK;
        }
        return result;
    }
}


text:
* [FluxPlus.Action](actions/action.md)
* [FluxPlus.BaseStore](stores/base-store.md)
* [FluxPlus.Dispatcher](dispatcher/dispatcher.md)

## Enums

* [FluxPlus.ActionSource](actions/action-source.md)
* [FluxPlus.EntityOperation](actions/entity-operation.md)

## Error types

* [FluxPlus.errors.ValidationError](errors/validation-error.md)
* [FluxPlus.errors.InvalidArgumentError](errors/invalid-argument-error.md)


text:
import unittest, time
from selenium import webdriver

class CreateAccountSuite(unittest.TestCase):

    def setUp(self):
        desired_capabilities = webdriver.DesiredCapabilities.FIREFOX
        desired_capabilities['version'] = '24'
        desired_capabilities['platform'] = 'Linux'
        desired_capabilities['name'] = 'Create Account'

        self.driver = webdriver.Remote(
            desired_capabilities=desired_capabilities,
            command_executor="http://esodvn:325caef9-81dd-47a5-8b74-433057ce888f@ondemand.saucelabs.com:80/wd/hub"
        )
        self.driver.implicitly_wait(30)

    def test_sauce(self):
        driver=self.driver
        driver.get('http://dvn-build.hmdc.harvard.edu/dataverseuser.xhtml')
        driver.find_element_by_id("dataverseUserForm:editAccountButton_button").click()
        driver.find_element_by_link_text("Create Account").click()
        driver.find_element_by_id("dataverseUserForm:userName").click()
        driver.find_element_by_id("dataverseUserForm:userName").clear()
        driver.find_element_by_id("dataverseUserForm:userName").send_keys("user1")
        driver.find_element_by_id("dataverseUserForm:inputPassword").click()
        driver.find_element_by_id("dataverseUserForm:inputPassword").clear()
        driver.find_element_by_id("dataverseUserForm:inputPassword").send_keys("u")
        driver.find_element_by_id("dataverseUserForm:retypePassword").click()
        driver.find_element_by_id("dataverseUserForm:retypePassword").clear()
        driver.find_element_by_id("dataverseUserForm:retypePassword").send_keys("u")
        driver.find_element_by_id("dataverseUserForm:firstName").click()
        driver.find_element_by_id("dataverseUserForm:firstName").clear()
        driver.find_element_by_id("dataverseUserForm:firstName").send_keys("user")
        driver.find_element_by_id("dataverseUserForm:lastName").click()
        driver.find_element_by_id("dataverseUserForm:lastName").clear()
        driver.find_element_by_id("dataverseUserForm:lastName").send_keys("zero")
        driver.find_element_by_id("dataverseUserForm:email").click()
        driver.find_element_by_id("dataverseUserForm:email").clear()
        driver.find_element_by_id("dataverseUserForm:email").send_keys("u@u.edu")
        driver.find_element_by_id("dataverseUserForm:institution").click()
        driver.find_element_by_id("dataverseUserForm:institution").clear()
        driver.find_element_by_id("dataverseUserForm:institution").send_keys("IQSS")
        driver.find_element_by_id("dataverseUserForm:j_idt45_focus").click()
        driver.find_element_by_id("dataverseUserForm:j_idt45_focus").send_keys("\\9")
        driver.find_element_by_css_selector("span.ui-icon.ui-icon-triangle-1-s").click()
        driver.find_element_by_xpath("//div[@class='ui-selectonemenu-items-wrapper']//li[.='Student']").click()
        driver.find_element_by_id("dataverseUserForm:phone").click()
        driver.find_element_by_id("dataverseUserForm:phone").click()
        driver.find_element_by_id("dataverseUserForm:phone").clear()
        driver.find_element_by_id("dataverseUserForm:phone").send_keys("888-888-8888")
        driver.find_element_by_id("dataverseUserForm:save").click()

    def tearDown(self):
        print("Link to your job: https://saucelabs.com/jobs/%s" % self.driver.session_id)
        self.driver.quit()

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


text:
/// <reference path='fourslash.ts'/>

////module ObjectLiterals {
////    interface MyPoint {
////        x1: number;
////        y1: number;
////    }
////
////    var p1: MyPoint = {
////        /*1*/
////    };
////
////    var p2: MyPoint = {
////        x1: 5,
////        /*2*/
////    };
////
////    var p3: MyPoint = {
////        x1/*3*/:
////    };
////
////    var p4: MyPoint = {
////        /*4*/y1
////    };
////}

// Literal member completion inside empty literal.
goTo.marker("1");
verify.completionListContains("x1", "(property) MyPoint.x1: number");
verify.completionListContains("y1", "(property) MyPoint.y1: number");

// Literal member completion for 2nd member name.
goTo.marker("2");
verify.completionListContains("y1", "(property) MyPoint.y1: number");

// Literal member completion at existing member name location.
goTo.marker("3");
verify.completionListContains("y1", "(property) MyPoint.y1: number");

goTo.marker("4");
verify.completionListContains("x1", "(property) MyPoint.x1: number");


text:
import collections
import itertools

import six

from purplex.exception import TableConflictError, StartSymbolNotReducedError
from purplex.grammar import Grammar, Production, END_OF_INPUT
from purplex.lex import Lexer
from purplex.token import Token

END_OF_INPUT_TOKEN = Token(END_OF_INPUT, '', '', 0, 0)

LEFT = 'left'
RIGHT = 'right'
DEFAULT_PREC = (LEFT, 0)

def attach(rule, prec_symbol=None):
    def wrapper(func):
        if not hasattr(func, 'productions'):
            func.productions = set()
        func.productions.add((Production(rule, func), prec_symbol))
        return func
    return wrapper

def attach_list(nonterminal, singular, single=True, epsilon=False):
    def wrapper(func):
        productions = [
            '{} : {} {}'.format(nonterminal, nonterminal, singular),
        ]
        if single:
            productions.append('{} : {}'.format(nonterminal, singular))
        if epsilon:
            productions.append('{} : '.format(nonterminal))

        for production in productions:
            attach(production)(func)
        return func
    return wrapper

def attach_sep_list(nonterminal, singular, separator, epsilon=False):
    def wrapper(func):
        inner_nonterminal = '{}_inner'.format(nonterminal)
        productions = [
            '{} : {}'.format(nonterminal, inner_nonterminal),
            '{} : {} {} {}'.format(inner_nonterminal, inner_nonterminal,
                                   separator, singular),
            '{} : {}'.format(inner_nonterminal, singular),
            ]
        if epsilon:
            productions.append('{} : '.format(nonterminal))

        for producution in productions:
            attach(producution)(func)
        return func
    return wrapper

class ParserBase(type):

    def __new__(cls, name, bases, dct):
        productions = set()
        for _, attr in dct.items():
            if hasattr(attr, 'productions'):
                productions |= attr.productions

        grammar = Grammar(dct['LEXER'].token_map.keys(),
                          [production for production, _ in productions],
                          start=dct['START'])
        precedence = cls.compute_precedence(grammar.terminals,
                                            productions,
                                            dct.get('PRECEDENCE') or ())
        INITIAL_STATE, ACTION, GOTO = cls.make_tables(grammar, precedence)
        dct.update({
            'grammar': grammar,
            'INITIAL_STATE': INITIAL_STATE,
            'ACTION': ACTION,
            'GOTO': GOTO,
        })
        return type.__new__(cls, name, bases, dct)

    @staticmethod
    def compute_precedence(terminals, productions, precedence_levels):
        """Computes the precedence of terminal and production.

        The precedence of a terminal is it's level in the PRECEDENCE tuple. For
        a production, the precedence is the right-most terminal (if it exists).
        The default precedence is DEFAULT_PREC - (LEFT, 0).

        Returns:
            precedence - dict[terminal | production] = (assoc, level)

        """
        precedence = collections.OrderedDict()

        for terminal in terminals:
            precedence[terminal] = DEFAULT_PREC

        level_precs = range(len(precedence_levels), 0, -1)
        for i, level in zip(level_precs, precedence_levels):
            assoc = level[0]
            for symbol in level[1:]:
                precedence[symbol] = (assoc, i)

        for production, prec_symbol in productions:
            if prec_symbol is None:
                prod_terminals = [symbol for symbol in production.rhs
                                  if symbol in terminals] or [None]
                precedence[production] = precedence.get(prod_terminals[-1],
                                                        DEFAULT_PREC)
            else:
                precedence[production] = precedence.get(prec_symbol,
                                                        DEFAULT_PREC)

        return precedence

    @staticmethod
    def make_tables(grammar, precedence):
        """Generates the ACTION and GOTO tables for the grammar.

        Returns:
            action - dict[state][lookahead] = (action, ...)
            goto - dict[state][just_reduced] = new_state

        """
        ACTION = {}
        GOTO = {}

        labels = {}

        def get_label(closure):
            if closure not in labels:
                labels[closure] = len(labels)
            return labels[closure]

        def resolve_shift_reduce(lookahead, s_action, r_action):
            s_assoc, s_level = precedence[lookahead]
            r_assoc, r_level = precedence[r_action[1]]

            if s_level < r_level:
                return r_action
            elif s_level == r_level and r_assoc == LEFT:
                return r_action
            else:
                return s_action

        initial, closures, goto = grammar.closures()
        for closure in closures:
            label = get_label(closure)

            for rule in closure:
                new_action, lookahead = None, rule.lookahead

                if not rule.at_end:
                    symbol = rule.rhs[rule.pos]
                    is_terminal = symbol in grammar.terminals
                    has_goto = symbol in goto[closure]
                    if is_terminal and has_goto:
                        next_state = get_label(goto[closure][symbol])
                        new_action, lookahead = ('shift', next_state), symbol
                elif rule.production == grammar.start and rule.at_end:
                    new_action = ('accept',)
                elif rule.at_end:
                    new_action = ('reduce', rule.production)

                if new_action is None:
                    continue

                prev_action = ACTION.get((label, lookahead))
                if prev_action is None or prev_action == new_action:
                    ACTION[label, lookahead] = new_action
                else:
                    types = (prev_action[0], new_action[0])
                    if types == ('shift', 'reduce'):
                        chosen = resolve_shift_reduce(lookahead,
                                                      prev_action,
                                                      new_action)
                    elif types == ('reduce', 'shift'):
                        chosen = resolve_shift_reduce(lookahead,
                                                      new_action,
                                                      prev_action)
                    else:
                        raise TableConflictError(prev_action, new_action)

                    ACTION[label, lookahead] = chosen

            for symbol in grammar.nonterminals:
                if symbol in goto[closure]:
                    GOTO[label, symbol] = get_label(goto[closure][symbol])

        return get_label(initial), ACTION, GOTO

@six.add_metaclass(ParserBase)
class Parser(object):

    LEXER = Lexer
    START = 'S'
    PRECEDENCE = ()

    grammar = None
    INITIAL_STATE = 0
    ACTION = {}
    GOTO = {}

    def parse(self, raw):
        """Parses an input string and applies the parser's grammar."""
        lexer = self.LEXER(raw)
        tokens = iter(itertools.chain(lexer, [END_OF_INPUT_TOKEN]))
        stack = [(self.INITIAL_STATE, '<initial>', '<begin>')]

        token = next(tokens)
        while stack:
            state, _, _ = stack[-1]

            action = self.ACTION.get((state, token.name))
            if action is None:
                raise StartSymbolNotReducedError(self.START)

            if action[0] == 'reduce':
                production = action[1]

                # Special case for epsilon rules
                if len(production):
                    args = (item[2] for item in stack[-len(production):])
                    del stack[-len(production):]
                else:
                    args = []

                prev_state, _, _ = stack[-1]
                new_state = self.GOTO[prev_state, production.lhs]
                stack.append((
                    new_state,
                    production.lhs,
                    production.func(self, *args),
                ))
            elif action[0] == 'shift':
                stack.append((action[1], token.name, token.value))
                token = next(tokens)
            elif action[0] == 'accept':
                return stack[-1][2]


text:
package jadx.gui.utils;

import jadx.api.JavaClass;
import jadx.api.JavaMethod;
import jadx.api.JavaNode;

import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

public class CodeLinesInfo {
	private NavigableMap<Integer, JavaNode> map = new TreeMap<Integer, JavaNode>();

	public CodeLinesInfo(JavaClass cls) {
		addClass(cls);
	}

	public void addClass(JavaClass cls) {
		map.put(cls.getDecompiledLine(), cls);
		for (JavaClass innerCls : cls.getInnerClasses()) {
			map.put(innerCls.getDecompiledLine(), innerCls);
			addClass(innerCls);
		}
		for (JavaMethod mth : cls.getMethods()) {
			map.put(mth.getDecompiledLine(), mth);
		}
	}

	public JavaNode getJavaNodeByLine(int line) {
		Map.Entry<Integer, JavaNode> entry = map.floorEntry(line);
		if (entry == null) {
			return null;
		}
		return entry.getValue();
	}
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class registered_user_model extends CI_Model {

    var $table = 'registered_user';

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }

    function edit($condition = array(), $data_array = array()) {

        if ($condition) {
            $this->db->where($condition);
        }
        if ($this->db->update($this->table, $data_array)) {
            return true;
        } else {
            return false;
        }
    }

    function get_all_entries($row, $limit, $condition = array(), $order_by_fieled, $order_by_type = "asc") {
        //$this->db->where('blog_status','E');
        if ($condition) {
            $this->db->where($condition);
        }
        if ($order_by_fieled) {
            $this->db->order_by($order_by_fieled, $order_by_type);
        }
        $query = $this->db->get($this->table, $limit, $row);

        if ($query->num_rows() > 0) {
            return $query->result_array();
        } else {
            return array();
        }
    }

    function get_all($condition = array(), $order_by_fieled = '', $order_by_type = "asc") {
        $this->db->from($this->table);
        if ($condition) {
            $this->db->where($condition);
        }
        if ($order_by_fieled) {
            $this->db->order_by($order_by_fieled, $order_by_type);
        }
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        } else {
            return array();
        }
    }

    function countrows($condition = array()) {

        $this->db->from($this->table);
        if ($condition) {
            $this->db->where($condition);
        }
        $query = $this->db->get();
        $row = $query->num_rows();
        return $row;
    }

    function add($data_array = array()) {

        $this->db->insert($this->table, $data_array);
        return $this->db->insert_id();
    }

    function get_entry($condition = array()) {

        $this->db->from($this->table);
        if ($condition) {
            $this->db->where($condition);
        }

        if ($query->num_rows() == 1) {
            return $query->row();
        } else {
            return false;
        }
    }

    function delete($condition = array()) {

        $this->db->where($condition);
        $this->db->delete($this->table);
    }

    function get_all_blog($condition = array(), $order_by_fieled = '', $order_by_type = "asc") {
        $this->db->from('registered_users_blog');
        if ($condition) {
            $this->db->where($condition);
        }
        if ($order_by_fieled) {
            $this->db->order_by($order_by_fieled, $order_by_type);
        }
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        } else {
            return array();
        }
    }

    function get_field_data($condition = array(), $field_name = '') {

        $this->db->select($field_name);
        $this->db->from($this->table);
        $this->db->where($condition);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $firstname = $query->row();

            $return_value = $firstname->$field_name;
            return $return_value;
        }
    }

    function check_login() {

        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $salt = sha1($password);
        $password = md5($salt . $password);
        $return = FALSE;
        $condition = array('registered_user_username' => $username,
            'registered_user_password' => $password,
            'registered_user_active' => 'Y'
        );
        $this->db->from($this->table);
        if ($condition) {
            $this->db->where($condition);
        }

        $query = $this->db->get();
        if ($query->num_rows() > 0) {

            $result = $query->result();
            $this->session->set_userdata('ADMIN_NAME', $result[0]->registered_user_full_name);
            $this->session->set_userdata('user_type', $result[0]->registered_user_usertype);
            $this->session->set_userdata('registered_user_id', $result[0]->registered_user_id);
            $return = TRUE;
        }

        return $return;
    }

    function change_password() {

        $password = $this->input->post('password');
        $old = $this->input->post('old_password');
        $salt = sha1($password);
        $password = md5($salt . $password);
        $salt = sha1($old);
        $old = md5($salt . $old);
        $this->db->where(array("registered_user_id" => $this->session->userdata('registered_user_id'), 'registered_user_password' => $old));
        $query = $this->db->get('registered_user');
        if ($query->num_rows() > 0) {
            $this->db->where(array("registered_user_id" => $this->session->userdata('registered_user_id')));
            $this->db->update('registered_user', array('registered_user_password' => $password));
            return 1;
        } else {
            return 0;
        }
    }

}

?>


text:
import {  Component, Input }  from '@angular/core';

@Component({
  selector: 'order-processor',
  template: `
    Buying {{quantity}} shares of {{stockSymbol}}
  `,
  styles:[`:host {background: cyan;}`]
})
export class OrderComponent {

  @Input() quantity: number;

  private _stockSymbol: string;

  @Input()
  set stockSymbol(value: string) {

    if (value != undefined) {
      this._stockSymbol = value;
      console.log(`Sending a Buy order to NASDAQ: ${this.stockSymbol}  ${this.quantity}`);
    }
  }

  get stockSymbol(): string {
    return this._stockSymbol;
  }
}


text:
@interface FlxOrderedCollection : NSObject <FlxCollectionProtocol, NSFastEnumeration>
@property (readonly) NSArray *keyPaths;
@property (readonly) NSUInteger count;
@property (readonly) NSArray *objects;
@property (readonly) id firstObject;
@property (readonly) id lastObject;
@property (readonly) NSUInteger lastIndex;
+ (instancetype) collectionWithKeyPaths:(NSArray *)keyPaths;
- (instancetype) initWithKeyPaths:(NSArray *)keyPaths;

- (id) objectAtIndex:(NSUInteger)index;
- (NSUInteger) indexOfObject:(id)object;
- (void) insertObject:(id)object atIndex:(NSUInteger)index;
- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object;
- (void) removeObjectAtIndex:(NSUInteger)index;
- (void) moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex;
- (void) moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex withBlock:(void (^)(id object, NSUInteger from, NSUInteger to))block;
- (void) swap:(NSUInteger)index with:(NSUInteger)index2;
- (void) setObject:(id)obj atIndexedSubscript:(NSUInteger)index;
- (id) objectAtIndexedSubscript:(NSUInteger)index;
@end


text:
package com.google.android.apps.muzei.sync;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.BaseColumns;
import android.util.Log;

import com.google.android.apps.muzei.api.MuzeiContract;
import com.google.android.apps.muzei.event.ArtworkLoadingStateChangedEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadArtworkTask extends AsyncTask<Void, Void, Boolean> {
    private static final String TAG = "DownloadArtworkTask";

    private static final int DEFAULT_READ_TIMEOUT = 30; // in seconds
    private static final int DEFAULT_CONNECT_TIMEOUT = 15; // in seconds

    private final Context mApplicationContext;

    public DownloadArtworkTask(Context context) {
        mApplicationContext = context.getApplicationContext();
    }

    @Override
    protected void onProgressUpdate(final Void... values) {
        EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(true, false));
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        ContentResolver resolver = mApplicationContext.getContentResolver();
        String[] projection = {BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI };
        Cursor data = resolver.query(MuzeiContract.Artwork.CONTENT_URI, projection, null, null, null);
        if (data == null || !data.moveToFirst()) {
            if (data != null) {
                data.close();
            }
            return false;
        }
        Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI,
                data.getLong(0));
        Uri imageUri = Uri.parse(data.getString(1));
        data.close();
        OutputStream out = null;
        InputStream in = null;
        try {
            out = resolver.openOutputStream(artworkUri);
            if (out == null) {
                // We've already downloaded the file
                return true;
            }
            // Only publish progress (i.e., say we've started loading the artwork)
            // if we actually need to download the artwork
            publishProgress();
            in = openUri(mApplicationContext, imageUri);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } catch (IOException e) {
            Log.e(TAG, "Error downloading artwork", e);
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error closing artwork input stream", e);
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error closing artwork output stream", e);
            }
        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        if (success) {
            EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(false, false));
        } else {
            EventBus.getDefault().postSticky(new ArtworkLoadingStateChangedEvent(false, true));
        }
    }

    private InputStream openUri(Context context, Uri uri)
            throws IOException {

        if (uri == null) {
            throw new IllegalArgumentException("Uri cannot be empty");
        }

        String scheme = uri.getScheme();
        if (scheme == null) {
            throw new IOException("Uri had no scheme");
        }

        InputStream in = null;
        if ("content".equals(scheme)) {
            try {
                in = context.getContentResolver().openInputStream(uri);
            } catch (SecurityException e) {
                throw new FileNotFoundException("No access to " + uri + ": " + e.toString());
            }

        } else if ("file".equals(scheme)) {
            List<String> segments = uri.getPathSegments();
            if (segments != null && segments.size() > 1
                    && "android_asset".equals(segments.get(0))) {
                AssetManager assetManager = context.getAssets();
                StringBuilder assetPath = new StringBuilder();
                for (int i = 1; i < segments.size(); i++) {
                    if (i > 1) {
                        assetPath.append("/");
                    }
                    assetPath.append(segments.get(i));
                }
                in = assetManager.open(assetPath.toString());
            } else {
                in = new FileInputStream(new File(uri.getPath()));
            }

        } else if ("http".equals(scheme) || "https".equals(scheme)) {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS)
                    .build();
            Request request;
            request = new Request.Builder().url(new URL(uri.toString())).build();

            Response response = client.newCall(request).execute();
            int responseCode = response.code();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response " + responseCode);
            }
            in = response.body().byteStream();
        }

        if (in == null) {
            throw new FileNotFoundException("Null input stream for URI: " + uri);
        }

        return in;
    }
}


text:
package com.nextbreakpoint.shop.designs.controllers.insert;

import com.nextbreakpoint.shop.common.model.Controller;
import com.nextbreakpoint.shop.common.model.events.DesignChangedEvent;
import com.nextbreakpoint.shop.common.vertx.DesignChangedMapper;
import com.nextbreakpoint.shop.designs.Store;
import com.nextbreakpoint.shop.designs.model.InsertDesignRequest;
import com.nextbreakpoint.shop.designs.model.InsertDesignResponse;
import io.vertx.core.json.Json;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.rxjava.kafka.client.producer.KafkaProducer;
import io.vertx.rxjava.kafka.client.producer.KafkaProducerRecord;
import rx.Single;

import java.util.Objects;

public class InsertDesignController implements Controller<InsertDesignRequest, InsertDesignResponse> {
    private Logger logger = LoggerFactory.getLogger(InsertDesignController.class);

    private final Store store;
    private final String topic;
    private final KafkaProducer<String, String> producer;
    private final DesignChangedMapper mapper;

    public InsertDesignController(Store store, String topic, KafkaProducer<String, String> producer, DesignChangedMapper mapper) {
        this.store = Objects.requireNonNull(store);
        this.topic = Objects.requireNonNull(topic);
        this.producer = Objects.requireNonNull(producer);
        this.mapper = Objects.requireNonNull(mapper);
    }

    @Override
    public Single<InsertDesignResponse> onNext(InsertDesignRequest request) {
        return store.insertDesign(request).flatMap(this::sendMessage);
    }

    protected Single<InsertDesignResponse> sendMessage(InsertDesignResponse response) {
        return createRecord(response)
                .flatMap(record -> producer.rxWrite(record).map(metadata -> response))
                .doOnError(err -> logger.error("Failed to write record into Kafka", err))
                .onErrorReturn(err -> response);
    }

    protected Single<KafkaProducerRecord<String, String>> createRecord(InsertDesignResponse response) {
        return Single.fromCallable(() -> KafkaProducerRecord.create(topic, response.getUuid().toString(), Json.encode(mapper.transform(new DesignChangedEvent(response.getUuid(), System.currentTimeMillis())))));
    }
}


text:
require 'htmlentities'

module RgraphHelper

def rgraph_includes(libraries)
  includes = ''
  includes << stylesheet_link_tag('rgraph/rgraph')

  includes << javascript_include_tag("prototype.js")
  includes << javascript_include_tag("rgraph/RGraph.common.core.js")
  includes << javascript_include_tag("rgraph/RGraph.common.context.js")
  includes << javascript_include_tag("rgraph/RGraph.common.annotate.js")
  includes << javascript_include_tag("rgraph/RGraph.common.tooltips.js")
  includes << javascript_include_tag("rgraph/RGraph.common.resizing.js")

  for l in libraries
    includes << javascript_include_tag('rgraph/Rgraph.'+l.to_s)
  end

  includes
end

def rgraph_get_csv_file(csv, text = 'CSV', class_name='verdeClaro')

  id = Rgraph::Util.generate_id

  <<-HTML

  <form id="rgraph_csv_#{id}" method="post" action="/#{controller_name}/rgraph_get_csv">
		#{hidden_field_tag(:data, YAML::dump(csv)) }
		#{hidden_field_tag request_forgery_protection_token.to_s, form_authenticity_token}
		#{text}
	</form>

	HTML

end

def rgraph_get_csv_file2(csv)
  includes = ''
    coder = HTMLEntities.new
    data = CGI.escape(URI.escape(coder.encode(csv, :named)))

#  includes << "hola"
#  includes << "
#{}"

#var myWindow=window.open("","new","")
#myWindow.document.open("application/excel")
#myWindow.document.write("1,2,3")
#myWindow.close()

end


text:
This sample uses jblubble-api and jblubble-jdbc. If you don't have them installed yet, install them first by:

	> cd jblubble-api
	> mvn install
	> cd jblubble-jdbc
	> mvn install

To run the sample:

	> mvn tomcat7:run

Then go to [http://localhost:8080/jblubble-sample/uploads](http://localhost:8080/jblubble-sample/uploads) which is handled by `UploadServlet`. You can also go to [http://localhost:8080/jblubble-sample/persons](http://localhost:8080/jblubble-sample/persons) which is handled by a Spring MVC controller — `PersonController` and uses JPA. There you can see how a BLOB is referenced by key. A JPA `AttributeConverter` was used to convert `BlobKey`.


text:
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32

#ifndef __NEWAUDIOENGINE_TEST_H_
#define __NEWAUDIOENGINE_TEST_H_

#include "cocos2d.h"
#include "../BaseTest.h"

#include "audio/include/AudioEngine.h"

DEFINE_TEST_SUITE(AudioEngineTests);

class AudioEngineTestDemo : public TestCase
{
public:
    virtual std::string title() const override;
    virtual void onExit() override;

};

class AudioControlTest : public AudioEngineTestDemo
{
public:
    CREATE_FUNC(AudioControlTest);

    virtual ~AudioControlTest();

    virtual bool init() override;

    virtual void update(float dt) override;

    virtual std::string title() const override;

private:
    int _audioID;
    bool _loopEnabled;
    float _volume;
    float _duration;
    float _timeRatio;

    void* _playItem;
    void* _timeSlider;
    bool _updateTimeSlider;
};

class PlaySimultaneouslyTest : public AudioEngineTestDemo
{
public:
    CREATE_FUNC(PlaySimultaneouslyTest);

    virtual ~PlaySimultaneouslyTest();

    virtual bool init() override;

    virtual std::string title() const override;
private:
    static const int TEST_COUNT = 10;
    std::string _files[TEST_COUNT];

    void* _playItem;
    int _playingcount;
};

class AudioProfileTest : public AudioEngineTestDemo
{
public:
    CREATE_FUNC(AudioProfileTest);

    virtual ~AudioProfileTest();

    virtual bool init() override;

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

    virtual void update(float dt) override;

private:
    static const int FILE_COUNT = 2;
    std::string _files[FILE_COUNT];
    cocos2d::experimental::AudioProfile _audioProfile;

    int _audioCount;
    cocos2d::Label* _showLabel;
    float _time;
    float _minDelay;
    void* _timeSlider;
};

class InvalidAudioFileTest : public AudioEngineTestDemo
{
public:
    CREATE_FUNC(InvalidAudioFileTest);

    virtual ~InvalidAudioFileTest();

    virtual bool init() override;

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

private:

};

class LargeAudioFileTest : public AudioEngineTestDemo
{
public:
    CREATE_FUNC(LargeAudioFileTest);

    virtual ~LargeAudioFileTest();

    virtual bool init() override;

    virtual std::string title() const override;

private:

};

class AudioLoadTest : public AudioEngineTestDemo
{
public:
    CREATE_FUNC(AudioLoadTest);

    virtual bool init() override;

    virtual std::string title() const override;
};

class AudioIssue11143Test : public AudioEngineTestDemo
{
public:
    CREATE_FUNC(AudioIssue11143Test);

    virtual bool init() override;

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

#endif /* defined(__NEWAUDIOENGINE_TEST_H_) */
#endif