text:
package co.omise.live;

import co.omise.Client;
import co.omise.models.*;
import co.omise.requests.Request;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.io.IOException;

import static junit.framework.TestCase.*;
import static org.junit.Assert.assertFalse;

public class LiveChargeRequestTest extends BaseLiveTest {
    private Client client;

    @Before
    public void setup() throws Exception {
        client = getLiveClient();
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveGetCharge() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .build();
        Charge createdCharge = client.sendRequest(createChargeRequest);

        Request<Charge> getChargeRequest = new Charge.GetRequestBuilder(createdCharge.getId()).build();
        Charge actualCharge = client.sendRequest(getChargeRequest);

        System.out.println("Retrieved charge: " + actualCharge.getId());

        assertEquals(createdCharge.getId(), actualCharge.getId());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveCreateCharge() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .build();

        Charge charge = client.sendRequest(createChargeRequest);

        System.out.println("created charge: " + charge.getId());

        assertNotNull(charge.getId());
        assertEquals(2000, charge.getAmount());
        assertEquals("USD", charge.getCurrency());
        assertEquals(token.getCard().getLastDigits(), charge.getCard().getLastDigits());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeWithInternetBanking() throws IOException, OmiseException {
        Request<Source> sourceRequest = new Source.CreateRequestBuilder()
                .type(SourceType.InternetBankingBay)
                .amount(10000)
                .currency("thb")
                .build();

        Source source = client.sendRequest(sourceRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .source(source.getId())
                        .amount(10000)
                        .currency("thb")
                        .returnUri("http://example.com/orders/345678/complete")
                        .build();

        Charge charge = client.sendRequest(createChargeRequest);

        System.out.println("created charge: " + charge.getId());

        assertNotNull(charge.getId());
        assertEquals(10000, charge.getAmount());
        assertEquals("THB", charge.getCurrency());
        assertEquals(SourceType.InternetBankingBay, charge.getSource().getType());
        assertEquals(FlowType.Redirect, charge.getSource().getFlow());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeWithBillPaymentTescoLotus() throws IOException, OmiseException {
        Request<Source> sourceRequest = new Source.CreateRequestBuilder()
                .type(SourceType.BillPaymentTescoLotus)
                .amount(10000)
                .currency("thb")
                .build();

        Source source = client.sendRequest(sourceRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .source(source.getId())
                        .amount(10000)
                        .currency("thb")
                        .returnUri("http://example.com/orders/345678/complete")
                        .build();

        Charge charge = client.sendRequest(createChargeRequest);

        System.out.println("created charge: " + charge.getId());

        assertNotNull(charge.getId());
        assertEquals(10000, charge.getAmount());
        assertEquals("THB", charge.getCurrency());
        assertEquals(SourceType.BillPaymentTescoLotus, charge.getSource().getType());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeWithAlipay() throws IOException, OmiseException {
        Request<Source> sourceRequest = new Source.CreateRequestBuilder()
                .type(SourceType.Alipay)
                .amount(10000)
                .currency("thb")
                .build();

        Source source = client.sendRequest(sourceRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .source(source.getId())
                        .amount(10000)
                        .currency("thb")
                        .returnUri("http://example.com/orders/345678/complete")
                        .build();

        Charge charge = client.sendRequest(createChargeRequest);

        System.out.println("Created charge: " + charge.getId());

        assertNotNull(charge.getId());
        assertEquals(SourceType.Alipay, charge.getSource().getType());
        assertEquals(FlowType.Redirect, charge.getSource().getFlow());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeWithZeroInterestsInstallments() throws IOException, OmiseException {
        Request<Source> sourceRequest = new Source.CreateRequestBuilder()
                .type(SourceType.InstallmentKbank)
                .zeroInterestInstallments(true)
                .installmentTerm(4)
                .amount(300000)
                .currency("thb")
                .build();

        Source source = client.sendRequest(sourceRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .source(source.getId())
                        .amount(300000)
                        .currency("thb")
                        .zeroInterestInstallments(true)
                        .returnUri("http://example.com/orders/345678/complete")
                        .build();

        Charge charge = client.sendRequest(createChargeRequest);

        System.out.println("Created charge: " + charge.getId());

        assertNotNull(charge.getId());
        assertEquals(SourceType.InstallmentKbank, charge.getSource().getType());
        assertTrue(charge.isZeroInterestInstallments());
        assertEquals(FlowType.Redirect, charge.getSource().getFlow());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeWithPromptpay() throws IOException, OmiseException {
        Request<Source> sourceRequest = new Source.CreateRequestBuilder()
                .type(SourceType.PromptPay)
                .amount(10000)
                .currency("thb")
                .build();

        Source source = client.sendRequest(sourceRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .source(source.getId())
                        .amount(10000)
                        .currency("thb")
                        .returnUri("http://example.com/orders/345678/complete")
                        .build();

        Charge charge = client.sendRequest(createChargeRequest);

        System.out.println("created charge: " + charge.getId());

        assertNotNull(charge.getId());
        assertEquals(10000, charge.getAmount());
        assertEquals("THB", charge.getCurrency());
        assertEquals(SourceType.PromptPay, charge.getSource().getType());
        assertEquals(Barcode.class, charge.getSource().getScannableCode().getClass());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeUpdate() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .build();

        Charge createdCharge = client.sendRequest(createChargeRequest);

        System.out.println("Created charge: " + createdCharge.getId());

        Request<Charge> updateChargeRequest =
                new Charge.UpdateRequestBuilder(createdCharge.getId())
                        .description("omise-java test charge")
                        .metadata("test-date", DateTime.now().dayOfMonth().toString())
                        .metadata("library", "omise-java")
                        .build();

        Charge updatedCharge = client.sendRequest(updateChargeRequest);

        System.out.println("Updated charge: " + updatedCharge.getId());

        assertNotNull(updatedCharge.getId());
        assertEquals(createdCharge.getId(), updatedCharge.getId());
        assertEquals("omise-java test charge", updatedCharge.getDescription());
        assertEquals(updatedCharge.getMetadata().get("library"), "omise-java");
        assertEquals(updatedCharge.getMetadata().get("test-date"), DateTime.now().dayOfMonth().toString());
        assertEquals(2000, updatedCharge.getAmount());
        assertEquals("USD", updatedCharge.getCurrency());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeCapture() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .capture(false)
                        .build();
        Charge unCapturedCharge = client.sendRequest(createChargeRequest);

        System.out.println("created charge: " + unCapturedCharge.getId());

        assertNotNull(unCapturedCharge.getId());
        assertFalse(unCapturedCharge.isCapture());

        Request<Charge> captureChargeRequest =
                new Charge.CaptureRequestBuilder(unCapturedCharge.getId()).build();

        Charge capturedCharge = client.sendRequest(captureChargeRequest);

        assertNotNull(capturedCharge);
        assertEquals(unCapturedCharge.getId(), capturedCharge.getId());
        assertTrue(capturedCharge.isPaid());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeReverse() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .capture(false)
                        .build();
        Charge initialCharge = client.sendRequest(createChargeRequest);

        System.out.println("created charge: " + initialCharge.getId());

        assertNotNull(initialCharge.getId());
        assertFalse(initialCharge.isReversed());

        Request<Charge> reverseChargeRequest =
                new Charge.ReverseRequestBuilder(initialCharge.getId())
                        .build();
        Charge reversedCharge = client.sendRequest(reverseChargeRequest);

        assertNotNull(reversedCharge.getId());
        assertEquals(initialCharge.getId(), reversedCharge.getId());
        assertTrue(reversedCharge.isReversed());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeListGet() throws IOException, OmiseException {
        Request<ScopedList<Charge>> getChargeListRequest =
                new Charge.ListRequestBuilder()
                        .build();

        ScopedList<Charge> charges = client.sendRequest(getChargeListRequest);

        assertEquals(20, charges.getLimit());
        assertTrue(charges.getTotal() > 0);

        Charge charge = charges.getData().get(0);
        assertNotNull(charge);
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeListGet_withOptions() throws IOException, OmiseException {
        Request<ScopedList<Charge>> getChargeListRequest =
                new Charge.ListRequestBuilder()
                        .options(new ScopedList.Options()
                                .limit(3)
                                .order(Ordering.Chronological))
                        .build();

        ScopedList<Charge> charges = client.sendRequest(getChargeListRequest);

        assertEquals(3, charges.getLimit());
        assertEquals(3, charges.getData().size());
        assertEquals(Ordering.Chronological, charges.getOrder());

        Charge charge = charges.getData().get(0);
        assertNotNull(charge);
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeDisputableFlag() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .build();
        Charge createdCharge = client.sendRequest(createChargeRequest);

        Request<Charge> getChargeRequest = new Charge.GetRequestBuilder(createdCharge.getId()).build();
        Charge actualCharge = client.sendRequest(getChargeRequest);

        System.out.println("Retrieved charge: " + actualCharge.getId());

        assertEquals(createdCharge.isDisputable(), actualCharge.isDisputable());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeCapturableFlag() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .build();
        Charge createdCharge = client.sendRequest(createChargeRequest);

        Request<Charge> getChargeRequest = new Charge.GetRequestBuilder(createdCharge.getId()).build();
        Charge actualCharge = client.sendRequest(getChargeRequest);

        System.out.println("Retrieved charge: " + actualCharge.getId());

        assertEquals(createdCharge.isCapturable(), actualCharge.isCapturable());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeReversibleFlag() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .build();
        Charge createdCharge = client.sendRequest(createChargeRequest);

        Request<Charge> getChargeRequest = new Charge.GetRequestBuilder(createdCharge.getId()).build();
        Charge actualCharge = client.sendRequest(getChargeRequest);

        System.out.println("Retrieved charge: " + actualCharge.getId());

        assertEquals(createdCharge.isReversible(), actualCharge.isReversible());
    }

    @Test
    @Ignore("only hit the network when we need to.")
    public void testLiveChargeRefundableFlag() throws IOException, OmiseException {
        Request<Token> tokenRequest = new Token.CreateRequestBuilder()
                .card(new Card.Create()
                        .name("Omise Co., Ltd. - testLiveCharge")
                        .number("4242424242424242")
                        .securityCode("123")
                        .expiration(10, 2020))
                .build();

        Token token = client.sendRequest(tokenRequest);

        Request<Charge> createChargeRequest =
                new Charge.CreateRequestBuilder()
                        .amount(2000) // $20
                        .currency("usd")
                        .description("omise-java test")
                        .card(token.getId())
                        .build();
        Charge createdCharge = client.sendRequest(createChargeRequest);

        Request<Charge> getChargeRequest = new Charge.GetRequestBuilder(createdCharge.getId()).build();
        Charge actualCharge = client.sendRequest(getChargeRequest);

        System.out.println("Retrieved charge: " + actualCharge.getId());

        assertEquals(createdCharge.isRefundable(), actualCharge.isRefundable());
    }
}


text:
'use strict';

var config = require('../src/lib/config');
var fs = require('fs');
var path = require('path');
var sh = require('shelljs');

function scaffoldPath (file) {
  return path.join('node_modules', 'chippy', 'bin', 'scaffolding', file);
}

function mkDefaultDir (dir) {
  if (!fs.existsSync(dir)) {
    sh.mkdir('-p', dir);
  }
}

function mkDefaultFile (file, data) {
  var dir = path.dirname(file);
  mkDefaultDir(dir);
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, data || '');
  }
}

function cpDefaultFile (file, dest) {
  mkDefaultFile(dest || file, fs.readFileSync(scaffoldPath(file)));
}

function mkDefaultJson (file, obj) {
  mkDefaultFile('package.json', JSON.stringify(obj, null, '  '));
}

function npmInstallDev (pkg) {
  if (!config('devDependencies.' + pkg)) {
    sh.exec('npm install ' + pkg + ' --save-dev');
  }
}

cpDefaultFile('dot-chippyrc', '.chippyrc');
cpDefaultFile('dot-gitignore', '.gitignore');
cpDefaultFile('dot-jshintrc', '.jshintrc');
cpDefaultFile('dot-jscsrc', '.jscsrc');
cpDefaultFile('gulpfile.js');
cpDefaultFile('LICENSE');
cpDefaultFile('README.md');
mkDefaultDir(config('build'));
mkDefaultDir(config('docs.basepath'));
mkDefaultFile(path.join(config('docs.basepath'), config('docs.source'), config('docs.mainHtmlSource')));
mkDefaultFile(path.join(config('docs.basepath'), config('docs.source'), config('docs.mainJsDestination'), config('docs.mainJsSource')));
mkDefaultFile(path.join(config('docs.basepath'), config('docs.source'), config('docs.mainLessDestination'), config('docs.mainLessSource')));
mkDefaultFile(config('perf.main'));
mkDefaultFile(config('test.main'));
mkDefaultJson('package.json', {
  name: config('name'),
  dependencies: {},
  devDependencies: {},
  peerDependencies: {}
});
npmInstallDev('babel');
npmInstallDev('gulp');
npmInstallDev('gulp-auto-task');
npmInstallDev('jshint');

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function() {

	$('.nav-toggle').click(function() {

		$('nav').slideToggle("fast");

	});

	$('.view-abstract').click(function() {

		$(this).next('.abstract').slideToggle();

		var currentName = $(this).html();

		if ( currentName == 'View Abstract' ) {
			$(this).html('Hide Abstract');
		} else {
			$(this).html('View Abstract');
		}

		return false;

	});

});


text:
package App::Fairy::Utils;
use strict;
use warnings;
use Archive::Extract;
use Exporter qw/import/;
use File::Path;
use File::Spec;
use File::Temp qw/tempdir/;
use HTTP::Request;
use LWP::UserAgent;

our @EXPORT_OK = qw/explode fetch/;

sub explode {
    my $file = shift;
    my $dir = tempdir('fairy-XXXXXX', DIR => File::Spec->tmpdir(), CLEANUP => 1);
    my $ae = Archive::Extract->new(archive => $file);
    eval {
        $ae->extract(to => $dir);
    } or die "Failed to extract ${file}.\n";
    return $dir;
}

sub fetch {
    my ($src, $dst, $flags) = @_;
    File::Path::make_path((File::Spec->splitpath($dst))[1]);
    my $ua = LWP::UserAgent->new(env_proxy => 1);
    my $req = HTTP::Request->new(GET => $src);
    $req->if_modified_since((stat($dst))[9])
        if (-f $dst && !$flags->{force});
    my $res = $ua->request($req)
        or die "LWP::UserAgent request (${src}) failsd: $!\n";
    if ($res->is_success) {
        open my $fh, '>:raw', $dst
            or die "Cannot open `${dst}': $!\n";
        print $fh $res->content;
        close $fh
            or die "Cannot close `${dst}': $!\n";
        utime(time, $res->last_modified, $dst)
            if $res->last_modified;
    } else {
        return unless $res->code == 304;
    }
    return 1;
}

1;

__END__

=pod

=encoding utf8

=head1 NAME

App::Fairy::Utils - Various Fairy utility subroutines

=head1 AUTHOR

Petr Šabata <contyk@redhat.com>

=head1 COPYRIGHT AND LICENSE

Copyright (c) 2015 Petr Šabata

See LICENSE for licensing details.

=cut


text:
require File.expand_path('../../spec_helper', __FILE__)

describe InstancePersistor do
  before do
    recreate_db("http://localhost:5984/instance_spec")

    @instance_persistor = InstancePersistor.new("http://localhost:5984/instance_spec")

    @instance = Instance.new({
                               :_id => 'instance-ID',
                               :job_id => 'job-ID',
                               :instance_id => 'i-42',
                               :public_ipaddress => '1.2.3.4',
                               :public_hostname => '1-2-3-4.dns.com',
                               :created_at => 'A long time ago',
                               :chef_log => 'I am a log',
                               :cloud_provider => 'AWS',
                               :cloud_objects => {
                                 :security_group => 'sg-id',
                                 :key_pair => 'kp-id'
                               },
                               :node_name => 'i-42',
                               :client_name => 'i-42'
                             })

    @instance2 = Instance.new({
                                :_id => 'instance-ID2',
                                :job_id => 'job-ID2',
                                :instance_id => 'i-43',
                                :public_ipaddress => '1.2.3.5',
                                :public_hostname => '1-2-3-5.dns.com',
                                :created_at => 'A longer time ago',
                                :chef_log => 'I am a longer log',
                                :cloud_provider => 'AWS',
                                :cloud_objects => {
                                  :security_group => 'sg-id2',
                                  :key_pair => 'kp-id2'
                                },
                                :node_name => 'i-43',
                                :client_name => 'i-43'
                              })
  end

  it "can retrieve the instance by its id" do
    @instance_persistor.save(@instance)
    retrieved_instance = @instance_persistor.find_by_id(@instance.db_id)
    @instance.should == retrieved_instance
  end

  it "can save more than once" do
    @instance_persistor.save(@instance)
    @instance_persistor.save(@instance)
  end

  it "can fetch documents by job_id" do
    # save these new docs with different job id's than @instance, as
    # there will be many of those (however many steps are enclosed
    # in this 'describe' block)
    instance1 = Instance.new(@instance.to_hash.merge(:_id => "instance-job-fetch-1", :job_id => "job-fetch-1"))
    @instance_persistor.save(instance1)
    instance2 = Instance.new(@instance.to_hash.merge(:_id => "instance-job-fetch-2", :job_id => "job-fetch-2"))
    @instance_persistor.save(instance2)

    # fetching documents by job_id doens't return the chef_log attachment, nor do we want it to
    # this could be a more robust test by checking fields other than the instance_id and job_id
    instances1 = @instance_persistor.find_by_job_id('job-fetch-1')
    instances1.length.should == 1
    inst = instances1.first
    inst.instance_id.should == instance1.instance_id
    inst.job_id.should == instance1.job_id

    instances2 = @instance_persistor.find_by_job_id('job-fetch-2')
    instances2.length.should == 1
    inst = instances2.first
    inst.instance_id.should == instance2.instance_id
    inst.job_id.should == instance2.job_id
  end

  it "can fetch documents by instance_id: #find_by_instance_id positive" do
    @instance_persistor.save(@instance)

    @instance_persistor.find_by_instance_id('i-42').should == @instance
  end

  it "will return nil if a non-existing instance_id is fetched: #find_by_instance_id negative" do
    @instance_persistor.find_by_instance_id('nonesuch').should == nil
  end

  it "can fetch all instances" do
    @instance_persistor.save(@instance)
    @instance_persistor.save(@instance2)
    @instance_persistor.find_all().length.should == 2
  end

end


text:
/**
 * Implementation of the exponentiation operations in mathematics.
 *
 * @author Zezhou Jing, University of Washington
 * @date August 25, 2016
 */
public class Exponentiation {
    // @param x: the base
    // @param n: the exponent
    // @return: the nth power of the base element
    public double pow(double x, int n) {
        // skipped positive and negative infinity cases
        // divide and conquer solution; time complexity O(log n), space O(1)
        // negative powers case, take the reciprocal and change sign
        if (n < 0) {
            return 1 / power(x, -n);
        } else {
            return power(x, n);
        }
    }

    private double power(double x, int n) {
        // base case, any number's zeroth power is 1
        if (n == 0) {
            return 1;
        }
        // recursively divide the power factor
        double halfPow = power(x, n / 2);
        // check odd and even cases and do the calculation
        if (n % 2 == 0) {
            return halfPow * halfPow;
        } else {
            // odd power, multiply by x
            return x * halfPow * halfPow;
        }
    }
}


text:
package TAM;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Interpreter {

	static String objectName;

	// DATA STORE

	static int[] data = new int[1024];

	// DATA STORE REGISTERS AND OTHER REGISTERS

	final static int CB = 0, SB = 0, HB = 1024; // = upper bound of data array +
												// 1

	static int CT, CP, ST, HT, LB, status;

	// status values
	final static int running = 0, halted = 1, failedDataStoreFull = 2,
			failedInvalidCodeAddress = 3, failedInvalidInstruction = 4,
			failedOverflow = 5, failedZeroDivide = 6, failedIOError = 7;

	static long accumulator;

	static int content(int r) {
		// Returns the current content of register r,
		// even if r is one of the pseudo-registers L1..L6.

		switch (r) {
		case Machine.CBr:
			return CB;
		case Machine.CTr:
			return CT;
		case Machine.PBr:
			return Machine.PB;
		case Machine.PTr:
			return Machine.PT;
		case Machine.SBr:
			return SB;
		case Machine.STr:
			return ST;
		case Machine.HBr:
			return HB;
		case Machine.HTr:
			return HT;
		case Machine.LBr:
			return LB;
		case Machine.L1r:
			return data[LB];
		case Machine.L2r:
			return data[data[LB]];
		case Machine.L3r:
			return data[data[data[LB]]];
		case Machine.L4r:
			return data[data[data[data[LB]]]];
		case Machine.L5r:
			return data[data[data[data[data[LB]]]]];
		case Machine.L6r:
			return data[data[data[data[data[data[LB]]]]]];
		case Machine.CPr:
			return CP;
		default:
			return 0;
		}
	}

	// PROGRAM STATUS

	static void dump() {
		// Writes a summary of the machine state.
		int addr, staticLink, dynamicLink, localRegNum;

		System.out.println("");
		System.out.println("State of data store and registers:");
		System.out.println("");
		if (HT == HB)
			System.out
					.println("            |--------|          (heap is empty)");
		else {
			System.out.println("       HB-->");
			System.out.println("            |--------|");
			for (addr = HB - 1; addr >= HT; addr--) {
				System.out.print(addr + ":");
				if (addr == HT)
					System.out.print(" HT-->");
				else
					System.out.print("      ");
				System.out.println("|" + data[addr] + "|");
			}
			System.out.println("            |--------|");
		}
		System.out.println("            |////////|");
		System.out.println("            |////////|");
		if (ST == SB)
			System.out
					.println("            |--------|          (stack is empty)");
		else {
			dynamicLink = LB;
			staticLink = LB;
			localRegNum = Machine.LBr;
			System.out.println("      ST--> |////////|");
			System.out.println("            |--------|");
			for (addr = ST - 1; addr >= SB; addr--) {
				System.out.print(addr + ":");
				if (addr == SB)
					System.out.print(" SB-->");
				else if (addr == staticLink) {
					switch (localRegNum) {
					case Machine.LBr:
						System.out.print(" LB-->");
						break;
					case Machine.L1r:
						System.out.print(" L1-->");
						break;
					case Machine.L2r:
						System.out.print(" L2-->");
						break;
					case Machine.L3r:
						System.out.print(" L3-->");
						break;
					case Machine.L4r:
						System.out.print(" L4-->");
						break;
					case Machine.L5r:
						System.out.print(" L5-->");
						break;
					case Machine.L6r:
						System.out.print(" L6-->");
						break;
					}
					staticLink = data[addr];
					localRegNum = localRegNum + 1;
				} else
					System.out.print("      ");
				if ((addr == dynamicLink) && (dynamicLink != SB))
					System.out.print("|SL=" + data[addr] + "|");
				else if ((addr == dynamicLink + 1) && (dynamicLink != SB))
					System.out.print("|DL=" + data[addr] + "|");
				else if ((addr == dynamicLink + 2) && (dynamicLink != SB))
					System.out.print("|RA=" + data[addr] + "|");
				else
					System.out.print("|" + data[addr] + "|");
				System.out.println("");
				if (addr == dynamicLink) {
					System.out.println("            |--------|");
					dynamicLink = data[addr + 1];
				}
			}
		}
		System.out.println("");
	}

	static void showStatus() {
		// Writes an indication of whether and why the program has terminated.
		System.out.println("");
		switch (status) {
		case running:
			System.out.println("Program is running.");
			break;
		case halted:
			System.out.println("Program has halted normally.");
			break;
		case failedDataStoreFull:
			System.out
					.println("Program has failed due to exhaustion of Data Store.");
			break;
		case failedInvalidCodeAddress:
			System.out
					.println("Program has failed due to an invalid code address.");
			break;
		case failedInvalidInstruction:
			System.out
					.println("Program has failed due to an invalid instruction.");
			break;
		case failedOverflow:
			System.out.println("Program has failed due to overflow.");
			break;
		case failedZeroDivide:
			System.out.println("Program has failed due to division by zero.");
			break;
		case failedIOError:
			System.out.println("Program has failed due to an IO error.");
			break;
		}
		if (status != halted)
			dump();
	}

	// INTERPRETATION

	static void checkSpace(int spaceNeeded) {
		// Signals failure if there is not enough space to expand the stack or
		// heap by spaceNeeded.

		if (HT - ST < spaceNeeded)
			status = failedDataStoreFull;
	}

	static boolean isTrue(int datum) {
		// Tests whether the given datum represents true.
		return (datum == Machine.trueRep);
	}

	static boolean equal(int size, int addr1, int addr2) {
		// Tests whether two multi-word objects are equal, given their common
		// size and their base addresses.

		boolean eq;
		int index;

		eq = true;
		index = 0;
		while (eq && (index < size))
			if (data[addr1 + index] == data[addr2 + index])
				index = index + 1;
			else
				eq = false;
		return eq;
	}

	static int overflowChecked(long datum) {
		// Signals failure if the datum is too large to fit into a single word,
		// otherwise returns the datum as a single word.

		if ((-Machine.maxintRep <= datum) && (datum <= Machine.maxintRep))
			return (int) datum;
		else {
			status = failedOverflow;
			return 0;
		}
	}

	static int toInt(boolean b) {
		return b ? Machine.trueRep : Machine.falseRep;
	}

	static int currentChar;

	static int readInt() throws java.io.IOException {
		int temp = 0;
		int sign = 1;

		do {
			currentChar = System.in.read();
		} while (Character.isWhitespace((char) currentChar));

		if ((currentChar == '-') || (currentChar == '+'))
			do {
				sign = (currentChar == '-') ? -1 : 1;
				currentChar = System.in.read();
			} while ((currentChar == '-') || currentChar == '+');

		if (Character.isDigit((char) currentChar))
			do {
				temp = temp * 10 + (currentChar - '0');
				currentChar = System.in.read();
			} while (Character.isDigit((char) currentChar));

		return sign * temp;
	}

	static void callPrimitive(int primitiveDisplacement) {
		// Invokes the given primitive routine.

		int addr, size;
		char ch;

		switch (primitiveDisplacement) {
		case Machine.idDisplacement:
			break; // nothing to be done
		case Machine.notDisplacement:
			data[ST - 1] = toInt(!isTrue(data[ST - 1]));
			break;
		case Machine.andDisplacement:
			ST = ST - 1;
			data[ST - 1] = toInt(isTrue(data[ST - 1]) & isTrue(data[ST]));
			break;
		case Machine.orDisplacement:
			ST = ST - 1;
			data[ST - 1] = toInt(isTrue(data[ST - 1]) | isTrue(data[ST]));
			break;
		case Machine.succDisplacement:
			data[ST - 1] = overflowChecked(data[ST - 1] + 1);
			break;
		case Machine.predDisplacement:
			data[ST - 1] = overflowChecked(data[ST - 1] - 1);
			break;
		case Machine.negDisplacement:
			data[ST - 1] = -data[ST - 1];
			break;
		case Machine.addDisplacement:
			ST = ST - 1;
			accumulator = data[ST - 1];
			data[ST - 1] = overflowChecked(accumulator + data[ST]);
			break;
		case Machine.subDisplacement:
			ST = ST - 1;
			accumulator = data[ST - 1];
			data[ST - 1] = overflowChecked(accumulator - data[ST]);
			break;
		case Machine.multDisplacement:
			ST = ST - 1;
			accumulator = data[ST - 1];
			data[ST - 1] = overflowChecked(accumulator * data[ST]);
			break;
		case Machine.divDisplacement:
			ST = ST - 1;
			accumulator = data[ST - 1];
			if (data[ST] != 0)
				data[ST - 1] = (int) (accumulator / data[ST]);
			else
				status = failedZeroDivide;
			break;
		case Machine.modDisplacement:
			ST = ST - 1;
			accumulator = data[ST - 1];
			if (data[ST] != 0)
				data[ST - 1] = (int) (accumulator % data[ST]);
			else
				status = failedZeroDivide;
			break;
		case Machine.ltDisplacement:
			ST = ST - 1;
			data[ST - 1] = toInt(data[ST - 1] < data[ST]);
			break;
		case Machine.leDisplacement:
			ST = ST - 1;
			data[ST - 1] = toInt(data[ST - 1] <= data[ST]);
			break;
		case Machine.geDisplacement:
			ST = ST - 1;
			data[ST - 1] = toInt(data[ST - 1] >= data[ST]);
			break;
		case Machine.gtDisplacement:
			ST = ST - 1;
			data[ST - 1] = toInt(data[ST - 1] > data[ST]);
			break;
		case Machine.eqDisplacement:
			size = data[ST - 1]; // size of each comparand
			ST = ST - 2 * size;
			data[ST - 1] = toInt(equal(size, ST - 1, ST - 1 + size));
			break;
		case Machine.neDisplacement:
			size = data[ST - 1]; // size of each comparand
			ST = ST - 2 * size;
			data[ST - 1] = toInt(!equal(size, ST - 1, ST - 1 + size));
			break;
		case Machine.eolDisplacement:
			data[ST] = toInt(currentChar == '\n');
			ST = ST + 1;
			break;
		case Machine.eofDisplacement:
			data[ST] = toInt(currentChar == -1);
			ST = ST + 1;
			break;
		case Machine.getDisplacement:
			ST = ST - 1;
			addr = data[ST];
			try {
				currentChar = System.in.read();
			} catch (java.io.IOException s) {
				status = failedIOError;
			}
			data[addr] = (int) currentChar;
			break;
		case Machine.putDisplacement:
			ST = ST - 1;
			ch = (char) data[ST];
			System.out.print(ch);
			break;
		case Machine.geteolDisplacement:
			try {
				while ((currentChar = System.in.read()) != '\n')
					;
			} catch (java.io.IOException s) {
				status = failedIOError;
			}
			break;
		case Machine.puteolDisplacement:
			System.out.println("");
			break;
		case Machine.getintDisplacement:
			ST = ST - 1;
			addr = data[ST];
			try {
				accumulator = readInt();
			} catch (java.io.IOException s) {
				status = failedIOError;
			}
			data[addr] = (int) accumulator;
			break;
		case Machine.putintDisplacement:
			ST = ST - 1;
			accumulator = data[ST];
			System.out.print(accumulator);
			break;
		case Machine.newDisplacement:
			size = data[ST - 1];
			checkSpace(size);
			HT = HT - size;
			data[ST - 1] = HT;
			break;
		case Machine.disposeDisplacement:
			ST = ST - 1; // no action taken at present
			break;
		}
	}

	static void interpretProgram() {
		// Runs the program in code store.

		Instruction currentInstr;
		int op, r, n, d, addr, index;

		// Initialize registers ...
		ST = SB;
		HT = HB;
		LB = SB;
		CP = CB;
		status = running;
		//Ñ»·Ö´ÐÐÖ¸Áî...
		do {
			// Fetch instruction ...
			currentInstr = Machine.code[CP];
			// Decode instruction ...
			op = currentInstr.op;
			r = currentInstr.r;
			n = currentInstr.n;
			d = currentInstr.d;
			// Execute instruction ...
			switch (op) {
			case Machine.LOADop:
				addr = d + content(r);
				checkSpace(n);
				for (index = 0; index < n; index++)
					data[ST + index] = data[addr + index];
				ST = ST + n;
				CP = CP + 1;
				break;
			case Machine.LOADAop:
				addr = d + content(r);
				checkSpace(1);
				data[ST] = addr;
				ST = ST + 1;
				CP = CP + 1;
				break;
			case Machine.LOADIop:
				ST = ST - 1;
				addr = data[ST];
				checkSpace(n);
				for (index = 0; index < n; index++)
					data[ST + index] = data[addr + index];
				ST = ST + n;
				CP = CP + 1;
				break;
			case Machine.LOADLop:
				checkSpace(1);
				data[ST] = d;
				ST = ST + 1;
				CP = CP + 1;
				break;
			case Machine.STOREop:
				addr = d + content(r);
				ST = ST - n;
				for (index = 0; index < n; index++)
					data[addr + index] = data[ST + index];
				CP = CP + 1;
				break;
			case Machine.STOREIop:
				ST = ST - 1;
				addr = data[ST];
				ST = ST - n;
				for (index = 0; index < n; index++)
					data[addr + index] = data[ST + index];
				CP = CP + 1;
				break;
			case Machine.CALLop:
				addr = d + content(r);
				if (addr >= Machine.PB) {
					callPrimitive(addr - Machine.PB);
					CP = CP + 1;
				} else {
					checkSpace(3);
					if ((0 <= n) && (n <= 15))
						data[ST] = content(n); // static link
					else
						status = failedInvalidInstruction;
					data[ST + 1] = LB; // dynamic link
					data[ST + 2] = CP + 1; // return address
					LB = ST;
					ST = ST + 3;
					CP = addr;
				}
				break;
			case Machine.CALLIop:
				ST = ST - 2;
				addr = data[ST + 1];
				if (addr >= Machine.PB) {
					callPrimitive(addr - Machine.PB);
					CP = CP + 1;
				} else {
					// data[ST] = static link already
					data[ST + 1] = LB; // dynamic link
					data[ST + 2] = CP + 1; // return address
					LB = ST;
					ST = ST + 3;
					CP = addr;
				}
				break;
			case Machine.RETURNop:
				addr = LB - d;
				CP = data[LB + 2];
				LB = data[LB + 1];
				ST = ST - n;
				for (index = 0; index < n; index++)
					data[addr + index] = data[ST + index];
				ST = addr + n;
				break;
			case Machine.PUSHop:
				checkSpace(d);
				ST = ST + d;
				CP = CP + 1;
				break;
			case Machine.POPop:
				addr = ST - n - d;
				ST = ST - n;
				for (index = 0; index < n; index++)
					data[addr + index] = data[ST + index];
				ST = addr + n;
				CP = CP + 1;
				break;
			case Machine.JUMPop:
				CP = d + content(r);
				break;
			case Machine.JUMPIop:
				ST = ST - 1;
				CP = data[ST];
				break;
			case Machine.JUMPIFop:
				ST = ST - 1;
				if (data[ST] == n)
					CP = d + content(r);
				else
					CP = CP + 1;
				break;
			case Machine.HALTop:
				status = halted;
				break;
			}
			if ((CP < CB) || (CP >= CT))
				status = failedInvalidCodeAddress;
		} while (status == running);
	}

	// LOADING

	static void loadObjectProgram(String objectName) {
		// Loads the TAM object program into code store from the named file.

		FileInputStream objectFile = null;
		DataInputStream objectStream = null;

		int addr;
		boolean finished = false;

		try {
			objectFile = new FileInputStream(objectName);
			objectStream = new DataInputStream(objectFile);

			addr = Machine.CB;
			while (!finished) {
				Machine.code[addr] = Instruction.read(objectStream);
				if (Machine.code[addr] == null)
					finished = true;
				else
					addr = addr + 1;
			}
			CT = addr;
			objectFile.close();
		} catch (FileNotFoundException s) {
			CT = CB;
			System.err.println("Error opening object file: " + s);
		} catch (IOException s) {
			CT = CB;
			System.err.println("Error reading object file: " + s);
		}
	}

	// RUNNING

	public static void main(String[] args) {
		System.out
				.println("********** TAM Interpreter (Java Version 2.1) **********");

		if (args.length == 1)
			objectName = args[0];
		else
			objectName = "obj.tam";

		loadObjectProgram(objectName);
		if (CT != CB) {
			interpretProgram();
			showStatus();
		}
	}
}


text:
			<button ng-repeat="type in machineTypes"
					type="button" class="btn btn-default"
					ng-click="toggleMachineType(type)"
					ng-class="{'active':isMachineTypeSelected(type)}">{{type.name}}
			</button>

				{{machine.name}}
				{{machine.introduction}}


text:
package api

// IsBuildDisabled returns true if the builder feature is disabled.
func IsBuildEnabled(config *MasterConfig) bool {
	return !config.DisabledFeatures.Has(FeatureBuilder)
}


text:
(function (angular) {
    'use strict';

    angular
        .module('cogeoApp')
        .controller('GroupsCtrl', GroupsCtrl);

    GroupsCtrl.$inject = [
        'CONFIG',
        'goTo',
        'httpRequest',
        '$state',
        'groupsFactory',
        'userFactory',
        'usersFactory',
        '$filter',
        '$scope',
        'cozenEnhancedLogs',
        'googleGraphGroupMembers',
        'googleGraphGroupStatus',
        'googleGraphGroupChannelsTypes',
        'cozenPopupFactory',
        '$rootScope'
    ];

    function GroupsCtrl(CONFIG, goTo, httpRequest, $state, groupsFactory, userFactory, usersFactory, $filter, $scope,
                        cozenEnhancedLogs, googleGraphGroupMembers, googleGraphGroupStatus, googleGraphGroupChannelsTypes,
                        cozenPopupFactory, $rootScope) {
        var vm = this;

        // Methods
        vm.methods = {
            save             : save,
            onDisplayDetails : onDisplayDetails,
            joinGroup        : joinGroup,
            leaveGroup       : leaveGroup,
            getKickedTime    : Utils.getKickedTime,
            getUserFullName  : usersFactory.getUserFullName,
            onShowAll        : onShowAll,
            getAllLogs       : getAllLogs,
            onRecruitInit    : onRecruitInit,
            recruit          : recruit,
            toggleRecruitMod : toggleRecruitMod,
            startLoading     : startLoading,
            stopLoading      : stopLoading,
            isEmailDuplicated: isEmailDuplicated,
            onInitDetails    : onInitDetails,
            onInitMembers    : onInitMembers
        };

        // Common data
        vm.CONFIG         = CONFIG;
        vm.loading        = false;
        vm.user           = userFactory.getUser();
        vm.groups         = groupsFactory.getGroupsWithUserRoles(vm.user.username);
        vm.all            = angular.merge({}, vm.all, angular.copy(vm.user.settings.preferences.allGroups));
        vm.details        = {};
        vm.edit           = {};
        vm.invitations    = angular.merge({}, vm.invitations, angular.copy(vm.user.settings.preferences.groupsInvitations));
        vm.members        = angular.merge({}, vm.members, angular.copy(vm.user.settings.preferences.groupsMembers));
        vm.log            = angular.merge({}, vm.log, angular.copy(vm.user.settings.preferences.groupsLogs));
        vm.groupsQuantity = groupsFactory.getGroups().length;
        vm.googleGraph    = {};

        // When the user factory is updated
        userFactory.subscribe($scope, function () {
            vm.methods.onDisplayDetails();
            vm.user        = userFactory.getUser();
            vm.invitations = angular.merge({}, vm.invitations, angular.copy(vm.user.settings.preferences.groupsInvitations));
            vm.members     = angular.merge({}, vm.members, angular.copy(vm.user.settings.preferences.groupsMembers));
            vm.log         = angular.merge({}, vm.log, angular.copy(vm.user.settings.preferences.groupsLogs));
            vm.methods.onInitMembers();
        });

        // When the group
        groupsFactory.subscribe($scope, function () {
            vm.methods.onDisplayDetails();
            vm.user        = userFactory.getUser();
            vm.invitations = angular.merge({}, vm.invitations, angular.copy(vm.user.settings.preferences.groupsInvitations));
            vm.members     = angular.merge({}, vm.members, angular.copy(vm.user.settings.preferences.groupsMembers));
            vm.log         = angular.merge({}, vm.log, angular.copy(vm.user.settings.preferences.groupsLogs));
            vm.methods.onInitMembers();
        });

        function save(form) {
            vm.methods.startLoading();
            switch (form) {
                case 'edit':
                    var updatedGroup = {
                        name       : vm.edit.name,
                        description: vm.edit.description,
                        picture    : vm.edit.picture,
                        username   : vm.user.username
                    };
                    groupsFactory.httpRequest.updateGroup(vm.details.group.name, updatedGroup, function () {
                        vm.methods.stopLoading();
                        goTo.view('app.groups.details', {groupName: updatedGroup.name});
                    }, function () {
                        vm.methods.stopLoading();
                        var btn = angular.element(document.querySelector('#submit-edit-group-btn'));
                        httpRequest.shakeElement(btn);
                    });
                    break;
            }
        }

        function onDisplayDetails() {
            vm.user   = userFactory.getUser();
            vm.params = $state.params;
            var name  = $state.params.groupName;
            var group = groupsFactory.getGroupByNameWithUserRoles(name, vm.user.username);
            if (group != null) {
                vm.details.group         = group;
                vm.details.user          = groupsFactory.getUserFromGroup(vm.user.username, name);
                vm.details.userIsInGroup = vm.details.user != null ? vm.details.user.hasLeft == 0 : false;
                vm.details.userIsAdmin   = vm.details.user != null ? vm.details.user.admin : false;
                vm.details.userHasRights = groupsFactory.doesUserHasRights(vm.details.user);
                vm.edit                  = angular.copy(group);
                vm.groupInvitations      = usersFactory.addUsersFullNames(group.invitations);
                vm.groupMembers          = groupsFactory.getActiveUsers(name);
                vm.logs                  = angular.copy(group.logs);
                if (!Methods.isNullOrEmpty(vm.logs)) {
                    vm.logs.forEach(function (log) {
                        log.text          = $filter('translate')('groups_log_' + log.tag, log.values);
                        log.formattedDate = $filter('date')(log.date, 'EEEE dd MMMM yyyy');
                        log.formattedDate += ' ';
                        log.formattedDate += $filter('translate')('other_time_at');
                        log.formattedDate += ' ';
                        log.formattedDate += $filter('date')(log.date, 'HH:mm');
                    });
                }

                // Send message to redraw graph
                $rootScope.$broadcast('cozenDrawChart');
                $rootScope.$broadcast('drawChartValuesInit');
            }
        }

        function joinGroup(groupName) {
            cozenPopupFactory.show({
                name: 'groupJoin',
                data: {
                    groupName: groupName
                }
            });
        }

        function leaveGroup($event, groupName) {
            $event.stopPropagation();
            cozenPopupFactory.show({
                name: 'groupLeave',
                data: {
                    groupName: groupName
                }
            });
        }

        function onShowAll() {
            vm.groups = groupsFactory.getGroupsWithUserRoles(vm.user.username);

            // It will hide the edit btn
            vm.details.userIsAdmin = false;
        }

        function getAllLogs() {
            vm.log.all = true;
        }

        function onRecruitInit() {
            vm.availableUsers = groupsFactory.getAvailableUsers($state.params.groupName);
            vm.recruitMod     = 'users';
            vm.recruitEmail   = [
                {
                    email: ''
                }
            ];
        }

        function recruit(type) {
            vm.methods.startLoading();

            // Common data
            var data = {
                username: vm.details.user.username
            };

            // Update the data
            switch (type) {
                case 'cogeoUsers':
                    data.invitations = vm.availableUsersSelected;
                    data.request     = 'sendCogeoInvitations';
                    break;
                case 'cogeoEmail':
                    data.invitations = vm.recruitEmail;
                    data.request     = 'sendEmailInvitations';
                    break;
            }
            if (CONFIG.dev) {
                cozenEnhancedLogs.info.explodeObject('GroupsCtrl', 'recruit() executed', data);
            }

            // Execute the request
            groupsFactory.httpRequest[data.request](vm.params.groupName, data, function () {
                vm.methods.stopLoading();
                goTo.view('app.groups.invitations', {
                    groupName: vm.params.groupName
                });
            }, function () {
                vm.methods.stopLoading();
                var btn = angular.element(document.querySelector('#submit-recruit-group-btn'));
                httpRequest.shakeElement(btn);
            });
        }

        function toggleRecruitMod() {
            vm.recruitMod = vm.recruitMod == 'users' ? 'email' : 'users';
        }

        function startLoading() {
            vm.loading = true;
        }

        function stopLoading() {
            vm.loading = false;
        }

        function isEmailDuplicated() {
            var emails = [];
            angular.forEach(vm.recruitEmail, function (email) {
                emails.push(email.email);
            });
            return Methods.hasDuplicates(emails);
        }

        function onInitDetails() {

            // Get the google graph for members
            vm.googleGraph.members       = googleGraphGroupMembers.getChart($state.params.groupName);
            vm.googleGraph.status        = googleGraphGroupStatus.getChart($state.params.groupName);
            vm.googleGraph.channelsTypes = googleGraphGroupChannelsTypes.getChart($state.params.groupName);
        }

        function onInitMembers() {
            vm.membersList = groupsFactory.getAllUsersExceptHasLeft($state.params.groupName);
            vm.membersList = usersFactory.addUsersFullNames(vm.membersList);
        }
    }

})(window.angular);


text:
#include "third_party/blink/renderer/core/editing/frame_caret.h"

#include "base/location.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/editing/caret_display_item_client.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/local_caret_rect.h"
#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
#include "third_party/blink/renderer/core/editing/selection_editor.h"
#include "third_party/blink/renderer/core/editing/visible_position.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/html/forms/text_control_element.h"
#include "third_party/blink/renderer/core/layout/layout_block.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h"

namespace blink {

namespace {

}  // anonymous namespace

FrameCaret::FrameCaret(LocalFrame& frame,
                       const SelectionEditor& selection_editor)
    : selection_editor_(&selection_editor),
      frame_(frame),
      display_item_client_(MakeGarbageCollected<CaretDisplayItemClient>()),
      caret_blink_timer_(frame.GetTaskRunner(TaskType::kInternalDefault),
                         this,
                         &FrameCaret::CaretBlinkTimerFired),
      effect_(EffectPaintPropertyNode::Create(
          EffectPaintPropertyNode::Root(),
          CaretEffectNodeState(/*visible*/ true,
                               TransformPaintPropertyNode::Root()))) {
#if DCHECK_IS_ON()
  effect_->SetDebugName("Caret");
#endif
}

FrameCaret::~FrameCaret() = default;

void FrameCaret::Trace(Visitor* visitor) const {
  visitor->Trace(selection_editor_);
  visitor->Trace(frame_);
  visitor->Trace(display_item_client_);
  visitor->Trace(caret_blink_timer_);
}

EffectPaintPropertyNode::State FrameCaret::CaretEffectNodeState(
    bool visible,
    const TransformPaintPropertyNodeOrAlias& local_transform_space) const {
  EffectPaintPropertyNode::State state;
  // Use 0.001f instead of 0 to ensure cc will add quad for the caret layer.
  // This is especially useful on Mac to limit the damage during caret blinking
  // within the CALayer for the caret.
  state.opacity = visible ? 1.f : 0.001f;
  state.local_transform_space = &local_transform_space;
  DEFINE_STATIC_LOCAL(
      CompositorElementId, element_id,
      (CompositorElementIdFromUniqueObjectId(
          NewUniqueObjectId(), CompositorElementIdNamespace::kPrimaryEffect)));
  state.compositor_element_id = element_id;
  state.direct_compositing_reasons = CompositingReason::kActiveOpacityAnimation;
  return state;
}

const PositionWithAffinity FrameCaret::CaretPosition() const {
  const VisibleSelection& selection =
      selection_editor_->ComputeVisibleSelectionInDOMTree();
  if (!selection.IsCaret())
    return PositionWithAffinity();
  DCHECK(selection.Start().IsValidFor(*frame_->GetDocument()));
  return PositionWithAffinity(selection.Start(), selection.Affinity());
}

bool FrameCaret::IsActive() const {
  return CaretPosition().IsNotNull();
}

void FrameCaret::UpdateAppearance() {
  DCHECK_GE(frame_->GetDocument()->Lifecycle().GetState(),
            DocumentLifecycle::kLayoutClean);

  bool new_should_show_caret = ShouldShowCaret();
  if (new_should_show_caret != should_show_caret_) {
    should_show_caret_ = new_should_show_caret;
    ScheduleVisualUpdateForPaintInvalidationIfNeeded();
  }

  if (!should_show_caret_) {
    StopCaretBlinkTimer();
    return;
  }
  // Start blinking with a black caret. Be sure not to restart if we're
  // already blinking in the right location.
  StartBlinkCaret();
}

void FrameCaret::StopCaretBlinkTimer() {
  if (caret_blink_timer_.IsActive() || IsVisibleIfActive())
    ScheduleVisualUpdateForPaintInvalidationIfNeeded();
  caret_blink_timer_.Stop();
  display_item_client_->SetActive(false);
  SetVisibleIfActive(false);
}

void FrameCaret::StartBlinkCaret() {
  // Start blinking with a black caret. Be sure not to restart if we're
  // already blinking in the right location.
  if (caret_blink_timer_.IsActive())
    return;

  base::TimeDelta blink_interval = LayoutTheme::GetTheme().CaretBlinkInterval();
  if (!blink_interval.is_zero())
    caret_blink_timer_.StartRepeating(blink_interval, FROM_HERE);

  display_item_client_->SetActive(true);
  SetVisibleIfActive(true);
  ScheduleVisualUpdateForPaintInvalidationIfNeeded();
}

void FrameCaret::SetCaretEnabled(bool enabled) {
  if (is_caret_enabled_ == enabled)
    return;

  is_caret_enabled_ = enabled;

  if (!is_caret_enabled_)
    StopCaretBlinkTimer();
  ScheduleVisualUpdateForPaintInvalidationIfNeeded();
}

void FrameCaret::LayoutBlockWillBeDestroyed(const LayoutBlock& block) {
  display_item_client_->LayoutBlockWillBeDestroyed(block);
}

void FrameCaret::UpdateStyleAndLayoutIfNeeded() {
  DCHECK_GE(frame_->GetDocument()->Lifecycle().GetState(),
            DocumentLifecycle::kLayoutClean);
  UpdateAppearance();
  display_item_client_->UpdateStyleAndLayoutIfNeeded(
      should_show_caret_ ? CaretPosition() : PositionWithAffinity());
}

void FrameCaret::InvalidatePaint(const LayoutBlock& block,
                                 const PaintInvalidatorContext& context) {
  display_item_client_->InvalidatePaint(block, context);
}

gfx::Rect FrameCaret::AbsoluteCaretBounds() const {
  DCHECK_NE(frame_->GetDocument()->Lifecycle().GetState(),
            DocumentLifecycle::kInPrePaint);
  DCHECK(!frame_->GetDocument()->NeedsLayoutTreeUpdate());
  DocumentLifecycle::DisallowTransitionScope disallow_transition(
      frame_->GetDocument()->Lifecycle());

  return AbsoluteCaretBoundsOf(CaretPosition());
}

bool FrameCaret::ShouldPaintCaret(const LayoutBlock& block) const {
  return display_item_client_->ShouldPaintCaret(block);
}

bool FrameCaret::ShouldPaintCaret(
    const NGPhysicalBoxFragment& box_fragment) const {
  return display_item_client_->ShouldPaintCaret(box_fragment);
}

void FrameCaret::SetVisibleIfActive(bool visible) {
  if (visible == IsVisibleIfActive())
    return;

  DCHECK(frame_);
  DCHECK(effect_);
  if (!frame_->View())
    return;

  auto change_type = effect_->Update(
      *effect_->Parent(),
      CaretEffectNodeState(visible, effect_->LocalTransformSpace()));
  DCHECK_EQ(PaintPropertyChangeType::kChangedOnlySimpleValues, change_type);
  if (auto* compositor = frame_->View()->GetPaintArtifactCompositor()) {
    if (compositor->DirectlyUpdateCompositedOpacityValue(*effect_)) {
      effect_->CompositorSimpleValuesUpdated();
      return;
    }
  }
  // Fallback to full update if direct update is not available.
  frame_->View()->SetPaintArtifactCompositorNeedsUpdate(
      PaintArtifactCompositorUpdateReason::kFrameCaretSetVisible);
}

void FrameCaret::PaintCaret(GraphicsContext& context,
                            const PhysicalOffset& paint_offset) const {
  if (effect_->Update(
          context.GetPaintController().CurrentPaintChunkProperties().Effect(),
          CaretEffectNodeState(IsVisibleIfActive(),
                               context.GetPaintController()
                                   .CurrentPaintChunkProperties()
                                   .Transform())) !=
      PaintPropertyChangeType::kUnchanged) {
    // Needs full PaintArtifactCompositor update if the parent or the local
    // transform space changed.
    frame_->View()->SetPaintArtifactCompositorNeedsUpdate(
        PaintArtifactCompositorUpdateReason::kFrameCaretPaint);
  }
  ScopedPaintChunkProperties scoped_properties(context.GetPaintController(),
                                               *effect_, *display_item_client_,
                                               DisplayItem::kCaret);

  display_item_client_->PaintCaret(context, paint_offset, DisplayItem::kCaret);
  if (frame_->Selection().IsHandleVisible() && !frame_->Selection().IsHidden())
    display_item_client_->RecordSelection(context, paint_offset);
}

bool FrameCaret::ShouldShowCaret() const {
  // Don't show the caret if it isn't visible or positioned.
  if (!is_caret_enabled_ || !IsActive())
    return false;

  Element* root = RootEditableElementOf(CaretPosition().GetPosition());
  if (root) {
    // Caret is contained in editable content. If there is no focused element,
    // don't show the caret.
    Element* focused_element = root->GetDocument().FocusedElement();
    if (!focused_element)
      return false;
  } else {
    // Caret is not contained in editable content--see if caret browsing is
    // enabled. If it isn't, don't show the caret.
    if (!frame_->IsCaretBrowsingEnabled())
      return false;
  }

  if (!IsEditablePosition(
          selection_editor_->ComputeVisibleSelectionInDOMTree().Start()) &&
      !frame_->IsCaretBrowsingEnabled())
    return false;

  // Only show the caret if the selection has focus.
  return frame_->Selection().SelectionHasFocus();
}

void FrameCaret::CaretBlinkTimerFired(TimerBase*) {
  DCHECK(is_caret_enabled_);
  if (IsCaretBlinkingSuspended() && IsVisibleIfActive())
    return;
  SetVisibleIfActive(!IsVisibleIfActive());
  ScheduleVisualUpdateForPaintInvalidationIfNeeded();
}

void FrameCaret::ScheduleVisualUpdateForPaintInvalidationIfNeeded() {
  if (LocalFrameView* frame_view = frame_->View())
    frame_view->ScheduleVisualUpdateForPaintInvalidationIfNeeded();
}

void FrameCaret::RecreateCaretBlinkTimerForTesting(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    const base::TickClock* tick_clock) {
  caret_blink_timer_.SetTaskRunnerForTesting(std::move(task_runner),
                                             tick_clock);
}

}  // namespace blink


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

package com.google.devtools.build.lib.analysis.config;

import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleTransitionFactory;

/**
 * A {@link RuleTransitionFactory} that composes other {@link RuleTransitionFactory}s.
 */
public class ComposingRuleTransitionFactory implements RuleTransitionFactory {

  private final RuleTransitionFactory rtf1;
  private final RuleTransitionFactory rtf2;

  /**
   * Creates a factory that applies the given factories in-order ({@code rtf1} first,
   * {@code rtf2} second).
   */
  public ComposingRuleTransitionFactory(RuleTransitionFactory rtf1, RuleTransitionFactory rtf2) {
    this.rtf1 = rtf1;
    this.rtf2 = rtf2;
  }

  @Override
  public Attribute.Transition buildTransitionFor(Rule rule) {
    PatchTransition transition1 = (PatchTransition) rtf1.buildTransitionFor(rule);
    PatchTransition transition2 = (PatchTransition) rtf2.buildTransitionFor(rule);

    if (transition1 == null) {
      return transition2;
    }

    if (transition2 == null) {
      return transition1;
    }

    return new ComposingPatchTransition(
        (PatchTransition) rtf1.buildTransitionFor(rule),
        (PatchTransition) rtf2.buildTransitionFor(rule));
  }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../tokio_threadpool/struct.Builder.html">

Redirecting to ../../tokio_threadpool/struct.Builder.html...


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

  <parent>
    <groupId>io.github.valters.build</groupId>
    <artifactId>xsdiff-parent</artifactId>
    <version>1.2.0</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <groupId>io.github.valters</groupId>
  <artifactId>xsdiff</artifactId>
  <packaging>jar</packaging>
  <name>${project.groupId}:${project.artifactId}</name>
  <description>Compares XML XSD schemas providing simple and straight differences report</description>

  <url>http://valters.github.io/xsdiff/</url>
  <licenses>
    <license>
      <name>Apache License Version 2.0, January 2004</name>
      <url>http://www.apache.org/licenses/</url>
    </license>
  </licenses>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.xmlunit</groupId>
      <artifactId>xmlunit-core</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
    </dependency>

    <dependency>
      <groupId>org.ahocorasick</groupId>
      <artifactId>ahocorasick</artifactId>
    </dependency>

    <dependency>
      <groupId>io.github.valters</groupId>
      <artifactId>daisydiff</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-integration</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using System.Web.UI.WebControls;

namespace AuditoriaParlamentar.Classes
{
    public class SuspeitasFornecedor
    {
        public void CarregaSuspeitas()
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("   SELECT txtCNPJCPF, cast(txtNumero as decimal) as txtNumero");
            sql.Append("     FROM lancamentos ");
            sql.Append("    WHERE txtCNPJCPF NOT IN (SELECT txtCNPJCPF FROM fornecedores_suspeitos)");
            sql.Append("      AND txtCNPJCPF NOT IN (SELECT txtCNPJCPF FROM denuncias)");
            //sql.Append("      AND txtCNPJCPF = '00547345000160'");
            sql.Append(" ORDER BY txtCNPJCPF, cast(txtNumero as decimal)");

            using (Banco banco = new Banco())
            {
                for (int qtd = 10; qtd >= 3; qtd--)
                {
                    DataTable tableLan = new DataTable("lancamentos");

                    using (MySqlDataReader reader = banco.ExecuteReader(sql.ToString(), 300))
                    {
                        tableLan.Load(reader);
                    }

                    String oldCnpjCpf = "";
                    Int64[] notas = new Int64[10];

                    foreach (DataRow rowLan in tableLan.Rows)
                    {
                        if (oldCnpjCpf != rowLan["txtCNPJCPF"].ToString())
                        {
                            for (int i = 0; i < 10; i++)
                                notas[i] = 0;
                        }

                        oldCnpjCpf = rowLan["txtCNPJCPF"].ToString();

                        try
                        {
                            for(int i = qtd - 1; i > 0; i--)
                                notas[i] = notas[i-1];

                            Int64.TryParse(rowLan["txtNumero"].ToString(), out notas[0]);

                            Int64 soma = 0;
                            for (int i = 0; i < 9; i++)
                                if (notas[i] > 0 && notas[i + 1] > 0)
                                    if (notas[i] - notas[i + 1] == 1)
                                        soma += 1;

                            if (soma == qtd -1)
                            {
                                banco.AddParameter("txtCNPJCPF", rowLan["txtCNPJCPF"].ToString());
                                banco.ExecuteNonQuery("INSERT INTO fornecedores_suspeitos (txtCNPJCPF, tipoSuspeita, descricao) VALUES (@txtCNPJCPF, 1, 'Notas Fiscais em Sequência: " + qtd.ToString("00") + "')");
                            }
                        }
                        catch (Exception ex)
                        {
                            for (int i = 0; i < 10; i++)
                                notas[i] = 0;
                        }
                    }
                }
            }
        }

        public static String StringStatus()
        {
            StringBuilder status = new StringBuilder();

            status.Append(" CASE fornecedores_suspeitos.tipoSuspeita");
            status.Append("     WHEN 1 THEN 'Notas em sequência'");
            status.Append("     ELSE ''");
            status.Append(" END AS tipoSuspeita");

            return status.ToString();
        }

        public void CarregaGrid(GridView grid)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("   SELECT fornecedores_suspeitos.UserName,");
            sql.Append("          fornecedores.txtCNPJCPF,");
            sql.Append("          SUBSTRING(fornecedores.txtBeneficiario, 1, 50) AS txtbeneficiario,");
            sql.Append("          fornecedores.Uf,");
            sql.Append("          fornecedores.Cidade,");
            sql.Append("          fornecedores_suspeitos.descricao");
            sql.Append("     FROM fornecedores_suspeitos, fornecedores");
            sql.Append("    WHERE fornecedores_suspeitos.txtCNPJCPF = fornecedores.txtCNPJCPF");
            sql.Append(" ORDER BY fornecedores_suspeitos.descricao DESC");

            using (Banco banco = new Banco())
            {
                using (MySqlDataReader reader = banco.ExecuteReader(sql.ToString(), 300))
                {
                    DataTable table = new DataTable("fornecedores_suspeitos");
                    table.Load(reader);

                    table.Columns[0].ColumnName = "Usuário";
                    table.Columns[1].ColumnName = "CNPJ/CPF";
                    table.Columns[2].ColumnName = "Razão Social";
                    table.Columns[3].ColumnName = "UF";
                    table.Columns[4].ColumnName = "Cidade";
                    table.Columns[5].ColumnName = "Suspeita";

                    grid.DataSource = table;
                    grid.DataBind();
                }
            }
        }

        public Boolean DefineUsuario(String userName, String txtCNPJCPF)
        {
            Int64 retorno = 0;
            StringBuilder sql = new StringBuilder();

            sql.Append("UPDATE fornecedores_suspeitos");
            sql.Append("   SET UserName          = @UserName");
            sql.Append(" WHERE txtCNPJCPF        = @txtCNPJCPF");
            sql.Append("   AND UserName          IS NULL");

            using (Banco banco = new Banco())
            {
                banco.AddParameter("UserName", userName);
                banco.AddParameter("txtCNPJCPF", txtCNPJCPF);

                banco.ExecuteNonQuery(sql.ToString());
                retorno = banco.Rows;
            }

            return (retorno > 0);
        }

        public Boolean RemoveUsuario(String userName, String txtCNPJCPF)
        {
            Int64 retorno = 0;
            StringBuilder sql = new StringBuilder();

            sql.Append("UPDATE fornecedores_suspeitos");
            sql.Append("   SET UserName          = NULL");
            sql.Append(" WHERE txtCNPJCPF        = @txtCNPJCPF");
            sql.Append("   AND UserName          = @UserName");

            using (Banco banco = new Banco())
            {
                banco.AddParameter("UserName", userName);
                banco.AddParameter("txtCNPJCPF", txtCNPJCPF);

                banco.ExecuteNonQuery(sql.ToString());
                retorno = banco.Rows;
            }

            return (retorno > 0);
        }
    }
}


text:
return {
  name = "LuaJIT gfx sandbox",
  description = "LuaJIT GFX Sandbox interpreter with debugger",
  api = {"baselib","luajit2","glfw3","glewgl", "shaderc", "vulkan1",},
  luaversion = '5.1',
  frun = function(self,wfilename,rundebug)
    local binpath = ide.config.path.luajitgfxsandbox or os.getenv("LUAJIT_GFX_SANDBOX_PATH")
    if not binpath then
      ide:Print("Failed to determine binary directory")
      return
    end
    local exe = binpath.."/luajit.cmd"
    local filepath = wfilename:GetFullPath()

    do
      -- if running on Windows and can't open the file, this may mean that
      -- the file path includes unicode characters that need special handling
      local fh = io.open(filepath, "r")
      if fh then fh:close() end
      if ide.osname == 'Windows' and pcall(require, "winapi")
      and wfilename:FileExists() and not fh then
        winapi.set_encoding(winapi.CP_UTF8)
        local shortpath = winapi.short_path(filepath)
        if shortpath == filepath then
          ide:Print(
            ("Can't get short path for a Unicode file name '%s' to open the file.")
            :format(filepath))
          ide:Print(
            ("You can enable short names by using `fsutil 8dot3name set %s: 0` and recreate the file or directory.")
            :format(wfilename:GetVolume()))
        end
        filepath = shortpath
      end
    end

    if rundebug then
      ide:GetDebugger():SetOptions({runstart = ide.config.debugger.runonstart == true})

      -- update arg to point to the proper file
      rundebug = ('if arg then arg[0] = [[%s]] end '):format(filepath)..rundebug

      local tmpfile = wx.wxFileName()
      tmpfile:AssignTempFileName(".")
      filepath = tmpfile:GetFullPath()
      local f = io.open(filepath, "w")
      if not f then
        ide:Print("Can't open temporary file '"..filepath.."' for writing.")
        return
      end
      f:write(rundebug)
      f:close()
    end
    local params = self:GetCommandLineArg("lua")
    local code = ([["%s"]]):format(filepath)
    local cmd = '"'..exe..'" '..code..(params and " "..params or "")

    -- CommandLineRun(cmd,wdir,tooutput,nohide,stringcallback,uid,endcallback)
    local pid = CommandLineRun(cmd,self:fworkdir(wfilename),true,false,nil,nil,
      function() if rundebug then wx.wxRemoveFile(filepath) end end)

    return pid
  end,
  hasdebugger = true,
  scratchextloop = false,
  unhideanywindow = true,
  takeparameters = true,
}


text:
package org.apache.hadoop.hbase.rest.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;

/**
 * A list of 'host:port' addresses of HTTP servers operating as a single
 * entity, for example multiple redundant web service gateways.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class Cluster {
  protected List<String> nodes =
    Collections.synchronizedList(new ArrayList<String>());
  protected String lastHost;

  /**
   * Constructor
   */
  public Cluster() {}

  /**
   * Constructor
   * @param nodes a list of service locations, in 'host:port' format
   */
  public Cluster(List<String> nodes) {
    nodes.addAll(nodes);
  }

  /**
   * @return true if no locations have been added, false otherwise
   */
  public boolean isEmpty() {
    return nodes.isEmpty();
  }

  /**
   * Add a node to the cluster
   * @param node the service location in 'host:port' format
   */
  public Cluster add(String node) {
    nodes.add(node);
    return this;
  }

  /**
   * Add a node to the cluster
   * @param name host name
   * @param port service port
   */
  public Cluster add(String name, int port) {
    StringBuilder sb = new StringBuilder();
    sb.append(name);
    sb.append(':');
    sb.append(port);
    return add(sb.toString());
  }

  /**
   * Remove a node from the cluster
   * @param node the service location in 'host:port' format
   */
  public Cluster remove(String node) {
    nodes.remove(node);
    return this;
  }

  /**
   * Remove a node from the cluster
   * @param name host name
   * @param port service port
   */
  public Cluster remove(String name, int port) {
    StringBuilder sb = new StringBuilder();
    sb.append(name);
    sb.append(':');
    sb.append(port);
    return remove(sb.toString());
  }
}


text:
package org.jetbrains.plugins.groovy.lang.completion;

import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.lookup.LookupElement;
import org.jetbrains.plugins.groovy.lang.groovydoc.completion.handlers.GroovyDocMethodHandler;

/**
 * @author ilyas
 */
public class GroovyInsertHandlerAdapter implements InsertHandler {
  private final GroovyDocMethodHandler myGroovyDocMethodHandler = new GroovyDocMethodHandler();

  public void handleInsert(InsertionContext context, LookupElement item) {
    if (myGroovyDocMethodHandler.isAcceptable(context, context.getStartOffset(), item)) {
      myGroovyDocMethodHandler.handleInsert(context, context.getStartOffset(), item);
      return;
    }

    GroovyInsertHandler.INSTANCE.handleInsert(context, item);
  }
}


text:
class Cms::Comment < ApplicationRecord
  belongs_to :user
  belongs_to :article, class_name: 'Cms::Article'

  validates :user_id, :article_id, :body, presence: true
end


text:
import * as R from 'ramda'
import { combineReducers } from 'redux'
import { FETCH_OPERATIONS_SUCCESS } from 'Coopcon/data/operation/actions'

const idsDefault = []
const ids = (state = idsDefault, action) => {
  switch(action.type) {
    case FETCH_OPERATIONS_SUCCESS:
      return R.union(
        R.compose(
          R.pluck('_id'),
          R.pluck('producer'),
        )(action.operations),
      )(state)
    default:
      return state
  }
}

const byIdDefault = {}
const byId = (state = byIdDefault, action) => {
  switch(action.type) {
    case FETCH_OPERATIONS_SUCCESS:
      return R.mergeDeepLeft(
        R.compose(
          R.indexBy(R.prop('_id')),
          R.pluck('producer'),
        )(action.operations),
      )(state)
    default:
      return state
  }
}

export default combineReducers({
  ids,
  byId,
})


text:
/**
 * Get the URL of the current active tab
 *
 * @param {function(string)} callback - called when the URL of the current tab is found
 */

function getCurrentTabUrl(callback) {
  // Query filter to be passed to chrome.tabs.query
  var queryInfo = {
    active: true,
    currentWindow: true
  };
  // Search for tabs matching the specified criteria
  chrome.tabs.query(queryInfo, function(tabs) {
    // Extract and return tab URL
    callback(tabs[0].url);
  });
}

function ebxGetAccountId(callback) {
  ebxGetCookie('accountId', callback);
}

function ebxGetAuthToken(callback) {
  ebxGetCookie('authToken', callback);
}

function ebxGetCookie(name, callback) {
  // Attempt to locate specified Echobox cookie
  chrome.cookies.getAll({ 'name': 'echobox.' + name, 'domain': 'echoboxapp.com' }, function (cookies) {
    if (cookies.length === 0) {
      // Cookie not found - return undefined
      callback();
    } else {
      // Cookie found - return cookie value
      callback(cookies[0].value);
    }
  });
}

function ebxGetAccountInfo(accountId, authToken, callback) {
  // Return account info for the specified account
  accountId = [].concat(accountId); // Cooerce accountId into an array due to weird endpoint
  var api = 'https://secure.echoboxapp.com/api/account'; // TODO - set this somewhere else
  $.ajax({
    type: 'GET',
    url: api,
    cache: false,
    data: {
      authToken: authToken, // TODO - set somewhere else e.g. in local storage on background page (when we have one)
      accountIds: accountId
    },
    success: callback,
    error: function (xhr, status, errorThrown) {
      console.log(xhr);
    }
  });
}

function ebxGetPageInfo(url, authToken, callback) {
  // Scrape page info for the specified URL
  var api = 'https://secure.echoboxapp.com/api/urlinfo'; // TODO - set this somewhere else
  $.ajax({
    type: 'GET',
    url: api,
    cache: false,
    data: {
      authToken: authToken, // TODO - set somewhere else e.g. in local storage on background page (when we have one)
      longURL: url
    },
    success: callback,
    error: function (xhr, status, errorThrown) {
      renderError('Something went wrong');
    }
  });
}

function renderContent(contentText) {
  $('.content').html(contentText);
}

function renderError(errorMessage) {
  renderTitle('Error');
  renderContent('
' + errorMessage + '
');
}

function renderFormError(errorMessage) {
  $('.message').html(errorMessage).show();
}

function renderLoading() {
  renderTitle('Loading extension...');
  renderContent('\

\
  \

\
  ');
  var interval = 1000;
  setInterval(function () {
    $('.loading img').fadeOut(interval / 2).fadeIn(interval / 2);
  }, interval);
}

function renderSelectNetwork(authToken, pageInfo, accountApiList) {
  renderTitle('Select Network(s)');
  var selectNetwork = '\

Schedule this article to the following network(s):
\
<form>';
  var accountApi, i;
  for (i = 0; i < accountApiList.length; i++) {
    accountApi = accountApiList[i];
    selectNetwork += '\
<input class="checkbox" name="accountApiId" type="checkbox" value="' + accountApi.accountApiId + '"> ' + accountApi.apiPostName + '
\
    ';
  }
  selectNetwork += '\

\
Schedule\
Cancel\

\
</form>\
  ';
  renderContent(selectNetwork);
  $('.submit').unbind();
  $('.submit').on('click', function () {
    var accountApis = [];
    $('input[name="accountApiId"]:checked').each(function () {
      accountApis.push(this.value);
    });
    if (accountApis.length === 0) {
      renderFormError('No networks selected');
      return;
    }
    alert('Hang on, I haven\'t build this bit yet!');
  });
  $('.cancel').unbind();
  $('.cancel').on('click', function () {
    window.close();
  });
}

function renderTitle(titleText) {
  $('.title').html(titleText);
}

document.addEventListener('DOMContentLoaded', function() {
  renderLoading();
  ebxGetAuthToken(function (authToken) {
    if (authToken) {
      getCurrentTabUrl(function (url) {
        renderTitle('Getting page info...');
        ebxGetPageInfo(url, authToken, function (pageInfo) {
          ebxGetAccountId(function (accountId) {
            renderTitle('Getting account info...');
            ebxGetAccountInfo(accountId, authToken, function (accountDetails) {
              var accountInfo = accountDetails.entries[0];
              if (accountInfo.accountStateId !== 3) {
                renderError('
Account not active
');
                return;
              }
              var accountApiList = [], i, accountApi;
              for (i = 0; i< accountInfo.accountApi.length; i++) {
                accountApi = accountInfo.accountApi[i];
                if ((accountApi.apiTypeId === 2 || accountApi.apiTypeId === 3) && accountApi.apiStateId === 1) {
                  accountApiList.push({
                    accountApiId: accountApi.accountApiId,
                    apiTypeId: accountApi.apiTypeId,
                    apiPostName: accountApi.apiPostName,
                    apiPostImage: accountApi.apiPostImage
                  });
                }
              }
              if (accountApiList.length === 0) {
                renderError('
No active networks
');
              }
              renderSelectNetwork(authToken, pageInfo, accountApiList);
            });
          });
        });
      });
    } else {
      renderError('You are not logged into Echobox');
    }
  })
});


text:
package net.krinsoft.teleportsuite.commands;

import net.krinsoft.teleportsuite.Request;
import net.krinsoft.teleportsuite.TeleportSuite;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;

import java.util.List;

/**
 * @author krinsdeath
 */
public class TPAHereCommand extends TeleportCommand {

    public TPAHereCommand(TeleportSuite plugin) {
        super(plugin);
        setName("TeleportSuite: TPA Here");
        setCommandUsage(  ChatColor.GREEN + "/tpahere" + ChatColor.GOLD + " [PLAYER]");
        addCommandExample(ChatColor.GREEN + "/tpahere" + ChatColor.GOLD + " Njodi   " + ChatColor.WHITE + " -- Ask Njodi to teleport to you.");
        setArgRange(1, 1);
        addKey("teleport tpahere");
        addKey("tps tpahere");
        addKey("tpahere");
        setPermission("teleport.tpahere", "Allows users to request a teleport with /tpahere.", PermissionDefault.TRUE);
    }

    public void runCommand(CommandSender sender, List<String> args) {
        super.runTeleport(sender, args.get(0), Request.Type.TPAHERE);
    }
}


text:
ZAP Scanners
============
The registry of scanners' (passive, active, custom...) IDs.

Format: `<ID> <NAME>`

If the scanner is no longer in use: `<ID> <NAME> [Deprecated]`

Scanners:
```
0       Directory browsing
1       Potential File Path Manipulation
2       Private IP disclosure
3       Session ID in URL rewrite
4       Obsolete file [Deprecated]
5       Obsolete file extended check [Deprecated]
6       Directory/Path traversal
7       Remote File Inclusion

41      Source Code Disclosure - Git
42      Source Code Disclosure - SVN
43      Source Code Disclosure - File Inclusion

10000   Password Autocomplete in browser [Deprecated]
10001   Secure page browser cache [Deprecated]

10009   In Page Banner Info Leak
10010   Cookie set without HttpOnly flag
10011   Cookie set without secure flag
10012   Password Autocomplete in browser [Deprecated]
10013   Weak HTTP authentication over an unsecured connection [Deprecated]
10014   Cross Site Request Forgery [Deprecated]
10015   Incomplete or no cache-control and pragma HTTPHeader set
10016   Web Browser XSS Protection Not Enabled
10017   Cross-domain JavaScript source file inclusion
10018   Untrusted domains in JavaScript source code
10019   Content-Type header missing
10020   X-Frame-Options header not set
10021   X-Content-Type-Options header missing
10022   Information disclosure - database error messages [Deprecated]
10023   Information disclosure - debug error messages
10024   Information disclosure - sensitive information in URL
10025   Information disclosure - sensitive information on HTTP Referrer header
10026   HTTP Parameter Override
10027   Information disclosure - suspicious comments
10028   Open redirect
10029   Cookie poisoning
10030   User controllable charset
10031   User controllable HTML element attribute (potential XSS)
10032   Viewstate scanner
10033   Directory Browsing
10034   Heartbleed OpenSSL Vulnerability
10035   Strict-Transport-Security Header Not Set
10036   Server Leaks Version Information via "Server" HTTP Response Header Field
10037   Server Leaks Information via "X-Powered-By" HTTP Response Header Field(s)
10038   Content Security Policy (CSP) Header Not Set
10039   X-Backend-Server Header Information Leak
10040   Secure pages including mixed content
10041   HTTP to HTTPS insecure transition in form post
10042   HTTPS to HTTP insecure transition in form post
10043   User controllable javascript event (XSS)
10044   Big Redirect Response
10045   Source Code Disclosure - WEB-INF folder
10046   Insecure Component
10047   HTTPS Content Available via HTTP
10048   ShellShock
10049   Cacheability and Retrievability Content
10050   Retrieved from Cache
10051   Relative Path Confusion
10052   X-ChromeLogger-Data Header Information Leak
10053   Apache Range Header DoS (CVE-2011-3192)
10054   Cookie set without SameSite attribute
10055   Content Security Policy Scanner
10056   X-Debug-Token Scanner
10057   Username Hash iDOR Scanner
10058   GET for POST Scanner
10059	Http Parameter Pollution (Client Side)
10060	Http Parameter Pollution (Server Side)
10061   Server Leaks Information via "X-AspNet-Version"/"X-AspNetMvc-Version" HTTP Response Header Field(s)
10062   Server Leaks PII in response body
10070   Use of SAML
10094   Base64 Disclosure
10095   Backup File Disclosure
10096   Timestamp Disclosure
10097   Hash Disclosure
10098   Cross-Domain Misconfiguration
10099   Source Code Disclosure

10101   Insufficient Authentication
10102   Insufficient Authorization

10103   Image Location Scanner - passive scanner finding
10104   TestUserAgent
10105   Weak Authentication Method
10106   Http Only Site
10107   Httpoxy - Proxy Header Misuse
10108   Blank link target

10200   Beast (via HTTPS Info Extension)
10201   Crime (via HTTPS Info Extension)
10202   Absence of Anti-CSRF Tokens
10203   Freak (via HTTPS Info Extension)
10204   Robot (via HTTPS Info Extension)

20000   Cold Fusion default file [Deprecated]
20001   Lotus Domino default files [Deprecated]
20002   IIS default file [Deprecated]
20003   Macromedia JRun default files [Deprecated]
20004   Tomcat source file disclosure [Deprecated]
20005   BEA WebLogic example files [Deprecated]
20006   IBM WebSphere default files [Deprecated]
20010   URL Redirector Abuse
20012   Anti CSRF Tokens Scanner
20014   HTTP Parameter Pollution
20015   Heartbleed OpenSSL Vulnerability
20016   Cross-Domain Requests Permitted
20017   Source Code Disclosure - CVE-2012-1823
20018   Remote Code Execution - CVE-2012-1823
20019   External Redirect

30001  Check for buffer overflow in back end C code
30002  Check for proper format string handling in back end c code.
30003  Check for proper integer handling in back end c code.

40000   Cross site scripting [Deprecated]
40001   Cross site scripting in SCRIPT section [Deprecated]
40002   Cross site scripting without brackets [Deprecated]
40003   CRLF injection
40004   SQL Injection Fingerprinting [Deprecated]
40005   SQL Injection [Deprecated]
40006   MS SQL Injection Enumeration [Deprecated]
40007   Oracle SQL Injection Enumeration [Deprecated]
40008   Parameter tampering
40009   Server side include
40010   Cross site scripting in TAG [Deprecated]
40011   Cross Site Scripting in TAG Attribute [Deprecated]
40012   Cross Site Scripting (Reflected)
40013   Session Fixation
40014   Persistent XSS (Attack)
40015   LDAP Injection
40016   Persistent XSS (Prime)
40017   Persistent XSS (Spider)
40018   SQL Injection
40019   SQL Injection MySQL
40020   SQL Injection Hypersonic
40021   SQL Injection Oracle
40022   SQL Injection Postgresql
40023   Username Enumeration
40024   SQL Injection SQLite
40025   Proxy Disclosure
40026   Cross site scripting (DOM)
40027   SQL Injection MsSQL
40028   ELMAH Scanner
40029   trace.axd Scanner
40030   Backslash Powered Scanner
40031   Cross Site Scripting - Detection by Callback
40032   .htaccess Scanner
40033	NoSQL Injection MongoDB
40034   .env File Scanner

50000   Active Scan scripts
50001   Passive Scan scripts
50002   Fuzzer HTTP Processor scripts
50003   Stats passive scan rule
50004   Zest scripts (Action - Fail)
50005   Client side Active Scan scripts
50006   Client side Passive Scan scripts

60000   Example simple passive rule
60001   Example file passive rule
60100   Example simple active rule
60101   Example file active rule

90001   Insecure JSF ViewState
90011   Charset Mismatch
90017	XSLT Injection
90018   SQL Injection SQLMap
90019   Code Injection
90020   Command Injection
90021   Xpath Injection
90022   Application Error scanner
90023   XXE External Entity
90024   Generic Padding Oracle
90025   Expression Language Injection
90026   SOAP Action Spoofing
90027   Cookie Slack Detector
90028   Insecure HTTP Method
90029   SOAP XML Injection
90030   WSDL File Detection
90033   Loosely Scoped Cookie

100000  Client/Server HTTP Error Response Codes [Script]
100001  Unexpected Content Types [Script]

322420463 Retire.js

```


text:
module Records
  module Po

    class PoBase < Records::Base

      def initialize(order, sequence, args)
        super(sequence, args)
        @order = order
      end

      def cdf_record
        cdf = super
        cdf << po_number
      end

      def po_number
        @order.number.ljust_trim 22
      end

      def line_item
        @options[:line_item]
      end

      def self.ensure_length(cdf)
        raise StandardError.new("Invalid Line Length '#{cdf.to_s.length}': #{cdf.to_s}") if cdf.to_s.length % 80 > 0
        cdf
      end

    end
  end
end


text:
Register-DbatoolsConfigValidation -Name "integer" -ScriptBlock {
    param (
        $Value
    )

    $Result = New-Object PSOBject -Property @{
        Success = $True
        Value   = $null
        Message = ""
    }

    try { [int]$number = $Value }
    catch {
        $Result.Message = "Not an integer: $Value"
        $Result.Success = $False
        return $Result
    }

    $Result.Value = $number

    return $Result
}


text:
#ifndef _FENV_H
# error "Never use <bits/fenv.h> directly; include <fenv.h> instead."
#endif

#include <bits/wordsize.h>

/* Define bits representing the exception.  We use the bit positions
   of the appropriate bits in the FPU control word.  */
enum
  {
    FE_INVALID = 0x01,
#define FE_INVALID	FE_INVALID
    __FE_DENORM = 0x02,
    FE_DIVBYZERO = 0x04,
#define FE_DIVBYZERO	FE_DIVBYZERO
    FE_OVERFLOW = 0x08,
#define FE_OVERFLOW	FE_OVERFLOW
    FE_UNDERFLOW = 0x10,
#define FE_UNDERFLOW	FE_UNDERFLOW
    FE_INEXACT = 0x20
#define FE_INEXACT	FE_INEXACT
  };

#define FE_ALL_EXCEPT \
	(FE_INEXACT | FE_DIVBYZERO | FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID)

/* The ix87 FPU supports all of the four defined rounding modes.  We
   use again the bit positions in the FPU control word as the values
   for the appropriate macros.  */
enum
  {
    FE_TONEAREST = 0,
#define FE_TONEAREST	FE_TONEAREST
    FE_DOWNWARD = 0x400,
#define FE_DOWNWARD	FE_DOWNWARD
    FE_UPWARD = 0x800,
#define FE_UPWARD	FE_UPWARD
    FE_TOWARDZERO = 0xc00
#define FE_TOWARDZERO	FE_TOWARDZERO
  };

/* Type representing exception flags.  */
typedef unsigned short int fexcept_t;

/* Type representing floating-point environment.  This structure
   corresponds to the layout of the block written by the `fstenv'
   instruction and has additional fields for the contents of the MXCSR
   register as written by the `stmxcsr' instruction.  */
typedef struct
  {
    unsigned short int __control_word;
    unsigned short int __unused1;
    unsigned short int __status_word;
    unsigned short int __unused2;
    unsigned short int __tags;
    unsigned short int __unused3;
    unsigned int __eip;
    unsigned short int __cs_selector;
    unsigned int __opcode:11;
    unsigned int __unused4:5;
    unsigned int __data_offset;
    unsigned short int __data_selector;
    unsigned short int __unused5;
#if __WORDSIZE == 64
    unsigned int __mxcsr;
#endif
  }
fenv_t;

/* If the default argument is used we use this value.  */
#define FE_DFL_ENV	((__const fenv_t *) -1)

#ifdef __USE_GNU
/* Floating-point environment where none of the exception is masked.  */
# define FE_NOMASK_ENV	((__const fenv_t *) -2)
#endif


text:
using KadGen.ClassTracker.Domain;
using KadGen.ClassTracker.Repository;
using System.Linq;

namespace ClassTracker.Repository.Mappers
{
    internal class TermMapper
    {
        public static Term MapEntityToDomainForOrganization(EfTerm entity, Organization organization)
            => new Term(entity.Id, organization, entity.Name, entity.StartDate, entity.EndDate);

        public static Term MapEntityToDomain(EfTerm entity)
            => new Term(entity.Id, null, entity.Name, entity.StartDate, entity.EndDate);

        public static void MapDomainToEntity(Term domain, EfTerm entity)
        {
            entity.Id = domain.Id;
            entity.Name = domain.Name;
        }
    }
}