text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CreativePlaceholder</title>
<meta name="date" content="2013-12-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.api.ads.dfp.v201302

Class CreativePlaceholder

java.lang.Object

com.google.api.ads.dfp.v201302.CreativePlaceholder

All Implemented Interfaces:

java.io.Serializable

public class CreativePlaceholder
extends java.lang.Object
implements java.io.Serializable

A CreativePlaceholder describes a slot that a creative
 is expected to
             fill. This is used primarily to help in forecasting, and
 also to validate
             that the correct creatives are associated with the line
 item. A
             CreativePlaceholder must contain a size, and it
 can optionally
             contain companions. Companions are only valid if the line
 item's environment
             type is EnvironmentType.VIDEO_PLAYER.

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

CreativePlaceholder()

CreativePlaceholder(Size size,
                   CreativePlaceholder[] companions,
                   AppliedLabel[] appliedLabels,
                   AppliedLabel[] effectiveAppliedLabels,
                   java.lang.Long id,
                   java.lang.Integer expectedCreativeCount,
                   CreativeSizeType creativeSizeType)

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

AppliedLabel[]
getAppliedLabels()

Gets the appliedLabels value for this CreativePlaceholder.

AppliedLabel
getAppliedLabels(int i)

CreativePlaceholder[]
getCompanions()

Gets the companions value for this CreativePlaceholder.

CreativePlaceholder
getCompanions(int i)

CreativeSizeType
getCreativeSizeType()

Gets the creativeSizeType value for this CreativePlaceholder.

static org.apache.axis.encoding.Deserializer
getDeserializer(java.lang.String mechType,
               java.lang.Class _javaType,
               javax.xml.namespace.QName _xmlType)

Get Custom Deserializer

AppliedLabel[]
getEffectiveAppliedLabels()

Gets the effectiveAppliedLabels value for this CreativePlaceholder.

AppliedLabel
getEffectiveAppliedLabels(int i)

java.lang.Integer
getExpectedCreativeCount()

Gets the expectedCreativeCount value for this CreativePlaceholder.

java.lang.Long
getId()

Gets the id value for this CreativePlaceholder.

static org.apache.axis.encoding.Serializer
getSerializer(java.lang.String mechType,
             java.lang.Class _javaType,
             javax.xml.namespace.QName _xmlType)

Get Custom Serializer

Size
getSize()

Gets the size value for this CreativePlaceholder.

static org.apache.axis.description.TypeDesc
getTypeDesc()

Return type metadata object

int
hashCode()

void
setAppliedLabels(AppliedLabel[] appliedLabels)

Sets the appliedLabels value for this CreativePlaceholder.

void
setAppliedLabels(int i,
                AppliedLabel _value)

void
setCompanions(CreativePlaceholder[] companions)

Sets the companions value for this CreativePlaceholder.

void
setCompanions(int i,
             CreativePlaceholder _value)

void
setCreativeSizeType(CreativeSizeType creativeSizeType)

Sets the creativeSizeType value for this CreativePlaceholder.

void
setEffectiveAppliedLabels(AppliedLabel[] effectiveAppliedLabels)

Sets the effectiveAppliedLabels value for this CreativePlaceholder.

void
setEffectiveAppliedLabels(int i,
                         AppliedLabel _value)

void
setExpectedCreativeCount(java.lang.Integer expectedCreativeCount)

Sets the expectedCreativeCount value for this CreativePlaceholder.

void
setId(java.lang.Long id)

Sets the id value for this CreativePlaceholder.

void
setSize(Size size)

Sets the size value for this CreativePlaceholder.

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CreativePlaceholder

public CreativePlaceholder()

CreativePlaceholder

public CreativePlaceholder(Size size,
                   CreativePlaceholder[] companions,
                   AppliedLabel[] appliedLabels,
                   AppliedLabel[] effectiveAppliedLabels,
                   java.lang.Long id,
                   java.lang.Integer expectedCreativeCount,
                   CreativeSizeType creativeSizeType)

Method Detail

getSize

public Size getSize()

Gets the size value for this CreativePlaceholder.

Returns:

size   * The dimensions that the creative is expected to have. This
 attribute is
                 required.

setSize

public void setSize(Size size)

Sets the size value for this CreativePlaceholder.

Parameters:

size - * The dimensions that the creative is expected to have. This
 attribute is
                 required.

getCompanions

public CreativePlaceholder[] getCompanions()

Gets the companions value for this CreativePlaceholder.

Returns:

companions   * The companions that the creative is expected to have. This
 attribute can
                 only be set if the line item it belongs to has an
                 environmentType of EnvironmentType.VIDEO_PLAYER.

setCompanions

public void setCompanions(CreativePlaceholder[] companions)

Sets the companions value for this CreativePlaceholder.

Parameters:

companions - * The companions that the creative is expected to have. This
 attribute can
                 only be set if the line item it belongs to has an
                 environmentType of EnvironmentType.VIDEO_PLAYER.

getCompanions

public CreativePlaceholder getCompanions(int i)

setCompanions

public void setCompanions(int i,
                 CreativePlaceholder _value)

getAppliedLabels

public AppliedLabel[] getAppliedLabels()

Gets the appliedLabels value for this CreativePlaceholder.

Returns:

appliedLabels   * The set of label frequency caps applied directly to this creative
 placeholder.

setAppliedLabels

public void setAppliedLabels(AppliedLabel[] appliedLabels)

Sets the appliedLabels value for this CreativePlaceholder.

Parameters:

appliedLabels - * The set of label frequency caps applied directly to this creative
 placeholder.

getAppliedLabels

public AppliedLabel getAppliedLabels(int i)

setAppliedLabels

public void setAppliedLabels(int i,
                    AppliedLabel _value)

getEffectiveAppliedLabels

public AppliedLabel[] getEffectiveAppliedLabels()

Gets the effectiveAppliedLabels value for this CreativePlaceholder.

Returns:

effectiveAppliedLabels   * Contains the set of labels applied directly to this creative
 placeholder
                 as well as those inherited from the creative template
 from which this
                 creative placeholder was instantiated.  This field
 is readonly and is
                 assigned by Google.

setEffectiveAppliedLabels

public void setEffectiveAppliedLabels(AppliedLabel[] effectiveAppliedLabels)

Sets the effectiveAppliedLabels value for this CreativePlaceholder.

Parameters:

effectiveAppliedLabels - * Contains the set of labels applied directly to this creative
 placeholder
                 as well as those inherited from the creative template
 from which this
                 creative placeholder was instantiated.  This field
 is readonly and is
                 assigned by Google.

getEffectiveAppliedLabels

public AppliedLabel getEffectiveAppliedLabels(int i)

setEffectiveAppliedLabels

public void setEffectiveAppliedLabels(int i,
                             AppliedLabel _value)

getId

public java.lang.Long getId()

Gets the id value for this CreativePlaceholder.

Returns:

id   * The ID of this placeholder. This field is generated by the
 server and is read-only.

setId

public void setId(java.lang.Long id)

Sets the id value for this CreativePlaceholder.

Parameters:

id - * The ID of this placeholder. This field is generated by the
 server and is read-only.

getExpectedCreativeCount

public java.lang.Integer getExpectedCreativeCount()

Gets the expectedCreativeCount value for this CreativePlaceholder.

Returns:

expectedCreativeCount   * Expected number of creatives that will be uploaded corresponding
 to this
                 creative placeholder.  This estimate is used to improve
 the accuracy of
                 forecasting; for example, if label frequency capping
 limits the number of
                 times a creative may be served.

setExpectedCreativeCount

public void setExpectedCreativeCount(java.lang.Integer expectedCreativeCount)

Sets the expectedCreativeCount value for this CreativePlaceholder.

Parameters:

expectedCreativeCount - * Expected number of creatives that will be uploaded corresponding
 to this
                 creative placeholder.  This estimate is used to improve
 the accuracy of
                 forecasting; for example, if label frequency capping
 limits the number of
                 times a creative may be served.

getCreativeSizeType

public CreativeSizeType getCreativeSizeType()

Gets the creativeSizeType value for this CreativePlaceholder.

Returns:

creativeSizeType   * Describes the types of sizes a creative can be. By default,
 the creative's size
                 is CreativeSizeType.PIXEL, which is a dimension
 based size (width-height pair).

setCreativeSizeType

public void setCreativeSizeType(CreativeSizeType creativeSizeType)

Sets the creativeSizeType value for this CreativePlaceholder.

Parameters:

creativeSizeType - * Describes the types of sizes a creative can be. By default,
 the creative's size
                 is CreativeSizeType.PIXEL, which is a dimension
 based size (width-height pair).

equals

public boolean equals(java.lang.Object obj)

Overrides:

equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

getTypeDesc

public static org.apache.axis.description.TypeDesc getTypeDesc()

Return type metadata object

getSerializer

public static org.apache.axis.encoding.Serializer getSerializer(java.lang.String mechType,
                                                java.lang.Class _javaType,
                                                javax.xml.namespace.QName _xmlType)

Get Custom Serializer

getDeserializer

public static org.apache.axis.encoding.Deserializer getDeserializer(java.lang.String mechType,
                                                    java.lang.Class _javaType,
                                                    javax.xml.namespace.QName _xmlType)

Get Custom Deserializer

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
CLI
===
.. automodule:: subliminal.cli

redpajama_set_name: RedPajamaGithub


text:
import { Web3Shim } from "../../shim";
import {
  InterfaceAdapter,
  EvmBlockType,
  Provider,
  Transaction
} from "../types";

export interface Web3InterfaceAdapterOptions {
  provider?: Provider;
  networkType?: string;
}

export class Web3InterfaceAdapter implements InterfaceAdapter {
  public web3: Web3Shim;

  constructor({ provider, networkType }: Web3InterfaceAdapterOptions = {}) {
    this.web3 = new Web3Shim({ provider, networkType });
  }

  public getNetworkId() {
    return this.web3.eth.net.getId();
  }

  public getBlock(block: EvmBlockType) {
    return this.web3.eth.getBlock(block);
  }

  public getTransaction(tx: string) {
    return this.web3.eth.getTransaction(tx);
  }

  public getTransactionReceipt(tx: string) {
    return this.web3.eth.getTransactionReceipt(tx);
  }

  public getBalance(address: string) {
    return this.web3.eth.getBalance(address);
  }

  public getCode(address: string) {
    return this.web3.eth.getCode(address);
  }

  public getAccounts() {
    return this.web3.eth.getAccounts();
  }

  public estimateGas(transactionConfig: Transaction) {
    return this.web3.eth.estimateGas(transactionConfig);
  }

  public getBlockNumber() {
    return this.web3.eth.getBlockNumber();
  }
}


