text:
var TT = TT || {};
TT.Autocomplete = (function () {

  var pub = {};

  pub.defaults = {
    applyOnClick: true,
    closeOnInputBlur: true,
    closeOnApply: true,
    maxHeight: 240,
    noActive: false,
    showInput: false
  };

  pub.options = {};
  pub.target = null;
  pub.input = null;
  pub.hasMouse = false;
  pub.closeOnLeave = false;

  pub.onInputBlur = function () {
    if (pub.hasMouse) {
      pub.closeOnLeave = true;
    } else if (pub.options.closeOnInputBlur) {
      pub.close();
    }
  };

  pub.open = function (options) {
    pub.close();

    pub.options = $.extend({}, pub.defaults, options);

    pub.hasMouse = false;
    pub.closeOnLeave = false;

    var data = {
      className: pub.options.className,
      items: pub.options.items,
      applyOnClick: pub.options.applyOnClick
    };

    var html = TT.View.render('autocomplete', data);
    TT.View.attach(html, 'body');

    pub.target = $(options.target);

    if (pub.options.showInput) {
      pub.input = $('#autocomplete-input').show().focus();
      if (pub.options.value) {
        pub.input.val(pub.options.value);
      }
    } else {
      if (pub.options.noActive) {
        $('#autocomplete-input').show().css({ position: 'absolute', top: '-9999px' }).focus().blur(pub.onInputBlur);
      }
      pub.input = pub.target;
    }

    if (pub.options.noActive === false) {
      var inputVal = pub.input.val();
      var active = $('#autocomplete .item').filter(function () {
        return $(this).data('value') === inputVal || $(this).text() === inputVal;
      });
      if (active.length) {
        pub.setActive(active);
      } else {
        pub.setActive();
      }
    }

    pub.input.keyup(pub.onKeyUp).blur(pub.onInputBlur);

    pub.setPosition(options.css);
    pub.setScrollTop();

    $('#autocomplete').mouseenter(function () {
      clearTimeout(pub.closeTimeout);
      pub.hasMouse = true;
    }).mouseleave(function () {
      if (pub.closeOnLeave) {
        pub.close();
      } else if (!pub.options.closeOnInputBlur) {
        pub.closeTimeout = setTimeout(pub.close, 500);
      }
      pub.hasMouse = false;
    });
  };

  pub.filter = function () {
    var value = pub.input.val().toLowerCase();

    if (value) {
      $('#autocomplete .item').show().filter(function () {
        return $(this).data('value').toLowerCase().indexOf(value) === -1;
      }).hide();
    } else {
      $('#autocomplete .item').show();
    }

    pub.setActive();
  };

  pub.close = function () {
    $('#autocomplete').remove();
    if (pub.input) {
      pub.input.unbind('keyup blur');
      pub.input = null;
    }

    $('body').unbind('.TT.Autocomplete');

    return false;
  };

  function getNextElement(defaultFn, fallbackFn) {
    var element = $('#autocomplete .item.active')[defaultFn]('.item:visible').first();
    if (element.length === 0) {
      element = $('#autocomplete .item:visible')[fallbackFn]();
    }

    return element;
  }

  pub.onKeyUp = function (e) {
    if (TT.Utils.keyPressed(e, 'DOWN_ARROW')) {
      pub.setActive(getNextElement('nextAll', 'first'));
      pub.input.val($('#autocomplete .active').data('value'));
    } else if (TT.Utils.keyPressed(e, 'UP_ARROW')) {
      pub.setActive(getNextElement('prevAll', 'last'));
      pub.input.val($('#autocomplete .active').data('value'));
    } else if (TT.Utils.keyPressed(e, 'RIGHT_ARROW')) {
      pub.input.val($('#autocomplete .active').data('value'));
    } else if (TT.Utils.keyPressed(e, 'ENTER')) {
      var active = $('#autocomplete .active');
      pub.applyValue(active.length ? active[0] : pub.input);
    } else if (TT.Utils.keyPressed(e, 'ESCAPE')) {
      pub.close();
    } else {
      pub.filter();
    }
  };

  pub.setPosition = function (customCSS) {
    var $autocomplete = $('#autocomplete');
    var offset = pub.target.offset();
    var customTopOffset = pub.options.customTopOffset || -1;

    $autocomplete.css($.extend({
      left: offset.left,
      top: offset.top + pub.target.outerHeight() + customTopOffset,
      width: pub.target.outerWidth() - 2
    }, customCSS || {}));

    $autocomplete.find('.list').css({ maxHeight: pub.options.maxHeight });

    $('#autocomplete-input').css({
      width: $('#autocomplete').outerWidth() - 22
    });

    $autocomplete.css({
      left: Math.min($autocomplete.offset().left, $(window).width() - $autocomplete.outerWidth() - 3),
      top: Math.min($autocomplete.offset().top, $(window).height() - $autocomplete.outerHeight() - 3)
    });
  };

  pub.setActive = function (element) {
    element = element || $('#autocomplete .item:visible').first();
    $('#autocomplete .active').removeClass('active');
    $(element).addClass('active');

    pub.setScrollTop();
  };

  pub.setScrollTop = function () {
    var active = $('#autocomplete .active');
    var top = 0;

    if (active.length) {
      var index = 0;
      var offset = Math.round(($('#autocomplete .list').outerHeight() / active.outerHeight()) / 2);

      $('#autocomplete .item:visible').filter(function (i) {
        if ($(this).hasClass('active')) {
          index = i;
        }
      });
      top = $('#autocomplete .active').outerHeight() * (index - offset);
    }

    $('#autocomplete .list').scrollTop(top);
  };

  pub.applyValue = function (element) {
    element = TT.Utils.isDomElement(element) ? element : this;

    var value = $(element).data('value');
    if (value) {
      pub.input.val(value);
    }
    value = pub.input.val();

    if (pub.options.onApply) {
      pub.options.onApply.call(element, value);
    }

    if (pub.options.closeOnApply) {
      pub.close();
    }

    return false;
  };

  return pub;

}());


text:
pub use crate::mod_types::stars_types::*;
use crate::sync::requests::SlackWebRequestSender;

/// Adds a star to an item.
///
/// Wraps https://api.slack.com/methods/stars.add

