text:
<script src="../../resources/testharness.js"></script>
<script src="../../resources/get-host-info.js?pipe=sub"></script>
<script src="test-helpers.js"></script>
<script>
var host_info = get_host_info();

function get_boundary(headers) {
  var reg = new RegExp('multipart\/form-data; boundary=(.*)');
  for (var i = 0; i < headers.length; ++i) {
    if (headers[i][0] != 'content-type') {
      continue;
    }
    var regResult = reg.exec(headers[i][1]);
    if (!regResult) {
      continue;
    }
    return regResult[1];
  }
  return '';
}

function create_file_system_file(file_name, data) {
  return new Promise(function(resolve, reject) {
      webkitRequestFileSystem(TEMPORARY, 1024, function(fs) {
          fs.root.getFile(
            file_name, {create: true, exclusive: true},
            function(fileEntry) {
              fileEntry.createWriter(function(fileWriter) {
                  fileWriter.onwriteend = function(e) {
                    fileEntry.file(function(file) { resolve(file); });
                  };
                  var blob = new Blob([data], {type: 'text/plain'});
                  fileWriter.write(blob);
                });
            }, function(e) { reject(e); });
        }, function(e) { reject(e); });
    });
}

function xhr_send(url_base, method, data, with_credentials) {
  return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest();
      xhr.onload = function() {
        resolve(JSON.parse(xhr.response));
      };
      xhr.onerror = function() {
        reject('XHR should succeed.');
      };
      xhr.responseType = 'text';
      if (with_credentials) {
        xhr.withCredentials = true;
      }
      xhr.open(method, url_base + '/dummy?test', true);
      xhr.send(data);
    });
}

function string_test() {
  return xhr_send(host_info['HTTP_ORIGIN'], 'POST', 'test string', false)
    .then(function(response) {
        assert_equals(response.method, 'POST');
        assert_equals(response.body, 'test string');
      });
}

function blob_test() {
  return xhr_send(host_info['HTTP_ORIGIN'], 'POST', new Blob(['test blob']),
                  false)
    .then(function(response) {
        assert_equals(response.method, 'POST');
        assert_equals(response.body, 'test blob');
      });
}

function custom_method_test() {
  return xhr_send(host_info['HTTP_ORIGIN'], 'XXX', 'test string xxx', false)
    .then(function(response) {
        assert_equals(response.method, 'XXX');
        assert_equals(response.body, 'test string xxx');
      });
}

function options_method_test() {
  return xhr_send(host_info['HTTP_ORIGIN'], 'OPTIONS', 'test string xxx', false)
    .then(function(response) {
        assert_equals(response.method, 'OPTIONS');
        assert_equals(response.body, 'test string xxx');
      });
}

function form_data_test() {
  return create_file_system_file('fsfile.txt', 'fs file content')
    .then(function(file_system_file) {
        var formData = new FormData();
        formData.append('sample string', '1234567890');
        formData.append('sample blob', new Blob(['blob content']));
        formData.append('sample file', new File(['file content'], 'file.dat'));
        formData.append('sample fs file', file_system_file);
        return xhr_send(host_info['HTTP_ORIGIN'], 'POST', formData, false);
      })
    .then(function(response) {
        assert_equals(response.method, 'POST');
        var boundary = get_boundary(response.headers);
        var expected_body =
          '--' + boundary + '\r\n' +
          'Content-Disposition: form-data; name="sample string"\r\n' +
          '\r\n' +
          '1234567890\r\n' +
          '--' + boundary + '\r\n' +
          'Content-Disposition: form-data; name="sample blob"; ' +
          'filename="blob"\r\n' +
          'Content-Type: application/octet-stream\r\n' +
          '\r\n' +
          'blob content\r\n' +
          '--' + boundary + '\r\n' +
          'Content-Disposition: form-data; name="sample file"; ' +
          'filename="file.dat"\r\n' +
          'Content-Type: application/octet-stream\r\n' +
          '\r\n' +
          'file content\r\n' +
          '--' + boundary + '\r\n' +
          'Content-Disposition: form-data; name="sample fs file"; ' +
          'filename="fsfile.txt"\r\n' +
          'Content-Type: text/plain\r\n' +
          '\r\n' +
          'fs file content\r\n' +
          '--' + boundary + '--\r\n';
        assert_equals(response.body, expected_body);
      });
}

function mode_credentials_test() {
  return xhr_send(host_info['HTTP_ORIGIN'], 'GET', '', false)
    .then(function(response){
        assert_equals(response.mode, 'cors');
        assert_equals(response.credentials, 'include');
        return xhr_send(host_info['HTTP_ORIGIN'], 'GET', '', true);
      })
    .then(function(response){
        assert_equals(response.mode, 'cors');
        assert_equals(response.credentials, 'include');
        return xhr_send(host_info['HTTP_REMOTE_ORIGIN'], 'GET', '', false);
      })
    .then(function(response){
        assert_equals(response.mode, 'cors');
        assert_equals(response.credentials, 'same-origin');
        return xhr_send(host_info['HTTP_REMOTE_ORIGIN'], 'GET', '', true);
      })
    .then(function(response){
        assert_equals(response.mode, 'cors');
        assert_equals(response.credentials, 'include');
      });
}

function data_url_test() {
  return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.onload = function() {
          resolve(xhr.response);
        };
        xhr.onerror = function() {
          reject('XHR should succeed.');
        };
        xhr.responseType = 'text';
        xhr.open('GET', 'data:text/html,Foobar', true);
        xhr.send();
      })
    .then(function(data) {
        assert_equals(data, 'Foobar');
      });
}

window.addEventListener('message', function(evt) {
    var port = evt.ports[0];
    string_test()
      .then(blob_test)
      .then(custom_method_test)
      .then(options_method_test)
      .then(form_data_test)
      .then(mode_credentials_test)
      .then(data_url_test)
      .then(function() { port.postMessage({results: 'finish'}); })
      .catch(function(e) { port.postMessage({results: 'failure:' + e}); });
  });
</script>


text:
layout: post
title: Atomic variables
description: How to implement Atomic counter in java, using atomic variables in Java
comments: true
categories:
- Java
tags:
- Java
author: sureshsajja
---

This post will demonstrate how to code wait-free, lock-free programming using Atomic variable classes that were added to JDK1.5.

The traditional way to coordinate access to shared fields in the Java language is to use synchronization, ensuring that all access to shared fields is done holding the appropriate lock. With synchronization, you are assured that whichever thread holds the lock that protects a given set of variables will have exclusive access to those variables, and changes to those variables will become visible to other threads when they subsequently acquire the lock.

Before JDK1.5, if we want to build a thread safe counter with get(), increment(), decrement() methods, each method needs to be synchronized to ensure that no updates are lost, and that all threads see the most recent value of the counter.

#### Example code

{% gist 949fdd412e14b8966f6a91a5fd18d614 %}

### But What's wrong with traditional approach

To execute any method, each thread has to acquire lock on object first.
If the lock is heavily contended (threads frequently ask to acquire the lock when it is already held by another thread), throughput can suffer, as contended synchronization can be quite expensive.

Another problem with lock-based algorithms is that if a thread holding a lock is delayed (due to a page fault, scheduling delay, or other unexpected delay), then no thread requiring that lock may make progress.

### Atomic Variables

In JDK5.0, a set of toolkit classes are introduced (java.util.concurrent.atomic) to support wait-free, lock-free programming
The atomic variable classes can be thought of as a generalization of volatile variables, extending the concept of volatile variables to support atomic conditional compare-and-set updates.
Reads and writes of atomic variables have the same memory semantics as read and write access to volatile variables.Operations on atomic variables get turned into the hardware primitives that the platform provides for concurrent access, such as compare-and-set.

