text:
from collections import defaultdict

from neutron_lib.plugins import constants as lib_const
from neutron_lib.plugins import directory
from neutron_lib.utils import runtime
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_service import periodic_task
from oslo_utils import excutils
from osprofiler import profiler

from neutron._i18n import _
from neutron.common import utils
from neutron.plugins.common import constants

LOG = logging.getLogger(__name__)

CORE_PLUGINS_NAMESPACE = 'neutron.core_plugins'

class ManagerMeta(profiler.TracedMeta, type(periodic_task.PeriodicTasks)):
    pass

class Manager(periodic_task.PeriodicTasks, metaclass=ManagerMeta):
    __trace_args__ = {"name": "rpc"}

    # Set RPC API version to 1.0 by default.
    target = oslo_messaging.Target(version='1.0')

    def __init__(self, host=None):
        if not host:
            host = cfg.CONF.host
        self.host = host
        conf = getattr(self, "conf", cfg.CONF)
        super(Manager, self).__init__(conf)

    def periodic_tasks(self, context, raise_on_error=False):
        self.run_periodic_tasks(context, raise_on_error=raise_on_error)

    def init_host(self):
        """Handle initialization if this is a standalone service.

        Child classes should override this method.

        """
        pass

    def after_start(self):
        """Handler post initialization stuff.

        Child classes can override this method.
        """
        pass

    def stop(self):
        """Handle stop.

        Child classes can override this method.
        """
        pass

def validate_pre_plugin_load():
    """Checks if the configuration variables are valid.

    If the configuration is invalid then the method will return an error
    message. If all is OK then it will return None.
    """
    if cfg.CONF.core_plugin is None:
        msg = _('Neutron core_plugin not configured!')
        return msg

class NeutronManager(object, metaclass=profiler.TracedMeta):
    """Neutron's Manager class.

    Neutron's Manager class is responsible for parsing a config file and
    instantiating the correct plugin that concretely implements
    neutron_plugin_base class.
    """
    # TODO(armax): use of the singleton pattern for this class is vestigial,
    # and it is mainly relied on by the unit tests. It is safer to get rid
    # of it once the entire codebase (neutron + subprojects) has switched
    # entirely to using the plugins directory.
    _instance = None
    __trace_args__ = {"name": "rpc"}

    def __init__(self, options=None, config_file=None):
        # Store instances of already loaded plugins to avoid instantiate same
        # plugin more than once
        self._loaded_plugins = {}
        # If no options have been provided, create an empty dict
        if not options:
            options = {}

        msg = validate_pre_plugin_load()
        if msg:
            LOG.critical(msg)
            raise Exception(msg)

        # NOTE(jkoelker) Testing for the subclass with the __subclasshook__
        #                breaks tach monitoring. It has been removed
        #                intentionally to allow v2 plugins to be monitored
        #                for performance metrics.
        plugin_provider = cfg.CONF.core_plugin
        LOG.info("Loading core plugin: %s", plugin_provider)
        # NOTE(armax): keep hold of the actual plugin object
        plugin = self._get_plugin_instance(CORE_PLUGINS_NAMESPACE,
                                           plugin_provider)
        directory.add_plugin(lib_const.CORE, plugin)

        # load services from the core plugin first
        self._load_services_from_core_plugin(plugin)
        self._load_service_plugins()
        # Used by pecan WSGI
        self.resource_plugin_mappings = {}
        self.resource_controller_mappings = {}
        self.path_prefix_resource_mappings = defaultdict(list)

    @staticmethod
    def load_class_for_provider(namespace, plugin_provider):
        """Loads plugin using alias or class name

        :param namespace: namespace where alias is defined
        :param plugin_provider: plugin alias or class name
        :returns: plugin that is loaded
        :raises ImportError: if fails to load plugin
        """

        try:
            return runtime.load_class_by_alias_or_classname(namespace,
                                                            plugin_provider)
        except ImportError:
            with excutils.save_and_reraise_exception():
                LOG.error("Plugin '%s' not found.", plugin_provider)

    def _get_plugin_class(self, namespace, plugin_provider):
        return self.load_class_for_provider(namespace, plugin_provider)

    def _get_plugin_instance(self, namespace, plugin_provider):
        plugin_class = self._get_plugin_class(namespace, plugin_provider)
        plugin_inst = self._loaded_plugins.get(plugin_class)
        if not plugin_inst:
            plugin_inst = plugin_class()
            self._loaded_plugins[plugin_class] = plugin_inst
        return plugin_inst

    def _load_services_from_core_plugin(self, plugin):
        """Puts core plugin in service_plugins for supported services."""
        LOG.debug("Loading services supported by the core plugin")

        # supported service types are derived from supported extensions
        for ext_alias in getattr(plugin, "supported_extension_aliases", []):
            if ext_alias in constants.EXT_TO_SERVICE_MAPPING:
                service_type = constants.EXT_TO_SERVICE_MAPPING[ext_alias]
                directory.add_plugin(service_type, plugin)
                LOG.info("Service %s is supported by the core plugin",
                         service_type)

    def _get_default_service_plugins(self):
        """Get default service plugins to be loaded."""
        core_plugin = directory.get_plugin()
        if core_plugin.has_native_datastore():
            return constants.DEFAULT_SERVICE_PLUGINS.keys()
        else:
            return []

    def _load_service_plugins(self):
        """Loads service plugins.

        Starts from the core plugin and checks if it supports
        advanced services then loads classes provided in configuration.
        """
        plugin_providers = cfg.CONF.service_plugins
        plugin_providers.extend(self._get_default_service_plugins())
        LOG.debug("Loading service plugins: %s", plugin_providers)
        for provider in plugin_providers:
            if provider == '':
                continue

            LOG.info("Loading Plugin: %s", provider)
            plugin_class = self._get_plugin_class(
                'neutron.service_plugins', provider)
            required_plugins = getattr(
                plugin_class, "required_service_plugins", [])
            for req_plugin in required_plugins:
                LOG.info("Loading service plugin %s, it is required by %s",
                         req_plugin, provider)
                self._create_and_add_service_plugin(req_plugin)
            # NOTE(liuyulong): adding one plugin multiple times does not have
            # bad effect for it. Since all the plugin has its own specific
            # unique name.
            self._create_and_add_service_plugin(provider)

    def _create_and_add_service_plugin(self, provider):
        plugin_inst = self._get_plugin_instance('neutron.service_plugins',
                                                provider)
        plugin_type = plugin_inst.get_plugin_type()
        directory.add_plugin(plugin_type, plugin_inst)

        # search for possible agent notifiers declared in service plugin
        # (needed by agent management extension)
        plugin = directory.get_plugin()
        if (hasattr(plugin, 'agent_notifiers') and
                hasattr(plugin_inst, 'agent_notifiers')):
            plugin.agent_notifiers.update(plugin_inst.agent_notifiers)

        # disable incompatible extensions in core plugin if any
        utils.disable_extension_by_service_plugin(plugin, plugin_inst)

        LOG.debug("Successfully loaded %(type)s plugin. "
                  "Description: %(desc)s",
                  {"type": plugin_type,
                   "desc": plugin_inst.get_plugin_description()})

    @classmethod
    @runtime.synchronized("manager")
    def _create_instance(cls):
        if not cls.has_instance():
            cls._instance = cls()

    @classmethod
    def has_instance(cls):
        return cls._instance is not None

    @classmethod
    def clear_instance(cls):
        cls._instance = None

    @classmethod
    def get_instance(cls):
        # double checked locking
        if not cls.has_instance():
            cls._create_instance()
        return cls._instance

    @classmethod
    def set_plugin_for_resource(cls, resource, plugin):
        cls.get_instance().resource_plugin_mappings[resource] = plugin

    @classmethod
    def get_plugin_for_resource(cls, resource):
        return cls.get_instance().resource_plugin_mappings.get(resource)

    @classmethod
    def set_controller_for_resource(cls, resource, controller):
        cls.get_instance().resource_controller_mappings[resource] = controller

    @classmethod
    def get_controller_for_resource(cls, resource):
        resource = resource.replace('_', '-')
        res_ctrl_mappings = cls.get_instance().resource_controller_mappings
        # If no controller is found for resource, try replacing dashes with
        # underscores
        return res_ctrl_mappings.get(
            resource,
            res_ctrl_mappings.get(resource.replace('-', '_')))

    # TODO(blogan): This isn't used by anything else other than tests and
    # probably should be removed
    @classmethod
    def get_service_plugin_by_path_prefix(cls, path_prefix):
        service_plugins = directory.get_unique_plugins()
        for service_plugin in service_plugins:
            plugin_path_prefix = getattr(service_plugin, 'path_prefix', None)
            if plugin_path_prefix and plugin_path_prefix == path_prefix:
                return service_plugin

    @classmethod
    def add_resource_for_path_prefix(cls, resource, path_prefix):
        resources = cls.get_instance().path_prefix_resource_mappings[
            path_prefix].append(resource)
        return resources

    @classmethod
    def get_resources_for_path_prefix(cls, path_prefix):
        return cls.get_instance().path_prefix_resource_mappings[path_prefix]

def init():
    """Call to load the plugins (core+services) machinery."""
    if not directory.is_loaded():
        NeutronManager.get_instance()


text:
import urllib,sys

def crawler(page):
    code = page.read()
    links = []
    while code.find('<a') is not -1:
        tag_begin = code.find('<a',0)
        code = code[tag_begin+2:]
        att_begin = code.find('href')
        code = code[att_begin+4:]
        link_begin = code.find('"')
        link_end = code.find('"',link_begin+1)
        if code[link_begin+1:link_end] not in links:
            links.append(code[link_begin+1:link_end])
        code = code[link_end:]
    return links

def link_counter(page):
    counter = 0
    code = page.read()
    while code.find('') is not -1:
        counter = counter + 1
        code = code[code.find('')+4:]
    return counter

# This function gets the input from command line
def main(argv):
    page = urllib.urlopen(argv[0])
    links = crawler(page)
    for link in links:
        print '"' + link + '"' + '\n'

if __name__ == "__main__":
	main(sys.argv[1:])

redpajama_set_name: RedPajamaGithub


text:
import * as Chai from "chai"
import * as H from "../helper"
import * as Kecubung from "kecubung"
import { ValidatorImpl } from "../../src/validator/validator"
import { DefaultIdentifierResolver, DefaultPathResolver } from "../../src/resolver"
import { MetaDataLoader } from "../../src/metadata-loader/metadata-loader"
import { RequiredValidator } from "../../src/validator/required-validator"
import { EmailValidator } from "../../src/validator/email-validator"
import { RangeValidator } from "../../src/validator/range-validator"
import { TypeValidator } from "../../src/validator/type-validator"
import { ValidatorCommand, FieldValidatorArg } from "kamboja-core"
import { UserModel } from "./model/user-model"
import { ItemModel } from "./model/item-model"
import {ValidatorBase} from "../../src/validator/baseclasses"

export class ExternalValidator extends ValidatorBase{
    validate(args:FieldValidatorArg){
        return undefined;
    }
}

