text:
using System;
using System.Runtime.InteropServices;

namespace VCSJones.FiddlerCertGen.Interop
{
    internal static class NCryptPropertyReader
    {
        public static string ReadStringUni(NCryptHandleBase handle, string propertyName)
        {
            return Read(handle, propertyName, Marshal.PtrToStringUni);
        }

        public static int ReadInt32(NCryptHandleBase handle, string propertyName)
        {
            return Read(handle, propertyName, Marshal.ReadInt32);
        }

        public static T Read<T>(NCryptHandleBase handle, string propertyName, Func<IntPtr, T> convert)
        {
            var buffer = IntPtr.Zero;
            uint size;
            if (NCrypt.NCryptGetProperty(handle, propertyName, buffer, 0, out size, 0u) != SECURITY_STATUS.ERROR_SUCCESS)
            {
                throw new InvalidOperationException("Unable to query property.");
            }
            buffer = Marshal.AllocHGlobal((int)size);
            try
            {
                if (NCrypt.NCryptGetProperty(handle, propertyName, buffer, size, out size, 0u) != SECURITY_STATUS.ERROR_SUCCESS)
                {
                    throw new InvalidOperationException("Unable to query property.");
                }
                return convert(buffer);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
    }
}


text:
using System.Collections.Generic;

namespace KadGen.Functional.Common
{
    public class ValidationIssue
    {
        public ValidationIssue(ValidationIssueId issueId, params string[] fieldNames)
        {
            ValidationIssueId = issueId;
            FieldNames = fieldNames;
        }

        public ValidationIssueId ValidationIssueId { get; }
        public IEnumerable<string> FieldNames { get; } //normally contains one
    }

    public enum ValidationIssueId
    {
        Unknown = 0,
        RequiredValueMissing,
        StringTooShort
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />

    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />

    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <link rel="stylesheet" href="icons/material.css">
    <link rel="stylesheet" href="css/materialize.min.css">
    <title>TP1</title>

Teste de Performance 1

            Bateria

            Sistema

            Acelerador

Minha Bateria

A bateria está com % de carga.

Seu aparelho  conectado a uma fonte de energia.

Info do Dispositivo

Modelo do dispositivo:

Plataforma:

Versão:

Fabricante:

Número Serial:

Tipo de conexão:

Versão do Cordova:

Posição x: 0

Posição y: 0

Posição z: 0

      menu

games

<img src="icons/ic_battery_unknown_white_24dp/android/drawable-hdpi/ic_battery_unknown_white_24dp.png"

vibration


text:
namespace Sekhmet.Serialization.XmlSerializerSupport.Test.Dummies
{
    public class SimpleBar
    {
        public string Value { get; set; }
    }
}


text:
package com.evolveum.midpoint.repo.sql.data.common.enums;

import com.evolveum.midpoint.repo.sql.query.definition.JaxbType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceAdministrativeStateType;

/**
 * @author lazyman
 */
@JaxbType(type = RResourceAdministrativeState.class)
public enum RResourceAdministrativeState implements SchemaEnum<ResourceAdministrativeStateType> {

    ENABLED(ResourceAdministrativeStateType.ENABLED),
    DISABLED(ResourceAdministrativeStateType.DISABLED);

    private ResourceAdministrativeStateType administrativeState;

    RResourceAdministrativeState(ResourceAdministrativeStateType administrativeState) {
        this.administrativeState = administrativeState;
    }

    @Override
    public ResourceAdministrativeStateType getSchemaValue() {
        return administrativeState;
    }
}


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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.petrofski.proleague.TabbedActivity">

    <android.support.design.widget.CoordinatorLayout 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"
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.petrofski.proleague.TabbedActivity"
        android:layout_above="@+id/adView3">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/appbar_padding_top"
            android:theme="@style/AppTheme.AppBarOverlay">

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

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

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    </android.support.design.widget.CoordinatorLayout>

    <com.google.android.gms.ads.AdView
        android:id="@id/adView3"
        android:layout_marginBottom="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"
        android:layout_gravity="center|bottom"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>


text:
<!DOCTYPE html>

		<title>Portfolio</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">

		<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">

		<link rel="stylesheet" type="text/css" href="assets/fonts/font-awesome/css/font-awesome.min.css">

		<link rel="stylesheet" type="text/css" href="style.css">

Using N-gram for Sentiment Analysis

Description

 Sentiment analysis is an important research area that identifies the people's sentiment underlying a text. Sentiment analysis widely studied in data mining. After reviewing and studying the current research on sentiment analysis, the goal of the proposed method is to get the more effective results of sentiment analysis on comment. The aim of this project is to improve the performance to classify the comment with sentiment information. We use n gram method for extracting the comment.

 View Details


text:
namespace hpc15 {

// Alignment must be a power of 2 !
template <typename T, unsigned int Alignment>
class aligned_allocator {
  public:
    typedef T*              pointer;
    typedef T const*        const_pointer;
    typedef T&              reference;
    typedef T const&        const_reference;
    typedef T               value_type;
    typedef std::size_t     size_type;
    typedef std::ptrdiff_t  difference_type;

    template <typename U>
    struct rebind {
        typedef aligned_allocator<U,Alignment> other;
    };

    aligned_allocator() NOEXCEPT_SPEC {
    }

    aligned_allocator(aligned_allocator const&) NOEXCEPT_SPEC {
    }

    template <typename U>
    aligned_allocator(aligned_allocator<U,Alignment> const&) NOEXCEPT_SPEC {
    }

    pointer allocate(size_type n) {
        pointer p;
#ifdef _WIN32
        p = _aligned_malloc(n*sizeof(T), Alignment);
        if(p == 0)
            throw std::bad_alloc();
#else
        if(posix_memalign(reinterpret_cast<void**>(&p), Alignment, n * sizeof(T) ))
            throw std::bad_alloc();
#endif
        return p;
    }

    void deallocate(pointer p, size_type) NOEXCEPT_SPEC {
        std::free(p);
    }

    size_type max_size() const NOEXCEPT_SPEC {
        std::allocator<T> a;
        return a.max_size();
    }

#if __cplusplus >= 201103L
    template <typename C, class... Args>
    void construct(C* c, Args&&... args) {
        new ((void*)c) C(std::forward<Args>(args)...);
    }
#else
    void construct(pointer p, const_reference t) {
        new((void *)p) T(t);
    }
#endif

    template <typename C>
    void destroy(C* c) {
        c->~C();
    }

    bool operator == (aligned_allocator const&) const NOEXCEPT_SPEC {
        return true;
    }

    bool operator != (aligned_allocator const&) const NOEXCEPT_SPEC {
        return false;
    }

    template <typename U, unsigned int UAlignment>
    bool operator == (aligned_allocator<U,UAlignment> const&) const NOEXCEPT_SPEC {
        return false;
    }

    template <typename U, unsigned int UAlignment>
    bool operator != (aligned_allocator<U,UAlignment> const&) const NOEXCEPT_SPEC {
        return true;
    }
};

}

#undef NOEXPECT_SPEC

#endif //HPC12_ALIGNED_ALLOCATOR_HPP


text:
package org.spongepowered.mod.mixin.core.client.gui;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiOverlayDebug;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.common.network.message.MessageTrackerDataRequest;
import org.spongepowered.common.network.message.SpongeMessageHandler;
import org.spongepowered.mod.bridge.client.gui.GUIOverlayDebugBridge_Forge;
import org.spongepowered.mod.bridge.client.MinecraftBridge_Forge;

import java.util.List;

@Mixin(GuiOverlayDebug.class)
public abstract class GuiOverlayDebugMixin_Forge implements GUIOverlayDebugBridge_Forge {

    private String forgeImpl$blockOwner = "";
    private String forgeImpl$blockNotifier = "";
    private BlockPos forgeImpl$cursorPos = new BlockPos(0, 0, 0);

    @Shadow @Final private Minecraft mc;

    @Inject(method = "<init>", at = @At(value = "RETURN") )
    private void forgeImpl$setDebugGui(final Minecraft mc, final CallbackInfo ci) {
        final MinecraftBridge_Forge spongeMc = (MinecraftBridge_Forge) mc;
        spongeMc.forgeBridge$setDebugGui((GuiOverlayDebug) (Object) this);
    }

    @Inject(method = "call()Ljava/util/List;", at = @At(value = "RETURN", ordinal = 1))
    private void forgeImpl$addOwnerInfo(final CallbackInfoReturnable<List<String>> cir) {
        final List<String> arraylist = cir.getReturnValue();
        if (this.mc.objectMouseOver != null
                && this.mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK
                && this.mc.objectMouseOver.getBlockPos() != null) {
            final BlockPos blockpos1 = this.mc.objectMouseOver.getBlockPos();
            if (!blockpos1.equals(this.forgeImpl$cursorPos)) {
                SpongeMessageHandler.getChannel().sendToServer(
                        new MessageTrackerDataRequest(0, -1, blockpos1.getX(), blockpos1.getY(), blockpos1.getZ()));
            }
            arraylist.add("Block Owner: " + this.forgeImpl$blockOwner);
            arraylist.add("Block Notifier: " + this.forgeImpl$blockNotifier);
            this.forgeImpl$cursorPos = this.mc.objectMouseOver.getBlockPos();
        } else if (this.mc.objectMouseOver != null && this.mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) {
            final Entity target = this.mc.objectMouseOver.entityHit;
            final BlockPos blockPos = target.getPosition();
            if (!blockPos.equals(this.forgeImpl$cursorPos)) {
                SpongeMessageHandler.getChannel().sendToServer(
                        new MessageTrackerDataRequest(1, target.getEntityId(), blockPos.getX(), blockPos.getY(), blockPos.getZ()));
            }
            arraylist.add("Entity Owner: " + this.forgeImpl$blockOwner);
            arraylist.add("Entity Notifier: " + this.forgeImpl$blockNotifier);
            this.forgeImpl$cursorPos = blockPos;
        }
    }