text:
FROM node:6.0
EXPOSE 8083
COPY . /places_service_app/
WORKDIR /places_service_app
CMD node places_service.js


text:
"""
Offset Codebook (OCB) mode.

OCB is Authenticated Encryption with Associated Data (AEAD) cipher mode
designed by Prof. Phillip Rogaway and specified in `RFC7253`_.

The algorithm provides both authenticity and privacy, it is very efficient,
it uses only one key and it can be used in online mode (so that encryption
or decryption can start before the end of the message is available).

This module implements the third and last variant of OCB (OCB3) and it only
works in combination with a 128-bit block symmetric cipher, like AES.

OCB is patented in US but `free licenses`_ exist for software implementations
meant for non-military purposes.

Example:
    >>> from Crypto.Cipher import AES
    >>> from Crypto.Random import get_random_bytes
    >>>
    >>> key = get_random_bytes(32)
    >>> cipher = AES.new(key, AES.MODE_OCB)
    >>> plaintext = b"Attack at dawn"
    >>> ciphertext, mac = cipher.encrypt_and_digest(plaintext)
    >>> # Deliver cipher.nonce, ciphertext and mac
    ...
    >>> cipher = AES.new(key, AES.MODE_OCB, nonce=nonce)
    >>> try:
    >>>     plaintext = cipher.decrypt_and_verify(ciphertext, mac)
    >>> except ValueError:
    >>>     print "Invalid message"
    >>> else:
    >>>     print plaintext

:undocumented: __package__

.. _RFC7253: http://www.rfc-editor.org/info/rfc7253
.. _free licenses: http://web.cs.ucdavis.edu/~rogaway/ocb/license.htm
"""

from Crypto.Util.py3compat import b, bord, bchr, unhexlify
from Crypto.Util.number import long_to_bytes, bytes_to_long
from Crypto.Util.strxor import strxor

from Crypto.Hash import BLAKE2s
from Crypto.Random import get_random_bytes

from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
                                  create_string_buffer, get_raw_buffer,
                                  SmartPointer, c_size_t, expect_byte_string,
                                  )

