text:
package laika.tree.helper

import scala.io.Codec
import laika.io.OutputProvider
import laika.tree.Paths.Path
import laika.tree.Paths.Root
import laika.tree.Paths.Current
import laika.io.OutputProvider.ProviderBuilder
import laika.io.Output
import laika.tree.Elements.TextContainer
import laika.tree.Elements.ElementContainer
import laika.tree.Elements.Element
import scala.collection.mutable.ListBuffer
import java.io.File
import scala.annotation.tailrec
import scala.io.Source

object OutputBuilder {

  /* translating render results to Elements gives us nicely formatted PrettyPrint for free */

  case class RenderedDocument (path: Path, content: String) extends Element

  trait TreeContent extends Element

  case class Documents (content: Seq[RenderedDocument]) extends ElementContainer[RenderedDocument, Documents] with TreeContent
  case class Subtrees (content: Seq[RenderedTree]) extends ElementContainer[RenderedTree, Subtrees] with TreeContent

  case class RenderedTree (path: Path, content: Seq[TreeContent]) extends ElementContainer[TreeContent, RenderedTree]

  class TestOutputProvider (val path: Path) extends OutputProvider {

    val documents = ListBuffer[(Path,StringBuilder)]()

    val subtrees = ListBuffer[TestOutputProvider]()

    def toTree: RenderedTree = new RenderedTree(path, List(
      Documents(documents map { case (path, builder) => RenderedDocument(path, builder.toString) }),
      Subtrees(subtrees map (_.toTree))
    ) filterNot { case c: ElementContainer[_,_] => c.content.isEmpty })

    def newOutput (name: String): Output = {
      val builder = new StringBuilder
      documents += ((path / name, builder))
      Output.toBuilder(builder)
    }

    def newChild (name: String): OutputProvider = {
      val provider = new TestOutputProvider(path / name)
      subtrees += provider
      provider
    }

  }

  class TestProviderBuilder extends ProviderBuilder {

    val provider = new TestOutputProvider(Root)

    def result: RenderedTree = provider.toTree

    def build (codec: Codec): OutputProvider = provider

  }

  def createTempDirectory (baseName: String): File = {
    val maxAttempts = 100
    val baseDir = new File(System.getProperty("java.io.tmpdir"))
    val name = System.currentTimeMillis() + "-";

    def abort () = throw new IllegalStateException("Failed to create directory within "
        + maxAttempts + " attempts (tried "
        + baseName + "0 to " + baseName + (maxAttempts - 1) + ')')

    @tailrec def createDir (num: Int): File = {
      val tempDir = new File(baseDir, name + num);
      if (tempDir.mkdir()) tempDir
      else if (num >= maxAttempts) abort()
      else createDir(num + 1)
    }

    createDir(1)
  }

  def readFile (base: String): String = readFile(new File(base))

  def readFile (f: File): String = {
    val source = Source.fromFile(f)
    val fileContent = source.mkString
    source.close()
    fileContent
  }

}


text:
'use strict';

/**
 * 生成对应的meta信息
 *
 * @param {Object} config - 对应的配置
 * @return {Object}
 */
module.exports = function*(config) {
    config = config || {};
    const options = config.options || {};
    const meta = options.meta || {};

    const keywords = meta.keywords || 'billund';
    const description = meta.description || '大众点评';

    return {
        result: `
        		<meta name="Keywords" content="${keywords}" />
    			<meta name="Description" content="${description}" />
    			<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    			<meta name="apple-mobile-web-app-status-bar-style" content="black" />
    			<meta name="format-detection" content="telephone=no" />
    			<meta name="format-detection" content="email=no" />
        		`
    };
};

redpajama_set_name: RedPajamaGithub


text:
package add

import (
	"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app"
	"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app/args"
	"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app/flags"
	"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app/flagsets"
	"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/app/with"
	"github.com/BytemarkHosting/bytemark-client/util/log"
	"github.com/urfave/cli"
)

func init() {
	Commands = append(Commands, cli.Command{
		Name:    "discs",
		Aliases: []string{"disc", "disk", "disks"},
		Flags: []cli.Flag{
			cli.GenericFlag{
				Name:  "disc",
				Usage: "A disc to add. You can specify as many discs as you like by adding more --disc flags.",
				Value: new(flags.DiscSpecFlag),
			},
			flagsets.Force,
			cli.GenericFlag{
				Name:  "server",
				Usage: "the server to add the disc to",
				Value: new(flags.VirtualMachineNameFlag),
			},
		},
		Usage:     "add virtual discs attached to one of your cloud servers",
		UsageText: "add discs [--disc <disc spec>]... <cloud server>",
		Description: `A disc spec looks like the following: label:grade:size
The label and grade fields are optional. If grade is empty, defaults to sata.
If there are two fields, they are assumed to be grade and size.
Multiple --disc flags can be used to add multiple discs`,
		Action: app.Action(args.Optional("server", "cores", "memory", "disc"), with.Auth, createDiscs),
	})
}

// createDiscs adds the disc(s) to the speicified server
func createDiscs(c *app.Context) (err error) {
	discs := flags.Discs(c, "disc")

	for i := range discs {
		d, err := discs[i].Validate()
		if err != nil {
			return err
		}
		discs[i] = *d
	}
	vmName := flags.VirtualMachineName(c, "server")

	log.Logf("Adding %d discs to %s:\r\n", len(discs), vmName)
	for _, d := range discs {
		log.Logf("    %dGiB %s...", d.Size/1024, d.StorageGrade)
		err := c.Client().CreateDisc(vmName, d)
		if err != nil {
			log.Errorf("failure! %v\r\n", err.Error())
		} else {
			log.Log("success!")
		}
	}
	return
}


text:
<?php
	include '../config/config.php';
	$query = mysqli_query($koneksi, "SELECT users.id_user, users.username, orders.id_order, orders.subtotal   FROM users INNER JOIN orders ON users.id_user = orders.id_user");
?>


text:
AwsSnsKit is a solution for integrating Amazon Web Service(AWS) Simple Notification Service(SNS) into a Rails application.

## Installation

Add this line to your application's Gemfile:

    gem 'aws_sns_kit'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install aws_sns_kit

## Configuration

Before using aws_sns_kit, you need to generate files using a generator.
Specify your model as first argument.

```ruby
rails generate aws_sns_kit:install MODEL_NAME
```

ex.
```ruby
rails generate aws_sns_kit:install User
```

This generator command create following files.

```ruby
config/initializers/aws_sns_kit.rb

db/migrate/20140715070941_add_aws_sns_kit_to_users.rb
```

Then, migrate.

```ruby
rake db:migrate
```

Also, you need to configure your initializer file.

Following configuration is for using aws-sdk.
More information here. https://github.com/aws/aws-sdk-ruby

```ruby
#config/initializers/aws_sns_kit.rb

AwsSnsKit.configure do |config|
  config.access_key_id = 'your access_key_id here'
  config.secret_access_key = 'your secret_access_key here'
  config.region = 'your region here'

  #specify PlatformApplicationArn respectively.

  config.end_point = {
    apns: '',
    apns_sandbox: '',
    gcm: ''
  }
end

```

## How to use?

#### APNS(Apple Push Notification Service)

You can use `push_notify` instance method with your model instance to send push notification via AWS SNS.
Before using this method, make sure that your model includes Notifier module from aws_sns_kit.

```ruby
class User < ActiveRecord::Base
  include AwsSnsKit::Notifier
end
```

Create a notification payload hash and send it by applying argument to `push_notify` method.

```ruby
user = User.first

notification = {
        alert: 'Message received via aws_sns_kit',
        sound: 'bingbong.aiff',
        badge: 2,
        content_available: 1,
        custom_data: { awesome: 'something' }
      }

user.push_notify(notification)
```

##### NOTE:
Since AWS SNS can send a notification to multiple platform, aws_sns_kit expect your MODEL to return the name of the platform when `sns_platform` method is called.
Specify your platform name from one of the following to your MODEL's attributes or instance method.

`[:apns, :apns_sandbox, :gcm]`

```ruby
# Set platform using model attribute

pry(main)> User.first.sns_platform
=> :apns

# Or specify it using instance method

class User < ActiveRecord::Base
  def sns_platform
    :apns
  end
end
```

#### GCM(Google Cloud Messaging)

Work in progress now.

#### Topics & Subscription

Work in progress now.

## Contributing