    @Override
    public void forgeBridge$setPlayerTrackerData(final String owner, final String notifier) {
        this.forgeImpl$blockOwner = owner;
        this.forgeImpl$blockNotifier = notifier;
    }
}


text:
package com.evolveum.midpoint.schema.constants;

import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;

import org.apache.commons.lang.Validate;

import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lazyman
 */
public enum ObjectTypes {

    CONNECTOR(SchemaConstants.C_CONNECTOR_TYPE, SchemaConstants.C_CONNECTOR,
            ConnectorType.class, ObjectManager.PROVISIONING, "connectors"),

    CONNECTOR_HOST(SchemaConstants.C_CONNECTOR_HOST_TYPE,
            SchemaConstants.C_CONNECTOR_HOST, ConnectorHostType.class, ObjectManager.PROVISIONING, "connectorHosts"),

    GENERIC_OBJECT(SchemaConstants.C_GENERIC_OBJECT_TYPE,
            SchemaConstants.C_GENERIC_OBJECT, GenericObjectType.class, ObjectManager.MODEL, "genericObjects"),

    RESOURCE(SchemaConstants.C_RESOURCE_TYPE, SchemaConstants.C_RESOURCE,
            ResourceType.class, ObjectManager.PROVISIONING, "resources"),

    USER(SchemaConstants.C_USER_TYPE, SchemaConstants.C_USER, UserType.class,
            ObjectManager.MODEL, "users"),

    OBJECT_TEMPLATE(SchemaConstants.C_OBJECT_TEMPLATE_TYPE,
            SchemaConstants.C_OBJECT_TEMPLATE, ObjectTemplateType.class, ObjectManager.MODEL, "objectTemplates"),

    SYSTEM_CONFIGURATION(SchemaConstants.C_SYSTEM_CONFIGURATION_TYPE, SchemaConstants.C_SYSTEM_CONFIGURATION,
            SystemConfigurationType.class, ObjectManager.MODEL, "systemConfigurations"),

    TASK(SchemaConstants.C_TASK_TYPE, SchemaConstants.C_TASK, TaskType.class, ObjectManager.TASK_MANAGER, "tasks"),

    SHADOW(SchemaConstants.C_SHADOW_TYPE, SchemaConstants.C_SHADOW, ShadowType.class, ObjectManager.PROVISIONING, "shadows"),

    ROLE(RoleType.COMPLEX_TYPE, SchemaConstantsGenerated.C_ROLE, RoleType.class, ObjectManager.MODEL, "roles"),

    PASSWORD_POLICY(ValuePolicyType.COMPLEX_TYPE, SchemaConstantsGenerated.C_VALUE_POLICY, ValuePolicyType.class,
            ObjectManager.MODEL, "valuePolicies"),

    NODE(NodeType.COMPLEX_TYPE, SchemaConstantsGenerated.C_NODE, NodeType.class, ObjectManager.TASK_MANAGER, "nodes"),

    ORG(OrgType.COMPLEX_TYPE, SchemaConstantsGenerated.C_ORG, OrgType.class, ObjectManager.MODEL, "orgs"),

    ABSTRACT_ROLE(AbstractRoleType.COMPLEX_TYPE, SchemaConstants.C_ABSTRACT_ROLE, AbstractRoleType.class,
            ObjectManager.MODEL, "abstractRoles"),

    FOCUS_TYPE(FocusType.COMPLEX_TYPE, SchemaConstants.C_FOCUS, FocusType.class, ObjectManager.MODEL, "focus"),

    REPORT(ReportType.COMPLEX_TYPE, SchemaConstants.C_REPORT, ReportType.class, ObjectManager.MODEL, "reports"),

    REPORT_OUTPUT(ReportOutputType.COMPLEX_TYPE, SchemaConstants.C_REPORT_OUTPUT, ReportOutputType.class,
                  ObjectManager.MODEL, "reportOutputs"),

    SECURITY_POLICY(SecurityPolicyType.COMPLEX_TYPE, SchemaConstants.C_SECURITY_POLICY, SecurityPolicyType.class,
    			ObjectManager.MODEL, "securityPolicies"),

    LOOKUP_TABLE(LookupTableType.COMPLEX_TYPE, SchemaConstantsGenerated.C_LOOKUP_TABLE, LookupTableType.class,
            ObjectManager.MODEL, "lookupTables"),

    ACCESS_CERTIFICATION_DEFINITION(AccessCertificationDefinitionType.COMPLEX_TYPE, SchemaConstantsGenerated.C_ACCESS_CERTIFICATION_DEFINITION, AccessCertificationDefinitionType.class,
            ObjectManager.MODEL, "accessCertificationDefinitions"),

    ACCESS_CERTIFICATION_CAMPAIGN(AccessCertificationCampaignType.COMPLEX_TYPE, SchemaConstantsGenerated.C_ACCESS_CERTIFICATION_CAMPAIGN, AccessCertificationCampaignType.class,
            ObjectManager.MODEL, "accessCertificationCampaigns"),

    // as for now, this has to remain disabled (they could be used e.g. in audit logs, when the repo will support them)
    //WORK_ITEM(WorkItemType.COMPLEX_TYPE, SchemaConstants.C_WORK_ITEM, WorkItemType.class, ObjectManager.WORKFLOW, "workItems"),
    //WF_PROCESS_INSTANCE(WfProcessInstanceType.COMPLEX_TYPE, SchemaConstants.C_WF_PROCESS_INSTANCE, WfProcessInstanceType.class, ObjectManager.WORKFLOW, "wfProcessInstances"),

    // this should be at end, because otherwise it presents itself as entry for all subtypes of ObjectType
    OBJECT(SchemaConstants.C_OBJECT_TYPE, SchemaConstants.C_OBJECT, ObjectType.class, ObjectManager.MODEL, "objects");

    public static enum ObjectManager {
        PROVISIONING, TASK_MANAGER, WORKFLOW, MODEL, REPOSITORY;
    }

    private QName type;
    private QName name;
    private Class<? extends ObjectType> classDefinition;
    private ObjectManager objectManager;
    private String restType;

    private ObjectTypes(QName type, QName name, Class<? extends ObjectType> classDefinition,
                        ObjectManager objectManager, String restType) {
        this.type = type;
        this.name = name;
        this.classDefinition = classDefinition;
        this.objectManager = objectManager;
        this.restType = restType;
    }

    public boolean isManagedByProvisioning() {
        return objectManager == ObjectManager.PROVISIONING;
    }

    public boolean isManagedByTaskManager() {
        return objectManager == ObjectManager.TASK_MANAGER;
    }

    public boolean isManagedByWorkflow() {
        return objectManager == ObjectManager.WORKFLOW;
    }

    public String getValue() {
        return type.getLocalPart();
    }

    public QName getQName() {
        return name;
    }

    public QName getTypeQName() {
        return type;
    }

    public Class<? extends ObjectType> getClassDefinition() {
        return classDefinition;
    }

    public String getRestType() {
        return restType;
    }

    public void setRestType(String restType) {
        this.restType = restType;
    }

    public String getObjectTypeUri() {
        return QNameUtil.qNameToUri(getTypeQName());
    }

    public ObjectManager getObjectManager() {
        return objectManager;
    }

    public static ObjectTypes getObjectType(String objectType) {
        for (ObjectTypes type : values()) {
            if (type.getValue().equals(objectType)) {
                return type;
            }
        }
        throw new IllegalArgumentException("Unsupported object type " + objectType);
    }

    public static ObjectTypes getObjectTypeFromTypeQName(QName typeQName) {
        if (typeQName == null) {
            return null;
        }
        // HACK WARNING! FIXME
        // UGLY HORRIBLE TERRIBLE AWFUL HACK FOLLOWS
        // The JAXB fails to correctly process QNames in default namespace (no prefix)
        // e.g it will not understand this: type="RoleType", even if defatult namespace
        // is set, it will parse it as null namespace.
        // Therefore substitute null namespace with common namespace
        if (typeQName.getNamespaceURI() == null || typeQName.getNamespaceURI().isEmpty()) {
            typeQName = new QName(SchemaConstants.NS_C, typeQName.getLocalPart());
        }
        // END OF UGLY HACK

        for (ObjectTypes type : values()) {
            if (QNameUtil.match(type.getTypeQName(), typeQName)) {
                return type;
            }
        }
        throw new IllegalArgumentException("Unsupported object type qname " + typeQName);
    }

    public static ObjectTypes getObjectTypeFromUri(String objectTypeUri) {
        for (ObjectTypes type : values()) {
            if (type.getObjectTypeUri().equals(objectTypeUri)) {
                return type;
            }
        }
        throw new IllegalArgumentException("Unsupported object type uri " + objectTypeUri);
    }

    public static String getObjectTypeUri(String objectType) {
        return getObjectType(objectType).getObjectTypeUri();
    }

    public static Class<? extends ObjectType> getObjectTypeClass(String objectType) {
        for (ObjectTypes type : values()) {
            if (type.getValue().equals(objectType)) {
                return type.getClassDefinition();
            }
        }

        throw new IllegalArgumentException("Unsupported object type " + objectType);
    }