_raw_ocb_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ocb", """
                                    int OCB_start_operation(void *cipher,
                                        const uint8_t *offset_0,
                                        size_t offset_0_len,
                                        void **pState);
                                    int OCB_encrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_decrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_update(void *state,
                                        const uint8_t *in,
                                        size_t data_len);
                                    int OCB_digest(void *state,
                                        uint8_t *tag,
                                        size_t tag_len);
                                    int OCB_stop_operation(void *state);
                                    """)

class OcbMode(object):
    """Offset Codebook (OCB) mode.

    :undocumented: __init__
    """

    def __init__(self, factory, nonce, mac_len, cipher_params):

        if factory.block_size != 16:
            raise ValueError("OCB mode is only available for ciphers"
                             " that operate on 128 bits blocks")

        self.block_size = 16
        """The block size of the underlying cipher, in bytes."""

        self.nonce = nonce
        """Nonce used for this session."""
        if len(nonce) not in range(1, 16):
            raise ValueError("Nonce must be at most 15 bytes long")

        self._mac_len = mac_len
        if not 8 <= mac_len <= 16:
            raise ValueError("MAC tag must be between 8 and 16 bytes long")

        # Cache for MAC tag
        self._mac_tag = None

        # Cache for unaligned associated data
        self._cache_A = b("")

        # Cache for unaligned ciphertext/plaintext
        self._cache_P = b("")

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt,
                      self.digest, self.verify]

        # Compute Offset_0
        params_without_key = dict(cipher_params)
        key = params_without_key.pop("key")
        nonce = (bchr(self._mac_len << 4 & 0xFF) +
                 bchr(0) * (14 - len(self.nonce)) +
                 bchr(1) +
                 self.nonce)
        bottom = bord(nonce[15]) & 0x3F   # 6 bits, 0..63
        ktop = factory.new(key, factory.MODE_ECB, **params_without_key)\
                      .encrypt(nonce[:15] + bchr(bord(nonce[15]) & 0xC0))
        stretch = ktop + strxor(ktop[:8], ktop[1:9])    # 192 bits
        offset_0 = long_to_bytes(bytes_to_long(stretch) >>
                                 (64 - bottom), 24)[8:]

        # Create low-level cipher instance
        raw_cipher = factory._create_base_cipher(cipher_params)
        if cipher_params:
            raise TypeError("Unknown keywords: " + str(cipher_params))

        self._state = VoidPointer()
        result = _raw_ocb_lib.OCB_start_operation(raw_cipher.get(),
                                                  offset_0,
                                                  c_size_t(len(offset_0)),
                                                  self._state.address_of())
        if result:
            raise ValueError("Error %d while instantiating the OCB mode"
                             % result)

        # Ensure that object disposal of this Python object will (eventually)
        # free the memory allocated by the raw library for the cipher mode
        self._state = SmartPointer(self._state.get(),
                                   _raw_ocb_lib.OCB_stop_operation)

        # Memory allocated for the underlying block cipher is now owed
        # by the cipher mode
        raw_cipher.release()

    def _update(self, assoc_data, assoc_data_len):
        expect_byte_string(assoc_data)
        result = _raw_ocb_lib.OCB_update(self._state.get(),
                                         assoc_data,
                                         c_size_t(assoc_data_len))
        if result:
            raise ValueError("Error %d while MAC-ing in OCB mode" % result)

    def update(self, assoc_data):
        """Process the associated data.

        If there is any associated data, the caller has to invoke
        this method one or more times, before using
        ``decrypt`` or ``encrypt``.

        By *associated data* it is meant any data (e.g. packet headers) that
        will not be encrypted and will be transmitted in the clear.
        However, the receiver shall still able to detect modifications.

        If there is no associated data, this method must not be called.

        The caller may split associated data in segments of any size, and
        invoke this method multiple times, each time with the next segment.

        :Parameters:
          assoc_data : byte string
            A piece of associated data.
        """

        if self.update not in self._next:
            raise TypeError("update() can only be called"
                            " immediately after initialization")

        self._next = [self.encrypt, self.decrypt, self.digest,
                      self.verify, self.update]

        if len(self._cache_A) > 0:
            filler = min(16 - len(self._cache_A), len(assoc_data))
            self._cache_A += assoc_data[:filler]
            assoc_data = assoc_data[filler:]

            if len(self._cache_A) < 16:
                return self

            # Clear the cache, and proceeding with any other aligned data
            self._cache_A, seg = b(""), self._cache_A
            self.update(seg)

        update_len = len(assoc_data) // 16 * 16
        self._cache_A = assoc_data[update_len:]
        self._update(assoc_data, update_len)
        return self

    def _transcrypt_aligned(self, in_data, in_data_len,
                            trans_func, trans_desc):

        out_data = create_string_buffer(in_data_len)
        result = trans_func(self._state.get(),
                            in_data,
                            out_data,
                            c_size_t(in_data_len))
        if result:
            raise ValueError("Error %d while %sing in OCB mode"
                             % (result, trans_desc))
        return get_raw_buffer(out_data)

    def _transcrypt(self, in_data, trans_func, trans_desc):
        # Last piece to encrypt/decrypt
        if in_data is None:
            out_data = self._transcrypt_aligned(self._cache_P,
                                                len(self._cache_P),
                                                trans_func,
                                                trans_desc)
            self._cache_P = b("")
            return out_data

        # Try to fill up the cache, if it already contains something
        expect_byte_string(in_data)
        prefix = b("")
        if len(self._cache_P) > 0:
            filler = min(16 - len(self._cache_P), len(in_data))
            self._cache_P += in_data[:filler]
            in_data = in_data[filler:]

            if len(self._cache_P) < 16:
                # We could not manage to fill the cache, so there is certainly
                # no output yet.
                return b("")

            # Clear the cache, and proceeding with any other aligned data
            prefix = self._transcrypt_aligned(self._cache_P,
                                              len(self._cache_P),
                                              trans_func,
                                              trans_desc)
            self._cache_P = b("")

        # Process data in multiples of the block size
        trans_len = len(in_data) // 16 * 16
        result = self._transcrypt_aligned(in_data,
                                          trans_len,
                                          trans_func,
                                          trans_desc)
        if prefix:
            result = prefix + result

        # Left-over
        self._cache_P = in_data[trans_len:]

        return result

    def encrypt(self, plaintext=None):
        """Encrypt the next piece of plaintext.

        After the entire plaintext has been passed (but before `digest`),
        you **must** call this method one last time with no arguments to collect
        the final piece of ciphertext.

        If possible, use the method `encrypt_and_digest` instead.

        :Parameters:
          plaintext : byte string
            The next piece of data to encrypt or ``None`` to signify
            that encryption has finished and that any remaining ciphertext
            has to be produced.
        :Return:
            the ciphertext, as a byte string.
            Its length may not match the length of the *plaintext*.
        """

        if self.encrypt not in self._next:
            raise TypeError("encrypt() can only be called after"
                            " initialization or an update()")

        if plaintext is None:
            self._next = [self.digest]
        else:
            self._next = [self.encrypt]
        return self._transcrypt(plaintext, _raw_ocb_lib.OCB_encrypt, "encrypt")

    def decrypt(self, ciphertext=None):
        """Decrypt the next piece of ciphertext.

        After the entire ciphertext has been passed (but before `verify`),
        you **must** call this method one last time with no arguments to collect
        the remaining piece of plaintext.

        If possible, use the method `decrypt_and_verify` instead.

        :Parameters:
          ciphertext : byte string
            The next piece of data to decrypt or ``None`` to signify
            that decryption has finished and that any remaining plaintext
            has to be produced.
        :Return:
            the plaintext, as a byte string.
            Its length may not match the length of the *ciphertext*.
        """

        if self.decrypt not in self._next:
            raise TypeError("decrypt() can only be called after"
                            " initialization or an update()")

        if ciphertext is None:
            self._next = [self.verify]
        else:
            self._next = [self.decrypt]
        return self._transcrypt(ciphertext,
                                _raw_ocb_lib.OCB_decrypt,
                                "decrypt")

    def _compute_mac_tag(self):

        if self._mac_tag is not None:
            return

        if self._cache_A:
            self._update(self._cache_A, len(self._cache_A))
            self._cache_A = b("")

        mac_tag = create_string_buffer(16)
        result = _raw_ocb_lib.OCB_digest(self._state.get(),
                                         mac_tag,
                                         c_size_t(len(mac_tag))
                                         )
        if result:
            raise ValueError("Error %d while computing digest in OCB mode"
                             % result)
        self._mac_tag = get_raw_buffer(mac_tag)[:self._mac_len]

    def digest(self):
        """Compute the *binary* MAC tag.

        Call this method after the final `encrypt` (the one with no arguments)
        to obtain the MAC tag.

        The MAC tag is needed by the receiver to determine authenticity
        of the message.

        :Return: the MAC, as a byte string.
        """

        if self.digest not in self._next:
            raise TypeError("digest() cannot be called now for this cipher")

        assert(len(self._cache_P) == 0)

        self._next = [self.digest]

        if self._mac_tag is None:
            self._compute_mac_tag()

        return self._mac_tag

    def hexdigest(self):
        """Compute the *printable* MAC tag.

        This method is like `digest`.

        :Return: the MAC, as a hexadecimal string.
        """
        return "".join(["%02x" % bord(x) for x in self.digest()])

    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        Call this method after the final `decrypt` (the one with no arguments)
        to check if the message is authentic and valid.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called now for this cipher")

        assert(len(self._cache_P) == 0)

        self._next = [self.verify]

        if self._mac_tag is None:
            self._compute_mac_tag()

        secret = get_random_bytes(16)
        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")

    def hexverify(self, hex_mac_tag):
        """Validate the *printable* MAC tag.

        This method is like `verify`.

        :Parameters:
          hex_mac_tag : string
            This is the *printable* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        self.verify(unhexlify(hex_mac_tag))

    def encrypt_and_digest(self, plaintext):
        """Encrypt the message and create the MAC tag in one step.

        :Parameters:
          plaintext : byte string
            The entire message to encrypt.
        :Return:
            a tuple with two byte strings:

            - the encrypted data
            - the MAC
        """

        return self.encrypt(plaintext) + self.encrypt(), self.digest()

    def decrypt_and_verify(self, ciphertext, received_mac_tag):
        """Decrypted the message and verify its authenticity in one step.

        :Parameters:
          ciphertext : byte string
            The entire message to decrypt.
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.

        :Return: the decrypted data (byte string).
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        plaintext = self.decrypt(ciphertext) + self.decrypt()
        self.verify(received_mac_tag)
        return plaintext

def _create_ocb_cipher(factory, **kwargs):
    """Create a new block cipher, configured in OCB mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Crypto.Cipher`
        (like `Crypto.Cipher.AES`).

    :Keywords:
      nonce : byte string
        A  value that must never be reused for any other encryption.
        Its length can vary from 1 to 15 bytes.
        If not specified, a random 15 bytes long nonce is generated.

      mac_len : integer
        Length of the MAC, in bytes.
        It must be in the range ``[8..16]``.
        The default is 16 (128 bits).

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    """

    try:
        nonce = kwargs.pop("nonce", None)
        if nonce is None:
            nonce = get_random_bytes(15)
        mac_len = kwargs.pop("mac_len", 16)
    except KeyError, e:
        raise TypeError("Keyword missing: " + str(e))

    return OcbMode(factory, nonce, mac_len, kwargs)


text:
<aside class="Sidebar">
	{% case page.collection %}
		{% when 'basic'%}
			{% assign menu=site.menus.basic %}
		{% when 'pro' %}
			{% assign menu=site.menus.pro %}
		{% when 'general' %}
			{% assign menu=site.menus.general %}
	{% endcase %}
	{% include menus.html menu=menu toplevel=true %}
</aside>


text:
'''

This module exists to allow running a server which can connect to
multiple clients.  It implements a server, emulating what an
OpalPythonDaemon does (from M2k).  The current incarnation does not
support adaptive serialization, but does allow a choice of Protocols:
Python Pickling Protocol 0,2 or no serialization.  See the MidasTalker
class for more details. (Adaptive serialization is slightly problematic
because it requires stealing C++ code from M2k which means that this
module would be more difficult to install because it would require C++
code and no longer be "only Python".  TODO: We hope to rectify this.)

The MidasServer supports both dual-socket and single socket mode.
Dual-socket mode exists for compatibility with very old sockets
libraries, and is the default mode for the M2k OpalPythonDaemon, thus
it is the default mode for the MidasServer.  If you can, you probably
want to use single socket mode, as frequent connects/disconnects
exposes a race condition in dual-socket mode.

The typical user will inherit from MidasServer, overriding the
methods

    acceptNewClient_    # Callback for when new client appears
    readClientData_     # Callback for when data appears for a client
    disconnectClient_   # Callback for when a client disconnects

The callback methods all pass a file descriptor to the user, which can
be used for a blockingSend back to the client.

'''

import select
from midassocket import *
import thread
import time

class MidasServer(MidasSocket_) :
    """ The MidasServer class:  A base class for users to inherit
        from to implement a server.
    """

    def __init__ (self, host, port, serialization = SERIALIZE_P0,
                  force_dual_socket=DUAL_SOCKET,
                  array_disposition=ARRAYDISPOSITION_AS_LIST):
        """Initialize the MidasServer with host and port number.  This
        doesn't open the server for business yet: see the open() method."""
        MidasSocket_.__init__(self, serialization, array_disposition)

        self.host = host
        self.port = port
        self.dual_socket = force_dual_socket
        self.s = None          # read and write socket descriptors
                               # 0 = read, 1 = write (like stdin, stdout)

        self.mainloop_stop   = 0
        self.mainloop_done   = 0
        self.mutex           = thread.allocate_lock()
        self.mainloop_mutex  = thread.allocate_lock()
        self.read_socks      = []
        self.write_socks     = []
        self.client_fd_table = { }

    def __del__ (self) :
        self.shutdown()
        self.waitForMainLoopToFinish()
        # thread.deallocate_lock(self.mutex)
        # thread.deallocate_lock(self.mainloop_mutex)

    def cleanUp (self) :
        """ Clean-up, disconnect everyone, and close file descriptors.
        This can be called over and over to set-up the server."""

        # Close all clients
        for client in self.client_fd_table.copy() :
            self.removeClient(client)
        if self.client_fd_table != { } :
            raise error, "Internal Error: Shouldn't be any clients"

        # Close main door
        if (self.s) :
            self.closing_(self.s)
            self.s = None
        self.read_socks = []

    def close(self) : self.cleanUp()

    def open (self, timeout=1.0) :
        """ Create a server thread that will start accepting clients.
        Timeout of None will block until some activity is detected on
        the socket.

        Note that we've changed the default on the open: This is how
        long the accept watches the the sockets inside the mainloop
        before it checks for shutdown events: if it's too long, it's
        hard for the server to recognize external events: too short,
        and it polls and wastes CPU.  NONE is almost always the wrong
        value, as it will never wakeup and look for the shutdown
        message: So we make 1.0 be the default: every 1.0 second, the
        accept wakes up, checks shutdown, then goeas back to watching
        the sockets.
        """

        self.cleanUp() # Clean-up file descriptors and reinitialize

        # Create the socket that we will be listening on
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)# Allow immediate reopen
        self.s.bind((self.host, self.port))
        self.s.listen(5)

        # Initialize
        self.timeout = timeout

        # A list of client file descriptors: Whenever a client
        # connects or disconnects, it is updated.  Structure:
        # { read_file_desc1 : (address1, write_file_desc1, address_write1),
        #   read_file_desc2 : (address2, write_file_desc2, address_write2),
        #   ... }
        # In single socket mode, since the read_file_desc is the same
        # as the write_file_desc, it is simply a duplicate.
        self.client_fd_table = { }

        # This is a list of currently active read file descriptors.
        # When a new client attaches, it goes to the end of the list.
        # When a client does away, it is deleted.  Note that the
        # "listen" port is always on the read_socks so we can listen
        # for new clients.
        self.read_socks = [self.s]

        # Create a thread that watches that socket
        thread.start_new(MidasServer.mainloop, (self,) )

    def now (self) :
        return time.ctime(time.time())

    def socketAccept (self, fd, preamble) :
        """ Helper code for when a socket connects: it connects and sends
        out the appropriate preamble (SNGL, RECV or SEND)*4.  In the case
        of single-socket mode, this is only called once, as the same socket
        is used for read/write.  In dual-socket, it is called twice:
        one accept for what will be the read socket, one accept for
        what will be the write socket."""
        (connection_fd, address) = fd.accept()
        if preamble is not None :
            self.writeExact_(connection_fd, preamble)
        return (connection_fd, address)

    def newClientConnect (self, fd) :
        """ A client has appeared and connected: perform maintenance and
        call user hook.  Users override the acceptNewClient_ routine to
        get the hook.
        """
        try :
            # New Client attempting connect
            if self.dual_socket == NORMAL_SOCKET :
                (read_fd, read_addr)   = self.socketAccept(fd, None)
                (write_fd, write_addr) = (read_fd, read_addr)

            elif self.dual_socket == DUAL_SOCKET:
                # This is why there is a potential race condition:  We do
                # two accepts right after each other.  This is why we suggest
                # you use single socket mode.
                (read_fd, read_addr)   = self.socketAccept(fd, 'RECV'*4)
                (write_fd, write_addr) = self.socketAccept(fd, 'SEND'*4)

            elif self.dual_socket == SINGLE_SOCKET : # Single socket
                (read_fd, read_addr) = self.socketAccept(fd, 'SNGL'*4)
                (write_fd, write_addr) = (read_fd, read_addr)
            else :
                raise error, "Unknown socket protocol?  Needs to be DUAL_SOCKET, SINGLE_SOCKET or NORMAL_SOCKET"

            # User hook
            #print 'acceptNewClient_'
            self.acceptNewClient_(read_fd, read_addr, write_fd, write_addr)
        except socket.error :
            print 'Problems with connection??? Aborting connection'
            self.closing_(read_fd)
            self.closing_(write_fd)
            return

        self.mutex.acquire() # Lock
        self.client_fd_table[read_fd] = (read_addr, write_fd, write_addr)
        self.read_socks.append(read_fd) # List of sockets to select
        self.mutex.release() # Unlock

    def newClientData (self, fd) :
        """ A client has gotten data: perform maintenance and call user hook.
        Users override the readClientData_ routine to get the hook.
        """
        data = self.recvBlocking_(fd)
        read_fd = write_fd = fd
        if self.dual_socket :
            self.mutex.acquire() # Lock
            (_, write_fd, _) = self.client_fd_table[read_fd]
            self.mutex.release() # Unlock
        self.readClientData_(read_fd, write_fd, data)

    def removeClient (self, fd) :
        """ A client has gone away.  Remove him from internal lists
            and cleanly close down its connection. """

        self.mutex.acquire()  # Lock
        # Remove from list containing active "read" file descriptors
        del self.read_socks[self.read_socks.index(fd)]
        # Remove from list containing list of file descriptors
        entry = self.client_fd_table[fd]  # .. keep copy of for close
        del self.client_fd_table[fd]
        self.mutex.release()  # Unlock

        read_fd = fd; write_fd = entry[1]
        if not self.mainloop_done :
            self.disconnectClient_(read_fd, write_fd) # User hook

        # Don't close until all done just in case client needs
        if self.dual_socket :
            self.closing_(read_fd)
            self.closing_(write_fd)
        else :
            self.closing_(read_fd)

    def mainloop (ms) :
        """ Mainloop for looping through and watching the socket. """
        ms.mainloop_mutex.acquire() # Keep wait out

        ms.mainloop_done = 0
        while 1:

            ms.mutex.acquire() # Lock
            # Do a FULL COPY so we only have to lock this transaction
            rs, ws = ms.read_socks[:], ms.write_socks[:]
            done = ms.mainloop_stop
            ms.mutex.release() # Unlock

            if done : break

            timeout = ms.timeout
            #timeout = 1
            #print 'MAIN LOOP: before select', timeout, rs, ws
            readables,writeables,exceptions=ms.mySelect_(rs, ws, [], timeout)
            #print 'MAIN LOOP: after select', timeout, readables, writeables, exceptions

            for r in readables :

                is_new_client = (r==ms.s) # Main port

                if is_new_client:         # New Client Asking To Connect
                    #print 'new client'
                    ms.newClientConnect(r)
                else :                    # Client with Data to be read
                    try :
                        #print 'new client data'
                        ms.newClientData(r)
                    except error, e :
                        # An error, client went away, take off list
                        #print 'remove client'
                        ms.removeClient(r)

            for w in writeables :
                pass#print "Shouldn't be any writables:",w

            for e in exceptions :
                pass#print "Shouldn't be any exceptions:",e

        # Finish main loop
        ms.mainloop_done = 1
        ms.mainloop_mutex.release() # All done with mainloop

    def waitForMainLoopToFinish (self) :
        """ Wait for the mainloop to finish. """
        while not(self.mainloop_done) :
            self.mainloop_mutex.acquire()
            self.mainloop_mutex.release() # really want condvars here...
        self.cleanUp()

    def shutdown (self) :
        """ Asynchronously tell the server to shutdown.
        Call waitForMainLoopToFinish to make sure it has finished. """
        self.mutex.acquire() # Lock
        self.mainloop_stop = 1
        self.mutex.release() # Unlock

    def acceptNewClient_ (self, read_fd, read_addr, write_fd, write_addr) :
        """ User Callback for when a new client is added.  Each client
        can be distiguished by its read_fd (a unique number for each
        client).  The read_addr (and write_addr) gives more
        information about the connection: It's a 2-tuple of address
        and info.  In dual-socket mode, the read_fd and write_fd are
        different numbers, in single-socket mode, they are the
        same."""
        pass

    def readClientData_ (self, read_fd, write_fd, data) :
        """ User Callback for when client data is posted.  The read_fd
        identifies the client that sent the data.  The write_fd is the
        file descriptor to use to send data back to that client.  In
        dual-socket mode, the read_fd and write_fd are different
        numbers, in single-socket mode, they are the same.  Use
        'self.sendBlocking_(write_fd, result)' to send data back to the
        client as a response."""
        pass

    def disconnectClient_ (self, read_fd, write_fd) :
        """ User Callback for when a client disconnects.  The read_fd
        distiguishes which client is disconnecting.  The read_fd and
        write_fd will be closed almost immediately after this method
        returns (the user does not have to close the descriptors)."""
        pass


text:
/* Desc: RFID Visualization Class
 * Author: Jonas Mellin & Zakiruz Zaman
 * Date: 6th December 2011
 */

#include "gazebo/transport/transport.hh"
#include "gazebo/rendering/Conversions.hh"
#include "gazebo/rendering/Scene.hh"
#include "gazebo/common/MeshManager.hh"
#include "gazebo/rendering/RFIDTagVisualPrivate.hh"
#include "gazebo/rendering/RFIDTagVisual.hh"

using namespace gazebo;
using namespace rendering;

/////////////////////////////////////////////////
RFIDTagVisual::RFIDTagVisual(const std::string &_name, VisualPtr _vis,
                             const std::string &_topicName)
  : Visual(*new RFIDTagVisualPrivate, _name, _vis)
{
  RFIDTagVisualPrivate *dPtr =
      reinterpret_cast<RFIDTagVisualPrivate *>(this->dataPtr);

  dPtr->node = transport::NodePtr(new transport::Node());
  dPtr->node->Init(dPtr->scene->GetName());

  dPtr->rfidSub = dPtr->node->Subscribe(_topicName,
      &RFIDTagVisual::OnScan, this);

  common::MeshManager::Instance()->CreateSphere("contact_sphere", .2, 10, 10);

  this->AttachMesh("contact_sphere");
  this->SetMaterial("Gazebo/OrangeTransparent");
}

/////////////////////////////////////////////////
RFIDTagVisual::~RFIDTagVisual()
{
}

/////////////////////////////////////////////////
void RFIDTagVisual::OnScan(ConstPosePtr &/*_msg*/)
{
  // math::Vector3 pt = msgs::Convert(_msg->position());
  // this->sceneNode->setPosition(Conversions::Convert(pt));
}


text:
package com.imquaker.ispovestiviewer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

public class CommentsFragment extends SherlockFragment implements OnCommentLikeListener {
	public static final String	CONFESSION_ID		= "confession_id";

	private static final String	REQ_LOAD_COMMENTS	= "load_comments";

	private static final String	URL_COMMENTS		= "http://ispovesti.com/php/load_comments.php";
	private static final String	URL_COMMENT_LIKE	= "http://ispovesti.com/php/like_add2.php";
	private static final String	URL_COMMENT_DISLIKE	= "http://ispovesti.com/php/hate_add2.php";

	private static final String	REQ_COMMENT_LIKE	= "like_comment";
	private static final String	REQ_COMMENT_DISLIKE	= "dislike_comment";

	private ConfessionActivity	mActivity;
	private CommentsListAdapter	mListAdapter;

	@Override
	public void onAttach( Activity activity ) {
		super.onAttach( activity );

		setHasOptionsMenu( true );
	}

	@Override
	public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
		return inflater.inflate( R.layout.comments_fragment, container, false );
	}

	@Override
	public void onStart( ) {
		super.onStart( );

		int confessionId = getArguments( ).getInt( CONFESSION_ID );
		if ( confessionId == 0 ) {
			getFragmentManager( ).popBackStack( );
			// TODO error - wrong id

			return;
		}

		mActivity = (ConfessionActivity) getActivity( );
		ConfessionApplication app = (ConfessionApplication) mActivity.getApplication( );
		ArrayList<Confession> confessionList = app.getConfessionList( );

		// TODO replace linear search
		Confession confession = null;
		for ( Confession c : confessionList ) {
			if ( c.getId( ) == confessionId )
				confession = c;
		}
		if ( confession == null ) {
			getFragmentManager( ).popBackStack( );
			// TODO error - invalid id

			return;
		}

		View view = getView( );
		ListView list = (ListView) view.findViewById( R.id.comments_list );
		mListAdapter = new CommentsListAdapter( mActivity, R.layout.comments_row, new ArrayList<Comment>( ), this );
		list.setAdapter( mListAdapter );

		RequestQueue requestQueue = mActivity.getRequestQueue( );
		requestQueue.cancelAll( REQ_LOAD_COMMENTS );

		Map<String, String> params = new HashMap<String, String>( );
		params.put( "isp_id", String.valueOf( confessionId ) );
		StringRequest request = new StringRequest( Method.POST, URL_COMMENTS, params, new Listener<String>( ) {
			@Override
			public void onResponse( String response ) {
				try {
					JSONObject root = new JSONObject( response );
					JSONArray comments = root.getJSONArray( "all_comments" );
					for ( int i = 0, size = comments.length( ); i < size; ++i ) {
						JSONObject comment = comments.getJSONObject( i );
						int id = comment.getInt( "id" );
						String nick = comment.getString( "name" );
						if ( nick.length( ) == 0 ) {
							nick = "Anonimus";
						}
						String content = comment.getString( "text" ).trim( );
						int likes = comment.getInt( "likes" );

						Comment c = new Comment( id, nick, content, likes );
						mListAdapter.add( c );
					}
				}
				catch ( Exception e ) {
					return;
				}
			}
		}, new ErrorListener( ) {
			@Override
			public void onErrorResponse( VolleyError error ) {
				// TODO
			}
		} );
		request.setRetryPolicy( mActivity.getDefaultRetryPolicy( ) );
		request.setTag( REQ_LOAD_COMMENTS );

		requestQueue.add( request );
	}

	@Override
	public void onCreateOptionsMenu( Menu menu, MenuInflater inflater ) {
		super.onCreateOptionsMenu( menu, inflater );
		menu.clear( );

		inflater.inflate( R.menu.actionbar_comments, menu );
	}

	@Override
	public boolean onOptionsItemSelected( MenuItem item ) {
		int itemId = item.getItemId( );
		switch ( itemId ) {
		case android.R.id.home:
			getActivity( ).getSupportFragmentManager( ).popBackStack( );
			break;
		}

		return super.onOptionsItemSelected( item );
	}

	@Override
	public void onCommentLike( View view, Comment comment ) {
		if ( comment.isLiked( ) || comment.isDisliked( ) ) {
			return;
		}

		comment.doLike( );
		mListAdapter.notifyDataSetChanged( );

		rateComment( comment, true );
	}

	@Override
	public void onCommentDislike( View view, Comment comment ) {
		if ( comment.isLiked( ) || comment.isDisliked( ) ) {
			return;
		}

		comment.doDislike( );
		mListAdapter.notifyDataSetChanged( );

		rateComment( comment, false );
	}

	private void rateComment( Comment comment, boolean like ) {
		int id = comment.getId( );
		String url = like ? URL_COMMENT_LIKE : URL_COMMENT_DISLIKE;
		String requestTag = like ? REQ_COMMENT_LIKE : REQ_COMMENT_DISLIKE;
		Map<String, String> params = new HashMap<String, String>( );

		params.put( "id", String.valueOf( id ) );
		StringRequest request = new StringRequest( Method.POST, url, params, new Listener<String>( ) {
			@Override
			public void onResponse( String response ) {
			}
		}, new ErrorListener( ) {
			@Override
			public void onErrorResponse( VolleyError error ) {
			}
		} );
		request.setTag( requestTag );
		mActivity.getRequestQueue( ).add( request );
	}
}


text:
#ifndef RuleFeature_h
#define RuleFeature_h

#include "wtf/Forward.h"
#include "wtf/HashSet.h"
#include "wtf/text/AtomicStringHash.h"

namespace WebCore {

class StyleRule;
class CSSSelector;
class CSSSelectorList;

struct RuleFeature {
    RuleFeature(StyleRule* rule, unsigned selectorIndex, bool hasDocumentSecurityOrigin)
        : rule(rule)
        , selectorIndex(selectorIndex)
        , hasDocumentSecurityOrigin(hasDocumentSecurityOrigin)
    {
    }
    StyleRule* rule;
    unsigned selectorIndex;
    bool hasDocumentSecurityOrigin;
};

class RuleFeatureSet {
public:
    RuleFeatureSet()
        : m_usesFirstLineRules(false)
        , m_usesBeforeAfterRules(false)
    { }

    void add(const RuleFeatureSet&);
    void clear();

    void collectFeaturesFromSelector(const CSSSelector*);

    bool usesSiblingRules() const { return !siblingRules.isEmpty(); }
    bool usesFirstLineRules() const { return m_usesFirstLineRules; }
    bool usesBeforeAfterRules() const { return m_usesBeforeAfterRules; }

    inline bool hasSelectorForAttribute(const AtomicString& attributeName) const
    {
        ASSERT(!attributeName.isEmpty());
        return attrsInRules.contains(attributeName);
    }

    inline bool hasSelectorForClass(const AtomicString& classValue) const
    {
        ASSERT(!classValue.isEmpty());
        return classesInRules.contains(classValue);
    }

    inline bool hasSelectorForId(const AtomicString& idValue) const
    {
        ASSERT(!idValue.isEmpty());
        return idsInRules.contains(idValue);
    }

    HashSet<AtomicString> idsInRules;
    HashSet<AtomicString> classesInRules;
    HashSet<AtomicString> attrsInRules;
    Vector<RuleFeature> siblingRules;
    Vector<RuleFeature> uncommonAttributeRules;
private:
    void collectFeaturesFromSelectorList(const CSSSelectorList*);

    bool m_usesFirstLineRules;
    bool m_usesBeforeAfterRules;
};

} // namespace WebCore

#endif // RuleFeature_h


text:
/*
*/
package com.udfv.udf250;

import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.*;
import org.apache.xerces.dom.*;
import com.udfv.core.*;
import com.udfv.util.*;
import com.udfv.exception.*;
import com.udfv.access.*;
import com.udfv.ecma167.*;

public class UDF_desc9 extends com.udfv.udf201.UDF_desc9
{
    /**
      コンストラクタ

      @param elem 親
      @param prefix ネームスコープ
      @param name 名前
    */
    public UDF_desc9(UDF_Element elem, String prefix, String name){
	super(elem, prefix, name == null ? getUDFClassName() : name);
    }

    public UDF_ErrorList verify() throws UDF_Exception{

	UDF_ErrorList el = new UDF_ErrorList();

	if(env.udf_revision != 0x250)
	    return super.verify();

	el.addError(verifyBase(UDF_Error.C_UDF250));

	el.setRName("Logical Volume Integrity Descriptor");
	el.addError(super.verify());
	el.setGlobalPoint(getGlobalPoint());

	return el;
    }

}


text:
Template

```html
<form #form="ngForm"
  (ngSubmit)="onSubmit(form.value)">
  . . .
