text:
#ifndef __HII_CONFIG_ROUTING_H__
#define __HII_CONFIG_ROUTING_H__

#define EFI_HII_CONFIG_ROUTING_PROTOCOL_GUID \
  { 0x587e72d7, 0xcc50, 0x4f79, { 0x82, 0x09, 0xca, 0x29, 0x1f, 0xc1, 0xa1, 0x0f } }

typedef struct _EFI_HII_CONFIG_ROUTING_PROTOCOL EFI_HII_CONFIG_ROUTING_PROTOCOL;

/**

  This function allows the caller to request the current
  configuration for one or more named elements from one or more
  drivers. The resulting string is in the standard HII
  configuration string format. If Successful, Results contains an
  equivalent string with "=" and the values associated with all
  names added in. The expected implementation is for each
  <ConfigRequest> substring in the Request to call the HII
  Configuration Routing Protocol ExtractProtocol function for the
  driver corresponding to the <ConfigHdr> at the start of the
  <ConfigRequest> substring. The request fails if no driver
  matches the <ConfigRequest> substring. Note: Alternative
  configuration strings may also be appended to the end of the
  current configuration string. If they are, they must appear
  after the current configuration. They must contain the same
  routing (GUID, NAME, PATH) as the current configuration string.
  They must have an additional description indicating the type of
  alternative configuration the string represents,
  "ALTCFG=<StringToken>". That <StringToken> (when converted from
  hexadecimal (encoded as text) to binary) is a reference to a string in the
  associated string pack. As an example, assume that the Request
  string is:
  GUID=...&NAME=00480050&PATH=...&Fred&George&Ron&Neville A result
  might be:
  GUID=...&NAME=00480050&PATH=...&Fred=16&George=16&Ron=12&Neville=11&
  GUID=...&NAME=00480050&PATH=...&ALTCFG=0037&Fred=12&Neville=7

  @param This       Points to the EFI_HII_CONFIG_ROUTING_PROTOCOL
                    instance.

  @param Request    A null-terminated string in <MultiConfigRequest> format.

  @param Progress   On return, points to a character in the
                    Request string. Points to the string's null
                    terminator if the request was successful. Points
                    to the most recent '&' before the first
                    failing name / value pair (or the beginning
                    of the string if the failure is in the first
                    name / value pair) if the request was not
                    successful

  @param Results    A null-terminated string in <MultiConfigAltResp> format
                    which has all values filled in for the names in the
                    Request string.

  @retval EFI_SUCCESS             The Results string is filled with the
                                  values corresponding to all requested
                                  names.

  @retval EFI_OUT_OF_RESOURCES    Not enough memory to store the
                                  parts of the results that must be
                                  stored awaiting possible future
                                  protocols.

  @retval EFI_INVALID_PARAMETER   For example, passing in a NULL
                                  for the Request parameter
                                  would result in this type of
                                  error. The Progress parameter
                                  is set to NULL.

  @retval EFI_NOT_FOUND           Routing data doesn't match any
                                  known driver. Progress set to
                                  the "G" in "GUID" of the
                                  routing header that doesn't
                                  match. Note: There is no
                                  requirement that all routing
                                  data be validated before any
                                  configuration extraction.

  @retval EFI_INVALID_PARAMETER   Illegal syntax. Progress set
                                  to the most recent & before the
                                  error, or the beginning of the
                                  string.
  @retval EFI_INVALID_PARAMETER   The ExtractConfig function of the
                                  underlying HII Configuration
                                  Access Protocol returned
                                  EFI_INVALID_PARAMETER. Progress
                                  set to most recent & before the
                                  error or the beginning of the
                                  string.

**/
typedef
EFI_STATUS
(EFIAPI * EFI_HII_EXTRACT_CONFIG)(
  IN CONST  EFI_HII_CONFIG_ROUTING_PROTOCOL *This,
  IN CONST  EFI_STRING                      Request,
  OUT       EFI_STRING                      *Progress,
  OUT       EFI_STRING                      *Results
);

/**
  This function allows the caller to request the current configuration
  for the entirety of the current HII database and returns the data in
  a null-terminated string.

  This function allows the caller to request the current
  configuration for all of the current HII database. The results
  include both the current and alternate configurations as
  described in ExtractConfig() above.

  @param This     Points to the EFI_HII_CONFIG_ROUTING_PROTOCOL instance.

  @param  Results Null-terminated Unicode string in
                  <MultiConfigAltResp> format which has all values
                  filled in for the entirety of the current HII
                  database. String to be allocated by the  called
                  function. De-allocation is up to the caller.

  @retval EFI_SUCCESS             The Results string is filled with the
                                  values corresponding to all requested
                                  names.

  @retval EFI_OUT_OF_RESOURCES    Not enough memory to store the
                                  parts of the results that must be
                                  stored awaiting possible future
                                  protocols.

  @retval EFI_INVALID_PARAMETERS  For example, passing in a NULL
                                  for the Results parameter
                                  would result in this type of
                                  error.

**/
typedef
EFI_STATUS
(EFIAPI * EFI_HII_EXPORT_CONFIG)(
  IN CONST  EFI_HII_CONFIG_ROUTING_PROTOCOL *This,
  OUT       EFI_STRING                      *Results
);

/**

  This function routes the results of processing forms to the
  appropriate targets. It scans for <ConfigHdr> within the string
  and passes the header and subsequent body to the driver whose
  location is described in the <ConfigHdr>. Many <ConfigHdr>s may
  appear as a single request. The expected implementation is to
  hand off the various <ConfigResp> substrings to the
  Configuration Access Protocol RouteConfig routine corresponding
  to the driver whose routing information is defined by the
  <ConfigHdr> in turn.

  @param This           Points to the EFI_HII_CONFIG_ROUTING_PROTOCOL instance.

  @param Configuration  A null-terminated string in <MulltiConfigResp> format.

  @param Progress       A pointer to a string filled in with the
                        offset of the most recent '&' before the
                        first failing name / value pair (or the
                        beginning of the string if the failure is in
                        the first name / value pair), or the
                        terminating NULL if all was successful.

  @retval EFI_SUCCESS             The results have been distributed or are
                                  awaiting distribution.

  @retval EFI_OUT_OF_RESOURCES    Not enough memory to store the
                                  parts of the results that must be
                                  stored awaiting possible future
                                  protocols.

  @retval EFI_INVALID_PARAMETERS  Passing in a NULL for the
                                  Results parameter would result
                                  in this type of error.

  @retval EFI_NOT_FOUND           The target for the specified routing data
                                  was not found.

**/
typedef
EFI_STATUS
(EFIAPI * EFI_HII_ROUTE_CONFIG)(
  IN CONST  EFI_HII_CONFIG_ROUTING_PROTOCOL *This,
  IN CONST  EFI_STRING                      Configuration,
  OUT       EFI_STRING                      *Progress
);

/**

  This function extracts the current configuration from a block of
  bytes. To do so, it requires that the ConfigRequest string
  consists of a list of <BlockName> formatted names. It uses the
  offset in the name to determine the index into the Block to
  start the extraction and the width of each name to determine the
  number of bytes to extract. These are mapped to a string
  using the equivalent of the C "%x" format (with optional leading
  spaces). The call fails if, for any (offset, width) pair in
  ConfigRequest, offset+value >= BlockSize.

  @param This      Points to the EFI_HII_CONFIG_ROUTING_PROTOCOL instance.

  @param ConfigRequest  A null-terminated string in <ConfigRequest> format.

  @param Block      An array of bytes defining the block's
                    configuration.

  @param BlockSize  The length in bytes of Block.

  @param Config     The filled-in configuration string. String
                    allocated by the function. Returned only if
                    call is successful. The null-terminated string
                    will be <ConfigResp> format.

  @param Progress   A pointer to a string filled in with the
                    offset of the most recent '&' before the
                    first failing name / value pair (or the
                    beginning of the string if the failure is in
                    the first name / value pair), or the
                    terminating NULL if all was successful.

  @retval EFI_SUCCESS             The request succeeded. Progress points
                                  to the null terminator at the end of the
                                  ConfigRequest string.

  @retval EFI_OUT_OF_RESOURCES    Not enough memory to allocate
                                  Config. Progress points to the
                                  first character of ConfigRequest.

  @retval EFI_INVALID_PARAMETERS  Passing in a NULL for the
                                  ConfigRequest or Block
                                  parameter would result in this
                                  type of error. Progress points
                                  to the first character of
                                  ConfigRequest.

  @retval EFI_NOT_FOUND           The target for the specified routing data
                                  was not found. Progress points to the
                                  'G' in "GUID" of the errant routing
                                  data.
  @retval EFI_DEVICE_ERROR        The block is not large enough. Progress undefined.

  @retval EFI_INVALID_PARAMETER   Encountered non <BlockName>
                                  formatted string. Block is
                                  left updated and Progress
                                  points at the '&' preceding
                                  the first non-<BlockName>.

**/
typedef
EFI_STATUS
(EFIAPI * EFI_HII_BLOCK_TO_CONFIG)(
  IN CONST  EFI_HII_CONFIG_ROUTING_PROTOCOL *This,
  IN CONST  EFI_STRING                      ConfigRequest,
  IN CONST  UINT8                           *Block,
  IN CONST  UINTN                           BlockSize,
  OUT       EFI_STRING                      *Config,
  OUT       EFI_STRING                      *Progress
);

/**
  This function maps a configuration containing a series of
  <BlockConfig> formatted name value pairs in ConfigResp into a
  Block so it may be stored in a linear mapped storage such as a
  UEFI Variable. If present, the function skips GUID, NAME, and
  PATH in <ConfigResp>. It stops when it finds a non-<BlockConfig>
  name / value pair (after skipping the routing header) or when it
  reaches the end of the string.
  Example Assume an existing block containing: 00 01 02 03 04 05
  And the ConfigResp string is:
  OFFSET=4&WIDTH=1&VALUE=7&OFFSET=0&WIDTH=2&VALUE=AA55
  The results are
  55 AA 02 07 04 05

  @param This           Points to the EFI_HII_CONFIG_ROUTING_PROTOCOL instance.

  @param ConfigResp     A null-terminated string in <ConfigResp> format.

  @param Block          A possibly null array of bytes
                        representing the current block. Only
                        bytes referenced in the ConfigResp
                        string in the block are modified. If
                        this parameter is null or if the
                        BlockLength parameter is (on input)
                        shorter than required by the
                        Configuration string, only the BlockSize
                        parameter is updated, and an appropriate
                        status (see below) is returned.

  @param BlockSize      The length of the Block in units of UINT8.
                        On input, this is the size of the Block. On
                        output, if successful, contains the largest
                        index of the modified byte in the Block, or
                        the required buffer size if the Block is not
                        large enough.

  @param Progress       On return, points to an element of the
                        ConfigResp string filled in with the offset
                        of the most recent "&" before the first
                        failing name / value pair (or the beginning
                        of the string if the failure is in the first
                        name / value pair), or the terminating NULL
                        if all was successful.

  @retval EFI_SUCCESS            The request succeeded. Progress points to the null
                                 terminator at the end of the ConfigResp string.
  @retval EFI_OUT_OF_RESOURCES   Not enough memory to allocate Config. Progress
                                 points to the first character of ConfigResp.
  @retval EFI_INVALID_PARAMETER  Passing in a NULL for the ConfigResp or
                                 Block parameter would result in this type of
                                 error. Progress points to the first character of
                                         ConfigResp.
  @retval EFI_INVALID_PARAMETER  Encountered non <BlockName> formatted name /
                                 value pair. Block is left updated and
                                 Progress points at the '&' preceding the first
                                 non-<BlockName>.
  @retval EFI_DEVICE_ERROR       Block not large enough. Progress undefined.
  @retval EFI_NOT_FOUND          Target for the specified routing data was not found.
                                 Progress points to the "G" in "GUID" of the errant
                                 routing data.
  @retval EFI_BUFFER_TOO_SMALL   Block not large enough. Progress undefined.
                                 BlockSize is updated with the required buffer size.

**/
typedef
EFI_STATUS
(EFIAPI * EFI_HII_CONFIG_TO_BLOCK)(
  IN CONST  EFI_HII_CONFIG_ROUTING_PROTOCOL *This,
  IN CONST  EFI_STRING                      ConfigResp,
  IN OUT    UINT8                           *Block,
  IN OUT    UINTN                           *BlockSize,
  OUT       EFI_STRING                      *Progress
);

