text:
/*
# This file is part of libkd.
# Licensed under a 3-clause BSD style license - see LICENSE
*/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <math.h>

#include "kdtree.h"
#include "kdtree_internal.h"

KD_DECLARE(kdtree_build_2, kdtree_t*, (kdtree_t* kd, void *data, int N, int D, int Nleaf, int treetype, unsigned int options, double* minval, double* maxval));

/* Build a tree from an array of data, of size N*D*sizeof(real) */
/* If the root node is level 0, then maxlevel is the level at which there may
 * not be enough points to keep the tree complete (i.e. last level) */
kdtree_t* KDFUNC(kdtree_build_2)
	 (kdtree_t* kd, void *data, int N, int D, int Nleaf,
	  int treetype, unsigned int options,
      double* minval, double* maxval) {

	KD_DISPATCH(kdtree_build_2, treetype, kd=, (kd, data, N, D, Nleaf, treetype, options, minval, maxval));
	return kd;
}

/* Range seach */
kdtree_qres_t* KDFUNC(kdtree_rangesearch)
	 (const kdtree_t *kd, const void *pt, double maxd2) {
	return KDFUNC(kdtree_rangesearch_options_reuse)(kd, NULL, pt, maxd2, KD_OPTIONS_COMPUTE_DISTS | KD_OPTIONS_SORT_DISTS);
}

kdtree_qres_t* KDFUNC(kdtree_rangesearch_nosort)
	 (const kdtree_t *kd, const void *pt, double maxd2) {
	return KDFUNC(kdtree_rangesearch_options_reuse)(kd, NULL, pt, maxd2, KD_OPTIONS_COMPUTE_DISTS);
}

kdtree_qres_t* KDFUNC(kdtree_rangesearch_options)
	 (const kdtree_t *kd, const void *pt, double maxd2, int options) {
	return KDFUNC(kdtree_rangesearch_options_reuse)(kd, NULL, pt, maxd2, options);
}

KD_DECLARE(kdtree_rangesearch_options, kdtree_qres_t*, (const kdtree_t* kd, kdtree_qres_t* res, const void* pt, double maxd2, int options));

kdtree_qres_t* KDFUNC(kdtree_rangesearch_options_reuse)
	 (const kdtree_t *kd, kdtree_qres_t* res, const void *pt, double maxd2, int options) {
    assert(kd->fun.rangesearch);
    return kd->fun.rangesearch(kd, res, pt, maxd2, options);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<archetype-descriptor
        xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd"
        name="webapp"
        xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <fileSets>
        <fileSet filtered="true" packaged="true" encoding="UTF-8">
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.java</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" packaged="true" encoding="UTF-8">
            <directory>src/main/orm</directory>
            <includes>
                <include>**/*.java</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" encoding="UTF-8">
            <directory>src/main/prop</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" encoding="UTF-8">
            <directory>src/main/webapp</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" encoding="UTF-8">
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" packaged="true" encoding="UTF-8">
            <directory>src/test/java</directory>
            <includes>
                <include>**/*.java</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" encoding="UTF-8">
            <directory>src/test/resources</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </fileSet>

        <fileSet filtered="false" encoding="UTF-8">
            <directory>other/</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
            <excludes>
                <exclude>log/</exclude>
                <exclude>xsd/</exclude>
            </excludes>
        </fileSet>

        <fileSet filtered="true" encoding="UTF-8">
            <directory>other/log</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </fileSet>
        <fileSet filtered="true" encoding="UTF-8">
            <directory>other/xsd</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </fileSet>

        <fileSet filtered="true" encoding="UTF-8">
            <directory></directory>
            <includes>
                <include>*.md</include>
            </includes>
        </fileSet>

    </fileSets>
</archetype-descriptor>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace spec\Sylius\Component\Locale\Context;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Locale\Context\ImmutableLocaleContext;
use Sylius\Component\Locale\Context\LocaleContextInterface;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
final class ImmutableLocaleContextSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith('pl_PL');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType(ImmutableLocaleContext::class);
    }

    function it_is_a_locale_context()
    {
        $this->shouldImplement(LocaleContextInterface::class);
    }

    function it_gets_a_locale_code()
    {
        $this->getLocaleCode()->shouldReturn('pl_PL');
    }
}


text:
module.exports = function( grunt ) {

  grunt.registerTask( 'default', [
    'jshint',
    'eslint',
    'mocha_istanbul'
  ]);

};


text:
Paragraphs eat blank lines.
The following are two paragraphs:
*** Parameters: ***
{}
*** Markdown input: ***
Paragraph1

Paragraph2
*** Output of inspect ***
md_el(:document,[md_par(["Paragraph1"]), md_par(["Paragraph2"])],{},[])
*** Output of to_html ***

Paragraph1

Paragraph2

*** Output of to_latex ***
Paragraph1

Paragraph2
*** Output of to_md ***
Paragraph1

Paragraph2
*** Output of to_s ***
Paragraph1Paragraph2
*** EOF ***

	OK!

*** Output of Markdown.pl ***

Paragraph1

Paragraph2

*** Output of Markdown.pl (parsed) ***
Error: #<NoMethodError: private method `write_children' called for
 ... </>:REXML::Element>


text:
package org.wildfly.extras.creaper.commands.security.realms;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.wildfly.extras.creaper.core.CommandFailedException;
import org.wildfly.extras.creaper.core.ManagementClient;
import org.wildfly.extras.creaper.core.offline.OfflineManagementClient;
import org.wildfly.extras.creaper.core.offline.OfflineOptions;

import static org.junit.Assert.fail;
import static org.wildfly.extras.creaper.XmlAssert.assertXmlIdentical;

public class RemoveLdapConnectionOfflineTest {

    private static final String ONE_LDAP_CONNECTION = ""
            + "<server xmlns=\"urn:jboss:domain:1.7\">\n"
            + "    <management>\n"
            + "        <outbound-connections>\n"
            + "            <ldap name=\"creaperLdapConnection\" url=\"ldap://localhost:389\"/>\n"
            + "        </outbound-connections>\n"
            + "    </management>\n"
            + "</server>";
    private static final String TWO_LDAP_CONNECTION = ""
            + "<server xmlns=\"urn:jboss:domain:1.7\">\n"
            + "    <management>\n"
            + "        <outbound-connections>\n"
            + "            <ldap name=\"creaperLdapConnection\" url=\"ldap://localhost:389\"/>\n"
            + "            <ldap name=\"creaperLdapConnection2\" url=\"ldap://localhost:10389\"/>\n"
            + "        </outbound-connections>\n"
            + "    </management>\n"
            + "</server>";
    private static final String NO_LDAP_CONNECTION = ""
            + "<server xmlns=\"urn:jboss:domain:1.7\">\n"
            + "    <management/>\n"
            + "</server>";

    @Rule
    public final TemporaryFolder tmp = new TemporaryFolder();

    @Before
    public void setUp() {
        XMLUnit.setNormalizeWhitespace(true);
    }

    @Test
    public void removeExistingLdapConnection() throws Exception {
        File cfg = tmp.newFile("xmlTransform.xml");
        Files.write(TWO_LDAP_CONNECTION, cfg, Charsets.UTF_8);

        OfflineManagementClient client = ManagementClient.offline(
                OfflineOptions.standalone().configurationFile(cfg).build());

        RemoveLdapConnection removeLdapConnection = new RemoveLdapConnection("creaperLdapConnection2");

        assertXmlIdentical(TWO_LDAP_CONNECTION, Files.toString(cfg, Charsets.UTF_8));
        client.apply(removeLdapConnection);
        assertXmlIdentical(ONE_LDAP_CONNECTION, Files.toString(cfg, Charsets.UTF_8));
    }

    @Test
    public void removeLastExistingLdapConnection() throws Exception {
        File cfg = tmp.newFile("xmlTransform.xml");
        Files.write(ONE_LDAP_CONNECTION, cfg, Charsets.UTF_8);

        OfflineManagementClient client = ManagementClient.offline(
                OfflineOptions.standalone().configurationFile(cfg).build());

        RemoveLdapConnection removeLdapConnection = new RemoveLdapConnection("creaperLdapConnection");

        assertXmlIdentical(ONE_LDAP_CONNECTION, Files.toString(cfg, Charsets.UTF_8));
        client.apply(removeLdapConnection);
        assertXmlIdentical(NO_LDAP_CONNECTION, Files.toString(cfg, Charsets.UTF_8));
    }

    @Test(expected = CommandFailedException.class)
    public void removeNonExistingLdapConnection() throws Exception {
        File cfg = tmp.newFile("xmlTransform.xml");
        Files.write(ONE_LDAP_CONNECTION, cfg, Charsets.UTF_8);

        OfflineManagementClient client = ManagementClient.offline(
                OfflineOptions.standalone().configurationFile(cfg).build());

        RemoveLdapConnection removeLdapConnection = new RemoveLdapConnection("wrongCreaperLdapConnection");

        assertXmlIdentical(ONE_LDAP_CONNECTION, Files.toString(cfg, Charsets.UTF_8));
        client.apply(removeLdapConnection);

        fail("Ldap connection wrongCreaperLdapConnection does not exist in configuration, exception should be thrown");
    }

}


text:
export interface IListItem {
  id: string;
  name?: string;
  webUrl?: string;
  createdDateTime?: Date;
  lastModifiedDateTime?: Date;
  createdBy?: {
      user: {
          displayName: string;
      }
  };
  lastModifiedBy?: {
      user: {
          displayName: string;
      }
  };
  fields?: { [fieldName: string]: any };
}


text:
<?php

function render_not_found($error = [JSON_ERROR => [UNSPECIFIED => "not_found"]])
{
    render_status_json(404, $error);
}

function render_ok_json($response)
{
    render_status_json(200, $response);
}

function render_ok()
{
    http_response_code(200);
}

function render_unsupported_media_type($error = [JSON_ERROR => [UNSPECIFIED => "unsupported_media_type"]])
{
    render_status_json(415, $error);
}