</form>
```

NgForm Directive

```typescript
outputs: ['ngSubmit']
```


text:
set -e

if [ $# -ne 1 ]; then
  echo "Usage: ${0} <path_to_android_ndk>"
  exit
fi

ndk="${1}"
shift 1

# configuration parameters common to all architectures
common_params="--disable-examples --disable-docs --enable-realtime-only"
common_params+=" --disable-vp8 --disable-vp9-encoder --disable-webm-io"
common_params+=" --disable-libyuv --disable-runtime-cpu-detect"

# configuration parameters for various architectures
arch[0]="armeabi-v7a"
config[0]="--target=armv7-android-gcc --sdk-path=$ndk --enable-neon"
config[0]+=" --enable-neon-asm"

arch[1]="armeabi"
config[1]="--target=armv7-android-gcc --sdk-path=$ndk --disable-neon"
config[1]+=" --disable-neon-asm"

arch[2]="mips"
config[2]="--force-target=mips32-android-gcc --sdk-path=$ndk"

arch[3]="x86"
config[3]="--force-target=x86-android-gcc --sdk-path=$ndk --disable-sse2"
config[3]+=" --disable-sse3 --disable-ssse3 --disable-sse4_1 --disable-avx"
config[3]+=" --disable-avx2 --enable-pic"

arch[4]="arm64-v8a"
config[4]="--force-target=armv8-android-gcc --sdk-path=$ndk --enable-neon"

arch[5]="x86_64"
config[5]="--force-target=x86_64-android-gcc --sdk-path=$ndk --disable-sse2"
config[5]+=" --disable-sse3 --disable-ssse3 --disable-sse4_1 --disable-avx"
config[5]+=" --disable-avx2 --enable-pic --disable-neon --disable-neon-asm"

arch[6]="mips64"
config[6]="--force-target=mips64-android-gcc --sdk-path=$ndk"

limit=$((${#arch[@]} - 1))

# list of files allowed after running configure in each arch directory.
# everything else will be removed.
allowed_files="libvpx_srcs.txt vpx_config.c vpx_config.h vpx_scale_rtcd.h"
allowed_files+=" vp8_rtcd.h vp9_rtcd.h vpx_version.h vpx_config.asm"
allowed_files+=" vpx_dsp_rtcd.h libvpx.ver"

remove_trailing_whitespace() {
  perl -pi -e 's/\s\+$//' "$@"
}

convert_asm() {
  for i in $(seq 0 ${limit}); do
    while read file; do
      case "${file}" in
        *.asm.[sS])
          # Some files may already have been processed (there are duplicated
          # .asm.s files for vp8 in the armeabi/armeabi-v7a configurations).
          file="libvpx/${file}"
          if [[ ! -e "${file}" ]]; then
            asm_file="${file%.[sS]}"
            cat "${asm_file}" | libvpx/build/make/ads2gas.pl > "${file}"
            remove_trailing_whitespace "${file}"
            rm "${asm_file}"
          fi
          ;;
      esac
    done < libvpx_android_configs/${arch[${i}]}/libvpx_srcs.txt
  done
}

extglob_status="$(shopt extglob | cut -f2)"
shopt -s extglob
for i in $(seq 0 ${limit}); do
  mkdir -p "libvpx_android_configs/${arch[${i}]}"
  pushd "libvpx_android_configs/${arch[${i}]}"

  # configure and make
  echo "build_android_configs: "
  echo "configure ${config[${i}]} ${common_params}"
  ../../libvpx/configure ${config[${i}]} ${common_params}
  rm -f libvpx_srcs.txt
  for f in ${allowed_files}; do
    # the build system supports multiple different configurations. avoid
    # failing out when, for example, vp8_rtcd.h is not part of a configuration
    make "${f}" || true
  done

  # remove files that aren't needed
  rm -rf !(${allowed_files// /|})
  remove_trailing_whitespace *

  popd
done

# restore extglob status as it was before
if [[ "${extglob_status}" == "off" ]]; then
  shopt -u extglob
fi

convert_asm

echo "Generated android config files."


text:
/* ================================================================
 * About NPOI
 * Author: Tony Qu
 * Author's email: tonyqus (at) gmail.com
 * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
 * HomePage: http://www.codeplex.com/npoi
 * Contributors:
 *
 * ==============================================================*/

using System;
using System.Collections;
using System.IO;

using NPOI.POIFS.Common;
using System.Collections.Generic;

namespace NPOI.POIFS.Storage
{
    /// <summary>
    /// Storage for documents that are too small to use regular
    /// DocumentBlocks for their data
    /// @author  Marc Johnson (mjohnson at apache dot org)
    /// </summary>
    public class SmallDocumentBlock : BlockWritable, ListManagedBlock
    {

        private const int BLOCK_SHIFT = 6;

        private byte[]            _data;
        private const byte _default_fill         = ( byte ) 0xff;
        private const int  _block_size           =  1 << BLOCK_SHIFT;
        private const int BLOCK_MASK = _block_size - 1;
        private static int _blocks_per_big_block =
            POIFSConstants.BIG_BLOCK_SIZE / _block_size;
        private POIFSBigBlockSize _bigBlockSize;

        public SmallDocumentBlock(POIFSBigBlockSize bigBlockSize, byte[] data, int index)
        {
            _bigBlockSize = bigBlockSize;
            _blocks_per_big_block = GetBlocksPerBigBlock(bigBlockSize);
            _data = new byte[_block_size];

            System.Array.Copy(data, index*_block_size, _data, 0, _block_size);
        }

        public SmallDocumentBlock(POIFSBigBlockSize bigBlockSize)
        {
            _bigBlockSize = bigBlockSize;
            _blocks_per_big_block = GetBlocksPerBigBlock(bigBlockSize);
            _data = new byte[_block_size];
        }

        private static int GetBlocksPerBigBlock(POIFSBigBlockSize bigBlockSize)
        {
            return bigBlockSize.GetBigBlockSize()/_block_size;
        }
        /// <summary>
        /// convert a single long array into an array of SmallDocumentBlock
        /// instances
        /// </summary>
        /// <param name="bigBlockSize">the poifs bigBlockSize</param>
        /// <param name="array">the byte array to be converted</param>
        /// <param name="size">the intended size of the array (which may be smaller)</param>
        /// <returns>an array of SmallDocumentBlock instances, filled from
        /// the array</returns>
        public static SmallDocumentBlock [] Convert(POIFSBigBlockSize bigBlockSize,
                                                    byte [] array,
                                                    int size)
        {
            SmallDocumentBlock[] rval = new SmallDocumentBlock[ (size + _block_size - 1) / _block_size ];
            int                  offset = 0;

            for (int k = 0; k < rval.Length; k++)
            {
                rval[ k ] = new SmallDocumentBlock(bigBlockSize);
                if (offset < array.Length)
                {
                    int length = Math.Min(_block_size, array.Length - offset);

                    Array.Copy(array, offset, rval[ k ]._data, 0, length);
                    if (length != _block_size)
                    {
                        for (int i = length; i < _block_size; i++)
                            rval[k]._data[i] = _default_fill;
                    }
                }
                else
                {
                    for (int j = 0; j < rval[k]._data.Length; j++)
                    {
                        rval[k]._data[j] = _default_fill;
                    }

                }
                offset += _block_size;
            }
            return rval;
        }

        /// <summary>
        /// fill out a List of SmallDocumentBlocks so that it fully occupies
        /// a Set of big blocks
        /// </summary>
        /// <param name="bigBlockSize"></param>
        /// <param name="blocks">the List to be filled out.</param>
        /// <returns>number of big blocks the list encompasses</returns>
        public static int Fill(POIFSBigBlockSize bigBlockSize,IList blocks)
        {
            int _blocks_per_big_block = GetBlocksPerBigBlock(bigBlockSize);
            int count           = blocks.Count;
            int big_block_count = (count + _blocks_per_big_block - 1) / _blocks_per_big_block;
            int full_count      = big_block_count * _blocks_per_big_block;

            for (; count < full_count; count++)
            {
                blocks.Add(MakeEmptySmallDocumentBlock(bigBlockSize));
            }
            return big_block_count;
        }

        /// <summary>
        /// Factory for creating SmallDocumentBlocks from DocumentBlocks
        /// </summary>
        /// <param name="bigBlocksSize"></param>
        /// <param name="store">the original DocumentBlocks</param>
        /// <param name="size">the total document size</param>
        /// <returns>an array of new SmallDocumentBlocks instances</returns>
        public static SmallDocumentBlock [] Convert(POIFSBigBlockSize bigBlocksSize,
                                                    BlockWritable [] store,
                                                    int size)
        {
            using (MemoryStream stream = new MemoryStream())
            {

                for (int j = 0; j < store.Length; j++)
                {
                    store[j].WriteBlocks(stream);
                }
                byte[] data = stream.ToArray();
            SmallDocumentBlock[] rval = new SmallDocumentBlock[ ConvertToBlockCount(size) ];

                for (int index = 0; index < rval.Length; index++)
                {
                rval[index] = new SmallDocumentBlock(bigBlocksSize,data, index);
                }
                return rval;
            }
        }

        /// <summary>
        /// create a list of SmallDocumentBlock's from raw data
        /// </summary>
        /// <param name="bigBlockSize"></param>
        /// <param name="blocks">the raw data containing the SmallDocumentBlock</param>
        /// <returns>a List of SmallDocumentBlock's extracted from the input</returns>
        public static List<SmallDocumentBlock> Extract(POIFSBigBlockSize bigBlockSize, ListManagedBlock [] blocks)
        {
            int _blocks_per_big_block = GetBlocksPerBigBlock(bigBlockSize);
            List<SmallDocumentBlock> sdbs = new List<SmallDocumentBlock>();

            for (int j = 0; j < blocks.Length; j++)
            {
                byte[] data = blocks[ j ].Data;

                for (int k = 0; k < _blocks_per_big_block; k++)
                {
                    sdbs.Add(new SmallDocumentBlock(bigBlockSize, data, k));
                }
            }
            return sdbs;
        }

        /// <summary>
        /// Read data from an array of SmallDocumentBlocks
        /// </summary>
        /// <param name="blocks">the blocks to Read from.</param>
        /// <param name="buffer">the buffer to Write the data into.</param>
        /// <param name="offset">the offset into the array of blocks to Read from</param>
        public static void Read(BlockWritable[] blocks, byte[] buffer, int offset)
        {
            int firstBlockIndex  = offset / _block_size;
            int firstBlockOffSet = offset % _block_size;
            int lastBlockIndex   = (offset + buffer.Length - 1) / _block_size;

            if (firstBlockIndex == lastBlockIndex)
            {
                Array.Copy(
                    (( SmallDocumentBlock ) blocks[ firstBlockIndex ])._data,
                    firstBlockOffSet, buffer, 0, buffer.Length);
            }
            else
            {
                int buffer_offset = 0;

                Array.Copy(
                    (( SmallDocumentBlock ) blocks[ firstBlockIndex ])._data,
                    firstBlockOffSet, buffer, buffer_offset,
                    _block_size - firstBlockOffSet);
                buffer_offset += _block_size - firstBlockOffSet;
                for (int j = firstBlockIndex + 1; j < lastBlockIndex; j++)
                {
                    Array.Copy((( SmallDocumentBlock ) blocks[ j ])._data,
                                     0, buffer, buffer_offset, _block_size);
                    buffer_offset += _block_size;
                }
                Array.Copy(
                    (( SmallDocumentBlock ) blocks[ lastBlockIndex ])._data, 0,
                    buffer, buffer_offset, buffer.Length - buffer_offset);
            }
        }

        public static DataInputBlock GetDataInputBlock(SmallDocumentBlock[] blocks, int offset)
        {
            int firstBlockIndex = offset >> BLOCK_SHIFT;

            int firstBlockOffset = offset & BLOCK_MASK;

            return new DataInputBlock(blocks[firstBlockIndex]._data, firstBlockOffset);
        }

        /// <summary>
        /// Calculate the storage size of a Set of SmallDocumentBlocks
        /// </summary>
        /// <param name="size"> number of SmallDocumentBlocks</param>
        /// <returns>total size</returns>
        public static int CalcSize(int size)
        {
            return size * _block_size;
        }

        /// <summary>
        /// Makes the empty small document block.
        /// </summary>
        /// <returns></returns>
        private static SmallDocumentBlock MakeEmptySmallDocumentBlock(POIFSBigBlockSize bigBlockSize)
        {
            SmallDocumentBlock block = new SmallDocumentBlock(bigBlockSize);
            for (int i = 0; i < block._data.Length; i++)
            {
                block._data[i] = _default_fill;
            }
            return block;
        }

        /// <summary>
        /// Converts to block count.
        /// </summary>
        /// <param name="size">The size.</param>
        /// <returns></returns>
        private static int ConvertToBlockCount(int size)
        {
            return (size + _block_size - 1) / _block_size;
        }

        /// <summary>
        /// Write the storage to an OutputStream
        /// </summary>
        /// <param name="stream">the OutputStream to which the stored data should
        /// be written</param>
        public void WriteBlocks(Stream stream)

        {
            stream.Write(_data,0,_data.Length);
        }

        /// <summary>
        /// Get the data from the block
        /// </summary>
        /// <value>the block's data as a byte array</value>
        public byte [] Data
        {
            get
            {
                return _data;
            }
        }

        public POIFSBigBlockSize BigBlockSize
        {
            get { return _bigBlockSize; }
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace BrianFaust\Ark\API\One;

use BrianFaust\Ark\API\AbstractAPI;
use Illuminate\Support\Collection;

class Loader extends AbstractAPI
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function status(): Collection
    {
        return $this->get('loader/autoconfigure');
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function syncing(): Collection
    {
        return $this->get('loader/status');
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function configuration(): Collection
    {
        return $this->get('loader/status/sync');
    }
}


text:
/*
 * TestSolver.hpp
 *
 *  Created on: 20.10.2015
 *      Author: marcus
 */

#ifndef TEST_INCLUDE_TESTOPENMPTEST_HPP_
#define TEST_INCLUDE_TESTOPENMPTEST_HPP_

#include "TestCommon.hpp"

class OpenMPTest : public TestCommon
{
 public:
    list<double> eventTimePoints;

    OpenMPTest()
            : TestCommon("./test/data/TestConfig_SimpleView_openmp.xml")
    {
    }

    ~OpenMPTest()
    {
    }
};

TEST_F (OpenMPTest, TestDependenciesOpenMP)
{
    ASSERT_EQ(_simulation->getSimulationType(),"serial");
    ASSERT_GT(_simulation->getSolver().size(),1);
    _simulation->initialize();
    _simulation->simulate();
    for(const auto& solv : _simulation->getSolver())
    {
        ASSERT_EQ(solv->getCurrentTime(),0.5);
    }
}

#endif /* TEST_INCLUDE_TESTOPENMPTEST_HPP_ */


text:
date: "2017-11-05 09:16:18 -0300"
title: "Gang of Four, o livro padrões de projetos"
tags: [Programar, Programação,  módulos,  Padrões de Projeto, Criaçonal, Comportamental, "Gangue dos Quatro", "Gang of Four", Prototype, Classes, POO]
categories: [programacao, padroes_de_projeto]
layout: article
share: true
toc: true
comments: true
feature:
 category: true
 index: true
image:
 feature: linuxmacwindows/allOS-logos-900x210.png
 teaser: linuxmacwindows/macwindowslinux-500x210.png
ads:
 show: true
tagcloud: true
coinbase:
 show: true
---

Aguarde, vou escrever em breve sobre o livro.

<!--more-->

Artigo sendo escrito
{ .notice }


text:
package astraiea.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Ranks data, taking into account of ties, for use in tests such as Wilcoxon and Brunner Munzel
 *
 * @author Geoffrey Neumann
 *
 */
public final class RankCalculator {

	// input data
	private double[] dataA;
	private double[] dataB;

	/** length of both datasets combined */
	private double totLength;

	/**
	 * maps to elements in the combined rank array (combinedArr)
	 * specifying if they came from dataA (true) or dataB (false)
	 */
	private boolean[] isFromA;

	/** ranks of all data */
	private double[] combinedArr;

	/** ranks of dataA when it is ranked with dataB */
	private double[] rankBothA;

	// as above - vice versa
	private double[] rankBothB;

	//indexes with dataA and dataB
	private int iA = 0;
	private int iB = 0;

	/** ranks of dataA when it is ranked on its own */
	private double[] rankAloneA;

	// as above - vice versa
	private double[] rankAloneB;

	/** for each tied value, each item in this array is the quantity of that tied value */
	private List<Integer> ties = new ArrayList<Integer>();

	/** rank a data array for cases in which only one data array is being ranked */
	private double [] rankOneSample;

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

	/**
	 * Which entity are we currently ranking (either data array,
	 * both data arrays combined or just one data array if there is only one)
	 */
	enum WhichRank{both, dataA, dataB, oneSample};

	public RankCalculator(double[] dataA, double[] dataB){
		//calculate ranks for copies so that original arrays don't get reordered
		calcRanks(Arrays.copyOf(dataA,dataA.length),Arrays.copyOf(dataB,dataB.length));
	}

	public RankCalculator(double[] data) {
		rankOneSample = new double[data.length];
		Arrays.sort(data);
		splitTiesAndRank(data,WhichRank.oneSample);
	}

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

	public List<Integer> getTies() { return ties; }

	public double[] getRanks() { return rankOneSample; }

	public double[] getCombinedRanks(int which){
		if(which == 0)
			return rankBothA;
		else
			return rankBothB;
	}

	public double[] getSeparateRanks(int which){
		if(which == 0)
			return rankAloneA;
		else
			return rankAloneB;
	}

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

	/**
	 * The main ranking method
	 *
	 * @param dataA
	 * @param dataB
	 */
	private void calcRanks(double[] dataA, double[] dataB){
		this.dataA = dataA;
		this.dataB = dataB;
		order();
		rankBothA = new double[dataA.length];
		rankBothB = new double[dataB.length];
		rankAloneA = new double[dataA.length];
		rankAloneB = new double[dataB.length];
		splitTiesAndRank(combinedArr,WhichRank.both);//produce an array with both arrays ranked together
		splitTiesAndRank(this.dataA,WhichRank.dataA);//and separately
		splitTiesAndRank(this.dataB,WhichRank.dataB);
	}

	/**
	 * Produce an array of ranks, with ties.
	 *
	 * @param inArr
	 * @param which which array to produce - for either dataA, dataB, for both (combinedArr) or in the case in which only one set of data is being ranked (rankOneSample)
	 */
	private void splitTiesAndRank(double[] inArr, WhichRank which) {
		ties.clear();
		for(int i =1; i <= inArr.length; i++){
			double rank = i;
			int iTie = i + 1;
			while(iTie < inArr.length && inArr[iTie - 1] == inArr[i - 1]){ //step forward from current index and count the number of ties ahead
				iTie++;
			}
			if(iTie - i > 1){ //if there are ties
				ties.add(iTie - i);
				rank = i + ((((double)iTie - 1) - (double)i)/2.0);
				for(;i < iTie; i++){
					addRank(rank, i - 1, which);
				}
				i--;
			}
			else{
				addRank(rank, i - 1, which);
			}
		}
	}

	/**
	 * Adds a rank to the appropriate array
	 *
	 * @param rank
	 * @param i
	 * @param which
	 */
	private void addRank(double rank, int i, WhichRank which) {
		if(which == WhichRank.both){
			if(isFromA[i]){
				rankBothA[iA] = rank;
				iA++;
			}
			else{
				rankBothB[iB] = rank;
				iB++;
			}
		}
		else if(which == WhichRank.dataA)
			rankAloneA[i] = rank;
		else if(which == WhichRank.dataB)
			rankAloneB[i] = rank;
		else
			rankOneSample[i] = rank;
	}

	/**
	 * Sort both arrays into ascending order and produce a combined array which contains data from both arrays sorted.
	 *
	 */
	private void order() {
		//sort separately
		Arrays.sort(dataA);
		Arrays.sort(dataB);
		int lengthA = dataA.length;
		int lengthB = dataB.length;
		totLength = lengthA + lengthB;
		isFromA = new boolean[(int)totLength];
		combinedArr = new double[(int)totLength];
		int iB = 0;
		int iBoth = 0;
		//sort into combined array
		for(int iA = 0; iA < lengthA; iA++){
			while(iB< lengthB && dataB[iB] < dataA[iA]){
				isFromA[iBoth] = false;
				combinedArr[iBoth] = dataB[iB];
				iB++;
				iBoth++;
			}
			isFromA[iBoth] = true;
			combinedArr[iBoth] = dataA[iA];
			iBoth++;
		}

	}
}

// End ///////////////////////////////////////////////////////////////


text:
namespace NPOI.HPSF.Extractor
{
    using System;
    using System.Text;
    using System.IO;
    using System.Collections;

    using NPOI;
    using NPOI.HPSF;
    using NPOI.POIFS.FileSystem;
    using NPOI.Util;
    using System.Globalization;

    /// <summary>
    /// Extracts all of the HPSF properties, both
    /// build in and custom, returning them in
    /// textual form.
    /// </summary>
    public class HPSFPropertiesExtractor : POIOLE2TextExtractor
    {
        public HPSFPropertiesExtractor(POIOLE2TextExtractor mainExtractor)
            : base(mainExtractor)
        {

        }
        public HPSFPropertiesExtractor(POIDocument doc)
            : base(doc)
        {

        }
        public HPSFPropertiesExtractor(POIFSFileSystem fs)
            : base(new HPSFPropertiesOnlyDocument(fs))
        {

        }
        public HPSFPropertiesExtractor(NPOIFSFileSystem fs)
            : base(new HPSFPropertiesOnlyDocument(fs))
        {

        }
        /// <summary>
        /// Gets the document summary information text.
        /// </summary>
        /// <value>The document summary information text.</value>
        public String DocumentSummaryInformationText
        {
            get
            {
                if (document == null)
                {  // event based extractor does not have a document
                    return "";
                }
                DocumentSummaryInformation dsi = document.DocumentSummaryInformation;
                StringBuilder text = new StringBuilder();

                // Normal properties
                text.Append(GetPropertiesText(dsi));

                // Now custom ones
                CustomProperties cps = dsi == null ? null : dsi.CustomProperties;

                if (cps != null)
                {
                    IEnumerator keys = cps.NameSet().GetEnumerator();
                    while (keys.MoveNext())
                    {
                        String key = keys.Current.ToString();
                        String val = HelperPropertySet.GetPropertyValueText(cps[key]);
                        text.Append(key + " = " + val + "\n");
                    }
                }
                // All done
                return text.ToString();
            }
        }
        /// <summary>
        /// Gets the summary information text.
        /// </summary>
        /// <value>The summary information text.</value>
        public String SummaryInformationText
        {
            get
            {
                if (document == null)
                {  // event based extractor does not have a document
                    return "";
                }
                SummaryInformation si = document.SummaryInformation;

                // Just normal properties
                return GetPropertiesText(si);
            }
        }

        /// <summary>
        /// Gets the properties text.
        /// </summary>
        /// <param name="ps">The ps.</param>
        /// <returns></returns>
        private static String GetPropertiesText(SpecialPropertySet ps)
        {
            if (ps == null)
            {
                // Not defined, oh well
                return "";
            }

            StringBuilder text = new StringBuilder();

            Wellknown.PropertyIDMap idMap = ps.PropertySetIDMap;
            Property[] props = ps.Properties;
            for (int i = 0; i < props.Length; i++)
            {
                String type = props[i].ID.ToString(CultureInfo.InvariantCulture);
                Object typeObj = idMap.Get(props[i].ID);
                if (typeObj != null)
                {
                    type = typeObj.ToString();
                }

                String val = HelperPropertySet.GetPropertyValueText(props[i].Value);
                text.Append(type + " = " + val + "\n");
            }

            return text.ToString();
        }

        /// <summary>
        /// Return the text of all the properties defined in
        /// the document.
        /// </summary>
        /// <value>All the text from the document.</value>
        public override String Text
        {
            get
            {
                return SummaryInformationText + DocumentSummaryInformationText;
            }
        }

        /// <summary>
        /// Returns another text extractor, which is able to
        /// output the textual content of the document
        /// metadata / properties, such as author and title.
        /// </summary>
        /// <value>The metadata text extractor.</value>
        public override POITextExtractor MetadataTextExtractor
        {
            get
            {
                throw new InvalidOperationException("You already have the Metadata Text Extractor, not recursing!");
            }
        }

        public abstract class HelperPropertySet : SpecialPropertySet
        {
            public HelperPropertySet()
                : base(null)
            {
            }
            public static String GetPropertyValueText(Object val)
            {
                if (val == null)
                {
                    return "(not set)";
                }
                return SpecialPropertySet.GetPropertyStringValue(val);
            }
        }
    }
}


text:
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const host = '0.0.0.0'
const port = '3000'

module.exports = {
  entry: [
    'react-hot-loader/patch',
    `webpack-dev-server/client?http://${host}:${port}`,
    'webpack/hot/only-dev-server',
    path.join(__dirname, '../dev/index.js'),
  ],

  output: {
    path: path.join(__dirname, '../dev/index.js'),
    filename: 'index.js',
    publicPath: '/',
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },

      {
        test: /\.css$/,
        include: [
          path.resolve('node_modules', 'react-select'),
        ],
        use: ['style-loader', 'css-loader'],
      },

      {
        test: /\.sass$/,
        exclude: /node_modules/,
        use: [ 'style-loader', 'css-loader', 'sass-loader' ],
      },
    ],
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    }),

    new webpack.NamedModulesPlugin(),

    new webpack.HotModuleReplacementPlugin(),

    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.join(__dirname, '../dev/index.html'),
    }),
  ],

  resolve: {
    extensions: [ '.js', '.css', '.sass' ],

    alias: {
      'react-alphabet-sorter': path.join(__dirname, '../dist'),
    },
  },

  devServer: {
    host,
    port,
    contentBase: path.resolve(__dirname, '../dev'),
    historyApiFallback: true,
    hot: true,
    publicPath: '/',
  },
}