For more information read package description [here](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#package_description)

#### Example code using AtomicInteger

{% gist 03f29e54153e8e9bdcdb6ea78c793501 %}

redpajama_set_name: RedPajamaGithub


text:
--TEST--
Test session_set_save_handler() function : error functionality
--INI--
session.save_path=
session.name=PHPSESSID
--SKIPIF--
<?php include('skipif.inc'); ?>
--FILE--
<?php

ob_start();

/*
 * Prototype : bool session_set_save_handler(callback $open, callback $close, callback $read, callback $write, callback $destroy, callback $gc)
 * Description : Sets user-level session storage functions
 * Source code : ext/session/session.c
 */

echo "*** Testing session_set_save_handler() : error functionality ***\n";
function open($save_path, $session_name) {
     throw new Exception("Do something bad..!");
}

function close() { return true; }
function read($id) { return false; }
function write($id, $session_data) { }
function destroy($id) {  return true; }
function gc($maxlifetime) {  return true; }

session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
session_start();
ob_end_flush();
?>
--EXPECTF--
*** Testing session_set_save_handler() : error functionality ***

Fatal error: Uncaught exception 'Exception' with message 'Do something bad..!' in %s:%d
Stack trace:
#0 [internal function]: open('', 'PHPSESSID')
#1 %s(%d): session_start()
#2 {main}
  thrown in %s on line %d


text:
from __future__ import unicode_literals

import django.core.validators
from django.db import migrations, models
import django.utils.timezone

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0008_alter_user_username_max_length'),
    ]

    operations = [
        migrations.CreateModel(
            name='Account',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),
                ('username', models.CharField(help_text='Required. 30 characters or fewer. Letters, digits and ./+/-/_ only.', max_length=30, validators=[django.core.validators.RegexValidator('^[\\w.+-]+$', 'Enter a valid username.', 'invalid')], verbose_name='username')),
                ('description', models.CharField(blank=True, help_text='User introduction', max_length=300, verbose_name='description')),
                ('language', models.CharField(default='en', max_length=5, verbose_name='language')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
            ],
            options={
                'verbose_name': 'user',
                'verbose_name_plural': 'users',
                'swappable': 'AUTH_USER_MODEL',
            },
        ),
    ]


text:
@(params: Map[String,Any])
@uk.gov.hmrc.hmrcemailrenderer.templates.helpers.html.template_main(params,s"Successful Receipt of Online Submission for Reference ${params("identifier")}") {

Thank you for sending the PAYE Works Number Update submission online.

The submission for reference @params("identifier") was successfully received on @params("receivedDate") and is being processed.

PAYE Works Number Update Online is just one of the many online services we offer that can save you time and paperwork.For the latest information on all of our Online Services please visit the HMRC website.

}


text:
/**
 * 实体转换缓存
 */
package com.baomidou.hibernateplus.converter.config;


text:
<!-- end warper-->

<!-- jQuery -->
<!--<script src="//code.jquery.com/jquery-1.12.4.js"></script>-->

<script src="<?php echo base_url(); ?>asset/vendor/jquery/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url(); ?>asset/vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- DataTables JavaScript -->
<script src="<?php echo base_url(); ?>asset/vendor/datatables/js/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url(); ?>asset/vendor/datatables-plugins/dataTables.bootstrap.min.js"></script>

<script src="<?php echo base_url(); ?>asset/vendor/datatables-responsive/dataTables.responsive.js"></script>
<!--Custom Theme JavaScript -->
<!--<script src="<?php //echo base_url();     ?>asset/dist/js/sb-admin-2.js"></script>-->
<!-- bootstrap js select-->
<script src="<?php echo base_url(); ?>asset/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>

<script>

    $(function () {

        // We can attach the `fileselect` event to all file inputs on the page
        $(document).on('change', ':file', function () {
            var input = $(this),
                    numFiles = input.get(0).files ? input.get(0).files.length : 1,
                    label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
            input.trigger('fileselect', [numFiles, label]);
        });

        // We can watch for our custom `fileselect` event like this
        $(document).ready(function () {
            $(':file').on('fileselect', function (event, numFiles, label) {

                var input = $(this).parents('.input-group').find(':text'),
                        log = numFiles > 1 ? numFiles + ' files selected' : label;

                if (input.length) {
                    input.val(log);
                } else {
                    if (log)
                        alert(log);
                }

            });
        });

    });

    function ajaxFunction(typeUser) {
        var keyUser = $("#colInModal1").val();
        var newPass = $('#colInModal2').val();

        $.ajax({
            url: '<?php echo base_url(); ?>index.php/MainController/editPass/' + typeUser + '/' + keyUser + '/' + newPass,
            type: 'POST',
            success: function () {
                alert('เปลี่ยนรหัสผ่านแล้ว');
                $('#modalChangePass').modal('hide');
                //the response variable will hold anything that is written in that php file(in html) and anything you echo in that file
            }
        });
        return false;
    }

    $(document).ready(function () {
        $("#form-password").submit(function (event) {
            event.preventDefault();
            $.ajax({
                url: "<?php echo base_url(); ?>index.php/MainController/editPass",
                type: "POST"
            });
        });
    });

    $('#changePass').on('click', function () {
        $("#colInModal1").val($('#col0').val());
    });
    $('#usersTDetail tbody').on('click', 'tr', function () {
        $("#tModal").modal("show");
        $("#col0").val($(this).closest('tr').children()[0].textContent);
        $("#col1").val($(this).closest('tr').children()[1].textContent);
        $("#col2").val($(this).closest('tr').children()[2].textContent);
        $("#col3").val($(this).closest('tr').children()[3].textContent);
        $("#col4").val($(this).closest('tr').children()[4].textContent);
        $("#col6").val($(this).closest('tr').children()[5].textContent);
        if ($(this).closest('tr').children()[6].textContent == 'มีสิทธ์') {
            $("#License").val('H');
        } else {
            $("#License").val('NH');
        }

    });

    $('#usersSDetail tbody').on('click', 'tr', function () {
        $("#sModal").modal("show");
        $("#col0").val($(this).closest('tr').children()[0].textContent);
        $("#col1").val($(this).closest('tr').children()[1].textContent);
        $("#col2").val($(this).closest('tr').children()[2].textContent);
        $("#col3").val($(this).closest('tr').children()[3].textContent);
        $("#col4").val($(this).closest('tr').children()[4].textContent);
        $("#col5").val($(this).closest('tr').children()[5].textContent);
        $("#col6").val($(this).closest('tr').children()[6].textContent);
        if ($(this).closest('tr').children()[7].textContent == 'มีสิทธ์') {
            $("#License").val('H');
        } else {
            $("#License").val('NH');
        }
    });

    function allowText(index) {
        var checkbox = document.getElementById('fancy-checkbox-primary' + index);
        document.getElementById('inputText' + index).disabled = !checkbox.checked;
        if (checkbox.checked) {
            document.getElementById('inputText' + index).value = 1;
        } else {
            document.getElementById('inputText' + index).value = '';
        }
    }

    $(document).ready(function () {
        $('#dataTables').DataTable({
            responsive: true
        });
    });
    function maxLengthCheck(object)
    {
        if (object.value.length > object.maxLength)
            object.value = object.value.slice(0, object.maxLength)
    }
    function testMC(n) {
        var ansT1 = document.getElementById('ansT1');
        var ansT2 = document.getElementById('ansT2');
        var ansT3 = document.getElementById('ansT3');
        var ansT4 = document.getElementById('ansT4');
        var x1 = document.getElementById('C1');
        var x2 = document.getElementById('C2');
        var x3 = document.getElementById('C3');
        var x4 = document.getElementById('C4');

        if (n == 1) {
            document.getElementById('ans1').textContent = 'ถูก';
            document.getElementById('ans2').textContent = 'ผิด';
            document.getElementById('ans3').textContent = 'ผิด';
            document.getElementById('ans4').textContent = 'ผิด';

            ansT1.style.background = '#98FB98';
            ansT2.style.background = '#FFFFFF';
            ansT3.style.background = '#FFFFFF';
            ansT4.style.background = '#FFFFFF';

            x1.value = 'ถูก';
            x2.value = 'ผิด';
            x3.value = 'ผิด';
            x4.value = 'ผิด';
        } else if (n == 2) {
            document.getElementById('ans1').textContent = 'ผิด';
            document.getElementById('ans2').textContent = 'ถูก';
            document.getElementById('ans3').textContent = 'ผิด';
            document.getElementById('ans4').textContent = 'ผิด';

            ansT1.style.background = '#FFFFFF';
            ansT2.style.background = '#98FB98';
            ansT3.style.background = '#FFFFFF';
            ansT4.style.background = '#FFFFFF';

            x1.value = 'ผิด';
            x2.value = 'ถูก';
            x3.value = 'ผิด';
            x4.value = 'ผิด';
        } else if (n == 3) {
            document.getElementById('ans1').textContent = 'ผิด';
            document.getElementById('ans2').textContent = 'ผิด';
            document.getElementById('ans3').textContent = 'ถูก';
            document.getElementById('ans4').textContent = 'ผิด';

            ansT1.style.background = '#FFFFFF';
            ansT2.style.background = '#FFFFFF';
            ansT3.style.background = '#98FB98';
            ansT4.style.background = '#FFFFFF';

            x1.value = 'ผิด';
            x2.value = 'ผิด';
            x3.value = 'ถูก';
            x4.value = 'ผิด';
        } else {
            document.getElementById('ans1').textContent = 'ผิด';
            document.getElementById('ans2').textContent = 'ผิด';
            document.getElementById('ans3').textContent = 'ผิด';
            document.getElementById('ans4').textContent = 'ถูก';

            ansT1.style.background = '#FFFFFF';
            ansT2.style.background = '#FFFFFF';
            ansT3.style.background = '#FFFFFF';
            ansT4.style.background = '#98FB98';

            x1.value = 'ผิด';
            x2.value = 'ผิด';
            x3.value = 'ผิด';
            x4.value = 'ถูก';
        }
    }

    function goBack() {
        window.history.back();
    }

    function testTF(n) {
        var z = document.getElementById('btn1');
        var x = document.getElementById('btn2');
        var a = document.getElementById('TF1');
        var b = document.getElementById('TF2');
        if (n == 1) {
            z.style.background = '#98FB98';
            x.style.background = '#E4FDDD';
            a.value = 'ถูก';
            b.value = 'ผิด';
        } else {
            x.style.background = '#98FB98';
            z.style.background = '#E4FDDD';
            a.value = 'ผิด';
            b.value = 'ถูก';
        }

    }

