text:
from __future__ import unicode_literals
import json

from moto.core.responses import BaseResponse
from .models import organizations_backend

class OrganizationsResponse(BaseResponse):

    @property
    def organizations_backend(self):
        return organizations_backend

    @property
    def request_params(self):
        try:
            return json.loads(self.body)
        except ValueError:
            return {}

    def _get_param(self, param, default=None):
        return self.request_params.get(param, default)

    def create_organization(self):
        return json.dumps(
            self.organizations_backend.create_organization(**self.request_params)
        )

    def describe_organization(self):
        return json.dumps(
            self.organizations_backend.describe_organization()
        )

    def list_roots(self):
        return json.dumps(
            self.organizations_backend.list_roots()
        )

    def create_organizational_unit(self):
        return json.dumps(
            self.organizations_backend.create_organizational_unit(**self.request_params)
        )

    def describe_organizational_unit(self):
        return json.dumps(
            self.organizations_backend.describe_organizational_unit(**self.request_params)
        )

    def list_organizational_units_for_parent(self):
        return json.dumps(
            self.organizations_backend.list_organizational_units_for_parent(**self.request_params)
        )

    def list_parents(self):
        return json.dumps(
            self.organizations_backend.list_parents(**self.request_params)
        )

    def create_account(self):
        return json.dumps(
            self.organizations_backend.create_account(**self.request_params)
        )

    def describe_account(self):
        return json.dumps(
            self.organizations_backend.describe_account(**self.request_params)
        )

    def list_accounts(self):
        return json.dumps(
            self.organizations_backend.list_accounts()
        )

    def list_accounts_for_parent(self):
        return json.dumps(
            self.organizations_backend.list_accounts_for_parent(**self.request_params)
        )

    def move_account(self):
        return json.dumps(
            self.organizations_backend.move_account(**self.request_params)
        )

    def list_children(self):
        return json.dumps(
            self.organizations_backend.list_children(**self.request_params)
        )


text:
$LOAD_PATH.unshift(File.dirname(File.realpath(__FILE__)) + '/../lib')

# Internal dependencies
require 'cogwheels/version'

# Cogwheels allows YAML configuration files to be loaded into Configuration
# instances for ease of use
#
# Cogwheels is licensed under the MIT license:
#
# Copyright (c) 2016 Christopher Lutz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
module Cogwheels
  autoload :Configuration, 'cogwheels/configuration'
  autoload :Loader, 'cogwheels/loader'
  autoload :Writer, 'cogwheels/writer'

  module_function

  def load(src, mutable = true)
    Cogwheels::Loader.load(src, mutable)
  end
end

redpajama_set_name: RedPajamaGithub


text:
#ifndef MSLIBS_DOTCONF_TREE_TEST_PERSON_INC_
#define MSLIBS_DOTCONF_TREE_TEST_PERSON_INC_
// =======================================================================
// Project:     dotconf
// Component:   libs/tree/test
// Copyright (C) 2004-2014 Алексей Бадяев
// Begin of module: libs/tree/test/person.hpp
// ==###==================================================================
/**
 * @file
 * @ingroup mslibs_dotconf_tree_test
 * @brief Определение типа Person
 */

#include "string.hpp"           // String_t
    // boost
#include "boost/shared_ptr.hpp" // boost::shared_ptr
#include "boost/operators.hpp"  // boost::equality_comparable
    // std
#include <ostream>              // std::ostream

//////////////////////////////////////////////////////////////////////////

namespace dotconf
{
/**
 * @addtogroup mslibs_dotconf_tree_test
 * @{
 */
/*----------------------------------------------------------------------*/

/**
 * @struct Person
 * @brief Информация о человеке
 */
struct Person ;

    /// Тип указателя на персону
typedef boost::shared_ptr< Person > PersonPtr_t ;

struct Person
    : private boost::equality_comparable< Person >
{
        /// Идентификатор человека
    unsigned    id ;
        /// Имя человека
    String_t    firstName ;
        /// Фамилия человека
    String_t    secondName ;
        /**
         * @brief Конструктор
         * @param id_arg Идентификатор человека
         * @param fname  Имя человека
         * @param sname  Фамилия человека
         */
    Person( unsigned id_arg  = 0
          , String_t fname   = "FirstName"
          , String_t sname   = "SecondName"
          )
          : id         ( id_arg )
          , firstName  ( fname )
          , secondName ( sname )
    { }
}; // struct Person

/*----------------------------------------------------------------------*/

/**
 * @brief Оператор сравнения записей о двух людях на равенство
 * @param pers1 Ссылка на информацию о первом человеке
 * @param pers2 Ссылка на информацию о втором человеке
 * @return Истина, если идентификаторы записей о людях равны между собой
 */
inline bool
operator ==( const Person & pers1 , const Person & pers2 )
{
    return pers1.id == pers2.id;
}

/**
 * @brief Оператор сравнения записей о двух людях на равенство
 * @param pers1_ptr Указатель на информацию о первом человеке
 * @param pers2_ptr Указатель на информацию о втором человеке
 * @return Истина, если идентификаторы записей о людях равны между собой
 */
inline
bool
operator ==( const PersonPtr_t & pers1_ptr , const PersonPtr_t & pers2_ptr )
{
    return (* pers1_ptr) == (* pers2_ptr);
}

/*----------------------------------------------------------------------*/

/**
 * @brief Оператор вывода информации о человеке в стандартный поток
 * @tparam CharT Тип символов потока вывода
 * @tparam CharTraits Тип свойств символов потока вывода
 * @param [in,out] stream Ссылка на стандартный поток вывода
 * @param person Ссылка на информацию о человеке
 * @return Ссылка на стандартный поток @c stream
 */
template< typename CharT , class CharTraits >
inline
std::basic_ostream< CharT , CharTraits > &
operator <<( std::basic_ostream< CharT , CharTraits > & stream
           , const Person &                             person
           )
{
    return stream << '[' << person.id
                  << ':' << person.firstName
                  << ' ' << person.secondName
                  << ']'
                  ;
}

/**
 * @brief Оператор вывода информации о человеке в стандартный поток
 * @tparam CharT Тип символов потока вывода
 * @tparam CharTraits Тип свойств символов потока вывода
 * @param [in,out] stream Ссылка на стандартный поток вывода
 * @param person_ptr Указатель на информацию о человеке
 * @return Ссылка на стандартный поток @c stream
 */
template< typename CharT , class CharTraits >
inline
std::basic_ostream< CharT , CharTraits > &
operator <<( std::basic_ostream< CharT , CharTraits > & stream
           , const PersonPtr_t &                        person_ptr
           )
{
    return stream << "PersonPtr_t->" << *person_ptr ;
}

/*----------------------------------------------------------------------*/

/**
 * @brief Оператор ввода информации о человеке их стандартного потока
 * @tparam CharT Тип символов потока ввода
 * @tparam CharTraits Тип свойств символов потока ввода
 * @param [in,out] stream Ссылка на стандартный поток ввода
 * @param person Ссылка на информацию о человеке
 * @return Ссылка на стандартный поток @c stream
 */
template< typename CharT , class CharTraits >
inline
std::basic_istream< CharT , CharTraits > &
operator >>( std::basic_istream< CharT , CharTraits > & stream
           , Person &                                   person
           )
{
    typedef std::basic_istream< CharT , CharTraits > Stream_t ;
    CharT ch ;
    stream.get( ch );
    if( '[' != ch )
        stream.setsate( Stream_t::failbit );
    stream >> person.id ;
    stream.get( ch );
    if( ':' != ch )
        stream.setsate( Stream_t::failbit );
    stream >> person.firstName >> person.secondName ;
    stream.get( ch );
    if( ']' != ch )
        stream.setsate( Stream_t::failbit );
    return stream ;
}

/*----------------------------------------------------------------------*/

/** @} */

} // namespace dotconf

// ==###==================================================================
// End of module: libs/tree/test/person.hpp
// =======================================================================
#endif // MSLIBS_DOTCONF_TREE_TEST_PERSON_INC_


text:
ERREUR 404

        lock_outline Oups.. La page que vous demandez n'existe pas, il se peut qu'elle est été déplacée ou supprimée. Cliquez <a href="<?php echo base_url(); ?>" rel="home" style="color:white!important">ici pour revenir sur la page d'accueil.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

     Copyright 2005-2014 Red Hat, Inc.

     Red Hat licenses this file to you under the Apache License, version
     2.0 (the "License"); you may not use this file except in compliance
     with the License.  You may obtain a copy of the License at

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

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
     implied.  See the License for the specific language governing
     permissions and limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.fusesource</groupId>
        <artifactId>fuse-project</artifactId>
        <version>6.2.0.redhat-SNAPSHOT</version>
        <relativePath>../../parent</relativePath>
    </parent>
    <groupId>io.fabric8.support</groupId>
    <artifactId>support-project</artifactId>
    <packaging>pom</packaging>

    <name>JBoss Fuse :: Support</name>
    <description>Tooling for support</description>

    <dependencies>
    </dependencies>

    <modules>
        <module>support-core</module>
        <module>support-commands</module>
        <module>support-karaf</module>
        <module>hawtio-plugin-redhat-access</module>
        <module>support-features</module>
        <!--temporary, until the jar will be published on some maven repo-->
        <module>redhat-support-lib-java</module>
        <module>support-webapp</module>
        <module>support-profiles</module>
    </modules>

</project>


text:
/**
 * Radio button widget
 * the inputs are value and a selected value
 *
 */
goog.provide('recoil.ui.widgets.RadioWidget');

goog.require('goog.dom');
goog.require('goog.ui.Container');
goog.require('recoil.ui.ComponentWidgetHelper');
goog.require('recoil.ui.Widget');
goog.require('recoil.ui.WidgetScope');
goog.require('recoil.ui.message.Message');
goog.require('recoil.ui.messages');

/**
 *
 * @template T
 * @param {!recoil.ui.WidgetScope} scope
 * @implements {recoil.ui.Widget}
 * @constructor
 */
recoil.ui.widgets.RadioWidget = function(scope) {
    this.scope_ = scope;
    this.radio_ = null;

    var toControl = recoil.ui.ComponentWidgetHelper.elementToControl;
    this.container_ = new goog.ui.Component();
    this.radio_ = goog.dom.createDom('input', {type: 'radio', autocomplete: 'off'});
    this.container_.addChild(toControl(this.radio_), true);
    this.helper_ = new recoil.ui.ComponentWidgetHelper(scope, this.container_, this, this.updateState_);
    this.tooltip_ = new recoil.ui.TooltipHelper(scope, this.container_);
};

