text:
package SimpleJob;

use CondorTest;

# need a memory so one can callbacks one per test
# not every call to RunCheck  bt 4/29/15
my %savedcallbacks = ();
my %args = ();

# track children so we can reap them later
my @children = ();

my $timeout = 0;
my $defaulttimeout = 300;
$timeout = $defaulttimeout;

$timed_callback = sub
{
	my $now = CondorTest::timestamp();
	print "SimpleJob timeout expired!\n";
	CondorTest::RegisterResult( 0, %args );
    die "$now Test failed from timeout expiring\n";
};

$submitted = sub
{
	my %info = @_;
	my $jobid = $info{'cluster'} . '.' . $info{'job'};
	CondorTest::debug("$jobid Job submitted\n",1);
};

$aborted = sub
{
	die "Abort event NOT expected\n";
};

$dummy = sub
{
};

$ExitSuccess = sub {
	my %info = @_;
	my $jobid = $info{'cluster'} . '.' . $info{'job'};
	CondorTest::debug("$jobid Job completed successfully\n",1);
};

my %defaultcallbacks = (
	"on_success" => $ExitSuccess,
	"on_submit" => $submitted,
	"on_abort" => 0,
	"on_failure" => 0,
	"on_exitedabnormal" => 0,
	"return_submit_file_name" => 0,
);

sub ShowKeys {
	foreach my $key (sort keys %savedcallbacks) {
		print "key: $key\n";
	}
}

sub CallbackReset {
	%savedcallbacks = ();
}

# we only want to set things into memory if they have been
# explicitly set and explicitly setting it again will override
# first setting.
sub CallBackMemoryUsage {
	my $action = shift;
	#print "Current action in CallBackMemoryUsage is:$action\n";
	#ShowKeys();
	if(exists $args{$action}) {
		#print "Saved and defaults for $action being requested\n";
	}
	if(exists $savedcallbacks{$action}) {
		#print "we have a saved callback for $action\n";
	}
	if((exists $savedcallbacks{$action}) & (!(exists $args{$action}))) {
		# this one has been set before and is not being reset
		#print "CallBackMemoryUsage: saved callback for $action\n";
		return($savedcallbacks{$action});
	} elsif((exists $savedcallbacks{$action}) & (exists $args{$action})) {
		# set before but overriding
		#print "CallBackMemoryUsage: saved callback for $action being changed\n";
		$savedcallbacks{$action} = $args{$action};
		return($args{$action});
	} elsif((!(exists $savedcallbacks{$action})) & (exists $args{$action})) {
		# being explictely set for first time
		#print "CallBackMemoryUsage:$action being set for first time\n";
		#ShowKeys();
		$savedcallbacks{$action} = $args{$action};
		#ShowKeys();
		return($args{$action});
	}
	# now we must look at default vaules which get returned but
	# NOT saved
	if((exists $defaultcallbacks{$action}) & ($defaultcallbacks{$action} != 0)) {
		#print "CallBackMemoryUsage: reserved call back for $action being set, not saved\n";
		# a non dummy callback
		return($defaultcallbacks{$action});
	} elsif((exists $defaultcallbacks{$action}) & ($defaultcallbacks{$action} == 0)) {
		#print "CallBackMemoryUsage: $action has no defaullt callback\n";
		# this one gets no default callback
		return(undef);
	} else {
		# this one gets the function $dummy
		#print "CallBackMemoryUsage: $action gets standard default callback\n";
		return($dummy);
	}
}

sub FigureTimedCallback {
	if((exists $savedcallbacks{alt_timed}) & (!(exists $args{alt_timed}))) {
		# this one has been set before and is not being reset
		#return($savedcallbacks{alt_timed});
	} elsif((exists $savedcallbacks{alt_timed}) & (exists $args{alt_timed})) {
		# set before but overriding
		#$savedcallbacks{alt_timed} = $args{alt_timed};
		return($args{alt_timed});
	} elsif((!(exists $savedcallbacks{alt_timed})) & (exists $args{alt_timed})) {
		# being explictely set for first time
		$savedcallbacks{alt_timed} = $args{alt_timed};
		return($args{alt_timed});
	} elsif((!(exists $savedcallbacks{alt_timed})) & (!(exists $args{alt_timed}))) {
		# using default time callback
		return($timed_callback);
	}
}

sub RunCheck
{
    %args = @_;
	my $availableslots = 0;
    my $result = 0;

################################################################################
#
#
# NOTE: In general there are callbacks requiring action and variable changes
# in the main test file. You can only use no_wait to fork for running really
# simple jobs like start a job that runs forever or start a job on hold.
#
# ANYTHING ELSE WILL NOT WORK AS YOU EXPECT	(bt 1/10/15)
#
#
################################################################################

	#print "Checking duration being passsed to RunCheck <$args{duration}>\n";
    my $execute_fn = CallBackMemoryUsage("on_execute");
    my $hold_fn = CallBackMemoryUsage("on_hold");
    my $shadow_fn = CallBackMemoryUsage("on_shadow");
    my $suspended_fn = CallBackMemoryUsage("on_suspended");
    my $released_fn = CallBackMemoryUsage("on_released");
    my $unsuspended_fn = CallBackMemoryUsage("on_unsuspended");
    my $disconnected_fn = CallBackMemoryUsage("on_disconnected");
    my $reconnected_fn = CallBackMemoryUsage("on_reconnected");
    my $reconnectfailed_fn = CallBackMemoryUsage("on_reconnectfailed");
    my $imageupdated_fn = CallBackMemoryUsage("on_imageupdated");
    my $evicted_ewc_fn = CallBackMemoryUsage("on_evictedwithcheckpoint");
    my $evicted_ewoc_fn = CallBackMemoryUsage("on_evictedwithoutcheckpoint");
    my $evicted_wreq_fn = CallBackMemoryUsage("on_evictedwithrequeue");
	my $wanterror_fn =CallBackMemoryUsage("on_wanterror");
    my $submit_fn = CallBackMemoryUsage("on_submit");
    my $ulog_fn = CallBackMemoryUsage("on_ulog");
    my $abort_fn = CallBackMemoryUsage("on_abort");
	# no default on abort handling handled in above function call
	my $donewithsuccess_fn = CallBackMemoryUsage("on_success");
	my $exitedabnormal_fn = CallBackMemoryUsage("on_exitedabnormal");
	my $exitedfailure_fn = CallBackMemoryUsage("on_failure");
	my $namecallback_fn = CallBackMemoryUsage("return_submit_file_name");

	# question when do I clear this timeout?
	my $timedcallback_fn = FigureTimedCallback();

	# we preset call backs before fork since if child does this and requests saved
	# callbacks, the next child won't see it

	my $submit_only = 0;
	if($args{no_wait}) {
		$submit_only = 1;
		$timedcallback_fn = undef;
# tj - 2015 - dont do this, no_wait really means 'I don't care if the job ever runs!'
#		my $pid = fork();
#		if($pid != 0) {
#			push @children, $pid;
#			#ShowChildren();
#			return(0);
#		}
	}

	my $queuesz = $args{queue_sz} || 1;

	if($args{check_slots}) {
		# Make sure we never try to start more jobs then slots we have!!!!!!
		$availableslots = ExamineSlots($args{check_slots});

		if($availableslots < $queuesz) {
			printf "RunCheck returning before submission. available slots:$availableslots vs requested:$queuesz\n";
    		CondorTest::RegisterResult( $result, %args );
    		return $result;
		}
	}

    my $testname = $args{test_name} || CondorTest::GetDefaultTestName();
    my $universe = $args{universe} || "vanilla";
	my $hold = $args{hold} || "False";
    my $user_log = $args{user_log} || CondorTest::TempFileName("$testname.user_log");
    my $output = $args{output} || "";
	if($output eq "*") {
		$output = "$testname.out";
	}
    my $input = $args{input} || "";
    my $error = $args{error} || "";
	if($error eq "*") {
		$error = "$testname.err";
	}
	my $deferralpreptime = $args{deferralpreptime} || "";
	my $deferraltime = $args{deferraltime} || "";
	my $deferralwindow = $args{deferralwindow} || "";
    my $requirements = $args{requirements} || "";
    my $streamoutput = $args{stream_output} || "";
    my $append_submit_commands = $args{append_submit_commands} || "";
    my $multi_queue = $args{multi_queue} || "";
    my $grid_resource = $args{grid_resource} || "";
	my $transfer_output_files = $args{transfer_output_files} || "";
	my $transfer_input_files = $args{transfer_input_files} || "";
    my $should_transfer_files = $args{should_transfer_files} || "";
    my $when_to_transfer_output = $args{when_to_transfer_output} || "";
    my $duration = "1";
	if(exists $args{duration}) {
		$duration = $args{duration};
	} else {
		#print "duration not set, defaulting to 1\n";
	}

	if(exists $args{timeout}){
		# either way we have to set a timeout
		# overwrite default timer value here
		$timeout = $args{timeout};
	}

	if(defined $abort_fn) {
    	CondorTest::RegisterAbort( $testname, $abort_fn );
	}
	if(defined $donewithsuccess_fn) {
    	CondorTest::RegisterExitedSuccess( $testname, $donewithsuccess_fn );
	}

	if(defined $execute_fn) {
    	CondorTest::RegisterExecute($testname, $execute_fn);
	}
	if(defined $ulog_fn) {
    	CondorTest::RegisterULog($testname, $ulog_fn);
	}
	if(defined $submit_fn) {
    	CondorTest::RegisterSubmit( $testname, $submit_fn );
	}

	#If we register thees to dummy, then we don't get
	#the error function registered which says this is bad

	if(defined $shadow_fn) {
    	CondorTest::RegisterShadow( $testname, $shadow_fn );
	}
	if(defined $wanterror_fn) {
    	CondorTest::RegisterWantError( $testname, $wanterror_fn );
	}
	if(defined $imageupdated_fn) {
    	CondorTest::RegisterImageUpdated( $testname, $imageupdated_fn );
	}
	if(defined $evicted_ewc_fn) {
    	CondorTest::RegisterEvictedWithCheckpoint( $testname, $evicted_ewc_fn );
	}
	if(defined $evicted_ewoc_fn) {
    	CondorTest::RegisterEvictedWithoutCheckpoint( $testname, $evicted_ewoc_fn );
	}
	if(defined $evicted_wreq_fn) {
    	CondorTest::RegisterEvictedWithRequeue( $testname, $evicted_wreq_fn );
	}
	if(defined $hold_fn) {
    	CondorTest::RegisterHold( $testname, $hold_fn );
	}
	if(defined $released_fn) {
    	CondorTest::RegisterRelease( $testname, $released_fn );
	}
	if(defined $exitedabnormal_fn) {
    	CondorTest::RegisterExitedAbnormal( $testname, $exitedabnormal_fn );
	}
	if(defined $evicted_fn) {
    	CondorTest::RegisterEvicted( $testname, $evicted_fn );
	}
	if(defined $disconnected_fn) {
    	CondorTest::RegisterDisconnected( $testname, $disconnected_fn );
	}
	if(defined $reconnectfailed_fn) {
    	CondorTest::RegisterReconnectFailed( $testname, $reconnectfailed_fn );
	}
	if(defined $reconnected_fn) {
    	CondorTest::RegisterReconnected( $testname, $reconnected_fn );
	}
	if(defined $suspended_fn) {
    	CondorTest::RegisterSuspended( $testname, $suspended_fn );
	}
	if(defined $unsuspended_fn) {
    	CondorTest::RegisterUnsuspended( $testname, $unsuspended_fn );
	}
	if(defined $exitedfailure_fn) {
		CondorTest::RegisterExitedFailure( $testname, $exitedfailure_fn );
	}

	if(defined $timedcallback_fn) {
		#print "Timed callbach set in simplejob\n";
		# here starts our new timer just for this module
		# look at timer use in other module here in Check
		# like the log checking ones
		CondorTest::RegisterSJTimed( $testname, $timedcallback_fn, $timeout  );
	}

	my $program = $args{runthis} || "x_sleep.pl";
    my $submit_fname = CondorTest::TempFileName("$testname.submit");

	# was used in concurrency tests is used job_max_running
	if(defined $namecallback_fn) {
		# call it
		&$namecallback_fn($submit_fname);
	}

    open( SUBMIT, ">$submit_fname" ) || die "error writing to $submit_fname: $!\n";
    print SUBMIT "universe = $universe\n";
    print SUBMIT "executable = $program\n";
    print SUBMIT "log = $user_log\n";
    print SUBMIT "hold = $hold\n";
    print SUBMIT "arguments = $duration\n";
    print SUBMIT "notification = never\n";
    if( $grid_resource ne "" ) {
	print SUBMIT "GridResource = $grid_resource\n"
    }
	if($output ne "") {
		print SUBMIT "output = $output\n";
	}
	if($input ne "") {
		print SUBMIT "input = $input\n";
	}
	if($error ne "") {
		print SUBMIT "error = $error\n";
	}
	if($args{request_memory}) {
		print SUBMIT "request_memory = $args{request_memory}\n";
	}
	if($deferralpreptime ne "") {
		print SUBMIT "DeferralPrepTime = $deferralpreptime\n";
	}
	if($deferraltime ne "") {
		print SUBMIT "DeferralTime = $deferraltime\n";
	}
	if($deferralwindow ne "") {
		print SUBMIT "DeferralWindow = $deferralwindow\n";
	}
	if($requirements ne "") {
		print SUBMIT "Requirements = $requirements\n";
	}
	if($streamoutput ne "") {
		print SUBMIT "stream_output = $streamoutput\n";
	}
	if( $transfer_output_files ne "" ) {
		print SUBMIT "transfer_output_files = $transfer_output_files\n";
	}
	if( $transfer_input_files ne "" ) {
		print SUBMIT "transfer_input_files = $transfer_input_files\n";
	}
    if( $should_transfer_files ne "" ) {
		print SUBMIT "should_transfer_files = $should_transfer_files\n";
    }
    if( $when_to_transfer_output ne "" ) {
		print SUBMIT "when_to_transfer_output = $when_to_transfer_output\n";
    }
    if( $append_submit_commands ne "" ) {
        print SUBMIT "\n" . $append_submit_commands . "\n";
    }
    print SUBMIT "queue $queuesz";
	if($multi_queue ne "") {
        print SUBMIT " " . $multi_queue;
	}
	print SUBMIT "\n";
    close( SUBMIT );

	if ($submit_only) {
		my $cluster = Condor::TestSubmit( $submit_fname );

		if(exists $args{ClusterIdCallback}) {
			my $clusteridcallback = $args{ClusterIdCallback};
			&$clusteridcallback($cluster);
		}

		return $cluster ? 0 : 1;
	}

	CondorTest::debug("  RunCheck: calling RunTest($testname, $submit_fname)\n");
	if (defined $args{GetClusterId}) {
    	$result = CondorTest::RunTest($testname, $submit_fname, 0, $args{GetClusterId});
	} else {
    	$result = CondorTest::RunTest($testname, $submit_fname, 0);
	}
	#print "Simple job back!\n";

	Condor::RemoveSJTimed();

    CondorTest::RegisterResult( $result, %args );
#	if(($args{no_wait}) & ($pid == 0)) {
#		#print "Child exiting\n";
#		exit(0);
#	}

}