//    function Counter(options) {
//        var timer;
//        var instance = this;
//        var seconds = options.seconds;
//        var min = options.min;
//        var onUpdateStatus = options.onUpdateStatus || function() {};
//        var onCounterEnd = options.onCounterEnd || function() {};
//        var onCounterStart = options.onCounterStart || function() {};
//
//        function decrementCounter() {
//                onUpdateStatus(min,seconds);
//                if (seconds === 0 & min === 0) {
//                    stopCounter();
//                    onCounterEnd();
//                    return;
//                }
//                if (seconds <= 0) {
//                    seconds = 60;
//                    min -= 1;
//                }
//                if (min <= -1) {
//                    seconds = 0;
//                    min += 1;
//                } else {
//                    seconds--;
//                }
//
//        };
//
//        function startCounter() {
//            onCounterStart();
//            clearInterval(timer);
//            timer = 0;
//            decrementCounter();
//            timer = setInterval(decrementCounter, 1000);
//        };
//
//        function stopCounter() {
//            clearInterval(timer);
//        };
//
//        return {
//            start: function () {
//                startCounter();
//            },
//            stop: function () {
//                stopCounter();
//            }
//        };
//    };

// Page-Level Demo Scripts - Tables - Use for reference

</script>
<!--<script>
    var countdown = new Counter({
    // number of seconds to count down
    min: 5,
    seconds: 0,

    onCounterStart: function () {
        //alert('begin');
    },

    // callback function for each second
    onUpdateStatus: function(min,second) {
         document.getElementById('d2').value = min+"."+second;
        // change the UI that displays the seconds remaining in the timeout
    },

    // callback function for final action after countdown
    onCounterEnd: function() {
        //alert('end');
        //window.location = '<?php echo base_url(); ?>index.php/MainController';
    }
    });
countdown.start();
</script>-->

</body>
</html>


text:
package eu.dnetlib.iis.wf.citationmatching;

import com.google.common.collect.Lists;
import eu.dnetlib.iis.citationmatching.schemas.BasicMetadata;
import eu.dnetlib.iis.citationmatching.schemas.DocumentMetadata;
import eu.dnetlib.iis.citationmatching.schemas.ReferenceMetadata;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapreduce.AvroKeyInputFormat;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import scala.Tuple2;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.*;

/**
 * @author madryk
 */
@ExtendWith(MockitoExtension.class)
public class ReferenceMetadataInputReaderTest {

    private ReferenceMetadataInputReader referenceMetadataInputReader = new ReferenceMetadataInputReader();

    @Mock
    private JavaSparkContext sparkContext;

    @Mock
    private JavaPairRDD<AvroKey<DocumentMetadata>, NullWritable> inputRecords;

    @Mock
    private JavaRDD<DocumentMetadata> documents;

    @Mock
    private JavaPairRDD<String, ReferenceMetadata> citations;

    @Captor
    private ArgumentCaptor<PairFlatMapFunction<DocumentMetadata, String, ReferenceMetadata>> documentToCitationsFunction;

    //------------------------ TESTS --------------------------

    @SuppressWarnings("unchecked")
    @Test
    public void readCitations() throws Exception {

        // given
        doReturn(inputRecords).when(sparkContext).newAPIHadoopFile(any(), any(), any(), any(), any());
        doReturn(documents).when(inputRecords).map(any());

        doReturn(citations).when(documents).flatMapToPair(any());

        // execute
        JavaPairRDD<String, ReferenceMetadata> retCitations = referenceMetadataInputReader.readCitations(sparkContext, "/some/path");

        // assert
        assertSame(retCitations, citations);
        verify(sparkContext).newAPIHadoopFile(
                eq("/some/path"), eq(AvroKeyInputFormat.class),
                eq(DocumentMetadata.class), eq(NullWritable.class),
                isA(Configuration.class));
        verify(documents).flatMapToPair(documentToCitationsFunction.capture());
        assertDocToCitationsFunction(documentToCitationsFunction.getValue());
    }

    //------------------------ PRIVATE --------------------------

    private void assertDocToCitationsFunction(PairFlatMapFunction<DocumentMetadata, String, ReferenceMetadata> function) throws Exception {
        ReferenceMetadata refMetadata1 = ReferenceMetadata.newBuilder().setPosition(3).setBasicMetadata(new BasicMetadata()).build();
        ReferenceMetadata refMetadata2 = ReferenceMetadata.newBuilder().setPosition(5).setBasicMetadata(new BasicMetadata()).build();
        ReferenceMetadata refMetadata3 = ReferenceMetadata.newBuilder().setPosition(6).setBasicMetadata(new BasicMetadata()).build();

        DocumentMetadata docMetadata = DocumentMetadata.newBuilder()
                .setId("someId")
                .setBasicMetadata(new BasicMetadata())
                .setReferences(Lists.newArrayList(refMetadata1, refMetadata2, refMetadata3))
                .build();

        Iterable<Tuple2<String, ReferenceMetadata>> retCitations = function.call(docMetadata);

        List<Tuple2<String, ReferenceMetadata>> retCitationsList = Lists.newArrayList(retCitations);
        assertEquals(3, retCitationsList.size());

        assertEquals("cit_someId_3", retCitationsList.get(0)._1);
        assertSame(retCitationsList.get(0)._2, refMetadata1);

        assertEquals("cit_someId_5", retCitationsList.get(1)._1);
        assertSame(retCitationsList.get(1)._2, refMetadata2);

        assertEquals("cit_someId_6", retCitationsList.get(2)._1);
        assertSame(retCitationsList.get(2)._2, refMetadata3);
    }
}


text:
#ifndef __CONVERT_JSON_H__
#define __CONVERT_JSON_H__

#include "json/json.h"

struct ModStoreMod;
struct ModStoreModDetails;

std::vector<ModStoreMod>    readModStoreList(Json::Value& modlist);
ModStoreModDetails          readModStoreModDetails(Json::Value& details);

Json::Value                 fetchJsonValue(const std::string &url,
                                           std::vector<std::string> *extra_headers);

#endif


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29920_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">GAS CAPTURE PLAN AFFIDAVIT

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">STATE OF TEXAS

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">COUNTY OF HARRIS

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Robert Eason, being duly sworn, states as follows:

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">He is employed by Oasis Petroleum North America LLC ("Oasis") as Marketing
Manager, is over the age of 21 and has personal knowledge of the matters set forth in this affidavit.
This affidavit is submitted in conjunction with the Application for Permit to Drill for the O M Erickson 5501 43-7 4B well, with a surface location in the NW NW of Section 18, Township 155 North, Range 101 West, Williams County, North Dakota (the "Well").
Oasis currently anticipates that gas to be produced from the Well will be gathered by Hiland Partners (the "Gathering Company"). Oasis has advised the Gathering Company of its intent to drill the Well and has advised the Gathering Company that it currently anticipates that the Well will be completed in October 2015, with an initial gas production rate of approximately 507 mcf/day.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Ganja",
Robert H. Eason Marketing Manager

    <p class="styleSans79.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Subscribed and sworn to before me this

