text:
package eu.bcvsolutions.idm.core.api.config.domain;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto;
import eu.bcvsolutions.idm.core.api.service.Configurable;
import eu.bcvsolutions.idm.core.api.service.ConfigurationService;

/**
 * Configuration for roles.
 *
 * @author Radek Tomiška
 *
 */
public interface RoleConfiguration extends Configurable {

	/**
	 * Default user role - permissions configured for the default role are automatically assigned to every logged identity.
	 * Business roles are NOT evaluated
	 */
	String PROPERTY_DEFAULT_ROLE = ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.role.default";
	String DEFAULT_DEFAULT_ROLE = "userRole";

	/**
	 * Admin role - e.g. used as fallback, when no approver in wf is defined.
	 */
	String PROPERTY_ADMIN_ROLE = ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.role.admin";
	String DEFAULT_ADMIN_ROLE = "superAdminRole";
	String PROPERTY_APPROVE_ROLE_CHANGE_ROLE =  ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.wf.approval.role-change.role";

	/**
	 * Helpdesk role.
	 *
	 * @since 10.5.0
	 */
	String PROPERTY_HELPDESK_ROLE = ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.role.helpdesk";
	String DEFAULT_HELPDESK_ROLE = "helpdeskRole";

	/**
	 * User manager role.
	 *
	 * @since 10.5.0
	 */
	String PROPERTY_USER_MANAGER_ROLE = ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.role.userManager";
	String DEFAULT_USER_MANAGER_ROLE = "userManagerRole";

	/**
	 * Role manager role.
	 *
	 * @since 10.5.0
	 */
	String PROPERTY_ROLE_MANAGER_ROLE = ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.role.roleManager";
	String DEFAULT_ROLE_MANAGER_ROLE = "roleManagerRole";

	/**
	 * Delegation role.
	 *
	 * @since 10.6.0
	 */
	String PROPERTY_DELEGATION_ROLE = ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.role.delegation";
	String DEFAULT_DELEGATION_ROLE = "delegationRole";

	/**
	 * If is true, then role-request description will be show on the detail.
	 *
	 * Description will hidden if this property will be false and role request
	 * doesn't contains any value in description (can be filled during the approval
	 * process)
	 *
	 * Default is true.
	 *
	 */
	String PROPERTY_SHOW_ROLE_REQUEST_DESCRIPTION =  ConfigurationService.IDM_PUBLIC_PROPERTY_PREFIX + "app.show.roleRequest.description";

	/**
	 * Show role environment in application for roles (table, role detail, niceLabel, info components, role select, bulk actions).
	 */
	String PROPERTY_SHOW_ENVIRONMENT = ConfigurationService.IDM_PUBLIC_PROPERTY_PREFIX + "app.show.environment";
	boolean DEFAULT_SHOW_ENVIRONMENT = true;

	/**
	 * Show role baseCode in frontend application for roles (table, role detail, niceLabel, info components, role select).
	 *
	 * @since 10.4.1
	 */
	String PROPERTY_SHOW_BASE_CODE =  ConfigurationService.IDM_PUBLIC_PROPERTY_PREFIX + "app.show.role.baseCode";
	boolean DEFAULT_SHOW_BASE_CODE = true;

	/**
	 * Separator for the suffix with environment used in role code.
	 * Look out: when separator is changed, then all roles should be updated (manually from ui, by scripted LRT or by change script).
	 */
	String PROPERTY_CODE_ENVIRONMENT_SEPARATOR = ConfigurationService.IDM_PRIVATE_PROPERTY_PREFIX + "core.role.codeEnvironmentSeperator";
	String DEFAULT_CODE_ENVIRONMENT_SEPARATOR = "|";

	@Override
	default String getConfigurableType() {
		return "role";
	}

	@Override
	default boolean isDisableable() {
		return false;
	}

	@Override
	default public boolean isSecured() {
		return true;
	}

	@Override
	default List<String> getPropertyNames() {
		List<String> properties = new ArrayList<>(); // we are not using superclass properties - enable and order does not make a sense here
		properties.add(getPropertyName(PROPERTY_DEFAULT_ROLE));
		properties.add(getPropertyName(PROPERTY_ADMIN_ROLE));
		properties.add(getPropertyName(PROPERTY_HELPDESK_ROLE));
		properties.add(getPropertyName(PROPERTY_USER_MANAGER_ROLE));
		properties.add(getPropertyName(PROPERTY_ROLE_MANAGER_ROLE));
		properties.add(getPropertyName(PROPERTY_APPROVE_ROLE_CHANGE_ROLE));
		properties.add(getPropertyName(PROPERTY_SHOW_ROLE_REQUEST_DESCRIPTION));
		properties.add(getPropertyName(PROPERTY_SHOW_ENVIRONMENT));
		properties.add(getPropertyName(PROPERTY_SHOW_BASE_CODE));
		properties.add(getPropertyName(PROPERTY_CODE_ENVIRONMENT_SEPARATOR));
		return properties;
	}

	/**
	 * Default role code from configuration.
	 *
	 * @return full role code
	 * @since 10.5.0
	 */
	String getDefaultRoleCode();

	/**
	 * Returns default role identifier
	 *
	 * @return
	 */
	UUID getDefaultRoleId();

	/**
	 * Returns default role
	 *
	 * @return
	 */
	IdmRoleDto getDefaultRole();

	/**
	 * Default role code from configuration.
	 *
	 * @return full role code
	 * @since 10.5.0
	 */
	String getAdminRoleCode();

	/**
	 * Returns admin role identifier
	 *
	 * @return
	 */
	UUID getAdminRoleId();

	/**
	 * Returns admin role
	 *
	 * @return
	 */
	IdmRoleDto getAdminRole();

	/**
	 * Helpdesk role code from configuration.
	 *
	 * @return full role code
	 * @since 10.5.0
	 */
	String getHelpdeskRoleCode();

	/**
	 * Returns helpdesk role
	 *
	 * @return
	 * @since 10.5.0
	 */
	IdmRoleDto getHelpdeskRole();

	/**
	 * User manager role code from configuration.
	 *
	 * @return full role code
	 * @since 10.5.0
	 */
	String getUserManagerRoleCode();

	/**
	 * Returns user manager role
	 *
	 * @return
	 * @since 10.5.0
	 */
	IdmRoleDto getUserManagerRole();

	/**
	 * Role manager role code from configuration.
	 *
	 * @return full role code
	 * @since 10.5.0
	 */
	String getRoleManagerRoleCode();

	/**
	 * Returns role manager role
	 *
	 * @return
	 * @since 10.5.0
	 */
	IdmRoleDto getRoleManagerRole();

	/**
	 * Delegation role code from configuration.
	 *
	 * @return full role code
	 * @since 10.6.0
	 */
	String getDelegationRoleCode();

	/**
	 * Returns delegation role
	 *
	 * @return
	 * @since 10.6.0
	 */
	IdmRoleDto getDelegationRole();

	/**
	 * Return role for approve change of role
	 * If is not defined, then admin role will be used.
	 *
	 * @return
	 */
	IdmRoleDto getRoleForApproveChangeOfRole();

	/**
	 * Separator for the suffix with environment used in role code.
	 *
	 * @return
	 */
	String getCodeEnvironmentSeperator();

	/**
	 * Show role environment in application for roles (table, role detail, niceLabel, info components, role select, bulk actions).
	 *
	 * @return true - environment is shown
	 */
	boolean isShowEnvironment();
}


text:
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Le bon coin',
    version:'0.1',
    prepareImgLinks:function (callback) {
        var res = [];
        hoverZoom.urlReplace(res,
            'img[src*="thumbs"], span.thumbs',
            'thumbs',
            'images'
        );
        callback($(res));
    }
});

redpajama_set_name: RedPajamaGithub


text:
window.__karma__.loaded = function() {

// For attaching the global window objects
if (typeof require !== "undefined")
require(["readium_cfi_js/cfi_API"], function () {
    window.__karma__.start();
});
else window.__karma__.start();

};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.a86c6f7964</groupId>
        <artifactId>ruist-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>ruist-example</artifactId>

    <dependencies>
        <!-- ruist -->
        <dependency>
            <groupId>com.a86c6f7964</groupId>
            <artifactId>ruist-jetty</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.a86c6f7964</groupId>
            <artifactId>ruist-jersey</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.a86c6f7964</groupId>
            <artifactId>ruist-varexport</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.a86c6f7964</groupId>
            <artifactId>ruist-status</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <!-- guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>17.0</version>
        </dependency>

        <!-- guice -->
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>4.0-beta4</version>
        </dependency>

        <!-- logging -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
        </dependency>

    </dependencies>

</project>


text:
package com.project.openface.gate.sockapi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.project.simpleserver.sockapi.SimpleHandler;
import com.project.simpleserver.utils.net.DefaultDecoder;
import com.project.simpleserver.utils.net.DefaultEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

public class GateServer {
	private static Logger logger = LoggerFactory.getLogger(GateServer.class);

	EventLoopGroup bossGroup = new NioEventLoopGroup();
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	ServerBootstrap bootstrap = new ServerBootstrap();

	public void start() {
		try {
			bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline p = ch.pipeline();

							// 记录底层日志,使用netty提供的功能
							p.addLast("logging", new LoggingHandler());

							// 提供编码器/解码器
							p.addLast("encoder", new DefaultEncoder());
							p.addLast("decoder", new DefaultDecoder());

							// 提供特殊消息处理器:心跳
							p.addLast("idleStateHandler", new IdleStateHandler(120, 120, 120));

							// 提供消息处理器,可为消息处理器提供线程池
							EventExecutorGroup executor = new DefaultEventExecutorGroup(20);
							p.addLast(executor, new SimpleHandler());
						}
					}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

			// 绑定地址
			ChannelFuture channelFuture = bootstrap.bind(8987);

			channelFuture.sync();
		} catch (InterruptedException e) {
			this.stop();
		}
	}

	public void stop() {
		//
	}
}


text:
package io.relayr.android;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import dagger.ObjectGraph;

@RunWith(RobolectricTestRunner.class)
public class TestEnvironment {

    protected CountDownLatch lock;

    @Before
    public void init() {
        lock = new CountDownLatch(1);
        MockitoAnnotations.initMocks(this);
    }

    public void inject() {
        ObjectGraph.create(new TestModule(Robolectric.application.getApplicationContext())).inject(this);
    }

    public void initSdk() {
        initSdk(true);
    }

    public void initSdk(boolean mock) {
        new io.relayr.android.RelayrSdk.Builder(Robolectric.application).inMockMode(mock).build();
    }

    public void await() {
        await(200);
    }