sub ExamineSlots
{
	my $expectedslots = shift;
	my $slots = $expectedslots;
	my $line = "";
	my $timelimit = 30;
	my $currenttime = 0;
	my $sleeptime = 3;
	my $slotcount = 0;

	print "checking for $slots\n";

	my $available = 0;
	my @jobs = ();
	my $cmd = "condor_status";
	print "In ExamineSlots\n";
	# allow some time to stabilize
	while(($slotcount < $slots) & ($currenttime < $timelimit)) {
		runCondorTool($cmd,\@jobs,2,{emit_output=>0});
		foreach my $job (@jobs) {
			chomp($job);
			$line = $job;
			#print "ExamineSlots\n";
			if($line =~ /^\s*Total\s+(\d+)\s*(\d+)\s*(\d+)\s*(\d+).*/) {
				print "<$4> unclaimed slots\n";
				$available = $4;
			}
		}
		if($avaiilable != $slots) {
			$slotcount = $available;
			$currenttime += $sleeptime;
			sleep($sleeptime);
		}
	}
	print "ExamineSlots returning $slotcount after $currenttime seconds\n";
	return($slotcount);
}

sub ShowChildren {
	my $kids = @children;
	print "ShowChildren: $kids kids\n";
	foreach my $child (@children) {
	}
}

sub HarvestChildren {
	my $kids = @children;
	#print "HarvestChildren: $kids kids\n";
	foreach my $child (@children) {
		#print "waiting for child:$child\n";
		while(($childpid = waitpid($child,0)) != -1) {
			$retvalue = $?;
			if($childpid == 0) {
				#print "Waitinng on child:$child waitpid says:$childpid\n";
			} else {
				#print "Child:$childpid has returned\n";
				if ($retvalue & 0x7f) {
					# died with signal and maybe coredump.
					# Ignore the fact a coredump happened for now.
					TestDebug( "Monitor done and status bad: \n",4);
					$accumulatedreturn += 1;
				} else {
					# Child returns valid exit code
					my $rc = $retvalue >> 8;
					#print "ProcessReturn: Exited normally $rc\n";
					$accumulatedreturn += $rc;
				}
			}
		}
	}
	#print "HarvestChildren: all done\n";
	return(0);
}

1;


text:
package com.twu.biblioteca.domain.repo;