    @SuppressWarnings("unchecked")
    public static ObjectTypes getObjectType(Class<? extends ObjectType> objectType) {
        for (ObjectTypes type : values()) {
            if (type.getClassDefinition().equals(objectType)) {
                return type;
            }
        }
        // No match. Try with superclass.
        Class<?> superclass = objectType.getSuperclass();
        if (superclass != null && !superclass.equals(ObjectType.class)) {
            return getObjectType((Class<? extends ObjectType>) superclass);
        }

        throw new IllegalArgumentException("Unsupported object type " + objectType);
    }

    public static boolean isManagedByProvisioning(ObjectType object) {
        Validate.notNull(object, "Object must not be null.");

        return isClassManagedByProvisioning(object.getClass());
    }

    public static boolean isClassManagedByProvisioning(Class<? extends ObjectType> clazz) {
        Validate.notNull(clazz, "Class must not be null.");

        for (ObjectTypes type : ObjectTypes.values()) {
            if (type.getClassDefinition().isAssignableFrom(clazz)) {
                return type.isManagedByProvisioning();
            }
        }

        return false;
    }

    public static boolean isObjectTypeManagedByProvisioning(Class<? extends ObjectType> objectType) {
        Validate.notNull(objectType, "Object type must not be null.");

        for (ObjectTypes type : ObjectTypes.values()) {
            if (type.getClassDefinition().equals(objectType)) {
                return type.isManagedByProvisioning();
            }
        }

        return false;
    }

    public static boolean isObjectTypeManagedByProvisioning(String objectType) {
        Validate.notEmpty(objectType, "Object type must not be null.");

        for (ObjectTypes type : ObjectTypes.values()) {
            if (type.getTypeQName().getLocalPart().equals(objectType)) {
                return type.isManagedByProvisioning();
            }
        }

        return false;
    }

    public static ObjectManager getObjectManagerForClass(Class<? extends ObjectType> clazz) {
        Validate.notNull(clazz, "Class must not be null.");

        for (ObjectTypes type : ObjectTypes.values()) {
            if (type.getClassDefinition().isAssignableFrom(clazz)) {
                return type.getObjectManager();
            }
        }

        return null;
    }

    public static Class getClassFromRestType(String restType) {
        Validate.notNull(restType, "Rest type must not be null.");

        for (ObjectTypes type : ObjectTypes.values()) {
            if (type.getRestType().equals(restType)) {
                return type.getClassDefinition();
            }
        }

        throw new IllegalArgumentException("Not suitable class found for rest type: " + restType);
    }

    public static List<Class<? extends ObjectType>> getAllObjectTypes() {
        List<Class<? extends ObjectType>> list = new ArrayList<>();
        for (ObjectTypes t : ObjectTypes.values()) {
            list.add(t.getClassDefinition());
        }

        return list;
    }
}


text:
/* Autogenerated with Kurento Idl */

/*
 * (C) Copyright 2013-2015 Kurento (http://kurento.org/)
 *
 * Licensed 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.
 */

var inherits = require('inherits');

var kurentoClient = require('kurento-client');

var disguise = kurentoClient.disguise;

var ChecktypeError = kurentoClient.checkType.ChecktypeError;

var Filter = require('kurento-client-core').abstracts.Filter;

/**
 * @classdesc
 *  Generic OpenCV Filter
 *
 * @abstract
 * @extends module:core/abstracts.Filter
 *
 * @constructor module:filters/abstracts.OpenCVFilter
 */
function OpenCVFilter(){
  OpenCVFilter.super_.call(this);
};
inherits(OpenCVFilter, Filter);

/**
 * @alias module:filters/abstracts.OpenCVFilter.constructorParams
 */
OpenCVFilter.constructorParams = {
};

/**
 * @alias module:filters/abstracts.OpenCVFilter.events
 *
 * @extends module:core/abstracts.Filter.events
 */
OpenCVFilter.events = Filter.events;

/**
 * Checker for {@link module:filters/abstracts.OpenCVFilter}
 *
 * @memberof module:filters/abstracts
 *
 * @param {external:String} key
 * @param {module:filters/abstracts.OpenCVFilter} value
 */
function checkOpenCVFilter(key, value)
{
  if(!(value instanceof OpenCVFilter))
    throw ChecktypeError(key, OpenCVFilter, value);
};

module.exports = OpenCVFilter;

OpenCVFilter.check = checkOpenCVFilter;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using EPiServer.Reference.Commerce.Shared.AutomapperProfiles;
using EPiServer.Reference.Commerce.Shared.Models;
using EPiServer.Reference.Commerce.Site.Features.Global.Shared.Models;
using Xunit;

namespace EPiServer.Reference.Commerce.Site.Tests.Features.Shared.Automapper.Controllers
{
    public class AutomapperControllerTests : IDisposable
    {
        public AutomapperControllerTests()
        {
            Mapper.Initialize(cfg => cfg.AddProfile<ProductProfile>());
        }

        [Fact]
        public void string_is_converted_to_integer()
        {
            var apiProduct = new ApiProductResult()
            {
                ResultId = "10",
                ResultDate = "10/12/2016",
                ResultDay = "Friday"
            };

            var item = Mapper.Map<ApiProductResult, ProductItem>(apiProduct);

            Assert.Equal(11, item.ProductId);
        }

        public void Dispose()
        {

        }
    }
}


text:
<?php

namespace MoySklad\Components\Specs\QuerySpecs\Reports;

use MoySklad\Components\Specs\QuerySpecs\QuerySpecs;

class SalesReportQuerySpecs extends QuerySpecs {
    protected static $cachedDefaultSpecs = null;
    public function getDefaults()
    {
        $res = parent::getDefaults();
        $res['product.id'] = null;
        $res['counterparty.id'] = null;
        $res['organization.id'] = null;
        $res['store.id'] = null;
        $res['project.id'] = null;
        $res['retailStore.id'] = null;
        return $res;
    }
}


text:
package net.mindengine.galen.suite.reader;

import java.util.LinkedList;
import java.util.List;

import net.mindengine.galen.parser.VarsContext;
import net.mindengine.galen.parser.GalenPageTestReader;
import net.mindengine.galen.parser.SyntaxException;
import net.mindengine.galen.suite.GalenPageAction;
import net.mindengine.galen.suite.GalenPageTest;

public class PageNode extends Node<GalenPageTest> {

    public PageNode(Line line) {
        super(line);
    }

    @Override
    public Node<?> processNewNode(Line line) {
        ActionNode actionNode = new ActionNode(line);
        add(actionNode);
        return actionNode;
    }

    @Override
    public GalenPageTest build(VarsContext context) {
        GalenPageTest pageTest;
        try {
            pageTest = GalenPageTestReader.readFrom(context.process(getArguments()));
        }
        catch (SyntaxException e) {
            e.setLine(getLine());
            throw e;
        }

        List<GalenPageAction> actions = new LinkedList<GalenPageAction>();
        pageTest.setActions(actions);

        for (Node<?> childNode : getChildNodes()) {
            if (childNode instanceof ActionNode) {
                ActionNode actionNode = (ActionNode)childNode;
                actions.add(actionNode.build(context));
            }
        }

        return pageTest;
    }

}


text:
import boto3
from botocore.exceptions import ClientError
import pytest
import sure  # noqa # pylint: disable=unused-import

from moto import mock_elb
from uuid import uuid4

@mock_elb
def test_create_lb_cookie_stickiness_policy():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    lbc_policies = balancer["Policies"]["LBCookieStickinessPolicies"]
    lbc_policies.should.have.length_of(0)