text:
package oap.json.schema.validator;

import oap.json.schema.AbstractJsonSchemaValidator;
import oap.json.schema.DefaultSchemaAST;
import oap.json.schema.DefaultSchemaASTWrapper;
import oap.json.schema.JsonSchemaParserContext;
import oap.json.schema.JsonValidatorProperties;
import oap.util.Lists;

import java.util.List;

public class AnyJsonValidator extends AbstractJsonSchemaValidator<DefaultSchemaAST> {
    public AnyJsonValidator() {
        super( "any" );
    }

    @Override
    public List<String> validate( JsonValidatorProperties properties, DefaultSchemaAST schema, Object value ) {
        return Lists.empty();
    }

    @Override
    public DefaultSchemaASTWrapper parse( JsonSchemaParserContext context ) {
        return defaultParse( context );
    }
}


text:
using System.Xml.Linq;

namespace OnScreenKeyboard
{
    internal interface IKeyboardBuilder
    {
        void Build(XDocument definition, Keyboard keyboard);
        void Build(string path, Keyboard keyboard);
    }
}


text:
require_relative "./benchmarking_support"
require_relative "./app"

Benchmark.run("ObjectWriter_OneProperty_PushValue") do
  writer = Panko::ObjectWriter.new

  writer.push_object
  writer.push_value "value1", "key1"
  writer.pop

  writer.output