describe("Validator", () => {
    let storage: MetaDataLoader;
    let validators: ValidatorCommand[]
    let test: ValidatorImpl;

    beforeEach(() => {
        storage = new MetaDataLoader(new DefaultIdentifierResolver(), new DefaultPathResolver(__dirname))
        storage.load("model", "Model")
        storage.load("controller", "Controller")
        test = new ValidatorImpl(storage, validators)
    })

    it("Should return undefined when provided correct value", () => {
        let clazz = storage.get("UserController, controller/user-controller")
        let model: UserModel = {
            email: "email@host.com",
            displayName: "Nobita Nobi",
            item: null
        }
        test.setValue([model], clazz, "saveUser")
        let isValid = test.isValid();
        let result = test.getValidationErrors();
        Chai.expect(result).undefined
        Chai.expect(isValid).true
    })

    it("Should return messages when provided incorrect value", () => {
        let clazz = storage.get("UserController, controller/user-controller")
        let model: UserModel = {
            email: "not-an-email",
            displayName: "Nobita Nobi",
            item: null
        }
        test.setValue([model], clazz, "saveUser")
        let isValid = test.isValid();
        let result = test.getValidationErrors();
        Chai.expect(result).deep.eq([{
            field: 'user.email',
            message: '[email] is not a valid email address'
        }])
        Chai.expect(isValid).false
    })

    it("Should not validate parameter without validation decorator", () => {
        let test = new ValidatorImpl(storage, [new ExternalValidator()])
        let clazz = storage.get("UserController, controller/user-controller")
        let model: UserModel = {
            email: "not-valid-email",
            displayName: "Nobita Nobi",
            item: null
        }
        test.setValue([model], clazz, "noValidator")
        let isValid = test.isValid();
        Chai.expect(isValid).true
    })

    it("Should not error if provided other decorator", () => {
        let test = new ValidatorImpl(storage, [new ExternalValidator()])
        let clazz = storage.get("UserController, controller/user-controller")
        let model: UserModel = {
            email: "not-valid-email",
            displayName: "Nobita Nobi",
            item: null
        }
        test.setValue([model], clazz, "customDecorator")
        let isValid = test.isValid();
        Chai.expect(isValid).true
    })

    it("Should able to use external validator", () => {
        let test = new ValidatorImpl(storage, [new ExternalValidator()])
        let clazz = storage.get("UserController, controller/user-controller")
        let model: UserModel = {
            email: "nobita@yahoo.com",
            displayName: "Nobita Nobi",
            item: null
        }
        test.setValue([model], clazz, "saveUser")
        let isValid = test.isValid();
        Chai.expect(isValid).true
    })
})


text:
package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
)

func main() {
	app := cli.NewApp()
	app.Name = "nsinit"
	app.Version = "2"
	app.Author = "libcontainer maintainers"
	app.Flags = []cli.Flag{
		cli.StringFlag{Name: "root", Value: "/var/run/nsinit", Usage: "root directory for containers"},
		cli.StringFlag{Name: "log-file", Value: "", Usage: "set the log file to output logs to"},
		cli.BoolFlag{Name: "debug", Usage: "enable debug output in the logs"},
	}
	app.Commands = []cli.Command{
		configCommand,
		execCommand,
		initCommand,
		oomCommand,
		pauseCommand,
		statsCommand,
		unpauseCommand,
		stateCommand,
	}
	app.Before = func(context *cli.Context) error {
		if context.GlobalBool("debug") {
			log.SetLevel(log.DebugLevel)
		}
		if path := context.GlobalString("log-file"); path != "" {
			f, err := os.Create(path)
			if err != nil {
				return err
			}
			log.SetOutput(f)
		}
		return nil
	}
	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}