import com.twu.biblioteca.domain.model.Book;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class BookRepoTest {

    private BookRepo bookRepo;

    private SimpleDateFormat formatter;

    @Before
    public void setUp() {
        bookRepo = new BookRepo();
        formatter = new SimpleDateFormat("yyyy-MM-dd");
    }

    @After
    public void tearDown() {
        bookRepo = null;
        formatter = null;
    }

    @Test
    public void should_can_get_list_of_books() throws ParseException {
        Map<String, Book> listOfBooks = bookRepo.getOriginalBooks();

        assertThat(listOfBooks.size(), is(6));
        assertThat(listOfBooks.get("B-01").getId(), is("B-01"));
        assertThat(listOfBooks.get("B-01").getTitle(), is("Refactoring"));
        assertThat(listOfBooks.get("B-01").getAuthor(), is("Martin Fowler & Kent Beck"));
        assertThat(listOfBooks.get("B-01").getPublishedYear(), is(formatter.parse("1999-07-08")));
        assertThat(listOfBooks.get("B-04").getId(), is("B-04"));
        assertThat(listOfBooks.get("B-04").getTitle(), is("The Art of Readable Code"));
        assertThat(listOfBooks.get("B-04").getAuthor(), is("Dustin Boswell & Trevor Foucher"));
        assertThat(listOfBooks.get("B-04").getPublishedYear(), is(formatter.parse("2011-12-02")));
    }

    @Test
    public void should_get_book_by_id() throws ParseException {
        Book book = bookRepo.getBookById("B-03");

        assertThat(book.getId(), is("B-03"));
        assertThat(book.getTitle(), is("Test Driven Development: By Example"));
        assertThat(book.getAuthor(), is("Kent Beck"));
        assertThat(book.getPublishedYear(), is(formatter.parse("2002-11-18")));
    }

    @Test
    public void should_judge_correct_when_call_is_book_exist() {
        assertTrue(bookRepo.isBookExist("B-02"));
        assertFalse(bookRepo.isBookExist("B-08"));
    }

    @Test
    public void should_get_empty_checked_out_books() {
        assertThat(bookRepo.getCheckedOutBooks().size(), is(0));
    }

    @Test
    public void should_get_correct_checked_out_books_after_add() {
        bookRepo.addCheckedOutBook("B-01", "C-01");

        assertThat(bookRepo.getCheckedOutBooks().size(), is(1));
        assertThat(bookRepo.getCheckedOutBooks().get("B-01"), is("C-01"));
    }

    @Test
    public void should_judge_correct_when_call_is_book_checked_out() {
        assertFalse(bookRepo.isBookCheckedOut("B-01"));

        bookRepo.addCheckedOutBook("B-01", "C-01");

        assertTrue(bookRepo.isBookCheckedOut("B-01"));
        assertFalse(bookRepo.isBookCheckedOutForCurrentCustomer("B-01", "C-02"));
    }

    @Test
    public void should_can_remove_checked_out_book() {

        bookRepo.addCheckedOutBook("B-01", "C-01");

        assertTrue(bookRepo.isBookCheckedOut("B-01"));

        bookRepo.removeCheckedOutBook("B-01");

        assertFalse(bookRepo.isBookCheckedOut("B-01"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
angular.module('uiGmapgoogle-maps.wrapped')
.service('uiGmapuuid', function() {
  //BEGIN REPLACE
  @@REPLACE_W_LIBS
  //END REPLACE
return UUID;
});


text:
package in.twizmwaz.cardinal.module.modules.teamPicker;

import com.google.common.base.Optional;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.chat.ChatConstant;
import in.twizmwaz.cardinal.chat.LocalizedChatMessage;
import in.twizmwaz.cardinal.match.MatchState;
import in.twizmwaz.cardinal.module.Module;
import in.twizmwaz.cardinal.module.modules.blitz.Blitz;
import in.twizmwaz.cardinal.module.modules.classModule.ClassModule;
import in.twizmwaz.cardinal.module.modules.team.TeamModule;
import in.twizmwaz.cardinal.util.Items;
import in.twizmwaz.cardinal.util.MiscUtil;
import in.twizmwaz.cardinal.util.Teams;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerLocaleChangeEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.Arrays;

public class TeamPicker implements Module {

    protected TeamPicker() {
    }

    @Override
    public void unload() {
        HandlerList.unregisterAll(this);
    }

    public Inventory getTeamPicker(Player player) {
        int size = (((GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class).size() + (Teams.getTeamByPlayer(player).isPresent() && Teams.getTeamByPlayer(player).get().isObserver() ? 0 : 1 )) / 9) + 1) * 9;
        int classesSize = ((GameHandler.getGameHandler().getMatch().getModules().getModules(ClassModule.class).size() + 8) / 9) * 9;
        Inventory picker = Bukkit.createInventory(null, size + classesSize, ChatColor.DARK_RED + new LocalizedChatMessage(ChatConstant.UI_TEAM_PICK).getMessage(player.getLocale()));
        int item = 0;

        int maxPlayers = 0;
        int totalPlayers = 0;
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (!team.isObserver()) {
                maxPlayers += team.getMax();
                totalPlayers += team.size();
            }
        }
        ItemStack autoJoin = Items.createItem(Material.CHAINMAIL_HELMET, 1, (short) 0, ChatColor.GRAY + "" + ChatColor.BOLD + new LocalizedChatMessage(ChatConstant.UI_TEAM_JOIN_AUTO).getMessage(player.getLocale()), Arrays.asList((totalPlayers >= maxPlayers ? ChatColor.RED + "" : ChatColor.GREEN + "") + totalPlayers + ChatColor.GOLD + " / " + ChatColor.RED + "" + maxPlayers, ChatColor.AQUA + new LocalizedChatMessage(ChatConstant.UI_TEAM_JOIN_AUTO_LORE).getMessage(player.getLocale())));
        picker.setItem(item, autoJoin);
        item++;
        for (TeamModule team : GameHandler.getGameHandler().getMatch().getModules().getModules(TeamModule.class)) {
            if (!team.isObserver()) {
                ItemStack teamStack = Items.createLeatherArmor(Material.LEATHER_HELMET, 1, team.getColor() + "" + ChatColor.BOLD + team.getName(), Arrays.asList((team.size() >= team.getMax() ? ChatColor.RED + "" : ChatColor.GREEN + "") + team.size() + ChatColor.GOLD + " / " + ChatColor.RED + "" + team.getMax(), ChatColor.GREEN + new LocalizedChatMessage(ChatConstant.UI_TEAM_CAN_PICK).getMessage(player.getLocale())), MiscUtil.convertChatColorToColor(team.getColor()));
                picker.setItem(item, teamStack);
                item++;
            }
        }
        item = size;
        if (!(Teams.getTeamByPlayer(player).isPresent() && Teams.getTeamByPlayer(player).get().isObserver())){
            ItemStack leave = Items.createItem(Material.LEATHER_BOOTS, 1, (short) 0, ChatColor.GREEN + "" + ChatColor.BOLD + new LocalizedChatMessage(ChatConstant.UI_TEAM_LEAVE).getMessage(player.getLocale()), Arrays.asList(ChatColor.DARK_PURPLE + new LocalizedChatMessage(ChatConstant.UI_TEAM_LEAVE_LORE).getMessage(player.getLocale())));
            picker.setItem(item - 1, leave);
        }
        for (ClassModule classModule : GameHandler.getGameHandler().getMatch().getModules().getModules(ClassModule.class)) {
            ItemStack classStack = Items.createItem(classModule.getIcon(), 1, (short) 0, ChatColor.GREEN + classModule.getName(), Arrays.asList(ChatColor.GOLD + classModule.getLongDescription()));
            ItemMeta classMeta = classStack.getItemMeta();
            if (classModule.equals(ClassModule.getClassByPlayer(player))) {
                classStack.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1);
            }
            classStack.setItemMeta(classMeta);
            picker.setItem(item, classStack);
            item++;
        }
        return picker;
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        ItemStack item = event.getCurrentItem();
        Player player = (Player) event.getWhoClicked();
        if (item != null) {
            Optional<TeamModule> team = Teams.getTeamByPlayer(player);
            if (team.isPresent() && team.get().isObserver() || !GameHandler.getGameHandler().getMatch().isRunning()) {
                if (event.getInventory().getName().equals(ChatColor.DARK_RED + new LocalizedChatMessage(ChatConstant.UI_TEAM_PICK).getMessage(player.getLocale()))) {
                    if (item.getType().equals(Material.CHAINMAIL_HELMET)) {
                        if (item.hasItemMeta()) {
                            if (item.getItemMeta().hasDisplayName()) {
                                if (item.getItemMeta().getDisplayName().equals(ChatColor.GRAY + "" + ChatColor.BOLD + new LocalizedChatMessage(ChatConstant.UI_TEAM_JOIN_AUTO).getMessage(player.getLocale()))) {
                                    event.setCancelled(true);
                                    player.closeInventory();
                                    player.playSound(player.getLocation(), Sound.CLICK, 1, 2);
                                    Bukkit.dispatchCommand(player, "join");
                                }
                            }
                        }
                    } else if (item.getType().equals(Material.LEATHER_BOOTS)) {
                        if (item.hasItemMeta()) {
                            if (item.getItemMeta().hasDisplayName()) {
                                if (item.getItemMeta().getDisplayName().equals(ChatColor.GREEN + "" + ChatColor.BOLD + new LocalizedChatMessage(ChatConstant.UI_TEAM_LEAVE).getMessage(player.getLocale()))) {
                                    event.setCancelled(true);
                                    player.closeInventory();
                                    player.playSound(player.getLocation(), Sound.CLICK, 1, 2);
                                    Bukkit.dispatchCommand(player, "leave");
                                }
                            }
                        }
                    } else if (item.getType().equals(Material.LEATHER_HELMET)) {
                        if (item.hasItemMeta()) {
                            if (item.getItemMeta().hasDisplayName()) {
                                if (Teams.getTeamByName(ChatColor.stripColor(item.getItemMeta().getDisplayName())) != null) {
                                    event.setCancelled(true);
                                    player.closeInventory();
                                    player.playSound(player.getLocation(), Sound.CLICK, 1, 2);
                                    Bukkit.dispatchCommand(player, "join " + ChatColor.stripColor(item.getItemMeta().getDisplayName()));
                                } else {
                                    event.setCancelled(true);
                                    player.closeInventory();
                                    player.playSound(player.getLocation(), Sound.CLICK, 1, 2);
                                    Bukkit.dispatchCommand(player, "class " + ChatColor.stripColor(item.getItemMeta().getDisplayName()));
                                }
                            }
                        }
                    } else {
                        if (item.hasItemMeta()) {
                            if (item.getItemMeta().hasDisplayName()) {
                                if (ClassModule.getClassByName(ChatColor.stripColor(item.getItemMeta().getDisplayName())) != null) {
                                    event.setCancelled(true);
                                    player.closeInventory();
                                    player.playSound(player.getLocation(), Sound.CLICK, 1, 2);
                                    Bukkit.dispatchCommand(player, "class " + ChatColor.stripColor(item.getItemMeta().getDisplayName()));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (!GameHandler.getGameHandler().getMatch().getState().equals(MatchState.ENDED) && !(Blitz.matchIsBlitz() && GameHandler.getGameHandler().getMatch().getState().equals(MatchState.PLAYING)) &&
                (event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) &&
                event.getPlayer().getItemInHand() != null && event.getPlayer().getItemInHand().getType().equals(Material.LEATHER_HELMET) &&
                event.getPlayer().getItemInHand().hasItemMeta() && event.getPlayer().getItemInHand().getItemMeta().hasDisplayName() &&
                (event.getPlayer().getItemInHand().getItemMeta().getDisplayName().equals(ChatColor.GREEN + "" + ChatColor.BOLD + new LocalizedChatMessage(ChatConstant.UI_TEAM_SELECTION).getMessage(event.getPlayer().getLocale())) ||
                        ChatColor.stripColor(event.getPlayer().getItemInHand().getItemMeta().getDisplayName()).equals(new LocalizedChatMessage(ChatConstant.UI_TEAM_CLASS_SELECTION).getMessage(event.getPlayer().getLocale())))) {
                    event.getPlayer().openInventory(getTeamPicker(event.getPlayer()));
        }
    }

    @EventHandler
    public void onPlayerLocaleChange(PlayerLocaleChangeEvent event) {
        if (event.getOldLocale() == null) return;
        for (ItemStack item : event.getPlayer().getInventory().getContents()) {
            if (item != null) {
                if (item.getType().equals(Material.LEATHER_HELMET)) {
                    if (item.hasItemMeta()) {
                        if (item.getItemMeta().hasDisplayName()) {
                            ItemMeta meta = item.getItemMeta();

                            StringBuilder name = new StringBuilder();
                            name.append(ChatColor.GREEN);
                            name.append(ChatColor.BOLD);

                            StringBuilder lore = new StringBuilder();
                            lore.append(ChatColor.DARK_PURPLE);
                            lore.append(new LocalizedChatMessage(ChatConstant.UI_TEAM_JOIN_TIP).getMessage(event.getPlayer().getLocale()));

                            if (item.getItemMeta().getDisplayName().equals(ChatColor.GREEN + "" + ChatColor.BOLD + new LocalizedChatMessage(ChatConstant.UI_TEAM_SELECTION).getMessage(event.getOldLocale()))) {
                                name.append(new LocalizedChatMessage(ChatConstant.UI_TEAM_SELECTION).getMessage(event.getNewLocale()));
                                meta.setDisplayName(name.toString());
                                meta.setLore(Arrays.asList(lore.toString()));
                            } else if (item.getItemMeta().getDisplayName().equals(ChatColor.GREEN + "" + ChatColor.BOLD + new LocalizedChatMessage(ChatConstant.UI_TEAM_CLASS_SELECTION).getMessage(event.getOldLocale()))) {
                                name.append(new LocalizedChatMessage(ChatConstant.UI_TEAM_CLASS_SELECTION).getMessage(event.getNewLocale()));
                                meta.setDisplayName(name.toString());
                                meta.setLore(Arrays.asList(lore.toString()));
                            }
                            item.setItemMeta(meta);
                        }
                    }
                }
            }
        }
    }
}


text:
import React from 'react'
import { AsyncStorage } from 'react-native'
import io from 'socket.io-client'

const SERVER_URL = 'http://192.168.31.144'
// const SERVER_URL = 'http://10.89.80.125'
// const SERVER_URL = 'http://10.89.151.157'

export const SOCKET_URL = `${SERVER_URL}:8081`
const API_URL = `${SERVER_URL}:8080`

const jsonHeader = {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
}

// Login
export function loginUser (form) {
  return fetch(`${API_URL}/login`, {
    method: 'POST',
    headers: { ...jsonHeader },
    body: JSON.stringify(form)
  })
    .then(response => response.json())
    .catch(err => console.error(err))
}

export async function logoutUser () {
  return AsyncStorage.removeItem('Authorization')
    .catch(err => console.error(err))
}

export function registerUser (form) {
  return fetch(`${API_URL}/user`, {
    method: 'POST',
    headers: { ...jsonHeader },
    body: JSON.stringify(form)
  })
    .then(response => response.json())
    .catch(err => console.error(err))
}

export async function fetchUserProfile (itsc) {
  let token = await AsyncStorage.getItem('Authorization')
  return fetch(`${API_URL}/user/${itsc}`, {
    headers: { Authorization: token }
  })
    .then(response => response.json())
    .catch(err => console.error(err))
}

// Task
export async function fetchTasks ({page, status, rfid, keyword}) {
  let token = await AsyncStorage.getItem('Authorization')
  console.log()
  return fetch(`${API_URL}/task?` + (page ? `page=${page}&` : '') + (status ? `status=${status}&` : '') + (rfid ? `rfid=${rfid}&` : '') + (keyword ? `keyword=${keyword}&` : ''), {
    headers: { Authorization: token, ...jsonHeader }
  })
    .then(response => response.json())
    .catch(err => console.error(err))
}

export async function fetchTaskByID (taskID) {
  let token = await AsyncStorage.getItem('Authorization')
  return fetch(`${API_URL}/task/${taskID}`, {
    headers: { Authorization: token, ...jsonHeader }
  })
    .then(response => response.json())
    .catch(err => console.error(err))
}

export async function fetchChats () {
  let token = await AsyncStorage.getItem('Authorization')
  let itsc = await AsyncStorage.getItem('itsc')
  return fetch(`${API_URL}/task?rfid=${itsc}&nstatus=COMPLETED`, {
    headers: { Authorization: token, ...jsonHeader }
  })
    .then(response => response.json())
    .catch(err => console.error(err))
}

export async function createTask (task) {
  let token = await AsyncStorage.getItem('Authorization')
  return fetch(`${API_URL}/task`, {
    method: 'POST',
    headers: { Authorization: token, ...jsonHeader },
    body: JSON.stringify(task)
  })
    .then(response => response.json())
    .catch(err => console.error(err))
}

export async function updateTask (task, change) {
  let token = await AsyncStorage.getItem('Authorization')
  return fetch(`${API_URL}/task/${task._id}`, {
    method: 'PUT',
    headers: { Authorization: token, ...jsonHeader },
    body: JSON.stringify(change)
  })
    .then(response => console.log(response))
    .catch(err => console.error(err))
}


text:
<?xml version="1.0"?>
<macros>
    <xml name="requirements">
        <requirements>
            <requirement type="package" version="@TOOL_VERSION@">vg</requirement>
        </requirements>
    </xml>
    <token name="@TOOL_VERSION@">1.23.0</token>
    <xml name="citations">
        <citations>
            <yield />
        </citations>
    </xml>
</macros>


text:
#pragma once

/*
 Helper object to handle SDL_GameControllers and joystick axis to d-pad button translation
 */

#include "SDL.h"
#include <vector>

class Gamepad
{
	bool controllerDefsLoaded;
	int controllerAxis[2];

	std::vector<SDL_GameController*> controller;

public:

	void translateAxisToDPad(const SDL_Event& event);
	bool loadDefinitions(const char *path);
	void initControllers();
	void deinitControllers();
};


text:
package adept.module;

import java.util.List;

import adept.common.Sentence;
import adept.common.SyntacticChunk;

/**
 * The Class SyntacticChunker.
 */
public abstract class SyntacticChunker extends AbstractModule implements
		ISentenceProcessor<SyntacticChunk> {

	/*
	 * (non-Javadoc)
	 *
	 * @see adept.module.ISentenceProcessor#process(adept.common.Sentence)
	 */
	@Override
	public List<SyntacticChunk> process(Sentence sentence) {
		// TODO Auto-generated method stub
		return null;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see adept.module.ISentenceProcessor#processAsync(adept.common.Sentence)
	 */
	@Override
	public long processAsync(Sentence sentence) {
		// TODO Auto-generated method stub
		return 0;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see adept.module.ISentenceProcessor#tryGetResult(long, java.util.List)
	 */
	@Override
	public Boolean tryGetResult(long requestId, List<SyntacticChunk> hltContents) {
		// TODO Auto-generated method stub
		return Boolean.FALSE;
	}

}


text:
/* rich Mar 3, 2008 */

package clojure.lang;

public interface IPersistentSet extends IPersistentCollection, Counted{
	public IPersistentSet disjoin(Object key) ;
	public boolean contains(Object key);
	public Object get(Object key);
}


text:
Places endpoint
===============

Endpoint to search and retrieve information about places.

All the responses are conform to the `HAL specification <http://stateless.co/hal_specification.html>`_.

.. http:get:: /places/(string:id)[,(string:id)...]

    Get details of one or multiple places by their ID

    **Example request**:

    .. sourcecode:: http

		GET /places/oxpoints:23232339 HTTP/1.1
		Host: api.m.ox.ac.uk
		Accept: application/json

    **Example request for multiple POIs**:

    The response representation for multiple POIs will be equivalent to the
    search method.

    .. sourcecode:: http

		GET /places/osm:3646652,oxpoints:23232392 HTTP/1.1
		Host: api.m.ox.ac.uk
		Accept: application/json

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
          "_embedded": {
            "files": [
              {
                "location": "oxpoints/54559254/depiction/original/primary.jpg",
                "primary": true,
                "type": "depiction",
                "url": "//mox-static-files.oucs.ox.ac.uk/oxpoints/54559254/depiction/original/primary.jpg"
              },
            ]
          },
          "_links": {
            "child": [
              {
                "href": "/places/oxpoints:32320005",
                "title": "Balliol College Library",
                "type": [
                  "/university/library"
                ],
                "type_name": [
                  "Library"
                ]
              }
            ],
            "primary_place": {
              "href": "/places/oxpoints:23232339",
              "title": "Balliol College",
              "type": [
                "/university/college"
              ],
              "type_name": [
                "College"
              ]
            },
            "self": {
              "href": "/places/oxpoints:23232339"
            }
          },
          "address": "Broad Street OX1 3BJ",
          "distance": 0,
          "id": "oxpoints:23232339",
          "identifiers": [
            "oxpoints:54559254",
            "oxpoints:23232339",
            "obn:851",
            "osm:187925177",
            "oucs:ball",
            "finance:RB"
          ],
          "lat": "51.754425",
          "lon": "-1.257216",
          "name": "Balliol College",
          "name_sort": "Balliol College",
          "shape": "POLYGON ((... 51.755528699999999 0,-1.2584285 51.755520099999998 0))",
          "social_facebook": [
            "https://www.facebook.com/balliolcollege"
          ],
          "social_twitter": [
            "https://www.twitter.com/BalliolOxford"
          ],
          "type": [
            "/university/college"
          ],
          "type_name": [
            "College"
          ],
          "website": "http://www.balliol.ox.ac.uk/"
        }

    :param id: ID of the resource, if multiple resources, separated by a comma
    :type id: string

    :statuscode 200: resource found
    :statuscode 301: redirection to the resource by its main ID
    :statuscode 404: no resource found
    :statuscode 503: Service not available

    If multiple resources are requested, as much documents as possible will be returned (i.e. if one of
    the identifier requested is not found, all other documents will be returned).

.. http:get:: /places/search

    Search for places using full-text search on name, tags and type of place.
    Also searches in identifiers (e.g. searching "69326473" will return the bus stop corresponding to this Naptan ID).
    Results can be filtered by a type and its subtypes or can be filtered by specific types (both options cannot be used at the same time).
    Note that the result might be using a different search as spellchecking is done (e.g. searching for "Wolverkote" will return results with "Wolvercote").

    **Example request**:

    .. sourcecode:: http

		GET /places/search?q=aldates&type=/transport HTTP/1.1
		Host: api.m.ox.ac.uk
		Accept: application/json
		Geo-Position: 0.232, 51.347

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
          "_embedded": {
            "pois": [
              {
                "_links": {
                  "child": [
                    {
                      "href": "/places/atco:340000004H5",
                      "title": "Stop H5 St Aldates",
                      "type": [
                        "/transport/bus-stop"
                      ],
                      "type_name": [
                        "Bus stop"
                      ]
                    },
                  ],
                  "parent": {
                    "href": "/places/stoparea:340G00004000",
                    "title": "Oxford City Centre",
                    "type": [
                      "/transport/stop-area"
                    ],
                    "type_name": [
                      "Bus stop area"
                    ]
                  },
                  "self": {
                    "href": "/places/stoparea:340G00003140"
                  }
                },
                "distance": 0,
                "id": "stoparea:340G00003140",
                "identifiers": [
                  "stoparea:340G00003140"
                ],
                "lat": "51.7508834555",
                "lon": "-1.2571120376",
                "name": "St Aldates",
                "name_sort": "St Aldates",
                "type": [
                  "/transport/stop-area"
                ],
                "type_name": [
                  "Bus stop area"
                ]
              },
              {
                "_links": {
                  "curie": {
                    "href": "http://moxie.readthedocs.org/en/latest/http_api/rti.html#{type}",
                    "name": "rti",
                    "templated": true
                  },
                  "parent": {
                    "href": "/places/stoparea:340G00003140",
                    "title": "St Aldates",
                    "type": [
                      "/transport/stop-area"
                    ],
                    "type_name": [
                      "Bus stop area"
                    ]
                  },
                  "rti:bus": {
                    "href": "/places/atco:340000004H5/rti/bus",
                    "title": "Live bus departure times"
                  },
                  "self": {
                    "href": "/places/atco:340000004H5"
                  }
                },
                "distance": 0,
                "id": "atco:340000004H5",
                "identifiers": [
                  "atco:340000004H5",
                  "naptan:69326543"
                ],
                "lat": "51.7502787977",
                "lon": "-1.2567597994",
                "name": "Stop H5 St Aldates",
                "name_sort": "Stop H5 St Aldates",
                "type": [
                  "/transport/bus-stop"
                ],
                "type_name": [
                  "Bus stop"
                ]
              },
            ]
          },
          "_links": {
            "curies": [
              {
                "href": "http://moxie.readthedocs.org/en/latest/http_api/relations/{rel}.html",
                "name": "hl",
                "templated": true
              },
              {
                "href": "http://moxie.readthedocs.org/en/latest/http_api/relations/facet.html",
                "name": "facet"
              }
            ],
            "hl:first": {
              "href": "/places/search?q=aldates&facet=type&type=%2Ftransport&count=35"
            },
            "hl:last": {
              "href": "/places/search?q=aldates&facet=type&type=%2Ftransport&count=35"
            },
            "hl:types": [
              {
                "count": 10,
                "href": "/places/search?q=aldates&facet=type&type=%2Ftransport%2Fbus-stop",
                "name": "/transport/bus-stop",
                "title": [
                  "Bus stop"
                ],
                "value": "/transport/bus-stop"
              },
              {
                "count": 1,
                "href": "/places/search?q=aldates&facet=type&type=%2Ftransport%2Fstop-area",
                "name": "/transport/stop-area",
                "title": [
                  "Bus stop area"
                ],
                "value": "/transport/stop-area"
              }
            ],
            "self": {
              "href": "/places/search?q=aldates&facet=type&type=%2Ftransport&count=35&start=0"
            }
          },
          "query": "aldates",
          "size": 11
        }

    :query q: what to search for
    :type q: string
    :query type: filter by a specific type in the hierarchy of types (will search within subtypes too)
    :type type: string
    :query type_exact: filter by exact types (as opposite to the type parameter), you can have this parameter multiple times.
    :type type_exact: string
    :query start: first result to retrieve
    :type start: int
    :query count: number of results to retrieve
    :type count: int
    :query lat: latitude (as an alternative to the Geo-Position header if spatial search required)
    :type lat: string
    :query lon: longitude (as an alternative to the Geo-Position header if spatial search required)
    :type lon: string
    :query inoxford: only get results within Oxford (value will be ignored)
    :type inoxford: string
    :query university_only: only get results from the University (value will be ignored)
    :type university_only: string
    :query exclude_university: exclude results from the University (value will be ignored) i.e. only amenities, transport...
    :type exclude_university: string

    **Accessibility filtering**

    Below are filters specific to accessibility features, coming from the university' access guide.

    :query accessibility_has_adapted_furniture: only get POIs known to have "adapted furniture"
    :type accessibility_has_adapted_furniture: boolean
    :query accessibility_has_cafe_refreshments: only get POIs known to have "accessible cafe / refreshments"
    :type accessibility_has_cafe_refreshments: boolean
    :query accessibility_has_computer_access: only get POIs known to have "accessible computer access"
    :type accessibility_has_computer_access: boolean
    :query accessibility_has_hearing_system: only get POIs known to have a "hearing system"
    :type accessibility_has_hearing_system: boolean
    :query accessibility_has_lifts_to_all_floors: only get POIs known to have "lift access to all floors"
    :type accessibility_has_lifts_to_all_floors: boolean
    :query accessibility_has_quiet_space: only get POIs known to have "accessible quiet space"
    :type accessibility_has_quiet_space: boolean
    :query accessibility_has_accessible_toilets: only get POIs known to have "accessible toilets"
    :type accessibility_has_accessible_toilets: boolean
    :query accessibility_has_accessible_parking_spaces: only get POIs known to have "accessible parking spaces"
    :type accessibility_has_accessible_parking_spaces: boolean

    **Application specific filtering**

    Below are filters made specifically for an application. It is not recommended to use these parameters, as it
    is mainly experimental and might change to be generic in the future.

    :query is_display_in_maps_department_list: only get POIs manually selected / curated as "featured" university departments
    :type is_display_in_maps_department_list: boolean

    If no geolocation is passed (either by header or query parameters), and if there is no full-text search (``q`` parameter),
    the result will be sorted by name (A-Z).

    :statuscode 200: query found
    :statuscode 400: Bad request (could happen if some parameters are used in combination e.g. type and type_exact)
    :statuscode 503: Service not available

.. http:get:: /places/types

    Display a list of types.

    :statuscode 200: display a list of types

.. http:get:: /places/suggest

    Suggest places based on name and alternative names.
    Results can be filtered by specific types.

    **Example request**:

    .. sourcecode:: http

		GET /places/suggest?q=sec&type_exact=/university/department HTTP/1.1
		Host: api.m.ox.ac.uk
		Accept: application/json

    **Example response**:

    The response only contains a subset of properties available in the search method to reduce the
    length of the response.

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
          "_embedded": {
            "pois": [
              {
                "_links": {
                  "self": {
                    "href": "/places/oxpoints:23233517"
                  }
                },
                "address": "Wellington Square OX1 2JD",
                "distance": 0,
                "id": "oxpoints:23233517",
                "identifiers": [],
                "name": "Council Secretariat",
                "type": [
                  "/university/department"
                ],
                "type_name": [
                  "Department"
                ]
              },
              {
                "_links": {
                  "self": {
                    "href": "/places/oxpoints:59801811"
                  }
                },
                "address": "Parks Road OX1 3QD",
                "distance": 0,
                "id": "oxpoints:59801811",
                "identifiers": [],
                "name": "Cyber Security Centre",
                "type": [
                  "/university/department"
                ],
                "type_name": [
                  "Department"
                ]
              },
              {
                "_links": {
                  "self": {
                    "href": "/places/oxpoints:58455192"
                  }
                },
                "address": "off South Parks Road OX1 3RQ",
                "distance": 0,
                "id": "oxpoints:58455192",
                "identifiers": [],
                "name": "Oxford University Security Services",
                "type": [
                  "/university/department"
                ],
                "type_name": [
                  "Department"
                ]
              },
            ]
          },
          "_links": {
            "curies": [
              {
                "href": "http://moxie.readthedocs.org/en/latest/http_api/relations/{rel}.html",
                "name": "hl",
                "templated": true
              }
            ],
            "hl:first": {
              "href": "/places/suggest?q=sec&count=20"
            },
            "hl:last": {
              "href": "/places/suggest?q=sec&count=20"
            },
            "self": {
              "href": "/places/suggest?q=sec&count=20&start=0"
            }
          },
          "query": "sec",
          "size": 13
        }

    :query q: what to search for
    :type q: string
    :query type_exact: filter by exact types (as opposite to the type parameter), you can have this parameter multiple times.
    :type type_exact: string
    :query start: first result to retrieve
    :type start: int
    :query count: number of results to retrieve
    :type count: int

    :statuscode 200: query found
    :statuscode 400: Bad request (e.g. missing parameters)
    :statuscode 503: Service not available


text:
/*************************************************************************/
/*  proximity_group.cpp                                                  */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "proximity_group.h"

#include "math_funcs.h"

void ProximityGroup::clear_groups() {

	Map<StringName, uint32_t>::Element *E;

	{
		const int size = 16;
		StringName remove_list[size];
		E = groups.front();
		int num = 0;
		while (E && num < size) {

			if (E->get() != group_version) {
				remove_list[num++] = E->key();
			};

			E = E->next();
		};
		for (int i=0; i<num; i++) {

			groups.erase(remove_list[i]);
		};
	};

	if (E) {
		clear_groups(); // call until we go through the whole list
	};
};

void ProximityGroup::update_groups() {

	if (grid_radius == Vector3(0, 0, 0))
		return;

	++group_version;

	Vector3 pos = get_global_transform().get_origin();
	Vector3 vcell = pos / cell_size;
	int cell[3] = { Math::fast_ftoi(vcell.x), Math::fast_ftoi(vcell.y), Math::fast_ftoi(vcell.z) };

	add_groups(cell, group_name, 0);

	clear_groups();
};

void ProximityGroup::add_groups(int* p_cell, String p_base, int p_depth) {

	p_base = p_base + "|";
	if (grid_radius[p_depth] == 0) {

		if (p_depth == 2) {
			_new_group(p_base);
		} else {
			add_groups(p_cell, p_base, p_depth + 1);
		};
	};

	int start = p_cell[p_depth] - grid_radius[p_depth];
	int end = p_cell[p_depth] + grid_radius[p_depth];

	for (int i=start; i<=end; i++) {

		String gname = p_base + itos(i);
		if (p_depth == 2) {
			_new_group(gname);
		} else {
			add_groups(p_cell, gname, p_depth + 1);
		};
	};
};

void ProximityGroup::_new_group(StringName p_name) {

	const Map<StringName, uint32_t>::Element* E = groups.find(p_name);
	if (!E) {
		add_to_group(p_name);
	};

	groups[p_name] = group_version;
};

void ProximityGroup::set_group_name(String p_group_name) {

	group_name = p_group_name;
};

void ProximityGroup::_notification(int what) {

	switch (what) {

	case NOTIFICATION_EXIT_TREE:
		++group_version;
		clear_groups();
		break;
	case NOTIFICATION_TRANSFORM_CHANGED:
		update_groups();
		break;
	};
};

void ProximityGroup::broadcast(String p_name, Variant p_params) {

	Map<StringName, uint32_t>::Element *E;
	E = groups.front();
	while (E) {

		get_tree()->call_group(SceneTree::GROUP_CALL_DEFAULT, E->key(), "_proximity_group_broadcast", p_name, p_params);
		E = E->next();
	};

};

void ProximityGroup::_proximity_group_broadcast(String p_name, Variant p_params) {

	if (dispatch_mode == MODE_PROXY) {

		get_parent()->call(p_name, p_params);
	} else {

		emit_signal("broadcast", p_name, p_params);
	};
};

void ProximityGroup::set_dispatch_mode(int p_mode) {

	dispatch_mode = (DispatchMode)p_mode;
};

void ProximityGroup::set_grid_radius(const Vector3& p_radius) {

	grid_radius = p_radius;
};

Vector3 ProximityGroup::get_grid_radius() const {

	return grid_radius;
};

void ProximityGroup::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("set_group_name","name"), &ProximityGroup::set_group_name);
	ObjectTypeDB::bind_method(_MD("broadcast","name", "parameters"), &ProximityGroup::broadcast);
	ObjectTypeDB::bind_method(_MD("set_dispatch_mode","mode"), &ProximityGroup::set_dispatch_mode);
	ObjectTypeDB::bind_method(_MD("_proximity_group_broadcast","name","params"), &ProximityGroup::_proximity_group_broadcast);
	ObjectTypeDB::bind_method(_MD("set_grid_radius","radius"), &ProximityGroup::set_grid_radius);
	ObjectTypeDB::bind_method(_MD("get_grid_radius"), &ProximityGroup::get_grid_radius);

	ADD_PROPERTY( PropertyInfo( Variant::VECTOR3, "grid_radius"), _SCS("set_grid_radius"), _SCS("get_grid_radius"));

	ADD_SIGNAL( MethodInfo("broadcast", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::ARRAY, "parameters")) );
};

ProximityGroup::ProximityGroup() {

	group_version = 0;
	dispatch_mode = MODE_PROXY;

	grid_radius = Vector3(1, 1, 1);

};

ProximityGroup::~ProximityGroup() {

};


text:
title: Github
visible: true
external_url: 'https://github.com/robbinworks/haywire-grav'
---


text:
package net.sf.j2ep.servers;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.j2ep.model.Server;

/**
 * A basic implementation of the Server interface using a single host name to
 * map all connections. Can be easily extended to create a server that gets it
 * host name in some other way. For instance a server fetching the host name
 * from the request could be made to change the proxy into a forwarding proxy.
 *
 * @author Anders Nyman
 */
/**
 *
 *
 * @author Anders Nyman
 */
public class BaseServer extends ServerContainerBase implements Server {

    private static final Logger logger = Logger.getLogger(BaseServer.class.getName());

    /**
     * Marks if this rule server will do any rewriting of links.
     */
    private boolean isRewriting;

    /**
     * The URL scheme identifying the protocol to use to communicate with the
     * server.
     */
    private String scheme;
    /**
     * The host and port for this server
     */
    private String domainName;

    /**
     * The path for this server
     */
    private String path;

    /**
     * Basic constructor that will initialize the directory to "".
     */
    public BaseServer() {
        logger.log(Level.SEVERE, "-----------------------base server reinitialized --------------");
        path = "";
        isRewriting = false;
    }

    /**
     * @param request
     * @return
     * @see
     * net.sf.j2ep.model.ServerContainer#getServer(javax.servlet.http.HttpServletRequest)
     */
    @Override
    public Server getServer(HttpServletRequest request) {
        return this;
    }

    /**
     * Will no do any handling
     *
     * @see
     * net.sf.j2ep.model.Server#preExecute(javax.servlet.http.HttpServletRequest)
     */
    @Override
    public HttpServletRequest preExecute(HttpServletRequest request) {
        return request;
    }

    /**
     * Will no do any handling
     *
     * @see
     * net.sf.j2ep.model.Server#postExecute(javax.servlet.http.HttpServletResponse)
     */
    @Override
    public HttpServletResponse postExecute(HttpServletResponse response) {
        return response;
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public String getScheme() {
        return scheme;
    }

    /**
     * @see net.sf.j2ep.model.Server#getDomainName()
     */
    @Override
    public String getDomainName() {
        return domainName;
    }

    /**
     * @see net.sf.j2ep.model.Server#getPath()
     */
    @Override
    public String getPath() {
        return path;
    }

    /**
     * @param location
     * @return
     * @see net.sf.j2ep.model.ServerContainer#getServerMapped(java.lang.String)
     */
    @Override
    public Server getServerMapped(String location) {
        String fullPath = getDomainName() + getPath() + "/";
        if (location.startsWith(fullPath) && isRewriting) {
            return this;
        } else {
            return null;
        }
    }

    /**
     * Set if this server wants absolute links mapped for this server to be
     * rewritten.
     *
     * @param rewrite Should be true if we want to do rewriting
     */
    public void setIsRewriting(String rewrite) {
        if (rewrite != null && rewrite.equals("true")) {
            isRewriting = true;
        }
    }

    public void setScheme(String scheme) {
        if (scheme == null || scheme.isEmpty()) {
            throw new IllegalArgumentException("URL scheme must not be null");
        }
        this.scheme = scheme;
    }

    /**
     * Sets the host and port we are mapping to.
     *
     * @param domainName Value to set
     */
    public void setDomainName(String domainName) {
        if (domainName == null) {
            throw new IllegalArgumentException(
                    "The hostAndPort string cannot be null.");
        } else {
            this.domainName = domainName;
        }
    }

    /**
     * Sets the path we are mapping to.
     *
     * @param path The path
     */
    public void setPath(String path) {
        if (path != null) {
            this.path = path;
        }
    }

    /**
     * @see
     * net.sf.j2ep.model.Server#setConnectionExceptionRecieved(java.lang.Exception)
     */
    @Override
    public void setConnectionExceptionRecieved(Exception e) {
        logger.log(Level.SEVERE, "BaseServer#setConnectionExceptionReceived {0}", e);
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.hadoop.hbase.io.encoding (HBase 0.98.7-hadoop2 API)</title>
<meta name="date" content="2014-10-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.apache.hadoop.hbase.io.encoding

Interfaces

DataBlockEncoder

DataBlockEncoder.EncodedSeeker

HFileBlockDecodingContext

HFileBlockEncodingContext

Classes

CopyKeyDataBlockEncoder

DiffKeyDeltaEncoder

DiffKeyDeltaEncoder.DiffCompressionState

DiffKeyDeltaEncoder.DiffSeekerState

EncodedDataBlock

FastDiffDeltaEncoder

FastDiffDeltaEncoder.FastDiffSeekerState

HFileBlockDefaultDecodingContext

HFileBlockDefaultEncodingContext

PrefixKeyDeltaEncoder

Enums

DataBlockEncoding

Exceptions

EncoderBufferTooSmallException


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package theory6.utilities;

/**
 *
 * @author Team 1241
 */
import com.sun.squawk.microedition.io.FileConnection;
import com.sun.squawk.util.LineReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.microedition.io.Connector;

public class Constants {
    private static Constants instance;
    public static Hashtable constants;
    private static boolean  usingFile;

    private Constants(){
        usingFile = true;
        this.load();
    }

    public static Constants getInstance(){
        if(instance == null)
        {
            instance = new Constants();
        }
        return instance;
    }

    public static void load(){

        constants = getDefaults();
        System.out.println("loading File");

        if(usingFile){
            InputStream is = null;
            try {
                System.out.println("creating FileConnection");
                FileConnection f = (FileConnection) Connector.open("file:///constants.txt", Connector.READ_WRITE);
                System.out.println("created FileConnection - Class: ");
                if(f.exists()){
                    System.out.println("FileConnection exists");
                    is = f.openInputStream();
                    LineReader r = new LineReader(new InputStreamReader(is));

                    String line = null;
                    int lineNum = 0;
                    while((line = r.readLine()) != null){
                        lineNum ++;
                        if(line.length() != 0 && line.charAt(0) != '#'){
                            int numSignPos = line.indexOf("#");
                            if(numSignPos > 0){
                                line = line.substring(0, numSignPos);
                            }

                            int equalsSignPos = line.indexOf("=");
                            if(equalsSignPos <= 1){
                                System.out.println("INVALID SETTING LINE: " + line + " (" + lineNum + ")");
                            }else{
                                String key = line.substring(0, equalsSignPos - 1).trim();
                                String value = line.substring(equalsSignPos + 1).trim();

                                if(key.length() > 0 && value.length() > 0){
                                    System.out.println("putting to HashTable: " + key + " = " + value);
                                    constants.put(key, value);
                                }
                            }
                        }

                    }
                }else{
                    f.create();
                    System.out.println("File has been Created");
                }
                f.close();
            } catch (Exception e) {
                System.out.println("failed to open fileConnection");
            }
        }

    }

    private static Hashtable getDefaults(){
        System.out.println("putting defaults");
        Hashtable defaults = new Hashtable();
        //////// DRIVE ////////
        //defaults.put("driveP", "0.1");
        //defaults.put("driveI", "0.2");
        //etc.
        System.out.println("defaults put");
        return defaults;
    }

    public static String getString(String constName, String def) {
        Object val = constants.get(constName);
        System.out.println("Reading String From Hash: " + val);
        if (val == null){
            System.out.println("Failed to return constant: " + constName);
            return def;
        }else{
            return (String) val;
        }
    }

    public static double getDouble (String constName) {
        try {
            double val = Double.parseDouble(getString(constName, ""));
            return val;
        } catch (Exception e) {
            return 0;
        }
    }

    public static int getInteger(String constName, int def) {
        try {
            int val = Integer.parseInt(getString(constName, ""));
            return val;
        } catch (Exception e) {
            return def;
        }
    }

    public static long getLong(String constName, long def) {
        try {
            long val = Long.parseLong(getString(constName,""));
            return val;
        } catch(NumberFormatException e){
            return def;
        }
    }

    public static boolean getBoolean (String constName, boolean def) {
        try {
            boolean val = getString(constName, "").toLowerCase().equals("true");
            if(getString(constName, "").toLowerCase().equals("false")){
                return val;
            }else{
                return def;
            }
        } catch(NumberFormatException e) {
            return def;
        }
    }
}


text:
<?php

namespace DTS\eBaySDK\Trading\Types;

/**
 *
 * @property string $Description
 * @property string $DetailVersion
 * @property integer $DispatchTimeMax
 * @property boolean $ExtendedHandling
 * @property \DateTime $UpdateTime
 */
class DispatchTimeMaxDetailsType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = array(
        'Description' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'Description'
        ),
        'DetailVersion' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'DetailVersion'
        ),
        'DispatchTimeMax' => array(
            'type' => 'integer',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'DispatchTimeMax'
        ),
        'ExtendedHandling' => array(
            'type' => 'boolean',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ExtendedHandling'
        ),
        'UpdateTime' => array(
            'type' => 'DateTime',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'UpdateTime'
        )
    );

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = array())
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
package net.ontopia.topicmaps.entry;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;

import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.infoset.impl.basic.URILocator;
import net.ontopia.topicmaps.core.StoreDeletedException;
import net.ontopia.topicmaps.core.TopicMapIF;
import net.ontopia.topicmaps.core.TopicMapStoreIF;
import net.ontopia.topicmaps.core.events.TopicMapListenerIF;
import net.ontopia.topicmaps.impl.utils.AbstractTopicMapStore;
import net.ontopia.utils.OntopiaRuntimeException;

/**
 * INTERNAL: An abstract topic map reference class that retrieves
 * topic maps referenced through URLs. Subclasses should implement the
 * loadTopicMap method.<p>
 *
 * @since 1.3.2
 */
public abstract class AbstractURLTopicMapReference
  extends AbstractTopicMapReference {

  protected URL url;
  protected LocatorIF base_address;
  protected boolean duplicate_suppression;

  protected boolean reuse_store = true;
  protected TopicMapStoreIF store;

  protected boolean maintainFulltextIndexes;
  protected String indexDirectory;

  public AbstractURLTopicMapReference(String id, String title, URL url,
                                      LocatorIF base_address) {
    super(id, title);
    this.url = url;
    this.base_address = base_address;
    if (base_address == null) {
      try {
        base_address = new URILocator(url);
      } catch (MalformedURLException e) {
        throw new OntopiaRuntimeException(e); // impossible error
      }
    }
  }

  /**
   * INTERNAL: Returns the URL of the topic map pointed at.
   */
  public URL getURL() {
    return url;
  }

  /**
   * INTERNAL: Returns the base address locator to be used when loading
   * the topic map.
   */
  public LocatorIF getBaseAddress() {
    return base_address;
  }

  /**
   * INTERNAL: Sets the base address locator to be used when loading
   * the topic map.
   */
  public void setBaseAddress(LocatorIF base_address) {
    this.base_address = base_address;
  }

  /**
   * INTERNAL: Gets the duplicate suppression flag. If the flag is
   * true duplicate suppression is to be performed when loading the
   * topic maps.
   *
   * @since 1.4.2
   */
  public boolean getDuplicateSuppression() {
    return duplicate_suppression;
  }

  /**
   * INTERNAL: Sets the duplicate suppression flag. If the flag is
   * true duplicate suppression is to be performed when loading the
   * topic maps.
   *
   * @since 1.4.2
   */
  public void setDuplicateSuppression(boolean duplicate_suppression) {
    this.duplicate_suppression = duplicate_suppression;
  }

  /**
   * INTERNAL: Flag that indicates whether the same store should be
   * returned by the createStore(boolean) method on every. If the flag
   * is false then a new store will be returned every time. Returning
   * a new store every time effectively means that the referenced
   * topic map will be loaded on every method call.
   *
   * @since 2.1
   */
  public boolean getReuseStore() {
    return reuse_store;
  }

  /**
   * INTERNAL: Sets the reuse_store flag.
   *
   * @since 2.1
   */
  public void setReuseStore(boolean reuse_store) {
    this.reuse_store = reuse_store;
  }

  @Override
  public synchronized void open() {
    // ignore if already open
    if (isOpen()) {
      return;
    }
    if (isDeleted()) {
      throw new StoreDeletedException("Topic map has been deleted through this reference.");
    }
    // make sure store is loaded
    if (reuse_store && store == null) {

      // load topic map store
      boolean readonly = false; // WARNING: store always read-write!!!
      TopicMapStoreIF store = null;
      try {
        store = loadTopicMap(readonly).getStore();
      } catch (IOException e) {
        throw new OntopiaRuntimeException(e);
      }
      // register store
      store.setReference(this);
      // register listeners
      ((AbstractTopicMapStore)store).setTopicListeners(getTopicListeners());

      this.store = store;
    }
    this.isopen = true;
  }

  @Override
  public synchronized void close() {
    // close and dereference store
    if (store != null) {
      if (store.isOpen()) {
        store.close();
      }
      store = null;
    }
    this.isopen = false;
  }

  /**
   * INTERNAL: Deletes the topic map pointed to. The reference is closed
   * before the topic map is deleted. Note that only URIs pointing to
   * through files can actually be deleted, i.e. "file:" URLs.
   *
   * @since 1.3.2
   */
  @Override
  public synchronized void delete() {
    if (source == null) {
      throw new UnsupportedOperationException("This reference cannot be deleted as it does not belong to a source.");
    }
    if (!source.supportsDelete()) {
      throw new UnsupportedOperationException("This reference cannot be deleted as the source does not allow deleting.");
    }

    // ignore if store already deleted
    if (isDeleted()) {
      return;
    }

    // close reference
    close();
    // delete file.
    if ("file".equals(url.getProtocol())) {
      File file = new File(url.getFile());
      // FIXME: complain if file does not exist?
      file.delete();
    }
    this.deleted = true;
  }

  @Override
  public synchronized TopicMapStoreIF createStore(boolean readonly) throws IOException {
    if (!isOpen()) {
      open();
    }

    if (reuse_store && store != null) {
      return store;
    }

    // load topic map store
    TopicMapStoreIF store = loadTopicMap(readonly).getStore();
    // register store
    store.setReference(this);
    // register listeners
    ((AbstractTopicMapStore)store).setTopicListeners(getTopicListeners());

    if (reuse_store) {
      this.store = store;
    }
    return store;
  }

  protected abstract TopicMapIF loadTopicMap(boolean readonly) throws IOException;

  @Override
  public String toString() {
    return super.toString() + " [" + url.toString() + "]";
  }

  /**
   * INTERNAL: Returns true if stores will keep underlying fulltext
   * indexes up-to-date.
   * @return True if fulltext indexes are maintained.
   * @since 3.0
   */
  public boolean getMaintainFulltextIndexes() {
    return maintainFulltextIndexes;
  }

  /**
   * INTERNAL: Specifies whether underlying fulltext indexes are to be
   * kept up-to-date or not.
   * @param maintainFulltextIndexes True if fulltext indexes are maintained.
   * @since 3.0
   */
  public void setMaintainFulltextIndexes(boolean maintainFulltextIndexes) {
    this.maintainFulltextIndexes = maintainFulltextIndexes;
  }

  public String getIndexDirectory() {
    return indexDirectory;
  }

  public void setIndexDirectory(String indexDirectory) {
    this.indexDirectory = indexDirectory;
  }

  @Override
  protected void setTopicListeners(TopicMapListenerIF[] topic_listeners) {
    super.setTopicListeners(topic_listeners);
    if (reuse_store && store != null) {
      // register listeners
      ((AbstractTopicMapStore)store).setTopicListeners(getTopicListeners());
    }
  }
}


text:
package fr.askjadev.xml.extfunctions.marklogic;

import fr.askjadev.xml.extfunctions.marklogic.utils.DatabaseUtils;
import fr.askjadev.xml.extfunctions.marklogic.utils.XQueryUtils;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.FailedRequestException;
import com.marklogic.client.ForbiddenUserException;
import com.marklogic.client.MarkLogicIOException;
import com.marklogic.client.eval.ServerEvaluationCall;
import com.marklogic.client.io.InputStreamHandle;
import fr.askjadev.xml.extfunctions.marklogic.config.QueryConfiguration;
import fr.askjadev.xml.extfunctions.marklogic.config.QueryConfigurationFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.StaticContext;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.ma.map.HashTrieMap;
import net.sf.saxon.ma.map.MapType;
import net.sf.saxon.om.*;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;

/**
 * Abstract class representing a Saxon MarkLogic extension function
 * @author Axel Court + Emmanuel Tourdot
 */
public abstract class AbstractMLExtensionFunction extends ExtensionFunctionDefinition {

    private String staticBaseUri;

    enum ExtentionType {
        XQUERY_URI, XQUERY_STRING, MODULE;
    }

    @Override
    public SequenceType[] getArgumentTypes() {
        return new SequenceType[] {
            SequenceType.SINGLE_STRING,
            MapType.OPTIONAL_MAP_ITEM,
            MapType.OPTIONAL_MAP_ITEM
        };
    }

    @Override
    public int getMinimumNumberOfArguments() {
        return 2;
    }

    @Override
    public int getMaximumNumberOfArguments() {
        return 3;
    }

    @Override
    public SequenceType getResultType(net.sf.saxon.value.SequenceType[] sts) {
        return SequenceType.ANY_SEQUENCE;
    }

    ExtensionFunctionCall constructExtensionFunctionCall(final ExtentionType type) {

        return new ExtensionFunctionCall() {

            @Override
            public Sequence call(XPathContext xpc, Sequence[] args) throws XPathException {
                // Check and get the configuration
                QueryConfiguration config = new QueryConfigurationFactory().getConfig(args);
                // Get the XQuery or the module to invoke
                String moduleOrQuery = getXQueryOrModule(args);
                // Launch
                Processor proc = new Processor(xpc.getConfiguration());
                DatabaseClient session = null;
                try {
                    session = DatabaseUtils.createMarkLogicClient(config);
                    // Eval query and get result
                    DocumentBuilder builder = proc.newDocumentBuilder();
                    ServerEvaluationCall call = session.newServerEval();
                    switch (type) {
                        case MODULE:
                            call.modulePath(moduleOrQuery);
                            break;
                        case XQUERY_STRING:
                            call.xquery(moduleOrQuery);
                            break;
                        case XQUERY_URI:
                            // Read the XQuery and send it as an InputStreamHandle
                            InputStreamHandle xquery = XQueryUtils.getXQueryFromURI(xpc, moduleOrQuery, staticBaseUri);
                            call.xquery(xquery);
                            xquery.close();
                            break;
                    }
                    if (args.length == 3) {
                    	try {
                            call = DatabaseUtils.addExternalVariables(call, xpc, proc, (HashTrieMap) args[2].head());
                    	}
                    	catch (ClassCastException ex) {
                            throw new XPathException("The 3d argument must be an XPath 3.0 map defining the query external variables.");
                        }
                    }
                    return DatabaseUtils.getQueryResult(call, builder, xpc);
                }
                catch (FailedRequestException | ForbiddenUserException | MarkLogicIOException ex) {
                    throw new XPathException(ex);
                }
            }

            @Override
            public void supplyStaticContext(StaticContext context, int locationId, Expression[] args) throws XPathException {
                // Add information about the static context
                staticBaseUri = context.getStaticBaseURI();
            }

        };

    }

    private String getXQueryOrModule(Sequence [] args) throws XPathException {
        // May be a reference to a module, the URI to a local XQuery or a string containing the XQuery
        String xqueryOrModule = ((StringValue) args[0].head()).getStringValue();
        return xqueryOrModule;
    }

}


text:
package com.laocuo.biyeban.bmob;

import java.util.ArrayList;

import cn.bmob.v3.BmobObject;

public class FreshNews extends BmobObject {
    private String userObjectId;
    private String content;
    private String time;
    private ArrayList<String> pics;
    private ArrayList<String> comments;

    /*
    * update freashnews
    */
    public FreshNews(String tablename) {
        this.setTableName(tablename);
    }

    /*
    * when create a new class, we need to add first freshnews.
    */
    public FreshNews(String userObjectId, String tablename) {
        this.setContent("Welcome!");
        this.setTime("1月1日");
        this.setTableName(tablename);
        this.setUserObjectId(userObjectId);
    }

    public String getUserObjectId() {
        return userObjectId;
    }

    public void setUserObjectId(String userObjectId) {
        this.userObjectId = userObjectId;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public ArrayList<String> getPics() {
        return pics;
    }

    public void setPics(ArrayList<String> pics) {
        this.pics = pics;
    }

    public ArrayList<String> getComments() {
        return comments;
    }

    public void setComments(ArrayList<String> comments) {
        this.comments = comments;
    }
}


text:
using System;
using System.Web;
using NShop.Model;
using NShop.Repositories;
using NShop.Services;

namespace NShop.Impl
{
	public class SecurityInformation : ISecurityInformation
	{
		IRepository<ISecurable> securityRepository;

		#region ISecurityInformation Members

		public bool HasAuthorizationFor(string action)
		{
			HttpContext current = HttpContext.Current;
			if(current == null)
				return false;
			return current.User.Identity.IsAuthenticated;
		}

		#endregion
	}
}


text:
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//     * Neither the name of Ayende Rahien nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

namespace Rhino.Mocks.Interfaces
{
	/*
	 * interface: IRepeat
	 *
	 * Allows to specified the number of times a method is called.
	 */
	/// <summary>
	/// Allows to specify the number of time for method calls
	/// </summary>
	public interface IRepeat<T>
	{
		/*
		 * Method: Twice
		 *
		 * The method will repeat twice
		 */
		/// <summary>
		/// Repeat the method twice.
		/// </summary>
		IMethodOptions<T> Twice();

		/*
		 * Method: Once
		 *
		 * The method will repeat once.
		 *
		 * note:
		 * This is the default behaviour.
		 */
		/// <summary>
		/// Repeat the method once.
		/// </summary>
		IMethodOptions<T> Once();

	    /// <summary>
        /// Repeat the method at least once, then repeat as many time as it would like.
        /// </summary>
        IMethodOptions<T> AtLeastOnce();

		/*
		 * Method: Any
		 *
		 * Repeat the method any number of times.
		 *
		 * note:
		 * This has special affects in that this method would now ignore orderring.
		 */
		/// <summary>
		/// Repeat the method any number of times.
		/// This has special affects in that this method would now ignore orderring.
		/// </summary>
		IMethodOptions<T> Any();

		/*
		 * Method: Times
		 *
		 * Repeat the method the specified number of time between min & max.
		 *
		 * Params:
		 *	- min - The minimum number of times the method can repeat
		 *  - max - The maximum number of times the method can repeat
		 *
		 */
		/// <summary>
		/// Set the range to repeat an action.
		/// </summary>
		/// <param name="min">Min.</param>
		/// <param name="max">Max.</param>
		IMethodOptions<T> Times(int min, int max);

		/*
		 * Method: Times
		 *
		 * Set the exact number of times this method can repeat.
		 */
		/// <summary>
		/// Set the amount of times to repeat an action.
		/// </summary>
		IMethodOptions<T> Times(int count);

		/*
		 * Method: Never
		 *
		 * This method must not appear in the replay state.
		 *
		 * note:
		 * This has special affects in that this method would now ignore orderring.
		 */
		/// <summary>
		/// This method must not appear in the replay state.
		/// This has special affects in that this method would now ignore orderring.
		/// </summary>
		IMethodOptions<T> Never();
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Search — PPMstar 0 documentation</title>
    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="#" />

  <link rel="stylesheet" href="_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

PPMstar

Navigation

Contents:

Installation

Data Assumptions

ppm

Search

    Please activate JavaScript to enable the search
    functionality.

    From here you can search these documents. Enter your search
    words into the box below and click "search". Note that the search
    function will automatically search for all of the words. Pages
    containing fewer words won't appear in the result list.

  <form action="" method="get">
    <input type="text" name="q" value="" />
    <input type="submit" value="search" />

  </form>

      ©2017, PPMstar.

      |
      Powered by Sphinx 1.6.5
      & Alabaster 0.7.10


text:
module Projects
  class UpdatePagesConfigurationService < BaseService
    include Gitlab::Utils::StrongMemoize

    attr_reader :project

    def initialize(project)
      @project = project
    end

    def execute
      # If the pages were never deployed, we can't write out the config, as the
      # directory would not exist.
      # https://gitlab.com/gitlab-org/gitlab/-/issues/235139
      return success unless project.pages_deployed?

      unless file_equals?(pages_config_file, pages_config_json)
        update_file(pages_config_file, pages_config_json)
        reload_daemon
      end

      success
    end

    private

    def pages_config_json
      strong_memoize(:pages_config_json) do
        pages_config.to_json
      end
    end

    def pages_config
      {
        domains: pages_domains_config,
        https_only: project.pages_https_only?,
        id: project.project_id,
        access_control: !project.public_pages?
      }
    end

    def pages_domains_config
      enabled_pages_domains.map do |domain|
        {
          domain: domain.domain,
          certificate: domain.certificate,
          key: domain.key,
          https_only: project.pages_https_only? && domain.https?,
          id: project.project_id,
          access_control: !project.public_pages?
        }
      end
    end

    def enabled_pages_domains
      if Gitlab::CurrentSettings.pages_domain_verification_enabled?
        project.pages_domains.enabled
      else
        project.pages_domains
      end
    end

    def reload_daemon
      # GitLab Pages daemon constantly watches for modification time of `pages.path`
      # It reloads configuration when `pages.path` is modified
      update_file(pages_update_file, SecureRandom.hex(64))
    end

    def pages_path
      @pages_path ||= project.pages_path
    end

    def pages_config_file
      File.join(pages_path, 'config.json')
    end

    def pages_update_file
      File.join(::Settings.pages.path, '.update')
    end

    def update_file(file, data)
      temp_file = "#{file}.#{SecureRandom.hex(16)}"
      File.open(temp_file, 'w') do |f|
        f.write(data)
      end
      FileUtils.move(temp_file, file, force: true)
    ensure
      # In case if the updating fails
      FileUtils.remove(temp_file, force: true)
    end

    def file_equals?(file, data)
      existing_data = read_file(file)
      data == existing_data.to_s
    end

    def read_file(file)
      File.open(file, 'r') do |f|
        f.read
      end
    rescue
      nil
    end
  end
end


text:
<?php

namespace Torchbox\Thankq\Api;

class doContactInsert
{

    /**
     * @var esitWSdoContactInsertArgument $doContactInsertArgument
     */
    protected $doContactInsertArgument = null;

    /**
     * @param esitWSdoContactInsertArgument $doContactInsertArgument
     */
    public function __construct($doContactInsertArgument)
    {
      $this->doContactInsertArgument = $doContactInsertArgument;
    }

    /**
     * @return esitWSdoContactInsertArgument
     */
    public function getDoContactInsertArgument()
    {
      return $this->doContactInsertArgument;
    }

    /**
     * @param esitWSdoContactInsertArgument $doContactInsertArgument
     * @return \Torchbox\Thankq\Api\doContactInsert
     */
    public function setDoContactInsertArgument($doContactInsertArgument)
    {
      $this->doContactInsertArgument = $doContactInsertArgument;
      return $this;
    }

}


text:
/*
My GeoLocation  module source
Author Jason
Date 2016/9/11
*/
//HTML5 Geolocation
define(['jquery','hmac-sha1'],function(jquery,CryptoJS){

//Global object. saved postion data.
    function CreateLocation(){
        this.latitude=undefined;
        this.longitude=undefined;
        this.setLatitude=function(latitude){
            this.latitude=latitude;
        }
        this.getLatitude=function(){
            return this.latitude;
        }
        this.setLongitude=function(longitude){
            this.longitude=longitude;
        }
        this.getLongitude=function(){
            return this.longitude;
        }
    }

    CreateLocation.prototype={

        getLocation:function(){
            if(navigator.geolocation){

                //navigator.geolocation.getCurrentPosition(locationSuccess,showError,);
                var self=this;
                var wpid=navigator.geolocation.watchPosition(self.locationSuccess,self.showError,{
                    //指示浏览器获取高精度的位置
                    enableHighAcuracy:true,
                    //指定获取地理位置的超时时间,ms
                    timeout:50000,
                    //最长有效期,重复获取地理位置时,此参数多久再次获取
                    maximumAge:30000
                });
            }
            else{
                alert("Geolocation is not supported by this browser!");
            }
        },
        locationSuccess:function(position){
            var coords=position.coords;
            navigator.geolocation.latitude=coords.latitude+0.00374531687912;//偏移量校正值
            navigator.geolocation.longitude=coords.longitude+0.008774687519;
            //console.log("Success ",this.latitude,this.longitude);
        },
        showError:function(error){
            switch(error.code)
            {
                case error.PERMISSION_DENIED:
                    console.log("User denied the request for Geolocation.");
                    break;
                case error.POSITION_UNAVAILABLE:
                    console.log("Location information is unavailable.");
                    break;
                case error.TIMEOUT:
                    console.log("The request to get user location timed out.");
                    break;
                case error.UNKNOWN_ERROR:
                    console.log("An unknown error occurred.");
                    break;
            }
        },

    //AJAX longPolling,but it needs the corperation with server-side
        longPolling:function(){
            var api="http://api.openweathermap.org/data/2.5/weather?q="; //http:
            var appid="&APPID=4c16d64121b3d1c838c58a8c8b100a15";
            var city="Shenzhen";
            // var lat="lat="+obj.latitude;
            // var lon="lon="+obj.longitude;
            //返回数据的单位。不设置默认不是摄氏度
            var units="&units=metric";
            var cb="&jsoncallback=JSON_CALLBACK";
            $.ajax({
                url:api+city+units+appid+cb,
                data:{"timed":new Date().getTime()},
                dataType:"jsonp",
                jsonpCallback:"JSON_CALLBACK",
                success:function(data){

                }
            });
        },
        myGetJSON:function(){
            var api="http://api.openweathermap.org/data/2.5/weather?";
            //var api="//api.thinkpage.cn/v3/weather/now.json";
            var appid="&APPID=4c16d64121b3d1c838c58a8c8b100a15";
            var userId="U8375BA840"; //no need
            var key="?key=prvl5fqcz7mcguh3";
            var city="q=Shenzhen";
            //返回数据的单位。不设置默认不是摄氏度
            var units="&units=metric"; //metric";c
            //&jsoncallback=?,设置为?是jq随机产生一个名字,但是此处必须指定一个名字,都可以除了?
            var lat="lat="+navigator.geolocation.latitude;//22.53675831687912);
            var lon="&lon="+navigator.geolocation.longitude;//113.93925068751899);
            //var location="?location="+navigator.geolocation.latitude+":"+navigator.geolocation.longitude;
            var cb="&jsoncallback=JSON_CALLBACK";
           // var cb="&callback=showWeather";
            var html='
MyWeather
';
                 //获取时间戳
            // var ts=Math.floor((new Date()).getTime()/1000);
            // //构造验证参数字符串
            // var str="&ts="+ts+"&uid="+userId;
            //     //使用HMAC-SHA1方式,以API秘钥为key对上一步生成的参数字符串进行加密
            //     //将加密结果用base64存储
            // var sig=CryptoJS.HmacSHA1(str,key).toString(CryptoJS.enc.Base64);
            // sig=encodeURIComponent(sig);
            // str=str+"&sig="+sig;
            var proxy='https://bird.ioliu.cn/v1/?url=';
            $.getJSON(proxy+api+lat+lon+units+appid+cb,function(data){
                var weatherData='
';
                    //data已经被转为jq的对象
                if(data.main){
                    var temp=Math.round(data.main.temp);
                    var descript=data.weather[0].description;
                        /*$.each(data,function(k,v){
                            console.log(k);
                         });*/
                    html+=''+data.name+','+data.sys.country+'';
                    $("#weather").html(html);
                    weatherData+='
'+temp+'\u2103'+'
'+'
'+descript+'
';
                    weatherData+='
';
                    $("#weather").append(weatherData);
                }
            });
        },
        handlePermission:function(){
            if(navigator.permissions){
                var self=this;
                navigator.permissions.query({name:'geolocation'}).then(function(result){
                if(result.state=='granted'){
                    self.report(result.state);
                    return false;//it doesn't need to ask if location is allowed to visited
                }else if(result.state=='prompt'){
                    self.report(result.state);
                    return true;
                }else if(result.state=='denied'){
                    self.report(result.state);
                    return false;
                }
                    result.onchange=function(){
                        self.report(result.state);
                    }
                });
            }
            else
            {
                console.log("The browser doesn't support Permissions API!");
            }
        },
        report:function(state){
            //console.log('Permission: '+state);
        }
    }
    return {
        CreateLocation:CreateLocation
    }

});