/**
 * @type {recoil.frp.Util.OptionsType}
 */
recoil.ui.widgets.RadioWidget.options =
    recoil.frp.Util.Options('value', 'selectValue',
                            {
                                enabled: recoil.ui.BoolWithExplanation.TRUE
                            });

/**
 * @param {!recoil.frp.Behaviour<T>|T} value the widget that will be displayed in the popup
 * @param {!recoil.frp.Behaviour<T>|T} selectValue the widget that will be displayed normally (no popup required
 * @suppress {missingProperties}
 */

recoil.ui.widgets.RadioWidget.prototype.attach = function(value, selectValue)  {
    recoil.ui.widgets.RadioWidget.options.value(value).selectValue(selectValue).attach(this);
};

/**
 * see recoil.ui.widgets.PopupWidget.options fro valid options
 * @param {!Object|!recoil.frp.Behaviour<Object>} options
 * @suppress {missingProperties}
 */
recoil.ui.widgets.RadioWidget.prototype.attachStruct = function(options) {
    var frp = this.helper_.getFrp();
    var bound = recoil.ui.widgets.RadioWidget.options.bind(frp, options);

    this.valueB_ = bound.value();
    this.selectValueB_ = bound.selectValue();
    this.enabledB_ = bound.enabled();

    this.helper_.attach(this.valueB_, this.selectValueB_, this.enabledB_);
    var me = this;
    this.radio_.onchange = function() {
        frp.accessTrans(function() {
            if (me.helper_.isGood()) {
                me.valueB_.set(me.selectValueB_.get());
            }
        }, me.valueB_, me.selectValueB_, me.enabledB_);
    };
    this.tooltip_.attach(this.enabledB_, this.helper_);
};

/**
 *
 * @param {recoil.ui.WidgetHelper} helper
 * @private
 */
recoil.ui.widgets.RadioWidget.prototype.updateState_ = function(helper) {
    this.radio_.disabled = !helper.isGood() || !this.enabledB_.get().val();
    if (helper.isGood()) {
        var newVal = recoil.util.object.isEqual(this.valueB_.get(), this.selectValueB_.get());
        if (this.radio_.checked != newVal) {
            this.radio_.checked = newVal;
        }
    }

};

/**
 * @return {!goog.ui.Component}
 */
recoil.ui.widgets.RadioWidget.prototype.getComponent = function() {
    return this.container_;
};

/**
 * all widgets should not allow themselves to be flatterned
 *
 * @type {!Object}
 */

recoil.ui.widgets.RadioWidget.prototype.flatten = recoil.frp.struct.NO_FLATTEN;


text:
<?php

/**
 * Autoloader routine
 *
 * @param string Class name
 */
function RecipeParser_Autoload($class_name) {
	if (!class_exists($class_name, false)) {
        $class_file_path = str_replace('_', '/', $class_name) . '.php';
        require($class_file_path);
	}
}

spl_autoload_register('RecipeParser_Autoload');


text:
package org.ovirt.engine.core.common.action;

import org.ovirt.engine.core.compat.*;

public class FenceVdsManualyParameters extends StoragePoolParametersBase {
    private static final long serialVersionUID = -5313772300704786422L;
    private boolean privateClearVMs;

    public boolean getClearVMs() {
        return privateClearVMs;
    }

    public void setClearVMs(boolean value) {
        privateClearVMs = value;
    }

    public FenceVdsManualyParameters(boolean clearVMs) {
        super(Guid.Empty);
        setClearVMs(clearVMs);
    }

