text:
"""HTTP related errors."""

import asyncio

__all__ = (
    'ClientError',

    'ClientConnectionError',
    'ClientOSError', 'ClientConnectorError', 'ClientProxyConnectionError',

    'ServerConnectionError', 'ServerTimeoutError', 'ServerDisconnectedError',
    'ServerFingerprintMismatch',

    'ClientResponseError', 'ClientPayloadError',
    'ContentTypeError',

    'ClientHttpProxyError', 'WSServerHandshakeError')

class ClientError(Exception):
    """Base class for client connection errors."""

class ClientResponseError(ClientError):
    """Connection error during reading response.

    :param request_info: instance of RequestInfo
    """

    def __init__(self, request_info, history, *,
                 code=0, message='', headers=None):
        self.request_info = request_info
        self.code = code
        self.message = message
        self.headers = headers
        self.history = history

        super().__init__("%s, message='%s'" % (code, message))

class ContentTypeError(ClientResponseError):
    """ContentType found is not valid."""

class WSServerHandshakeError(ClientResponseError):
    """websocket server handshake error."""

class ClientHttpProxyError(ClientResponseError):
    """HTTP proxy error.

    Raised in :class:`aiohttp.connector.TCPConnector` if
    proxy responds with status other than ``200 OK``
    on ``CONNECT`` request.
    """

class ClientConnectionError(ClientError):
    """Base class for client socket errors."""

class ClientOSError(ClientConnectionError, OSError):
    """OSError error."""

class ClientConnectorError(ClientOSError):
    """Client connector error.

    Raised in :class:`aiohttp.connector.TCPConnector` if
        connection to proxy can not be established.
    """
    def __init__(self, connection_key, os_error):
        self._conn_key = connection_key
        super().__init__(os_error.errno, os_error.strerror)

    @property
    def host(self):
        return self._conn_key.host

    @property
    def port(self):
        return self._conn_key.port

    @property
    def ssl(self):
        return self._conn_key.ssl

    def __str__(self):
        return ('Cannot connect to host {0.host}:{0.port} ssl:{0.ssl} [{1}]'
                .format(self._conn_key, self.strerror))

class ClientProxyConnectionError(ClientConnectorError):
    """Proxy connection error.

    Raised in :class:`aiohttp.connector.TCPConnector` if
        connection to proxy can not be established.
    """

class ServerConnectionError(ClientConnectionError):
    """Server connection errors."""

class ServerDisconnectedError(ServerConnectionError):
    """Server disconnected."""

    def __init__(self, message=None):
        self.message = message

class ServerTimeoutError(ServerConnectionError, asyncio.TimeoutError):
    """Server timeout error."""

class ServerFingerprintMismatch(ServerConnectionError):
    """SSL certificate does not match expected fingerprint."""

    def __init__(self, expected, got, host, port):
        self.expected = expected
        self.got = got
        self.host = host
        self.port = port

    def __repr__(self):
        return '<{} expected={} got={} host={} port={}>'.format(
            self.__class__.__name__, self.expected, self.got,
            self.host, self.port)

class ClientPayloadError(ClientError):
    """Response payload error."""


text:
package eu.qualimaster.common.signal;

import eu.qualimaster.base.serializer.KryoSwitchTupleSerializer;

/**
 * Record the signal states.
 * @author Cui Qin
 *
 */

public class SignalStates {
    private static SignalStates signalStatesInstance;
    private static boolean isActiveOrgINT = true;
    private static boolean isActiveTrgINT = false;
    private static boolean isActiveOrgEND = true;
    private static boolean isActiveTrgEND = false;
    private static boolean isPassivateTrgINT = false;
    private static boolean isPassivateOrgINT = false;
    private static boolean isTransferringTrgINT = false;
    private static boolean isTransferringOrgINT = false;
    private static boolean isEmitOrgEND = true;
    private static boolean isEmitTrgEND = false;
    private static boolean isTransferAll = false;
    private static boolean isEmitOrgPRE = true;
    private static boolean isEmitTrgPRE = false;
    private static boolean isDataSynExisted = false;
    // ---to be changed
    private static boolean isBothPRE = false;
    private static boolean isEmitPRE = true;
    // ---to be changed
    private static long firstId = 0;
    private static int numTransferredData = 0;
    private static long lastProcessedId = 0;
    private static long lastEmittedId = 0;
    private static long headId = 0;
    private static long algStartPoint = 0;
    private static int targetPort = 6027;
    private static KryoSwitchTupleSerializer kryoSerOrgINT = null;
    private static int synQueueSizeOrgINT = 10;
    private static int synQueueSizeTrgINT = 50;

    /**
     * Constructor for the class.
     */
    private SignalStates() {
    }

    /**
     * Returns the instance of the singleton class.
     *
     * @return the instance of the singleton class
     */
    public static SignalStates getInstance() {
        if (null == signalStatesInstance) {
            signalStatesInstance = new SignalStates();
        }
        return signalStatesInstance;
    }

    /**
     * Initialize the initial values of the signal states.
     */
    public static void init() {
        isActiveOrgINT = true;
        isActiveTrgINT = false;
        isActiveOrgEND = true;
        isActiveTrgEND = false;
        isPassivateTrgINT = false;
        isPassivateOrgINT = false;
        isTransferringTrgINT = false;
        isTransferringOrgINT = false;
        isEmitOrgEND = true; // initially the original end node emits
        isEmitTrgEND = false; // initially the target end node is disabled
                                  // to emit
        isDataSynExisted = false;
        isTransferAll = false;
        isEmitOrgPRE = true;
        isEmitTrgPRE = false;
        isBothPRE = false;
        isEmitPRE = true;
        firstId = 0;
        numTransferredData = 0;
        lastProcessedId = 0;
        lastEmittedId = 0;
        headId = 0;
        targetPort = 6027;
    }

    /**
     * Return whether it is passivate in the target intermediary node.
     *
     * @return true it is passivate; otherwise false
     */
    public static boolean isPassivateTrgINT() {
        return isPassivateTrgINT;
    }

    /**
     * Set the state of whether it is passivate in the target intermediary node.
     *
     * @param isPassivateTrgINT
     *            true it is passivate; otherwise
     *            false
     */
    public static void setPassivateTrgINT(boolean isPassivateTrgINT) {
        SignalStates.isPassivateTrgINT = isPassivateTrgINT;
    }

    /**
     * Return whether it is passivate in the original intermediary node.
     *
     * @return true it is passivate; otherwise false
     */
    public static boolean isPassivateOrgINT() {
        return isPassivateOrgINT;
    }

    /**
     * Set the state of whether it is passivate in the original intermediary
     * node.
     *
     * @param isPassivateOrgINT
     *            true it is passivate; otherwise
     *            false
     */
    public static void setPassivateOrgINT(boolean isPassivateOrgINT) {
        SignalStates.isPassivateOrgINT = isPassivateOrgINT;
    }

    /**
     * Return whether it is transferring, used in the target intermediary node.
     *
     * @return true it is transferring; otherwise
     *         false
     */
    public static boolean isTransferringTrgINT() {
        return isTransferringTrgINT;
    }

    /**
     * Set the state of transferring in the target intermediary node.
     *
     * @param isTransferringTrgINT
     *            true it is transferring; otherwise
     *            false
     */
    public static void setTransferringTrgINT(boolean isTransferringTrgINT) {
        SignalStates.isTransferringTrgINT = isTransferringTrgINT;
    }

    /**
     * Return whether it is transferring, used in the original intermediary
     * node.
     *
     * @return true it is transferring; otherwise
     *         false
     */
    public static boolean isTransferringOrgINT() {
        return isTransferringOrgINT;
    }

    /**
     * Set the state of transferring in the original intermediary node.
     *
     * @param isTransferringOrgINT
     *            true it is transferring; otherwise
     *            false
     */
    public static void setTransferringOrgINT(boolean isTransferringOrgINT) {
        SignalStates.isTransferringOrgINT = isTransferringOrgINT;
    }

    /**
     * Return the id of the first tuple to be transferred, used in the target
     * intermediary node.
     *
     * @return the id of the first tuple to be transferred, used the target
     *         intermediary node
     */
    public static long getFirstId() {
        return firstId;
    }

    /**
     * Record the id of the first tuple to be transferred, used in the target
     * intermediary node.
     *
     * @param firstId
     *            the id of the first tuple to be transferred, used in the
     *            target intermediary node
     */
    public static void setFirstId(long firstId) {
        SignalStates.firstId = firstId;
    }

    /**
     * Return whether it is emitting in the original end node.
     *
     * @return true it is emitting; otherwise false.
     */
    public static boolean isEmitOrgEND() {
        return isEmitOrgEND;
    }

    /**
     * Sets the state of whether it is emitting in the original end node.
     *
     * @param isEmittingOrgEND
     *            true it is emitting; otherwise false
     *            .
     */
    public static void setEmitOrgEND(boolean isEmittingOrgEND) {
        SignalStates.isEmitOrgEND = isEmittingOrgEND;
    }

    /**
     * Return whether it is emitting in the target end node.
     *
     * @return true it is emitting; otherwise false.
     */
    public static boolean isEmitTrgEND() {
        return isEmitTrgEND;
    }

    /**
     * Sets the state of whether it is emitting in the target end node.
     *
     * @param isEmittingTrgEND
     *            true it is emitting; otherwise false
     *            .
     */
    public static void setEmitTrgEND(boolean isEmittingTrgEND) {
        SignalStates.isEmitTrgEND = isEmittingTrgEND;
    }

    /**
     * Return the number of data items to be transferred.
     *
     * @return the number of data items to be transferred
     */
    public static int getNumTransferredData() {
        return numTransferredData;
    }

    /**
     * Sets the number of data items to be transferred.
     *
     * @param numTransferredData
     *            the number of data items to be transferred
     */
    public static void setNumTransferredData(int numTransferredData) {
        SignalStates.numTransferredData = numTransferredData;
    }

    /**
     * Return the id of the last processed tuple.
     *
     * @return the last processed id
     */
    public static long getLastProcessedId() {
        return lastProcessedId;
    }

