text:
Next: Using Wide Char Classes, Previous: Case Conversion, Up: Character Handling   [Contents][Index]

4.3 Character class determination for wide characters

Amendment 1 to ISO C90 defines functions to classify wide
characters.  Although the original ISO C90 standard already defined
the type wchar_t, no functions operating on them were defined.

The general design of the classification functions for wide characters
is more general.  It allows extensions to the set of available
classifications, beyond those which are always available.  The POSIX
standard specifies how extensions can be made, and this is already
implemented in the GNU C Library implementation of the localedef
program.

The character class functions are normally implemented with bitsets,
with a bitset per character.  For a given character, the appropriate
bitset is read from a table and a test is performed as to whether a
certain bit is set.  Which bit is tested for is determined by the
class.

For the wide character classification functions this is made visible.
There is a type classification type defined, a function to retrieve this
value for a given class, and a function to test whether a given
character is in this class, using the classification value.  On top of
this the normal character classification functions as used for
char objects can be defined.

Data type: wctype_t

The wctype_t can hold a value which represents a character class.
The only defined way to generate such a value is by using the
wctype function.

This type is defined in <samp>wctype.h</samp>.

Function: wctype_t wctype (const char *<var>property</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

The wctype returns a value representing a class of wide
characters which is identified by the string <var>property</var>.  Beside
some standard properties each locale can define its own ones.  In case
no property with the given name is known for the current locale
selected for the LC_CTYPE category, the function returns zero.

The properties known in every locale are:

"alnum"	"alpha"	"cntrl"	"digit"

"graph"	"lower"	"print"	"punct"

"space"	"upper"	"xdigit"

This function is declared in <samp>wctype.h</samp>.

To test the membership of a character to one of the non-standard classes
the ISO C standard defines a completely new function.

Function: int iswctype (wint_t <var>wc</var>, wctype_t <var>desc</var>)

Preliminary:
| MT-Safe
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

This function returns a nonzero value if <var>wc</var> is in the character
class specified by <var>desc</var>.  <var>desc</var> must previously be returned
by a successful call to wctype.

This function is declared in <samp>wctype.h</samp>.

To make it easier to use the commonly-used classification functions,
they are defined in the C library.  There is no need to use
wctype if the property string is one of the known character
classes.  In some situations it is desirable to construct the property
strings, and then it is important that wctype can also handle the
standard classes.

Function: int iswalnum (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

This function returns a nonzero value if <var>wc</var> is an alphanumeric
character (a letter or number); in other words, if either iswalpha
or iswdigit is true of a character, then iswalnum is also
true.

This function can be implemented using

iswctype (wc, wctype ("alnum"))

It is declared in <samp>wctype.h</samp>.

Function: int iswalpha (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is an alphabetic character (a letter).  If
iswlower or iswupper is true of a character, then
iswalpha is also true.

In some locales, there may be additional characters for which
iswalpha is true—letters which are neither upper case nor lower
case.  But in the standard "C" locale, there are no such
additional characters.

This function can be implemented using

iswctype (wc, wctype ("alpha"))

It is declared in <samp>wctype.h</samp>.

Function: int iswcntrl (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a control character (that is, a character that
is not a printing character).

This function can be implemented using

iswctype (wc, wctype ("cntrl"))

It is declared in <samp>wctype.h</samp>.

Function: int iswdigit (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a digit (e.g., ‘<samp>0</samp>’ through ‘<samp>9</samp>’).
Please note that this function does not only return a nonzero value for
decimal digits, but for all kinds of digits.  A consequence is
that code like the following will not work unconditionally for
wide characters:

n = 0;
while (iswdigit (*wc))
  {
    n *= 10;
    n += *wc++ - L'0';
  }

This function can be implemented using

iswctype (wc, wctype ("digit"))

It is declared in <samp>wctype.h</samp>.

Function: int iswgraph (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a graphic character; that is, a character
that has a glyph associated with it.  The whitespace characters are not
considered graphic.

This function can be implemented using

iswctype (wc, wctype ("graph"))

It is declared in <samp>wctype.h</samp>.

Function: int iswlower (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a lower-case letter.  The letter need not be
from the Latin alphabet, any alphabet representable is valid.

This function can be implemented using

iswctype (wc, wctype ("lower"))

It is declared in <samp>wctype.h</samp>.

Function: int iswprint (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a printing character.  Printing characters
include all the graphic characters, plus the space (‘<samp> </samp>’) character.

This function can be implemented using

iswctype (wc, wctype ("print"))

It is declared in <samp>wctype.h</samp>.

Function: int iswpunct (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a punctuation character.
This means any printing character that is not alphanumeric or a space
character.

This function can be implemented using

iswctype (wc, wctype ("punct"))

It is declared in <samp>wctype.h</samp>.

Function: int iswspace (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a whitespace character.  In the standard
"C" locale, iswspace returns true for only the standard
whitespace characters:

L' '

space

L'\f'

formfeed

L'\n'

newline

L'\r'

carriage return

L'\t'

horizontal tab

L'\v'

vertical tab

This function can be implemented using

iswctype (wc, wctype ("space"))

It is declared in <samp>wctype.h</samp>.

Function: int iswupper (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is an upper-case letter.  The letter need not be
from the Latin alphabet, any alphabet representable is valid.

This function can be implemented using

iswctype (wc, wctype ("upper"))

It is declared in <samp>wctype.h</samp>.

Function: int iswxdigit (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a hexadecimal digit.
Hexadecimal digits include the normal decimal digits ‘<samp>0</samp>’ through
‘<samp>9</samp>’ and the letters ‘<samp>A</samp>’ through ‘<samp>F</samp>’ and
‘<samp>a</samp>’ through ‘<samp>f</samp>’.

This function can be implemented using

iswctype (wc, wctype ("xdigit"))

It is declared in <samp>wctype.h</samp>.

The GNU C Library also provides a function which is not defined in the
ISO C standard but which is available as a version for single byte
characters as well.

Function: int iswblank (wint_t <var>wc</var>)

Preliminary:
| MT-Safe locale
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

Returns true if <var>wc</var> is a blank character; that is, a space or a tab.
This function was originally a GNU extension, but was added in ISO C99.
It is declared in <samp>wchar.h</samp>.

Next: Using Wide Char Classes, Previous: Case Conversion, Up: Character Handling   [Contents][Index]


text:
#include "arm_compute/graph/nodes/FusedDepthwiseConvolutionBatchNormalizationNode.h"

#include "arm_compute/core/Utils.h"
#include "arm_compute/graph/Graph.h"
#include "arm_compute/graph/INodeVisitor.h"
#include "arm_compute/graph/Utils.h"

namespace arm_compute
{
namespace graph
{
FusedDepthwiseConvolutionBatchNormalizationNode::FusedDepthwiseConvolutionBatchNormalizationNode(float                      epsilon,
                                                                                PadStrideInfo              info,
                                                                                unsigned int               depth_multiplier,
                                                                                DepthwiseConvolutionMethod method,
                                                                                ActivationLayerInfo        fused_activation)
    : _epsilon(epsilon), _info(std::move(info)), _depth_multiplier(depth_multiplier), _method(method), _fused_activation(fused_activation)
{
    _input_edges.resize(7, EmptyEdgeID);
    _outputs.resize(1, NullTensorID);
}

void FusedDepthwiseConvolutionBatchNormalizationNode::set_depthwise_convolution_method(DepthwiseConvolutionMethod method)
{
    _method = method;
}

DepthwiseConvolutionMethod FusedDepthwiseConvolutionBatchNormalizationNode::depthwise_convolution_method() const
{
    return _method;
}

float FusedDepthwiseConvolutionBatchNormalizationNode::epsilon() const
{
    return _epsilon;
}

PadStrideInfo FusedDepthwiseConvolutionBatchNormalizationNode::convolution_info() const
{
    return _info;
}

unsigned int FusedDepthwiseConvolutionBatchNormalizationNode::depth_multiplier() const
{
    return _depth_multiplier;
}

ActivationLayerInfo FusedDepthwiseConvolutionBatchNormalizationNode::fused_activation() const
{
    return _fused_activation;
}

void FusedDepthwiseConvolutionBatchNormalizationNode::set_fused_activation(ActivationLayerInfo fused_activation)
{
    _fused_activation = fused_activation;
}

TensorDescriptor FusedDepthwiseConvolutionBatchNormalizationNode::compute_output_descriptor(const TensorDescriptor &input_descriptor,
                                                                                const TensorDescriptor &weights_descriptor,
                                                                                const PadStrideInfo    &info,
                                                                                int                     depth_multiplier)
{
    unsigned int output_width  = 0;
    unsigned int output_height = 0;

    const unsigned int input_width    = get_dimension_size(input_descriptor, DataLayoutDimension::WIDTH);
    const unsigned int input_height   = get_dimension_size(input_descriptor, DataLayoutDimension::HEIGHT);
    const unsigned int input_channels = get_dimension_size(input_descriptor, DataLayoutDimension::CHANNEL);
    const unsigned int kernel_width   = get_dimension_size(weights_descriptor, DataLayoutDimension::WIDTH);
    const unsigned int kernel_height  = get_dimension_size(weights_descriptor, DataLayoutDimension::HEIGHT);

    std::tie(output_width, output_height) = scaled_dimensions(input_width, input_height, kernel_width, kernel_height, info);

    TensorDescriptor output_descriptor = input_descriptor;
    output_descriptor.shape.set(get_dimension_idx(output_descriptor.layout, DataLayoutDimension::WIDTH), output_width);
    output_descriptor.shape.set(get_dimension_idx(output_descriptor.layout, DataLayoutDimension::HEIGHT), output_height);
    output_descriptor.shape.set(get_dimension_idx(output_descriptor.layout, DataLayoutDimension::CHANNEL), input_channels * depth_multiplier);

    return output_descriptor;
}

bool FusedDepthwiseConvolutionBatchNormalizationNode::forward_descriptors()
{
    if((input_id(0) != NullTensorID) && (input_id(1) != NullTensorID) && (output_id(0) != NullTensorID))
    {
        Tensor *dst = output(0);
        ARM_COMPUTE_ERROR_ON(dst == nullptr);
        dst->desc() = configure_output(0);
        return true;
    }
    return false;
}

TensorDescriptor FusedDepthwiseConvolutionBatchNormalizationNode::configure_output(size_t idx) const
{
    ARM_COMPUTE_UNUSED(idx);
    const Tensor *src     = input(0);
    const Tensor *weights = input(1);

    ARM_COMPUTE_ERROR_ON(src == nullptr || weights == nullptr);

    TensorDescriptor output_info = compute_output_descriptor(src->desc(), weights->desc(), _info, _depth_multiplier);

    return output_info;
}

NodeType FusedDepthwiseConvolutionBatchNormalizationNode::type() const
{
    return FusedDepthwiseConvolutionBatchNormalizationNode::node_type;
}

void FusedDepthwiseConvolutionBatchNormalizationNode::accept(INodeVisitor &v)
{
    v.visit(*this);
}
} // namespace graph
} // namespace arm_compute

redpajama_set_name: RedPajamaGithub


text:
package org.apache.servicecomb.foundation.protobuf.internal.schema.deserializer.scalar;

import java.io.IOException;

import org.apache.servicecomb.foundation.common.utils.bean.ByteSetter;
import org.apache.servicecomb.foundation.common.utils.bean.IntSetter;
import org.apache.servicecomb.foundation.common.utils.bean.ShortSetter;
import org.apache.servicecomb.foundation.protobuf.internal.ProtoUtils;
import org.apache.servicecomb.foundation.protobuf.internal.bean.PropertyDescriptor;
import org.apache.servicecomb.foundation.protobuf.internal.schema.deserializer.scalar.AbstractScalarReadSchemas.AbstractIntSchema;

import com.fasterxml.jackson.databind.JavaType;

import io.protostuff.InputEx;
import io.protostuff.compiler.model.Field;
import io.protostuff.runtime.FieldSchema;

public class Int32ReadSchemas {
  public static <T> FieldSchema<T> create(Field protoField, PropertyDescriptor propertyDescriptor) {
    JavaType javaType = propertyDescriptor.getJavaType();
    if (int.class.equals(javaType.getRawClass())) {
      return new IntFieldIntPrimitiveSchema<>(protoField, propertyDescriptor);
    }

    if (short.class.equals(javaType.getRawClass())) {
      return new ShortFieldIntPrimitiveSchema<>(protoField, propertyDescriptor);
    }

    if (byte.class.equals(javaType.getRawClass())) {
      return new ByteFieldIntPrimitiveSchema<>(protoField, propertyDescriptor);
    }

    if (Integer.class.equals(javaType.getRawClass()) || Byte.class.equals(javaType.getRawClass()) || Short.class
        .equals(javaType.getRawClass()) || javaType
        .isJavaLangObject()) {
      return new Int32Schema<>(protoField, propertyDescriptor);
    }

    ProtoUtils.throwNotSupportMerge(protoField, propertyDescriptor.getJavaType());
    return null;
  }

  private static class Int32Schema<T> extends AbstractIntSchema<T> {
    public Int32Schema(Field protoField, PropertyDescriptor propertyDescriptor) {
      super(protoField, propertyDescriptor);
    }

    @Override
    public int mergeFrom(InputEx input, T message) throws IOException {
      int value = input.readInt32();
      if (Byte.class.equals(javaType.getRawClass())) {
        setter.set(message, (byte) value);
      } else if (Short.class.equals(javaType.getRawClass())) {
        setter.set(message, (short) value);
      } else {
        setter.set(message, value);
      }
      return input.readFieldNumber();
    }
  }

  private static class IntFieldIntPrimitiveSchema<T> extends FieldSchema<T> {
    protected final IntSetter<T> setter;

    public IntFieldIntPrimitiveSchema(Field protoField, PropertyDescriptor propertyDescriptor) {
      super(protoField, propertyDescriptor.getJavaType());
      this.setter = propertyDescriptor.getSetter();
    }

    @Override
    public int mergeFrom(InputEx input, T message) throws IOException {
      int value = input.readInt32();
      setter.set(message, value);
      return input.readFieldNumber();
    }
  }

  private static class ShortFieldIntPrimitiveSchema<T> extends FieldSchema<T> {
    protected final ShortSetter<T> setter;

    public ShortFieldIntPrimitiveSchema(Field protoField, PropertyDescriptor propertyDescriptor) {
      super(protoField, propertyDescriptor.getJavaType());
      this.setter = propertyDescriptor.getSetter();
    }

    @Override
    public int mergeFrom(InputEx input, T message) throws IOException {
      int value = input.readInt32();
      setter.set(message, (short) value);
      return input.readFieldNumber();
    }
  }

  private static class ByteFieldIntPrimitiveSchema<T> extends FieldSchema<T> {
    protected final ByteSetter<T> setter;

    public ByteFieldIntPrimitiveSchema(Field protoField, PropertyDescriptor propertyDescriptor) {
      super(protoField, propertyDescriptor.getJavaType());
      this.setter = propertyDescriptor.getSetter();
    }

    @Override
    public int mergeFrom(InputEx input, T message) throws IOException {
      int value = input.readInt32();
      setter.set(message, (byte) value);
      return input.readFieldNumber();
    }
  }
}


text:
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.PowerShell.CmdletHelpAttributes;

namespace OfficeDevPnP.PowerShell.Commands
{
    [Cmdlet(VerbsCommon.Set, "SPOHomePage")]
    [CmdletHelp("Sets the home page of the current web.")]
    [CmdletExample(
        Code = @"
    PS:> Set-SPOHomePage -Path SitePages/Home.aspx
",
        Remarks = "Sets the home page to the home.aspx file which resides in the SitePages library")]
    public class SetHomePage : SPOWebCmdlet
    {
        [Parameter(Mandatory = true, HelpMessage = "The root folder relative path of the homepage", Position=0, ValueFromPipeline=true)]
        public string Path = string.Empty;

        protected override void ExecuteCmdlet()
        {
            SelectedWeb.SetHomePage(Path);
        }
    }

}


text:
#ifndef xeumeuleu_import_hpp
#define xeumeuleu_import_hpp

#include <xeumeuleu/bridges/xerces/detail/xerces.hpp>
#include <xeumeuleu/bridges/xerces/detail/xerces_ptr.hpp>

namespace xml
{
namespace detail
{
    inline bool is_empty( const XERCES_CPP_NAMESPACE::DOMNode& node )
    {
        if( node.getNodeType() != XERCES_CPP_NAMESPACE::DOMNode::TEXT_NODE
         && node.getNodeType() != XERCES_CPP_NAMESPACE::DOMNode::CDATA_SECTION_NODE )
            return false;
        const XMLCh* const value = node.getNodeValue();
        return XERCES_CPP_NAMESPACE::XMLChar1_1::isAllSpaces( value, XERCES_CPP_NAMESPACE::XMLString::stringLen( value ) );
    }

    inline XERCES_CPP_NAMESPACE::DOMNode& clone( XERCES_CPP_NAMESPACE::DOMDocument& document,
                                                 const XERCES_CPP_NAMESPACE::DOMNode& from,
                                                 XERCES_CPP_NAMESPACE::DOMNode& to )
    {
        xerces_ptr< XERCES_CPP_NAMESPACE::DOMNode > child( document.importNode( const_cast< XERCES_CPP_NAMESPACE::DOMNode* >( &from ), false ) );
        to.appendChild( child.get() );
        return child.release();
    }
}

    inline void import( XERCES_CPP_NAMESPACE::DOMDocument& document,
                        const XERCES_CPP_NAMESPACE::DOMNode* from,
                        XERCES_CPP_NAMESPACE::DOMNode& to )
    {
        while( from )
        {
            if( ! detail::is_empty( *from ) )
                import( document, from->getFirstChild(), detail::clone( document, *from, to ) );
            from = from->getNextSibling();
        }
    }

    inline XERCES_CPP_NAMESPACE::DOMNode& import( XERCES_CPP_NAMESPACE::DOMDocument& document,
                                                  const XERCES_CPP_NAMESPACE::DOMNode& from,
                                                  XERCES_CPP_NAMESPACE::DOMNode& to )
    {
        if( from.getNodeType() == XERCES_CPP_NAMESPACE::DOMNode::DOCUMENT_NODE )
        {
            if( from.getFirstChild() )
                import( document, *from.getFirstChild(), to );
            return document;
        }
        XERCES_CPP_NAMESPACE::DOMNode& added = detail::clone( document, from, to );
        import( document, from.getFirstChild(), added );
        return added;
    }
}

#endif // xeumeuleu_import_hpp


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

+ (AppDelegate *)sharedAppDelegate;
- (void)showLoader:(BOOL)show;
- (void)handleSignUpCompletion;
- (void)scheduleLocalNNotification;
- (void)cancelNotificationNotification;
@end


text:
<?php

/**
 * Look up sockpuppets
 * @since Version 3.10.0
 * @package Railpage
 * @author Michael Greenhill
 */

namespace Railpage\Users;

use Exception;
use DateTime;
use InvalidArgumentException;
use Railpage\Debug;
use Railpage\AppCore;
use Railpage\Url;
use Tga\SimHash\SimHash;
use Tga\SimHash\Extractor\SimpleTextExtractor;
use Tga\SimHash\Comparator\GaussianComparator;

require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/SimHash.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Fingerprint.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Comparator/ComparatorInterface.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Comparator/GaussianComparator.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Extractor/ExtractorInterface.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Extractor/SimpleTextExtractor.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Extractor/HtmlExtractor.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Tokenizer/TokenizerInterface.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Tokenizer/String128Tokenizer.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Tokenizer/String32Tokenizer.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Tokenizer/String64Tokenizer.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Vectorizer/VectorizerInterface.php");
require_once(RP_SITE_ROOT . "/vendor/tga/simhash-php/lib/Tga/SimHash/Vectorizer/DefaultVectorizer.php");

class SockpuppetManager extends AppCore {

    /**
     * The user we're basing the comparisons on
     * @since Version 3.10.0
     * @var \Railpage\Users\User $ReferenceUser
     */

    private $ReferenceUser;

    /**
     * An array of users we want to compare against
     * @since Version 3.10.0
     * @var array $suspects
     */

    private $suspects = array();

    /**
     * Set the reference user
     * @since Version 3.10.0
     * @param \Railpage\Users\User $userObject
     * @return \Railpage\Users\SockpuppetManager
     */

    public function setReferenceUser(User $userObject) {

        $this->ReferenceUser = $userObject;

        return $this;

    }

    /**
     * Add a suspect to our lookup array
     * @since Version 3.10.0
     * @param \Railpage\Users\User $userObject
     * @return \Railpage\Users\SockpuppetManager
     */

    public function addSuspect(User $userObject) {

        $this->suspects[$userObject->id] = $userObject;

        return $this;

    }

    /**
     * GoCompare!
     * @since Version 3.10.0
     * @return \Railpage\Users\SockpuppetManager
     */

    public function compare() {

        /**
         * Load our reference data first
         */

        $ref = array(
            "ips" => json_encode($this->ReferenceUser->getIPs(new DateTime("6 months ago")))
        );

        /**
         * Start our SimHash stuff
         */

        $SimHash = new SimHash;
        $Extractor = new SimpleTextExtractor;
        $Comparator = new GaussianComparator(3);

        foreach ($ref as $key => $lookup) {
            $this->hashes[$key]['reference'] = $SimHash->hash($Extractor->extract($lookup), SimHash::SIMHASH_64);
        }

        foreach ($this->suspects as $Suspect) {

            $suspectData = array(
                "ips" => json_encode($Suspect->getIPs(new DateTime("6 months ago")))
            );

            foreach ($suspectData as $key => $lookup) {
                $this->hashes[$key]['suspect'] = $SimHash->hash($Extractor->extract($lookup), SimHash::SIMHASH_64);
            }

            foreach ($this->hashes as $key => $users) {
                $this->results[$Suspect->id][$key] = $Comparator->compare($users['reference'], $users['suspect']);
            }

        }

    }

    /**
     * Get the results of this scan
     * @since Version 3.10.0
     * @return array
     */

    public function getResults() {

        printArray($this->results);

    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnError="false"
         stopOnFailure="false"
         verbose="true"
         syntaxCheck="false">
    <testsuites>
        <testsuite name="TPLink Smartplug Test Suite">
            <directory suffix=".php">./tests/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory>
            <exclude>
                <directory suffix=".php">./src/Laravel</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `get_vtable_index_of_object_method` fn in crate `rustc_trans`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, get_vtable_index_of_object_method">

    <title>rustc_trans::middle::traits::get_vtable_index_of_object_method - Rust</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

rustc_trans::<wbr>middle::<wbr>traits

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Function rustc_trans::<wbr>middle::<wbr>traits::<wbr>get_vtable_index_of_object_method<wbr>Unstable
            [-] [+]
        [src]

pub fn get_vtable_index_of_object_method(tcx: &ctxt<'tcx>, object_trait_ref: Binder<Rc<TraitRef<'tcx>>>, trait_def_id: DefId, method_offset_in_trait: usize) -> usize

Given an object of type object_trait_ref, returns the index of
the method n_method found in the trait trait_def_id (which
should be a supertrait of object_trait_ref) within the vtable
for object_trait_ref.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
package cf.brforgers.mods.ArchitectFriend;

public class Lib {
    //Mod Identity
    public static final String MODID = "ArchitectFriend";
    public static final String VERSION = "1.2";
    public static final String MODNAME = "Architect's Friend";
    public static final String DEPS = "required-after:BRCore@[1.0,)"; // + ";required-after:MODID"; for Each other MOD

    //Little Helper, huh?
    public static final String TEXTURE_PATH = MODID + ":";

    //Easter Eggs
    public static final String INITLOG = "Feeling a Architect, huh?";
}


text:
#pragma once
#ifndef BE_GFX_TEX_TEXTURE_FILE_ERROR_HPP_
#define BE_GFX_TEX_TEXTURE_FILE_ERROR_HPP_

#include <be/core/enum_traits.hpp>

/*!! include 'tex/texture_file_error' !! 53 */
/* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */

namespace be::gfx::tex {

///////////////////////////////////////////////////////////////////////////////
enum class TextureFileError : U8 {
   corrupted = 1,
   unsupported,
   image_unavailable,
   fatal_error
};

bool is_valid(TextureFileError constant) noexcept;
const char* texture_file_error_name(TextureFileError constant) noexcept;
std::array<const TextureFileError, 4> texture_file_error_values() noexcept;
std::ostream& operator<<(std::ostream& os, TextureFileError constant);
const char* texture_file_error_msg(TextureFileError constant) noexcept;

} // be::gfx::tex

namespace be {

///////////////////////////////////////////////////////////////////////////////
template <>
struct EnumTraits<::be::gfx::tex::TextureFileError> {
   using type = ::be::gfx::tex::TextureFileError;
   using underlying_type = typename std::underlying_type<type>::type;

   static constexpr std::size_t count = 4;

   static bool is_valid(type value) {
      return ::be::gfx::tex::is_valid(value);
   }

   static const char* name(type value) {
      return ::be::gfx::tex::texture_file_error_name(value);
   }

   template <typename C = std::array<const type, count>>
   static C values() {
      return {
         ::be::gfx::tex::TextureFileError::corrupted,
         ::be::gfx::tex::TextureFileError::unsupported,
         ::be::gfx::tex::TextureFileError::image_unavailable,
         ::be::gfx::tex::TextureFileError::fatal_error,
      };
   }
};

} // be

/* ######################### END OF GENERATED CODE ######################### */

namespace be::gfx::tex {

///////////////////////////////////////////////////////////////////////////////
class TextureFileErrorCategory : public std::error_category {
public:
   virtual const char* name() const noexcept { return "Texture File Error"; }
   virtual S message(int condition) const;
};

const std::error_category& texture_file_error_category();
std::error_code make_error_code(TextureFileError e);
std::error_condition make_error_condition(TextureFileError e);

} // be::gfx::tex

namespace std {

///////////////////////////////////////////////////////////////////////////////
template <>
struct is_error_condition_enum<be::gfx::tex::TextureFileError> : std::true_type { };

} // std

#endif


text:
namespace scriptor
{
  // Singleton class
  class AgentScriptor : public Scriptor
  {
  private:

    AgentScriptor();

    // copy ctor and assignment should be private
    AgentScriptor( const AgentScriptor& );
    AgentScriptor& operator = ( const AgentScriptor& );

  public:

    static AgentScriptor* Instance();

  };

} // namespace script

#endif


text:
This is the documentation for the nipy package.  Nipy aims to provide a
complete Python environment for the analysis of structural and functional
neuroimaging data. It currently has a full system for general
linear modeling of functional magnetic resonance imaging (fMRI).


text:
//@module

exports.pins = {
    red: { type: "PWM", value: 1 },
    green: { type: "PWM", value: 1  },
    blue: { type: "PWM", value: 1  },
    anode: { type: "Digital", direction: "output", value: 1  }
};

exports.configure = function( led ) {
	this.red.init();
	this.green.init();
	this.blue.init();
	this.anode.init();

	//turn off the lights
	this.red.write( led.pins.red.value );
	this.green.write( led.pins.green.value );
	this.blue.write( led.pins.blue.value );
	this.anode.write( led.pins.anode.value );
}

var THRESHOLD = 0.7;
var VALUE_ON_THRESHOLD = 0.3;

function convert(val) {
	var fraction = val / 255;
	return Math.pow(fraction, 4);

	if (fraction < 0) fraction = 0;
	else if (fraction > 1.0) fraction = 1.0;

	var offset, max;
	if (fraction <= THRESHOLD) {
		offset = 0;
		max = VALUE_ON_THRESHOLD;
		fraction /= THRESHOLD;
	} else {
		offset = VALUE_ON_THRESHOLD;
		max = 1.0 - VALUE_ON_THRESHOLD;
		fraction = (fraction - THRESHOLD) / (1.0 - THRESHOLD);
	}

	return offset + max * fraction;
}

exports.write = function( parameters ) {
	if ('red' in parameters)
		this.red.write( 1 - convert(parameters.red) );
	if ('green' in parameters)
		this.green.write( 1 - convert(parameters.green) );
	if ('blue' in parameters)
		this.blue.write( 1 - convert(parameters.blue) );
}

exports.close = function( led ){
	this.red.write(0);
	this.green.write(0);
	this.blue.write(0);
	this.anode.write(0);

	this.red.close();
	this.green.close();
	this.blue.close();
	this.anode.close();
}


text:
<?php

class PaymentException extends Exception {

	protected $_attributes = null;

	protected $_messageTemplate = null;

	public function __construct($message, $code = null) {
		if (is_array($message)) {
			$this->_attributes = $message;
			$message = sprintf($this->_messageTemplate, $message);
		}

		parent::__construct($message, $code);
	}

}


text:
#pragma once

#include <iostream>
#include <memory>
#include <utility>
#include <atomic>
#include <set>
#include <algorithm>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <boost/smart_ptr.hpp>

#include "../common.h"

using namespace boost::system;

#define MIN_PACKET_SIZE             64
#define MAX_PACKET_SIZE	            (64 * 1024)

// Whether use atomic update realtime?
#define USE_ATOMIC_REALTIME_UPDATE  0

#define QUERY_COUNTER_INTERVAL      99

#define MAX_UPDATE_CNT              5
#define MAX_UPDATE_BYTES            32768

using namespace boost::asio;

namespace asio_test {

const std::string g_request_html_header =
        "GET /cookies HTTP/1.1\r\n"
        "Host: 127.0.0.1:8090\r\n"
        "Connection: keep-alive\r\n"
        "Cache-Control: max-age=0\r\n"
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
        "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17\r\n"
        "Accept-Encoding: gzip,deflate,sdch\r\n"
        "Accept-Language: en-US,en;q=0.8\r\n"
        "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n"
        "Cookie: name=wookie\r\n"
        "\r\n";

const std::string g_response_html =
        "HTTP/1.1 200 OK\r\n"
        "Date: Fri, 31 Aug 2016 16:25:26 GMT\r\n"
        "Server: boost-asio\r\n"
        "Content-Type: text/html\r\n"
        "Content-Length: 12\r\n"
        "Connection: Keep-Alive\r\n\r\n"
        "Hello World!";

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

                            < Http Ring Buffer >

 Bottom        Back         Parsed              Front                          Top
    |-----------|--------------|------------------|-----------------------------|
                ^              ^                  ^
*/
////////////////////////////////////////////////////////////////////////////////////

class http_ring_buffer {
private:
    std::unique_ptr<char> buffer_;
    std::size_t buffer_size_;
    char * top_;
    char * back_;
    char * parsed_;
    char * front_;

public:
    http_ring_buffer(std::size_t buffer_size)
        : buffer_size_(buffer_size), top_(nullptr), back_(nullptr),
          parsed_(nullptr), front_(nullptr) {
        init_ring_buffer(buffer_size);
    }
    ~http_ring_buffer() {}

private:
    void init_ring_buffer(std::size_t buffer_size) {
        char * newBuffer = new (std::nothrow) char [buffer_size * 2];
        if (newBuffer) {
            ::memset(newBuffer, 0, buffer_size * 2 * sizeof(char));
        }
        buffer_.reset(newBuffer);

        char * _bottom = buffer_.get();
        top_ = _bottom + buffer_size * 2;
        back_ = _bottom;
        parsed_ = _bottom;
        front_ = _bottom;
    }

public:
    std::size_t buffer_size() const { return buffer_size_; }
    std::size_t total_sizes() const { return buffer_size_ * 2; }
    std::size_t offset() const { return static_cast<std::size_t>(back_ - buffer_.get()); }
    std::size_t empty_size() const { return offset(); }
    std::size_t free_size() const { return static_cast<std::size_t>(top_ - front_); }
    std::size_t data_length() const { return static_cast<std::size_t>(front_ - back_); }

    std::size_t parse_pos() const { return static_cast<std::size_t>(parsed_ - back_); }

    char * data() const { return buffer_.get(); }

    char * bottom() const { return buffer_.get(); }
    char * top() const { return top_; }
    char * back() const { return back_; }
    char * parsed() const { return parsed_; }
    char * front() const { return front_; }

    void reset(std::size_t data_bytes, std::size_t parsed_pos) {
        char * _bottom = buffer_.get();
        back_ = _bottom;
        parsed_ = _bottom + parsed_pos;
        front_ = _bottom + data_bytes;
    }

    void rollback() {
        std::size_t offset = this->offset();
        std::size_t free_bytes = free_size();
        std::size_t data_bytes = data_length();
        std::size_t parsed_offset = parse_pos();

        if (offset >= 16) {
            ::memcpy((void *)bottom(), (void *)back(), data_bytes * sizeof(char));
        }
        else {
            ::memmove((void *)bottom(), (void *)back(), data_bytes * sizeof(char));
        }
        reset(data_bytes, parsed_offset);
    }

    bool read(std::size_t recv_size) {
        if (front_ + recv_size <= top_) {
            front_ += recv_size;
            return true;
        }
        else {
            return false;
        }
    }

    void parse_to(char * parsed) {
        back_ = parsed;
        parsed_ = parsed;
    }

    bool parse_add(std::size_t parse_size) {
        if (parsed_ + parse_size < top_) {
            parsed_ += parse_size;
            back_ = parsed_;
            return true;
        }
        else {
            parsed_ = top_;
            back_ = top_;
            return false;
        }
    }

    bool parse(char * &parsed) {
        // Forward-tracking find method
        char * cur = parsed_;
        while (cur <= (front_ - 4)) {
            if (cur[0] == '\r' && cur[2] == '\r'
                && cur[1] == '\n' && cur[3] == '\n') {
                parsed = (cur + 4);
                return true;
            }
            cur++;
            assert(cur < top_);
        }
        parsed = cur;
        return false;
    }

    bool back_parse(char * &parsed) {
        // Back-tracking find method
        char * cur = front_ - 4;
        while (cur >= parsed_) {
            if (cur[0] == '\r') {
                if (cur[2] == '\r') {
                    if (cur[1] == '\n' && cur[3] == '\n') {
                        parsed = (cur + 4);
                        return true;
                    }
                    // TODO: If HTTP header request format is standard, this way is Ok.
                    cur -= 4;
                }
                else if (cur[1] == '\n') {
                    cur -= 2;
                }
                else {
                    cur -= 4;
                }
            }
            else if (cur[0] == '\n') {
                cur--;
            }
            else {
                cur -= 4;
            }
        }
        parsed = front_;
        return false;
    }
};

class connection_manager;

class asio_http_session : public std::enable_shared_from_this<asio_http_session>,
                          private boost::noncopyable {
private:
    enum { PACKET_SIZE = MAX_PACKET_SIZE };

    /// Socket for the connection.
    ip::tcp::socket socket_;
    /// The manager for this connection.
    connection_manager * connection_manager_;

    bool        nodelay_;
    uint32_t    need_echo_;
    uint32_t    buffer_size_;
    uint32_t    packet_size_;
    uint64_t    recv_counter_;
    uint64_t    send_counter_;

    uint32_t    recv_bytes_;
    uint32_t    send_bytes_;
    uint32_t    recv_cnt_;
    uint32_t    send_cnt_;

    uint32_t    delta_recv_count_;
    uint32_t    delta_send_count_;
    uint32_t    recv_bytes_remain_;
    uint32_t    send_bytes_remain_;

    http_ring_buffer buffer_;

public:
    asio_http_session(boost::asio::io_service & io_service, connection_manager * manager, uint32_t buffer_size,
                      uint32_t packet_size, uint32_t need_echo = mode_need_echo)
        : socket_(io_service), connection_manager_(manager), nodelay_(false), need_echo_(need_echo),
          buffer_size_(buffer_size), packet_size_(packet_size),
          recv_counter_(0), send_counter_(0), recv_bytes_(0), send_bytes_(0), recv_cnt_(0), send_cnt_(0),
          delta_recv_count_(0), delta_send_count_(0), recv_bytes_remain_(0), send_bytes_remain_(0), buffer_(buffer_size)
    {
        nodelay_ = (g_nodelay != 0);
        if (buffer_size_ > MAX_PACKET_SIZE)
            buffer_size_ = MAX_PACKET_SIZE;
        if (packet_size_ > MAX_PACKET_SIZE)
            packet_size_ = MAX_PACKET_SIZE;
    }

    ~asio_http_session()
    {
    }

    void start()
    {
        set_socket_send_bufsize(MAX_PACKET_SIZE);
        set_socket_recv_bufsize(MAX_PACKET_SIZE);

        static const int kNetSendTimeout = 45 * 1000;    // Send timeout is 45 seconds.
        static const int kNetRecvTimeout = 45 * 1000;    // Recieve timeout is 45 seconds.
        ::setsockopt(socket_.native_handle(), SOL_SOCKET, SO_SNDTIMEO, (const char *)&kNetSendTimeout, sizeof(kNetSendTimeout));
        ::setsockopt(socket_.native_handle(), SOL_SOCKET, SO_RCVTIMEO, (const char *)&kNetRecvTimeout, sizeof(kNetRecvTimeout));

        socket_.set_option(ip::tcp::no_delay(nodelay_));

        linger sLinger;
        sLinger.l_onoff = 1;    // Enable linger
        sLinger.l_linger = 5;   // After shutdown(), socket send/recv 5 second data yet.
        ::setsockopt(socket_.native_handle(), SOL_SOCKET, SO_LINGER, (const char *)&sLinger, sizeof(sLinger));

        g_client_count++;

        if (g_first_time) {
            g_first_time = false;
            g_start_time = high_resolution_clock::now();
        }

        start_connection();

        do_read_some();
    }

    void stop()
    {
        if (socket_.is_open()) {
            init_shutdown();

#if !defined(_WIN32_WINNT) || (_WIN32_WINNT >= 0x0600)
            //socket_.cancel();
#endif
            socket_.close();

            if (g_client_count.load() != 0)
                g_client_count--;
        }
    }

    void start_connection();
    void stop_connection(const boost::system::error_code & ec);

    void init_shutdown()
    {
        // Initiate graceful connection closure.
        boost::system::error_code ignored_ec;
        socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
    }

    ip::tcp::socket & socket()
    {
        return socket_;
    }

    static boost::shared_ptr<asio_http_session> create_new(
        boost::asio::io_service & io_service, connection_manager * conn_manager, uint32_t buffer_size, uint32_t packet_size) {
        return boost::shared_ptr<asio_http_session>(new asio_http_session(io_service, conn_manager, buffer_size, packet_size, g_test_mode));
    }

private:
    int get_socket_send_bufsize() const
    {
        boost::asio::socket_base::send_buffer_size send_bufsize_option;
        socket_.get_option(send_bufsize_option);
        return send_bufsize_option.value();
    }

    void set_socket_send_bufsize(int buffer_size)
    {
        boost::asio::socket_base::receive_buffer_size send_bufsize_option(buffer_size);
        socket_.set_option(send_bufsize_option);
    }

    int get_socket_recv_bufsize() const
    {
        boost::asio::socket_base::receive_buffer_size recv_bufsize_option;
        socket_.get_option(recv_bufsize_option);
        return recv_bufsize_option.value();
    }

    void set_socket_recv_bufsize(int buffer_size)
    {
        boost::asio::socket_base::receive_buffer_size recv_bufsize_option(buffer_size);
        socket_.set_option(recv_bufsize_option);
    }

    inline void do_recieve_counter(uint32_t bytes_recieved)
    {
#if defined(USE_ATOMIC_REALTIME_UPDATE) && (USE_ATOMIC_REALTIME_UPDATE > 0)
        if (bytes_recieved > 0) {
            g_recv_bytes.fetch_add(bytes_recieved);
        }
#else
        if (bytes_recieved > 0) {
            recv_bytes_ += bytes_recieved;
            recv_cnt_++;
            if (recv_cnt_ >= MAX_UPDATE_CNT || recv_bytes_ >= MAX_UPDATE_BYTES) {
                g_recv_bytes.fetch_add(recv_bytes_);
                recv_bytes_ = 0;
                recv_cnt_ = 0;
            }
        }
#endif
    }

    inline void do_send_counter(uint32_t bytes_sent)
    {
#if defined(USE_ATOMIC_REALTIME_UPDATE) && (USE_ATOMIC_REALTIME_UPDATE > 0)
        if (bytes_sent > 0) {
            g_send_bytes.fetch_add(bytes_sent);
        }
#else
        if (bytes_sent > 0) {
            send_bytes_ += bytes_sent;
            send_cnt_++;
            if (send_cnt_ >= MAX_UPDATE_CNT || send_bytes_ >= MAX_UPDATE_BYTES) {
                g_send_bytes.fetch_add(send_bytes_);
                send_bytes_ = 0;
                send_cnt_ = 0;
            }
        }
#endif
    }

    inline void do_recv_qps_counter()
    {
#if defined(USE_ATOMIC_REALTIME_UPDATE) && (USE_ATOMIC_REALTIME_UPDATE > 0)
        g_query_count.fetch_add(1);
#else
        recv_counter_++;
        if (recv_counter_ >= QUERY_COUNTER_INTERVAL) {
            g_query_count.fetch_add(QUERY_COUNTER_INTERVAL);
            recv_counter_ = 0;
        }
#endif
    }

    inline void do_recv_qps_counter_read_some(uint32_t recv_bytes)
    {
        uint32_t delta_bytes = recv_bytes_remain_ + recv_bytes;
        if (delta_bytes >= g_request_html_header.size()) {
            uint64_t delta_send_count = delta_bytes / g_request_html_header.size();
#if defined(USE_ATOMIC_REALTIME_UPDATE) && (USE_ATOMIC_REALTIME_UPDATE > 0)
            if (delta_send_count > 0) {
                g_query_count.fetch_add(delta_send_count);
                recv_bytes_remain_ = delta_bytes - g_request_html_header.size() * delta_send_count;
                return;
            }
#else
            if (delta_send_count >= QUERY_COUNTER_INTERVAL) {
                g_query_count.fetch_add(delta_send_count);
                recv_bytes_remain_ = delta_bytes - (uint32_t)(g_request_html_header.size() * delta_send_count);
                return;
            }
#endif
        }
        recv_bytes_remain_ = delta_bytes;
    }

    inline void do_send_counter_write_some(uint32_t send_bytes)
    {
        uint32_t delta_bytes = send_bytes_remain_ + send_bytes;
        static const uint32_t response_size = (uint32_t)g_response_html.size();
        if (delta_bytes >= response_size) {
            uint32_t delta_query_count = delta_bytes / response_size;
#if defined(USE_ATOMIC_REALTIME_UPDATE) && (USE_ATOMIC_REALTIME_UPDATE > 0)
            if (delta_query_count > 0) {
                //g_query_count.fetch_add(delta_query_count);
                send_bytes_remain_ = delta_bytes - response_size * delta_query_count;
                return;
            }
#else
            if (delta_query_count >= QUERY_COUNTER_INTERVAL) {
                //g_query_count.fetch_add(delta_query_count);
                send_bytes_remain_ = delta_bytes - response_size * delta_query_count;
                return;
            }
#endif
        }
        send_bytes_remain_ = delta_bytes;
    }

    inline void do_send_counter_sync_write()
    {
#if defined(USE_ATOMIC_REALTIME_UPDATE) && (USE_ATOMIC_REALTIME_UPDATE > 0)
        g_query_count.fetch_add(1);
#else
        delta_send_count_++;
        if (delta_send_count_ >= QUERY_COUNTER_INTERVAL) {
            //g_query_count.fetch_add(delta_send_count_);
            delta_send_count_ = 0;
        }
#endif
    }

    void do_read()
    {
        boost::asio::async_read(socket_, boost::asio::buffer(buffer_.data(), packet_size_),
            [this](const boost::system::error_code & ec, std::size_t recv_bytes)
            {
                if ((uint32_t)recv_bytes != packet_size_) {
                    std::cout << "asio_http_session::do_read(): async_read(), recv_bytes = "
                              << recv_bytes << " bytes." << std::endl;
                }
                if (!ec) {
                    // Count the recieved bytes
                    do_recieve_counter((uint32_t)recv_bytes);

                    // A successful request, can be used to statistic qps
                    do_write();
                }
                else {
                    // Write error log
                    std::cout << "asio_http_session::do_read() - Error: (code = " << ec.value() << ") "
                              << ec.message().c_str() << std::endl;

                    stop_connection(ec);
                }
            }
        );
    }

    void do_write()
    {
        boost::asio::async_write(socket_, boost::asio::buffer(buffer_.data(), packet_size_),
            [this](const boost::system::error_code & ec, std::size_t send_bytes)
            {
                if (!ec) {
                    // Count the sent bytes
                    do_send_counter((uint32_t)send_bytes);

                    // If get a circle of ping-pong, we count the query one time.
                    do_send_counter_write_some((uint32_t)send_bytes);

                    if ((uint32_t)send_bytes != packet_size_) {
                        std::cout << "asio_http_session::do_write(): async_write(), send_bytes = "
                                  << send_bytes << " bytes." << std::endl;
                    }

                    do_read();
                }
                else {
                    // Write error log
                    std::cout << "asio_http_session::do_write() - Error: (code = " << ec.value() << ") "
                              << ec.message().c_str() << std::endl;

                    stop_connection(ec);
                }
            }
        );
    }

    void do_read_some()
    {
        static bool is_first_read = true;
        static int debug_output_cnt = 0;

        if (buffer_.free_size() <= 1024) {
            // Roll back the ring buffer
            buffer_.rollback();
        }

        char * read_data = buffer_.front();
        std::size_t read_size = std::min(buffer_size_, (uint32_t)buffer_.free_size());
        assert(read_size > 0);

        socket_.async_read_some(boost::asio::buffer(read_data, read_size),
            [this](const boost::system::error_code & ec, std::size_t recv_bytes)
            {
                if (!ec) {
                    if (is_first_read) {
                        packet_size_ = (uint32_t)recv_bytes;
                        g_packet_size = packet_size_;
                        is_first_read = false;
                        std::cout << "recv_bytes = " << recv_bytes << std::endl;
                    }
                    else {
#if 0
                        if (debug_output_cnt < 20) {
                            std::cout << "recv_bytes = " << recv_bytes << std::endl;
                            debug_output_cnt++;
                        }
#endif
                    }

                    // Count the recieved bytes
                    do_recieve_counter((uint32_t)recv_bytes);

                    bool is_ok = buffer_.read(recv_bytes);
                    if (!is_ok) {
                        // Roll back the ring buffer
                        buffer_.rollback();

                        do_read_some();
                        return;
                    }

                    char * scanned;
                    bool http_header_ok;
                    do {
                        http_header_ok = buffer_.parse(scanned);
                        if (http_header_ok) {
                            buffer_.parse_to(scanned);

                            do_recv_qps_counter();

                            // A successful http request, can be used to statistic qps.
                            if (!nodelay_) {
                                // nodelay = false;
#if 1
                                do_async_write_http_response();
#else
                                do_async_write_http_response_some();
#endif
                            }
                            else {
                                // nodelay = true;
                                do_sync_write_http_response();
                            }
                        }
                        else {
                            break;
                        }
                    } while (1);

                    do_read_some();
                }
                else {
                    // Write error log
#if 1
                    std::cout << "asio_http_session::do_read_some() - Error: (recv_bytes = " << recv_bytes
                              << ", code = " << ec.value() << ") "
                              << ec.message().c_str() << std::endl;
#endif
                    stop_connection(ec);
                }
            }
        );
    }

    void do_sync_write_http_response()
    {
        static bool is_first_read = true;
        boost::system::error_code ec;
        std::size_t send_bytes = boost::asio::write(socket_,
            boost::asio::buffer(g_response_html.c_str(), g_response_html.size()),
            ec);
        if (!ec) {
#if 0
            if (is_first_read) {
                std::cout << "g_response_html.size() = " << g_response_html.size() << std::endl;
                is_first_read = false;
            }
#endif
            // Count the sent bytes
            do_send_counter((uint32_t)send_bytes);

            // If get a circle of ping-pong, we count the query one time.
            do_send_counter_sync_write();

            if ((uint32_t)send_bytes != g_response_html.size() && send_bytes != 0) {
                std::cout << "asio_http_session::do_sync_write_http_response(): async_write(), send_bytes = "
                            << send_bytes << " bytes." << std::endl;
            }

            //do_read_some();
        }
        else {
            // Write error log
            std::cout << "asio_http_session::do_sync_write_http_response() - Error: (send_bytes = " << send_bytes
                        << ", code = " << ec.value() << ") "
                        << ec.message().c_str() << std::endl;

            stop_connection(ec);
        }
    }

    void do_async_write_http_response()
    {
        static bool is_first_read = true;
        boost::asio::async_write(socket_, boost::asio::buffer(g_response_html.c_str(), g_response_html.size()),
            [this](const boost::system::error_code & ec, std::size_t send_bytes)
            {
                if (!ec) {
#if 0
                    if (is_first_read) {
                        std::cout << "g_response_html.size() = " << g_response_html.size() << std::endl;
                        is_first_read = false;
                    }
#endif
                    // Count the sent bytes
                    do_send_counter((uint32_t)send_bytes);

                    // If get a circle of ping-pong, we count the query one time.
                    do_send_counter_sync_write();

                    if ((uint32_t)send_bytes != g_response_html.size() && send_bytes != 0) {
                        std::cout << "asio_http_session::do_async_write_http_response(): async_write(), send_bytes = "
                                  << send_bytes << " bytes." << std::endl;
                    }

                    //do_read_some();
                }
                else {
                    // Write error log
                    std::cout << "asio_http_session::do_async_write_http_response() - Error: (send_bytes = " << send_bytes
                              << ", code = " << ec.value() << ") "
                              << ec.message().c_str() << std::endl;

                    stop_connection(ec);
                }
            }
        );
    }

    void do_async_write_http_response_some()
    {
        static bool is_first_read = true;
        socket_.async_write_some(boost::asio::buffer(g_response_html.c_str(), g_response_html.size()),
            [this](const boost::system::error_code & ec, std::size_t send_bytes)
            {
                if (!ec) {
#if 0
                    if (is_first_read) {
                        std::cout << "g_response_html.size() = " << g_response_html.size() << std::endl;
                        is_first_read = false;
                    }
#endif
                    // Count the sent bytes
                    do_send_counter((uint32_t)send_bytes);

                    // If get a circle of ping-pong, we count the query one time.
                    do_send_counter_sync_write();

                    if ((uint32_t)send_bytes != g_response_html.size() && send_bytes != 0) {
                        std::cout << "asio_http_session::do_async_write_http_response_some(): async_write(), send_bytes = "
                                  << send_bytes << " bytes." << std::endl;
                    }

                    //do_read_some();
                }
                else {
                    // Write error log
                    std::cout << "asio_http_session::do_async_write_http_response_some() - Error: (send_bytes = " << send_bytes
                              << ", code = " << ec.value() << ") "
                              << ec.message().c_str() << std::endl;

                    stop_connection(ec);
                }
            }
        );
    }

    void do_write_some(int32_t total_send_bytes)
    {
        while (total_send_bytes > 0) {
            std::size_t buffer_size;
            if (total_send_bytes < PACKET_SIZE)
                buffer_size = total_send_bytes;
            else
                buffer_size = PACKET_SIZE;
#if 1
            // async write one time <= PACKET_SIZE
            boost::asio::async_write(socket_, boost::asio::buffer(buffer_.data(), buffer_size),
                [this, buffer_size](const boost::system::error_code & ec, std::size_t send_bytes)
                {
                    if (!ec) {
                        // Count the sent bytes
                        do_send_counter((uint32_t)send_bytes);

                        // If get a circle of ping-pong, we count the query one time.
                        do_send_counter_write_some((uint32_t)send_bytes);

                        if ((uint32_t)send_bytes != buffer_size) {
                            std::cout << "asio_http_session::do_write_some(): async_write(), send_bytes = "
                                      << send_bytes << " bytes." << std::endl;
                        }

                        do_read_some();
                    }
                    else {
                        // Write error log
                        std::cout << "asio_http_session::do_write_some() - Error: (send_bytes = " << send_bytes
                                  << ", code = " << ec.value() << ") "
                                  << ec.message().c_str() << std::endl;

                        stop_connection(ec);
                    }
                }
            );
#else
            // async write some one time <= PACKET_SIZE
            socket_.async_write_some(boost::asio::buffer(buffer_.data(), buffer_size),
                [this, buffer_size](const boost::system::error_code & ec, std::size_t send_bytes)
                {
                    if (!ec) {
                        // Count the sent bytes
                        do_send_counter((uint32_t)send_bytes);

                        // If get a circle of ping-pong, we count the query one time.
                        do_send_counter_write_some((uint32_t)send_bytes);

                        if ((uint32_t)send_bytes != buffer_size) {
                            std::cout << "asio_http_session::do_write_some(): async_write(), send_bytes = "
                                      << send_bytes << " bytes." << std::endl;
                        }

                        do_read_some();
                    }
                    else {
                        // Write error log
                        std::cout << "asio_http_session::do_write() - Error: (code = " << ec.value() << ") "
                                  << ec.message().c_str() << std::endl;

                        stop_connection(ec);
                    }
                }
            );
#endif
            total_send_bytes -= PACKET_SIZE;
        }
    }
};

typedef std::shared_ptr<asio_http_session> connection_ptr;

//
// See: https://www.boost.org/doc/libs/1_48_0/doc/html/boost_asio/example/http/server/connection.hpp
//

/// Manages open connections so that they may be cleanly stopped when the server
/// needs to shut down.
class connection_manager : private boost::noncopyable
{
private:
    /// The managed connections.
    std::set<connection_ptr> connections_;

public:
    /// Add the specified connection to the manager and start it.
    void connection_manager::start(connection_ptr connection)
    {
        connections_.insert(connection);
        //connection->start();
    }

    /// Stop the specified connection.
    void connection_manager::stop(connection_ptr connection)
    {
        connections_.erase(connection);
        connection->stop();
    }

    /// Stop all connections.
    void connection_manager::stop_all()
    {
        std::for_each(connections_.begin(), connections_.end(), std::bind(&asio_http_session::stop, std::placeholders::_1));
        connections_.clear();
    }
};

void asio_http_session::start_connection()
{
    //if (connection_manager_)
    //    connection_manager_->start(asio_http_session::shared_from_this());
}

void asio_http_session::stop_connection(const boost::system::error_code & ec)
{
    if (ec != boost::asio::error::operation_aborted)
    {
        //if (connection_manager_)
        //    connection_manager_->stop(asio_http_session::shared_from_this());
        stop();
    }
}

} // namespace asio_test

#undef USE_ATOMIC_REALTIME_UPDATE
#undef QUERY_COUNTER_INTERVAL

#undef MAX_UPDATE_CNT
#undef MAX_UPDATE_BYTES


text:
require "spec_helper"

<% module_namespacing do -%>
describe <%= class_name %> do
<% for action in actions -%>
  describe "<%= action %>" do
    let(:mail) { <%= class_name %>.<%= action %> }

    it "renders the headers" do
      mail.subject.should eq(<%= action.to_s.humanize.inspect %>)
      mail.to.should eq(["to@example.org"])
      mail.from.should eq(["from@example.com"])
    end

    it "renders the body" do
      mail.body.encoded.should match("Hi")
    end
  end

<% end -%>
<% if actions.blank? -%>
  pending "add some examples to (or delete) #{__FILE__}"
<% end -%>
end
<% end -%>


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * @author  Peter Boros
 * @date    2004/09/05
 * @version $Id$
 * @file    singleton.h
 * @brief   Singleton pattern.
 */

#pragma once

#include <list>

#include "mutex.h"

namespace fsa {

// {{{ class SingletonExitHandler

/**
 * @class SingletonExitHandler
 * @brief %Singleton exit handler.
 *
 * %Singleton exit handler. Uses the atexit() librarary call to
 * destory all Singleton objects in reverse order as they were
 * created. It is also a singleton self.
 */
class SingletonExitHandler
{
private:

  /** Default constructor */
  SingletonExitHandler();

  /** Method to call at exit, destroys all Singletons. */
  static void atExit();

  /** Instance pointer */
  static SingletonExitHandler* _instance;

  /** Destroy method -  does the dirty work */
  void destroy();

  typedef std::list<void(*)()>            FunctionList;
  typedef std::list<void(*)()>::iterator  FunctionListIterator;

  /** List of Singleton destroy functions */
  FunctionList _functionList;

public:

  /** Destructor */
  virtual ~SingletonExitHandler();

  /**
   * @brief Get instance pointer.
   *
   * @return pointer to instance.
   */
  static SingletonExitHandler* instance();

  /**
   * @brief Register a singleton.
   *
   * @param p Pointer to destroy function of the singleton.
   */
  void registerSingletonDestroyer(void (*p)());

};

// }}}

// {{{ class Singleton

/**
 * @class Singleton
 * @brief %Singleton template.
 *
 * %Singleton template (from Design Patterns by Gamma et al.). To use
 * it, subclass as follows, and make constructors private:
 *
 *  class MyClass : public Singleton<MyClass> {
 *    friend class Singleton<MyClass>;
 *  private:
 *    MyClass();
 *  public:
 *    void MyMethod();
 *  ...
 *  }
 *
 * and then call MyMethod as:
 *
 *   MyClass::instance().MyMethod();
 *
 */
template<typename T>
class Singleton
{
  /** SingletonExitHandler handles destruction. */
  friend class SingletonExitHandler;

public:
  /** Destructor */
  virtual ~Singleton();

  /**
   * @brief Get reference to the instance.
   *
   * Get reference to the instance. The first call of this method will
   * create the instance, and register the destroy function with the
   * exit handler.
   *
   * @return Reference to the instance.
   */
  static T& instance();

protected:

  /** Explicit constructor (to avoid implicit conversion). */
  explicit Singleton();

private:

  /** Copy constructor (unimplemented) */
  Singleton(const Singleton&);
  /** Assignment operator (unimplemented) */
  Singleton& operator=(const Singleton&);

  /** Destroy function - this will be registered with the exit handler. */
  static void destroy();

  static Mutex _lock;  /**< Mutex for synchronization. */

  static T* _instance; /**< Instance pointer.          */
};

template<typename T> Singleton<T>::Singleton() {}

template<typename T> Singleton<T>::~Singleton() {}

template<typename T> void Singleton<T>::destroy()
{
  delete _instance;
  _instance = NULL;
}

template<typename T> T& Singleton<T>::instance()
{
  if (_instance == NULL) {
    _lock.lock();
    if (_instance == NULL) {
      SingletonExitHandler::instance()->registerSingletonDestroyer(&destroy);
      _instance = new T();
    }
    _lock.unlock();
  }

  return *_instance;
}

template<typename T> T* Singleton<T>::_instance = NULL;

template<typename T> Mutex Singleton<T>::_lock;

// }}}

} // namespace fsa


text:
//
//   Copyright 2013 Pixar
//
//   Licensed under the Apache License, Version 2.0 (the "Apache License")
//   with the following modification; you may not use this file except in
//   compliance with the Apache License and the following modification to it:
//   Section 6. Trademarks. is deleted and replaced with:
//
//   6. Trademarks. This License does not grant permission to use the trade
//      names, trademarks, service marks, or product names of the Licensor
//      and its affiliates, except as required to comply with Section 4(c) of
//      the License and to reproduce the content of the NOTICE file.
//
//   You may obtain a copy of the Apache License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the Apache License with the above modification is
//   distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//   KIND, either express or implied. See the Apache License for the specific
//   language governing permissions and limitations under the Apache License.
//

#include <algorithm>
#include <vector>
#include <cstring>
#include <cstdio>
#include <cassert>
#include "hud.h"
#include "font_image.h"

#if _MSC_VER
#define snprintf _snprintf
#endif

Hud::Hud() : _visible(true), _windowWidth(0), _windowHeight(0),
             _framebufferWidth(0), _framebufferHeight(0),
             _requiresRebuildStatic(true)
{
    _capturedSlider = -1;
}

Hud::~Hud()
{
}

void
Hud::Init(int width, int height, int framebufferWidth, int framebufferHeight)
{
    _windowWidth = width;
    _windowHeight = height;
    _framebufferWidth = framebufferWidth;
    _framebufferHeight = framebufferHeight;
}

int
Hud::GetWidth() const
{
    return _windowWidth;
}

int
Hud::GetHeight() const
{
    return _windowHeight;
}

void
Hud::Clear()
{
    _radioButtons.clear();
    _checkBoxes.clear();
    _sliders.clear();
    _vboSource.clear();
    _requiresRebuildStatic = true;
}

bool
Hud::KeyDown(int key)
{
    for (std::vector<RadioButton>::iterator it = _radioButtons.begin();
        it != _radioButtons.end(); ++it) {
        if (key == it->shortcut) {
            int nextLocalIndex = it->localIndex;
            if (it->sharedShortcut) {
                // find checked radio button in this group
                int maxLocalIndex = 0;
                for (std::vector<RadioButton>::iterator it2 = _radioButtons.begin();
                     it2 != _radioButtons.end(); ++it2) {

                    if (it2->group == it->group) {
                        maxLocalIndex = std::max(maxLocalIndex, it2->localIndex);
                        if (it2->checked) {
                            nextLocalIndex = it2->localIndex+1;
                        }
                    }
                }
                if (nextLocalIndex > maxLocalIndex) nextLocalIndex = 0;
            }
            for (std::vector<RadioButton>::iterator it2 = _radioButtons.begin();
                 it2 != _radioButtons.end(); ++it2) {
                if (it2->group == it->group) {
                    if (it2->localIndex == nextLocalIndex) {
                        it2->checked = true;
                        it2->callback(it2->callbackData);
                    } else {
                        it2->checked = false;
                    }
                }
            }
            _requiresRebuildStatic = true;
            return true;
        }
    }
    for (std::vector<CheckBox>::iterator it = _checkBoxes.begin();
         it != _checkBoxes.end(); ++it) {

        if (key == it->shortcut) {
            it->checked = !it->checked;
            it->callback(it->checked, it->callbackData);
            _requiresRebuildStatic = true;
            return true;
        }
    }
    for (std::vector<PullDown>::iterator it = _pulldowns.begin();
         it != _pulldowns.end(); ++it) {
        if (key==it->shortcut) {
            // cycle through selections
            ++it->selected;
            if (it->selected>=(int)it->labels.size()) {
                 it->selected=0;
            }
            it->callback(it->values[it->selected]);
            _requiresRebuildStatic = true;
            return true;
        }
    }

    return false;
}

bool
Hud::MouseClick(int x, int y)
{
    if (!IsVisible()) {
        return false;
    }

    for (std::vector<RadioButton>::iterator it = _radioButtons.begin();
        it != _radioButtons.end(); ++it) {
        if (hitTest(*it, x, y)) {
            for (std::vector<RadioButton>::iterator it2 = _radioButtons.begin();
                 it2 != _radioButtons.end(); ++it2) {

                if (it2->group == it->group && it != it2) it2->checked = false;
            }
            it->checked = true;
            it->callback(it->callbackData);
            _requiresRebuildStatic = true;
            return true;
        }
    }
    for (std::vector<CheckBox>::iterator it = _checkBoxes.begin();
        it != _checkBoxes.end(); ++it) {
        if (hitTest(*it, x, y)) {
            it->checked = !it->checked;
            it->callback(it->checked, it->callbackData);
            _requiresRebuildStatic = true;
            return true;
        }
    }
    for (std::vector<Slider>::iterator it = _sliders.begin();
         it != _sliders.end(); ++it) {
        if (hitTest(*it, x, y)) {
            int bx = 0, by = 0;
            getWindowPos(*it, &bx, &by);
            it->SetValue(((x-bx-FONT_CHAR_WIDTH/2)/float(it->w))*(it->max - it->min) + it->min);
            it->callback(it->value, it->callbackData);
            _capturedSlider = (int)(it - _sliders.begin());
            _requiresRebuildStatic = true;
            return true;
        }
    }
    for (std::vector<PullDown>::iterator it = _pulldowns.begin();
         it != _pulldowns.end(); ++it) {
        if (hitTest(*it, x, y)) {
            if (not it->open) {
                it->h = FONT_CHAR_HEIGHT;
                it->h *= (int)it->labels.size();
                it->open=true;
            } else {
                int label_width = (3+(int)it->label.size()) * FONT_CHAR_WIDTH;
                int bx = 0, by = 0;
                getWindowPos(*it, &bx, &by);
                if (x > (bx+label_width)) {
                    int sel = it->selected;
                    it->SetSelected((y-by)/FONT_CHAR_HEIGHT);
                    if (it->selected!=sel) {
                        it->callback(it->values[it->selected]);
                    }
                } else {
                    it->open=not it->open;
                }
            }
            _requiresRebuildStatic = true;
            return true;
        }
    }
    return false;
}

void
Hud::MouseMotion(int x, int /* y */)
{
    if (_capturedSlider != -1) {
        std::vector<Slider>::iterator it = _sliders.begin() + _capturedSlider;

        int bx = it->x > 0 ? it->x : _windowWidth + it->x;
        it->SetValue(((x-bx-FONT_CHAR_WIDTH/2)/float(it->w))*(it->max - it->min) + it->min);
        it->callback(it->value, it->callbackData);
        _requiresRebuildStatic = true;
    }
}

bool
Hud::MouseCapture() const
{
    return _capturedSlider != -1;
}

void
Hud::MouseRelease()
{
    _capturedSlider = -1;
}

void
Hud::AddLabel(const char *label, int x, int y)
{
    Item l;
    l.label = label;
    l.x = x;
    l.y = y;

    _labels.push_back(l);
    _requiresRebuildStatic = true;
}

void
Hud::AddCheckBox(const char *label, bool checked, int x, int y,
                 CheckBoxCallback callback, int data, int shortcut)
{
    CheckBox cb;
    cb.label = label;
    cb.checked = checked;
    cb.x = x;
    cb.y = y;
    cb.w = (int)(strlen(label)+1) * FONT_CHAR_WIDTH;
    cb.h = FONT_CHAR_HEIGHT;
    cb.callback = callback;
    cb.callbackData = data;
    cb.shortcut = shortcut;

    _checkBoxes.push_back(cb);
    _requiresRebuildStatic = true;
}

void
Hud::AddRadioButton(int group, const char *label, bool checked, int x, int y,
                    RadioButtonCallback callback, int data, int shortcut)
{
    RadioButton rb;
    rb.group = group;
    rb.label = label;
    rb.checked = checked;
    rb.x = x;
    rb.y = y;
    rb.w = (int)(strlen(label)+1) * FONT_CHAR_WIDTH;
    rb.h = FONT_CHAR_HEIGHT;
    rb.callback = callback;
    rb.callbackData = data;
    rb.shortcut = shortcut;
    rb.sharedShortcut = false;
    rb.localIndex = 0;

    for (std::vector<RadioButton>::iterator it = _radioButtons.begin();
         it != _radioButtons.end(); ++it) {
        if (it->group == group) {
            rb.localIndex = it->localIndex+1;
            if (it->shortcut == shortcut) {
                it->sharedShortcut = true;
                rb.sharedShortcut = true;
            }
        }
    }

    _radioButtons.push_back(rb);
    _requiresRebuildStatic = true;
}

void
Hud::AddSlider(const char *label, float min, float max, float value,
               int x, int y, int width, bool intStep, SliderCallback callback, int data)
{
    Slider slider;
    slider.label = label;
    slider.x = x;
    slider.y = y;
    slider.w = width * FONT_CHAR_WIDTH;
    slider.h = FONT_CHAR_HEIGHT * 2;
    slider.min = min;
    slider.max = max;
    slider.value = value;
    slider.callback = callback;
    slider.callbackData = data;
    slider.intStep = intStep;

    _sliders.push_back(slider);
    _requiresRebuildStatic = true;
}

int
Hud::AddPullDown(const char *label, int x, int y, int width,
                 PullDownCallback callback, int shortcut)
{

    PullDown pd;
    pd.label = label;
    pd.x = x;
    pd.y = y;
    pd.w = width;
    pd.h =  FONT_CHAR_HEIGHT;
    pd.open = false;
    pd.selected = 0;
    pd.callback = callback;
    pd.shortcut = shortcut;

    _pulldowns.push_back(pd);
    _requiresRebuildStatic = true;

    return (int)_pulldowns.size()-1;
}

void
Hud::AddPullDownButton(int handle, const char *label, int value, bool checked)
{
    if (handle < (int)_pulldowns.size()) {

        PullDown & pulldown = _pulldowns[handle];

        pulldown.labels.push_back(label);
        pulldown.values.push_back(value);
        if (checked) {
            pulldown.selected = (int)pulldown.labels.size()-1;
        }
    }
}

int
Hud::drawChar(std::vector<float> &vboSource,
              int x, int y, float r, float g, float b, char ch)
{
    const float w = 1.0f/FONT_TEXTURE_COLUMNS;
    const float h = 1.0f/FONT_TEXTURE_ROWS;

    float u = (ch%FONT_TEXTURE_COLUMNS)/(float)FONT_TEXTURE_COLUMNS;
    float v = (ch/FONT_TEXTURE_COLUMNS)/(float)FONT_TEXTURE_ROWS;

    vboSource.push_back(float(x));
    vboSource.push_back(float(y));
    vboSource.push_back(r);
    vboSource.push_back(g);
    vboSource.push_back(b);
    vboSource.push_back(u);
    vboSource.push_back(v);

    vboSource.push_back(float(x));
    vboSource.push_back(float(y+FONT_CHAR_HEIGHT));
    vboSource.push_back(r);
    vboSource.push_back(g);
    vboSource.push_back(b);
    vboSource.push_back(u);
    vboSource.push_back(v+h);

    vboSource.push_back(float(x+FONT_CHAR_WIDTH));
    vboSource.push_back(float(y));
    vboSource.push_back(r);
    vboSource.push_back(g);
    vboSource.push_back(b);
    vboSource.push_back(u+w);
    vboSource.push_back(v);

    vboSource.push_back(float(x+FONT_CHAR_WIDTH));
    vboSource.push_back(float(y));
    vboSource.push_back(r);
    vboSource.push_back(g);
    vboSource.push_back(b);
    vboSource.push_back(u+w);
    vboSource.push_back(v);

    vboSource.push_back(float(x));
    vboSource.push_back(float(y+FONT_CHAR_HEIGHT));
    vboSource.push_back(r);
    vboSource.push_back(g);
    vboSource.push_back(b);
    vboSource.push_back(u);
    vboSource.push_back(v+h);

    vboSource.push_back(float(x+FONT_CHAR_WIDTH));
    vboSource.push_back(float(y+FONT_CHAR_HEIGHT));
    vboSource.push_back(r);
    vboSource.push_back(g);
    vboSource.push_back(b);
    vboSource.push_back(u+w);
    vboSource.push_back(v+h);

    return x + FONT_CHAR_WIDTH;
}

int
Hud::drawString(std::vector<float> &vboSource,
                int x, int y, float r, float g, float b, const char *c)
{
    while (*c) {
        char ch = (char)((*c) & 0x7f);
        x = drawChar(vboSource, x, y, r, g, b, ch);
        c++;
    }
    return x;
}

void
Hud::DrawString(int x, int y, const char *fmt, ...)
{
    char buf[1024];
    va_list args;
    va_start(args, fmt);
    vsnprintf(buf, sizeof(buf), fmt, args);
    va_end(args);

    x = x > 0 ? x : _windowWidth + x;
    y = y > 0 ? y : _windowHeight + y;

    drawString(_vboSource, x, y, 1, 1, 1, buf);
}

void
Hud::DrawString(int x, int y, float r, float g, float b, const char *fmt, ...)
{
    char buf[1024];
    va_list args;
    va_start(args, fmt);
    vsnprintf(buf, sizeof(buf), fmt, args);
    va_end(args);

    x = x > 0 ? x : _windowWidth + x;
    y = y > 0 ? y : _windowHeight + y;

    drawString(_vboSource, x, y, r, g, b, buf);
}

void
Hud::Rebuild(int width, int height, int framebufferWidth, int framebufferHeight)
{
    _requiresRebuildStatic = false;
    _windowWidth = width;
    _windowHeight = height;
    _framebufferWidth = framebufferWidth;
    _framebufferHeight = framebufferHeight;

    _staticVboSource.clear();

    int x, y;
    // add UI elements
    for (std::vector<Item>::const_iterator it = _labels.begin();
         it != _labels.end(); ++it) {
        getWindowPos(*it, &x, &y);
        drawString(_staticVboSource, x, y, 1, 1, 1, it->label.c_str());
    }
    // draw radio buttons
    for (std::vector<RadioButton>::const_iterator it = _radioButtons.begin();
         it != _radioButtons.end(); ++it) {
        getWindowPos(*it, &x, &y);
        if (it->checked) {
            x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_RADIO_BUTTON_ON);
            drawString(_staticVboSource, x, y, 1, 1, 0, it->label.c_str());
        } else {
            x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_RADIO_BUTTON_OFF);
            drawString(_staticVboSource, x, y, .5f, .5f, .5f, it->label.c_str());
        }
    }
    // draw checkboxes
    for (std::vector<CheckBox>::const_iterator it = _checkBoxes.begin();
         it != _checkBoxes.end(); ++it) {
        getWindowPos(*it, &x, &y);
        if (it->checked) {
            x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_CHECK_BOX_ON);
            drawString(_staticVboSource, x, y, 1, 1, 0, it->label.c_str());
        } else {
            x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_CHECK_BOX_OFF);
            drawString(_staticVboSource, x, y, .5f, .5f, .5f, it->label.c_str());
        }
    }
    // draw sliders
    for (std::vector<Slider>::const_iterator it = _sliders.begin();
         it != _sliders.end(); ++it) {
        getWindowPos(*it, &x, &y);
        int sx = x;
        x = drawString(_staticVboSource, x, y, 1, 1, 1, it->label.c_str());
        char value[16];
        snprintf(value, 16, " : %.2f", it->value);
        drawString(_staticVboSource, x, y, 1, 1, 1, value);

        // new line
        y += FONT_CHAR_HEIGHT;
        x = sx;

        x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_SLIDER_LEFT);
        int nw = it->w / FONT_CHAR_WIDTH;
        for (int i = 1; i < nw; ++i) {
            x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_SLIDER_MIDDLE);
        }
        drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_SLIDER_RIGHT);
        int pos = (int)((it->value/float(it->max-it->min))*it->w);
        drawChar(_staticVboSource, sx+pos, y, 1, 1, 0, FONT_SLIDER_CURSOR);
    }
    // draw pulldowns
    for (std::vector<PullDown>::const_iterator it = _pulldowns.begin();
         it != _pulldowns.end(); ++it) {
        getWindowPos(*it, &x, &y);

        x = drawString(_staticVboSource, x, y, .5f, .5f, .5f, it->label.c_str());
        x += FONT_CHAR_WIDTH;

        if (it->open) {
            x = drawChar(_staticVboSource, x, y, 1, 1, 0, FONT_ARROW_DOWN);
            x += FONT_CHAR_WIDTH;
            for (int i=0; i<(int)it->labels.size(); ++i, y+=FONT_CHAR_HEIGHT) {
                if (i==it->selected) {
                    drawString(_staticVboSource, x, y, 1, 1, 0, it->labels[i]);
                } else {
                    drawString(_staticVboSource, x, y, 0.5f, 0.5f, 0.5f, it->labels[i]);
                }
            }
        } else {
            x = drawChar(_staticVboSource, x, y, .5f, .5f, .5f, FONT_ARROW_RIGHT);
            x += FONT_CHAR_WIDTH;
            drawString(_staticVboSource, x, y, 1, 1, 0, it->labels[it->selected]);
        }
    }

    drawString(_staticVboSource, _windowWidth-80, _windowHeight-48, .5, .5, .5,
               "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f");
    drawString(_staticVboSource, _windowWidth-80, _windowHeight-32, .5, .5, .5,
               "\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f");
}

bool
Hud::Flush()
{
    if (!_visible) {
        _vboSource.clear();
        return false;
    }

    if (_requiresRebuildStatic)
        this->Rebuild(_windowWidth, _windowHeight, _framebufferWidth, _framebufferHeight);

    return true;
}

bool
Hud::IsVisible() const
{
    return _visible;
}

void
Hud::SetVisible(bool visible)
{
    _visible = visible;
}

std::vector<float> &
Hud::getVboSource()
{
    return _vboSource;
}

std::vector<float> &
Hud::getStaticVboSource()
{
    return _staticVboSource;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/semi_light_transparent">
    <item android:drawable="@color/grey_lighter"/>
</ripple>


text:
package org.jboss.pnc.termdbuilddriver;

import org.jboss.pnc.enums.BuildStatus;
import org.jboss.pnc.spi.builddriver.BuildDriverResult;
import org.jboss.pnc.spi.builddriver.CompletedBuild;
import org.jboss.pnc.spi.builddriver.exception.BuildDriverException;
import org.jboss.pnc.spi.environment.RunningEnvironment;

import java.util.Optional;

/**
 * @author Matej Lazar
 */
public class DefaultCompletedBuild implements CompletedBuild {

    private RunningEnvironment runningEnvironment;
    private BuildStatus buildStatus;
    private Optional<String> outputChecksum;

    private String buildLog;

    public DefaultCompletedBuild(
            RunningEnvironment runningEnvironment,
            BuildStatus buildStatus,
            Optional<String> outputChecksum,
            String buildLog) {
        this.runningEnvironment = runningEnvironment;
        this.buildStatus = buildStatus;
        this.outputChecksum = outputChecksum;
        this.buildLog = buildLog;
    }

    @Override
    public BuildDriverResult getBuildResult() throws BuildDriverException {
        return new DefaultBuildDriverResult(buildLog, buildStatus, outputChecksum);
    }

    @Override
    public RunningEnvironment getRunningEnvironment() {
        return runningEnvironment;
    }
}


text:
package shared.responses.groups.members

import shared.responses.PaginatedResponse

case class MemberAssociatedToGroupInfo(
  user: String,
  joined: String
)
case class MemberGroupResponse(
  members: List[MemberAssociatedToGroupInfo],
  offset: Int,
  limit: Int,
  total: Int
) extends PaginatedResponse


text:
  <button class="open_sidebar j-open_sidebar"></button>

 {{chatName}}

      person_add

      delete

    <ng-container *ngFor="let data of messages">

          {{data[0]}}

      <app-message *ngFor="let message of data[1];" [message]="message" class="message__wrap" id="{{message._id}}" >
      </app-message>
    </ng-container>

  <form (ngSubmit)="onSubmit()" autocomplete="off" class="send_message" name="send_message">
    <textarea #field autocapitalize="off" (keydown)="onKeydown($event)"
              (keyup.shift)="shiftDown = false"
              autocomplete="off" autocorrect="off" autofocus
              class="message_feald" [(ngModel)]="messageField" name="message_feald" placeholder="Type a message"></textarea>

        <ng-container *ngFor="let data of attachments">

        </ng-container>

        attachment
        <input accept="image/*" class="attach_input" id="attach_btn" (change)="prepareToUpload($event)" name="attach_file" type="file"/>

      <button class="send_btn">send</button>

  </form>


text:
/* channels.js
 *
 * Multiplexed JSON messages.
 *
 * A jsonSocket that supports multiplexing into multiple channels.
 * Applications may associate handlers with both channels and the
 * underlying socket.
 *
 * Requires: SockJS jsonSocket.js
 */

var channels = (function () {
"use strict";

function channel(name, server) {
    var handlers = {};

    function handleMessage(msg) {
	if (handlers[msg.type]) {
	    handlers[msg.type](msg);
	}
    }

    function sendMessage(msg) {
	server.send({type: "send",
		     name: name,
		     content: msg});
    }

    function setMsgHandler(msg, handler) {
	handlers[msg] = handler;
    }

    function leave() {
	server.leave(name);
    }

    return {
	leave: leave,
	handle: handleMessage,
	send: sendMessage,
	setMsgHandler: setMsgHandler
    };
}

function socket(url) {
    var sock = jsonSocket.socket(url);
    var channels = {};

    function handleChannelMessage(message) {
	if (channels[message.name]) {
	    channels[message.name].handle(message.content);
	}
    }

    sock.join = function (name, handler) {
	if (!channels[name]) {
	    sock.send({type: "join",
		       name: name});
	    channels[name] = channel(name, sock);
	} else {
	    console.log("channels.socket: already joined to " + name);
	}

	return channels[name];
    };

    sock.leave = function (name) {
	sock.send({type: "leave",
		   name: name});
	delete channels[name];
    };

    sock.setMsgHandler("channel-message", handleChannelMessage);

    return sock;
}

return {
    socket: socket
};

})();


text:
template<class It>
inline spdlog::async_logger::async_logger(const std::string& logger_name,
        const It& begin,
        const It& end,
        size_t queue_size,
        const  async_overflow_policy overflow_policy,
        const std::function<void()>& worker_warmup_cb,
        const std::chrono::milliseconds& flush_interval_ms) :
    logger(logger_name, begin, end),
    _async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms))
{
}

inline spdlog::async_logger::async_logger(const std::string& logger_name,
        sinks_init_list sinks,
        size_t queue_size,
        const  async_overflow_policy overflow_policy,
        const std::function<void()>& worker_warmup_cb,
        const std::chrono::milliseconds& flush_interval_ms) :
    async_logger(logger_name, sinks.begin(), sinks.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms) {}

inline spdlog::async_logger::async_logger(const std::string& logger_name,
        sink_ptr single_sink,
        size_t queue_size,
        const  async_overflow_policy overflow_policy,
        const std::function<void()>& worker_warmup_cb,
        const std::chrono::milliseconds& flush_interval_ms) :
    async_logger(logger_name,
{
    single_sink
}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms) {}

inline void spdlog::async_logger::flush()
{

    _async_log_helper->flush();
}

inline void spdlog::async_logger::_set_formatter(spdlog::formatter_ptr msg_formatter)
{
    _formatter = msg_formatter;
    _async_log_helper->set_formatter(_formatter);
}

inline void spdlog::async_logger::_set_pattern(const std::string& pattern)
{
    _formatter = std::make_shared<pattern_formatter>(pattern);
    _async_log_helper->set_formatter(_formatter);
}

inline void spdlog::async_logger::_log_msg(details::log_msg& msg)
{
    _async_log_helper->log(msg);
}


text:
<?php

namespace Falc\Flysystem\Plugin\Symlink\Sftp;

use League\Flysystem\FilesystemInterface;
use League\Flysystem\PluginInterface;

/**
 * Sftp IsSymlink plugin.
 *
 * Implements a isSymlink($filename) method for Filesystem instances using SftpAdapter.
 */
class IsSymlink implements PluginInterface
{
    /**
     * FilesystemInterface instance.
     *
     * @var FilesystemInterface
     */
    protected $filesystem;

    /**
     * Sets the Filesystem instance.
     *
     * @param FilesystemInterface $filesystem
     */
    public function setFilesystem(FilesystemInterface $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * Gets the method name.
     *
     * @return string
     */
    public function getMethod()
    {
        return 'isSymlink';
    }

    /**
     * Method logic.
     *
     * Tells whether the specified $filename exists and is a symlink.
     *
     * @param   string  $filename   Filename.
     * @return  boolean             True if $filename is a symlink. Else false.
     */
    public function handle($filename)
    {
        $filename = $this->filesystem->getAdapter()->getRoot().ltrim($filename, '/');

        $connection = $this->filesystem->getAdapter()->getConnection();
        return $connection->is_link($filename);
    }
}


text:
#include <aws/elasticache/model/TestFailoverResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <utility>

using namespace Aws::ElastiCache::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;

TestFailoverResult::TestFailoverResult()
{
}

TestFailoverResult::TestFailoverResult(const AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

TestFailoverResult& TestFailoverResult::operator =(const AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (rootNode.GetName() != "TestFailoverResult")
  {
    resultNode = rootNode.FirstChild("TestFailoverResult");
  }

  if(!resultNode.IsNull())
  {
    XmlNode replicationGroupNode = resultNode.FirstChild("ReplicationGroup");
    if(!replicationGroupNode.IsNull())
    {
      m_replicationGroup = replicationGroupNode;
    }
  }

  XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
  m_responseMetadata = responseMetadataNode;
  AWS_LOGSTREAM_DEBUG("Aws::ElastiCache::Model::TestFailoverResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );

  return *this;
}


text:
#ifndef MBED_DEVICE_H
#define MBED_DEVICE_H

//MODTRONIX BEGIN - mbed Defines //////////////////////////////////////////////
//Provide place for adding mbed defines. Alternative to adding them in IDE project properties.
//Add project defines here, or add them to your toolchain compiler preprocessor

//MODTRONIX END ///////////////////////////////////////////////////////////////

#define DEVICE_PORTIN           1
#define DEVICE_PORTOUT          1
#define DEVICE_PORTINOUT        1

#define DEVICE_INTERRUPTIN      1

#define DEVICE_ANALOGIN         1
#define DEVICE_ANALOGOUT        1

#define DEVICE_SERIAL           1

#define DEVICE_I2C              1
#define DEVICE_I2CSLAVE         1

#define DEVICE_SPI              1
#define DEVICE_SPISLAVE         1

#define DEVICE_RTC              1

#define DEVICE_PWMOUT           1

#define DEVICE_SLEEP            1

//=======================================

#define DEVICE_SEMIHOST         0
#define DEVICE_LOCALFILESYSTEM  0
#define DEVICE_ID_LENGTH       24

#define DEVICE_DEBUG_AWARENESS  0

#define DEVICE_STDIO_MESSAGES   1

#define DEVICE_ERROR_RED        0

#include "objects.h"

#endif


text:
import logging
import re
import datetime
from typing import List

from django.db import transaction

import tkapi
from tkapi.document import Document as TKDocument
from tkapi.document import VerslagAlgemeenOverleg

from document.models import CommissieDocument
from document.models import Dossier
from document.models import Kamerstuk
from parliament.models import Commissie

from openkamer.document import DocumentFactory

logger = logging.getLogger(__name__)

def create_verslagen_algemeen_overleg(year, max_n=None, skip_if_exists=False):
    logger.info('BEGIN: {}'.format(year))
    year = int(year)
    begin_datetime = datetime.datetime(year=year, month=1, day=1)
    end_datetime = datetime.datetime(year=year+1, month=1, day=1)
    tk_verslagen = get_tk_verlag_algemeen_overleg(begin_datetime, end_datetime)
    counter = 1
    for tk_verslag in tk_verslagen:
        try:
            create_verslag_ao(tk_verslag, skip_if_exists=skip_if_exists)
        except Exception as error:
            logger.error('error for kamervraag id: {}'.format(tk_verslag.document_url))
            logger.exception(error)
        if max_n and counter >= max_n:
            return
        counter += 1
    logger.info('END: {}'.format(year))

def create_verslag_ao(tk_verslag, skip_if_exists=False):
    dossier = tk_verslag.dossiers[0]
    dossier_id = Dossier.create_dossier_id(dossier.nummer, dossier.toevoeging)
    name = tk_verslag.voortouwcommissie_namen[0] if tk_verslag.voortouwcommissie_namen else ''
    logger.info('commissie name: {}'.format(name))
    name_short = Commissie.create_short_name(name)
    slug = Commissie.create_slug(name_short)
    commissie, created = Commissie.objects.get_or_create(name=name, name_short=name_short, slug=slug)
    commissie_document = create_verslag(
        tk_document=tk_verslag,
        overheidnl_document_id=tk_verslag.document_url.replace('https://zoek.officielebekendmakingen.nl/', ''),
        dossier_id=dossier_id,
        kamerstuk_nr=tk_verslag.volgnummer,
        commissie=commissie,
        skip_if_exists=skip_if_exists,
    )
    return commissie_document

@transaction.atomic
def create_verslag(tk_document: TKDocument, overheidnl_document_id, dossier_id, kamerstuk_nr, commissie, skip_if_exists=False):
    if skip_if_exists and Kamerstuk.objects.filter(document__document_id=overheidnl_document_id).exists():
        return
    document_factory = DocumentFactory()
    document = document_factory.create_document(tk_document, overheidnl_document_id, dossier_id=dossier_id)
    document.save()
    Kamerstuk.objects.filter(document=document).delete()
    kamerstuk = Kamerstuk.objects.create(
        document=document,
        id_main=dossier_id,
        id_sub=kamerstuk_nr,
        type_short='Verslag',
        type_long=tk_document.soort.value
    )
    CommissieDocument.objects.filter(document=document).delete()
    verslag = CommissieDocument.objects.create(
        document=document,
        kamerstuk=kamerstuk,
        commissie=commissie
    )
    return verslag

def get_tk_verlag_algemeen_overleg(begin_datetime, end_datetime) -> List[VerslagAlgemeenOverleg]:
    pd_filter = TKDocument.create_filter()
    pd_filter.filter_date_range(begin_datetime, end_datetime)
    tk_verslagen = tkapi.TKApi.get_verslagen_van_algemeen_overleg(pd_filter)
    return tk_verslagen


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Classification.Classifiers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers

    Friend Class OperatorOverloadSyntaxClassifier
        Inherits AbstractSyntaxClassifier

        Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(
            GetType(BinaryExpressionSyntax),
            GetType(UnaryExpressionSyntax))

        Public Overrides Sub AddClassifications(
            syntax As SyntaxNode,
            semanticModel As SemanticModel,
options As ClassificationOptions,
            result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken)

            Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken)
            If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso
                DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then

                If TypeOf syntax Is BinaryExpressionSyntax Then
                    result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
                ElseIf TypeOf syntax Is UnaryExpressionSyntax Then
                    result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
                End If
            End If
        End Sub
    End Class
End Namespace