function render_conflict($error)
{
    render_status_json(409, $error);
}

function render_internal_server_error($error = [JSON_ERROR => [UNSPECIFIED => "something_went_wrong"]])
{
    render_status_json(500, $error);
}

function render_not_allowed_json($error = [JSON_ERROR => [UNSPECIFIED => "method_not_allowed"]])
{
    render_status_json(405, $error);
}

function render_bad_request_json($error)
{
    render_status_json(400, $error);
    ob_flush();
}

function render_not_authorized_json($error = [JSON_ERROR => [UNSPECIFIED => "not_authorized"]])
{
    render_status_json(401, $error);
}

function render_forbidden($error = [JSON_ERROR => [UNSPECIFIED => "forbidden"]])
{
    render_status_json(403, $error);
}

function render_status_json($code, $message)
{
    http_response_code($code);
    echo json_encode($message);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Fpm.MainUI.Helpers;
using Fpm.ProfileData;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Fpm.MainUITest.Helpers
{
    [TestClass]
    public class UserDetailsTest
    {
        [TestMethod]
        public void TestFpmUser()
        {
            var user = UserWithRights().FpmUser;
            Assert.IsNotNull(user, "No user object found");
            Assert.AreEqual(FpmUserIds.Doris, user.Id, "UserDetails ID not as expected");
        }

        [TestMethod]
        public void TestNewUserFromUserId()
        {
            var user = UserWithRights().FpmUser;
            Assert.IsNotNull(user, "No user object found");
            Assert.AreEqual(FpmUserIds.Doris, user.Id, "UserDetails ID not as expected");
        }

        [TestMethod]
        public void TestConvertUserNameToDisplayName()
        {
            var user = UserDetails.ConvertUserNameToDisplayName(UserNames.Doris);
            Assert.AreEqual("Doris Hain", user);
        }

        [TestMethod]
        public void TestHasWritePermissionsToProfile()
        {
            Assert.IsTrue(UserWithRights()
                .HasWritePermissionsToProfile(ProfileIds.Phof));

            Assert.IsFalse(UserWithNoRights()
                .HasWritePermissionsToProfile(ProfileIds.Phof));
        }

        [TestMethod]
        public void TestGetProfilesUserHasPermissionsTo()
        {
            Assert.IsTrue(UserWithRights().GetProfilesUserHasPermissionsTo().Count() > 10);

            Assert.AreEqual(0, UserWithNoRights().GetProfilesUserHasPermissionsTo().Count());
        }

        [TestMethod]
        public void TestGetProfilesUserHasPermissionsTo2()
        {
            Assert.IsTrue(UserWithRights().GetProfilesUserHasPermissionsTo().Count() > 10);
            var user = UserDetails.NewUserFromUserId(FpmUserIds.FarrukhAyub);
            var userProfiles = user.GetProfilesUserHasPermissionsTo();
            foreach (var userProfile in userProfiles)
            {
                Assert.IsNotNull(userProfile);
            }
        }

        private static UserDetails UserWithNoRights()
        {
            return UserDetails.NewUserFromUserId(FpmUserIds.UserWithNoRightsToAnything);
        }

        private static UserDetails UserWithRights()
        {
            return UserDetails.NewUserFromUserId(FpmUserIds.Doris);
        }
    }
}


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <px4_config.h>
#include <stdint.h>
#include "boot_config.h"
#include "board.h"

#include <debug.h>
#include <string.h>
#include <arch/board/board.h>

#include <nuttx/board.h>
#include "led.h"

/************************************************************************************
 * Name: stm32_boardinitialize
 *
 * Description:
 *   All STM32 architectures must provide the following entry point.  This entry point
 *   is called early in the initialization -- after all memory has been configured
 *   and mapped but before any devices have been initialized.
 *
 ************************************************************************************/

__EXPORT void stm32_boardinitialize(void)
{
	putreg32(getreg32(STM32_RCC_APB1ENR) | RCC_APB1ENR_CAN1EN, STM32_RCC_APB1ENR);
	stm32_configgpio(GPIO_CAN1_RX);
	stm32_configgpio(GPIO_CAN1_TX);
	stm32_configgpio(GPIO_CAN1_SILENT_S0);
	stm32_configgpio(GPIO_CAN1_TERMINATION);
	putreg32(getreg32(STM32_RCC_APB1RSTR) | RCC_APB1RSTR_CAN1RST, STM32_RCC_APB1RSTR);
	putreg32(getreg32(STM32_RCC_APB1RSTR) & ~RCC_APB1RSTR_CAN1RST, STM32_RCC_APB1RSTR);

#if defined(OPT_WAIT_FOR_GETNODEINFO_JUMPER_GPIO)
	stm32_configgpio(GPIO_GETNODEINFO_JUMPER);
#endif

}

/************************************************************************************
 * Name: board_deinitialize
 *
 * Description:
 *   This function is called by the bootloader code prior to booting
 *   the application. Is should place the HW into an benign initialized state.
 *
 ************************************************************************************/

void board_deinitialize(void)
{
	putreg32(getreg32(STM32_RCC_APB1RSTR) | RCC_APB1RSTR_CAN1RST, STM32_RCC_APB1RSTR);
}

/****************************************************************************
 * Name: board_get_product_name
 *
 * Description:
 *   Called to retrieve the product name. The returned value is a assumed
 *   to be written to a pascal style string that will be length prefixed
 *   and not null terminated
 *
 * Input Parameters:
 *    product_name - A pointer to a buffer to write the name.
 *    maxlen       - The maximum number of charter that can be written
 *
 * Returned Value:
 *   The length of characters written to the buffer.
 *
 ****************************************************************************/

uint8_t board_get_product_name(uint8_t *product_name, size_t maxlen)
{
	DEBUGASSERT(maxlen > UAVCAN_STRLEN(HW_UAVCAN_NAME));
	memcpy(product_name, HW_UAVCAN_NAME, UAVCAN_STRLEN(HW_UAVCAN_NAME));
	return UAVCAN_STRLEN(HW_UAVCAN_NAME);
}

/****************************************************************************
 * Name: board_get_hardware_version
 *
 * Description:
 *   Called to retrieve the hardware version information. The function
 *   will first initialize the the callers struct to all zeros.
 *
 * Input Parameters:
 *    hw_version - A pointer to a uavcan_hardwareversion_t.
 *
 * Returned Value:
 *   Length of the unique_id
 *
 ****************************************************************************/

size_t board_get_hardware_version(uavcan_HardwareVersion_t *hw_version)
{
	memset(hw_version, 0, sizeof(uavcan_HardwareVersion_t));

	hw_version->major = HW_VERSION_MAJOR;
	hw_version->minor = HW_VERSION_MINOR;

	return board_get_mfguid(*(mfguid_t *) hw_version->unique_id);
}

/****************************************************************************
 * Name: board_indicate
 *
 * Description:
 *   Provides User feedback to indicate the state of the bootloader
 *   on board specific  hardware.
 *
 * Input Parameters:
 *    indication - A member of the uiindication_t
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/
#define led(n, code, r , g , b, h) {.red = (r),.green = (g), .blue = (b),.hz = (h)}

typedef begin_packed_struct struct led_t {
	uint8_t red;
	uint8_t green;
	uint8_t blue;
	uint8_t hz;
} end_packed_struct led_t;

static const  led_t i2l[] = {

	led(0, off,                             0,     0,     0,     0),
	led(1, reset,                          128,   128,   128,   30),
	led(2, autobaud_start,                  0,   128,     0,     1),
	led(3, autobaud_end,                    0,   128,     0,     2),
	led(4, allocation_start,                0,     0,    64,     2),
	led(5, allocation_end,                  0,   128,    64,     3),
	led(6, fw_update_start,                32,   128,    64,     3),
	led(7, fw_update_erase_fail,           32,   128,    32,     3),
	led(8, fw_update_invalid_response,     64,     0,     0,     1),
	led(9, fw_update_timeout,              64,     0,     0,     2),
	led(a, fw_update_invalid_crc,          64,     0,     0,     4),
	led(b, jump_to_app,                     0,   128,     0,    10),

};

void board_indicate(uiindication_t indication)
{
	rgb_led(i2l[indication].red,
		i2l[indication].green,
		i2l[indication].blue,
		i2l[indication].hz);
}


text:
<!doctype html>
<html>
  <head>
      <meta charset="utf-8">
      <title>BodyMap!</title>
      <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
      <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
      <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
      <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
      <link rel="stylesheet" href="{{ url_for('static', filename='css/datatables.min.css') }}">

      <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
      <script src="{{ url_for('static', filename='js/select2.min.js') }}"></script>
      <link rel="stylesheet" href="{{ url_for('static', filename='css/select2.min.css') }}">
      <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
      <script src="{{ url_for('static', filename='js/datatables.min.js') }}"></script>
      <script src="https://d3js.org/d3.v3.min.js"></script>
      {% block head %}
      {% endblock %}

  </head>
  <body>

    <div class="container-fluid">
    {% block content %}
    {% endblock %}
    </div>

{% block scripts %}
{% endblock %}

</body>

</html>


text:
namespace BattleShip
{
    partial class form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(form1));
            this.btnNewGame = new System.Windows.Forms.Button();
            this.btnControls = new System.Windows.Forms.Button();
            this.btnExit = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.btnHighscores = new System.Windows.Forms.Button();
            this.btnContinue = new System.Windows.Forms.Button();
            this.label6 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // btnNewGame
            //
            this.btnNewGame.BackColor = System.Drawing.Color.Transparent;
            this.btnNewGame.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnNewGame.BackgroundImage")));
            this.btnNewGame.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro;
            this.btnNewGame.FlatAppearance.CheckedBackColor = System.Drawing.Color.Transparent;
            this.btnNewGame.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnNewGame.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnNewGame.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnNewGame.Font = new System.Drawing.Font("Agency FB", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnNewGame.ForeColor = System.Drawing.SystemColors.ButtonFace;
            this.btnNewGame.Location = new System.Drawing.Point(464, 142);
            this.btnNewGame.Name = "btnNewGame";
            this.btnNewGame.Size = new System.Drawing.Size(87, 42);
            this.btnNewGame.TabIndex = 0;
            this.btnNewGame.Text = "New Game";
            this.btnNewGame.UseVisualStyleBackColor = false;
            this.btnNewGame.Click += new System.EventHandler(this.btnNewGame_Click);
            this.btnNewGame.MouseEnter += new System.EventHandler(this.btnNewGame_MouseEnter);
            //
            // btnControls
            //
            this.btnControls.BackColor = System.Drawing.Color.Transparent;
            this.btnControls.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnControls.BackgroundImage")));
            this.btnControls.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro;
            this.btnControls.FlatAppearance.CheckedBackColor = System.Drawing.Color.Transparent;
            this.btnControls.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnControls.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnControls.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnControls.Font = new System.Drawing.Font("Agency FB", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnControls.ForeColor = System.Drawing.SystemColors.ButtonFace;
            this.btnControls.Location = new System.Drawing.Point(464, 190);
            this.btnControls.Name = "btnControls";
            this.btnControls.Size = new System.Drawing.Size(87, 42);
            this.btnControls.TabIndex = 1;
            this.btnControls.Text = "How To Play";
            this.btnControls.UseVisualStyleBackColor = false;
            this.btnControls.Click += new System.EventHandler(this.btnControls_Click);
            this.btnControls.MouseEnter += new System.EventHandler(this.btnControls_MouseEnter);
            //
            // btnExit
            //
            this.btnExit.BackColor = System.Drawing.Color.Transparent;
            this.btnExit.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnExit.BackgroundImage")));
            this.btnExit.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro;
            this.btnExit.FlatAppearance.CheckedBackColor = System.Drawing.Color.Transparent;
            this.btnExit.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnExit.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnExit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnExit.Font = new System.Drawing.Font("Agency FB", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnExit.ForeColor = System.Drawing.SystemColors.ButtonFace;
            this.btnExit.Location = new System.Drawing.Point(464, 286);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(87, 42);
            this.btnExit.TabIndex = 2;
            this.btnExit.Text = "Exit";
            this.btnExit.UseVisualStyleBackColor = false;
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            this.btnExit.MouseEnter += new System.EventHandler(this.btnExit_MouseEnter);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.BackColor = System.Drawing.Color.Transparent;
            this.label1.Font = new System.Drawing.Font("Lucida Sans Unicode", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
            this.label1.Location = new System.Drawing.Point(305, 445);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(69, 15);
            this.label1.TabIndex = 3;
            this.label1.Text = "© VIM 2017";
            //
            // btnHighscores
            //
            this.btnHighscores.BackColor = System.Drawing.Color.Transparent;
            this.btnHighscores.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnHighscores.BackgroundImage")));
            this.btnHighscores.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro;
            this.btnHighscores.FlatAppearance.CheckedBackColor = System.Drawing.Color.Transparent;
            this.btnHighscores.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnHighscores.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnHighscores.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnHighscores.Font = new System.Drawing.Font("Agency FB", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnHighscores.ForeColor = System.Drawing.SystemColors.ButtonFace;
            this.btnHighscores.Location = new System.Drawing.Point(464, 238);
            this.btnHighscores.Name = "btnHighscores";
            this.btnHighscores.Size = new System.Drawing.Size(87, 42);
            this.btnHighscores.TabIndex = 4;
            this.btnHighscores.Text = "Highscores";
            this.btnHighscores.UseVisualStyleBackColor = false;
            this.btnHighscores.Click += new System.EventHandler(this.btnHighscores_Click);
            this.btnHighscores.MouseEnter += new System.EventHandler(this.btnHighscores_MouseEnter);
            //
            // btnContinue
            //
            this.btnContinue.BackColor = System.Drawing.Color.Transparent;
            this.btnContinue.BackgroundImage = global::BattleShip.Properties.Resources.btnCont6;
            this.btnContinue.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro;
            this.btnContinue.FlatAppearance.CheckedBackColor = System.Drawing.Color.Transparent;
            this.btnContinue.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnContinue.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnContinue.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnContinue.Font = new System.Drawing.Font("Agency FB", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnContinue.ForeColor = System.Drawing.SystemColors.ButtonFace;
            this.btnContinue.Location = new System.Drawing.Point(464, 94);
            this.btnContinue.Name = "btnContinue";
            this.btnContinue.Size = new System.Drawing.Size(87, 42);
            this.btnContinue.TabIndex = 5;
            this.btnContinue.Text = "Continue";
            this.btnContinue.UseVisualStyleBackColor = false;
            this.btnContinue.Click += new System.EventHandler(this.btnContinue_Click);
            this.btnContinue.MouseEnter += new System.EventHandler(this.btnContinue_MouseEnter);
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.BackColor = System.Drawing.Color.Transparent;
            this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label6.Image = global::BattleShip.Properties.Resources.mute;
            this.label6.Location = new System.Drawing.Point(556, 26);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(48, 17);
            this.label6.TabIndex = 17;
            this.label6.Text = "          ";
            this.label6.Visible = false;
            this.label6.Click += new System.EventHandler(this.Label6_Click);
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.BackColor = System.Drawing.Color.Transparent;
            this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.Image = global::BattleShip.Properties.Resources.unmute;
            this.label4.Location = new System.Drawing.Point(556, 26);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(48, 17);
            this.label4.TabIndex = 18;
            this.label4.Text = "          ";
            this.label4.Click += new System.EventHandler(this.Label4_Click);
            //
            // form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.ClientSize = new System.Drawing.Size(654, 486);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.btnContinue);
            this.Controls.Add(this.btnHighscores);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnExit);
            this.Controls.Add(this.btnControls);
            this.Controls.Add(this.btnNewGame);
            this.DoubleBuffered = true;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "BattleShip";
            this.Load += new System.EventHandler(this.form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnNewGame;
        private System.Windows.Forms.Button btnControls;
        private System.Windows.Forms.Button btnExit;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnHighscores;
        private System.Windows.Forms.Button btnContinue;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label4;
    }
}


text:
title: Представления (View)
sidebar: flexberry-designer_sidebar
keywords: Flexberry Desinger, представления, View, атрибуты, мастер, детейл, наследование, пример
summary: Назначение представлений и особенности работы с ними
toc: true
permalink: ru/fd_view-definition.html
lang: ru
---

## Определение представления

`Представление (ракурс)` описывает некоторую логическую совокупность:
* собственных [атрибутов класса](fo_attributes-class-data.html),
* [мастеров](fd_key-concepts.html) любой вложенности и их атрибутов,
* представлений [детейлов](fd_key-concepts.html).

Представление является средством разработчика, позволяющим обеспечить отражение некоторого множества атрибутов связанных ассоциациями классов.

Для того чтобы правильно понять, что такое представление, можно представить исписанный лист бумаги и другой чистый лист бумаги с прямоугольными прорезями. Наложение второго листа на первый позволит видеть через прорези только некоторые слова или даже буквы. В этом примере: исписанный лист — объект данных, лист с прорезями — представление, наложенные листы — объект данных в представлении.

## Назначение представлений

Практическая ценность представлений очевидна: почти всегда происходит манипулирование довольно ограниченным набором свойств. Таким образом, во многих операциях (например, при чтении объекта) удобно ограничить набор свойств, вместо обработки всех, что позволит существенно увеличить производительность.

Представление используется как для формирования форм пользовательского интерфейса, так и для реализации операций (например, чтение объектов данных по представлению).

Представление является средством разработчика, позволяющим обеспечить отражение некоторого множества атрибутов, связанных ассоциациями классов.

`Обратите внимание!` Нельзя в одно представление дважды добавлять одно и то же свойство (атрибут), так как [сервис данных](fo_data-service.html) не сможет обработать данную ситуацию. Если же возникает необходимость в повторном использовании свойства, следует использовать [вычислимые поля](fo_not-stored-attributes.html).

## Виды представлений

Существуют разные виды представлений. Подробнее о них можно узнать из статьи [Основные виды представлений](fd_View-types.html):

* [E-представление](fd_e-view.html)
* [L-представление](fd_l-view.html)
* [T-представление](fd_t-view.html)
* [D-представление](fd_d-view.html)

### Наследование представлений

Объявленные статически представления [наследуются](fd_inheritance.html) (`наследуемые представления`), т.е. представления, объявленные для предков, действительны для потомков, более того, работа для любого объекта потомка через класс (тип) предка обеспечивается полиморфно для потомков (например, если есть список для некоторого класса, то все объекты потомков этого класса могут быть отображены в этом же списке, в этом же представлении). Статически объявленные для предков представления могут быть полностью `переопределены` в наследниках.

В связи с наследованием представлений:
* Особым образом настраивается [чтение принадлежащих различным классам объектов в одном представлении](fo_reading-several-types-objects.html)
* Реализованы [адаптивные представления](fo_adaptive-views-details.html).

### Задание представлений

Представление может быть задано:
* статически (приписано метаданными-атрибутами к классам данных)
* динамически (конструироваться в исходном коде).

Представления приписываются классам данных и именуются.

### Статически заданные представления

Статически, представление определяется следующими атрибутами:

* `ViewAttribute` — объявляет представление для класса. Указывается имя представления и состав собственных и мастеровых свойств произвольного уровня. Формат указания:

```
[(Имя св-ва мастера).(Имя св-ва мастера мастера).(Имя св-ва мастера мастера мастера ...).)(Имя атрибута) [as (пользовательское имя атрибута)) [on (путь расположения на форме))
```

* `AssociatedDetailViewAttribute` — указывает для представления [класса-шапки](fd_key-concepts.html) представление детейла, поскольку представление [шапки](fd_key-concepts.html) включает в себя представление детейла. Здесь же можно указать:
	* Должны ли детейлы прочитываться сервисами данных вместе с загрузкой [шапки](fd_key-concepts.html);
	* Путь расположения на форме;
	* Заголовок на форме;
	* Видимость на форме;
	* Имена агрегирующих функций, доступных пользователю из данного представления;
	* Должно ли представление быть [адаптивным (UseAdaptiveViewsLoading)](fo_adaptive-views-details.html).

* `MasterViewDefineAttribute` — дополнительно настраивает мастера в представлении [шапки](fd_key-concepts.html), можно указать:
	* Тип выбора (lookup type) мастерового объекта;
	* Строку для инициализации объекта (контрола) выбора мастерового объекта;
	* Отображаемое свойство при типе выбора LookupTypeEnum.Combo.

Путь расположения на форме указывается строкой вида:

```
[-|)[Имя)[\ [-|)[Имя))…
```

где:
* `-` означает группировку (`GroupBox`),
* `|` - закладку (Tab) на формах редактирования,
* `\` — разделитель пути.
* `Имя` — имя соответствующей закладки/группы.

В качестве имён свойств можно указывать "звездочку", что будет означать, что необходимо использовать все свойства. Например, если просто указать "звездочку", то в представление автоматически попадают все собственные свойства, если указать `Master.*`, то это будет означать, что в представление попадают все свойства указанного мастера. Программист может отключить автоматическое попадание какого-либо свойства в представление указанием перед свойством атрибута `DisableAutoViewing`.

[Пример](https://github.com/Flexberry/FlexberryORM-DemoApp/blob/master/FlexberryORM/CDLIB/Objects/CDDA.cs) статически определённых представлений:

```
[View("Generator", new string[) { "Company on \'|Common\-Copyright\'", "Product on \'|Common\-Copyright\'", "Copyright on \'|Common\-Copyright\' ", "Version" } ) )
[AssociatedDetailView( "Generator", "Classes", "Generator", true, "", "", true, new string[) { } ))
[AssociatedDetailView( "Generator", "Inheritances", "Generator", true, "", "", true, new string[) { } ))
[View( "Edit", new string[) { "Company", "Product", "Copyright", "Version", "DataObjectNameSpace" } ) )
public class Stage:STORMCASE.Repository.Stage
{
	…
}
```

В `RunTime` представления являются экземплярами класса `ICSSoft.STORMNET.View`. Разработчик может получить проинициализированный экземпляр класса, соответствующий статически определённому представлению, вызовом метода [Information](fo_methods-class-information.html).GetView, либо через [специальные статические свойства](fo_static-view-accessors.html).

### Динамически заданные представления

Для того, чтобы динамически определить представление, необходимо конструировать экземпляр класса `View` ([пример](https://github.com/Flexberry/FlexberryORM-DemoApp/blob/master/FlexberryORM/CDLIB/CDADMTEST/Form1.cs|)). Это можно сделать четырьмя способами:
* Конструировать пустое представление, затем пользоваться методами `DefineClassType, AddDetailInView, AddMasterInView, AddProperty` для дальнейшего определения.
* Конструировать представление с указанием экземпляра класса `ViewAttribute` (он же атрибут, служащий для задания статических представлений).
* Конструировать представление по проинициализированным свойствам (загруженные + отличные от [внутренней копии данных](fo_data-object-copy.html)) объекта данных.
* Конструировать представление `по-умолчанию` (попадают только собственные свойства, а также детейловые свойства, что указывается соответствующим параметром)

Также, через методы класса `View` можно полностью получить структуру представления, а также изменить её (получить/добавить/удалить элементы, входящие в представление).

Стоит также отметить, что настоятельно рекомендуется определять имя для динамически создаваемых представлений.

{% include note.html content="Кеширование View на форме для разных вычиток может приводить к ошибкам, поскольку при чтении с наложением ограничения конкретная инстанция View может быть изменена [сервисом данных](fo_data-service.html)." %}

## Проверка соответствия объекта представлению

Для проверки того, удовлетворяет ли некоторый [объект](fo_data-object.html) представлению, необходимо вызвать у экземпляра класса `View` метод `TestObjectForViewing`.

## Дополнительные сведения о представлениях

* Во [Flexberry ORM](fo_flexberry-orm.html) существуют [стандартные операции](fo_view-operations.html), позволяющие найти для нескольких классов их общего предка и общие представления. Также можно манипулировать с представлениями, как с множествами: вычислить, например, объединение или разность представлений.
* Существуют [рекомендации по добавлению мастеров в представления](fd_masters-view.html).
* Существует [способ проверить, удовлетворяет ли некоторый объект представлению](fo_test-object-for-viewing.html).
* [ViewPropertyAppender](fo_view-property-appender.html) - класс, который позволяет расширять представление свойствами, которые находятся в [ограничении](fo_limit-function.html)


text:
package me.shzylo.mansionazazel.level.tile;

import me.shzylo.mansionazazel.graphics.Screen;
import me.shzylo.mansionazazel.graphics.Sprite;

/**
 * Fourth piece of the car

 * Solid Tile
 */
public class Car_3Tile extends Tile {
	public Car_3Tile(Sprite sprite) {
		super(sprite);
	}

	public void render(int x, int y, Screen screen) {
		screen.renderTile(x << 4, y << 4, this);
	}

	public boolean isSolid() {
		return true;
	}
}


text:
///<binding ProjectOpened="default" />

// Variables
var del = require("del"),
    exec = require("child_process").exec,
    gulp = require("gulp"),
    path = require("path");

// Tasks
gulp.task("default", ["build", "watch"]);

gulp.task("build", function () {
    return build();
});

gulp.task("compile-typescript", function () {
    return compileTypescript("./tsconfig.json");
});

gulp.task("watch", function () {
    gulp.watch("app/**/*.ts", ["compile-typescript"]);
});

// Functions
function build() {
    return compileAheadOfTime().then(function () {
        return bundle().then(function () {
            return compileTypescript("./tsconfig.json");
        });
    });
}

function bundle() {

    var rollup = require("rollup"),
        alias = require("rollup-plugin-alias"),
        commonjs = require("rollup-plugin-commonjs"),
        nodeResolve = require("rollup-plugin-node-resolve");

    var aliases = {
        "breeze-client": path.resolve(__dirname, "node_modules", "breeze-client/breeze.base.debug.js"),
        "breeze.dataService.odata": path.resolve(__dirname, "node_modules", "breeze-client/breeze.dataService.odata.js"),
        "breeze.modelLibrary.backingStore": path.resolve(__dirname, "node_modules", "breeze-client/breeze.modelLibrary.backingStore.js"),
        "breeze.uriBuilder.odata": path.resolve(__dirname, "node_modules", "breeze-client/breeze.uriBuilder.odata.js")
    };

    return rollup.rollup({
        entry: "./app/boot-aot.js",
        plugins: [
            alias(aliases),
            commonjs({
                namedExports: {
                    "node_modules/breeze-client/breeze.base.debug.js": [
                        "DataService",
                        "EntityManager"
                    ]
                }
            }),
            nodeResolve({ jsnext: true, module: true })
        ]
    })
        .then(function (bundle) {
            return bundle.write({
                format: "iife",
                moduleName: "app",
                dest: "./app/app.js"
            });
        });
}

function compileAheadOfTime() {

    return new Promise(function (resolve, reject) {

        var buildFile = "tsconfig-build-aot.json";

        return del(["aot"]).then(() => {
            return exec("node_modules\\.bin\\ngc -p " + buildFile, function (err, stdout, stderr) {

                console.log(stdout);
                console.log(stderr);

                var compileFile = "tsconfig-compile-aot.json";

                return compileTypescript("./" + compileFile)
                    .then(function () {
                        resolve();
                    });
            });
        });
    });
}

function compileTypescript(projectFile) {
    return new Promise(function (resolve, reject) {
        return exec("node_modules\\.bin\\tsc -p " + projectFile, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            resolve();
        });
    });
}