    /**
     * Set the id of the last processed tuple.
     *
     * @param lastProcessedId
     *            the last processed id
     */
    public static void setLastProcessedId(long lastProcessedId) {
        SignalStates.lastProcessedId = lastProcessedId;
    }

    /**
     * Return the id of the last emitted tuple.
     *
     * @return the id of the last emitted tuple
     */
    public static long getLastEmittedId() {
        return lastEmittedId;
    }

    /**
     * Set the id of the last emitted tuple.
     *
     * @param lastEmittedId
     *            the id of the last emitted tuple
     */
    public static void setLastEmittedId(long lastEmittedId) {
        SignalStates.lastEmittedId = lastEmittedId;
    }

    /**
     * Return the id of the first tuple to be transferred.
     *
     * @return the id of the first tuple to be transferred
     */
    public static long getHeadId() {
        return headId;
    }

    /**
     * Set the id of the first tuple to be transferred.
     *
     * @param headId
     *            the id of the first tuple to be transferred
     */
    public static void setHeadId(long headId) {
        SignalStates.headId = headId;
    }

    /**
     * Return whether it is transferring all tuples.
     *
     * @return true it is transferring all tuples; otherwise
     *         false
     */
    public static boolean isTransferAll() {
        return isTransferAll;
    }

    /**
     * Set the state of whether it is transferring all tuples.
     *
     * @param isTransferAll
     *            true it is transferring all tuples; otherwise
     *            false
     */
    public static void setTransferAll(boolean isTransferAll) {
        SignalStates.isTransferAll = isTransferAll;
    }

    /**
     * Return the timestamp when the original algorithm is started to process
     * tuples.
     *
     * @return the timestamp when the original algorithm is started to process
     *         tuples
     */
    public static long getAlgStartPoint() {
        return algStartPoint;
    }

    /**
     * Set the timestamp when the original algorithm is started to process
     * tuples.
     *
     * @param algStartPoint
     *            the timestamp when the original algorithm is started to
     *            process tuples
     */
    public static void setAlgStartPoint(long algStartPoint) {
        SignalStates.algStartPoint = algStartPoint;
    }

    /**
     * Return the port of the target node.
     *
     * @return the port of the target node
     */
    public static int getTargetPort() {
        return targetPort;
    }

    /**
     * Set the port of the target node.
     *
     * @param targetPort
     *            the port of the target node
     */
    public static void setTargetPort(int targetPort) {
        SignalStates.targetPort = targetPort;
    }

    /**
     * Return the kryo serializer for the original intermediary node.
     *
     * @return the kryo serializer
     */
    public static KryoSwitchTupleSerializer getKryoSerOrgINT() {
        return kryoSerOrgINT;
    }

    /**
     * Set the kryo serializer for the original intermediary node.
     *
     * @param kryoSerOrgINT
     *            the kryo serializer
     */
    public static void setKryoSerOrgINT(KryoSwitchTupleSerializer kryoSerOrgINT) {
        SignalStates.kryoSerOrgINT = kryoSerOrgINT;
    }

    /**
     * Return the size of the synchronized queue in the original intermediary
     * node.
     *
     * @return the size of the synchronized queue
     */
    public static int getSynQueueSizeOrgINT() {
        return synQueueSizeOrgINT;
    }

    /**
     * Set the size of the synchronized queue in the original intermediary node.
     *
     * @param synQueueSizeOrgINT
     *            the size of the synchronized queue
     */
    public static void setSynQueueSizeOrgINT(int synQueueSizeOrgINT) {
        SignalStates.synQueueSizeOrgINT = synQueueSizeOrgINT;
    }

    /**
     * Return the size of the synchronized queue in the target intermediary
     * node.
     *
     * @return the size of the synchronized queue
     */
    public static int getSynQueueSizeTrgINT() {
        return synQueueSizeTrgINT;
    }

    /**
     * Set the size of the synchronized queue in the target intermediary node.
     *
     * @param synQueueSizeTrgINT
     *            the size of the synchronized queue
     */
    public static void setSynQueueSizeTrgINT(int synQueueSizeTrgINT) {
        SignalStates.synQueueSizeTrgINT = synQueueSizeTrgINT;
    }

    /**
     * Return whether the original intermediary node is active.
     *
     * @return true it is active, otherwise false
     */
    public static boolean isActiveOrgINT() {
        return isActiveOrgINT;
    }

    /**
     * Set the state of whether the original intermediary node is active.
     *
     * @param isActiveOrgINT
     *            true it is active, otherwise false
     */
    public static void setActiveOrgINT(boolean isActiveOrgINT) {
        SignalStates.isActiveOrgINT = isActiveOrgINT;
    }

    /**
     * Return whether the target intermediary node is active.
     *
     * @return true it is active, otherwise false
     */
    public static boolean isActiveTrgINT() {
        return isActiveTrgINT;
    }

    /**
     * Set the state of whether the target intermediary node is active.
     *
     * @param isActiveTrgINT
     *            true it is active, otherwise false
     */
    public static void setActiveTrgINT(boolean isActiveTrgINT) {
        SignalStates.isActiveTrgINT = isActiveTrgINT;
    }

    /**
     * Return whether the data stream to the original algorithm is enabled.
     *
     * @return true the data stream to the original algorithm is
     *         enabled, otherwise false
     */
    public static boolean isEmitOrgPRE() {
        return isEmitOrgPRE;
    }

    /**
     * Set the state of whether the data stream to the original algorithm is
     * enabled.
     *
     * @param isOrgEmitPRE
     *            true the data stream to the original algorithm is
     *            enabled, otherwise false
     */
    public static void setEmitOrgPRE(boolean isOrgEmitPRE) {
        SignalStates.isEmitOrgPRE = isOrgEmitPRE;
    }

    /**
     * Return whether the data stream to the target algorithm is enabled.
     *
     * @return true the data stream to the target algorithm is
     *         enabled, otherwise false
     */
    public static boolean isEmitTrgPRE() {
        return isEmitTrgPRE;
    }

    /**
     * Set the state of whether the data stream to the target algorithm is
     * enabled.
     *
     * @param isTrgEmitPRE
     *            true the data stream to the target algorithm is
     *            enabled, otherwise false
     */
    public static void setEmitTrgPRE(boolean isTrgEmitPRE) {
        SignalStates.isEmitTrgPRE = isTrgEmitPRE;
    }

    /**
     * Return whether both algorithms emit data in parallel.
     *
     * @return true both algorithms emit data, otherwise
     *         false
     */
    public static boolean isBothPRE() {
        return isBothPRE;
    }

    /**
     * Set the state of whether both algorithms emit data in parallel.
     *
     * @param isBothPRE
     *            true both algorithms emit data, otherwise
     *            false
     */
    public static void setBothPRE(boolean isBothPRE) {
        SignalStates.isBothPRE = isBothPRE;
    }

    /**
     * Return whether it shall emit data.
     *
     * @return true it shall emit data, otherwise
     *         false
     */
    public static boolean isEmitPRE() {
        return isEmitPRE;
    }

    /**
     * Set the state of whether it shall emit data.
     *
     * @param isEmitPRE
     *            true it shall emit data, otherwise
     *            false
     */
    public static void setEmitPRE(boolean isEmitPRE) {
        SignalStates.isEmitPRE = isEmitPRE;
    }

    /**
     * Return whether the original end node is active.
     *
     * @return true it is active, otherwise false
     */
    public static boolean isActiveOrgEND() {
        return isActiveOrgEND;
    }

    /**
     * Set the state of whether the original end node is active.
     *
     * @param isActiveOrgEND
     *            true it is active, otherwise false
     */
    public static void setActiveOrgEND(boolean isActiveOrgEND) {
        SignalStates.isActiveOrgEND = isActiveOrgEND;
    }

    /**
     * Return whether the target end node is active.
     *
     * @return true it is active, otherwise false
     */
    public static boolean isActiveTrgEND() {
        return isActiveTrgEND;
    }

    /**
     * Set the state of whether the target end node is active.
     *
     * @param isActiveTrgEND
     *            true it is active, otherwise false
     */
    public static void setActiveTrgEND(boolean isActiveTrgEND) {
        SignalStates.isActiveTrgEND = isActiveTrgEND;
    }

    /**
     * Return whether there is data synchronization existed in the switch variant.
     * @return true it is existed, otherwise false
     */
    public static boolean isDataSynExisted() {
        return isDataSynExisted;
    }

