text:
package de.fesere.hypermedia.cj.model;

import org.junit.Assert;
import org.junit.Test;

import java.net.URI;
import java.util.Arrays;

import static de.fesere.hypermedia.cj.model.builder.DataEntryFactory.create;

public class CollectionSerializationTest extends SerializationTestBase {

    private static final URI TEST_COM = URI.create("http://writeToStringExample.com");

    @Test
    public void testPOJOtoJSON() {
        Collection collection = new Collection(TEST_COM);

        assertCollectionSerialization("{\"collection\":{\"href\":\"http://writeToStringExample.com\",\"version\":\"1.0\"}}", collection);
    }

    @Test
    public void testJSONtoPOJO() {
        String givenJson = "{\"collection\":{\"href\":\"http://writeToStringExample.com\",\"version\":\"1.0\"}}";

        Collection collection = serializer.deserialize(givenJson, Collection.class);

        Assert.assertEquals("1.0", collection.getVersion());
        Assert.assertEquals(TEST_COM, collection.getHref());
    }

    @Test
    public void serializeCollectionWithSingleItem() {
        Item item = new Item(URI.create("http://writeToStringExample.com/items/1"));
        Collection collection = new Collection(TEST_COM, Arrays.asList(item), null, null, null);

        assertCollectionSerialization("{\"collection\":{\"href\":\"http://writeToStringExample.com\",\"version\":\"1.0\",\"items\":[{\"href\":\"http://writeToStringExample.com/items/1\"}]}}", collection);
    }

    @Test
    public void serializeCollectionWithSingleItemWithData() {
        Item item = new Item(URI.create("http://writeToStringExample.com/items/1"));
        item.addData(create("foo", "bar"));

        Collection collection = new Collection(TEST_COM, Arrays.asList(item), null, null, null);

        assertCollectionSerialization("{\"collection\":{" +
                "\"href\":\"http://writeToStringExample.com\"," +
                "\"version\":\"1.0\"," +
                "\"items\":[" +
                "{\"href\":\"http://writeToStringExample.com/items/1\"," +
                "\"data\":[" +
                "{\"name\":\"foo\", \"value\":\"bar\"}" +
                "]" +
                "}" +
                "]" +
                "}" +
                "}", collection);
    }
}


text:
package de.spricom.dessert.modules.jdk;

import de.spricom.dessert.modules.core.FixedModule;
import de.spricom.dessert.slicing.Classpath;
import de.spricom.dessert.slicing.Slices;

/**
 * Generated by de.spricom.dessert.tools.GenerateStaticModulesTool.
 */
class CompilerModule extends FixedModule {