/**
  This helper function is to be called by drivers to extract portions of
  a larger configuration string.

  @param This              A pointer to the EFI_HII_CONFIG_ROUTING_PROTOCOL instance.
  @param ConfigResp        A null-terminated string in <ConfigAltResp> format.
  @param Guid              A pointer to the GUID value to search for in the
                           routing portion of the ConfigResp string when retrieving
                           the requested data. If Guid is NULL, then all GUID
                           values will be searched for.
  @param Name              A pointer to the NAME value to search for in the
                           routing portion of the ConfigResp string when retrieving
                           the requested data. If Name is NULL, then all Name
                           values will be searched for.
  @param DevicePath        A pointer to the PATH value to search for in the
                           routing portion of the ConfigResp string when retrieving
                           the requested data. If DevicePath is NULL, then all
                           DevicePath values will be searched for.
  @param AltCfgId          A pointer to the ALTCFG value to search for in the
                           routing portion of the ConfigResp string when retrieving
                           the requested data.  If this parameter is NULL,
                           then the current setting will be retrieved.
  @param AltCfgResp        A pointer to a buffer which will be allocated by the
                           function which contains the retrieved string as requested.
                           This buffer is only allocated if the call was successful.
                           The null-terminated string will be <ConfigResp> format.

  @retval EFI_SUCCESS             The request succeeded. The requested data was extracted
                                  and placed in the newly allocated AltCfgResp buffer.
  @retval EFI_OUT_OF_RESOURCES    Not enough memory to allocate AltCfgResp.
  @retval EFI_INVALID_PARAMETER   Any parameter is invalid.
  @retval EFI_NOT_FOUND           The target for the specified routing data was not found.
**/
typedef
EFI_STATUS
(EFIAPI * EFI_HII_GET_ALT_CFG)(
  IN  CONST EFI_HII_CONFIG_ROUTING_PROTOCOL    *This,
  IN  CONST EFI_STRING                         ConfigResp,
  IN  CONST EFI_GUID                           *Guid,
  IN  CONST EFI_STRING                         Name,
  IN  CONST EFI_DEVICE_PATH_PROTOCOL           *DevicePath,
  IN  CONST UINT16                             *AltCfgId,
  OUT EFI_STRING                               *AltCfgResp
  );

///
/// This protocol defines the configuration routing interfaces
/// between external applications and the HII. There may only be one
/// instance of this protocol in the system.
///
struct _EFI_HII_CONFIG_ROUTING_PROTOCOL {
  EFI_HII_EXTRACT_CONFIG  ExtractConfig;
  EFI_HII_EXPORT_CONFIG   ExportConfig;
  EFI_HII_ROUTE_CONFIG    RouteConfig;
  EFI_HII_BLOCK_TO_CONFIG BlockToConfig;
  EFI_HII_CONFIG_TO_BLOCK ConfigToBlock;
  EFI_HII_GET_ALT_CFG     GetAltConfig;
};

extern EFI_GUID gEfiHiiConfigRoutingProtocolGuid;

#endif


text:
<?php

namespace RedjanYm\FCMBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * @link http://symfony.com/doc/current/cookbook/bundles/extension.html
 */
class RedjanYmFCMExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('redjan_ym_fcm.firebase_api_key', $config['firebase_api_key']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const Model = require('trails/model')
const TAG_MODELS = require('../../lib').Enums.TAG_MODELS
const _ = require('lodash')

/**
 * @module ItemTag
 * @description Item Tag Model n:m
 */
module.exports = class ItemTag extends Model {

  static config (app, Sequelize) {
    return {
      options: {
        underscored: true,
        enums: {
          TAG_MODELS: TAG_MODELS
        },
        classMethods: {
          /**
           * Associate the Model
           * @param models
           */
          associate: (models) => {
            models.ItemTag.belongsTo(models.Tag, {
              foreignKey: 'tag_id'
            })
          }
        }
      }
    }
  }

  static schema (app, Sequelize) {
    return {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      tag_id: {
        type: Sequelize.INTEGER,
        unique: 'tag_model',
        notNull: true
      },
      model: {
        type: Sequelize.ENUM,
        unique: 'tag_model',
        values: _.values(TAG_MODELS)
      },
      model_id: {
        type: Sequelize.INTEGER,
        unique: 'tag_model',
        references: null
      }
    }
  }
}


text:
package net.iovar.web.bin.shell.task;

// local imports:
import net.iovar.parse.*;
import net.iovar.web.lib.*;

// java imports:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// 3rd-party imports:

/**
 * Reference to a variable.
 *
 * @author  shawn@lannocc.com
 */
class Variable implements Graph, Text
{
    String name;

    Variable ()
    {
    }

    public boolean assemble (final GraphReader in) throws IOException, GraphException
    {
        if ('$' != in.peek ()) return false;
        in.discard ();
        this.name = null;

        boolean braces = ('{'==in.peek ());
        if (braces) in.discard ();

        // special reserved variable names
        if ('?'==in.peek () || '@'==in.peek () || '#'==in.peek ())
        {
            final char c = (char) in.pop ();
            this.name = String.valueOf (c);
            if (!braces) return true;
        }

        final StringBuffer s = new StringBuffer ();

        for (int c; (c = in.peek ())>=0; s.append ((char) c))
        {
            if (braces)
            {
                in.discard ();

                if ('}'==c)
                {
                    braces = false;
                    break;
                }
            }
            else if ( !allowed ((char) c) )
            {
                break;
            }
            else
            {
                in.discard ();
            }
        }

        if (braces) throw new GraphException ("Missing closing curly-brace: "+s);

        if (this.name==null)
        {
            if (s.length ()<1) throw new GraphException ("Zero-length variable name");
            this.name = s.toString ();
        }
        else // special variable
        {
            if ("#".equals (this.name))
            {
                if (s.length () > 0) try
                {
                    final int ival = Integer.parseInt (s.toString ());
                    if (ival<0) throw new GraphException ("Invalid parameter number for $#: "+ival);
                    this.name += ival;
                }
                catch (NumberFormatException e)
                {
                    throw new GraphException ("Invalid parameter number for $#: "+e);
                }
            }
            else if (s.length () > 0)
            {
                throw new GraphException ("Invalid variable name: "+this.name + s);
            }
        }

        return true;
    }

    public String value (Session shell, final ServletContext context, final HttpSession htsession)
    {
        if (shell!=null) return shell.get (name);
        else return "";
    }

    public String toString ()
    {
        return "${"+name+"}";
    }

    /**
     * Test if the specified character is allowed in a variable name.
     */
    public static boolean allowed (final char c)
    {
        return ('a'<=c && c<='z') || ('A'<=c && c<='Z') || ('1'<=c && c<='9') || '0'==c || '_'==c;
    }
}


text:
package org.apache.isis.core.metamodel.specloader.specimpl.dflt;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

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

import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.filter.Filter;
import org.apache.isis.applib.filter.Filters;
import org.apache.isis.core.commons.lang.StringExtensions;
import org.apache.isis.core.commons.util.ToString;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.facetapi.Facet;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.FacetedMethod;
import org.apache.isis.core.metamodel.facets.ImperativeFacet;
import org.apache.isis.core.metamodel.facets.all.i18n.NamedFacetTranslated;
import org.apache.isis.core.metamodel.facets.all.i18n.PluralFacetTranslated;
import org.apache.isis.core.metamodel.facets.all.named.NamedFacet;
import org.apache.isis.core.metamodel.facets.all.named.NamedFacetInferred;
import org.apache.isis.core.metamodel.facets.object.mixin.MixinFacet;
import org.apache.isis.core.metamodel.facets.object.plural.PluralFacet;
import org.apache.isis.core.metamodel.facets.object.plural.inferred.PluralFacetInferred;
import org.apache.isis.core.metamodel.facets.object.value.ValueFacet;
import org.apache.isis.core.metamodel.facets.object.viewmodel.ViewModelFacet;
import org.apache.isis.core.metamodel.facets.object.wizard.WizardFacet;
import org.apache.isis.core.metamodel.services.ServicesInjector;
import org.apache.isis.core.metamodel.spec.ActionType;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.feature.Contributed;
import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation;
import org.apache.isis.core.metamodel.spec.feature.ObjectMember;
import org.apache.isis.core.metamodel.specloader.classsubstitutor.ClassSubstitutor;
import org.apache.isis.core.metamodel.specloader.facetprocessor.FacetProcessor;
import org.apache.isis.core.metamodel.specloader.specimpl.FacetedMethodsBuilder;
import org.apache.isis.core.metamodel.specloader.specimpl.FacetedMethodsBuilderContext;
import org.apache.isis.core.metamodel.specloader.specimpl.ObjectActionDefault;
import org.apache.isis.core.metamodel.specloader.specimpl.ObjectSpecificationAbstract;
import org.apache.isis.core.metamodel.specloader.specimpl.OneToManyAssociationDefault;
import org.apache.isis.core.metamodel.specloader.specimpl.OneToOneAssociationDefault;

public class ObjectSpecificationDefault extends ObjectSpecificationAbstract implements FacetHolder {

    private final static Logger LOG = LoggerFactory.getLogger(ObjectSpecificationDefault.class);

    private static final ClassSubstitutor classSubstitutor = new ClassSubstitutor();

    private static String determineShortName(final Class<?> introspectedClass) {
        final String name = introspectedClass.getName();
        return name.substring(name.lastIndexOf('.') + 1);
    }

    //region > constructor, fields

    /**
     * Lazily built by {@link #getMember(Method)}.
     */
    private Map<Method, ObjectMember> membersByMethod = null;

    private final FacetedMethodsBuilder facetedMethodsBuilder;
    private final boolean isService;

    public ObjectSpecificationDefault(
            final Class<?> correspondingClass,
            final FacetedMethodsBuilderContext facetedMethodsBuilderContext,
            final ServicesInjector servicesInjector,
            final FacetProcessor facetProcessor,
            final NatureOfService natureOfServiceIfAny) {
        super(correspondingClass, determineShortName(correspondingClass),
                servicesInjector, facetProcessor);

        this.isService = natureOfServiceIfAny != null;
        this.facetedMethodsBuilder = new FacetedMethodsBuilder(this, facetedMethodsBuilderContext);
    }

    //endregion

    //region > introspectTypeHierarchyAndMembers
    @Override
    public void introspectTypeHierarchyAndMembers() {

        metadataProperties = null;
        if(isNotIntrospected()) {
            metadataProperties = facetedMethodsBuilder.introspectClass();
        }

        // name
        if(isNotIntrospected()) {
            addNamedFacetAndPluralFacetIfRequired();
        }

        // go no further if a value
        if(this.containsFacet(ValueFacet.class)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("skipping full introspection for value type " + getFullIdentifier());
            }
            return;
        }

        // superclass
        if(isNotIntrospected()) {
            final Class<?> superclass = getCorrespondingClass().getSuperclass();
            updateSuperclass(superclass);
        }

        // walk superinterfaces

        //
        // REVIEW: the processing here isn't quite the same as with
        // superclasses, in that with superclasses the superclass adds this type as its
        // subclass, whereas here this type defines itself as the subtype.
        //
        // it'd be nice to push the responsibility for adding subclasses to
        // the interface type... needs some tests around it, though, before
        // making that refactoring.
        //
        final Class<?>[] interfaceTypes = getCorrespondingClass().getInterfaces();
        final List<ObjectSpecification> interfaceSpecList = Lists.newArrayList();
        for (final Class<?> interfaceType : interfaceTypes) {
            final Class<?> substitutedInterfaceType = classSubstitutor.getClass(interfaceType);
            if (substitutedInterfaceType != null) {
                final ObjectSpecification interfaceSpec = getSpecificationLoader().loadSpecification(substitutedInterfaceType);
                interfaceSpecList.add(interfaceSpec);
            }
        }

        if(isNotIntrospected()) {
            updateAsSubclassTo(interfaceSpecList);
        }
        if(isNotIntrospected()) {
            updateInterfaces(interfaceSpecList);
        }

        // associations and actions
        if(isNotIntrospected()) {
            final List<ObjectAssociation> associations = createAssociations(metadataProperties);
            sortAndUpdateAssociations(associations);
        }

        if(isNotIntrospected()) {
            final List<ObjectAction> actions = createActions(metadataProperties);
            sortCacheAndUpdateActions(actions);
        }

        if(isNotIntrospected()) {
            facetedMethodsBuilder.introspectClassPostProcessing(metadataProperties);
        }

        if(isNotIntrospected()) {
            updateFromFacetValues();
        }
    }

    private void addNamedFacetAndPluralFacetIfRequired() {
        NamedFacet namedFacet = getFacet(NamedFacet.class);
        if (namedFacet == null) {
            namedFacet = new NamedFacetInferred(StringExtensions.asNaturalName2(getShortIdentifier()), this);
            addFacet(namedFacet);
        }

        PluralFacet pluralFacet = getFacet(PluralFacet.class);
        if (pluralFacet == null) {
            if(namedFacet instanceof NamedFacetTranslated) {
                final NamedFacetTranslated facet = (NamedFacetTranslated) namedFacet;
                pluralFacet = new PluralFacetTranslated(facet, this);
            } else {
                pluralFacet = new PluralFacetInferred(StringExtensions.asPluralName(namedFacet.value()), this);
            }
            addFacet(pluralFacet);
        }
    }

    //endregion

    //region > create associations and actions
    private List<ObjectAssociation> createAssociations(Properties properties) {
        final List<FacetedMethod> associationFacetedMethods = facetedMethodsBuilder.getAssociationFacetedMethods(properties);
        final List<ObjectAssociation> associations = Lists.newArrayList();
        for (FacetedMethod facetedMethod : associationFacetedMethods) {
            final ObjectAssociation association = createAssociation(facetedMethod);
            if(association != null) {
                associations.add(association);
            }
        }
        return associations;
    }

    private ObjectAssociation createAssociation(final FacetedMethod facetMethod) {
        if (facetMethod.getFeatureType().isCollection()) {
            return new OneToManyAssociationDefault(facetMethod, servicesInjector);
        } else if (facetMethod.getFeatureType().isProperty()) {
            return new OneToOneAssociationDefault(facetMethod, servicesInjector);
        } else {
            return null;
        }
    }

    private List<ObjectAction> createActions(Properties metadataProperties) {
        final List<FacetedMethod> actionFacetedMethods = facetedMethodsBuilder.getActionFacetedMethods(metadataProperties);
        final List<ObjectAction> actions = Lists.newArrayList();
        for (FacetedMethod facetedMethod : actionFacetedMethods) {
            final ObjectAction action = createAction(facetedMethod);
            if(action != null) {
                actions.add(action);
            }
        }
        return actions;
    }

    private ObjectAction createAction(final FacetedMethod facetedMethod) {
        if (facetedMethod.getFeatureType().isAction()) {
            return new ObjectActionDefault(facetedMethod, servicesInjector);
        } else {
            return null;
        }
    }

    //endregion

    //region > isXxx

    @Override
    public boolean isViewModel() {
        return containsFacet(ViewModelFacet.class);
    }

    @Override
    public boolean isViewModelCloneable(ObjectAdapter targetAdapter) {
        final ViewModelFacet facet = getFacet(ViewModelFacet.class);
        if(facet == null) {
            return false;
        }
        final Object pojo = targetAdapter.getObject();
        return facet.isCloneable(pojo);
    }

    @Override
    public boolean isMixin() {
        return containsFacet(MixinFacet.class);
    }

    @Override
    public boolean isWizard() {
        return containsFacet(WizardFacet.class);
    }

    @Override
    public boolean isService() {
        return isService;
    }

    //endregion

    //region > getObjectAction

    @Override
    public ObjectAction getObjectAction(final ActionType type, final String id, final List<ObjectSpecification> parameters) {
        final List<ObjectAction> actions =
                getObjectActions(type, Contributed.INCLUDED, Filters.<ObjectAction>any());
        return firstAction(actions, id, parameters);
    }

    @Override
    public ObjectAction getObjectAction(final ActionType type, final String id) {
        final List<ObjectAction> actions =
                getObjectActions(type, Contributed.INCLUDED, Filters.<ObjectAction>any());
        return firstAction(actions, id);
    }

    @Override
    public ObjectAction getObjectAction(final String id) {
        final List<ObjectAction> actions =
                getObjectActions(ActionType.ALL, Contributed.INCLUDED, Filters.<ObjectAction>any());
        return firstAction(actions, id);
    }

    private static ObjectAction firstAction(
            final List<ObjectAction> candidateActions,
            final String actionName,
            final List<ObjectSpecification> parameters) {
        outer: for (int i = 0; i < candidateActions.size(); i++) {
            final ObjectAction action = candidateActions.get(i);
            if (actionName != null && !actionName.equals(action.getId())) {
                continue outer;
            }
            if (action.getParameters().size() != parameters.size()) {
                continue outer;
            }
            for (int j = 0; j < parameters.size(); j++) {
                if (!parameters.get(j).isOfType(action.getParameters().get(j).getSpecification())) {
                    continue outer;
                }
            }
            return action;
        }
        return null;
    }

    private static ObjectAction firstAction(
            final List<ObjectAction> candidateActions,
            final String id) {
        if (id == null) {
            return null;
        }
        for (int i = 0; i < candidateActions.size(); i++) {
            final ObjectAction action = candidateActions.get(i);
            if (id.equals(action.getIdentifier().toNameParmsIdentityString())) {
                return action;
            }
            if (id.equals(action.getIdentifier().toNameIdentityString())) {
                return action;
            }
            continue;
        }
        return null;
    }

    //endregion

    //region > getMember, catalog... (not API)

    public ObjectMember getMember(final Method method) {
        if (membersByMethod == null) {
            this.membersByMethod = catalogueMembers();
        }
        return membersByMethod.get(method);
    }

    private HashMap<Method, ObjectMember> catalogueMembers() {
        final HashMap<Method, ObjectMember> membersByMethod = Maps.newHashMap();
        cataloguePropertiesAndCollections(membersByMethod);
        catalogueActions(membersByMethod);
        return membersByMethod;
    }

    private void cataloguePropertiesAndCollections(final Map<Method, ObjectMember> membersByMethod) {
        final Filter<ObjectAssociation> noop = Filters.anyOfType(ObjectAssociation.class);
        final List<ObjectAssociation> fields = getAssociations(Contributed.EXCLUDED, noop);
        for (int i = 0; i < fields.size(); i++) {
            final ObjectAssociation field = fields.get(i);
            final List<Facet> facets = field.getFacets(ImperativeFacet.FILTER);
            for (final Facet facet : facets) {
                final ImperativeFacet imperativeFacet = ImperativeFacet.Util.getImperativeFacet(facet);
                for (final Method imperativeFacetMethod : imperativeFacet.getMethods()) {
                    membersByMethod.put(imperativeFacetMethod, field);
                }
            }
        }
    }

    private void catalogueActions(final Map<Method, ObjectMember> membersByMethod) {
        final List<ObjectAction> userActions = getObjectActions(Contributed.INCLUDED);
        for (int i = 0; i < userActions.size(); i++) {
            final ObjectAction userAction = userActions.get(i);
            final List<Facet> facets = userAction.getFacets(ImperativeFacet.FILTER);
            for (final Facet facet : facets) {
                final ImperativeFacet imperativeFacet = ImperativeFacet.Util.getImperativeFacet(facet);
                for (final Method imperativeFacetMethod : imperativeFacet.getMethods()) {
                    membersByMethod.put(imperativeFacetMethod, userAction);
                }
            }
        }
    }

    //endregion

    //region > toString
    @Override
    public String toString() {
        final ToString str = new ToString(this);
        str.append("class", getFullIdentifier());
        str.append("type", (isParentedOrFreeCollection() ? "Collection" : "Object"));
        str.append("persistable", persistability());
        str.append("superclass", superclass() == null ? "Object" : superclass().getFullIdentifier());
        return str.toString();
    }

    //endregion

}


text:
package tastytest

final class basicAnnot[T](member: T) extends scala.annotation.StaticAnnotation


text:
package org.lwjgl.fmod;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 *
Layout

 *
 *

 * struct FMOD_STUDIO_CPU_USAGE {
 *     float update;
 * }

 */
public class FMOD_STUDIO_CPU_USAGE extends Struct implements NativeResource {

    /** The struct size in bytes. */
    public static final int SIZEOF;

    /** The struct alignment in bytes. */
    public static final int ALIGNOF;

