text:
use MooseX::Declare;
use Method::Signatures::Simple;

=head2

PACKAGE		Configure

PURPOSE

    1. CONFIGURE THE Agua DATABASE

    2. CONFIGURE DATA AND APPLICATION PATHS AND SETTINGS

        E.G., PATHS TO BASIC EXECUTABLES IN CONF FILE:

        [applications]
        STARCLUSTER	      	/data/apps/starcluster/0.92.rc1/bin/starcluster
        BOWTIE              /data/apps/bowtie/0.12.2
        CASAVA              /data/apps/casava/1.6.0/bin
        CROSSMATCH          /data/apps/crossmatch/0.990329/cross_match
        CUFFLINKS           /data/apps/cufflinks/0.8.2
        ...

=cut
use strict;
use warnings;
use Carp;

#### USE LIB FOR INHERITANCE
use FindBin::Real;
use lib FindBin::Real::Bin() . "/lib";
use Data::Dumper;

class Agua::Configure with (Logger, Agua::Common) {

#### USE LIB
use FindBin::Real;
use lib FindBin::Real::Bin() . "/lib";

#### EXTERNAL MODULES
use Data::Dumper;
use Term::ReadKey;

#### INTERNAL MODULES
use Agua::DBaseFactory;
use Conf::Yaml;

# Booleans
has 'log'		=>  ( isa => 'Int', is => 'rw', default => 1 );
has 'printlog'		=>  ( isa => 'Int', is => 'rw', default => 1 );
has 'validated'		=> ( isa => 'Int', is => 'rw', default => 0 );

# Strings
has 'arch'			=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'username'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'requestor'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'cluster'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'outputdir'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'configfile'	=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'logfile'		=> ( isa => 'Str|Undef', is => 'rw' );
has 'dumpfile'		=> ( isa => 'Str|Undef', is => 'rw' );
has 'database'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'user'			=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'password'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'guestuser'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'testdatabase'	=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'testuser'		=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'testpassword'	=> ( isa => 'Str|Undef', is => 'rw', default => '' );
has 'rootuser'		=> ( isa => 'Str|Undef', is => 'ro', default => 'root' );
has 'rootpassword'	=> ( isa => 'Str|Undef', is => 'rw', default => '' );

# Objects
has 'json'			=> ( isa => 'HashRef', is => 'rw', required => 0 );
has 'aguadb'		=> ( isa => 'Agua::DBase::MySQL', is => 'rw', required => 0 );
has 'rootdb'		=> ( isa => 'Agua::DBase::MySQL', is => 'rw', required => 0 );
has 'db'			=> ( isa => 'Agua::DBase::MySQL', is => 'rw', required => 0 );
has 'conf' 			=> (
	is =>	'rw',
	isa => 'Conf::Yaml',
	default	=>	sub { Conf::Yaml->new( {} );	}
);

####/////}

method BUILD ($hash) {
	#$self->logDebug("Agua::Configure::BUILD()");
	$self->logDebug("self", $self);
	$self->initialise();
}

method initialise {
	#### IF JSON IS DEFINED, ADD VALUES TO SLOTS
	my $json = $self->json();
	if ( $json )
	{
		foreach my $key ( keys %{$json} )
		{
			$self->logDebug("SETTING self->$key", $json->{$key}) if $self->can($key);
			$self->$key($json->{$key}) if $self->can($key);
		}
	}
	$self->logDebug("json", $json);

 	#### SET CONF LOG
	$self->conf()->log($self->log());
	$self->conf()->printlog($self->printlog());
}

method config {

	#### COPY DEFAULT CONFIG FILE
	$self->copyConf();

	#### SET UP MYSQL DATABASE AND DB USER
	$self->mysql();

	#### CONFIGURE CRON JOB TO MONITOR StarCluster LOAD BALANCER
	$self->cron();

	#### CREATE guest USER ACCOUNT ON FILESYSTEM AND IN Agua DATABASE
	$self->guestUser();

	#### CREATE admin USER ACCOUNT ON FILESYSTEM AND IN Agua DATABASE
	$self->adminUser();

	#### EDIT /etc/fstab TO ENABLE REBOOT FOR MICRO INSTANCES
	$self->fixFstab();

print "\n\n\n";
print "************************************       ************************************\n";
print "*********                        Completed 'config'                   *********\n";
print "************************************       ************************************\n";
print "\n\n\n";

	$self->logDebug("Completed $0");
}

#### COPY CONFIG FILE
method copyConf {
#### COPY config.yaml FILE FROM RESOURCES TO conf DIR
	my $confdir = "$Bin/../../conf";
	$self->logDebug("confdir", $confdir);
	my $resourcedir = "$Bin/resources/agua/conf";
	$self->logDebug("resourcedir", $resourcedir);
	my $sourcefile = "$resourcedir/config.yaml";
	my $targetfile = "$confdir/config.yaml";
	$self->backupFile($targetfile) if -f $targetfile;

	#### COPY
	my $command = "cp -f $sourcefile $targetfile";
	$self->logDebug("command", $command);
	`$command`;
}
#### SSH
method enableSsh {
#### ENABLE SSH PASSWORD LOGIN
	$self->logDebug("");

	#### VERIFY ADMIN OR root USER
	my $isadmin = $self->_isAdminOrRoot();
	$self->logDebug("isadmin", $isadmin);

	$self->logError("User is not admin user") and exit if not $isadmin;

	#### SET KEY VALUE IN CONF FILE
	$self->conf()->setKey("agua", "SSHPASSWORDLOGIN", "YES");

	#### EDIT sshd_config TO ENABLE SSH
	$self->_enableSshPasswordLogin();
}

=head2

SUBROUTINE         admin

PURPOSE

	DISABLE SSH PASSWORD LOGIN

=cut

method disableSsh {
	$self->logDebug("");

	#### VERIFY ADMIN OR root USER
	$self->logError("User is not admin user") and exit if not $self->_isAdminOrRoot();

	#### SET KEY VALUE IN CONF FILE
	$self->conf()->setKey("agua", "SSHPASSWORDLOGIN", "NO");

	#### EDIT sshd_config TO DISABLE SSH
	$self->_disableSshPasswordLogin();
}

method _isAdminOrRoot {
	my $username = $self->username() || '';
	$self->logDebug("username", $username);

	my $whoami = `whoami` || '';
	$whoami =~ s/\s+//;
	$self->logDebug("whoami", $whoami);

	my $user = $username;
	$user = $whoami if not defined $user or not $user;

	my $adminuser = $self->conf()->getKey("agua", "ADMINUSER") || '';
	$self->logDebug("adminuser", $adminuser);

	return 0 if $username ne $adminuser and $whoami ne "root";
	return 1;
}

#### CREATE SGEADMIN AND ADMIN USERS
method createUsers {
	#$self->sgeUser();

	$self->adminUser();
}

method sgeUser {
#### CREATE SGE USER LINUX ACCOUNT

print "\n\n\n";
print "****************************************************************\n";
print "********            CREATE SGE USER ACCOUNT            *********\n";
print "****************************************************************\n";
print "\n\n\n";

    #### SGE USERNAME
	my $username = $self->conf()->getKey("agua", "SGEUSER");
	$self->logDebug("username", $username);
	$username = $self->_inputValue("SGE username", $username);
    $self->logError("username not defined") if not defined $username;
	$self->logDebug("FINAL username", $username);

	#### SGE USERID
	my $userid = $self->conf()->getKey("agua", "SGEUSERID");
	$self->logDebug("username", $username);
	$userid = $self->_inputValue("SGE userid", $userid);
    $self->logError("userid not defined") if not defined $userid;
	$self->logDebug("FINAL userid ", $userid);

	my $object = {
		username	=>	$username,
		userid		=>	$userid,
		firstname	=>	"admin",
		lastname	=>	"admin"
	};
    $self->logDebug("object", $object);

	#### ADD LINUX ACCOUNT FOR ADMIN USER AND CREATE HOME DIRECTORY
	$self->_addLinuxDaemon($object);

print "\n\n\n";
print "****************************************************************\n";
print "**********    SGE USER ACCOUNT SUCCESSFULLY CREATED   **********\n";
print "****************************************************************\n";
print "\n\n\n";

}

method adminUser {
=head2

SUBROUTINE         admin

PURPOSE

	CREATE THE ADMIN USER LINUX ACCOUNT

=cut

print "\n\n\n";
print "****************************************************************\n";
print "**********      CREATE admin LINUX USER ACCOUNT      ***********\n";
print "\n\n\n";

    #### ADMIN USERNAME
	my $username = $self->conf()->getKey("agua", "ADMINUSER");
	$username = $self->_inputValue("Admin username", $username);
    $self->logError("username not defined") if not defined $username;

    #### ADMIN USERNAME
	my $firstname = "admin";
	$firstname = $self->_inputValue("Admin firstname", $firstname);
    $self->logError("firstname not defined") if not defined $firstname;

    #### ADMIN USERNAME
	my $lastname = "admin";
	$lastname = $self->_inputValue("Admin lastname", $lastname);
    $self->logError("lastname not defined") if not defined $lastname;

    #### ADMIN PASSWORD
	my $password = $self->_setAdminPassword();

    #### ADMIN EMAIL
	my $email = "";
	$email = $self->_inputValue("Admin email", $email);
    $self->logError("email not defined") if not defined $email;

	my $object = {
		username	=>	$username,
		password	=>	$password,
		email		=>	$email,
		firstname	=>	$firstname,
		lastname	=>	$lastname
	};
    $self->logDebug("object", $object);

	$self->setDbh();

	### REMOVE OLD ADMIN USER ENTRY
	$self->_removeUser($object);

	#### ADD ADMIN USER TO AGUA DATABASE
	$self->_addUser($object);

	#### ADD LINUX ACCOUNT FOR ADMIN USER AND CREATE HOME DIRECTORY
	$self->_addLinuxUser($object);

print "\n\n\n";
print "*************    admin LINUX USER ACCOUNT CREATED   ************\n";
print "****************************************************************\n";
print "\n\n\n";

}

method _setAdminPassword {
$self->logDebug("Agua::Configure::_setAdminPassword()");

	#### MASK TYPING FOR PASSWORD INPUT
    ReadMode 2;

	my $password = '';
	my $minlength = 8;
	while ( length($password) < $minlength )
	{
		print "\n\nPlease input admin user password (Minimum $minlength characters)\n\n";
		$password = $self->_inputHiddenValue("Please input admin user password (will not appear on screen)", $password);
	}

    #### UNMASK TYPING
    ReadMode 0;

	return $password;
}

#### TEST USER
method testUser {

print "\n\n\n";
print "*********************************************************************\n";
print "***************** CREATING TEST USER LINUX ACCOUNT ******************\n";
print "*********************************************************************\n";
print "\n\n\n";

	my $username 	= $self->conf()->getKey("database", "TESTUSER");
	my $firstname 	= "";
	my $lastname 	= "";
	my $email 		= "test\@trash.com";
	my $object 		= {
		username	=>	$username,
		password	=>	"",
		email		=>	$email,
		firstname	=>	$firstname,
		lastname	=>	$lastname
	};
    $self->logDebug("object", $object);

	### REMOVE OLD AGUA TEST LINUX ACCOUNT
	$self->_removeLinuxUser($object);

	### ADD NEW AGUA TEST LINUX ACCOUNT AND CREATE DIRECTORY IF NOT EXISTS
	$self->_addLinuxUser($object);

	#### SET TEST USER MYSQL ACCOUNT
	$self->setTestUser();

print "\n\n\n";
print "*********************************************************************\n";
print "************    TEST USER ACCOUNT SUCCESSFULLY CREATED    ***********\n";
print "*********************************************************************\n";
print "\n\n\n";
}

method _loadUserData ($username, $database, $subdir) {
    my $rootpassword   	=   $self->rootpassword();
	$rootpassword 		=	$self->_inputRootPassword() if not defined $rootpassword;
	#$self->logDebug("rootpassword", $rootpassword);

	my $dumpfile		=	$self->_getDumpfile($username, $subdir);
	$self->logDebug("dumpfile", $dumpfile);

	my $command = "mysql -u root -p$rootpassword $database < $dumpfile";
	#$self->logDebug("command", $command);
	print `$command`;

}
method _getDumpfile ($username, $subdir) {

	my $dumpfile	=	"$Bin/../sql/dump/$subdir/$username.dump";

	return $dumpfile;
}
#### SET CRON JOB
method cron {
=head2

	SUBROUTINE		cron

	PURPOSE

		INSERT INTO /etc/crontab COMMANDS TO BE RUN AUTOMATICALLY

		ACCORDING TO THE DESIRED TIMETABLE:

			1. checkBalancers.pl	-	VERIFY LOAD BALANCERS ARE

				RUNNING AND RESTART THEM IF THEY HAVE STOPPED. THIS

				TASK RUNS ONCE A MINUTE

	NOTES

		cat /etc/crontab
		# /etc/crontab: system-wide crontab
		# Unlike any other crontab you don't have to run the `crontab'
		# command to install the new version when you edit this file
		# and files in /etc/cron.d. These files also have username fields,
		# that none of the other crontabs do.

		SHELL=/bin/sh
		PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

		# m h dom mon dow user	command
		17 *	* * *	root    cd / && run-parts --report /etc/cron.hourly
		25 6	* * *	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
		47 6	* * 7	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
		52 6	1 * *	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

=cut

	print "Running cron configuration\n";

	my $installdir = $self->conf()->getKey("agua", 'INSTALLDIR');
	my $inserts	= [
		qq{* 20     * * *   root    MAILTO=""; $installdir/bin/scripts/checkBalancers.pl > /tmp/agua-loadbalancers.out}
];
	my $crontext = `crontab -l`;
	$crontext = `crontab -l` if $crontext =~ /No crontab for root/;

	#### REMOVE INSERTS IF ALREADY PRESENT
	foreach my $insert ( @$inserts )
	{
		my $temp = $insert;
		$temp =~ s/\*/\\*/g;
		$temp =~ s/\$/\$/g;
		$temp =~ s/\-/\\-/g;
		$temp =~ s/\//\\\//g;
		$crontext =~ s/$temp//msg;
	}

	#### ADD INSERTS TO BOTTOM OF CRON LIST
	$crontext =~ s/\s+$//;
	foreach my $insert ( @$inserts ) {	$crontext .= "\n$insert";	}
	$crontext .= "\n";

	`echo '$crontext' | crontab -`;
}

method _crontextFromFile ($crontab) {
	$crontab = "/etc/crontab" if not defined $crontab;
	$self->backupFile($crontab);
	my $temp = $/;
	$/ = undef;
	open(FILE, $crontab) or die "Can't open crontab: $crontab\n";
	my $crontext = <FILE>;
	close(FILE) or die "Can't close crontab: $crontab\n";
	$/ = $temp;

	return $crontext;
}

method _crontextToFile ($crontab, $crontext) {
	open(OUT, ">$crontab") or die "Can't open crontab: $crontab\n";
	print OUT $crontext;
	close(OUT) or die "Can't close crontab: $crontab\n";
}

=head2

SUBROUTINE         fixFstab

PURPOSE