text:
@implementation AKSampler
{
    NSMutableDictionary *players;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        players = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (NSArray *)trackNames {
    return [players allKeys];
}

- (void)startRecordingToTrack:(NSString *)trackName
{
    [[AKManager sharedManager] startRecordingToURL:[self recordingURLForTrack:trackName]];
}
- (void)stopRecordingToTrack:(NSString *)trackName
{
    [[AKManager sharedManager] stopRecording];

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[self recordingURLForTrack:trackName] error:nil];
    [players setObject:player forKey:trackName];
}

- (void)startPlayingTrack:(NSString *)trackName
{
    if ([[players allKeys] containsObject:trackName]) {
        AVAudioPlayer *player = [players objectForKey:trackName];
        [player play];
    }
}
- (void)stopPlayingTrack:(NSString *)trackName
{
    if ([[players allKeys] containsObject:trackName]) {
        AVAudioPlayer *player = [players objectForKey:trackName];
        [player stop];
        [player setCurrentTime:0];
    }
}

- (NSURL *)recordingURLForTrack:(NSString *)name
{
    NSURL *localDocDirURL = nil;
    if (localDocDirURL == nil) {
        NSString *docDirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        localDocDirURL = [NSURL fileURLWithPath:docDirPath];
    }
    NSString *filename = [NSString stringWithFormat:@"sampler-%@.wav", name];

    return [localDocDirURL URLByAppendingPathComponent:filename];
}