dayof; ital)! ,2014.
Notary Public in and for the State of Texas MANDINA BARRON . . .. . Notg§y Public, State of Iexos My Commlssmn expues.
My Commission Expiies June 05. 2018

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">000

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
service apache2 restart
service mysql restart

# Start cachefilesd service.
# Note: Two attempts are made to start the service,
# as the first attempt may not succeed.
systemctl stop cachefilesd
if ! ps ax | grep -v grep | grep cachefilesd > /dev/null
then
    systemctl start cachefilesd
    if ! ps ax | grep -v grep | grep cachefilesd > /dev/null
    then
        systemctl stop cachefilesd
        systemctl start cachefilesd
    fi
fi


text:
import os
import io
from setuptools import setup, find_packages

cwd = os.path.abspath(os.path.dirname(__file__))

with io.open(os.path.join(cwd, 'README.rst'), encoding='utf-8') as fd:
    long_description = fd.read()

setup(
    name='configuration',
    version='0.4.1',
    description=('Thin wrapper around PyYAML that allows you to '
                 'access values in dot notation config.value...'),
    long_description=long_description,
    url='https://github.com/Digitalxero/configuration',
    author='Dj Gilcrease',
    author_email='digitalxero',
    license='BSD',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Topic :: Utilities',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
    ],
    keywords=('yaml config configuration'),
    packages=find_packages(),
    install_requires=['PyYAML']
)


text:
import { VariablesProvider } from './variablesProvider';
import { VariableAdapter } from './variable';
import { FrameAdapter } from './frame';
import { ThreadAdapter } from './thread';
import { ObjectGripActorProxy } from '../firefox/actorProxy/objectGrip';

/**
 * Adapter class for a javascript object.
 */
export class ObjectGripAdapter implements VariablesProvider {

	public readonly variablesProviderId: number;
	public readonly actor: ObjectGripActorProxy;
	public get threadAdapter(): ThreadAdapter {
		return this.variableAdapter.threadAdapter;
	}
	/** a javascript expression for accessing the object represented by this adapter */
	public get referenceExpression(): string | undefined {
		return this.variableAdapter.referenceExpression;
	}
	/** the stackframe to use when executing the `referenceExpression` */
	public get referenceFrame(): FrameAdapter | undefined {
		return this.variableAdapter.referenceFrame;
	}

	public constructor(
		private readonly variableAdapter: VariableAdapter,
		objectGrip: FirefoxDebugProtocol.ObjectGrip,
		public threadLifetime: boolean,
		private readonly isPrototype: boolean
	) {
		this.actor = this.threadAdapter.debugSession.getOrCreateObjectGripActorProxy(objectGrip);
		this.actor.increaseRefCount();
		this.variablesProviderId = this.threadAdapter.debugSession.variablesProviders.register(this);
		this.threadAdapter.registerObjectGripAdapter(this);
	}

	/**
	 * get the referenced object's properties and its prototype as an array of Variables.
	 * This method can only be called when the thread is paused.
	 */
	public async getVariables(): Promise<VariableAdapter[]> {

		let prototypeAndProperties = await this.threadAdapter.coordinator.runOnPausedThread(
			() => this.actor.fetchPrototypeAndProperties());

		let variables: VariableAdapter[] = [];
		let symbolVariables: VariableAdapter[] = [];
		let safeGetterValues = prototypeAndProperties.safeGetterValues || {};
		let symbolProperties = prototypeAndProperties.ownSymbols || [];

		for (let varname in prototypeAndProperties.ownProperties) {
			if (!safeGetterValues[varname]) {
				variables.push(VariableAdapter.fromPropertyDescriptor(
					varname, this.referenceExpression, this.referenceFrame,
					prototypeAndProperties.ownProperties[varname],
					this.threadLifetime, this.threadAdapter));
			}
		}

		for (let varname in safeGetterValues) {
			variables.push(VariableAdapter.fromSafeGetterValueDescriptor(
				varname, this.referenceExpression, this.referenceFrame,
				safeGetterValues[varname],
				this.threadLifetime, this.threadAdapter));
		}

		for (let symbolProperty of symbolProperties) {
			symbolVariables.push(VariableAdapter.fromPropertyDescriptor(
				symbolProperty.name, undefined, undefined,
				symbolProperty.descriptor, this.threadLifetime, this.threadAdapter));
		}

		let prototypeVariable: VariableAdapter | undefined = undefined;
		let accessorsFromPrototypes: VariableAdapter[] = [];
		if (prototypeAndProperties.prototype.type !== 'null') {
			prototypeVariable = VariableAdapter.fromGrip(
				'__proto__', this.referenceExpression, this.referenceFrame,
				prototypeAndProperties.prototype,
				this.threadLifetime, this.threadAdapter
			);

			if (!this.isPrototype) {
				const prototypeLevels = this.threadAdapter.debugSession.config.liftAccessorsFromPrototypes;
				if (prototypeLevels > 0) {
					accessorsFromPrototypes = await this.fetchAccessorsFromPrototypes(prototypeVariable, prototypeLevels);
				}
			}
		}

		VariableAdapter.sortVariables(variables);
		VariableAdapter.sortVariables(symbolVariables);
		VariableAdapter.sortVariables(accessorsFromPrototypes);
		variables.push(...symbolVariables);
		variables.push(...accessorsFromPrototypes);

		if (prototypeVariable) {
			variables.push(prototypeVariable);
		}

		return variables;
	}

	/**
	 * used to "lift" accessor properties from the prototype chain to an object if the
	 * `liftAccessorsFromPrototypes` configuration property is set.
	 * Have a look at the [`GetterValueAdapter`](./getterValue.ts) for more info.
	 */
	private async fetchAccessorsFromPrototypes(
		prototypeVariable: VariableAdapter,
		levels: number
	): Promise<VariableAdapter[]> {

		let objectGripAdapter: ObjectGripAdapter | undefined = <any>prototypeVariable.variablesProvider;
		let variables: VariableAdapter[] = [];
		let level = 0;
		while ((level < levels) && objectGripAdapter) {

			let prototypeAndProperties = await objectGripAdapter.actor.fetchPrototypeAndProperties();

			for (const varname in prototypeAndProperties.ownProperties) {

				const propertyDescriptor = prototypeAndProperties.ownProperties[varname];
				if ((varname !== '__proto__') &&
					(<FirefoxDebugProtocol.AccessorPropertyDescriptor>propertyDescriptor).get) {

					variables.push(VariableAdapter.fromPropertyDescriptor(
						varname, this.referenceExpression, this.referenceFrame,
						propertyDescriptor, this.threadLifetime, this.threadAdapter
					));
				}
			}

			prototypeVariable = VariableAdapter.fromGrip(
				'__proto__', this.referenceExpression, this.referenceFrame,
				prototypeAndProperties.prototype,
				this.threadLifetime, this.threadAdapter
			);
			objectGripAdapter = <any>prototypeVariable.variablesProvider;

			level++;
		}

		return variables;
	}

	public dispose(): void {
		this.actor.decreaseRefCount();
		this.threadAdapter.debugSession.variablesProviders.unregister(this.variablesProviderId);
	}
}


text:
#pragma once
//------------------------------------------------------------------------------
/**
    @class Oryol::GfxFrameInfo
    @brief per-frame stats of the Gfx module
*/
#include "Core/Types.h"

namespace Oryol {

struct GfxFrameInfo {
    int NumApplyRenderTarget = 0;
    int NumApplyViewPort = 0;
    int NumApplyScissorRect = 0;
    int NumApplyDrawState = 0;
    int NumApplyUniformBlock = 0;
    int NumUpdateVertices = 0;
    int NumUpdateIndices = 0;
    int NumUpdateTextures = 0;
    int NumDraw = 0;
    int NumDrawInstanced = 0;
};

} // namespace Oryol


text:
namespace xxaml { namespace ui { namespace xaml {