	REMOVE A LINE ADDED TO /etc/fstab BY cloud-init THAT

	STOPS t1.micro INSTANCES FROM REBOOTING

=cut

method fixFstab {
print "Fixing /etc/fstab to allow micro instance to reboot successfully\n";

my $file = "/etc/fstab";
open(FILE, $file) or die "Agua::Configure::fixFstab    Can't open file: $file\n";
my @lines = <FILE>;
close(FILE) or die "Can't close file: $file\n";
for ( my $i = 0; $i < $#lines + 1; $i++ )
{
    my $line = $lines[$i];
    next if $line =~ /^#/;
    if ( $line =~ /comment=cloudconfig/ )
    {
        splice @lines, $i, 1;
        $i--;
    }
}
open(OUT, ">$file") or die "Agua::Configure::fixFstab    Can't open file: $file\n";
foreach my $line ( @lines ) {   print OUT $line;    }
close(OUT) or die "Can't close file: $file\n";
}

#### MYSQL
method mysql {
=head2

SUBROUTINE         mysql

PURPOSE

	1. SET MYSQL ROOT PASSWORD (OPTIONAL)

	2. LOAD THE AGUA DATABASE (BACKS UP EXISTING DATA)

	3. CREATE AGUA MYSQL USER

	4. CREATE TEST AGUA MYSQL USER

=cut

	$self->printMysqlWelcome();

    print qq{\n
Configuring MySQL. Please input values or accept the [default_value])

};

	#### CHECK TO RESET ROOTPASSWORD, OTHERWISE GET FROM CONF FILE
	print "\n**** SET MYSQL ROOT PASSWORD\n\n";
	$self->setMysqlRoot();

    #### SET DATABASE NAME
	print "\n**** SET DATABASE NAME\n\n";
    my $database        =   $self->setDatabase();

	#### RELOAD DATABASE
	return if not defined $self->reloadDatabase();

	#### OPTIONALLY RESET AGUA MYSQL USER AND PASSWORD
	print "\n**** SET AGUA LINUX USER\n\n";
	my ($user, $password) = $self->setAguaUser();

	#### CREATE TEST DATABASE
	print "\n**** CREATE TEST DATABASE\n\n";
	$self->createTestDb();

	#### OPTIONALLY RESET TEST AGUA MYSQL USER AND PASSWORD
	print "\n**** SET TEST USER\n\n";
	my ($testuser, $testpassword) = $self->setTestUser();

    #### PRINT CONFIRMATION THAT THE agua DATABASE HAS BEEN CREATED
	$self->printMysqlConfirmation($database, $user, $password);
}

method printMysqlWelcome {
		#### PRINT INFO
    print qq{\n
	The Agua configuration utility does the following:

	1. Set the root MySQL password (if not already set)

	2. Create a new Agua database (backs up existing data, loads data from dump file)

	3. Set the Agua MySQL user name and password

	4. Set the name and password for the Agua test MySQL user

\n};

	#### CHECK FOR QUIT
    print "\nExiting\n\n" and exit if not $self->yes("Do you want to continue (Y/N)?");
}

method printMysqlConfirmation ($database, $user, $password) {
	my $configfile = $self->configfile();
	my $logfile = $self->logfile();
	my $timestamp = $self->db()->timestamp();
	print qq{
*******************************************************
MySQL configuration completed.

Please make a note of your MySQL access credentials:

\tDatabase:\t$database
\tUsername:\t$user
\tPassword:\t$password

You can test this on the command line:

\tmysql -u $user -p$password
\tUSE $database
\tSHOW TABLES

Your updated configuration file is here:

\t$configfile

This transaction has been recorded in the log:

\t$logfile

$timestamp
*******************************************************\n};
}

method setDbObject ($database, $user, $password) {
	$self->logDebug("database", $database);

   #### CREATE DB OBJECT USING DBASE FACTORY
    my $db = Agua::DBaseFactory->new( 'MySQL',
        {
			database	=>	$database,
            user      	=>  $user,
            password  	=>  $password,
			logfile		=>	$self->logfile(),
			log		=>	2,
			printlog	=>	2
        }
    ) or die "Can't create database object to create database: $database. $!\n";

	$self->db($db);
}

method setAguaUser {
	my $database = $self->database();
	$self->logDebug("database not defined") and exit if not defined $database;

	#### SET DB OBJECT
	my $rootpassword = $self->_getRootPassword();
	$self->logError("rootpassword not defined") and return if not defined $rootpassword;
	$self->setDbObject($database, "root", $rootpassword) if not defined $self->db();

	#### GET CURRENT VALUES
    my $user		=   $self->user();
	$user 			=	$self->conf()->getKey("database", "USER") if not $user;
    my $password   	=   $self->password();
	$password		=	$self->conf()->getKey("database", "PASSWORD") if not $password;
	my $length 		= 	9;
	$password		=	$self->createRandomPassword($length) if not $password;

	#### Agua USER NAME
	$user = $self->_inputValue("Agua MySQL user name", $user);
    $self->logError("user not defined") if not defined $user;

    #### Agua USER PASSWORD
	$password = $self->_inputValue("Agua MySQL user password", $password);
    $self->logError("password not defined") if not defined $password;

	#### SET Agua USER AND PASSWORD
	$self->_createDbUser($database, $user, $password);

	#### UPDATE CONF FILE
	my $oldmemory = $self->conf()->memory();
	$self->conf()->memory(0);
	$self->logDebug("self->conf()->memory()", $self->conf()->memory());
	$self->conf()->setKey("database", "USER", $user);
	$self->conf()->setKey("database", "PASSWORD", $password);
	$self->conf()->memory($oldmemory);

	#### UPDATE SLOTS
    $self->user($user);
    $self->password($password);

	return $user, $password;
}

method setDatabase {
	print "\n";
	my $database = $self->database() || $self->conf()->getKey("database", "DATABASE");
	$database = $self->_inputValue("Agua MySQL database name", $database);
    $self->logError("database not defined") if not defined $database;

    $self->database($database);
	$self->conf()->setKey("database", "DATABASE", $database);

	return $database;
}

method setMysqlRoot {
	#### PROMPT TO SET ROOT MYSQL PASSWORD
	print "\n";
	my $resetroot = qq{Do you want to reset the MySQL root password (Y/N)?};

	my $rootpassword;
	if ( $self->yes($resetroot) ) {
		my $rootpassword = $self->_inputRootPassword();
		$self->logError("rootpassword not defined") and return if not defined $rootpassword;

		$self->_setRootPassword($rootpassword);
	}
	else {
		print "\nMySQL root password will not be changed.\n\n";
		my $rootpassword = $self->_inputRootPassword();
		$self->logError("rootpassword not defined") and return if not defined $rootpassword;
		$self->rootpassword($rootpassword);
	}
}

method _inputRootPassword {
#### MASK TYPING FOR PASSWORD INPUT
    ReadMode 2;
	print "\n";
	my $rootpassword = $self->_inputValue("Please input the current MySQL root password (Will not appear on screen)", undef);

    #### UNMASK TYPING
    ReadMode 0;
    $self->rootpassword($rootpassword);

	return $rootpassword;
}

method createRandomPassword ($length) {
	my $password = '';
	for ( my $i = 0; $i < $length; $i++ ) {
		my $random = int(rand(16)) + 1;
		my $hex = lc(sprintf("%01X", $random));
		$password .= "$hex";
	}
	return $password;
}

method _setRootPassword ($rootpassword) {
	#### RESTART MYSQL WITH  --skip-grant-tables

	print "Setting mysql root password...\n";
	$self->stopMysql();
	$self->killMysql();

	my $arch	=	$self->getArch();
	my $start = "sudo mysqld --skip-grant-tables &";
	$start = "sudo mysqld_safe --skip-grant-tables &" if $arch eq "centos";
	print "$start\n";
	system($start);
	sleep(5);
	print "Completed\n";

	#### SET root USER PASSWORD
	my $sqlfile = FindBin::Real::Bin() . "/../../conf/setRootPassword.sql";
	$self->logDebug("sqlfile", $sqlfile);
	my $create = qq{
UPDATE mysql.user SET Password=PASSWORD('$rootpassword') WHERE User='root';
FLUSH PRIVILEGES;
};
	$self->printToFile($sqlfile, $create);
	my $command = "mysql < $sqlfile";
	$self->logDebug("command", $command);

	print "$command\n";
	print `$command`;

	`rm -fr $sqlfile`;

	#### SET self->rootpassword
	$self->rootpassword($rootpassword);
}

method stopMysql {
	$self->logDebug("");
	my $mysql = $self->getMysql();
    my $command = "$mysql stop";
	print "Agua::Init::mountMysql    command: $command\n";
	print `$command`;
}

method getMysql {
	my $mysql = "/etc/init.d/mysqld";
	$mysql = "/etc/init.d/mysql" if not -f $mysql;

	return $mysql;
}

method killMysql {
#### KILL MYSQL IF RUNNING
	$self->logDebug("");
	my @lines = split "\n", `ps aux | egrep "^mysql"`;
	$self->logDebug("lines", \@lines);
	foreach my $line ( @lines ) {
		$self->logDebug("line", $line);
		my ($pid) = $line =~ /^mysql\s+(\d+)/;
		$self->logDebug("pid", $pid);
		my $command = "kill -9 $pid";
		$self->logDebug("command", $command);
		`$command`;
	}
}

method _getRootPassword {
	my $rootpassword = $self->rootpassword();
	if ( not $rootpassword ) {
		$rootpassword = $self->_inputRootPassword();
		$self->rootpassword($rootpassword);
	}

	return $rootpassword;
}

#### RELOAD DATABASE
method reloadDatabase {
	my $database = $self->database() || $self->conf()->getKey("database", "DATABASE");
	$self->logDebug("database", $database);
	$self->logDebug("database not defined") and exit if not defined $database;

	#### SET DB OBJECT
	my $rootpassword = $self->_getRootPassword();
	$self->logError("rootpassword not defined") and return if not defined $rootpassword;

	#### SET DB OBJECT
	$self->setDbObject("mysql", "root", $rootpassword);

	#### CHECK OVERWRITE
	my $overwrite = 1;
	if ( $self->db()->isDatabase($database) ) {
		$overwrite = $self->_checkOverwrite($database);
	}

	#### CREATE DATABASE
	$self->_createDb($database) if $overwrite;

	#### POPULATE DATABASE WITH DUMP FILE
	my $dumpfile	=	$self->_getDumpfile("agua", "agua");
	$self->_loadDumpfile($database, $dumpfile) if $overwrite;
}

method _checkOverwrite ($database) {
    my $rootuser       	=   $self->rootuser();
    my $rootpassword   	=   $self->rootpassword();

	my $warning = "Database '$database' exists already.\nPress 'Y' to overwrite it or 'N' to skip";
	return 0 if not $self->yes($warning);

	#### CREATE DUMPFILE OF AGUA DATABASE
	print "Doing dumpfile backup of current database: $database\n";
	my $dumpfile = $self->_dumpDb($database, $rootuser, $rootpassword, undef);

	#### DELETE DATABASE
	$self->db()->dropDatabase($database) or die "Can't drop database: $database. $!\n";

	$self->_printOverwriteReport($database, $dumpfile);

	return 1;
}

method _printOverwriteReport ($database, $dumpfile) {
	#### TIMESTAMP
	my $timestamp = $self->db()->timestamp();
	my $logfile = $self->logfile();
	my $report = qq{
*******************************************************
Successfully deleted database: $database

The tables and data in the existing database have been
saved here:

$dumpfile

This transaction has been recorded in the log:

\t$logfile

$timestamp
*******************************************************\n\n\n};
	print  $report;
	$self->logDebug("report: ", $report);
}

method _dropDatabase ($database) {
	$self->logDebug("database", $database);

	my $query = qq{DROP DATABASE $database};
	my $success = $self->db()->do($query);
	$self->logDebug("Drop database success", $success);
}

method _loadDumpfile ($database, $dumpfile) {
	$self->logDebug("database", $database);
	$self->logDebug("dumpfile", $dumpfile);

    my $rootpassword   	=   $self->rootpassword();
	my $command = "mysql -u root -p$rootpassword $database < $dumpfile";
	$self->logDebug("command", $command);
	print `$command`;
}

#### TEST DATABASE
method createTestDb {
	my $testdatabase = $self->conf()->getKey("database", "TESTDATABASE");
	$self->logDebug("testdatabase", $testdatabase);
	$self->logDebug("testdatabase not defined") and exit if not defined $testdatabase;

	#### SET DB OBJECT
	my $rootpassword = $self->_getRootPassword();
	$self->logError("rootpassword not defined") and return if not defined $rootpassword;

	#### SET DB OBJECT
	$self->setDbObject("mysql", "root", $rootpassword);

	#print "\nChecking to see if test database already exists\n";
	#print "\nTest database found\n" and return 1 if $self->db()->isDatabase($testdatabase);
	#print "\nTest database not found. Creating test database\n";

	#### CHECK OVERWRITE
	my $overwrite = 1;
	if ( $self->db()->isDatabase($testdatabase) ) {
		$overwrite = $self->_checkOverwrite($testdatabase);
	}

	if ( $overwrite ) {
		#### CREATE DATABASE
		$self->_createDb($testdatabase);

		#### POPULATE DATABASE WITH DUMP FILE
		my $dumpfile	=	$self->_getDumpfile("agua", "test");
		$self->_loadDumpfile($testdatabase, $dumpfile);
	}
}
#### TEST USER
method setTestUser {
	my $testdatabase = $self->testdatabase() || $self->conf()->getKey("database", "TESTDATABASE");
	$self->logDebug("testdatabase not defined") and exit if not defined $testdatabase;

	#### SET DB OBJECT
	my $rootpassword = $self->_getRootPassword();
	$self->logError("rootpassword not defined") and return if not defined $rootpassword;
	$self->setDbObject($testdatabase, "root", $rootpassword) if not defined $self->db();

	#### GET CURRENT VALUES
    my $testuser       	=   $self->testuser() || $self->conf()->getKey("database", "TESTUSER");
    my $testpassword   	=   $self->testpassword() || $self->conf()->getKey("database", "TESTPASSWORD");
	my $length 		= 9;
	$testpassword		=	$self->createRandomPassword($length) if not $testpassword;

#    #### TEST USER NAME
#	print "\n";
#	$testuser = $self->_inputValue("Test MySQL username", $testuser);

    #### TEST USER PASSWORD
	$testpassword = $self->_inputValue("User '$testuser' MySQL password", $testpassword);

	#### SET MYSQL USER AND PASSWORD
	$self->_createDbUser($testdatabase, $testuser, $testpassword);

	#### UPDATE CONF FILE
#	$self->conf()->setKey("database", "TESTUSER", $testuser);
	$self->conf()->setKey("database", "TESTPASSWORD", $testpassword);

	#### UPDATE SLOTS
    $self->testuser($testuser);
    $self->testpassword($testpassword);

	#### SET TEST DATABASE HANDLE
	$self->setDbh({
		database	=>	$testdatabase,
		dbuser		=>	$testuser,
		dbpassword	=>	$testpassword
	});

	#### ALLOW agua USER ACCESS TO TEST DATABASE
	my $user		=	$self->conf()->getKey("database", "USER");
	$self->grantAccess($testdatabase, $testuser);

	#### UPDATE TESTUSER PASSWORD IN TEST DATABASE
	$self->updateUserPassword($testuser, $testpassword);

	#### LOAD TEST USER DATA INTO TEST DATABASE
	$self->_loadUserData($testuser, $testdatabase, "test");

	#### RESET DATABASE
	my $database	=	$self->conf()->getKey("database", "DATABASE");
	$self->setDbh({
		database	=>	$database,
	});

	return $testuser, $testpassword;
}

method updateUserPassword ($username, $password) {
	if ( $self->db()->query("SELECT 1 FROM users WHERE username='$username'")) {
		my $query	=	"UPDATE users SET password='$password' WHERE username='$username'";
		$self->db()->do($query);
	}
	else {
		my $query	=	"INSERT INTO users VALUES('$username', '$password', '','','','', NOW())";
		$self->db()->do($query);
	}
}

#### DATABASE UTILS
method _createDb ($database) {
    my $rootpassword   	=   $self->rootpassword();
    my $user       		=   $self->user();
    my $password   		=   $self->password();
	print "Creating database: $database\n";

	#### CREATE DATABASE AND Agua USER AND PASSWORD
	my $sqlfile = FindBin::Real::Bin() . "/../sql/_createDb.sql";
    $self->logDebug("sqlfile", $sqlfile);
	my $create = qq{CREATE DATABASE $database;};
	$self->printToFile($sqlfile, $create);
	my $command = "mysql -u root -p$rootpassword < $sqlfile";
	$self->logDebug("$command");
	print `$command`;
	`rm -fr $sqlfile`;

	print "Created database: $database\n";
}

method _createDbUser ($database, $user, $password) {
    my $rootuser       	=   $self->rootuser();
    my $rootpassword   	=   $self->rootpassword();

	#### CREATE DATABASE AND Agua USER AND PASSWORD
	my $sqlfile = FindBin::Real::Bin() . "/../sql/_createDbUser.sql";
    $self->logDebug("sqlfile: $sqlfile");
	my $create = qq{
USE mysql;
GRANT SHOW DATABASES ON *.* TO '$user'\@'localhost' IDENTIFIED BY '$password';
GRANT ALL ON $database.* TO '$user'\@'localhost' IDENTIFIED BY '$password';
FLUSH PRIVILEGES;};
	$self->printToFile($sqlfile, $create);
	my $command = "mysql -u $rootuser -p$rootpassword < $sqlfile";
	$self->logDebug("$command");
	print `$command`;

	#### CLEAN UP
	`rm -fr $sqlfile`;
}

method grantAccess ($database, $user) {

	my $query = qq{GRANT ALL ON $database.* TO '$user'};
	$self->logDebug("query", $query);

	$self->db()->do($query);
}

method _getTimestamp ($database, $user, $password) {
	#### SET DB OBJECT
	$self->setDbObject($database, $user, $password) if not defined $self->db();

	my $timestamp = $self->db()->timestamp();
	$timestamp =~ s/\s+/-/g;
	return $timestamp;
}

method _dumpDb ($database, $user, $password, $dumpfile) {
	$self->logDebug("dumpfile", $dumpfile);

	#### PRINT DUMP COMMAND FILE
	my $timestamp = $self->_getTimestamp($database, $user, $password);
	$timestamp	=~ s/::/-/g;

	#### SET DEFAULT dumpfile
	$dumpfile = FindBin::Real::Bin() . "/../sql/dump/agua/$user.$timestamp.dump" if not defined $dumpfile;
	$self->logDebug("dumpfile", $dumpfile);

	#### CREATE DUMP DIR
	my ($dumpdir) = $dumpfile =~ /^(.+)\/[^\/]+$/;
	$self->logDebug("dumpdir", $dumpdir);
	`mkdir -p $dumpdir` if not -d $dumpdir;
	print "Agua::Configure::_dumpDb    Can't create dumpdir: $dumpdir\n" if not -d $dumpdir;

	#### SET DUMP COMMAND FILE
	my $cmdfile = "$dumpdir/$user.$timestamp.cmd";
	$self->printToFile($cmdfile, "#!/bin/sh\n\nmysqldump -u $user -p$password $database > $dumpfile\n");

	#### DUMP CONTENTS OF Agua DATABASE TO FILE
	`chmod 755 $cmdfile`;
	print `$cmdfile`;
	`rm -fr $cmdfile`;

	return $dumpfile;
}

#### GUEST USER
method guestUser {

print "\n\n\n";
print "*********************************************************************\n";
print "***************** CREATING guest USER LINUX ACCOUNT ******************\n";
print "\n\n";

	my $username 	= $self->conf()->getKey("database", "GUESTUSER");
	my $firstname 	= "";
	my $lastname 	= "";
	my $email 		= "guest\@trash.com";
	my $object 		= {
		username	=>	$username,
		password	=>	"",
		email		=>	$email,
		firstname	=>	$firstname,
		lastname	=>	$lastname
	};
    $self->logDebug("object", $object);

	#### REMOVE OLD AGUA guest LINUX ACCOUNT
	$self->_removeLinuxUser($object);

	#### ADD NEW AGUA guest LINUX ACCOUNT
	#### AND CREATE DIRECTORY IF NOT EXISTS
	$self->_addLinuxUser($object);

	#### SET guest USER MYSQL ACCOUNT
	$self->setGuestUser();

print "\n\n";
print "************    guest USER ACCOUNT SUCCESSFULLY CREATED    ***********\n";
print "*********************************************************************\n";
print "\n\n\n";

}

method setGuestUser {
	my $database = $self->database() || $self->conf()->getKey("database", "DATABASE");
	$self->logDebug("database not defined") and exit if not defined $database;

	#### SET DB OBJECT
	my $rootpassword = $self->_getRootPassword();
	$self->logError("rootpassword not defined") and return if not defined $rootpassword;
	$self->setDbObject($database, "root", $rootpassword) if not defined $self->db();

	#### GET CURRENT VALUES
    my $guestuser       	=   $self->conf()->getKey("database", "GUESTUSER");
    my $guestpassword   	=   $self->conf()->getKey("database", "GUESTPASSWORD");
	my $length 		= 9;
	$guestpassword		=	$self->createRandomPassword($length) if not $guestpassword;

    #### GUEST USER NAME
	print "\n";
	$guestuser = $self->_inputValue("Guest MySQL username", $guestuser);

    #### GUEST USER PASSWORD
	$guestpassword = $self->_inputValue("User '$guestuser' MySQL password", $guestpassword);

	#### SET MYSQL USER AND PASSWORD
	$self->_createDbUser($database, $guestuser, $guestpassword);

	#### UPDATE CONF FILE
	$self->conf()->setKey("database", "GUESTUSER", $guestuser);
	$self->conf()->setKey("database", "GUESTPASSWORD", $guestpassword);

	#### LOAD GUEST USER DATA INTO GUEST DATABASE
	$self->_loadUserData($guestuser, $database, "agua");

	#### CREATE FOLDERS FOR WORKFLOWS
	$self->_createFileDirs($guestuser, $database);

	return $guestuser, $guestpassword;
}

method _createFileDirs ($username, $database) {

	$self->setDbh({
		database	=>	$database
	});

	##### CREATE PROJECT DIRS
	#$self->_createProjectDirs($username);

	#### CREATE WORKFLOW DIRS
	$self->_createWorkflowDirs($username);
}

method _createProjectDirs ($username) {
	my $query	=	"SELECT * FROM project WHERE username='$username'";
	my $projects = $self->db()->queryhasharray($query);
	$self->logDebug("projects", $projects);

	my $userdir 	= 	$self->conf()->getKey("agua", 'USERDIR');
	my $homedir		=	"$userdir/$username";
	my $aguadir 	= 	$self->conf()->getKey("agua", 'AGUADIR');

	foreach my $entry ( @$projects ) {
		my $project		=	$entry->{name};
		$self->logDebug("project", $project);
		my $filepath	=	"$homedir/$aguadir/$project";
		$self->logDebug("filepath", $filepath);
		$self->logDebug("DOING mkdir -p $filepath") if not -d $filepath;
		`mkdir -p $filepath` if not -d $filepath;
	}
}

method _createWorkflowDirs ($username) {
	my $query	=	"SELECT * FROM workflow WHERE username='$username'";
	my $workflows = $self->db()->queryhasharray($query);
	$self->logDebug("workflows", $workflows);

	my $userdir 	= 	$self->conf()->getKey("agua", 'USERDIR');
	my $homedir		=	"$userdir/$username";
	my $aguadir 	= 	$self->conf()->getKey("agua", 'AGUADIR');

	foreach my $entry ( @$workflows ) {
		my $project		=	$entry->{project};
		my $workflow	=	$entry->{name};
		$self->logDebug("project", $project);
		$self->logDebug("workflow", $workflow);
		my $filepath	=	"$homedir/$aguadir/$project/$workflow";
		$self->logDebug("filepath", $filepath);
		`mkdir -p $filepath` if not -d $filepath;
	}
}

#### MISC UTILS
method getArch {
	my $arch = $self->arch();
    $self->logDebug("STORED arch", $arch) if defined $arch and $arch ne "";

	return $arch if defined $arch and $arch ne "";

	my $releasefile = "/etc/centos-release";
	return "centos" if -f $releasefile;

	$arch 	= 	"linux";
	my $command = "uname -a";
    my $output = `$command`;
	#$self->logDebug("output", $output);

    #### Linux ip-10-126-30-178 2.6.32-305-ec2 #9-Ubuntu SMP Thu Apr 15 08:05:38 UTC 2010 x86_64 GNU/Linux
    $arch	=	 "ubuntu" if $output =~ /ubuntu/i;
    #### Linux ip-10-127-158-202 2.6.21.7-2.fc8xen #1 SMP Fri Feb 15 12:34:28 EST 2008 x86_64 x86_64 x86_64 GNU/Linux
    $arch	=	 "centos" if $output =~ /fc\d+/;
    $arch	=	 "centos" if $output =~ /\.el\d+\./;
	$arch	=	 "debian" if $output =~ /debian/i;
	$arch	=	 "freebsd" if $output =~ /freebsd/i;
	$arch	=	 "osx" if $output =~ /darwin/i;

	$self->arch($arch);
    $self->logDebug("FINAL arch", $arch);

	return $arch;
}

method _inputValue ($message, $default) {
	$self->logError("message is not defined") if not defined $message;
	$default = '' if not defined $default;
	print "$message [$default]: ";

	my $input = '';
    while ( $input =~ /^\s*$/ )
    {
        $input = <STDIN>;
        $input =~ s/\s+//g;

		$default = $input if $input;
		print "\n" and return $default if $default;

        print "\n$message [$default]: ";
    }
}

method _inputHiddenValue ($message, $default) {
	$self->logDebug("Agua::Configure::inputHiddeValue(message, default)");
	$self->logDebug("message", $message);
	$self->logDebug("default", $default);

	$self->logError("Agua::Configure::_inputHiddenValue    message is not defined") if not defined $message;
	$default = '' if not defined $default;
	print "$message []: ";

	my $input = '';
    while ( $input =~ /^\s*$/ )
    {
        $input = <STDIN>;
        $input =~ s/\s+//g;
		$default = $input if $input;
		print "\n" and return $default if $default;

        print "\n$message []: ";
    }
}

method yes ($message) {
#### PROMPT THE USER TO ENTER 'Y' OR 'N'
	return if not defined $message;
	print "$message: ";
    my $max_times = 10;

	$/ = "\n";
	my $input = <STDIN>;
	my $counter = 0;
	while ( $input !~ /^Y$/i and $input !~ /^N$/i )
	{
		if ( $counter > $max_times ) { print "Exceeded 10 tries. Exiting...\n"; }
		print "$message: ";
		$input = <STDIN>;
		$counter++;
	}

	if ( $input =~ /^N$/i )	{	return 0;	}
	else {	return 1;	}
}

method backupFile ($filename) {
	my $counter = 1;
	my $backupfile = "$filename.$counter";
	while ( -f $backupfile )
	{
		$counter++;
		$backupfile = "$filename.$counter";
	}
	`cp $filename $backupfile`;

	$self->logError("Could not create backupfile: $backupfile") if not -f $backupfile;
	print "backupfile created: $backupfile\n";
}

method printToFile ($file, $text) {
	$self->logDebug("file", $file);
	#### PRINT TO FILE
	open(OUT, ">$file") or $self->logCaller() and $self->logCritical("Can't open file: $file") and exit;
	print OUT $text;
	close(OUT) or $self->logCaller() and $self->logCritical("Can't close file: $file") and exit;
}

=head2 APPS