@end


text:
@protocol NavSlotViewDelegate <NSObject>
- (void)slotViewChanged:(id)aNavSlotView;
@end

@interface NavSlotView : NSView

//@property (strong, nonatomic) NavSlot *slot;
@property (assign, nonatomic) id delegate;

- (void)syncFromSlot;
- (void)syncToSlot;

- (void)setSlot:(NavSlot *)aSlot;

@end


text:
using std::string;

using syncer::ModelType;

namespace fake_server {

UniqueClientEntity::~UniqueClientEntity() { }

// static
FakeServerEntity* UniqueClientEntity::Create(
    const sync_pb::SyncEntity& client_entity) {
  DCHECK(client_entity.has_client_defined_unique_tag());
  DCHECK(!client_entity.folder());
  DCHECK(!client_entity.deleted());
  ModelType model_type =
      syncer::GetModelTypeFromSpecifics(client_entity.specifics());
  string id = client_entity.version() == 0 ?
      FakeServerEntity::CreateId(model_type, base::GenerateGUID()) :
      client_entity.id_string();
  return new UniqueClientEntity(id,
                                model_type,
                                client_entity.version(),
                                client_entity.name(),
                                client_entity.client_defined_unique_tag(),
                                client_entity.specifics(),
                                client_entity.ctime(),
                                client_entity.mtime());
}

UniqueClientEntity::UniqueClientEntity(
    const string& id,
    const ModelType& model_type,
    int64 version,
    const string& name,
    const string& client_defined_unique_tag,
    const sync_pb::EntitySpecifics& specifics,
    int64 creation_time,
    int64 last_modified_time)
    : FakeServerEntity(id, model_type, version, name),
      client_defined_unique_tag_(client_defined_unique_tag),
      specifics_(specifics),
      creation_time_(creation_time),
      last_modified_time_(last_modified_time) { }

string UniqueClientEntity::GetParentId() const {
  // Return a dummy value that cannot be a real parent ID. This type should
  // never have parents.
  return string();
}

sync_pb::SyncEntity* UniqueClientEntity::SerializeAsProto() {
  sync_pb::SyncEntity* sync_entity = new sync_pb::SyncEntity();
  FakeServerEntity::SerializeBaseProtoFields(sync_entity);

  sync_pb::EntitySpecifics* specifics = sync_entity->mutable_specifics();
  specifics->CopyFrom(specifics_);

  sync_entity->set_client_defined_unique_tag(client_defined_unique_tag_);
  sync_entity->set_ctime(creation_time_);
  sync_entity->set_mtime(last_modified_time_);

  return sync_entity;
}

bool UniqueClientEntity::IsDeleted() const {
  return false;
}

bool UniqueClientEntity::IsFolder() const {
  return false;
}

}  // namespace fake_server