    /**
     * Set the state of whether there is data transfer existed in the switch variant.
     * @param isDataSynExisted true it is existed, otherwise false
     */
    public static void setDataSynExisted(boolean isDataSynExisted) {
        SignalStates.isDataSynExisted = isDataSynExisted;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#import "RCTTextField.h"

#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTUtils.h"
#import "UIView+React.h"

@implementation RCTTextField
{
  RCTEventDispatcher *_eventDispatcher;
  NSMutableArray *_reactSubviews;
  BOOL _jsRequestingFirstResponder;
}

- (instancetype)initWithEventDispatcher:(RCTEventDispatcher *)eventDispatcher
{
  if ((self = [super initWithFrame:CGRectZero])) {

    _eventDispatcher = eventDispatcher;
    [self addTarget:self action:@selector(_textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
    [self addTarget:self action:@selector(_textFieldBeginEditing) forControlEvents:UIControlEventEditingDidBegin];
    [self addTarget:self action:@selector(_textFieldEndEditing) forControlEvents:UIControlEventEditingDidEnd];
    [self addTarget:self action:@selector(_textFieldSubmitEditing) forControlEvents:UIControlEventEditingDidEndOnExit];
    _reactSubviews = [[NSMutableArray alloc] init];
  }
  return self;
}

- (void)setText:(NSString *)text
{
  if (![text isEqualToString:self.text]) {
    [super setText:text];
  }
}

static void RCTUpdatePlaceholder(RCTTextField *self)
{
  if (self.placeholder.length > 0 && self.placeholderTextColor) {
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder
                                                                 attributes:@{
                                                                              NSForegroundColorAttributeName : self.placeholderTextColor
                                                                              }];
  } else if (self.placeholder.length) {
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder];
  }
}

- (void)setPlaceholderTextColor:(UIColor *)placeholderTextColor
{
  _placeholderTextColor = placeholderTextColor;
  RCTUpdatePlaceholder(self);
}

- (void)setPlaceholder:(NSString *)placeholder
{
  super.placeholder = placeholder;
  RCTUpdatePlaceholder(self);
}

- (NSArray *)reactSubviews
{
  // TODO: do we support subviews of textfield in React?
  // In any case, we should have a better approach than manually
  // maintaining array in each view subclass like this
  return _reactSubviews;
}

- (void)removeReactSubview:(UIView *)subview
{
  // TODO: this is a bit broken - if the TextField inserts any of
  // its own views below or between React's, the indices won't match
  [_reactSubviews removeObject:subview];
  [subview removeFromSuperview];
}

- (void)insertReactSubview:(UIView *)view atIndex:(NSInteger)atIndex
{
  // TODO: this is a bit broken - if the TextField inserts any of
  // its own views below or between React's, the indices won't match
  [_reactSubviews insertObject:view atIndex:atIndex];
  [super insertSubview:view atIndex:atIndex];
}

- (CGRect)caretRectForPosition:(UITextPosition *)position
{
  if (_caretHidden) {
    return CGRectZero;
  }
  return [super caretRectForPosition:position];
}

- (CGRect)textRectForBounds:(CGRect)bounds
{
  CGRect rect = [super textRectForBounds:bounds];
  return UIEdgeInsetsInsetRect(rect, _contentInset);
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
  return [self textRectForBounds:bounds];
}

- (void)setAutoCorrect:(BOOL)autoCorrect
{
  self.autocorrectionType = (autoCorrect ? UITextAutocorrectionTypeYes : UITextAutocorrectionTypeNo);
}

- (BOOL)autoCorrect
{
  return self.autocorrectionType == UITextAutocorrectionTypeYes;
}

#define RCT_TEXT_EVENT_HANDLER(delegateMethod, eventName) \
- (void)delegateMethod                                    \
{                                                         \
  [_eventDispatcher sendTextEventWithType:eventName       \
                                 reactTag:self.reactTag   \
                                     text:self.text];     \
}

RCT_TEXT_EVENT_HANDLER(_textFieldDidChange, RCTTextEventTypeChange)
RCT_TEXT_EVENT_HANDLER(_textFieldEndEditing, RCTTextEventTypeEnd)
RCT_TEXT_EVENT_HANDLER(_textFieldSubmitEditing, RCTTextEventTypeSubmit)

- (void)_textFieldBeginEditing
{
  if (_selectTextOnFocus) {
    dispatch_async(dispatch_get_main_queue(), ^{
      [self selectAll:nil];
    });
  }
  [_eventDispatcher sendTextEventWithType:RCTTextEventTypeFocus
                                 reactTag:self.reactTag
                                     text:self.text];
}

// TODO: we should support shouldChangeTextInRect (see UITextFieldDelegate)

- (BOOL)becomeFirstResponder
{
  _jsRequestingFirstResponder = YES;
  BOOL result = [super becomeFirstResponder];
  _jsRequestingFirstResponder = NO;
  return result;
}

- (BOOL)resignFirstResponder
{
  BOOL result = [super resignFirstResponder];
  if (result)
  {
    [_eventDispatcher sendTextEventWithType:RCTTextEventTypeBlur
                                   reactTag:self.reactTag
                                       text:self.text];
  }
  return result;
}

- (BOOL)canBecomeFirstResponder
{
  return _jsRequestingFirstResponder;
}

@end


text:
package com.elmakers.mine.bukkit.utility.platform.v1_14;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;

import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.entity.EntityExtraData;
import com.elmakers.mine.bukkit.utility.platform.Platform;
import com.elmakers.mine.bukkit.utility.platform.v1_14.entity.EntityCatData;
import com.elmakers.mine.bukkit.utility.platform.v1_14.entity.EntityEndermiteData;
import com.elmakers.mine.bukkit.utility.platform.v1_14.entity.EntityFoxData;
import com.elmakers.mine.bukkit.utility.platform.v1_14.entity.EntityPhantomData;
import com.elmakers.mine.bukkit.utility.platform.v1_14.entity.EntityVillagerData;

public class EntityUtils extends com.elmakers.mine.bukkit.utility.platform.v1_13.EntityUtils  {
    public EntityUtils(final Platform platform) {
        super(platform);
    }

    @Override
    public EntityExtraData getExtraData(MageController controller, Entity entity) {
        switch (entity.getType()) {
            case FOX:
                return new EntityFoxData(entity);
            case CAT:
                return new EntityCatData(entity);
            case PHANTOM:
                return new EntityPhantomData(entity);
            case ENDERMITE:
                return new EntityEndermiteData(entity);
            case VILLAGER:
                return new EntityVillagerData(entity);
            default:
                return super.getExtraData(controller, entity);
        }
    }

    @Override
    public EntityExtraData getExtraData(MageController controller, EntityType type, ConfigurationSection parameters) {
        switch (type) {
            case CAT:
                return new EntityCatData(parameters, controller);
            case FOX:
                return new EntityFoxData(parameters, controller);
            case PHANTOM:
                return new EntityPhantomData(parameters);
            case ENDERMITE:
                return new EntityEndermiteData(parameters);
            case VILLAGER:
                return new EntityVillagerData(parameters, controller);
            default:
                return super.getExtraData(controller, type, parameters);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Visualization recommender</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="styles.css"/>

Visualization recommender

This demo aims to show how it's possible to infer which types of visualizations can be rendered from a JSON dataset, and with which data field(s).

It's based on the work of the Interactive Data Lab and especially on their tools Datalib, Voyager, vega-lite-ui, as well as the research document Voyager: Exploratory Analysis via Faceted Browsing of Visualization Recommendations published in 2015.

      <footnote>
Developed by
Clément Prod'homme

Source
</footnote>

        <input v-model="url"
               @keyup.enter="computeRecommendations()"
               type="text"
               class="input"
               placeholder="Enter the URL of a JSON dataset here"
        />
        <button class="button" @click="computeRecommendations()">
          Let's go
        </button>

          Error: Unable to fetch or parse the dataset. Make sure you load a JSON file and that it's just an array. See the console.

X

Type of charts

                {{chart.name}}

Fields

              First field:

                {{field.name}}

                Second field:

                  {{field.name}}

Start by entering an URL above

Dataset

                  {{field.name}}
                  ({{field.type}})

                  {{row[field.name]}}

    </app>


text:
use std::ffi::{CString, NulError};
use std::ptr;
use std::os::raw::{c_char,c_int};

use video::WindowRef;
use get_error;

use sys::messagebox as ll;

bitflags! {
    pub flags MessageBoxFlag: u32 {
        const MESSAGEBOX_ERROR =
            ::sys::messagebox::SDL_MessageBoxFlags::SDL_MESSAGEBOX_ERROR as u32,
        const MESSAGEBOX_WARNING =
            ::sys::messagebox::SDL_MessageBoxFlags::SDL_MESSAGEBOX_WARNING as u32,
        const MESSAGEBOX_INFORMATION =
            ::sys::messagebox::SDL_MessageBoxFlags::SDL_MESSAGEBOX_INFORMATION as u32
    }
}

bitflags! {
    pub flags MessageBoxButtonFlag: u32 {
        const MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT =
            ::sys::messagebox::SDL_MessageBoxButtonFlags::SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT as u32,
        const MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT =
            ::sys::messagebox::SDL_MessageBoxButtonFlags::SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT as u32,
        const MESSAGEBOX_BUTTON_NOTHING = 0
    }
}

#[derive(Debug)]
pub struct MessageBoxColorScheme {
    pub background:(u8,u8,u8),
    pub text:(u8,u8,u8),
    pub button_border:(u8,u8,u8),
    pub button_background:(u8,u8,u8),
    pub button_selected:(u8,u8,u8)
}

/// button_id is the integer that will be returned
/// by show_message_box. It is not sed by SDL2,
/// and should only be used to know which button has been triggered
#[derive(Debug)]
pub struct ButtonData<'a> {
    pub flags:MessageBoxButtonFlag,
    pub button_id:i32,
    pub text:&'a str
}

#[derive(Debug)]
pub enum ClickedButton<'a> {
    CloseButton,
    CustomButton(&'a ButtonData<'a>)
}

impl From<MessageBoxColorScheme> for [ll::SDL_MessageBoxColor ; 5] {
    fn from(scheme:MessageBoxColorScheme) -> [ll::SDL_MessageBoxColor ; 5] {
        fn to_message_box_color(t:(u8,u8,u8)) -> ll::SDL_MessageBoxColor {
            ll::SDL_MessageBoxColor {
                r:t.0,
                g:t.1,
                b:t.2
            }
        };
        [to_message_box_color(scheme.background),
        to_message_box_color(scheme.text),
        to_message_box_color(scheme.button_border),
        to_message_box_color(scheme.button_background),
        to_message_box_color(scheme.button_selected)]
    }
}

#[derive(Debug)]
pub enum ShowMessageError {
    InvalidTitle(NulError),
    InvalidMessage(NulError),
    /// Second argument of the tuple (i32) corresponds to the
    /// first button_id having an error
    InvalidButton(NulError,i32),
    SdlError(String),
}

/// Show a simple message box, meant to be informative only.
///
/// There is no way to know if the user clicked "Ok" or closed the message box,
/// If you want to retrieve which button was clicked and customize a bit more
/// your message box, use `show_message_box` instead.
pub fn show_simple_message_box(flags: MessageBoxFlag, title: &str,
        message: &str, window: Option<&WindowRef>)
        -> Result<(), ShowMessageError> {
    use self::ShowMessageError::*;
    let result = unsafe {
        let title = match CString::new(title) {
            Ok(s) => s,
            Err(err) => return Err(InvalidTitle(err)),
        };
        let message = match CString::new(message) {
            Ok(s) => s,
            Err(err) => return Err(InvalidMessage(err)),
        };
        ll::SDL_ShowSimpleMessageBox(
            flags.bits(),
            title.as_ptr() as *const c_char,
            message.as_ptr() as *const c_char,
            window.map_or(ptr::null_mut(), |win| win.raw())
        )
    } == 0;

    if result {
        Ok(())
    } else {
        Err(SdlError(get_error()))
    }
}

/// Show a customizable message box.
///
/// An array of buttons is required for it to work. The array can be empty,
/// but it will have no button beside the close button.
///
/// On success, it will return either the button clicked or the close button.
/// Note that the variant of the `ClickedButton` enum will also be returned if the message box
/// has been forcefully closed (Alt-F4, ...)
///
pub fn show_message_box<'a>(flags:MessageBoxFlag, buttons:&'a [ButtonData], title:&str,
    message:&str, window:Option<&WindowRef>, scheme:Option<MessageBoxColorScheme>)
    -> Result<ClickedButton<'a>,ShowMessageError> {
    use self::ShowMessageError::*;
    let mut button_id : c_int = 0;
    let title = match CString::new(title) {
        Ok(s) => s,
        Err(err) => return Err(InvalidTitle(err)),
    };
    let message = match CString::new(message) {
        Ok(s) => s,
        Err(err) => return Err(InvalidMessage(err)),
    };
    let button_texts : Result<Vec<_>,(_,i32)> = buttons.iter().map(|b|{
        CString::new(b.text).map_err(|e|(e,b.button_id))
    }).collect(); // Create CString for every button; and catch any CString Error
    let button_texts = match button_texts {
        Ok(b) => b,
        Err(e) => return Err(InvalidButton(e.0,e.1))
    };
    let raw_buttons : Vec<ll::SDL_MessageBoxButtonData> =
        buttons.iter().zip(button_texts.iter()).map(|(b,b_text)|{
        ll::SDL_MessageBoxButtonData {
            flags:b.flags.bits(),
            buttonid:b.button_id as c_int,
            text:b_text.as_ptr()
        }
    }).collect();
    let result = unsafe {
        let msg_box_data = ll::SDL_MessageBoxData {
            flags:flags.bits(),
            window:window.map_or(ptr::null_mut(), |win| win.raw()),
            title: title.as_ptr() as *const c_char,
            message: message.as_ptr() as *const c_char,
            numbuttons: raw_buttons.len() as c_int,
            buttons: raw_buttons.as_ptr(),
            color_scheme: if let Some(scheme) = scheme {
                &ll::SDL_MessageBoxColorScheme {
                    colors:From::from(scheme)
                } as *const _
            } else {
                ptr::null()
            }
        };
        ll::SDL_ShowMessageBox(
            &msg_box_data as *const _,
            &mut button_id as &mut _
        )
    } == 0;
    if result {
        match button_id {
            -1 => Ok(ClickedButton::CloseButton),
            id => {
                let button = buttons.iter().find(|b| b.button_id == id);
                Ok(ClickedButton::CustomButton(button.unwrap()))
            }
        }
    } else {
        Err(SdlError(get_error()))
    }
}


text:
using NQuery.Text;

namespace NQuery.Authoring.BraceMatching
{
    public struct BraceMatchingResult
    {
        public static readonly BraceMatchingResult None = new();