    /** The struct member offsets. */
    public static final int
        UPDATE;

    static {
        Layout layout = __struct(
            __member(4)
        );

        SIZEOF = layout.getSize();
        ALIGNOF = layout.getAlignment();

        UPDATE = layout.offsetof(0);
    }

    /**
     * Creates a {@code FMOD_STUDIO_CPU_USAGE} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
     * visible to the struct instance and vice versa.
     *
     *
The created instance holds a strong reference to the container object.

     */
    public FMOD_STUDIO_CPU_USAGE(ByteBuffer container) {
        super(memAddress(container), __checkContainer(container, SIZEOF));
    }

    @Override
    public int sizeof() { return SIZEOF; }

    /** @return the value of the {@code update} field. */
    public float update() { return nupdate(address()); }

    /** Sets the specified value to the {@code update} field. */
    public FMOD_STUDIO_CPU_USAGE update(float value) { nupdate(address(), value); return this; }

    /**
     * Copies the specified struct data to this struct.
     *
     * @param src the source struct
     *
     * @return this struct
     */
    public FMOD_STUDIO_CPU_USAGE set(FMOD_STUDIO_CPU_USAGE src) {
        memCopy(src.address(), address(), SIZEOF);
        return this;
    }

    // -----------------------------------

    /** Returns a new {@code FMOD_STUDIO_CPU_USAGE} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
    public static FMOD_STUDIO_CPU_USAGE malloc() {
        return wrap(FMOD_STUDIO_CPU_USAGE.class, nmemAllocChecked(SIZEOF));
    }

    /** Returns a new {@code FMOD_STUDIO_CPU_USAGE} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
    public static FMOD_STUDIO_CPU_USAGE calloc() {
        return wrap(FMOD_STUDIO_CPU_USAGE.class, nmemCallocChecked(1, SIZEOF));
    }

    /** Returns a new {@code FMOD_STUDIO_CPU_USAGE} instance allocated with {@link BufferUtils}. */
    public static FMOD_STUDIO_CPU_USAGE create() {
        ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
        return wrap(FMOD_STUDIO_CPU_USAGE.class, memAddress(container), container);
    }