    SUBROUTINE      apps

    PURPOSE

        CONFIGURE APPLICATIONS INTERACTIVELY:

            1. SET THE PATHS TO EXISTING APPLICATION ENTRIES

            2. ADD NEW APPLICATIONS

			3. DELETE APPLICATIONS

=cut

method apps {

	### PRINT APPLICATION PATHS
    my $apps = $self->conf()->get("apps");

    my $message = "You can set application paths or use the default paths. Do you want to use the default paths (Y/N)?";
	print "$message\n";
    return if yes($message);

    my $continue;
    while ( not defined $continue )
    {
        my $counter = 1;
        foreach my $app ( @$apps )
        {
            my @keys = keys %$app;
            my $key = $keys[0];
            print "$counter $key\t:\t$app->{$key}\n";
            $counter++;
        }

        $continue = input("Type application number or 'Q' for quit");

        if ( $continue !~ /^\d+$/ and $continue !~ /^q$/i )
        {
            print "\n**** Invalid input: $continue\n\n";
            $continue = undef;
            next;
        }

        ### CONTINUE MUST BE A NUMBER OR 'Q'
        if ( $continue =~ /^q$/i )
        {
            last;
        }
        else
        {
            my $app = $$apps[$continue - 1];
            if ( not defined $app )
            {
                print "No application entry for index: $continue\n";
            }
            else
            {
                my @keys = keys %$app;
                my $key = $keys[0];

                my $value = input("Enter path to $key [$app->{$key}]");
                $$apps[$continue - 1] = { $key => $value };
            }

            $continue = undef;
        }
    }
}

method getKey {
	my $key		=	$self->key();
	$self->logError("Agua::Configure::_getKey    key not defined (--key)") if not $key;
	my $value = $self->_getKey();
	print "$value\n";
}

method _getKey {
	my $key		=	$self->key();
	print "Agua::Configure::_getKey    key: $key\n";

	return $self->conf()->getValue($key);
}

}