text:
package net.minidev.ovh.api.hosting.web;

import java.util.Date;
import net.minidev.ovh.api.hosting.web.database.dump.OvhDateEnum;
import net.minidev.ovh.api.hosting.web.database.dump.OvhStatusEnum;

/**
 * Dump
 */
public class OvhDump {
	/**
	 * Source database name
	 *
	 * canBeNull && readOnly
	 */
	public String databaseName;

	/**
	 * Automatic deletion date of the dump
	 *
	 * canBeNull && readOnly
	 */
	public Date deletionDate;

	/**
	 * Dump id
	 *
	 * canBeNull && readOnly
	 */
	public Long id;

	/**
	 * Dump type
	 *
	 * canBeNull && readOnly
	 */
	public OvhDateEnum type;

	/**
	 * If source database was deleted
	 *
	 * canBeNull && readOnly
	 */
	public Boolean orphan;

	/**
	 * Creation date of the dump
	 *
	 * canBeNull && readOnly
	 */
	public Date creationDate;

	/**
	 * Dump url access
	 *
	 * canBeNull && readOnly
	 */
	public String url;

	/**
	 * The task ID working on this dump
	 *
	 * canBeNull && readOnly
	 */
	public Long taskId;

	/**
	 * The dump status
	 *
	 * canBeNull && readOnly
	 */
	public OvhStatusEnum status;
}


text:
#!/usr/bin/env node

var program = require('commander');
var chalk = require('chalk');
var encrypt = require('../lib/encrypt');

program
    .usage('<password> [source-path] [destination-path]')
    .option('-h, --hide', 'hide list');

program.on('--help', function () {
    console.log('  Examples:');
    console.log();
    console.log(chalk.gray('    # encrypt a single file'));
    console.log("    $ safe encrypt 'password' /home/downloads/secret.pdf /home/downloads/secret.safe");
    console.log();
    console.log(chalk.gray('    # encrypt a folder and all files recursively'));
    console.log("    $ safe encrypt 'password' /home/downloads/secret-folder /home/downloads/mydocs.safe");
    console.log();
});

/**
 * Help
 */

var help = function() {
    program.parse(process.argv)
    if (program.args.length < 1) return program.help()
};
help();

/**
 * Settings
 */
var pwd = program.args[0];
var src = program.args[1];
var dst = program.args[2];

/**
 * Run
 */
var run = function() {
    encrypt(pwd, src, dst);
};
run();


text:
class Company < ApplicationRecord
  belongs_to :ceo, foreign_key: 'ceo_id', optional: true, :class_name => 'Employee', autosave: true, counter_cache: true
  has_and_belongs_to_many :employees
  validates :name, presence: true
  before_save :hireCeo

  def hireCeo
    hireEmployee(ceo) if ceo.present?
  end

  def fireEmployee(employee)
    return unless employee.present?
    self.ceo = nil if self.ceo.eql?(employee)
    self.employees.delete(employee)
    self.save
  end

  def hireEmployee(employee)
    return unless employee.present?
    self.employees << employee unless employees.include?(employee)
    self.save
  end
end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Unknown Station</location>
	<station_id>62133</station_id>
	<observation_time>Last Updated on May 14 2015, 2:00 pm MDT</observation_time>
        <observation_time_rfc822>Thu, 14 May 2015 14:00:00 -0600</observation_time_rfc822>
	<wind_string>North at 12.8 MPH (11.08 KT)</wind_string>
	<wind_dir>North</wind_dir>
	<wind_degrees>360</wind_degrees>
	<wind_mph>12.8</wind_mph>
	<wind_gust_mph>0.0</wind_gust_mph>
	<wind_kt>11.08</wind_kt>
	<pressure_string>1018.1 mb</pressure_string>
	<pressure_mb>1018.1</pressure_mb>
	<pressure_tendency_mb>0.8</pressure_tendency_mb>
	<windchill_string>48 F (9 C)</windchill_string>
      	<windchill_f>48</windchill_f>
      	<windchill_c>9</windchill_c>
	<wave_height_m>1.8</wave_height_m>
	<wave_height_ft>5.91</wave_height_ft>
	<mean_wave_dir>Northeast</mean_wave_dir>
	<mean_wave_degrees></mean_wave_degrees>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
import sys, os, asyncore, websocket

if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.stderr.write('usage: %s <message>\n' % os.path.abspath(__file__))
        sys.exit(1)

    ws = websocket.WebSocket('ws://localhost:8080',
                             onopen=lambda: ws.send(sys.argv[1]),
                             onmessage=lambda m: sys.stdout.write('Echo: %s\n' % m),
                             onclose=lambda: sys.stdout.write('Connection closed.\n'))
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        ws.close()


text:
import zRS_util from './zRS_util';
import zRS_core from './zRS_core';

declare type Settings = {
	transition?: string,
	inner?: string,
	slides?: string,
	controls?: Array<HTMLElement>,
	pager?: Array<string> | null,
	delay?: number,
	speed?: number,
	slideBy?: number,
	slideSpacing?: number,
	direction?: string,
	keyboardControls?: boolean,
	alignment?: number | string,
	visibleSlides?: number,
	setVisibleSlides?: null | {[key: number] : number},
	drag?: boolean,
	infinite?: boolean,
	verbose?: boolean,
	freeStyle?: boolean,
	friction?: number
};

declare type Instances = zRS_core | {[key: any] : zRS_core};

class zRS {

	element: string | Array<HTMLElement> | HTMLElement;
	defaults: Settings;
	settings: Settings;
	sliders: boolean | Array<HTMLElement> | HTMLElement;
	instances: Instances;

	static version() {

		return `4.1.10`;

	}

	constructor(element: string | Array<HTMLElement> | HTMLElement, options: {} = {}): Instances {

		this.element = element;
		this.instances = {};
		this.defaults = this.settings = {

			transition: 'fade',
			inner: '.zRS__inner',
			slides: 'zRS__slide',
			controls: [],
			pager: null,
			delay: 5000,
			speed: 750,
			slideBy: 1,
			slideSpacing: 0,
			direction: 'forward',
			keyboardControls: true,
			alignment: 0,
			visibleSlides: 1,
			setVisibleSlides: null,
			drag: true,
			infinite: true,
			verbose: false,
			freeStyle: false,
			friction: 0.35

		};

		this.sliders = zRS_util.findElement(document, this.element);

		if(!this.sliders || this.sliders.length === 0) {

			return;

		}

		this.setOptions(options);
		this.setObjects();

		return this.instances;

	}

	setOptions(update: {}): void {

		if(!update) {

			return;

		}

		if(typeof update !== 'object') {

			zRS_util.log(`Please provide an object for this method`, `warn`);

			return;

		}

		for(let key in this.defaults) {

			if(this.defaults.hasOwnProperty(key)) {

				if(update[key] === undefined) {

					this.settings[key] = this.defaults[key];
					continue;

				}

				this.settings[key] = update[key];

			}

		}

		this.manipulateOptions();

	}

	manipulateOptions(): void {

		if(this.settings.direction === 'reverse') {

			this.settings.slideBy = -Math.abs(this.settings.slideBy);

		}

		if(this.settings.transition === 'fade') {

			this.settings.visibleSlides = 1;

		}

		if(typeof this.settings.alignment === 'string') {

			switch(this.settings.alignment) {

				case 'right' :

					this.settings.alignment = 1;

					break;

				case 'center' :

					this.settings.alignment = 0.5;

					break;

				default :

					this.settings.alignment = 0;

					break;

			}

		}

		if(typeof this.settings.alignment !== 'number') {

			zRS_util.log('Alignment setting needs to be either an int or a string. Transition will not function correctly until rectified.', 'error', this.settings.verbose);

			return;

		}

		this.settings.alignment = Math.min(this.settings.alignment, 1);
		this.settings.alignment = Math.max(this.settings.alignment, 0);

	}

