text:
layout: post
header-img: img/default-blog-pic.jpg
author: PGarg
description:
post_id: 3527
created: 2010/05/24 10:31:25
created_gmt: 2010/05/24 05:31:25
comment_status: open
image: /assets/article_images/2014-07-06-oracle/desktop.jpg

---

# Functional Programming in Java Using "lambdaj"

The new JVM based Post Modern Functional Languages (as creator of Scala, Martin Ordesky named them) like Scala and JRuby which are influenced from both Object Oriented and Functional programming languages  have gone far ahead in the terms of functionality that they offer as compared to Java.

    Apart from the object richness, these languages are loaded with most characteristics of a FL like (first class functions, closures, traits static/dynamic type inference, lazy evaluation, etc) which helps in bringing more modularity to the code and from aesthetics perspective these languages are less verbose and more readable as compared to java.

    Few people have put efforts and wrote libraries which can help in leveraging some of these features in Java too. The motivation is not to compete with scala or ruby as they are far ahead. It's like if you don't have the option to switch over to these languages (especially scala) or you are still waiting for the Java7 release.

    The ones which I have been using are lambdaj written by Mario Fusco and Enumerable written by Hakan Raberg. Others I am aware of but not used are FunctionalJ and FunctionalJava .Most of them provide a similar set of features and differ bit in syntax , it only like the one to which you get accustomed too.