text:
[![Build Status](http://img.shields.io/travis/ONSdigital/ons-data-api.svg)](https://travis-ci.org/ONSdigital/ons-data-api)
[![Dependency Status](http://img.shields.io/gemnasium/ONSdigital/ons-data-api.svg)](https://gemnasium.com/ONSdigital/ons-data-api)
[![Code Climate](http://img.shields.io/codeclimate/github/ONSdigital/ons-data-api.svg)](https://codeclimate.com/github/ONSdigital/ons-data-api)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://ONSdigital.mit-license.org)
[![Badges](http://img.shields.io/:badges-5/5-ff6799.svg)](https://github.com/pikesley/badger)

For background and context on this project see [https://github.com/ONSdigital/prototype-frontend](https://github.com/ONSdigital/prototype-frontend).

THIS IS PURELY A PROTOTYPE. THIS IS NOT A SOURCE OF TRUTH OR OFFICIAL ONS DATA.

Open Statistics Prototype API
=============================

This is a prototype API used in the implementation of the [Open Statistics prototype](https://github.com/ONSdigital/prototype-frontend). It is not a finished application and only implements enough functionality to support the prototype application.

The code is dependent on some [shared data models](https://github.com/ONSdigital/ons_data_models) that are used to access a MongoDB database which contains the statistical data being queried.

The key functionality exposed by the API is:

* Expose a JSON representation of the key model objects, e.g. Series, Releases, Datasets, and Observations
* Expose a simple API for querying over the set of Observations associated with a Dataset, e.g. to filter observations to those that match a specific set of dimension values.

Broadly, each of the model objects is exposed as a resource that can be directly accessed through the API, returning a JSON description of the resource.

Example URIs include:

* Series: `/series/producer-price-index.json`
* Releases in a series: `/series/producer-price-index/releases.json`
* An individual Release: `/series/producer-price-index/releases/2014-02-18.json`
* Datasets in a Release: `/series/producer-price-index/releases/2014-02-18/datasets.json`
* An individual Dataset: `/series/producer-price-index/releases/2014-02-18/datasets/ppi-csdb-ds.json`
* An Observation in a Dataset: `/series/producer-price-index/releases/2014-02-18/datasets/ppi-csdb-ds/observations/mca5-2013may.json`
* Query over Observations in a Dataset to generate a slice: `/series/producer-price-index/releases/2014-02-18/datasets/ppi-csdb-ds/observations.json?product=MCA5&date=2013APR`

The JSON responses use a custom format. The are some standard keys that are present for all objects (e.g. `slug`, `url`). Related objects are described by nested JSON objects, these references don't include the full description of the resource, typically just a url and a title to allow links to be built on web pages and for the API to be traversed.

The frontend application typically makes several API requests to build each page, e.g. to fetch metadata for an Observation, its Dataset, etc.

The API support for querying is implemented in the `[Dataset.slice](https://github.com/ONSdigital/ons_data_models/blob/master/app/models/dataset.rb#L104)` method in the , in the Dataset object. The API query is turned into a Mongo query based on the search parameters with some expansion.

For more background on the design of the API, read [the original design document](http://open-statistics.herokuapp.com/about/technical-architecture) the API designed there is not completely implemented, but the core elements are in place.

## Deploying the API

### Installing the API

First install the basic dependencies:

* Ruby 2.1
* Ruby gems
* [Bundler](http://bundler.io/)
* [MongoDB](https://www.mongodb.org/) for local development and testing

This provides a basic environment. To install the ruby libraries used in the application run:

```
bundle install
```

This will install all of the necessary dependencies which are listed in the `Gemfile`. A key dependency is the `ons_data_models` project which contains the code necessary to interact with the database.

### Running the API Locally

The API expects to talk to a MongoDB database in order to fetch the required data. Mongo is accessed via the [Mongoid](http://mongoid.org/en/mongoid/index.html) library.

The Mongo connection details can be found in `mongoid.yml`. By default the development version will run against a local database called `ons_poc_data_development`. This is the database which the [data conversion scripts](https://github.com/ONSdigital/ons-poc-data) populate, so run those first if you need some initial data.

To use a different database, then edit `mongoid.yml` to alter the connection details.

If Mongo is running, then to run the application locally, just run:

```
bundle exec rackup
```

This should start the application running against the local development database.

To use a different environment then change the value of the `RACK_ENV` environment variable.

### Running the API on Heroku

See the Mongo documentation on deploying Rack applications. All of the essential configuration is included in the project.

The deployed demo application uses a Mongo instance hosted in MongoHQ. An environment variable is used to configure the URL for the database `MONGOHQ_URL`. This will need to be configured.

The `RACK_ENV` environment variable should be set to be `production`.


text:
'use strict';

const Boom = require('boom');
const Person = require('../../../models/Person');
const objIsEmpty = require('../common.js').objIsEmpty;

module.exports.verifyUniqueUser = function (request, reply) {

  // Find an entry from the database that
  // matches either the email
  Person.query()
        .where('email', request.payload.email)
        .then(person => {

          // Check whether the email
          // is already taken and error out if so
          //if(person.length !== 0){
          if(!objIsEmpty(person)){

            if(person[0].email === request.payload.email){

              var error = Boom.create(400, 'Bad request', { timestamp: Date.now() });
              reply(error);
              return;
            }
          }
          // If everything checks out, send the payload through
          // to the route handler

          reply(request.payload);
        })
        .catch((err) => {
          console.log(err);
        });
};

module.exports.emailIsExist = function (email, doneChecking) {

  // Find an entry from the database that
  // matches either the email
  Person.query()
        .where('email', email)
        .then(person => {

          // Check whether the email
          // is already taken and error out if so
          //if(person.length !== 0){
          if(objIsEmpty(person)){

            return;
          }

          doneChecking(person[0].salt);
        })
        .catch((err) => {
          console.log(err);
        });

  //call back
  // doneChecking(salt);
};


text:
package com.smoketurner.uploader.handler;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.Lists;
import io.netty.handler.ipfilter.IpSubnetFilterRule;
import java.net.InetSocketAddress;
import java.util.List;
import org.junit.Test;

public class AccessControlListFilterTest {

  @Test
  public void testGetRules() {
    final List<String> accept = Lists.newArrayList("127.0.0.1", "10.0.0.0/8");
    final List<String> reject = Lists.newArrayList("3.0.0.0/8");

    final IpSubnetFilterRule[] actual = AccessControlListFilter.getRules(accept, reject);

    assertThat(actual[0].matches(newSockAddress("127.0.0.1"))).isTrue();
    assertThat(actual[1].matches(newSockAddress("10.57.30.10"))).isTrue();
    assertThat(actual[2].matches(newSockAddress("3.113.4.4"))).isTrue();
  }

  private static InetSocketAddress newSockAddress(String ipAddress) {
    return new InetSocketAddress(ipAddress, 8080);
  }
}


text:
export class ImportGraphResult {
  type: string;
  content: string;
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_add_group"
        android:icon="@drawable/ic_add"
        android:title="@string/action_add_group"
        app:showAsAction="ifRoom"/>
</menu>


text:
.console-container{padding-top:30px;padding-bottom:100px}
.account-pannel dt,.account-pannel dd{padding:6px 3px}
.user-avatar{margin-top:20px}
img.user-logo-img{width:100px;height:100px;border-radius:100px;border:1px solid #ddd;-webkit-box-shadow:2px 2px 2px #888;box-shadow:2px 2px 2px #888}
.username{font-size:18px;font-weight:bold;padding:20px 0}
.operation-result{width:80%;margin:50px auto}


text:
package com.dd;

import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;

public class ComposeAction extends AnAction {

    private static final String DECOMPOSE = "Ungroup";
    private static final String COMPOSE = "Group";

    @Override
    public void actionPerformed(AnActionEvent actionEvent) {
        Object nav = actionEvent.getData(CommonDataKeys.NAVIGATABLE);
        if (nav instanceof PsiDirectory) {
            PsiDirectory directory = (PsiDirectory) nav;

            String path = directory.getVirtualFile().getPath();

            if (SettingsManager.isComposed(path)) {
                SettingsManager.removeComposedFolder(path);
            } else {
                SettingsManager.addComposedFolder(path);
            }

            Project project = actionEvent.getData(CommonDataKeys.PROJECT);
            if (project != null) {
                ProjectView.getInstance(project).refresh();
            }
        }
    }

    @Override
    public void update(AnActionEvent actionEvent) {
        boolean enabledAndVisible = false;
        Project project = actionEvent.getData(CommonDataKeys.PROJECT);
        if (project != null) {
            Object nav = actionEvent.getData(CommonDataKeys.NAVIGATABLE);

            if (nav instanceof PsiDirectory) {
                PsiDirectory directory = (PsiDirectory) nav;

                String path = directory.getVirtualFile().getPath();

                if (SettingsManager.isComposed(path)) {
                    actionEvent.getPresentation().setText(DECOMPOSE);
                } else {
                    actionEvent.getPresentation().setText(COMPOSE);
                }

                enabledAndVisible = true;
            }
        }
        actionEvent.getPresentation().setEnabledAndVisible(enabledAndVisible);
    }
}


text:
#ifndef LOVE_PHYSICS_BOX2D_WRAP_SHAPE_H
#define LOVE_PHYSICS_BOX2D_WRAP_SHAPE_H

// LOVE
#include "common/runtime.h"
#include "Shape.h"
#include "wrap_Physics.h"

namespace love
{
namespace physics
{
namespace box2d
{

Shape *luax_checkshape(lua_State *L, int idx);
int w_Shape_getType(lua_State *L);
int w_Shape_getRadius(lua_State *L);

int w_Shape_getChildCount(lua_State *L);
int w_Shape_testPoint(lua_State *L);
int w_Shape_rayCast(lua_State *L);
int w_Shape_computeAABB(lua_State *L);
int w_Shape_computeMass(lua_State *L);

extern "C" int luaopen_shape(lua_State *L);

} // box2d
} // physics
} // love

#endif // LOVE_PHYSICS_BOX2D_WRAP_SHAPE_H


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="de.nordakademie.mobile.innovation" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>SmartKitchen</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@callback.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
</widget>


text:
English Words

Turkish Meanings

English Words

Turkish Meanings

in a bad way

kötü bir durumda

adventure

riske atmak, macera

effort

cehd

approach

yaklaşım

situation

vaziyet

study

irdelemek

example

numune

instance

örnek(aşama)

thought

tefekkür, görüş

judgment

muhakeme

pen pal/

-mektup arkadaşı

derived/

türetmek

feel/

kızgın

perceive/

algılamak

sentence

hüküm

refer/

ima etmek

placement/

yerleştirme

put

yerleştirmek, koyulmak

perform/

yerine getirmek

/carry out/

gerçekleştirmek

might(modal)

fiilen gerçekleşmeyen kuramsal durumlar

might/

geçici olarak izin istemek

may(modal)

mümkün olan olgusal durumlar

may/

yapmadan önce olan bir şeyi kabul etmek

make

meydana getirmek

chase

peşine düşmek

tag

yafta, künye

have

malik olmak, haiz olmak

/appear/

görünmek

/range/

sıralı olmak

/dense/

sık

/cluster/

hevenk

associate

bağdaştırmak

/by which/

-e neden olan

/go about/

başlamak

/means/

vesile

/closet/

dolap

/shove/

tıkıştırmak

way

yöntem, davranış tarzı

/although/

rağmen

hunt

aramak, araştırmak

search

araştırmak, arayış

/Even though/

Buna rağmen

confused

aklı karışmış

/impossibly/

imkansız bir şekilde

/show up/

boy göstermek

/spoil/

bozulmak

/onto/

üzerine

keep

bakım yapıp saklamak , zarardan korumak, sürdürmek

feel

duygu, his (bir şeyin dokununca uyandırdığı)

sense

sezmek

/to be aware of/

farkında olmak

/awareness/

farkında olma

/property/

özellik

delight

keyif, sevinç

available

müsait, yararlanılır

x

x, x

x

x x


text:
<?php declare(strict_types=1);

namespace Composer\Test\Package\Loader;

use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\Link;
use Composer\Test\TestCase;

class ArrayLoaderTest extends TestCase
{
    /**
     * @var ArrayLoader
     */
    private $loader;

    public function setUp(): void
    {
        $this->loader = new ArrayLoader(null);
    }

    public function testSelfVersion(): void
    {
        $config = [
            'name' => 'A',
            'version' => '1.2.3.4',
            'replace' => [
                'foo' => 'self.version',
            ],
        ];

        $package = $this->loader->load($config);
        $replaces = $package->getReplaces();
        $this->assertEquals('== 1.2.3.4', (string) $replaces['foo']->getConstraint());
    }

    public function testTypeDefault(): void
    {
        $config = [
            'name' => 'A',
            'version' => '1.0',
        ];

        $package = $this->loader->load($config);
        $this->assertEquals('library', $package->getType());

        $config = [
            'name' => 'A',
            'version' => '1.0',
            'type' => 'foo',
        ];

        $package = $this->loader->load($config);
        $this->assertEquals('foo', $package->getType());
    }

    public function testNormalizedVersionOptimization(): void
    {
        $config = [
            'name' => 'A',
            'version' => '1.2.3',
        ];

        $package = $this->loader->load($config);
        $this->assertEquals('1.2.3.0', $package->getVersion());

        $config = [
            'name' => 'A',
            'version' => '1.2.3',
            'version_normalized' => '1.2.3.4',
        ];

        $package = $this->loader->load($config);
        $this->assertEquals('1.2.3.4', $package->getVersion());
    }

    public function parseDumpProvider(): array
    {
        $validConfig = [
            'name' => 'A/B',
            'version' => '1.2.3',
            'version_normalized' => '1.2.3.0',
            'description' => 'Foo bar',
            'type' => 'library',
            'keywords' => ['a', 'b', 'c'],
            'homepage' => 'http://example.com',
            'license' => ['MIT', 'GPLv3'],
            'authors' => [
                ['name' => 'Bob', 'email' => 'bob@example.org', 'homepage' => 'example.org', 'role' => 'Developer'],
            ],
            'funding' => [
                ['type' => 'example', 'url' => 'https://example.org/fund'],
            ],
            'require' => [
                'foo/bar' => '1.0',
            ],
            'require-dev' => [
                'foo/baz' => '1.0',
            ],
            'replace' => [
                'foo/qux' => '1.0',
            ],
            'conflict' => [
                'foo/quux' => '1.0',
            ],
            'provide' => [
                'foo/quuux' => '1.0',
            ],
            'autoload' => [
                'psr-0' => ['Ns\Prefix' => 'path'],
                'classmap' => ['path', 'path2'],
            ],
            'include-path' => ['path3', 'path4'],
            'target-dir' => 'some/prefix',
            'extra' => ['random' => ['things' => 'of', 'any' => 'shape']],
            'bin' => ['bin1', 'bin/foo'],
            'archive' => [
                'exclude' => ['/foo/bar', 'baz', '!/foo/bar/baz'],
            ],
            'transport-options' => ['ssl' => ['local_cert' => '/opt/certs/test.pem']],
            'abandoned' => 'foo/bar',
        ];

        return [[$validConfig]];
    }

    /**
     * @param array<string, mixed> $config
     *
     * @return array<string, mixed>
     */
    protected function fixConfigWhenLoadConfigIsFalse(array $config): array
    {
        $expectedConfig = $config;
        unset($expectedConfig['transport-options']);

        return $expectedConfig;
    }

    /**
     * The default parser should default to loading the config as this
     * allows require-dev libraries to have transport options included.
     *
     * @dataProvider parseDumpProvider
     *
     * @param array<string, mixed> $config
     */
    public function testParseDumpDefaultLoadConfig(array $config): void
    {
        $package = $this->loader->load($config);
        $dumper = new ArrayDumper;
        $expectedConfig = $this->fixConfigWhenLoadConfigIsFalse($config);
        $this->assertEquals($expectedConfig, $dumper->dump($package));
    }

    /**
     * @dataProvider parseDumpProvider
     *
     * @param array<string, mixed> $config
     */
    public function testParseDumpTrueLoadConfig(array $config): void
    {
        $loader = new ArrayLoader(null, true);
        $package = $loader->load($config);
        $dumper = new ArrayDumper;
        $expectedConfig = $config;
        $this->assertEquals($expectedConfig, $dumper->dump($package));
    }

    /**
     * @dataProvider parseDumpProvider
     *
     * @param array<string, mixed> $config
     */
    public function testParseDumpFalseLoadConfig(array $config): void
    {
        $loader = new ArrayLoader(null, false);
        $package = $loader->load($config);
        $dumper = new ArrayDumper;
        $expectedConfig = $this->fixConfigWhenLoadConfigIsFalse($config);
        $this->assertEquals($expectedConfig, $dumper->dump($package));
    }

    public function testPackageWithBranchAlias(): void
    {
        $config = [
            'name' => 'A',
            'version' => 'dev-master',
            'extra' => ['branch-alias' => ['dev-master' => '1.0.x-dev']],
        ];

        $package = $this->loader->load($config);

        $this->assertInstanceOf('Composer\Package\AliasPackage', $package);
        $this->assertEquals('1.0.x-dev', $package->getPrettyVersion());

        $config = [
            'name' => 'A',
            'version' => 'dev-master',
            'extra' => ['branch-alias' => ['dev-master' => '1.0-dev']],
        ];

        $package = $this->loader->load($config);

        $this->assertInstanceOf('Composer\Package\AliasPackage', $package);
        $this->assertEquals('1.0.x-dev', $package->getPrettyVersion());

        $config = [
            'name' => 'B',
            'version' => '4.x-dev',
            'extra' => ['branch-alias' => ['4.x-dev' => '4.0.x-dev']],
        ];

        $package = $this->loader->load($config);

        $this->assertInstanceOf('Composer\Package\AliasPackage', $package);
        $this->assertEquals('4.0.x-dev', $package->getPrettyVersion());

        $config = [
            'name' => 'B',
            'version' => '4.x-dev',
            'extra' => ['branch-alias' => ['4.x-dev' => '4.0-dev']],
        ];

        $package = $this->loader->load($config);

        $this->assertInstanceOf('Composer\Package\AliasPackage', $package);
        $this->assertEquals('4.0.x-dev', $package->getPrettyVersion());

        $config = [
            'name' => 'C',
            'version' => '4.x-dev',
            'extra' => ['branch-alias' => ['4.x-dev' => '3.4.x-dev']],
        ];

        $package = $this->loader->load($config);

        $this->assertInstanceOf('Composer\Package\CompletePackage', $package);
        $this->assertEquals('4.x-dev', $package->getPrettyVersion());
    }

    public function testAbandoned(): void
    {
        $config = [
            'name' => 'A',
            'version' => '1.2.3.4',
            'abandoned' => 'foo/bar',
        ];

        $package = $this->loader->load($config);
        $this->assertTrue($package->isAbandoned());
        $this->assertEquals('foo/bar', $package->getReplacementPackage());
    }

    public function testNotAbandoned(): void
    {
        $config = [
            'name' => 'A',
            'version' => '1.2.3.4',
        ];

        $package = $this->loader->load($config);
        $this->assertFalse($package->isAbandoned());
    }

    public function providePluginApiVersions(): array
    {
        return [
            ['1.0'],
            ['1.0.0'],
            ['1.0.0.0'],
            ['1'],
            ['=1.0.0'],
            ['==1.0'],
            ['~1.0.0'],
            ['*'],
            ['3.0.*'],
            ['@stable'],
            ['1.0.0@stable'],
            ['^5.1'],
            ['>=1.0.0 <2.5'],
            ['x'],
            ['1.0.0-dev'],
        ];
    }

    /**
     * @dataProvider providePluginApiVersions
     */
    public function testPluginApiVersionAreKeptAsDeclared(string $apiVersion): void
    {
        $links = $this->loader->parseLinks('Plugin', '9.9.9', Link::TYPE_REQUIRE, ['composer-plugin-api' => $apiVersion]);

        $this->assertArrayHasKey('composer-plugin-api', $links);
        $this->assertSame($apiVersion, $links['composer-plugin-api']->getConstraint()->getPrettyString());
    }

    public function testPluginApiVersionDoesSupportSelfVersion(): void
    {
        $links = $this->loader->parseLinks('Plugin', '6.6.6', Link::TYPE_REQUIRE, ['composer-plugin-api' => 'self.version']);

        $this->assertArrayHasKey('composer-plugin-api', $links);
        $this->assertSame('6.6.6', $links['composer-plugin-api']->getConstraint()->getPrettyString());
    }

    public function testParseLinksIntegerTarget(): void
    {
        $links = $this->loader->parseLinks('Plugin', '9.9.9', Link::TYPE_REQUIRE, ['1' => 'dev-main']);

        $this->assertArrayHasKey('1', $links);
    }

    public function testNoneStringVersion(): void
    {
        $config = [
            'name' => 'acme/package',
            'version' => 1,
        ];

        $package = $this->loader->load($config);
        $this->assertSame('1', $package->getPrettyVersion());
    }

    public function testNoneStringSourceDistReference(): void
    {
        $config = [
            'name' => 'acme/package',
            'version' => 'dev-main',
            'source' => [
                'type' => 'svn',
                'url' => 'https://example.org/',
                'reference' => 2019,
            ],
            'dist' => [
                'type' => 'zip',
                'url' => 'https://example.org/',
                'reference' => 2019,
            ],
        ];

        $package = $this->loader->load($config);
        $this->assertSame('2019', $package->getSourceReference());
        $this->assertSame('2019', $package->getDistReference());
    }

    public function testBranchAliasIntegerIndex(): void
    {
        $config = [
            'name' => 'acme/package',
            'version' => 'dev-1',
            'extra' => [
                'branch-alias' => [
                    '1' => '1.3-dev',
                ],
            ],
            'dist' => [
                'type' => 'zip',
                'url' => 'https://example.org/',
            ],
        ];

        $this->assertNull($this->loader->getBranchAlias($config));
    }

    public function testPackageLinksRequire(): void
    {
        $config = array(
            'name' => 'acme/package',
            'version' => 'dev-1',
            'require' => [
                'foo/bar' => '1.0',
            ],
        );

        $package = $this->loader->load($config);
        $this->assertArrayHasKey('foo/bar', $package->getRequires());
        $this->assertSame('1.0', $package->getRequires()['foo/bar']->getConstraint()->getPrettyString());
    }

    public function testPackageLinksRequireInvalid(): void
    {
        $config = array(
            'name' => 'acme/package',
            'version' => 'dev-1',
            'require' => [
                'foo/bar' => [
                    'random-string' => '1.0',
                ],
            ],
        );

        $package = $this->loader->load($config);
        $this->assertCount(0, $package->getRequires());
    }

    public function testPackageLinksReplace(): void
    {
        $config = array(
            'name' => 'acme/package',
            'version' => 'dev-1',
            'replace' => [
                'coyote/package' => 'self.version',
            ],
        );

        $package = $this->loader->load($config);
        $this->assertArrayHasKey('coyote/package', $package->getReplaces());
        $this->assertSame('dev-1', $package->getReplaces()['coyote/package']->getConstraint()->getPrettyString());
    }

    public function testPackageLinksReplaceInvalid(): void
    {
        $config = array(
            'name' => 'acme/package',
            'version' => 'dev-1',
            'replace' => 'coyote/package',
        );

        $package = $this->loader->load($config);
        $this->assertCount(0, $package->getReplaces());
    }
}


text:
package com.abilists.controller.works;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.abilists.bean.AbilistsModel;
import com.abilists.bean.MemoSortBean;
import com.abilists.bean.model.sum.UserMemoSumByMonthModel;
import com.abilists.bean.model.user.UsersModel;
import com.abilists.bean.model.works.UserMemoModel;
import com.abilists.bean.para.admin.SrhAutoCompletePara;
import com.abilists.bean.para.memo.DltMemoPara;
import com.abilists.bean.para.memo.IstMemoPara;
import com.abilists.bean.para.memo.MemoListAjax;
import com.abilists.bean.para.memo.UdtMemoPara;
import com.abilists.bean.para.memo.UdtMemoSortPara;
import com.abilists.core.common.bean.CommonBean;
import com.abilists.core.controller.AbstractBaseController;
import com.abilists.core.service.UsersService;
import com.abilists.core.service.profile.ProfileService;
import com.abilists.core.service.works.MemoService;

import base.bean.para.CommonPara;
import io.utility.security.TokenUtility;

@Controller
@RequestMapping("/works")
public class MemoAbilistsController extends AbstractBaseController {

	final Logger logger = LoggerFactory.getLogger(MemoAbilistsController.class);
	private String MESSAGE_CODE = "parameter.error.invalid";

	@Autowired
	private ProfileService profileService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private MemoService memoService;
	@Autowired
	private CommonBean commonBean;

    @RequestMapping(value = { "/{userId}/sltMemoList" })
	public String sltMemoList(@PathVariable String userId, HttpSession session, ModelMap model) throws Exception {

		AbilistsModel abilistsModel = new AbilistsModel();
		abilistsModel.setMenu("sltMemoList");

		// Set user id
		CommonPara commonPara = new CommonPara();
		commonPara.setUserId(userId);

		// User information in profile
		UsersModel users = profileService.sltUser(commonPara);
		abilistsModel.setUsers(users);

		// Set Paging list
		int intSum = memoService.sltMemoSum(commonPara);
		abilistsModel.setPaging(usersService.makePaging(commonPara, intSum));

		// Get user projects, 0 is default row
		List<UserMemoModel> userMemoList = memoService.sltMemoHtmlList(commonPara, 0);
		abilistsModel.setUserMemoList(userMemoList);

		// Chart for memo
		List<UserMemoSumByMonthModel> userMemoSumByMonthList = memoService.sltUserMemoSumByMonthList(commonPara);
		abilistsModel.setUserMemoSumByMonthList(userMemoSumByMonthList);

		model.addAttribute("model", abilistsModel);

		// User information in profile
		UsersModel user = (UsersModel) session.getAttribute("user");
		// Read only from other users
		if (!userId.equals(user.getUserId())) {
			model.addAttribute("view", "true");
			return "apps/works/viewMemoList";
		}

		abilistsModel.setNavi("works");

		// Get key and token
		String token = TokenUtility.generateToken(TokenUtility.SHA_256);
		String key = this.makeKey(commonPara.getUserId(), AbstractBaseController.PREFIX_UDT_KEY);
		commonBean.addTokenExpireMap(key, token);
		abilistsModel.setToken(token);

		model.addAttribute("model", abilistsModel);

		return "apps/works/sltMemoList";
	}

	@RequestMapping(value = {"istMemo"})
	public String istMemo(@Valid IstMemoPara istMemoPara,
			BindingResult bindingResult, ModelMap model, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception {

		AbilistsModel abilistsModel = new AbilistsModel();
		abilistsModel.setNavi("works");
		abilistsModel.setMenu("sltMemoList");

		// Set language in Locale.
		Locale locale = RequestContextUtils.getLocale(request);

		Map<String, String> mapErrorMessage = null;
		// If it occurs errors, set the default value.
		if (bindingResult.hasErrors()) {
			logger.error("istMemo - Parameter error occured.");
			response.setStatus(400);
			mapErrorMessage = this.handleErrorMessages(bindingResult.getAllErrors(), MESSAGE_CODE, locale);
			model.addAttribute("mapErrorMessage",  mapErrorMessage);

			return "apps/errors/error";
		}

		// Set user id
		this.handleSessionInfo(request.getSession(), istMemoPara);

		// Validate token
		String key = this.makeKey(istMemoPara.getUserId(), AbstractBaseController.PREFIX_UDT_KEY);
		if(!istMemoPara.getToken().equals(commonBean.getTokenExpireMap(key))) {
			logger.error("istMemo - Token error occured.");
			model.addAttribute("errorMessage", message.getMessage("parameter.error.message", null, LOCALE));
			return "apps/errors/error";
		}

		// Execute the transaction
		if(!memoService.istMemo(istMemoPara)) {
			logger.error("istMemo - Insert error occured.");
			model.addAttribute("errorMessage", message.getMessage("parameter.error.message", null, LOCALE));
			return "apps/errors/error";
		}

		// Pass the parameters with post.
		redirectAttributes.addFlashAttribute("save", "completed");
		return "redirect:/works/" + istMemoPara.getUserId() + "/sltMemoList";
	}

	@RequestMapping(value = {"udtMemo"})
	public String udtMemo(@Valid UdtMemoPara udtMemoPara,
			BindingResult bindingResult, ModelMap model, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception {

		AbilistsModel abilistsModel = new AbilistsModel();
		abilistsModel.setNavi("works");
		abilistsModel.setMenu("sltMemoList");

		// Set language in Locale.
		Locale locale = RequestContextUtils.getLocale(request);

		Map<String, String> mapErrorMessage = null;
		// If it occurs errors, set the default value.
		if (bindingResult.hasErrors()) {
			logger.error("udtMemo - There are parameter errors.");
			response.setStatus(400);
			mapErrorMessage = this.handleErrorMessages(bindingResult.getAllErrors(), MESSAGE_CODE, locale);
			model.addAttribute("mapErrorMessage",  mapErrorMessage);
			return "apps/errors/error";
		}

		// Set user id
		this.handleSessionInfo(request.getSession(), udtMemoPara);

		// Validate token
		String key = this.makeKey(udtMemoPara.getUserId(), AbstractBaseController.PREFIX_UDT_KEY);
		if(!udtMemoPara.getToken().equals(commonBean.getTokenExpireMap(key))) {
			model.addAttribute("errorMessage", message.getMessage("parameter.error.message", null, LOCALE));
			return "apps/errors/error";
		}

		// Execute the transaction
		if(!memoService.udtMemo(udtMemoPara)) {
			model.addAttribute("errorMessage", message.getMessage("parameter.error.message", null, locale));
			return "apps/errors/error";
		}

		// Pass the parameters with post.
		redirectAttributes.addFlashAttribute("save", "completed");

		return "redirect:/works/" + udtMemoPara.getUserId() + "/sltMemoList";
	}

	/**
	 * Get list more by Ajax
	 *
	 * @param commonPara
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "sltMemoListAjax" }, method = RequestMethod.POST)
	public @ResponseBody MemoListAjax sltMemoListAjax(@RequestBody CommonPara commonPara,
			HttpSession session) throws Exception {

//		// Set user id
//		this.handleSessionInfo(session, commonPara);
		logger.info("userId >> " + commonPara.getUserId());

		// Get tech list in detail.
		List<UserMemoModel> userMemoList = memoService.sltMemoHtmlList(commonPara, 0);
		logger.info("userMemoList size = " + userMemoList.size());

		MemoListAjax memoListAjax = new MemoListAjax();
		memoListAjax.setUserMemoList(userMemoList);

		return memoListAjax;
	}

	@RequestMapping(value="/{userId}/udtMemoSortAjax")
	public @ResponseBody UdtMemoSortPara udtMemoSortAjax(@RequestBody UdtMemoSortPara udtMemoSortPara,
			HttpSession session, HttpServletResponse response) throws Exception {

//		// Validate token
//		String key = this.makeKey(udtMemoSortPara.getUserId(), AbstractBaseController.PREFIX_UDT_KEY);
//		if(!udtMemoSortPara.getToken().equals(commonBean.getTokenExpireMap(key))) {
//			logger.info("token error >> " + udtMemoSortPara.getToken());
//			this.handleWriteAjax("error", response, AbstractBaseController.CONTENT_TYPE_JSON);
//			return null;
//		}

		for(MemoSortBean memoSortBean : udtMemoSortPara.getMemoSortBeanList()) {
			logger.info("umNo=" + memoSortBean.getUmNoOrder() + ", umSort=" + memoSortBean.getUmSortOrder());
		}

		// Set user id
		this.handleSessionInfo(session, udtMemoSortPara);

		// Get user Tasks.
		if(!memoService.udtMemoSort(udtMemoSortPara)) {
			logger.info("Sort error >> " + udtMemoSortPara.getToken());
			this.handleWriteAjax("error", response, AbstractBaseController.CONTENT_TYPE_JSON);
			return null;
		}

//		// Get key and token
//		String token = TokenUtility.generateToken(TokenUtility.SHA_256);
//		String key = this.makeKey(udtMemoSortPara.getUserId(), AbstractBaseController.PREFIX_UDT_KEY);
//		commonBean.addTokenExpireMap(key, token);

		return udtMemoSortPara;

//		HttpHeaders headers = new HttpHeaders();
//		MediaType mediaType = new MediaType("text", "html", Charset.forName("utf-8"));
//		headers.setContentType(mediaType);
//		return new ResponseEntity<UdtMemoSortPara>(headers, HttpStatus.OK);
	}

	/*
	 * Users by Ajax
	 */
    @RequestMapping(value="/{userId}/srhForMemoAjax")
	public @ResponseBody List<UserMemoModel> srhForMemoAjax(@PathVariable String userId,
			@Valid @RequestBody SrhAutoCompletePara srhAutoCompletePara, BindingResult bindingResult) throws Exception {

    	List<UserMemoModel> userMemoList = null;

		// If it occurs a error, set the default value.
		if (bindingResult.hasErrors()) {
			logger.warn("srhForMemoAjax - Special charaters are included in the parameters.");
			return new ArrayList<UserMemoModel>();
		}

		// Set userId
		srhAutoCompletePara.setUserId(userId);

		// Get user information
		userMemoList = memoService.srhMemoList(srhAutoCompletePara);

    	return userMemoList;
	}

	@RequestMapping(value = { "/{userId}/srhForMemo" })
	public String srhForMemo(@PathVariable String userId, @Valid SrhAutoCompletePara srhAutoCompletePara,
			BindingResult bindingResult, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		AbilistsModel abilistsModel = new AbilistsModel();
		abilistsModel.setNavi("works");
		abilistsModel.setMenu("sltMemoList");

		// Set language in Locale.
		Locale locale = RequestContextUtils.getLocale(request);

		// If it occurs a error, set the default value.
		Map<String, String> mapErrorMessage = null;
		// If it occurs errors, set the default value.
		if (bindingResult.hasErrors()) {
			logger.error("srhForMTechs - There are parameter errors.");
			response.setStatus(400);
			mapErrorMessage = this.handleErrorMessages(bindingResult.getAllErrors(), MESSAGE_CODE, locale);
			model.addAttribute("mapErrorMessage",  mapErrorMessage);
			return "apps/errors/error";
		}

		// Set userId
		srhAutoCompletePara.setUserId(userId);

		// TODO : If you are yourself, Not need to select your data.
		// User information in profile
		UsersModel users = profileService.sltUser(srhAutoCompletePara);
		abilistsModel.setUsers(users);

		// Get user information
		List<UserMemoModel> userMemoList = memoService.srhMemoHtmlList(srhAutoCompletePara);
		abilistsModel.setUserMemoList(userMemoList);

		// Get key and token
		String token = TokenUtility.generateToken(TokenUtility.SHA_256);
		String key = this.makeKey(srhAutoCompletePara.getUserId(), AbstractBaseController.PREFIX_UDT_KEY);
		commonBean.addTokenExpireMap(key, token);
		abilistsModel.setToken(token);

		model.addAttribute("model", abilistsModel);

		return "apps/works/sltMemoList";
	}

	@RequestMapping(value = {"dltMemo"})
	public String dltMemo(@Valid DltMemoPara dltMemoPara,
			BindingResult bindingResult, ModelMap model, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception {

		AbilistsModel abilistsModel = new AbilistsModel();
		abilistsModel.setNavi("works");
		abilistsModel.setMenu("sltProjectsList");

		// Set language in Locale.
		Locale locale = RequestContextUtils.getLocale(request);

		Map<String, String> mapErrorMessage = null;
		// If it occurs errors, set the default value.
		if (bindingResult.hasErrors()) {
			logger.error("dltProjects - There are parameter errors.");
			response.setStatus(400);
			mapErrorMessage = this.handleErrorMessages(bindingResult.getAllErrors(), MESSAGE_CODE, locale);
			model.addAttribute("mapErrorMessage",  mapErrorMessage);
			return "apps/errors/error";
		}

		// Set user Id
		this.handleSessionInfo(request.getSession(), dltMemoPara);

		// Validate token
		String key = this.makeKey(dltMemoPara.getUserId(), AbstractBaseController.PREFIX_UDT_KEY);
		if(!dltMemoPara.getToken().equals(commonBean.getTokenExpireMap(key))) {
			model.addAttribute("errorMessage", message.getMessage("parameter.error.message", null, LOCALE));
			return "apps/errors/error";
		}

		// Execute the transaction
		if(!memoService.dltMemo(dltMemoPara)) {
			model.addAttribute("errorMessage", message.getMessage("parameter.error.message", null, locale));
			return "apps/errors/error";
		}

		return "redirect:/works/" + dltMemoPara.getUserId() + "/sltMemoList";
	}

}


text:
My solutions to HackerRank problems.

My focus is to use the standard libraries extensively.

Files ending with CC contain C++ (TR1) code and files ending with CPP contain
C++14 code.


text:
const { BotkitConversation } = require('botkit');

module.exports = function(controller) {

    if (controller.adapter.name === 'Web Adapter') {

        console.log('Loading sample Websocket features...');

        controller.publicFolder('/',__dirname  + '/../public');

        /**
         * Send a message to new users / people with no user id cookie set
         */
        controller.on('hello', async(bot, message) => {
            await bot.reply(message,'Nice to meet you, human!');
        });

        /**
         * Send a message to returning users
         */
        controller.on('welcome_back', async(bot, message) => {
            await bot.reply(message,'Welcome back, human.');
        });

        /**
         * demo the use of the quick reply feature
         */
        controller.hears(new RegExp('quick'), 'message', async (bot, message) => {

            await bot.reply(message,{
                text: 'Here are some quick replies',
                quick_replies: [
                    {
                        title: 'Foo',
                        payload: 'foo',
                    },
                    {
                        title: 'Bar',
                        payload: 'bar',
                    }
                ]
            });
        });

        let typing = new BotkitConversation('typing', controller);

        typing.say('I am going to type for a while now...');
        typing.addAction('typing');

        // start the typing indicator
        typing.addMessage({type: 'typing'}, 'typing');
        // trigger a gotoThread, which gives us an opportunity to delay the next message
        typing.addAction('next_thread','typing');

        typing.addMessage('typed!','next_thread');

       // use the before handler to delay the next message
        typing.before('next_thread',  async() => {
            return new Promise((resolve, reject) => {
                // simulate some long running process
                setTimeout(resolve, 3000);
            });
        });

        controller.addDialog(typing);

        controller.hears('typing dialog', 'message', async(bot, message) => {
            await bot.beginDialog('typing');
        });

        controller.hears('typing reply', 'message', async(bot, message) => {

            await bot.reply(message, {type: 'typing'});

            setTimeout(async () => {
                // will have to reset context because turn has now ended.
                await bot.changeContext(message.reference);
                await bot.reply(message, 'Typed!');
            }, 1000);

        });

        let replies = new BotkitConversation('replies', controller);
        replies.ask({
            text: 'Click one of these suggestions!',
            quick_replies: [
                {
                    title: 'Foo',
                    payload: 'foo',
                },
                {
                    title: 'Bar',
                    payload: 'bar',
                }
            ]
        }, [], 'reply');
        replies.say('You clicked {{vars.reply}}');
        replies.ask({
            text: 'Click one of these suggestions!',
            quick_replies: [
                {
                    title: 'Norm',
                    payload: 'norm',
                },
                {
                    title: 'Flarm',
                    payload: 'flarm',
                }
            ]
        }, async(response, convo, bot, message) => {
            console.log('GOT REPLY', response);
            console.log('FULL PAyLOAD',message);
        }, 'reply');
        replies.say('You clicked {{vars.reply}}');

        controller.addDialog(replies);

        controller.hears('qqq', 'message', async(bot, message) => {
            await bot.beginDialog('replies');
        });

    }

}


text:
package kata.app;

import org.apache.logging.log4j.simple.*;
import org.apache.logging.log4j.*;
import org.apache.logging.log4j.util.PropertiesUtil;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class HelloLog4J2SimpleLogger {

    public static void main(String... args) {
        System.out.println("Hello Log4J2 SimpleLogger!");

        PrintStream ps = new PrintStream(new FileOutputStream(FileDescriptor.out));

        SimpleLogger logger = new SimpleLogger(
            "kata.app.HelloLog4J2SimpleLogger", Level.DEBUG, true, true, true, true, "DD/MM/YY", null, PropertiesUtil.getProperties(), ps);

        logger.info("This is an information entry");
        logger.debug("This is a debugging entry");
        logger.warn("This is a warning entry");
        logger.error("This is an error entry");
    }
}


text:
pimcore.registerNS("pimcore.document.tags.renderlet");
pimcore.document.tags.renderlet = Class.create(pimcore.document.tag, {

    defaultHeight: 100,

    initialize: function(id, name, options, data, inherited) {
        this.id = id;
        this.name = name;
        this.options = this.parseOptions(options);

        //TODO maybe there is a nicer way, the Panel doesn't like this
        this.controller = options.controller;
        delete(options.controller);

        this.data = {};

        if (!data) {
            data = {};
        }

        // height management
        this.defaultHeight = 100;
        if (this.options.defaultHeight) {
            this.defaultHeight = this.options.defaultHeight;
        }
        if (!this.options.height && !data.path) {
            this.options.height = this.defaultHeight;
        }

        this.setupWrapper();

        this.options.name = id + "_editable";
        this.options.border = false;
        this.options.bodyStyle = "min-height: 40px;";

        this.element = new Ext.Panel(this.options);

        this.element.on("render", function (el) {

            // register at global DnD manager
            dndManager.addDropTarget(el.getEl(), this.onNodeOver.bind(this), this.onNodeDrop.bind(this));

            this.getBody().setStyle({
                overflow: "auto"
            });

            this.getBody().insertHtml("beforeEnd",'

');
            this.getBody().addCls("pimcore_tag_snippet_empty");

            el.getEl().on("contextmenu", this.onContextMenu.bind(this));

        }.bind(this));

        this.element.render(id);

        // insert snippet content
        if (data) {
            this.data = data;
            if (this.data.id) {
                this.updateContent();
            }
        }
    },

    onNodeDrop: function (target, dd, e, data) {

        // get path from nodes data
        this.data.id = data.node.attributes.id;
        this.data.type = data.node.attributes.elementType;
        this.data.subtype = data.node.attributes.type;

        if (this.options.reload) {
            this.reloadDocument();
        } else {
            this.updateContent();
        }

        return true;
    },

    onNodeOver: function(target, dd, e, data) {

        return Ext.dd.DropZone.prototype.dropAllowed;

    },

    getBody: function () {
        // get the id from the body element of the panel because there is no method to set body's html
        // (only in configure)
        var bodyId = this.element.getEl().query(".x-panel-body")[0].getAttribute("id");
        return Ext.get(bodyId);
    },

    updateContent: function (path) {

        this.getBody().removeCls("pimcore_tag_snippet_empty");
        this.getBody().dom.innerHTML = '
  Loading ...';

        var params = this.data;
        params.controller = this.controller;
        Ext.apply(params, this.options);

        try {
            // add the id of the current document, so that the renderlet knows in which document it is embedded
            // this information is then grabbed in Pimcore_Controller_Action_Frontend::init() to set the correct locale
            params["pimcore_parentDocument"] = window.editWindow.document.id;
        } catch (e) {

        }

        Ext.Ajax.request({
            method: "get",
            url: "/pimcore_document_tag_renderlet",
            success: function (response) {
                this.getBody().dom.innerHTML = response.responseText;
                this.getBody().insertHtml("beforeEnd",'

');
                this.updateDimensions();
            }.bind(this),
            params: params
        });
    },

    updateDimensions: function () {
        this.getBody().setStyle({
            height: "auto"
        });
    },

    onContextMenu: function (e) {

        var menu = new Ext.menu.Menu();

        if(this.data["id"]) {
            menu.add(new Ext.menu.Item({
                text: t('empty'),
                iconCls: "pimcore_icon_delete",
                handler: function () {
                    var height = this.options.height;
                    if (!height) {
                        height = this.defaultHeight;
                    }
                    this.data = {};
                    this.getBody().update('');
                    this.getBody().insertHtml("beforeEnd",'

');
                    this.getBody().addCls("pimcore_tag_snippet_empty");
                    this.getBody().setHeight(height + "px");

                    if (this.options.reload) {
                        this.reloadDocument();
                    }

                }.bind(this)
            }));

            menu.add(new Ext.menu.Item({
                text: t('open'),
                iconCls: "pimcore_icon_open",
                handler: function () {
                    if(this.data.id) {
                        pimcore.helpers.openElement(this.data.id, this.data.type, this.data.subtype);
                    }
                }.bind(this)
            }));

            menu.add(new Ext.menu.Item({
                text: t('show_in_tree'),
                iconCls: "pimcore_icon_fileexplorer",
                handler: function (item) {
                    item.parentMenu.destroy();
                    pimcore.helpers.selectElementInTree(this.data.type, this.data.id);
                }.bind(this)
            }));
        }

        menu.add(new Ext.menu.Item({
            text: t('search'),
            iconCls: "pimcore_icon_search",
            handler: function (item) {
                item.parentMenu.destroy();

                this.openSearchEditor();
            }.bind(this)
        }));

        menu.showAt(e.getXY());

        e.stopEvent();
    },

    openSearchEditor: function () {
        pimcore.helpers.itemselector(false, this.addDataFromSelector.bind(this), {});
    },

    addDataFromSelector: function (item) {
        if(item) {
            // get path from nodes data
            this.data.id = item.id;
            this.data.type = item.type;
            this.data.subtype = item.subtype;

            if (this.options.reload) {
                this.reloadDocument();
            } else {
                this.updateContent();
            }
        }
    },

    getValue: function () {
        return this.data;
    },

    getType: function () {
        return "renderlet";
    }
});


text:
var database = null;

module.exports.setConfig = function (options) {
  database = options.database || null;
  database.setConfig(options);
};

module.exports.getDatabase = function () {
  return database;
};


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.creators;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.CandidateInSequenceFinder;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.Item;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.Itemset;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.Sequence;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.abstractions.Abstraction_Generic;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.abstractions.Abstraction_Qualitative;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.abstractions.ItemAbstractionPair;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.patterns.Pattern;
import ca.pfv.spmf.algorithms.sequentialpatterns.gsp_AGP.items.patterns.PatternCreator;

/**
 * This class is the implementation of a creator of a qualitative abstraction.
 *
 * Copyright Antonio Gomariz Peñalver 2013
 *
 * This file is part of the SPMF DATA MINING SOFTWARE
 * (http://www.philippe-fournier-viger.com/spmf).
 *
 * SPMF is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * SPMF is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * SPMF. If not, see <http://www.gnu.org/licenses/>.
 *
 * @author agomariz
 */
public class AbstractionCreator_Qualitative implements AbstractionCreator {

    /**
     * Static reference to make this class singleton
     */
    private static AbstractionCreator_Qualitative instance = null;

    private AbstractionCreator_Qualitative() {
    }

    /**
     * Get the static instance of this singleton class
     *
     * @return the instance
     */
    public static AbstractionCreator_Qualitative getInstance() {
        if (instance == null) {
            instance = new AbstractionCreator_Qualitative();
        }
        return instance;
    }

    /**
     * It creates the default abstraction. Defined to false, for this
     * implementation.
     *
     * @return the abstraction
     */
    @Override
    public Abstraction_Generic CreateDefaultAbstraction() {
        return Abstraction_Qualitative.create(false);
    }

    /**
     * It creates the abstraction such as is given by the argument
     *
     * @param appearingInTheSameItemset the abstraction value
     * @return the abstraction
     */
    public Abstraction_Generic createAbstraction(boolean appearingInTheSameItemset) {
        return Abstraction_Qualitative.create(appearingInTheSameItemset);
    }

    @Override
    public List<Pattern> createSize2Sequences(List<Sequence> sequences) {
        Map<Pattern, Pattern> totalMap = new HashMap<Pattern, Pattern>();
        List<Pattern> output = new LinkedList<Pattern>();
        for (Sequence s : sequences) {
            List<Itemset> itemsets = s.getItemsets();
            //For each sequence itemset
            for (int i = 0; i < itemsets.size(); i++) {
                Itemset currentItemset = itemsets.get(i);
                //We get each one of the items appearing there
                for (int j = 0; j < currentItemset.size(); j++) {
                    Item item = currentItemset.get(j);

                    ItemAbstractionPair pair1 = new ItemAbstractionPair(item, CreateDefaultAbstraction());
                    //With all of the rest of items in the itemset we make 2-itemsets extensions
                    for (int k = j + 1; k < currentItemset.size(); k++) {
                        Item item2 = currentItemset.get(k);
                        ItemAbstractionPair pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(true));
                        updateAppeareanceSet(totalMap, pair1, pair2, s.getId());
                    }
                    //And with all the items that are in later itemsets we make 2-sequence extensions
                    for (int k = i + 1; k < itemsets.size(); k++) {
                        Itemset nextItemset = itemsets.get(k);
                        for (int n = 0; n < nextItemset.size(); n++) {
                            Item item2 = nextItemset.get(n);
                            ItemAbstractionPair pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(false));
                            updateAppeareanceSet(totalMap, pair1, pair2, s.getId());
                        }
                    }
                }
            }
        }
        output.addAll(totalMap.values());
        Collections.sort(output);
        return output;
    }

    public void updateAppeareanceSet(Map<Pattern, Pattern> totalMap, ItemAbstractionPair pair1, ItemAbstractionPair pair2, int seqId) {
        PatternCreator patternCreator = PatternCreator.getInstance();
        List<ItemAbstractionPair> elementsPatternSize2 = new ArrayList<ItemAbstractionPair>(2);
        elementsPatternSize2.add(pair1);
        elementsPatternSize2.add(pair2);
        Pattern newPattern = patternCreator.createPattern(elementsPatternSize2);

        Pattern existingPattern = totalMap.get(newPattern);
        if (existingPattern == null) {
            existingPattern = newPattern;
            totalMap.put(newPattern, newPattern);
        }
        existingPattern.addAppearance(seqId);
    }

    /**
     * It returns the subpattern obtained by removing an item
     *  at a given index in a pattern.
     *
     * @param extension The pattern on which we will get a subpattern
     * @param index the element to remove from the given pattern
     * @return the resulting subpattern
     */
    @Override
    public Pattern getSubpattern(Pattern extension, int index) {
        ItemAbstractionPairCreator pairCreator = ItemAbstractionPairCreator.getInstance();
        PatternCreator patternCreator = PatternCreator.getInstance();
        List<ItemAbstractionPair> subpatternElements = new ArrayList<ItemAbstractionPair>(extension.size() - 1);
        Abstraction_Generic abstraction = null;
        int nextIndex = index + 1;
        //For each element in the pattern
        for (int i = 0; i < extension.size(); i++) {
            //we copy it if is not in the given index argument
            if (i != index) {
                //If is the element that appears after our index
                if (i == nextIndex) {
                    //If we do no have any value in "abstraction" it means that it was not prepared before. In that case we take the abstraction appearing in the ith-element
                    if (abstraction == null) {
                        abstraction = extension.getIthElement(i).getAbstraction();
                    }
                    //Otherwise, we use the abstraction that we had previously prepared
                    subpatternElements.add(pairCreator.getItemAbstractionPair(extension.getIthElement(i).getItem(), abstraction));
                } else {
                    subpatternElements.add(extension.getIthElement(i));
                }
                //If we remove it, we check how are the temporal relations when we do it
            } else {
                //If it is the first element in the pattern, we establish the default abstraction for the next element
                if (index == 0) {
                    abstraction = CreateDefaultAbstraction();
                } else {
                    //If it is not the first element, we check if it appears in a itemset later than its predecessor
                    Abstraction_Qualitative abstractionOfRemovedElement = (Abstraction_Qualitative) extension.getIthElement(i).getAbstraction();
                    //If that is the case, we prepare the abstraction for its sucessor
                    if (!abstractionOfRemovedElement.hasEqualRelation()) {
                        abstraction = createAbstraction(false);
                    }
                }
            }
        }
        return patternCreator.createPattern(subpatternElements);
    }

    @Override
    public List<Pattern> createSize2Sequences(Map<Integer, Map<Item, List<Integer>>> bbdd, Map<Item, Pattern> frequentItems) {
        Map<Pattern, Pattern> totalMap = new HashMap<Pattern, Pattern>();
        List<Pattern> output = new LinkedList<Pattern>();
        for (Entry<Integer, Map<Item, List<Integer>>> seq : bbdd.entrySet()) {
            Integer sequenceId = seq.getKey();
            List<Entry<Item, List<Integer>>> itemItemsetsAssociations = new ArrayList(seq.getValue().entrySet());
            //For each sequence itemset
            for (int i = 0; i < itemItemsetsAssociations.size(); i++) {
                Entry<Item, List<Integer>> currentEntry1 = itemItemsetsAssociations.get(i);
                Item item1 = currentEntry1.getKey();
                List<Integer> appearances1 = currentEntry1.getValue();
                if (!isFrequent(item1, frequentItems)) {
                    continue;
                }

                for (int m = 0; m < appearances1.size(); m++) {
                    int appearanceItem1 = appearances1.get(m);

                    ItemAbstractionPair pair1 = new ItemAbstractionPair(item1, CreateDefaultAbstraction());

                    for (int j = 0; j < itemItemsetsAssociations.size(); j++) {
                        Entry<Item, List<Integer>> currentEntry2 = itemItemsetsAssociations.get(j);
                        Item item2 = currentEntry2.getKey();
                        List<Integer> appearances2 = currentEntry2.getValue();
                        if (!isFrequent(item2, frequentItems)) {
                            continue;
                        }
                        for (int k = 0; k < appearances2.size(); k++) {
                            int appearanceItem2 = appearances2.get(k);
                            ItemAbstractionPair pair2 = null;
                            if (appearanceItem2 == appearanceItem1) {
                                if (-item2.compareTo(item1) == 1) {
                                    pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(true));
                                }
                            } else if (appearanceItem2 > appearanceItem1) {
                                pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(false));
                            }
                            if (pair2 != null) {
                                updateAppeareanceSet(totalMap, pair1, pair2, sequenceId);
                            }
                        }
                    }
                }
            }
        }
        output.addAll(totalMap.values());
        Collections.sort(output);
        return output;
    }

    private boolean isFrequent(Item item1, Map<Item, Pattern> itemsfrecuentes) {
        return (itemsfrecuentes.get(item1)) != null;
    }

    @Override
    public void clear() {
        instance = null;
    }

    public static void sclear() {
        instance = null;
    }

    /**
     * Method that creates an abstraction depending of two time values. The
     * abstraction will be true if both times are the same, otherwise it will be
     * false. The two time values usually comes from comparing the time of two
     * items.
     *
     * @param currentTime  the current time
     * @param previousTime the previous time
     * @return the abstraction
     */
    public Abstraction_Generic createAbstraction(long currentTime, long previousTime) {
        boolean inTheSameItemset = false;
        if (currentTime == previousTime) {
            inTheSameItemset = true;
        }
        Abstraction_Qualitative abstraction = Abstraction_Qualitative.create(inTheSameItemset);
        return abstraction;
    }

    /**
     * Method that finds the position that an item has within a concrete
     * sequence. The position is returned in a duple <itemset index, item
     * index>. The method used to find the item it depends on how the relations,
     * between the current item and the previous one, are
     *
     * @param sequence The sequence where we want to find the item
     * @param itemPair Item to find
     * @param absPair abstraction of the item to find
     * @param previousAbs Previous abstraction in the pattern of this item
     * @param itemsetIndex Itemset index that the current item has
     * @param itemIndex Item index that the current item has.
     * @param previousItemsetIndex Itemset index of the previous item in the
     * pattern
     * @param previousItemIndex Item index of the previous item in the pattern
     * @return The position where the item is
     */
    public int[] findPositionOfItemInSequence(Sequence sequence, Item itemPair, Abstraction_Generic absPair, Abstraction_Generic previousAbs, int itemsetIndex, int itemIndex, int previousItemsetIndex, int previousItemIndex) {
        Abstraction_Qualitative abs = (Abstraction_Qualitative) absPair;
        int[] pos = null;
        //If our item has an equal relation
        if (abs.hasEqualRelation()) {
            //If both itemset indices, for the current and the previous ones, are the same
            if (itemsetIndex == previousItemsetIndex) {
                //We search for the item in the same itemset
                pos = sequence.SearchForItemAtTheSameItemset(itemPair, itemsetIndex, itemIndex);
            }
        } else {//If, conversely, our item has not an equal relation
            int itemsetIndexToSearchFor = itemsetIndex;
            int itemIndexToSearchFor = itemIndex;
            //If the current itemset index and the previous one point out to the same position
            if (itemsetIndex == previousItemsetIndex) {
                //We make the current itemset index to point to the next itemset, starting from the first item index
                itemsetIndexToSearchFor++;
                itemIndexToSearchFor = 0;
            }
            //And, finally, we look for the item in all the itemsets that appear later than the original itemset index
            //pos = sequence.searchForAnItemInLaterItemset(itemPair, itemsetIndexToSearchFor, itemIndexToSearchFor);
            pos = sequence.searchForTheFirstAppearance(itemsetIndexToSearchFor, itemIndexToSearchFor, itemPair);
        }
        return pos;
    }

    /**
     * Method that generates a candidate from two given patterns. if all the
     * elements of pattern1, except the first one, are the same as all the
     * elements of pattern2, except the last one. For example, if pattern1= a <
     * (b c) < d, and pattern2=(b c) < d < e, we are interested in checking if
     * the subpattern of pattern1, obtaining by suppressing the first item, is
     * equal to the subpattern of pattern2 that is obtained by removing its last
     * item. I.e.,
     * p1 = a < (b c) < d
     * p2 = (b c) < d < e
     * and we want two know if the central part of both pattern is the same.
     * If is not, we set different to true.
     *

     *
     * @param creator
     * @param pattern1 The pattern that plays the role of prefix
     * @param pattern2 The pattern that plays the rol of suffix
     * @param minSupport The minimum relative support
     * @return The candidate generated from the two patterns
     */
    public Pattern generateCandidates(AbstractionCreator creator, Pattern pattern1, Pattern pattern2, double minSupport) {
        // Flag to know if the central part of the pattern is different
        boolean different = false;
        List<ItemAbstractionPair> elements1 = pattern1.getElements();
        List<ItemAbstractionPair> elements2 = pattern2.getElements();
        for (int i = 0; i < (elements1.size() - 1) && !different; i++) {
            ItemAbstractionPair pair1 = elements1.get(i + 1);
            ItemAbstractionPair pair2 = elements2.get(i);
            if (i == 0) {
                if (!pair1.getItem().equals(pair2.getItem())) {
                    different = true;
                }
            } else {
                if (!pair1.equals(pair2)) {
                    different = true;
                }
            }
        }
        if (different) {//If we cannot compose any candidate we return null
            return null;
        } else {/*otherwise, we first check if the junction of their appearing
         * sets still has more appearances than the minimum relative support is
         */
            BitSet intersection = (BitSet) pattern1.getAppearingIn().clone();
            intersection.and(pattern2.getAppearingIn());
            //If we have more appearences than the minSupport is
            if (intersection.cardinality() >= minSupport) {
                //the candidate can be frequent, so we keep it
                Pattern newPattern = pattern1.clonePattern();
                newPattern.add(pattern2.getLastElement());
                return newPattern;
            } else {//Otherwise, it never could be frequent and we can remove it
                return null;
            }
        }
    }

    /**
     * Method to find a candidate in a sequence. It is an intermedium call in
     * order to separate the implementation and to be able to define different
     * ways of searching.
     * @param finder finder of candidates
     * @param candidate The candidate to find
     * @param sequence The sequence where we want to try finding the candidate
     * @param k The level in which we are, i.e. the candidate length
     * @param i the candidate item in which we start
     * @param position The position list for all the candiate elements
     */
    public void isCandidateInSequence(CandidateInSequenceFinder finder, Pattern candidate, Sequence sequence, int k, int i, List<int[]> position) {
        finder.isCandidatePresentInTheSequence_qualitative(candidate, sequence, k, 0, position);
    }

    public List<Pattern> generateSize2Candidates(AbstractionCreator creator, Pattern pat1, Pattern pat2) {
        List<Pattern> output = new LinkedList<Pattern>();
        PatternCreator patternCreator = PatternCreator.getInstance();
        ItemAbstractionPairCreator pairCreator = ItemAbstractionPairCreator.getInstance();

        ItemAbstractionPair elementFromPattern1 = pat1.getIthElement(0);
        ItemAbstractionPair elementFromPattern2 = pat2.getIthElement(0);

        List<ItemAbstractionPair> elementsOfNewPattern1 = new ArrayList<ItemAbstractionPair>(2);
        elementsOfNewPattern1.add(elementFromPattern1);
        elementsOfNewPattern1.add(pairCreator.getItemAbstractionPair(elementFromPattern2.getItem(), Abstraction_Qualitative.create(false)));
        Pattern newPattern1 = patternCreator.createPattern(elementsOfNewPattern1);
        output.add(newPattern1);

        if (!elementFromPattern1.equals(elementFromPattern2)) {
            List<ItemAbstractionPair> elementsOfNewPattern2 = new ArrayList<ItemAbstractionPair>(2);
            elementsOfNewPattern2.add(elementFromPattern2);
            elementsOfNewPattern2.add(pairCreator.getItemAbstractionPair(elementFromPattern1.getItem(), Abstraction_Qualitative.create(false)));
            Pattern newPattern2 = patternCreator.createPattern(elementsOfNewPattern2);
            output.add(newPattern2);

            ItemAbstractionPair smallestPair, greaterPair;
            if (elementFromPattern1.compareTo(elementFromPattern2) > 0) {
                smallestPair = elementFromPattern1;
                greaterPair = elementFromPattern2;
            } else {
                smallestPair = elementFromPattern2;
                greaterPair = elementFromPattern1;
            }
            List<ItemAbstractionPair> elementsOfNewPattern3 = new ArrayList<ItemAbstractionPair>(2);
            elementsOfNewPattern3.add(smallestPair);
            elementsOfNewPattern3.add(pairCreator.getItemAbstractionPair(greaterPair.getItem(), Abstraction_Qualitative.create(true)));
            Pattern newPattern3 = patternCreator.createPattern(elementsOfNewPattern3);
            output.add(newPattern3);
        }
        return output;
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\migrate\Plugin\migrate\process\d6\SkipProcessOnEmpty.
 */

namespace Drupal\migrate\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateSkipProcessException;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * If the value evaluates to false, skip further processing.
 *
 * @MigrateProcessPlugin(
 *   id = "skip_process_on_empty"
 * )
 */
class SkipProcessOnEmpty extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   *
   * Skip the rest of the processing on 0.
   */
  public function transform($value, MigrateExecutable $migrate_executable, Row $row, $destination_property) {
    if (!$value) {
      throw new MigrateSkipProcessException();
    }
    return $value;
  }

}


text:
'use strict';

const concat = require('broccoli-concat');
const funnel = require('broccoli-funnel');
const merge = require('broccoli-merge-trees');

const dependencies = require('./scripts/dependencies');
const modules = require('./scripts/modules');
const main = require('./scripts/main');

const pkg = require('../../../../package.json');

let tree = merge([
  dependencies,
  modules,
  main
]);

//const uglify = require('broccoli-uglify-js');
//tree = uglify(tree);

tree = funnel(tree, {
  destDir: 'assets/scripts'
});

module.exports = tree;


text:
<resources>

    <!-- Machine Translation Only. Latest update release notes.-->
    <string-array name="randremind_release_notes">
        <item name="line0">"Pievienots iespēja skaidru atgādinājuma žurnālā."</item>
        <item name="line1">"Pievienots paziņojumu kategorijas."</item>
        <item name="line2">"Pievienots saraksts paziņojuma skaņas spējas."</item>
        <item name="line5">"Pievienots saiti nobaudīt atgādinājumus un ikonu pakas uz jamesmorrisstudios mājas lapā."</item>
        <item name="line3">"Pievienots iespēja parādīt atgādinājuma attēlu paziņojumā."</item>
        <item name="line4">"Pievienots Android Intent balstīta spraudnis atbalsts izmantošanai ar automatizācijas progr."</item>
        <item name="line4">"Pievienots RSS feed atbalstu ziņojumiem."</item>
        <item name="line4">"Fiksētie bug kur auto atlikšanas nevarētu strādāt ar atrašanās vietas izraisīja atgādinājumu."</item>
    </string-array>

    <!--DO NOT TRANSLATE Latest update release notes.-->
    <string-array name="matchblock_release_notes">
        <item name="line0">"sākotnējās izlaišanas"</item>
    </string-array>

    <!--DO NOT TRANSLATE Latest update release notes.-->
    <string-array name="oneup_release_notes">
        <item name="line0">"Vienkāršota izvēlnes dizainu, pārvietojot visu, lai navigācijas atvilktni."</item>
        <item name="line0">"Mainīts reklāmas formātu iespiestās reklāmas un izņemti reklāmas bannerus."</item>
        <item name="line0">"Mainīts reklāmas sniedzēju tā reklāmas ir pārsvarā vairāk spēļu saistīti."</item>
        <item name="line0">"Uzlabots spēle sniegumu."</item>
        <item name="line0">"Pievienots pasūtījuma tēma atbalstu."</item>
    </string-array>

    <!--DO NOT TRANSLATE Latest update release notes.-->
    <string-array name="bandit_release_notes">
        <item name="line0">"nekas"</item>
    </string-array>

</resources>


text:
<?php
declare(strict_types=1);

namespace Genkgo\Push\Unit;

use Genkgo\Push\AbstractTestCase;
use Genkgo\Push\Body;
use Genkgo\Push\Exception\UnsupportedMessageRecipient;
use Genkgo\Push\Gateway;
use Genkgo\Push\Message;
use Genkgo\Push\Recipient\AndroidDeviceRecipient;
use Genkgo\Push\SenderInterface;

final class GatewayTest extends AbstractTestCase
{
    public function testSend(): void
    {
        $message = new Message(new Body('test'));
        $recipient = new AndroidDeviceRecipient('token');

        $sender = $this->createMock(SenderInterface::class);
        $sender->method('supports')->with($message, $recipient)->willReturn(true);
        $sender->method('send')->with($message, $recipient);

        $gateway = new Gateway([$sender]);
        $gateway->send($message, $recipient);

        $this->addToAssertionCount(1);
    }

    public function testExceptionUnsupportedSender(): void
    {
        $this->expectException(UnsupportedMessageRecipient::class);

        $message = new Message(new Body('test'));
        $recipient = new AndroidDeviceRecipient('token');

        $sender = $this->createMock(SenderInterface::class);
        $sender->method('supports')->with($message, $recipient)->willReturn(false);

        $gateway = new Gateway([$sender]);
        $gateway->send($message, $recipient);
    }
}


text:
module MultiJson
  class Version
    MAJOR = 1 unless defined? MultiJson::Version::MAJOR
    MINOR = 8 unless defined? MultiJson::Version::MINOR
    PATCH = 1 unless defined? MultiJson::Version::PATCH
    PRE = nil unless defined? MultiJson::Version::PRE

    class << self

      # @return [String]
      def to_s
        [MAJOR, MINOR, PATCH, PRE].compact.join('.')
      end

    end

  end

  VERSION = Version.to_s.freeze
end


text:
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import injectSheet from 'react-jss';
import { Helmet } from 'react-helmet';

import { SignUpForm } from './forms';
import { signUp } from '../actions';

const styles = {
  pageTitle: {
    color: '#000',
    fontFamily: 'Canela',
    fontSize: '48px',
    fontWeight: 500,
    lineHeight: 1,
    marginBottom: '11px',
  },
  hr: {
    margin: '10px 0',
  },
  signUpRedirect: {
    color: '#3084df',
    display: 'block',
    fontFamily: 'Minion Pro',
    fontSize: '17px',
    marginBottom: '7px',
  },
};

function SignUpPage({ classes, signUp }) {
  return (
    <Grid fluid>
      <Helmet titleTemplate="%s | The Stuyvesant Spectator">
        <title>Sign Up</title>
        <meta />
      </Helmet>
      <Row>
        <Col
          xs={12}
          sm={6}
          smOffset={3}
          md={6}
          mdOffset={3}
          lg={6}
          lgOffset={3}
        >

Create an Account

          <Link to="/myaccount" className={classes.signUpRedirect}>
            Already have an account? Log in »
          </Link>

          <SignUpForm onSubmit={signUp} />
        </Col>
      </Row>
    </Grid>
  );
}

const mapDispatchToProps = dispatch => bindActionCreators({ signUp }, dispatch);

export default connect(null, mapDispatchToProps)(
  injectSheet(styles)(SignUpPage),
);


text:
<?php

namespace Nanoserv;

/**
 * Server exception class
 *
 * @package nanoserv
 * @subpackage Core
 * @since 2.0
 */
class ServerException extends namespace\Exception {
    public $listener;

    public function __construct($errmsg, $errno, $addr, Listener $listener = NULL) {
        parent::__construct($errmsg, $errno, $addr);

        $this->listener = $listener;
    }
}


text:
Sh@rebox is an easy and safe way to lend, borrow, or trade items with local residents and friends in your area. Through a set of localized smart pods, modular storage spaces are filled with __insert awesome stuff here__. The online platform manages the inventory and keeps the process transparent and efficient, so sharing can be second nature. Got a slow cooker you used once for a party that's now taking up space? Add it to Sh@rebox and allow your neighbors to use it too!

Sh@rebox exists to help people make better use of what they already have by sharing items with nearby neighbors and friends that would otherwise go unused.

###### Basic features list:
 * Signup for the first time via Facebook, Twitter, or email
 * Create a user profile (must put in an address so that the nearest Sh@reBox pod can be located)
 * Post things to add to store and to borrow
 * Post local articles/news

######  Based off of MEAN.io Stack and BoilerPlate(original is in the READMEMean.md file located in root). Technologies include:
 * MySQL
 * AngularJS
 * Node.js
 * Express
 * Jade
 * Bootstrap
 * Sequelize
 * Grunt
 * Passport
 * Cloudinary
 * Heroku

To run locally:
```
1) Clone this repo
2) npm & bower install
3) Create Cloudinary account. Cloudinary API is used for photo uploads. By default 5gs worth!! To use Cloudinary, you also need to download the ngFileUpload module.
```
Future versions will include:

 * Push notifications
 * More pods/locations in the database
 * User reviews


text:
import logging
import os

from angr.calling_conventions import DEFAULT_CC, SimCCUnknown
from angr import SimState, sim_options as o, Project
from archinfo import all_arches, ArchAMD64, ArchSoot

l = logging.getLogger("angr.tests.test_stack_alignment")

def test_alignment():
    for arch in all_arches:
        if arch.name in DEFAULT_CC and DEFAULT_CC[arch.name] is not SimCCUnknown:
            # There is nothing to test for soot about stack alignment
            if isinstance(arch, ArchSoot):
                continue
            l.info("Testing stack alignment for %s", arch.name)
            st = SimState(arch=arch)
            cc = DEFAULT_CC[arch.name](arch=arch)

            st.regs.sp = -1

            # setup callsite with one argument (0x1337), "returning" to 0
            cc.setup_callsite(st, 0, [0x1337], 'void foo(int x)')

            # ensure stack alignment is correct
            assert st.solver.is_true(
                ((st.regs.sp + cc.STACKARG_SP_DIFF) % cc.STACK_ALIGNMENT == 0)
            ), ("non-zero stack alignment after setup_callsite for %s" % cc)

def test_sys_v_abi_compliance():
    arch = ArchAMD64()
    st = SimState(arch=arch)
    cc = DEFAULT_CC[arch.name](arch=arch)

    st.regs.sp = -1

    # setup callsite with one argument (0x1337), "returning" to 0
    cc.setup_callsite(st, 0, [0x1337], 'void foo(int x)')

    # (rsp+8) must be aligned to 16 as required by System V ABI.
    # ref: https://raw.githubusercontent.com/wiki/hjl-tools/x86-psABI/x86-64-psABI-1.0.pdf , page 18t
    assert st.solver.is_true(((st.regs.rsp + 8) % 16 == 0)),  'System V ABI calling convention violated!'

def test_initial_allocation():
    # not strictly about alignment but it's about stack initialization so whatever
    p = Project(
        os.path.join(os.path.dirname(__file__), "../../binaries/tests/x86_64/true"),
        auto_load_libs=False,
    )
    s = p.factory.entry_state(add_options={o.STRICT_PAGE_ACCESS})
    s.memory.load(s.regs.sp - 0x10000, size=4)

if __name__ == "__main__":
    test_alignment()
    test_sys_v_abi_compliance()