	setObjects(): void {

		if(typeof this.sliders === 'object' && this.sliders.length > 0) {

			for(let i = 0, l = this.sliders.length; i < l; i++) {

				let slider: HTMLElement = this.sliders[i],
					id = slider.getAttribute('id') || i;

				this.instances[id] = new zRS_core(slider, this.settings);

			}

		} else {

			this.instances = new zRS_core(this.sliders, this.settings);

		}

	}

}

export default zRS;


text:
module ImgFlipMemes
  class GonnaHaveABadTime < BaseMeme
    def template_id
      100951
    end

    def text1
      "You're gonna have a bad time"
    end

    def tokenize
      captures = text.match(/#{trigger_word},? (?<text0>.+),? you're gonna have a bad time/i)
      self.captures[:text0] = captures[:text0]
      true
    end
  end
end


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

namespace Chrisguitarguy\RequestId;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * The bundle!
 *
 * @since   1.0
 */
final class ChrisguitarguyRequestIdBundle extends Bundle
{
    // noop
}


text:
package org.elasticsearch.index.reindex.remote;

import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.reindex.ScrollableHitSource;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class RemoteResponseParsersTests extends ESTestCase {

    /**
     * Check that we can parse shard search failures without index information.
     */
    public void testFailureWithoutIndex() throws IOException {
        ShardSearchFailure failure = new ShardSearchFailure(new EsRejectedExecutionException("exhausted"));
        XContentBuilder builder = jsonBuilder();
        builder.startObject();
        failure.toXContent(builder, ToXContent.EMPTY_PARAMS);
        builder.endObject();
        try (XContentParser parser = createParser(builder)) {
            ScrollableHitSource.SearchFailure parsed = RemoteResponseParsers.SEARCH_FAILURE_PARSER.parse(parser, XContentType.JSON);
            assertNotNull(parsed.getReason());
            assertThat(parsed.getReason().getMessage(), Matchers.containsString("exhausted"));
            assertThat(parsed.getReason(), Matchers.instanceOf(EsRejectedExecutionException.class));
        }
    }
}


text:
module Azure::SQL::Mgmt::V2014_04_01
  module Models
    #
    # The response to a list database metrics request.
    #
    class MetricListResult

      include MsRestAzure

      # @return [Array<Metric>] The list of metrics for the database.
      attr_accessor :value

      #
      # Mapper for MetricListResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'MetricListResult',
          type: {
            name: 'Composite',
            class_name: 'MetricListResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: true,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'MetricElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'Metric'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package com.mossle.api.whitelist;

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

public class WhitelistDTO {
    private String name;
    private String description;
    private List<String> hosts = new ArrayList<String>();
    private List<String> ips = new ArrayList<String>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<String> getHosts() {
        return hosts;
    }

    public void setHosts(List<String> hosts) {
        this.hosts = hosts;
    }

    public List<String> getIps() {
        return ips;
    }

    public void setIps(List<String> ips) {
        this.ips = ips;
    }

    // ~ ==================================================
    public boolean notValidHost(String host) {
        return !hosts.contains(host);
    }

    public boolean notValidIp(String ip) {
        return !ips.contains(ip);
    }

    public void addHosts(List<String> list) {
        this.hosts.addAll(list);
    }

    public void addIps(List<String> list) {
        this.ips.addAll(list);
    }
}


text:
<?php

namespace FFMpeg\Filters\Video;

use FFMpeg\Coordinate\Point;
use FFMpeg\Media\Video;
use FFMpeg\Coordinate\TimeCode;
use FFMpeg\Coordinate\Dimension;
use FFMpeg\Coordinate\FrameRate;
use FFMpeg\Filters\Audio\AudioResamplableFilter;
use FFMpeg\Filters\Audio\AudioFilters;

/**
 * Class VideoFilters
 *
 * @package FFMpeg\Filters\Video
 */
class VideoFilters extends AudioFilters
{
    /**
     * @param \FFMpeg\Media\Video $media
     */
    public function __construct(Video $media)
    {
        parent::__construct($media);
    }

    /**
     * Resizes a video to a given dimension.
     *
     * @param Dimension $dimension
     * @param string    $mode
     * @param Boolean   $forceStandards
     *
     * @return VideoFilters
     */
    public function resize(Dimension $dimension, $mode = ResizeFilter::RESIZEMODE_FIT, $forceStandards = true)
    {
        $this->media->addFilter(new ResizeFilter($dimension, $mode, $forceStandards));

        return $this;
    }

    /**
     * Changes the video framerate.
     *
     * @param FrameRate $framerate
     * @param integer   $gop
     *
     * @return VideoFilters
     */
    public function framerate(FrameRate $framerate, $gop)
    {
        $this->media->addFilter(new FrameRateFilter($framerate, $gop));

        return $this;
    }

    /**
     * Synchronizes audio and video.
     *
     * @return VideoFilters
     */
    public function synchronize()
    {
        $this->media->addFilter(new SynchronizeFilter());

        return $this;
    }

    /**
     * Clips (cuts) the video.
     *
     * @param TimeCode $start
     * @param TimeCode $duration
     *
     * @return VideoFilters
     */
    public function clip($start, $duration = null)
    {
        $this->media->addFilter(new ClipFilter($start, $duration));

        return $this;
    }

    /**
     * Resamples the audio file.
     *
     * @param Integer $rate
     *
     * @return AudioFilters
     */
    public function audioResample($rate)
    {
        $this->media->addFilter(new AudioResamplableFilter($rate));

        return $this;
    }

    /**
     * @param string $angle
     *
     * @return $this
     */
    public function rotate($angle)
    {
        $this->media->addFilter(new RotateFilter($angle, 30));

        return $this;
    }

    /**
     * Crops the video
     *
     * @param Point     $point
     * @param Dimension $dimension
     *
     * @return VideoFilters
     */
    public function crop(Point $point, Dimension $dimension)
    {
        $this->media->addFilter(new CropFilter($point, $dimension));

        return $this;
    }

    /**
     * @param string $imagePath
     * @param array  $coordinates
     *
     * @return $this
     */
    public function watermark($imagePath, array $coordinates = [])
    {
        $this->media->addFilter(new WatermarkFilter($imagePath, $coordinates));

        return $this;
    }

    /**
     * Synchronizes audio and video.
     *
     * @return VideoFilters
     */
    public function fastStart()
    {
        $this->media->addFilter(new PrepareForWebFilter());

        return $this;
    }

    /**
     * Prepend a movie to current video
     *
     * @param string $videoPath
     *
     * @return \FFMpeg\Filters\Video\VideoFilters
     */
    public function concat($videoPath)
    {
        $this->media->addFilter(new ConcatFilter($videoPath));

        return $this;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical"
    tools:context="com.dly.hfut.SettingActivity">

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:id="@+id/setting_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerInParent="true"
                        android:text="@string/setting"
                        android:textColor="#fff"
                        android:textSize="20sp" />

                </RelativeLayout>
            </android.support.v7.widget.Toolbar>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="180dp"
                    android:background="@color/colorPrimary"
                    android:padding="10dp">

                    <de.hdodenhof.circleimageview.CircleImageView
                        android:id="@+id/icon_image"
                        android:layout_width="70dp"
                        android:layout_height="70dp"
                        android:layout_centerInParent="true"
                        android:src="@drawable/andy" />

                    <TextView
                        android:id="@+id/username"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_above="@+id/dept"
                        android:layout_centerHorizontal="true"
                        android:text="杜琳义"
                        android:textColor="#FFF"
                        android:textSize="14sp" />

                    <TextView
                        android:id="@+id/dept"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_centerHorizontal="true"
                        android:text="计算机13-2班"
                        android:textColor="#FFF"
                        android:textSize="14sp" />

                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:layout_margin="10dp">

                    <TextView
                        android:id="@+id/week_appear"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_centerVertical="true"
                        android:layout_marginStart="30dp"
                        android:text="@string/week_appear"
                        android:textColor="#000"
                        android:textSize="18sp" />

                    <Switch
                        android:id="@+id/swi_week"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginStart="70dp"
                        android:layout_toEndOf="@id/week_appear" />

                </RelativeLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="0.5dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginStart="10dp"
                    android:background="@color/colorPrimary" />

                <RelativeLayout
                    android:id="@+id/celar_cache_rela"
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:layout_margin="10dp"
                    android:clickable="true">

                    <TextView
                        android:id="@+id/clear_cache"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_centerVertical="true"
                        android:layout_marginStart="30dp"
                        android:text="@string/cache_clear"
                        android:textColor="#000"
                        android:textSize="18sp" />
                </RelativeLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="0.5dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginStart="10dp"
                    android:background="@color/colorPrimary" />

                <RelativeLayout
                    android:id="@+id/about_rela"
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:layout_margin="10dp"
                    android:clickable="true">

                    <TextView
                        android:id="@+id/about"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_centerVertical="true"
                        android:layout_marginStart="30dp"
                        android:clickable="true"
                        android:text="@string/app_about"
                        android:textColor="#000"
                        android:textSize="18sp" />
                </RelativeLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="0.5dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginStart="10dp"
                    android:background="@color/colorPrimary" />

            </LinearLayout>

        </LinearLayout>

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/nav_menu" />

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>


text:
package org.apache.activemq.artemis.core.protocol.stomp;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.zip.Inflater;

import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.message.BodyEncoder;
import org.apache.activemq.artemis.core.message.impl.MessageImpl;
import org.apache.activemq.artemis.core.persistence.OperationContext;
import org.apache.activemq.artemis.core.persistence.StorageManager;
import org.apache.activemq.artemis.core.persistence.impl.journal.LargeServerMessageImpl;
import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
import org.apache.activemq.artemis.core.server.LargeServerMessage;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.ServerConsumer;
import org.apache.activemq.artemis.core.server.ServerMessage;
import org.apache.activemq.artemis.core.server.ServerSession;
import org.apache.activemq.artemis.core.server.impl.ServerMessageImpl;
import org.apache.activemq.artemis.core.server.impl.ServerSessionImpl;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.activemq.artemis.spi.core.protocol.SessionCallback;
import org.apache.activemq.artemis.spi.core.remoting.ReadyListener;
import org.apache.activemq.artemis.utils.ByteUtil;
import org.apache.activemq.artemis.utils.ConfigurationHelper;
import org.apache.activemq.artemis.utils.PendingTask;
import org.apache.activemq.artemis.utils.UUIDGenerator;

import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE;

public class StompSession implements SessionCallback {

   private final StompProtocolManager manager;

   private final StompConnection connection;

   private ServerSession session;

   private final OperationContext sessionContext;

   private final BlockingDeque<PendingTask> afterDeliveryTasks = new LinkedBlockingDeque<>();

   private final Map<Long, StompSubscription> subscriptions = new ConcurrentHashMap<>();

   // key = message ID, value = consumer ID
   private final Map<Long, Pair<Long, Integer>> messagesToAck = new ConcurrentHashMap<>();

   private volatile boolean noLocal = false;

   private final int consumerCredits;

   StompSession(final StompConnection connection, final StompProtocolManager manager, OperationContext sessionContext) {
      this.connection = connection;
      this.manager = manager;
      this.sessionContext = sessionContext;
      this.consumerCredits = ConfigurationHelper.getIntProperty(TransportConstants.STOMP_CONSUMERS_CREDIT, TransportConstants.STOMP_DEFAULT_CONSUMERS_CREDIT, connection.getAcceptorUsed().getConfiguration());
   }

   @Override
   public boolean isWritable(ReadyListener callback) {
      return connection.isWritable(callback);
   }

   void setServerSession(ServerSession session) {
      this.session = session;
   }

   public ServerSession getSession() {
      return session;
   }

   @Override
   public boolean hasCredits(ServerConsumer consumerID) {
      return true;
   }

   @Override
   public void sendProducerCreditsMessage(int credits, SimpleString address) {
   }

   @Override
   public void sendProducerCreditsFailMessage(int credits, SimpleString address) {
   }

   @Override
   public void afterDelivery() throws Exception {
      PendingTask task;
      while ((task = afterDeliveryTasks.poll()) != null) {
         task.run();
      }
   }

   @Override
   public void browserFinished(ServerConsumer consumer) {

   }

   @Override
   public boolean updateDeliveryCountAfterCancel(ServerConsumer consumer, MessageReference ref, boolean failed) {
      return false;
   }

   @Override
   public int sendMessage(MessageReference ref, ServerMessage serverMessage, final ServerConsumer consumer, int deliveryCount) {
      LargeServerMessageImpl largeMessage = null;
      ServerMessage newServerMessage = serverMessage;
      try {
         StompSubscription subscription = subscriptions.get(consumer.getID());
         StompFrame frame = null;
         if (serverMessage.isLargeMessage()) {
            newServerMessage = serverMessage.copy();

            largeMessage = (LargeServerMessageImpl) serverMessage;
            BodyEncoder encoder = largeMessage.getBodyEncoder();
            encoder.open();
            int bodySize = (int) encoder.getLargeBodySize();

            //large message doesn't have a body.
            ((ServerMessageImpl) newServerMessage).createBody(bodySize);
            encoder.encode(newServerMessage.getBodyBuffer(), bodySize);
            encoder.close();
         }

         if (serverMessage.getBooleanProperty(Message.HDR_LARGE_COMPRESSED)) {
            //decompress
            ActiveMQBuffer qbuff = newServerMessage.getBodyBuffer();
            int bytesToRead = qbuff.writerIndex() - MessageImpl.BODY_OFFSET;
            Inflater inflater = new Inflater();
            inflater.setInput(ByteUtil.getActiveArray(qbuff.readBytes(bytesToRead).toByteBuffer()));

            //get the real size of large message
            long sizeBody = newServerMessage.getLongProperty(Message.HDR_LARGE_BODY_SIZE);

            byte[] data = new byte[(int) sizeBody];
            inflater.inflate(data);
            inflater.end();
            qbuff.resetReaderIndex();
            qbuff.resetWriterIndex();
            qbuff.writeBytes(data);
         }

         frame = connection.createStompMessage(newServerMessage, subscription, deliveryCount);

         int length = frame.getEncodedSize();

         if (subscription.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) {
            if (manager.send(connection, frame)) {
               final long messageID = newServerMessage.getMessageID();
               final long consumerID = consumer.getID();

               // this will be called after the delivery is complete
               // we can't call sesison.ack within the delivery
               // as it could dead lock.
               afterDeliveryTasks.offer(new PendingTask() {
                  @Override
                  public void run() throws Exception {
                     //we ack and commit only if the send is successful
                     session.acknowledge(consumerID, messageID);
                     session.commit();
                  }
               });
            }
         }
         else {
            messagesToAck.put(newServerMessage.getMessageID(), new Pair<>(consumer.getID(), length));
            // Must send AFTER adding to messagesToAck - or could get acked from client BEFORE it's been added!
            manager.send(connection, frame);
         }

         return length;
      }
      catch (Exception e) {
         if (ActiveMQStompProtocolLogger.LOGGER.isDebugEnabled()) {
            ActiveMQStompProtocolLogger.LOGGER.debug(e);
         }
         return 0;
      }
      finally {
         if (largeMessage != null) {
            largeMessage.releaseResources();
            largeMessage = null;
         }
      }

   }

   @Override
   public int sendLargeMessageContinuation(ServerConsumer consumer,
                                           byte[] body,
                                           boolean continues,
                                           boolean requiresResponse) {
      return 0;
   }

   @Override
   public int sendLargeMessage(MessageReference ref, ServerMessage msg, ServerConsumer consumer, long bodySize, int deliveryCount) {
      return 0;
   }

   @Override
   public void closed() {
   }

   @Override
   public void disconnect(ServerConsumer consumerId, String queueName) {
      StompSubscription stompSubscription = subscriptions.remove(consumerId.getID());
      if (stompSubscription != null) {
         StompFrame frame = connection.getFrameHandler().createStompFrame(Stomp.Responses.ERROR);
         frame.addHeader(Stomp.Headers.CONTENT_TYPE, "text/plain");
         frame.setBody("consumer with ID " + consumerId + " disconnected by server");
         connection.sendFrame(frame);
      }
   }

   public void acknowledge(String messageID, String subscriptionID) throws Exception {
      long id = Long.parseLong(messageID);
      Pair<Long, Integer> pair = messagesToAck.remove(id);

      if (pair == null) {
         throw BUNDLE.failToAckMissingID(id).setHandler(connection.getFrameHandler());
      }

      long consumerID = pair.getA();
      int credits = pair.getB();

      StompSubscription sub = subscriptions.get(consumerID);

      if (subscriptionID != null) {
         if (!sub.getID().equals(subscriptionID)) {
            throw BUNDLE.subscriptionIDMismatch(subscriptionID, sub.getID()).setHandler(connection.getFrameHandler());
         }
      }

      if (this.consumerCredits != -1) {
         session.receiveConsumerCredits(consumerID, credits);
      }

      if (sub.getAck().equals(Stomp.Headers.Subscribe.AckModeValues.CLIENT_INDIVIDUAL)) {
         session.individualAcknowledge(consumerID, id);
      }
      else {
         session.acknowledge(consumerID, id);
      }

      session.commit();
   }

   public void addSubscription(long consumerID,
                               String subscriptionID,
                               String clientID,
                               String durableSubscriptionName,
                               String destination,
                               String selector,
                               String ack) throws Exception {
      SimpleString queueName = SimpleString.toSimpleString(destination);
      boolean pubSub = false;
      int receiveCredits = consumerCredits;
      if (ack.equals(Stomp.Headers.Subscribe.AckModeValues.AUTO)) {
         receiveCredits = -1;
      }

      if (destination.startsWith("jms.topic")) {
         // subscribes to a topic
         pubSub = true;
         if (durableSubscriptionName != null) {
            if (clientID == null) {
               throw BUNDLE.missingClientID();
            }
            queueName = SimpleString.toSimpleString(clientID + "." + durableSubscriptionName);
            if (manager.getServer().locateQueue(queueName) == null) {
               session.createQueue(SimpleString.toSimpleString(destination), queueName, SimpleString.toSimpleString(selector), false, true);
            }
         }
         else {
            queueName = UUIDGenerator.getInstance().generateSimpleStringUUID();
            session.createQueue(SimpleString.toSimpleString(destination), queueName, SimpleString.toSimpleString(selector), true, false);
         }
         session.createConsumer(consumerID, queueName, null, false, false, receiveCredits);
      }
      else {
         session.createConsumer(consumerID, queueName, SimpleString.toSimpleString(selector), false, false, receiveCredits);
      }

      StompSubscription subscription = new StompSubscription(subscriptionID, ack, queueName, pubSub);
      subscriptions.put(consumerID, subscription);

      session.start();
   }

   public boolean unsubscribe(String id, String durableSubscriptionName, String clientID) throws Exception {
      boolean result = false;
      Iterator<Entry<Long, StompSubscription>> iterator = subscriptions.entrySet().iterator();

      while (iterator.hasNext()) {
         Map.Entry<Long, StompSubscription> entry = iterator.next();
         long consumerID = entry.getKey();
         StompSubscription sub = entry.getValue();
         if (id != null && id.equals(sub.getID())) {
            iterator.remove();
            SimpleString queueName = sub.getQueueName();
            session.closeConsumer(consumerID);
            if (sub.isPubSub() && manager.getServer().locateQueue(queueName) != null) {
               session.deleteQueue(queueName);
            }
            result = true;
         }
      }

      if (!result && durableSubscriptionName != null && clientID != null) {
         SimpleString queueName = SimpleString.toSimpleString(clientID + "." + durableSubscriptionName);
         if (manager.getServer().locateQueue(queueName) != null) {
            session.deleteQueue(queueName);
         }
         result = true;
      }

      return result;
   }

   boolean containsSubscription(String subscriptionID) {
      for (Entry<Long, StompSubscription> entry : subscriptions.entrySet()) {
         StompSubscription sub = entry.getValue();
         if (sub.getID().equals(subscriptionID)) {
            return true;
         }
      }
      return false;
   }

   public RemotingConnection getConnection() {
      return connection;
   }

   public OperationContext getContext() {
      return sessionContext;
   }

   public boolean isNoLocal() {
      return noLocal;
   }

   public void setNoLocal(boolean noLocal) {
      this.noLocal = noLocal;
   }

   public void sendInternal(ServerMessageImpl message, boolean direct) throws Exception {
      session.send(message, direct);
   }

   public void sendInternalLarge(ServerMessageImpl message, boolean direct) throws Exception {
      int headerSize = message.getHeadersAndPropertiesEncodeSize();
      if (headerSize >= connection.getMinLargeMessageSize()) {
         throw BUNDLE.headerTooBig();
      }

      StorageManager storageManager = ((ServerSessionImpl) session).getStorageManager();
      long id = storageManager.generateID();
      LargeServerMessage largeMessage = storageManager.createLargeMessage(id, message);

      byte[] bytes = new byte[message.getBodyBuffer().writerIndex() - MessageImpl.BODY_OFFSET];
      message.getBodyBuffer().readBytes(bytes);

      largeMessage.addBytes(bytes);

      largeMessage.releaseResources();

      largeMessage.putLongProperty(Message.HDR_LARGE_BODY_SIZE, bytes.length);

      session.send(largeMessage, direct);

      largeMessage = null;
   }

}


text:
name: CreateLocalGitHubRepository
last_update: 2016-05-26
 .left-column[
  ### Local GitHub Repo

No manual input required here.

.footnote[.red.bold[] [
Table of Contents](./toc.html)

   Last update

    {{ last_update  }}
]
]
.right-column[
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ - o 0 o - ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
#### Create our **local** GitHub repository.
In this step we :
 -  initialize a local .git repository
 -  add all the files to the local repo and commit
 -  establish our GitHub project as the remote repository
 -  push our new files to GitHub

**This step is NOT idempotent.**  If you have already pushed to GitHub you might get errors. If so, eliminate the project from GitHub and run this step again. *Also note : SSH may ask you to confirm GitHub's PK fingerprint.*

##### Example Commands
```terminal
git init
git add .
git commit -am 'First commit'
git remote add ${PROJECT_NAME}_origin git@github-${GITHUB_ORGANIZATION_NAME}-${PROJECT_NAME}:${GITHUB_ORGANIZATION_NAME}/${PROJECT_NAME}.git
git push -u ${PROJECT_NAME}_origin master
```

.center[.footnote[.red.bold[] Code for this step.] ]
]


text:
import React, {PureComponent} from 'react'
import {connect} from 'react-redux'
import {withRouter, RouteComponentProps} from 'react-router-dom'
import {isEmpty} from 'lodash'

// Components
import {Sort, ComponentSize, EmptyState} from '@influxdata/clockface'
import SearchWidget from 'src/shared/components/search_widget/SearchWidget'
import TokenList from 'src/authorizations/components/TokenList'
import FilterList from 'src/shared/components/FilterList'
import TabbedPageHeader from 'src/shared/components/tabbed_page/TabbedPageHeader'
import GenerateTokenDropdown from 'src/authorizations/components/GenerateTokenDropdown'
import ResourceSortDropdown from 'src/shared/components/resource_sort_dropdown/ResourceSortDropdown'

// Types
import {AppState, Authorization, ResourceType} from 'src/types'
import {SortTypes} from 'src/shared/utils/sort'

// Selectors
import {getAll} from 'src/resources/selectors'

enum AuthSearchKeys {
  Description = 'description',
  Status = 'status',
  CreatedAt = 'createdAt',
}

interface State {
  searchTerm: string
  sortKey: SortKey
  sortDirection: Sort
  sortType: SortTypes
}

interface StateProps {
  tokens: Authorization[]
}

type SortKey = keyof Authorization

type Props = StateProps & RouteComponentProps<{orgID: string}>

const FilterAuthorizations = FilterList<Authorization>()

class TokensTab extends PureComponent<Props, State> {
  constructor(props) {
    super(props)
    this.state = {
      searchTerm: '',
      sortKey: 'description',
      sortDirection: Sort.Ascending,
      sortType: SortTypes.String,
    }
  }

  public render() {
    const {searchTerm, sortKey, sortDirection, sortType} = this.state
    const {tokens} = this.props

    const leftHeaderItems = (
      <>
        <SearchWidget
          searchTerm={searchTerm}
          placeholderText="Filter Tokens..."
          onSearch={this.handleChangeSearchTerm}
          testID="input-field--filter"
        />
        <ResourceSortDropdown
          resourceType={ResourceType.Authorizations}
          sortDirection={sortDirection}
          sortKey={sortKey}
          sortType={sortType}
          onSelect={this.handleSort}
          width={238}
        />
      </>
    )

    const rightHeaderItems = <GenerateTokenDropdown />

    return (
      <>
        <TabbedPageHeader
          childrenLeft={leftHeaderItems}
          childrenRight={rightHeaderItems}
        />
        <FilterAuthorizations
          list={tokens}
          searchTerm={searchTerm}
          searchKeys={this.searchKeys}
        >
          {filteredAuths => (
            <TokenList
              auths={filteredAuths}
              emptyState={this.emptyState}
              searchTerm={searchTerm}
              sortKey={sortKey}
              sortDirection={sortDirection}
              sortType={sortType}
              onClickColumn={this.handleClickColumn}
            />
          )}
        </FilterAuthorizations>
      </>
    )
  }

  private handleSort = (
    sortKey: SortKey,
    sortDirection: Sort,
    sortType: SortTypes
  ): void => {
    this.setState({sortKey, sortDirection, sortType})
  }

  private handleClickColumn = (nextSort: Sort, sortKey: SortKey) => {
    const sortType = SortTypes.String
    this.setState({sortKey, sortDirection: nextSort, sortType})
  }

  private handleChangeSearchTerm = (searchTerm: string): void => {
    this.setState({searchTerm})
  }

  private get searchKeys(): AuthSearchKeys[] {
    return [
      AuthSearchKeys.Status,
      AuthSearchKeys.Description,
      AuthSearchKeys.CreatedAt,
    ]
  }

  private get emptyState(): JSX.Element {
    const {searchTerm} = this.state

    if (isEmpty(searchTerm)) {
      return (
        <EmptyState size={ComponentSize.Large}>
          <EmptyState.Text>
            Looks like there aren't any <b>Tokens</b>, why not generate one?
          </EmptyState.Text>
          <GenerateTokenDropdown />
        </EmptyState>
      )
    }

    return (
      <EmptyState size={ComponentSize.Large}>
        <EmptyState.Text>No Tokens match your query</EmptyState.Text>
      </EmptyState>
    )
  }
}

const mstp = (state: AppState) => ({
  tokens: getAll<Authorization>(state, ResourceType.Authorizations),
})

export default connect<StateProps>(mstp)(withRouter(TokensTab))


text:
layout: post
date: 2016-06-11
title: "Jovani Sheer Crystal Embellished Gown 99054 Sleeveless Sweep/Brush Train Mermaid/Trumpet"
category: Jovani
tags: [Jovani ,Jovani,Mermaid/Trumpet,Illusion,Sweep/Brush Train,Sleeveless]
---
### Jovani Sheer Crystal Embellished Gown 99054
Just **$518.98**
###   Sleeveless Sweep/Brush Train Mermaid/Trumpet

BRANDS	Jovani

Silhouette	Mermaid/Trumpet

Neckline	Illusion

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/jovani-/39445-jovani-sheer-crystal-embellished-gown-99054.html](https://www.readybrides.com/en/jovani-/39445-jovani-sheer-crystal-embellished-gown-99054.html)


text:
export * from './emitters';
export * from './forces';
export * from './generators';
export * from './constraints';
export * from './Tw2ParticleSystem';
export * from './Tw2ParticleElement';


text:
int main( ){
	ofGLFWWindowSettings msettings;
	msettings.setSize(1024, 768);
	msettings.numSamples = 0;
	msettings.monitor = 0;
	msettings.windowMode = OF_FULLSCREEN;
	auto mainWin = ofCreateWindow(msettings);

	auto app = make_shared<ofApp>();
	ofRunApp(mainWin, app);
	ofRunMainLoop();

}


text:
import { Mongo } from 'meteor/mongo';

const SavedResult  = new Mongo.Collection('savedresult');
SavedResult.schema = new SimpleSchema ({
  randomString: {
    type: String,
  },
  filteredResult: {
    type: [results_obj],
    blackbox: true,
  },
});
const results_obj={
  id: { type: String },
};

SavedResult.attachSchema(SavedResult.schema)

export default SavedResult;


text: KingConquest Plugin


text:
{% load i18n %}
{% load get_thumbnail from product_images %}
{% load placeholder %}
{% load price from taxed_prices %}
{% load static %}

  {% if quantity > 0 %}
    <div id="checkout-preview-dropdown-list" class="checkout-preview-dropdown__list{% if lines|length <= 2 %} overflow{% endif %}">
    {% for line in lines %}

              {{ line.product.translated }}
              x{{ line.quantity }}

{{ line.variant.translated }}

              {% price line.line_total %}

    {% endfor %}

          {% trans "Subtotal" context "Order subtotal" %}

          {% trans "Shipment and taxes calculated at checkout" context "Checkout dropdown text" %}

        <h3 class="float-md-right price {% if lines|length <= 2 %}single{% endif %}" data-quantity="{{ quantity }}">

            {% price total %}

        {% trans "Go to checkout" context "Checkout dropdown secondary action" %}

        {% trans "Checkout" context "Checkout dropdown primary action" %}

  {% else %}

{% trans "There are no products in your shopping checkout." context "Empty checkout message" %}

      {% trans "Check out our sales" context "Empty checkout link" %}

  {% endif %}