end

Benchmark.run("ObjectWriter_TwoProperty_PushValue") do
  writer = Panko::ObjectWriter.new

  writer.push_object
  writer.push_value "value1", "key1"
  writer.push_value "value2", "key2"
  writer.pop

  writer.output
end

Benchmark.run("ObjectWriter_OneProperty_PushValuePushKey") do
  writer = Panko::ObjectWriter.new

  writer.push_object
  writer.push_key "key1"
  writer.push_value "value1"
  writer.pop

  writer.output
end

Benchmark.run("ObjectWriter_TwoProperty_PushValuePushKey") do
  writer = Panko::ObjectWriter.new

  writer.push_object
  writer.push_key "key1"
  writer.push_value "value1"

  writer.push_key "key2"
  writer.push_value "value2"
  writer.pop

  writer.output
end

Benchmark.run("ObjectWriter_NestedObject") do
  writer = Panko::ObjectWriter.new

  writer.push_object
  writer.push_value "value1", "key1"

  writer.push_object "key2"
  writer.push_value "value2", "key2"
  writer.pop

  writer.pop

  writer.output
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document name="report">
  <ns2:reports_common xmlns:ns2="http://collectionspace.org/services/report">
    <name>Accession Report - Excel</name>
    <notes></notes>
    <forDocTypes>
      <forDocType>Group</forDocType>
    </forDocTypes>
    <supportsSingleDoc>true</supportsSingleDoc>
    <supportsDocList>false</supportsDocList>
    <supportsGroup>false</supportsGroup>
    <supportsNoContext>true</supportsNoContext>
    <filename>ucbgAccessionGroupExcel.jasper</filename>
    <outputMIME>application/vnd.ms-excel</outputMIME>
  </ns2:reports_common>