        public BraceMatchingResult(TextSpan left, TextSpan right)
        {
            IsValid = true;
            Left = left;
            Right = right;
        }

        public bool IsValid { get; }

        public TextSpan Left { get; }

        public TextSpan Right { get; }
    }
}


text:
<package>

  <name>crane_moveit_config</name>
  <version>0.2.0</version>
  <description>
     An automatically generated package with all the configuration and launch files for using the robospect with the MoveIt Motion Planning Framework
  </description>
  <author email="assistant@moveit.ros.org">MoveIt Setup Assistant</author>
  <maintainer email="assistant@moveit.ros.org">MoveIt Setup Assistant</maintainer>

  <license>BSD</license>

  <url type="website">http://moveit.ros.org/</url>
  <url type="bugtracker">https://github.com/ros-planning/moveit_setup_assistant/issues</url>
  <url type="repository">https://github.com/ros-planning/moveit_setup_assistant</url>

  <run_depend>moveit_ros_move_group</run_depend>
  <run_depend>moveit_planners_ompl</run_depend>
  <run_depend>moveit_ros_visualization</run_depend>
  <run_depend>joint_state_publisher</run_depend>
  <run_depend>robot_state_publisher</run_depend>
  <run_depend>xacro</run_depend>
  <build_depend>robospect_description</build_depend>
  <run_depend>robospect_description</run_depend>

  <buildtool_depend>catkin</buildtool_depend>

</package>


text:
var parser = require('../src/training_parser.js');
var api = require('../src/api.js');
var train = require('../src/training_server.js');
var template = require('../src/to_template.js');

var store_templates = {templates: [], size: 0};

function get_next_template(size){

    if(store_templates.size != size){
        var templates = [];
        templates = parser.get_templates(size,templates);
        console.log('i am here');

        store_templates.size = size;
        store_templates.templates = [];
        for(var i = 0; i < templates.length; i++){
            store_templates.templates.push(templates[i].lisp_arr);
            //console.log(templates[i].template_arr);
        }
    }
    //return store_templates.templates;

    if(store_templates.templates.length)
        return store_templates.templates.pop();
    else
        return false;

}
var templates = [];
/*
 for(var i = 5; i<=30; i++){
 templates[i] = [];
 }
 templates[42] = [];
 size = 5;
 while(size<43){
 if(size > 30)
 size = 42;
 templates[size] = parser(size,templates[size]);
 size++;
 }
 */

size = 12;
//templates = parser(size,templates);
do {
    var t = get_next_template(size);
    console.log(t);
}
while(t)

//console.log(templates);
/*
setInterval(function() {

    if(size > 30)
            size = 11;

    var templates = [];
    templates = parser(size,templates,'fold');
    //templates = train(size,templates,'fold');
    size++;
}, 6000 );
*/
/*
var size = 12;
api.train(size, ["tfold"], function (problem ) {
    //fs.write(file_handle, '{"challenge": "'+ problem.challenge +'", "template": [' + arrtostr(template(problem.challenge))+"]},\n", null, 'ascii', function(err, written) {
    if(problem.challenge != undefined){
        //templ.challenge = problem.challenge;
        console.log(problem.challenge);
        console.log(template(problem.challenge));
    }
});
    */


text:
.class Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;
.super Ljava/lang/Object;
.source "InputMethodSubtypeSwitchingController.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "InputMethodAndSubtypeList"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList$1;
    }
.end annotation

# instance fields
.field private final mContext:Landroid/content/Context;

.field private final mPm:Landroid/content/pm/PackageManager;

.field private final mSettings:Lcom/android/internal/inputmethod/InputMethodUtils$InputMethodSettings;

.field private final mSortedImmis:Ljava/util/TreeMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/TreeMap",
            "<",
            "Landroid/view/inputmethod/InputMethodInfo;",
            "Ljava/util/List",
            "<",
            "Landroid/view/inputmethod/InputMethodSubtype;",
            ">;>;"
        }
    .end annotation
.end field

.field private final mSystemLocaleStr:Ljava/lang/String;

# direct methods
.method static synthetic -get0(Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;)Landroid/content/pm/PackageManager;
    .locals 1

    iget-object v0, p0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mPm:Landroid/content/pm/PackageManager;

    return-object v0
.end method

.method public constructor <init>(Landroid/content/Context;Lcom/android/internal/inputmethod/InputMethodUtils$InputMethodSettings;)V
    .locals 3
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "settings"    # Lcom/android/internal/inputmethod/InputMethodUtils$InputMethodSettings;

    .prologue
    .line 169
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 178
    new-instance v1, Ljava/util/TreeMap;

    .line 179
    new-instance v2, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList$1;

    invoke-direct {v2, p0}, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList$1;-><init>(Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;)V

    .line 178
    invoke-direct {v1, v2}, Ljava/util/TreeMap;-><init>(Ljava/util/Comparator;)V

    .line 177
    iput-object v1, p0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSortedImmis:Ljava/util/TreeMap;

    .line 170
    iput-object p1, p0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mContext:Landroid/content/Context;

    .line 171
    iput-object p2, p0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSettings:Lcom/android/internal/inputmethod/InputMethodUtils$InputMethodSettings;

    .line 172
    invoke-virtual {p1}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v1

    iput-object v1, p0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mPm:Landroid/content/pm/PackageManager;

    .line 173
    invoke-virtual {p1}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;

    move-result-object v1

    invoke-virtual {v1}, Landroid/content/res/Resources;->getConfiguration()Landroid/content/res/Configuration;

    move-result-object v1

    iget-object v0, v1, Landroid/content/res/Configuration;->locale:Ljava/util/Locale;

    .line 174
    .local v0, "locale":Ljava/util/Locale;
    if-eqz v0, :cond_0

    invoke-virtual {v0}, Ljava/util/Locale;->toString()Ljava/lang/String;

    move-result-object v1

    :goto_0
    iput-object v1, p0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSystemLocaleStr:Ljava/lang/String;

    .line 169
    return-void

    .line 174
    :cond_0
    const-string/jumbo v1, ""

    goto :goto_0
.end method

# virtual methods
.method public getSortedInputMethodAndSubtypeList()Ljava/util/List;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/List",
            "<",
            "Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$ImeSubtypeListItem;",
            ">;"
        }
    .end annotation

    .prologue
    const/4 v1, 0x0

    .line 196
    const/4 v0, 0x1

    invoke-virtual {p0, v0, v1, v1}, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->getSortedInputMethodAndSubtypeList(ZZZ)Ljava/util/List;

    move-result-object v0

    return-object v0
.end method