text: This sample demonstrates how to use Orleans Streams with Azure Event Hubs and implicit subscribers.

redpajama_set_name: RedPajamaGithub


text:
package com.zheng.upms.dao.model;

import java.io.Serializable;

public class UpmsRole implements Serializable {
    /**
     * 编号
     *
     * @mbg.generated
     */
    private Integer roleId;

    /**
     * 角色名称
     *
     * @mbg.generated
     */
    private String name;

    /**
     * 角色标题
     *
     * @mbg.generated
     */
    private String title;

    /**
     * 角色描述
     *
     * @mbg.generated
     */
    private String description;

    /**
     * 创建时间
     *
     * @mbg.generated
     */
    private Long ctime;

    /**
     * 排序
     *
     * @mbg.generated
     */
    private Long orders;

    private static final long serialVersionUID = 1L;

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Long getCtime() {
        return ctime;
    }

    public void setCtime(Long ctime) {
        this.ctime = ctime;
    }

    public Long getOrders() {
        return orders;
    }

    public void setOrders(Long orders) {
        this.orders = orders;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", roleId=").append(roleId);
        sb.append(", name=").append(name);
        sb.append(", title=").append(title);
        sb.append(", description=").append(description);
        sb.append(", ctime=").append(ctime);
        sb.append(", orders=").append(orders);
        sb.append("]");
        return sb.toString();
    }

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        UpmsRole other = (UpmsRole) that;
        return (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId()))
            && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
            && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))
            && (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription()))
            && (this.getCtime() == null ? other.getCtime() == null : this.getCtime().equals(other.getCtime()))
            && (this.getOrders() == null ? other.getOrders() == null : this.getOrders().equals(other.getOrders()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode());
        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
        result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode());
        result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode());
        result = prime * result + ((getCtime() == null) ? 0 : getCtime().hashCode());
        result = prime * result + ((getOrders() == null) ? 0 : getOrders().hashCode());
        return result;
    }
}