1. Fork it ( https://github.com/awingla/aws_sns_kit/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
<?php

  define('MODULE_PAYMENT_MONEYBOOKERS_DNK_TEXT_TITLE', 'Moneybookers - Dankort (Denmark)');
  define('MODULE_PAYMENT_MONEYBOOKERS_DNK_TEXT_PUBLIC_TITLE', 'Dankort');
  define('MODULE_PAYMENT_MONEYBOOKERS_DNK_TEXT_DESCRIPTION', ' Visit Moneybookers Website');
?>


text:
* **What git concepts were you struggling with prior to the GPS session?**

*git fetch and merge conflicts, I kept forgeting to fetch updated files before which caused some files to be deleted and now I try to make it a habit to always fetch new files.  With merge conflicts it was more of not having any real practice.  I would go on codecademy.com and alos look at serveral youtube videos to get different perspectives on the command and it helped a lot, but real practice makes a big difference.*

* **What concepts were clarified during the GPS?**

*Merge clonflicts were clarified.  I guess I never realized that making edits on different branches may cause merge conflicts*

* **What questions did you ask your pair and the guide?**

*I asked questions about best practices and alternative methods to use git and terminal.  I learned that if I enter the first few letters of a file name and press the "tab" key, it fill auto complete the line.  I asked my guide how to prepate and work through challenges efficiently and how if there were recommendations on what resources to ultilize.*

* **What still confuses you about git?**

*Nothing in regards to the challenge, but the idea of a git reset --hard, --soft, and --mix, I think I don't fully understand the differences and how to use them to my advantage.*

* **How was your first experience of pairing in a GPS?**

*It was not as scary as I thought it would be.  I learned a lot from my guide.  I learned shortcut commands that were useful such as the find field in sublime.  I learned that If I make a change and one branch, then checkout into another branch, that sublime will automatically know that.  My guide was extremely knowledgable.*


text:
"use strict";
var Block = (function () {
    function Block(id, content) {
        this.id = id;
        this.content = content;
    }
    return Block;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Block;


text:
import { FunctionAppVersion } from './../models/constants';

export interface FunctionsVersionInfo {
  runtimeStable: string[];
  runtimeDefault: string;
}

export class FunctionsVersionInfoHelper {
  public static needToUpdateRuntime(version: FunctionsVersionInfo, extensionVersion: string) {
    const match = version.runtimeStable.find(v => {
      return extensionVersion.toLowerCase() === v;
    });
    return !match;
  }

  public static getFunctionGeneration(runtimeVersion: string) {
    if (!runtimeVersion) {
      return FunctionAppVersion.v1;
    }

    return runtimeVersion.startsWith('~2') || runtimeVersion.startsWith('2') || runtimeVersion.startsWith('beta')
      ? FunctionAppVersion.v2
      : FunctionAppVersion.v1;
  }

  public static getEventGridUri(generation: string, mainSiteUrl: string, functionName: string, code: string) {
    const path = generation === FunctionAppVersion.v1 ? 'admin/extensions/EventGridExtensionConfig' : 'runtime/webhooks/EventGrid';

    return `${mainSiteUrl.toLowerCase()}/${path}?functionName=${functionName}&code=${code}`;
  }
}


text:
layout: model
title: Named Entity Recognition - CoNLL03 DeBERTa Large (nerdl_conll_deberta_large)
author: John Snow Labs
name: nerdl_conll_deberta_large
date: 2022-06-01
tags: [en, english, conll, deberta, v3, large, open_source]
task: Named Entity Recognition
language: en
edition: Spark NLP 4.0.0
spark_version: 3.0
supported: true
annotator: NerDLModel
article_header:
  type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

`nerdl_conll_deberta_large` is a Named Entity Recognition (or NER) model, meaning it annotates text to find features like the names of people, places, and organizations. It was trained on the CoNLL 2003 text corpus. This NER model does not read words directly but instead reads word embeddings, which represent words as points such that more semantically similar words are closer together. `nerdl_conll_deberta_large` model is trained with the `deberta_v3_large` word embeddings, so be sure to use the same embeddings in the pipeline.

## Predicted Entities

`PER`, `LOC`, `ORG`, `MISC`

{:.btn-box}
[Live Demo](https://demo.johnsnowlabs.com/public/NER_EN){:.button.button-orange}
[Open in Colab](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/NER_EN.ipynb){:.button.button-orange.button-orange-trans.co.button-icon}
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/nerdl_conll_deberta_large_en_4.0.0_3.0_1654103260615.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
document_assembler = DocumentAssembler() \
    .setInputCol('text') \
    .setOutputCol('document')

tokenizer = Tokenizer() \
    .setInputCols(['document']) \
    .setOutputCol('token')

embeddings = DeBertaEmbeddings.pretrained("deberta_v3_large", "en")\
      .setInputCols(["token", "document"])\
      .setOutputCol("embeddings")\
      .setCaseSensitive(True)\
      .setMaxSentenceLength(512)

ner_model = NerDLModel.pretrained('nerdl_conll_deberta_large', 'en') \
    .setInputCols(['document', 'token', 'embeddings']) \
    .setOutputCol('ner')

ner_converter = NerConverter() \
    .setInputCols(['document', 'token', 'ner']) \
    .setOutputCol('entities')

pipeline = Pipeline(stages=[
    document_assembler,
    tokenizer,
    embeddings,
    ner_model,
    ner_converter
])

example = spark.createDataFrame([['My name is John!']]).toDF("text")
result = pipeline.fit(example).transform(example)
```
```scala
val document_assembler = DocumentAssembler()
    .setInputCol("text")
    .setOutputCol("document")

val tokenizer = Tokenizer()
    .setInputCols("document")
    .setOutputCol("token")

val embeddings = DeBertaEmbeddings.pretrained("deberta_v3_large", "en")
    .setInputCols("document", "token")
    .setOutputCol("embeddings")
    .setCaseSensitive(true)
    .setMaxSentenceLength(512)

val ner_model = NerDLModel.pretrained("nerdl_conll_deberta_large", "en")
    .setInputCols("document"', "token", "embeddings")
    .setOutputCol("ner")

val ner_converter = NerConverter()
    .setInputCols("document", "token", "ner")
    .setOutputCol("entities")

val pipeline = new Pipeline().setStages(Array(document_assembler, tokenizer, embeddings, ner_model, ner_converter))

val example = Seq.empty["My name is John!"].toDS.toDF("text")

val result = pipeline.fit(example).transform(example)
```

{:.nlu-block}
```python
import nlu

text = ["My name is John!"]

ner_df = nlu.load('en.ner.nerdl_conll_deberta_large').predict(text, output_level='token')
```
</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|nerdl_conll_deberta_large|
|Type:|ner|
|Compatibility:|Spark NLP 4.0.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[sentence, token, embeddings]|
|Output Labels:|[ner]|
|Language:|en|
|Size:|16.9 MB|

## References

[https://www.clips.uantwerpen.be/conll2003/ner/](https://www.clips.uantwerpen.be/conll2003/ner/)

## Benchmarking

```bash
Test:

       label  precision    recall  f1-score   support
       B-LOC       0.94      0.93      0.93      1668
       I-ORG       0.88      0.94      0.91       835
      I-MISC       0.72      0.74      0.73       216
       I-LOC       0.86      0.89      0.88       257
       I-PER       0.99      0.99      0.99      1156
      B-MISC       0.84      0.83      0.83       702
       B-ORG       0.90      0.93      0.91      1661
       B-PER       0.98      0.97      0.97      1617
   micro-avg       0.92      0.93      0.93      8112
weighted-avg       0.92      0.93      0.93      8112

Dev:

       label  precision    recall  f1-score   support
       B-LOC       0.96      0.97      0.97      1837
       I-ORG       0.93      0.95      0.94       751
      I-MISC       0.91      0.82      0.86       346
       I-LOC       0.95      0.93      0.94       257
       I-PER       0.99      0.98      0.98      1307
      B-MISC       0.94      0.89      0.92       922
       B-ORG       0.93      0.95      0.94      1341
       B-PER       0.98      0.99      0.98      1842
   micro-avg       0.96      0.96      0.96      8603
weighted-avg       0.96      0.96      0.96      8603
```


text:
import PropTypes from "prop-types";
import CustomPropTypes from "../victory-util/prop-types";

export default {
  active: PropTypes.bool,
  className: PropTypes.string,
  data: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
  events: PropTypes.object,
  index: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  origin: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }),
  polar: PropTypes.bool,
  role: PropTypes.string,
  scale: PropTypes.oneOfType([
    CustomPropTypes.scale,
    PropTypes.shape({ x: CustomPropTypes.scale, y: CustomPropTypes.scale })
  ]),
  shapeRendering: PropTypes.string,
  style: PropTypes.object,
  transform: PropTypes.string
};


text:
$('.form').find('input, textarea').on('keyup blur focus', function (e) {

  var $this = $(this),
      label = $this.prev('label');

	  if (e.type === 'keyup') {
			if ($this.val() === '') {
          label.removeClass('active highlight');
        } else {
          label.addClass('active highlight');
        }
    } else if (e.type === 'blur') {
    	if( $this.val() === '' ) {
    		label.removeClass('active highlight');
			} else {
		    label.removeClass('highlight');
			}
    } else if (e.type === 'focus') {

      if( $this.val() === '' ) {
    		label.removeClass('highlight');
			}
      else if( $this.val() !== '' ) {
		    label.addClass('highlight');
			}
    }

});

$('.tab a').on('click', function (e) {

  e.preventDefault();

  $(this).parent().addClass('active');
  $(this).parent().siblings().removeClass('active');

  target = $(this).attr('href');

  $('.tab-content > div').not(target).hide();

  $(target).fadeIn(600);

});
$('.tab b').on('click', function (e) {

  e.preventDefault();

  $(this).parent().addClass('active');
  $(this).parent().siblings().removeClass('active');

  target = $(this).attr('href');

  $('.tab-content > div').not(target).hide();

  $(target).fadeIn(600);

});

$('.forgot').on('click', function (e) {

  e.preventDefault();

  $(this).parent().addClass('active');
  $(this).parent().siblings().removeClass('active');

  target = $(this).attr('href');

  $('.tab-content > div').not(target).hide();

  $(target).fadeIn(600);

});

$('.choice').on('click', function (e) {

  e.preventDefault();

  $(this).parent().addClass('active');
  $(this).parent().siblings().removeClass('active');

  $('.tab-content > div').not(target).hide();

  $(target).fadeIn(600);

});

function checkPass()
{
    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');
    var elmt = document.getElementById("pass2");

    var goodColor = "#1ab188";
    var badColor = "#ff6666";
    if(pass1.value == pass2.value){
      elmt.style.borderColor = goodColor;

    }else{

// on récupère l'élément

// on modifie son style
elmt.style.borderColor = badColor;

         }
}

function check(input) {
        if (input.value != document.getElementById('pass1').value) {
            input.setCustomValidity('Password Must be Matching.');
        } else {
            // input is valid -- reset the error message
            input.setCustomValidity('');
        }
    }


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Redux starter boilerplate</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
    <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
          crossorigin="anonymous">


text:
<button ng-click='commentCtrl.show_comments(expense)' ng-hide='commentCtrl.displayComments'>Show Comments</button>

		{{comment.text}} -- {{comment.pub_date|date:'longDate'}}

		<textarea class="form-control" ng-model='commentCtrl.comment_text' cols=24 rows=3 />

		<button class='btn btn-warning' ng-click='commentCtrl.create(expense)'>Send</button>


text:
@implementation Entity3

@dynamic identifier;
@dynamic name;

+ (NSManagedObjectContext *)mainThreadManagedObjectContext
{
    return [SLRESTfulCoreDataSharedManagedObjectContext sharedInstance].managedObjectContext;
}

+ (NSManagedObjectContext *)backgroundThreadManagedObjectContext
{
    return [SLRESTfulCoreDataSharedManagedObjectContext sharedInstance].managedObjectContext;
}

@end


text:
package org.apache.jena.tdb.transaction;

import org.apache.jena.atlas.lib.InternalErrorException ;
import org.apache.jena.atlas.logging.Log ;

public enum JournalEntryType
{
    // Abort is used
    Block(1), Buffer(2), Object(3), Commit(4), Abort(5), Checkpoint(6) ;

    final int id ;
    JournalEntryType(int x) { id = x ; }
    int getId() { return id ; }
    static public JournalEntryType type(int x)
    {
        if ( x == Block.id )                return Block ;
        else if ( x == Buffer.id )          return Buffer ;
        else if ( x == Object.id )          return Object ;
        else if ( x == Commit.id )          return Commit ;
        else if ( x == Abort.id )           return Abort ;
        else if ( x == Checkpoint.id )      return Checkpoint ;
        else
        {
            Log.fatal(JournalEntryType.class, "Unknown type: "+x) ;
            throw new InternalErrorException("Unknown type: "+x) ;
        }
    }
}


text:
void gui_block_tab(Tab *tab);
void gui_unblock_tab(Tab *tab);
void gui_set_command(const char *cmd);
void gui_switch_mode(void);
void gui_new_tab(Tab *tab);
void gui_close_tab(Tab *tab);
void gui_free(void);
void gui_show_quick_history(void);
void gui_close_quick_history(void);
void gui_quick_history_up(void);
void gui_quick_history_down(void);
int gui_init(void);

#endif


text:
package edu.nyu.vida.data_polygamy.utils;

import java.util.HashMap;

/**
 * Disjoint set class, using union by rank and path compression.
 * Adapted using the code by Mark Allen Weiss
 */
public class DisjointSets {

	HashMap<Integer, Integer> set;

	public DisjointSets() {
		set = new HashMap<Integer, Integer>();
	}

	public void clear() {
		set.clear();
	}
	/**
	 * Union two disjoint sets using the height heuristic. root1 and root2 are
	 * distinct and represent set names.
	 *
	 * @param root1
	 *            the root of set 1.
	 * @param root2
	 *            the root of set 2.
	 */
	public void union(int root1, int root2) {
		if (root1 == root2)
			return;

		int r1 = set.get(root1);
		int r2 = set.get(root2);

		if (r2 < r1) {
			// root2 is deeper
			// Make root2 new root
			set.remove(root1);
			set.put(root1, root2);
		} else {
			if (r1 == r2) {
				// Update height if same
				r1--;
				set.remove(root1);
				set.put(root1, r1);
			}
			// Make root1 new root
			set.remove(root2);
			set.put(root2, root1);
		}
	}

	/**
	 * Perform a find with path compression.
	 *
	 * @param x
	 *            the element being searched for.
	 * @return the set containing x.
	 */
	public int find(int x) {
		Integer f = set.get(x);
		if (f == null) {
			f = -1;
			set.put(x, -1);
		}
		if (f < 0) {
			return x;
		} else {
			int xx = find(f);
			set.remove(x);
			set.put(x, xx);
			return xx;
		}
	}

	// Test main; all finds on same output line should be identical
	public static void main(String[] args) {
		int numElements = 128;
		int numInSameSet = 16;

		// DisjointSets ds = new DisjointSets( numElements );
		DisjointSets ds = new DisjointSets();
		int set1, set2;

		for (int k = 1; k < numInSameSet; k *= 2) {
			for (int j = 0; j + k < numElements; j += 2 * k) {
				set1 = ds.find(j);
				set2 = ds.find(j + k);
				ds.union(set1, set2);
			}
		}

		for (int i = 0; i < numElements; i++) {
			System.out.print(ds.find(i) + "*");
			if (i % numInSameSet == numInSameSet - 1)
				System.out.println();
		}
		System.out.println();
	}
}


text:
/*! \addtogroup osclproc OSCL Proc
 *
 * @{
 */

/** \file oscl_aostatus.h
    \brief Some basic types used with active objects.
*/
#ifndef OSCL_AOSTATUS_H_INCLUDED
#define OSCL_AOSTATUS_H_INCLUDED

#ifndef OSCLCONFIG_PROC_H_INCLUDED
#include "osclconfig_proc.h"
#endif

#ifndef OSCL_BASE_H_INCLUDED
#include "oscl_base.h"
#endif

//Request status values.  These are negative so that
//they won't conflict with system error codes.
const int32 OSCL_REQUEST_ERR_NONE = 0;
const int32 OSCL_REQUEST_PENDING = (-0x7fffffff);
const int32 OSCL_REQUEST_ERR_CANCEL = (-1);
const int32 OSCL_REQUEST_ERR_GENERAL = (-2);

//Request status type
class OsclAOStatus
{
    public:
        OSCL_INLINE OsclAOStatus();
        OSCL_INLINE OsclAOStatus(int32 aStatus);
        OSCL_INLINE int32 operator=(int32 aStatus);
        OSCL_INLINE int32 operator==(int32 aStatus) const;
        OSCL_INLINE int32 operator!=(int32 aStatus) const;
        OSCL_INLINE int32 operator>=(int32 aStatus) const;
        OSCL_INLINE int32 operator<=(int32 aStatus) const;
        OSCL_INLINE int32 operator>(int32 aStatus) const;
        OSCL_INLINE int32 operator<(int32 aStatus) const;
        OSCL_INLINE int32 Value() const;
    private:
        int32 iStatus;
};

#if !(OSCL_DISABLE_INLINES)
#include "oscl_aostatus.inl"
#endif

#endif

/*! @} */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Map;
using System.IO;
using Explorer.Explorers;
using Generator.Generators;

namespace MapGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            var seed = args.Length > 1 ? Convert.ToInt32(args[0]) : int.MaxValue;
            var moves = args.Length > 2 ? Convert.ToInt32(args[0]) : 10000;
            var maxPath = args.Length > 3 ? Convert.ToInt32(args[1]) : 100;
            var map = new Map.Map();
            var generator = new StraightPathGenerator(seed, map);
            var explorer = new RandomExplorer(map, new List<Explorer.ILocationListener>() { generator });
            explorer.Explore(seed, moves);

            MapDrawer drawer = new MapDrawer();
            drawer.DrawMap(map);
            drawer.DrawPath(explorer.Path);
        }
    }
}


text:
#pragma once
#include <aws/forecast/ForecastService_EXPORTS.h>
#include <aws/forecast/ForecastServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/forecast/model/DataDestination.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/forecast/model/Tag.h>
#include <utility>

namespace Aws
{
namespace ForecastService
{
namespace Model
{

  /**
   */
  class AWS_FORECASTSERVICE_API CreateForecastExportJobRequest : public ForecastServiceRequest
  {
  public:
    CreateForecastExportJobRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateForecastExportJob"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name for the forecast export job.

     */
    inline const Aws::String& GetForecastExportJobName() const{ return m_forecastExportJobName; }

    /**
     *
The name for the forecast export job.

     */
    inline bool ForecastExportJobNameHasBeenSet() const { return m_forecastExportJobNameHasBeenSet; }

    /**
     *
The name for the forecast export job.

     */
    inline void SetForecastExportJobName(const Aws::String& value) { m_forecastExportJobNameHasBeenSet = true; m_forecastExportJobName = value; }

    /**
     *
The name for the forecast export job.

     */
    inline void SetForecastExportJobName(Aws::String&& value) { m_forecastExportJobNameHasBeenSet = true; m_forecastExportJobName = std::move(value); }

    /**
     *
The name for the forecast export job.

     */
    inline void SetForecastExportJobName(const char* value) { m_forecastExportJobNameHasBeenSet = true; m_forecastExportJobName.assign(value); }

    /**
     *
The name for the forecast export job.

     */
    inline CreateForecastExportJobRequest& WithForecastExportJobName(const Aws::String& value) { SetForecastExportJobName(value); return *this;}

    /**
     *
The name for the forecast export job.

     */
    inline CreateForecastExportJobRequest& WithForecastExportJobName(Aws::String&& value) { SetForecastExportJobName(std::move(value)); return *this;}

    /**
     *
The name for the forecast export job.

     */
    inline CreateForecastExportJobRequest& WithForecastExportJobName(const char* value) { SetForecastExportJobName(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline const Aws::String& GetForecastArn() const{ return m_forecastArn; }

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline bool ForecastArnHasBeenSet() const { return m_forecastArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline void SetForecastArn(const Aws::String& value) { m_forecastArnHasBeenSet = true; m_forecastArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline void SetForecastArn(Aws::String&& value) { m_forecastArnHasBeenSet = true; m_forecastArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline void SetForecastArn(const char* value) { m_forecastArnHasBeenSet = true; m_forecastArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline CreateForecastExportJobRequest& WithForecastArn(const Aws::String& value) { SetForecastArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline CreateForecastExportJobRequest& WithForecastArn(Aws::String&& value) { SetForecastArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the forecast that you want to export.

     */
    inline CreateForecastExportJobRequest& WithForecastArn(const char* value) { SetForecastArn(value); return *this;}

    /**
     *
The location where you want to save the forecast and an AWS Identity and
     * Access Management (IAM) role that Amazon Forecast can assume to access the
     * location. The forecast must be exported to an Amazon S3 bucket.

If
     * encryption is used, Destination must include an AWS Key Management
     * Service (KMS) key. The IAM role must allow Amazon Forecast permission to access
     * the key.

     */
    inline const DataDestination& GetDestination() const{ return m_destination; }

    /**
     *
The location where you want to save the forecast and an AWS Identity and
     * Access Management (IAM) role that Amazon Forecast can assume to access the
     * location. The forecast must be exported to an Amazon S3 bucket.

If
     * encryption is used, Destination must include an AWS Key Management
     * Service (KMS) key. The IAM role must allow Amazon Forecast permission to access
     * the key.

     */
    inline bool DestinationHasBeenSet() const { return m_destinationHasBeenSet; }

    /**
     *
The location where you want to save the forecast and an AWS Identity and
     * Access Management (IAM) role that Amazon Forecast can assume to access the
     * location. The forecast must be exported to an Amazon S3 bucket.

If
     * encryption is used, Destination must include an AWS Key Management
     * Service (KMS) key. The IAM role must allow Amazon Forecast permission to access
     * the key.

     */
    inline void SetDestination(const DataDestination& value) { m_destinationHasBeenSet = true; m_destination = value; }

    /**
     *
The location where you want to save the forecast and an AWS Identity and
     * Access Management (IAM) role that Amazon Forecast can assume to access the
     * location. The forecast must be exported to an Amazon S3 bucket.

If
     * encryption is used, Destination must include an AWS Key Management
     * Service (KMS) key. The IAM role must allow Amazon Forecast permission to access
     * the key.

     */
    inline void SetDestination(DataDestination&& value) { m_destinationHasBeenSet = true; m_destination = std::move(value); }

    /**
     *
The location where you want to save the forecast and an AWS Identity and
     * Access Management (IAM) role that Amazon Forecast can assume to access the
     * location. The forecast must be exported to an Amazon S3 bucket.

If
     * encryption is used, Destination must include an AWS Key Management
     * Service (KMS) key. The IAM role must allow Amazon Forecast permission to access
     * the key.

     */
    inline CreateForecastExportJobRequest& WithDestination(const DataDestination& value) { SetDestination(value); return *this;}

    /**
     *
The location where you want to save the forecast and an AWS Identity and
     * Access Management (IAM) role that Amazon Forecast can assume to access the
     * location. The forecast must be exported to an Amazon S3 bucket.

If
     * encryption is used, Destination must include an AWS Key Management
     * Service (KMS) key. The IAM role must allow Amazon Forecast permission to access
     * the key.

     */
    inline CreateForecastExportJobRequest& WithDestination(DataDestination&& value) { SetDestination(std::move(value)); return *this;}

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline CreateForecastExportJobRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline CreateForecastExportJobRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline CreateForecastExportJobRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
The optional metadata that you apply to the forecast export job to help you
     * categorize and organize them. Each tag consists of a key and an optional value,
     * both of which you define.

The following basic restrictions apply to
     * tags:

Maximum number of tags per resource - 50.

     *
For each resource, each tag key must be unique, and each tag key can have
     * only one value.

Maximum key length - 128 Unicode characters in
     * UTF-8.

Maximum value length - 256 Unicode characters in
     * UTF-8.

If your tagging schema is used across multiple services
     * and resources, remember that other services may have restrictions on allowed
     * characters. Generally allowed characters are: letters, numbers, and spaces
     * representable in UTF-8, and the following characters: + - = . _ : / @.

     *

Tag keys and values are case sensitive.

Do not use
     * aws:, AWS:, or any upper or lowercase combination of
     * such as a prefix for keys as it is reserved for AWS use. You cannot edit or
     * delete tag keys with this prefix. Values can have this prefix. If a tag value
     * has aws as its prefix but the key does not, then Forecast considers
     * it to be a user tag and will count against the limit of 50 tags. Tags with only
     * the key prefix of aws do not count against your tags per resource
     * limit.

     */
    inline CreateForecastExportJobRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_forecastExportJobName;
    bool m_forecastExportJobNameHasBeenSet;

    Aws::String m_forecastArn;
    bool m_forecastArnHasBeenSet;

    DataDestination m_destination;
    bool m_destinationHasBeenSet;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;
  };

} // namespace Model
} // namespace ForecastService
} // namespace Aws


text:
package mutate

import (
	"testing"

	"github.com/qiniu/logkit/transforms"
	. "github.com/qiniu/logkit/utils/models"

	"github.com/stretchr/testify/assert"
)

func TestLabelTransformer(t *testing.T) {
	// simple label
	label := &Label{
		Key:   "new_key",
		Value: "new_value",
	}
	data, err := label.Transform([]Data{{}, {"old_key": "old_value"}})
	assert.NoError(t, err)
	exp := []Data{{"new_key": "new_value"}, {"old_key": "old_value", "new_key": "new_value"}}
	assert.Equal(t, exp, data)
	assert.Equal(t, label.Stage(), transforms.StageAfterParser)

	// no override explicitly
	label2 := &Label{
		Key:      "new_key",
		Value:    "new_value",
		Override: false,
	}
	data2, err := label2.Transform([]Data{{"new_key": "old_value"}})
	assert.NotNil(t, err)
	assert.Equal(t, int64(1), label2.Stats().Errors)
	exp2 := []Data{{"new_key": "old_value"}}
	assert.Equal(t, exp2, data2)

	// override explicitly
	label3 := &Label{
		Key:      "new_key",
		Value:    "new_value",
		Override: true,
	}
	data3, err := label3.Transform([]Data{{"new_key": "old_value"}})
	assert.NoError(t, err)
	exp3 := []Data{{"new_key": "new_value"}}
	assert.Equal(t, exp3, data3)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.hadoop.security.token.TokenIdentifier (Hadoop 0.20.2-cdh3u4 API)
</TITLE>

<META NAME="date" CONTENT="2012-05-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.hadoop.security.token.TokenIdentifier

Packages that use TokenIdentifier

org.apache.hadoop.ipc
Tools to help define network clients and servers.

org.apache.hadoop.mapreduce.security

org.apache.hadoop.mapreduce.security.token

org.apache.hadoop.mapreduce.security.token.delegation

org.apache.hadoop.security

org.apache.hadoop.security.token

org.apache.hadoop.security.token.delegation

Uses of TokenIdentifier in org.apache.hadoop.ipc

Method parameters in org.apache.hadoop.ipc with type arguments of type TokenIdentifier

static RPC.Server
RPC.getServer(Object instance,
          String bindAddress,
          int port,
          int numHandlers,
          boolean verbose,
          Configuration conf,
          SecretManager<? extends TokenIdentifier> secretManager)

          Construct a server for a protocol implementation instance listening on a
 port and address, with a secret manager.

Constructor parameters in org.apache.hadoop.ipc with type arguments of type TokenIdentifier

RPC.Server(Object instance,
           Configuration conf,
           String bindAddress,
           int port,
           int numHandlers,
           boolean verbose,
           SecretManager<? extends TokenIdentifier> secretManager)

          Construct an RPC server.

Server(String bindAddress,
       int port,
       Class<? extends Writable> paramClass,
       int handlerCount,
       Configuration conf,
       String serverName,
       SecretManager<? extends TokenIdentifier> secretManager)

          Constructs a server listening on the named port and address.

Uses of TokenIdentifier in org.apache.hadoop.mapreduce.security

Method parameters in org.apache.hadoop.mapreduce.security with type arguments of type TokenIdentifier

static void
TokenCache.setJobToken(Token<? extends TokenIdentifier> t,
            Credentials credentials)

          store job token

Uses of TokenIdentifier in org.apache.hadoop.mapreduce.security.token

Subclasses of TokenIdentifier in org.apache.hadoop.mapreduce.security.token

 class
JobTokenIdentifier

          The token identifier for job token

Method parameters in org.apache.hadoop.mapreduce.security.token with type arguments of type TokenIdentifier

 Token<JobTokenIdentifier>
JobTokenSelector.selectToken(Text service,
            Collection<Token<? extends TokenIdentifier>> tokens)

Uses of TokenIdentifier in org.apache.hadoop.mapreduce.security.token.delegation

Subclasses of TokenIdentifier in org.apache.hadoop.mapreduce.security.token.delegation

 class
DelegationTokenIdentifier

          A delegation token identifier that is specific to MapReduce.

Uses of TokenIdentifier in org.apache.hadoop.security

Methods in org.apache.hadoop.security with type parameters of type TokenIdentifier

static

<T extends TokenIdentifier>

T

SaslRpcServer.getIdentifier(String id,
              SecretManager<T> secretManager)

Methods in org.apache.hadoop.security that return types with arguments of type TokenIdentifier

 Collection<Token<? extends TokenIdentifier>>
Credentials.getAllTokens()

          Return all the tokens in the in-memory map

 Token<? extends TokenIdentifier>
Credentials.getToken(Text alias)

          Returns the Token object for the alias

 Set<TokenIdentifier>
UserGroupInformation.getTokenIdentifiers()

          Get the set of TokenIdentifiers belonging to this UGI

 Collection<Token<? extends TokenIdentifier>>
UserGroupInformation.getTokens()

          Obtain the collection of tokens associated with this user.

Methods in org.apache.hadoop.security with parameters of type TokenIdentifier

 boolean
UserGroupInformation.addTokenIdentifier(TokenIdentifier tokenId)

          Add a TokenIdentifier to this UGI.

Method parameters in org.apache.hadoop.security with type arguments of type TokenIdentifier

 void
Credentials.addToken(Text alias,
         Token<? extends TokenIdentifier> t)

          Add a token in the storage (in memory)

 boolean
UserGroupInformation.addToken(Token<? extends TokenIdentifier> token)

          Add a token to this UGI

Constructor parameters in org.apache.hadoop.security with type arguments of type TokenIdentifier

SaslRpcClient(SaslRpcServer.AuthMethod method,
              Token<? extends TokenIdentifier> token,
              String serverPrincipal)

          Create a SaslRpcClient for an authentication method

SaslRpcServer.SaslDigestCallbackHandler(SecretManager<TokenIdentifier> secretManager,
                                        Server.Connection connection)

Uses of TokenIdentifier in org.apache.hadoop.security.token

Classes in org.apache.hadoop.security.token with type parameters of type TokenIdentifier

 class
SecretManager<T extends TokenIdentifier>

          The server-side secret manager for each token type.

 class
Token<T extends TokenIdentifier>

          The client-side form of the token.

 interface
TokenSelector<T extends TokenIdentifier>

          Select token of type T from tokens for use with named service

Method parameters in org.apache.hadoop.security.token with type arguments of type TokenIdentifier

 Token<T>
TokenSelector.selectToken(Text service,
            Collection<Token<? extends TokenIdentifier>> tokens)

Uses of TokenIdentifier in org.apache.hadoop.security.token.delegation

Subclasses of TokenIdentifier in org.apache.hadoop.security.token.delegation

 class
AbstractDelegationTokenIdentifier

Method parameters in org.apache.hadoop.security.token.delegation with type arguments of type TokenIdentifier

 Token<TokenIdent>
AbstractDelegationTokenSelector.selectToken(Text service,
            Collection<Token<? extends TokenIdentifier>> tokens)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2009 The Apache Software Foundation


text:
export interface ResultsProps {
  isVerified: boolean | null;
  result: BacktrackResult | null;
}

const Results: React.FC<ResultsProps> = ({ isVerified, result }) => {
  const { isSolutionFound, error, statistics } = result || {};
  const { elapsedTime = 0, nbrOfIteration } = statistics || {};

  if (!result) {
    return null;
  }

  return (

        {isVerified === false ? "Invalid Sudoku" : ""}

          {isSolutionFound ? "Solution found 😊" : "No solution 😢"}

         Error happened: {JSON.stringify(error)}

          Elapsed time: {elapsedTime.toFixed(2)} msec

        Iterations: {nbrOfIteration}

  );
};

export default Results;


text:
[![Chat](https://badges.gitter.im/Avaq/Fluture.svg)](https://gitter.im/Avaq/Fluture)
[![NPM Version](https://badge.fury.io/js/fluture.svg)](https://www.npmjs.com/package/fluture)
[![Dependencies](https://david-dm.org/avaq/fluture.svg)](https://david-dm.org/avaq/fluture)
[![Build Status](https://travis-ci.org/Avaq/Fluture.svg?branch=master)](https://travis-ci.org/Avaq/Fluture)
[![Code Coverage](https://codecov.io/gh/Avaq/Fluture/branch/master/graph/badge.svg)](https://codecov.io/gh/Avaq/Fluture)

Fluture offers a control structure similar to Promises, Tasks, Deferreds, and
what-have-you. Let's call them Futures.

Much like Promises, Futures represent the value arising from the success or
failure of an asynchronous operation (I/O). Though unlike Promises Futures are
*lazy* and *monadic* by design. They conform to the [Fantasy Land][FL] algebraic
JavaScript specification.

Fluture boasts the following features:

* Fine-grained control over asynchronous flow through generic monadic
  transformations and an array of control utilities.
* [Cancellation](#future).
* [Resource management utilities](#resource-management).
* Plays nicely with functional libraries such as [Ramda][20] and [Sanctuary][21].
* Provides a pleasant debugging experience through informative error messages.
* Considerable performance benefits over Promises and the likes.

For more information:

* [Wiki: Compare Futures to Promises][22]
* [Wiki: Compare Fluture to similar libraries][15]
* [Video: Monad a Day by @DrBoolean - Futures][23]

## Usage

> `npm install --save fluture`

```js
const fs = require('fs');
const Future = require('fluture');

const getPackageName = file =>
  Future.node(done => fs.readFile(file, 'utf8', done))
  .chain(Future.encase(JSON.parse))
  .map(x => x.name);

getPackageName('package.json')
.fork(console.error, console.log);
//> "fluture"
```

For front-end applications and node <v4, please use `require('fluture/es5')`.

## Table of contents

- [Usage](#usage)
- [Interoperability](#interoperability)
- [Documentation](#documentation)
  1. [Type signatures](#type-signatures)
  1. [Creating Futures](#creating-futures)
    * [Future](#future)
    * [of](#of)
    * [reject](#reject)
    * [after](#after)
    * [rejectAfter](#rejectafter)
    * [try](#try)
    * [encase](#encase)
    * [fromForkable](#fromforkable)
    * [fromPromise](#frompromise)
    * [node](#node)
    * [chainRec](#chainrec)
  1. [Transforming Futures](#transforming-futures)
    * [map](#map)
    * [bimap](#bimap)
    * [chain](#chain)
    * [ap](#ap)
    * [swap](#swap)
  1. [Error handling](#error-handling)
    * [mapRej](#maprej)
    * [chainRej](#chainrej)
    * [fold](#fold)
  1. [Resource management](#resource-management)
    * [hook](#hook)
    * [finally](#finally)
  1. [Consuming Futures](#consuming-futures)
    * [fork](#fork)
    * [value](#value)
    * [promise](#promise)
  1. [Parallelism](#parallelism)
    * [race](#race)
    * [and](#and)
    * [or](#or)
    * [both](#both)
    * [parallel](#parallel)
  1. [Utility functions](#utility-functions)
    * [isFuture](#isfuture)
    * [isForkable](#isforkable)
    * [cache](#cache)
    * [do](#do)
  1. [Sanctuary](#sanctuary)
  1. [Futurization](#futurization)
- [Benchmarks](#benchmarks)
- [Butterfly](#butterfly)

## Interoperability

[][FL]
[][25]

Fluture implements [FantasyLand 1][FL1], [FantasyLand 2][FL2],
[FantasyLand 3][FL3] and [Static Land][25] compatible `Functor`, `Bifunctor`,
`Apply`, `Applicative`, `Chain`, `ChainRec` and `Monad`.

FantasyLand 0.x is *mostly* supported. Everything but `Apply` (`ap`) is, this
means that dispatchers to FantasyLand 0.x `ap` will not work.

## Documentation

### Type signatures

[Hindley-Milner][9] type signatures are used to document functions. Signatures
starting with a `.` refer to "static" functions, whereas signatures starting
with a `#` refer to functions on the prototype.

A list of all types used within the signatures follows:

- **Forkable** - Any Object with a `fork` method that takes at least two
  arguments. This includes instances of Fluture, instances of Task from
  [`data.task`][10] or instances of Future from [`ramda-fantasy`][11].
- **Future** - Instances of Future provided by Fluture.
- **Promise** - Values which conform to the [Promises/A+ specification][33].
- **Functor** - Values which conform to the [Fantasy Land Functor specification][12]
  as determined by [Sanctuary Type Classes][27].
- **Bifunctor** - Values which conform to the [Fantasy Land Bifunctor specification][24]
  as determined by [Sanctuary Type Classes][28].
- **Chain** - Values which conform to the [Fantasy Land Chain specification][13]
  as determined by [Sanctuary Type Classes][29].
- **Apply** - Values which conform to the [Fantasy Land Apply specification][14]
  as determined by [Sanctuary Type Classes][30].
- **Iterator** - Objects with `next`-methods which conform to the [Iterator protocol][18].
- **Iteration** - `{done, value}`-Objects as defined by the [Iterator protocol][18].
- **Next** - An incomplete (`{done: false}`) Iteration.
- **Done** - A complete (`{done: true}`) Iteration.
- **Cancel** - The nullary cancellation functions returned from computations.

### Creating Futures

#### Future
##### `Future :: ((a -> (), b -> ()) -> Cancel) -> Future a b`

Creates a Future with the given computation. A computation is a function which
takes two callbacks. Both are continuations for the computation. The first is
`reject`, commonly abbreviated to `rej`. The second `resolve`, which abbreviates
to `res`. When the computation is finished (possibly asynchronously) it may call
the appropriate continuation with a failure or success value.

```js
Future(function computation(reject, resolve){
  //Asynchronous work:
  const x = setTimeout(resolve, 3000, 'world');
  //Cancellation:
  return () => clearTimeout(x);
});
```

Additionally, the computation may return a nullary function containing
cancellation logic. This function is executed when the Future is cancelled
after it's [forked](#fork).

#### of
##### `.of :: a -> Future _ a`

Creates a Future which immediately resolves with the given value. This function
is compliant with the [Fantasy Land Applicative specification][16].

```js
const eventualThing = Future.of('world');
eventualThing.fork(
  console.error,
  thing => console.log(`Hello ${thing}!`)
);
//> "Hello world!"
```

#### reject
##### `.reject :: a -> Future a _`

Creates a Future which immediately rejects with the given value. Just like `of`
but for the rejection branch.

#### after
##### `.after :: Number -> b -> Future a b`

Creates a Future which resolves with the given value after n milliseconds.

```js
const eventualThing = Future.after(500, 'world');
eventualThing.fork(console.error, thing => console.log(`Hello ${thing}!`));
//> "Hello world!"
```

#### rejectAfter
##### `.rejectAfter :: Number -> a -> Future a b`

Creates a Future which rejects with the given reason after n milliseconds.

```js
const eventualError = Future.rejectAfter(500, new Error('Kaputt!'));
eventualError.fork(err => console.log('Oh no - ' + err.message), console.log);
//! Oh no - Kaputt!
```

#### try
##### `.try :: (() -> !a | b) -> Future a b`

Creates a Future which resolves with the result of calling the given function,
or rejects with the error thrown by the given function.

Sugar for `Future.encase(f, undefined)`.

```js
const data = {foo: 'bar'}
Future.try(() => data.foo.bar.baz)
.fork(console.error, console.log)
//> [TypeError: Cannot read property 'baz' of undefined]
```

#### encase
##### `.encase :: (a -> !e | r) -> a -> Future e r`
##### `.encase2 :: (a, b -> !e | r) -> a -> b -> Future e r`
##### `.encase3 :: (a, b, c -> !e | r) -> a -> b -> c -> Future e r`

Takes a function and a value, and returns a Future which when forked calls the
function with the value and resolves with the result. If the function throws
an exception, it is caught and the Future will reject with the exception:

```js
const data = '{"foo" = "bar"}'
Future.encase(JSON.parse, data)
.fork(console.error, console.log)
//! [SyntaxError: Unexpected token =]
```

Partially applying `encase` with a function `f` allows us to create a "safe"
version of `f`. Instead of throwing exceptions, the encased version always
returns a Future when given the remaining argument(s):

```js
const data = '{"foo" = "bar"}'
const safeJsonParse = Future.encase(JSON.parse)
safeJsonParse(data).fork(console.error, console.log)
//! [SyntaxError: Unexpected token =]
```

Furthermore; `encase2` and `encase3` are binary and ternary versions of
`encase`, applying two or three arguments to the given function respectively.

#### fromForkable
##### `.fromForkable :: Forkable a b -> Future a b`

Cast any [Forkable](#type-signatures) to a [Future](#type-signatures).

```js
Future.fromForkable(require('data.task').of('hello')).value(console.log);
//> "hello"
```

#### fromPromise
##### `.fromPromise :: (a -> Promise e r) -> a -> Future e r`
##### `.fromPromise2 :: (a, b -> Promise e r) -> a -> b -> Future e r`
##### `.fromPromise3 :: (a, b, c -> Promise e r) -> a -> b -> c -> Future e r`

Allows Promise-returning functions to be turned into Future-returning functions.

Takes a function which returns a Promise, and a value, and returns a Future
which calls the function to produce the Promise, and resolves with the Promise
resolution value, or rejects with the Promise rejection reason.

```js
const fetchf = Future.fromPromise(fetch);

fetchf('https://api.github.com/users/Avaq')
.chain(res => Future.fromPromise(_ => res.json(), 0))
.map(user => user.name)
.fork(console.error, console.log);
//> "Aldwin Vlasblom"
```

Furthermore; `fromPromise2` and `fromPromise3` are binary and ternary versions
of `fromPromise`, applying two or three arguments to the given function respectively.

#### node
##### `.node :: (((a, b) -> ()) -> ()) -> Future a b`

Creates a Future which rejects with the first argument given to the function,
or resolves with the second if the first is not present.

This is a convenience for NodeJS users who wish to easily obtain a Future from
a node style callback API. To permanently turn a function into one that returns
a Future, check out [futurization](#futurization).

```js
Future.node(done => fs.readFile('package.json', 'utf8', done))
.fork(console.error, console.log)
//> "{...}"
```

#### chainRec
##### `.chainRec :: ((b -> Next, c -> Done, b) -> Future a Iteration) -> b -> Future a c`

Stack- and memory-safe asynchronous "recursion" based on [FantasyLand ChainRec][26].

Calls the given function with the initial value (as third argument), and expects
a Future of an [Iteration](#type-signatures). If the Iteration is incomplete
(`{done: false}`), then the function is called again with the Iteration value
until it returns a Future of a complete (`{done: true}`) Iteration.

For convenience and interoperability, the first two arguments passed to the
function are functions for creating an incomplete Iteration, and for creating a
complete Iteration, respectively.

```js
Future.chainRec((next, done, x) => Future.of(x < 1000000 ? next(x + 1) : done(x)), 0)
.fork(console.error, console.log);
//> 1000000
```

### Transforming Futures

#### map
##### `#map :: Future a b ~> (b -> c) -> Future a c`
##### `.map :: Functor m => (a -> b) -> m a -> m b`

Transforms the resolution value inside the Future, and returns a new Future with
the transformed value. This is like doing `promise.then(x => x + 1)`, except
that it's lazy, so the transformation will not be applied before the Future is
forked. The transformation is only applied to the resolution branch: If the
Future is rejected, the transformation is ignored. To learn more about the exact
behaviour of `map`, check out its [spec][12].

```js
Future.of(1)
.map(x => x + 1)
.fork(console.error, console.log);
//> 2
```

#### bimap
##### `#bimap :: Future a b ~> (a -> c) -> (b -> d) -> Future c d`
##### `.bimap :: Bifunctor m => (a -> b) -> (c -> d) -> m a c -> m b d`

Maps the left function over the rejection value, or the right function over the
resolution value, depending on which is present.

```js
Future.of(1)
.bimap(x => x + '!', x => x + 1)
.fork(console.error, console.log);
//> 2

Future.reject('error')
.bimap(x => x + '!', x => x + 1)
.fork(console.error, console.log);
//> "error!"
```

#### chain
##### `#chain :: Future a b ~> (b -> Future a c) -> Future a c`
##### `.chain :: Chain m => (a -> m b) -> m a -> m b`

Allows the creation of a new Future based on the resolution value. This is like
doing `promise.then(x => Promise.resolve(x + 1))`, except that it's lazy, so the
new Future will not be created until the other one is forked. The function is
only ever applied to the resolution value; it's ignored when the Future was
rejected. To learn more about the exact behaviour of `chain`, check out its [spec][13].

```js
Future.of(1)
.chain(x => Future.of(x + 1))
.fork(console.error, console.log);
//> 2
```

Note that, due to its lazy nature, the stack and/or heap will slowly fill up as
you chain more over the same structure. It's therefore recommended that you use
[`chainRec`](#chainrec) in cases where you wish to `chain` recursively or
traverse a large list (10000+ items).

#### ap
##### `#ap :: Future a b ~> Future a (b -> c) -> Future a c`
##### `.ap :: Apply m => m (a -> b) -> m a -> m b`

Applies the function contained in the right-hand Future or Apply to the value
contained in the left-hand Future or Apply. If one of the Futures rejects the
resulting Future will also be rejected. To learn more about the exact behaviour
of `ap`, check out its [spec][14].

```js
Future.of(1)
.ap(Future.of(x => x + 1))
.fork(console.error, console.log);
//> 2
```

#### swap
##### `#swap :: Future a b ~> Future b a`
##### `.swap :: Future a b -> Future b a`

Resolve with the rejection reason, or reject with the resolution value.

```js
Future.of(new Error('It broke')).swap().fork(console.error, console.log);
//! [It broke]

Future.reject('Nothing broke').swap().fork(console.error, console.log);
//> "Nothing broke"
```

### Error handling

Functions listed under this category allow you to get at or transform the
rejection reason in Futures, or even coerce Futures back into the resolution
branch in several different ways.

#### mapRej
##### `#mapRej :: Future a b ~> (a -> c) -> Future c b`
##### `.mapRej :: (a -> b) -> Future a c -> Future b c`

Map over the **rejection** reason of the Future. This is like `map`, but for the
rejection branch.

```js
Future.reject(new Error('It broke!')).mapRej(err => {
  return new Error('Some extra info: ' + err.message);
})
.fork(console.error, console.log)
//! [Some extra info: It broke!]
```

#### chainRej
##### `#chainRej :: Future a b ~> (a -> Future a c) -> Future a c`
##### `.chainRej :: (a -> Future a c) -> Future a b -> Future a c`

Chain over the **rejection** reason of the Future. This is like `chain`, but for
the rejection branch.

```js
Future.reject(new Error('It broke!')).chainRej(err => {
  console.error(err);
  return Future.of('All is good')
})
.fork(console.error, console.log)
//> "All is good"
```

#### fold
##### `#fold :: Future a b ~> (a -> c, b -> c) -> Future _ c`
##### `.fold :: (a -> c) -> (b -> c) -> Future a b -> Future _ c`

Applies the left function to the rejection value, or the right function to the
resolution value, depending on which is present, and resolves with the result.

This provides a convenient means to ensure a Future is always resolved. It can
be used with other type constructors, like [`S.Either`][7], to maintain a
representation of failures:

```js
Future.of('hello')
.fold(S.Left, S.Right)
.value(console.log);
//> Right('hello')

Future.reject('it broke')
.fold(S.Left, S.Right)
.value(console.log);
//> Left('it broke')
```

### Resource management

Functions listed under this category allow for more fine-grained control over
the flow of acquired values.

#### hook
##### `#hook :: Future a b ~> (b -> Future a c) -> (b -> Future a d) -> Future a d`
##### `.hook :: Future a b -> (b -> Future a c) -> (b -> Future a d) -> Future a d`

Much like [`chain`](#chain), but takes a "dispose" operation first, which runs
*after* the second settles (successfully or unsuccessfully). So the signature is
like `hook(acquire, dispose, consume)`, where `acquire` is a Future which might
create connections, open file handlers, etc. `dispose` is a function that takes
the result from `acquire` and should be used to clean up (close connections etc)
and `consume` also takes the result from `acquire`, and may be used to perform
any arbitrary computations using the resource. The resolution value of `dispose`
is ignored.

```js
const withConnection = Future.hook(
  openConnection('localhost'),
  closeConnection
);

withConnection(
  conn => query(conn, 'EAT * cakes FROM bakery')
)
.fork(console.error, console.log)
```

In the case that a hooked Future is *cancelled* after the resource was acquired,
`dispose` will be executed and immediately cancelled. This means that rejections
which may happen during this disposal are **silently ignored**. To ensure that
resources are disposed during cancellation, you might synchronously dispose
resources in the `cancel` function of the disposal Future:

```js
const closeConnection = conn => Future((rej, res) => {

  //We try to dispose gracefully.
  conn.flushGracefully(err => {
    if(err === null){
      conn.close();
      res();
    }else{
      rej(err);
    }
  });

  //On cancel, we force dispose.
  return () => conn.close();

});
```

#### finally
##### `#finally :: Future a b ~> Future a c -> Future a b`
##### `.finally :: Future a c -> Future a b -> Future a b`

Run a second Future after the first settles (successfully or unsuccessfully).
Rejects with the rejection reason from the first or second Future, or resolves
with the resolution value from the first Future.

```js
Future.of('Hello')
.finally(Future.of('All done!').map(console.log))
.fork(console.error, console.log)
//> "All done!"
//> "Hello"
```

Note that the *first* Future is given as the *last* argument to `Future.finally()`:

```js
const program = S.pipe([
  Future.of,
  Future.finally(Future.of('All done!').map(console.log)),
  Future.fork(console.error, console.log)
])

program('Hello')
//> "All done!"
//> "Hello"
```

### Consuming Futures

#### fork
##### `#fork :: Future a b ~> (a -> (), b -> ()) -> Cancel`
##### `.fork :: (a -> ()) -> (b -> ()) -> Future a b -> Cancel`

Execute the computation that was passed to the Future at [construction](#future)
using the given `reject` and `resolve` callbacks.

```js
Future.of('world').fork(
  err => console.log(`Oh no! ${err.message}`),
  thing => console.log(`Hello ${thing}!`)
);
//> "Hello world!"

Future.reject(new Error('It broke!')).fork(
  err => console.log(`Oh no! ${err.message}`),
  thing => console.log(`Hello ${thing}!`)
);
//> "Oh no! It broke!"

const consoleFork = Future.fork(console.error, console.log);
consoleFork(Future.of('Hello'));
//> "Hello"
```

After you `fork` a Future, the computation will start running. If you wish to
cancel the computation, you may use the function returned by `fork`:

```js
const fut = Future.after(300, 'hello');
const cancel = fut.fork(console.error, console.log);
cancel();
//Nothing will happen. The Future was cancelled before it could settle.
```

#### value
##### `#value :: Future a b ~> (b -> ()) -> Cancel`
##### `.value :: (b -> ()) -> Future a b -> Cancel`

Extracts the value from a resolved Future by forking it. Only use this function
if you are sure the Future is going to be resolved, for example; after using
`.fold()`. If the Future rejects and `value` was used, an (likely uncatchable)
`Error` will be thrown.

```js
Future.reject(new Error('It broke'))
.fold(S.Left, S.Right)
.value(console.log)
//> Left([Error: It broke])
```

Just like [fork](#fork), `value` returns the `Cancel` function:

```js
Future.after(300, 'hello').value(console.log)();
//Nothing will happen. The Future was cancelled before it could settle.
```

#### promise
##### `#promise :: Future a b ~> Promise b a`
##### `.promise :: Future a b -> Promise b a`

An alternative way to `fork` the Future. This eagerly forks the Future and
returns a Promise of the result. This is useful if some API wants you to give it
a Promise. It's the only method which forks the Future without a forced way to
handle the rejection branch, so I recommend against using it for anything else.

```js
Future.of('Hello').promise().then(console.log);
//> "Hello"
```

### Parallelism

#### race
##### `#race :: Future a b ~> Future a b -> Future a b`
##### `.race :: Future a b -> Future a b -> Future a b`

Race two Futures against each other. Creates a new Future which resolves or
rejects with the resolution or rejection value of the first Future to settle.

```js
Future.after(100, 'hello')
.race(Future.after(50, 'bye'))
.fork(console.error, console.log)
//> "bye"

const first = futures => futures.reduce(race);
first([
  Future.after(100, 'hello'),
  Future.after(50, 'bye'),
  Future.rejectAfter(25, 'nope')
])
.fork(console.error, console.log)
//! "nope"
```

#### and
##### `#and :: Future a b ~> Future a b -> Future a b`
##### `.and :: Future a b -> Future a b -> Future a b`

Logical and for Futures.

Returns a new Future which either rejects with the first rejection reason, or
resolves with the last resolution value once and if both Futures resolve.

This behaves analogues to how JavaScript's and operator does, except both
Futures run simultaneously, so it is *not* short-circuited. That means that
if the second has side-effects, they will run (and possibly be cancelled) even
if the first rejects.

```js
//An asynchronous version of:
//const result = isResolved() && getValue();
const result = isResolved().and(getValue());
```

#### or
##### `#or :: Future a b ~> Future a b -> Future a b`
##### `.or :: Future a b -> Future a b -> Future a b`

Logical or for Futures.

Returns a new Future which either resolves with the first resolution value, or
rejects with the last rejection value once and if both Futures reject.

This behaves analogues to how JavaScript's or operator does, except both
Futures run simultaneously, so it is *not* short-circuited. That means that
if the second has side-effects, they will run even if the first resolves.

```js
//An asynchronous version of:
//const result = planA() || planB();
const result = planA().or(planB());

const program = S.pipe([
  reject,
  or(of('second chance')),
  value(console.log)
]);
program('first chance')
> "second chance"
```

In the example, assume both plans return Futures. Both plans are executed in
parallel. If `planA` resolves, the returned Future will resolve with its value.
If `planA` fails there is always `planB`. If both plans fail then the returned
Future will also reject using the rejection reason of `planB`.

#### both
##### `#both :: Future a b ~> Future a b -> Future a b`
##### `.both :: Future a b -> Future a b -> Future a b`

Run two Futures in parallel. Basically like calling
[`Future.parallel`](#parallel) with exactly two Futures:

```js
Future.parallel(2, [a, b])
===
Future.both(a, b)
===
a.both(b)
```

#### parallel
##### `.parallel :: PositiveInteger -> Array (Future a b) -> Future a (Array b)`

Creates a Future which when forked runs all Futures in the given `array` in
parallel, ensuring no more than `limit` Futures are running at once.

```js
const tenFutures = Array.from(Array(10).keys()).map(Future.after(20));

//Runs all Futures in sequence:
Future.parallel(1, tenFutures).fork(console.error, console.log);
//after about 200ms:
//> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

//Runs upto five Futures in parallel:
Future.parallel(5, tenFutures).fork(console.error, console.log);
//after about 40ms:
//> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

//Runs all Futures in parallel:
Future.parallel(Infinity, tenFutures).fork(console.error, console.log);
//after about 20ms:
//> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```

If you want to settle all Futures, even if some may fail, you can use this in
combination with [fold](#fold):

```js
const instableFutures = Array.from({length: 4}, (_, i) =>
  Future.node(done => done(Math.random() > 0.75 ? 'failed' : null, i))
);

const stabalizedFutures = instableFutures.map(Future.fold(S.Left, S.Right))

Future.parallel(Infinity, stabalizedFutures).fork(console.error, console.log);
//> [ Right(0), Left("failed"), Right(2), Right(3) ]
```

### Utility functions

#### isFuture
##### `.isFuture :: a -> Boolean`

Returns true for [Futures](#type-signatures) and false for everything else. This
function (and [`S.is`][17]) also return `true` for instances of Future that were
created within other contexts. It is therefore recommended to use this over
`instanceof`, unless your intent is to explicitly check for Futures created
using the exact `Future` constructor you're testing against.

```js
const Future1 = require('/path/to/fluture');
const Future2 = require('/other/path/to/fluture');

const m1 = Future1(noop);
Future1.isFuture(m1) === (m1 instanceof Future1);

const m2 = Future2(noop);
Future1.isFuture(m2) !== (m2 instanceof Future1);
```

#### isForkable
##### `.isForkable :: a -> Boolean`

Returns true for [Forkables](#type-signatures) and false for everything else.

#### cache
##### `.cache :: Future a b -> Future a b`

Returns a Future which caches the resolution value of the given Future so that
whenever it's forked, it can load the value from cache rather than reexecuting
the chain.

```js
const eventualPackage = Future.cache(
  Future.node(done => {
    console.log('Reading some big data');
    fs.readFile('package.json', 'utf8', done)
  })
);

eventualPackage.fork(console.error, console.log);
//> "Reading some big data"
//> "{...}"

eventualPackage.fork(console.error, console.log);
//> "{...}"
```

#### do
##### `.do :: (() -> Iterator) -> Future a b`

A specialized version of [fantasy-do][19] which works only for Futures, but has
the advantage of type-checking and not having to pass `Future.of`. Another
advantage is that the returned Future can be forked multiple times, as opposed
to with a general `fantasy-do` solution, where forking the Future a second time
behaves erroneously.

Takes a function which returns an [Iterator](#type-signatures), commonly a
generator-function, and chains every produced Future over the previous.

This allows for writing sequential asynchronous code without the pyramid of
doom. It's known as "coroutines" in Promise land, and "do-notation" in Haskell
land.

```js
Future.do(function*(){
  const thing = yield Future.after(300, 'world');
  const message = yield Future.after(300, 'Hello ' + thing);
  return message + '!';
})
.fork(console.error, console.log)
//After 600ms:
//> "Hello world!"
```

Error handling is slightly different in do-notation, you need to [`fold`](#fold)
the error into your control domain, I recommend folding into an [`Either`][7]:

```js
const attempt = Future.fold(S.Left, S.Right);
const ajaxGet = url => Future.reject('Failed to load ' + url);
Future.do(function*(){
  const e = yield attempt(ajaxGet('/message'));
  return S.either(
    e => `Oh no! ${e}`,
    x => `Yippee! ${x}`,
    e
  );
})
.fork(console.error, console.log);
//> "Oh no! Failed to load /message"
```

### Sanctuary

When using this module with [Sanctuary Def][31] (and [Sanctuary][21] by
extension) you might run into the following issue:

```js
const S = require('sanctuary');
const Future = require('fluture');
S.I(Future.of(1));
//! Since there is no type of which all the above values are members,
//! the type-variable constraint has been violated.
```

This happens because Sanctuary Def needs to know about the Future type in order
to determine whether the variable types are consistent.

To let Sanctuary know about Futures, we can provide it a `FutureType` using
[`BinaryType`][35] from Sanctuary Def, and pass it to Sanctuary using [`S.create`][32]:

```js
const $ = require('sanctuary-def');
const Future = require('fluture');
const {env, create} = require('sanctuary');

const FutureType = $.BinaryType(
  Future.name,
  'https://github.com/Avaq/Fluture#future',
  Future.isFuture,
  Future.extractLeft,
  Future.extractRight
);

const S = create({checkTypes: true, env: env.concat([FutureType])});

S.I(Future.of(1));
//> Future.of(1)
```

### Futurization

To reduce the boilerplate of making Node or Promise functions return Futures
instead, one might use the [Futurize][6] library:

```js
const Future = require('fluture');
const futurize = require('futurize').futurize(Future);
const readFile = futurize(require('fs').readFile);
readFile('README.md', 'utf8')
.map(text => text.split('\n'))
.map(lines => lines[0])
.fork(console.error, console.log);
//> "# Fluture"
```

## Benchmarks

Simply run `node ./bench/<file>` to see how a specific method compares to
implementations in `data.task`, `ramda-fantasy.Future` and `Promise`*.

\* Promise is not included in all benchmarks because it tends to make the
  process run out of memory.

## Butterfly

The name "Fluture" is a conjunction of "FL" (the acronym to [Fantasy Land][FL])
and "future". Fluture means butterfly in Romanian: A creature you might expect
to see in Fantasy Land.

Credits for the logo go to [Erik Fuente][34].

----

[MIT licensed](LICENSE)

[FL]:  https://github.com/fantasyland/fantasy-land
[FL1]: https://github.com/fantasyland/fantasy-land/tree/v1.0.1
[FL2]: https://github.com/fantasyland/fantasy-land/tree/v2.2.0
[FL3]: https://github.com/fantasyland/fantasy-land

[2]:  http://sanctuary.js.org/#pipe
[3]:  http://ramdajs.com/docs/#map
[4]:  http://ramdajs.com/docs/#chain
[5]:  http://ramdajs.com/docs/#ap
[6]:  https://github.com/futurize/futurize
[7]:  http://sanctuary.js.org/#either-type
[8]:  https://github.com/fantasyland/fantasy-land/pull/124
[9]:  https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch7.html
[10]: https://github.com/folktale/data.task
[11]: https://github.com/ramda/ramda-fantasy
[12]: https://github.com/fantasyland/fantasy-land#functor
[13]: https://github.com/fantasyland/fantasy-land#chain
[14]: https://github.com/fantasyland/fantasy-land#apply
[15]: https://github.com/Avaq/Fluture/wiki/Comparison-of-Future-Implementations
[16]: https://github.com/fantasyland/fantasy-land#applicative
[17]: http://sanctuary.js.org/#is
[18]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator
[19]: https://github.com/russellmcc/fantasydo
[20]: http://ramdajs.com/
[21]: http://sanctuary.js.org/
[22]: https://github.com/Avaq/Fluture/wiki/Comparison-to-Promises
[23]: https://vimeo.com/106008027
[24]: https://github.com/fantasyland/fantasy-land#bifunctor
[25]: https://github.com/rpominov/static-land
[26]: https://github.com/fantasyland/fantasy-land#chainrec
[27]: https://github.com/sanctuary-js/sanctuary-type-classes#Functor
[28]: https://github.com/sanctuary-js/sanctuary-type-classes#Bifunctor
[29]: https://github.com/sanctuary-js/sanctuary-type-classes#Chain
[30]: https://github.com/sanctuary-js/sanctuary-type-classes#Apply
[31]: https://github.com/sanctuary-js/sanctuary-def
[32]: https://sanctuary.js.org/#create
[33]: https://promisesaplus.com/
[34]: http://erikfuente.com/
[35]: https://github.com/sanctuary-js/sanctuary-def#BinaryType


text:
import unittest

import mock
import webapp2
import webtest

from dashboard import bisect_stats
from dashboard.common import testing_common

class BisectStatsTest(testing_common.TestCase):

  def setUp(self):
    super(BisectStatsTest, self).setUp()
    app = webapp2.WSGIApplication(
        [('/bisect_stats', bisect_stats.BisectStatsHandler)])
    self.testapp = webtest.TestApp(app)

  @mock.patch.object(
      bisect_stats, '_GetLastMondayTimestamp',
      mock.MagicMock(return_value=1407110400000))
  def testGet(self):
    bisect_stats.UpdateBisectStats('win_bot', 'failed')
    bisect_stats.UpdateBisectStats('win_bot', 'failed')
    bisect_stats.UpdateBisectStats('win_bot', 'completed')
    bisect_stats.UpdateBisectStats('win_bot', 'completed')
    bisect_stats.UpdateBisectStats('linux_bot', 'failed')
    bisect_stats.UpdateBisectStats('linux_bot', 'completed')
    bisect_stats.UpdateBisectStats('mac_bot', 'completed')

    expected_series_data = {
        'completed': {
            'linux': [[1407110400000, 1]],
            'mac': [[1407110400000, 1]],
            'win': [[1407110400000, 2]],
        },
        'failed': {
            'linux': [[1407110400000, 1]],
            'win': [[1407110400000, 2]],
        },
    }

    expected_total_series_data = {
        'completed': [[1407110400000, 4]],
        'failed': [[1407110400000, 3]],
    }

    response = self.testapp.get('/bisect_stats')
    series_data = self.GetEmbeddedVariable(response, 'SERIES_DATA')
    total_series_data = self.GetEmbeddedVariable(
        response, 'TOTAL_SERIES_DATA')

    self.assertEqual(expected_series_data, series_data)
    self.assertEqual(expected_total_series_data, total_series_data)

if __name__ == '__main__':
  unittest.main()


text:
#include "core/dom/TreeScopeStyleSheetCollection.h"

#include "core/css/ActiveStyleSheets.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/StyleRuleImport.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Element.h"
#include "core/dom/StyleEngine.h"
#include "core/html/HTMLLinkElement.h"
#include "core/html/HTMLStyleElement.h"

namespace blink {

TreeScopeStyleSheetCollection::TreeScopeStyleSheetCollection(
    TreeScope& treeScope)
    : m_treeScope(treeScope) {}

void TreeScopeStyleSheetCollection::addStyleSheetCandidateNode(Node& node) {
  if (node.isConnected())
    m_styleSheetCandidateNodes.add(&node);
}

bool TreeScopeStyleSheetCollection::mediaQueryAffectingValueChanged() {
  bool needsActiveStyleUpdate = false;
  for (const auto& activeSheet : m_activeAuthorStyleSheets) {
    if (activeSheet.first->mediaQueries())
      needsActiveStyleUpdate = true;
    StyleSheetContents* contents = activeSheet.first->contents();
    if (contents->hasMediaQueries())
      contents->clearRuleSet();
  }
  return needsActiveStyleUpdate;
}

void TreeScopeStyleSheetCollection::applyActiveStyleSheetChanges(
    StyleSheetCollection& newCollection) {
  document().styleEngine().applyRuleSetChanges(
      treeScope(), activeAuthorStyleSheets(),
      newCollection.activeAuthorStyleSheets());
  newCollection.swap(*this);
}

DEFINE_TRACE(TreeScopeStyleSheetCollection) {
  visitor->trace(m_treeScope);
  visitor->trace(m_styleSheetCandidateNodes);
  StyleSheetCollection::trace(visitor);
}

}  // namespace blink


text:
package com.sematext.solr.handler.component.relaxer.query;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.DisMaxQParser;
import org.apache.solr.search.SyntaxError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 *
 * {@link QueryConverter} that converts query to a list of {@link Clause}s.
 *
 * @author sematext, http://www.sematext.com/
 */
public class EdismaxQueryConverter extends QueryConverter {
  private static final Logger LOG = LoggerFactory.getLogger(EdismaxQueryConverter.class);

  @Override
  public List<Clause> convert(String query, SolrQueryRequest req) {
    try {
      Map<String, Float> queryFields = DisMaxQParser.parseQueryFields(req.getSchema(), req.getParams());
      return splitIntoClauses(query, queryFields.keySet(), false);
    } catch (SyntaxError e) {
      throw new RuntimeException();
    }
  }

  private List<Clause> splitIntoClauses(String s, Set<String> defaultFields, boolean ignoreQuote) {
    ArrayList<Clause> lst = new ArrayList<Clause>(4);
    Clause clause;

    int pos = 0;
    int end = s.length();
    char ch = 0;
    int start;
    boolean disallowUserField;
    while (pos < end) {
      clause = new Clause();
      disallowUserField = true;

      ch = s.charAt(pos);

      while (Character.isWhitespace(ch)) {
        if (++pos >= end)
          break;
        ch = s.charAt(pos);
      }

      start = pos;

      if (ch == '+' || ch == '-') {
        clause.must = ch;
        pos++;
      }

      clause.field = getFieldName(s, pos, end);
      if (clause.field != null) {
        disallowUserField = false;
        int colon = s.indexOf(':', pos);
        clause.rawField = s.substring(pos, colon);
        pos += colon - pos; // skip the field name
        pos++; // skip the ':'
      }

      if (pos >= end)
        break;

      char inString = 0;

      ch = s.charAt(pos);
      if (!ignoreQuote && ch == '"') {
        clause.isPhrase = true;
        inString = '"';
        pos++;
      }

      StringBuilder sb = new StringBuilder();
      while (pos < end) {
        ch = s.charAt(pos++);
        if (ch == '\\') { // skip escaped chars, but leave escaped
          sb.append(ch);
          if (pos >= end) {
            sb.append(ch); // double backslash if we are at the end of the string
            break;
          }
          ch = s.charAt(pos++);
          sb.append(ch);
          continue;
        } else if (inString != 0 && ch == inString) {
          inString = 0;
          break;
        } else if (Character.isWhitespace(ch)) {
          clause.hasWhitespace = true;
          if (inString == 0) {
            // end of the token if we aren't in a string, backing
            // up the position.
            pos--;
            break;
          }
        }

        if (inString == 0) {
          switch (ch) {
            case '!':
            case '(':
            case ')':
            case ':':
            case '^':
            case '[':
            case ']':
            case '{':
            case '}':
            case '~':
            case '*':
            case '?':
            case '"':
            case '+':
            case '-':
            case '\\':
            case '|':
            case '&':
            case '/':
              clause.hasSpecialSyntax = true;
              sb.append('\\');
          }
        } else if (ch == '"') {
          // only char we need to escape in a string is double quote
          sb.append('\\');
        }
        sb.append(ch);
      }

      clause.val = sb.toString();
      Analyzer analyzer = findField(clause.field, defaultFields, getFieldAnalyzerMaps());
      if (analyzer != null) {
        try {
          clause.tokens = analyze(sb.toString(), analyzer);
        } catch (IOException e) {
          LOG.warn("Analysis text:" + sb.toString() + ": failed by " + analyzer.toString(), e);
        }
      }

      if (clause.isPhrase) {
        if (inString != 0) {
          // detected bad quote balancing... retry
          // parsing with quotes like any other char
          return splitIntoClauses(s, defaultFields, true);
        }

        // special syntax in a string isn't special
        clause.hasSpecialSyntax = false;
      } else {
        // an empty clause... must be just a + or - on it's own
        if (clause.val.length() == 0) {
          clause.syntaxError = true;
          if (clause.must != 0) {
            clause.val = "\\" + clause.must;
            clause.must = 0;
            clause.hasSpecialSyntax = true;
          } else {
            // uh.. this shouldn't happen.
            clause = null;
          }
        }
      }

      if (clause != null) {
        if (disallowUserField) {
          clause.raw = s.substring(start, pos);
          // escape colons, except for "match all" query
          if (!"*:*".equals(clause.raw)) {
            clause.raw = clause.raw.replaceAll(":", "\\\\:");
          }
        } else {
          clause.raw = s.substring(start, pos);
        }
        lst.add(clause);
      }
    }

    return lst;
  }

  private Analyzer findField(String field, Set<String> defaultFields, Map<Pattern, Analyzer> fieldAnalyzerMaps) {
    if (fieldAnalyzerMaps != null && !fieldAnalyzerMaps.isEmpty()) {
      if (field == null) {
        if (defaultFields != null) {
          for (String defaultField : defaultFields) {
            Analyzer analyzer = findAnalyzer(defaultField, fieldAnalyzerMaps);
            if (analyzer != null) {
              return analyzer;
            }
          }
        }
      } else {
        return findAnalyzer(field, fieldAnalyzerMaps);
      }

    }

    return null;
  }

  private Analyzer findAnalyzer(String field, Map<Pattern, Analyzer> fieldAnalyzerMaps) {
    for (Pattern pattern : fieldAnalyzerMaps.keySet()) {
      if (pattern.matcher(field).find()) {
        return fieldAnalyzerMaps.get(pattern);
      }
    }
    return null;
  }

  /**
   * returns a field name from the current position of the string
   */
  private String getFieldName(String s, int pos, int end) {
    if (pos >= end)
      return null;
    int p = pos;
    int colon = s.indexOf(':', pos);
    // make sure there is space after the colon, but not whitespace
    if (colon <= pos || colon + 1 >= end || Character.isWhitespace(s.charAt(colon + 1)))
      return null;
    char ch = s.charAt(p++);
    while ((ch == '(' || ch == '+' || ch == '-') && (pos < end)) {
      ch = s.charAt(p++);
      pos++;
    }
    if (!Character.isJavaIdentifierPart(ch))
      return null;
    while (p < colon) {
      ch = s.charAt(p++);
      if (!(Character.isJavaIdentifierPart(ch) || ch == '-' || ch == '.'))
        return null;
    }
    String fname = s.substring(pos, p);

    return fname;
  }

  protected String[] analyze(String text, Analyzer analyzer) throws IOException {
    List<String> result = new ArrayList<String>();
    TokenStream stream = analyzer.tokenStream("", new StringReader(text));
    CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
    stream.reset();
    while (stream.incrementToken()) {
      result.add(new String(termAtt.buffer(), 0, termAtt.length()));
    }
    stream.end();
    stream.close();

    return result.toArray(new String[result.size()]);
  }
}