	const wchar_t xxaml__ui__xaml__dependency_object[] = L"XXaml.UI.Xaml.DependencyObject";
	class dependency_object
		: public foundation::xobject
	{
	public:
		XXAML_IMPORT foundation::xresult clear_value( dependency_property const* dp );
		XXAML_IMPORT foundation::xresult get_value( dependency_property const* dp, foundation::xobject** result ) const;
		XXAML_IMPORT foundation::xresult set_value( dependency_property const* dp, foundation::xobject* value );

	protected:
		XXAML_IMPORT dependency_object();

	public:
		XXAML_IMPORT virtual foundation::type_name type() const override;
		XXAML_IMPORT core::core_dispatcher const* dispatcher() const;

	private:
		core::core_dispatcher const* dispatcher_;
		::std::unordered_map<from_name, foundation::xobject_sptr<foundation::xobject>> property_map_;
	};

} } }


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace SOURCE.Domaine
{
    public partial class TypeDocument
    {
        [DataMember]
        public long ID { get; set; }
        [DataMember]
        [StringLength(50)]
        public string Code { get; set; }
        [DataMember]
        [StringLength(1000)]
        public string CodeEchange { get; set; }
        [DataMember]
        [StringLength(1000)]
        public string Description { get; set; }
        [DataMember]
        public bool IsLocked { get; set; }
        [DataMember]
        public bool WithComment { get; set; }
        [DataMember]
        public bool Archive { get; set; }
        [DataMember]
        public bool PourMaintien { get; set; }
    }
}


text:
package org.wicketstuff.gmap.api;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.time.Duration;
import org.wicketstuff.gmap.GMapHeaderContributor;
import org.wicketstuff.gmap.geocoder.GeocoderStatus;

/**
 */
public abstract class GClientGeocoder extends AjaxEventBehavior
{
    private static final long serialVersionUID = 1L;

    // the markup id of the TextField providing the requested address.
    private final String addressFieldMarkupId;

    private final GMapHeaderContributor headerContrib;

    /**
     * The time to wait before making a new request to self
     */
    private final Duration timeout;

    /**
     * Construct.
     *
     * @param event
     */
    public GClientGeocoder(String event, TextField<?> addressField)
    {
        this(event, addressField, Duration.milliseconds(500));
    }

    public GClientGeocoder(String event, TextField<?> addressField, Duration timeout)
    {
        super(event);

        addressField.setOutputMarkupId(true);
        this.addressFieldMarkupId = addressField.getMarkupId();

        this.headerContrib = new GMapHeaderContributor();
        this.timeout = timeout;
    }

    @Override
    public void renderHead(Component c, IHeaderResponse response)
    {
        super.renderHead(c, response);
        headerContrib.renderHead(c, response);
    }

    @Override
    protected void onEvent(AjaxRequestTarget target)
    {
        Request request = RequestCycle.get().getRequest();
        IRequestParameters requestParameters = request.getRequestParameters();
	    String status = requestParameters.getParameterValue("status").toString();
	    GeocoderStatus geocoderStatus = status != null ? GeocoderStatus.valueOf(status) : null;

        String address = null;
        GLatLng coordinates = null;
        if (geocoderStatus == null)
        {
            StringBuilder js = new StringBuilder();
            js.append("setTimeout(function() {")
            .append(getCallbackScript())
            .append("}, ")
            .append(timeout.getMilliseconds())
            .append(");");
             target.appendJavaScript(js);
        }
        else
        {
            if (GeocoderStatus.OK.equals(geocoderStatus))
            {
                address = requestParameters.getParameterValue("address").toString();
                coordinates = GLatLng.parse(requestParameters.getParameterValue("coordinates").toString());
            }
            onGeoCode(target, geocoderStatus, address, coordinates);
        }
    }

	/**
	 * @param target
	 * @param status  The status of the client side operation.
	 * @param address The address if the status is {@code GeocoderStatus#OK}, otherwise- {@code null}
	 * @param latLng  The coordinates if the status is {@code GeocoderStatus#OK}, otherwise- {@code null}
	 */
    public abstract void onGeoCode(AjaxRequestTarget target, GeocoderStatus status, String address, GLatLng latLng);

    @Override
    public CharSequence getCallbackScript()
    {
        return "Wicket.geocoder.getLatLng('" + getCallbackUrl() + "', '" + addressFieldMarkupId + "');";
    }
}


text:
using CommandLineParser.Arguments;
using System;
using System.Diagnostics;
using VSTSShared.BaseClasses;
using VSTSShared.Helpers;

namespace VSTSKeep
{
    class Program
    {
        static void Main(string[] args)
        {
            // Setup parser and extract command line arguments
            var parser = new CommandLineParser.CommandLineParser();
            var cmdLineArgs = new CommandLineArgs();

            try
            {
                // Add the verbose switch programmatically because I am having issues with the attributes
                var verbose = new SwitchArgument('v', "verbose", "Turns on verbose output.", false);
                var keepForever = new SwitchArgument('k', "keep", "If specified, sets to \"Keep Forever\"; Otherwise, removes the flag.", false);

                parser.Arguments.Add(verbose);
                parser.Arguments.Add(keepForever);

                parser.ShowUsageHeader = "Sets or removes \"keep forever\" retention for the specified build number in VSTS.\r\n\r\n" +
                    "VSTS-KEEP -a <Account> [-u <User ID>] -p <Password> -t <Project> -b <BuildNumber> [-k]";
                parser.ShowUsageOnEmptyCommandline = true;

                parser.ExtractArgumentAttributes(cmdLineArgs);
                parser.ParseCommandLine(args);

                if (parser.ParsingSucceeded)
                {
                    var authentication = new BasicAuthentication(cmdLineArgs.Account, cmdLineArgs.UserId, cmdLineArgs.Password);
                    var helper = new VstsHelper();

                    Console.WriteLine(helper.KeepForever(authentication, cmdLineArgs.Project, cmdLineArgs.BuildNumber,
                        keepForever.Value, verbose.Value)
                        ? "    Retention set successfully."
                        : "    Failed to set retention.");
                }
            }
            catch (System.Net.WebException ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.Message.Contains("(401) Unauthorized."))
                {
                    Console.WriteLine("VSTS-Keep requires access to the account's OAuth token in order to correctly set the keep forever config.");
                    Console.WriteLine("Please go to this build definition's options tab and enable build scripts to access the OAuth token.");
                }
                parser.ShowUsage();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                parser.ShowUsage();
            }

            if (Debugger.IsAttached)
            {
                // Keep the console window from closing when running from IDE
                Console.WriteLine("\r\nPress any key to close command window.");
                Console.ReadKey();
            }
        }
    }
}