    /** Returns a new {@code FMOD_STUDIO_CPU_USAGE} instance for the specified memory address. */
    public static FMOD_STUDIO_CPU_USAGE create(long address) {
        return wrap(FMOD_STUDIO_CPU_USAGE.class, address);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static FMOD_STUDIO_CPU_USAGE createSafe(long address) {
        return address == NULL ? null : wrap(FMOD_STUDIO_CPU_USAGE.class, address);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_CPU_USAGE.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_CPU_USAGE.Buffer malloc(int capacity) {
        return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_CPU_USAGE.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_CPU_USAGE.Buffer calloc(int capacity) {
        return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_CPU_USAGE.Buffer} instance allocated with {@link BufferUtils}.
     *
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_CPU_USAGE.Buffer create(int capacity) {
        ByteBuffer container = __create(capacity, SIZEOF);
        return wrap(Buffer.class, memAddress(container), capacity, container);
    }

    /**
     * Create a {@link FMOD_STUDIO_CPU_USAGE.Buffer} instance at the specified memory.
     *
     * @param address  the memory address
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_CPU_USAGE.Buffer create(long address, int capacity) {
        return wrap(Buffer.class, address, capacity);
    }

    /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static FMOD_STUDIO_CPU_USAGE.Buffer createSafe(long address, int capacity) {
        return address == NULL ? null : wrap(Buffer.class, address, capacity);
    }

    /**
     * Returns a new {@code FMOD_STUDIO_CPU_USAGE} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack the stack from which to allocate
     */
    public static FMOD_STUDIO_CPU_USAGE malloc(MemoryStack stack) {
        return wrap(FMOD_STUDIO_CPU_USAGE.class, stack.nmalloc(ALIGNOF, SIZEOF));
    }

    /**
     * Returns a new {@code FMOD_STUDIO_CPU_USAGE} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack the stack from which to allocate
     */
    public static FMOD_STUDIO_CPU_USAGE calloc(MemoryStack stack) {
        return wrap(FMOD_STUDIO_CPU_USAGE.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
    }

    /**
     * Returns a new {@link FMOD_STUDIO_CPU_USAGE.Buffer} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_CPU_USAGE.Buffer malloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_CPU_USAGE.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_CPU_USAGE.Buffer calloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
    }

    // -----------------------------------

    /** Unsafe version of {@link #update}. */
    public static float nupdate(long struct) { return UNSAFE.getFloat(null, struct + FMOD_STUDIO_CPU_USAGE.UPDATE); }

    /** Unsafe version of {@link #update(float) update}. */
    public static void nupdate(long struct, float value) { UNSAFE.putFloat(null, struct + FMOD_STUDIO_CPU_USAGE.UPDATE, value); }

    // -----------------------------------

    /** An array of {@link FMOD_STUDIO_CPU_USAGE} structs. */
    public static class Buffer extends StructBuffer<FMOD_STUDIO_CPU_USAGE, Buffer> implements NativeResource {

        private static final FMOD_STUDIO_CPU_USAGE ELEMENT_FACTORY = FMOD_STUDIO_CPU_USAGE.create(-1L);

        /**
         * Creates a new {@code FMOD_STUDIO_CPU_USAGE.Buffer} instance backed by the specified container.
         *
         * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
         * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
         * by {@link FMOD_STUDIO_CPU_USAGE#SIZEOF}, and its mark will be undefined.
         *
         *
The created buffer instance holds a strong reference to the container object.

         */
        public Buffer(ByteBuffer container) {
            super(container, container.remaining() / SIZEOF);
        }

        public Buffer(long address, int cap) {
            super(address, null, -1, 0, cap, cap);
        }

        Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
            super(address, container, mark, pos, lim, cap);
        }

        @Override
        protected Buffer self() {
            return this;
        }

        @Override
        protected FMOD_STUDIO_CPU_USAGE getElementFactory() {
            return ELEMENT_FACTORY;
        }

        /** @return the value of the {@code update} field. */
        public float update() { return FMOD_STUDIO_CPU_USAGE.nupdate(address()); }

        /** Sets the specified value to the {@code update} field. */
        public FMOD_STUDIO_CPU_USAGE.Buffer update(float value) { FMOD_STUDIO_CPU_USAGE.nupdate(address(), value); return this; }

    }

}


text:
var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var generatorWebappUtils = require('../../util/generator-webapp-utils.js');
var reusablePrompts = require('../../util/reusable-prompts.js');

module.exports = generators.Base.extend({

  constructor: function () {

    generators.Base.apply(this, arguments);

    this.argument('serviceName', { type: String, required: false });
    if (!this.serviceName) {
      throw new Error(chalk.red('Must specify a service name : yo modular:service myService'));
    }

    this.type = 'controller';
    this.defaultPath = 'src/services/' + this.serviceName;
    this.rtfm = 'https://github.com/kosz/generator-modular/wiki/yo-modular:service';

  },

  helloWorld: function () {
    this.log(yosay(
      'This will generate a ' + chalk.yellow('service') + ' and a ' + chalk.yellow('spec') + ' file'
    ));
  },

  promptPath: reusablePrompts.promptPath,

  promptInjections: reusablePrompts.promptInjections,

  promptScopeMethods: reusablePrompts.promptScopeMethods,

  promptServiceType: function () {

    var done = this.async();

    this.prompt({
      type: 'list',
      name: 'serviceType',
      message: 'Will this be a service of a factory ?',
      choices: [
        "service (not supported yet)",
        "factory"
      ],
      filter: function (val) {
        var filterMap = {
          "service (not supported yet)": 'service',
          "factory": 'factory'
        }
        return filterMap[val];
      },
      store: true,
    }, function (answers) {
      this.serviceType = answers.serviceType;
      done();
    }.bind(this));

  },

  processTemplates: function () {

    this.template('service.service.js', generatorWebappUtils.sanitizePath(this.path) + this.serviceName + '.' + this.serviceType + '.js');
    this.template('service.service.spec.js', generatorWebappUtils.sanitizePath(this.path) + this.serviceName + '.' + this.serviceType + '.spec.js');

  }

});


text:
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//
// Cleaver - A MultiMaterial Tetrahedral Mesher
// -- 3D Analytic Field
//
// Primary Author: Jonathan Bronson (bronson@sci.utah.edu)
//
//-------------------------------------------------------------------
//-------------------------------------------------------------------

#ifndef _ANALYTIC_FIELD_3D_
#define _ANALYTIC_FIELD_3D_

#include "Field3D.h"
#include "vec3.h"
#include <vector>

namespace Cleaver
{

class AnalyticField3D: public Field3D
{
public:
    AnalyticField3D();
    ~AnalyticField3D(){}

    float value(float x, float y, float z, int mat) const;
    float operator()(float x, float y, float z, int mat) const;

    int width() const { return w; }
    int height() const { return h; }
    int depth() const { return d; }
    int numMaterials() const { return m; }

private:
    int w,h,d,m;

    std::vector<vec3> x1;
    std::vector<vec3> x2;
    std::vector<float> r;
};

}

#endif // _ANALYTIC_FIELD_3D_


text:
layout: post
title: active model serializers for rails json
categories: [rails]
tags: [rails]
comments: true
description: 'rails gems for json'
---

### 运用背景
随着rails-api的引入,为了更好的支持api的编写,自带的as_json又很不放方便

### 原理
`active_model_serializers`通过继承`ActiveModel::Serializer`,根据每个model来生自定义不同的json数据方式,方便返回给用户

以下面结构关系为例
 ![relations](https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2015/10/1444739329models-large.png)
### 用法
* scaffold

  `$ rails g serializer --help`

* 单表

  ~~~
  class UserSerializer < ActiveModel::Serializer
    attribute :id, :name
  end
  ~~~
  controller use
  ~~~
  ...
    render json: @user
    or
    render json: @users
  ...
  ~~~

* 同model定义不同json以及自定方法

  ~~~
  class UserAuthSerializer < ActiveModel::Serializer
    attribute :id, :name, :auth_token

    def auth_token
      ...
    end
  end
  ~~~

  controller use
  ~~~
  ...
    render json: @user, serializer: UserAuthSerializer
  ...
  ~~~

* 多表关联
  ~~~
  class UserVideoSerializer < ActiveModel::Serializer
    attribute :id, :name
    has_many :videos, serializer: VideoSerializer #default is       ModelNameSerializer
  end

  class VideoSerializer < ActiveModel::Serializer
    attribute :id, :name
  end
  ~~~
  controller use
  ~~~
  ...
    render json :@user,  serializer: UserVideoSerializer
  ...
  ~~~

* 分页

  ~~~
  class PaginatedSerializer < ActiveModel::Serializer::ArraySerializer
    def initialize(object, options={})
      meta_key = options[:meta_key] || :meta
      options[meta_key] ||= {}
      options[meta_key] = {
        current_page: object.current_page,
        next_page: object.next_page,
        prev_page: object.prev_page,
        total_pages: object.total_pages,
        total_count: object.total_count
      }
      super(object, options)
    end
  end
  ~~~

  ~~~
  class CommentSerializer < ActiveModel::Serializer
    attribute :id, :content
    has_one :user
  end
  ~~~

  controller use
  ~~~
  ...
    @comments = @comments.page(params[:page]).per(params[:per_page] || 10)
    render json: @comments, serializer: PaginatedSerializer, each_serlizer: CommentSerializer
  ...
  ~~~

* 嵌入式数据

  ~~~
  class VideoSerializer < VideoSerializer
    embed :ids, include: true
    has_one :user
  end
  ~~~
  ~~~
  ...
    render json: @videos
  ...

  it will return the user_id at the video same level
  ~~~


text:
using System.Collections.Generic;
using Wargaming.WebAPI.Responses;
using Wargaming.WebAPI.WoT.Model;

namespace Wargaming.WebAPI.WoT.Responses
{
	public class ClanRatingsResponse : ResponseBase<Dictionary<string, ClanRating>>
	{
	}
}


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_Sprites_DataUtility : LuaObject {
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int constructor(IntPtr l) {
		LuaDLL.lua_remove(l,1);
		UnityEngine.Sprites.DataUtility o;
		if(matchType(l,1)){
			o=new UnityEngine.Sprites.DataUtility();
			pushObject(l,o);
			return 1;
		}
		return 0;
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int GetInnerUV(IntPtr l) {
		try{
			UnityEngine.Sprite a1;
			checkType(l,1,out a1);
			UnityEngine.Vector4 ret=UnityEngine.Sprites.DataUtility.GetInnerUV(a1);
			pushValue(l,ret);
			return 1;
		}
		catch(Exception e) {
			LuaDLL.luaL_error(l, e.ToString());
			return 0;
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int GetOuterUV(IntPtr l) {
		try{
			UnityEngine.Sprite a1;
			checkType(l,1,out a1);
			UnityEngine.Vector4 ret=UnityEngine.Sprites.DataUtility.GetOuterUV(a1);
			pushValue(l,ret);
			return 1;
		}
		catch(Exception e) {
			LuaDLL.luaL_error(l, e.ToString());
			return 0;
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int GetPadding(IntPtr l) {
		try{
			UnityEngine.Sprite a1;
			checkType(l,1,out a1);
			UnityEngine.Vector4 ret=UnityEngine.Sprites.DataUtility.GetPadding(a1);
			pushValue(l,ret);
			return 1;
		}
		catch(Exception e) {
			LuaDLL.luaL_error(l, e.ToString());
			return 0;
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int GetMinSize(IntPtr l) {
		try{
			UnityEngine.Sprite a1;
			checkType(l,1,out a1);
			UnityEngine.Vector2 ret=UnityEngine.Sprites.DataUtility.GetMinSize(a1);
			pushValue(l,ret);
			return 1;
		}
		catch(Exception e) {
			LuaDLL.luaL_error(l, e.ToString());
			return 0;
		}
	}
	static public void reg(IntPtr l) {
		getTypeTable(l,"UnityEngine.Sprites.DataUtility");
		addMember(l,GetInnerUV, "GetInnerUV");
		addMember(l,GetOuterUV, "GetOuterUV");
		addMember(l,GetPadding, "GetPadding");
		addMember(l,GetMinSize, "GetMinSize");
		newType(l, constructor);
		createTypeMetatable(l, typeof(UnityEngine.Sprites.DataUtility));
		LuaDLL.lua_pop(l, 1);
	}
}


text:
#ifndef _HTTP_PARSER_URL_H_
#define _HTTP_PARSER_URL_H_
#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <zephyr/types.h>
#include <stddef.h>
#include <net/http_parser_state.h>

enum http_parser_url_fields {
	  UF_SCHEMA           = 0
	, UF_HOST             = 1
	, UF_PORT             = 2
	, UF_PATH             = 3
	, UF_QUERY            = 4
	, UF_FRAGMENT         = 5
	, UF_USERINFO         = 6
	, UF_MAX              = 7
};

/* Result structure for http_parser_url_fields().
 *
 * Callers should index into field_data[] with UF_* values iff field_set
 * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
 * because we probably have padding left over), we convert any port to
 * a u16_t.
 */
struct http_parser_url {
	u16_t field_set;           /* Bitmask of (1 << UF_*) values */
	u16_t port;                /* Converted UF_PORT string */

	struct {
		u16_t off;               /* Offset into buffer in which field
					  * starts
					  */
		u16_t len;               /* Length of run in buffer */
	} field_data[UF_MAX];
};

enum state parse_url_char(enum state s, const char ch);

/* Initialize all http_parser_url members to 0 */
void http_parser_url_init(struct http_parser_url *u);

/* Parse a URL; return nonzero on failure */
int http_parser_parse_url(const char *buf, size_t buflen,
			  int is_connect, struct http_parser_url *u);

#ifdef __cplusplus
}
#endif
#endif


text:
//============================================================
//
//  ledutil.c - Win32 example code that tracks changing
//  outputs and updates the keyboard LEDs in response
//
//============================================================
//
//  Copyright Aaron Giles
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or
//  without modification, are permitted provided that the
//  following conditions are met:
//
//    * Redistributions of source code must retain the above
//      copyright notice, this list of conditions and the
//      following disclaimer.
//    * Redistributions in binary form must reproduce the
//      above copyright notice, this list of conditions and
//      the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//    * Neither the name 'MAME' nor the names of its
//      contributors may be used to endorse or promote
//      products derived from this software without specific
//      prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
//  EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//  DAMAGE (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
//  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//============================================================
//
//  This is sample code. To use it as a starting point, you
//  should do the following:
//
//  1. Change the CLIENT_ID define to something unique.
//
//  2. Change the WINDOW_CLASS and WINDOW_NAME defines to
//  something unique.
//
//  3. Delete all the code from the >8 snip 8< comment and
//  downward.
//
//  4. Implement the following functions:
//
//      output_startup - called at app init time
//      output_shutdown - called before the app exits
//      output_mame_start - called when MAME starts
//      output_mame_stop - called when MAME exits
//      output_set_state - called whenever state changes
//
//============================================================

// standard windows headers
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winioctl.h>

// standard C headers
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// MAME output header file
typedef int running_machine;
#include "osdcomm.h"
#include "output.h"

//============================================================
//  DEBUGGING
//============================================================

// note you need to compile as a console app to have any of
// these printfs show up
#define DEBUG_VERSION		0

#if DEBUG_VERSION
#define DEBUG_PRINTF(x)		printf x
#else
#define DEBUG_PRINTF(x)
#endif

//============================================================
//  CONSTANTS
//============================================================

// unique client ID
#define CLIENT_ID							(('M' << 24) | ('L' << 16) | ('E' << 8) | ('D' << 0))

// LED methods
#define LED_METHOD_PS2						0
#define LED_METHOD_USB						1
#define LED_METHOD_WIN9X					2

// window parameters
#define WINDOW_CLASS						TEXT("LEDSample")
#define WINDOW_NAME							TEXT("LEDSample")

// window styles
#define WINDOW_STYLE						WS_OVERLAPPEDWINDOW
#define WINDOW_STYLE_EX						0

// Define the keyboard indicators.
// (Definitions borrowed from ntddkbd.h)

#define IOCTL_KEYBOARD_SET_INDICATORS		CTL_CODE(FILE_DEVICE_KEYBOARD, 0x0002, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_KEYBOARD_QUERY_TYPEMATIC		CTL_CODE(FILE_DEVICE_KEYBOARD, 0x0008, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_KEYBOARD_QUERY_INDICATORS		CTL_CODE(FILE_DEVICE_KEYBOARD, 0x0010, METHOD_BUFFERED, FILE_ANY_ACCESS)

#define KEYBOARD_SCROLL_LOCK_ON 			1
#define KEYBOARD_NUM_LOCK_ON				2
#define KEYBOARD_CAPS_LOCK_ON				4

//============================================================
//  TYPE DEFINITIONS
//============================================================

typedef struct _KEYBOARD_INDICATOR_PARAMETERS
{
    USHORT UnitId;             // Unit identifier.
    USHORT LedFlags;           // LED indicator state.
} KEYBOARD_INDICATOR_PARAMETERS, *PKEYBOARD_INDICATOR_PARAMETERS;

typedef struct _id_map_entry id_map_entry;
struct _id_map_entry
{
	id_map_entry *			next;
	const char *			name;
	WPARAM					id;
};

//============================================================
//  GLOBAL VARIABLES
//============================================================

static int					ledmethod;
static int					original_state;
static int					current_state;
static int					pause_state;
static HANDLE				hKbdDev;

static HWND					mame_target;
static HWND					listener_hwnd;

static id_map_entry *		idmaplist;

// message IDs
static UINT					om_mame_start;
static UINT					om_mame_stop;
static UINT					om_mame_update_state;
static UINT					om_mame_register_client;
static UINT					om_mame_unregister_client;
static UINT					om_mame_get_id_string;

//============================================================
//  FUNCTION PROTOTYPES
//============================================================

static int create_window_class(void);
static LRESULT CALLBACK listener_window_proc(HWND wnd, UINT message, WPARAM wparam, LPARAM lparam);
static LRESULT handle_mame_start(WPARAM wparam, LPARAM lparam);
static LRESULT handle_mame_stop(WPARAM wparam, LPARAM lparam);
static LRESULT handle_copydata(WPARAM wparam, LPARAM lparam);
static void reset_id_to_outname_cache(void);
static const char *map_id_to_outname(WPARAM id);
static LRESULT handle_update_state(WPARAM wparam, LPARAM lparam);

// these functions provide the meat
static void output_startup(const char *commandline);
static void output_mame_start(void);
static void output_set_state(const char *name, INT32 state);
static void output_mame_stop(void);
static void output_shutdown(void);

static int led_get_state(void);
static void led_set_state(int state);

//============================================================
//  main
//============================================================

int main(int argc, char *argv[])
{
	const char *arg = (argc > 1) ? argv[1] : "";
	int exitcode = 1;
	HWND otherwnd;
	MSG message;
	int result;

	// see if there is another instance of us running
	otherwnd = FindWindow(WINDOW_CLASS, WINDOW_NAME);

	// if the argument is "-kill", post a close message
	if (strcmp(arg, "-kill") == 0)
	{
		if (otherwnd != NULL)
			PostMessage(otherwnd, WM_QUIT, 0, 0);
		return (otherwnd != NULL) ? 1 : 0;
	}

	// if we had another instance, defer to it
	if (otherwnd != NULL)
		return 0;

	// call the startup code
	output_startup(arg);

	// create our window class
	result = create_window_class();
	if (result != 0)
		goto error;

	// create a window
	listener_hwnd = CreateWindowEx(
						WINDOW_STYLE_EX,
						WINDOW_CLASS,
						WINDOW_NAME,
						WINDOW_STYLE,
						0, 0,
						1, 1,
						NULL,
						NULL,
						GetModuleHandle(NULL),
						NULL);
	if (listener_hwnd == NULL)
		goto error;

	// allocate message ids
	om_mame_start = RegisterWindowMessage(OM_MAME_START);
	if (om_mame_start == 0)
		goto error;
	om_mame_stop = RegisterWindowMessage(OM_MAME_STOP);
	if (om_mame_stop == 0)
		goto error;
	om_mame_update_state = RegisterWindowMessage(OM_MAME_UPDATE_STATE);
	if (om_mame_update_state == 0)
		goto error;

	om_mame_register_client = RegisterWindowMessage(OM_MAME_REGISTER_CLIENT);
	if (om_mame_register_client == 0)
		goto error;
	om_mame_unregister_client = RegisterWindowMessage(OM_MAME_UNREGISTER_CLIENT);
	if (om_mame_unregister_client == 0)
		goto error;
	om_mame_get_id_string = RegisterWindowMessage(OM_MAME_GET_ID_STRING);
	if (om_mame_get_id_string == 0)
		goto error;

	// see if MAME is already running
	otherwnd = FindWindow(OUTPUT_WINDOW_CLASS, OUTPUT_WINDOW_NAME);
	if (otherwnd != NULL)
		handle_mame_start((WPARAM)otherwnd, 0);

	// process messages
	while (GetMessage(&message, NULL, 0, 0))
	{
		TranslateMessage(&message);
		DispatchMessage(&message);
	}

	// reset on the way out if still live
	if (mame_target != NULL)
		handle_mame_stop((WPARAM)mame_target, 0);
	exitcode = 0;

error:
	// call the shutdown code
	output_shutdown();

	return exitcode;
}

//============================================================
//  create_window_class
//============================================================

static int create_window_class(void)
{
	static int classes_created = FALSE;

	/* only do this once */
	if (!classes_created)
	{
		WNDCLASS wc = { 0 };

		// initialize the description of the window class
		wc.lpszClassName	= WINDOW_CLASS;
		wc.hInstance		= GetModuleHandle(NULL);
		wc.lpfnWndProc		= listener_window_proc;

		// register the class; fail if we can't
		if (!RegisterClass(&wc))
			return 1;
		classes_created = TRUE;
	}

	return 0;
}

//============================================================
//  window_proc
//============================================================

static LRESULT CALLBACK listener_window_proc(HWND wnd, UINT message, WPARAM wparam, LPARAM lparam)
{
	// OM_MAME_START: register ourselves with the new MAME (first instance only)
	if (message == om_mame_start)
		return handle_mame_start(wparam, lparam);

	// OM_MAME_STOP: no need to unregister, just note that we've stopped caring and reset the LEDs
	else if (message == om_mame_stop)
		return handle_mame_stop(wparam, lparam);

	// OM_MAME_UPDATE_STATE: update the state of this item if we care
	else if (message == om_mame_update_state)
		return handle_update_state(wparam, lparam);

	// WM_COPYDATA: extract the string and create an ID map entry
	else if (message == WM_COPYDATA)
		return handle_copydata(wparam, lparam);

	// everything else is default
	else
		return DefWindowProc(wnd, message, wparam, lparam);
}

//============================================================
//  handle_mame_start
//============================================================

static LRESULT handle_mame_start(WPARAM wparam, LPARAM lparam)
{
	DEBUG_PRINTF(("mame_start (%08X)\n", (UINT32)wparam));

	// make this the targeted version of MAME
	mame_target = (HWND)wparam;

	// initialize the LED states
	output_mame_start();
	reset_id_to_outname_cache();

	// register ourselves as a client
	PostMessage(mame_target, om_mame_register_client, (WPARAM)listener_hwnd, CLIENT_ID);

	// get the game name
	map_id_to_outname(0);
	return 0;
}

//============================================================
//  handle_mame_stop
//============================================================

static LRESULT handle_mame_stop(WPARAM wparam, LPARAM lparam)
{
	DEBUG_PRINTF(("mame_stop (%08X)\n", (UINT32)wparam));

	// ignore if this is not the instance we care about
	if (mame_target != (HWND)wparam)
		return 1;

	// clear our target out
	mame_target = NULL;
	reset_id_to_outname_cache();

	// reset the LED states
	output_mame_stop();
	return 0;
}

//============================================================
//  handle_copydata
//============================================================

static LRESULT handle_copydata(WPARAM wparam, LPARAM lparam)
{
	COPYDATASTRUCT *copydata = (COPYDATASTRUCT *)lparam;
	copydata_id_string *data = (copydata_id_string *)copydata->lpData;
	id_map_entry *entry;
	char *string;

	DEBUG_PRINTF(("copydata (%08X)\n", (UINT32)wparam));

	// ignore requests we don't care about
	if (mame_target != (HWND)wparam)
		return 1;

	// allocate memory
	entry = (id_map_entry *)malloc(sizeof(*entry));
	if (entry == NULL)
		return 0;

	string = (char *)malloc(strlen(data->string) + 1);
	if (string == NULL)
	{
		free(entry);
		return 0;
	}

	// if all allocations worked, make a new entry
	entry->next = idmaplist;
	entry->name = string;
	entry->id = data->id;

	// copy the string and hook us into the list
	strcpy(string, data->string);
	idmaplist = entry;

	DEBUG_PRINTF(("  id %d = '%s'\n", entry->id, entry->name));

	return 0;
}

//============================================================
//  reset_id_to_outname_cache
//============================================================

static void reset_id_to_outname_cache(void)
{
	// free our ID list
	while (idmaplist != NULL)
	{
		id_map_entry *temp = idmaplist;
		idmaplist = temp->next;
		free((void*)temp->name);
		free(temp);
	}
}

//============================================================
//  map_id_to_outname
//============================================================

static const char *map_id_to_outname(WPARAM id)
{
	id_map_entry *entry;

	// see if we have an entry in our map
	for (entry = idmaplist; entry != NULL; entry = entry->next)
		if (entry->id == id)
			return entry->name;

	// no entry yet; we have to ask
	SendMessage(mame_target, om_mame_get_id_string, (WPARAM)listener_hwnd, id);

	// now see if we have the entry in our map
	for (entry = idmaplist; entry != NULL; entry = entry->next)
		if (entry->id == id)
			return entry->name;

	// if not, use an empty string
	return "";
}

//============================================================
//  handle_update_state
//============================================================

static LRESULT handle_update_state(WPARAM wparam, LPARAM lparam)
{
	DEBUG_PRINTF(("update_state: id=%d state=%d\n", (UINT32)wparam, (UINT32)lparam));
	output_set_state(map_id_to_outname(wparam), lparam);
	return 0;
}

//
// END BOILERPLATE CODE
//
// ------------------------>8 snip 8<-------------------------
//
// BEGIN LED-SPECIFIC CODE
//

//============================================================
//  output_startup
//============================================================

static void output_startup(const char *commandline)
{
	OSVERSIONINFO osinfo = { sizeof(OSVERSIONINFO) };

	// default to PS/2, override if USB is specified as a parameter
	ledmethod = LED_METHOD_PS2;
	if (commandline != NULL && strcmp(commandline, "-usb") == 0)
		ledmethod = LED_METHOD_USB;

	// force Win9x method if we're on Win 9x
	GetVersionEx(&osinfo);
	if (osinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
		ledmethod = LED_METHOD_WIN9X;

	// output the method
	switch (ledmethod)
	{
		case LED_METHOD_PS2:
			DEBUG_PRINTF(("Using PS/2 method\n"));
			break;

		case LED_METHOD_USB:
			DEBUG_PRINTF(("Using USB method\n"));
			break;

		case LED_METHOD_WIN9X:
			DEBUG_PRINTF(("Using Win9x method\n"));
			break;
	}
}

//============================================================
//  output_shutdown
//============================================================

static void output_shutdown(void)
{
	// nothing to do here
}

//============================================================
//  output_mame_start
//============================================================

static void output_mame_start(void)
{
	HRESULT error_number;

	// initialize the system based on the method
	switch (ledmethod)
	{
		case LED_METHOD_PS2:
			if (!DefineDosDevice(DDD_RAW_TARGET_PATH, TEXT("Kbd"), TEXT("\\Device\\KeyboardClass0")))
			{
				error_number = GetLastError();
				fprintf(stderr, "Unable to open the keyboard device. (error %d)\n", (UINT32)error_number);
				return;
			}

			hKbdDev = CreateFile(TEXT("\\\\.\\Kbd"), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
			if (hKbdDev == INVALID_HANDLE_VALUE)
			{
				error_number = GetLastError();
				fprintf(stderr, "Unable to open the keyboard device. (error %d)\n", (UINT32)error_number);
				return;
			}
			break;
	}

	// remember the initial LED states
	original_state = current_state = led_get_state();
}

//============================================================
//  output_mame_stop
//============================================================

static void output_mame_stop(void)
{
	int error_number = 0;

	// restore the initial LED states
	led_set_state(original_state);

	switch (ledmethod)
	{
		case LED_METHOD_PS2:
			if (!DefineDosDevice(DDD_REMOVE_DEFINITION, TEXT("Kbd"), NULL))
			{
				error_number = GetLastError();
				fprintf(stderr, "Unable to close the keyboard device. (error %d)\n", error_number);
				return;
			}
			if (!CloseHandle(hKbdDev))
			{
				error_number = GetLastError();
				fprintf(stderr, "Unable to close the keyboard device. (error %d)\n", error_number);
				return;
			}
			break;
	}
}

//============================================================
//  output_set_state
//============================================================

static void output_set_state(const char *outname, INT32 state)
{
	// look for pause state
	if (strcmp(outname, "pause") == 0)
	{
		if (state)
		{
			pause_state = led_get_state();
			led_set_state(original_state);
		}
		else
		{
			original_state = led_get_state();
			led_set_state(pause_state);
		}
	}
	// look for LED0/LED1/LED2 states and update accordingly
	else if (strcmp(outname, "led0") == 0)
		led_set_state((current_state & ~1) | (state & 1));
	else if (strcmp(outname, "led1") == 0)
		led_set_state((current_state & ~2) | ((state & 1) << 1));
	else if (strcmp(outname, "led2") == 0)
		led_set_state((current_state & ~4) | ((state & 1) << 2));
}

//============================================================
//  led_get_state
//============================================================

static int led_get_state(void)
{
	int result = 0;

	switch (ledmethod)
	{
		case LED_METHOD_WIN9X:
		case LED_METHOD_USB:
		{
			BYTE key_states[256];

			// get the current state
			GetKeyboardState(&key_states[0]);

			// set the numlock bit
			result |= (key_states[VK_NUMLOCK] & 1);
			result |= (key_states[VK_CAPITAL] & 1) << 1;
			result |= (key_states[VK_SCROLL] & 1) << 2;
			break;
		}

		case LED_METHOD_PS2:
		{
			KEYBOARD_INDICATOR_PARAMETERS OutputBuffer;	  // Output buffer for DeviceIoControl
			ULONG				DataLength = sizeof(KEYBOARD_INDICATOR_PARAMETERS);
			ULONG				ReturnedLength; // Number of bytes returned in output buffer

			// Address first keyboard
			OutputBuffer.UnitId = 0;

			DeviceIoControl(hKbdDev, IOCTL_KEYBOARD_QUERY_INDICATORS,
							NULL, 0,
							&OutputBuffer, DataLength,
							&ReturnedLength, NULL);

			// Demangle lights to match 95/98
			if (OutputBuffer.LedFlags & KEYBOARD_NUM_LOCK_ON) result |= 0x1;
			if (OutputBuffer.LedFlags & KEYBOARD_CAPS_LOCK_ON) result |= 0x2;
			if (OutputBuffer.LedFlags & KEYBOARD_SCROLL_LOCK_ON) result |= 0x4;
			break;
		}
	}

	return result;
}

//============================================================
//  led_set_state
//============================================================

static void led_set_state(int state)
{
	current_state = state;

	switch (ledmethod)
	{
		case LED_METHOD_WIN9X:
		{
			// thanks to Lee Taylor for the original version of this code
			BYTE key_states[256];

			// get the current state
			GetKeyboardState(&key_states[0]);

			// mask states and set new states
			key_states[VK_NUMLOCK] = (key_states[VK_NUMLOCK] & ~1) | ((state >> 0) & 1);
			key_states[VK_CAPITAL] = (key_states[VK_CAPITAL] & ~1) | ((state >> 1) & 1);
			key_states[VK_SCROLL] = (key_states[VK_SCROLL] & ~1) | ((state >> 2) & 1);

			SetKeyboardState(&key_states[0]);
			break;
		}

		case LED_METHOD_USB:
		{
			static const BYTE vk[3] = { VK_NUMLOCK, VK_CAPITAL, VK_SCROLL };
			BYTE keyState[256];
			int k;

			GetKeyboardState((LPBYTE)&keyState);
			for (k = 0; k < 3; k++)
			{
				if ((((state >> k) & 1) && !(keyState[vk[k]] & 1)) ||
					(!((state >> k) & 1) && (keyState[vk[k]] & 1)))
				{
					// Simulate a key press
					keybd_event(vk[k], 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);

					// Simulate a key release
					keybd_event(vk[k], 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
				}
			}

			keyState[VK_NUMLOCK] = (keyState[VK_NUMLOCK] & ~1) | ((state >> 0) & 1);
			keyState[VK_CAPITAL] = (keyState[VK_CAPITAL] & ~1) | ((state >> 1) & 1);
			keyState[VK_SCROLL] = (keyState[VK_SCROLL] & ~1) | ((state >> 2) & 1);
			SetKeyboardState(&keyState[0]);
			break;
		}

		case LED_METHOD_PS2:
		{
			KEYBOARD_INDICATOR_PARAMETERS InputBuffer;	  // Input buffer for DeviceIoControl
			ULONG				DataLength = sizeof(KEYBOARD_INDICATOR_PARAMETERS);
			ULONG				ReturnedLength; // Number of bytes returned in output buffer
			UINT				LedFlags=0;

			// Demangle lights to match 95/98
			if (state & 0x1) LedFlags |= KEYBOARD_NUM_LOCK_ON;
			if (state & 0x2) LedFlags |= KEYBOARD_CAPS_LOCK_ON;
			if (state & 0x4) LedFlags |= KEYBOARD_SCROLL_LOCK_ON;

			// Address first keyboard
			InputBuffer.UnitId = 0;
			InputBuffer.LedFlags = LedFlags;
			DeviceIoControl(hKbdDev, IOCTL_KEYBOARD_SET_INDICATORS,
							&InputBuffer, DataLength,
							NULL, 0,
							&ReturnedLength, NULL);
			break;
		}
	}
}


text:
package de.lmu.ifi.nm.www;

/**
 * This interface defines a network agent. A network agent discovers the
 * network topology, sets static routes on network devices and converts a
 * proprietary graph object to an open one (e.g. JGraphT).
 *
 * @author Dawin Schmidt, dawin.schmidt@lmu.de
 * @since October 2, 2013
 */
public interface INetworkAgent {
	/**
	 * Discover the network topology. Will be called by the Satellite.
	 */
	public void getTopology();

	/**
	 * Set a static route on a network element.
	 *
	 * @param source
	 *            - The source IP-Address of the network element where to
	 *            configure the route.
	 * @param destNet
	 *            - The destination network address.
	 * @param destSubnetMask
	 *            - The destination subnet mask or prefix.
	 * @param nextHop
	 *            - The IP-Address of the next hop.
	 * @param sourceInt
	 *            - The source interface of the network element where to
	 *            configure the route.
	 * @return True or false whether a route has been placed successfully or
	 *         not.
	 */
	public boolean setRoute(String source, String destNet, int destSubnetMask,
			String nextHop, String sourceInt);

	/**
	 * Convert a proprietary topology graph object to a JGraphT graph object.
	 */
	public void toJGraphT();
}


text:
{% extends "cosinnus_event/base.html" %}
{% load i18n l10n static cosinnus_tags thumbnail %}

{% block page_title %}
{{ object.title }} {{ block.super }}
{% endblock page_title %}

{% block extrahead %}
{{ block.super }}
<link rel="stylesheet" href="{% static "leaflet/leaflet.css" %}" />
{% endblock extrahead %}

{% block content_title %}
{{ group.name }}: {{ object.title }}
{% endblock content_title %}

{% block content %}

  {% if object.image %}

  {% endif %}

{{ object.title }}

      {% if object.note %}

{{ object.note|linebreaksbr|urlize|safe }}

      {% endif %}
      {% if object.from_date %}
      {% trans "Start" %} {{ object.from_date|date:"d. F Y h:i" }}

      {% endif %}
      {% if object.to_date %}
      {% trans "End" %} {% if object.single_day %}{{ object.to_date|date:"h:i" }}{% else %}{{ object.to_date|date:"d. F Y h:i" }}{% endif %}

      {% endif %}
      {% trans "Created by" %} {{ object.creator }}

      {% if object.state %}
      {% trans "State" %} {{ object.get_state_display }}

      {% endif %}

      {% if object.location %}
      {% trans "Location" %}:

      {% endif %}
      {% if object.street %}
      {% trans "Street" %} {{ object.street }}

      {% endif %}
      {% if object.zipcode %}
      {% trans "ZIP code" %} {{ object.zipcode }}

      {% endif %}
      {% if object.city %}
      {% trans "City" %} {{ object.city }}

      {% endif %}

{% trans "Suggestions" %}

        {% for suggestion in object.suggestions.all %}

          {% if suggestion.single_day %}
            {{ suggestion.from_date|date:"d. F Y h:i" }} - {{ suggestion.to_date|date:"h:i" }}
          {% else %}
            {{ suggestion.from_date|date:"d. F Y h:i" }} - {{ suggestion.to_date|date:"d. F Y h:i" }}
          {% endif %}
          {% if suggestion.votes.all %}
            ({{ suggestion.count }})
            {% for vote in suggestion.votes.all %}
              {% if not forloop.first %}, {% endif %}{{ vote.voter }}
            {% endfor %}
          {% else %}
            {% trans "No votes for this suggestion." %}
          {% endif %}

        {% endfor %}

      {% if user.is_superuser or user|is_group_member:group %}

          {% trans "Actions" %}

 {% trans "Edit" %}

 {% trans "Delete" %}

 {% trans "Vote" context "the verb" %}

      {% endif %}

{% endblock content %}

{% block extrafooter %}
{{ block.super }}

{% endblock extrafooter %}


text:
var tape = require('tape'),
    vega = require('../');

tape('isArray tests arrays', t => {
  t.equal(vega.isArray([]), true);
  t.equal(vega.isArray({}), false);
  t.equal(vega.isArray('a'), false);
  t.end();
});

tape('isBoolean tests booleans', t => {
  t.equal(vega.isBoolean(true), true);
  t.equal(vega.isBoolean(false), true);
  t.equal(vega.isBoolean({}), false);
  t.equal(vega.isBoolean('a'), false);
  t.equal(vega.isBoolean(0), false);
  t.end();
});

tape('isDate tests dates', t => {
  t.equal(vega.isDate(new Date()), true);
  t.equal(vega.isDate(Date.now()), false);
  t.equal(vega.isDate({}), false);
  t.equal(vega.isDate([]), false);
  t.end();
});

tape('isFunction tests functions', t => {
  t.equal(vega.isFunction(() => 1), true);
  t.equal(vega.isFunction({}), false);
  t.equal(vega.isFunction(null), false);
  t.end();
});

tape('isNumber tests numbers', t => {
  t.equal(vega.isNumber(0), true);
  t.equal(vega.isNumber(1e5), true);
  t.equal(vega.isNumber(NaN), true);
  t.equal(vega.isNumber(Infinity), true);
  t.equal(vega.isNumber(null), false);
  t.equal(vega.isNumber('a'), false);
  t.equal(vega.isNumber('1'), false);
  t.equal(vega.isNumber(''), false);
  t.end();
});

tape('isObject tests objects', t => {
  t.equal(vega.isObject({}), true);
  t.equal(vega.isObject([]), true);
  t.equal(vega.isObject(new Date()), true);
  t.equal(vega.isObject(0), false);
  t.equal(vega.isObject('a'), false);
  t.equal(vega.isObject(true), false);
  t.end();
});

tape('isRegExp tests regular expressions', t => {
  t.equal(vega.isRegExp(/grep+/), true);
  t.equal(vega.isRegExp(null), false);
  t.equal(vega.isRegExp('a'), false);
  t.end();
});

tape('isString tests strings', t => {
  t.equal(vega.isString(''), true);
  t.equal(vega.isString('a'), true);
  t.equal(vega.isString([]), false);
  t.equal(vega.isString(0), false);
  t.end();
});


text:
package Task0_NumberNotANumber;

import java.util.Scanner;

public class Task0_NumberNotANumber {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String input = scanner.nextLine();
            if (input.equals("END")) {
                break;
            }
            try {
                Integer.parseInt(input);
                System.out.println("Number");
            } catch (NumberFormatException ex) {
                System.out.println("Not a number");
            }
        }
    }
}


text:
namespace operations_research {
class CourseSchedulingSolver {
 public:
  CourseSchedulingSolver() : solve_for_rooms_(false) {}
  virtual ~CourseSchedulingSolver() {}

  using ConflictPairs = absl::flat_hash_set<std::pair<int, int>>;

  CourseSchedulingResult Solve(const CourseSchedulingModel& model);

 protected:
  virtual absl::Status ValidateModelAndLoadClasses(
      const CourseSchedulingModel& model);

  virtual CourseSchedulingResult SolveModel(
      const CourseSchedulingModel& model, const ConflictPairs& class_conflicts);

  virtual absl::Status VerifyCourseSchedulingResult(
      const CourseSchedulingModel& model, const CourseSchedulingResult& result);

 private:
  CourseSchedulingResult ScheduleCourses(const ConflictPairs& class_conflicts,
                                         const CourseSchedulingModel& model);

  // This method will modify the CourseSchedulingResult returned from
  // ScheduleCoursesMip, which is why the result is passed in as a pointer.
  ConflictPairs AssignStudents(const CourseSchedulingModel& model,
                               CourseSchedulingResult* result);

  int GetTeacherIndex(int course_index, int section);

  void InsertSortedPairs(const std::vector<int>& list, ConflictPairs* pairs);

  bool ShouldCreateVariable(int course_index, int section, int time_slot,
                            int room);

  std::vector<int> GetRoomIndices(const Course& course);

  std::vector<absl::flat_hash_set<int>> GetClassesByTimeSlot(
      const CourseSchedulingResult* result);

  void AddVariableIfNonNull(double coeff, const MPVariable* var,
                            MPConstraint* ct);

  CourseSchedulingResultStatus MipStatusToCourseSchedulingResultStatus(
      MPSolver::ResultStatus mip_status);

  bool solve_for_rooms_;
  int class_count_;
  int time_slot_count_;
  int room_count_;
  ConflictPairs course_conflicts_;
  std::vector<absl::flat_hash_set<int>> teacher_to_classes_;
  std::vector<absl::flat_hash_set<int>> teacher_to_restricted_slots_;
  std::vector<std::vector<int>> course_to_classes_;
};

}  // namespace operations_research

#endif  // OR_TOOLS_EXAMPLES_COURSE_SCHEDULING_H_


text:
/**
 * @file
 * @brief Measure time
 *
 */
#include <kernel.h>
#include <zephyr.h>
#include <tc_util.h>
#include <ksched.h>
#include "timing_info.h"
#include <app_memory/app_memdomain.h>

K_APPMEM_PARTITION_DEFINE(bench_ptn);
struct k_mem_domain bench_domain;

extern char sline[256];
extern u64_t __end_drop_to_usermode_time;

u32_t drop_to_user_mode_end_time, drop_to_user_mode_start_time;
u32_t user_thread_creation_end_time, user_thread_creation_start_time;

struct k_thread my_thread_user;
K_THREAD_STACK_EXTERN(my_stack_area);
K_THREAD_STACK_EXTERN(my_stack_area_0);

/******************************************************************************/
/* syscall needed to read timer value when in user space */
u32_t _impl_userspace_read_timer_value(void)
{
	TIMING_INFO_PRE_READ();
	return TIMING_INFO_GET_TIMER_VALUE();
}

Z_SYSCALL_HANDLER(userspace_read_timer_value)
{
	TIMING_INFO_PRE_READ();
	return TIMING_INFO_GET_TIMER_VALUE();
}

/******************************************************************************/

void drop_to_user_mode(void);
void user_thread_creation(void);
void syscall_overhead(void);
void validation_overhead(void);

void userspace_bench(void)
{
	struct k_mem_partition *parts[] = {
		&bench_ptn
	};

	k_mem_domain_init(&bench_domain, ARRAY_SIZE(parts), parts);
	k_mem_domain_add_thread(&bench_domain, k_current_get());

	drop_to_user_mode();

	user_thread_creation();

	syscall_overhead();

	validation_overhead();
}
/******************************************************************************/

void test_drop_to_user_mode_1(void *p1, void *p2, void *p3)
{
	volatile u32_t dummy = 100U;

	dummy++;
}

void drop_to_user_mode_thread(void *p1, void *p2, void *p3)
{
	TIMING_INFO_PRE_READ();
	drop_to_user_mode_start_time = TIMING_INFO_GET_TIMER_VALUE();
	k_thread_user_mode_enter(test_drop_to_user_mode_1, NULL, NULL, NULL);
}

void drop_to_user_mode(void)
{
#ifdef SysTick
	/* Reset the counter so that a interrupt doesn't happen inbetween
	 * the benchmark test
	 */
	SysTick->VAL = 0;
#endif

	/* Test time to drop to usermode from SU */

	k_thread_create(&my_thread_user, my_stack_area_0, STACK_SIZE,
			drop_to_user_mode_thread,
			NULL, NULL, NULL,
			-1 /*priority*/, K_INHERIT_PERMS, 0);

	k_yield();

	drop_to_user_mode_end_time = (u32_t)
		SUBTRACT_CLOCK_CYCLES(__end_drop_to_usermode_time);

	u32_t tmp_start_time =
		SUBTRACT_CLOCK_CYCLES(drop_to_user_mode_start_time);

	u32_t total_drop_to_user_mode_time =
		CYCLES_TO_NS((u32_t)
			     ((drop_to_user_mode_end_time - tmp_start_time) &
			      0xFFFFFFFFULL));

	PRINT_STATS("Drop to user mode",
		    (u32_t)((drop_to_user_mode_end_time - tmp_start_time) &
		     0xFFFFFFFFULL),
		    (u32_t) (total_drop_to_user_mode_time  & 0xFFFFFFFFULL));

}

/******************************************************************************/
void user_thread_creation(void)
{
	u32_t total_user_thread_creation_time;

	TIMING_INFO_PRE_READ();
	user_thread_creation_start_time = TIMING_INFO_GET_TIMER_VALUE();

	k_thread_create(&my_thread_user, my_stack_area, STACK_SIZE,
			test_drop_to_user_mode_1,
			NULL, NULL, NULL,
			0 /*priority*/, K_INHERIT_PERMS | K_USER, 0);

	TIMING_INFO_PRE_READ();
	user_thread_creation_end_time = TIMING_INFO_GET_TIMER_VALUE();
	k_thread_abort(&my_thread_user);

	u32_t total_cycles = (u32_t)
		((SUBTRACT_CLOCK_CYCLES(user_thread_creation_end_time) -
		  SUBTRACT_CLOCK_CYCLES(user_thread_creation_start_time)) &
		 0xFFFFFFFFULL);

	total_user_thread_creation_time = CYCLES_TO_NS(total_cycles);

	PRINT_STATS("User thread Creation",
		    total_cycles,
		    (u32_t) (total_user_thread_creation_time  & 0xFFFFFFFFULL));

}

/******************************************************************************/
/* dummy syscalls creation */
K_APP_BMEM(bench_ptn) u32_t syscall_overhead_start_time,
	syscall_overhead_end_time;

int _impl_k_dummy_syscall(void)
{
	return 0;
}

Z_SYSCALL_HANDLER(k_dummy_syscall)
{
	TIMING_INFO_PRE_READ();
	syscall_overhead_end_time = TIMING_INFO_GET_TIMER_VALUE();
	return 0;
}

void syscall_overhead_user_thread(void *p1, void *p2, void *p3)
{
	syscall_overhead_start_time = userspace_read_timer_value();
	int val = k_dummy_syscall();

	val |= 0xFF;
}

void syscall_overhead(void)
{
	u32_t total_syscall_overhead_time;

	k_thread_create(&my_thread_user, my_stack_area_0, STACK_SIZE,
			syscall_overhead_user_thread,
			NULL, NULL, NULL,
			-1 /*priority*/, K_INHERIT_PERMS | K_USER, 0);

	u32_t total_cycles = (u32_t)
		((SUBTRACT_CLOCK_CYCLES(syscall_overhead_end_time) -
		  SUBTRACT_CLOCK_CYCLES(syscall_overhead_start_time)) &
		 0xFFFFFFFFULL);

	total_syscall_overhead_time = CYCLES_TO_NS(total_cycles);

	PRINT_STATS("Syscall overhead",
		    total_cycles,
		    (u32_t) (total_syscall_overhead_time  & 0xFFFFFFFFULL));

}

/******************************************************************************/
K_SEM_DEFINE(test_sema, 1, 10);
u32_t validation_overhead_obj_init_start_time;
u32_t validation_overhead_obj_init_end_time;
u32_t validation_overhead_obj_start_time;
u32_t validation_overhead_obj_end_time;

int _impl_validation_overhead_syscall(void)
{
	return 0;
}

Z_SYSCALL_HANDLER(validation_overhead_syscall)
{
	TIMING_INFO_PRE_READ();
	validation_overhead_obj_init_start_time = TIMING_INFO_GET_TIMER_VALUE();

	bool status_0 = Z_SYSCALL_OBJ_INIT(&test_sema, K_OBJ_SEM);

	TIMING_INFO_PRE_READ();
	validation_overhead_obj_init_end_time = TIMING_INFO_GET_TIMER_VALUE();

	TIMING_INFO_PRE_READ();
	validation_overhead_obj_start_time = TIMING_INFO_GET_TIMER_VALUE();

	bool status_1 = Z_SYSCALL_OBJ(&test_sema, K_OBJ_SEM);

	TIMING_INFO_PRE_READ();
	validation_overhead_obj_end_time = TIMING_INFO_GET_TIMER_VALUE();
	return status_0 || status_1;
}

void validation_overhead_user_thread(void *p1, void *p2, void *p3)
{
	/* get validation numbers */
	validation_overhead_syscall();
}

void validation_overhead(void)
{
	k_thread_access_grant(k_current_get(), &test_sema);

	k_thread_create(&my_thread_user, my_stack_area, STACK_SIZE,
			validation_overhead_user_thread,
			NULL, NULL, NULL,
			-1 /*priority*/, K_INHERIT_PERMS | K_USER, 0);

	u32_t total_cycles_obj_init = (u32_t)
		((SUBTRACT_CLOCK_CYCLES(validation_overhead_obj_init_end_time) -
		  SUBTRACT_CLOCK_CYCLES(validation_overhead_obj_init_start_time)
		  ) & 0xFFFFFFFFULL);

	u32_t total_cycles_obj = (u32_t)
		((SUBTRACT_CLOCK_CYCLES(validation_overhead_obj_end_time) -
		  SUBTRACT_CLOCK_CYCLES(validation_overhead_obj_start_time)) &
		 0xFFFFFFFFULL);

	u32_t total_validation_overhead_obj_init_time =
		CYCLES_TO_NS(total_cycles_obj_init);

	u32_t  total_validation_overhead_obj_time =
		CYCLES_TO_NS(total_cycles_obj);

	PRINT_STATS("Validation overhead k object init",
		    total_cycles_obj_init,
		    (u32_t) (total_validation_overhead_obj_init_time  &
			     0xFFFFFFFFULL));

	PRINT_STATS("Validation overhead k object permission",
		    total_cycles_obj,
		    (u32_t) (total_validation_overhead_obj_time  &
			     0xFFFFFFFFULL));

}


text:
@implementation DirectoryMO

- (NSDictionary *)dictValue
{
	return [NSDictionary dictionaryWithObjectsAndKeys:
			self.title, @"title",
			@"", @"subtitle",
			[self icon], @"icon",
			nil];
}

@end


text:
<?php

return array(
    'Link my Google Account' => 'Knytt til min Google-konto',
    'Unlink my Google Account' => 'Fjern knytningen til min Google-konto',
    'Login with my Google Account' => 'Login med min Google-konto',
    'Google Account' => 'Google-konto',
    // 'Google Authentication' => '',
    // 'Help on Google authentication' => '',
);