pub fn add<R>(
    client: &R,
    token: &str,
    request: &AddRequest<'_>,
) -> Result<AddResponse, AddError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let timestamp = request.timestamp.as_ref().map(|t| t.to_param_value());
    let params = vec![
        Some(("token", token)),
        request.file.map(|file| ("file", file)),
        request
            .file_comment
            .map(|file_comment| ("file_comment", file_comment)),
        request.channel.map(|channel| ("channel", channel)),
        timestamp
            .as_ref()
            .map(|timestamp| ("timestamp", &timestamp[..])),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("stars.add");
    client
        .send(&url, &params[..])
        .map_err(AddError::Client)
        .and_then(|result| {
            serde_json::from_str::<AddResponse>(&result)
                .map_err(|e| AddError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}

/// Lists stars for a user.
///
/// Wraps https://api.slack.com/methods/stars.list

pub fn list<R>(
    client: &R,
    token: &str,
    request: &ListRequest,
) -> Result<ListResponse, ListError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let count = request.count.map(|count| count.to_string());
    let page = request.page.map(|page| page.to_string());
    let params = vec![
        Some(("token", token)),
        count.as_ref().map(|count| ("count", &count[..])),
        page.as_ref().map(|page| ("page", &page[..])),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("stars.list");
    client
        .send(&url, &params[..])
        .map_err(ListError::Client)
        .and_then(|result| {
            serde_json::from_str::<ListResponse>(&result)
                .map_err(|e| ListError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}

/// Removes a star from an item.
///
/// Wraps https://api.slack.com/methods/stars.remove

pub fn remove<R>(
    client: &R,
    token: &str,
    request: &RemoveRequest<'_>,
) -> Result<RemoveResponse, RemoveError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let timestamp = request.timestamp.as_ref().map(|t| t.to_param_value());
    let params = vec![
        Some(("token", token)),
        request.file.map(|file| ("file", file)),
        request
            .file_comment
            .map(|file_comment| ("file_comment", file_comment)),
        request.channel.map(|channel| ("channel", channel)),
        timestamp
            .as_ref()
            .map(|timestamp| ("timestamp", &timestamp[..])),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("stars.remove");
    client
        .send(&url, &params[..])
        .map_err(RemoveError::Client)
        .and_then(|result| {
            serde_json::from_str::<RemoveResponse>(&result)
                .map_err(|e| RemoveError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}

redpajama_set_name: RedPajamaGithub


text:
@interface ABI42_0_0EXTaskService : ABI42_0_0UMSingletonModule <ABI42_0_0UMTaskServiceInterface, ABI42_0_0EXTaskDelegate>

+ (BOOL)hasBackgroundModeEnabled:(nonnull NSString *)backgroundMode;

// AppDelegate handlers
- (void)applicationDidFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions;
- (void)runTasksWithReason:(ABI42_0_0UMTaskLaunchReason)launchReason
                  userInfo:(nullable NSDictionary *)userInfo
         completionHandler:(nullable void (^)(UIBackgroundFetchResult))completionHandler;

@end


text:
package io.debezium.relational;

import static io.debezium.relational.RelationalDatabaseConnectorConfig.COLUMN_EXCLUDE_LIST;

import java.util.function.Predicate;

import io.debezium.config.Configuration;
import io.debezium.relational.Selectors.TableIdToStringMapper;
import io.debezium.relational.Selectors.TableSelectionPredicateBuilder;
import io.debezium.relational.Tables.TableFilter;
import io.debezium.relational.history.SchemaHistory;
import io.debezium.schema.DataCollectionFilters;

public class RelationalTableFilters implements DataCollectionFilters {

    // Filter that filters tables based only on datbase/schema/system table filters but not table filters
    // Represents the list of tables whose schema needs to be captured
    private final TableFilter eligibleTableFilter;
    // Filter that filters tables based on table filters
    private final TableFilter tableFilter;
    private final Predicate<String> databaseFilter;
    private final String excludeColumns;

    /**
     * Evaluate whether the table is eligible for schema snapshotting or not.
     * This closely relates to fact whether only captured tables schema should be stored in database
     * history or all tables schema.
     */
    private final TableFilter schemaSnapshotFilter;

    public RelationalTableFilters(Configuration config, TableFilter systemTablesFilter, TableIdToStringMapper tableIdMapper, boolean useCatalogBeforeSchema) {
        // Define the filter that provides the list of tables that could be captured if configured
        final TableSelectionPredicateBuilder eligibleTables = Selectors.tableSelector()
                .includeDatabases(config.getString(RelationalDatabaseConnectorConfig.DATABASE_INCLUDE_LIST))
                .excludeDatabases(config.getString(RelationalDatabaseConnectorConfig.DATABASE_EXCLUDE_LIST))
                .includeSchemas(config.getString(RelationalDatabaseConnectorConfig.SCHEMA_INCLUDE_LIST))
                .excludeSchemas(config.getString(RelationalDatabaseConnectorConfig.SCHEMA_EXCLUDE_LIST));
        final Predicate<TableId> eligibleTablePredicate = eligibleTables.build();

        Predicate<TableId> finalEligibleTablePredicate = config.getBoolean(RelationalDatabaseConnectorConfig.TABLE_IGNORE_BUILTIN)
                ? eligibleTablePredicate.and(systemTablesFilter::isIncluded)
                : eligibleTablePredicate;

        this.eligibleTableFilter = finalEligibleTablePredicate::test;

        // Define the filter using the include and exclude lists for tables and database names ...
        Predicate<TableId> tablePredicate = eligibleTables
                .includeTables(
                        config.getString(RelationalDatabaseConnectorConfig.TABLE_INCLUDE_LIST),
                        tableIdMapper)
                .excludeTables(
                        config.getString(RelationalDatabaseConnectorConfig.TABLE_EXCLUDE_LIST),
                        tableIdMapper)
                .build();

        Predicate<TableId> finalTablePredicate = config.getBoolean(RelationalDatabaseConnectorConfig.TABLE_IGNORE_BUILTIN)
                ? tablePredicate.and(systemTablesFilter::isIncluded)
                : tablePredicate;
        String signalDataCollection = config.getString(RelationalDatabaseConnectorConfig.SIGNAL_DATA_COLLECTION);
        if (signalDataCollection != null) {
            TableId signalDataCollectionTableId = TableId.parse(signalDataCollection, useCatalogBeforeSchema);
            if (!finalTablePredicate.test(signalDataCollectionTableId)) {
                final Predicate<TableId> signalDataCollectionPredicate = Selectors.tableSelector()
                        .includeTables(tableIdMapper.toString(signalDataCollectionTableId), tableIdMapper).build();
                finalTablePredicate = finalTablePredicate.or(signalDataCollectionPredicate);
            }
        }
        this.tableFilter = finalTablePredicate::test;

        // Define the database filter using the include and exclude lists for database names ...
        this.databaseFilter = Selectors.databaseSelector()
                .includeDatabases(config.getString(RelationalDatabaseConnectorConfig.DATABASE_INCLUDE_LIST))
                .excludeDatabases(config.getString(RelationalDatabaseConnectorConfig.DATABASE_EXCLUDE_LIST))
                .build();

        Predicate<TableId> eligibleSchemaPredicate = config.getBoolean(RelationalDatabaseConnectorConfig.TABLE_IGNORE_BUILTIN)
                ? systemTablesFilter::isIncluded
                : x -> true;

        this.schemaSnapshotFilter = config.getBoolean(SchemaHistory.STORE_ONLY_CAPTURED_TABLES_DDL)
                ? eligibleSchemaPredicate.and(tableFilter::isIncluded)::test
                : eligibleSchemaPredicate::test;

        this.excludeColumns = config.getString(COLUMN_EXCLUDE_LIST);
    }

    @Override
    public TableFilter dataCollectionFilter() {
        return tableFilter;
    }

    public TableFilter eligibleDataCollectionFilter() {
        return eligibleTableFilter;
    }

    public TableFilter eligibleForSchemaDataCollectionFilter() {
        return schemaSnapshotFilter;
    }

    public Predicate<String> databaseFilter() {
        return databaseFilter;
    }

    public String getExcludeColumns() {
        return excludeColumns;
    }
}


text:
require 'spec_helper'

describe Secretary::Config do
  let(:config) { Secretary::Config.new }
  subject { config }

  its(:user_class) { should eq "::User" }
  its(:ignored_attributes) { should eq ['id', 'created_at', 'updated_at'] }
end


text:
from msrest.serialization import Model

class AddStorageAccountParameters(Model):
    """The parameters used to add a new Azure Storage account.

    :param access_key: The access key associated with this Azure Storage
     account that will be used to connect to it.
    :type access_key: str
    :param suffix: The optional suffix for the storage account.
    :type suffix: str
    """

    _validation = {
        'access_key': {'required': True},
    }

    _attribute_map = {
        'access_key': {'key': 'properties.accessKey', 'type': 'str'},
        'suffix': {'key': 'properties.suffix', 'type': 'str'},
    }

    def __init__(self, access_key, suffix=None):
        super(AddStorageAccountParameters, self).__init__()
        self.access_key = access_key
        self.suffix = suffix


text:
import functools
import logging
import sys
import traceback
import warnings

# Use module-specific logger with a default null handler.
_logger = logging.getLogger('backoff')
_logger.addHandler(logging.NullHandler())  # pragma: no cover
_logger.setLevel(logging.INFO)

# Evaluate arg that can be either a fixed value or a callable.
def _maybe_call(f, *args, **kwargs):
    if callable(f):
        try:
            return f(*args, **kwargs)
        except TypeError:
            return f
    else:
        return f

def _init_wait_gen(wait_gen, wait_gen_kwargs):
    kwargs = {k: _maybe_call(v) for k, v in wait_gen_kwargs.items()}
    initialized = wait_gen(**kwargs)
    initialized.send(None)  # Initialize with an empty send
    return initialized

def _next_wait(wait, send_value, jitter, elapsed, max_time):
    value = wait.send(send_value)
    try:
        if jitter is not None:
            seconds = jitter(value)
        else:
            seconds = value
    except TypeError:
        warnings.warn(
            "Nullary jitter function signature is deprecated. Use "
            "unary signature accepting a wait value in seconds and "
            "returning a jittered version of it.",
            DeprecationWarning,
            stacklevel=2,
        )

        seconds = value + jitter()

    # don't sleep longer than remaining allotted max_time
    if max_time is not None:
        seconds = min(seconds, max_time - elapsed)

    return seconds

def _prepare_logger(logger):
    if isinstance(logger, str):
        logger = logging.getLogger(logger)
    return logger

# Configure handler list with user specified handler and optionally
# with a default handler bound to the specified logger.
def _config_handlers(
    user_handlers, *, default_handler=None, logger=None, log_level=None
):
    handlers = []
    if logger is not None:
        assert log_level is not None, "Log level is not specified"
        # bind the specified logger to the default log handler
        log_handler = functools.partial(
            default_handler, logger=logger, log_level=log_level
        )
        handlers.append(log_handler)

    if user_handlers is None:
        return handlers

    # user specified handlers can either be an iterable of handlers
    # or a single handler. either way append them to the list.
    if hasattr(user_handlers, '__iter__'):
        # add all handlers in the iterable
        handlers += list(user_handlers)
    else:
        # append a single handler
        handlers.append(user_handlers)

    return handlers

# Default backoff handler
def _log_backoff(details, logger, log_level):
    msg = "Backing off %s(...) for %.1fs (%s)"
    log_args = [details['target'].__name__, details['wait']]

    exc_typ, exc, _ = sys.exc_info()
    if exc is not None:
        exc_fmt = traceback.format_exception_only(exc_typ, exc)[-1]
        log_args.append(exc_fmt.rstrip("\n"))
    else:
        log_args.append(details['value'])
    logger.log(log_level, msg, *log_args)

# Default giveup handler
def _log_giveup(details, logger, log_level):
    msg = "Giving up %s(...) after %d tries (%s)"
    log_args = [details['target'].__name__, details['tries']]

    exc_typ, exc, _ = sys.exc_info()
    if exc is not None:
        exc_fmt = traceback.format_exception_only(exc_typ, exc)[-1]
        log_args.append(exc_fmt.rstrip("\n"))
    else:
        log_args.append(details['value'])

    logger.log(log_level, msg, *log_args)


text:
import ad_converter
import filter
# import network

from filter import MyClass

print "Hello Tobias!"

x = MyClass()

y = x.f()

print y


text:
import { BaseCell, BaseCellArgs } from "./BaseCell";
import { PlayerActor } from "../Actor/PlayerActor";
import { Exportable, ExportType } from "../../Exportable";

export interface FireCellArgs extends BaseCellArgs
{
    damage?: number;
}

/**
 * Damages the player if being stand on.
 */
export class DamageCell extends BaseCell
{
    @Exportable.Register(ExportType.NetDisk)
    protected damage: number;

    /**
     * @inheritDoc
     */
    public Init(args: FireCellArgs = {})
    {
        super.Init(args);
    }

    /**
     * @inheritDoc
     */
    protected InitPre(args: FireCellArgs = {})
    {
        super.InitPre(args);

        this.damage = args.damage === undefined ? this.damage : args.damage;
    }

    /**
     * @inheritDoc
     */
    protected OnTick(dt: number): void
    {
        super.OnTick(dt);

        this.actors.forEach(id =>
        {
            const actor = this.world.GetActors().Get(id);

            if(actor instanceof PlayerActor)
            {
                actor.Damage(this.damage * dt);
            }
        });
    }
}

Exportable.Dependency(DamageCell);


text:
package com.google.template.soy.jbcsrc;

import static com.google.template.soy.jbcsrc.restricted.BytecodeUtils.SOY_RECORD_TYPE;

import com.google.auto.value.AutoValue;
import com.google.template.soy.data.LoggingAdvisingAppendable;
import com.google.template.soy.jbcsrc.restricted.ConstructorRef;
import com.google.template.soy.jbcsrc.restricted.MethodRef;
import com.google.template.soy.jbcsrc.restricted.TypeInfo;
import com.google.template.soy.jbcsrc.shared.CompiledTemplate;
import com.google.template.soy.jbcsrc.shared.Names;
import com.google.template.soy.jbcsrc.shared.RenderContext;
import com.google.template.soy.soytree.TemplateNode;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;

/**
 * Information about a compiled template.
 *
 *
This should contain basic information about a single template that will be useful for
 * generating that template as well as calls to the template.
 */
@AutoValue
abstract class CompiledTemplateMetadata {
  /**
   * The {@link Method} signature of all generated constructors for the {@link CompiledTemplate}
   * classes.
   */
  private static final Method GENERATED_CONSTRUCTOR =
      new Method(
          "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, SOY_RECORD_TYPE, SOY_RECORD_TYPE));

  /**
   * The {@link Method} signature of the {@link CompiledTemplate#render(AdvisingAppendable,
   * RenderContext)} method.
   */
  private static final Method RENDER_METHOD;

  /** The {@link Method} signature of the {@link CompiledTemplate#kind()} method. */
  private static final Method KIND_METHOD;

  static {
    try {
      RENDER_METHOD =
          Method.getMethod(
              CompiledTemplate.class.getMethod(
                  "render", LoggingAdvisingAppendable.class, RenderContext.class));
      KIND_METHOD = Method.getMethod(CompiledTemplate.class.getMethod("kind"));
    } catch (NoSuchMethodException | SecurityException e) {
      throw new RuntimeException(e);
    }
  }

  static CompiledTemplateMetadata create(String templateName, TemplateNode node) {
    String className = Names.javaClassNameFromSoyTemplateName(templateName);
    TypeInfo type = TypeInfo.create(className);
    return new AutoValue_CompiledTemplateMetadata(
        ConstructorRef.create(type, GENERATED_CONSTRUCTOR),
        MethodRef.createInstanceMethod(type, RENDER_METHOD).asNonNullable(),
        MethodRef.createInstanceMethod(type, KIND_METHOD).asCheap(),
        type,
        node);
  }

  /**
   * The template constructor.
   *
   *
The constructor has the same interface as {@link
   * com.google.template.soy.jbcsrc.shared.CompiledTemplate.Factory#create}
   */
  abstract ConstructorRef constructor();

  /** The {@link CompiledTemplate#render(AdvisingAppendable, RenderContext)} method. */
  abstract MethodRef renderMethod();

  /** The {@link CompiledTemplate#kind()} method. */
  abstract MethodRef kindMethod();

  /** The name of the compiled template. */
  abstract TypeInfo typeInfo();

  /** The actual template. */
  abstract TemplateNode node();
}


text:
<topbar>
	Lost in Living
	<links>
		Our Members
		See Projects (as)

		The Mission

	</links>
</topbar>


text:
namespace StiGame
{

namespace Gui
{

/// \class Item
/// \brief Base class for GuiItem
class Item :
	public Rectangle
{
public:
    static const int MAX_WIDTH;
    static const int MAX_HEIGHT;
	/// \brief Create an GuiItem
	Item(void);
	/// \brief Create an GuiItem
	/// \param m_name Name of the item
	Item(std::string m_name);
	/// \brief Destructor
	virtual ~Item(void);
	/// \brief GuiItem Render method
	/// \return Rendered surface of the item
	virtual Surface* render(void) = 0;
	/// \brief Clear item members
	virtual void clear(void);
	/// \brief Get the name of the item
	/// \return Name
	std::string getName(void);
	/// \brief Set the background color
	/// \param m_background SColor pointer
	virtual void setBackground(Color* m_background);
	/// \brief Get the background color pointer
	/// \return SColor pointer
	Color *getBackground(void);
	/// \brief Set the foreground color
	/// \param m_foreground SColor pointer
	virtual void setForeground(Color* m_foreground);
	/// \brief Get the foreground color
	/// \return SColor pointer
	Color *getForeground(void);
	/// \brief Get the style of the item
	/// \return GuiStyle pointer
	Style *getStyle(void);
	/// \brief Get mouse over
	bool getMouseOver(void);
	/// \brief Set mouse over
	virtual void setMouseOver(bool);
	/// \brief Virtual method to override, provide mouse position, only over the GuiItem region
	/// \param relp Relative position over the Item
	virtual void onMouseMotion(Point *relp);
	/// \brief Virtual method to override, called when the item is clicked
	/// \param relp Relative position of the click
	virtual void onClick(Point *relp);
	/// \brief Text Input Event Handling
	/// \param text New Char to append
	virtual void onTextInput(char* text);
	/// \brief On Key Up Event handling
	/// \param evt SDL_KeyboardEvent Pointer
	virtual void onKeyUp(SDL_KeyboardEvent *evt);
	/// \brief Set the Item Rectangle (Position and dimension)
	/// \param m_x X Position (px)
	/// \param m_y Y Position (px)
	/// \param m_width Width (px)
	/// \param m_height Height (px)
	virtual void setRectangle(int m_x, int m_y, int m_width, int m_height);

	/// \brief Set current width of the Item
	/// \param m_width Width (px)
	void setWidth(int m_width);

	/// \brief Set current height of the Item
	/// \param m_height Height (px)
	void setHeight(int m_height);

	/// \brief Set Item Current Dimension
	/// \param m_width Width (px)
	/// \param m_height Height (px)
	void setDimension(int m_width, int m_height);

	/// \brief Is the Key Event Handled by this Item
	/// \return Handled or not
    virtual bool isHandleKey(void);

	/// \brief Is the Item has focus
	/// \return Focused or not
	virtual bool isFocus(void);

	/// \brief Set the Focus of the Item
	/// \param m_focus New Focus value
	virtual void setFocus(bool m_focus);

	/// \brief Set the minimum size of the Item, for Layout placement
	/// \param m_width Minimum Width (px)
	/// \param m_height Minimum Height (px)
	void setMinimumSize(int m_width, int m_height);

	/// \brief Set the maximum size of the Item, for Layout placement
	/// \param m_width Maximum Width (px)
	/// \param m_height Maximum Height (px)
	void setMaximumSize(int m_width, int m_height);

	/// \brief Set the maximum, minimum and current Size of the Item
	/// \param m_width Fixed Width (px)
	/// \param m_height Fixed Height (px)
	void setFixedSize(int m_width, int m_height);

	/// \brief Get Current Minimum Size
	/// \return Dimension Pointer of the minimum size
	Dimension* getMinimumSize(void);

	/// \brief Get Current Maximum Size
	/// \return Dimension Pointer of the minimum size
	Dimension* getMaximumSize(void);

	/// \brief Is the Item Visible
	/// \return Visible or not
	bool isVisible(void);

	/// \brief Set the new visibility
	/// \param m_visible Visible or not
	void setVisible(bool m_visible);

    int getId(void);

    virtual void prerender(void);

protected:
	/// \brief Name of the item
	std::string name;
	/// \brief Background color
	Color *background;
	/// \brief Foreground color
	Color *foreground;
	/// \brief Item GuiStyle
	Style *style;
	/// \brief is mouse over
	bool mouseOver;
	/// \brief Event Key Handled
	bool handleKey;

	/// \brief Resize callback
	virtual void resized(void);

	/// \brief Current Focus value
	bool focus;

	/// \brief Visibility
	bool visible;

	/// \brief Minimum Size
	MDimension minimumSize;
	/// \brief Maximum Size
	MDimension maximumSize;
private:
    static int incrementId(void);
    static int _currentId;
    int _id;
	/// \brief Initialization
	void init(void);
};

}

}


text:
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/* All files in http2d are Copyright (C) 2012 Alvaro Lopez Ortega.
 *
 *   Authors:
 *     * Alvaro Lopez Ortega <alvaro@alobbs.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "common-internal.h"
#include "trace.h"
#include "buffer.h"
#include "util.h"
#include "access.h"
#include "socket.h"
#include "connection.h"

#ifdef HAVE_SYSLOG_H
# include <syslog.h>
#endif

typedef struct {
	http2d_buffer_t  modules;
	bool             use_syslog;
	bool             print_time;
	bool             print_thread;
	http2d_access_t *from_filter;
} http2d_trace_t;

static http2d_trace_t trace = {
	HTTP2D_BUF_INIT,
	false,
	false,
	false,
	NULL
};

/* http2d_trace_do_trace() calls complex functions that might do
 * some tracing as well, and that would generate a loop. This flag is
 * used to disable the tracing while a previous trace call is ongoin.
 */
static bool disabled = false;

ret_t
http2d_trace_init (void)
{
	const char        *env;
	http2d_buffer_t  tmp = HTTP2D_BUF_INIT;

	/* Read the environment variable
	 */
	env = getenv (TRACE_ENV);
	if (env == NULL)
		return ret_ok;

	/* Set it up
	 */
	http2d_buffer_fake (&tmp, env, strlen(env));
	http2d_trace_set_modules (&tmp);

	return ret_ok;
}

ret_t
http2d_trace_set_modules (http2d_buffer_t *modules)
{
	ret_t            ret;
	char            *p;
	char            *end;
	http2d_buffer_t  tmp = HTTP2D_BUF_INIT;

	/* Store a copy of the modules
	 */
	http2d_buffer_clean (&trace.modules);

	if (trace.from_filter != NULL) {
		http2d_access_free (trace.from_filter);
	}
	trace.from_filter = NULL;

	if (http2d_buffer_case_cmp_str (modules, "none") != 0) {
		http2d_buffer_add_buffer (&trace.modules, modules);
	}

	/* Check the special properties
	 */
	trace.use_syslog   = (strstr (modules->buf, "syslog") != NULL);
	trace.print_time   = (strstr (modules->buf, "time") != NULL);
	trace.print_thread = (strstr (modules->buf, "thread") != NULL);

	/* Even a more special 'from' property
	 */
	p = strstr (modules->buf, "from=");
	if (p != NULL) {
		p += 5;

		end = strchr(p, ',');
		if (end == NULL) {
			end = p + strlen(p);
		}

		if (end > p) {
			ret = http2d_access_new (&trace.from_filter);
			if (ret != ret_ok) return ret_error;

			http2d_buffer_add (&tmp, p, end-p);

			ret = http2d_access_add (trace.from_filter, tmp.buf);
			if (ret != ret_ok) {
				ret = ret_error;
				goto out;
			}
		}
	}

	ret = ret_ok;

out:
	http2d_buffer_mrproper (&tmp);
	return ret;
}

void
http2d_trace_do_trace (const char *entry, const char *file, int line, const char *func, const char *fmt, ...)
{
	ret_t                  ret;
	char                  *p;
	char                  *lentry;
	char                  *lentry_end;
	va_list                args;
	http2d_connection_t *conn;
	http2d_buffer_t     *trace_modules = &trace.modules;
	bool                 do_log        = false;
	http2d_buffer_t      entries       = HTTP2D_BUF_INIT;

	/* Prevents loops
	 */
	if (disabled) {
		return;
	}

	disabled = true;

	/* Return ASAP if nothing is being traced
	 */
	if (http2d_buffer_is_empty (&trace.modules)) {
		goto out;
	}

	/* Check the connection source, if possible
	 */
	if (trace.from_filter != NULL) {
		/* Current conn is available in a thread property
		 */
		conn = CONN (pthread_getspecific (thread_connection_ptr));

		/* No conn, no trace entry
		 */
		if (conn == NULL) {
			goto out;
		}

		if (conn->socket.socket < 0) {
			goto out;
		}

		/* Skip the trace if the conn doesn't match
		 */
		ret = http2d_access_ip_match (trace.from_filter, &conn->socket);
		if (ret != ret_ok) {
			goto out;
		}
	}

	/* Also, check for 'all'
	 */
	p = strstr (trace_modules->buf, "all");
	if (p == NULL) {
		/* Parse the In-code module string
		 */
		http2d_buffer_add (&entries, entry, strlen(entry));

		for (lentry = entries.buf;;) {
			lentry_end = strchr (lentry, ',');
			if (lentry_end) *lentry_end = '\0';

			/* Check the type
			 */
			p = strstr (trace_modules->buf, lentry);
			if (p) {
				char *tmp = p + strlen(lentry);
				if ((*tmp == '\0') || (*tmp == ',') || (*tmp == ' '))
					do_log = true;
			}

			if ((lentry_end == NULL) || (do_log))
				break;

			lentry = lentry_end + 1;
		}

		/* Return if trace entry didn't match with the configured list
		 */
		if (! do_log) {
			goto out;
		}
	}

	/* Format the message and log it:
	 * 'entries' is not needed at this stage, reuse it
	 */
	http2d_buffer_clean (&entries);
	if (trace.print_thread) {
		int        len;
		char       tmp[32+1];
		static int longest_len = 0;

		len = snprintf (tmp, 32+1, "%llX", (unsigned long long) HTTP2D_THREAD_SELF);
		longest_len = MAX (longest_len, len);

		http2d_buffer_add_str    (&entries, "{0x");
		http2d_buffer_add_char_n (&entries, '0', longest_len - len);
		http2d_buffer_add        (&entries, tmp, len);
		http2d_buffer_add_str    (&entries, "} ");
	}

	if (trace.print_time) {
		http2d_buffer_add_char (&entries, '[');
		http2d_buf_add_bogonow (&entries, true);
		http2d_buffer_add_str  (&entries, "] ");
	}

	http2d_buffer_add_va (&entries, "%18s:%04d (%30s): ", file, line, func);

	va_start (args, fmt);
	http2d_buffer_add_va_list (&entries, (char *)fmt, args);
	va_end (args);

	if (trace.use_syslog) {
		http2d_syslog (LOG_DEBUG, &entries);
	} else {
#ifdef HAVE_FLOCKFILE
		flockfile (stdout);
#endif
		fprintf (stdout, "%s", entries.buf);
#ifdef HAVE_FUNLOCKFILE
		funlockfile (stdout);
#endif
	}

out:
	http2d_buffer_mrproper (&entries);
	disabled = false;
}

ret_t
http2d_trace_get_trace (http2d_buffer_t **buf_ref)
{
	if (buf_ref == NULL)
		return ret_not_found;

	*buf_ref = &trace.modules;
	return ret_ok;
}

int
http2d_trace_is_tracing (void)
{
	return (! http2d_buffer_is_empty (&trace.modules));
}


text:
package DesignVisitor;

public class Mouse implements ComputerPart {

    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);
    }
}


text:
/**
 * Created by y.brisch on 26.06.17.
 */
public final class AlgorithmConstants {

  /**
   * prohibit accidental instantiation
   */
  private AlgorithmConstants() {
  }

  /**
   * holds the minimal populations size
   */
  public static final int MIN_POP_SIZE = 4;

  /**
   * holds the maximal populations size
   */
  public static final int MAX_POP_SIZE = 12;

  /**
   * holds the bonus for a successful landing
   */
  public static final double LANDING_BONUS = 0.2;

  /**
   * holds the initial mutation factor
   */
  public static final double INIT_MUTATION = 0.1;

  /**
   * holds the minimal mutation factor
   */
  public static final double MIN_MUTATION = 0;

  /**
   * holds the maximal mutation factor
   */
  public static final double MAX_MUTATION = 0.9;

  /**
   * Holds the min initial generations
   */
  public static final int MIN_GENERATIONS = 5;

  /**
   * Holds the min initial generations
   */
  public static final int MAX_GENERATIONS = 800;

  /**
   * The ratings for the fitness function. The higher the rating the more emphasis lies on the specific factor.
   * The ratings have to add up to 1
   */
  public static final double RATING_TIME = 0.2;
  public static final double RATING_FUEL = 0.2;
  public static final double RATING_DISTANCE = 0.55;
  public static final double RATING_SPEED = 0.05;

}


text:
package jp.co.codeya.salesforcecli.command;

import jp.co.codeya.salesforcecli.SalesforceParameters;

/**
 * {@link Whoami} 用の起動時引数を管理する。
 *
 * @author eiichiro.takahashi
 */
public class WhoamiParameters extends SalesforceParameters.LoginSupportSalesforceParameters {

    /**
     * {@link WhoamiParameters} を生成する。
     */
    public WhoamiParameters() {
        super();
    }
}


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2009 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.account;

import java.util.*;

import org.lockss.config.*;
import org.lockss.util.*;

/** Simple record of user login sessions
 */
public class UserSession {
  String name;
  String runningServlet;
  String reqHost;
  long loginTime;
  long idleTime;

  public UserSession(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setRunningServlet(String val) {
    runningServlet = val;
  }

  public String getReqHost() {
    return reqHost;
  }

  public void setReqHost(String val) {
    reqHost = val;
  }

  public String getRunningServlet() {
    return runningServlet;
  }

  public void setLoginTime(long val) {
    loginTime = val;
  }

  public long getLoginTime() {
    return loginTime;
  }

  public void setIdleTime(long val) {
    idleTime = val;
  }

  public long getIdleTime() {
    return idleTime;
  }
}


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../yarn-state-behavior/yarn-state-behavior.html">
<link rel="import" href="reflux-core.html">

<script>
var Funk = Funk || {};

(function() {

  var Reflux = Funk.Reflux = require('reflux-core');

  /**
  This behavior turns a Polymer component into a store that can subscribe to Reflux actions and publish state changes to your Polymer views.

  Each property with `{ notify: true }` is mirrored on to `state[storeName]`, which is available to any of your views that have the `Funk.ViewBehavior` (simply an alias for [`YarnBehaviors.StateBehavior`](https://github.com/yarn-co/yarn-state-behavior)).

  Not only is the store mirrored on to `state[storeName]`, but data-binding is also perfectly preserved.  So your views can subscribe to changes to your stores using all the familiar means: computed properties, observers, and one-way DOM-binding (i.e. `[[state.myStore.someProp]]`), etc.

  _**Note:** Be sure not to use two-way binding with `state` to keep that funky, fluxy one-directional data-flow!_

  Aside from providing several helper methods, this behavior also imparts all of Reflux's listening methods to your store component, including `hasListener()`, `listenToMany()`, `validateListening()`, `listenTo()`, `stopListeningTo()`, `stopListeningToAll()`, `joinTrailing()`, `joinLeading()`, `joinConcat()`, and `joinStrict()`.

  A note on timing: stores may be initialized all the way through the `attached()` Polymer lifecycle hook– `state[myStore]` comes into effect _directly after_ the `attached()` hook (using microtask timing).  This is consistent with the timing with which Polymer's computed properties resolve.

  @polymerBehavior Funk.StoreBehavior
  @demo demo/index.html
  */
  Funk.StoreBehaviorImpl = {

    properties: {

      /**
       * The name of the store.
       * This name will be used as the key that gets placed on
       * `state` to reference the store, e.g. `state[storeName]`
       * can be used throughout your views to reference this
       * store (on all `Funk.ViewBehavior` elements).
       */
      storeName: {
        type: String,
        readOnly: true
      },

      /**
       * Behaves identically to Reflux's [listenables](https://github.com/reflux/refluxjs#the-listenables-shorthand).
       */
      funkListenables: {
        type: Array,
        value: function() {
          return [];
        }
      }

    },

    ready: function() {

      if (!this.storeName) {
        throw new Error('Store must have a name.');
      }

      // Hook-up listenables

      var listenables = [].concat(this.funkListenables);
      for (var i = 0; i < listenables.length; i++) {
        this.listenToMany(listenables[i]);
      }
    },

    attached: function() {

      // Wrap binding logic in async to allow computed bindings, etc. to settle
      this.async(function() {

        // Init storage spot
        this.state[this.storeName] = {};

        // Link store names to state

        var notifies;
        var propName;
        var properties = Object.keys(this.properties);
        for (var i = 0; i < properties.length; i++) {

          propName = properties[i];
          notifies = this.properties[propName].notify;

          if (propName !== 'storeName' && propName !== 'state' && notifies) {

            // Set state and link paths.  Path linking takes care of passing
            // along deep changes, but not shallow ones.
            // E.g. passes along `someProp.length` but not `someProp`
            this.set(['state', this.storeName, propName], this[propName]);
            this.linkPaths('state.' + this.storeName + '.' + propName, propName);

            // Now take care of shallow changes by simply listening, ignoring
            // changes to deep paths.
            var changedEvent = Polymer.CaseMap.camelToDashCase(propName) + '-changed';
            var changedListener = function(prop, e) {

              if (!e.detail.path) {
                this.set(['state', this.storeName, prop], this[prop]);
              }
            };

            this.addEventListener(changedEvent, changedListener.bind(this, propName));
          }
        }
      });
    }

  };

  /**
  This behavior provides utilities to work with Funk collections.
  A collection is simply an id-keyed object of the form,
  `{ 22: {...}, 144: {...}, 3: {...} }`.

  @polymerBehavior Funk.CollectionBehavior
  @demo demo/index.html
  */
Funk.CollectionBehavior = {

    /**
     * If you'd like a property to mirror one of the items
     * in a collection, you would use `deriveItem()`.
     *
     * Ex.
     * ```js
     * this.collection = { 22: {...}, 144: {...}, 3: { val: 'fluxy!' } };
     * this.deriveItem('someItem', 'collection', 3);
     * this.someItem; // { val: 'fluxy!' }
     *
     * // This will notify anyone observing someItem
     * this.set('collection.3.val', 'funky!');
     * this.someItem; // { val: 'funky!' }
     * ```
     */
    deriveItem: function(prop, collection, id) {

      this.set(prop, this.get([collection, id]));

      // Implicitly unlinks any previously linked paths
      this.linkPaths(prop, collection + '.' + id);
    },

    /**
     * If you'd like a property to mirror a fixed list of the
     * items in a collection as an array, you would use `deriveList()`.
     *
     * Ex.
     * ```js
     * this.collection = { 22: {...}, 144: { val: 'gross!' }, 3: { val: 'fluxy!' } };
     * this.deriveList('someList', 'collection', [144, 3]);
     * this.someList; // [{ val: 'gross!' }, { val: 'fluxy!' }]
     *
     * // This will notify anyone observing someList.#0
     * this.set('collection.144.val', 'mmm!');
     * this.someList; // [{ val: 'mmm!' }, { val: 'fluxy!' }]
     * ```
     */
    deriveList: function(prop, collection, ids) {

      // Unlink existing paths
      var currentList = this.get(prop) || [];
      for (var i = 0; i < currentList.length; i++) {
        this.unlinkPaths(prop + '.#' + i);
      }

      // Create new list, linking paths
      var list = [];
      var id;
      for (var j = 0; j < ids.length; j++) {
        id = ids[j];
        list.push(this.get([collection, id]));
        this.linkPaths(prop + '.#' + j, collection + '.' + id);
      }

      // Finally set list
      this.set(prop, list);
    },

    /**
     * If you'd like a property to mirror a dynamic list of the
     * items in a collection as an array, you would use `deriveDynList()`.
     *
     * The dynamic list `dyn` must be a notifying property.
     *
     * Ex.
     * ```js
     * this.friendIds = [3, 5, 8, 13];
     * this.deriveDynList('friends', 'usersCollection', 'friendIds');
     * // Notifies friends.splices
     * this.push('friendIds', 21);
     * // Notifies friends.#4.name
     * this.set(['usersCollection', 21, 'name'], 'Copernicus');
     * ```
     */
    deriveDynList: function(prop, collection, dyn) {

      var self = this;

      // Ensure the dynamic ids list is notifying,
      // hopefully only until Polymer/polymer#3460
      if (dyn.indexOf('.') === -1 && !this.getPropertyInfo(dyn).notify) {
        throw new Error('Property "' + dyn + '" must be notifying ' +
                        'in order to be used as a dynamic list.');
      }

      var changedEvent = Polymer.CaseMap.camelToDashCase(dyn) + '-changed';
      var changedListener = function(e) {

        var dynIds = this.get(dyn);

        // Complete reset
        if (!e.detail.path) {
          return this.deriveList(prop, collection, dynIds);
        }

        if (e.detail.path === dyn + '.splices') {

          var splices = e.detail.value.indexSplices;

          if (!splices.length) {
            return;
          }

          // Currently cannot apply multiple splices one at a time,
          // see Polymer/polymer#3578
          if (splices.length > 1) {
            return this.deriveList(prop, collection, dynIds);
          }

          var start = splices[0].index;
          var numAdded = splices[0].addedCount;
          var numRemoved = splices[0].removed.length;
          var propValue = this.get(prop);
          var addedObjs = dynIds.slice(start, start + numAdded).map(function(id) {
            return self.get([collection, id]);
          });

          // Make the actual splice!
          this.splice.apply(this, [prop, start, numRemoved].concat(addedObjs));

          // Link as few paths as necessary

          var end = (numAdded === numRemoved) ? start + numAdded : propValue.length;
          for (var i = start; i < end; ++i) {
            this.linkPaths(prop + '.#' + i, collection + '.' + dynIds[i]);
          }

          // Remove vestigial links

          var propLength = propValue.length;
          var deadTail = numRemoved - numAdded;
          for (var j = propLength; j < propLength + deadTail; ++j) {
            this.unlinkPaths(prop + '.#' + j);
          }

        }

      };

      this.deriveList(prop, collection, this.get(dyn) || []);
      this.addEventListener(changedEvent, changedListener);
    },

    /**
     * Converts an array of the format `[{ id: 1 }, { id: 38 }]`
     * to an object of the format `{ 1: { id: 1 }, 38: { id: 38 } }`
     * (a Funk collection).
     *
     * This is intended to be used to facilitate collections
     * used by `deriveItem()` and `deriveList()`.
     *
     * The second argument `keyName` may override the keying field-name,
     * and defaults to `'id'`.
     */
    arrayToCollection: function(list, keyName) {

      keyName = keyName || 'id';

      var obj = {};
      for (var i = 0; i < list.length; i++) {
        obj[list[i][keyName]] = list[i];
      }

      return obj;
    }

  };

  /** @polymerBehavior */
  Funk.StoreBehavior = [
    YarnBehaviors.StateBehavior,
    Reflux.ListenerMethods,
    Funk.CollectionBehavior,
    Funk.StoreBehaviorImpl
  ];

  /**
  An alias of [YarnBehaviors.StateBehavior](https://github.com/yarn-co/yarn-state-behavior)

  @polymerBehavior Funk.ViewBehavior
  @demo demo/index.html
  */
  Funk.ViewBehavior = [
    YarnBehaviors.StateBehavior
  ];

})();
</script>


text:
<BroadcastMonitor>
  <updated>2015-08-06T16:23:37</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-06T16:23:23</startTime>
    <itemId>1000080573:0</itemId>
    <titleId>216100634</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** BED - Dubbele Portie 90s Soul</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>669</CategoryCode>
    <CategoryName>Bedjes</CategoryName>
    <itemDuration>121</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-06T16:25:25</startTime>
    <itemId>1000080573:0</itemId>
    <titleId>216100635</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** DP 90SOUL LOS</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>671</CategoryCode>
    <CategoryName>Sweepers</CategoryName>
    <itemDuration>4</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
import { HTTP } from '../platform/constants'
import { exists } from '../utils';
import { LoggerFactory } from '../logging';
import { KeycloakConnection } from './keycloakConnection';

class KeycloakFunctions {

    constructor() {
        this.connection = new KeycloakConnection();
    }

    createLoginConnection(directConnection, authEndpoint, realmName, appName, user, password) {
        let connection;
        let content;

        const encodedUser = encodeURIComponent(user);
        const encodedPassword = encodeURIComponent(password);
        const encodedAppName = encodeURIComponent(appName);

        if (directConnection) {
            if (exists(appName)) {
                connection = this.connection.createDirectConnection(authEndpoint,realmName);
                content = 'client_id=' + encodedAppName + '&username=' + encodedUser + '&password=' + encodedPassword + '&grant_type=password';
            } else {
                throw Error('No app name set!');
            }
        } else {
            connection = this.connection.createServerProxyConnection(authEndpoint, realmName);
            content = 'username=' + encodedUser + '&password=' + encodedPassword + '&grant_type=password';
        }

        return { connection, content };
    }

    createRefreshConnection(directConnection, authEndpoint, realmName, appName, refreshToken) {
        let connection;
        let content;

        const encodedAppName = encodeURIComponent(appName);

        if (directConnection) {
            if (exists(appName)) {
                connection = this.connection.createDirectConnection(authEndpoint, realmName);
                content = 'grant_type=refresh_token&refresh_token=' + refreshToken + '&client_id=' + encodedAppName;
            } else {
                throw Error('No app name set!');
            }
        } else {
            connection = this.connection.createServerProxyConnection(authEndpoint);
            content = 'grant_type=refresh_token&refresh_token=' + refreshToken;
        }

        return { connection, content };
    }

    receiveToken(httpRequest, body) {
        return new Promise((resolve, reject) => {
            httpRequest.ontimeout = function (error) {
                reject(error);
            }

            httpRequest.onerror = function (error) {
                reject(error);
            }

            httpRequest.onreadystatechange = function () {
                if (this.readyState === HTTP.XMLHTTPREQUEST_READYSTATE.DONE && this.status === HTTP.STATUS.OK) {
                    resolve(this.response);
                } else if (this.readyState === HTTP.XMLHTTPREQUEST_READYSTATE.DONE && this.status !== HTTP.STATUS.OK) {
                    reject(this.status);
                }
            }

            KeycloakFunctions.LOGGER.trace('Receiving token');
            httpRequest.send(body);
        });
    }

    refreshToken(directConnection, authEndpoint, realmName, appName, refreshToken) {
        const { connection, content } = this.createRefreshConnection(directConnection, authEndpoint, realmName, appName, refreshToken);
        return this.receiveToken(connection, content);
    }

}

KeycloakFunctions.LOGGER = LoggerFactory.getLogger('KeycloakFunctions');

export { KeycloakFunctions }


text:
namespace GoogleARCore.Examples.ObjectManipulationInternal
{
    using GoogleARCore;
    using UnityEngine;

    /// <summary>
    /// Provides helper functions for common functionality for transforming objects in AR.
    /// </summary>
    public static class TransformationUtility
    {
        /// <summary>
        /// Slight offset of the down ray used in GetBestPlacementPosition to ensure that the
        /// current groundingPlane is included in the hit results.
        /// </summary>
        private const float k_DownRayOffset = 0.01f;

        /// <summary>
        /// Max amount (inches) to offset the screen touch in GetBestPlacementPosition.
        /// The actual amount if dependent on the angle of the camera relative.
        /// The further downward the camera is angled, the more the screen touch is offset.
        /// </summary>
        private const float k_MaxScreenTouchOffset = 0.4f;

        /// <summary>
        /// In GetBestPlacementPosition, when the camera is closer than this value to the object,
        /// reduce how much the object hovers.
        /// </summary>
        private const float k_HoverDistanceThreshold = 1.0f;

        /// <summary>
        /// Translation mode.
        /// </summary>
        public enum TranslationMode
        {
            /// <summary>
            /// Horizontal translation mode.
            /// </summary>
            Horizontal,

            /// <summary>
            /// Vertical translation mode.
            /// </summary>
            Vertical,

            /// <summary>
            /// Horizontal or vertical translation mode.
            /// </summary>
            Any,
        }

        /// <summary>
        /// Calculates the best position to place an object in AR based on screen position.
        /// Could be used for tapping a location on the screen, dragging an object, or using a fixed
        /// cursor in the center of the screen for placing and moving objects.
        ///
        /// Objects are placed along the x/z of the grounding plane. When placed on an AR plane
        /// below the grounding plane, the object will drop straight down onto it in world space.
        /// This prevents the object from being pushed deeper into the scene when moving from a
        /// higher plane to a lower plane. When moving from a lower plane to a higher plane, this
        /// function returns a new groundingPlane to replace the old one.
        /// </summary>
        /// <returns>The best placement position.</returns>
        /// <param name="currentAnchorPosition">Position of the parent anchor, i.e., where the
        /// object is before translation starts.</param>
        /// <param name="screenPos">Location on the screen in pixels to place the object at.</param>
        /// <param name="groundingPlaneHeight">The starting height of the plane that the object is
        /// being placed along.</param>
        /// <param name="hoverOffset">How much should the object hover above the groundingPlane
        /// before it has been placed.</param>
        /// <param name="maxTranslationDistance">The maximum distance that the object can be
        /// translated.</param>
        /// <param name="translationMode">The translation mode, indicating the plane types allowed.
        /// </param>
        public static Placement GetBestPlacementPosition(
            Vector3 currentAnchorPosition,
            Vector2 screenPos,
            float groundingPlaneHeight,
            float hoverOffset,
            float maxTranslationDistance,
            TranslationMode translationMode)
        {
            Placement result = new Placement();
            result.UpdatedGroundingPlaneHeight = groundingPlaneHeight;

            // Get the angle between the camera and the object's down direction.
            float angle = Vector3.Angle(Camera.main.transform.forward, Vector3.down);

            angle = 90.0f - angle;

            float touchOffsetRatio = Mathf.Clamp01(angle / 90.0f);
            float screenTouchOffset = touchOffsetRatio * k_MaxScreenTouchOffset;
            screenPos.y += GestureTouchesUtility.InchesToPixels(screenTouchOffset);

            float hoverRatio = Mathf.Clamp01(angle / 45.0f);
            hoverOffset *= hoverRatio;

            float distance = (Camera.main.transform.position - currentAnchorPosition).magnitude;
            float distanceHoverRatio = Mathf.Clamp01(distance / k_HoverDistanceThreshold);
            hoverOffset *= distanceHoverRatio;

            // The best estimate of the point in the plane where the object will be placed:
            Vector3 groundingPoint;

            // Get the ray to cast into the scene from the perspective of the camera.
            TrackableHit hit;
            if (Frame.Raycast(
                screenPos.x, screenPos.y, TrackableHitFlags.PlaneWithinBounds, out hit))
            {
                if (hit.Trackable is DetectedPlane)
                {
                    DetectedPlane plane = hit.Trackable as DetectedPlane;
                    if (IsPlaneTypeAllowed(translationMode, plane.PlaneType))
                    {
                        // Avoid detecting the back of existing planes.
                        if ((hit.Trackable is DetectedPlane) &&
                            Vector3.Dot(Camera.main.transform.position - hit.Pose.position,
                                        hit.Pose.rotation * Vector3.up) < 0)
                        {
                            Debug.Log("Hit at back of the current DetectedPlane");
                            return result;
                        }

                        // Don't allow hovering for vertical or horizontal downward facing planes.
                        if (plane.PlaneType == DetectedPlaneType.Vertical ||
                            plane.PlaneType == DetectedPlaneType.HorizontalDownwardFacing)
                        {
                            // Limit the translation to maxTranslationDistance.
                            groundingPoint = LimitTranslation(
                                hit.Pose.position, currentAnchorPosition, maxTranslationDistance);

                            result.PlacementPlane = hit;
                            result.PlacementPosition = groundingPoint;
                            result.HoveringPosition = groundingPoint;
                            result.UpdatedGroundingPlaneHeight = groundingPoint.y;
                            result.PlacementRotation = hit.Pose.rotation;
                            return result;
                        }

                        // Allow hovering for horizontal upward facing planes.
                        if (plane.PlaneType == DetectedPlaneType.HorizontalUpwardFacing)
                        {
                            // Return early if the camera is pointing upwards.
                            if (angle < 0f)
                            {
                                return result;
                            }

                            // Limit the translation to maxTranslationDistance.
                            groundingPoint = LimitTranslation(
                                hit.Pose.position, currentAnchorPosition, maxTranslationDistance);

                            // Find the hovering position by casting from the camera onto the
                            // grounding plane and offsetting the result by the hover offset.
                            result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset);

                            // If the AR Plane is above the grounding plane, then the hit plane's
                            // position is used to replace the current groundingPlane. Otherwise,
                            // the hit is ignored because hits are only detected on lower planes by
                            // casting straight downwards in world space.
                            if (groundingPoint.y > groundingPlaneHeight)
                            {
                                result.PlacementPlane = hit;
                                result.PlacementPosition = groundingPoint;
                                result.UpdatedGroundingPlaneHeight = hit.Pose.position.y;
                                result.PlacementRotation = hit.Pose.rotation;
                                return result;
                            }
                        }
                        else
                        {
                            // Not supported plane type.
                            return result;
                        }
                    }
                    else
                    {
                        // Plane type not allowed.
                        return result;
                    }
                }
                else
                {
                    // Hit is not a plane.
                    return result;
                }
            }

            // Return early if the camera is pointing upwards.
            if (angle < 0f)
            {
                return result;
            }

            // If the grounding point is lower than the current gorunding plane height, or if the
            // raycast did not return a hit, then we extend the grounding plane to infinity, and do
            // a new raycast into the scene from the perspective of the camera.
            Ray cameraRay = Camera.main.ScreenPointToRay(screenPos);
            Plane groundingPlane =
                new Plane(Vector3.up, new Vector3(0.0f, groundingPlaneHeight, 0.0f));

            // Find the hovering position by casting from the camera onto the grounding plane
            // and offsetting the result by the hover offset.
            float enter;
            if (groundingPlane.Raycast(cameraRay, out enter))
            {
                groundingPoint = LimitTranslation(
                    cameraRay.GetPoint(enter), currentAnchorPosition, maxTranslationDistance);

                result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset);
            }
            else
            {
                // If we can't successfully cast onto the groundingPlane, just return early.
                return result;
            }

            // Cast straight down onto AR planes that are lower than the current grounding plane.
            if (Frame.Raycast(
                    groundingPoint + (Vector3.up * k_DownRayOffset), Vector3.down,
                    out hit, Mathf.Infinity, TrackableHitFlags.PlaneWithinBounds))
            {
                result.PlacementPosition = hit.Pose.position;
                result.PlacementPlane = hit;
                result.PlacementRotation = hit.Pose.rotation;
                return result;
            }

            return result;
        }

        /// <summary>
        /// Limits the translation to the maximum distance allowed.
        /// </summary>
        /// <returns>The new target position, limited so that the object does not tranlsate more
        /// than the maximum allowed distance.</returns>
        /// <param name="desiredPosition">Desired position.</param>
        /// <param name="currentPosition">Current position.</param>
        /// <param name="maxTranslationDistance">Max translation distance.</param>
        private static Vector3 LimitTranslation(Vector3 desiredPosition, Vector3 currentPosition,
                                                float maxTranslationDistance)
        {
            if ((desiredPosition - currentPosition).magnitude > maxTranslationDistance)
            {
                return currentPosition + (
                    (desiredPosition - currentPosition).normalized * maxTranslationDistance);
            }

            return desiredPosition;
        }

        private static bool IsPlaneTypeAllowed(
            TranslationMode translationMode, DetectedPlaneType planeType)
        {
            if (translationMode == TranslationMode.Any)
            {
                return true;
            }

            if (translationMode == TranslationMode.Horizontal &&
               (planeType == DetectedPlaneType.HorizontalDownwardFacing ||
                planeType == DetectedPlaneType.HorizontalUpwardFacing))
            {
                return true;
            }

            if (translationMode == TranslationMode.Vertical &&
               planeType == DetectedPlaneType.Vertical)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Result of the function GetBestPlacementPosition that indicates if a placementPosition
        /// was found and information about the placement position.
        /// </summary>
        public struct Placement
        {
            /// <summary>
            /// The position that the object should be displayed at before the placement has been
            /// confirmed.
            /// </summary>
            public Vector3? HoveringPosition;

            /// <summary>
            /// The resulting position that the object should be placed at.
            /// </summary>
            public Vector3? PlacementPosition;

            /// <summary>
            /// The resulting rotation that the object should have.
            /// </summary>
            public Quaternion? PlacementRotation;

            /// <summary>
            /// The AR Plane that the object is being placed on.
            /// </summary>
            public TrackableHit? PlacementPlane;

            /// <summary>
            /// This is the updated groundingPlaneHeight resulting from this hit detection.
            /// </summary>
            public float UpdatedGroundingPlaneHeight;
        }
    }
}


text:
import React, { Component } from 'react';

class Lazy extends Component {
  componentWillUpdate() {
    console.log('top2 will update');
  }

  componentDidUpdate() {
    console.log('top2 did update');
  }

  render() {
    console.log('top2 will render');
    return (
      <div>
        13444
      </div>
    );
  }
}

export default Lazy;


text:
package arms

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// DispatchRulesInListActivatedAlerts is a nested struct in arms response
type DispatchRulesInListActivatedAlerts struct {
	DispatchRule []DispatchRuleInListActivatedAlerts `json:"DispatchRule" xml:"DispatchRule"`
}


text:
package com.hp.autonomy.frontend.find.idol.dashboards.widgets;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.hp.autonomy.frontend.configuration.ConfigException;
import com.hp.autonomy.frontend.find.idol.dashboards.WidgetNameSetting;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@SuppressWarnings("WeakerAccess")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@JsonDeserialize(builder = StaticContentWidget.StaticContentWidgetBuilder.class)
public class StaticContentWidget extends Widget<StaticContentWidget, StaticContentWidgetSettings> {
    @SuppressWarnings("ConstructorWithTooManyParameters")
    @Builder(toBuilder = true)
    public StaticContentWidget(final String name, final String type, final Integer x, final Integer y, final Integer width, final Integer height, final WidgetNameSetting displayWidgetName, final StaticContentWidgetSettings widgetSettings, final String cssClass) {
        super(name, type, x, y, width, height, displayWidgetName, widgetSettings, cssClass);
    }

    @Override
    public void basicValidate(final String section) throws ConfigException {
        if (widgetSettings == null) {
            throw new ConfigException("Static Content Widget", "Widget Settings must be specified for Static Content Widget");
        }

        super.basicValidate(section);
    }

    @JsonPOJOBuilder(withPrefix = "")
    public static class StaticContentWidgetBuilder {
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.Cdn.Models
{
    public partial class EdgeNode : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(IPAddressGroups))
            {
                writer.WritePropertyName("ipAddressGroups");
                writer.WriteStartArray();
                foreach (var item in IPAddressGroups)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static EdgeNode DeserializeEdgeNode(JsonElement element)
        {
            ResourceIdentifier id = default;
            string name = default;
            ResourceType type = default;
            Optional<SystemData> systemData = default;
            Optional<IList<IPAddressGroup>> ipAddressGroups = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("ipAddressGroups"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<IPAddressGroup> array = new List<IPAddressGroup>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(IPAddressGroup.DeserializeIPAddressGroup(item));
                            }
                            ipAddressGroups = array;
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new EdgeNode(id, name, type, systemData.Value, Optional.ToList(ipAddressGroups));
        }
    }
}


text:
#region License
//   Copyright 2010 John Sheehan
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
#endregion

namespace RestSharp.Deserializers
{
    using System;

    /// <summary>
    /// Allows control how class and property names and values are deserialized by XmlAttributeDeserializer
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public sealed class DeserializeAsAttribute : Attribute
    {
        /// <summary>
        /// The name to use for the serialized element
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Sets if the property to Deserialize is an Attribute or Element (Default: false)
        /// </summary>
        public bool Attribute { get; set; }
    }
}


text:
package io.aos.elasticsearch.analysis;

import static org.elasticsearch.common.settings.ImmutableSettings.Builder.EMPTY_SETTINGS;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import io.aos.elasticsearch.analysis.icu.IcuAnalysisBinderProcessor;
import io.aos.elasticsearch.analysis.icu.IcuCollationTokenFilterFactory;
import io.aos.elasticsearch.analysis.icu.IcuFoldingTokenFilterFactory;
import io.aos.elasticsearch.analysis.icu.IcuNormalizerTokenFilterFactory;
import io.aos.elasticsearch.analysis.icu.IcuTokenizerFactory;
import io.aos.elasticsearch.analysis.icu.IcuTransformTokenFilterFactory;

import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.common.inject.ModulesBuilder;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.EnvironmentModule;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNameModule;
import org.elasticsearch.index.analysis.AnalysisModule;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.analysis.TokenFilterFactory;
import org.elasticsearch.index.analysis.TokenizerFactory;
import org.elasticsearch.index.settings.IndexSettingsModule;
import org.elasticsearch.indices.analysis.IndicesAnalysisModule;
import org.elasticsearch.indices.analysis.IndicesAnalysisService;
import org.junit.Test;

/**
 */
public class SimpleIcuAnalysisTests {

    @Test
    public void testDefaultsIcuAnalysis() {
        Index index = new Index("test");

        Injector parentInjector = new ModulesBuilder().add(new SettingsModule(EMPTY_SETTINGS), new EnvironmentModule(new Environment(EMPTY_SETTINGS)), new IndicesAnalysisModule()).createInjector();
        Injector injector = new ModulesBuilder().add(
                new IndexSettingsModule(index, EMPTY_SETTINGS),
                new IndexNameModule(index),
                new AnalysisModule(EMPTY_SETTINGS, parentInjector.getInstance(IndicesAnalysisService.class)).addProcessor(new IcuAnalysisBinderProcessor()))
                .createChildInjector(parentInjector);

        AnalysisService analysisService = injector.getInstance(AnalysisService.class);

        TokenizerFactory tokenizerFactory = analysisService.tokenizer("icu_tokenizer");
        assertThat(tokenizerFactory, instanceOf(IcuTokenizerFactory.class));

        TokenFilterFactory filterFactory = analysisService.tokenFilter("icu_normalizer");
        assertThat(filterFactory, instanceOf(IcuNormalizerTokenFilterFactory.class));

        filterFactory = analysisService.tokenFilter("icu_folding");
        assertThat(filterFactory, instanceOf(IcuFoldingTokenFilterFactory.class));

        filterFactory = analysisService.tokenFilter("icu_collation");
        assertThat(filterFactory, instanceOf(IcuCollationTokenFilterFactory.class));

        filterFactory = analysisService.tokenFilter("icu_transform");
        assertThat(filterFactory, instanceOf(IcuTransformTokenFilterFactory.class));
    }
}


text:
import warning from 'warning'
import { REPLACE } from 'history/lib/Actions'
import useQueries from 'history/lib/useQueries'
import createLocation from 'history/lib/createLocation'
import computeChangedRoutes from './computeChangedRoutes'
import { runEnterHooks, runLeaveHooks } from './TransitionUtils'
import { default as _isActive } from './isActive'
import getComponents from './getComponents'
import matchRoutes from './matchRoutes'

function hasAnyProperties(object) {
  for (const p in object)
    if (object.hasOwnProperty(p))
      return true

  return false
}

/**
 * Returns a new createHistory function that may be used to create
 * history objects that know about routing.
 *
 * - isActive(pathname, query)
 * - match(location, (error, nextState, nextLocation) => {})
 * - listenBeforeLeavingRoute(route, (?nextLocation) => {})
 * - listen((error, nextState) => {})
 */
function useRoutes(createHistory) {
  return function (options={}) {
    let { routes, ...historyOptions } = options
    let history = useQueries(createHistory)(historyOptions)
    let state = {}

    function isActive(pathname, query, indexOnly=false) {
      return _isActive(pathname, query, indexOnly, state.location, state.routes, state.params)
    }

    let partialNextState

    function match(location, callback) {
      if (partialNextState && partialNextState.location === location) {
        // Continue from where we left off.
        finishMatch(partialNextState, callback)
      } else {
        matchRoutes(routes, location, function (error, nextState) {
          if (error) {
            callback(error)
          } else if (nextState) {
            finishMatch({ ...nextState, location }, callback)
          } else {
            callback()
          }
        })
      }
    }

    function createLocationFromRedirectInfo({ pathname, query, state }) {
      return createLocation(
        history.createPath(pathname, query), state, REPLACE, history.createKey()
      )
    }

    function finishMatch(nextState, callback) {
      let { leaveRoutes, enterRoutes } = computeChangedRoutes(state, nextState)

      runLeaveHooks(leaveRoutes)

      runEnterHooks(enterRoutes, nextState, function (error, redirectInfo) {
        if (error) {
          callback(error)
        } else if (redirectInfo) {
          callback(null, createLocationFromRedirectInfo(redirectInfo))
        } else {
          // TODO: Fetch components after state is updated.
          getComponents(nextState, function (error, components) {
            if (error) {
              callback(error)
            } else {
              callback(null, null, { ...nextState, components })
            }
          })
        }
      })
    }

    let RouteGuid = 1

    function getRouteID(route) {
      return route.__id__ || (route.__id__ = RouteGuid++)
    }

    const RouteHooks = {}

    function getRouteHooksForRoutes(routes) {
      return routes.reduce(function (hooks, route) {
        hooks.push.apply(hooks, RouteHooks[getRouteID(route)])
        return hooks
      }, [])
    }

    function transitionHook(location, callback) {
      matchRoutes(routes, location, function (error, nextState) {
        if (nextState == null) {
          // TODO: We didn't actually match anything, but hang
          // onto error/nextState so we don't have to matchRoutes
          // again in the listen callback.
          callback()
          return
        }

        // Cache some state here so we don't have to
        // matchRoutes() again in the listen callback.
        partialNextState = { ...nextState, location }

        let hooks = getRouteHooksForRoutes(
          computeChangedRoutes(state, nextState).leaveRoutes
        )

        let result
        for (let i = 0, len = hooks.length; result == null && i < len; ++i) {
          // Passing the location arg here indicates to
          // the user that this is a transition hook.
          result = hooks[i](location)
        }

        callback(result)
      })
    }

    function beforeUnloadHook() {
      // Synchronously check to see if any route hooks want
      // to prevent the current window/tab from closing.
      if (state.routes) {
        let hooks = getRouteHooksForRoutes(state.routes)

        let message
        for (let i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) {
          // Passing no args indicates to the user that this is a
          // beforeunload hook. We don't know the next location.
          message = hooks[i]()
        }

        return message
      }
    }

    let unlistenBefore, unlistenBeforeUnload

    /**
     * Registers the given hook function to run before leaving the given route.
     *
     * During a normal transition, the hook function receives the next location
     * as its only argument and must return either a) a prompt message to show
     * the user, to make sure they want to leave the page or b) false, to prevent
     * the transition.
     *
     * During the beforeunload event (in browsers) the hook receives no arguments.
     * In this case it must return a prompt message to prevent the transition.
     *
     * Returns a function that may be used to unbind the listener.
     */
    function listenBeforeLeavingRoute(route, hook) {
      // TODO: Warn if they register for a route that isn't currently
      // active. They're probably doing something wrong, like re-creating
      // route objects on every location change.
      let routeID = getRouteID(route)
      let hooks = RouteHooks[routeID]

      if (hooks == null) {
        let thereWereNoRouteHooks = !hasAnyProperties(RouteHooks)

        hooks = RouteHooks[routeID] = [ hook ]

        if (thereWereNoRouteHooks) {
          // setup transition & beforeunload hooks
          unlistenBefore = history.listenBefore(transitionHook)

          if (history.listenBeforeUnload)
            unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook)
        }
      } else if (hooks.indexOf(hook) === -1) {
        hooks.push(hook)
      }

      return function () {
        let hooks = RouteHooks[routeID]

        if (hooks != null) {
          let newHooks = hooks.filter(item => item !== hook)

          if (newHooks.length === 0) {
            delete RouteHooks[routeID]

            if (!hasAnyProperties(RouteHooks)) {
              // teardown transition & beforeunload hooks
              if (unlistenBefore) {
                unlistenBefore()
                unlistenBefore = null
              }

              if (unlistenBeforeUnload) {
                unlistenBeforeUnload()
                unlistenBeforeUnload = null
              }
            }
          } else {
            RouteHooks[routeID] = newHooks
          }
        }
      }
    }

    /**
     * This is the API for stateful environments. As the location
     * changes, we update state and call the listener. We can also
     * gracefully handle errors and redirects.
     */
    function listen(listener) {
      // TODO: Only use a single history listener. Otherwise we'll
      // end up with multiple concurrent calls to match.
      return history.listen(function (location) {
        if (state.location === location) {
          listener(null, state)
        } else {
          match(location, function (error, nextLocation, nextState) {
            if (error) {
              listener(error)
            } else if (nextLocation) {
              history.transitionTo(nextLocation)
            } else if (nextState) {
              listener(null, (state = nextState))
            } else {
              warning(
                false,
                'Location "%s" did not match any routes',
                location.pathname + location.search
              )
            }
          })
        }
      })
    }

    return {
      ...history,
      isActive,
      match,
      listenBeforeLeavingRoute,
      listen
    }
  }
}

export default useRoutes


text:
<?php
/**
 * Created by PhpStorm.
 * User: binll
 * Date: 21/08/2017
 * Time: 9:42
 */

namespace AppBundle\Controller;

use AppBundle\Services\Helpers;
use BackendBundle\Entity\Comment;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\JsonResponse;

use BackendBundle\Entity\User;
use BackendBundle\Entity\Video;

class CommentController extends Controller
{

    public function newAction(Request $request){
        $helpers = $this->get(Helpers::class);

        $hash = $request->get("authorization", null);

        $authCheck = $helpers->authCheck($hash);

        if($authCheck){
            $identity = $helpers->authCheck($hash, true);

            $json = $request->get("json", null);

            if($json != null){
                $params = json_decode($json);
                $createdAt = new \DateTime('now');
                $user_id = (isset($identity->sub)) ? $identity->sub : null;
                $video_id = (isset($params->video_id)) ? $params->video_id : null;
                $body = (isset($params->body)) ? $params->body : null;

                if($user_id != null && $video_id != null){
                    $em = $this->getDoctrine()->getManager();
                    $user = $em -> getRepository("BackendBundle:User")->findOneBy([
                       "id" => $user_id
                    ]);
                    $video = $em -> getRepository("BackendBundle:Video")->findOneBy([
                        "id" => $video_id
                    ]);

                    $comment = new Comment();
                    $comment->setUser($user);
                    $comment->setVideo($video);
                    $comment->setBody($body);
                    $comment->setCreatedAt($createdAt);

                    $em->persist($comment);
                    $em->flush();

                    $data = [
                        "status" => "success",
                        "code" => 200,
                        "msg" => "Comment  created"
                    ];
                }
                else{
                    $data = [
                        "status" => "error",
                        "code" => 400,
                        "msg" => "Comment not created"
                    ];
                }
            }
            else{

                $data = [
                    "status" => "error",
                    "code" => 400,
                    "msg" => "Params no válido"
                ];
            }
        }
        else{
            $data = [
              "status" => "error",
              "code" => 400,
              "msg" => "Usuario no válido"
            ];
        }
        return $helpers->getJson($data);
    }

    public  function  deleteAction(Request$request, $id = null){
        $helpers = $this->get(Helpers::class);

        $hash = $request->get("authorization", null);

        $authCheck = $helpers->authCheck($hash);

        if($authCheck){
            $identity = $helpers->authCheck($hash, true);

            $user_id = ($identity->sub != null) ? $identity->sub : null;

            $em = $this->getDoctrine()->getManager();
            $comment = $em->getRepository("BackendBundle:Comment")->findOneBy([
               "id" => $id
            ]);
            if(is_object($comment) && $user_id != null){
                if(isset($identity->sub) &&
                    ($identity->sub == $comment->getUser()->getId() ||
                     $identity->sub == $comment->getVideo()->getUser()->getId()
                    )){
                    $em -> remove($comment);
                    $em->flush();

                    $data = [
                        "status" => "success",
                        "code" => 200,
                        "msg" => "Comment delete success"
                    ];
                }
                else{

                    $data = [
                        "status" => "error",
                        "code" => 400,
                        "msg" => "Comment not delete"
                    ];
                }

            }
            else{

                $data = [
                    "status" => "error",
                    "code" => 400,
                    "msg" => "Comment not delete"
                ];
            }
         }
        else{
            $data = [
                "status" => "error",
                "code" => 400,
                "msg" => "Authentication no válido"
            ];
        }
        return $helpers->getJson($data);
    }

    public function listAction(Request $request, $id = null){
        $helpers = $this->get(Helpers::class);
        $em = $this->getDoctrine()->getManager();

        $video = $em->getRepository("BackendBundle:Video")->findOneBy([
           "id" => $id
        ]);
        $comments = $em->getRepository("BackendBundle:Comment")->findBy([
           "video" => $video
        ], ["id" => "DESC"]);

        if(count($comments) >= 1){
            $data = [
                "status" => "success",
                "code" => 200,
                "data" => $comments
            ];
        }
        else{
            $data = [
                "status" => "error",
                "code" => 400,
                "msg" => "Dont exists comments in this video!!"
            ];
        }

        return $helpers->getJson($data);

    }

}


text:
package org.qi4j.api.query;

public class QueryExpressionException
    extends QueryException
{
    public QueryExpressionException( String message )
    {
        super( message );
    }
}


text:
namespace sevent
{
    namespace asiosocket
    {
        AsioFacade::AsioFacade()
        {
            _service = AsioService::make();
            _sessionRegistry = socket::SessionRegistry::make();
            _connector = socket::Connector_ptr(new AsioConnector(
                        _service, _sessionRegistry));
        }
        AsioFacade::~AsioFacade()
        {
        }

        AsioFacade_ptr AsioFacade::make()
        {
            return AsioFacade_ptr(new AsioFacade());
        }

        void AsioFacade::setWorkerThreads(unsigned numberOfWorkerThreads,
                                                allEventsHandler_t allEventsHandler)
        {
            setWorkerThreads(numberOfWorkerThreads, defaultWorkerThreadHandler, allEventsHandler);
        }

        void AsioFacade::setWorkerThreads(unsigned numberOfWorkerThreads,
                                                workerThread_t workerThreadHandler,
                                                allEventsHandler_t allEventsHandler)
        {
            _allEventsHandler = allEventsHandler;
            _sessionRegistry->setAllEventsHandler(
                boost::bind(allEventsHandler, shared_from_this(), _1, _2));
            for (unsigned x = 0; x < numberOfWorkerThreads; ++x)
            {
                _worker_threads.create_thread(
                    boost::bind(workerThreadHandler, shared_from_this()));
            }
        }

        socket::Listener_ptr AsioFacade::listen(socket::Address_ptr address)
        {
            if(!_allEventsHandler)
            {
                std::runtime_error("Can not create a listener without calling setWorkerThreads first.");
            }
            socket::Listener_ptr listener = boost::make_shared<AsioListener>(_service, _sessionRegistry);
            listener->listen(address);
            saveListener(*address, listener);
            return listener;
        }

        socket::Session_ptr AsioFacade::connect(socket::Address_ptr address)
        {
            return _connector->connect(address);
        }

        socket::Service_ptr AsioFacade::service()
        {
            return _service;
        }

        socket::SessionRegistry_ptr AsioFacade::sessionRegistry()
        {
            return _sessionRegistry;
        }

        void AsioFacade::joinAllWorkerThreads()
        {
            _worker_threads.join_all();
        }

        void AsioFacade::sendEvent(socket::Session_ptr session,
                                   event::Event_ptr event)
        {
            if(isLocalSession(session))
            {
                invokeAllEventsHandler(session, event);
            } else
            {
                session->sendEvent(event);
            }
        }

        void AsioFacade::invokeAllEventsHandler(socket::Session_ptr session,
                                                event::Event_ptr event)
        {
            _allEventsHandler(shared_from_this(), session, event);
        }

        void AsioFacade::defaultWorkerThreadHandler(socket::Facade_ptr facade)
        {
            try
            {
                facade->service()->run();
            }
            catch (boost::exception& e)
            {
                std::cerr << "[" << boost::this_thread::get_id()
                          << "] Exception: " << boost::diagnostic_information(e)
                          << std::endl;
            }
            catch (std::exception& e)
            {
                std::cerr << "[" << boost::this_thread::get_id()
                          << "] Exception: " << e.what() << std::endl;
            }
            facade->service()->stop(); // As soon as one worker fails, we abort all of them (good for debugging)
        }
    }
}


text: export {InnerSubscriber} from 'rxjs/internal-compatibility';


text:
import { PageConfig } from '@jupyterlab/coreutils';
import { JupyterServer } from '@jupyterlab/testutils';
import { ServerConnection } from '../src';
import { getRequestHandler } from './utils';

const server = new JupyterServer();

beforeAll(async () => {
  await server.start();
});

afterAll(async () => {
  await server.shutdown();
});

describe('ServerConnection', () => {
  describe('.makeRequest()', () => {
    it('should make a request to the server', async () => {
      const settings = getRequestHandler(200, 'hello');
      const response = await ServerConnection.makeRequest(
        settings.baseUrl,
        {},
        settings
      );
      expect(response.statusText).toBe('OK');
      const data = await response.json();
      expect(data).toBe('hello');
    });
  });

  describe('.makeSettings()', () => {
    it('should use default settings', () => {
      const settings = ServerConnection.makeSettings();
      expect(settings.baseUrl).toBe(PageConfig.getBaseUrl());
      expect(settings.wsUrl).toBe(PageConfig.getWsUrl());
      expect(settings.token).toBe(PageConfig.getOption('token'));
    });

    it('should use baseUrl for wsUrl', () => {
      const conf: Partial<ServerConnection.ISettings> = {
        baseUrl: 'https://host/path'
      };
      const settings = ServerConnection.makeSettings(conf);
      expect(settings.baseUrl).toBe(conf.baseUrl);
      expect(settings.wsUrl).toBe('wss://host/path');
    });

    it('should handle overrides', () => {
      const defaults: Partial<ServerConnection.ISettings> = {
        baseUrl: 'http://localhost/foo',
        wsUrl: 'http://localhost/bar',
        init: {
          credentials: 'same-origin'
        },
        token: 'baz'
      };
      const settings = ServerConnection.makeSettings(defaults);
      expect(settings.baseUrl).toBe(defaults.baseUrl);
      expect(settings.wsUrl).toBe(defaults.wsUrl);
      expect(settings.token).toBe(defaults.token);
      expect(settings.init.credentials).toBe(defaults.init!.credentials);
    });
  });

  describe('.makeError()', () => {
    it('should create a server error from a server response', async () => {
      const settings = getRequestHandler(200, 'hi');
      const init = { body: 'hi', method: 'POST' };
      const response = await ServerConnection.makeRequest(
        settings.baseUrl,
        init,
        settings
      );
      const err = new ServerConnection.ResponseError(response);
      expect(err.message).toBe('Invalid response: 200 OK');
    });
  });
});