text:
steal("can/compute", "can/test", "can/map", "steal-qunit", function () {
	QUnit.module('can/compute');
	test('single value compute', function () {
		var num = can.compute(1);
		num.bind('change', function (ev, newVal, oldVal) {
			equal(newVal, 2, 'newVal');
			equal(oldVal, 1, 'oldVal');
		});
		num(2);
	});
	test('inner computes values are not bound to', function () {
		var num = can.compute(1);
		var outer = can.compute(function() {
			var inner = can.compute(function() {
				return num() + 1;
			});
			return 2 * inner();
		});

		var handler = function () {};
		outer.bind('change', handler);
		// We do a timeout because we temporarily bind on num so that we can use its cached value.
		stop();
		setTimeout(function () {
			equal(num.computeInstance._bindings, 1, 'inner compute only bound once');
			equal(outer.computeInstance._bindings, 1, 'outer compute only bound once');
			start();
		}, 50);
	});

	test('can.compute.truthy', function () {
		var result = 0;
		var num = can.compute(3);
		var truthy = can.compute.truthy(num);
		var tester = can.compute(function () {
			if (truthy()) {
				return ++result;
			} else {
				return ++result;
			}
		});
		tester.bind('change', function (ev, newVal, oldVal) {
			if (num() === 0) {
				equal(newVal, 2, '2 is the new val');
			} else if (num() === -1) {
				equal(newVal, 3, '3 is the new val');
			} else {
				ok(false, 'change should not be called');
			}
		});
		equal(tester(), 1, 'on bind, we call tester once');
		num(2);
		num(1);
		num(0);
		num(-1);
	});
	test('a binding compute does not double read', function () {
		var sourceAge = 30,
			timesComputeIsCalled = 0;
		var age = can.compute(function (newVal) {
			timesComputeIsCalled++;
			if (timesComputeIsCalled === 1) {
				ok(true, 'reading age to get value');
			} else if (timesComputeIsCalled === 2) {
				equal(newVal, 31, 'the second time should be an update');
			} else if (timesComputeIsCalled === 3) {
				ok(true, 'called after set to get the value');
			} else {
				ok(false, 'You\'ve called the callback ' + timesComputeIsCalled + ' times');
			}
			if (arguments.length) {
				sourceAge = newVal;
			} else {
				return sourceAge;
			}
		});
		var info = can.compute(function () {
			return 'I am ' + age();
		});
		var k = function () {};
		info.bind('change', k);
		equal(info(), 'I am 30');
		age(31);
		equal(info(), 'I am 31');
	});
	test('cloning a setter compute (#547)', function () {
		var name = can.compute('', function (newVal) {
			return this.txt + newVal;
		});
		var cloned = name.clone({
			txt: '.'
		});
		cloned('-');
		equal(cloned(), '.-');
	});

	test('compute updated method uses get and old value (#732)', function () {
		expect(9);
		var input = {
			value: 1
		};
		var value = can.compute('', {
			get: function () {
				return input.value;
			},
			set: function (newVal) {
				input.value = newVal;
			},
			on: function (update) {
				input.onchange = update;
			},
			off: function () {
				delete input.onchange;
			}
		});
		equal(value(), 1, 'original value');
		ok(!input.onchange, 'nothing bound');
		value(2);
		equal(value(), 2, 'updated value');
		equal(input.value, 2, 'updated input.value');

		value.bind('change', function (ev, newVal, oldVal) {
			equal(newVal, 3, 'newVal');
			equal(oldVal, 2, 'oldVal');
			value.unbind('change', this.Constructor);
		});
		ok(input.onchange, 'binding to onchange');

		input.value = 3;
		input.onchange({});

		ok(!input.onchange, 'removed binding');
		equal(value(), 3);
	});

	test("a compute updated by source changes within a batch is part of that batch", function(){

		var computeA = can.compute("a");
		var computeB = can.compute("b");

		var combined1 = can.compute(function(){

			return computeA()+" "+computeB();

		});

		var combined2 = can.compute(function(){

			return computeA()+" "+computeB();

		});

		var combo = can.compute(function(){
			return combined1()+" "+combined2();
		});

		var callbacks = 0;
		combo.bind("change", function(){
			if(callbacks === 0){
				ok(true, "called change once");
			} else {
				ok(false, "called change multiple times");
			}
			callbacks++;
		});

		can.batch.start();
		computeA("A");
		computeB("B");
		can.batch.stop();
	});

	test("compute.async can be like a normal getter", function(){
		var first = can.compute("Justin"),
			last = can.compute("Meyer"),
			fullName = can.compute.async("", function(){
				return first()+" "+last();
			});

		equal(fullName(), "Justin Meyer");
	});

	test("compute.async operate on single value", function(){

		var a = can.compute(1);
		var b = can.compute(2);

		var obj = can.compute.async({}, function( curVal ){
			if(a()) {
				curVal.a = a();
			} else {
				delete curVal.a;
			}
			if(b()) {
				curVal.b = b();
			} else {
				delete curVal.b;
			}
			return curVal;
		});

		obj.bind("change", function(){});

		deepEqual( obj(), {a: 1, b: 2}, "object has all properties" );

		a(0);

		deepEqual( obj(), {b: 2}, "removed a" );

		b(0);

		deepEqual( obj(), {}, "removed b" );

	});

	test("compute.async async changing value", function(){

		var a = can.compute(1);
		var b = can.compute(2);

		var async = can.compute.async(undefined,function( curVal, setVal ){

			if(a()) {
				setTimeout(function(){
					setVal("a");
				},10);
			} else if(b()) {
				setTimeout(function(){
					setVal("b");
				},10);
			} else {
				return null;
			}
		});

		var changeArgs = [
			{newVal: "a", oldVal: undefined, run: function(){ a(0); } },
			{newVal: "b", oldVal: "a", run: function(){ b(0); }},
			{newVal: null, oldVal: "b", run: function(){ start(); }}
		],
			changeNum = 0;

		stop();

		async.bind("change", function(ev, newVal, oldVal){
			var data = changeArgs[changeNum++];
			equal( newVal, data.newVal, "newVal is correct" );
			equal( oldVal, data.oldVal, "oldVal is correct" );

			setTimeout(data.run, 10);

		});

	});

	test("can.Construct derived classes should be considered objects, not functions (#450)", function() {
		var foostructor = can.Map({ text: "bar" }, {}),
			obj = {
				next_level: {
					thing: foostructor,
					text: "In the inner context"
				}
			},
			read;
		foostructor.self = foostructor;

		read = can.compute.read(obj, ["next_level","thing","self","text"]);
		equal(read.value, "bar", "static properties on a can.Construct-based function");

		read = can.compute.read(obj, ["next_level","thing","self"], { isArgument: true });
		ok(read.value === foostructor, "arguments shouldn't be executed");

		foostructor.self = function() { return foostructor; };
		read = can.compute.read(obj, ["next_level","thing","self","text"], { executeAnonymousFunctions: true });
		equal(read.value, "bar", "anonymous functions in the middle of a read should be executed if requested");
	});

	test("compute.async read without binding", function(){

		var source = can.compute(1);

		var async = can.compute.async([],function( curVal, setVal ){
			curVal.push(source());
			return curVal;
		});

		ok(async(), "calling async worked");

	});

	test("compute.read works with a Map wrapped in a compute", function() {
		var parent = can.compute(new can.Map({map: {first: "Justin" }}));
		var reads = ["map", "first"];

		var result = can.compute.read(parent, reads);
		equal(result.value, "Justin", "The correct value is found.");
	});

	test('compute.read works with a Map wrapped in a compute', function() {
		var parent = new can.Compute(new can.Map({map: {first: 'Justin' }}));
		var reads = ['map', 'first'];

		var result = can.Compute.read(parent, reads);
		equal(result.value, 'Justin', 'The correct value is found.');
	});

	test("compute.read returns constructor functions instead of executing them (#1332)", function() {
		var Todo = can.Map.extend({});
		var parent = can.compute(new can.Map({map: { Test: Todo }}));
		var reads = ["map", "Test"];

		var result = can.compute.read(parent, reads);
		equal(result.value, Todo, 'Got the same Todo');
	});

	test("compute.set with different values", 4, function() {
		var comp = can.compute("David");
		var parent = {
			name: "David",
			comp: comp
		};
		var map = new can.Map({
			name: "David"
		});

		map.bind('change', function(ev, attr, how, value) {
			equal(value, "Brian", "Got change event on map");
		});

		can.compute.set(parent, "name", "Matthew");
		equal(parent.name, "Matthew", "Name set");

		can.compute.set(parent, "comp", "Justin");
		equal(comp(), "Justin", "Name updated");

		can.compute.set(map, "name", "Brian");
		equal(map.attr("name"), "Brian", "Name updated in map");
	});

	// ========================================
	QUnit.module('can/Compute');

	test('single value compute', function () {
		expect(2);
		var num = new can.Compute(1);
		num.bind('change', function (ev, newVal, oldVal) {
			equal(newVal, 2, 'newVal');
			equal(oldVal, 1, 'oldVal');
		});
		num.set(2);
	});

	test('inner computes values are not bound to', function () {
		var num = new can.Compute(1),
			numBind = num.bind,
			numUnbind = num.unbind;
		var bindCount = 0;
		num.bind = function() {
			bindCount++;
			return numBind.apply(this, arguments);
		};
		num.unbind = function() {
			bindCount--;
			return numUnbind.apply(this, arguments);
		};
		var outer = new can.Compute(function() {
			var inner = new can.Compute(function() {
				return num.get() + 1;
			});
			return 2 * inner.get();
		});
		var handler = function() {};
		outer.bind('change', handler);
		// We do a timeout because we temporarily bind on num so that we can use its cached value.
		stop();
		setTimeout(function() {
			equal(bindCount, 1, 'compute only bound to once');
			start();
		}, 50);
	});

	test('can.Compute.truthy', function() {
		var result = 0;
		var num = new can.Compute(3);
		var truthy = can.Compute.truthy(num);
		var tester = new can.Compute(function() {
			if(truthy.get()) {
				return ++result;
			} else {
				return ++result;
			}
		});

		tester.bind('change', function(ev, newVal, oldVal) {
			if (num.get() === 0) {
				equal(newVal, 2, '2 is the new val');
			} else if (num.get() === -1) {
				equal(newVal, 3, '3 is the new val');
			} else {
				ok(false, 'change should not be called');
			}
		});
		equal(tester.get(), 1, 'on bind, we call tester once');
		num.set(2);
		num.set(1);
		num.set(0);
		num.set(-1);
	});

	test('a binding compute does not double read', function () {
		var sourceAge = 30,
			timesComputeIsCalled = 0;
		var age = new can.Compute(function (newVal) {
			timesComputeIsCalled++;
			if (timesComputeIsCalled === 1) {
				ok(true, 'reading age to get value');
			} else if (timesComputeIsCalled === 2) {
				equal(newVal, 31, 'the second time should be an update');
			} else if (timesComputeIsCalled === 3) {
				ok(true, 'called after set to get the value');
			} else {
				ok(false, 'You\'ve called the callback ' + timesComputeIsCalled + ' times');
			}
			if (arguments.length) {
				sourceAge = newVal;
			} else {
				return sourceAge;
			}
		});

		var info = new can.Compute(function () {
			return 'I am ' + age.get();
		});

		var k = function () {};
		info.bind('change', k);
		equal(info.get(), 'I am 30');
		age.set(31);
		equal(info.get(), 'I am 31');
	});

	test('cloning a setter compute (#547)', function () {
		var name = new can.Compute('', function(newVal) {
			return this.txt + newVal;
		});

		var cloned = name.clone({
			txt: '.'
		});

		cloned.set('-');
		equal(cloned.get(), '.-');
	});

	test('compute updated method uses get and old value (#732)', function () {
		expect(9);

		var input = {
			value: 1
		};

		var value = new can.Compute('', {
			get: function () {
				return input.value;
			},
			set: function (newVal) {
				input.value = newVal;
			},
			on: function (update) {
				input.onchange = update;
			},
			off: function () {
				delete input.onchange;
			}
		});

		equal(value.get(), 1, 'original value');
		ok(!input.onchange, 'nothing bound');
		value.set(2);
		equal(value.get(), 2, 'updated value');
		equal(input.value, 2, 'updated input.value');

		value.bind('change', function (ev, newVal, oldVal) {
			equal(newVal, 3, 'newVal');
			equal(oldVal, 2, 'oldVal');
			value.unbind('change', this.Constructor);
		});

		ok(input.onchange, 'binding to onchange');

		input.value = 3;
		input.onchange({});

		ok(!input.onchange, 'removed binding');
		equal(value.get(), 3);
	});

	test('a compute updated by source changes within a batch is part of that batch', function () {
		var computeA = new can.Compute('a');
		var computeB = new can.Compute('b');

		var combined1 = new can.Compute(function() {
			return computeA.get() + ' ' + computeB.get();
		});

		var combined2 = new can.Compute(function() {
			return computeA.get() + ' ' + computeB.get();
		});

		var combo = new can.Compute(function() {
			return combined1.get() + ' ' + combined2.get();
		});

		var callbacks = 0;
		combo.bind('change', function(){
			if(callbacks === 0){
				ok(true, 'called change once');
			} else {
				ok(false, 'called change multiple times');
			}
			callbacks++;
		});

		can.batch.start();
		computeA.set('A');
		computeB.set('B');
		can.batch.stop();
	});

	test('compute.async can be like a normal getter', function() {
		var first = new can.Compute('Justin'),
			last = new can.Compute('Meyer'),
			fullName = can.Compute.async('', function(){
				return first.get() + ' ' + last.get();
			});

		equal(fullName.get(), 'Justin Meyer');
	});

	test('compute.async operate on single value', function() {
		var a = new can.Compute(1);
		var b = new can.Compute(2);

		var obj = can.Compute.async({}, function(curVal) {
			if(a.get()) {
				curVal.a = a.get();
			} else {
				delete curVal.a;
			}

			if(b.get()) {
				curVal.b = b.get();
			} else {
				delete curVal.b;
			}

			return curVal;
		});

		obj.bind('change', function() {});
		deepEqual(obj.get(), {a: 1, b: 2}, 'object has all properties');

		a.set(0);
		deepEqual(obj.get(), {b: 2}, 'removed a');

		b.set(0);
		deepEqual(obj.get(), {}, 'removed b');
	});

	test('compute.async async changing value', function() {
		var a = new can.Compute(1);
		var b = new can.Compute(2);

		var async = can.Compute.async(undefined, function(curVal, setVal) {
			if(a.get()) {
				setTimeout(function() {
					setVal('a');
				}, 10);
			} else if(b.get()) {
				setTimeout(function() {
					setVal('b');
				}, 10);
			} else {
				return null;
			}
		});

		var changeArgs = [
			{newVal: 'a', oldVal: undefined, run: function() { a.set(0); } },
			{newVal: 'b', oldVal: 'a', run: function() { b.set(0); }},
			{newVal: null, oldVal: 'b', run: function() { start(); }}
		],
		changeNum = 0;

		stop();

		async.bind('change', function(ev, newVal, oldVal) {
			var data = changeArgs[changeNum++];
			equal( newVal, data.newVal, 'newVal is correct' );
			equal( oldVal, data.oldVal, 'oldVal is correct' );

			setTimeout(data.run, 10);
		});
	});

	test('can.Construct derived classes should be considered objects, not functions (#450)', function() {
		var foostructor = can.Map({ text: 'bar' }, {}),
			obj = {
				next_level: {
					thing: foostructor,
					text: 'In the inner context'
				}
			},
			read;
		foostructor.self = foostructor;

		read = can.Compute.read(obj, ['next_level','thing','self','text']);
		equal(read.value, 'bar', 'static properties on a can.Construct-based function');

		read = can.Compute.read(obj, ['next_level','thing','self'], { isArgument: true });
		ok(read.value === foostructor, 'arguments shouldn\'t be executed');

		foostructor.self = function() { return foostructor; };
		read = can.Compute.read(obj, ['next_level','thing','self','text'], { executeAnonymousFunctions: true });
		equal(read.value, 'bar', 'anonymous functions in the middle of a read should be executed if requested');
	});

	test('compute.async read without binding', function() {
		var source = new can.Compute(1);

		var async = can.Compute.async([],function( curVal, setVal ) {
			curVal.push(source.get());
			return curVal;
		});

		ok(async.get(), 'calling async worked');
	});

	test('Compute.async set uses last set or initial value', function() {

		var add = new can.Compute(1);

		var fnCount = 0;

		var async = can.Compute.async(10,function( curVal ) {
			switch(fnCount++) {
				case 0:
					equal(curVal, 10);
					break;
				case 1:
					equal(curVal, 20);
					break;
				case 2:
					equal(curVal, 30, "on bind");
					break;
				case 3:
					equal(curVal, 30, "on bind");
					break;
			}
			return curVal+add.get();
		});

		equal(async.get(), 11, "initial value");

		async.set(20);

		async.bind("change", function(){});

		async.set(20);

		async.set(30);
	});

	test("setting compute.async with a observable dependency gets a new value and can re-compute", 4, function(){
		// this is needed for define with a set and get.
		var compute = can.compute(1);
		var add;

		var async = can.compute.async(1, function(curVal){
			add = curVal;
			return compute()+add;
		});

		equal( async(), 2, "can read unbound");

		async.bind("change", function(ev, newVal, oldVal){
			equal(newVal, 3, "change new val");
			equal(oldVal, 2, "change old val");
		});

		async(2);

		equal( async(), 3, "can read unbound");
	});

	test('compute.async getter has correct when length === 1', function(){
		var m = new can.Map();

		var getterCompute = can.compute.async(false, function (singleArg) {
			equal(this, m, 'getter has the right context');
		}, m);

		getterCompute.bind('change', can.noop);
	});

	test("bug with nested computes and batch ordering (#1519)", function(){

		var ft = can.compute('a');
		var other = can.compute(3);

		var propA = can.compute(function(){
			return ft() ==='a';
		});

		var propB = can.compute(function(){
			return ft() === 'b';
		});

		var combined = can.compute(function(){
			var valA = propA(),
				valB = propB();

			return valA || valB;
		});

		equal(combined(), true);

		combined.bind('change', function(){ });

		ft.bind('change', function() {
			can.batch.start();
			other(2);
			can.batch.stop();
		});

		can.batch.start();
		ft('b');
		can.batch.stop();

		equal(combined(), true);
		equal(other(), 2);
	});

	test("can.Compute.read can read a promise (#179)", function(){

		var def = new can.Deferred();
		var map = new can.Map();

		var c = can.compute(function(){
			return can.Compute.read({map: map},["map","data","value"]).value;
		});

		var calls = 0;
		c.bind("change", function(ev, newVal, oldVal){
			calls++;
			equal(calls, 1, "only one call");
			equal(newVal, "Something", "new value");
			equal(oldVal, undefined, "oldVal");
			start();
		});

		map.attr("data", def);

		setTimeout(function(){
			def.resolve("Something");
		},2);

		stop();

	});

	test('compute change handler context is set to the function not can.Compute', function() {
		var comp = can.compute(null);

		comp.bind('change', function() {
			equal(typeof this, 'function');
		});

		comp('test');
	});
});