    CompilerModule(Classpath cp) {
        super("jdk.compiler", "17",
                Slices.of(
                        cp.slice("com.sun.source.doctree.*"),
                        cp.slice("com.sun.source.tree.*"),
                        cp.slice("com.sun.source.util.*"),
                        cp.slice("com.sun.tools.javac.*")
                ),
                Slices.of(
                        cp.slice("com.sun.source.doctree.*"),
                        cp.slice("com.sun.source.tree.*"),
                        cp.slice("com.sun.source.util.*"),
                        cp.slice("com.sun.tools.doclint.*"),
                        cp.slice("com.sun.tools.javac.*"),
                        cp.slice("com.sun.tools.javac.api.*"),
                        cp.slice("com.sun.tools.javac.code.*"),
                        cp.slice("com.sun.tools.javac.comp.*"),
                        cp.slice("com.sun.tools.javac.file.*"),
                        cp.slice("com.sun.tools.javac.jvm.*"),
                        cp.slice("com.sun.tools.javac.launcher.*"),
                        cp.slice("com.sun.tools.javac.main.*"),
                        cp.slice("com.sun.tools.javac.model.*"),
                        cp.slice("com.sun.tools.javac.parser.*"),
                        cp.slice("com.sun.tools.javac.platform.*"),
                        cp.slice("com.sun.tools.javac.processing.*"),
                        cp.slice("com.sun.tools.javac.resources.*"),
                        cp.slice("com.sun.tools.javac.tree.*"),
                        cp.slice("com.sun.tools.javac.util.*"),
                        cp.slice("com.sun.tools.sjavac.*"),
                        cp.slice("com.sun.tools.sjavac.client.*"),
                        cp.slice("com.sun.tools.sjavac.comp.*"),
                        cp.slice("com.sun.tools.sjavac.comp.dependencies.*"),
                        cp.slice("com.sun.tools.sjavac.options.*"),
                        cp.slice("com.sun.tools.sjavac.pubapi.*"),
                        cp.slice("com.sun.tools.sjavac.server.*"),
                        cp.slice("com.sun.tools.sjavac.server.log.*"),
                        cp.slice("jdk.internal.shellsupport.doc.*"),
                        cp.slice("jdk.internal.shellsupport.doc.resources.*"),
                        cp.slice("sun.tools.serialver.*"),
                        cp.slice("sun.tools.serialver.resources.*")
                ));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.codehaus.mojo.natives.it.linkages.win32</groupId>
    <artifactId>win32</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>ExeStatic</artifactId>

  <name>ExeStatic.exe</name>

  <packaging>exe</packaging>

  <dependencies>
    <dependency>
      <groupId>org.codehaus.mojo.natives.it.linkages.win32</groupId>
      <artifactId>SubFuncStatic</artifactId>
      <type>lib</type>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.mojo.natives.it.linkages.win32</groupId>
      <artifactId>SubFuncStatic</artifactId>
      <type>inczip</type>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.mojo.natives.it.linkages.win32</groupId>
      <artifactId>FuncStatic</artifactId>
      <type>lib</type>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.mojo.natives.it.linkages.win32</groupId>
      <artifactId>FuncStatic</artifactId>
      <type>inczip</type>
      <version>${project.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>native-maven-plugin</artifactId>
        <configuration>
          <compilerStartOptions>
            <compilerStartOption>${commonCompilerOptions}</compilerStartOption>
          </compilerStartOptions>

          <sources>
            <source>
              <directory>${native.source.dir}</directory>
              <includes>
                <include>**/hello.c</include>
              </includes>
            </source>

            <!--
              intentionally disable this to make sure inczip works
              <source>
                <directory>${native.source.dir}/include</directory>
              </source>
            -->

          </sources>

          <linkerStartOptions>
            <linkerStartOption></linkerStartOption>
          </linkerStartOptions>

          <!-- the is no need to setup the order of linking on windows -->
          <!-- it is just here for testing purpose -->
          <linkingOrderLibs>
            <linkingOrderLib>
              org.codehaus.mojo.natives.it.linkages.win32:SubFuncStatic
            </linkingOrderLib>
            <linkingOrderLib>
              org.codehaus.mojo.natives.it.linkages.win32:FuncStatic
            </linkingOrderLib>
          </linkingOrderLibs>

        </configuration>

      </plugin>

    </plugins>

  </build>

</project>


text:
![iReading_Logo](./Reading_Logo.png)

[![Build Status](https://travis-ci.org/attentiveness/reading.svg?branch=master)](https://travis-ci.org/attentiveness/reading)
[![Code Climate](https://codeclimate.com/github/attentiveness/reading/badges/gpa.svg)](https://codeclimate.com/github/attentiveness/reading)
[![Join the chat at https://gitter.im/attentiveness/reading](https://badges.gitter.im/attentiveness/reading.svg)](https://gitter.im/attentiveness/reading)
[![License Apache2.0](https://img.shields.io/hexpm/l/plug.svg)](https://raw.githubusercontent.com/attentiveness/reading/master/LICENSE)
[![GitHub release](https://img.shields.io/github/release/attentiveness/reading.svg?maxAge=2592000?style=flat-square)](https://github.com/attentiveness/reading/releases)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/attentiveness/reading/pulls)

iReading App Write In React-Native(Studying and Programing)

**Support: Android 4.1 (API 16)+   IOS(8.0+)**

> No Profit, No Advertisement, Only Feelings

## Screenshot

![iReading_Main](./screenshot/iReading_Main.png)
![iReading_Article](./screenshot/iReading_Article.png)
![iReading_Category](./screenshot/iReading_Category.png)
![iReading_IOS_Main](./screenshot/iReading_iOS_Main.png)
![iReading_IOS_Share](./screenshot/iReading_iOS_Share.png)

## Download

### β Version(master branch)

*Android:* [Download iReading](http://fir.im/w7gu)

### From Android Market(Old)

*360 Android Market:* [Download iReading](http://zhushou.360.cn/detail/index/soft_id/3217938?recrefer=SE_D_Reading)

*Wandou Labs:* [Download iReading](http://www.wandoujia.com/apps/com.reading)

### From App Store(Old)

[Download iReading](https://itunes.apple.com/cn/app/ireading/id1135411121?l=zh&ls=1&mt=8)

## Application Architecture

- [Microsoft Code Push](https://github.com/Microsoft/react-native-code-push) for dynamic update.
- [Redux](https://github.com/reactjs/redux) is a predictable state container for reading application, together with [React Native](https://github.com/facebook/react-native).
- [Redux-Saga](https://github.com/yelouafi/redux-saga/) is a library that aims to make side effects in reading application easier and better.
- [react-navigation](https://github.com/react-community/react-navigation) is an extensible yet easy-to-use navigation solution, can also be used across React and React Native projects allowing for a higher degree of shared code.
- [Jest](https://facebook.github.io/jest/) for testing [React Native](https://github.com/facebook/react-native) components and UT.
- [Eslint](https://github.com/eslint/eslint) is a tool for identifying and reporting on patterns found in reading application code.
- [react-native-exceptions-manager](https://github.com/Richard-Cao/react-native-exceptions-manager) for handling crashes in release version.

## Development Workflow

### Step One

```
yarn(or npm) install -g react-native-cli
```
### Step Two

```
yarn(or npm) install
```
### Step Three

```
react-native start
```
### Run Test

```
yarn(or npm) test
```

### Format Code

```
yarn(or npm run) format
```

### Run Lint

```
yarn(or npm run) lint
```

## Importance

[ShowAPI](https://www.showapi.com/api/lookPoint/582/2) was used by iReading from free to charge, so my key doesn't work. You could apply for a new key and replace in [UrlUtil.js](https://github.com/attentiveness/reading/blob/master/app/utils/UrlUtil.js), it will work properly.
Reference this issue: [Cannot convert undefined or null to object](https://github.com/attentiveness/reading/issues/127).
I apologize to inconvenience you.

## Release Note

[Reading Release Note](https://github.com/attentiveness/reading/releases)

## Contributing

**For more information about contributing PRs and issues, see our [Contribution Guidelines](https://github.com/attentiveness/reading/blob/master/CONTRIBUTING.md).**

## License

Apache License 2.0


text:
package org.apache.maven.plugin.ear.util;

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

import org.apache.maven.plugin.ear.EarModule;

/**
 * This class will check the list of modules if there exist a duplicate artifactId. If we have such case it's necessary
 * to create a warning to the user otherwise it can happen to overwrite existing artifacts during the EAR creation
 * process. This is a temporary solution to keep backward compatibility with previous versions. For the next major
 * release 3.X the creation of the EAR archive should be done based on unique identifiers like
 * {@code groupId:artifactId:version}.
 *
 * @author Karl Heinz Marbaise <khmarbaise@apache.org>
 */
public class ModuleIdentifierValidator
{

    private List<EarModule> earModules;

    private Map<String, List<EarModule>> result;

    /**
     * @param earModules The list of {@link EarModule} which will be checked.
     */
    public ModuleIdentifierValidator( List<EarModule> earModules )
    {
        if ( earModules == null )
        {
            throw new IllegalArgumentException( "Not allowed to give null for earModules." );
        }
        this.earModules = earModules;
        this.result = new HashMap<String, List<EarModule>>();
    }

    /**
     * You have to call {@link #checkForDuplicateArtifacts()} before
     * otherwise you will get always {@code false}.
     * @return true in case of existing duplicates false otherwise.
     */
    public boolean existDuplicateArtifacts()
    {
        return !result.isEmpty();
    }

    /**
     * Trigger the module list check.
     *
     * @return this for fluent usage.
     */
    public ModuleIdentifierValidator checkForDuplicateArtifacts()
    {
        analyze();
        return this;
    }

    private void analyze()
    {
        final Map<String, List<EarModule>> newList = new HashMap<String, List<EarModule>>();

        for ( EarModule earModule : earModules )
        {
            String earId = earModule.getArtifact().getArtifactId() + ":" + earModule.getArtifact().getVersion();

            if ( newList.containsKey( earId ) )
            {
                newList.get( earId ).add( earModule );
            }
            else
            {
                List<EarModule> list = new ArrayList<EarModule>();
                list.add( earModule );
                newList.put( earId, list );
            }
        }

        result.clear();
        for ( Map.Entry<String, List<EarModule>> item : newList.entrySet() )
        {
            if ( item.getValue().size() > 1 )
            {
                result.put( item.getKey(), item.getValue() );
            }
        }

    }

    /**
     * @return A map of duplicate artifacts.
     */
    public Map<String, List<EarModule>> getDuplicateArtifacts()
    {
        return result;
    }

    /**
     * @return The list of {@link EarModule}
     */
    public List<EarModule> getEarModules()
    {
        return earModules;
    }

    /**
     * @param paramEarModules {@link EarModule}
     * @return {@link ModuleIdentifierValidator}
     */
    public ModuleIdentifierValidator setEarModules( List<EarModule> paramEarModules )
    {
        if ( paramEarModules == null )
        {
            throw new IllegalArgumentException( "Not allowed to give null for earModules." );
        }
        this.earModules = paramEarModules;
        return this;
    }
}


text:
var assert = require('assert'),
    _ = require('lodash');

describe('Association Interface', function() {

  describe('Has Many Association', function() {
    describe('create nested associations()', function() {

      describe('with single level depth', function() {

        describe('and objects', function() {

          /////////////////////////////////////////////////////
          // TEST METHODS
          ////////////////////////////////////////////////////

          it('should create a new customer and payment association', function(done) {

            var data = {
              name: 'has many nested',
              payments: [
                { amount: 1 },
                { amount: 2 }
              ]
            };

            Associations.Customer.create(data).exec(function(err, values) {
              if(err) return done(err);

              // Look up the customer again to be sure the payments were added
              Associations.Customer.findOne(values.id)
              .populate('payments')
              .exec(function(err, model) {
                if(err) return done(err);
                assert(model.payments.length === 2);
                assert(model.payments[1].amount === 2);
                done();
              });

            });
          });
        });

        describe('and objects mixed with ids', function() {
          var pmtId;

          before(function(done) {
            Associations.Payment.create({ amount: 1 }).exec(function(err, payment) {
              if(err) return done(err);
              pmtId = payment.id;
              done();
            });
          });

          /////////////////////////////////////////////////////
          // TEST METHODS
          ////////////////////////////////////////////////////

          it('should create a new customer and payment association', function(done) {

            var data = {
              name: 'has many nested',
              payments: [
                pmtId,
                { amount: 2 }
              ]
            };

            Associations.Customer.create(data).exec(function(err, values) {
              assert(!err);

              // Look up the customer again to be sure the payments were added
              Associations.Customer.findOne(values.id)
              .populate('payments')
              .exec(function(err, model) {
                assert(!err);
                assert(model.payments.length === 2);
                assert(model.payments[1].amount === 2);
                done();
              });

            });
          });
        });

      });
    });
  });
});


text:
import vcAutocomplete from './Autocomplete'

export default vcAutocomplete
export { vcAutocomplete }


text:
using System;
using System.Linq;
using Newtonsoft.Json;

namespace TraktSharp.Entities {

	/// Describes whether a particular episode is completed in the context of a collection or watched history
	[Serializable]
	public class TraktEpisodeProgress {

		/// The episode number within the season to which it belongs
		[JsonProperty(PropertyName = "number")]
		public int? EpisodeNumber { get; set; }

		/// <c>true</c> if the episode is completed, otherwise <c>false</c>
		[JsonProperty(PropertyName = "completed")]
		public bool Completed { get; set; }

	}

}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEventsUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events_users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('event_id')->unsigned()->references('id')->on('events');
            $table->integer('user_id')->unsigned()->references('id')->on('users');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('events_users');
    }
}


text:
import json

from datetime import datetime
from moto.core import BaseBackend, BackendDict, BaseModel

from .exceptions import (
    InvalidResourceStateFault,
    ResourceAlreadyExistsFault,
    ResourceNotFoundFault,
)
from .utils import filter_tasks

class DatabaseMigrationServiceBackend(BaseBackend):
    def __init__(self, region_name, account_id):
        super().__init__(region_name, account_id)
        self.replication_tasks = {}

    @staticmethod
    def default_vpc_endpoint_service(service_region, zones):
        """Default VPC endpoint service."""
        return BaseBackend.default_vpc_endpoint_service_factory(
            service_region, zones, "dms"
        )

    def create_replication_task(
        self,
        replication_task_identifier,
        source_endpoint_arn,
        target_endpoint_arn,
        replication_instance_arn,
        migration_type,
        table_mappings,
        replication_task_settings,
    ):
        """
        The following parameters are not yet implemented:
        CDCStartTime, CDCStartPosition, CDCStopPosition, Tags, TaskData, ResourceIdentifier
        """
        replication_task = FakeReplicationTask(
            replication_task_identifier=replication_task_identifier,
            source_endpoint_arn=source_endpoint_arn,
            target_endpoint_arn=target_endpoint_arn,
            replication_instance_arn=replication_instance_arn,
            migration_type=migration_type,
            table_mappings=table_mappings,
            replication_task_settings=replication_task_settings,
            account_id=self.account_id,
            region_name=self.region_name,
        )

        if self.replication_tasks.get(replication_task.arn):
            raise ResourceAlreadyExistsFault(
                "The resource you are attempting to create already exists."
            )

        self.replication_tasks[replication_task.arn] = replication_task

        return replication_task

    def start_replication_task(self, replication_task_arn):
        """
        The following parameters have not yet been implemented:
        StartReplicationTaskType, CDCStartTime, CDCStartPosition, CDCStopPosition
        """
        if not self.replication_tasks.get(replication_task_arn):
            raise ResourceNotFoundFault("Replication task could not be found.")

        return self.replication_tasks[replication_task_arn].start()

    def stop_replication_task(self, replication_task_arn):
        if not self.replication_tasks.get(replication_task_arn):
            raise ResourceNotFoundFault("Replication task could not be found.")

        return self.replication_tasks[replication_task_arn].stop()

    def delete_replication_task(self, replication_task_arn):
        if not self.replication_tasks.get(replication_task_arn):
            raise ResourceNotFoundFault("Replication task could not be found.")

        task = self.replication_tasks[replication_task_arn]
        task.delete()
        self.replication_tasks.pop(replication_task_arn)

        return task

    def describe_replication_tasks(self, filters, max_records):
        """
        The parameter WithoutSettings has not yet been implemented
        """
        replication_tasks = filter_tasks(self.replication_tasks.values(), filters)

        if max_records and max_records > 0:
            replication_tasks = replication_tasks[:max_records]

        return replication_tasks

class FakeReplicationTask(BaseModel):
    def __init__(
        self,
        replication_task_identifier,
        migration_type,
        replication_instance_arn,
        source_endpoint_arn,
        target_endpoint_arn,
        table_mappings,
        replication_task_settings,
        account_id,
        region_name,
    ):
        self.id = replication_task_identifier
        self.region = region_name
        self.migration_type = migration_type
        self.replication_instance_arn = replication_instance_arn
        self.source_endpoint_arn = source_endpoint_arn
        self.target_endpoint_arn = target_endpoint_arn
        self.table_mappings = table_mappings
        self.replication_task_settings = replication_task_settings

        self.arn = f"arn:aws:dms:{region_name}:{account_id}:task:{self.id}"
        self.status = "creating"

        self.creation_date = datetime.utcnow()
        self.start_date = None
        self.stop_date = None

    def to_dict(self):
        start_date = self.start_date.isoformat() if self.start_date else None
        stop_date = self.stop_date.isoformat() if self.stop_date else None

        return {
            "ReplicationTaskIdentifier": self.id,
            "SourceEndpointArn": self.source_endpoint_arn,
            "TargetEndpointArn": self.target_endpoint_arn,
            "ReplicationInstanceArn": self.replication_instance_arn,
            "MigrationType": self.migration_type,
            "TableMappings": json.dumps(self.table_mappings),
            "ReplicationTaskSettings": json.dumps(self.replication_task_settings),
            "Status": self.status,
            "ReplicationTaskCreationDate": self.creation_date.isoformat(),
            "ReplicationTaskStartDate": start_date,
            "ReplicationTaskArn": self.arn,
            "ReplicationTaskStats": {
                "FullLoadProgressPercent": 100,
                "ElapsedTimeMillis": 100,
                "TablesLoaded": 1,
                "TablesLoading": 0,
                "TablesQueued": 0,
                "TablesErrored": 0,
                "FreshStartDate": start_date,
                "StartDate": start_date,
                "StopDate": stop_date,
                "FullLoadStartDate": start_date,
                "FullLoadFinishDate": stop_date,
            },
        }

    def ready(self):
        self.status = "ready"
        return self

    def start(self):
        self.status = "starting"
        self.start_date = datetime.utcnow()
        self.run()
        return self

    def stop(self):
        if self.status != "running":
            raise InvalidResourceStateFault("Replication task is not running")

        self.status = "stopped"
        self.stop_date = datetime.utcnow()
        return self

    def delete(self):
        self.status = "deleting"
        return self

    def run(self):
        self.status = "running"
        return self

dms_backends = BackendDict(DatabaseMigrationServiceBackend, "dms")


text:
var namespaceorg_1_1onosproject_1_1bgprouter =
[
    [ "BgpRouter", "classorg_1_1onosproject_1_1bgprouter_1_1BgpRouter.html", "classorg_1_1onosproject_1_1bgprouter_1_1BgpRouter" ],
    [ "IcmpHandler", "classorg_1_1onosproject_1_1bgprouter_1_1IcmpHandler.html", "classorg_1_1onosproject_1_1bgprouter_1_1IcmpHandler" ],
    [ "NextHop", "classorg_1_1onosproject_1_1bgprouter_1_1NextHop.html", "classorg_1_1onosproject_1_1bgprouter_1_1NextHop" ],
    [ "NextHopGroupKey", "classorg_1_1onosproject_1_1bgprouter_1_1NextHopGroupKey.html", "classorg_1_1onosproject_1_1bgprouter_1_1NextHopGroupKey" ],
    [ "TunnellingConnectivityManager", "classorg_1_1onosproject_1_1bgprouter_1_1TunnellingConnectivityManager.html", "classorg_1_1onosproject_1_1bgprouter_1_1TunnellingConnectivityManager" ]
];


text:
package org.apache.hadoop.fs.shell.find;

import static org.junit.Assert.*;
import static org.apache.hadoop.fs.shell.find.TestHelper.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.shell.PathData;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.junit.Test;

public class TestName {
  private FileSystem mockFs;
  private Name name;

  @Rule
  public Timeout globalTimeout = new Timeout(10000, TimeUnit.MILLISECONDS);

  @Before
  public void resetMock() throws IOException {
    mockFs = MockFileSystem.setup();
  }

  private void setup(String arg) throws IOException {
    name = new Name();
    addArgument(name, arg);
    name.setOptions(new FindOptions());
    name.prepare();
  }

  // test a matching name
  @Test
  public void applyMatch() throws IOException {
    setup("name");
    PathData item = new PathData("/directory/path/name", mockFs.getConf());
    assertEquals(Result.PASS, name.apply(item, -1));
  }

  // test a non-matching name
  @Test
  public void applyNotMatch() throws IOException {
    setup("name");
    PathData item = new PathData("/directory/path/notname", mockFs.getConf());
    assertEquals(Result.FAIL, name.apply(item, -1));
  }

  // test a different case name
  @Test
  public void applyMixedCase() throws IOException {
    setup("name");
    PathData item = new PathData("/directory/path/NaMe", mockFs.getConf());
    assertEquals(Result.FAIL, name.apply(item, -1));
  }

  // test a matching glob pattern
  @Test
  public void applyGlob() throws IOException {
    setup("n*e");
    PathData item = new PathData("/directory/path/name", mockFs.getConf());
    assertEquals(Result.PASS, name.apply(item, -1));
  }

  // test a glob pattern with different case
  @Test
  public void applyGlobMixedCase() throws IOException {
    setup("n*e");
    PathData item = new PathData("/directory/path/NaMe", mockFs.getConf());
    assertEquals(Result.FAIL, name.apply(item, -1));
  }

  // test a non-matching glob pattern
  @Test
  public void applyGlobNotMatch() throws IOException {
    setup("n*e");
    PathData item = new PathData("/directory/path/notmatch", mockFs.getConf());
    assertEquals(Result.FAIL, name.apply(item, -1));
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Add" android:id="@+id/add_item" app:showAsAction="always"
          android:icon="@drawable/recycler_view_stick_header_ic_action_content_new"/>
    <item android:title="Github" android:id="@+id/github" />
</menu>


text:
package com.intellij.psi.impl.compiled;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.impl.InheritanceImplUtil;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.PsiSuperMethodImplUtil;
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
import com.intellij.psi.impl.java.stubs.PsiTypeParameterStub;
import com.intellij.psi.impl.light.LightEmptyImplementsList;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.Collection;
import java.util.List;

/**
 * @author max
 */
public class ClsTypeParameterImpl extends ClsRepositoryPsiElement<PsiTypeParameterStub> implements PsiTypeParameter {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.compiled.ClsTypeParameterImpl");
  static final ClsTypeParameterImpl[] EMPTY_ARRAY = new ClsTypeParameterImpl[0];
  private final LightEmptyImplementsList myLightEmptyImplementsList;

  public ClsTypeParameterImpl(final PsiTypeParameterStub stub) {
    super(stub);
    myLightEmptyImplementsList = new LightEmptyImplementsList(getManager());
  }

  public String getQualifiedName() {
    return null;
  }

  public boolean isInterface() {
    return false;
  }

  public boolean isAnnotationType() {
    return false;
  }

  public boolean isEnum() {
    return false;
  }

  @NotNull
  public PsiField[] getFields() {
    return PsiField.EMPTY_ARRAY;
  }

  @NotNull
  public PsiMethod[] getMethods() {
    return PsiMethod.EMPTY_ARRAY;
  }

  public PsiMethod findMethodBySignature(PsiMethod patternMethod, boolean checkBases) {
    return PsiClassImplUtil.findMethodBySignature(this, patternMethod, checkBases);
  }

  @NotNull
  public PsiMethod[] findMethodsBySignature(PsiMethod patternMethod, boolean checkBases) {
    return PsiClassImplUtil.findMethodsBySignature(this, patternMethod, checkBases);
  }

  public PsiField findFieldByName(String name, boolean checkBases) {
    return PsiClassImplUtil.findFieldByName(this, name, checkBases);
  }

  @NotNull
  public PsiMethod[] findMethodsByName(String name, boolean checkBases) {
    return PsiClassImplUtil.findMethodsByName(this, name, checkBases);
  }

  @NotNull
  public List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(String name, boolean checkBases) {
    return PsiClassImplUtil.findMethodsAndTheirSubstitutorsByName(this, name, checkBases);
  }

  @NotNull
  public List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors() {
    return PsiClassImplUtil.getAllWithSubstitutorsByMap(this, PsiMethod.class);
  }

  public PsiClass findInnerClassByName(String name, boolean checkBases) {
    return PsiClassImplUtil.findInnerByName(this, name, checkBases);
  }

  public PsiTypeParameterList getTypeParameterList() {
    return null;
  }

  public boolean hasTypeParameters() {
    return false;
  }

  // very special method!
  public PsiElement getScope() {
    return getParent().getParent();
  }

  public boolean isInheritorDeep(PsiClass baseClass, PsiClass classToByPass) {
    return InheritanceImplUtil.isInheritorDeep(this, baseClass, classToByPass);
  }

  public boolean isInheritor(@NotNull PsiClass baseClass, boolean checkDeep) {
    return InheritanceImplUtil.isInheritor(this, baseClass, checkDeep);
  }

  public PsiIdentifier getNameIdentifier() {
    return null;
  }

  public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) {
    return PsiClassImplUtil.processDeclarationsInClass(this, processor, state, null, lastParent, place, false);
  }

  public String getName() {
    return getStub().getName();
  }

  public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
    throw new IncorrectOperationException("Cannot change compiled classes");
  }

  @NotNull
  public PsiMethod[] getConstructors() {
    return PsiMethod.EMPTY_ARRAY;
  }

  public PsiDocComment getDocComment() {
    return null;
  }

  public boolean isDeprecated() {
    return false;
  }

  @NotNull
  public PsiReferenceList getExtendsList() {
    return getStub().findChildStubByType(JavaStubElementTypes.EXTENDS_BOUND_LIST).getPsi();
  }

  public PsiReferenceList getImplementsList() {
    return myLightEmptyImplementsList;
  }

  @NotNull
  public PsiClassType[] getExtendsListTypes() {
    return getExtendsList().getReferencedTypes();
  }

  @NotNull
  public PsiClassType[] getImplementsListTypes() {
    return PsiClassType.EMPTY_ARRAY;
  }

  @NotNull
  public PsiClass[] getInnerClasses() {
    return PsiClass.EMPTY_ARRAY;
  }

  @NotNull
  public PsiField[] getAllFields() {
    return PsiField.EMPTY_ARRAY;
  }

  @NotNull
  public PsiMethod[] getAllMethods() {
    return PsiMethod.EMPTY_ARRAY;
  }

  @NotNull
  public PsiClass[] getAllInnerClasses() {
    return PsiClass.EMPTY_ARRAY;
  }

  @NotNull
  public PsiClassInitializer[] getInitializers() {
    return PsiClassInitializer.EMPTY_ARRAY;
  }

  @NotNull
  public PsiTypeParameter[] getTypeParameters() {
    return PsiTypeParameter.EMPTY_ARRAY;
  }

  public PsiClass getSuperClass() {
    return PsiClassImplUtil.getSuperClass(this);
  }

  public PsiClass[] getInterfaces() {
    return PsiClassImplUtil.getInterfaces(this);
  }

  @NotNull
  public PsiClass[] getSupers() {
    return PsiClassImplUtil.getSupers(this);
  }

  @NotNull
  public PsiClassType[] getSuperTypes() {
    return PsiClassImplUtil.getSuperTypes(this);
  }

  public PsiClass getContainingClass() {
    return null;
  }

  @NotNull
  public Collection<HierarchicalMethodSignature> getVisibleSignatures() {
    return PsiSuperMethodImplUtil.getVisibleSignatures(this);
  }

  public PsiModifierList getModifierList() {
    return null;
  }

  public boolean hasModifierProperty(@NotNull String name) {
    return false;
  }

  public PsiJavaToken getLBrace() {
    return null;
  }

  public PsiJavaToken getRBrace() {
    return null;
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitTypeParameter(this);
    }
    else {
      visitor.visitElement(this);
    }
  }

  @NonNls
  public String toString() {
    return "PsiTypeParameter";
  }

  public void appendMirrorText(final int indentLevel, @NonNls final StringBuffer buffer) {
    buffer.append(getName());
    PsiJavaCodeReferenceElement[] bounds = getExtendsList().getReferenceElements();
    if (bounds.length > 0) {
      buffer.append(" extends ");
      for (int i = 0; i < bounds.length; i++) {
        PsiJavaCodeReferenceElement bound = bounds[i];
        if (i > 0) buffer.append(" & ");
        buffer.append(bound.getCanonicalText());
      }
    }
  }

  public void setMirror(@NotNull TreeElement element) {
    setMirrorCheckingType(element, null);

    PsiTypeParameter mirror = (PsiTypeParameter)SourceTreeToPsiMap.treeElementToPsi(element);
      ((ClsReferenceListImpl)getExtendsList()).setMirror((TreeElement)SourceTreeToPsiMap.psiElementToTree(mirror.getExtendsList()));
  }

  @NotNull
  public PsiElement[] getChildren() {
    return PsiElement.EMPTY_ARRAY;
  }

  public PsiTypeParameterListOwner getOwner() {
    return (PsiTypeParameterListOwner)getParent().getParent();
  }

  public int getIndex() {
    final PsiTypeParameterStub st = getStub();
    return st.getParentStub().getChildrenStubs().indexOf(st);
  }

  public PsiMetaData getMetaData() {
    return MetaRegistry.getMeta(this);
  }

  public Icon getElementIcon(final int flags) {
    return PsiClassImplUtil.getClassIcon(flags, this);
  }

  @Override
  public boolean isEquivalentTo(final PsiElement another) {
    return PsiClassImplUtil.isClassEquivalentTo(this, another);
  }

  @NotNull
  public SearchScope getUseScope() {
    return PsiClassImplUtil.getClassUseScope(this);
  }

  //todo parse annotataions
  @NotNull
  public PsiAnnotation[] getAnnotations() {
    return PsiAnnotation.EMPTY_ARRAY;
  }

  public PsiAnnotation findAnnotation(@NotNull @NonNls String qualifiedName) {
    return null;
  }

  @NotNull
  public PsiAnnotation addAnnotation(@NotNull @NonNls String qualifiedName) {
    throw new IncorrectOperationException();
  }
  @NotNull
  public PsiAnnotation[] getApplicableAnnotations() {
    return getAnnotations();
  }
}


text:
A basic Node.js tool designed for persistent finding and replacing based on misspellings and flagged characters/strings. Originally designed to handle u's and v's, and j's and i's being randomly swapped by typographers in Shakespeare's First Folio, Replcer.js will search through one or more text files and present the user with misspelled words that contain optional user specified targets such as 'u' an 'v'. **(NOTE: 0.1 is currently hard-coded to use u, v, j, and i, customizable flags are coming soon)**. The user can then specify a new spelling to swap in, which will automatically be applied in the future. Replacer.js will never ask you about the same word twice.

### Installing
Replacer.js requires Node.js and npm in order to run, so make sure you [install those first](https://docs.npmjs.com/getting-started/installing-node). Then download the zip, and install the dependent libraries, [readline-sync](https://github.com/anseki/readline-sync) and [spellchecker](https://github.com/atom/node-spellchecker), by going to the this project's root directory in the command line and typing:
```
npm install
```
Once the most recent versions of readline-sync and spellchecker are installed by npm, Replacer.js will be ready to use.

### License and Copyright
Standard [MIT License](https://github.com/delventhalz/replacer.js/blob/master/LICENSE.md) applies. If Replacer.js is useful to you, do what you like with it, but credit me and it's not my fault if it breaks.

### Using Replacer.js
From within the directory where you downloaded this repo, type the command:
```
node replacer
```
This will run the replacer with the default target text file, `target.txt`, and the `ignore.json` and `cipher.json` files located in the `words` directory.

You may specify different target files in the command line as arguments to the replacer command. For example:
```
node replacer macbeth.txt /tempest/act1.md
```
This will run the replacer on `macbeth.txt` and `/tempest/act1.md`.

You may also specify a different directory for `cipher.json` and `ignore.json` by using the `@` character. For example:
```
node replacer @ff
```
This will use `ignore.json` and `cipher.json` files stored in the `/ff` directory, creating them from scratch if necessary. **(NOTE: 0.1 does not currently support this @ argument, and will always default to the 'words' directory)**

You can mix and match these arguments however you like:
```
node replacer hamlet.md @ff /midsummer/act5.txt
```

### Default Commands
While running, Replacer.js will prompt the user with targeted words which it doesn't recognize. There are a few possible responses.

* If the user types in a replacement for the word, Replacer will make the switch, and remember it next time the word comes up.
* Alternatively, if the user simply presses enter without inputting any text, the word will be unchanged, and added to the ignore list.
* If the user inputs a backtick `` ` ``, the word will be skipped, but not added to the ignore list (useful for words that the user is unsure of).
* If the user inputs an asterisk ` * `, and custom shortcuts have been set (see below), then every possible replacement specified by those shortcuts will be executed.

### Custom Shortcuts
**(NOTE: In 0.1, custom shortcut functionality is hard-wired for u, v, i, j)**
Customs shortcuts are the key getting the most out of Replacer.js, greatly speeding up text processing. They serve a dual purpose. Shortcut keys form a watchlist, narrowing Replacer's prompts to misspelled words that contain items on the watchlist. Additionally, when prompted, the user is able to type in just the desired value for the shortcut to switch all instances to that value.

For example, with custom shortcuts of:

```
{
  "v": "u",
  "u": "v"
}
```

And text of:
```
I'ue vpturned vs!
```

With these prompts and responses:
```
I'ue? v
vpturned? u
```

The text will change to:
```
I've upturned vs!
```

Notice that to use a shortcut you type in the letter you wish targeted letters to *become*. Notice also, that in the case of `vpturned`, using the shortcut `u` affected only the v's in the word, *not* the u's. Finally, `vs` is in the american english dictionary, and so never generayes a prompt. In order to change `vs` to `us`, manually add `"vs": "us"` to `cipher.json`, and it will be swapped regardless of spelling.

In order to customize your shortcuts, simply modify the `shortcuts.json` file in same folder as the cipher and ignore files you are using. For example, adding a key value combo of `"i": "j"` will watch for misspelled words with an 'i', and allow the user to type `j` to replace replace all i's in a word with a 'j'.

### Using Replacer.js with Shakespeare's First Folio
The default cipher and ignore files included in this repo are designed specifically to make Shakespeare's First Folio more readable by switching u's, v's, j's, and i's appropriately. If that is your purpose in downloading Replacer.js, then it is rather simple to use. After installing:

1. Copy your chosen First Folio text to the clipboard. I prefer the formatting on the [University of Chicago's site](http://www.lib.uchicago.edu/efts/OTA-SHK/restricted/search.form.html).
2. Paste the text into `target.txt` or another text file you plan on using.
3. Run Replacer.js on your files (see above).
4. Respond to any user prompts.
5. That's it! Your text file(s) have been modified.

### Bugs and Typos
If you notice any bugs in the code, or typos in the included First Folio cipher and ignore files, please send as detailed a bug report (including the text being changed) to [delventhalz@gmail.com](mailto:delventhalz@gmail.com?subject=Replacer%20Bug%20Report).


text:
package com.rackspace.com.papi.components.checker.wadl

import com.rackspace.com.papi.components.checker.{LogAssertions, TestConfig}
import org.apache.logging.log4j.Level
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class WADLCheckerCompSpecSaxonEE extends BaseCheckerSpec with LogAssertions {
  //
  //  Register some common prefixes, you'll need the for XPath
  //  assertions.
  //
  register ("xsd", "http://www.w3.org/2001/XMLSchema")
  register ("wadl","http://wadl.dev.java.net/2009/02")
  register ("chk","http://www.rackspace.com/repose/wadl/checker")

  val creatorString = {
    val title = getClass.getPackage.getImplementationTitle
    val version = getClass.getPackage.getImplementationVersion
    s"$title ($version)"
  }

  val config = {
    val c = TestConfig()
    c.validateChecker = true
    c.xsdEngine="SaxonEE"
    c
  }

  //
  //  A simple checker that accepts a GET on /foo
  //
  val fooGETChecker =  <checker xmlns="http://www.rackspace.com/repose/wadl/checker">
                             <meta>
                                <built-by>Test</built-by>
                                <created-by>{creatorString}</created-by>
                                <created-on>2014-11-10T10:00:07.811-06:00</created-on>
                                {
                                  config.checkerMetaMap.map(c => <config option={c._1} value={c._2.toString} />)
                                }
                             </meta>
                             <step id="S0" type="START" next="F1 notFoo noMETHOD"/>
                             <step id="F1" type="URL" match="foo" next="G1 noURL notGET"/>
                             <step id="G1" type="METHOD" match="GET" label="GET Foo" next="A"/>
                             <step id="A" type="ACCEPT" priority="19999"/>
                             <step id="notFoo" type="URL_FAIL" notMatch="foo" />
                             <step id="notGET" type="METHOD_FAIL" notMatch="GET" />
                             <step id="noMETHOD" type="METHOD_FAIL" />
                             <step id="noURL" type="URL_FAIL" />
                         </checker>

  scenario ("Load a plain checker document that ends with .checker extension (check SaxonEE)") {
    Given("a plain checker document that ends in .checker")
    val in = ("foo.checker", fooGETChecker)
      When("the document is loaded...")
    val goodCheckerLog = log (Level.DEBUG) {
      val checker = builder.build (in,config)
      assert(checker, "/chk:checker/chk:step[@type='START']/@next = 'F1 notFoo noMETHOD'")
      assert(checker, "/chk:checker/chk:step[@type='URL']/@match = 'foo'")
      assert(checker, "/chk:checker/chk:step[@type='URL']/@next = 'G1 noURL notGET'")
      assert(checker, "/chk:checker/chk:step[@type='METHOD']/@next = 'A'")
      assert(checker, "/chk:checker/chk:step[@type='METHOD']/@match = 'GET'")
      assert(checker, "/chk:checker/chk:step[@type='ACCEPT']")
      assert(checker, "/chk:checker/chk:step[@type='URL_FAIL']/@notMatch='foo'")
      assert(checker, "/chk:checker/chk:step[@type='URL_FAIL' and not(@notMatch)]")
      assert(checker, "/chk:checker/chk:step[@type='METHOD_FAIL']/@notMatch='GET'")
      assert(checker, "/chk:checker/chk:step[@type='METHOD_FAIL' and not(@notMatch)]")
    }
    Then ("An appropriate DEBUG messages should be emmited.")
    assert(goodCheckerLog,"Using SaxonEE for checker validation")
  }
}


text:
import os
import subprocess

def discover_commit_hash(target):
    target = os.path.abspath(target)
    previous_directory = os.path.abspath(os.getcwd())

    os.chdir(target)

    cmd = 'git rev-parse --verify HEAD'

    output = ''

    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    for line in iter(proc.stdout.readline,''):
        output = line
        break

    if len(output) > 0 and output[-1] == '\n':
        output = output[:-1]

    os.chdir(previous_directory)

    return output


text:
<iterator-tree description="const-folded expr">
  <PromoteIterator type="xs:double">
    <SingletonIterator value="xs:integer(5000)"/>
  </PromoteIterator>
</iterator-tree>
<iterator-tree description="main query">
  <SequentialIterator>
    <CtxVarDeclareIterator varid="4" varname="input-context"/>
    <FLWORIterator>
      <LetVariable name="auction" materialize="true">
        <FnDocIterator>
          <PromoteIterator type="xs:string">
            <FnDataIterator>
              <CtxVarIterator varid="4" varname="input-context" varkind="global"/>
            </FnDataIterator>
          </PromoteIterator>
        </FnDocIterator>
      </LetVariable>
      <LetVariable name="$$opt_temp_0" materialize="true">
        <HoistIterator>
          <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,initial)" typename="*" nill-allowed="false">
            <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,open_auction)" typename="*" nill-allowed="false">
              <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,open_auctions)" typename="*" nill-allowed="false">
                <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,site)" typename="*" nill-allowed="false">
                  <LetVarIterator varname="auction"/>
                </ChildAxisIterator>
              </ChildAxisIterator>
            </ChildAxisIterator>
          </ChildAxisIterator>
        </HoistIterator>
      </LetVariable>
      <ForVariable name="p">
        <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,person)" typename="*" nill-allowed="false">
          <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,people)" typename="*" nill-allowed="false">
            <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,site)" typename="*" nill-allowed="false">
              <LetVarIterator varname="auction"/>
            </ChildAxisIterator>
          </ChildAxisIterator>
        </ChildAxisIterator>
      </ForVariable>
      <LetVariable name="$$opt_temp_1" materialize="true">
        <HoistIterator>
          <FnDataIterator>
            <AttributeAxisIterator test-kind="match_name_test" qname="xs:QName(,,income)" typename="*" nill-allowed="false">
              <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,profile)" typename="*" nill-allowed="false">
                <ForVarIterator varname="p"/>
              </ChildAxisIterator>
            </AttributeAxisIterator>
          </FnDataIterator>
        </HoistIterator>
      </LetVariable>
      <ReturnClause>
        <ElementIterator>
          <SingletonIterator value="xs:QName(,,items)"/>
          <AttributeIterator qname="xs:QName(,,name)">
            <EnclosedIterator attr_cont="true">
              <FnDataIterator>
                <ChildAxisIterator test-kind="match_text_test" qname="*" typename="*" nill-allowed="false">
                  <ChildAxisIterator test-kind="match_name_test" qname="xs:QName(,,name)" typename="*" nill-allowed="false">
                    <ForVarIterator varname="p"/>
                  </ChildAxisIterator>
                </ChildAxisIterator>
              </FnDataIterator>
            </EnclosedIterator>
          </AttributeIterator>
          <EnclosedIterator attr_cont="false">
            <FnCountIterator>
              <FLWORIterator>
                <ForVariable name="i">
                  <UnhoistIterator>
                    <LetVarIterator varname="$$opt_temp_0"/>
                  </UnhoistIterator>
                </ForVariable>
                <WhereClause>
                  <CompareIterator>
                    <UnhoistIterator>
                      <LetVarIterator varname="$$opt_temp_1"/>
                    </UnhoistIterator>
                    <SpecificNumArithIterator_MultiplyOperation_DOUBLE>
                      <SingletonIterator value="xs:double(5000)"/>
                      <PromoteIterator type="xs:double">
                        <FnDataIterator>
                          <FnExactlyOneIterator>
                            <ChildAxisIterator test-kind="match_text_test" qname="*" typename="*" nill-allowed="false">
                              <ForVarIterator varname="i"/>
                            </ChildAxisIterator>
                          </FnExactlyOneIterator>
                        </FnDataIterator>
                      </PromoteIterator>
                    </SpecificNumArithIterator_MultiplyOperation_DOUBLE>
                  </CompareIterator>
                </WhereClause>
                <ReturnClause>
                  <ForVarIterator varname="i"/>
                </ReturnClause>
              </FLWORIterator>
            </FnCountIterator>
          </EnclosedIterator>
        </ElementIterator>
      </ReturnClause>
    </FLWORIterator>
  </SequentialIterator>
</iterator-tree>


text:
wchar_t* get_string(const wchar_t* path, uint64_t offset, uint32_t size, CTextViewer::type_t type, bool replace_terminator)
{
	handle_wrapper hFile(INVALID_HANDLE_VALUE);
	hFile = ::CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile.isErr()) {
		::AfxGetMainWnd()->MessageBox(_T("File Open Error."), nullptr, MB_ICONWARNING);
		return nullptr;
	}

	handle_wrapper hMap(NULL);
	hMap = ::CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
	if (hMap.isErr()) {
		::AfxGetMainWnd()->MessageBox(_T("File Mapping Error."), nullptr, MB_ICONWARNING);
		return nullptr;
	}

	LPVOID pFile = ::MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
	if (pFile == NULL) {
		::AfxGetMainWnd()->MessageBox(_T("File Mapping Error."), nullptr, MB_ICONWARNING);
		return nullptr;
	}
	char* src = reinterpret_cast<char*>(pFile) + offset;

	wchar_t* buf = nullptr;
	rsize_t leng = 0;
	switch (type)
	{
	case CTextViewer::utf16:
		leng = size;
		buf = (wchar_t*)calloc(leng + 1, sizeof(wchar_t));
		if (buf)
		{
			memcpy(buf, src, leng);
		}
		break;

	default:
		UINT codepage = CP_ACP;
		switch (type)
		{
		case CTextViewer::ascii:
			codepage = CP_ACP;
			break;
		case CTextViewer::latin1:
			codepage = agalia::CP_LATIN1;
			break;
		case CTextViewer::utf8:
			codepage = CP_UTF8;
			break;
		case CTextViewer::jis:
			codepage = agalia::CP_JIS;
			break;
		}
		leng = ::MultiByteToWideChar(codepage, 0, (char*)src, size, nullptr, 0);
		buf = (wchar_t*)calloc(leng + 1, sizeof(wchar_t));
		if (buf)
		{
			::MultiByteToWideChar(codepage, 0, (char*)src, size, buf, (int)leng);
		}
	}

	if (buf)
	{
		if (replace_terminator) {
			for (rsize_t i = 0; i < (leng + 1) - 1; i++) {
				if (buf[i] == L'\0') {
					buf[i] = L' ';
				}
			}
		}
	}

	::UnmapViewOfFile(pFile);

	return buf;
}

void create_edit(CEdit& edit, CWnd* parent, bool wrap)
{
	// "ǂݍž'ݍς݂ł 'ê'Έê"x"jŠü'·'é
	if (::IsWindow(edit.GetSafeHwnd())) {
		edit.DestroyWindow();
	}

	// eƒEƒBƒ"ƒhƒEiƒ'[ƒhƒŒƒXƒ_ƒCƒAƒƒOj'̃Nƒ‰ƒCƒAƒ"ƒg—̈æ'̃TƒCƒY'ðŽæ"¾
	CRect rc;
	parent->GetClientRect(&rc);

	// ƒGƒfƒBƒbƒgƒ{ƒbƒNƒX'ð\'z
	edit.Create(
		WS_CHILD | WS_VISIBLE |
		WS_BORDER |
		ES_MULTILINE |
		ES_READONLY |
		WS_VSCROLL | ES_AUTOVSCROLL |
		(wrap ? 0 : (WS_HSCROLL | ES_AUTOHSCROLL)),
		rc, parent, 0);

	// OS'©'çƒtƒHƒ"ƒgî•ñ'ðŽæ"¾
	NONCLIENTMETRICS ncm = {};
	ncm.cbSize = sizeof(ncm);
	::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0);

	// ƒtƒHƒ"ƒg'ðì¬'µ'ăGƒfƒBƒbƒgƒ{ƒbƒNƒX'É"K—p
	CFont font;
	font.CreateFontIndirect(&ncm.lfMessageFont);
	edit.SetFont(&font);
	font.Detach();

	edit.SetFocus();
}

// CTextViewer

IMPLEMENT_DYNAMIC(CTextViewer, CWnd)

CTextViewer::CTextViewer()
{
	offset = 0;
	size = 0;
	type = ascii;
	replace_terminator = false;
}

CTextViewer::~CTextViewer()
{
}

BEGIN_MESSAGE_MAP(CTextViewer, CWnd)
	ON_WM_SIZE()
	ON_WM_CREATE()
	ON_WM_INITMENUPOPUP()
	ON_COMMAND(IDM_WRAP, &CTextViewer::OnWrap)
	ON_COMMAND(ID_FILE_CLOSE, &CTextViewer::OnFileClose)
	ON_COMMAND(IDM_REPLACE_TERMINATOR, &CTextViewer::OnReplaceTerminator)
	ON_COMMAND(ID_EDIT_COPY, &CTextViewer::OnEditCopy)
	ON_COMMAND(ID_EDIT_SELECT_ALL, &CTextViewer::OnSelectAll)
	ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, &CTextViewer::OnUpdateEditCopy)
	ON_UPDATE_COMMAND_UI(IDM_REPLACE_TERMINATOR, &CTextViewer::OnUpdateReplaceTerminator)
	ON_UPDATE_COMMAND_UI(IDM_WRAP, &CTextViewer::OnUpdateWrap)
END_MESSAGE_MAP()

// CTextViewer message handlers

void CTextViewer::CreateViewer(LPARAM lParam, type_t type)
{
	auto param = reinterpret_cast<agaliaItem*>(lParam);

	uint64_t offset = 0;
	param->getValueAreaOffset(&offset);

	uint64_t raw_size = 0;
	param->getValueAreaSize(&raw_size);
	uint32_t size = 0;
	auto hr = UInt64ToUInt32(raw_size, &size);
	if (FAILED(hr)) return;

	const agaliaContainer* image = nullptr;
	hr = param->getAsocImage(&image);
	if (FAILED(hr)) return;
	agaliaStringPtr path;
	hr = image->getFilePath(&path);
	if (FAILED(hr)) return;

	TCHAR sz[1024] = {};
	_stprintf_s(sz, _T("%s %I64u-%u"), ::PathFindFileName(path), offset, size);

	wchar_t* buf = get_string(path, offset, size, type, false);
	if (buf == nullptr)
	{
		return;
	}

	CRect rcParent;
	::AfxGetMainWnd()->GetWindowRect(&rcParent);

	CRect rcWindow(0, 0, 640, 480);
	rcWindow.OffsetRect(
		rcParent.left + (rcParent.Width() - rcWindow.Width()) / 2,
		rcParent.top + (rcParent.Height() - rcWindow.Height()) / 2);

	CTextViewer* pViewer = new CTextViewer;
	pViewer->path = path;
	pViewer->offset = offset;
	pViewer->size = size;
	pViewer->type = type;
	pViewer->CreateEx(
		0,
		::AfxRegisterWndClass(
			CS_VREDRAW | CS_HREDRAW,
			::LoadCursor(NULL, IDC_ARROW),
			0,
			::LoadIcon(::GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_MAINFRAME))),
		sz,
		WS_OVERLAPPEDWINDOW | WS_VISIBLE,
		rcWindow,
		::AfxGetMainWnd(),
		0);
	pViewer->m_child.SetWindowText(buf);

	free(buf);
}

void CTextViewer::PostNcDestroy()
{
	CWnd::PostNcDestroy();
	delete this;
}

// WM_CREATE message handler
int CTextViewer::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	CMenu popupEdit;
	popupEdit.CreateMenu();
	popupEdit.AppendMenu(MF_STRING, ID_EDIT_SELECT_ALL, L"Select &All	Ctrl+A");
	popupEdit.AppendMenu(MF_STRING, ID_EDIT_COPY, L"&Copy	Ctrl+C");

	CMenu popupFormat;
	popupFormat.CreateMenu();
	popupFormat.AppendMenu(MF_STRING, IDM_WRAP, L"&Wrap");
	popupFormat.AppendMenu(MF_STRING, IDM_REPLACE_TERMINATOR, L"&Replace Terminator");

	CMenu menu;
	menu.CreateMenu();
	menu.AppendMenu(MF_STRING, ID_FILE_CLOSE, L"E&xit");
	menu.AppendMenu(MF_POPUP, (UINT_PTR)popupEdit.GetSafeHmenu(), L"&Edit");
	menu.AppendMenu(MF_POPUP, (UINT_PTR)popupFormat.GetSafeHmenu(), L"F&ormat");
	SetMenu(&menu);

	menu.Detach();
	popupFormat.Detach();
	popupEdit.Detach();

	create_edit(m_child, this, false);

	return 0;
}

// WM_SIZE message handler
void CTextViewer::OnSize(UINT nType, int cx, int cy)
{
	CWnd::OnSize(nType, cx, cy);
	if (m_child.GetSafeHwnd())
	{
		CRect rcClient;
		GetClientRect(&rcClient);
		m_child.MoveWindow(rcClient);
	}
}

// WM_INITMENUPOPUP message handler
void CTextViewer::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
	::OnInitMenuPopup(this, pPopupMenu, nIndex, bSysMenu);
}

void CTextViewer::OnUpdateEditCopy(CCmdUI* pCmdUI)
{
	int nStartChar = 0;
	int nEndChar = 0;
	m_child.GetSel(nStartChar, nEndChar);

	pCmdUI->Enable(nStartChar != nEndChar);
}

void CTextViewer::OnUpdateWrap(CCmdUI* pCmdUI)
{
	pCmdUI->SetCheck(!(m_child.GetStyle() & ES_AUTOHSCROLL));
}

void CTextViewer::OnUpdateReplaceTerminator(CCmdUI* pCmdUI)
{
	pCmdUI->SetCheck(replace_terminator);
}

void CTextViewer::OnFileClose()
{
	DestroyWindow();
}

void CTextViewer::OnEditCopy()
{
	m_child.Copy();
}

void CTextViewer::OnSelectAll()
{
	m_child.SetSel(0, -1);
}

// IDM_WRAP command message handler
void CTextViewer::OnWrap()
{
	DWORD style = m_child.GetStyle();
	bool wrap = (style & ES_AUTOHSCROLL) == 0;
	create_edit(m_child, this, !wrap);

	wchar_t* buf = get_string(path.c_str(), offset, size, type, replace_terminator);
	m_child.SetWindowText(buf);
	free(buf);
}

// IDM_REPLACE_TERMINATOR command message handler
void CTextViewer::OnReplaceTerminator()
{
	replace_terminator = !replace_terminator;

	wchar_t* buf = get_string(path.c_str(), offset, size, type, replace_terminator);
	m_child.SetWindowText(buf);
	free(buf);
}


text:
// standard
#include <memory>  // std::unique_ptr
#include <utility> // std::swap
#include <vector>

// server
#include <server/ConnectionToClient.hpp>

// self
#include <server/Connections.h>

using namespace std;

class Connections::Impl {
public:
  Impl() = default;
  ~Impl() = default;

  ConnectionToClient &insert(unique_ptr<ConnectionToClient> connection);
  void erase(ConnectionToClient &connection);
  void for_each(function<void(ConnectionToClient &)> f);
  void handle_erase(function<void(ConnectionToClient &)> f);

private:
  bool isToBeCleared(ConnectionToClient const &connection) const;
  vector<unique_ptr<ConnectionToClient>> connections;
  vector<ConnectionToClient *> connectionsToClear;
};

ConnectionToClient &
Connections::Impl::insert(unique_ptr<ConnectionToClient> connection) {
  ConnectionToClient *con = connection.get();
  connections.push_back(move(connection));
  return *con;
}

bool Connections::Impl::isToBeCleared(
    ConnectionToClient const &connection) const {
  return find(connectionsToClear.begin(), connectionsToClear.end(),
              &connection) != connectionsToClear.end();
}

void Connections::Impl::erase(ConnectionToClient &connection) {
  if (!isToBeCleared(connection))
    connectionsToClear.push_back(&connection);
}

void Connections::Impl::for_each(function<void(ConnectionToClient &)> f) {
  for (unique_ptr<ConnectionToClient> const &conn : connections) {
    // This is not needed in the time of writing,
    // but it might be useful later
    if (isToBeCleared(*conn))
      continue;

    f(*conn);
  }
}

/*
 * If the callback does not throw, then this does not throw, either.
 * Otherwise it provides normal exception guarantee.
 */
void Connections::Impl::handle_erase(function<void(ConnectionToClient &)> f) {

  auto end = connectionsToClear.end();
  for (auto it = connectionsToClear.begin(); it != end; ++it) {
    ConnectionToClient *toClear = *it;
    connectionsToClear.erase(it);

    // Find the unique pointer
    auto found = find_if(connections.begin(), connections.end(),
                         [&](auto const &u) { return u.get() == toClear; });
    assert(found != connections.end());

    unique_ptr<ConnectionToClient> connection;
    connection.swap(*found);
    connections.erase(found);

    // Until now, no exception could occur.
    // Now it can, but we do not mind it.
    f(*toClear);
  }
}

/*************************************
 * pImpl outer
 */

Connections::Connections() { pImpl = make_unique<Impl>(); }

Connections::~Connections() = default;

ConnectionToClient &
Connections::insert(unique_ptr<ConnectionToClient> connection) {
  return pImpl->insert(move(connection));
}

void Connections::erase(ConnectionToClient &connection) {
  return pImpl->erase(connection);
}

void Connections::for_each(function<void(ConnectionToClient &)> f) {
  return pImpl->for_each(move(f));
}

void Connections::handle_erase(function<void(ConnectionToClient &)> f) {
  return pImpl->handle_erase(move(f));
}


text:
import React from 'react';
import { Fade, Collapse } from '@material-ui/core';
import A from 'components/A';
import Title from 'components/Title';
import icons from 'assets';
import style from './style';
import { usePortfolioDispatch, usePortfolioState } from '../usePortfolio';

function DetailTitleWithNav({ name, totalPortfolios }: { name: string; totalPortfolios: number }) {
  const { selected } = usePortfolioState();
  const dispatch = usePortfolioDispatch();
  const prev = () => dispatch({ type: 'prev' });
  const next = () => dispatch({ type: 'next' });
  return (

      <Fade in={selected !== 0}>
        <button onClick={prev} style={style.arrow}>

{'<'}

        </button>
      </Fade>
      <Title style={style.title}>{name}</Title>
      <Fade in={selected !== totalPortfolios}>
        <button onClick={next} style={style.arrow}>

{'>'}

        </button>
      </Fade>

  );
}

export default function Detail() {
  const { selected, portfolios, current } = usePortfolioState();
  const dispatch = usePortfolioDispatch();
  const close = () => dispatch({ type: 'close' });
  return current ? (
    <Collapse in={selected !== -1} style={style.container}>

        <DetailTitleWithNav
          name={current.fromGit.name.replace(/-/g, ' ')}
          totalPortfolios={portfolios ? portfolios.length - 1 : 0}
        />
        {current.image && }
        {current.extraContent.about.map((element: string, i: number) => (

{element}

        ))}

Language: {current.fromGit.language}

        {current.fromGit.homepage && (

            View in action on Github pages

        )}

            View the code on Github

        <button onClick={close} style={{ ...style.arrow, fontSize: 14 }}>

Close

        </button>

    </Collapse>
  ) : (
    <></>
  );
}


text:
package com.github.rockjam.iqnotes.http

import com.typesafe.config.Config

import scala.util.Try

object HttpConfig {
  def load(config: Config): Try[HttpConfig] = Try {
    val c = config.getConfig("iqnotes.http")
    HttpConfig(c.getString("interface"), c.getInt("port"))
  }
}

final case class HttpConfig(interface: String, port: Int)


text:
package psychicnova.utils;

import net.minecraft.block.Block;
import net.minecraft.item.Item;

/**
 * Useful utilities for handling blocks
 */
public class BlockUtils {
    /** Returns true if the block is an item. */
    public static final boolean isBlockItem(Item expected, Block actual) {
        return expected.getUnlocalizedName().equals(actual.getUnlocalizedName());
    }
}


text:
A memoization library that only caches the result of the most recent arguments.

[![npm](https://img.shields.io/npm/v/memoize-one.svg)](https://www.npmjs.com/package/memoize-one)
![types](https://img.shields.io/badge/types-typescript%20%7C%20flow-blueviolet)
[![minzip](https://img.shields.io/bundlephobia/minzip/memoize-one.svg)](https://www.npmjs.com/package/memoize-one)
[![Downloads per month](https://img.shields.io/npm/dm/memoize-one.svg)](https://www.npmjs.com/package/memoize-one)

## Rationale

Unlike other memoization libraries, `memoize-one` only remembers the latest arguments and result. No need to worry about cache busting mechanisms such as `maxAge`, `maxSize`, `exclusions` and so on, which can be prone to memory leaks. A function memoized with `memoize-one` simply remembers the last arguments, and if the memoized function is next called with the same arguments then it returns the previous result.

> For working with promises, [@Kikobeats](https://github.com/Kikobeats) has built [async-memoize-one](https://github.com/microlinkhq/async-memoize-one).

## Usage

```js
// memoize-one uses the default import
import memoizeOne from 'memoize-one';

function add(a, b) {
  return a + b;
}
const memoizedAdd = memoizeOne(add);

memoizedAdd(1, 2);
// add function: is called
// [new value returned: 3]

memoizedAdd(1, 2);
// add function: not called
// [cached result is returned: 3]

memoizedAdd(2, 3);
// add function: is called
// [new value returned: 5]

memoizedAdd(2, 3);
// add function: not called
// [cached result is returned: 5]

memoizedAdd(1, 2);
// add function: is called
// [new value returned: 3]
// 👇
// While the result of `add(1, 2)` was previously cached
// `(1, 2)` was not the *latest* arguments (the last call was `(2, 3)`)
// so the previous cached result of `(1, 3)` was lost
```

## Installation

```bash
# yarn
yarn add memoize-one

# npm
npm install memoize-one --save
```

## Function argument equality

By default, we apply our own _fast_ and _relatively naive_ equality function to determine whether the arguments provided to your function are equal. You can see the full code here: [are-inputs-equal.ts](https://github.com/alexreardon/memoize-one/blob/master/src/are-inputs-equal.ts).

(By default) function arguments are considered equal if:

1. there is same amount of arguments
2. each new argument has strict equality (`===`) with the previous argument
3. **[special case]** if two arguments are not `===` and they are both `NaN` then the two arguments are treated as equal

What this looks like in practice:

```js
import memoizeOne from 'memoize-one';

// add all numbers provided to the function
const add = (...args = []) =>
  args.reduce((current, value) => {
    return current + value;
  }, 0);
const memoizedAdd = memoizeOne(add);
```

> 1. there is same amount of arguments

```js
memoizedAdd(1, 2);
// the amount of arguments has changed, so add function is called
memoizedAdd(1, 2, 3);
```

> 2. new arguments have strict equality (`===`) with the previous argument

```js
memoizedAdd(1, 2);
// each argument is `===` to the last argument, so cache is used
memoizedAdd(1, 2);
// second argument has changed, so add function is called again
memoizedAdd(1, 3);
// the first value is not `===` to the previous first value (1 !== 3)
// so add function is called again
memoizedAdd(3, 1);
```

> 3. **[special case]** if the arguments are not `===` and they are both `NaN` then the argument is treated as equal

```js
memoizedAdd(NaN);
// Even though NaN !== NaN these arguments are
// treated as equal as they are both `NaN`
memoizedAdd(NaN);
```

## Custom equality function

You can also pass in a custom function for checking the equality of two sets of arguments

```js
const memoized = memoizeOne(fn, isEqual);
```

An equality function should return `true` if the arguments are equal. If `true` is returned then the wrapped function will not be called.

**Tip**: A custom equality function needs to compare `Arrays`. The `newArgs` array will be a new reference every time so a simple `newArgs === lastArgs` will always return `false`.

Equality functions are not called if the `this` context of the function has changed (see below).

Here is an example that uses a [lodash.isEqual](https://lodash.com/docs/4.17.15#isEqual) deep equal equality check

> `lodash.isequal` correctly handles deep comparing two arrays

```js
import memoizeOne from 'memoize-one';
import isDeepEqual from 'lodash.isequal';

const identity = (x) => x;

const shallowMemoized = memoizeOne(identity);
const deepMemoized = memoizeOne(identity, isDeepEqual);

const result1 = shallowMemoized({ foo: 'bar' });
const result2 = shallowMemoized({ foo: 'bar' });

result1 === result2; // false - different object reference

const result3 = deepMemoized({ foo: 'bar' });
const result4 = deepMemoized({ foo: 'bar' });

result3 === result4; // true - arguments are deep equal
```

The equality function needs to conform to the `EqualityFn` `type`:

```ts
// TFunc is the function being memoized
type EqualityFn<TFunc extends (...args: any[]) => any> = (
  newArgs: Parameters<TFunc>,
  lastArgs: Parameters<TFunc>,
) => boolean;

// You can import this type
import type { EqualityFn } from 'memoize-one';
```

The `EqualityFn` type allows you to create equality functions that are extremely typesafe. You are welcome to provide your own less type safe equality functions.

Here are some examples of equality functions which are ordered by most type safe, to least type safe:

  Example equality function types

```ts
// the function we are going to memoize
function add(first: number, second: number): number {
  return first + second;
}

// Some options for our equality function
// ↑ stronger types
// ↓ weaker types

// ✅ exact parameters of `add`
{
  const isEqual = function (first: Parameters<typeof add>, second: Parameters<typeof add>) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ tuple of the correct types
{
  const isEqual = function (first: [number, number], second: [number, number]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ❌ tuple of incorrect types
{
  const isEqual = function (first: [number, string], second: [number, number]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ array of the correct types
{
  const isEqual = function (first: number[], second: number[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ❌ array of incorrect types
{
  const isEqual = function (first: string[], second: number[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ tuple of 'unknown'
{
  const isEqual = function (first: [unknown, unknown], second: [unknown, unknown]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ❌ tuple of 'unknown' of incorrect length
{
  const isEqual = function (first: [unknown, unknown, unknown], second: [unknown, unknown]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ array of 'unknown'
{
  const isEqual = function (first: unknown[], second: unknown[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ spread of 'unknown'
{
  const isEqual = function (...first: unknown[]) {
    return !!first;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ tuple of 'any'
{
  const isEqual = function (first: [any, any], second: [any, any]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ❌ tuple of 'any' or incorrect size
{
  const isEqual = function (first: [any, any, any], second: [any, any]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ array of 'any'
{
  const isEqual = function (first: any[], second: any[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ two arguments of type any
{
  const isEqual = function (first: any, second: any) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ a single argument of type any
{
  const isEqual = function (first: any) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}

// ✅ spread of any type
{
  const isEqual = function (...first: any[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
}
```

## `this`

### `memoize-one` correctly respects `this` control

This library takes special care to maintain, and allow control over the the `this` context for **both** the original function being memoized as well as the returned memoized function. Both the original function and the memoized function's `this` context respect [all the `this` controlling techniques](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md):

- new bindings (`new`)
- explicit binding (`call`, `apply`, `bind`);
- implicit binding (call site: `obj.foo()`);
- default binding (`window` or `undefined` in `strict mode`);
- fat arrow binding (binding to lexical `this`)
- ignored this (pass `null` as `this` to explicit binding)

### Changes to `this` is considered an argument change

Changes to the running context (`this`) of a function can result in the function returning a different value even though its arguments have stayed the same:

```js
function getA() {
  return this.a;
}

const temp1 = {
  a: 20,
};
const temp2 = {
  a: 30,
};

getA.call(temp1); // 20
getA.call(temp2); // 30
```

Therefore, in order to prevent against unexpected results, `memoize-one` takes into account the current execution context (`this`) of the memoized function. If `this` is different to the previous invocation then it is considered a change in argument. [further discussion](https://github.com/alexreardon/memoize-one/issues/3).

Generally this will be of no impact if you are not explicity controlling the `this` context of functions you want to memoize with [explicit binding](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#explicit-binding) or [implicit binding](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#implicit-binding). `memoize-One` will detect when you are manipulating `this` and will then consider the `this` context as an argument. If `this` changes, it will re-execute the original function even if the arguments have not changed.

## Clearing the memoization cache

A `.clear()` property is added to memoized functions to allow you to clear it's memoization cache.

This is helpful if you want to:

- Release memory
- Allow the result function to be called again without having to change arguments

```ts
import memoizeOne from 'memoize-one';

function add(a: number, b: number): number {
  return a + b;
}

const memoizedAdd = memoizeOne(add);

// first call - not memoized
const first = memoizedAdd(1, 2);

// second call - cache hit (result function not called)
const second = memoizedAdd(1, 2);

// 👋 clearing memoization cache
memoizedAdd.clear();

// third call - not memoized (cache was cleared)
const third = memoizedAdd(1, 2);
```

## When your result function `throw`s

> There is no caching when your result function throws

If your result function `throw`s then the memoized function will also throw. The throw will not break the memoized functions existing argument cache. It means the memoized function will pretend like it was never called with arguments that made it `throw`.

```js
const canThrow = (name: string) => {
  console.log('called');
  if (name === 'throw') {
    throw new Error(name);
  }
  return { name };
};

const memoized = memoizeOne(canThrow);

const value1 = memoized('Alex');
// result function called: console.log => 'called'

const value2 = memoized('Alex');
// result function not called (cache hit)

console.log(value1 === value2);
// console.log => true

try {
  memoized('throw');
  // console.log => 'called'
} catch (e) {
  firstError = e;
}

try {
  memoized('throw');
  // console.log => 'called'
  // the result function was called again even though it was called twice
  // with the 'throw' string
} catch (e) {
  secondError = e;
}

console.log(firstError !== secondError);
// console.log => true

const value3 = memoized('Alex');
// result function not called as the original memoization cache has not been busted

console.log(value1 === value3);
// console.log => true
```

## Function properties

Functions memoized with `memoize-one` do not preserve any properties on the function object.

> This behaviour is correctly reflected in the TypeScript types

```ts
import memoizeOne from 'memoize-one';

function add(a, b) {
  return a + b;
}
add.hello = 'hi';

console.log(typeof add.hello); // string

const memoized = memoizeOne(add);

// hello property on the `add` was not preserved
console.log(typeof memoized.hello); // undefined
```

> If you feel strongly that `memoize-one` _should_ preserve function properties, please raise an issue. This decision was made in order to keep `memoize-one` as light as possible.

For _now_, the `.length` property of a function is not preserved on the memoized function

```ts
import memoizeOne from 'memoize-one';

function add(a, b) {
  return a + b;
}

console.log(add.length); // 2

const memoized = memoizeOne(add);

console.log(memoized.length); // 0
```

There is no (great) way to correctly set the `.length` property of the memoized function while also supporting ie11. Once we [remove ie11 support](https://github.com/alexreardon/memoize-one/issues/125) then we plan on setting the `.length` property of the memoized function to match the original function

[→ discussion](https://github.com/alexreardon/memoize-one/pull/124).

## Memoized function `type`

The resulting function you get back from `memoize-one` has _almost_ the same `type` as the function that you are memoizing

```ts
declare type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = {
  clear: () => void;
  (this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>;
};
```

- the same call signature as the function being memoized
- a `.clear()` function property added
- other function object properties on `TFunc` as not carried over

You are welcome to use the `MemoizedFn` generic directly from `memoize-one` if you like:

```ts
import memoize, { MemoizedFn } from 'memoize-one';
import isDeepEqual from 'lodash.isequal';
import { expectTypeOf } from 'expect-type';

// Takes any function: TFunc, and returns a Memoized<TFunc>
function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc): MemoizedFn<TFunc> {
  return memoize(fn, isDeepEqual);
}

function add(first: number, second: number): number {
  return first + second;
}

const memoized = withDeepEqual(add);

expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();
```

In this specific example, this type would have been correctly inferred too

```ts
import memoize, { MemoizedFn } from 'memoize-one';
import isDeepEqual from 'lodash.isequal';
import { expectTypeOf } from 'expect-type';

// return type of MemoizedFn<TFunc> is inferred
function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc) {
  return memoize(fn, isDeepEqual);
}

function add(first: number, second: number): number {
  return first + second;
}

const memoized = withDeepEqual(add);

// type test still passes
expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();
```

## Performance 🚀

### Tiny

`memoize-one` is super lightweight at [![min](https://img.shields.io/bundlephobia/min/memoize-one.svg?label=)](https://www.npmjs.com/package/memoize-one) minified and [![minzip](https://img.shields.io/bundlephobia/minzip/memoize-one.svg?label=)](https://www.npmjs.com/package/memoize-one) gzipped. (`1KB` = `1,024 Bytes`)

### Extremely fast

`memoize-one` performs better or on par with than other popular memoization libraries for the purpose of remembering the latest invocation.

The comparisons are not exhaustive and are primarily to show that `memoize-one` accomplishes remembering the latest invocation really fast. There is variability between runs. The benchmarks do not take into account the differences in feature sets, library sizes, parse time, and so on.

  Expand for results

node version `16.11.1`

You can run this test in the repo by:

1. Add `"type": "module"` to the `package.json` (why is things so hard)
2. Run `yarn perf:library-comparison`

**no arguments**

| Position | Library                                      | Operations per second |
| -------- | -------------------------------------------- | --------------------- |
| 1        | memoize-one                                  | 80,112,981            |
| 2        | moize                                        | 72,885,631            |
| 3        | memoizee                                     | 35,550,009            |
| 4        | mem (JSON.stringify strategy)                | 4,610,532             |
| 5        | lodash.memoize (JSON.stringify key resolver) | 3,708,945             |
| 6        | no memoization                               | 505                   |
| 7        | fast-memoize                                 | 504                   |

**single primitive argument**

| Position | Library                                      | Operations per second |
| -------- | -------------------------------------------- | --------------------- |
| 1        | fast-memoize                                 | 45,482,711            |
| 2        | moize                                        | 34,810,659            |
| 3        | memoize-one                                  | 29,030,828            |
| 4        | memoizee                                     | 23,467,065            |
| 5        | mem (JSON.stringify strategy)                | 3,985,223             |
| 6        | lodash.memoize (JSON.stringify key resolver) | 3,369,297             |
| 7        | no memoization                               | 507                   |

**single complex argument**

| Position | Library                                      | Operations per second |
| -------- | -------------------------------------------- | --------------------- |
| 1        | moize                                        | 27,660,856            |
| 2        | memoize-one                                  | 22,407,916            |
| 3        | memoizee                                     | 19,546,835            |
| 4        | mem (JSON.stringify strategy)                | 2,068,038             |
| 5        | lodash.memoize (JSON.stringify key resolver) | 1,911,335             |
| 6        | fast-memoize                                 | 1,633,855             |
| 7        | no memoization                               | 504                   |

**multiple primitive arguments**

| Position | Library                                      | Operations per second |
| -------- | -------------------------------------------- | --------------------- |
| 1        | moize                                        | 22,366,497            |
| 2        | memoize-one                                  | 17,241,995            |
| 3        | memoizee                                     | 9,789,442             |
| 4        | mem (JSON.stringify strategy)                | 3,065,328             |
| 5        | lodash.memoize (JSON.stringify key resolver) | 2,663,599             |
| 6        | fast-memoize                                 | 1,219,548             |
| 7        | no memoization                               | 504                   |

**multiple complex arguments**

| Position | Library                                      | Operations per second |
| -------- | -------------------------------------------- | --------------------- |
| 1        | moize                                        | 21,788,081            |
| 2        | memoize-one                                  | 17,321,248            |
| 3        | memoizee                                     | 9,595,420             |
| 4        | lodash.memoize (JSON.stringify key resolver) | 873,283               |
| 5        | mem (JSON.stringify strategy)                | 850,779               |
| 6        | fast-memoize                                 | 687,863               |
| 7        | no memoization                               | 504                   |

**multiple complex arguments (spreading arguments)**

| Position | Library                                      | Operations per second |
| -------- | -------------------------------------------- | --------------------- |
| 1        | moize                                        | 21,701,537            |
| 2        | memoizee                                     | 19,463,942            |
| 3        | memoize-one                                  | 17,027,544            |
| 4        | lodash.memoize (JSON.stringify key resolver) | 887,816               |
| 5        | mem (JSON.stringify strategy)                | 849,244               |
| 6        | fast-memoize                                 | 691,512               |
| 7        | no memoization                               | 504                   |

## Code health 👍

- Tested with all built in [JavaScript types](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/types%20%26%20grammar/ch1.md)
- Written in `Typescript`
- Correct typing for `Typescript` and `flow` type systems
- No dependencies


text:
"use strict";

var ast = require("../ast");

var ione = require("../parse-helpers").ione;

module.exports = function(ps) {
  /// I'm not incredibly a fan of having IdentExpr, but it helps the linter
  /// know when an identifier is being used for its name vs when it's being
  /// used for the value it references.
  return ione(ast.IdentifierExpression, ps.Identifier);
};


text:
<?php

namespace WellCommerce\Bundle\ReviewBundle\EventListener;

use WellCommerce\Bundle\CatalogBundle\Entity\Product;
use WellCommerce\Bundle\CoreBundle\EventListener\AbstractEventSubscriber;
use WellCommerce\Component\Form\Event\FormEvent;

/**
 * Class ReviewSubscriber
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ReviewSubscriber extends AbstractEventSubscriber
{
    public static function getSubscribedEvents()
    {
        return [
            'admin.product.pre_form_init' => ['onProductFormAdminInit'],
        ];
    }

    public function onProductFormAdminInit(FormEvent $event)
    {
        $resource = $event->getResource();
        if ($resource instanceof Product) {
            $form    = $event->getForm();
            $builder = $event->getFormBuilder();

            $mainData = $form->getChildren()->get('main_data');

            $mainData->addChild($builder->getElement('checkbox', [
                'name'    => 'enableReviews',
                'label'   => 'review.label.enable_reviews',
                'default' => true,
            ]));
        }
    }
}


text:
<?php

namespace Google\Service\Contentwarehouse;

class RepositoryWebrefWebrefMustangAttachment extends \Google\Collection
{
  protected $collection_key = 'undermergedMembers';
  /**
   * @var int[]
   */
  public $categoryConfidenceE2;
  /**
   * @var string[]
   */
  public $categoryEncodedMid;
  /**
   * @var int[]
   */
  public $confidenceE2;
  /**
   * @var string[]
   */
  public $encodedMid;
  protected $entityMetadataType = RepositoryWebrefWebrefAttachmentMetadata::class;
  protected $entityMetadataDataType = 'array';
  protected $iqlAttachmentType = KnowledgeAnswersIntentQueryIndexingIQLAttachment::class;
  protected $iqlAttachmentDataType = '';
  /**
   * @var int[]
   */
  public $isAuthorIndex;
  /**
   * @var int[]
   */
  public $isPublisherIndex;
  /**
   * @var int[]
   */
  public $referencePageIndex;
  /**
   * @var int[]
   */
  public $topicalityE2;
  /**
   * @var string[]
   */
  public $unboundIntentMid;
  /**
   * @var int[]
   */
  public $unboundIntentScoreE2;
  protected $undermergedMembersType = RepositoryWebrefWebrefMustangAttachmentUndermergedMembers::class;
  protected $undermergedMembersDataType = 'array';

  /**
   * @param int[]
   */
  public function setCategoryConfidenceE2($categoryConfidenceE2)
  {
    $this->categoryConfidenceE2 = $categoryConfidenceE2;
  }
  /**
   * @return int[]
   */
  public function getCategoryConfidenceE2()
  {
    return $this->categoryConfidenceE2;
  }
  /**
   * @param string[]
   */
  public function setCategoryEncodedMid($categoryEncodedMid)
  {
    $this->categoryEncodedMid = $categoryEncodedMid;
  }
  /**
   * @return string[]
   */
  public function getCategoryEncodedMid()
  {
    return $this->categoryEncodedMid;
  }
  /**
   * @param int[]
   */
  public function setConfidenceE2($confidenceE2)
  {
    $this->confidenceE2 = $confidenceE2;
  }
  /**
   * @return int[]
   */
  public function getConfidenceE2()
  {
    return $this->confidenceE2;
  }
  /**
   * @param string[]
   */
  public function setEncodedMid($encodedMid)
  {
    $this->encodedMid = $encodedMid;
  }
  /**
   * @return string[]
   */
  public function getEncodedMid()
  {
    return $this->encodedMid;
  }
  /**
   * @param RepositoryWebrefWebrefAttachmentMetadata[]
   */
  public function setEntityMetadata($entityMetadata)
  {
    $this->entityMetadata = $entityMetadata;
  }
  /**
   * @return RepositoryWebrefWebrefAttachmentMetadata[]
   */
  public function getEntityMetadata()
  {
    return $this->entityMetadata;
  }
  /**
   * @param KnowledgeAnswersIntentQueryIndexingIQLAttachment
   */
  public function setIqlAttachment(KnowledgeAnswersIntentQueryIndexingIQLAttachment $iqlAttachment)
  {
    $this->iqlAttachment = $iqlAttachment;
  }
  /**
   * @return KnowledgeAnswersIntentQueryIndexingIQLAttachment
   */
  public function getIqlAttachment()
  {
    return $this->iqlAttachment;
  }
  /**
   * @param int[]
   */
  public function setIsAuthorIndex($isAuthorIndex)
  {
    $this->isAuthorIndex = $isAuthorIndex;
  }
  /**
   * @return int[]
   */
  public function getIsAuthorIndex()
  {
    return $this->isAuthorIndex;
  }
  /**
   * @param int[]
   */
  public function setIsPublisherIndex($isPublisherIndex)
  {
    $this->isPublisherIndex = $isPublisherIndex;
  }
  /**
   * @return int[]
   */
  public function getIsPublisherIndex()
  {
    return $this->isPublisherIndex;
  }
  /**
   * @param int[]
   */
  public function setReferencePageIndex($referencePageIndex)
  {
    $this->referencePageIndex = $referencePageIndex;
  }
  /**
   * @return int[]
   */
  public function getReferencePageIndex()
  {
    return $this->referencePageIndex;
  }
  /**
   * @param int[]
   */
  public function setTopicalityE2($topicalityE2)
  {
    $this->topicalityE2 = $topicalityE2;
  }
  /**
   * @return int[]
   */
  public function getTopicalityE2()
  {
    return $this->topicalityE2;
  }
  /**
   * @param string[]
   */
  public function setUnboundIntentMid($unboundIntentMid)
  {
    $this->unboundIntentMid = $unboundIntentMid;
  }
  /**
   * @return string[]
   */
  public function getUnboundIntentMid()
  {
    return $this->unboundIntentMid;
  }
  /**
   * @param int[]
   */
  public function setUnboundIntentScoreE2($unboundIntentScoreE2)
  {
    $this->unboundIntentScoreE2 = $unboundIntentScoreE2;
  }
  /**
   * @return int[]
   */
  public function getUnboundIntentScoreE2()
  {
    return $this->unboundIntentScoreE2;
  }
  /**
   * @param RepositoryWebrefWebrefMustangAttachmentUndermergedMembers[]
   */
  public function setUndermergedMembers($undermergedMembers)
  {
    $this->undermergedMembers = $undermergedMembers;
  }
  /**
   * @return RepositoryWebrefWebrefMustangAttachmentUndermergedMembers[]
   */
  public function getUndermergedMembers()
  {
    return $this->undermergedMembers;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(RepositoryWebrefWebrefMustangAttachment::class, 'Google_Service_Contentwarehouse_RepositoryWebrefWebrefMustangAttachment');


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using chat.services;
using chat.network.server;
using Hashtable=System.Collections.Hashtable;

namespace chat.client
{
    static class StartChatClient
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //IChatServer server=new ChatServerMock();
            IChatServer server = new ChatServerProxy("127.0.0.1", 55555);
            ChatClientCtrl ctrl=new ChatClientCtrl(server);
            LoginWindow win=new LoginWindow(ctrl);
            Application.Run(win);
        }
    }
}


text:
<?php
declare(strict_types=1);
namespace MyPlot\forms;

use dktapps\pmforms\MenuOption;
use MyPlot\MyPlot;
use MyPlot\subcommand\SubCommand;
use pocketmine\player\Player;
use pocketmine\utils\TextFormat;

class MainForm extends SimpleMyPlotForm {

	/** @var SubCommand[] $link */
	private array $link = [];

	/**
	 * MainForm constructor.
	 *
	 * @param Player $player
	 * @param SubCommand[] $subCommands
	 *
	 * @throws \ReflectionException
	 */
	public function __construct(Player $player, array $subCommands) {
		$plugin = MyPlot::getInstance();
		$this->setPlot($plugin->getPlotByPosition($player->getPosition()));

		$elements = [];
		foreach($subCommands as $command) {
			if(!$command->canUse($player) or $command->getForm($player) === null)
				continue;
			$name = (new \ReflectionClass($command))->getShortName();
			$name = preg_replace('/([a-z])([A-Z])/s','$1 $2', $name);
			if($name === null)
				continue;
			$length = strlen($name) - strlen("Sub Command");
			$name = substr($name, 0, $length);
			$elements[] = new MenuOption(TextFormat::DARK_RED.ucfirst($name));
			$this->link[] = $command;
		}
		parent::__construct(
			TextFormat::BLACK.$plugin->getLanguage()->translateString("form.header", ["Main"]),
			"",
			$elements,
			function(Player $player, int $selectedOption) : void {
				$form = $this->link[$selectedOption]->getForm($player);
				if($form === null)
					return;
				$form->setPlot($this->plot);
				$player->sendForm($form);
			},
			function(Player $player) : void {}
		);
	}
}


text:
package fr.landel.utils.assertor;

import fr.landel.utils.assertor.helper.HelperStep;

/**
 * This class is an intermediate or final link in chain, see {@link Step}.
 *
 * @since Aug 3, 2016
 * @author Gilles
 *
 * @param <I>
 *            the {@link Iterable} type
 * @param <T>
 *            the {@link Iterable} elements type
 */
@FunctionalInterface
public interface StepIterable<I extends Iterable<T>, T> extends Step<StepIterable<I, T>, I> {

    default StepIterable<I, T> get(final StepAssertor<I> result) {
        return () -> result;
    }

    @Override
    default AssertorStepIterable<I, T> and() {
        return () -> HelperStep.and(this.getStep());
    }

    @Override
    default AssertorStepIterable<I, T> or() {
        return () -> HelperStep.or(this.getStep());
    }

    @Override
    default AssertorStepIterable<I, T> xor() {
        return () -> HelperStep.xor(this.getStep());
    }

    @Override
    default AssertorStepIterable<I, T> nand() {
        return () -> HelperStep.nand(this.getStep());
    }

    @Override
    default AssertorStepIterable<I, T> nor() {
        return () -> HelperStep.nor(this.getStep());
    }
}