    client.create_lb_cookie_stickiness_policy(
        LoadBalancerName=lb_name, PolicyName="pname", CookieExpirationPeriod=42
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    policies = balancer["Policies"]
    lbc_policies = policies["LBCookieStickinessPolicies"]
    lbc_policies.should.have.length_of(1)
    lbc_policies[0].should.equal({"PolicyName": "pname", "CookieExpirationPeriod": 42})

@mock_elb
def test_create_lb_cookie_stickiness_policy_no_expiry():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    lbc_policies = balancer["Policies"]["LBCookieStickinessPolicies"]
    lbc_policies.should.have.length_of(0)

    client.create_lb_cookie_stickiness_policy(
        LoadBalancerName=lb_name, PolicyName="pname"
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    policies = balancer["Policies"]
    lbc_policies = policies["LBCookieStickinessPolicies"]
    lbc_policies.should.have.length_of(1)
    lbc_policies[0].should.equal({"PolicyName": "pname"})

@mock_elb
def test_create_app_cookie_stickiness_policy():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    lbc_policies = balancer["Policies"]["AppCookieStickinessPolicies"]
    lbc_policies.should.have.length_of(0)

    client.create_app_cookie_stickiness_policy(
        LoadBalancerName=lb_name, PolicyName="pname", CookieName="cname"
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    policies = balancer["Policies"]
    lbc_policies = policies["AppCookieStickinessPolicies"]
    lbc_policies.should.have.length_of(1)
    lbc_policies[0].should.equal({"CookieName": "cname", "PolicyName": "pname"})

@mock_elb
def test_create_lb_policy():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    client.create_load_balancer_policy(
        LoadBalancerName=lb_name,
        PolicyName="ProxyPolicy",
        PolicyTypeName="ProxyProtocolPolicyType",
        PolicyAttributes=[{"AttributeName": "ProxyProtocol", "AttributeValue": "true"}],
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    policies = balancer["Policies"]
    policies.should.have.key("OtherPolicies").equal(["ProxyPolicy"])

@mock_elb
def test_set_policies_of_listener():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[
            {"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080},
            {"Protocol": "https", "LoadBalancerPort": 81, "InstancePort": 8081},
        ],
        AvailabilityZones=["us-east-1a"],
    )

    client.create_app_cookie_stickiness_policy(
        LoadBalancerName=lb_name, PolicyName="pname", CookieName="cname"
    )

    client.set_load_balancer_policies_of_listener(
        LoadBalancerName=lb_name, LoadBalancerPort=81, PolicyNames=["pname"]
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]

    http_l = [
        listener
        for listener in balancer["ListenerDescriptions"]
        if listener["Listener"]["Protocol"] == "HTTP"
    ][0]
    http_l.should.have.key("PolicyNames").should.equal([])

    https_l = [
        listener
        for listener in balancer["ListenerDescriptions"]
        if listener["Listener"]["Protocol"] == "HTTPS"
    ][0]
    https_l.should.have.key("PolicyNames").should.equal(["pname"])

@mock_elb
def test_set_policies_of_backend_server():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[
            {"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080},
            {"Protocol": "https", "LoadBalancerPort": 81, "InstancePort": 8081},
        ],
        AvailabilityZones=["us-east-1a"],
    )

    client.create_app_cookie_stickiness_policy(
        LoadBalancerName=lb_name, PolicyName="pname", CookieName="cname"
    )

    client.set_load_balancer_policies_for_backend_server(
        LoadBalancerName=lb_name, InstancePort=8081, PolicyNames=["pname"]
    )

    balancer = client.describe_load_balancers(LoadBalancerNames=[lb_name])[
        "LoadBalancerDescriptions"
    ][0]
    balancer.should.have.key("BackendServerDescriptions")
    desc = balancer["BackendServerDescriptions"]
    desc.should.have.length_of(1)
    desc[0].should.equal({"InstancePort": 8081, "PolicyNames": ["pname"]})

@mock_elb
def test_describe_load_balancer_policies__initial():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    resp = client.describe_load_balancer_policies(LoadBalancerName=lb_name)
    resp.should.have.key("PolicyDescriptions").equals([])

@mock_elb
def test_describe_load_balancer_policies():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    client.create_load_balancer_policy(
        LoadBalancerName=lb_name,
        PolicyName="ProxyPolicy",
        PolicyTypeName="ProxyProtocolPolicyType",
        PolicyAttributes=[{"AttributeName": "ProxyProtocol", "AttributeValue": "true"}],
    )

    client.create_load_balancer_policy(
        LoadBalancerName=lb_name,
        PolicyName="DifferentPolicy",
        PolicyTypeName="DifferentProtocolPolicyType",
        PolicyAttributes=[{"AttributeName": "DiffProtocol", "AttributeValue": "true"}],
    )

    resp = client.describe_load_balancer_policies(LoadBalancerName=lb_name)
    resp.should.have.key("PolicyDescriptions").length_of(2)

    resp = client.describe_load_balancer_policies(
        LoadBalancerName=lb_name, PolicyNames=["DifferentPolicy"]
    )
    resp.should.have.key("PolicyDescriptions").length_of(1)
    resp["PolicyDescriptions"][0].should.equal(
        {
            "PolicyName": "DifferentPolicy",
            "PolicyTypeName": "DifferentProtocolPolicyType",
            "PolicyAttributeDescriptions": [
                {"AttributeName": "DiffProtocol", "AttributeValue": "true"}
            ],
        }
    )

@mock_elb
def test_describe_unknown_load_balancer_policy():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    with pytest.raises(ClientError) as exc:
        client.describe_load_balancer_policies(
            LoadBalancerName=lb_name, PolicyNames=["unknown"]
        )
    err = exc.value.response["Error"]
    err["Code"].should.equal("PolicyNotFound")

@mock_elb
def test_delete_load_balancer_policies():
    lb_name = str(uuid4())[0:6]

    client = boto3.client("elb", region_name="us-east-1")
    client.create_load_balancer(
        LoadBalancerName=lb_name,
        Listeners=[{"Protocol": "http", "LoadBalancerPort": 80, "InstancePort": 8080}],
        AvailabilityZones=["us-east-1a"],
    )

    client.create_load_balancer_policy(
        LoadBalancerName=lb_name,
        PolicyName="ProxyPolicy",
        PolicyTypeName="ProxyProtocolPolicyType",
        PolicyAttributes=[{"AttributeName": "ProxyProtocol", "AttributeValue": "true"}],
    )

    client.create_load_balancer_policy(
        LoadBalancerName=lb_name,
        PolicyName="DifferentPolicy",
        PolicyTypeName="DifferentProtocolPolicyType",
        PolicyAttributes=[{"AttributeName": "DiffProtocol", "AttributeValue": "true"}],
    )

    client.delete_load_balancer_policy(
        LoadBalancerName=lb_name, PolicyName="ProxyPolicy"
    )

    resp = client.describe_load_balancer_policies(LoadBalancerName=lb_name)
    resp.should.have.key("PolicyDescriptions").length_of(1)


text:
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public final class MainPanel extends JPanel {
    private final JComboBox<? extends Enum> verticalOrientationChoices = new JComboBox<>(VerticalOrientation.values());
    private final JComboBox<? extends Enum> justificationChoices       = new JComboBox<>(Justification.values());
    private final TitledBorder border = BorderFactory.createTitledBorder("Test Test");
    private final JPanel panel = new JPanel();

    public MainPanel() {
        super(new BorderLayout());
        verticalOrientationChoices.addItemListener(new ItemListener() {
            @Override public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    initTitleBorder();
                }
            }
        });
        justificationChoices.addItemListener(new ItemListener() {
            @Override public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    initTitleBorder();
                }
            }
        });
        panel.setBorder(border);

        JPanel p2 = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridheight = 1;
        c.gridx   = 0;
        c.insets  = new Insets(5, 5, 5, 0);
        c.anchor  = GridBagConstraints.WEST;
        c.gridy   = 0; p2.add(new JLabel(" TitlePosition"), c);
        c.gridy   = 1; p2.add(new JLabel(" TitleJustification"), c);
        c.gridx   = 1;
        c.weightx = 1d;
        c.fill    = GridBagConstraints.HORIZONTAL;
        c.gridy   = 0; p2.add(verticalOrientationChoices, c);
        c.gridy   = 1; p2.add(justificationChoices, c);

        add(p2, BorderLayout.NORTH); add(panel);
        setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        setPreferredSize(new Dimension(320, 240));
    }
    private void initTitleBorder() {
        VerticalOrientation vo = (VerticalOrientation) verticalOrientationChoices.getSelectedItem();
        border.setTitlePosition(vo.mode);
        Justification jc = (Justification) justificationChoices.getSelectedItem();
        border.setTitleJustification(jc.mode);
        panel.repaint();
    }

    public static void main(String... args) {
        EventQueue.invokeLater(new Runnable() {
            @Override public void run() {
                createAndShowGUI();
            }
        });
    }
    public static void createAndShowGUI() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException
               | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }
        JFrame frame = new JFrame("@title@");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MainPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

enum VerticalOrientation {
    DEFAULT_POSITION (TitledBorder.DEFAULT_POSITION, "Default Position"),
    ABOVE_TOP        (TitledBorder.ABOVE_TOP,        "Above Top"),
    TOP              (TitledBorder.TOP,              "Top"),
    BELOW_TOP        (TitledBorder.BELOW_TOP,        "Below Top"),
    ABOVE_BOTTOM     (TitledBorder.ABOVE_BOTTOM,     "Above Bottom"),
    BOTTOM           (TitledBorder.BOTTOM,           "Bottom"),
    BELOW_BOTTOM     (TitledBorder.BELOW_BOTTOM,     "Below Bottom");
    public final int mode;
    private final String description;
    VerticalOrientation(int mode, String description) {
        this.mode = mode;
        this.description = description;
    }
    @Override public String toString() {
        return description;
    }
}

enum Justification {
    DEFAULT_JUSTIFICATION (TitledBorder.DEFAULT_JUSTIFICATION, "Default Justification"),
    LEFT                  (TitledBorder.LEFT,                  "Left"),
    CENTER                (TitledBorder.CENTER,                "Center"),
    RIGHT                 (TitledBorder.RIGHT,                 "Right"),
    LEADING               (TitledBorder.LEADING,               "Leading"),
    TRAILING              (TitledBorder.TRAILING,              "Trailing");
    public final int mode;
    private final String description;
    Justification(int mode, String description) {
        this.mode = mode;
        this.description = description;
    }
    @Override public String toString() {
        return description;
    }
}


text:
`DParser` is a simple but powerful tool for parsing.  You
can specify the form of the text to be parsed using a combination of
regular expressions and grammar productions.  Because of the
parsing technique (technically a scannerless GLR parser based on the
Tomita algorithm) there are no restrictions.  The grammar can be
ambiguous, right or left recursive, have any number of null
productions,
and because there is no separate tokenizer, can include whitespace in
terminals and have terminals which are prefixes of other terminals.
`DParser` handles not just well formed computer languages and data
files, but just about any wacky situation that occurs in the real world.
The result is natural grammars and powerful parsing.

## Features

* Powerful GLR parsing
* Simple EBNF-style grammars and regular expression terminals
* State-specific symbol table
* Priorities and associativities for token and rules
* Built-in error recovery
* Can be compiled to work with or without the Boehm garbage collector
* Speculative actions (for semantic disambiguation)
* Auto-building of parse tree (optionally)
* Final actions as you go, or on the complete parse tree
* Tree walkers and default actions (multi-pass compilation support)
* Symbol table built for ambiguous parsing
* Partial parses, recursive parsing, parsing starting with any non-terminal
* Whitespace can be specified as a subgrammar
* External (C call interface) tokenizers and terminal scanners
* Good asymptotic efficiency
* Comes with ANSI-C, Python and Verilog grammars
* Comes with full source
* Portable C for easy compilation and linking
* BSD licence, so you can include it in your application without worrying about licensing

## Example Grammars

* [ANSI-C](ansic/ansic.g)
* [Python](tests/python.test.g)
* [Verilog](verilog/verilog.g)

## Documentation
* [Man page for parser generator](make_dparser.cat)
* [Manual](docs/manual.md)
* [FAQ](docs/faq.md)

## Public Headers

* [dparse.h](dparse.h) - main parser data structures and functions
* [dparse_tables.h](dparse_tables.h) - parse tables data structures
* [dsymtab.h](dsymtab.h) - optional symbol table

## Building

* To build: `gmake` -- only available with source code package
* To test: `gmake test` -- only available with source code package
* To install: `gmake install` -- binary or source code packages

For python support: `cd python; gmake install`

## Makefile Options

* `D_USE_GC`: set to 1 to use the Boehm garbage collector
* `D_DEBUG`: set to 1 to compile with debugging support (`-g`)
* `D_OPTIMIZE`: set to 1 to compile with optimizations (`-O3`)
* `D_PROFILE`: set to 1 to compile with profiling support (`-pg`)
* `D_LEAK_DETECT`: set to 1 to compile with memory leak detection (`-lleak`)
* `D_USE_FREELISTS`: set to 1 to use free lists instead of straign free/malloc (defaults to 1)

## Contact
Contact the author: `jplevyak` `at` `gmail`


text:
Changelog
===
*2019 December 26*

Since now remi is adopting class properties to setup css style and html attributes to make the applicable properties explicit.
This means that for example, to change a widget background you can now do:

```python
    mywidget.css_background_color = 'green'
```

The old method to setup style and attributes is still accepted:

```python
    mywidget.style['background-color'] = 'green'
```

*2019 November 21*

Widget class has no more **append** method. This means it cannot be used as a Container.
Use the new class Container as a generic container instead.
This allows higher code consistency.

*2019 April 1*

Event listener registration can now be done by the **do** instruction instead of **connect** (that stays available for compatibility reasons).
i.e.
```python
mybutton.onclick.do(myevent_listener)
```

*Older changes*

The current branch includes improvements about resource files handling.
App constructor accepts **static_file_path** parameter. Its value have to be a dictionary, where elements represents named resources paths.

i.e.
```python
super(MyApp, self).__init__(*args, static_file_path = {'my_resources':'./files/resources/', 'my_other_res':'./other/'})
```
To address a specific resource, the user have to specify the resource folder key, prepending it to the filename in the format **'/key:'**
i.e.
```python
my_widget.attributes['background-image'] = "url('/my_resources:image.png')"
```
Subfolders are accepted, and so:
```python
my_widget.attributes['background-image'] = "url('/my_resources:subfolder/other_subfolder/image.png')"
```

The event TextInput.onenter is no longer supported.

The events TextInput.onkeydown and TextInput.onkeyup are now different, and require a different listener format. There is an additional parameter keycode.

The TextInput.onchange event now occurs also in case of Enter key pressed, if TextInput is single_line.


text:
@CHARSET "UTF-8";

.circular {
	width: 300px;
	height: 300px;
	border-radius: 150px;
	-webkit-border-radius: 150px;
	-moz-border-radius: 150px;
	background: url(<%= request.getContextPath() %>/resources/pics/prof_man1.jpg) no-repeat;
	}


text:
package loon.core.graphics.component;

public class CollisionPointQuery implements CollisionQuery {