lambdaj offers more features compared to Enumerable. Just include the jar and it works, since it uses the proxies for the implementation it's a bit slow. Enumerable takes different approach for closure support it uses ASM byte code manipulation to capture expressions as closures. So you have to perform an extra simple step of compiling the lamdas before hand.

    Lets dive into some of the code snippets that we regularly write in java and see how they can be made concise and readable using these libraries.

    Constructs for Collections - Iterate through a Collection<String> and return a collection<String> starting with "inv"

    Using Java

    [sourcecode lang="java"]
    List<String> list = Arrays.asList("invalid1", "invalid2");

    List<String> filteredList = new ArrayList<String>();

    for(String string : list) {

      if(string.startsWith("inv"))

        filteredList.add(string);

    }
    return filteredList;

    [/sourcecode]

    Using lambdaj
    [sourcecode lang="java"]
     List<String> list = Arrays.asList("invalid1", " invalid2");

    return filter(startsWith("inv"), list);
    [/sourcecode]
    Using Enumerable
    [sourcecode lang="java"]
    List</span> list = Arrays.asList("invalid1", " invalid2");

    return Collect(list,fn(s,s.startsWith("inv"));
    [/sourcecode]
    Filter/Collect are static methods provided in the lambdaj/Enumerable library which do the actual filtering/collection on collection. "startsWith" is expressed as a hamcrest matcher and the lambda expression fn(s,s.startsWith("inv")) will be converted to below , after you do the lambda expression weaving.
    [sourcecode lang="java"]
    new Fn1() {
    public Object call(Object arg) {
    return (String) arg.startsWith("inv");
    }};
    [/sourcecode]

    In this case the 6 lines of code are just reduced to 1.

Closures

    We have a scenario where you have search for an employee, compare its name with some pattern and if it matches, send the message. Now gradually you can have more criteria on which you want to match, you want a regex match or don't want to use ignore case and many more.  For all those cases you will end up duplicating the sendMessage() method with different line instead of the one shown marked with dashes(-).

    Using Java
    [sourcecode lang="java"]
    public boolean  sendMessage(String pattern) {

        FinderService service = context.getService("finderService");

        boolean found = false;

            try {

            Employee employee = service.find();

            if (null != employee) {

        --------  if (employee.getName().equalsIgnoreCase(pattern)) -------
               found = true;

            }

            if(found)  service.sendMessage("Found the employee");

           } catch (Exception e) {

             found = false;

           }
        return found;
    }

    [/sourcecode]
    Using lambdaj
    [sourcecode lang="java"]
    public boolean sendMessageUsingIgnoreCase() {

        Closure2<Employee, String> ignoreCaseClosure  = closure(Employee.class, String.class);

        {of(this).ignore(var(Employee.class), var(String.class));}

        return sendMessage("pattern", ignoreCaseClosure);

    }

    public boolean sendMessageUsingRegexCriteria() {

        Closure2<Employee, String> regexClosure   =closure(Employee.class,String.class);

        {of(this).regex(var(Employee.class), var(String.class));}

        return sendMessage("pattern", regexClosure);
    }

    private boolean ignore(Employee emp, String pattern) {

        return emp.getName().equalsIgnoreCase(pattern);
    }

    private boolean regex(Employee employee, String pattern) {

        Pattern p = Pattern.compile(pattern);

        return p.matcher(employee.getName()).find();

    }

    private boolean sendMessage(String pattern,Closure2<Employee, String> closure) {

            FinderService service = context.getService("finderService");

            boolean found = false;

                try {

                Employee employee = service.find();

                if (null != employee) {

        ----------  if ((Boolean) closure.apply(employee, pattern)){ ---------
                   found = true;

                }

                if(found)  service.sendMessage("Found the employee");

               } catch (Exception e) {

                 found = false;

               }
            return found;
    }
    [/sourcecode]
    We created two closures ignoreCaseClosure and regexClosure which are basically the ignore and regex methods that will be used inside the sendMessage() method . This was you can create as many closures as you want based on different criteria's and pass them to sendMessage().Here we extracted the logic which is variable and avoid duplication.

    Matchers

    Consider this code snippet in java, which iterates though a collection and creates a concatenation string in the format "key = Value & key = value &...".While processing it ignores the entries which have keys starting with "graphType" or "type".

    Using Java
    [sourcecode lang="java"]
    for (Entry<String, String> param : params.entries()) {

        if (!"graphPage".equals(param.getKey()) && !"type".equals(param.getKey())) {

            if (sb == null) {

                sb= <strong>new</strong> StringBuffer();

        } else {

        sb.append('&');

    }

    sb.append(param.getKey()).append('=').append(param.getValue());

    [/sourcecode]

    Using lambdaj
    [sourcecode lang="java"]
    OrMatcher<String> toExclude = or(equalTo("type"), equalTo("graphPage"));

    List<Entry<String, String>> paramsList = select(params.entries(),  not(having(on(Entry.class).getKey(), toExclude)));

    String graphLink = join(paramsList, "&");
    [/sourcecode]

    The code is almost self explanatory you create an orMatcher for the types to be excluded. Then you apply select on the list using that matcher which return you a List<Entries>. Finally a join on it to return a string of concatenated entries.

    There are more features available with these libraries which are quite useful. One way of using them in you application is to create a seperate maven project with the available source code of library and then use it. This is also help in modifying/adding new stuff to the library as per project requirements.


text:
/*

	Write a program that takes a string and displays it after
	replacing each character by the next one in alphabetical order.

	'z' becomes 'a' and 'Z' becomes 'A'.

	Upper case letters stay upper case. Lower case letter stay lower case.

	The output will always be followed by a '\n'.
	If no parameters are passed, the program displays '\n'.

  */

redpajama_set_name: RedPajamaGithub


text:
#ifndef SVGAnimateMotionElement_h
#define SVGAnimateMotionElement_h

#include "core/svg/SVGAnimationElement.h"
#include "platform/graphics/Path.h"

namespace WebCore {

class AffineTransform;

class SVGAnimateMotionElement FINAL : public SVGAnimationElement {
public:
    virtual ~SVGAnimateMotionElement();

    static PassRefPtr<SVGAnimateMotionElement> create(Document&);
    void updateAnimationPath();

private:
    explicit SVGAnimateMotionElement(Document&);

    virtual bool hasValidAttributeType();
    virtual bool hasValidAttributeName();

    bool isSupportedAttribute(const QualifiedName&);
    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;

    virtual void resetAnimatedType();
    virtual void clearAnimatedType(SVGElement* targetElement);
    virtual bool calculateToAtEndOfDurationValue(const String& toAtEndOfDurationString);
    virtual bool calculateFromAndToValues(const String& fromString, const String& toString);
    virtual bool calculateFromAndByValues(const String& fromString, const String& byString);
    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGSMILElement* resultElement);
    virtual void applyResultsToTarget();
    virtual float calculateDistance(const String& fromString, const String& toString);

    enum RotateMode {
        RotateAngle,
        RotateAuto,
        RotateAutoReverse
    };
    RotateMode rotateMode() const;

    bool m_hasToPointAtEndOfDuration;

    virtual void updateAnimationMode() OVERRIDE;

    // Note: we do not support percentage values for to/from coords as the spec implies we should (opera doesn't either)
    FloatPoint m_fromPoint;
    FloatPoint m_toPoint;
    FloatPoint m_toPointAtEndOfDuration;

    Path m_path;
    Path m_animationPath;
};

} // namespace WebCore

#endif // SVGAnimateMotionElement_h


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Dart+ People Mosaic</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
    <link rel="stylesheet" href="dart_people_mosaic.css">

Dart+ People Mosaic

      Sign in with Google

      Disconnect

        Tolerance (1-100): <input type="number" id="tolerance" value="5" min="1" max="100"><button id="create">Create mosaic</button>

        <button id="zoom">Show Full Size</button>

        <canvas id="mosaic"></canvas>


text:
#ifndef VOICE_CHANGE_H
#define VOICE_CHANGE_H

#include <atomic>

#include "almalloc.h"

struct Voice;

using uint = unsigned int;

enum class VChangeState {
    Reset,
    Stop,
    Play,
    Pause,
    Restart
};
struct VoiceChange {
    Voice *mOldVoice{nullptr};
    Voice *mVoice{nullptr};
    uint mSourceID{0};
    VChangeState mState{};

    std::atomic<VoiceChange*> mNext{nullptr};

    DEF_NEWDEL(VoiceChange)
};

#endif /* VOICE_CHANGE_H */


text:
#include <Thor/Framework/ThObjectTable.h>
#include <Thor/Framework/Singleton.h>

#ifdef THOR_USE_TBB
	#include <tbb/concurrent_vector.h>
	#include <tbb/concurrent_queue.h>
#endif

namespace Thor
{

#ifdef THOR_USE_TBB

//----------------------------------------------------------------------------------------
//
//					ThObjectTableImpl
//
//----------------------------------------------------------------------------------------
class ThObjectTableImpl: public NonCopyable
{
public:
	static ThObjectTableImpl& Instance();

	ThiRtti*	GetObject(ThU32 handle);

	ThU32		GetObjectHandle(const ThUUID& uuid);

	ThU32		AddObject(ThiRtti* obj);

	void		RemoveObject(ThU32 handle);

	void		RemoveObject(ThiRtti* obj);

private:

	ThObjectTableImpl();

	typedef Singleton<ThObjectTableImpl> singleton_t;
	friend class Singleton<ThObjectTableImpl>;

	typedef tbb::concurrent_vector<ThiRtti*>		object_list_t;
	typedef tbb::concurrent_queue<ThU32>			handle_list_t;

	object_list_t	m_ObjectList;
	handle_list_t	m_FreeHandles;
	tbb::atomic<ThU32>			m_InsertIndex;
};

#else
//----------------------------------------------------------------------------------------
//
//					ThObjectTableImpl
//
//----------------------------------------------------------------------------------------
class ThObjectTableImpl: public NonCopyable
{
public:
	static ThObjectTableImpl& Instance();

	ThiRtti*	GetObject(ThU32 handle);

	ThU32		GetObjectHandle(const ThUUID& uuid);

	ThU32		AddObject(ThiRtti* obj);

	void		RemoveObject(ThU32 handle);

	void		RemoveObject(ThiRtti* obj);

private:

	ThObjectTableImpl();

	typedef Singleton<ThObjectTableImpl> singleton_t;
	friend class Singleton<ThObjectTableImpl>;

	typedef std::vector<ThiRtti*>		object_list_t;
	typedef std::vector<ThU32>			handle_list_t;

	tbb::spin_mutex m_Mutex;
	object_list_t	m_ObjectList;
	handle_list_t	m_FreeHandles;
	ThU32			m_MaxObjInsertIndex;
	ThU32			m_MaxFreeObjIndex;
};

#endif

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>JSlawitsky</title>

    <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

    <link href="css/creative.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Jonathan Slawitsky

                        About

                        Skills

                        Resume

                        Portfolio

                        Contact

Jonathan Slawitsky

Engineer | Healthcare Enthusiast | Environmentalist

                Find Out More About Me

I'm the man for the job!

                      I'm Jonathan, an engineer with a diverse, highly technical background. I studied mechanical engineering as an
                      undergraduate, and have experience in the healthcare software field. I love mulling over abstract algorithms and
                      deeply understanding complex problems. If you're looking for a candidate with strong critical thinking skills, I'm
                      your man!

                    My Credentials

                    Resume

Skills

Ruby

Rails

HTML

CSS

Javascript

jQuery

Redux

React

Git

PostgreSQL

mySQL

Education

McGill University

App Academy

Portfolio

                                    Full Stack

                                    Formulator

A multipage, form-building and sharing app hosted on Heroku.

                        Github Repo

                                    Front End

                                    Flow Sim

A fluid-flow visualization app using a Lattice Boltzmann solver.

                        Github Repo

                                    Back End

                                    Ruby Archive

An ActiveRecord inspired ORM library.

                        Github Repo

Contact

                      Want to get in touch with me? Do you have feedback you'd like to share? I'd love to hear from you!
                      Give me a call, send me an email, or check out my LinkedIn and I'll get back to you as soon as possible.

609-955-1439

jonathan.slawitsky@gmail.com

Jonathan Slawitsky

GitHub


text:
from heat.common import exception
from heat.engine import clients
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources.neutron import neutron
from heat.openstack.common import log as logging

if clients.neutronclient is not None:
    from neutronclient.common.exceptions import NeutronClientException

logger = logging.getLogger(__name__)

class NetworkGateway(neutron.NeutronResource):
    '''
    A resource for the Network Gateway resource in Neutron Network Gateway.
    '''

    PROPERTIES = (
        NAME, DEVICES, CONNECTIONS,
    ) = (
        'name', 'devices', 'connections',
    )

    _DEVICES_KEYS = (
        ID, INTERFACE_NAME,
    ) = (
        'id', 'interface_name',
    )

    _CONNECTIONS_KEYS = (
        NETWORK_ID, SEGMENTATION_TYPE, SEGMENTATION_ID,
    ) = (
        'network_id', 'segmentation_type', 'segmentation_id',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            description=_('The name of the network gateway.'),
            update_allowed=True
        ),
        DEVICES: properties.Schema(
            properties.Schema.LIST,
            description=_('Device info for this network gateway.'),
            required=True,
            constraints=[constraints.Length(min=1)],
            update_allowed=True,
            schema=properties.Schema(
                properties.Schema.MAP,
                schema={
                    ID: properties.Schema(
                        properties.Schema.STRING,
                        description=_('The device id for the network '
                                      'gateway.'),
                        required=True
                    ),
                    INTERFACE_NAME: properties.Schema(
                        properties.Schema.STRING,
                        description=_('The interface name for the '
                                      'network gateway.'),
                        required=True
                    )
                }
            )
        ),
        CONNECTIONS: properties.Schema(
            properties.Schema.LIST,
            description=_('Connection info for this network gateway.'),
            default={},
            update_allowed=True,
            schema=properties.Schema(
                properties.Schema.MAP,
                schema={
                    NETWORK_ID: properties.Schema(
                        properties.Schema.STRING,
                        description=_(
                            'The id of internal network to connect on '
                            'the network gateway.'),
                        required=True
                    ),
                    SEGMENTATION_TYPE: properties.Schema(
                        properties.Schema.STRING,
                        description=_(
                            'L2 segmentation strategy on the external '
                            'side of the network gateway.'),
                        default='flat',
                        constraints=[constraints.AllowedValues(
                            ('flat', 'vlan'))]
                    ),
                    SEGMENTATION_ID: properties.Schema(
                        properties.Schema.INTEGER,
                        description=_(
                            'The id for L2 segment on the external side '
                            'of the network gateway. Must be specified '
                            'when using vlan.'),
                        constraints=[constraints.Range(0, 4094)]
                    )
                }
            )
        )
    }

    attributes_schema = {
        "default": _("A boolean value of default flag."),
        "show": _("All attributes.")
    }

    update_allowed_keys = ('Properties',)

    def _show_resource(self):
        return self.neutron().show_network_gateway(
            self.resource_id)['network_gateway']

    def validate(self):
        '''
        Validate any of the provided params
        '''
        super(NetworkGateway, self).validate()
        connections = self.properties[self.CONNECTIONS]

        for connection in connections:
            segmentation_type = connection[self.SEGMENTATION_TYPE]
            segmentation_id = connection.get(self.SEGMENTATION_ID)

            if segmentation_type == 'vlan' and segmentation_id is None:
                msg = _("segmentation_id must be specified for using vlan")
                raise exception.StackValidationFailed(message=msg)

            if segmentation_type == 'flat' and segmentation_id:
                msg = _(
                    "segmentation_id cannot be specified except 0 for "
                    "using flat")
                raise exception.StackValidationFailed(message=msg)

    def handle_create(self):
        props = self.prepare_properties(
            self.properties,
            self.physical_resource_name())

        connections = props.pop(self.CONNECTIONS)
        ret = self.neutron().create_network_gateway(
            {'network_gateway': props})['network_gateway']

        for connection in connections:
            self.neutron().connect_network_gateway(
                ret['id'], connection
            )

        self.resource_id_set(ret['id'])

    def handle_delete(self):
        if not self.resource_id:
            return
        client = self.neutron()

        connections = self.properties[self.CONNECTIONS]
        for connection in connections:
            try:
                client.disconnect_network_gateway(
                    self.resource_id, connection
                )
            except NeutronClientException as ex:
                self._handle_not_found_exception(ex)

        try:
            client.delete_network_gateway(self.resource_id)
        except NeutronClientException as ex:
            self._handle_not_found_exception(ex)
        else:
            return self._delete_task()

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        props = self.prepare_update_properties(json_snippet)
        connections = props.pop(self.CONNECTIONS)

        if self.DEVICES in prop_diff:
            self.handle_delete()
            self.properties.data.update(props)
            self.handle_create()
            return
        else:
            props.pop(self.DEVICES, None)

        if self.NAME in prop_diff:
            self.neutron().update_network_gateway(
                self.resource_id, {'network_gateway': props})

        if self.CONNECTIONS in prop_diff:
            for connection in self.properties[self.CONNECTIONS]:
                try:
                    self.neutron().disconnect_network_gateway(
                        self.resource_id, connection
                    )
                except NeutronClientException as ex:
                    self._handle_not_found_exception(ex)
            for connection in connections:
                self.neutron().connect_network_gateway(
                    self.resource_id, connection
                )

def resource_mapping():
    if clients.neutronclient is None:
        return {}

    return {
        'OS::Neutron::NetworkGateway': NetworkGateway,
    }


text:
define([
  'intern!object',
  'intern/chai!expect',
  '../helper/fixtures/focusable.fixture',
  '../helper/fixtures/shadow-input.fixture',
  '../helper/supports',
  'platform',
  'ally/query/focusable',
], function(
  registerSuite,
  expect,
  focusableFixture,
  shadowInputFixture,
  supports,
  platform,
  queryFocusable
) {

  registerSuite(function() {
    var fixture;

    return {
      name: 'query/focusable.all',

      beforeEach: function() {
        fixture = focusableFixture();
      },
      afterEach: function() {
        fixture.remove();
        fixture = null;
      },

      document: function() {
        var result = queryFocusable({
          strategy: 'all',
        }).map(fixture.nodeToString);

        var canTestVideoEmbed = Boolean(document.getElementById('embed'));
        var expected = [
          '#tabindex--1',
          '#tabindex-0',
          '#tabindex-1',
          supports.canFocusInvalidTabindex && '#tabindex-bad',
          '#link',
          '#link-tabindex--1',
          '#image-map-area',
          supports.canFocusAreaWithoutHref && '#image-map-area-nolink',
          '#object-svg',
          platform.name === 'IE' && '#svg',
          supports.canFocusObjectSvg && '#object-tabindex-svg',
          '#svg-link',
          canTestVideoEmbed && '#embed',
          canTestVideoEmbed && '#embed-tabindex-0',
          '#embed-svg',
          '#embed-tabindex-svg',
          supports.canFocusAudioWithoutControls && '#audio',
          '#audio-controls',
          '#input',
          '#input-tabindex--1',
          '#input-disabled',
          supports.canFocusFieldset && 'fieldset',
          '#fieldset-disabled-input',
          '#span-contenteditable',
          document.body.style.webkitUserModify !== undefined && '#span-user-modify',
          '#img-ismap-link',
          supports.canFocusImgIsmap && '#img-ismap',
          supports.canFocusScrollContainer && '#scroll-container',
          supports.canFocusScrollBody && '#scroll-body',
          supports.canFocusScrollContainerWithoutOverflow && '#scroll-container-without-overflow',
          supports.canFocusScrollContainerWithoutOverflow && '#scroll-body-without-overflow',
        ].filter(Boolean);

        expect(result).to.deep.equal(expected);
      },

      context: function() {
        var expected = [
          '#link',
          '#link-tabindex--1',
        ];
        var result = queryFocusable({
          strategy: 'all',
          context: '.context',
        }).map(fixture.nodeToString);

        expect(result).to.deep.equal(expected);
      },

      'context and self': function() {
        fixture.root.querySelector('.context').setAttribute('tabindex', '-1');

        var expected = [
          'div',
          '#link',
          '#link-tabindex--1',
        ];
        var result = queryFocusable({
          strategy: 'all',
          context: '.context',
          includeContext: true,
        }).map(fixture.nodeToString);

        expect(result).to.deep.equal(expected);
      },

      'children of <canvas>': function() {
        var container = fixture.add([
          /*eslint-disable indent */
          '<canvas>',
            '<input type="text" id="canvas-input">',
            '<input type="text" id="canvas-input-tabindex--1" tabindex="-1">',
            'hello',
            'hello',
            'hello',
            'hello',
          '</canvas>',
          /*eslint-enable indent */
        ], 'canvas-container');

        var expected = [
          '#canvas-input',
          '#canvas-input-tabindex--1',
          '#canvas-a',
          '#canvas-a-tabindex--1',
          '#canvas-span-tabindex-0',
          '#canvas-span-tabindex--1',
        ];
        var result = queryFocusable({
          strategy: 'all',
          context: container,
          includeContext: true,
        }).map(fixture.nodeToString);

        expect(result).to.deep.equal(expected);
      },

      'extended: Shadow DOM': function() {
        if (document.body.createShadowRoot === undefined) {
          this.skip('Shadow DOM not supported');
        }

        var host = document.createElement('div');
        host.id = 'first-shadow-host';
        fixture.root.appendChild(host);
        shadowInputFixture.createShadowRoot(fixture);

        var result = queryFocusable({
          strategy: 'all',
        }).map(fixture.nodeToString);

        var canTestVideoEmbed = Boolean(document.getElementById('embed'));
        var expected = [
          '#tabindex--1',
          '#tabindex-0',
          '#tabindex-1',
          supports.canFocusInvalidTabindex && '#tabindex-bad',
          '#link',
          '#link-tabindex--1',
          '#image-map-area',
          supports.canFocusAreaWithoutHref && '#image-map-area-nolink',
          supports.canFocusObjectSvg && '#object-svg',
          supports.canFocusObjectSvg && '#object-tabindex-svg',
          '#svg-link',
          canTestVideoEmbed && '#embed',
          canTestVideoEmbed && '#embed-tabindex-0',
          '#embed-svg',
          '#embed-tabindex-svg',
          supports.canFocusAudioWithoutControls && '#audio',
          '#audio-controls',
          '#input',
          '#input-tabindex--1',
          '#input-disabled',
          '#fieldset-disabled-input',
          '#span-contenteditable',
          document.body.style.webkitUserModify !== undefined && '#span-user-modify',
          '#img-ismap-link',
          supports.canFocusScrollContainer && '#scroll-container',
          '#first-input',
          '#second-input',
          '#third-input',
        ].filter(Boolean);

        expect(result).to.deep.equal(expected);
      },
    };
  });
});


text:
package uk.ac.ox.oucs.oxpoints.gaboto.entities;

import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;

import java.lang.reflect.Method;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import net.sf.gaboto.GabotoSnapshot;

import net.sf.gaboto.node.GabotoEntity;

import net.sf.gaboto.node.annotation.BagLiteralProperty;
import net.sf.gaboto.node.annotation.ResourceProperty;

import net.sf.gaboto.node.pool.EntityPool;

import uk.ac.ox.oucs.oxpoints.gaboto.entities.Unit;

/**
 * Gaboto generated Entity.
 * @see net.sf.gaboto.generation.GabotoGenerator
 */
public class Library extends Unit {
  protected Collection<String> oLISCode;
  protected String libraryHomepage;

  private static Map<String, List<Method>> indirectPropertyLookupTable;
  static{
    indirectPropertyLookupTable = new HashMap<String, List<Method>>();
  }

  @Override
  public String getType(){
    return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#Library";
  }

  @BagLiteralProperty(
    value = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasOLISCode",
    datatypeType = "javaprimitive",
    javaType = "String"
  )
  public Collection<String> getOLISCode(){
    return this.oLISCode;
  }

  @BagLiteralProperty(
    value = "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasOLISCode",
    datatypeType = "javaprimitive",
    javaType = "String"
  )
  public void setOLISCode(Collection<String> oLISCode){
    this.oLISCode = oLISCode;
  }

  public void addOLISCode(String oLISCodeP){
    if(this.oLISCode == null)
      setOLISCode( new HashSet<String>() );
    this.oLISCode.add(oLISCodeP);
  }

  @ResourceProperty("http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasLibraryHomepage")
  public String getLibraryHomepage(){
    return this.libraryHomepage;
  }

  @ResourceProperty("http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasLibraryHomepage")
  public void setLibraryHomepage(String libraryHomepage){
    this.libraryHomepage = libraryHomepage;
  }

  public void loadFromSnapshot(Resource res, GabotoSnapshot snapshot, EntityPool pool) {
    super.loadFromSnapshot(res, snapshot, pool);
    Statement stmt;

    // Load BAG_LITERAL_PROPERTY oLISCode
    {
        StmtIterator stmts = res.listProperties(snapshot.getProperty("http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasOLISCode"));
        while (stmts.hasNext()) {
            RDFNode node = stmts.next().getObject();
            if(! node.isLiteral())
              throw new IllegalArgumentException("node should be a literal");

            addOLISCode(((Literal)node).getString());
        }
    }

    // Load SIMPLE_RESOURCE_PROPERTY libraryHomepage
    stmt = res.getProperty(snapshot.getProperty("http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#hasLibraryHomepage"));
    if(stmt != null && stmt.getObject().isURIResource()){
      this.setLibraryHomepage(((Resource) stmt.getObject()).getURI());
    }

  }
  protected List<Method> getIndirectMethodsForProperty(String propertyURI){
    List<Method> list = super.getIndirectMethodsForProperty(propertyURI);
    if(list == null)
      return indirectPropertyLookupTable.get(propertyURI);

    else{
      List<Method> tmp = indirectPropertyLookupTable.get(propertyURI);
      if(tmp != null)
        list.addAll(tmp);
    }
    return list;
  }

}


text:
'use strict';

module.exports = function RegisterModel() {
    return {
        name: 'krakenexample'
    };
};


text:
//The MIT License (MIT)

//Copyright (c) 2015 Jordi Corbilla

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

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

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

using System.IO;
using System.Text;

namespace Thundax.MapReduce
{
    /// <summary>
    /// Writer class
    /// </summary>
    public class Writer
    {
        private static readonly object Locker = new object();

        /// <summary>
        /// Write to file
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="text"></param>
        public void WriteToFile(string filepath, StringBuilder text)
        {
            lock (Locker)
            {
                using (FileStream file = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                {
                    writer.WriteLine(text.ToString());
                }
            }

        }
    }
}


text:
import { Component, Input, OnChanges } from '@angular/core';
import { NavigationNode } from 'app/navigation/navigation.model';

@Component({
  selector: 'aio-nav-item',
  template: `

        {{ node.title }}

        {{ node.title }}
        <mat-icon class="rotating-icon" svgIcon="keyboard_arrow_right"></mat-icon>

      <button
        *ngIf="node.url == null"
        type="button"
        [ngClass]="classes"
        title="{{ node.tooltip }}"
        (click)="headerClicked()"
        class="vertical-menu-item heading"
        [attr.aria-pressed]="isExpanded"
      >
        {{ node.title }}
        <mat-icon class="rotating-icon" svgIcon="keyboard_arrow_right"></mat-icon>
      </button>

        <aio-nav-item
          *ngFor="let node of nodeChildren"
          [level]="level + 1"
          [isWide]="isWide"
          [isParentExpanded]="isExpanded"
          [node]="node"
          [selectedNodes]="selectedNodes"
        ></aio-nav-item>

`,
})
export class NavItemComponent implements OnChanges {
  @Input() isWide = false;
  @Input() level = 1;
  @Input() node: NavigationNode;
  @Input() isParentExpanded = true;
  @Input() selectedNodes: NavigationNode[] | undefined;

  isExpanded = false;
  isSelected = false;
  classes: { [index: string]: boolean };
  nodeChildren: NavigationNode[];

  ngOnChanges() {
    this.nodeChildren = this.node && this.node.children ? this.node.children.filter((n) => !n.hidden) : [];

    if (this.selectedNodes) {
      const ix = this.selectedNodes.indexOf(this.node);
      this.isSelected = ix !== -1; // this node is the selected node or its ancestor
      this.isExpanded =
        this.isParentExpanded &&
        (this.isSelected || // expand if selected or ...
          // preserve expanded state when display is wide; collapse in mobile.
          (this.isWide && this.isExpanded));
    } else {
      this.isSelected = false;
    }

    this.setClasses();
  }

  setClasses() {
    this.classes = {
      ['level-' + this.level]: true,
      collapsed: !this.isExpanded,
      expanded: this.isExpanded,
      selected: this.isSelected,
    };
  }

  headerClicked() {
    this.isExpanded = !this.isExpanded;
    this.setClasses();
  }
}


text:
* {
  box-sizing: border-box;
}

div {
  -webkit-transform: translate3d(0, 0, 0);
}

html {
  margin: 0;
  width: 100%;
  font: 11px/18px "Lucida Grande", "Helvetica Neue", sans-serif;
  -webkit-font-smoothing: antialiased;
  text-shadow: 0 1px 0 #ffffff;
  cursor: default;
  background: transparent;
}

::selection {
  background: Highlight;
}

body {
  margin: 0;
  overflow-x: hidden;
  width: 100%;
}

section {
  padding-top: 8px;
  padding-bottom: 12px;
  display: none;
}

section#all, section#errors {
  display: block;
}

section strong {
  text-transform: uppercase;
  color: #999;
  width: 100%;
  font-weight: bold;
  font-size: 11px;
  display: block;
  padding-left: 14px;
  padding-right: 14px;
  padding-bottom: 6px;
  border-bottom: 1px solid rgb(226, 228, 226);
  box-shadow: 0 1px 0 rgba(235, 236, 235, .3);
  margin-bottom: -1px;
  position: relative;
  z-index: 99;
}

section#images strong, section#other strong, section#ignored strong {
  padding-bottom: 5px;
}

section article {
  padding-top: 6px;
  padding-bottom: 6px;
  line-height: 16px;
  position: relative;
  padding-right: 80px;
  background: url(IconOther.png) no-repeat 15px 7px;
  padding-left: 35px;
  -webkit-transition: background-color ease .2s;
}

span.from-cache {
  /*background: #ededed;*/
  /*color: white;*/
  font-style: italic;
  /*padding: 2px 5px;*/
  /*border-radius: 8px;*/
  display: inline;
}

section article.include {
  opacity: 0.7;
}

section article.html {
  background: url(IconHTML.png) no-repeat 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.html.include {
  background-image: url(IconHTMLInclude.png);
  background-position: 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.haml {
  background: url(IconHAML.png) no-repeat 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.haml.include {
  background-image: url(IconHAMLInclude.png);
  background-position: 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.slim {
  background: url(IconSLIM.png) no-repeat 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.slim.include {
  background-image: url(IconSLIMInclude.png);
  background-position: 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.md {
  background: url(IconMD.png) no-repeat 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.md.include {
  background-image: url(IconMDInclude.png);
  background-position: 14px 12px;
  padding-left: 57px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.css {
  background: url(IconCSS.png) no-repeat 14px 12px;
  padding-left: 46px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.css.optimized {
  background-image: url(IconCSSOptimized.png);
  padding-left: 54px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.sass {
  background: url(IconSASS.png) no-repeat 14px 12px;
  padding-left: 46px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.scss {
  background: url(IconSCSS.png) no-repeat 14px 12px;
  padding-left: 46px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.sass.optimized {
  background-image: url(IconSASSOptimized.png);
  padding-left: 54px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.scss.optimized {
  background-image: url(IconSCSSOptimized.png);
  padding-left: 54px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.js, section article.jst {
  background: url(IconJS.png) no-repeat 14px 12px;
  padding-left: 46px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.js.optimized, section article.jst.optimized {
  background-image: url(IconJSOptimized.png);
  padding-left: 54px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.coffee {
  background: url(IconCoff.png) no-repeat 14px 12px;
  padding-left: 46px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.coffee.optimized {
  background-image: url(IconCoffOptimized.png);
  padding-left: 54px;
  padding-top: 8px;
  padding-bottom: 10px;
}

section article.image {
  background: url(IconImage.png) no-repeat 14px 7px;
  padding-left: 39px;
  padding-top: 6px;
  padding-bottom: 6px;
}

section article.ignored {
  background: url(IconIgnored.png) no-repeat 15px 7px;
  padding-left: 35px;
  padding-top: 6px;
  padding-bottom: 6px;
}

section article:hover {
  background-color: #fafafa;
}

section article.selected {
  background-color: #fafafa;
  box-shadow: inset 0 1px 0 #edf0f1, inset 0 -1px 0 #edf0f1;
}

section#todos article {
  border-bottom: 1px solid #eee;
  padding-left: 60px;
}

section#todos article:nth-of-type(even) {
  background-color: #fff;
}

section .set {
  margin-bottom: 10px;
}

section article span.filename {
  font-weight: bold;
  color: #444;
  display: block;
}

section article.error span.filename {
  color: #d95351;
}

section article span.filename a {
  border-radius: 20px;
  padding: 1px 6px 2px 6px;
  margin-left: -6px;
  text-decoration: none;
  color: #444;
  -webkit-transition: all ease .2s;
}

section article:hover span.filename a {
  color: #fff;
  border-radius: 20px;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.2);
  background-color: #539ed8;
  -moz-box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
}

section article#placeholder {
  border-bottom: none;
  padding-left: 35px;
}

section article#placeholder span.filename {
  color: #a6a9b1;
}

section article.ignored span.filename {
  color: #a6a9b1;
}

section article span {
  display: block;
}

section article small {
  font-size: 11px;
  color: #a6a9b1;
  display: block;
  cursor: default;
}

section article small a {
  color: #a6a9b1;
  font-weight: bold;
  text-decoration: none;
}

section article small a:hover {
  color: #539ed8;
  font-weight: bold;
  text-decoration: none;
}

section article small.compiled {
  background: url(IconCompiled.png) no-repeat left 2px;
  padding-left: 20px;
}

section article span.todo {
  background: url(IconNote.png) no-repeat left 2px;
  padding-left: 18px;
  color: #c88c2d;
  margin-top: 2px;
}

section article span.error {
  color: #d95351;
}

section article span.error::after {
  content: '';
  position: absolute;
  width: 16px;
  height: 16px;
  background: url(IconError.png) no-repeat 1px 2px;
  top: 26px;
  left: 18px;
}

article a.edit {
  background: url(IconEdit.png) no-repeat left 1px;
  position: absolute;
  width: 32px;
  height: 16px;
  text-indent: -9999px;
  overflow: hidden;
  right: 38px;
  top: 50%;
  margin-top: -8px;
  opacity: 0;
  pointer-events: none;
  -webkit-transition: opacity ease .2s;
}

article a.edit:active {
  background: url(IconEditPushed.png) no-repeat left 1px;
}

article a.reveal {
  background: url(IconReveal.png) no-repeat left 1px;
  position: absolute;
  width: 14px;
  height: 16px;
  text-indent: -9999px;
  overflow: hidden;
  right: 14px;
  top: 50%;
  margin-top: -8px;
  opacity: 0;
  pointer-events: none;
  -webkit-transition: opacity ease .2s;
}

article a.reveal:active {
  background: url(IconRevealPushed.png) no-repeat left 1px;
}

article a.browser {
  background: url(IconBrowser.png) no-repeat left 0;
  position: absolute;
  width: 14px;
  height: 16px;
  text-indent: -9999px;
  overflow: hidden;
  right: 80px;
  top: 50%;
  margin-top: -8px;
  opacity: 0;
  pointer-events: none;
  -webkit-transition: opacity ease .2s;
}

article a.browser:active {
  background: url(IconBrowserPushed.png) no-repeat left 0px;
}

article:hover a.edit, article:hover a.reveal, article:hover a.browser {
  opacity: 1;
  pointer-events: auto;
}

.wrap .load {
  margin-top: 5px;
  margin-left: 15px;
  margin-right: 15px;
}

.wrap .load a {
  background-image: -webkit-gradient(linear, left bottom, left top, from(#f5f5f5), to(#ffffff));
  background-image: -moz-linear-gradient(90deg, #f5f5f5 0%, #ffffff 100%);
  text-align: center;
  color: #999;
  border: 1px solid #dfdfdf;
  border-radius: 3px;
  padding-top: 4px;
  padding-bottom: 4px;
  cursor: pointer;
  display: block;
  text-decoration: none;
}

.wrap .load a:active {
  background-image: -webkit-gradient(linear, left bottom, left top, from(#cfcfcf), to(#adadad));
  background-image: -moz-linear-gradient(90deg, #cfcfcf 0%, #adadad 100%);
  color: #fff;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  border: 1px solid #999;
}

.build-error {
  padding-top: 50px;
  text-align: center;
  width: 90%;
  top: 80px;
  margin: 80px auto 0;
  display: block;
  background: url(MissingFolder.png) top center no-repeat;
}

.build-error.no-files span {
  margin-top: -20px;
  background: none;
}

.build-error span {
  position: absolute;
  left: 50%;
  margin-left: -150px;
  top: 50%;
  margin-top: -40px;
  width: 300px;
  height: 80px;
  padding-top: 60px;
  color: #aaa;
  text-align: center;
}

.build-error h1 {
  font-size: 20px;
}

.build-error p {
  width: 100%;
  margin: 10px auto;
  background: #efefef;
  padding: 5px;
  text-align: left;
}

.not-found span {
  background: url(MissingFolder.png) top center no-repeat;
}

.no-files span {
  background: url(NoFiles.png) top center no-repeat;
}

.too-big span {
  background: url(WarningStatus.png) top center no-repeat;
}

@media all and (-webkit-min-device-pixel-ratio: 2) {

  section article {
    background-image: url(IconOther@2x.png);
    background-size: 12px 15px;
  }

  section article.html {
    background-image: url(IconHTML@2x.png);
    background-size: 35px 28px;
  }

  section article.html.include {
    background-image: url(IconHTMLInclude@2x.png);
    background-size: 29px 28px;
  }

  section article.haml {
    background-image: url(IconHAML@2x.png);
    background-size: 35px 28px;
  }

  section article.haml.include {
    background-image: url(IconHAMLInclude@2x.png);
    background-size: 29px 28px;
  }

  section article.slim {
    background-image: url(IconSLIM@2x.png);
    background-size: 35px 28px;
  }

  section article.slim.include {
    background-image: url(IconSLIMInclude@2x.png);
    background-size: 29px 28px;
  }

  section article.md {
    background-image: url(IconMD@2x.png);
    background-size: 35px 28px;
  }

  section article.md.include {
    background-image: url(IconMDInclude@2x.png);
    background-size: 29px 28px;
  }

  section article.css {
    background-image: url(IconCSS@2x.png);
    background-size: 24px 28px;
  }

  section article.css.optimized {
    background-image: url(IconCSSOptimized@2x.png);
    background-size: 32px 28px;
  }

  section article.sass {
    background-image: url(IconSASS@2x.png);
    background-size: 24px 28px;
  }

  section article.scss {
    background-image: url(IconSCSS@2x.png);
    background-size: 24px 28px;
  }

  section article.sass.optimized {
    background-image: url(IconSASSOptimized@2x.png);
    background-size: 32px 28px;
  }

  section article.scss.optimized {
    background-image: url(IconSCSSOptimized@2x.png);
    background-size: 32px 28px;
  }

  section article.js, section article.jst {
    background-image: url(IconJS@2x.png);
    background-size: 24px 28px;
  }

  section article.js.optimized, section article.jst.optimized {
    background-image: url(IconJSOptimized@2x.png);
    background-size: 32px 28px;
  }

  section article.coffee {
    background-image: url(IconCoff@2x.png);
    background-size: 24px 28px;
  }

  section article.coffee.optimized {
    background-image: url(IconCoffOptimized@2x.png);
    background-size: 32px 28px;
  }

  section article.image {
    background-image: url(IconImage@2x.png);
    background-size: 18px 16px;
  }

  section article.ignored {
    background-image: url(IconIgnored@2x.png);
    background-size: 12px 15px;
  }

  section article small.compiled {
    background-image: url(IconCompiled@2x.png);
    background-size: 15px 13px;
  }

  section article span.todo {
    background-image: url(IconNote@2x.png);
    background-size: 12px 13px;
  }

  article a.edit {
    background-image: url(IconEdit@2x.png);
    background-size: 32px 15px;
  }

  article a.edit:active {
    background-image: url(IconEditPushed@2x.png);
    background-size: 32px 15px;
  }

  article a.reveal {
    background-image: url(IconReveal@2x.png);
    background-size: 14px 15px;
  }

  article a.reveal:active {
    background-image: url(IconRevealPushed@2x.png);
    background-size: 14px 15px;
  }

  article a.browser {
    background-image: url(IconBrowser@2x.png);
    background-size: 14px 15px;
  }

  article a.browser:active {
    background-image: url(IconBrowserPushed@2x.png);
    background-size: 14px 15px;
  }

  section article span.error::after {
    background-image: url(IconError@2x.png);
    background-size: 14px 13px;
  }

  .not-found span {
    background: url(MissingFolder@2x.png) top center no-repeat;
    background-size: 65px 50px;
  }

  .no-files span {
    background: url(NoFiles@2x.png) top center no-repeat;
    background-size: 54px 56px;
  }

  .too-big span {
    background: url(WarningStatus@2x.png) top center no-repeat;
    background-size: 60px 53px;
  }

}

/* Missing messages */

section .message {
  background-color: #fff;
  text-align: center;
  margin-left: 14px;
  margin-right: 14px;
  margin-top: 15px;
  border-radius: 4px;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .03), inset 0 0 20px rgba(0, 0, 0, .05);
  color: #999;
  padding: 10px 30px;
}

section .message b {
  display: block;
  padding-bottom: 8px;
}

section .message code {
  font-weight: normal;
  font-style: normal;
  font-family: Monaco, monospace;
  padding-left: 5px;
}

#version:hover {
  opacity: 0.5;
}

#version {
  width: 100%;
  opacity: 0.1;
  text-align: center;
  position: relative;
  padding-right: 15px;
  bottom: 20px;
}


text:
namespace Appleseed.Services.Base.Engine.Processors.Impl
{
    public class IdentityAggregator : IAggregateData
    {
        public void Aggregate()
        {
            // Do nothing.  Data input to database manually
        }
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var INITIAL_STATE = {
  component: null,
  location: null,
  open: false
};

var open = function open(state, action) {
  return {
    component: action.component,
    location: action.location,
    open: true
  };
};

var close = function close(state, action) {
  return _extends({}, state, {
    open: false
  });
};

var clear = function clear(state, action) {
  return _extends({}, INITIAL_STATE);
};

var reducer = function reducer() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : INITIAL_STATE;
  var action = arguments[1];

  switch (action.type) {

    case 'OPEN':
      return open(state, action);

    case 'CLOSE':
      return close(state, action);

    case 'CLEAR':
      return clear(state, action);

    default:
      return state;
  }
};

exports.default = reducer;


text:
//
//  GDataFeedSpreadsheetCell.m
//

#if !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_SPREADSHEET_SERVICE

#import "GDataEntrySpreadsheetCell.h"
#import "GDataSpreadsheetConstants.h"
#import "GDataFeedSpreadsheetCell.h"
#import "GDataCategory.h"
#import "GDataRowColumnCount.h"

@implementation GDataFeedSpreadsheetCell

+ (NSString *)coreProtocolVersionForServiceVersion:(NSString *)serviceVersion {
  return [GDataSpreadsheetConstants coreProtocolVersionForServiceVersion:serviceVersion];
}

+ (GDataFeedSpreadsheetCell *)spreadsheetCellFeedWithXMLData:(NSData *)data {
  return [self feedWithXMLData:data];
}

+ (GDataFeedSpreadsheetCell *)spreadsheetCellFeed {
  GDataFeedSpreadsheetCell *feed = [self object];
  [feed setNamespaces:[GDataSpreadsheetConstants spreadsheetNamespaces]];
  return feed;
}

#pragma mark -

+ (NSString *)standardEntryKind {
  // spreadsheet categories do not use the standard Kind scheme
  // (kGDataCategoryScheme) so cannot be init'd by GDataEntryBase
  return nil;
}

+ (void)load {
  // spreadsheet categories do not use the standard Kind scheme
  // (kGDataCategoryScheme) so cannot be registered with +registerEntryClass
  [GDataFeedBase registerFeedClass:[self class]
             forCategoryWithScheme:nil
                              term:kGDataCategorySpreadsheetCell];
}

- (void)addExtensionDeclarations {

  [super addExtensionDeclarations];

  Class entryClass = [self class];

  // Worksheet extensions
  [self addExtensionDeclarationForParentClass:entryClass
                                   childClasses:
   [GDataColumnCount class],
   [GDataRowCount class],
   nil];
}

- (id)init {
  self = [super init];
  if (self) {
    [self addCategory:[GDataCategory categoryWithScheme:kGDataCategorySchemeSpreadsheet
                                                   term:kGDataCategorySpreadsheetCell]];
  }
  return self;
}

#if !GDATA_SIMPLE_DESCRIPTIONS
- (NSMutableArray *)itemsForDescription {

  NSMutableArray *items = [super itemsForDescription];

  NSString *colStr = [NSString stringWithFormat:@"%d", (int) [self columnCount]];
  NSString *rowStr = [NSString stringWithFormat:@"%d", (int) [self rowCount]];

  [self addToArray:items objectDescriptionIfNonNil:colStr withName:@"cols"];
  [self addToArray:items objectDescriptionIfNonNil:rowStr withName:@"rows"];

  return items;
}
#endif

- (Class)classForEntries {
  return [GDataEntrySpreadsheetCell class];
}

+ (NSString *)defaultServiceVersion {
  return kGDataSpreadsheetDefaultServiceVersion;
}

#pragma mark -

- (NSInteger)rowCount {
  GDataRowCount *rowCount =
    (GDataRowCount *) [self objectForExtensionClass:[GDataRowCount class]];

  return [rowCount count];
}

- (NSInteger)columnCount {
  GDataColumnCount *columnCount =
    (GDataColumnCount *) [self objectForExtensionClass:[GDataColumnCount class]];

  return [columnCount count];
}

@end

#endif // !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_SPREADSHEET_SERVICE


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xunce.signin" >

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Act.SplashActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Act.SignInActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".ActAccount.RegisterActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".ActAccount.LoginActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".ActAccount.ForgetPswActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".Act.SummaryActivity"
            android:label="@string/title_activity_summary" >
        </activity>
    </application>

</manifest>


text:
$(function(){
  $('.scan').click(function(){

    $.ajax({
      type: "GET",
      url: "/scan",
      success: function(response){
        console.log(response);
        console.log("nice!");
        $flash = $('.error-holder');
        $flash.hide();
        $flash.append('
Tweets Scanned
');
        $flash.fadeIn(800, function(){
          $flash.fadeOut(800);
        });

      },
      error: function(response){
        console.log(response);
        console.log("uh oh");
      }
    });

  });

});


text:
STOP_WORDS = set(
    """
a à â abord afin ah ai aie ainsi ait allaient allons
alors anterieur anterieure anterieures antérieur antérieure antérieures
apres après as assez attendu au
aupres auquel aura auraient aurait auront
aussi autre autrement autres autrui aux auxquelles auxquels avaient
avais avait avant avec avoir avons ayant

bas basee bat

c' c' ça car ce ceci cela celle celle-ci celle-la celle-là celles celles-ci celles-la celles-là
celui celui-ci celui-la celui-là cent cependant certain certaine certaines certains certes ces
cet cette ceux ceux-ci ceux-là chacun chacune chaque chez ci cinq cinquantaine cinquante
cinquantième cinquième combien comme comment compris concernant

d' d' da dans de debout dedans dehors deja dejà delà depuis derriere
derrière des desormais desquelles desquels dessous dessus deux deuxième
deuxièmement devant devers devra different differente differentes differents différent
différente différentes différents dire directe directement dit dite dits divers
diverse diverses dix dix-huit dix-neuf dix-sept dixième doit doivent donc dont
douze douzième du duquel durant dès déja déjà désormais

effet egalement eh elle elle-meme elle-même elles elles-memes elles-mêmes en encore
enfin entre envers environ es ès est et etaient étaient etais étais etait était
etant étant etc etre être eu eux eux-mêmes exactement excepté également

fais faisaient faisant fait facon façon feront font

gens

ha hem hep hi ho hormis hors hou houp hue hui huit huitième
hé i il ils importe

j' j' je jusqu jusque juste

l' l' la laisser laquelle le lequel les lesquelles lesquels leur leurs longtemps
lors lorsque lui lui-meme lui-même là lès

m' m' ma maint maintenant mais malgre malgré me meme memes merci mes mien
mienne miennes miens mille moi moi-meme moi-même moindres moins
mon même mêmes

n' n' na ne neanmoins neuvième ni nombreuses nombreux nos notamment
notre nous nous-mêmes nouveau nul néanmoins nôtre nôtres

o ô on ont onze onzième or ou ouias ouste outre
ouvert ouverte ouverts où

par parce parfois parle parlent parler parmi partant
pas pendant pense permet personne peu peut peuvent peux plus
plusieurs plutot plutôt possible possibles pour pourquoi
pourrais pourrait pouvait prealable precisement
premier première premièrement
pres procedant proche près préalable précisement pu puis puisque

qu' qu' quand quant quant-à-soi quarante quatorze quatre quatre-vingt
quatrième quatrièmement que quel quelconque quelle quelles quelqu'un quelque
quelques quels qui quiconque quinze quoi quoique

relative relativement rend rendre restant reste
restent retour revoici revoila revoilà

s' s' sa sait sans sauf se seize selon semblable semblaient
semble semblent sent sept septième sera seraient serait seront ses seul seule
seulement seuls seules si sien sienne siennes siens sinon six sixième soi soi-meme soi-même soit
soixante son sont sous souvent specifique specifiques spécifique spécifiques stop
suffisant suffisante suffit suis suit suivant suivante
suivantes suivants suivre sur surtout

t' t' ta tant te tel telle tellement telles tels tenant tend tenir tente
tes tien tienne tiennes tiens toi toi-meme toi-même ton touchant toujours tous
tout toute toutes treize trente tres trois troisième troisièmement très
tu té

un une unes uns

va vais vas vers via vingt voici voila voilà vont vos
votre votres vous vous-mêmes vu vé vôtre vôtres

y

""".split()
)


text:
using Org.Apache.Reef.Utilities.Diagnostics;
using Org.Apache.Reef.Utilities.Logging;
using Org.Apache.Reef.Wake.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reactive;
using System.Threading.Tasks;

namespace Org.Apache.Reef.Wake.Remote.Impl
{
    /// <summary>
    /// Manages incoming and outgoing messages between remote hosts.
    /// </summary>
    public class DefaultRemoteManager<T> : IRemoteManager<T>
    {
        private static readonly Logger LOGGER = Logger.GetLogger(typeof(DefaultRemoteManager<T>));

        private ObserverContainer<T> _observerContainer;
        private TransportServer<IRemoteEvent<T>> _server;
        private Dictionary<IPEndPoint, ProxyObserver> _cachedClients;
        private ICodec<IRemoteEvent<T>> _codec;

        /// <summary>
        /// Constructs a DefaultRemoteManager listening on the specified address and any
        /// available port.
        /// </summary>
        /// <param name="localAddress">The address to listen on</param>
        /// <param name="codec">The codec used for serializing messages</param>
        public DefaultRemoteManager(IPAddress localAddress, ICodec<T> codec) : this(localAddress, 0, codec)
        {
        }

        /// <summary>
        /// Constructs a DefaultRemoteManager listening on the specified IPEndPoint.
        /// </summary>
        /// <param name="localEndpoint">The endpoint to listen on</param>
        /// <param name="codec">The codec used for serializing messages</param>
        public DefaultRemoteManager(IPEndPoint localEndpoint, ICodec<T> codec)
        {
            if (localEndpoint == null)
            {
                throw new ArgumentNullException("localEndpoint");
            }
            if (localEndpoint.Port < 0)
            {
                throw new ArgumentException("Listening port must be greater than or equal to zero");
            }
            if (codec == null)
            {
                throw new ArgumentNullException("codec");
            }

            _codec = new RemoteEventCodec<T>(codec);
            _observerContainer = new ObserverContainer<T>();
            _cachedClients = new Dictionary<IPEndPoint, ProxyObserver>();

            // Begin to listen for incoming messages
            _server = new TransportServer<IRemoteEvent<T>>(localEndpoint, _observerContainer, _codec);
            _server.Run();

            LocalEndpoint = _server.LocalEndpoint;
            Identifier = new SocketRemoteIdentifier(LocalEndpoint);
        }

        /// <summary>
        /// Constructs a DefaultRemoteManager listening on the specified address and any
        /// available port.
        /// </summary>
        /// <param name="localAddress">The address to listen on</param>
        /// <param name="port">The port to listen on</param>
        /// <param name="codec">The codec used for serializing messages</param>
        public DefaultRemoteManager(IPAddress localAddress, int port, ICodec<T> codec)
        {
            if (localAddress == null)
            {
                throw new ArgumentNullException("localAddress");
            }
            if (port < 0)
            {
                throw new ArgumentException("Listening port must be greater than or equal to zero");
            }
            if (codec == null)
            {
                throw new ArgumentNullException("codec");
            }

            _observerContainer = new ObserverContainer<T>();
            _codec = new RemoteEventCodec<T>(codec);
            _cachedClients = new Dictionary<IPEndPoint, ProxyObserver>();

            IPEndPoint localEndpoint = new IPEndPoint(localAddress, port);

            // Begin to listen for incoming messages
            _server = new TransportServer<IRemoteEvent<T>>(localEndpoint, _observerContainer, _codec);
            _server.Run();

            LocalEndpoint = _server.LocalEndpoint;
            Identifier = new SocketRemoteIdentifier(LocalEndpoint);
        }

        /// <summary>
        /// Constructs a DefaultRemoteManager. Does not listen for incoming messages.
        /// </summary>
        /// <param name="codec">The codec used for serializing messages</param>
        public DefaultRemoteManager(ICodec<T> codec)
        {
            using (LOGGER.LogFunction("DefaultRemoteManager::DefaultRemoteManager"))
            {
                if (codec == null)
                {
                    throw new ArgumentNullException("codec");
                }

                _observerContainer = new ObserverContainer<T>();
                _codec = new RemoteEventCodec<T>(codec);
                _cachedClients = new Dictionary<IPEndPoint, ProxyObserver>();

                LocalEndpoint = new IPEndPoint(NetworkUtils.LocalIPAddress, 0);
                Identifier = new SocketRemoteIdentifier(LocalEndpoint);
            }
        }

        /// <summary>
        /// Gets the RemoteIdentifier for the DefaultRemoteManager
        /// </summary>
        public IRemoteIdentifier Identifier { get; private set; }

        /// <summary>
        /// Gets the local IPEndPoint for the DefaultRemoteManager
        /// </summary>
        public IPEndPoint LocalEndpoint { get; private set; }

        /// <summary>
        /// Returns an IObserver used to send messages to the remote host at
        /// the specified IPEndpoint.
        /// </summary>
        /// <param name="remoteEndpoint">The IPEndpoint of the remote host</param>
        /// <returns>An IObserver used to send messages to the remote host</returns>
        public IObserver<T> GetRemoteObserver(RemoteEventEndPoint<T> remoteEndpoint)
        {
            if (remoteEndpoint == null)
            {
                throw new ArgumentNullException("remoteEndpoint");
            }

            SocketRemoteIdentifier id = remoteEndpoint.Id as SocketRemoteIdentifier;
            if (id == null)
            {
                throw new ArgumentException("ID not supported");
            }

            return GetRemoteObserver(id.Addr);
        }

        /// <summary>
        /// Returns an IObserver used to send messages to the remote host at
        /// the specified IPEndpoint.
        /// </summary>
        /// <param name="remoteEndpoint">The IPEndpoint of the remote host</param>
        /// <returns>An IObserver used to send messages to the remote host</returns>
        public IObserver<T> GetRemoteObserver(IPEndPoint remoteEndpoint)
        {
            if (remoteEndpoint == null)
            {
                throw new ArgumentNullException("remoteEndpoint");
            }

            ProxyObserver remoteObserver;
            if (!_cachedClients.TryGetValue(remoteEndpoint, out remoteObserver))
            {
                TransportClient<IRemoteEvent<T>> client =
                    new TransportClient<IRemoteEvent<T>>(remoteEndpoint, _codec, _observerContainer);

                remoteObserver = new ProxyObserver(client);
                _cachedClients[remoteEndpoint] = remoteObserver;
            }

            return remoteObserver;
        }

        /// <summary>
        /// Registers an IObserver used to handle incoming messages from the remote host
        /// at the specified IPEndPoint.
        /// The IDisposable that is returned can be used to unregister the IObserver.
        /// </summary>
        /// <param name="remoteEndpoint">The IPEndPoint of the remote host</param>
        /// <param name="observer">The IObserver to handle incoming messages</param>
        /// <returns>An IDisposable used to unregister the observer with</returns>
        public IDisposable RegisterObserver(RemoteEventEndPoint<T> remoteEndpoint, IObserver<T> observer)
        {
            if (remoteEndpoint == null)
            {
                throw new ArgumentNullException("remoteEndpoint");
            }

            SocketRemoteIdentifier id = remoteEndpoint.Id as SocketRemoteIdentifier;
            if (id == null)
            {
                throw new ArgumentException("ID not supported");
            }

            return RegisterObserver(id.Addr, observer);
        }

        /// <summary>
        /// Registers an IObserver used to handle incoming messages from the remote host
        /// at the specified IPEndPoint.
        /// The IDisposable that is returned can be used to unregister the IObserver.
        /// </summary>
        /// <param name="remoteEndpoint">The IPEndPoint of the remote host</param>
        /// <param name="observer">The IObserver to handle incoming messages</param>
        /// <returns>An IDisposable used to unregister the observer with</returns>
        public IDisposable RegisterObserver(IPEndPoint remoteEndpoint, IObserver<T> observer)
        {
            if (remoteEndpoint == null)
            {
                throw new ArgumentNullException("remoteEndpoint");
            }
            if (observer == null)
            {
                throw new ArgumentNullException("observer");
            }

            return _observerContainer.RegisterObserver(remoteEndpoint, observer);
        }

        /// <summary>
        /// Registers an IObserver used to handle incoming messages from the remote host
        /// at the specified IPEndPoint.
        /// The IDisposable that is returned can be used to unregister the IObserver.
        /// </summary>
        /// <param name="observer">The IObserver to handle incoming messages</param>
        /// <returns>An IDisposable used to unregister the observer with</returns>
        public IDisposable RegisterObserver(IObserver<IRemoteMessage<T>> observer)
        {
            if (observer == null)
            {
                throw new ArgumentNullException("observer");
            }

            return _observerContainer.RegisterObserver(observer);
        }

        /// <summary>
        /// Release all resources for the DefaultRemoteManager.
        /// </summary>
        public void Dispose()
        {
            foreach (ProxyObserver cachedClient in _cachedClients.Values)
            {
                cachedClient.Dispose();
            }

            if (_server != null)
            {
                _server.Dispose();
            }
        }

        /// <summary>
        /// Observer to send messages to connected remote host
        /// </summary>
        private class ProxyObserver : IObserver<T>, IDisposable
        {
            private TransportClient<IRemoteEvent<T>> _client;
            private int _messageCount;

            /// <summary>
            /// Create new ProxyObserver
            /// </summary>
            /// <param name="client">The connected transport client used to send
            /// messages to remote host</param>
            public ProxyObserver(TransportClient<IRemoteEvent<T>> client)
            {
                _client = client;
                _messageCount = 0;
            }

            /// <summary>
            /// Send the message to the remote host
            /// </summary>
            /// <param name="message">The message to send</param>
            public void OnNext(T message)
            {
                IRemoteEvent<T> remoteEvent = new RemoteEvent<T>(_client.Link.LocalEndpoint, _client.Link.RemoteEndpoint, message)
                {
                    Sink = "default",
                    Sequence = _messageCount
                };

                _messageCount++;
                _client.Send(remoteEvent);
            }

            /// <summary>
            /// Close underlying transport client
            /// </summary>
            public void Dispose()
            {
                _client.Dispose();
            }

            public void OnError(Exception error)
            {
                throw new NotImplementedException();
            }

            public void OnCompleted()
            {
                throw new NotImplementedException();
            }
        }
    }
}


text:
// JSON C# Class Generator
// http://at-my-window.blogspot.com/?page=json-class-generator

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ZendeskApi_v2.Models.Requests
{

    public class GroupRequestResponse : GroupResponseBase
    {

        [JsonProperty("requests")]
        public IList<Request> Requests { get; set; }
    }
}


text:
import unittest
import collections
from SequenceUtils import calcIdenticalRate, getMismatchIndex

Word = collections.namedtuple('Word', ['word', 'discarded'])

class WordRoleCriteria:
  def __init__(self, primerSequenceStart, primerSequence, primerSilimarRatio, identicalSequenceStart, identicalSequence, siteAllows):
    self.PrimerSequence = primerSequence
    self.PrimerSequenceStart = primerSequenceStart
    self.PrimerSequenceEnd = self.PrimerSequenceStart + len(self.PrimerSequence)
    self.PrimerSimilarRatio = primerSilimarRatio
    self.IdenticalSequence = identicalSequence
    self.IdenticalSequenceStart = identicalSequenceStart
    self.IdenticalSequenceEnd = self.IdenticalSequenceStart + len(self.IdenticalSequence)
    self.SiteAllows = siteAllows

class WordRole:
  def __init__(self, sampleName, barcode, primerSequenceStart, primerSequence, primerSilimarRatio, identicalStart, identicalSequence, siteAllows):
    self.SampleName = sampleName
    self.Barcode = barcode
    self.PrimerSequenceStart = primerSequenceStart
    self.PrimerSequence = primerSequence
    self.PrimerSimilarRatio = primerSilimarRatio
    self.IdenticalStart = identicalStart
    self.IdenticalSequence = identicalSequence
    self.SiteAllows = siteAllows

  def getWord(self, sequence):
    curBarcode = sequence[0:len(self.Barcode)]

    if self.Barcode != curBarcode :
      return(Word("", False))

    curPrimerSequence = sequence[self.PrimerSequenceStart:self.PrimerSequenceStart + len(self.PrimerSequence)]
    similarRatio = calcIdenticalRate(self.PrimerSequence, curPrimerSequence)
    if similarRatio < self.PrimerSimilarRatio:
      return(Word("", False))

    curSequence = sequence[self.IdenticalStart:self.IdenticalStart + len(self.IdenticalSequence)]
    word = ""
    for idx in range(0, len(self.IdenticalSequence)):
      refBase = self.IdenticalSequence[idx]
      if refBase == 'R':
        if curSequence[idx] not in self.SiteAllows:
          return(Word("", True))
        word = word + curSequence[idx]
      elif curSequence[idx] != refBase:
        return(Word("", True))

    return((Word(word, False)))

class TestWordRole(unittest.TestCase):
    def testGetWordTurnee(self):
        role = WordRole("MalikG", "ATATGA", 6, "GCTGGACCGGTATGTAGCA", 0.9, 25, "RTRCGTRRTCCTRTTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAA", ['A', 'G'])
        sequence = "ATATGAGCTGGACCGGTATGTAGCAGTACGTAGTCCTATTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAAGATTGCCATCGTTTGGGCAATATCAATAGGAGTTTCAGTTCCTATCCCTGTGATTGGACTGAGGGACGAAAGCAAAGTGTTCGTGAATAATACTACCTGCGTGCTCAATGACCCGAACTTCGTTCTCATCGGGTCCTTCGTGGCATTCTTCATCCCGTTGACAATTATGGTGATCACCTACTTCTTAACGATCTACGTCCTACGCCGTCAAGCTTTGAT"
        curWord = role.getWord(sequence)
        self.assertEqual(curWord.word, "GAAGA")
        self.assertFalse(curWord.discarded)

    def testGetWordTurneeNotDiscard1(self):
        role = WordRole("MalikG", "ATATGA", 6, "GCTGGACCGGTATGTAGCA", 0.9, 25, "RTRCGTRRTCCTRTTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAA", ['A', 'G'])
        sequence = "TTATGAGCTGGACCGGTATGTAGCAGTACGTAGTCCTATTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAAGATTGCCATCGTTTGGGCAATATCAATAGGAGTTTCAGTTCCTATCCCTGTGATTGGACTGAGGGACGAAAGCAAAGTGTTCGTGAATAATACTACCTGCGTGCTCAATGACCCGAACTTCGTTCTCATCGGGTCCTTCGTGGCATTCTTCATCCCGTTGACAATTATGGTGATCACCTACTTCTTAACGATCTACGTCCTACGCCGTCAAGCTTTGAT"
        curWord = role.getWord(sequence)
        self.assertEqual(curWord.word, "")
        self.assertFalse(curWord.discarded)

    def testGetWordTurneeNotDiscard2(self):
        role = WordRole("MalikG", "ATATGA", 6, "GCTGGACCGGTATGTAGCA", 0.9, 25, "RTRCGTRRTCCTRTTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAA", ['A', 'G'])
        sequence = "ATATGAGCTaaACCGGTATGTAGCAGTACGTAGTCCTATTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAAGATTGCCATCGTTTGGGCAATATCAATAGGAGTTTCAGTTCCTATCCCTGTGATTGGACTGAGGGACGAAAGCAAAGTGTTCGTGAATAATACTACCTGCGTGCTCAATGACCCGAACTTCGTTCTCATCGGGTCCTTCGTGGCATTCTTCATCCCGTTGACAATTATGGTGATCACCTACTTCTTAACGATCTACGTCCTACGCCGTCAAGCTTTGAT"
        curWord = role.getWord(sequence)
        self.assertEqual(curWord.word, "")
        self.assertFalse(curWord.discarded)

    def testGetWordTurneeDiscard(self):
        role = WordRole("MalikG", "ATATGA", 6, "GCTGGACCGGTATGTAGCA", 0.9, 25, "RTRCGTRRTCCTRTTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAA", ['A', 'G'])
        sequence = "ATATGAGCTGGACCGGTATGTAGCAGTACGTAGaCCTATTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAAGATTGCCATCGTTTGGGCAATATCAATAGGAGTTTCAGTTCCTATCCCTGTGATTGGACTGAGGGACGAAAGCAAAGTGTTCGTGAATAATACTACCTGCGTGCTCAATGACCCGAACTTCGTTCTCATCGGGTCCTTCGTGGCATTCTTCATCCCGTTGACAATTATGGTGATCACCTACTTCTTAACGATCTACGTCCTACGCCGTCAAGCTTTGAT"
        curWord = role.getWord(sequence)
        self.assertEqual(curWord.word, "")
        self.assertTrue(curWord.discarded)

    def testGetWordKayla(self):
        role = WordRole("Kayla1", "AGATAC", 7, "TTAACCCTCACTAAAGGGATTCTCA", 0.9, 43, "GTGATAAGGTCAATGRGGAGATGTATATA", ['A', 'G'])
        sequence = "AGATACATTAACCCTCACTAAAGGGATTCTCAGGATGTCCTTCGTGATAAGGTCAATGAGGAGATGTATATAGAAAGGTTATTTGATCAATGGTACAACAGCTCCATGAACATCATCTGCACGTGGCTGACCCTATAGTGAGTCGTATTAAGATCGGAAGATCTCGTATGCCGTCTTCTGCTTGAAAAAAAAAAAAAAGAAAAAGAAGAATGGAATGAAGACAATGAAAAGAAAAAAAAAAATAGAATAGTTAATAGTACATTACGGCGGAGGATAAGAGTAAGAGTAGAATGAATAGAG"
        curWord = role.getWord(sequence)
        self.assertEqual(curWord.word, "A")
        self.assertFalse(curWord.discarded)

    def testGetWordHussain(self):
        role = WordRole("Hussain1", "AACCAT", 7, "TTAACCCTCACTAAAGGGAGCTGAT", 0.9, 200, "RTRCGTRRTCCTRTTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAA", ['A', 'G'])
        sequence = "AACCATATTAACCCTCACTAAAGGGAGCTGATATGCTGGTGGGACTACTTGTCATGCCCCTGTCTCTGCTTGCAATTCTTTATGATTATGTCTGGCCTTTACCTAGATATTTGTGCCCCGTCTGGATTTCACTAGATGTGCTATTTTCAACTGCGTCCATCATGCACCTCTGCGCCATATCGCTGGACCGGTATGTAGCAGTGCGTAATCCTGTTGAGCATAGCCGGTTCAATTCGCGGACTAAGGCCATCATGAAGATTGCCATCGTTTGGGCAATATCAATAGGAGTTTCAGTTCCTA"
        curWord = role.getWord(sequence)
        self.assertEqual(curWord.word, "GGAAG")
        self.assertFalse(curWord.discarded)


text:
package cogx.platform.cpumemory

import cogx.cogmath.algebra.real.Vector
import cogx.platform.types.FieldType
import cogx.platform.types.ElementTypes.Float32
import java.nio.FloatBuffer
import cogx.platform.opencl.OpenCLParallelCommandQueue
import cogx.platform.cpumemory.readerwriter.{VectorFieldWriter, VectorFieldReader, FieldReader}
import cogx.cogmath.geometry.Shape

/** CPU memory for a vector field.
  *
  * @param fieldType Type of the field.
  * @param bufferType Type of Java Buffer used to hold data in the field.
  * @param commandQueue Command queue needed to create pinned buffers.
  *
  * @author Greg Snider
  */

final class VectorFieldMemory private[cpumemory] (fieldType: FieldType,
                                            bufferType: BufferType,
                                            commandQueue: OpenCLParallelCommandQueue = null)
        extends AbstractFieldMemory(fieldType, bufferType, commandQueue)
        with VectorFieldReader
        with VectorFieldWriter
{
  require(tensorOrder == 1)
  require(elementType == Float32)
  if (bufferType == PinnedDirectBuffer)
    require(commandQueue != null)
  private val writable = true

  /** Byte buffer cast to appropriate buffer type to handle endianness. */
  _directBuffer = _byteBuffer.asFloatBuffer

  /** The direct buffer for this memory. This is always a view of _byteBuffer,
    * but upcast to the appropriate subclass of Buffer using, for example,
    * ByteBuffer.asFloatBuffer. The view calls are somewhat dangerous because
    * they create a view with proper endianness for Java (which uses the native
    * endianness internally) but they can also change the endianness of
    * _byteBuffer. This is subtle, so read the Java documentation carefully if
    * you need to change this.
    */
  def directBuffer: FloatBuffer = _directBuffer.asInstanceOf[FloatBuffer]

  /** Fill memory with values produced by an iterator. */
  def write(values: Iterator[Vector]) {
    synchronized {
      dimensions match {
        case 0 => fill0D(values)
        case 1 => fill1D(values)
        case 2 => fill2D(values)
        case 3 => fill3D(values)
      }
    }
  }

  /** Read the single value in a 0D vector field into `out`. */
  def read(out: Vector) {
    require(dimensions == 0)
    readTensor(0, out.asArray)
  }

  /** Read the value at (`col`) in a 1D vector field into `out`. */
  def read(col: Int, out: Vector) {
    require(dimensions == 1)
    readTensor(col, out.asArray)
  }

  /** Read the value at (`row`, `col`) in a 2D vector field into `out`. */
  def read(row: Int, col: Int, out: Vector) {
    require(dimensions == 2)
    readTensor(row * paddedColumns + col, out.asArray)
  }

  /** Read the value at (`layer`, `row`, `col`) in a 3D vector field into `out`. */
  def read(layer: Int, row: Int, col: Int, out: Vector) {
    require(dimensions == 3)
    readTensor(layer * rows * paddedColumns + row * paddedColumns + col, out.asArray)
  }

  /** Read the entire field as a flat array; used only for testing. */
  private[cogx] def readAsPaddedArray: Array[Float] = {
    val array = new Array[Float](bufferSize)
    for (i <- 0 until bufferSize)
      array(i) = directBuffer.get(i)
    array
  }

  /** Read a tensor from the field memory into an array.
    *
    * @param startIndex Index in direct buffer for the start of the tensor.
    * @param to Array where tensor is to be written.
    */
  private def readTensor(startIndex: Int, to: Array[Float]) {
    var index = startIndex
    for (i <- 0 until tensorShape.points) {
      to(i) = directBuffer.get(index)
      index += tensorStride
    }
  }

  /** Write a tensor from an array into the field memory.
    *
    * @param startIndex Index in direct buffer for the start of the tensor.
    * @param from Array where tensor is to be read
    */
  private def writeTensor(startIndex: Int, from: Array[Float]) {
    var index = startIndex
    for (i <- 0 until tensorShape.points) {
      directBuffer.put(index, from(i))
      index += tensorStride
    }
  }

  /** Write `out` to a 0D vector field. */
  def write(out: Vector) {
    require(dimensions == 0 && writable)
    writeTensor(0, out.asArray)
  }

  /** Write `out` to a 1D vector field at (`col`). */
  def write(col: Int, out: Vector) {
    require(dimensions == 1 && writable)
    writeTensor(col, out.asArray)
  }

  /** Write `out` to a 2D vector field at (`row`, `col`). */
  def write(row: Int, col: Int, out: Vector) {
    require(dimensions == 2 && writable)
    writeTensor(row * paddedColumns + col, out.asArray)
  }

  /** Write `out` to a 3D vector field at (`row`, `col`). */
  def write(layer: Int, row: Int, col: Int, out: Vector) {
    require(dimensions == 3 && writable)
    writeTensor(layer * rows * paddedColumns + row * paddedColumns + col, out.asArray)
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def init(generator: () => Vector) {
    require(dimensions == 0)
    write(generator())
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def init(generator: (Int) => Vector) {
    require(dimensions == 1)
    for (col <- 0 until fieldType.fieldShape(0))
      write(col, generator(col))
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def init(generator: (Int, Int) => Vector) {
    require(dimensions == 2)
    val rows = fieldType.fieldShape(0)
    val columns = fieldType.fieldShape(1)
    for (row <- 0 until rows; col <- 0 until columns)
      write(row, col, generator(row, col))
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def init(generator: (Int, Int, Int) => Vector) {
    require(dimensions == 3)
    val layers = fieldType.fieldShape(0)
    val rows = fieldType.fieldShape(1)
    val columns = fieldType.fieldShape(2)
    for (layer <- 0 until layers; row <- 0 until rows; col <- 0 until columns)
      write(layer, row, col, generator(layer, row, col))
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def fill0D(values: Iterator[Vector]) {
    require(dimensions == 0 && writable)
    writeTensor(0, values.next().asArray)
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def fill1D(values: Iterator[Vector]) {
    require(dimensions == 1 && writable)
    for (col <- 0 until fieldType.fieldShape(0))
      writeTensor(col, values.next().asArray)
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def fill2D(values: Iterator[Vector]) {
    require(dimensions == 2 && writable)
    val rows = fieldType.fieldShape(0)
    val columns = fieldType.fieldShape(1)
    for (row <- 0 until rows; col <- 0 until columns)
      writeTensor(row * paddedColumns + col,
        values.next().asArray)
  }

  /** Fill memory with values produced by `generator`. */
  private[cogx] def fill3D(values: Iterator[Vector]) {
    require(dimensions == 3 && writable)
    val layers = fieldType.fieldShape(0)
    val rows = fieldType.fieldShape(1)
    val columns = fieldType.fieldShape(2)
    for (layer <- 0 until layers; row <- 0 until rows; col <- 0 until columns)
      writeTensor(layer * rows * paddedColumns + row * paddedColumns + col,
        values.next().asArray)
  }

  /** Compute the L-infinity norm on the difference of `this` and `that`.
    *
    * @param that AbstractFieldMemory to compare to `this`
    * @return L-infinity error
    */
  def compareLinf(that: FieldReader): Float = {
    require(fieldType.equals(that.fieldType))
    require(that.isInstanceOf[VectorFieldReader])
    require(dimensions >= 0 && dimensions <= 3)
    require(tensorShape.dimensions == 1)

    val v1 = Vector(tensorShape(0), _ => 0f)
    val v2 = Vector(tensorShape(0), _ => 0f)

    dimensions match {
      case 0 =>
        read(v1)
        that.asInstanceOf[VectorFieldReader].read(v2)
        (v1 - v2).abs.reduce(_.max(_))

      case 1 =>
        var err = 0f
        for (i <- 0 until fieldShape(0)) {
          read(i, v1)
          that.asInstanceOf[VectorFieldReader].read(i, v2)
          err = err.max((v1 - v2).abs.reduce(_.max(_)))
        }
        err

      case 2 =>
        var err = 0f
        for (i <- 0 until fieldShape(0)) {
          for (j <- 0 until fieldShape(1)) {
            read(i, j, v1)
            that.asInstanceOf[VectorFieldReader].read(i, j, v2)
            err = err.max((v1 - v2).abs.reduce(_.max(_)))
          }
        }
        err

      case 3 =>
        var err = 0f
        for (i <- 0 until fieldShape(0)) {
          for (j <- 0 until fieldShape(1)) {
            for (k <- 0 until fieldShape(2)) {
              read(i, j, k, v1)
              that.asInstanceOf[VectorFieldReader].read(i, j, k, v2)
              err = err.max((v1 - v2).abs.reduce(_.max(_)))
            }
          }
        }
        err

    }
  }

  /** Print out the field for debugging. */
  def print() {
    throw new RuntimeException("not implemented yet")
  }

}


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

/**
 * @fileoverview Invalid syntax .ts file, used by scripts/linters/
 * js_ts_linter_test.py. eslint @typescript-eslint no explicit any
 * is not allowed to use.
 */

// eslint-disable-next-line @typescript-eslint/no-explicit-any
let a: any;


text:
/* Generated by Together */

package edu.unm.neat.jneat;

import edu.unm.neat.jNeatCommon.IOseq;
import edu.unm.neat.jNeatCommon.NeatRoutine;

import java.util.StringTokenizer;

/**
 * A Trait is a group of parameters that can be expressed
 * as a group more than one time.  Traits save a genetic
 * algorithm from having to search vast parameter landscapes
 * on every node.  Instead, each node can simply point to a trait
 * and those traits can evolve on their own
 */
public class Trait extends Neat {
    /**
     * Numeric identification of trait
     */
    int trait_id;

    /**
     * Vector width real value for this object trait
     */
    double[] params;

    public Trait(Trait t) {
        trait_id = t.trait_id;

        this.params = new double[Neat.p_num_trait_params];
        for (int j = 0; j < Neat.p_num_trait_params; j++)
            params[j] = t.params[j];

    }

    public int getTrait_id() {
        return trait_id;
    }

    public void setTrait_id(int trait_id) {
        this.trait_id = trait_id;
    }

    public double[] getParams() {
        return params;
    }

    public double getParams(int j) {
        return params[j];
    }

    public void setParams(double[] params) {
        this.params = params;
    }

    /**
     * Insert the method's description here.
     * Creation date: (11/01/2002 16.40.34)
     */
    public Trait() {
        trait_id = 0;
        params = new double[Neat.p_num_trait_params];
        for (int j = 0; j < Neat.p_num_trait_params; j++)
            params[j] = 0.0;
    }

    /**
     * Insert the method's description here.
     * Creation date: (11/01/2002 16.24.46)
     *
     * @param i int
     */
    public Trait(String xline) {
        StringTokenizer st;
        String curword;

        st = new StringTokenizer(xline);

        // skip keyword
        curword = st.nextToken();

        //Get the trait_id
        curword = st.nextToken();
        trait_id = Integer.parseInt(curword);
        params = new double[Neat.p_num_trait_params];

        //get real values....
        for (int j = 0; j < Neat.p_num_trait_params; j++) {
            curword = st.nextToken();
            params[j] = Double.parseDouble(curword);

        }

    }

    /**
     * Insert the method's description here.
     * Creation date: (14/01/2002 11.46.30)
     */
    public void viewtext(String header) {
        System.out.print(header);
        //System.out.print("\n +TRAIT: ");
        System.out.print("id = " + trait_id);
        System.out.print(", params = [ ");
        for (int j = 0; j < Neat.p_num_trait_params; j++) {
            System.out.print(params[j] + " ");
        }
        System.out.print("]\n");

    }

    public void op_view() {

        System.out.print(" Trait #" + trait_id + "\t");

        for (int count = 0; count < Neat.p_num_trait_params; count++) {
            System.out.print(params[count] + " ");
        }
        System.out.print("\n");
    }/**
     * Insert the method's description here.
     * Creation date: (18/01/2002 13.02.06)
     */

    /**
     * Special Constructor creates a new Trait which is the average
     * of 2 existing traits passed in
     */
    public Trait(Trait t1, Trait t2) {
        params = new double[Neat.p_num_trait_params];
        for (int count = 0; count < Neat.p_num_trait_params; count++)
            params[count] = (t1.params[count] + t2.params[count]) / 2.0;
        trait_id = t1.trait_id;

    }

    /**
     * Insert the method's description here.
     * Creation date: (18/01/2002 13.02.06)
     */
    public void mutate() {
        for (int count = 0; count < Neat.p_num_trait_params; count++) {
            if (NeatRoutine.randfloat() > Neat.p_trait_param_mut_prob) {
                params[count] += (NeatRoutine.randposneg() * NeatRoutine.randfloat()) * Neat.p_trait_mutation_power;
                if (params[count] < 0)
                    params[count] = 0;
            }
        }
    }

    /**
     * Insert the method's description here.
     * Creation date: (01/02/2002 8.23.59)
     *
     * @param a char
     */
    public Trait(char a) {
    }

    /**
     * Insert the method's description here.
     * Creation date: (01/02/2002 8.23.59)
     *
     * @param a char
     */

    public Trait(int id, double p1, double p2, double p3, double p4, double p5, double p6, double p7, double p8, double p9) {

        params = new double[Neat.p_num_trait_params];

        trait_id = id;

        params[0] = p1;
        params[1] = p2;
        params[2] = p3;
        params[3] = p4;
        params[4] = p5;
        params[5] = p6;
        params[6] = p7;
        params[7] = 0;
    }

    public void print_to_file(IOseq xFile) {
        StringBuffer s2 = new StringBuffer("");

        s2.append("trait ");
        s2.append(trait_id + " ");

        for (int count = 0; count < Neat.p_num_trait_params; count++) {
            s2.append(params[count] + " ");
        }
        xFile.IOseqWrite(s2.toString());

    }
}


text:
var expect = require('chai').expect,
    sudokuFireStarter = require('../src/sudoku-firestarter'),
    utilities = require('../src/sudoku-utilities'),
    testData = require('../src/data');

describe('SudokuFirestarter', function () {
    describe('#solveSudoku()', function () {
        it('Sudoku data to be invalid', function () {
            expect(sudokuFireStarter.checkResult(testData.superHard())).to.be.false;
        });

        it('Sudoku result data to be valid', function () {
            expect(sudokuFireStarter.checkResult(testData.superHardSolved())).to.be.true;
        });

        it('Detects zero and duplicates', function () {
            expect(sudokuFireStarter.eachNumberExistsOnce([0, 2, 2])).to.be.false;
        });

        it('Solve Sudoku', function () {
            //   sudokuFireStarter.solveSudoku(testData.easy().input);
        });

    });

    describe('#possibleValuesForCell()', function () {
        it('Returns empty array when solved', function () {
            expect(sudokuFireStarter.possibleValuesForCell([[1]], 0, 0)).to.be.deep.equal([]);
        });
        it('Returns single value when only one value missing', function () {
            expect(sudokuFireStarter.possibleValuesForCell([[0, 1, 2], [4, 5, 6], [7, 8, 9]], 0, 0)).to.be.deep.equal([3]);
        });

        it('Returns multiple values', function () {
            expect(sudokuFireStarter.possibleValuesForCell(testData.easy().input, 1, 1)).to.be.deep.equal([3, 6]);
        });
        it('Returns missing value within center of 3rd quadrant', function () {
            expect(sudokuFireStarter.possibleValuesForCell(testData.easy().input, 1, 7)).to.be.deep.equal([6]);
        });
    });

    describe('#getExistingNumbersInRow()', function () {
        it('Returns the number that exists in 2nd row', function () {
            expect(sudokuFireStarter.getExistingNumbersInRow(testData.easy().input, 1)).to.deep.equal([8, 1, 7, 5, 4]);
        });
    });

    describe('#getExistingNumbersInQuadrant()', function () {
        it('Returns the number that exists in 1st quadrant', function () {
            expect(sudokuFireStarter.getExistingNumbersInQuadrant(testData.easy().input, 0, 0)).to.deep.equal([8, 1, 9, 4]);
        });

        it('Returns the number that exists in 2nd quadrant from column start', function () {
            expect(sudokuFireStarter.getExistingNumbersInQuadrant(testData.easy().input, 0, 3)).to.deep.equal([7, 1]);
        });

        it('Returns the number that exists in 2nd quadrant from column middle', function () {
            expect(sudokuFireStarter.getExistingNumbersInQuadrant(testData.easy().input, 0, 4)).to.deep.equal([7, 1]);
        });

        it('Returns the number that exists in 2nd quadrant from column end', function () {
            expect(sudokuFireStarter.getExistingNumbersInQuadrant(testData.easy().input, 0, 5)).to.deep.equal([7, 1]);
        });

        it('Returns the number that exists in 5th quadrant from row start', function () {
            expect(sudokuFireStarter.getExistingNumbersInQuadrant(testData.easy().input, 3, 4)).to.deep.equal([2, 4]);
        });

        it('Returns the number that exists in 5th quadrant from row middle', function () {
            expect(sudokuFireStarter.getExistingNumbersInQuadrant(testData.easy().input, 4, 4)).to.deep.equal([2, 4]);
        });
    });

    describe('#hasNumber()', function () {
        it('Returns false if row has no zeros', function () {
            expect(utilities.hasNumber([1, 2, 3], 0)).to.be.false;

        });

        it('Returns true if row has zeros', function () {
            expect(utilities.hasNumber([1, 0, 2], 0)).to.be.true;
        });
    });

    describe('#eachNumberExistsOnce()', function () {
        it('Each number exists once', function () {
            expect(sudokuFireStarter.eachNumberExistsOnce([1, 3, 2])).to.be.true;
        });

        it('Detects duplicate values', function () {
            expect(sudokuFireStarter.eachNumberExistsOnce([1, 2, 2])).to.be.false;
        });
    })
});