text:
      Item ID
      Item Name
      Item


text:
BSLS_IDENT("$Id$ $CSID$")

#include <bslh_defaultseededhashalgorithm.h> // for testing only
#include <bslh_siphashalgorithm.h>           // for testing only
#include <bslh_spookyhashalgorithm.h>        // for testing only

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


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms.Design;
using System.Windows.Forms;
using FlatRedBall.Glue.SaveClasses;
using System.Collections;
using System.Reflection;
using System.IO;
using FlatRedBall.Glue.FormHelpers.PropertyGrids;
using FlatRedBall.Glue.Plugins.ExportedImplementations;

using FlatRedBall.Glue.SaveClasses.Helpers;

namespace FlatRedBall.Glue.Controls.PropertyGridControls
{
    public class StateValueEditor : UITypeEditor
    {
        const string CanInterpolateFile = @"Content\Icons\CanInterpolate.bmp";
        const string CantInterpolateFile = @"Content\Icons\CantInterpolate.bmp";
        const string NeedsInterpolationVariable = @"Content\Icons\NeedsInterpolateVariable.bmp";

        Image mImage;

        Image mCanInterpolate;
        Image mCantInterpolate;
        Image mNeedsVelocityVariable;

        public StateValueEditor()
            : base()
        {

            mCanInterpolate = Resources.Resource1.CanInterpolate;

            mCantInterpolate = Resources.Resource1.CantInterpolate;

            mNeedsVelocityVariable = Resources.Resource1.NeedsInterpolateVariable;
        }