    public void await(int milliseconds) {
        try {
            lock.await(milliseconds, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void countDown() {
        lock.countDown();
    }
}


text:
require 'wsdl/info'
require 'xsd/namedelements'

module WSDL
module XMLSchema

class ComplexContent < Info
  attr_accessor :restriction
  attr_accessor :extension
  attr_accessor :mixed

  def initialize
    super
    @restriction = nil
    @extension = nil
    @mixed = false
  end

  def targetnamespace
    parent.targetnamespace
  end

  def elementformdefault
    parent.elementformdefault
  end

  def content
    @extension || @restriction
  end

  def base
    content ? content.base : nil
  end

  def have_any?
    content ? content.have_any? : nil
  end

  def choice?
    content ? content.choice? : nil
  end

  def elements
    content ? content.elements : XSD::NamedElements::Empty
  end

  def attributes
    content ? content.attributes : XSD::NamedElements::Empty
  end

  def nested_elements
    # restrict and extension does not have particle.
    content ? content.nested_elements : XSD::NamedElements::Empty
  end

  def check_type
    if content
      content.check_type
    else
      raise ArgumentError.new("incomplete complexContent")
    end
  end

  def parse_element(element)
    case element
    when RestrictionName
      raise ArgumentError.new("incomplete complexContent") if content
      @restriction = ComplexRestriction.new
    when ExtensionName
      raise ArgumentError.new("incomplete complexContent") if content
      @extension = ComplexExtension.new
    end
  end

  def parse_attr(attr, value)
    case attr
    when MixedAttrName
      @mixed = to_boolean(value)
    else
      nil
    end
  end
end

end
end


text:
<?php

namespace Google\Service\Document;

class GoogleCloudDocumentaiV1beta2DocumentPageTokenDetectedBreak extends \Google\Model
{
  /**
   * @var string
   */
  public $type;

  /**
   * @param string
   */
  public function setType($type)
  {
    $this->type = $type;
  }
  /**
   * @return string
   */
  public function getType()
  {
    return $this->type;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDocumentaiV1beta2DocumentPageTokenDetectedBreak::class, 'Google_Service_Document_GoogleCloudDocumentaiV1beta2DocumentPageTokenDetectedBreak');


text:
void TEST_RM_0(const string &tableName)
{
    // Functions Tested
    // 1. Get Attributes
    cout << "****In Test Case 0****" << endl;

    // GetAttributes
    vector<Attribute> attrs;
    RC rc = rm->getAttributes(tableName, attrs);
    assert(rc == success);

    for(unsigned i = 0; i < attrs.size(); i++)
    {
        cout << "Attribute Name: " << attrs[i].name << endl;
        cout << "Attribute Type: " << (AttrType)attrs[i].type << endl;
        cout << "Attribute Length: " << attrs[i].length << endl << endl;
    }
    cout<<"** Test Case 0 passed"<<endl;
    return;
}

int main()
{
    cout << endl << "Test Get Attributes .." << endl;

    // Get Attributes
    TEST_RM_0("tbl_employee");

    return 0;
}


text:
package com.fishercoder;

import com.fishercoder.solutions._325;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class _325Test {
    private static _325.Solution1 solution1;
    private static int[] nums;

    @BeforeClass
    public static void setup() {
        solution1 = new _325.Solution1();
    }

    @Test
    public void test1() {
        nums = new int[]{-2, -1, 2, 1};
        assertEquals(2, solution1.maxSubArrayLen(nums, 1));
    }

    @Test
    public void test2() {
        nums = new int[]{1, -1, 5, -2, 3};
        assertEquals(4, solution1.maxSubArrayLen(nums, 3));
    }
}


text:
package org.elasticsearch.xpack.security.authz.accesscontrol;

import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.Version;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;
import org.elasticsearch.xpack.core.security.authz.accesscontrol.IndicesAccessControl;
import org.elasticsearch.xpack.core.security.authz.permission.FieldPermissions;
import org.elasticsearch.xpack.core.security.authz.permission.FieldPermissionsCache;
import org.elasticsearch.xpack.core.security.authz.permission.FieldPermissionsDefinition;
import org.elasticsearch.xpack.core.security.authz.permission.IndicesPermission;
import org.elasticsearch.xpack.core.security.authz.permission.Role;
import org.elasticsearch.xpack.core.security.authz.privilege.IndexPrivilege;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

public class IndicesPermissionTests extends ESTestCase {

    public void testAuthorize() {
        IndexMetaData.Builder imbBuilder = IndexMetaData.builder("_index")
                .settings(Settings.builder()
                                .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                                .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
                                .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                )
                .putAlias(AliasMetaData.builder("_alias"));
        MetaData md = MetaData.builder().put(imbBuilder).build();
        FieldPermissionsCache fieldPermissionsCache = new FieldPermissionsCache(Settings.EMPTY);

        // basics:
        Set<BytesReference> query = Collections.singleton(new BytesArray("{}"));
        String[] fields = new String[]{"_field"};
        Role role = Role.builder("_role")
                .add(new FieldPermissions(fieldPermissionDef(fields, null)), query, IndexPrivilege.ALL, "_index").build();
        IndicesAccessControl permissions = role.authorize(SearchAction.NAME, Sets.newHashSet("_index"), md, fieldPermissionsCache);
        assertThat(permissions.getIndexPermissions("_index"), notNullValue());
        assertTrue(permissions.getIndexPermissions("_index").getFieldPermissions().grantsAccessTo("_field"));
        assertTrue(permissions.getIndexPermissions("_index").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_index").getQueries().size(), equalTo(1));
        assertThat(permissions.getIndexPermissions("_index").getQueries(), equalTo(query));

        // no document level security:
        role = Role.builder("_role")
                .add(new FieldPermissions(fieldPermissionDef(fields, null)), null, IndexPrivilege.ALL, "_index").build();
        permissions = role.authorize(SearchAction.NAME, Sets.newHashSet("_index"), md, fieldPermissionsCache);
        assertThat(permissions.getIndexPermissions("_index"), notNullValue());
        assertTrue(permissions.getIndexPermissions("_index").getFieldPermissions().grantsAccessTo("_field"));
        assertTrue(permissions.getIndexPermissions("_index").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_index").getQueries(), nullValue());

        // no field level security:
        role = Role.builder("_role").add(new FieldPermissions(), query, IndexPrivilege.ALL, "_index").build();
        permissions = role.authorize(SearchAction.NAME, Sets.newHashSet("_index"), md, fieldPermissionsCache);
        assertThat(permissions.getIndexPermissions("_index"), notNullValue());
        assertFalse(permissions.getIndexPermissions("_index").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_index").getQueries().size(), equalTo(1));
        assertThat(permissions.getIndexPermissions("_index").getQueries(), equalTo(query));

        // index group associated with an alias:
        role = Role.builder("_role")
                .add(new FieldPermissions(fieldPermissionDef(fields, null)), query, IndexPrivilege.ALL, "_alias")
                .build();
        permissions = role.authorize(SearchAction.NAME, Sets.newHashSet("_alias"), md, fieldPermissionsCache);
        assertThat(permissions.getIndexPermissions("_index"), notNullValue());
        assertTrue(permissions.getIndexPermissions("_index").getFieldPermissions().grantsAccessTo("_field"));
        assertTrue(permissions.getIndexPermissions("_index").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_index").getQueries().size(), equalTo(1));
        assertThat(permissions.getIndexPermissions("_index").getQueries(), equalTo(query));

        assertThat(permissions.getIndexPermissions("_alias"), notNullValue());
        assertTrue(permissions.getIndexPermissions("_alias").getFieldPermissions().grantsAccessTo("_field"));
        assertTrue(permissions.getIndexPermissions("_alias").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_alias").getQueries().size(), equalTo(1));
        assertThat(permissions.getIndexPermissions("_alias").getQueries(), equalTo(query));

        // match all fields
        String[] allFields = randomFrom(new String[]{"*"}, new String[]{"foo", "*"},
        new String[]{randomAlphaOfLengthBetween(1, 10), "*"});
        role = Role.builder("_role")
                .add(new FieldPermissions(fieldPermissionDef(allFields, null)), query, IndexPrivilege.ALL, "_alias").build();
        permissions = role.authorize(SearchAction.NAME, Sets.newHashSet("_alias"), md, fieldPermissionsCache);
        assertThat(permissions.getIndexPermissions("_index"), notNullValue());
        assertFalse(permissions.getIndexPermissions("_index").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_index").getQueries().size(), equalTo(1));
        assertThat(permissions.getIndexPermissions("_index").getQueries(), equalTo(query));

        assertThat(permissions.getIndexPermissions("_alias"), notNullValue());
        assertFalse(permissions.getIndexPermissions("_alias").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_alias").getQueries().size(), equalTo(1));
        assertThat(permissions.getIndexPermissions("_alias").getQueries(), equalTo(query));

        IndexMetaData.Builder imbBuilder1 = IndexMetaData.builder("_index_1")
                .settings(Settings.builder()
                        .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                        .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
                        .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                )
                .putAlias(AliasMetaData.builder("_alias"));
        md = MetaData.builder(md).put(imbBuilder1).build();

        // match all fields with more than one permission
        Set<BytesReference> fooQuery = Collections.singleton(new BytesArray("{foo}"));
        allFields = randomFrom(new String[]{"*"}, new String[]{"foo", "*"},
                new String[]{randomAlphaOfLengthBetween(1, 10), "*"});
        role = Role.builder("_role")
                .add(new FieldPermissions(fieldPermissionDef(allFields, null)), fooQuery, IndexPrivilege.ALL, "_alias")
                .add(new FieldPermissions(fieldPermissionDef(allFields, null)), query, IndexPrivilege.ALL, "_alias").build();
        permissions = role.authorize(SearchAction.NAME, Sets.newHashSet("_alias"), md, fieldPermissionsCache);
        Set<BytesReference> bothQueries = Sets.union(fooQuery, query);
        assertThat(permissions.getIndexPermissions("_index"), notNullValue());
        assertFalse(permissions.getIndexPermissions("_index").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_index").getQueries().size(), equalTo(2));
        assertThat(permissions.getIndexPermissions("_index").getQueries(), equalTo(bothQueries));

        assertThat(permissions.getIndexPermissions("_index_1"), notNullValue());
        assertFalse(permissions.getIndexPermissions("_index_1").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_index_1").getQueries().size(), equalTo(2));
        assertThat(permissions.getIndexPermissions("_index_1").getQueries(), equalTo(bothQueries));

        assertThat(permissions.getIndexPermissions("_alias"), notNullValue());
        assertFalse(permissions.getIndexPermissions("_alias").getFieldPermissions().hasFieldLevelSecurity());
        assertThat(permissions.getIndexPermissions("_alias").getQueries().size(), equalTo(2));
        assertThat(permissions.getIndexPermissions("_alias").getQueries(), equalTo(bothQueries));

    }

    public void testAuthorizeMultipleGroupsMixedDls() {
        IndexMetaData.Builder imbBuilder = IndexMetaData.builder("_index")
                .settings(Settings.builder()
                        .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                        .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
                        .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                )
                .putAlias(AliasMetaData.builder("_alias"));
        MetaData md = MetaData.builder().put(imbBuilder).build();
        FieldPermissionsCache fieldPermissionsCache = new FieldPermissionsCache(Settings.EMPTY);

        Set<BytesReference> query = Collections.singleton(new BytesArray("{}"));
        String[] fields = new String[]{"_field"};
        Role role = Role.builder("_role")
                .add(new FieldPermissions(fieldPermissionDef(fields, null)), query, IndexPrivilege.ALL, "_index")
                .add(new FieldPermissions(fieldPermissionDef(null, null)), null, IndexPrivilege.ALL, "*")
                .build();
        IndicesAccessControl permissions = role.authorize(SearchAction.NAME, Sets.newHashSet("_index"), md, fieldPermissionsCache);
        assertThat(permissions.getIndexPermissions("_index"), notNullValue());
        assertTrue(permissions.getIndexPermissions("_index").getFieldPermissions().grantsAccessTo("_field"));
        assertFalse(permissions.getIndexPermissions("_index").getFieldPermissions().hasFieldLevelSecurity());
        // null implies that there is no DLS. Currently a index permissions only has queries defined
        // on it and not a true document level permission object like fields
        assertNull(permissions.getIndexPermissions("_index").getQueries());
    }

    public void testIndicesPrivilegesStreaming() throws IOException {
        BytesStreamOutput out = new BytesStreamOutput();
        String[] allowed = new String[]{randomAlphaOfLength(5) + "*", randomAlphaOfLength(5) + "*", randomAlphaOfLength(5) + "*"};
        String[] denied = new String[]{allowed[0] + randomAlphaOfLength(5), allowed[1] + randomAlphaOfLength(5),
                allowed[2] + randomAlphaOfLength(5)};
        RoleDescriptor.IndicesPrivileges.Builder indicesPrivileges = RoleDescriptor.IndicesPrivileges.builder();
        indicesPrivileges.grantedFields(allowed);
        indicesPrivileges.deniedFields(denied);
        indicesPrivileges.query("{match_all:{}}");
        indicesPrivileges.indices(randomAlphaOfLength(5), randomAlphaOfLength(5), randomAlphaOfLength(5));
        indicesPrivileges.privileges("all", "read", "priv");
        indicesPrivileges.build().writeTo(out);
        out.close();
        StreamInput in = out.bytes().streamInput();
        RoleDescriptor.IndicesPrivileges readIndicesPrivileges = RoleDescriptor.IndicesPrivileges.createFrom(in);
        assertEquals(readIndicesPrivileges, indicesPrivileges.build());

        out = new BytesStreamOutput();
        out.setVersion(Version.V_6_0_0);
        indicesPrivileges = RoleDescriptor.IndicesPrivileges.builder();
        indicesPrivileges.grantedFields(allowed);
        indicesPrivileges.deniedFields(denied);
        indicesPrivileges.query("{match_all:{}}");
        indicesPrivileges.indices(readIndicesPrivileges.getIndices());
        indicesPrivileges.privileges("all", "read", "priv");
        indicesPrivileges.build().writeTo(out);
        out.close();
        in = out.bytes().streamInput();
        in.setVersion(Version.V_6_0_0);
        RoleDescriptor.IndicesPrivileges readIndicesPrivileges2 = RoleDescriptor.IndicesPrivileges.createFrom(in);
        assertEquals(readIndicesPrivileges, readIndicesPrivileges2);
    }

    // tests that field permissions are merged correctly when we authorize with several groups and don't crash when an index has no group
    public void testCorePermissionAuthorize() {
        final Settings indexSettings = Settings.builder().put("index.version.created", Version.CURRENT).build();
        final MetaData metaData = new MetaData.Builder()
                .put(new IndexMetaData.Builder("a1").settings(indexSettings).numberOfShards(1).numberOfReplicas(0).build(), true)
                .put(new IndexMetaData.Builder("a2").settings(indexSettings).numberOfShards(1).numberOfReplicas(0).build(), true)
                .build();

        FieldPermissionsCache fieldPermissionsCache = new FieldPermissionsCache(Settings.EMPTY);
        IndicesPermission.Group group1 = new IndicesPermission.Group(IndexPrivilege.ALL, new FieldPermissions(), null, "a1");
        IndicesPermission.Group group2 = new IndicesPermission.Group(IndexPrivilege.ALL,
                new FieldPermissions(fieldPermissionDef(null, new String[]{"denied_field"})), null, "a1");
        IndicesPermission core = new IndicesPermission(group1, group2);
        Map<String, IndicesAccessControl.IndexAccessControl> authzMap =
                core.authorize(SearchAction.NAME, Sets.newHashSet("a1", "ba"), metaData, fieldPermissionsCache);
        assertTrue(authzMap.get("a1").getFieldPermissions().grantsAccessTo("denied_field"));
        assertTrue(authzMap.get("a1").getFieldPermissions().grantsAccessTo(randomAlphaOfLength(5)));
        // did not define anything for ba so we allow all
        assertFalse(authzMap.get("ba").getFieldPermissions().hasFieldLevelSecurity());

        assertTrue(core.check(SearchAction.NAME));
        assertFalse(core.check("unknown"));

        // test with two indices
        group1 = new IndicesPermission.Group(IndexPrivilege.ALL, new FieldPermissions(), null, "a1");
        group2 = new IndicesPermission.Group(IndexPrivilege.ALL,
                new FieldPermissions(fieldPermissionDef(null, new String[]{"denied_field"})), null, "a1");
        IndicesPermission.Group group3 = new IndicesPermission.Group(IndexPrivilege.ALL,
                new FieldPermissions(fieldPermissionDef(new String[]{"*_field"}, new String[]{"denied_field"})), null, "a2");
        IndicesPermission.Group group4 = new IndicesPermission.Group(IndexPrivilege.ALL,
                new FieldPermissions(fieldPermissionDef(new String[]{"*_field2"}, new String[]{"denied_field2"})), null, "a2");
        core = new IndicesPermission(group1, group2, group3, group4);
        authzMap = core.authorize(SearchAction.NAME, Sets.newHashSet("a1", "a2"), metaData, fieldPermissionsCache);
        assertFalse(authzMap.get("a1").getFieldPermissions().hasFieldLevelSecurity());
        assertFalse(authzMap.get("a2").getFieldPermissions().grantsAccessTo("denied_field2"));
        assertFalse(authzMap.get("a2").getFieldPermissions().grantsAccessTo("denied_field"));
        assertTrue(authzMap.get("a2").getFieldPermissions().grantsAccessTo(randomAlphaOfLength(5) + "_field"));
        assertTrue(authzMap.get("a2").getFieldPermissions().grantsAccessTo(randomAlphaOfLength(5) + "_field2"));
        assertTrue(authzMap.get("a2").getFieldPermissions().hasFieldLevelSecurity());

        assertTrue(core.check(SearchAction.NAME));
        assertFalse(core.check("unknown"));
    }

    public void testErrorMessageIfIndexPatternIsTooComplex() {
        List<String> indices = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            String prefix = randomAlphaOfLengthBetween(4, 12);
            String suffixBegin = randomAlphaOfLengthBetween(12, 36);
            indices.add("*" + prefix + "*" + suffixBegin + "*");
        }
        final ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class,
                () -> new IndicesPermission.Group(IndexPrivilege.ALL, new FieldPermissions(), null, indices.toArray(Strings.EMPTY_ARRAY)));
        assertThat(e.getMessage(), containsString(indices.get(0)));
        assertThat(e.getMessage(), containsString("too complex to evaluate"));
    }

    private static FieldPermissionsDefinition fieldPermissionDef(String[] granted, String[] denied) {
        return new FieldPermissionsDefinition(granted, denied);
    }
}


text:
import LogServerCollection from './models/LogServerCollection';
import LogCategoryList from './controller/LogCategoryList';
import LogView from './controller/LogView';

// Skeleton with header (navigation) and footer (pagination)
const logview = new LogView();
// Get type of log to display from volt view (data-log HTML attribute)
const type = $('#logapplication').data('log');
// Query (HTTP or stream) server list
const servers = new LogServerCollection({
    logType: type
});
// Render tabs with server logs (one tab per server)
const menu = new LogCategoryList({
    collection: servers,
    logview: logview,
    logType: type // 'errors', 'accesses' or 'global'
});

// Place log application to volt template
$('#logapplication')
    .append(menu.$el)
    .append(logview.$el);

if (type != 'global') {
    // Global error log does not require server list
    servers.fetch();
}
else {
    // Update of server list triggers render() which does not
    // occur for global error log
    menu.render();
}


text:
#include "tensorflow/core/kernels/data/experimental/list_dataset_op.h"

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/data/split_utils.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/util/batch_util.h"

namespace tensorflow {
namespace data {

// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following op.

/* static */ constexpr const char* const ListDatasetOp::kDatasetType;
/* static */ constexpr const char* const ListDatasetOp::kTensors;
/* static */ constexpr const char* const ListDatasetOp::kTinputTypes;
/* static */ constexpr const char* const ListDatasetOp::kOutputTypes;
/* static */ constexpr const char* const ListDatasetOp::kOutputShapes;

class ListDatasetOp::Dataset : public DatasetBase {
 public:
  Dataset(OpKernelContext* ctx, std::vector<Tensor> tensors,
          const DataTypeVector& input_types, const DataTypeVector& output_types,
          const std::vector<PartialTensorShape>& output_shapes,
          int num_components)
      : DatasetBase(DatasetContext(ctx)),
        tensors_(std::move(tensors)),
        num_elements_(tensors_.size() / num_components),
        num_components_(num_components),
        input_types_(input_types),
        output_types_(output_types),
        output_shapes_(output_shapes) {}

  std::unique_ptr<IteratorBase> MakeIteratorInternal(
      const string& prefix) const override {
    return std::make_unique<Iterator>(Iterator::Params{
        this, name_utils::IteratorPrefix(kDatasetType, prefix)});
  }

  Status MakeSplitProviders(std::vector<std::unique_ptr<SplitProvider>>*
                                split_providers) const override {
    split_providers->push_back(
        std::make_unique<IndexSplitProvider>(num_elements_));
    return OkStatus();
  }

  const DataTypeVector& output_dtypes() const override { return output_types_; }

  const std::vector<PartialTensorShape>& output_shapes() const override {
    return output_shapes_;
  }

  string DebugString() const override {
    return name_utils::DatasetDebugString(kDatasetType);
  }

  int64_t CardinalityInternal() const override { return num_elements_; }

  int64_t CardinalityInternal(CardinalityOptions options) const override {
    return num_elements_;
  }

  Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
    return OkStatus();
  }

  Status CheckExternalState() const override { return OkStatus(); }

  Status Get(OpKernelContext* ctx, int64 index,
             std::vector<Tensor>* out_tensors) const override {
    TF_RETURN_IF_ERROR(CheckRandomAccessCompatible(index));
    out_tensors->clear();
    out_tensors->reserve(num_components_);
    for (int i = 0; i < num_components_; ++i) {
      out_tensors->push_back(tensors_[i + num_components_ * index]);
    }
    return OkStatus();
  }

 protected:
  Status AsGraphDefInternal(SerializationContext* ctx,
                            DatasetGraphDefBuilder* b,
                            Node** output) const override {
    std::vector<Node*> tensors;
    tensors.reserve(tensors_.size());
    for (const Tensor& t : tensors_) {
      Node* node;
      if (!ctx->is_graph_rewrite()) {
        TF_RETURN_IF_ERROR(b->AddDatasetOrTensor(ctx, t, &node));
      } else {
        TF_RETURN_IF_ERROR(b->AddPlaceholder(t, &node));
        DCHECK_NE(ctx->input_list(), nullptr);
        ctx->input_list()->emplace_back(node->name(), t);
      }
      tensors.emplace_back(node);
    }
    AttrValue input_types;
    b->BuildAttrValue(input_types_, &input_types);
    TF_RETURN_IF_ERROR(b->AddDataset(this, {}, {{0, tensors}},
                                     {{kTinputTypes, input_types}}, output));
    return OkStatus();
  }

 private:
  class Iterator : public DatasetIterator<Dataset> {
   public:
    explicit Iterator(const Params& params)
        : DatasetIterator<Dataset>(params) {}

    bool SymbolicCheckpointCompatible() const override { return true; }

    Status Initialize(IteratorContext* ctx) override {
      if (ctx->split_providers().empty()) {
        split_provider_ =
            std::make_shared<IndexSplitProvider>(dataset()->num_elements_);
      } else {
        TF_ASSIGN_OR_RETURN(split_provider_,
                            GetSingleSplitProvider(ctx, dataset()));
      }
      return OkStatus();
    }

    Status GetNextInternal(IteratorContext* ctx,
                           std::vector<Tensor>* out_tensors,
                           bool* end_of_sequence) override {
      Tensor split;
      TF_RETURN_IF_ERROR(split_provider_->GetNext(&split, end_of_sequence));
      if (*end_of_sequence) {
        return OkStatus();
      }
      int64_t index = split.scalar<int64_t>()();
      out_tensors->reserve(dataset()->num_components_);
      for (size_t i = 0; i < dataset()->num_components_; ++i) {
        out_tensors->push_back(
            dataset()->tensors_[i + dataset()->num_components_ * index]);
      }
      *end_of_sequence = false;
      return OkStatus();
    }

   protected:
    std::shared_ptr<model::Node> CreateNode(
        IteratorContext* ctx, model::Node::Args args) const override {
      return model::MakeSourceNode(std::move(args));
    }

    Status SaveInternal(SerializationContext* ctx,
                        IteratorStateWriter* writer) override {
      return split_provider_->Save(
          [this](const std::string& key) { return full_name(key); }, writer);
    }

    Status RestoreInternal(IteratorContext* ctx,
                           IteratorStateReader* reader) override {
      return split_provider_->Restore(
          [this](const std::string& key) { return full_name(key); }, reader);
    }

   private:
    std::shared_ptr<SplitProvider> split_provider_;
  };

  const std::vector<Tensor> tensors_;
  int64 num_elements_;
  size_t num_components_;
  DataTypeVector input_types_;
  DataTypeVector output_types_;
  std::vector<PartialTensorShape> output_shapes_;
};

ListDatasetOp::ListDatasetOp(OpKernelConstruction* ctx) : DatasetOpKernel(ctx) {
  OP_REQUIRES_OK(ctx, ctx->GetAttr(kTinputTypes, &input_types_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr(kOutputTypes, &output_types_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr(kOutputShapes, &output_shapes_));
}

void ListDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase** output) {
  OpInputList inputs;
  OP_REQUIRES_OK(ctx, ctx->input_list(kTensors, &inputs));
  std::vector<Tensor> tensors(inputs.begin(), inputs.end());
  *output = new Dataset(ctx, std::move(tensors), input_types_, output_types_,
                        output_shapes_, output_shapes_.size());
  OP_REQUIRES_OK(ctx,
                 VerifyTypesMatch((*output)->output_dtypes(), output_types_));
  OP_REQUIRES_OK(
      ctx, VerifyShapesCompatible((*output)->output_shapes(), output_shapes_));
}

namespace {

REGISTER_KERNEL_BUILDER(Name("ListDataset").Device(DEVICE_CPU), ListDatasetOp);
}  // namespace
}  // namespace data
}  // namespace tensorflow


text:
from __future__ import unicode_literals

import ckeditor.fields
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('Lookup', '0003_auto_20191223_1604'),
    ]

    operations = [
        migrations.AlterField(
            model_name='people',
            name='relationshiptootherpeople',
            field=ckeditor.fields.RichTextField(blank=True, db_column='relationshiptootherpeople', null=True, verbose_name='relationship to other people'),
        ),
    ]


text:
<?xml version="1.0"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">

<Configure id="Server" class="org.eclipse.jetty.server.Server">
  <!-- Minimal jetty.xml to run on a specific port, locked to localhost -->
  <Call name="addConnector">
    <Arg>
      <New id="httpConnector" class="org.eclipse.jetty.server.ServerConnector">
        <Arg name="server"><Ref refid="Server" /></Arg>
        <Arg name="factories">
          <Array type="org.eclipse.jetty.server.ConnectionFactory">
            <Item>
              <New class="org.eclipse.jetty.server.HttpConnectionFactory"/>
            </Item>
          </Array>
        </Arg>
        <Set name="port">1077</Set>
      </New>
    </Arg>
  </Call>
</Configure>


text:
from conans import python_requires
import os

common = python_requires('llvm-common/0.0.0@orbitdeps/stable')

class LLVMScalarOpts(common.LLVMModulePackage):
    version = common.LLVMModulePackage.version
    name = 'llvm_scalar_opts'
    llvm_component = 'llvm'
    llvm_module = 'ScalarOpts'
    llvm_requires = ['llvm_headers', 'llvm_analysis', 'llvm_core', 'llvm_instcombine', 'llvm_support', 'llvm_transform_utils']


text:
package com.bgfurfeature.hdfs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
/**
 *
 * 客户端去操作hdfs时,是有一个用户身份的
 * 默认情况下,hdfs客户端api会从jvm中获取一个参数来作为自己的用户身份:-DHADOOP_USER_NAME=hadoop
 *
 * 也可以在构造客户端fs对象时,通过参数传递进去
 * @author
 *
 */
public class HdfsClientDemo {
	FileSystem fs = null;
	Configuration conf = null;
	@Before
	public void init() throws Exception{

		conf = new Configuration();
		conf.set("fs.defaultFS", "hdfs://master:9000");

		//拿到一个文件系统操作的客户端实例对象
		/*fs = FileSystem.get(conf);*/
		//可以直接传入 uri和用户身份
		fs = FileSystem.get(new URI("hdfs://master:9000"),conf,"hadoop"); //最后一个参数为用户名
	}

	@Test
	public void testDownLoadFileToLocal() throws IllegalArgumentException, IOException{

		//先获取一个文件的输入流----针对hdfs上的
		FSDataInputStream in = fs.open(new Path("/jdk-7u65-linux-i586.tar.gz"));

		//再构造一个文件的输出流----针对本地的
		FileOutputStream out = new FileOutputStream(new File("c:/jdk.tar.gz"));

		//再将输入流中数据传输到输出流
		IOUtils.copyBytes(in, out, 4096);

	}

	@Test
	public void testUploadByStream() throws Exception{

		//hdfs文件的输出流
		FSDataOutputStream fsout = fs.create(new Path("/aaa.txt"));

		//本地文件的输入流
		FileInputStream fsin = new FileInputStream("c:/111.txt");

		IOUtils.copyBytes(fsin, fsout,4096);

	}

	/**
	 * hdfs支持随机定位进行文件读取,而且可以方便地读取指定长度
	 * 用于上层分布式运算框架并发处理数据
	 * @throws IllegalArgumentException
	 * @throws IOException
	 */
	@Test
	public void testRandomAccess() throws IllegalArgumentException, IOException {

		FSDataInputStream in = fs.open(new Path("/iloveyou.txt"));//先获取一个文件的输入流----针对hdfs上的
		in.seek(22);	//可以将流的起始偏移量进行自定义
		FileOutputStream out = new FileOutputStream(new File("c:/iloveyou.line.2.txt"));//再构造一个文件的输出流----针对本地的
		IOUtils.copyBytes(in,out,19L,true);	//apache的工具类, 3.缓冲大小,4.是否关闭流

	}

	/**
	 * 读取指定的block
	 * @throws IOException
	 * @throws IllegalArgumentException
	 */
	@Test
	public void testCat() throws IllegalArgumentException, IOException {

		FSDataInputStream in = fs.open(new Path("/weblog/input/access.log.10"));
		//拿到文件信息
		FileStatus[] listStatus = fs.listStatus(new Path("/weblog/input/access.log.10"));
		//获取这个文件的所有block的信息
		BlockLocation[] fileBlockLocations = fs.getFileBlockLocations(listStatus[0], 0L, listStatus[0].getLen());

		//第一个block的长度
		long length = fileBlockLocations[0].getLength();
		//第一个block的起始偏移量
		long offset = fileBlockLocations[0].getOffset();

		System.out.println(length);
		System.out.println(offset);

		//获取第一个block写入输出流
//		IOUtils.copyBytes(in, System.out, (int)length);
		byte[] b = new byte[4096];

		FileOutputStream os = new FileOutputStream(new File("d:/block0"));
		while(in.read(offset, b, 0, 4096)!=-1){
			os.write(b);
			offset += 4096;
			if(offset>length) return;
		};

		os.flush();
		os.close();
		in.close();

	}

	@Test
	public void testUpload() throws Exception {

		Thread.sleep(2000);
		fs.copyFromLocalFile(new Path("G:/access.log"), new Path("/access.log.copy"));
		fs.close();
	}

	@Test
	public void testDownload() throws Exception {

		// IOUtils.copyBytes(); IOUtil类实现数据传输的封装
		fs.copyToLocalFile(new Path("/access.log.copy"), new Path("d:/"));
		fs.close();
	}

	@Test
	public void testConf(){
		Iterator<Entry<String, String>> iterator = conf.iterator();
		while (iterator.hasNext()) {
			Entry<String, String> entry = iterator.next();
			System.out.println(entry.getValue() + "--" + entry.getValue());//conf加载的内容
		}
	}

	/**
	 * 创建目录
	 */
	@Test
	public void makdirTest() throws Exception {
		boolean mkdirs = fs.mkdirs(new Path("/aaa/bbb"));
		System.out.println(mkdirs);
	}

	/**
	 * 删除
	 */
	@Test
	public void deleteTest() throws Exception{
		boolean delete = fs.delete(new Path("/aaa"), true);//true, 递归删除
		System.out.println(delete);
	}

	@Test
	public void listTest() throws Exception{

		FileStatus[] listStatus = fs.listStatus(new Path("/"));
		for (FileStatus fileStatus : listStatus) {
			System.err.println(fileStatus.getPath() +" ================= " + fileStatus.toString());
		}
		//会递归找到所有的文件
		RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
		while(listFiles.hasNext()){
			LocatedFileStatus next = listFiles.next();
			String name = next.getPath().getName();
			Path path = next.getPath();
			System.out.println(name + "---" + path.toString());
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS", "hdfs://master:9000");
		//拿到一个文件系统操作的客户端实例对象
		FileSystem fs = FileSystem.get(conf);

		fs.copyFromLocalFile(new Path("G:/access.log"), new Path("/access.log.copy"));
		fs.close();
	}

}


text:
package com.vlkan.hrrs.replayer.jtl;

import com.vlkan.hrrs.replayer.cli.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

import static com.google.common.base.Preconditions.checkNotNull;

public class JtlFilePrinter implements JtlPrinter {

    private static final Logger LOGGER = LoggerFactory.getLogger(JtlFilePrinter.class);

    private final PrintStream printStream;

    public JtlFilePrinter(Config config) throws FileNotFoundException {
        checkNotNull(config, "config");
        FileOutputStream outputStream = new FileOutputStream(config.getJtlOutputFile());
        this.printStream = new PrintStream(outputStream);
        printStream.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        printStream.println("<testResults version=\"1.2\">");
        LOGGER.debug("instantiated (file={})", config.getJtlOutputFile());
    }

    @Override
    public void print(long timestampMillis, String label, int statusCode, long latency, String threadName) {
        String entry = String.format(
                "<httpSample t=\"%d\" lt=\"%d\" ts=\"%d\" s=\"%s\" rc=\"%d\" lb=\"%s\" tn=\"%s\"/>",
                latency,
                latency,
                timestampMillis,
                (statusCode & 200) == 200,
                statusCode,
                label,
                threadName);
        synchronized (this) {
            printStream.println(entry);
        }
    }

    @Override
    public synchronized void close() {
        LOGGER.debug("closing");
        printStream.println("</testResults>");
        printStream.close();
    }

}


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'test_helper'))
class NewRelic::Agent::Instrumentation::ControllerInstrumentationTest < Test::Unit::TestCase
  require 'new_relic/agent/instrumentation/controller_instrumentation'
  class TestObject
    include NewRelic::Agent::Instrumentation::ControllerInstrumentation
  end

  def setup
    @object = TestObject.new
  end

  def test_detect_upstream_wait_basic
    start_time = Time.now
    # should return the start time above by default
    @object.expects(:newrelic_request_headers).returns({:request => 'headers'}).twice
    NewRelic::Agent::Instrumentation::QueueTime.expects(:parse_frontend_timestamp) \
      .with({:request => 'headers'}, start_time).returns(start_time)
    assert_equal(start_time, @object.send(:_detect_upstream_wait, start_time))
  end

  def test_detect_upstream_wait_with_upstream
    start_time = Time.now
    runs_at = start_time + 1
    @object = TestObject.new
    @object.expects(:newrelic_request_headers).returns(true).twice
    NewRelic::Agent::Instrumentation::QueueTime.expects(:parse_frontend_timestamp) \
      .with(true, runs_at).returns(start_time)
    assert_equal(start_time, @object.send(:_detect_upstream_wait, runs_at))
  end

  def test_detect_upstream_wait_swallows_errors
    start_time = Time.now
    # should return the start time above when an error is raised
    @object.expects(:newrelic_request_headers).returns({:request => 'headers'}).twice
    NewRelic::Agent::Instrumentation::QueueTime.expects(:parse_frontend_timestamp) \
      .with({:request => 'headers'}, start_time).raises("an error")
    assert_equal(start_time, @object.send(:_detect_upstream_wait, start_time))
  end

  def test_transaction_name_calls_newrelic_metric_path
    @object.stubs(:newrelic_metric_path).returns('some/wacky/path')
    assert_equal('Controller/some/wacky/path', @object.send(:transaction_name))
  end

  def test_transaction_name_applies_category_and_path
    assert_equal('Controller/metric/path',
                 @object.send(:transaction_name,
                              :category => :controller,
                              :path => 'metric/path'))
    assert_equal('OtherTransaction/Background/metric/path',
                 @object.send(:transaction_name,
                              :category => :task, :path => 'metric/path'))
    assert_equal('Controller/Rack/metric/path',
                 @object.send(:transaction_name,
                              :category => :rack, :path => 'metric/path'))
    assert_equal('Controller/metric/path',
                 @object.send(:transaction_name,
                              :category => :uri, :path => 'metric/path'))
    assert_equal('Controller/Sinatra/metric/path',
                 @object.send(:transaction_name,
                              :category => :sinatra,
                              :path => 'metric/path'))
    assert_equal('Blarg/metric/path',
                 @object.send(:transaction_name,
                              :category => 'Blarg', :path => 'metric/path'))

  end

  def test_transaction_name_uses_class_name_if_path_not_specified
    assert_equal('Controller/NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject',
                 @object.send(:transaction_name, :category => :controller))
  end

  def test_transaction_name_applies_action_name_if_specified_and_not_path
    assert_equal('Controller/NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject/action',
                 @object.send(:transaction_name, :category => :controller,
                              :name => 'action'))
  end

  def test_transaction_name_applies_name_rules
    rule = NewRelic::Agent::RulesEngine::Rule.new('match_expression' => '[0-9]+',
                                                  'replacement'      => '*',
                                                  'replace_all'      => true)
    NewRelic::Agent.instance.transaction_rules << rule
    assert_equal('foo/*/bar/*',
                 @object.send(:transaction_name, :category => 'foo',
                              :path => '1/bar/22'))
  ensure
    NewRelic::Agent.instance.instance_variable_set(:@transaction_rules,
                                              NewRelic::Agent::RulesEngine.new)
  end

  def test_path_class_and_action
    result = @object.send(:path_class_and_action, {})
    assert_equal("NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject", result)
  end

  def test_path_class_and_action_with_name
    result = @object.send(:path_class_and_action, :name => "test")
    assert_equal("NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject/test", result)
  end

  def test_path_class_and_action_with_overridden_class_name
    result = @object.send(:path_class_and_action, :name => "perform", :class_name => 'Resque')
    assert_equal("Resque/perform", result)
  end
end


text:
class AccountTracker::InvoiceViewModel < BaseJump::ViewModel::Base
  def page_header
    "New Invoice <small>#{owning_entity_display}</small>".html_safe
  end

  def form_fields
    groups = []

    groups << build_fields("Invoice overview", :invoice_line_items)
    groups << build_fields("Payment information", :payment_information)

    groups
  end

  def create_form_actions(form)
    actions = [submit_form_button(form)]
    actions << continue_action(data_context.line_items.first.billable_item) if data_context.line_items.size == 1

    actions
  end
  def continue_action(billable)
    link_to "Continue without payment", polymorphic_path(billable, ignore_payment: true), class: "btn btn-link"
  end

  def owning_entity_options(field_name, nested_under)
    { label: "Invoice for", readonly: true, input_html: { value: owning_entity_display } }
  end

  def owning_entity_display
    return owning_entity.name if owning_entity.respond_to?(:name)
    return owning_entity.format if owning_entity.respond_to?(:format)
  end

end


text:
import {SuiteModuleBuilder} from 'ember-runtime/tests/suites/suite';
import {get} from 'ember-metal/property_get';
import {set} from 'ember-metal/property_set';

var suite = SuiteModuleBuilder.create();

suite.module('firstObject');

suite.test('returns first item in enumerable', function() {
  var obj = this.newObject();
  equal(get(obj, 'firstObject'), this.toArray(obj)[0]);
});

suite.test('returns undefined if enumerable is empty', function() {
  var obj = this.newObject([]);
  equal(get(obj, 'firstObject'), undefined);
});

suite.test('can not be set', function() {
  var obj = this.newObject([]);

  equal(get(obj, 'firstObject'), this.toArray(obj)[0]);

  throws(function() {
    set(obj, 'firstObject', 'foo!');
  }, /Cannot set read-only property "firstObject" on object/);
});

export default suite;


text:
require "truefactor/version"
require 'active_support'
require 'active_record'
require 'action_controller'
require "truefactor/model"
require "truefactor/controller"
require "truefactor/helper"

require 'securerandom'
require 'uri'
require 'openssl'

module Truefactor
  class << self
    attr_accessor :configuration
  end

  def self.configure
    self.configuration ||= Configuration.new
    yield(configuration)
  end

  def self._model_
    self.configuration.model_class.constantize
  end

  class Configuration
    attr_accessor :web_origin, :desktop_origin, :tfid_type, :origin_name, :origin, :icon, :model_class

    def initialize
      @web_origin     = 'https://truefactor.io'
      @desktop_origin = 'truefactor://'
      @tfid_type      = :email
      @origin_name    = 'Truefactorized app'
    end
  end
end

ActiveSupport.on_load(:active_record) do
  include Truefactor::Model
end

ActiveSupport.on_load(:action_controller) do
  include Truefactor::Controller
end

ActiveSupport.on_load(:action_view) do
  include Truefactor::Helper
end


text:
/**
 * @note 多线程多lua虚拟机情况下,应该在每个线程单独对虚拟机执行lua_binding_mgr::me()->proc(L);以防止多线程冲突
 */

#ifndef SCRIPT_LUA_LUABINDINGMGR
#define SCRIPT_LUA_LUABINDINGMGR

#pragma once

#include <assert.h>
#include <stdint.h>
#include <cstddef>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <string>

#include <config/compiler_features.h>
#include <design_pattern/singleton.h>
#include <std/explicit_declare.h>

#include <lock/lock_holder.h>
#include <lock/spin_rw_lock.h>

#include "lua_binding_utils.h"

namespace script {
    namespace lua {

        class lua_engine;

        class lua_binding_class_mgr_base {
        protected:
            lua_binding_class_mgr_base();

        public:
            virtual ~lua_binding_class_mgr_base() = 0;

            virtual int proc(lua_State *L) = 0;

            virtual void add_lua_state(lua_State *L) = 0;

            virtual void remove_lua_state(lua_State *L) = 0;
        };

        template <typename TC>
        class lua_binding_class_mgr_inst : public lua_binding_class_mgr_base,
                                           public util::design_pattern::singleton<lua_binding_class_mgr_inst<TC> > {
        public:
            virtual int proc(lua_State *L) UTIL_CONFIG_OVERRIDE {
                if (NULL == L) {
                    ::util::lock::write_lock_holder< ::util::lock::spin_rw_lock> wlh(cache_lock_);
                    cache_maps_.clear();
                    return 0;
                }

                ::util::lock::read_lock_holder< ::util::lock::spin_rw_lock> rlh(cache_lock_);
                intptr_t index = reinterpret_cast<intptr_t>(L);
                auto iter = cache_maps_.find(index);
                if (cache_maps_.end() == iter) {
                    return -1;
                }

                iter->second.clear();
                return 0;
            }

            bool add_ref(lua_State *L, const std::shared_ptr<TC> &ptr) {
                if (NULL == L) {
                    return false;
                }

                ::util::lock::read_lock_holder< ::util::lock::spin_rw_lock> rlh(cache_lock_);

                intptr_t index = reinterpret_cast<intptr_t>(L);
                auto iter = cache_maps_.find(index);
                if (cache_maps_.end() == iter) {
                    return false;
                }

                iter->second.push_back(ptr);
                return true;
            }

            virtual void add_lua_state(lua_State *L) UTIL_CONFIG_OVERRIDE {
                ::util::lock::write_lock_holder< ::util::lock::spin_rw_lock> wlh(cache_lock_);

                intptr_t index = reinterpret_cast<intptr_t>(L);
                cache_maps_[index];
            }

            virtual void remove_lua_state(lua_State *L) UTIL_CONFIG_OVERRIDE {
                ::util::lock::write_lock_holder< ::util::lock::spin_rw_lock> wlh(cache_lock_);

                intptr_t index = reinterpret_cast<intptr_t>(L);
                cache_maps_.erase(index);
            }

        private:
            std::map<intptr_t, std::list<std::shared_ptr<TC> > > cache_maps_;
            ::util::lock::spin_rw_lock cache_lock_;
        };

        class lua_binding_mgr : public util::design_pattern::singleton<lua_binding_mgr> {
        public:
            typedef std::function<void(lua_State *)> func_type;

        protected:
            lua_binding_mgr();
            ~lua_binding_mgr();

        public:
            int add_lua_engine(lua_engine *engine);
            int remove_lua_engine(lua_engine *engine);

            /**
             * 自动更新/清理入口
             * @param 指定要清理的lua虚拟机,不指定为清理全部
             */
            int proc(lua_engine *engine = NULL);

            void add_bind(func_type fn);

        public:
            template <typename TC>
            bool add_ref(lua_State *L, const std::shared_ptr<TC> &ptr) {
                return lua_binding_class_mgr_inst<TC>::me()->add_ref(L, ptr);
            }

        private:
            std::list<func_type> auto_bind_list_;
            std::list<lua_binding_class_mgr_base *> lua_states_;
            friend class lua_binding_class_mgr_base;
        };

        class lua_binding_wrapper {
        public:
            lua_binding_wrapper(lua_binding_mgr::func_type);
            ~lua_binding_wrapper();
        };
    }  // namespace lua
}  // namespace script

#define LUA_BIND_VAR_NAME(name) script_lua_LuaBindMgr_Var_##name
#define LUA_BIND_FN_NAME(name) script_lua_LuaBindMgr_Fn_##name

#define LUA_BIND_OBJECT(name, L)                                                             \
    static void LUA_BIND_FN_NAME(name)(lua_State *);                                         \
    static script::lua::lua_binding_wrapper LUA_BIND_VAR_NAME(name)(LUA_BIND_FN_NAME(name)); \
    void LUA_BIND_FN_NAME(name)(EXPLICIT_UNUSED_ATTR lua_State * L)

#endif


text:
import argparse
import logging
import os
import re
import shlex
import sys
import xml.dom.minidom

from pylib import cmd_helper
from pylib import constants

_FINDBUGS_HOME = os.path.join(constants.DIR_SOURCE_ROOT, 'third_party',
                              'findbugs')
_FINDBUGS_JAR = os.path.join(_FINDBUGS_HOME, 'lib', 'findbugs.jar')
_FINDBUGS_MAX_HEAP = 768
_FINDBUGS_PLUGIN_PATH = os.path.join(
    constants.DIR_SOURCE_ROOT, 'tools', 'android', 'findbugs_plugin', 'lib',
    'chromiumPlugin.jar')

def _ParseXmlResults(results_doc):
  warnings = set()
  for en in (n for n in results_doc.documentElement.childNodes
             if n.nodeType == xml.dom.Node.ELEMENT_NODE):
    if en.tagName == 'BugInstance':
      warnings.add(_ParseBugInstance(en))
  return warnings

def _GetMessage(node):
  for c in (n for n in node.childNodes
            if n.nodeType == xml.dom.Node.ELEMENT_NODE):
    if c.tagName == 'Message':
      if (len(c.childNodes) == 1
          and c.childNodes[0].nodeType == xml.dom.Node.TEXT_NODE):
        return c.childNodes[0].data
  return None

def _ParseBugInstance(node):
  bug = FindBugsWarning(node.getAttribute('type'))
  msg_parts = []
  for c in (n for n in node.childNodes
            if n.nodeType == xml.dom.Node.ELEMENT_NODE):
    if c.tagName == 'Class':
      msg_parts.append(_GetMessage(c))
    elif c.tagName == 'Method':
      msg_parts.append(_GetMessage(c))
    elif c.tagName == 'Field':
      msg_parts.append(_GetMessage(c))
    elif c.tagName == 'SourceLine':
      bug.file_name = c.getAttribute('sourcefile')
      if c.hasAttribute('start'):
        bug.start_line = int(c.getAttribute('start'))
      if c.hasAttribute('end'):
        bug.end_line = int(c.getAttribute('end'))
      msg_parts.append(_GetMessage(c))
    elif (c.tagName == 'ShortMessage' and len(c.childNodes) == 1
          and c.childNodes[0].nodeType == xml.dom.Node.TEXT_NODE):
      msg_parts.append(c.childNodes[0].data)
  bug.message = tuple(m for m in msg_parts if m)
  return bug

class FindBugsWarning(object):

  def __init__(self, bug_type='', end_line=0, file_name='', message=None,
               start_line=0):
    self.bug_type = bug_type
    self.end_line = end_line
    self.file_name = file_name
    if message is None:
      self.message = tuple()
    else:
      self.message = message
    self.start_line = start_line

  def __cmp__(self, other):
    return (cmp(self.file_name, other.file_name)
            or cmp(self.start_line, other.start_line)
            or cmp(self.end_line, other.end_line)
            or cmp(self.bug_type, other.bug_type)
            or cmp(self.message, other.message))

  def __eq__(self, other):
    return self.__dict__ == other.__dict__

  def __hash__(self):
    return hash((self.bug_type, self.end_line, self.file_name, self.message,
                 self.start_line))

  def __ne__(self, other):
    return not self == other

  def __str__(self):
    return '%s: %s' % (self.bug_type, '\n  '.join(self.message))

def Run(exclude, classes_to_analyze, auxiliary_classes, output_file,
        findbug_args, jars):
  """Run FindBugs.

  Args:
    exclude: the exclude xml file, refer to FindBugs's -exclude command option.
    classes_to_analyze: the list of classes need to analyze, refer to FindBug's
                        -onlyAnalyze command line option.
    auxiliary_classes: the classes help to analyze, refer to FindBug's
                       -auxclasspath command line option.
    output_file: An optional path to dump XML results to.
    findbug_args: A list of addtional command line options to pass to Findbugs.
  """
  # TODO(jbudorick): Get this from the build system.
  system_classes = [
    os.path.join(constants.ANDROID_SDK_ROOT, 'platforms',
                 'android-%s' % constants.ANDROID_SDK_VERSION, 'android.jar')
  ]
  system_classes.extend(os.path.abspath(classes)
                        for classes in auxiliary_classes or [])

  cmd = ['java',
         '-classpath', '%s:' % _FINDBUGS_JAR,
         '-Xmx%dm' % _FINDBUGS_MAX_HEAP,
         '-Dfindbugs.home="%s"' % _FINDBUGS_HOME,
         '-jar', _FINDBUGS_JAR,
         '-textui', '-sortByClass',
         '-pluginList', _FINDBUGS_PLUGIN_PATH, '-xml:withMessages']
  if system_classes:
    cmd.extend(['-auxclasspath', ':'.join(system_classes)])
  if classes_to_analyze:
    cmd.extend(['-onlyAnalyze', classes_to_analyze])
  if exclude:
    cmd.extend(['-exclude', os.path.abspath(exclude)])
  if output_file:
    cmd.extend(['-output', output_file])
  if findbug_args:
    cmd.extend(findbug_args)
  cmd.extend(os.path.abspath(j) for j in jars or [])

  if output_file:
    cmd_helper.RunCmd(cmd)
    results_doc = xml.dom.minidom.parse(output_file)
  else:
    raw_out = cmd_helper.GetCmdOutput(cmd)
    results_doc = xml.dom.minidom.parseString(raw_out)

  current_warnings_set = _ParseXmlResults(results_doc)

  return (' '.join(cmd), current_warnings_set)


text:
int bitonic_2(
		char *verilog_filename,
		char *c_filename,
		unsigned inputs,
		unsigned period,
		unsigned type,
		char *e,
		unsigned e_sz);


text:
/* eslint-disable prefer-template */
import { API_PATH } from './application_constants';

const ApiUrls = {
    'accounts': API_PATH + 'accounts/',
    'accounts_detail': API_PATH + 'accounts/%(accountId)s/',
    'assets_for_account': API_PATH + 'accounts/%(accountId)s/assets/',
    'assets': API_PATH + 'assets/',
    'assets_detail': API_PATH + 'assets/%(assetId)s/',
    'assets_transfer': API_PATH + 'assets/%(assetId)s/%(cid)s/transfer/',
    'assets_escrow': API_PATH + 'assets/%(assetId)s/%(cid)s/escrow/',
    'assets_escrow_fulfill': API_PATH + 'assets/%(assetId)s/%(cid)s/escrow/fulfill/'
};

export default ApiUrls;


text:
package com.aspose.pdf.examples.AsposePdfExamples.Tables;

import com.aspose.pdf.Document;
import com.aspose.pdf.Row;
import com.aspose.pdf.TableAbsorber;
import com.aspose.pdf.TextFragment;

public class ManipulateTablesInExistingPDF {

	/*
	 * Update contents in particular table cell
	 */
	public static void main(String[] args) {
		// load existing PDF file
		Document pdfDocument = new Document("table.pdf");
		// Create TableAbsorber object to find tables
		TableAbsorber absorber = new TableAbsorber();
		// Visit first page with absorber
		absorber.visit(pdfDocument.getPages().get_Item(1));
		// Get access to first table on page, their first cell and text
		// fragments in it
		TextFragment fragment = absorber.getTableList().get_Item(0).getRowList().get_Item(0).getCellList().get_Item(0).getTextFragments().get_Item(1);
		// Change text of the first text fragment in the cell
		fragment.setText("Hello World !");
		// save updated document
		pdfDocument.save("Table_Manipulated.pdf");
	}
}


text:
package org.springframework.orm.ojb;

import java.util.Collection;
import java.util.Iterator;

import org.apache.ojb.broker.query.Query;

import org.springframework.dao.DataAccessException;

/**
 * Interface that specifies a basic set of OJB PersistenceBroker operations.
 * Implemented by PersistenceBrokerTemplate. Not often used, but a useful
 * option to enhance testability, as it can easily be mocked or stubbed.
 *
 *
Provides PersistenceBrokerTemplate's data access methods that mirror
 * various PersistenceBroker methods. See the PersistenceBroker javadocs
 * for details on those methods.
 *
 * @author Juergen Hoeller
 * @since 02.07.2004
 * @see PersistenceBrokerTemplate
 * @see org.apache.ojb.broker.PersistenceBroker
 */
public interface PersistenceBrokerOperations {

	/**
	 * Execute the action specified by the given action object within a
	 * PersistenceBroker. Application exceptions thrown by the action object
	 * get propagated to the caller (can only be unchecked). OJB exceptions
	 * are transformed into appropriate DAO ones. Allows for returning a
	 * result object, i.e. a domain object or a collection of domain objects.
	 *
Note: Callback code is not supposed to handle transactions itself!
	 * Use an appropriate transaction manager like PersistenceBrokerTransactionManager.
	 * @param action action object that specifies the OJB action
	 * @return a result object returned by the action, or null
	 * @throws org.springframework.dao.DataAccessException in case of OJB errors
	 * @see PersistenceBrokerTransactionManager
	 * @see org.springframework.dao
	 * @see org.springframework.transaction
	 */
	Object execute(PersistenceBrokerCallback action) throws DataAccessException;

	/**
	 * Execute the specified action assuming that the result object is a
	 * Collection. This is a convenience method for executing OJB queries
	 * within an action.
	 * @param action action object that specifies the OJB action
	 * @return a result object returned by the action, or null
	 * @throws org.springframework.dao.DataAccessException in case of OJB errors
	 */
	Collection executeFind(PersistenceBrokerCallback action) throws DataAccessException;

	//-------------------------------------------------------------------------
	// Convenience methods for load, find, save, delete
	//-------------------------------------------------------------------------

	Object getObjectByQuery(Query query) throws DataAccessException;

	Collection getCollectionByQuery(Query query) throws DataAccessException;

	Iterator getIteratorByQuery(final Query query) throws DataAccessException;

	Iterator getReportQueryIteratorByQuery(Query query);

	int getCount(Query query) throws DataAccessException;

	void removeFromCache(Object entityOrId) throws DataAccessException;

	void clearCache() throws DataAccessException;

	void store(Object entity) throws DataAccessException;

	void delete(Object entity) throws DataAccessException;

	void deleteByQuery(Query query) throws DataAccessException;

}


text:
#pragma once

// Set to true if "--no-slow" is passed to the test.
extern bool g_noSlowTests;


text:
{% extends 'base.html' %}
{% load staticfiles %}
{% load blog %}

{% block title %}
{% endblock %}

{% block css %}
{% endblock %}

{% block page-header %}

博客列表

    {% render_notice_links %}
{% endblock %}

{% block page-body %}

            {% render_month_links %}
            {% render_category_links %}
            {% render_assess_links %}
            {% render_friendly_links %}

        {% include 'blog/post_list.html' with object_list=object_list %}

{% endblock %}

{% block js %}
{% endblock %}


text:
package views.tradingpremises

import forms.EmptyForm
import generators.tradingpremises.TradingPremisesGenerator
import models.status.NotCompleted
import models.tradingpremises.{Address, TradingPremises, YourTradingPremises}
import org.scalatest.MustMatchers
import play.api.i18n.Messages
import play.twirl.api.HtmlFormat
import utils.AmlsViewSpec
import views.Fixture
import views.html.tradingpremises.your_trading_premises

class your_trading_premisesSpec extends AmlsViewSpec with MustMatchers with TradingPremisesGenerator {

  trait ViewFixture extends Fixture {
    lazy val your_trading_premises = app.injector.instanceOf[your_trading_premises]
    implicit val requestWithToken = addTokenForView()
  }

  val tpAddress = Address("CPLT 1", "SecondLine", Some("ThirdLine"), Some("FourthLine"), "AQ11QA")

  val completeTp = TradingPremises(yourTradingPremises = Some(YourTradingPremises("Complete TP 1", tpAddress)))
  val completeTp2 = TradingPremises(yourTradingPremises = Some(YourTradingPremises("Complete TP 2", tpAddress.copy(addressLine1 = "CPLT 2"))))
  val incompleteTp1 = TradingPremises(yourTradingPremises = Some(YourTradingPremises("inComplete TP 1", tpAddress.copy(addressLine1 = "INCPLT 1"))))
  val incompleteTp2 = TradingPremises(yourTradingPremises = Some(YourTradingPremises("inComplete TP 2", tpAddress.copy(addressLine1 = "INCPLT 2"))))

  val completeTpSeq = Seq((completeTp,0),(completeTp2,1))
  val incompleteTpSeq = Seq((incompleteTp1,2),(incompleteTp2,3))

  "Your trading premises View" must {
    "have correct title, headings displayed, no complete/incomplete headers displayed" in new ViewFixture {

      def view = your_trading_premises(EmptyForm, false, NotCompleted, Seq.empty[(TradingPremises, Int)], Seq.empty[(TradingPremises, Int)])

      doc.title must be(Messages("tradingpremises.yourpremises.title") +
        " - " + Messages("tradingpremises.subheading") +
        " - " + Messages("title.amls") +
        " - " + Messages("title.gov"))
      heading.html must be(Messages("tradingpremises.yourpremises.title"))
      subHeading.html must include(Messages("tradingpremises.subheading"))

      doc.getElementsByAttributeValue("id", "addTradingPremises") must not be empty

      html must not include Messages("tradingpremises.yourpremises.incomplete")
      html must not include Messages("tradingpremises.yourpremises.complete")

      html must include(Messages("tradingpremises.yourpremises.line_1"))
      html must include(Messages("tradingpremises.yourpremises.line_2"))
      html must include(Messages("tradingpremises.yourpremises.line_3"))
    }

    "have list with Incomplete and Complete headers displayed when there are both types of lists" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, completeTpSeq, incompleteTpSeq)

      html must include(Messages("tradingpremises.yourpremises.incomplete"))
      html must include(Messages("tradingpremises.yourpremises.complete"))
    }

    "have list with Incomplete header displayed when there are only incomplete TP's" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, Seq.empty[(TradingPremises, Int)], incompleteTpSeq)

      html must include(Messages("tradingpremises.yourpremises.incomplete"))
      html must not include Messages("tradingpremises.yourpremises.complete")
    }

    "have list without Complete/Incomplete headers displayed when there are only complete TP's" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, completeTpSeq, Seq.empty[(TradingPremises, Int)])

      html must not include Messages("tradingpremises.yourpremises.incomplete")
      html must not include Messages("tradingpremises.yourpremises.complete")
    }

    "have an add a trading premises link with the correct text and going to the what you need page" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, completeTpSeq, incompleteTpSeq)

      doc.getElementById("addTradingPremises").text must be(Messages("tradingpremises.summary.addanother"))
      doc.getElementById("addTradingPremises").attr("href") must be(controllers.tradingpremises.routes.TradingPremisesAddController.get(true).url)
    }

    "have an incomplete/complete sections with addresses displayed and edit/remove links" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, completeTpSeq, incompleteTpSeq)

      doc.getElementById("complete-header").text must include(Messages("tradingpremises.yourpremises.complete"))

      doc.getElementById("detail-edit-0").attr("href") must be(controllers.tradingpremises.routes.DetailedAnswersController.get(1).url)
      doc.getElementById("detail-remove-0").attr("href") must be(controllers.tradingpremises.routes.RemoveTradingPremisesController.get(1).url)

      doc.getElementById("detail-edit-1").attr("href") must be(controllers.tradingpremises.routes.DetailedAnswersController.get(2).url)
      doc.getElementById("detail-remove-1").attr("href") must be(controllers.tradingpremises.routes.RemoveTradingPremisesController.get(2).url)

      doc.getElementById("incomplete-header").text must include(Messages("tradingpremises.yourpremises.incomplete"))

      doc.getElementById("incomplete-detail-2").text must include("INCPLT 1")
      doc.getElementById("detail-edit-2").attr("href") must be(controllers.tradingpremises.routes.YourTradingPremisesController.getIndividual(3, true).url)
      doc.getElementById("detail-remove-2").attr("href") must be(controllers.tradingpremises.routes.RemoveTradingPremisesController.get(3).url)

      doc.getElementById("incomplete-detail-3").text must include("INCPLT 2")
      doc.getElementById("detail-edit-3").attr("href") must be(controllers.tradingpremises.routes.YourTradingPremisesController.getIndividual(4, true).url)
      doc.getElementById("detail-remove-3").attr("href") must be(controllers.tradingpremises.routes.RemoveTradingPremisesController.get(4).url)

    }