	private float x;

	private float y;

	private Class<?> cls;

	public void init(float x, float y, Class<?> cls) {
		this.x = x;
		this.y = y;
		this.cls = cls;
	}

	@Override
	public boolean checkCollision(Actor actor) {
		return this.cls != null && !this.cls.isInstance(actor) ? false : actor
				.containsPoint(this.x, this.y);
	}
}


text:
package skidbladnir
import scala.collection.mutable.{Map => MutMap},
       java.lang.reflect.Field,
       java.lang.Class

protected class Shadow (val proto:Prototype) extends Handle with Functions{
  //Fields
  val compoFlags = new CompoFlags
  var runtime:Runtime = null
  var name:String = null
  var compoThtead:Thread = null
  var compoThteadNotify:Boolean = true
  val compoInterfaces = MutMap[String, IntrDescr]() //Supported interfaces list
  var interfCount = 0
  val rootConnecions =  MutMap[Shadow, IntrDescr]() //List of component which connect their the root interface, to this.
  //Runtime methods (create/destroy)
  def init() = {
    //Get field map
    val fm = MutMap[Half, (String, String)]()  // -> (name, type name)
    var c:Class[_] = proto.getClass()
    while(c != null){
      c.getDeclaredFields().foreach(e => {
        e.setAccessible(true)
        val o = e.get(proto)
        if(o.isInstanceOf[Half]){
          fm += (o.asInstanceOf[Half] -> (e.getName(), e.getType().getName()))}})
      c = c.getSuperclass()}
    //Check interfaces names
    fm.foreach(e =>{
      val (in,itn) = (e._2._1,e._2._2)
      val sp = itn.split("\\$")
      if(sp.size < 2){throw new CompoException("Interface half can't be defined in outside object, extends Interface")}
      val ccn = sp(sp.size - 1)
      if(!(ccn == "Am" || ccn == "Pm")){throw new CompoException("Incorrect interface half class name '" + ccn + "' mast be 'Am' or 'Pm'")}})
    //Matching interfaces
    var hil = List[String]()
    val ci = MutMap[String, IntrDescr]()
    compoInterfaces.foreach(e =>{
      val id = e._2; val in = fm(id.halfLink)
      id.name = in._1; id.typeName = in._2.split("\\$").init.mkString("$")
      ci += (id.name -> id)
      hil :+= id.name})
    compoInterfaces.clear(); compoInterfaces ++= ci
    //Matching root
     if(this.isInstanceOf[CompoShadow]){
       val ri = this.asInstanceOf[CompoShadow].rootIntrface
       val in = fm(ri.halfLink)
       ri.name = in._1; ri.typeName = in._2.split("\\$").init.mkString("$")
       hil :+= ri.name}
    //Check interfaces
    compoInterfaces.foreach(e =>{checkIntrface(e._2.halfLink, e._2.mono_multi, e._1)})
    //Check root
    if(this.isInstanceOf[CompoShadow]){
      val ri = this.asInstanceOf[CompoShadow].rootIntrface
      checkIntrface(ri.halfLink, ri.mono_multi, ri.name)}
    //Add interface list
    val fl = this.getClass().getSuperclass().getDeclaredField("interfaces")
    fl.setAccessible(true)
    fl.set(this, hil)
  }
  def start() = {
     if(compoThtead != null && compoFlags.stat == 2){compoThtead.start()} //Start internal thread
  }
  def deinit() = {
  }
  //Runtime methods (interfaces)
  def getCompoInterface(in:String):IntrDescr = {
   // if(compoFlags.stat == 5){throw new CompoException("Component '" + this + "' not exist, state: " +  compoFlags.stat)}
    if(compoInterfaces.contains(in)){
      compoInterfaces(in)}
    else{
      if(proto.isInstanceOf[Compo]){
        this.asInstanceOf[CompoShadow].rootIntrface}
      else{
        null}}
  }
  //Prototype methods
  def addInterface(jack_plug:Boolean, mono_multi:Boolean, intr:Half, connection:(Handle)=>Unit, disconnection:(Handle,Int)=>Unit, switching:(Handle, Handle)=>Unit) = { //Add to interface list
    if(compoFlags.stat != 0){throw new CompoException("You can not add inetefaces in runtime")}
    interfCount += 1
    compoInterfaces += (interfCount.toString -> new IntrDescr(this, null, null, intr, jack_plug, mono_multi, false, connection, disconnection, switching))
  }
  //Functions
  def checkIntrface(intr:Half, mono_multi:Boolean, in:String) = {
    val ic = getAmOrPmClass(intr.getClass())
    try{
      val af = ic.getDeclaredField("imports")
      val ftn = af.getType().getName()
      if(mono_multi){
        val s = ftn.split("\\$").last
        if(!(s == "Am" ||s == "Pm")){throw new Exception("Incorrect type")}}
      else{
        val s = ftn.split("\\.").last
        if(s != "Map"){throw new Exception("Incorrect type")}}}
    catch{
      case e:Exception => {
        throw new CompoException("Incorrect field 'imports' in intrface '" + in + "' of " + this + " exeption: " + e)}}
  }
}

class CompoFlags {
 // var exist = false //Component exist
  var operation = 0 //Connection/disconnection
  var stat = 0     //0-init, 1-construction, 2-work, 3-prepare 4-destruction, 5-die
}


text:
playcurrentdir() {
    mpvp <(find "$PWD" -type f -follow)
}

playdir() {
    if [[ $# == 0 ]]; then
        echo "playdir requires one or more directories on input."
    else
        if [[ $(uname) == "Linux" ]]; then READLINK=readlink;
        else READLINK=greadlink; fi
        mpvshuf --playlist <(find "$@" -type f -follow -exec $READLINK -f {} \;)
        unset READLINK
    fi
}

alias mpvnova='mpv --no-video'
alias mpvshuf='mpvnova --shuffle --loop-playlist inf'
alias mpvp='mpvshuf --playlist'
alias pcd='playcurrentdir'
alias pd='playdir'


text:
<ScrollView sdkExampleTitle sdkToggleNavButton>
    <StackLayout class="form">
        <StackLayout class="input-field">

            <TextField class="input input-border" [(ngModel)]="fileName" hint="Enter new file name"></TextField>
        </StackLayout>
        <Button class="btn btn-primary btn-active" text="Change file name" (tap)="onFileRename()"></Button>

        <StackLayout class="input-field">

            <TextField class="input input-border" [(ngModel)]="folderName" hint="Enter new folder name"></TextField>
        </StackLayout>
        <Button class="btn btn-primary btn-active" text="Change folder name" (tap)="onFolderRename()"></Button>

    </StackLayout>
</ScrollView>


text:
layout: article
title: "Furry hat snuggling a Siamese cat"
excerpt: "PaperFaces portrait of @ihatealexwright drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-ihatealexwright-twitter-lg.jpg
  thumb: paperfaces-ihatealexwright-twitter-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53]
---

PaperFaces portrait of [@ihatealexwright](http://twitter.com/ihatealexwright).

{% include paperfaces-boilerplate.html %}


text:
<link rel="import" href="src/paper-radio-button/paper-radio-button.html">
<link rel="import" href="paper_ripple_nodart.html">
<link rel="import" href="../../packages/core_elements/core_a11y_keys_nodart.html">


text:
(async function testRemoteObjects(testRunner) {

  const { dp, session } = await testRunner.startBlank('Tests ConsoleOM APIs with unique argument behavior.');

  const ConsoleTestHelper = await testRunner.loadScript('./resources/console-test-helper.js');
  const consoleHelper = new ConsoleTestHelper(testRunner, dp,
    (expression, contextId) => dp.Runtime.evaluate({ expression, contextId })
  );
  dp.Runtime.enable();
  dp.DOM.enable();
  const response1 = await dp.Runtime.onceExecutionContextCreated();
  const pageContextId = response1.params.context.id; // main page
  session.evaluate(`
    window.frame = document.createElement('iframe');
    frame.src = '${testRunner.url('../resources/blank.html')}';
    document.body.appendChild(frame);
  `);

  const response2 = await dp.Runtime.onceExecutionContextCreated();
  const frameContextId = response2.params.context.id; // IFrame

  dp.Runtime.onConsoleAPICalled(({params}) => {
    const firstParamValue = params.args[0].value;
    const value = params.type === "timeEnd" ? firstParamValue.split(':')[0] : firstParamValue;
    testRunner.log(`${params.type}: ${value}`);
  });

  await testRunner.runTestSuite([
    async function testConsoleAssertNoContext() {
      await consoleHelper.testConsoleAssert();
    },
    async function testConsoleTimeNoContext() {
      await consoleHelper.testConsoleTime();
    },
    async function testConsoleCountNoContext() {
      await consoleHelper.testConsoleCount();
    },
    async function testConsoleAssertPageContext() {
      await consoleHelper.testConsoleAssert(pageContextId);
    },
    async function testConsoleTimePageContext() {
      await consoleHelper.testConsoleTime(pageContextId);
    },
    async function testConsoleCountPageContext() {
      await consoleHelper.testConsoleCount(pageContextId);
    },
    async function testConsoleAssertFrameContext() {
      await consoleHelper.testConsoleAssert(frameContextId);
    },
    async function testConsoleTimeFrameContext() {
      await consoleHelper.testConsoleTime(frameContextId);
    },
    async function testConsoleCountFrameContext() {
      await consoleHelper.testConsoleCount(frameContextId);
    },
  ]);
  testRunner.completeTest();

});


text:
package org.apache.hadoop.hbase.regionserver.wal;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * A Future on a filesystem sync call. It given to a client or 'Handler' for it to wait on till the
 * sync completes.
 *

 * Handlers coming in call append, append, append, and then do a flush/sync of the edits they have
 * appended the WAL before returning. Since sync takes a while to complete, we give the Handlers
 * back this sync future to wait on until the actual HDFS sync completes. Meantime this sync future
 * goes across a queue and is handled by a background thread; when it completes, it finishes up the
 * future, the handler get or failed check completes and the Handler can then progress.
 *

 * This is just a partial implementation of Future; we just implement get and failure.
 *

 * There is not a one-to-one correlation between dfs sync invocations and instances of this class. A
 * single dfs sync call may complete and mark many SyncFutures as done; i.e. we batch up sync calls
 * rather than do a dfs sync call every time a Handler asks for it.
 *

 * SyncFutures are immutable but recycled. Call #reset(long, Span) before use even if it the first
 * time, start the sync, then park the 'hitched' thread on a call to #get().
 */
@InterfaceAudience.Private
class SyncFuture {
  // Implementation notes: I tried using a cyclicbarrier in here for handler and sync threads
  // to coordinate on but it did not give any obvious advantage and some issues with order in which
  // events happen.
  private static final long NOT_DONE = -1L;

  /**
   * The transaction id of this operation, monotonically increases.
   */
  private long txid;

  /**
   * The transaction id that was set in here when we were marked done. Should be equal or > txnId.
   * Put this data member into the NOT_DONE state while this class is in use.
   */
  private long doneTxid;

  /**
   * If error, the associated throwable. Set when the future is 'done'.
   */
  private Throwable throwable;

  private Thread t;

  private boolean forceSync;

  /**
   * Call this method to clear old usage and get it ready for new deploy.
   * @param txid the new transaction id
   * @return this
   */
  synchronized SyncFuture reset(long txid) {
    if (t != null && t != Thread.currentThread()) {
      throw new IllegalStateException();
    }
    t = Thread.currentThread();
    if (!isDone()) {
      throw new IllegalStateException("" + txid + " " + Thread.currentThread());
    }
    this.doneTxid = NOT_DONE;
    this.txid = txid;
    this.throwable = null;
    return this;
  }

  @Override
  public synchronized String toString() {
    return "done=" + isDone() + ", txid=" + this.txid;
  }

  synchronized long getTxid() {
    return this.txid;
  }

  synchronized boolean isForceSync() {
    return forceSync;
  }

  synchronized SyncFuture setForceSync(boolean forceSync) {
    this.forceSync = forceSync;
    return this;
  }

  /**
   * @param txid the transaction id at which this future 'completed'.
   * @param t Can be null. Set if we are 'completing' on error (and this 't' is the error).
   * @return True if we successfully marked this outstanding future as completed/done. Returns false
   *         if this future is already 'done' when this method called.
   */
  synchronized boolean done(final long txid, final Throwable t) {
    if (isDone()) {
      return false;
    }
    this.throwable = t;
    if (txid < this.txid) {
      // Something badly wrong.
      if (throwable == null) {
        this.throwable =
            new IllegalStateException("done txid=" + txid + ", my txid=" + this.txid);
      }
    }
    // Mark done.
    this.doneTxid = txid;
    // Wake up waiting threads.
    notify();
    return true;
  }

  boolean cancel(boolean mayInterruptIfRunning) {
    throw new UnsupportedOperationException();
  }

  synchronized long get(long timeoutNs) throws InterruptedException,
      ExecutionException, TimeoutIOException {
    final long done = System.nanoTime() + timeoutNs;
    while (!isDone()) {
      wait(1000);
      if (System.nanoTime() >= done) {
        throw new TimeoutIOException(
            "Failed to get sync result after " + TimeUnit.NANOSECONDS.toMillis(timeoutNs)
                + " ms for txid=" + this.txid + ", WAL system stuck?");
      }
    }
    if (this.throwable != null) {
      throw new ExecutionException(this.throwable);
    }
    return this.doneTxid;
  }

  synchronized boolean isDone() {
    return this.doneTxid != NOT_DONE;
  }

  synchronized boolean isThrowable() {
    return isDone() && getThrowable() != null;
  }

  synchronized Throwable getThrowable() {
    return this.throwable;
  }
}


text:
package org.apache.spark

import java.util.concurrent.{ScheduledFuture, TimeUnit}

import scala.collection.mutable
import scala.concurrent.Future

import org.apache.spark.executor.TaskMetrics
import org.apache.spark.rpc.{ThreadSafeRpcEndpoint, RpcEnv, RpcCallContext}
import org.apache.spark.storage.BlockManagerId
import org.apache.spark.scheduler._
import org.apache.spark.util.{Clock, SystemClock, ThreadUtils, Utils}

/**
 * A heartbeat from executors to the driver. This is a shared message used by several internal
 * components to convey liveness or execution information for in-progress tasks. It will also
 * expire the hosts that have not heartbeated for more than spark.network.timeout.
  * 从执行者到driver的心跳,这是几个内部组件使用的共享消息,用于传达正在进行的任务的活动或执行信息。
  * 它也将使不超过spark.network.timeout的心跳的主机过期。
 */
private[spark] case class Heartbeat(
    executorId: String,
    taskMetrics: Array[(Long, TaskMetrics)], // taskId -> TaskMetrics
    blockManagerId: BlockManagerId)

/**
 * An event that SparkContext uses to notify HeartbeatReceiver that SparkContext.taskScheduler is
 * created.
  * SparkContext用于通知HeartbeatReceiver SparkContext.taskScheduler的事件。
 */
private[spark] case object TaskSchedulerIsSet
//过期死亡主机
private[spark] case object ExpireDeadHosts

private case class ExecutorRegistered(executorId: String)

private case class ExecutorRemoved(executorId: String)
//心跳反应
private[spark] case class HeartbeatResponse(reregisterBlockManager: Boolean)

/**
 * Lives in the driver to receive heartbeats from executors..
  * driver活着得到执行者的心跳
 */
private[spark] class HeartbeatReceiver(sc: SparkContext, clock: Clock)
  extends ThreadSafeRpcEndpoint with SparkListener with Logging {

  def this(sc: SparkContext) {
    this(sc, new SystemClock)
  }

  sc.addSparkListener(this)

  override val rpcEnv: RpcEnv = sc.env.rpcEnv

  private[spark] var scheduler: TaskScheduler = null

  // executor ID -> timestamp of when the last heartbeat from this executor was received
  //Key值executor ID,value值最后一次心跳被接收时间
  private val executorLastSeen = new mutable.HashMap[String, Long]

  // "spark.network.timeout" uses "seconds", while `spark.storage.blockManagerSlaveTimeoutMs` uses
  // "milliseconds"从节点超时120秒
  //"spark.network.timeout"使用"秒",而`spark.storage.blockManagerSlaveTimeoutMs`使用"毫秒"
  private val slaveTimeoutMs =
    sc.conf.getTimeAsMs("spark.storage.blockManagerSlaveTimeoutMs", "120s")
    //executor网络超时1200毫秒
  private val executorTimeoutMs =
    sc.conf.getTimeAsSeconds("spark.network.timeout", s"${slaveTimeoutMs}ms") * 1000

  // "spark.network.timeoutInterval" uses "seconds", while
  // "spark.storage.blockManagerTimeoutIntervalMs" uses "milliseconds"
  // "spark.network.timeoutInterval"使用"秒",
  // 而"spark.storage.blockManagerTimeoutIntervalMs"使用"毫秒"
  //指定检查BlockManager超时时间间隔
  private val timeoutIntervalMs =
    sc.conf.getTimeAsMs("spark.storage.blockManagerTimeoutIntervalMs", "60s")
    //Worker超时60秒
  private val checkTimeoutIntervalMs =
    sc.conf.getTimeAsSeconds("spark.network.timeoutInterval", s"${timeoutIntervalMs}ms") * 1000

  private var timeoutCheckingTask: ScheduledFuture[_] = null

  // "eventLoopThread" is used to run some pretty fast actions. The actions running in it should not
  // block the thread for a long time.
  //"eventLoopThread"用于运行一些非常快的动作,其中运行的操作不应该长时间堵塞线程。
  private val eventLoopThread =
    ThreadUtils.newDaemonSingleThreadScheduledExecutor("heartbeat-receiver-event-loop-thread")

  private val killExecutorThread = ThreadUtils.newDaemonSingleThreadExecutor("kill-executor-thread")

  override def onStart(): Unit = {
    //schedule和scheduleAtFixedRate的区别在于,如果指定开始执行的时间在当前系统运行时间之前,
    // scheduleAtFixedRate会把已经过去的时间也作为周期执行,而schedule不会把过去的时间算上。
    timeoutCheckingTask = eventLoopThread.scheduleAtFixedRate(new Runnable {
      override def run(): Unit = Utils.tryLogNonFatalError {
        //删除心跳超时的Executor,默认超进
        Option(self).foreach(_.ask[Boolean](ExpireDeadHosts))
      }
    }, 0, checkTimeoutIntervalMs, TimeUnit.MILLISECONDS)
  }

  override def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {

    // Messages sent and received locally
    //消息在本地发送和接收
    case ExecutorRegistered(executorId) =>
      executorLastSeen(executorId) = clock.getTimeMillis()
      context.reply(true)
    case ExecutorRemoved(executorId) =>
      executorLastSeen.remove(executorId)
      context.reply(true)
    case TaskSchedulerIsSet =>
      scheduler = sc.taskScheduler
      //使用方法askWithRetry[Boolean]请求TaskSchedulerIsSet消息并要求返回Boolean值
      //println("receiveAndReply:"+scheduler.applicationId()+"==="+scheduler.defaultParallelism())
      context.reply(true)
    case ExpireDeadHosts =>
      //删除心跳超时的executor
      expireDeadHosts()
      context.reply(true)

    // Messages received from executors
    //发送HeartbeatResponse消息到HeartbeatReceiver.receiveAndReply
     //接收executors发送的Heartbeat信息,
     //通知blockManagerMaster,此Executor上的blockManager依然活着,
    case heartbeat @ Heartbeat(executorId, taskMetrics, blockManagerId) =>
      if (scheduler != null) {
        if (executorLastSeen.contains(executorId)) {
          executorLastSeen(executorId) = clock.getTimeMillis()
          //submit,则该call方法自动在一个线程上执行,并且会返回执行结果Future对象
          eventLoopThread.submit(new Runnable {
            override def run(): Unit = Utils.tryLogNonFatalError {
              //用于更新Stage的各种测量数据.
              //blockManagerMaster持有blockManagerMasterActor发送BlockManagerHeartBeat消息到 BlockManagerMasterEndpoint
              val unknownExecutor = !scheduler.executorHeartbeatReceived(
                executorId, taskMetrics, blockManagerId)
              val response = HeartbeatResponse(reregisterBlockManager = unknownExecutor)
              //返回HeartbeatResponse
              context.reply(response)
            }
          })
        } else {
          // This may happen if we get an executor's in-flight heartbeat immediately
          // after we just removed it. It's not really an error condition so we should
          // not log warning here. Otherwise there may be a lot of noise especially if
          // we explicitly remove executors (SPARK-4134).
          //如果我们刚刚删除后立即得到执行者的飞行心跳,可能会发生这种情况,这不是真的错误的条件,所以我们不应该在这里记录警告。
          // 否则可能会有很多噪音,特别是如果我们明确删除执行器(SPARK-4134)。
          logDebug(s"Received heartbeat from unknown executor $executorId")
          context.reply(HeartbeatResponse(reregisterBlockManager = true))
        }
      } else {
        // Because Executor will sleep several seconds before sending the first "Heartbeat", this
        // case rarely happens. However, if it really happens, log it and ask the executor to
        // register itself again.
        //因为执行者将在发送第一个"心跳"之前睡眠几秒钟,这种情况很少发生,但是,如果真的发生了,请登录并请执行人再次注册。
        logWarning(s"Dropping $heartbeat because TaskScheduler is not ready yet")
        context.reply(HeartbeatResponse(reregisterBlockManager = true))
      }
  }

  /**
   * Send ExecutorRegistered to the event loop to add a new executor. Only for test.
    * 发送执行者注册到事件循环添加一个新的执行器,只用于测试
   *
   * @return if HeartbeatReceiver is stopped, return None. Otherwise, return a Some(Future) that
   *         indicate if this operation is successful.
    *         如果HeartbeatReceiver被停止,则返回None,否则,返回一个(Future),指示此操作是否成功。
   */
  def addExecutor(executorId: String): Option[Future[Boolean]] = {
    //向自己发送ExecutorRegistered消息,receiveAndReply方法接收消息
    Option(self).map(_.ask[Boolean](ExecutorRegistered(executorId)))
  }

  /**
   * If the heartbeat receiver is not stopped, notify it of executor registrations.
    * 如果心跳接收器未停止,请通知执行器注册。
   */
  override def onExecutorAdded(executorAdded: SparkListenerExecutorAdded): Unit = {
    addExecutor(executorAdded.executorId)
  }

  /**
   * Send ExecutorRemoved to the event loop to remove a executor. Only for test.
    * 将执行程序发送到事件循环以删除执行程序,只用于测试
   *
   * @return if HeartbeatReceiver is stopped, return None. Otherwise, return a Some(Future) that
   *         indicate if this operation is successful.
    *         如果HeartbeatReceiver被停止,则返回None,否则,返回一个(Future),指示此操作是否成功。
   */
  def removeExecutor(executorId: String): Option[Future[Boolean]] = {
    Option(self).map(_.ask[Boolean](ExecutorRemoved(executorId)))
  }

  /**
   * If the heartbeat receiver is not stopped, notify it of executor removals so it doesn't
   * log superfluous errors.
    * 如果心跳接收器没有停止,请通知它的执行器删除,否则不会记录多余的错误
   *
   * Note that we must do this after the executor is actually removed to guard against the
   * following race condition: if we remove an executor's metadata from our data structure
   * prematurely, we may get an in-flight heartbeat from the executor before the executor is
   * actually removed, in which case we will still mark the executor as a dead host later
   * and expire it with loud error messages.
    * 请注意:我们必须在执行者被实际删除以防止以下竞争条件之后执行此操作:
    * 如果我们过早地从数据结构中删除了执行者的元数据,则在执行者实际删除之前,我们可能会从执行器获取一个正在运行中的心跳,
    * 在这种情况下,我们仍然会将执行人标记为死主,稍后会出现大声错误讯息。
   */
  override def onExecutorRemoved(executorRemoved: SparkListenerExecutorRemoved): Unit = {
    removeExecutor(executorRemoved.executorId)
  }
  /**
   * 过期不活动机器
   */
  private def expireDeadHosts(): Unit = {
    logTrace("Checking for hosts with no recent heartbeats in HeartbeatReceiver.")
    val now = clock.getTimeMillis()
    for ((executorId, lastSeenMs) <- executorLastSeen) {//executorLastSeen最后一次接收到信息
      if (now - lastSeenMs > executorTimeoutMs) {
        //当前时间减去executor发送最新心跳时间大于超时时间,判断executor是不可用状态
        logWarning(s"Removing executor $executorId with no recent heartbeats: " +
          s"${now - lastSeenMs} ms exceeds timeout $executorTimeoutMs ms")
        scheduler.executorLost(executorId, SlaveLost("Executor heartbeat " +
          s"timed out after ${now - lastSeenMs} ms"))
          // Asynchronously kill the executor to avoid blocking the current thread
        //异步地杀死执行器以避免阻止当前线程
        killExecutorThread.submit(new Runnable {
          override def run(): Unit = Utils.tryLogNonFatalError {
            // Note: we want to get an executor back after expiring this one,
            // so do not simply call `sc.killExecutor` here (SPARK-8119)
            //注意:我们希望在过期之后让执行者回来,所以不要简单地在这里调用`sc.killExecutor`(SPARK-8119)
            sc.killAndReplaceExecutor(executorId)
          }
        })
        executorLastSeen.remove(executorId)
      }
    }
  }

  override def onStop(): Unit = {
    if (timeoutCheckingTask != null) {
      timeoutCheckingTask.cancel(true)
    }
    eventLoopThread.shutdownNow()
    killExecutorThread.shutdownNow()
  }
}

object HeartbeatReceiver {
  val ENDPOINT_NAME = "HeartbeatReceiver"
}


text:
namespace media {
namespace cast {

MockRtpPayloadFeedback::MockRtpPayloadFeedback() {
}

MockRtpPayloadFeedback::~MockRtpPayloadFeedback() {
}

}  // namespace cast
}  // namespace media


text:
/*
 * MPAO.hpp
 *
 *  Created on: 20 March 2015
 *      Author: cyosp
 */

#ifndef INCLUDES_MPA_API_REST_V1_MPAO_HPP_
#define INCLUDES_MPA_API_REST_V1_MPAO_HPP_

class MPAFactory;

#include "com/cyosp/mpa/core/MPA.hpp"

#include <boost/property_tree/ptree.hpp>
using boost::property_tree::ptree;

#include <map>
using std::map;

#include <string>
using std::string;

#include <vector>
using std::vector;

enum HttpRequestType
{
    GET, POST
};
enum ActionType
{
    NONE, LOGIN, ADD, DELETE, UPDATE
};

static const string INVALID_TOKEN = "Invalid token";
static const string TOKEN_ARGUMENT_NOT_FOUND = "Token argument not found";
static const string THERE_ARE_MISSING_PARAMETERS = "There are missing parameters";
static const string PASSWORDS_DONT_MATCH = "Passwords don't match";
static const string BAD_IDENTIFIER = "Bad identifier";
static const string BAD_PASSWORD = "Bad password";
static const string PASSWORD_SECURITY_TOO_LOW = "Password security is too low";
static const string USER_ALREADY_EXISTS = "User already exists";
static const string USER_ACCOUNT_BLOCKED = "User account is blocked";
static const string ADMIN_ACCOUNT_NOT_DEFINED = "Administrator account is not defined";

namespace mpa_api_rest_v1
{

    class MPAO
    {

        public:
            static string DEFAULT_JSON_ID;
            static string OK_JSON_ID;

        private:
            HttpRequestType httpRequestType;

        protected:
            ActionType actionType;
            // Request parameters received
            map<string, string> argvals;
            // URI stored in a vector
            vector<std::pair<string, int> > urlPairs;
            bool restrictedAccess;
            string badParamsMsg;

            string login;

            int version;

            virtual bool isValidAccess();

            virtual bool areGetParametersOk() = 0;
            virtual bool arePostLoginParametersOk();
            virtual bool arePostAddParametersOk() = 0;
            virtual bool arePostDeleteParametersOk();
            virtual bool arePostUpdateParametersOk();

            virtual string executeGetRequest(ptree & root) = 0;
            virtual string executePostLoginRequest(ptree & root);
            virtual string executePostAddRequest(ptree & root) = 0;
            virtual string executePostDeleteRequest(ptree & root) = 0;
            virtual string executePostUpdateRequest(ptree & root) = 0;

        public:
            MPAO(HttpRequestType httpRequestType, ActionType actionType, const map<string, string>& argvals,
                    vector<std::pair<string, int> > urlPairs);

            bool areParametersOk();
            string getBadParamsMsg();

            string executeRequest(ptree & root);

            string & getLogin();

            int getVersion();

            virtual ~MPAO();
    };

}

#endif


text:
<link rel="import" href="../../bower_components/polymer/polymer.html" />

<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html" />
<link rel="import" href="../../bower_components/iron-icons/iron-icons.html" />

<link rel="import" href="../../bower_components/paper-header-panel/paper-header-panel.html" />
<link rel="import" href="../../bower_components/paper-material/paper-material.html" />
<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html" />
<link rel="import" href="../../bower_components/paper-toolbar/paper-toolbar.html" />
<link rel="import" href="../../bower_components/paper-item/paper-item.html" />
<link rel="import" href="../../bower_components/paper-item/paper-icon-item.html" />
<link rel="import" href="../../bower_components/paper-item/paper-item-body.html" />
<link rel="import" href="../../bower_components/paper-input/paper-input.html" />
<link rel="import" href="../../bower_components/paper-spinner/paper-spinner.html" />

<link rel="import" href="../file-type-icon/file-type-icon.html" />

<dom-module id="resource-view-list">
  <template>

    <paper-header-panel>
      <paper-toolbar>
        <paper-icon-button icon="menu"
                           on-click="_fireMenu"
                           paper-drawer-toggle></paper-icon-button>

          <paper-input value="{{query}}"
                       label="Termos de busca"
                       type="text"
                       no-label-float></paper-input>

        <paper-icon-button icon="search"
                           on-click="search"></paper-icon-button>
        <paper-icon-button icon="refresh"
                           disabled$="[[loading]]"
                           on-click="refresh"></paper-icon-button>
      </paper-toolbar>

        <paper-material elevation="1">
          <template is="dom-repeat" items="[[resources]]">

              <paper-icon-item>
                <file-type-icon type="[[item.type]]" item-icon></file-type-icon>
                <paper-item-body three-line>

[[item.name]]

[[_formatDate(item.lastUpdate)]]

[[_formatTags(item.tags)]]

                </paper-item-body>
              </paper-icon-item>

          </template>
        </paper-material>

            <iron-icon icon="help" class="big"></iron-icon>

            Não há recursos a serem exibidos. Sugestões:

              Verifique sua conexão com a internet

              Tente termos de pesquisa diferentes

              Tente termos de pesquisa mais genéricos

              Certifique-se que as palavras chaves estejam escritas corretamente

        <paper-spinner active="[[loading]]"></paper-spinner>

    </paper-header-panel>

    <iron-ajax id="ajax-resource"
               url="http://0.0.0.0:3000/api/Resources"
               method="GET"
               handle-as="json"
              on-response="_handleResourceResponse"></iron-ajax>
  </template>

</dom-module>


text:
<!DOCTYPE html>

		 <?php
		global $wpdb;

                $results = $wpdb->get_results( 'SELECT distinct trainer_id FROM `trainer_choice`', OBJECT);

		if (count($results) > 0) {
                        echo "Showing " . ((string)count($results)) . " trainers (only their most recent enrollment)";
                        echo "
";
                        echo "
Coach Name	1st choice	2nd choice	3rd choice
";
                        foreach ( $results as $row )
                        {
                                $trainername = $wpdb->get_row( $wpdb->prepare('SELECT first_name, last_name, title
FROM `trainers`
WHERE id=%d', $row->trainer_id), OBJECT);

                                echo "
";
                                echo "".$trainername->title." ".$trainername->first_name." ".$trainername->last_name."	";
                                for ( $choice=1; $choice<=3; $choice++ )
                                {
                                        $col = $wpdb->get_col( $wpdb->prepare('SELECT course_id FROM `trainer_choice` WHERE trainer_id=%d AND choice=%d', $row->trainer_id, $choice));
                                        $coursename = $wpdb->get_var( $wpdb->prepare('SELECT course_code FROM `courses` WHERE id=%d', end($col)));

                                        echo "".$coursename."	";
                                }

                                echo "
";
                        }
                        echo "
";
		} else {
			echo "0 results";
		}

		?>


text:
#ifndef FileSystemCallback_h
#define FileSystemCallback_h

#include "platform/heap/Handle.h"

namespace blink {

class DOMFileSystem;

class FileSystemCallback : public GarbageCollectedFinalized<FileSystemCallback> {
public:
    virtual ~FileSystemCallback() { }
    virtual void trace(Visitor*) { }
    virtual void handleEvent(DOMFileSystem*) = 0;
};

} // namespace

#endif // FileSystemCallback_h


text:
module.exports = {
  'app': './static_resource/app'
}


text:
package winrm

import (
	"net"
	"net/http"
	"net/url"

	"github.com/Azure/go-ntlmssp"
	"github.com/masterzen/winrm/soap"
)

// ClientNTLM provides a transport via NTLMv2
type ClientNTLM struct {
	clientRequest
}

// Transport creates the wrapped NTLM transport
func (c *ClientNTLM) Transport(endpoint *Endpoint) error {
	if err := c.clientRequest.Transport(endpoint); err != nil {
		return err
	}
	c.clientRequest.transport = &ntlmssp.Negotiator{RoundTripper: c.clientRequest.transport}
	return nil
}

// Post make post to the winrm soap service (forwarded to clientRequest implementation)
func (c ClientNTLM) Post(client *Client, request *soap.SoapMessage) (string, error) {
	return c.clientRequest.Post(client, request)
}

//NewClientNTLMWithDial NewClientNTLMWithDial
func NewClientNTLMWithDial(dial func(network, addr string) (net.Conn, error)) *ClientNTLM {
	return &ClientNTLM{
		clientRequest{
			dial: dial,
		},
	}
}

//NewClientNTLMWithProxyFunc NewClientNTLMWithProxyFunc
func NewClientNTLMWithProxyFunc(proxyfunc func(req *http.Request) (*url.URL, error)) *ClientNTLM {
	return &ClientNTLM{
		clientRequest{
			proxyfunc: proxyfunc,
		},
	}
}