.method public getSortedInputMethodAndSubtypeList(ZZZ)Ljava/util/List;
    .locals 22
    .param p1, "showSubtypes"    # Z
    .param p2, "includeAuxiliarySubtypes"    # Z
    .param p3, "isScreenLocked"    # Z
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(ZZZ)",
            "Ljava/util/List",
            "<",
            "Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$ImeSubtypeListItem;",
            ">;"
        }
    .end annotation

    .prologue
    .line 202
    new-instance v15, Ljava/util/ArrayList;

    invoke-direct {v15}, Ljava/util/ArrayList;-><init>()V

    .line 204
    .local v15, "imList":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$ImeSubtypeListItem;>;"
    move-object/from16 v0, p0

    iget-object v1, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSettings:Lcom/android/internal/inputmethod/InputMethodUtils$InputMethodSettings;

    .line 205
    move-object/from16 v0, p0

    iget-object v6, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mContext:Landroid/content/Context;

    .line 204
    invoke-virtual {v1, v6}, Lcom/android/internal/inputmethod/InputMethodUtils$InputMethodSettings;->getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(Landroid/content/Context;)Ljava/util/HashMap;

    move-result-object v17

    .line 206
    .local v17, "immis":Ljava/util/HashMap;, "Ljava/util/HashMap<Landroid/view/inputmethod/InputMethodInfo;Ljava/util/List<Landroid/view/inputmethod/InputMethodSubtype;>;>;"
    if-eqz v17, :cond_0

    invoke-virtual/range {v17 .. v17}, Ljava/util/HashMap;->size()I

    move-result v1

    if-nez v1, :cond_1

    .line 207
    :cond_0
    invoke-static {}, Ljava/util/Collections;->emptyList()Ljava/util/List;

    move-result-object v1

    return-object v1

    .line 209
    :cond_1
    if-eqz p3, :cond_2

    if-eqz p2, :cond_2

    .line 213
    const/16 p2, 0x0

    .line 215
    .end local p2    # "includeAuxiliarySubtypes":Z
    :cond_2
    move-object/from16 v0, p0

    iget-object v1, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSortedImmis:Ljava/util/TreeMap;

    invoke-virtual {v1}, Ljava/util/TreeMap;->clear()V

    .line 216
    move-object/from16 v0, p0

    iget-object v1, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSortedImmis:Ljava/util/TreeMap;

    move-object/from16 v0, v17

    invoke-virtual {v1, v0}, Ljava/util/TreeMap;->putAll(Ljava/util/Map;)V

    .line 217
    move-object/from16 v0, p0

    iget-object v1, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSortedImmis:Ljava/util/TreeMap;

    invoke-virtual {v1}, Ljava/util/TreeMap;->keySet()Ljava/util/Set;

    move-result-object v1

    invoke-interface {v1}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v16

    .local v16, "imi$iterator":Ljava/util/Iterator;
    :cond_3
    :goto_0
    invoke-interface/range {v16 .. v16}, Ljava/util/Iterator;->hasNext()Z

    move-result v1

    if-eqz v1, :cond_9

    invoke-interface/range {v16 .. v16}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v4

    check-cast v4, Landroid/view/inputmethod/InputMethodInfo;

    .line 218
    .local v4, "imi":Landroid/view/inputmethod/InputMethodInfo;
    if-eqz v4, :cond_3

    .line 221
    move-object/from16 v0, v17

    invoke-virtual {v0, v4}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v14

    check-cast v14, Ljava/util/List;

    .line 222
    .local v14, "explicitlyOrImplicitlyEnabledSubtypeList":Ljava/util/List;, "Ljava/util/List<Landroid/view/inputmethod/InputMethodSubtype;>;"
    new-instance v13, Ljava/util/HashSet;

    invoke-direct {v13}, Ljava/util/HashSet;-><init>()V

    .line 223
    .local v13, "enabledSubtypeSet":Ljava/util/HashSet;, "Ljava/util/HashSet<Ljava/lang/String;>;"
    invoke-interface {v14}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v19

    .local v19, "subtype$iterator":Ljava/util/Iterator;
    :goto_1
    invoke-interface/range {v19 .. v19}, Ljava/util/Iterator;->hasNext()Z

    move-result v1

    if-eqz v1, :cond_4

    invoke-interface/range {v19 .. v19}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v18

    check-cast v18, Landroid/view/inputmethod/InputMethodSubtype;

    .line 224
    .local v18, "subtype":Landroid/view/inputmethod/InputMethodSubtype;
    invoke-virtual/range {v18 .. v18}, Landroid/view/inputmethod/InputMethodSubtype;->hashCode()I

    move-result v1

    invoke-static {v1}, Ljava/lang/String;->valueOf(I)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v13, v1}, Ljava/util/HashSet;->add(Ljava/lang/Object;)Z

    goto :goto_1

    .line 226
    .end local v18    # "subtype":Landroid/view/inputmethod/InputMethodSubtype;
    :cond_4
    move-object/from16 v0, p0

    iget-object v1, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mPm:Landroid/content/pm/PackageManager;

    invoke-virtual {v4, v1}, Landroid/view/inputmethod/InputMethodInfo;->loadLabel(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;

    move-result-object v2

    .line 227
    .local v2, "imeLabel":Ljava/lang/CharSequence;
    if-eqz p1, :cond_8

    invoke-virtual {v13}, Ljava/util/HashSet;->size()I

    move-result v1

    if-lez v1, :cond_8

    .line 228
    invoke-virtual {v4}, Landroid/view/inputmethod/InputMethodInfo;->getSubtypeCount()I

    move-result v20

    .line 232
    .local v20, "subtypeCount":I
    const/4 v5, 0x0

    .local v5, "j":I
    :goto_2
    move/from16 v0, v20

    if-ge v5, v0, :cond_3

    .line 233
    invoke-virtual {v4, v5}, Landroid/view/inputmethod/InputMethodInfo;->getSubtypeAt(I)Landroid/view/inputmethod/InputMethodSubtype;

    move-result-object v18

    .line 234
    .restart local v18    # "subtype":Landroid/view/inputmethod/InputMethodSubtype;
    invoke-virtual/range {v18 .. v18}, Landroid/view/inputmethod/InputMethodSubtype;->hashCode()I

    move-result v1

    invoke-static {v1}, Ljava/lang/String;->valueOf(I)Ljava/lang/String;

    move-result-object v21

    .line 236
    .local v21, "subtypeHashCode":Ljava/lang/String;
    move-object/from16 v0, v21

    invoke-virtual {v13, v0}, Ljava/util/HashSet;->contains(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_5

    .line 237
    if-nez p2, :cond_6

    invoke-virtual/range {v18 .. v18}, Landroid/view/inputmethod/InputMethodSubtype;->isAuxiliary()Z

    move-result v1

    if-eqz v1, :cond_6

    .line 232
    :cond_5
    :goto_3
    add-int/lit8 v5, v5, 0x1

    goto :goto_2

    .line 239
    :cond_6
    invoke-virtual/range {v18 .. v18}, Landroid/view/inputmethod/InputMethodSubtype;->overridesImplicitlyEnabledSubtype()Z

    move-result v1

    if-eqz v1, :cond_7

    const/4 v3, 0x0

    .line 242
    :goto_4
    new-instance v1, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$ImeSubtypeListItem;

    .line 243
    invoke-virtual/range {v18 .. v18}, Landroid/view/inputmethod/InputMethodSubtype;->getLocale()Ljava/lang/String;

    move-result-object v6

    move-object/from16 v0, p0

    iget-object v7, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSystemLocaleStr:Ljava/lang/String;

    .line 242
    invoke-direct/range {v1 .. v7}, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$ImeSubtypeListItem;-><init>(Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/view/inputmethod/InputMethodInfo;ILjava/lang/String;Ljava/lang/String;)V

    invoke-virtual {v15, v1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z

    .line 248
    move-object/from16 v0, v21

    invoke-virtual {v13, v0}, Ljava/util/HashSet;->remove(Ljava/lang/Object;)Z

    goto :goto_3

    .line 240
    :cond_7
    move-object/from16 v0, p0

    iget-object v1, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mContext:Landroid/content/Context;

    invoke-virtual {v4}, Landroid/view/inputmethod/InputMethodInfo;->getPackageName()Ljava/lang/String;

    move-result-object v6

    .line 241
    invoke-virtual {v4}, Landroid/view/inputmethod/InputMethodInfo;->getServiceInfo()Landroid/content/pm/ServiceInfo;

    move-result-object v7

    iget-object v7, v7, Landroid/content/pm/ServiceInfo;->applicationInfo:Landroid/content/pm/ApplicationInfo;

    .line 239
    move-object/from16 v0, v18

    invoke-virtual {v0, v1, v6, v7}, Landroid/view/inputmethod/InputMethodSubtype;->getDisplayName(Landroid/content/Context;Ljava/lang/String;Landroid/content/pm/ApplicationInfo;)Ljava/lang/CharSequence;

    move-result-object v3

    .local v3, "subtypeLabel":Ljava/lang/CharSequence;
    goto :goto_4

    .line 252
    .end local v3    # "subtypeLabel":Ljava/lang/CharSequence;
    .end local v5    # "j":I
    .end local v18    # "subtype":Landroid/view/inputmethod/InputMethodSubtype;
    .end local v20    # "subtypeCount":I
    .end local v21    # "subtypeHashCode":Ljava/lang/String;
    :cond_8
    new-instance v6, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$ImeSubtypeListItem;

    .line 253
    move-object/from16 v0, p0

    iget-object v12, v0, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$InputMethodAndSubtypeList;->mSystemLocaleStr:Ljava/lang/String;

    .line 252
    const/4 v8, 0x0

    const/4 v10, -0x1

    const/4 v11, 0x0

    move-object v7, v2

    move-object v9, v4

    invoke-direct/range {v6 .. v12}, Lcom/android/internal/inputmethod/InputMethodSubtypeSwitchingController$ImeSubtypeListItem;-><init>(Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/view/inputmethod/InputMethodInfo;ILjava/lang/String;Ljava/lang/String;)V

    invoke-virtual {v15, v6}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z

    goto/16 :goto_0

    .line 256
    .end local v2    # "imeLabel":Ljava/lang/CharSequence;
    .end local v4    # "imi":Landroid/view/inputmethod/InputMethodInfo;
    .end local v13    # "enabledSubtypeSet":Ljava/util/HashSet;, "Ljava/util/HashSet<Ljava/lang/String;>;"
    .end local v14    # "explicitlyOrImplicitlyEnabledSubtypeList":Ljava/util/List;, "Ljava/util/List<Landroid/view/inputmethod/InputMethodSubtype;>;"
    .end local v19    # "subtype$iterator":Ljava/util/Iterator;
    :cond_9
    invoke-static {v15}, Ljava/util/Collections;->sort(Ljava/util/List;)V

    .line 257
    return-object v15
.end method


text:
/*
In NativeScript, the app.css file is where you place CSS rules that
you would like to apply to your entire application. Check out
http://docs.nativescript.org/ui/styling for a full list of the CSS
selectors and properties you can use to style UI components.
*/

/*
In many cases you may want to use the NativeScript core theme instead
of writing your own CSS rules. For a full list of class names in the theme
refer to http://docs.nativescript.org/ui/theme.
*/
@import 'nativescript-theme-core/css/core.light.css';

.page-text {
   vertical-align: center;
   text-align: center;
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao;

import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.LeafQueueTemplateInfo.ConfItem;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class AutoQueueTemplatePropertiesInfo {

  private ArrayList<ConfItem> property =
      new ArrayList<>();

  public AutoQueueTemplatePropertiesInfo() {
  }

  public ArrayList<ConfItem> getProperty() {
    return property;
  }

  public void add(ConfItem confItem) {
    property.add(confItem);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="24dp"
        android:layout_marginTop="@dimen/drink_detail_recipe_margin"
        android:orientation="horizontal">

        <View
            android:id="@+id/color1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <View
            android:id="@+id/color2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <View
            android:id="@+id/color3"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <View
            android:id="@+id/color4"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp">

        <TextView
            android:id="@+id/history"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-light"
            android:textSize="18sp" />

        <Button
            android:id="@+id/wikipedia"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/button_drinks"
            android:fontFamily="sans-serif-light"
            android:textColor="@color/holo_blue_dark" />

        <TextView
            android:id="@+id/drinks_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="24sp"
            android:visibility="gone" />

    </LinearLayout>
</LinearLayout>


text:
\chapter{Introduction}\label{introduction}

An Introduction usually is used only to provide a background, a motivation and a short readers guide. In this document it is used to reproduce some information about writing a thesis and writing in \LaTeX. To get started, just delete this content and start writing your own.

\section{How to Organize your Thesis}
In this section some revision of a generic structure of a thesis will be given. Please note that the complete text can be found on:
\begin{quote}
	http://www.sce.carleton.ca/faculty/chinneck/thesis.html
\end{quote}
Translations to other languages are available too:
\begin{quote}
	http://www.sce.carleton.ca/faculty/chinneck/thesis/translations.html
\end{quote}
Please see also \cite{Leunen:Scholars:1992,Zuber-Skerritt:ThesisWriting:1986}.

\subsection{Introduction}

This is a general introduction to what the thesis is all about -- it is not just
a description of the contents of each section. Briefly summarize the question
(you will be stating the question in detail later), some of the reasons why it
is a worthwhile question, and perhaps give an overview of your main results.
This is a birds-eye view of the answers to the main questions answered in the
thesis (see above).

\subsection{Background Information (optional)}

A brief section giving background information may be necessary, especially if
your work spans two or more traditional fields. That means that your readers may
not have any experience with some of the material needed to follow your thesis,
so you need to give it to them. A different title than that given above is
usually better; e.g., 'A Brief Review of Frammis Algebra.'

\subsection{Review of the State of the Art}

Here you review the state of the art relevant to your thesis. Again, a different title is probably appropriate; e.g., 'State of the Art in Zylon Algorithms.' The idea is to present (critical analysis comes a little bit later) the major ideas in the state of the art right up to, but not including, your own personal brilliant ideas.

You organize this section by idea, and not by author or by publication. For example if there have been three important main approaches to Zylon Algorithms to date, you might organize subsections around these three approaches, if necessary:
\begin{itemize}
	\item[3.1] Iterative Approximation of Zylons
	\item[3.2] Statistical Weighting of Zylons
	\item[3.3] Graph-Theoretic Approaches to Zylon Manipulation
\end{itemize}

\subsection{Research Question or Problem Statement}

Engineering theses tend to refer to a 'problem' to be solved where other disciplines talk in terms of a 'question' to be answered. In either case, this section has three main parts:

\begin{enumerate}
	\item a concise statement of the question that your thesis tackles
	\item justification, by direct reference to section 3, that your question is previously unanswered
	\item discussion of why it is worthwhile to answer this question.
\end{enumerate}

Item 2 above is where you analyze the information which you presented in Section 3. For example, maybe your problem is to 'develop a Zylon algorithm capable of handling very large scale problems in reasonable time' (you would further describe what you mean by 'large scale' and 'reasonable time' in the problem statement). Now in your analysis of the state of the art you would show how each class of current approaches fails (i.e. can handle only small problems, or takes too much time). In the last part of this section you would explain why having a large-scale fast Zylon algorithm is useful; e.g., by describing applications where it can be used.

Since this is one of the sections that the readers are definitely looking for, highlight it by using the word 'problem' or 'question' in the title: e.g. 'Research Question' or 'Problem Statement', or maybe something more specific such as 'The Large-Scale Zylon Algorithm Problem.'

\subsection{Description of How You Solved the Problem or Answered the Question}

This part of the thesis is much more free-form. It may have one or several sections and subsections. But it all has only one purpose: to convince the examiners that you answered the question or solved the problem that you set for yourself in Section 4. So show what you did that is relevant to answering the question or solving the problem: if there were blind alleys and dead ends, do not include these, unless specifically relevant to the demonstration that you answered the thesis question.

\subsection{Conclusions}

You generally cover three things in the Conclusions section, and each of these usually merits a separate subsection:

\begin{enumerate}
	\item Conclusions
	\item Summary of Contributions
	\item Future Research
\end{enumerate}

Conclusions are not a rambling summary of the thesis: they are short, concise statements of the inferences that you have made because of your work. It helps to organize these as short numbered paragraphs, ordered from most to least important. All conclusions should be directly related to the research question stated in Section 4. Examples:

\begin{enumerate}
	\item The problem stated in Section 4 has been solved: as shown in Sections ? to ??, an algorithm capable of handling large-scale Zylon problems in reasonable time has been developed.
	\item The principal mechanism needed in the improved Zylon algorithm is the Grooty mechanism.
	\item Etc.
\end{enumerate}

The Summary of Contributions will be much sought and carefully read by the examiners. Here you list the contributions of new knowledge that your thesis makes. Of course, the thesis itself must substantiate any claims made here. There is often some overlap with the Conclusions, but that's okay. Concise numbered paragraphs are again best. Organize from most to least important. Examples:

\begin{enumerate}
	\item Developed a much quicker algorithm for large-scale Zylon problems.
	\item Demonstrated the first use of the Grooty mechanism for Zylon calculations.
	\item Etc.
\end{enumerate}

The Future Research subsection is included so that researchers picking up this work in future have the benefit of the ideas that you generated while you were working on the project. Again, concise numbered paragraphs are usually best.

\subsection{Appendices}

What goes in the appendices? Any material which impedes the smooth development of your presentation, but which is important to justify the results of a thesis. Generally it is material that is of too nitty-gritty a level of detail for inclusion in the main body of the thesis, but which should be available for perusal by the examiners to convince them sufficiently. Examples include program listings, immense tables of data, lengthy mathematical proofs or derivations, etc.

\subsection{Bibliography}

The list of references is closely tied to the review of the state of the art given in section 3. Most examiners scan your list of references looking for the important works in the field, so make sure they are listed and referred to in section 3. Truth be known, most examiners also look for their own publications if they are in the topic area of the thesis, so list these too. Besides, reading your examiner's papers usually gives you a clue as to the type of questions they are likely to ask.

All references given must be referred to in the main body of the thesis. Note the difference from a Bibliography, which may include works that are not directly referenced in the thesis. Organize the list of references either alphabetically by author surname (preferred), or by order of citation in the thesis.

\section{Revision: Writing in \LaTeX}
As thought in the seminars, \LaTeX is quite useful for writing a paper or a thesis. Nevertheless it comes with its own rules.

\subsection{Word processing with \LaTeX}
\label{sec:model:subsec:latex}

This document has already introduced the most important constructs of
\LaTeX. What is necessary to produce documents with \LaTeX is simple
any normal text editor and a \LaTeX distribution. This is commonly
installed on practically all UNIX-type systems; for Windows, an
excellent \LaTeX exists, called MikTeX, available from
\url{www.miktex.org}. Almost all distributions come with a large patch
of examples and introductory material; consult your local installation
for details.

Lots of supplementary and background information, FAQs, etc.\ is
available from the Comprehensive TeX Archive Network (CTAN); the
German mirror of which is \url{www.dante.de}.

\subsection{Tables in \LaTeX}
\label{sec:model:subsec:tables}
The table should be centred and should always have a caption positioned above it. A caption in a sentence form as well as in a short form must end with a period as seen in table~\ref{tab:sample}. Ideally the table can be understood sorely by the table and the caption itself. The parameters ``hbtp'' provide a list of priorities for the arrangement of the table: here, bottom, top, (next) page.

\begin{table}[hbtp]
  \caption{This caption has one line so it is centered.}\label{tab:sample}
  \centering
  \begin{tabular}{|c|c|}
    \hline
    Example column 1 & Example column 2 \\
    \hline
    Example text 1 & Example text 2 \\
    \hline
  \end{tabular}
\end{table}

\subsection{Figures in \LaTeX}
\label{sec:model:subsec:figures}
Note that a figure is a so-called floating object: it is moved around the actual text in order to best fit on a page. This is in strong contrast to some GUI-based word processing tools, where the placement of figures is usually more associated with luck than principle.

As figures float around, expressions like ``the following figure'' must never be used. Instead, figures need a caption, a label, and must be properly referenced in the main text. A figure caption is placed centred below the figure and describes the figure in (very) short. Again, ideally the figure can be understood sorely by the figure and the caption itself.

In general, only vector graphics in encapsulated postscript (EPS) or a similar format (SVG, PDF) should be included in any kind of text, as this allows arbitrary scaling, rotation etc.\ without any loss of quality. Bitmap formats (JPEG, GIF, \dots) should only be used if no other alternative exists --- basically the only case where bitmaps can be justified is when scanned pictures need to be included in a text, however, this should be avoided as hard as possible as the quality in usually not satisfactory. If a screen shot is needed a high resolution picture without visible fragments of a jpeg compression is allowed. Figures like the figure~\ref{fig:samplefig} (this is how you refer to figures correctly! the tilde is used as a non-breaking space) should always appear after the first referencing it.
\begin{figure}[hbtp]
 	 \centerline{\includegraphics[width=0.6\textwidth]{samplefig}}
	 {\caption{Network of transputers and the structure of individual
processes.}\label{fig:samplefig}}
\end{figure}

Smartphones have long become a central part of our lives. During the last decade
the usage of phones has changed from a simple tool to call other people on the
way to a source of information and entertainment. With the growing number of
applications the context where smartphones are used has bevome more and more
complex. Traditional smartphone interaction requieres one hand to hold the phone
and most likely your second hand to touch the screen.
Very often users find themselfs in situations where they have only one hand
available for using their smartphone. This requires a more complex way of
interaction than just a simple touch screen, especially as with growing display
size it is no longer possible to both hold the phone and reach every point on
the display at the same time only using one hand.

Free hand gesture recognition can improve user experience by providing a more
intuitive and effective way of using the smartphone, especially in situations
with limited hand access to the screen. A simple counter clockwise circle could
be used for decreasing the volume, an upwards stroke for zooming out of a map
etc.

Smartphones supply different kinds of sensors for measuring force, location and
orientation that can be used to track position and movement of the phone in
space. Unfortunatly all those contain bias and noise making it hard or alsmost
impossible to integragte over them and create trajectories in 3d space.
Therefore another more resistant approach is needed.

Today there are many ways to classify gestures from IMU values ranging from stochstical to neuroal approaches.

blablalaa über was die anderen schon gemacht haben

Commonlyused classifiers for gesture recognition are: k-nearest neighbours,
hiden markov models, finite state machine, neural network and support verctor
machines. \cite{Wu-CHeng:MultiModalGestureRecognition:2014}

In this thesis a specific kind of artificial neural network will be used called
Echo State Network (ESN). It belongs to the area of recurrent neural networks,
or more specific to the domain of reservoir computing. A huge amount of
interconnected neurons is used as an excitable medium (the reservoir) that can
be observed by a trained liear readout layer to minimize an error function. Echo
State Networks have first been introduced by Herbert Jaeger in 2001 and since
then enjoy growing interest within the neural network community. Training
traditional recurrent neural networks (RNNs) is prone to local maxima and very
time intesive. When training an ESN only few connections need to be learned,
reducing the needed time greatly.

\subsection{Related Work}


text:
  <pnc-header>
    <pnc-header-title>{{ detailCtrl.project.name || 'Empty' }}</pnc-header-title>
    <pnc-header-buttons>
      <button type="button" class="btn btn-lg btn-default" data-toggle="tooltip" title="Edit Project" ng-click="projectForm.$show()">
         Edit
      </button>
      <button type="button" class="btn btn-lg btn-danger disabled" data-toggle="tooltip" title="Delete Project">
         Delete
      </button>
    </pnc-header-buttons>
  </pnc-header>

  <form editable-form name="projectForm" class="form-horizontal" onbeforesave="detailCtrl.update()">

      Name

{{ detailCtrl.project.name || 'Empty' }}

      Description

{{ detailCtrl.project.description || 'Empty' }}

      URL

{{ detailCtrl.project.projectUrl || 'Empty' }}

      Issue tracker

{{ detailCtrl.project.issueTrackerUrl || 'Empty' }}

        <button type="submit" class="btn btn-primary" ng-disabled="projectForm.$waiting">
          Save
        </button>
        <button type="button" class="btn btn-default" ng-disabled="projectForm.$waiting" ng-click="projectForm.$cancel()">
          Cancel
        </button>

  </form>

  <pnc-header>
    <pnc-header-title>Build Configurations</pnc-header-title>
    <pnc-header-buttons>
        <button type="button" class="btn btn-lg btn-default disabled" data-toggle="tooltip" title="Create Build Configuration">
             Create
        </button>
    </pnc-header-buttons>
  </pnc-header>

  <input ng-model="searchText" placeholder="filter config...">

      Name
      Description
      Project
      SCM Repository
      SCM Revision
      Created
      Modified
      User

            {{ configuration.name }}

        {{ configuration.description }}
        {{ configuration.projectId }}
        {{ configuration.scmRepoURL }}
        {{ configuration.scmRevision }}
        {{ configuration.creationTime | date:'medium'}}
        {{ configuration.lastModificationTime | date:'medium'}}


text:
drop database if exists ci_blog;

create database ci_blog;

use ci_blog;

grant select, insert, update, delete on ci_blog.* to 'www'@'localhost' identified by 'www';

create table users (
    `id` varchar(50) not null,
    `email` varchar(50) not null,
    `passwd` varchar(50) not null,
    `admin` bool not null,
    `name` varchar(50) not null,
    `image` varchar(500) not null,
    `created_at` datetime not null,
    unique key `idx_email` (`email`),
    key `idx_created_at` (`created_at`),
    primary key (`id`)
) engine=innodb default charset=utf8;

create table blogs (
    `id` varchar(50) not null,
    `user_id` varchar(50) not null,
    `user_name` varchar(50) not null,
    `user_image` varchar(500) not null,
    `name` varchar(50) not null,
    `summary` varchar(200) not null,
    `content` mediumtext not null,
    `created_at` datetime not null,
    key `idx_created_at` (`created_at`),
    primary key (`id`)
) engine=innodb default charset=utf8;

create table comments (
    `id` varchar(50) not null,
    `blog_id` varchar(50) not null,
    `user_id` varchar(50) not null,
    `user_name` varchar(50) not null,
    `user_image` varchar(500) not null,
    `content` mediumtext not null,
    `created_at` datetime not null,
    key `idx_created_at` (`created_at`),
    primary key (`id`)
) engine=innodb default charset=utf8;

create table categorys(
    `id` varchar(50) not null,
    `name` varchar(50) not null,
    `created_at` datetime not null,
    primary key (`id`)
)engine=innodb default charset=utf8;

create table categorys_blogs(
    `id` varchar(50) not null,
    `category_id` varchar(50) not null,
    `blog_id` varchar(50) not null,
    index (`category_id`),
    index (`blog_id`)
)engine=innodb default charset=utf8;


text:
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

import decimal
import math

def isstring(value):
    return isinstance(value, (str,) + (str, bytes))

def isinf(value):
    try:
        return decimal.Decimal(value).is_infinite()
    except OverflowError:
        return True
    except TypeError:
        return False
    except (ValueError, decimal.InvalidOperation):
        return False

def isnan(value):
    try:
        return math.isnan(value)
    except (TypeError, OverflowError):
        return False


text:
@interface DLSharedToastManager : NSObject

+ (DLSharedToastManager *)sharedManager;
- (void)showToast:(NSString *)toast controller:(UIViewController *)controller;

@end


text:
#include "FE_GPU_API.h"

FE_GPU_Command::FE_GPU_Command(){}
FE_GPU_Command::~FE_GPU_Command(){}

/** FE_GPU_CreateVBOCMD
  * command that creates a buffer
  **/
FE_RENDERTYPE FE_GPU_Command::rend_type;
FE_GPU_Info* FE_GPU_Command::info = nullptr;

FE_GPU_CreateVBOCMD::FE_GPU_CreateVBOCMD(){}
FE_GPU_CreateVBOCMD::~FE_GPU_CreateVBOCMD(){}

void FE_GPU_CreateVBOCMD::update(){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: updateGL3(); break;
        case FE_OPENGLES3: updateGL3(); break;
        default: cout << "";
    }
};
void FE_GPU_CreateVBOCMD::flush(FE_GPU_Thread* thread){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: flushGL3(thread); break;
        case FE_OPENGLES3: flushGL3(thread); break;
        default: cout << "";
    }
};

/** FE_GPU_SetVBODataCMD
  * command that creates a buffer
  **/

FE_GPU_SetVBODataCMD::FE_GPU_SetVBODataCMD(){}
FE_GPU_SetVBODataCMD::~FE_GPU_SetVBODataCMD(){}

void FE_GPU_SetVBODataCMD::update(){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: updateGL3(); break;
        case FE_OPENGLES3: updateGL3(); break;
        default: cout << "";
    }
};
void FE_GPU_SetVBODataCMD::flush(FE_GPU_Thread* thread){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: flushGL3(thread); break;
        case FE_OPENGLES3: flushGL3(thread); break;
        default: cout << "";
    }
};

/** FE_GPU_SetVBOSubDataCMD
  * command that creates a buffer
  **/

FE_GPU_SetVBOSubDataCMD::FE_GPU_SetVBOSubDataCMD(){}
FE_GPU_SetVBOSubDataCMD::~FE_GPU_SetVBOSubDataCMD(){}

void FE_GPU_SetVBOSubDataCMD::update(){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: updateGL3(); break;
        case FE_OPENGLES3: updateGL3(); break;
        default: cout << "";
    }
};
void FE_GPU_SetVBOSubDataCMD::flush(FE_GPU_Thread* thread){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: flushGL3(thread); break;
        case FE_OPENGLES3: flushGL3(thread); break;
        default: cout << "";
    }
};