    public FenceVdsManualyParameters() {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PersonApplication
{
        class Teacher : Person
        {
            public string Room { get; set; }

            // default constructor
            public Teacher()
            {
            }

            // parametric constuctor calls base class constructor with parameters
            public Teacher(string firstName, string lastName, string room)
                : base(firstName, lastName)
            {
                Room = room;
            }

            // just one method what Teacher can do
            public void TeacherMethod()
            {
                Console.WriteLine("This method belongs to Teacher!");
            }

            // override base class ToString()-method
            public override string ToString()
            {
                return base.ToString() + " " + Room;
            }
        }
    }


text:
package org.transparencia.gov2go.model;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.transparencia.gov2go.util.constantes.Provedor;

/**
 * Created by pedrosjc on 14/04/14.
 */
public class Localizacao {

    private static final long serialVersionUID = 1L;

    public Localizacao () {}

    public Localizacao(String latitude, String longitude, Provedor provedor) {
        this.latitude = latitude;
        this.longitude = longitude;
        this.provedor = provedor;
    }

    private String latitude;

    private String longitude;

    private Provedor provedor;

    @JsonIgnore
    private Ocorrencia ocorrencia;

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public Provedor getProvedor() {
        return provedor;
    }

    public void setProvedor(Provedor provedor) {
        this.provedor = provedor;
    }

    public Ocorrencia getOcorrencia() {
        return ocorrencia;
    }

    public void setOcorrencia(Ocorrencia ocorrencia) {
        this.ocorrencia = ocorrencia;
    }
}


text:
package org.cleverframe.fastdfs.protocol.storage.request;

import org.cleverframe.fastdfs.constant.CmdConstants;
import org.cleverframe.fastdfs.constant.OtherConstants;
import org.cleverframe.fastdfs.protocol.BaseRequest;
import org.cleverframe.fastdfs.protocol.ProtocolHead;
import org.cleverframe.fastdfs.mapper.DynamicFieldType;
import org.cleverframe.fastdfs.mapper.FastDFSColumn;

/**
 * 作者:LiZW

 * 创建时间:2016/11/20 17:08

 */
public class GetMetadataRequest extends BaseRequest {
    /**
     * 组名
     */
    @FastDFSColumn(index = 0, max = OtherConstants.FDFS_GROUP_NAME_MAX_LEN)
    private String groupName;

    /**
     * 路径名
     */
    @FastDFSColumn(index = 1, dynamicField = DynamicFieldType.allRestByte)
    private String path;

    /**
     * 删除文件命令
     *
     * @param groupName 组名
     * @param path      文件路径
     */
    public GetMetadataRequest(String groupName, String path) {
        super();
        this.groupName = groupName;
        this.path = path;
        this.head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_GET_METADATA);
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}


text:
namespace ra
{

SceneObject::SceneObject()
	: m_ZOrder(0)
	, m_visible(true)
{
}

SceneObject::~SceneObject()
{
}

ra::Int32 SceneObject::GetZOrder() const
{
	return m_ZOrder;
}

void SceneObject::SetZOrder(int z)
{
	m_ZOrder = z;
}

bool SceneObject::IsVisible() const
{
	return m_visible;
}

void SceneObject::Show()
{
	m_visible = true;
}

void SceneObject::Hide()
{
	m_visible = false;
}

} // namespace ra


text:
/**
 * @name restSvcs
 * @requires ngResource
 * @description Module containing the REST services. The received objects properties can be taken from the REST-Api documentation
 */
var restSvcs = angular.module('restSvcs', ['ngResource']);

/**
 * @ngdoc service
 * @name restSvcs.Workshops
 * @description Provides CRUD operations for Workshop-functions provided by the API. All functions return a $promise object resolved with the requested data
 */
restSvcs.factory('Workshops', ['$resource', function ($resource) {
    return $resource('/api/workshops/:id', {}, {
        /**
         * @ngdoc funtion
         * @name restSvcs.Workshops#getAll
         * @description get a list of all currently available workshops.
         * @methodOf restSvcs.Workshops
         * @returns { Array<Workshop>} List of workshops
         */
        'getAll': {method: 'GET', params: {id: 'all'}, isArray: true},
        /**
         * @ngdoc funtion
         * @name restSvcs.Workshops#get
         * @description get a single workshops
         * @methodOf restSvcs.Workshops
         * @param {number} id Workshop-ID
         */
        'getWorkshop': {method: 'GET', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc funtion
         * @name restSvcs.Workshops#getParticipants
         * @description get list of enrolled participants to a workshop
         * @methodOf restSvcs.Workshops
         * @param {number} id Workshop-ID
         */
        'getParticipants': {method: 'GET', url: '/api/workshops/:id/participants', params: {id: '@id'}, isArray: true},
        /**
         * @ngdoc funtion
         * @name restSvcs.Workshops#enrollWorkshop
         * @description Action to enroll a Workshop
         * @methodOf restSvcs.Workshops
         * @param {number} id Workshop-ID
         */
        'enroll': {method: 'POST', url: '/api/workshops/:id/enroll', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc funtion
         * @name restSvcs.Workshops#unsubscribeWorkshop
         * @description Action to unsubscribe a Workshop
         * @methodOf restSvcs.Workshops
         * @param {number} id Workshop-ID
         * @param {string} token Unsubscribetoken
         */
        'unsubscribe': {method: 'POST', url: '/api/workshops/unsubscribe', isArray: false},
        /**
         * @ngdoc funtion
         * @name restSvcs.Workshops#unsubscribeWorkshop
         * @description Get Waitinglist of a Workshop
         * @methodOf restSvcs.Workshops
         * @param {number} id Workshop-ID
         */
        'getWaitinglist': {method: 'GET', url: '/api/workshops/:id/waitinglist', params: {id: '@id'}, isArray: true},
        /**
         * @ngdoc funtion
         * @name restSvcs.Workshops#unsubscribeWorkshop
         * @description Confirm Enrollment of the WOrkshop
         * @methodOf restSvcs.Workshops
         * @param {number} id Workshop-ID
         * @param {number} participantsid Participants-ID
         * @param {string} token Confirmtoken
         */
        'confirmEnroll': {method: 'GET', url: '/api/workshops/:id/enroll/:userid/confirm/:token', params: {id: '@id', userid: '@userid', token: '@token'}, isArray: false},
        'unsubscribeConfirm': {method: 'GET', url: '/api/workshops/:id/unsubscribe/:token/confirmation/:participantId'}
    });
}]);
/**
 * @ngdoc service
 * @name restSvcs.WorkshopTemplate
 * @description Provides CRUD operations for Workshop-Template-functions provided by the API
 */
restSvcs.factory('WorkshopTemplate', ['$resource', function ($resource) {
    return $resource('/api/admin/workshops/template/:id', {}, {
        /**
         * @ngdoc funtion
         * @name restSvcs.WorkshopTemplate#getAll
         * @description get a list of all currently available workshoptemplates.
         * @methodOf restSvcs.WorkshopTemplate
         * @returns {httpPromise} resolve with fetched data, or fails with error description.
         */
        'getAll': {method: 'GET', params: {id: 'list'}, isArray: true},
        /**
         * @ngdoc funtion
         * @name restSvcs.WorkshopTemplate#get
         * @description get a single workshoptemplate
         * @methodOf restSvcs.WorkshopTemplate
         * @param {integer} id Workshop-ID
         */
        'get': {method: 'GET', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.WorkshopTemplate#edit
         * @description edit a single workshoptemplate
         * @methodOf restSvcs.WorkshopTemplate
         * @param {integer} id Workshop-ID
         */
        'edit': {method: 'PATCH', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.WorkshopTemplate#put
         * @description create a new workshoptemplate
         * @methodOf restSvcs.WorkshopTemplate
         */
        'put': { method: 'PUT', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.WorkshopTemplate#delete
         * @description delete a workshoptemplate
         * @methodOf restSvcs.WorkshopTemplate
         * @param {integer} id Workshop-ID
         */
        'deleteWorkshopTemplate': {method: 'DELETE', params: {id: '@id'}, isArray: false}
    });
}]);
/**
 * @ngdoc service
 * @name restSvcs.AdminWorkshop
 * @description Provides CRUD operations for Admin-Workshop-functions provided by the API
 */
restSvcs.factory('AdminWorkshop', ['$resource', function ($resource) {
    return $resource('/api/admin/workshops/:id', {}, {
        /**
         * @ngdoc function
         * @name restSvcs.AdminWorkshop#gethistory
         * @description show all workshops
         * @methodOf restSvcs.AdminWorkshop
         * @returns {httpPromise} resolve with fetched data, or fails with error description.
         */
        'gethistory': {method: 'GET', params: {id: 'history'}, isArray: true},
        /**
         * @ngdoc function
         * @name restSvcs.AdminWorkshop#put
         * @description create a new workshop
         * @methodOf restSvcs.AdminWorkshop
         */
        'putWorkshop': {method: 'PUT', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.AdminWorkshop#patch
         * @description edit a single workshop
         * @methodOf restSvcs.AdminWorkshop
         * @param {integer} id Workshop-ID
         */
        'edit': {method: 'PATCH', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.AdminWorkshop#delete
         * @description delete a workshop
         * @methodOf restSvcs.AdminWorkshop
         * @param {integer} id Workshop-ID
         */
        'deleteWorkshop': {method: 'DELETE', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.AdminWorkshop#patchwaitinglist
         * @description overbook the workshop
         * @methodOf restSvcs.AdminWorkshop
         * @param {integer} id Workshop-ID
         * @param {integer} participantsid Participants-ID
         */
        'overbook': {method: 'PATCH', url: '/api/admin/workshops/:id/waitinglist/:participantid', params: {id: '@id', participantid: '@participantid'}, isArray: false},
        'participants': {method: 'GET', url: '/api/admin/workshops/:id/participants', params: {id: '@id'}, isArray: true},
        'waitinglist': {method: 'GET', url: '/api/admin/workshops/:id/waitinglist', params: {id: '@id'}, isArray: true},
        'confirmParticipation': {method: 'POST', url: '/api/admin/workshops/:id/participated/:participant', params: {id: '@id', participant: '@participant'}, isArray: true}
    });
}]);
/**
 * @ngdoc service
 * @name restSvcs.Participants
 * @description Provides CRUD operations for Participant-functions provided by the API
 */
restSvcs.factory('Participants', ['$resource', function ($resource) {
    return $resource('/api/admin/participants/:id', {}, {
        /**
         * @ngdoc function
         * @name restSvcs.Participants#all
         * @description show all participants
         * @methodOf restSvcs.Participants
         * @returns {httpPromise} resolve with fetched data, or fails with error description
         */
        'getall': {method: 'GET', params: {id: 'all'}, isArray: true},
        /**
         * @ngdoc function
         * @name restSvcs.Participants#all
         * @description show all blacklisted participants
         * @methodOf restSvcs.Participants
         * @returns {httpPromise} resolve with fetched data, or fails with error description
         */
        'getblacklistall': {method: 'GET', url: '/api/admin/participants/blacklist/all', isArray: true},
        /**
         * @ngdoc function
         * @name restSvcs.Participants#blacklist
         * @description Put participants on blacklist
         * @methodOf restSvcs.Participants
         */
        'blacklist': {method: 'PUT', url: '/api/admin/participants/:id/blacklist', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Participants#delete
         * @description remove a participant from blacklist
         * @methodOf restSvcs.Participants
         * @param {integer} id Participants-ID
         */
        'removeBlacklist': {url: '/api/admin/participants/:id/blacklist', method: 'DELETE', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc funtion
         * @name restSvcs.Participants#get
         * @description get a single participant
         * @methodOf restSvcs.Participants
         * @param {integer} id Participants-ID
         */
        'getParticipant': {method: 'GET', params: {id: '@id'}, isArray: false},
        'remove': {method: 'DELETE', url: ' /api/admin/participants/:participant/remove/:workshop', params: {participant: '@participant'}, workshop: '@workshop', isArray: false}
    });
}]);
/**
 * @ngdoc service
 * @name restSvcs.EmailTemplate
 * @description Provides CRUD operations for Emailtemplate-functions provided by the API
 */
restSvcs.factory('EmailTemplate', ['$resource', function ($resource) {
    return $resource('/api/admin/email/template/:id', {}, {
        /**
         * @ngdoc function
         * @name restSvcs.EmailTemplate#all
         * @description show all emailtemplates
         * @methodOf restSvcs.EmailTemplate
         * @returns {httpPromise} resolve with fetched data, or fails with error description
         */
        'getAll': {url: '/api/admin/email/template/list', method: 'GET', isArray: true},
        /**
         * @ngdoc funtion
         * @name restSvcs.EmailTemplate#get
         * @description get a single emailtemplate
         * @methodOf restSvcs.EmailTemplate
         * @param {integer} id Emailtemplate-ID
         */
        'get': {method: 'GET', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.EmailTemplate#patch
         * @description edit a single emailtemplate
         * @methodOf restSvcs.EmailTemplate
         * @param {integer} id Emailtemplate-ID
         */
        'edit': {method: 'PATCH', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.EmailTemplate#put
         * @description create a new Emailtemplate
         * @methodOf restSvcs.EmailTemplate
         */
        'put': {method: 'PUT', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.EmailTemplate#delete
         * @description remove a emailtemplate
         * @methodOf restSvcs.EmailTemplate
         * @param {integer} id Emailtemplate-ID
         */
        'delete': {method: 'DELETE', params: {id: '@id'}, isArray: false}
    });
}]);
/**
 * @ngdoc service
 * @name restSvcs.Email
 * @description Provides CRUD operations for Email-functions provided by the API
 */
restSvcs.factory('Email', ['$resource', function ($resource) {
    return $resource('/api/admin/email/:id/send', {}, {
        /**
         * @ngdoc function
         * @name restSvcs.Email#send
         * @description send Email
         * @methodOf restSvcs.Email
         * @param {number} workshopid Workshop-ID
         */
        'sendEmail': {method: 'POST', params: {id: '@id'}, isArray: false}
    });
}]);
/**
 * @ngdoc service
 * @name restSvcs.Admin
 * @description Provides operations for Admin-Managment
 */
restSvcs.factory('Admin', ['$resource', function ($resource) {
    return $resource('/api/admin', {}, {
        /**
         * @ngdoc function
         * @name restSvcs.Admin#list
         * @description Returns a list of all currentyl active Admins
         * @methodOf restSvcs.Admin
         */
        'list': {url: '/api/admin/user/list', method: 'GET', isArray: true},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#remove
         * @description Deactivates an admin account
         * @methodOf restSvcs.Admin
         */
        'delete': {url: '/api/admin/user/:id', method: 'DELETE', params: {id: '@id'}, isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#changePassword
         * @description Changes the admin password
         * @methodOf restSvcs.Admin
         */
        'changePassword': {url: '/api/admin/user', method: 'PATCH', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#resetPassword
         * @description Resets the password, if the provided token is valid
         * @methodOf restSvcs.Admin
         */
        'resetPassword': {url: '/api/user/reset/password', method: 'POST', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#requestReset
         * @description Creates a request for a email with password-reset link at the server
         * @methodOf restSvcs.Admin
         */
        'requestReset': {url: ' /api/user/send/password/forgot/email', method: 'POST', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#invite
         * @description Sends an invite link to the passed e-mail
         * @methodOf restSvcs.Admin
         */
        'invite': {url: '/api/admin/user/invite', method: 'POST', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#editContact
         * @description Edits the contact data saved on the server
         * @methodOf restSvcs.Admin
         */
        'editContact': {url: '/api/admin/user/contact/data', method: 'PUT', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#editLegalNotice
         * @description Edits the legal Notice saved on the server
         * @methodOf restSvcs.Admin
         */
        'editLegalNotice': {url: '/api/admin/user/legal/notice', method: 'PUT', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#editContact
         * @description Edits the contact data saved on the server
         * @methodOf restSvcs.Admin
         */
        'getContact': {url: '/api/user/contact/data', method: 'GET', isArray: false},
        /**
         * @ngdoc function
         * @name restSvcs.Admin#editLegalNotice
         * @description Edits the legal Notice saved on the server
         * @methodOf restSvcs.Admin
         */
        'getLegalNotice': {url: '/api/user/legal/notice', method: 'GET', isArray: false},
        'changeEmail': {url: '/api/admin/user/email', method: 'PATCH', isArray: false},
        'createAdmin': {url: '/api/user/create/admin', method: 'POST', isArray: false}
    });
}]);


text:
layout: post
category: java
title:  "Source code of RandomAccessFile in java."
comments: true
description: "Analyze source code of RandomAccessFile ."
tags: [java,source]
---

## 说明

本类的实例支持同一个文件的读写。一个`RandomAccessFile`就像是保存在文件系统中的一个大的字节数组,数组上有一个指针或是索引,叫做`file pointer`。读取操作从这个指针的位置开始读取然后边读边移动指针。如果创建实例时设置成读/写模式,写入操作也同样可以。同样也是在指针位置开始写入,然后边写边移动指针。当写入操作超过文件当前的末尾会扩容数组。这个指针可以用`getFilePointer`获取或`seek`来设置。

## implements

```
 implements DataOutput, DataInput, Closeable
```

## fields

### 文件描述符

```
private FileDescriptor fd;
```

### 文件通道

```
private FileChannel channel = null;
```

### 同时读写

```
private boolean rw;
```

### 文件的路径

```
private final String path;
```

### 锁

```
private Object closeLock = new Object();
```

### 关闭标志

```
private volatile boolean closed = false;
```

### 读写标志

```
private static final int O_RDONLY = 1;//只读
private static final int O_RDWR =   2;//读写
private static final int O_SYNC =   4;//将文件的内容或元数据变动立即写入底层存储设备
private static final int O_DSYNC =  8;//将文件的内容变动立即写入底层存储设备
```

### 静态方法

```
static {
    initIDs();
}

private static native void initIDs();

```

## methods

### 构造器

```
public RandomAccessFile(File file, String mode)
    throws FileNotFoundException
{
    String name = (file != null ? file.getPath() : null);
    int imode = -1;
    if (mode.equals("r"))
        imode = O_RDONLY;
    else if (mode.startsWith("rw")) {
        imode = O_RDWR;//如果文件不存在,会创建
        rw = true;
        if (mode.length() > 2) {
            if (mode.equals("rws"))
                imode |= O_SYNC;
            else if (mode.equals("rwd"))
                imode |= O_DSYNC;
            else
                imode = -1;
        }
    }
    if (imode < 0)
        throw new IllegalArgumentException("Illegal mode \"" + mode
                                           + "\" must be one of "
                                           + "\"r\", \"rw\", \"rws\","
                                           + " or \"rwd\"");
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkRead(name);//是否可读
        if (rw) {
            security.checkWrite(name);//是否可写
        }
    }
    if (name == null) {
        throw new NullPointerException();
    }
    if (file.isInvalid()) {
        throw new FileNotFoundException("Invalid file path");
    }
    fd = new FileDescriptor();
    fd.attach(this);
    path = name;
    open(name, imode);//打开文件
}

public RandomAccessFile(String name, String mode)
	throws FileNotFoundException
{
	this(name != null ? new File(name) : null, mode);
}
```

### 获取文件描述符

```
public final FileDescriptor getFD() throws IOException {
    if (fd != null) {
        return fd;
    }
    throw new IOException();
}
```

### 获取文件通道,通道的位置与`getFilePointer`方法返回的指针位移量相等

```
public final FileChannel getChannel() {
    synchronized (this) {
        if (channel == null) {
            channel = FileChannelImpl.open(fd, path, true, rw, this);
        }
        return channel;
    }
}
```

### 打开文件

```
private native void open0(String name, int mode)
    throws FileNotFoundException;

private void open(String name, int mode)
	throws FileNotFoundException {
	open0(name, mode);
}
```

### 读取一个字节

```
public int read() throws IOException {
    return read0();
}

private native int read0() throws IOException;
```

### 读取字节到数组中

```
private native int readBytes(byte b[], int off, int len) throws IOException;

public int read(byte b[], int off, int len) throws IOException {
    return readBytes(b, off, len);
}

public int read(byte b[]) throws IOException {
    return readBytes(b, 0, b.length);
}
```

### 读满数组

```
public final void readFully(byte b[]) throws IOException {
    readFully(b, 0, b.length);
}

public final void readFully(byte b[], int off, int len) throws IOException {
    int n = 0;
    do {
        int count = this.read(b, off + n, len - n);
        if (count < 0)
            throw new EOFException();
        n += count;
    } while (n < len);
}
```

### 跳过字节

```
public int skipBytes(int n) throws IOException {
    long pos;
    long len;
    long newpos;

    if (n <= 0) {
        return 0;
    }
    pos = getFilePointer();//指针位置
    len = length();//文件长度
    newpos = pos + n;
    if (newpos > len) {
        newpos = len;
    }
    seek(newpos);//设置位置

    //返回实际跳过的字节数
    return (int) (newpos - pos);
}
```

### 写入一个字节

```
public void write(int b) throws IOException {
    write0(b);
}

private native void write0(int b) throws IOException;
```

### 将数组写入

```
private native void writeBytes(byte b[], int off, int len) throws IOException;

public void write(byte b[]) throws IOException {
    writeBytes(b, 0, b.length);
}

public void write(byte b[], int off, int len) throws IOException {
    writeBytes(b, off, len);
}
```

### 获取文件指针

```
public native long getFilePointer() throws IOException;
```

### 设置文件指针

```
public void seek(long pos) throws IOException {
    if (pos < 0) {
        throw new IOException("Negative seek offset");
    } else {
        seek0(pos);
    }
}

private native void seek0(long pos) throws IOException;
```

### 获取文件长度

```
public native long length() throws IOException;
```

### 设置文件长度,如果实际长度大于设置的长度,则文件会被截取,否则文件会被扩展,扩展部分未定义

```
public native void setLength(long newLength) throws IOException;
```

### 关闭

```
public void close() throws IOException {
    synchronized (closeLock) {
        if (closed) {
            return;
        }
        closed = true;
    }
    if (channel != null) {
        channel.close();
    }

    fd.closeAll(new Closeable() {
        public void close() throws IOException {
           close0();
       }
    });
}
```

### 读写基础类型

```
//其他方法与DataInputStream,DataOutputStream一致
public final boolean readBoolean() throws IOException {
    int ch = this.read();
    if (ch < 0)
        throw new EOFException();
    return (ch != 0);
}
```


text:
FactoryGirl.define do
  factory :item do
    project_id    { FactoryGirl.create(:project).id }
    creator_id    1
    item_type     'story'
    who           'user'
    what          'something'
    why           'something'
  end
end


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview The entry point for all ChromeVox2 related code for the
 * background page.
 */

goog.provide('cvox2.Background');
goog.provide('cvox2.global');

goog.require('cvox.TabsApiHandler');

/** Classic Chrome accessibility API. */
cvox2.global.accessibility =
    chrome.accessibilityPrivate || chrome.experimental.accessibility;

/**
 * ChromeVox2 background page.
 */
cvox2.Background = function() {
  /**
   * A list of site substring patterns to use with ChromeVox next. Keep these
   * strings relatively specific.
   * @type {!Array.<string>}
   */
  this.whitelist_ = ['http://www.chromevox.com/', 'chromevox_next_test'];

  /** @type {cvox.TabsApiHandler} @private */
  this.tabsHandler_ = new cvox.TabsApiHandler(cvox.ChromeVox.tts,
                                              cvox.ChromeVox.braille,
                                              cvox.ChromeVox.earcons);

  // Only needed with unmerged ChromeVox classic loaded before.
  cvox2.global.accessibility.setAccessibilityEnabled(false);

  // Manually bind all functions to |this|.
  for (var func in this) {
    if (typeof(this[func]) == 'function')
      this[func] = this[func].bind(this);
  }

  // Register listeners for ...
  // Desktop.
  chrome.automation.getDesktop(this.onGotTree);

  // Tabs.
  chrome.tabs.onUpdated.addListener(this.onTabUpdated);
};

cvox2.Background.prototype = {
  /**
   * Handles chrome.tabs.onUpdated.
   * @param {number} tabId
   * @param {Object} changeInfo
   */
  onTabUpdated: function(tabId, changeInfo) {
    chrome.tabs.get(tabId, function(tab) {
      if (!tab.url)
        return;

      if (!this.isWhitelisted_(tab.url)) {
        chrome.commands.onCommand.removeListener(this.onGotCommand);
        cvox.ChromeVox.background.injectChromeVoxIntoTabs([tab], true);
        return;
      }

      if (!chrome.commands.onCommand.hasListeners()) {
        chrome.commands.onCommand.addListener(this.onGotCommand);
      }

      this.disableClassicChromeVox_(tab.id);

      chrome.automation.getTree(this.onGotTree.bind(this));
    }.bind(this));
  },

  /**
   * Handles all setup once a new automation tree appears.
   * @param {AutomationTree} tree The new automation tree.
   */
  onGotTree: function(root) {
    // Register all automation event listeners.
    root.addEventListener(chrome.automation.EventType.focus,
                          this.onAutomationEvent.bind(this),
                          true);
  },

  /**
   * A generic handler for all desktop automation events.
   * @param {AutomationEvent} evt The event.
   */
  onAutomationEvent: function(evt) {
    var output = evt.target.attributes.name + ' ' + evt.target.role;
    cvox.ChromeVox.tts.speak(output, cvox.AbstractTts.QUEUE_MODE_FLUSH);
    cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(output));
    chrome.accessibilityPrivate.setFocusRing([evt.target.location]);
  },

  /**
   * Handles chrome.commands.onCommand.
   * @param {string} command
   */
  onGotCommand: function(command) {
  },

  /**
   * @private
   * @param {string} url
   * @return {boolean} Whether the given |url| is whitelisted.
   */
  isWhitelisted_: function(url) {
    return this.whitelist_.some(function(item) {
      return url.indexOf(item) != -1;
    }.bind(this));
  },

  /**
   * Disables classic ChromeVox.
   * @param {number} tabId The tab where ChromeVox classic is running.
   */
  disableClassicChromeVox_: function(tabId) {
    chrome.tabs.executeScript(
          tabId,
          {'code': 'try { window.disableChromeVox(); } catch(e) { }\n',
           'allFrames': true});
  }
};

/** @type {cvox2.Background} */
cvox2.global.backgroundObj = new cvox2.Background();


text:
namespace Microsoft.VisualStudio.CodeTools
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.Shell.Interop;
    using System.Diagnostics;
    using Microsoft.Win32;
    using System.IO;

    // Common static helper functions
    static internal class Common
    {
        #region Private fields
        static private IServiceProvider serviceProvider;
        #endregion

        #region Construction
        static public void Initialize(IServiceProvider provider)
        {
            serviceProvider = provider;
        }

        static public void Release()
        {
            serviceProvider = null;
        }
        #endregion

        #region Trace and GetService
        [Conditional("TRACE")]
        static public void Trace(string message)
        {
            System.Diagnostics.Trace.WriteLine("CodeTools: " + message);
        }

        static public object GetService(Type serviceType)
        {
            if (serviceProvider != null)
                return serviceProvider.GetService(serviceType);
            else
                return null;
        }
        #endregion

        #region Registry stuff
        static private string VsRoot = null;
        static public String GetLocalRegistryRoot()
        {
            // Get the visual studio root key
            if (VsRoot == null)
            {
                ILocalRegistry2 localReg = GetService(typeof(SLocalRegistry)) as ILocalRegistry2;
                if (localReg != null)
                {
                    localReg.GetLocalRegistryRoot(out VsRoot);
                }

                if (VsRoot == null)
                {
                    VsRoot = @"Software\Microsoft\VisualStudio\10.0"; // Guess on failure
                }
            }
            return VsRoot;
        }

        static public String GetCodeToolsRegistryRoot()
        {
            return (GetLocalRegistryRoot() + "\\CodeTools");
        }

        #endregion
    }
}


text:
package org.eclipse.ui.examples.javaeditor.java;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class JavaEditorMessages {

	private static final String RESOURCE_BUNDLE= "org.eclipse.ui.examples.javaeditor.JavaEditorMessages";//$NON-NLS-1$

	private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);

	private JavaEditorMessages() {
	}

	public static String getString(String key) {
		try {
			return fgResourceBundle.getString(key);
		} catch (MissingResourceException e) {
			return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
		}
	}
}


text:
namespace Castle.Components.Validator.Tests.ContributorsTests
{

	using NUnit.Framework;

	[TestFixture]
	public class SelfValidationContributorTestCase
	{
		private SelfValidationContributor contributor;

		[SetUp]
		public void Init()
		{
			contributor = new SelfValidationContributor();
		}

		[Test]
		public void ObjectValidator()
		{
			TestTarget target = new TestTarget();
			target.ItemSKUs = new string[] { "ITEM-1" };
			target.Total = 10000.00;
			Assert.IsTrue(contributor.IsValid(target, RunWhen.Everytime).HasError);

			target.Total = 10.00;
			Assert.IsFalse(contributor.IsValid(target, RunWhen.Everytime).HasError);
		}

		[Test, ExpectedException(typeof(ValidationException),
			ExpectedMessage = "The class Castle.Components.Validator.Tests.ContributorsTests.SelfValidationContributorTestCase+InvalidTestTarget " +
							  "wants to use self validation, however the methods must be only taking one parameter of type ErrorSummary. Please " +
							  "correct the following methods: Invalid, AnotherInvalid")]
		public void ThrowsOnInvalidTarget()
		{
			InvalidTestTarget target = new InvalidTestTarget();
			contributor.IsValid(target, RunWhen.Everytime);
		}

		[Test]
		public void HonorsRunWhen()
		{
			TestTarget target = new TestTarget();
			target.ItemSKUs = new string[] { "ITEM-1" };
			target.Total = 10000.00;
			Assert.IsTrue(contributor.IsValid(target, RunWhen.Everytime).HasError);
			Assert.IsTrue(target.ValidateOnUpdateRan);

			target = new TestTarget();
			target.ItemSKUs = new string[] { "ITEM-1" };
			target.Total = 10000.00;
			Assert.IsTrue(contributor.IsValid(target, RunWhen.Custom).HasError);
			Assert.IsFalse(target.ValidateOnUpdateRan);
		}

		public class TestTarget
		{
			private string[] itemSKUs;
			private double total;
			private bool _validationOnUpdateRan;

			public TestTarget()
			{
			}

			public TestTarget(string[] itemSKUs, double total)
			{
				this.itemSKUs = itemSKUs;
				this.total = total;
			}

			public string[] ItemSKUs
			{
				get { return itemSKUs; }
				set { itemSKUs = value; }
			}

			public double Total
			{
				get { return total; }
				set { total = value; }
			}

			public bool ValidateOnUpdateRan
			{
				get { return _validationOnUpdateRan; }
				set { _validationOnUpdateRan = value; }
			}

			[ValidateSelf]
			public void Validate(ErrorSummary errorSummary)
			{
				if (total > 1000 && ItemSKUs.Length == 1)
					//TODO Make it easy to register an error message with a key
					errorSummary.RegisterErrorMessage("total", "Customers cannot purchase 1 item if it is more than $1000 dollars.");
			}

			[ValidateSelf(RunWhen = RunWhen.Update)]
			public void ValidateOnUpdate(ErrorSummary errorSummary)
			{
				ValidateOnUpdateRan = true;
			}
		}

		public class InvalidTestTarget
		{
			[ValidateSelf]
			public void Valid(ErrorSummary errorSummary)
			{
			}

			[ValidateSelf]
			public void Invalid()
			{
			}

			[ValidateSelf]
			public void AnotherInvalid(out ErrorSummary errors)
			{
				errors = new ErrorSummary();
			}
		}
	}
}


text:
package movement;

import entities.Entity;
import entities.MoveableDecor;
import graphics.LayerData2;

/**
 * this Movement clones the Maintexture of its owner and moves both textures.
 * when a Texture completely leaves the screen it resets.
 * Used with the asteroid belts.
 * Condition for the texture:
 *  -bigger than the screen
 *  -repeating design (horizontal)
 * */
public class InfiniteScroll extends Move{
	private LayerData2 clone;
	private double speedX;

	public InfiniteScroll(Entity getOwner, double moveX, double moveY) {
		super(getOwner);
		speedX = moveX;

		clone = new LayerData2(owner, owner.LayerDatas.get(0).texturepath, 1, 1);
		clone.spriteDisplayX = owner.LayerDatas.get(0).spriteDisplayX;
		clone.spriteDisplayY = owner.LayerDatas.get(0).spriteDisplayY;
		clone.pos = new double[]{owner.LayerDatas.get(0).spriteDisplayX,0};
		clone.layer = owner.LayerDatas.get(0).layer;
		owner.addNewLayer(clone);
	}

	/**
	 * This method makes necessary recalulation before moving anything.
	 * Not needed in this movement.
	 * */
	protected void calculateMove(){
	}

	/**
	 * This method sends the final movement command
	 * */
	protected void makeMove(){

		if(((MoveableDecor)owner).mainTexture.pos[0] < 0-((MoveableDecor)owner).mainTexture.spriteDisplayX){
			((MoveableDecor)owner).mainTexture.pos[0] = ((MoveableDecor)owner).mainTexture.spriteDisplayX;
		}else{
			((MoveableDecor)owner).mainTexture.pos[0] -= speedX;
		}
		if(clone.pos[0] < 0-clone.spriteDisplayX){
			clone.pos[0] = clone.spriteDisplayX;
		}else{
			clone.pos[0] -= speedX;
		}
	}
}


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

#pragma once

#include "render_pass_context.hpp"

namespace neam::hydra
{
  struct hydra_context;

  /// \brief Provide the base process of how to render stuff using hydra
  /// Hydra uses a prepare/submit process:
  ///  - prepare: create all the temporary buffers and setup the cpu -> gpu transfers
  ///  - submit: fill the command buffers. It may run on multiple threads.
  ///
  /// Right after the prepare phase, cpu -> gpu transfers are started, all the gpu memory is unmapped and the memory allocator is frozen.
  /// It is not possible to allocate gpu-memory during the submit phase.
  ///
  /// Allocations marked as pass-local are expected to be heavilly re-used, so they must not leave the pass.
  /// Allocations marked as frame-local are not reused during the frame and so can leave the pass, but not the frame.
  class render_pass
  {
    public:
      render_pass(hydra_context& _context);
      virtual ~render_pass();

      virtual bool enabled() const
      {
        return true;
      }

      // Called at init
      // Single threaded, in order of insertion in the pass manager
      virtual void setup(render_pass_context& /*rpctx*/)
      {
      }

      // Single threaded, in order of insertion in the pass manager
      virtual void prepare(render_pass_context& /*rpctx*/)
      {
        // create buffers, allocate memory, setup cpu -> gpu transfers, ...
      }

      // multi-threaded
      virtual render_pass_output submit(render_pass_context& /*rpctx*/)
      {
        // work with the command buffer
        return {};
      }

      virtual void cleanup()
      {
        // end !
      }

  protected:
      hydra_context& context;

      vk::command_pool graphic_transient_cmd_pool;
      vk::command_pool compute_transient_cmd_pool;

      bool need_setup = true;
      friend class pass_manager;
  };
}


text:
package com.ycsoft.report.dao.keycon;

import org.springframework.stereotype.Component;

import com.ycsoft.daos.abstracts.BaseEntityDao;
import com.ycsoft.report.bean.RepTemplateKey;

@Component
public class RepTemplateKeyDao extends BaseEntityDao<RepTemplateKey> {
	public RepTemplateKeyDao(){}
}


text:
namespace g2o {

  ParameterSE3Offset::ParameterSE3Offset(){
    setOffset();
  }

  void ParameterSE3Offset::setOffset(const Isometry3D& offset_){
    _offset = offset_;
    _inverseOffset = _offset.inverse();
  }

  bool ParameterSE3Offset::read(std::istream& is) {
    Vector7d off;
    for (int i=0; i<7; i++) {
      is >> off[i];
    }
    // normalize the quaternion to recover numerical precision lost by storing as human readable text
    Vector4D::MapType(off.data()+3).normalize();
    setOffset(internal::fromVectorQT(off));
    return is.good();
  }

  bool ParameterSE3Offset::write(std::ostream& os) const {
    Vector7d off =internal::toVectorQT(_offset);
    for (int i=0; i<7; i++)
      os << off[i] << " ";
    return os.good();
  }

  CacheSE3Offset::CacheSE3Offset() :
    Cache(),
    _offsetParam(0)
  {
  }

  bool CacheSE3Offset::resolveDependancies(){
    _offsetParam = dynamic_cast <ParameterSE3Offset*> (_parameters[0]);
    return _offsetParam != 0;
  }

  void CacheSE3Offset::updateImpl(){
    const VertexSE3* v = static_cast<const VertexSE3*>(vertex());
    _n2w = v->estimate() * _offsetParam->offset();
    _w2n = _n2w.inverse();
    _w2l = v->estimate().inverse();
  }

  void CacheSE3Offset::setOffsetParam(ParameterSE3Offset* offsetParam)
  {
    _offsetParam = offsetParam;
  }

#ifdef G2O_HAVE_OPENGL
  CacheSE3OffsetDrawAction::CacheSE3OffsetDrawAction(): DrawAction(typeid(CacheSE3Offset).name()){
    _previousParams = (DrawAction::Parameters*)0x42;
    refreshPropertyPtrs(0);
  }

  bool CacheSE3OffsetDrawAction::refreshPropertyPtrs(HyperGraphElementAction::Parameters* params_){
    if (! DrawAction::refreshPropertyPtrs(params_))
      return false;
    if (_previousParams){
      _cubeSide = _previousParams->makeProperty<FloatProperty>(_typeName + "::CUBE_SIDE", .05f);
    } else {
      _cubeSide = 0;
    }
    return true;
  }

  HyperGraphElementAction* CacheSE3OffsetDrawAction::operator()(HyperGraph::HyperGraphElement* element,
                HyperGraphElementAction::Parameters* params_){
    if (typeid(*element).name()!=_typeName)
      return 0;
    CacheSE3Offset* that = static_cast<CacheSE3Offset*>(element);
    refreshPropertyPtrs(params_);
    if (! _previousParams)
      return this;

    if (_show && !_show->value())
      return this;
    float cs = _cubeSide ? _cubeSide->value() : 1.0f;
    glPushAttrib(GL_COLOR);
    glColor3f(POSE_PARAMETER_COLOR);
    glPushMatrix();
    glMultMatrixd(that->offsetParam()->offset().data());
    opengl::drawBox(cs,cs,cs);
    glPopMatrix();
    glPopAttrib();
    return this;
  }
#endif

} // end namespace


text:
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UIViewController *rootViewController;

@end


text:
<?php
/**
 * This a Leaf page controller
 *
 */
// Include essential condig-file which also creates the $leaf variable with its defaults
include (__DIR__ . '/config.php');

// Check if user is authenticated.
$acronym = isset($_SESSION['user']) ? $_SESSION['user']->acronym : null;

if($acronym) {
  $output = "Du är inloggad som: $acronym ({$_SESSION['user']->name})";
}
else {
  $output = "Du är INTE inloggad.";
}

// Logout the user
if(isset($_POST['logout'])) {
  unset($_SESSION['user']);
  header('Location: movie_logout.php');
}
// Do it and store it all in variables in the Leaf container.
$leaf['title'] = "Logout";

$leaf['main'] = <<<EOD

{$leaf['title']}

<form method=post>
  <fieldset>
  <legend>Logout</legend>

<input type='submit' name='logout' value='Logout'/>

Login

  <output>{$output}</output>
  </fieldset>
</form>

EOD;

// Finally, leave it all to the rendering phase of Leaf.
include(LEAF_THEME_PATH);


text:
  Saint-Avit est
       un village
       géographiquement positionné dans le département des Landes en Aquitaine. Elle comptait 608 habitants en 2008.

À proximité de Saint-Avit sont localisées les communes de
Lucbardez-et-Bargues située à 4 km, 374 habitants,
Saint-Pierre-du-Mont située à 8 km, 8 171 habitants,
Bostens à 7 km, 162 habitants,
Laglorieuse située à 8 km, 565 habitants,
Canenx-et-Réaut à 7 km, 160 habitants,
Gaillères localisée à 5 km, 541 habitants,
 entre autres. De plus, Saint-Avit est située à seulement six km de Mont-de-Marsan.

La ville compte quelques  équipements, elle propose entre autres un terrain de tennis, un parcours de golf et un terrain de sport.

À Saint-Avit, le prix moyen à l'achat d'un appartement se situe à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 755 € du m². À la location la valorisation moyenne se situe à 8,33 € du m² par mois.

Si vous pensez venir habiter à Saint-Avit, vous pourrez aisément trouver une maison à vendre.

Le parc d'habitations, à Saint-Avit, était réparti en 2011 en cinq appartements et 261 maisons soit
 un marché plutôt équilibré.


text:
<?php

if ( !function_exists( 'mbtheme_font_awesome_enqueue' ) ) {

    /**
     * enqueue font-awesome style and script before main style and script of theme
     */
    function mbtheme_font_awesome_enqueue() {
        $url = MBTHEME_URI_MODULES . '/font-awesome';

        // font-awesome style
        wp_enqueue_style( 'mbtheme-font-awesome-style', $url . '/css/font-awesome.min.css', array(), false );
    }

}

add_action( 'mbtheme_enqueue_scripts_before_main', 'mbtheme_font_awesome_enqueue' );


text:
import { NDArray } from './';
/**
 * @static
 * @memberof module:Globals
 * @function abs
 * @description Returns the absolute value of each element of `x`.
 * @param {NDArray} x
 * @returns {NDArray}
 * @example
 * import { abs } from 'vectorious/core/abs';
 *
 * abs([-1, -2, -3]) // => array([1, 2, 3])
 */
export declare const abs: (x: NDArray | ArrayLike<any>) => NDArray;
/**
 * @function abs
 * @memberof NDArray.prototype
 * @description Returns the absolute value of each element of current array.
 * @returns {this}
 * @example
 * import { array } from 'vectorious/core/array';
 *
 * array([-1, -2, -3]).abs() // <=> array([1, 2, 3])
 */
export default function (this: NDArray): NDArray;


text:
/**
 * Original author: David Eads (https://github.com/eads)
 *
 * Wrap D3 charting components in a simple Backbone view interface
 *
 * Provides a redrawing path, data sync, and fallback for non-d3 browsers.
 *
 * Views that extend ChartView should implement their own "draw" function and go to work.
 *
 * var collection = new Backbone.Collection([ ["Maria", 33], ["Heather", 29] ]);
 * var view = new MyChartView({ $el: $("#topper-chart"), collection: collection});
 *
 **/

var ChartBaseView = Backbone.View.extend({
  constructor: function(options) {
    this.default_options = {
      base_height: 320,
      /*breakpoints: {
        // width->height multiplier
        "768": 0.9,
        "420": 0.7
      },*/
      margin: {
        top: 20,
        right: 30,
        bottom: 30,
        left: 50
      },
      type: ""
    };

    this.options = $.extend(true, this.default_options, options);

    /*var breakpoints = _.pairs(this.options.breakpoints);
    this.options.breakpoints = _.sortBy(breakpoints, function(item) {
      return Number(item[0]);
    });*/

    // Fallback if d3 is unavailable, add some formatters otherwise.
    if (!this.d3) {
      this.draw = this.fallback_draw;
    }
    else {
      this.formatNumber = d3.format(".lf");
      this.formatCommas = d3.format(",");
      this.formatPercent = d3.format("%");
    }
    Backbone.View.apply(this, arguments);
  },
  initialize: function(options) {
    // Wrap chart
    this.$el.wrap($('
'));
    this.$chart_container = this.$el.parent();
    this.chart_container = this.$chart_container.get(0);
    this.get_dimensions();

    if (this.collection)
      this.collection.on("sync", _.bind(this.render, this));
    else if (this.options.data)
      this.data = this.options.data;

    //$(window).on("resize", _.debounce(_.bind(this.render, this), 100));
    if(Modernizr.touch){
      window.addEventListener("orientationchange", _.debounce(_.bind(this.render, this), 100), false);
    }
  },
  get_dimensions: function() {
    var window_width = $(window).width();
    var wrapperWidth = this.$chart_container.width();
    var width = wrapperWidth - this.options.margin.left - this.options.margin.right;
    var height = this.options.base_height - this.options.margin.bottom - this.options.margin.top;

    /*_.every(this.options.breakpoints, _.bind(function(breakpoint) {
      var width = breakpoint[0];
      if (window_width <= width) {
        var multiplier = breakpoint[1];
        height = (height - this.options.margin.bottom - this.options.margin.top) * multiplier;
        return false;
      }
      return true;
    }, this));*/

    wrapperHeight = height + this.options.margin.top + this.options.margin.bottom;

    //console.log('VIEW OPTIONS', this.options);
    this.$el
     .height(wrapperHeight);

    this.dimensions = {
      width: width,
      height: height,
      wrapperWidth: wrapperWidth,
      wrapperHeight: wrapperHeight
    };
  },
  // The render function wraps drawing with responsivosity
  render: function() {
    if (this.collection)
      this.data = this.collection.toJSON();
    this.$el.empty();
    this.get_dimensions();
    this.draw();
  },
  draw: function() {
    return this;
  },
  fallback_draw: function() {
    this.$el.html(
      '

Warning! You are using an unsupported browser. ' +
      'Please upgrade to Chrome, Firefox, or Internet Explorer version 9 or higher to view ' +
      'charts on this site.

');
    return this;
  },
  d3: function() {
    return (typeof d3 !== 'undefined');
  },
/*Hospital App specific methods*/

  create_svg: function() {
    var chart = this;
    //create new svg for the bar chart
    chart.svg = d3.select(chart.el).append("svg")
      .attr("width", chart.dimensions.wrapperWidth)
      .attr("height", chart.dimensions.wrapperHeight)
      .attr("class", "chart")
    .append("g")
      .attr("transform", "translate(" + chart.options.margin.left + ", " + chart.options.margin.top + ")");
  },

  create_axis: function(axis, orientation) {
    this[axis+"Axis"] = d3.svg.axis()
      .scale(this[axis+"Scale"])
      .orient(orientation);

    //too many ticks on tablets
    if(this.dimensions.wrapperWidth < 475 && axis === "x"){
      this.xAxis.ticks(5)
    }
  }
});


text:
#include "search/retrieval.hpp"

#include "search/cancel_exception.hpp"
#include "search/feature_offset_match.hpp"
#include "search/interval_set.hpp"
#include "search/mwm_context.hpp"
#include "search/search_index_header.hpp"
#include "search/search_index_values.hpp"
#include "search/search_trie.hpp"
#include "search/token_slice.hpp"

#include "editor/osm_editor.hpp"

#include "indexer/classificator.hpp"
#include "indexer/editable_map_object.hpp"
#include "indexer/feature.hpp"
#include "indexer/feature_data.hpp"
#include "indexer/feature_source.hpp"
#include "indexer/scales.hpp"
#include "indexer/search_delimiters.hpp"
#include "indexer/search_string_utils.hpp"
#include "indexer/trie_reader.hpp"

#include "platform/mwm_version.hpp"

#include "coding/compressed_bit_vector.hpp"
#include "coding/reader_wrapper.hpp"

#include "base/checked_cast.hpp"
#include "base/control_flow.hpp"
#include "base/macros.hpp"

#include <algorithm>
#include <cstddef>
#include <vector>

using namespace std;
using namespace strings;
using osm::EditableMapObject;
using osm::Editor;

namespace search
{
namespace
{
class FeaturesCollector
{
public:
  FeaturesCollector(base::Cancellable const & cancellable, vector<uint64_t> & features,
                    vector<uint64_t> & exactlyMatchedFeatures)
    : m_cancellable(cancellable)
    , m_features(features)
    , m_exactlyMatchedFeatures(exactlyMatchedFeatures)
    , m_counter(0)
  {
  }

  template <typename Value>
  void operator()(Value const & value, bool exactMatch)
  {
    if ((++m_counter & 0xFF) == 0)
      BailIfCancelled(m_cancellable);

    m_features.emplace_back(value.m_featureId);
    if (exactMatch)
      m_exactlyMatchedFeatures.emplace_back(value.m_featureId);
  }

  void operator()(uint32_t feature)
  {
    if ((++m_counter & 0xFF) == 0)
      BailIfCancelled(m_cancellable);

    m_features.emplace_back(feature);
  }

  void operator()(uint64_t feature, bool exactMatch)
  {
    if ((++m_counter & 0xFF) == 0)
      BailIfCancelled(m_cancellable);

    m_features.emplace_back(feature);
    if (exactMatch)
      m_exactlyMatchedFeatures.emplace_back(feature);
  }

private:
  base::Cancellable const & m_cancellable;
  vector<uint64_t> & m_features;
  vector<uint64_t> & m_exactlyMatchedFeatures;
  uint32_t m_counter;
};

class EditedFeaturesHolder
{
public:
  explicit EditedFeaturesHolder(MwmSet::MwmId const & id) : m_id(id)
  {
    auto & editor = Editor::Instance();
    m_deleted = editor.GetFeaturesByStatus(id, FeatureStatus::Deleted);
    m_modified = editor.GetFeaturesByStatus(id, FeatureStatus::Modified);
    m_created = editor.GetFeaturesByStatus(id, FeatureStatus::Created);
  }

  bool ModifiedOrDeleted(uint32_t featureIndex) const
  {
    return binary_search(m_deleted.begin(), m_deleted.end(), featureIndex) ||
           binary_search(m_modified.begin(), m_modified.end(), featureIndex);
  }

  template <typename Fn>
  void ForEachModifiedOrCreated(Fn && fn)
  {
    ForEach(m_modified, fn);
    ForEach(m_created, fn);
  }

private:
  template <typename Fn>
  void ForEach(vector<uint32_t> const & features, Fn & fn)
  {
    auto & editor = Editor::Instance();
    for (auto const index : features)
    {
      // Ignore feature load errors related to mwm removal and feature parse errors from editor.
      if (auto emo = editor.GetEditedFeature(FeatureID(m_id, index)))
        fn(*emo, index);
    }
  }

  MwmSet::MwmId const & m_id;
  vector<uint32_t> m_deleted;
  vector<uint32_t> m_modified;
  vector<uint32_t> m_created;
};

Retrieval::ExtendedFeatures SortFeaturesAndBuildResult(vector<uint64_t> && features,
                                                       vector<uint64_t> && exactlyMatchedFeatures)
{
  using Builder = coding::CompressedBitVectorBuilder;
  base::SortUnique(features);
  base::SortUnique(exactlyMatchedFeatures);
  auto featuresCBV = CBV(Builder::FromBitPositions(move(features)));
  auto exactlyMatchedFeaturesCBV = CBV(Builder::FromBitPositions(move(exactlyMatchedFeatures)));
  return Retrieval::ExtendedFeatures(move(featuresCBV), move(exactlyMatchedFeaturesCBV));
}

Retrieval::ExtendedFeatures SortFeaturesAndBuildResult(vector<uint64_t> && features)
{
  using Builder = coding::CompressedBitVectorBuilder;
  base::SortUnique(features);
  auto const featuresCBV = CBV(Builder::FromBitPositions(move(features)));
  return Retrieval::ExtendedFeatures(featuresCBV);
}

template <typename DFA>
pair<bool, bool> MatchesByName(vector<UniString> const & tokens, vector<DFA> const & dfas)
{
  for (auto const & dfa : dfas)
  {
    for (auto const & token : tokens)
    {
      auto it = dfa.Begin();
      DFAMove(it, token);
      if (it.Accepts())
        return {true, it.ErrorsMade() == 0};
    }
  }

  return {false, false};
}

template <typename DFA>
pair<bool, bool> MatchesByType(feature::TypesHolder const & types, vector<DFA> const & dfas)
{
  if (dfas.empty())
    return {false, false};

  auto const & c = classif();

  for (auto const & type : types)
  {
    UniString const s = FeatureTypeToString(c.GetIndexForType(type));

    for (auto const & dfa : dfas)
    {
      auto it = dfa.Begin();
      DFAMove(it, s);
      if (it.Accepts())
        return {true, it.ErrorsMade() == 0};
    }
  }

  return {false, false};
}

template <typename DFA>
pair<bool, bool> MatchFeatureByNameAndType(EditableMapObject const & emo,
                                           SearchTrieRequest<DFA> const & request)
{
  auto const & th = emo.GetTypes();

  pair<bool, bool> matchedByType = MatchesByType(th, request.m_categories);

  // Exactly matched by type.
  if (matchedByType.second)
    return {true, true};

  pair<bool, bool> matchedByName = {false, false};
  emo.GetNameMultilang().ForEach([&](int8_t lang, string const & name) {
    if (name.empty() || !request.HasLang(lang))
      return base::ControlFlow::Continue;

    vector<UniString> tokens;
    NormalizeAndTokenizeString(name, tokens, Delimiters());
    auto const matched = MatchesByName(tokens, request.m_names);
    matchedByName = {matchedByName.first || matched.first, matchedByName.second || matched.second};
    if (!matchedByName.second)
      return base::ControlFlow::Continue;

    return base::ControlFlow::Break;
  });

  return {matchedByType.first || matchedByName.first, matchedByType.second || matchedByName.second};
}

bool MatchFeatureByPostcode(EditableMapObject const & emo, TokenSlice const & slice)
{
  string const postcode = emo.GetPostcode();
  vector<UniString> tokens;
  NormalizeAndTokenizeString(postcode, tokens, Delimiters());
  if (slice.Size() > tokens.size())
    return false;
  for (size_t i = 0; i < slice.Size(); ++i)
  {
    if (slice.IsPrefix(i))
    {
      if (!StartsWith(tokens[i], slice.Get(i).GetOriginal()))
        return false;
    }
    else if (tokens[i] != slice.Get(i).GetOriginal())
    {
      return false;
    }
  }
  return true;
}

template <typename Value, typename DFA>
Retrieval::ExtendedFeatures RetrieveAddressFeaturesImpl(Retrieval::TrieRoot<Value> const & root,
                                                        MwmContext const & context,
                                                        base::Cancellable const & cancellable,
                                                        SearchTrieRequest<DFA> const & request)
{
  EditedFeaturesHolder holder(context.GetId());
  vector<uint64_t> features;
  vector<uint64_t> exactlyMatchedFeatures;
  FeaturesCollector collector(cancellable, features, exactlyMatchedFeatures);

  MatchFeaturesInTrie(
      request, root,
      [&holder](Value const & value) {
        return !holder.ModifiedOrDeleted(base::asserted_cast<uint32_t>(value.m_featureId));
      } /* filter */,
      collector);

  holder.ForEachModifiedOrCreated([&](EditableMapObject const & emo, uint64_t index) {
    auto const matched = MatchFeatureByNameAndType(emo, request);
    if (matched.first)
    {
      features.emplace_back(index);
      if (matched.second)
        exactlyMatchedFeatures.emplace_back(index);
    }
  });

  return SortFeaturesAndBuildResult(move(features), move(exactlyMatchedFeatures));
}

template <typename Value>
Retrieval::ExtendedFeatures RetrievePostcodeFeaturesImpl(Retrieval::TrieRoot<Value> const & root,
                                                         MwmContext const & context,
                                                         base::Cancellable const & cancellable,
                                                         TokenSlice const & slice)
{
  EditedFeaturesHolder holder(context.GetId());
  vector<uint64_t> features;
  vector<uint64_t> exactlyMatchedFeatures;
  FeaturesCollector collector(cancellable, features, exactlyMatchedFeatures);

  MatchPostcodesInTrie(
      slice, root,
      [&holder](Value const & value) {
        return !holder.ModifiedOrDeleted(base::asserted_cast<uint32_t>(value.m_featureId));
      } /* filter */,
      collector);

  holder.ForEachModifiedOrCreated([&](EditableMapObject const & emo, uint64_t index) {
    if (MatchFeatureByPostcode(emo, slice))
      features.push_back(index);
  });

  return SortFeaturesAndBuildResult(move(features));
}

Retrieval::ExtendedFeatures RetrieveGeometryFeaturesImpl(MwmContext const & context,
                                                         base::Cancellable const & cancellable,
                                                         m2::RectD const & rect, int scale)
{
  EditedFeaturesHolder holder(context.GetId());

  covering::Intervals coverage;
  CoverRect(rect, scale, coverage);

  vector<uint64_t> features;
  vector<uint64_t> exactlyMatchedFeatures;

  FeaturesCollector collector(cancellable, features, exactlyMatchedFeatures);

  context.ForEachIndex(coverage, scale, collector);

  holder.ForEachModifiedOrCreated([&](EditableMapObject const & emo, uint64_t index) {
    auto const center = emo.GetMercator();
    if (rect.IsPointInside(center))
      features.push_back(index);
  });
  return SortFeaturesAndBuildResult(move(features), move(exactlyMatchedFeatures));
}

template <typename T>
struct RetrieveAddressFeaturesAdaptor
{
  template <typename... Args>
  Retrieval::ExtendedFeatures operator()(Args &&... args)
  {
    return RetrieveAddressFeaturesImpl<T>(forward<Args>(args)...);
  }
};

template <typename T>
struct RetrievePostcodeFeaturesAdaptor
{
  template <typename... Args>
  Retrieval::ExtendedFeatures operator()(Args &&... args)
  {
    return RetrievePostcodeFeaturesImpl<T>(forward<Args>(args)...);
  }
};

template <typename Value>
unique_ptr<Retrieval::TrieRoot<Value>> ReadTrie(ModelReaderPtr & reader)
{
  return trie::ReadTrie<SubReaderWrapper<Reader>, ValueList<Value>>(
      SubReaderWrapper<Reader>(reader.GetPtr()), SingleValueSerializer<Value>());
}
}  // namespace

Retrieval::Retrieval(MwmContext const & context, base::Cancellable const & cancellable)
  : m_context(context), m_cancellable(cancellable), m_reader(unique_ptr<ModelReader>())
{
  auto const & value = context.m_value;

  version::MwmTraits mwmTraits(value.GetMwmVersion());
  auto const format = mwmTraits.GetSearchIndexFormat();
  if (format == version::MwmTraits::SearchIndexFormat::CompressedBitVector)
  {
    m_reader = context.m_value.m_cont.GetReader(SEARCH_INDEX_FILE_TAG);
  }
  else if (format == version::MwmTraits::SearchIndexFormat::CompressedBitVectorWithHeader)
  {
    FilesContainerR::TReader reader = value.m_cont.GetReader(SEARCH_INDEX_FILE_TAG);

    SearchIndexHeader header;
    header.Read(*reader.GetPtr());
    CHECK(header.m_version == SearchIndexHeader::Version::V2, (base::Underlying(header.m_version)));

    m_reader = reader.SubReader(header.m_indexOffset, header.m_indexSize);
  }
  else
  {
    CHECK(false, ("Unsupported search index format", format));
  }
  m_root = ReadTrie<Uint64IndexValue>(m_reader);
}

Retrieval::ExtendedFeatures Retrieval::RetrieveAddressFeatures(
    SearchTrieRequest<UniStringDFA> const & request) const
{
  return Retrieve<RetrieveAddressFeaturesAdaptor>(request);
}

Retrieval::ExtendedFeatures Retrieval::RetrieveAddressFeatures(
    SearchTrieRequest<PrefixDFAModifier<UniStringDFA>> const & request) const
{
  return Retrieve<RetrieveAddressFeaturesAdaptor>(request);
}

Retrieval::ExtendedFeatures Retrieval::RetrieveAddressFeatures(
    SearchTrieRequest<LevenshteinDFA> const & request) const
{
  return Retrieve<RetrieveAddressFeaturesAdaptor>(request);
}

Retrieval::ExtendedFeatures Retrieval::RetrieveAddressFeatures(
    SearchTrieRequest<PrefixDFAModifier<LevenshteinDFA>> const & request) const
{
  return Retrieve<RetrieveAddressFeaturesAdaptor>(request);
}

Retrieval::Features Retrieval::RetrievePostcodeFeatures(TokenSlice const & slice) const
{
  return Retrieve<RetrievePostcodeFeaturesAdaptor>(slice).m_features;
}

Retrieval::Features Retrieval::RetrieveGeometryFeatures(m2::RectD const & rect, int scale) const
{
  return RetrieveGeometryFeaturesImpl(m_context, m_cancellable, rect, scale).m_features;
}

template <template <typename> class R, typename... Args>
Retrieval::ExtendedFeatures Retrieval::Retrieve(Args &&... args) const
{
  R<Uint64IndexValue> r;
  ASSERT(m_root, ());
  return r(*m_root, m_context, m_cancellable, forward<Args>(args)...);
}
}  // namespace search


text:
using JetBrains.Annotations;
using JetBrains.ReSharper.Psi;

namespace JetBrains.ReSharper.Plugins.Yaml.Psi
{
  [LanguageDefinition(Name)]
  public class YamlLanguage : KnownLanguage
  {
    public new const string Name = "YAML";

    [CanBeNull, UsedImplicitly]
    public static YamlLanguage Instance { get; private set; }

    public YamlLanguage() : base(Name, "YAML")
    {
    }

    protected YamlLanguage([NotNull] string name, [NotNull] string presentableName) : base(name, presentableName)
    {
    }
  }
}


text: <script src="http://facebook.github.io/react/js/jsfiddle-integration.js"></script>


text:
/** @jsxRuntime classic */
/** @jsx jsx */

/**
 * TODO:
 *
 * - This component needs to be brought into line with either buttons (including support for tones)
 *   or better represented in the theme.
 * - Needs proper tokens and styling functions
 * - Needs size support
 * - Needs focus support
 * - Needs disabled support
 * - Needs a label wrapper like radio and checkbox
 * - Should this be stateful like a checkbox? check react-aria
 */

import { ButtonHTMLAttributes, forwardRef, ReactNode } from 'react';
import { jsx, useTheme, VisuallyHidden } from '@keystone-ui/core';

import { ControlLabel } from './components/ControlLabel';

type SwitchProps = {
  /** The switch label content. */
  children: ReactNode;
} & SwitchControlProps;

export const Switch = forwardRef<HTMLButtonElement, SwitchProps>(
  ({ children, className, ...props }, ref) => {
    return (
      <ControlLabel className={className} control={<SwitchControl ref={ref} {...props} />}>
        {children}
      </ControlLabel>
    );
  }
);

type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement>;

type SwitchControlProps = {
  /** Optionally pass in "On" and "Off" label text for screen readers */
  a11yLabels?: { on: string; off: string };
  /** The current checked state. */
  checked?: boolean;
  /** Handle change events. */
  onChange?: (checked: boolean) => void;
} & Omit<ButtonProps, 'onChange'>;

export const SwitchControl = forwardRef<HTMLButtonElement, SwitchControlProps>(
  ({ a11yLabels = { on: 'On', off: 'Off' }, checked = false, onChange, ...props }, ref) => {
    let onClick = () => {
      if (onChange) {
        onChange(!checked);
      }
    };

    return (
      <Button aria-checked={checked} role="switch" onClick={onClick} ref={ref} {...props}>
        <VisuallyHidden>{checked ? a11yLabels.on : a11yLabels.off}</VisuallyHidden>
      </Button>
    );
  }
);

const Button = forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => {
  const { animation, fields, sizing } = useTheme();

  let gutter = 3;
  let trackHeight = sizing.xsmall + gutter;
  let trackWidth = trackHeight * 2 - 2 * gutter;
  let handleSize = trackHeight - gutter * 2;

  return (
    <button
      ref={ref}
      css={{
        backgroundColor: fields.controlBorderColor,
        borderRadius: 9999,
        padding: gutter,
        border: 0,
        boxSizing: 'border-box',
        display: 'block',
        outline: 0,
        overflow: 'hidden',
        position: 'relative',
        whiteSpace: 'nowrap',
        // height: trackHeight,
        width: trackWidth,
        cursor: 'pointer',

        '&[aria-checked="true"]': {
          backgroundColor: fields.selected.controlBorderColor,

          '::before': {
            transform: 'translateX(100%)',
          },
        },

        '::before': {
          height: handleSize,
          width: handleSize,
          marginTop: -1,

          backgroundColor: fields.switchForeground,
          borderRadius: '50%',
          content: '" "',
          display: 'block',
          position: 'relative',
          transition: `transform ${animation.duration400} ${animation.easeOut}`,
        },
      }}
      {...props}
    />
  );
});


text:
$(document).ready(function () {
  'use strict';

  if ($('#taxon_option_type_ids').length > 0) {
    $('#taxon_option_type_ids').select2({
      placeholder: Spree.translations.option_type_placeholder,
      multiple: true,
      initSelection: function (element, callback) {
        var url = Spree.url(Spree.routes.option_type_search, {
          ids: element.val(),
          token: Spree.api_key
        });
        return $.getJSON(url, null, function (data) {
          return callback(data);
        });
      },
      ajax: {
        url: Spree.routes.option_type_search,
        quietMillis: 200,
        datatype: 'json',
        data: function (term) {
          return {
            q: {
              name_cont: term
            },
            token: Spree.api_key
          };
        },
        results: function (data) {
          return {
            results: data
          };
        }
      },
      formatResult: function (option_type) {
        return option_type.presentation + ' (' + option_type.name + ')';
      },
      formatSelection: function (option_type) {
        return option_type.presentation + ' (' + option_type.name + ')';
      }
    });
  }
});


text:
@interface LBCalendar(){
    LBCalendarAppearance *calendarAppearance;
    BOOL cacheLastWeekMode;
}

@end

@implementation LBCalendar

- (instancetype)init
{
    self = [super init];
    if(!self){
        return nil;
    }

    self->_currentDate = [NSDate date];
    calendarAppearance = [LBCalendarAppearance new];

    return self;
}

- (void)setContentView:(LBCalendarContentView *)contentView
{
    [self->_contentView setDelegate:nil];
    [self->_contentView setCalendarManager:nil];

    self->_contentView = contentView;
    [self->_contentView setDelegate:self];
    [self->_contentView setCalendarManager:self];

    [self.contentView setCurrentDate:self.currentDate];
    [self.contentView reloadAppearance];
}

- (void)reloadData
{
    // Position to the middle page
    CGFloat pageWidth = CGRectGetWidth(self.contentView.frame);
    self.contentView.contentOffset = CGPointMake(pageWidth * ((NUMBER_PAGES_LOADED / 2)), self.contentView.contentOffset.y);

    [self.contentView reloadData];

}

- (void)reloadAppearance
{
    [self.contentView reloadAppearance];

    if(cacheLastWeekMode != self.calendarAppearance.isWeekMode){
        cacheLastWeekMode = self.calendarAppearance.isWeekMode;
        [self setCurrentDate:self.currentDate]; // Reload all data
    }
}

- (void)setCurrentDate:(NSDate *)currentDate
{
    self->_currentDate = currentDate;

    [self.contentView setCurrentDate:currentDate];

    [self reloadData]; // For be on the good page and update all DayView

}

- (LBCalendarAppearance *)calendarAppearance
{
    return calendarAppearance;
}

#pragma mark - UIScrollView delegate

// Use for scroll with scrollRectToVisible or setContentOffset
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self updatePage];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self updatePage];
}

- (void)updatePage
{
    CGFloat pageWidth = CGRectGetWidth(self.contentView.frame);
    CGFloat fractionalPage = self.contentView.contentOffset.x / pageWidth;

    int currentPage = roundf(fractionalPage);
    if (currentPage == (NUMBER_PAGES_LOADED / 2)){
        self.contentView.scrollEnabled = YES;
        return;
    }

    NSCalendar *calendar = calendarAppearance.calendar;
    NSDateComponents *dayComponent = [NSDateComponents new];

    if(!self.calendarAppearance.isWeekMode){
        dayComponent.month = currentPage - (NUMBER_PAGES_LOADED / 2);
    }
    else{
        dayComponent.day = 7 * (currentPage - (NUMBER_PAGES_LOADED / 2));
    }

    NSDate *currentDate = [calendar dateByAddingComponents:dayComponent toDate:self.currentDate options:0];

    [self setCurrentDate:currentDate];

    self.contentView.scrollEnabled = YES;
}

- (void)loadNextMonth
{
    if(self.calendarAppearance.isWeekMode){
        NSLog(@"LBCalendar loadNextMonth ignored");
        return;
    }

    CGRect frame = self.contentView.frame;
    frame.origin.x = frame.size.width * ((NUMBER_PAGES_LOADED / 2) + 1);
    frame.origin.y = 0;
    [self.contentView scrollRectToVisible:frame animated:YES];
}

- (void)loadPreviousMonth
{
    if(self.calendarAppearance.isWeekMode){
        NSLog(@"LBCalendar loadPreviousMonth ignored");
        return;
    }

    CGRect frame = self.contentView.frame;
    frame.origin.x = frame.size.width * ((NUMBER_PAGES_LOADED / 2) - 1);
    frame.origin.y = 0;
    [self.contentView scrollRectToVisible:frame animated:YES];
}

@end