text:
"use strict";

var winHeight = $(window).height();
var headHeight = $("#outerhead").height();
var yScroll = 0;
var check = 0;
var checkr = 0;
var width = $("#center-column").width();

$(window).scroll(function () {
    yScroll = $(this).scrollTop();
    console.log(yScroll);
    parallax();
});

function parallax() {
    if ($(window).width() > 650) {
        if (yScroll > 120) {
            $("#content-inside").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 730) {
            $("#exampledec").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 960) {
            $("#examplebin").css({
                '-animation': 'fadein 3s forwards'
            });
        }

        if (yScroll > 1260) {
            $("#hidetest").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 1740) {
            $("#testbinOneTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 1940) {
            $("#testbinTwoTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2040) {
            $("#testbinThreeTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2240) {
            $("#testbinFourTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2340) {
            $("#testbinFiveTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2970) {
            $("#newcolumn").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 3280) {
            $("#bitsbyte").css({
                'animation': 'fadein 3s forwards',
            });
        }
        //ASCII head changes height from here
        if (yScroll > 3805) {
            $("#ascitable-div").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 5020 && checkr === 0 || yScroll > 4290 && checkr === 1) {
            $("#equation").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 5490 && checkr === 0 || yScroll > 4790 && checkr === 1) {
            $("#memoryCalc").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 5730 && checkr === 0 || yScroll > 5030 && checkr === 1) {
            $("#memequal").css({
                'animation': 'fadein 3s forwards',
            });
        }
    } else {
        if (yScroll > 170) {
            $("#content-inside").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 1010) {
            $("#exampledec").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 1320) {
            $("#examplebin").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 1560) {
            $("#hidetest").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2240) {
            $("#testbinOneTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2340) {
            $("#testbinTwoTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2510) {
            $("#testbinThreeTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2610) {
            $("#testbinFourTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 2810) {
            $("#testbinFiveTable").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 3210) {
            $("#newcolumn").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 3510) {
            $("#bitsbyte").css({
                'animation': 'fadein 3s forwards',
            });
        }
        //ASCII head changes height from here
        if (yScroll > 4170) {
            $("#ascitable-div").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 6110 && checkr === 0 || yScroll > 5210 && checkr === 1) {
            $("#equation").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 6810 && checkr === 0 || yScroll > 5910 && checkr === 1) {
            $("#memoryCalc").css({
                'animation': 'fadein 3s forwards',
            });
        }

        if (yScroll > 7310 && checkr === 0 || yScroll > 6370 && checkr === 1) {
            $("#memequal").css({
                'animation': 'fadein 3s forwards',
            });
        }
    }
}

$(document).ready(function () {

    width = $("#center-column").width();
    //for the first time
    generateRandomNumber();

    //Permanent storage of Highest Streak
    if (localStorage.getItem("High Score") !== null) {
        $("#highScore").text(localStorage.getItem("High Score"));
        var highestStreak = localStorage.getItem("High Score");
    } else {
        $("#highScore").text('0');
        highestStreak = 0;
    }

    var binaryAdd = [];
    var answerCheck = 0;
    var streak = 0;
    var motivation = ['Keep going! You can do it!', "Keep going! You'll get it next time!", "No worries! Get it next time!"];

    $('button').click(function () {
        answerCheck = 1;
        correctOrWrong();
    });

    function correctOrWrong() {
        var userAnswer = 0;

        binaryAdd.map(function (num) {
            var nums = parseInt(num);
            userAnswer = userAnswer + nums;
            return userAnswer;
        });

        var answer = parseInt($('#thenumber').text());

        if (userAnswer !== answer) {
            var random = motivation[Math.floor(Math.random() * motivation.length)];
            $("#webApp-inside").prepend('
 Incorrect. ' + random + '
').children('#correctandwrong').hide().fadeIn('600');
            setTimeout(function () {
                $("#correctandwrong").remove();
                console.log("fff");
            }, 1500);
            streak = 0;
            $('#streaknum').text('0');
        } else {
            $("#webApp-inside").prepend('
 Correct! Keep going!
').children('#correctandwrong').hide().fadeIn('600');
            setTimeout(function () {
                $("#correctandwrong").remove();
            }, 1000);
            streak += 1;
            $('#streaknum').text(streak);
        }

        if (streak > highestStreak) {
            localStorage.setItem('High Score', streak);
            $("#highScore").text(localStorage.getItem("High Score"));
        }

        nukeIt();
    }

    function nukeIt() {
        binaryAdd = [];
        $('#cards').children().css('background-color', '#000000');
        $('#cards').children().children().text('0');
        generateRandomNumber();
        answerCheck = 0;
    }

    function generateRandomNumber() {
        var newNum = Math.floor(1 + Math.random() * 255);
        $('#thenumber').text(newNum);
    }

    $('#cards').children().click(function () {
        if (answerCheck === 0) {
            var index = $(this).index() + 1;
            if ($(this).children().text() === '0') {
                $(this).css('background-color', '#72EA30');
                binaryAdd.push($("#values :nth-child(" + index + ')').children().text());
                $(this).children().text('1');
            } else {
                $(this).css('background-color', '#000000');
                $(this).children().text('0');
                for (i = 0, j = binaryAdd.length; i < j; i++) {
                    if (binaryAdd[i] === $("#values :nth-child(" + index + ')').children().text()) {
                        binaryAdd.splice(i, 1);
                    }
                }
            }
        }
    });

    asciitable();

    $("#hidetest").one('click', function () {
        $(this).css('cursor', 'default');
        $("#hidetest th:nth-child(2)").fadeOut('200', function () {
            $("#hidetest th:nth-child(2)").text('1').fadeIn(300);
        });
    });
    $("#testbinOneTable").one('click', function () {
        $(this).css('cursor', 'default');
        $("#testbinOneTable th:nth-child(2), #testbinOneTable th:nth-child(3)").fadeOut('200', function () {
            $(this).text('1').fadeIn(300);
        });
    });
    $("#testbinTwoTable").one('click', function () {
        $(this).css('cursor', 'default');
        $("#testbinTwoTable th:nth-child(1)").fadeOut('200', function () {
            $(this).text('1').fadeIn(300);
        });
    });
    $("#testbinThreeTable").one('click', function () {
        $(this).css('cursor', 'default');
        $("#testbinThreeTable th:nth-child(1), #testbinThreeTable th:nth-child(3)").fadeOut('200', function () {
            $(this).text('1').fadeIn(300);
        });
    });
    $("#testbinFourTable").one('click', function () {
        $(this).css('cursor', 'default');
        $("#testbinFourTable th:nth-child(1), #testbinFourTable th:nth-child(2) ").fadeOut('200', function () {
            $(this).text('1').fadeIn(300);
        });
    });
    $("#testbinFiveTable").one('click', function () {
        $(this).css('cursor', 'default');
        $("#testbinFiveTable th:nth-child(1), #testbinFiveTable th:nth-child(2), #testbinFiveTable th:nth-child(3)").fadeOut('200', function () {
            $(this).text('1').fadeIn(300);
        });
    });

    var once = 0;
    setInterval(ratio, 100);

    function ratio() {
        //For the first time
        if (once === 0) {
            var cHeight = Math.round(width / 16 * 9);
            $("iframe").attr('height', cHeight);
            once = 1;
        }
        if (width != $("#center-column").width()) {
            cHeight = Math.round(width / 16 * 9);
            $("iframe").attr('height', cHeight);
            console.log("cmon " + width);
            width = $("#center-column").width();
        } else if (width === 680) {
            //This is the max width, no need to change the iframe
            $("iframe").attr('height', '383');
        }
    }

    function asciitable() {
        $("#ascii-head").click(function () {
            if (checkr === 0) {
                checkr = 1;
                $("#ascii-table-one,#ascii-table-two").hide('fast');
            } else {
                checkr = 0;
                $("#ascii-table-one,#ascii-table-two").show('fast');
            }
        });
    }

    $("#last-second-inside p:nth-child(3)").one('click', function () {
        $(this).css('cursor', 'default');
        var str = "Vg'f fvzcyr, lbh jvyy whfg nqq nabgure pbyhza nsgre sbhe'f cynpr naq gung pbyhza jvyy unir gur cynpr inyhr bs rvtug'f.";
        var strArr = str.split('');
        var decodedArr = [];
        var increaseNum = 0;
        descramble();

        function descramble() {
            var num = str[increaseNum++];
            var currentLetter = num.charCodeAt();
            if (currentLetter >= 65 && currentLetter <= 90 || currentLetter >= 97 && currentLetter <= 122) {
                if (currentLetter >= 78 && currentLetter <= 90 || currentLetter >= 110 && currentLetter >= 97) {
                    decodedArr.push(String.fromCharCode(currentLetter - 13));
                } else {
                    decodedArr.push(String.fromCharCode(currentLetter + 13));
                }
            } else {
                decodedArr.push(num);
            }
            var sliced = str.slice(increaseNum + 1, str.length - 1);
            $("#last-second-inside p:nth-child(3)").text(decodedArr.join('') + sliced);
            if (increaseNum < str.length) {
                setTimeout(descramble, 70);
            }
        }
    });

    $("#questions-first-inside p:nth-child(3)").one('click', function () {
        $(this).css('cursor', 'default');
        var str = "Gur uneq qevir unf 1000TO nf nqiregvfrq ohg pbzchgre pnyhyngrf vg va gur cbjre bs 2 . Fb, 1000TO pbairegrq vagb Olgrf vf 1r+12(1 gura 12 mrebf nsgre gung) naq ol qvivqvat vg ol gur ynetrfg cbjre bs 2 gung pna svg va 1000TO juvpu vf 1024 ^3 be 2^ 30 juvpu erfhyg va gur nafjre 931TO.";
        var strArr = str.split('');
        var decodedArr = [];
        var increaseNum = 0;
        descramble();

        function descramble() {
            var num = str[increaseNum++];
            var currentLetter = num.charCodeAt();
            if (currentLetter >= 65 && currentLetter <= 90 || currentLetter >= 97 && currentLetter <= 122) {
                if (currentLetter >= 78 && currentLetter <= 90 || currentLetter >= 110 && currentLetter >= 97) {
                    decodedArr.push(String.fromCharCode(currentLetter - 13));
                } else {
                    decodedArr.push(String.fromCharCode(currentLetter + 13));
                }
            } else {
                decodedArr.push(num);
            }
            var sliced = str.slice(increaseNum + 1, str.length - 1);
            $("#questions-first-inside p:nth-child(3)").text(decodedArr.join('') + sliced);
            if (increaseNum < str.length) {
                setTimeout(descramble, 50);
            }
        }
    });
});


text:
import BoutEvents from "./bout-events";
import Bout from "./bout";

/**
 * Abstract representation of bouts.
 */
export default class Bouts {

  /**
   * Constructor.
   *
   * @param  {Tenant} tenant The tenant instance.
   */
  constructor(tenant) {

    /**
     * The tenant.
     * @type {Tenant}
     */
    this.tenant = tenant;
  }

  /**
   * Provides access to bouts events.
   *
   * @return {BoutEvents}
   */
  events() {
    return new BoutEvents(this.tenant);
  }

  /**
   * Retrieve a bout object to perform operations on it.
   *
   * @param  {String} id        The id of the bout.
   * @return {Bout}
   */
  bout(id) {
    return new Bout(this.tenant, id);
  }

}


text:
package doctor

import (
	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/log"
)

func checkUserType(logger log.Logger, autofix bool) error {
	count, err := models.CountWrongUserType()
	if err != nil {
		logger.Critical("Error: %v whilst counting wrong user types")
		return err
	}
	if count > 0 {
		if autofix {
			if count, err = models.FixWrongUserType(); err != nil {
				logger.Critical("Error: %v whilst fixing wrong user types")
				return err
			}
			logger.Info("%d users with wrong type fixed", count)
		} else {
			logger.Warn("%d users with wrong type exist", count)
		}
	}
	return nil
}

func init() {
	Register(&Check{
		Title:     "Check if user with wrong type exist",
		Name:      "check-user-type",
		IsDefault: true,
		Run:       checkUserType,
		Priority:  3,
	})
}


text:
package pl.zankowski.iextrading4j.client.rest.request.stocks;

import org.junit.jupiter.api.Test;
import pl.zankowski.iextrading4j.api.stocks.VenueVolume;
import pl.zankowski.iextrading4j.client.rest.manager.MethodType;
import pl.zankowski.iextrading4j.client.rest.manager.RestRequest;

import jakarta.ws.rs.core.GenericType;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

class VenueVolumeRequestBuilderTest {

    @Test
    void shouldSuccessfullyCreateRequest() {
        final String symbol = "IBM";

        final RestRequest<List<VenueVolume>> request = new VenueVolumeRequestBuilder()
                .withSymbol(symbol)
                .build();

        assertThat(request.getMethodType()).isEqualTo(MethodType.GET);
        assertThat(request.getPath()).isEqualTo("/stock/{symbol}/volume-by-venue");
        assertThat(request.getResponseType()).isEqualTo(new GenericType<List<VenueVolume>>() {});
        assertThat(request.getPathParams()).containsExactly(entry("symbol", symbol));
        assertThat(request.getQueryParams()).isEmpty();
    }

}


text:
@interface UserLoginViewController ()

@end

@implementation UserLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self prepareUI];
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    // Log user behaviour
    [self.analyticsManager logScreen:kAnalyticsManagerScreenUserLogin];
}

#pragma mark - Protected -

- (void)commonInit {

    [super commonInit];

    // ...
}

- (void)prepareUI {

    [super prepareUI];

    self.title = GMLocalizedString(kUserLoginViewControllerTitle);
    _subTitleLabel.text = GMLocalizedString(kUserLoginViewControllerSubTitle);
    _orLabel.text = GMLocalizedString(kUserLoginViewControllerLoginOrLabel);
    [_loginButton setTitle:GMLocalizedString(kUserLoginViewControllerLoginButtonKey) forState:UIControlStateNormal];
    [_signUpButton setTitle:GMLocalizedString(kUserLoginViewControllerLoginSignUpButtonKey) forState:UIControlStateNormal];

    [self adjustScrollVieWidthToFitScreen];
    [self setupTextFields];
}

- (void)renderUI {

    [super renderUI];

    // ...
}

- (void)loadModel {

    [super loadModel];

    // ...
}

- (void)updateModel {

    UserObject *user = [[UserObject alloc] init];
    user.email = _emailTextField.text;
    user.password = _passwordTextField.text;

    [_model updateModelWithData:user];
}

#pragma mark Language change handling

- (void)notificationLocalizationHasChanged {

    [self prepareUI];
}

#pragma mark - Public -

- (void)clearTextFields {

    [_model clearData];

    _emailTextField.text = nil;
    _passwordTextField.text = nil;

    [self.keyboardControls.activeField resignFirstResponder];
}

#pragma mark IBActions

- (IBAction)loginPressed:(id)sender {

    [self updateModel];

    NSError *validationError = [_model validateData];

    if (validationError) {

        // Mark required but empty fields in red
        [self applyStyleForMissingRequiredFields];

        DDLogDebug(@"SignUpPressedWithWrongData");

        [self.messageBarManager showMessageWithTitle:@"" description:validationError.localizedDescription type:MessageBarMessageTypeError duration:kMessageBarManagerMessageDuration];

    } else {

        // Reset previous warnings from fields
        [self resetStyleForMissingRequiredFields];

        __weak typeof(self) weakSelf = self;
        [weakSelf showScreenActivityIndicator];

        // Do login
        [_model login:^(BOOL success, id result, NSError *error){

            [weakSelf hideScreenActivityIndicator];

            if (success) {

                DDLogDebug(@"UserLoginSuccess");

                [weakSelf clearTextFields];
                [_delegate didFinishLogin];

            } else {

                DDLogDebug(@"UserLoginFail: %@", error.localizedDescription);
            }
        }];
    }
}

- (IBAction)signUpPressed:(id)sender {

    if ([_delegate respondsToSelector:@selector(didPressSignUp)]) {

        [_delegate didPressSignUp];
    }
}

- (IBAction)resetPasswordPressed:(id)sender {

    if ([_delegate respondsToSelector:@selector(didPressForgotPasswordWithEmail:)]) {

    // TODO.. pass email
        [_delegate didPressForgotPasswordWithEmail:nil];
    }
}

#pragma mark - KeyboardControlDelegate -

- (void)didPressGo {

    [self loginPressed:nil];
}

#pragma mark - Private -

// Add toolbar with previous and next buttons for navigating between input fields
- (void)setupTextFields {

    // Add placeholders
    _emailTextField.placeholder = GMLocalizedString(kUserLoginViewControllerLoginUsernameKey);
    _passwordTextField.placeholder = GMLocalizedString(kUserLoginViewControllerLoginPasswordKey);

    // Set required fields
    _emailTextField.isRequired = YES;
    _passwordTextField.isRequired = YES;

    // Apply style
    _emailTextField.position = kTextFieldPositionIsFirst;
    _passwordTextField.position = kTextFieldPositionIsLast;

    // Setup keyboard controls
    NSArray *textFields = @[_emailTextField, _passwordTextField];
    [self setTextFieldsForKeyboard:textFields];
}

@end


text:
/**
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the latest version of the GNU Lesser General
 * Public License as published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program (LICENSE.txt); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.jamwiki.parser.jflex;

import java.util.Map;
import org.jamwiki.parser.ParserException;

/**
 * Interface for custom parser tags.  Note that as of JAMWiki 1.1 this
 * interface is still under development, so anyone interested in building
 * their own custom tags should be aware that this is NOT a stable API.
 *
 * See the /WEB-INF/classes/jamwiki-configuration-1.3.xml for
 * configuration - any custom parser tag must currently be identified in
 * that file in order for it to be used by the parser.
 */
public interface JFlexCustomTagItem {

	/**
	 * Initialize the tag with any key-value params passed in from the configuration.
	 * This method will be called immediately after the tag is instantiated.
	 */
	public void initParams(Map<String, String> initParams);

	/**
	 * Return the tag name.  If the tag is "<custom>" then the tag name is "custom".
	 */
	public String getTagName();

	/**
	 * Set the tag name.  If the tag is "<custom>" then the tag name is "custom".
	 */
	public void setTagName(String tagName);

	/**
	 * Parse a custom tag of the form <custom attribute="value">content</custom>
	 * into wiki text.  Note that the custom tag parser runs after the template
	 * parser, so wiki text generated by this method cannot include templates,
	 * signatures, or other wiki text that would have already been parsed earlier
	 * in the parser cycle.
	 *
	 * @param lexer A reference to the current lexer instance.
	 * @param attributes A map of key-value pairs representing all of the tag's
	 *  attributes.  Note that if the same key is specified more than once then
	 *  only the final occurrence will be included in the attribute map.
	 * @param content The tag's content, or null if the tag has
	 *  no body content.
	 * @return Wiki text representing the parsed tag output.  This output may be
	 *  further parsed into HTML by later parser iterations.  Note that if the
	 *  custom tag returns HTML then that HTML may not render as expected
	 *  depending on whether or not the wiki is configured to allow HTML, so
	 *  output should always be as wiki text.
	 * @throws ParserException Thrown if any error occurs during parsing.
	 */
	public String parse(JFlexLexer lexer, Map<String, String> attributes, String content) throws ParserException;
}


text:
To build & serve locally, do `jekyll serve`.

_Constructed using [this foundation](https://github.com/aigarsdz/brume)_


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  LoadComPortList
  cRegAccess

  LoadRegDeviceDetails
  cRegAccess

  LoadRegDeviceList
  cRegAccess

  Lock
  cMutex

Searching...

No Matches


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>All Classes (rdfutils 1.0 API)</title>
<meta name="date" content="2015-04-13">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

AutocompleteLengthException

Config

ConfigException

CsvExistanceException

CsvLabelImportException

CsvLanguageException

Logging

NoInputException

RDF

RdfException

ResourceNotAvailableException

SesameConnect

SesameSparqlException

UniqueIdentifierException


text:
package org.chocosolver.solver.variables;

import org.chocosolver.choco.checker.DomainBuilder;
import org.chocosolver.solver.Cause;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.IntConstraintFactory;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.search.strategy.IntStrategyFactory;
import org.chocosolver.util.iterators.DisposableRangeIterator;
import org.chocosolver.util.iterators.DisposableValueIterator;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Random;

/**
 * <br/>
 *
 * @author Charles Prud'homme
 * @since 23/08/11
 */
public class ViewMinusTest {

    @Test(groups = "1s")
    public void test1() {
        Solver solver = new Solver();

        IntVar X = VariableFactory.enumerated("X", 1, 10, solver);
        IntVar Y = VariableFactory.minus(X);

        try {
			if(!solver.getSettings().enableViews())
				solver.propagate();
            Assert.assertFalse(Y.isInstantiated());
            Assert.assertEquals(Y.getLB(), -10);
            Assert.assertEquals(Y.getUB(), -1);
            Assert.assertTrue(Y.contains(-5));
            Assert.assertEquals(Y.nextValue(-11), -10);
            Assert.assertEquals(Y.nextValue(-5), -4);
            Assert.assertEquals(Y.nextValue(-1), Integer.MAX_VALUE);
            Assert.assertEquals(Y.previousValue(0), -1);
            Assert.assertEquals(Y.previousValue(-4), -5);
            Assert.assertEquals(Y.previousValue(-10), Integer.MIN_VALUE);

            Y.updateLowerBound(-9, Cause.Null);
			if(!solver.getSettings().enableViews())
				solver.propagate();
            Assert.assertEquals(Y.getLB(), -9);
            Assert.assertEquals(X.getUB(), 9);

            Y.updateUpperBound(-2, Cause.Null);
			if(!solver.getSettings().enableViews())
				solver.propagate();
            Assert.assertEquals(Y.getUB(), -2);
            Assert.assertEquals(X.getLB(), 2);

            Y.removeValue(-4, Cause.Null);
			if(!solver.getSettings().enableViews())
				solver.propagate();
            Assert.assertFalse(Y.contains(-4));
            Assert.assertFalse(X.contains(4));

            Y.removeInterval(-8, -6, Cause.Null);
			if(!solver.getSettings().enableViews())
				solver.propagate();
            Assert.assertFalse(Y.contains(-8));
            Assert.assertFalse(Y.contains(-7));
            Assert.assertFalse(Y.contains(-6));
            Assert.assertFalse(X.contains(6));
            Assert.assertFalse(X.contains(7));
            Assert.assertFalse(X.contains(8));

            Assert.assertEquals(X.getDomainSize(), 4);
            Assert.assertEquals(Y.getDomainSize(), 4);

            Y.instantiateTo(-5, Cause.Null);
			if(!solver.getSettings().enableViews())
				solver.propagate();
            Assert.assertTrue(X.isInstantiated());
            Assert.assertTrue(Y.isInstantiated());
            Assert.assertEquals(X.getValue(), 5);
            Assert.assertEquals(Y.getValue(), -5);

        } catch (ContradictionException ignored) {

        }
    }

    @Test(groups = "1s")
    public void test2() {
        Random random = new Random();
        for (int seed = 0; seed < 2000; seed++) {
            random.setSeed(seed);
            Solver ref = new Solver();
            {
                IntVar[] xs = new IntVar[2];
                xs[0] = VariableFactory.bounded("x", 1, 15, ref);
                xs[1] = VariableFactory.bounded("y", -15, -1, ref);
                ref.post(IntConstraintFactory.sum(xs, VariableFactory.fixed(0, ref)));
                ref.set(IntStrategyFactory.random_bound(xs, seed));
            }
            Solver solver = new Solver();
            {
                IntVar[] xs = new IntVar[2];
                xs[0] = VariableFactory.bounded("x", 1, 15, solver);
                xs[1] = VariableFactory.minus(xs[0]);
                solver.post(IntConstraintFactory.sum(xs, VariableFactory.fixed(0, solver)));
                solver.set(IntStrategyFactory.random_bound(xs, seed));
            }
            ref.findAllSolutions();
            solver.findAllSolutions();
            Assert.assertEquals(solver.getMeasures().getSolutionCount(), ref.getMeasures().getSolutionCount());

        }
    }

    @Test(groups = "1s")
    public void test3() {
        Random random = new Random();
        for (int seed = 0; seed < 2000; seed++) {
            random.setSeed(seed);
            Solver ref = new Solver();
            {
                IntVar[] xs = new IntVar[2];
                xs[0] = VariableFactory.enumerated("x", 1, 15, ref);
                xs[1] = VariableFactory.enumerated("y", -15, -1, ref);
                ref.post(IntConstraintFactory.sum(xs, VariableFactory.fixed(0, ref)));
                ref.set(IntStrategyFactory.random_value(xs, seed));
            }
            Solver solver = new Solver();
            {
                IntVar[] xs = new IntVar[2];
                xs[0] = VariableFactory.enumerated("x", 1, 15, solver);
                xs[1] = VariableFactory.minus(xs[0]);
                solver.post(IntConstraintFactory.sum(xs, VariableFactory.fixed(0, solver)));
                solver.set(IntStrategyFactory.random_value(xs, seed));
            }
            ref.findAllSolutions();
            solver.findAllSolutions();
            Assert.assertEquals(solver.getMeasures().getSolutionCount(), ref.getMeasures().getSolutionCount());

        }
    }

    @Test(groups = "1s")
    public void testIt1() {
        Random random = new Random();
        for (int seed = 0; seed < 200; seed++) {
            random.setSeed(seed);
            Solver solver = new Solver();
            int[][] domains = DomainBuilder.buildFullDomains(1, -5, 5, random, random.nextDouble(), random.nextBoolean());
            IntVar o = VariableFactory.bounded("o", domains[0][0], domains[0][domains[0].length - 1], solver);
            IntVar v = VariableFactory.minus(o);
            DisposableValueIterator vit = v.getValueIterator(true);
            while (vit.hasNext()) {
                Assert.assertTrue(o.contains(-vit.next()));
            }
            vit.dispose();
            vit = v.getValueIterator(false);
            while (vit.hasPrevious()) {
                Assert.assertTrue(o.contains(-vit.previous()));
            }
            vit.dispose();
            DisposableRangeIterator rit = v.getRangeIterator(true);
            while (rit.hasNext()) {
                Assert.assertTrue(o.contains(-rit.min()));
                Assert.assertTrue(o.contains(-rit.max()));
                rit.next();
            }
            rit = v.getRangeIterator(false);
            while (rit.hasPrevious()) {
                Assert.assertTrue(o.contains(-rit.min()));
                Assert.assertTrue(o.contains(-rit.max()));
                rit.previous();
            }
        }
    }

    @Test(groups = "1s")
    public void testIt2() {
        Random random = new Random();
        for (int seed = 0; seed < 200; seed++) {
            random.setSeed(seed);
            Solver solver = new Solver();
            int[][] domains = DomainBuilder.buildFullDomains(1, -5, 5, random, random.nextDouble(), random.nextBoolean());
            IntVar o = VariableFactory.enumerated("o", domains[0], solver);
            IntVar v = VariableFactory.minus(o);
			if(!solver.getSettings().enableViews()){
				try {
					solver.propagate();
				}catch (Exception e){
					e.printStackTrace();
					throw new UnsupportedOperationException();
				}
			}
            DisposableValueIterator vit = v.getValueIterator(true);
            while (vit.hasNext()) {
                Assert.assertTrue(o.contains(-vit.next()));
            }
            vit.dispose();
            vit = v.getValueIterator(false);
            while (vit.hasPrevious()) {
                Assert.assertTrue(o.contains(-vit.previous()));
            }
            vit.dispose();
            DisposableRangeIterator rit = v.getRangeIterator(true);
            while (rit.hasNext()) {
                Assert.assertTrue(o.contains(-rit.min()));
                Assert.assertTrue(o.contains(-rit.max()));
                rit.next();
            }
            rit = v.getRangeIterator(false);
            while (rit.hasPrevious()) {
                Assert.assertTrue(o.contains(-rit.min()));
                Assert.assertTrue(o.contains(-rit.max()));
                rit.previous();
            }
        }
    }

}


text:
#{about}

#{title}
#{from}

#{support}

          #{appsite}

          #{website}

          #{mail}

#{copy}


text:
class AddDateHardMaxMinToVariables < ActiveRecord::Migration[4.2]
  def change
    add_column :variables, :date_hard_maximum, :date
    add_column :variables, :date_hard_minimum, :date
  end
end


text:
{% assign url = page.url|remove:'index.html' %}
{% assign navlist = site.navigation %}

<!doctype html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>{{ page.title }}</title>
  <meta name="description" content="Shannon Stanley aerial & dance">
  <meta name="author" content="Shannon Stanley">
  <meta name="keywords" content="dance, aerial, ballet, silks, sling, fabric, circus, performance">

  <meta name="viewport" content="initial-scale=1.0, width=device-width, maximum-scale=1" />
  <link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
  <link href="https://fonts.googleapis.com/css?family=Merriweather:300,400,700" rel="stylesheet">

  <link rel="shortcut icon" type="image/x-icon" href="/iterum.png">

  <link rel="stylesheet" href="/app/css/import.css">
  <link rel="stylesheet" href="/app/css/fluidbox.min.css">

        {{ content }}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<title>Step 6: Create a Shared Library</title>

Step By Step

    Step 6: Create a Shared Library

Remember in Step 1: Write the Java Code you
used the following method call to load a shared library named
hello into your program at runtime:

System.loadLibrary("hello");

Now you are ready to create the shared library.

In the previous two steps you create two native language files:
in Step 4: Create a Stubs File you created
a stubs file named HelloWorld.c, and in
 Step 5: Write the Native Method Implementation
you wrote the implementation for the displayHelloWorld() native
method and saved it in HelloWorldImp.c. You compile these two
files into a library named hello to create it.

Use whatever tools you have to compile the native language code that you
created in the previous two steps into a shared library. On Solaris
and MacOS, you'll create a shared library, on Windows 95/Nt
you'll create a dynamically loadable library (DLL).

Step By Step


text:
<?php
/**
 * ARC2 SPARQL ASK query handler
 *
 * @author Benjamin Nowack
 * @license <http://arc.semsol.org/license>
 * @homepage <http://arc.semsol.org/>
 * @package ARC2
 * @version 2009-12-15
*/

ARC2::inc('StoreSelectQueryHandler');

class ARC2_StoreAskQueryHandler extends ARC2_StoreSelectQueryHandler {

  function __construct($a = '', &$caller) {/* caller has to be a store */
    parent::__construct($a, $caller);
  }

  function ARC2_StoreAskQueryHandler($a = '', &$caller) {
    $this->__construct($a, $caller);
  }

  function __init() {/* db_con */
    parent::__init();
    $this->store =& $this->caller;
  }

  /*  */

  function runQuery($infos) {
    $infos['query']['limit'] = 1;
    $this->infos = $infos;
    $this->buildResultVars();
    return parent::runQuery($this->infos);
  }

  /*  */

  function buildResultVars() {
    $this->infos['query']['result_vars'][] = array('var' => '1', 'aggregate' => '', 'alias' => 'success');
  }

  /*  */

  function getFinalQueryResult($q_sql, $tmp_tbl) {
    $con = $this->store->getDBCon();
    $rs = mysql_query('SELECT success FROM ' . $tmp_tbl, $con);
    $r = ($row = mysql_fetch_array($rs)) ? $row['success'] : 0;
    return $r ? true : false;
  }

  /*  */

}


text:
package org.apache.directory.fortress.core;

/**
 * This exception extends {@link SecurityException} and is thrown when DAO cannot find entity.
 * See the {@link GlobalErrIds} javadoc for list of error ids.
 *
 * @author Apache Directory Project
 */
public class FinderException extends SecurityException
{
    /** Default serialVersionUID */
    private static final long serialVersionUID = 1L;

    /**
     * Create an exception with an error code that maps to {@link GlobalErrIds} and message text.
     *
     * @param  errorId see {@link GlobalErrIds} for list of valid error codes that can be set.  Valid values between
     * 0 & 100_000.
     * @param msg contains textual information including method of origin and description of the root cause.
     */
    public FinderException( int errorId, String msg )
    {
        super( errorId, msg );
        setHttpStatus(404);
    }

    /**
     * Create exception with error id, message and related exception.
     * @param  errorId see {@link GlobalErrIds} for list of valid error codes that can be set.  Valid values between
     * 0  & 100_000.
     * @param msg contains textual information including method of origin and description of the root cause.
     * @param previousException contains reference to related exception which usually is system related, i.e. ldap.
     */
    public FinderException( int errorId, String msg, Exception previousException )
    {
        super( errorId, msg, previousException );
        setHttpStatus(404);
    }
}


text:
title: Implement the Serialization of a Passport User
localeTitle: Implementar a serialização de um usuário do Passport
---
## Implementar a serialização de um usuário do Passport

Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/information-security-and-quality-assurance/advanced-node-and-express/implement-the-serialization-of-a-passport-user/index.md) .

[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
<xul:groupbox{% if request.is_xhr %} xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"{% endif %} url="{{url_for('.path', path=g.item.path)}}" id='editor-box'>
    <xul:caption style='text:bold;' label='{{g.item.name}}'></xul:caption>
    {%- for name, item in g.item %}
    {%- if name in g.item.view.editable_fields %}
        {{item.view.render(name, item)|safe}}
    {%- endif %}
    {%- endfor %}
</xul:groupbox>


text:
/* jshint esversion: 6 */

var tap = require('tap');
var MinibossHelper = require('./lib/miniboss_helper.js').MinibossHelper;
var GearmanHelper = require('./lib/gearman_helper.js').GearmanHelper;

tap.test("server can be connected", t => {
    var miniboss_helper = new MinibossHelper();
    var gearman_helper = new GearmanHelper();
    miniboss_helper.create_local_miniboss_with_random_port_until_success( server => {
        gearman_helper.create_connected_client_for_single_server( server, ( client ) => {
            t.pass();
            t.end();
        } );
    } );
    t.tearDown( () => {
        gearman_helper.tear_down();
        miniboss_helper.tear_down();
    });
});


text:
<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'id'); ?>
		<?php echo $form->textField($model,'id',array('size'=>6,'maxlength'=>6)); ?>

		<?php echo $form->label($model,'first_name'); ?>
		<?php echo $form->textField($model,'first_name',array('size'=>24,'maxlength'=>24)); ?>

		<?php echo $form->label($model,'last_name'); ?>
		<?php echo $form->textField($model,'last_name',array('size'=>24,'maxlength'=>24)); ?>

		<?php echo $form->label($model,'email'); ?>
		<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>64)); ?>

		<?php echo $form->label($model,'username'); ?>
		<?php echo $form->textField($model,'username',array('size'=>32,'maxlength'=>32)); ?>

		<?php echo $form->label($model,'phone'); ?>
		<?php echo $form->textField($model,'phone',array('size'=>20,'maxlength'=>20)); ?>

		<?php echo $form->label($model,'birthday'); ?>
		<?php echo $form->textField($model,'birthday'); ?>

		<?php echo $form->label($model,'gamertag'); ?>
		<?php echo $form->textField($model,'gamertag',array('size'=>60,'maxlength'=>64)); ?>

		<?php echo $form->label($model,'blurb'); ?>
		<?php echo $form->textArea($model,'blurb',array('rows'=>6, 'cols'=>50)); ?>

		<?php echo $form->label($model,'id_role'); ?>
		<?php echo $form->textField($model,'id_role'); ?>

		<?php echo $form->label($model,'datetime_join'); ?>
		<?php echo $form->textField($model,'datetime_join'); ?>

		<?php echo $form->label($model,'active'); ?>
		<?php echo $form->textField($model,'active'); ?>

		<?php echo $form->label($model,'hash'); ?>
		<?php echo $form->textField($model,'hash',array('size'=>32,'maxlength'=>32)); ?>

		<?php echo CHtml::submitButton('Search'); ?>

<?php $this->endWidget(); ?>


text:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;

/**
 * This is {@link CheckSpringConfigurationConditionals}.
 *
 * @author Misagh Moayyed
 * @since 6.3.0
 */
public class CheckSpringConfigurationConditionals {
    public static void main(final String[] args) throws Exception {
        checkPattern(args[0]);
    }

    private static void print(final String message, final Object... args) {
        //CHECKSTYLE:OFF
        System.out.printf(message, args);
        //CHECKSTYLE:ON
    }

    private static String readFile(final Path file) {
        try {
            return Files.readString(file);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected static void checkPattern(final String arg) throws IOException {
        var failBuild = new AtomicBoolean(false);
        var pattern = Pattern.compile("@ConditionalOnProperty.+public (static)* class .+Configuration", Pattern.DOTALL);
        Files.walk(Paths.get(arg))
            .filter(f -> Files.isRegularFile(f) && f.toFile().getName().endsWith("Configuration.java"))
            .forEach(file -> {
                var text = readFile(file);
                if (text.contains("@Configuration") && !text.contains("@SuppressWarnings(\"ConditionalOnProperty\")")
                    && pattern.matcher(text).find()) {
                    print("- Using @ConditionalOnProperty on configuration classes found in %s is not allowed. "
                          + "Consider using a feature module if appropriate, or using the BeanSupplier/BeanCondition API "
                          + "to allow bean definitions to support resfresh requests and application context refreshes."
                          + "If you determine that using @ConditionalOnProperty is appropriate for the use case at hand, "
                          + "you may annotate the class with @SuppressWarnings(\"ConditionalOnProperty\").%n%n", file.getFileName().toString());
                    failBuild.set(true);
                }

            });
        if (failBuild.get()) {
            System.exit(1);
        }
    }
}


text:
package nom.bdezonia.zorbage.type.universal;

/**
 *
 * @author Barry DeZonia
 *
 */
public enum PrimitiveRepresentation {

	BYTE, SHORT, INT, LONG, FLOAT, DOUBLE, BIGINTEGER, BIGDECIMAL
	// purposely skipping BOOLEAN since it's not numeric

}


text:
* Introduce `PureeLogger`, removing `PureeLogRegistry` to mock `Puree` easily
  * See PureeTest.java to see how to mock `Puree` static methods.

* https://github.com/cookpad/puree-android/compare/v3.2.0...v3.3.0

# v3.2.0 2015/06/17

* Introduce `PureeLogRegistry` and remove `Pure.serilaizeLog()` and `Puree.getRegisteredOutputPlugins()`

* https://github.com/cookpad/puree-android/compare/v3.1.0...v3.2.0

# v3.1.0 2015/06/17

* Add `Puree.serializeLog()` and `Puree.getRegisteredOutputPlugins()` to test the use of Puree
  * https://github.com/cookpad/puree-android/pull/34
* Optimize internals
  * https://github.com/cookpad/puree-android/pull/35

* https://github.com/cookpad/puree-android/compare/v3.0.0...v3.1.0

# v3.0.0 2015/6/16

Puree v3 is not compatible with v2, which uses [Gson](https://github.com/google/gson) for the fundamental JSON framework,
 instead of [org.json.JSONObject](http://developer.android.com/reference/org/json/package-summary.html) used before v3.

`Gson` has `JsonObject` class which is functionally compatible with `org.json.JSONObject` so migration is really easy.

Here is the diff between v2 and v3 for the SamplingFilter example:

```diff
     @Override
-    public JSONObject apply(JSONObject jsonLog) throws JSONException {
+    public JsonObject apply(JsonObject jsonLog) {
         return (samplingRate < Math.random() ? null : jsonLog);
     }
 }
```

The main development branch is here: https://github.com/cookpad/puree-android/pull/32

* https://github.com/cookpad/puree-android/compare/v2.0.0...v3.0.0

# v2.0.0 2015/2/26

Puree v2 is not compatible with v1; you can now connect a log classes with output plugins.

The main development branch is here: https://github.com/cookpad/puree-android/pull/22

* https://github.com/cookpad/puree-android/compare/v1.0.0...v2.0.0

# v1.0.0 2014/11/25

* https://github.com/cookpad/puree-android/compare/v0.0.8...v1.0.0

# v0.0.8 2014/11/5

* https://github.com/cookpad/puree-android/compare/v0.0.6...v0.0.8

# v0.0.6 2014/11/4

* The first tagged version


text:
package WebRHINO;
use Moose;
use namespace::autoclean;

use Catalyst::Runtime 5.80;

# Set flags and add plugins for the application.
#
# Note that ORDERING IS IMPORTANT here as plugins are initialized in order,
# therefore you almost certainly want to keep ConfigLoader at the head of the
# list if you're using it.
#
#         -Debug: activates the debug mode for very useful log messages
#   ConfigLoader: will load the configuration from a Config::General file in the
#                 application's home directory
# Static::Simple: will serve static files from the application's root
#                 directory

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple

    Session::Store::FastMmap
    StatusMessage

    Authentication
    Authorization::Roles

    Session
    Session::Store::File
    Session::State::Cookie
/;

extends 'Catalyst';

our $VERSION = '0.01';

# Configure the application.
#
# Note that settings in webrhino.conf (or other external
# configuration file that you set up manually) take precedence
# over this when using ConfigLoader. Thus configuration
# details given here can function as a default configuration,
# with an external configuration file acting as an override for
# local deployment.

__PACKAGE__->config(
    name => 'WebRHINO',
    # Disable deprecated behavior needed by old applications
    disable_component_resolution_regex_fallback => 1,
    enable_catalyst_header => 1, # Send X-Catalyst header
    default_view => 'HTML',
);

__PACKAGE__->config (
    'Plugin::Authentication' => {
        default => {
            class              => 'SimpleDB',
            user_model         => 'Rhino::User',
            password_type      => 'self_check',
            #password_field     => 'password',
            #password_type      => 'hashed',
            #password_hash_type => 'SHA-1',
        },
    },
);

# Start the application
__PACKAGE__->setup();

=encoding utf8

=head1 NAME

WebRHINO - Catalyst based application

=head1 SYNOPSIS

    script/webrhino_server.pl

=head1 DESCRIPTION

[enter your description here]

=head1 SEE ALSO

L<WebRHINO::Controller::Root>, L<Catalyst>

=head1 AUTHOR

Catalyst developer

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;


text:
using System;
using Mondo.Extensions;

namespace Mondo
{
    /// <summary>
    /// Endpoints which enumerate objects support time-based and cursor-based pagination.
    /// </summary>
    public sealed class PaginationOptions
    {
        /// <summary>
        /// Limits the number of results per-page.
        /// </summary>
        public int? Limit { get; set; }

        /// <summary>
        /// An RFC 3339-encoded timestamp.
        /// </summary>
        public DateTime? SinceTime { get; set; }

        /// <summary>
        /// Or an object id.
        /// </summary>
        public string SinceId { get; set; }

        /// <summary>
        /// An RFC 3339 encoded-timestamp
        /// </summary>
        public DateTime? BeforeTime { get; set; }

        /// <summary>
        /// Format the pagination options as a query string.
        /// </summary>
        public override string ToString()
        {
            string since = SinceTime?.ToRfc3339String() ?? SinceId;
            string before = BeforeTime?.ToRfc3339String();

            return $"&limit={Limit}&since={since}&before={before}";
        }
    }
}


text:
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/bitly/go-nsq"
	"github.com/bitly/nsq/util"
)

var (
	topic            = flag.String("topic", "", "nsq topic")
	delimiter        = flag.String("delimiter", "\n", "what from stdin to split on (lines by default)")
	destNsqdTCPAddrs = util.StringArray{}
	readerOpts       = util.StringArray{}
)

func init() {
	flag.Var(&readerOpts, "reader-opt", "option to passthrough to nsq.Consumer (may be given multiple times)")
	flag.Var(&destNsqdTCPAddrs, "nsqd-tcp-address", "destination nsqd TCP address (may be given multiple times)")
}

var logger *log.Logger

func main() {
	logger = log.New(os.Stderr, "", log.LstdFlags)

	// handle stopping
	stopChan := make(chan bool)
	termChan := make(chan os.Signal, 1)
	signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)

	// parse flags
	flag.Parse()
	if len(*topic) == 0 {
		fatal(true, "Must specify a valid topic")
	}
	if len(*delimiter) != 1 {
		fatal(true, "Delimiter must be a single byte")
	}

	// prepare the configuration
	wcfg := nsq.NewConfig()
	wcfg.UserAgent = fmt.Sprintf("to_nsq/%s go-nsq/%s", util.BINARY_VERSION, nsq.VERSION)
	if err := util.ParseReaderOpts(wcfg, readerOpts); err != nil {
		fatal(true, err)
	}

	// make the producers
	producers := make(map[string]*nsq.Producer)
	for _, addr := range destNsqdTCPAddrs {
		producer, err := nsq.NewProducer(addr, wcfg)
		if err != nil {
			fatal(true, "failed creating producer", err)
		}
		producer.SetLogger(logger, nsq.LogLevelInfo)
		producers[addr] = producer
		defer producer.Stop()
	}
	if len(producers) == 0 {
		fatal(true, "Must specify at least one nsqd-tcp-address")
	}

	var fatalErr error

	// scan the input
	r := bufio.NewReader(os.Stdin)
	delim := (*delimiter)[0]
	go func() {
		for {
			if err := readAndPublish(r, delim, producers); err != nil {
				if err != io.EOF {
					fatalErr = err
				}
				stopChan <- true // stop
				break
			}
		}
	}()

	// wait for things to finish
	select {
	case <-termChan:
	case <-stopChan:
	}

	// if a fatal error occurred - report it
	if fatalErr != nil {
		fatal(false, fatalErr)
	}

}

// readAndPublish reads to the delim from r and publishes the bytes
// to the map of producers.
func readAndPublish(r *bufio.Reader, delim byte, producers map[string]*nsq.Producer) error {

	line, readErr := r.ReadBytes(delim)

	if len(line) > 0 { // trim the delimiter
		line = line[:len(line)-1]
	}
	if len(line) > 0 {
		for _, producer := range producers {
			if err := producer.Publish(*topic, line); err != nil {
				return err
			}
		}
	}

	return readErr

}

// fatal writes an error and exits
func fatal(usage bool, args ...interface{}) {
	logger.Println(args...)
	if usage {
		flag.PrintDefaults()
	}
	os.Exit(1)
}