        //public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        //{
        //    if (context == null)
        //    {
        //        return UITypeEditorEditStyle.None;
        //    }
        //    else
        //    {
        //        TypeConverter typeConverter = context.PropertyDescriptor.Converter;
        //        if (typeConverter is StringConverter)
        //        {
        //            return UITypeEditorEditStyle.None;
        //        }
        //        else
        //        {
        //            return UITypeEditorEditStyle.Modal;
        //        }
        //    }
        //}

        public override object EditValue(
            ITypeDescriptorContext context,
            IServiceProvider provider,
            object value)
        {
            IWindowsFormsEditorService editorService = null;

            if (provider != null)
            {
                editorService =
                    provider.GetService(
                    typeof(IWindowsFormsEditorService))
                    as IWindowsFormsEditorService;
            }

            if (editorService != null)
            {
                ListBox listBox = new ListBox();

                if (context != null)
                {
                    ICollection collection = context.PropertyDescriptor.Converter.GetStandardValues();

                    foreach (object item in collection)
                    {
                        listBox.Items.Add(item);
                    }

                }
                editorService.DropDownControl(listBox);
        //        LightShapeSelectionControl selectionControl =
        //            new LightShapeSelectionControl(
        //            (MarqueeLightShape)value,
        //            editorService);

        //        editorService.DropDownControl(selectionControl);

        //        value = selectionControl.LightShape;
            }

            return value;
        }

        // This method indicates to the design environment that
        // the type editor will paint additional content in the
        // LightShape entry in the PropertyGrid.
        public override bool GetPaintValueSupported(
            ITypeDescriptorContext context)
        {
            FlatRedBall.Glue.SaveClasses.StateSave stateSave =
                ((StateSavePropertyGridDisplayer)context.Instance).Instance as StateSave;

            //if (context.PropertyDescriptor.)
            //{
            //    int m = 3;
            //}
            return mPaintIcon;
        }

        bool mPaintIcon = true;

        // This method paints a graphical representation of the
        // selected value of the LightShpae property.
        public override void PaintValue(PaintValueEventArgs e)
        {
            if (e.Bounds.Left == 1 && e.Bounds.Top == 1)
            {

                if (e.Context.Instance is StateSavePropertyGridDisplayer)
                {
                    FlatRedBall.Glue.SaveClasses.StateSave stateSave =
                        ((StateSavePropertyGridDisplayer)e.Context.Instance).Instance as StateSave;

                    PropertyInfo[] properties = e.Context.GetType().GetProperties();

                    PropertyInfo info = e.Context.GetType().GetProperty("PropertyName");

                    string variableName = (string)info.GetValue(e.Context, null);

                    CustomVariable variable = GlueState.Self.CurrentElement.GetCustomVariable(variableName);
                    if (variable != null)
                    {

                        InterpolationCharacteristic interpolationCharacteristic =
                            CustomVariableHelper.GetInterpolationCharacteristic(variable, GlueState.Self.CurrentElement);

                        Image bitmap = null;
                        if (interpolationCharacteristic == InterpolationCharacteristic.CanInterpolate ||
                            (interpolationCharacteristic == InterpolationCharacteristic.NeedsVelocityVariable && variable.HasAccompanyingVelocityProperty))
                        {
                            bitmap = mCanInterpolate;
                        }
                        else if (interpolationCharacteristic == InterpolationCharacteristic.NeedsVelocityVariable)
                        {
                            bitmap = mNeedsVelocityVariable;
                        }
                        else
                        {
                            bitmap = mCantInterpolate;
                        }

                        e.Graphics.DrawImage(bitmap, e.Bounds.Left, e.Bounds.Top, bitmap.Width, bitmap.Height);

                    }
                }
            }
            else
            {
                //e.Graphics.DrawEllipse(Pens.Yellow, e.Bounds);
            }
        }

    }
}


text:
package org.mockito.verification;

import static org.mockito.internal.exceptions.Reporter.atMostAndNeverShouldNotBeUsedWithTimeout;

import org.mockito.internal.util.Timer;
import org.mockito.internal.verification.VerificationOverTimeImpl;
import org.mockito.internal.verification.VerificationWrapper;

/**
 * See the javadoc for {@link VerificationWithTimeout}
 *

 * Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class.
 * See javadoc for {@link VerificationWithTimeout}
 */
public class Timeout extends VerificationWrapper<VerificationOverTimeImpl>
        implements VerificationWithTimeout {

    /**
     * See the javadoc for {@link VerificationWithTimeout}
     *

     * Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class.
     * See javadoc for {@link VerificationWithTimeout}
     */
    public Timeout(long millis, VerificationMode delegate) {
        this(10, millis, delegate);
    }

    /**
     * See the javadoc for {@link VerificationWithTimeout}
     */
    Timeout(long pollingPeriodMillis, long millis, VerificationMode delegate) {
        this(new VerificationOverTimeImpl(pollingPeriodMillis, millis, delegate, true));
    }

    /**
     * See the javadoc for {@link VerificationWithTimeout}
     */
    Timeout(long pollingPeriodMillis, VerificationMode delegate, Timer timer) {
        this(new VerificationOverTimeImpl(pollingPeriodMillis, delegate, true, timer));
    }

    Timeout(VerificationOverTimeImpl verificationOverTime) {
        super(verificationOverTime);
    }

    @Override
    protected VerificationMode copySelfWithNewVerificationMode(
            VerificationMode newVerificationMode) {
        return new Timeout(wrappedVerification.copyWithVerificationMode(newVerificationMode));
    }

    public VerificationMode atMost(int maxNumberOfInvocations) {
        throw atMostAndNeverShouldNotBeUsedWithTimeout();
    }

    public VerificationMode never() {
        throw atMostAndNeverShouldNotBeUsedWithTimeout();
    }
}