/** FE_GPU_DestroyVBOCMD
  * command that creates a buffer
  **/

FE_GPU_DestroyVBOCMD::FE_GPU_DestroyVBOCMD(){}
FE_GPU_DestroyVBOCMD::~FE_GPU_DestroyVBOCMD(){}

void FE_GPU_DestroyVBOCMD::update(){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: updateGL3(); break;
        case FE_OPENGLES3: updateGL3(); break;
        default: cout << "";
    }
};
void FE_GPU_DestroyVBOCMD::flush(FE_GPU_Thread* thread){
    /// api-specific codebases
    switch(FE_GPU_Command::rend_type){
        case FE_OPENGL3_2: flushGL3(thread); break;
        case FE_OPENGLES3: flushGL3(thread); break;
        default: cout << "";
    }
};


text:
Generic and extensible callable invoker.

[![Build Status](https://img.shields.io/travis/PHP-DI/Invoker.svg?style=flat-square)](https://travis-ci.org/PHP-DI/Invoker)
[![Coverage Status](https://img.shields.io/coveralls/PHP-DI/Invoker/master.svg?style=flat-square)](https://coveralls.io/r/PHP-DI/Invoker?branch=master)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/PHP-DI/Invoker.svg?style=flat-square)](https://scrutinizer-ci.com/g/PHP-DI/Invoker/?branch=master)
[![Latest Version](https://img.shields.io/github/release/PHP-DI/invoker.svg?style=flat-square)](https://packagist.org/packages/PHP-DI/invoker)

## Why?

Who doesn't need an over-engineered `call_user_func()`?

### Named parameters

Does this [Silex](http://silex.sensiolabs.org) example look familiar:

```php
$app->get('/project/{project}/issue/{issue}', function ($project, $issue) {
    // ...
});
```

Or this command defined with [Silly](https://github.com/mnapoli/silly#usage):

```php
$app->command('greet [name] [--yell]', function ($name, $yell) {
    // ...
});
```

Same pattern in [Slim](http://www.slimframework.com):

```php
$app->get('/hello/:name', function ($name) {
    // ...
});
```

You get the point. These frameworks invoke the controller/command/handler using something akin to named parameters: whatever the order of the parameters, they are matched by their name.

**This library allows to invoke callables with named parameters in a generic and extensible way.**

### Dependency injection

Anyone familiar with AngularJS is familiar with how dependency injection is performed:

```js
angular.controller('MyController', ['dep1', 'dep2', function(dep1, dep2) {
    // ...
}]);
```

In PHP we find this pattern again in some frameworks and DI containers with partial to full support. For example in Silex you can type-hint the application to get it injected, but it only works with `Silex\Application`:

```php
$app->get('/hello/{name}', function (Silex\Application $app, $name) {
    // ...
});
```

In Silly, it only works with `OutputInterface` to inject the application output:

```php
$app->command('greet [name]', function ($name, OutputInterface $output) {
    // ...
});
```

[PHP-DI](http://php-di.org/doc/container.html) provides a way to invoke a callable and resolve all dependencies from the container using type-hints:

```php
$container->call(function (Logger $logger, EntityManager $em) {
    // ...
});
```

**This library provides clear extension points to let frameworks implement any kind of dependency injection support they want.**

### TL/DR

In short, this library is meant to be a base building block for calling a function with named parameters and/or dependency injection.

## Installation

```sh
$ composer require PHP-DI/invoker
```

## Usage

### Default behavior

By default the `Invoker` can call using named parameters:

```php
$invoker = new Invoker\Invoker;

$invoker->call(function () {
    echo 'Hello world!';
});

// Simple parameter array
$invoker->call(function ($name) {
    echo 'Hello ' . $name;
}, ['John']);

// Named parameters
$invoker->call(function ($name) {
    echo 'Hello ' . $name;
}, [
    'name' => 'John'
]);

// Use the default value
$invoker->call(function ($name = 'world') {
    echo 'Hello ' . $name;
});

// Invoke any PHP callable
$invoker->call(['MyClass', 'myStaticMethod']);

// Using Class::method syntax
$invoker->call('MyClass::myStaticMethod');
```

Dependency injection in parameters is supported but needs to be configured with your container. Read on or jump to [*Built-in support for dependency injection*](#built-in-support-for-dependency-injection) if you are impatient.

Additionally, callables can also be resolved from your container. Read on or jump to [*Resolving callables from a container*](#resolving-callables-from-a-container) if you are impatient.

### Parameter resolvers

Extending the behavior of the `Invoker` is easy and is done by implementing a [`ParameterResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/ParameterResolver.php).

This is explained in details the [Parameter resolvers documentation](doc/parameter-resolvers.md).

#### Built-in support for dependency injection

Rather than have you re-implement support for dependency injection with different containers every time, this package ships with 2 optional resolvers:

- [`TypeHintContainerResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/Container/TypeHintContainerResolver.php)

    This resolver will inject container entries by searching for the class name using the type-hint:

    ```php
    $invoker->call(function (Psr\Logger\LoggerInterface $logger) {
        // ...
    });
    ```

    In this example it will `->get('Psr\Logger\LoggerInterface')` from the container and inject it.

    This resolver is only useful if you store objects in your container using the class (or interface) name. Silex or Symfony for example store services under a custom name (e.g. `twig`, `db`, etc.) instead of the class name: in that case use the resolver shown below.

- [`ParameterNameContainerResolver`](https://github.com/PHP-DI/Invoker/blob/master/src/ParameterResolver/Container/ParameterNameContainerResolver.php)

    This resolver will inject container entries by searching for the name of the parameter:

    ```php
    $invoker->call(function ($twig) {
        // ...
    });
    ```

    In this example it will `->get('twig')` from the container and inject it.

These resolvers can work with any dependency injection container compliant with [container-interop](https://github.com/container-interop/container-interop). If you container is not compliant you can use the [Acclimate](https://github.com/jeremeamia/acclimate-container) package.

Setting up those resolvers is simple:

```php
// $container must be an instance of Interop\Container\ContainerInterface
$container = ...

$containerResolver = new TypeHintContainerResolver($container);
// or
$containerResolver = new ParameterNameContainerResolver($container);

$invoker = new Invoker\Invoker;
// Register it before all the other parameter resolvers
$invoker->getParameterResolver()->prependResolver($containerResolver);
```

You can also register both resolvers at the same time if you wish by prepending both. Implementing support for more tricky things is easy and up to you!

### Resolving callables from a container

The `Invoker` can be wired to your DI container to resolve the callables.

For example with an invokable class:

```php
class MyHandler
{
    public function __invoke()
    {
        // ...
    }
}

// By default this doesn't work: an instance of the class should be provided
$invoker->call('MyHandler');

// If we set up the container to use
$invoker = new Invoker\Invoker(null, $container);
// Now 'MyHandler' is resolved using the container!
$invoker->call('MyHandler');
```

The same works for a class method:

```php
class WelcomeController
{
    public function home()
    {
        // ...
    }
}

// By default this doesn't work: home() is not a static method
$invoker->call(['WelcomeController', 'home']);

// If we set up the container to use
$invoker = new Invoker\Invoker(null, $container);
// Now 'WelcomeController' is resolved using the container!
$invoker->call(['WelcomeController', 'home']);
// Alternatively we can use the Class::method syntax
$invoker->call('WelcomeController::home');
```

That feature can be used as the base building block for a framework's dispatcher.

Again, any [container-interop](https://github.com/container-interop/container-interop) compliant container can be provided, and [Acclimate](https://github.com/jeremeamia/acclimate-container) can be used for incompatible containers.


text:
const uuid = require('uuid');

export default {
  debug: true,
  state: {
    languages: [],
    currentLanguge: '',
    translateLanguage: '',
    moduleList: [],
    rows: [],

    translateMode: false,
    vm: null,

    editorStart: null,
    selo: null,
    editorElement: null,
    editorElementDynamic: null,
    editorElementStable: null,
  },
  init(type, data) {
    this.state[type] = data;
  },
  /*----------------------------------------------*/
  addRow(r, i) {
    const tmp = JSON.parse(JSON.stringify(r));
    tmp.index = uuid.v1();

    if (isNaN(i)) {
      this.state.rows.push(tmp);
    } else {
      this.state.rows.splice(i, 0, tmp);
    }

    this.state.vm.$plekanEvent.onAdd(tmp);
  },
  updateRows(index, row) {
    const tmp = JSON.parse(JSON.stringify(this.state.rows));
    tmp[index] = row;
    this.state.rows = tmp;
    this.state.vm.$plekanEvent.onUpdate(tmp, index);
  },
  deleteRow(r, i) {
    const tmp = this.state.rows.splice(i, 1);
    this.state.vm.$plekanEvent.onDelete(tmp, i);
  },
  dublicateRow(r, i) {
    this.addRow(r, i);
    this.state.vm.$plekanEvent.onDuplicate(r, i);
  },
  sortRows(_new, old) {
    this.state.rows.move(old, _new);
    this.state.vm.$plekanEvent.onSort(_new, old);
    //
  },
  /*----------------------------------------------*/
  changeTranslateMode() {
    this.state.translateMode = !this.state.translateMode;
  },
};


text:
'use strict';

var through  = require('through2'),
    gutil    = require('gulp-util'),
    fs       = require('fs'),
    _        = require('lodash'),
    path     = require('path'),
    ext      = gutil.replaceExtension;

module.exports = function(opts){
  if(opts == null){opts = {};}

  return through.obj(function(file, enc, cb){
    var template, data, dir;

    if(file.isNull()) {
      this.push(file);
      return cb();
    }
    if(file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-tmpl', 'Streaming not supported'));
      return cb();
    }
    try {

      template = _.template(file.contents.toString('utf8'));
      dir = path.dirname(file.path);

      fs.readdir(dir, function(err, files){
        var data = {},
            re = opts.re || /^_(.+)\.html$/,
            x;

        _.each(files, function(basename){
          if(x = re.exec(basename)) {
            data[x[1]] = fs.readFileSync(dir + "/" + basename).toString('utf8');
          }
        });

        var out = template(data);
        file.contents = new Buffer(out, 'utf8');
        file.path = ext(file.path, ".html");
        this.push(file);
        return cb();
      }.bind(this));
    } catch (e) {
      console.log(e);
      this.emit('error', new gutil.PluginError('gulp-tmpl', 'Error processing template file', e));
      return cb();
    }
  });

};


text:
<?php

namespace Core\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Helper que inclui a sessão nas views
 *
 * @category Application
 * @package View\Helper
 * @author  Elton Minetto <eminetto@coderockr.com>
 */
class Session extends AbstractHelper implements ServiceLocatorAwareInterface
{
    /**
     * Set the service locator.
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return CustomHelper
     */
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        return $this;
    }
    /**
     * Get the service locator.
     *
     * @return \Zend\ServiceManager\ServiceLocatorInterface
     */
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }
    public function __invoke()
    {
        $helperPluginManager = $this->getServiceLocator();
        $serviceManager = $helperPluginManager->getServiceLocator();
        return $serviceManager->get('Session');
    }
}