    "show the correct continuation button when there are both types of lists" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, completeTpSeq, incompleteTpSeq)
      html must include(Messages("button.returntoapplicationprogress"))
    }

    "show the correct continuation button when there are only incomplete tps" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, Seq.empty[(TradingPremises, Int)], incompleteTpSeq)
      html must include(Messages("button.returntoapplicationprogress"))
    }

    "show the correct continuation button when there are only complete TP's" in new ViewFixture {
      def  view = your_trading_premises(EmptyForm, false, NotCompleted, completeTpSeq, Seq.empty[(TradingPremises, Int)])
      html must include(Messages("button.checkyouranswers.acceptandcomplete"))
    }

    "show the correct continuation button when there are no TPs" in new ViewFixture {
      def view = your_trading_premises(EmptyForm, false, NotCompleted, Seq.empty[(TradingPremises, Int)], Seq.empty[(TradingPremises, Int)])
      html must include (Messages("button.returntoapplicationprogress"))
    }
  }
}


text:
```eval_rst
..  _semantic_role_labeling:
```

# Semantic Role labeling Tutorial #

Semantic role labeling (SRL) is a form of shallow semantic parsing whose goal is to discover the predicate-argument structure of each predicate in a given input sentence. SRL is useful as an intermediate step in a wide range of natural language processing tasks, such as information extraction. automatic document categorization and question answering.  An instance is as following [1]:

 [ A0 He ] [ AM-MOD would ][ AM-NEG n't ] [ V accept] [ A1 anything of value ] from [A2 those he was writing about ].

- V: verb
- A0: acceptor
- A1: thing accepted
- A2: accepted-from
- A3: Attribute
- AM-MOD: modal
- AM-NEG: negation

Given the verb "accept", the chunks in sentence would play certain semantic roles. Here, the label scheme is from Penn Proposition Bank.

To this date, most of the successful SRL systems are built on top of some form of parsing results where pre-defined feature templates over the syntactic structure are used. This tutorial will present an end-to-end system using deep bidirectional long short-term memory (DB-LSTM)[2] for solving the SRL task, which largely outperforms the previous state-of-the-art systems. The system regards SRL task as the sequence labelling problem.

## Data Description
The relevant paper[2] takes the data set in CoNLL-2005&2012 Shared Task for training and testing. Accordingto data license,  the demo adopts the test data set of CoNLL-2005, which can be reached on website.

To download and process the original data, user just need to execute the following command:

```bash
cd data
./get_data.sh
```
Several new files appear in the `data `directory as follows.
```bash
conll05st-release:the test data set of CoNll-2005 shared task
test.wsj.words:the Wall Street Journal data sentences
test.wsj.props:  the propositional arguments
feature: the extracted features from data set
```

## Training
### DB-LSTM
Please refer to the Sentiment Analysis demo to learn more about the long short-term memory unit.

Unlike Bidirectional-LSTM that used in Sentiment Analysis demo,  the DB-LSTM adopts another way to stack LSTM layer. First a standard LSTM processes the sequence in forward direction. The input and output of this LSTM layer are taken by the next LSTM layer as input, processed in reversed direction. These two standard LSTM layers compose a pair of LSTM. Then we stack LSTM layers pair after pair to obtain the deep LSTM model.

The following figure shows a temporal expanded 2-layer DB-LSTM network.

![pic](./src/network_arch.png)

### Features
Two input features play an essential role in this pipeline: predicate (pred) and argument (argu). Two other features: predicate context (ctx-p) and region mark (mr) are also adopted. Because a single predicate word can not exactly describe the predicate information, especially when the same words appear more than one times in a sentence. With the predicate context, the ambiguity can be largely eliminated. Similarly, we use region mark mr = 1 to denote the argument position if it locates in the predicate context region, or mr = 0 if does not. These four simple features are all we need for our SRL system. Features of one sample with context size set to 1 is showed as following[2]:

![pic](./src/feature.jpg)

In this sample, the coresponding labelled sentence is:

[ A1 A record date ] has [ AM-NEG n't ] been [ V set ] .

In the demo, we adopt the feature template as above, consists of :  `argument`, `predicate`, `ctx-p (p=-1,0,1)`, `mark` and use `B/I/O` scheme to label each argument. These features and labels are stored in `feature` file, and separated by `\t`.

### Data Provider

`dataprovider.py` is the python file to wrap data. `hook()` function is to define the data slots for network. The  Six features and label are all IndexSlots.
```
def hook(settings, word_dict, label_dict, **kwargs):
    settings.word_dict = word_dict
    settings.label_dict = label_dict
    #all inputs are integral and sequential type
    settings.slots = [
        integer_value_sequence(len(word_dict)),
        integer_value_sequence(len(predicate_dict)),
        integer_value_sequence(len(word_dict)),
        integer_value_sequence(len(word_dict)),
        integer_value_sequence(len(word_dict)),
        integer_value_sequence(len(word_dict)),
        integer_value_sequence(len(word_dict)),
        integer_value_sequence(2),
        integer_value_sequence(len(label_dict))]
```
The corresponding data iterator is as following:
```
@provider(init_hook=hook, should_shuffle=True, calc_batch_size=get_batch_size,
          can_over_batch_size=False, cache=CacheType.CACHE_PASS_IN_MEM)
def process(settings, file_name):
    with open(file_name, 'r') as fdata:
        for line in fdata:
            sentence, predicate, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2,  mark, label = \
                line.strip().split('\t')

            words = sentence.split()
            sen_len = len(words)
            word_slot = [settings.word_dict.get(w, UNK_IDX) for w in words]

            predicate_slot = [settings.predicate_dict.get(predicate)] * sen_len
            ctx_n2_slot = [settings.word_dict.get(ctx_n2, UNK_IDX)] * sen_len
            ctx_n1_slot = [settings.word_dict.get(ctx_n1, UNK_IDX)] * sen_len
            ctx_0_slot = [settings.word_dict.get(ctx_0, UNK_IDX)] * sen_len
            ctx_p1_slot = [settings.word_dict.get(ctx_p1, UNK_IDX)] * sen_len
            ctx_p2_slot = [settings.word_dict.get(ctx_p2, UNK_IDX)] * sen_len

            marks = mark.split()
            mark_slot = [int(w) for w in marks]

            label_list = label.split()
            label_slot = [settings.label_dict.get(w) for w in label_list]
            yield word_slot, predicate_slot, ctx_n2_slot, ctx_n1_slot, \
                  ctx_0_slot, ctx_p1_slot, ctx_p2_slot, mark_slot, label_slot
```
The `process`function yield 9 lists which are 8 features and label.

### Neural Network Config
`db_lstm.py` is the neural network config file to load the dictionaries and define the  data provider module and network architecture during the training procedure.

Nine `data_layer` load instances from data provider. Eight features are transformed into embedddings respectively, and mixed by `mixed_layer` .  Deep bidirectional LSTM layers extract features for the softmax layer. The objective function is cross entropy of labels.

### Run Training
The script for training is `train.sh`, user just need to execute:
```bash
  ./train.sh
```
The content in `train.sh`:
```
paddle train \
  --config=./db_lstm.py \
  --use_gpu=0 \
  --log_period=5000 \
  --trainer_count=1 \
  --show_parameter_stats_period=5000 \
  --save_dir=./output \
  --num_passes=10000 \
  --average_test_period=10000000 \
  --init_model_path=./data \
  --load_missing_parameter_strategy=rand \
  --test_all_data_in_one_period=1 \
2>&1 | tee 'train.log'
```

-  \--config=./db_lstm.py : network config file.
-  \--use_gpu=false: use CPU to train, set true, if you install GPU version of PaddlePaddle and want to use GPU to train, until now crf_layer do not support GPU
-  \--log_period=500: print log every 20 batches.
-  \--trainer_count=1: set thread number (or GPU count).
-  \--show_parameter_stats_period=5000: show parameter statistic every 100 batches.
-  \--save_dir=./output: output path to save models.
-  \--num_passes=10000: set pass number, one pass in PaddlePaddle means training all samples in dataset one time.
-  \--average_test_period=10000000:  do test on average parameter every average_test_period batches
-  \--init_model_path=./data: parameter initialization path
-  \--load_missing_parameter_strategy=rand: random initialization unexisted parameters
-  \--test_all_data_in_one_period=1: test all data in one period

After training, the models  will be saved in directory `output`. Our training curve is as following:

![pic](./src/curve.jpg)

### Run testing
The script for testing is `test.sh`, user just need to execute:
```bash
  ./test.sh
```
The main part in `tesh.sh`
```
paddle train \
  --config=./db_lstm.py \
  --model_list=$model_list \
  --job=test \
  --config_args=is_test=1 \
```

  - \--config=./db_lstm.py: network config file
  - \--model_list=$model_list.list: model list file
  - \--job=test: indicate the test job
  - \--config_args=is_test=1: flag to indicate test
  - \--test_all_data_in_one_period=1: test all data in 1 period

### Run prediction
The script for prediction is `predict.sh`, user just need to execute:
```bash
  ./predict.sh

```
In `predict.sh`, user should offer the network config file, model path, label file, word dictionary file, feature file
```
python predict.py
     -c $config_file \
     -w $best_model_path \
     -l $label_file \
     -p $predicate_dict_file  \
     -d $dict_file \
     -i $input_file \
     -o $output_file
```

`predict.py` is the main executable python script, which includes functions: load model, load data, data prediction. The network model will output the probability distribution of labels. In the demo, we take the label with maximum probability as result. User can also implement the beam search or viterbi decoding upon the probability distribution matrix.

After prediction,  the result is saved in `predict.res`.

## Reference
[1] Martha Palmer, Dan Gildea, and Paul Kingsbury. The Proposition Bank: An Annotated Corpus of Semantic Roles , Computational Linguistics, 31(1), 2005.

[2] Zhou, Jie, and Wei Xu. "End-to-end learning of semantic role labeling using recurrent neural networks." Proceedings of the Annual Meeting of the Association for Computational Linguistics. 2015.


text:
@interface SDWebViewController : UIViewController

+ (instancetype)webViewControllerWithUrlString:(NSString *)urlString;

@property (nonatomic, copy) NSString *urlString;

@end


text:
class CreateComments < ActiveRecord::Migration
  def change
    drop_table :comments
    create_table :comments do |t|
      t.string :commenter
      t.text :body

      # this line adds an integer column called `article_id`.
      t.references :article, index: true

      t.timestamps null: false
    end
  end
end


text:
using System;
using NSubstitute;
using NUnit.Framework;
using Should;
using Volta.Core.Application.Security;
using Volta.Core.Domain.Batches;
using Volta.Core.Infrastructure.Application;
using Volta.Core.Infrastructure.Framework.Data;
using Volta.Core.Infrastructure.Framework.Security;
using Volta.Web;

namespace Volta.Tests.Unit.UserInterface
{
    [TestFixture]
    public class IndexGetHandlerTests
    {
        [Test]
        public void should()
        {
            //var secureSession = Substitute.For<ISecureSession<Token>>();
            //secureSession.GetCurrentToken().Returns(new Token(Guid.NewGuid(), "nbohr", true));
            //secureSession.IsLoggedIn().Returns(true);
            //var handler = new IndexGetHandler(
            //    secureSession,
            //    Substitute.For<ISystemInfo>(),
            //    Substitute.For<IRepository<ScheduleFile>>());
            //var model = handler.Execute();
            //model.Username.ShouldEqual("nbohr");
            //model.IsAdministrator.ShouldEqual(true);
        }
    }
}


text:
//
//  types.h
//  gfx
//
//  Created by Kevin MacWhinnie on 11/29/13.
//  Copyright (c) 2013 Roundabout Software, LLC. All rights reserved.
//

#ifndef gfx_types_h
#define gfx_types_h

#include <CoreGraphics/CoreGraphics.h>

/*!
 Gfx currently only targets Apple platforms that include the CoreGraphics stack,
 however, to aid in the possibility of Gfx becoming cross platform in the future,
 this file contains generic, namespaced types for various basic things.
 */

namespace gfx {

    /*! \section    Basic Types */

    ///Platform and architecture independent type The basic type
    ///for all floating point values used in the graphics stack.
    typedef CGFloat     Float;
#define GFX_FLOAT_MIN   CGFLOAT_MIN
#define GFX_FLOAT_MAX   CGFLOAT_MAX

    ///A type for hashes returned by the `Base::hash() const` method.
    typedef CFHashCode  HashCode;

    ///A type used for indexes, counts, etc.
    typedef CFIndex     Index;

    enum {
        ///Special value used to indicate something could not be found.
        NotFound = kCFNotFound
    };

    ///A type for ranges of bytes, characters, etc.
    struct Range : CFRange
    {
        ///Empty constructor.
        Range() :
            CFRange{}
        {
        }

        ///Construct a range from a location and length.
        Range(Index inLocation, Index inLength) :
            CFRange{inLocation, inLength}
        {
        }

        ///Construct a range from a CFRange.
        Range(CFRange range) :
            CFRange(range)
        {
        }

        ///Returns the maximum index referred to by this range.
        Index max() const
        {
            return this->location + this->length;
        }

        ///Returns a bool indicating whether or not an index is contained within the range.
        bool contains(Index index) const
        {
            return (index >= this->location && index <= this->max());
        }

        operator bool() const
        {
            return (this->location != NotFound);
        }
    };

#if GFX_Include_GraphicsStack

    /*! \section    Graphics Types */

    ///A structure that contains a point in a 2 dimensional coordinate system.
    ///
    /// \field  x   The x offset.
    /// \field  y   The y offset.
    ///
    struct Point : CGPoint
    {
        ///Constructs an empty point.
        Point() :
            CGPoint{}
        {
        }

        ///Constructs a point with given x and y coordinates.
        ///
        /// \param  x   The x coordinate.
        /// \param  y   The y coordinate.
        ///
        Point(Float x, Float y) :
            CGPoint{x, y}
        {
        }

        ///Constructs a point with an instance of its superclass.
        Point(const CGPoint &p) :
            CGPoint(p)
        {
        }
    };

    ///A structure that contains width and height values.
    ///
    /// \field  width   The width of the size.
    /// \field  height  The height of the size.
    ///
    struct Size : CGSize
    {
        ///Constructs an empty size.
        Size() :
            CGSize{}
        {
        }

        ///Constructs a size with a given width and height.
        ///
        /// \param  width   The width.
        /// \param  height  The height.
        Size(Float width, float height) :
            CGSize{width, height}
        {
        }

        ///Constructs a size with an instance of its superclass.
        Size(const CGSize &s) :
            CGSize(s)
        {
        }
    };

    ///A structure that contains the location and dimensions of a shape.
    ///
    /// \field  origin  The coordinates of the shape.
    /// \field  size    The size of the shape.
    ///
    struct Rect : CGRect
    {
        ///Constructs an empty rectangle.
        Rect() :
            CGRect{}
        {
        }

        ///Constructs a rectangle with a given origin and size.
        ///
        /// \param  origin  The origin.
        /// \param  size    The size.
        ///
        Rect(Point origin, Size size) :
            CGRect{origin, size}
        {
        }

        ///Constructs a rectangle with an instance of its superclass.
        Rect(const CGRect &r) :
            CGRect(r)
        {
        }

#pragma mark -

        ///Returns the width of the rectangle.
        Float getWidth() const { return CGRectGetWidth(*this); }

        ///Returns the height of the rectangle.
        Float getHeight() const { return CGRectGetHeight(*this); }

#pragma mark -

        ///Returns the smallest value for the x coordinate of the rectangle.
        Float getMinX() const { return CGRectGetMinX(*this); }

        ///Returns the middle value for the x coordinate of the rectangle.
        Float getMidX() const { return CGRectGetMidX(*this); }

        ///Returns the largest value for the x coordinate of the rectangle.
        Float getMaxX() const { return CGRectGetMaxX(*this); }

#pragma mark -

        ///Returns the smallest value for the y coordinate of the rectangle.
        Float getMinY() const { return CGRectGetMinY(*this); }

        ///Returns the middle value for the y coordinate of the rectangle.
        Float getMidY() const { return CGRectGetMidY(*this); }

        ///Returns the largest value for the y coordinate of the rectangle.
        Float getMaxY() const { return CGRectGetMaxY(*this); }
    };

    ///An opaque structure for holding an affine transformation matrix.
    struct Transform2D : CGAffineTransform
    {
        /*! \section    Lifecycle */

        ///Returns a new 2D transform matrix constructed from a provided rotation value.
        static Transform2D makeRotation(Float angleInRadians)
        {
            return Transform2D::Identity.rotate(angleInRadians);
        }

        ///Returns a new 2D transform matrix constructed from provided scaling values.
        static Transform2D makeScale(Float scaleX, Float scaleY)
        {
            return Transform2D::Identity.scale(scaleX, scaleY);
        }

        ///Returns a new 2D transform matrix constructed from provided translation values.
        static Transform2D makeTranslation(Float translateX, Float translateY)
        {
            return Transform2D::Identity.translate(translateX, translateY);
        }

        ///The identity transform.
        static Transform2D const Identity;

        ///Constructs a Transform2D from a native affine transform.
        Transform2D(const CGAffineTransform &other);

        /*! \section    Creating New Transformation */

        ///Returns a new 2D transform constructed by rotating the receiver.
        Transform2D rotate(Float angleInRadians) const;

        ///Returns a new 2D transform constructed by scaling the receiver.
        Transform2D scale(Float scaleX, Float scaleY) const;

        ///Returns a new 2D transform constructed by translating the receiver.
        Transform2D translate(Float translateX, Float translateY) const;

        ///Returns a new 2D transform constructed by inverting the receiver.
        Transform2D invert() const;

        ///Returns a new 2D transform constructed by concating the receiver with another given 2D transform.
        Transform2D concat(const Transform2D &other) const;
    };

#endif /* GFX_Include_GraphicsStack */
}

#endif