</document>


text:
package com.viaversion.viaversion.protocols.protocol1_14to1_13_2.packets;

import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
import com.github.steveice10.opennbt.tag.builtin.ListTag;
import com.github.steveice10.opennbt.tag.builtin.StringTag;
import com.github.steveice10.opennbt.tag.builtin.Tag;
import com.viaversion.viaversion.api.Via;
import com.viaversion.viaversion.api.minecraft.Position;
import com.viaversion.viaversion.api.minecraft.item.Item;
import com.viaversion.viaversion.api.protocol.Protocol;
import com.viaversion.viaversion.api.protocol.packet.PacketWrapper;
import com.viaversion.viaversion.api.protocol.remapper.PacketHandler;
import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13;
import com.viaversion.viaversion.protocols.protocol1_14to1_13_2.ServerboundPackets1_14;

import java.util.Collections;

public class PlayerPackets {

    public static void register(Protocol protocol) {
        protocol.registerClientbound(ClientboundPackets1_13.OPEN_SIGN_EDITOR, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.POSITION, Type.POSITION1_14);
            }
        });

        protocol.registerServerbound(ServerboundPackets1_14.QUERY_BLOCK_NBT, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.VAR_INT);
                map(Type.POSITION1_14, Type.POSITION);
            }
        });

        protocol.registerServerbound(ServerboundPackets1_14.EDIT_BOOK, new PacketRemapper() {
            @Override
            public void registerMap() {
                handler(new PacketHandler() {
                    @Override
                    public void handle(PacketWrapper wrapper) throws Exception {
                        Item item = wrapper.passthrough(Type.FLAT_VAR_INT_ITEM);
                        protocol.getItemRewriter().handleItemToServer(item);

                        if (item == null) return;

                        CompoundTag tag = item.tag();
                        if (tag == null) return;

                        Tag pages = tag.get("pages");

                        // Fix for https://github.com/ViaVersion/ViaVersion/issues/2660
                        if (pages == null) {
                            tag.put("pages", new ListTag(Collections.singletonList(new StringTag())));
                        }

                        // Client limit when editing a book was upped from 50 to 100 in 1.14, but some anti-exploit plugins ban with a size higher than the old client limit
                        if (Via.getConfig().isTruncate1_14Books() && pages instanceof ListTag) {
                            ListTag listTag = (ListTag) pages;
                            if (listTag.size() > 50) {
                                listTag.setValue(listTag.getValue().subList(0, 50));
                            }
                        }
                    }
                });
            }
        });

        protocol.registerServerbound(ServerboundPackets1_14.PLAYER_DIGGING, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.VAR_INT); // Action
                map(Type.POSITION1_14, Type.POSITION); // Position
            }
        });

        protocol.registerServerbound(ServerboundPackets1_14.RECIPE_BOOK_DATA, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.VAR_INT);
                handler(new PacketHandler() {
                    @Override
                    public void handle(PacketWrapper wrapper) throws Exception {
                        int type = wrapper.get(Type.VAR_INT, 0);
                        if (type == 0) {
                            wrapper.passthrough(Type.STRING);
                        } else if (type == 1) {
                            wrapper.passthrough(Type.BOOLEAN); // Crafting Recipe Book Open
                            wrapper.passthrough(Type.BOOLEAN); // Crafting Recipe Filter Active
                            wrapper.passthrough(Type.BOOLEAN); // Smelting Recipe Book Open
                            wrapper.passthrough(Type.BOOLEAN); // Smelting Recipe Filter Active

                            // Unknown new booleans
                            wrapper.read(Type.BOOLEAN);
                            wrapper.read(Type.BOOLEAN);
                            wrapper.read(Type.BOOLEAN);
                            wrapper.read(Type.BOOLEAN);
                        }
                    }
                });
            }
        });

        protocol.registerServerbound(ServerboundPackets1_14.UPDATE_COMMAND_BLOCK, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.POSITION1_14, Type.POSITION);
            }
        });
        protocol.registerServerbound(ServerboundPackets1_14.UPDATE_STRUCTURE_BLOCK, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.POSITION1_14, Type.POSITION);
            }
        });
        protocol.registerServerbound(ServerboundPackets1_14.UPDATE_SIGN, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.POSITION1_14, Type.POSITION);
            }
        });

        protocol.registerServerbound(ServerboundPackets1_14.PLAYER_BLOCK_PLACEMENT, new PacketRemapper() {
            @Override
            public void registerMap() {
                handler(new PacketHandler() {
                    @Override
                    public void handle(PacketWrapper wrapper) throws Exception {
                        int hand = wrapper.read(Type.VAR_INT);
                        Position position = wrapper.read(Type.POSITION1_14);
                        int face = wrapper.read(Type.VAR_INT);
                        float x = wrapper.read(Type.FLOAT);
                        float y = wrapper.read(Type.FLOAT);
                        float z = wrapper.read(Type.FLOAT);
                        wrapper.read(Type.BOOLEAN);  // new unknown boolean

                        wrapper.write(Type.POSITION, position);
                        wrapper.write(Type.VAR_INT, face);
                        wrapper.write(Type.VAR_INT, hand);
                        wrapper.write(Type.FLOAT, x);
                        wrapper.write(Type.FLOAT, y);
                        wrapper.write(Type.FLOAT, z);
                    }
                });
            }
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
		<encoder charset="UTF-8">
			<pattern>%d{MM-dd HH:mm:ss.SSS} %-5thread %-5level %logger{1} -	%msg%n</pattern>
		</encoder>
	</appender>
	<appender name="defaultAppender"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${catalina.home}/logs/Ignite-2015.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<FileNamePattern>${catalina.home}/logs/Ignite-2015.log.out.%d{yyyy-MM-dd}
			</FileNamePattern>
		</rollingPolicy>
		<encoder>
			<pattern>%-16(%d{MM-dd HH:mm:ss}) %-5thread %-5level %logger{3} -%msg%n</pattern>
		</encoder>
	</appender>

	<root level="debug">
		<appender-ref ref="defaultAppender" />
		<appender-ref ref="stdout" />
	</root>
</configuration>


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Core\Model;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Model\AdjustmentInterface;
use Sylius\Component\Core\Model\OrderItemUnitInterface;
use Sylius\Component\Resource\Model\VersionedInterface;

final class OrderItemSpec extends ObjectBehavior
{
    function it_implements_versioned_interface(): void
    {
        $this->shouldImplement(VersionedInterface::class);
    }

    function it_returns_0_tax_total_when_there_are_no_units(): void
    {
        $this->getTaxTotal()->shouldReturn(0);
    }

    function it_returns_tax_of_all_unit(OrderItemUnitInterface $orderItemUnit1, OrderItemUnitInterface $orderItemUnit2): void
    {
        $orderItemUnit1->getTotal()->willReturn(1200);
        $orderItemUnit1->getTaxTotal()->willReturn(200);
        $orderItemUnit1->getOrderItem()->willReturn($this);
        $orderItemUnit2->getTotal()->willReturn(1120);
        $orderItemUnit2->getTaxTotal()->willReturn(120);
        $orderItemUnit2->getOrderItem()->willReturn($this);

        $this->addUnit($orderItemUnit1);
        $this->addUnit($orderItemUnit2);

        $this->getTaxTotal()->shouldReturn(320);
    }

    function it_returns_tax_of_all_units_and_both_neutral_and_non_neutral_tax_adjustments(
        OrderItemUnitInterface $orderItemUnit1,
        OrderItemUnitInterface $orderItemUnit2,
        AdjustmentInterface $nonNeutralTaxAdjustment,
        AdjustmentInterface $neutralTaxAdjustment
    ): void {
        $orderItemUnit1->getTotal()->willReturn(1200);
        $orderItemUnit1->getTaxTotal()->willReturn(200);
        $orderItemUnit1->getOrderItem()->willReturn($this);
        $orderItemUnit2->getTotal()->willReturn(1120);
        $orderItemUnit2->getTaxTotal()->willReturn(120);
        $orderItemUnit2->getOrderItem()->willReturn($this);

        $this->addUnit($orderItemUnit1);
        $this->addUnit($orderItemUnit2);

        $neutralTaxAdjustment->isNeutral()->willReturn(true);
        $neutralTaxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $neutralTaxAdjustment->getAmount()->willReturn(200);
        $nonNeutralTaxAdjustment->isNeutral()->willReturn(false);
        $nonNeutralTaxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $nonNeutralTaxAdjustment->getAmount()->willReturn(300);

        $neutralTaxAdjustment->setAdjustable($this)->shouldBeCalled();
        $nonNeutralTaxAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($neutralTaxAdjustment);
        $this->addAdjustment($nonNeutralTaxAdjustment);

        $this->getTaxTotal()->shouldReturn(820);
    }

    function it_returns_discounted_unit_price_which_is_first_unit_price_lowered_by_unit_promotions(
        OrderItemUnitInterface $unit
    ): void {
        $this->setUnitPrice(10000);

        $unit->getOrderItem()->willReturn($this);
        $unit->getTotal()->willReturn(9000);
        $unit->getAdjustmentsTotal(AdjustmentInterface::ORDER_UNIT_PROMOTION_ADJUSTMENT)->willReturn(-500);

        $this->addUnit($unit);

        $this->getDiscountedUnitPrice()->shouldReturn(9500);
    }

    function it_returns_unit_price_as_discounted_unit_price_if_there_are_no_units(): void
    {
        $this->setUnitPrice(10000);

        $this->getDiscountedUnitPrice()->shouldReturn(10000);
    }

    function it_returns_subtotal_which_consist_of_discounted_unit_price_multiplied_by_quantity(
        OrderItemUnitInterface $firstUnit,
        OrderItemUnitInterface $secondUnit
    ): void {
        $this->setUnitPrice(10000);

        $firstUnit->getOrderItem()->willReturn($this);
        $firstUnit->getTotal()->willReturn(9000);
        $firstUnit->getAdjustmentsTotal(AdjustmentInterface::ORDER_UNIT_PROMOTION_ADJUSTMENT)->willReturn(-500);

        $secondUnit->getOrderItem()->willReturn($this);
        $secondUnit->getTotal()->willReturn(9000);
        $secondUnit->getAdjustmentsTotal(AdjustmentInterface::ORDER_UNIT_PROMOTION_ADJUSTMENT)->willReturn(-500);

        $this->addUnit($firstUnit);
        $this->addUnit($secondUnit);

        $this->getSubtotal()->shouldReturn(19000);
    }

    function it_has_no_variant_by_default(): void
    {
        $this->getVariant()->shouldReturn(null);
    }

    function it_has_version_1_by_default(): void
    {
        $this->getVersion()->shouldReturn(1);
    }
}