text:
package #
Devel::CheckLib;

use 5.00405; #postfix foreach
use strict;
use vars qw($VERSION @ISA @EXPORT);
$VERSION = '0.93_001';
use Config qw(%Config);
use Text::ParseWords 'quotewords';

use File::Spec;
use File::Temp;
use File::Path qw(rmtree);

require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(assert_lib check_lib_or_exit check_lib);

# localising prevents the warningness leaking out of this module
local $^W = 1;    # use warnings is a 5.6-ism

_findcc(); # bomb out early if there's no compiler

=head1 NAME

Devel::CheckLib - check that a library is available

=head1 DESCRIPTION

Devel::CheckLib is a perl module that checks whether a particular C
library and its headers are available.

=head1 SYNOPSIS

    use Devel::CheckLib;

    check_lib_or_exit( lib => 'jpeg', header => 'jpeglib.h' );
    check_lib_or_exit( lib => [ 'iconv', 'jpeg' ] );

    # or prompt for path to library and then do this:
    check_lib_or_exit( lib => 'jpeg', libpath => $additional_path );

=head1 USING IT IN Makefile.PL or Build.PL

If you want to use this from Makefile.PL or Build.PL, do
not simply copy the module into your distribution as this may cause
problems when PAUSE and search.cpan.org index the distro.  Instead, use
the use-devel-checklib script.

=head1 HOW IT WORKS

You pass named parameters to a function, describing to it how to build
and link to the libraries.

It works by trying to compile some code - which defaults to this:

    int main(void) { return 0; }

and linking it to the specified libraries.  If something pops out the end
which looks executable, it gets executed, and if main() returns 0 we know
that it worked.  That tiny program is
built once for each library that you specify, and (without linking) once
for each header file.

If you want to check for the presence of particular functions in a
library, or even that those functions return particular results, then
you can pass your own function body for main() thus:

    check_lib_or_exit(
        function => 'foo();if(libversion() > 5) return 0; else return 1;'
        incpath  => ...
        libpath  => ...
        lib      => ...
        header   => ...
    );

In that case, it will fail to build if either foo() or libversion() don't
exist, and main() will return the wrong value if libversion()'s return
value isn't what you want.

=head1 FUNCTIONS

All of these take the same named parameters and are exported by default.
To avoid exporting them, C<use Devel::CheckLib ()>.

=head2 assert_lib

This takes several named parameters, all of which are optional, and dies
with an error message if any of the libraries listed can
not be found.  B<Note>: dying in a Makefile.PL or Build.PL may provoke
a 'FAIL' report from CPAN Testers' automated smoke testers.  Use
C<check_lib_or_exit> instead.

The named parameters are:

=over

=item lib

Must be either a string with the name of a single
library or a reference to an array of strings of library names.  Depending
on the compiler found, library names will be fed to the compiler either as
C<-l> arguments or as C<.lib> file names.  (E.g. C<-ljpeg> or C<jpeg.lib>)

=item libpath

a string or an array of strings
representing additional paths to search for libraries.

=item LIBS

a C<ExtUtils::MakeMaker>-style space-seperated list of
libraries (each preceded by '-l') and directories (preceded by '-L').

This can also be supplied on the command-line.

=back

And libraries are no use without header files, so ...

=over

=item header

Must be either a string with the name of a single
header file or a reference to an array of strings of header file names.

=item incpath

a string or an array of strings
representing additional paths to search for headers.

=item INC

a C<ExtUtils::MakeMaker>-style space-seperated list of
incpaths, each preceded by '-I'.

This can also be supplied on the command-line.

=back

If you need to perform know more than "does it link?" you can provide
code to be compiled and run:

=over

=item function

the body of the <main()> function.  If not provided C<return 0;> is
used.

=item prologue

code to insert between the C<#include> of the headers and the
definition of main.

=back

=head2 check_lib_or_exit

This behaves exactly the same as C<assert_lib()> except that instead of
dieing, it warns (with exactly the same error message) and exits.
This is intended for use in Makefile.PL / Build.PL
when you might want to prompt the user for various paths and
things before checking that what they've told you is sane.

If any library or header is missing, it exits with an exit value of 0 to avoid
causing a CPAN Testers 'FAIL' report.  CPAN Testers should ignore this
result -- which is what you want if an external library dependency is not
available.

=head2 check_lib

This behaves exactly the same as C<assert_lib()> except that it is silent,
returning false instead of dieing, or true otherwise.

=cut

sub check_lib_or_exit {
    eval 'assert_lib(@_)';
    if($@) {
        warn $@;
        exit;
    }
}

sub check_lib {
    eval 'assert_lib(@_)';
    return $@ ? 0 : 1;
}

sub assert_lib {
    my %args = @_;
    my (@libs, @libpaths, @headers, @incpaths);

    # FIXME: these four just SCREAM "refactor" at me
    @libs = (ref($args{lib}) ? @{$args{lib}} : $args{lib})
        if $args{lib};
    @libpaths = (ref($args{libpath}) ? @{$args{libpath}} : $args{libpath})
        if $args{libpath};
    @headers = (ref($args{header}) ? @{$args{header}} : $args{header})
        if $args{header};
    @incpaths = (ref($args{incpath}) ? @{$args{incpath}} : $args{incpath})
        if $args{incpath};

    # each entry is an arrayref containing:
    # 0: arrayref of library search paths
    # 1: arrayref of library names
    my @link_cfgs = map [ \@libpaths, [ $_ ] ], @libs;

    # work-a-like for Makefile.PL's LIBS and INC arguments
    # if given as command-line argument, append to %args
    for my $arg (@ARGV) {
        for my $mm_attr_key (qw(LIBS INC)) {
            if (my ($mm_attr_value) = $arg =~ /\A $mm_attr_key = (.*)/x) {
            # it is tempting to put some \s* into the expression, but the
            # MM command-line parser only accepts LIBS etc. followed by =,
            # so we should not be any more lenient with whitespace than that
                $args{$mm_attr_key} .= " $mm_attr_value";
            }
        }
    }

    # using special form of split to trim whitespace
    if(defined($args{LIBS})) {
        if (ref $args{LIBS}) {
	    foreach my $arg (@{$args{LIBS}}) {
		my @sep = split ' ', $arg;
		my @libs = map { /^-l(.+)$/ ? $1 : () } @sep;
		my @paths = map { /^-L(.+)$/ ? $1 : () } @sep;
		push @link_cfgs, [ \@paths, \@libs ];
	    }
	}
	else {
	    my @libs;
	    my @paths;
	    foreach my $arg (split(' ', $args{LIBS})) {
		die("LIBS argument badly-formed: $arg\n") unless($arg =~ /^-l/i);
		push @{$arg =~ /^-l/ ? \@libs : \@paths}, substr($arg, 2);
	    }
	    push @link_cfgs, map [ \@paths, [ $_ ] ], @libs;
	}
    }
    if(defined($args{INC})) {
        foreach my $arg (_shellwords($args{INC})) {
            die("INC argument badly-formed: $arg\n") unless($arg =~ /^-I/);
            push @incpaths, substr($arg, 2);
        }
    }

    my ($cc, $ld) = _findcc();
    my @missing;
    my @wrongresult;
    my @use_headers;

    # first figure out which headers we can't find ...
    for my $header (@headers) {
        push @use_headers, $header;
        my($ch, $cfile) = File::Temp::tempfile(
            'assertlibXXXXXXXX', SUFFIX => '.c'
        );
        print $ch qq{#include <$_>\n} for @use_headers;
        print $ch qq{int main(void) { return 0; }\n};
        close($ch);
        my $exefile = File::Temp::mktemp( 'assertlibXXXXXXXX' ) . $Config{_exe};
        my @sys_cmd;
        # FIXME: re-factor - almost identical code later when linking
        if ( $Config{cc} eq 'cl' ) {                 # Microsoft compiler
            require Win32;
            @sys_cmd = (
                @$cc,
                $cfile,
                "/Fe$exefile",
                (map { '/I'.Win32::GetShortPathName($_) } @incpaths),
                "/link",
                @$ld
            );
        } elsif($Config{cc} =~ /bcc32(\.exe)?/) {    # Borland
            @sys_cmd = (
                @$cc,
                (map { "-I$_" } @incpaths),
                "-o$exefile",
                $cfile,
                @$ld
            );
        } else { # Unix-ish: gcc, Sun, AIX (gcc, cc), ...
            @sys_cmd = (
                @$cc,
                @$ld,
                $cfile,
                (map { "-I$_" } @incpaths),
                "-o", "$exefile"
            );
        }
        warn "# @sys_cmd\n" if $args{debug};
        my $rv = $args{debug} ? system(@sys_cmd) : _quiet_system(@sys_cmd);
        push @missing, $header if $rv != 0 || ! -x $exefile;
        _cleanup_exe($exefile);
        unlink $cfile;
    }

    # now do each library in turn with headers
    my($ch, $cfile) = File::Temp::tempfile(
        'assertlibXXXXXXXX', SUFFIX => '.c'
    );
    print $ch qq{#include <$_>\n} foreach (@headers);
    print $ch "\n$args{prologue}\n" if $args{prologue};
    print $ch "int main(void) { ".($args{function} || 'return 0;')." }\n";
    close($ch);
    for my $link_cfg ( @link_cfgs ) {
	my ($paths, $libs) = @$link_cfg;
        my $exefile = File::Temp::mktemp( 'assertlibXXXXXXXX' ) . $Config{_exe};
        my @sys_cmd;
        if ( $Config{cc} eq 'cl' ) {                 # Microsoft compiler
            require Win32;
            my @libpath = map {
                q{/libpath:} . Win32::GetShortPathName($_)
            } @libpaths;
            # this is horribly sensitive to the order of arguments
            @sys_cmd = (
                @$cc,
                $cfile,
                ( map { "$_.lib" } @$libs ),
                "/Fe$exefile",
                (map { '/I'.Win32::GetShortPathName($_) } @incpaths),
                "/link",
		@$ld,
                (map {'/libpath:'.Win32::GetShortPathName($_)} @$paths),
            );
        } elsif($Config{cc} eq 'CC/DECC') {          # VMS
        } elsif($Config{cc} =~ /bcc32(\.exe)?/) {    # Borland
            @sys_cmd = (
                @$cc,
		@$ld,
                "-o$exefile",
                (map { "-l$_" } @$libs ),
                (map { "-I$_" } @incpaths),
                (map { "-L$_" } @$paths),
                $cfile);
        } else {                                     # Unix-ish
                                                     # gcc, Sun, AIX (gcc, cc)
            @sys_cmd = (
                @$cc,
		@$ld,
                $cfile,
                "-o", "$exefile",
                (map { "-l$_" } @$libs ),
                (map { "-I$_" } @incpaths),
                (map { "-L$_" } @$paths)
            );
        }
        warn "# @sys_cmd\n" if $args{debug};
        my $rv = $args{debug} ? system(@sys_cmd) : _quiet_system(@sys_cmd);
        push @missing, @$libs if $rv != 0 || ! -x $exefile;
        my $absexefile = File::Spec->rel2abs($exefile);
        $absexefile = '"'.$absexefile.'"' if $absexefile =~ m/\s/;
        push @wrongresult, @$libs if $rv == 0 && -x $exefile && system($absexefile) != 0;
        _cleanup_exe($exefile);
    }
    unlink $cfile;

    my $miss_string = join( q{, }, map { qq{'$_'} } @missing );
    die("Can't link/include $miss_string\n") if @missing;
    my $wrong_string = join( q{, }, map { qq{'$_'} } @wrongresult);
    die("wrong result: $wrong_string\n") if @wrongresult;
}

sub _cleanup_exe {
    my ($exefile) = @_;
    my $ofile = $exefile;
    $ofile =~ s/$Config{_exe}$/$Config{_o}/;
    unlink $exefile if -f $exefile;
    unlink $ofile if -f $ofile;
    unlink "$exefile\.manifest" if -f "$exefile\.manifest";
    if ( $Config{cc} eq 'cl' ) {
	# MSVC also creates foo.ilk and foo.pdb
	my $ilkfile = $exefile;
	$ilkfile =~ s/$Config{_exe}$/.ilk/;
	my $pdbfile = $exefile;
	$pdbfile =~ s/$Config{_exe}$/.pdb/;
	unlink $ilkfile if -f $ilkfile;
	unlink $pdbfile if -f $pdbfile;
    }
    # created by clang on darwin
    my $dsym_dir = $exefile;
    $dsym_dir =~ s/\Q$Config{_exe}\E$/.dSYM/;
    rmtree $dsym_dir if -d $dsym_dir;

    return
}

# return ($cc, $ld)
# where $cc is an array ref of compiler name, compiler flags
# where $ld is an array ref of linker flags
sub _findcc {
    # Need to use $keep=1 to work with MSWin32 backslashes and quotes
    my $Config_ccflags =  $Config{ccflags};  # use copy so ASPerl will compile
    my @Config_ldflags =  @Config{qw(ldflags perllibs)};
    my @ccflags = grep { length } quotewords('\s+', 1, $Config_ccflags);
    my @ldflags = grep { length } quotewords('\s+', 1, @Config_ldflags);
    my @paths = split(/$Config{path_sep}/, $ENV{PATH});
    my @cc = split(/\s+/, $Config{cc});
    return ( [ @cc, @ccflags ], \@ldflags ) if -x $cc[0];
    foreach my $path (@paths) {
        my $compiler = File::Spec->catfile($path, $cc[0]) . $Config{_exe};
        return ([ $compiler, @cc[1 .. $#cc], @ccflags ], \@ldflags)
            if -x $compiler;
    }
    die("Couldn't find your C compiler\n");
}

sub _shellwords {
    my $line = shift;

    if ($^O eq "MSWin32") {
	my @elements;
	$line =~ s/^\s+//;
	while ($line =~ s/^"([^"]*)"// || $line =~ s/^(\S+)//) {
	  push @elements, $1;
	  $line =~ s/^\s+//;
	}
	return @elements;
    }
    else {
	return grep defined && /\S/, quotewords('\s+', 0, $line);
    }
}

# code substantially borrowed from IPC::Run3
sub _quiet_system {
    my (@cmd) = @_;

    # save handles
    local *STDOUT_SAVE;
    local *STDERR_SAVE;
    open STDOUT_SAVE, ">&STDOUT" or die "CheckLib: $! saving STDOUT";
    open STDERR_SAVE, ">&STDERR" or die "CheckLib: $! saving STDERR";

    # redirect to nowhere
    local *DEV_NULL;
    open DEV_NULL, ">" . File::Spec->devnull
        or die "CheckLib: $! opening handle to null device";
    open STDOUT, ">&" . fileno DEV_NULL
        or die "CheckLib: $! redirecting STDOUT to null handle";
    open STDERR, ">&" . fileno DEV_NULL
        or die "CheckLib: $! redirecting STDERR to null handle";

    # run system command
    my $rv = system(@cmd);

    # restore handles
    open STDOUT, ">&" . fileno STDOUT_SAVE
        or die "CheckLib: $! restoring STDOUT handle";
    open STDERR, ">&" . fileno STDERR_SAVE
        or die "CheckLib: $! restoring STDERR handle";

    return $rv;
}

=head1 PLATFORMS SUPPORTED

You must have a C compiler installed.  We check for C<$Config{cc}>,
both literally as it is in Config.pm and also in the $PATH.

It has been tested with varying degrees on rigourousness on:

=over

=item gcc (on Linux, *BSD, Mac OS X, Solaris, Cygwin)

=item Sun's compiler tools on Solaris

=item IBM's tools on AIX

=item SGI's tools on Irix 6.5

=item Microsoft's tools on Windows

=item MinGW on Windows (with Strawberry Perl)

=item Borland's tools on Windows

=item QNX

=back

=head1 WARNINGS, BUGS and FEEDBACK

This is a very early release intended primarily for feedback from
people who have discussed it.  The interface may change and it has
not been adequately tested.

Feedback is most welcome, including constructive criticism.
Bug reports should be made using L<http://rt.cpan.org/> or by email.

When submitting a bug report, please include the output from running:

    perl -V
    perl -MDevel::CheckLib -e0

=head1 SEE ALSO

L<Devel::CheckOS>

L<Probe::Perl>

=head1 AUTHORS

David Cantrell E<lt>david@cantrell.org.ukE<gt>

David Golden E<lt>dagolden@cpan.orgE<gt>

Yasuhiro Matsumoto E<lt>mattn@cpan.orgE<gt>

Thanks to the cpan-testers-discuss mailing list for prompting us to write it
in the first place;

to Chris Williams for help with Borland support;

to Tony Cook for help with Microsoft compiler command-line options

=head1 COPYRIGHT and LICENCE

Copyright 2007 David Cantrell. Portions copyright 2007 David Golden.

This module is free-as-in-speech software, and may be used, distributed,
and modified under the same conditions as perl itself.

=head1 CONSPIRACY

This module is also free-as-in-mason software.

=cut

1;


text:
#include "gp.h"

/* It executes the Binary Geometric Semantic Genetic Programming for function minimization
Parameters:
s: search space
Evaluate: pointer to the function used to evaluate particles
arg: list of additional arguments */
void runBGSGP(SearchSpace *s, prtFun Evaluate, ...)
{
	va_list arg, argtmp;
	int t, i, j, z, n_reproduction, n_mutation, n_crossover;
	int *reproduction = NULL, *mutation = NULL, *crossover = NULL;
	int father_cross_point, mother_crosspoint, ctr;
	double beta, prob;
	Node **tmpTree = NULL, *aux = NULL;

	va_start(arg, Evaluate);
	va_copy(argtmp, arg);

	if (!s)
	{
		fprintf(stderr, "\nSearch space not allocated @runBGSGP.\n");
		exit(-1);
	}

	EvaluateSearchSpace(s, _GP_, Evaluate, arg); /* Initial evaluation */
	tmpTree = (Node **)malloc(s->m * sizeof(Node *));
	ShowSearchSpace(s, _GP_);

	for (t = 1; t <= s->iterations; t++)
	{
		fprintf(stderr, "\nRunning iteration %d/%d ... ", t, s->iterations);

		for (i = 0; i < s->m; i++)
			tmpTree[i] = CopyTree(s->T[i]);

		/* Calcultating the number of individuals to be reproducted */
		n_reproduction = round(s->m * s->pReproduction);
		reproduction = RouletteSelection(s, n_reproduction);

		/* Calcultating the number of individuals to be mutated */
		n_mutation = round(s->m * s->pMutation);
		mutation = RouletteSelection(s, n_mutation);

		/* Calcultating the number of individuals to perform the crossover */
		n_crossover = s->m - (n_reproduction + n_mutation);
		crossover = RouletteSelection(s, n_crossover);

		/* It performs the reproduction */
		for (i = 0; i < n_reproduction; i++)
		{
			DestroyTree(&s->T[i]);
			s->T[i] = CopyTree(tmpTree[reproduction[i]]);
		}

		/* It performs the mutation */
		z = 0;
		for (j = n_reproduction; j < n_reproduction + n_mutation; j++)
		{
			DestroyTree(&s->T[j]);
			s->T[j] = SGMB(s, tmpTree[mutation[z]]);
			z++;
		}

		/* It performs the crossover */
		z = 0;
		for (j = n_reproduction + n_mutation; j < n_reproduction + n_mutation + n_crossover; j++)
		{
			ctr = 1;
			do
			{
				father_cross_point = GenerateUniformRandomNumber(0, n_crossover);
				mother_crosspoint = GenerateUniformRandomNumber(0, n_crossover);
				ctr++;
			} while ((father_cross_point == mother_crosspoint) && (ctr <= 10));

			aux = SGXB(s, tmpTree[crossover[father_cross_point]], tmpTree[crossover[mother_crosspoint]]);
			DestroyTree(&(s->T[j]));
			s->T[j] = CopyTree(aux);
			DestroyTree(&aux);
			z++;
		}

		free(reproduction);
		free(mutation);
		free(crossover);

		for (i = 0; i < s->m; i++)
			DestroyTree(&tmpTree[i]);

		EvaluateSearchSpace(s, _GP_, Evaluate, arg);

		fprintf(stderr, "OK (minimum fitness value %lf) -> Best tree: %d.", s->gfit, s->best);
		va_copy(arg, argtmp);
	}

	free(tmpTree);
	va_end(arg);
}
/*************************/

/* It executes standard (real-valued) Geometric Semantic Genetic Programming for function minimization
Parameters:
s: search space
Evaluate: pointer to the function used to evaluate particles
arg: list of additional arguments */
void runGSGP(SearchSpace *s, prtFun Evaluate, ...)
{
	va_list arg, argtmp;
	int t, i, j, z, n_reproduction, n_mutation, n_crossover;
	int *reproduction = NULL, *mutation = NULL, *crossover = NULL;
	int father_cross_point, mother_crosspoint, ctr;
	double beta, prob;
	Node **tmpTree = NULL, *aux = NULL;

	va_start(arg, Evaluate);
	va_copy(argtmp, arg);

	if (!s)
	{
		fprintf(stderr, "\nSearch space not allocated @runBGSGP.\n");
		exit(-1);
	}

	EvaluateSearchSpace(s, _GP_, Evaluate, arg); /* Initial evaluation */
	tmpTree = (Node **)malloc(s->m * sizeof(Node *));
	ShowSearchSpace(s, _GP_);

	for (t = 1; t <= s->iterations; t++)
	{
		fprintf(stderr, "\nRunning iteration %d/%d ... ", t, s->iterations);

		for (i = 0; i < s->m; i++)
			tmpTree[i] = CopyTree(s->T[i]);

		/* Calcultating the number of individuals to be reproducted */
		n_reproduction = round(s->m * s->pReproduction);
		reproduction = RouletteSelection(s, n_reproduction);

		/* Calcultating the number of individuals to be mutated */
		n_mutation = round(s->m * s->pMutation);
		mutation = RouletteSelection(s, n_mutation);

		/* Calcultating the number of individuals to perform the crossover */
		n_crossover = round(s->m * s->pCrossover);
		crossover = RouletteSelection(s, n_crossover);

		/* It performs the reproduction */
		for (i = 0; i < n_reproduction; i++)
		{
			DestroyTree(&s->T[i]);
			s->T[i] = CopyTree(tmpTree[reproduction[i]]);
		}

		/* It performs the mutation */
		z = 0;
		for (j = n_reproduction; j < n_reproduction + n_mutation; j++)
		{
			ctr = 1;
			do
			{
				father_cross_point = GenerateUniformRandomNumber(0, n_reproduction);
				mother_crosspoint = GenerateUniformRandomNumber(0, n_reproduction);
				ctr++;
			} while ((father_cross_point == mother_crosspoint) && (ctr <= 10));

			fprintf(stderr, "%d %d %d\n", n_reproduction, n_mutation, n_crossover);

			aux = SGME(s, tmpTree[crossover[father_cross_point]], tmpTree[crossover[mother_crosspoint]]);
			DestroyTree(&s->T[j]);
			s->T[j] = CopyTree(aux);
			DestroyTree(&aux);
			z++;
		}

		/* It performs the crossover */
		z = 0;
		for (j = n_reproduction + n_mutation; j < n_reproduction + n_mutation + n_crossover; j++)
		{
			ctr = 1;
			do
			{
				father_cross_point = GenerateUniformRandomNumber(0, n_crossover);
				mother_crosspoint = GenerateUniformRandomNumber(0, n_crossover);
				ctr++;
			} while ((father_cross_point == mother_crosspoint) && (ctr <= 10));

			aux = SGXE(s, tmpTree[crossover[father_cross_point]], tmpTree[crossover[mother_crosspoint]]);
			DestroyTree(&(s->T[j]));
			s->T[j] = CopyTree(aux);
			DestroyTree(&aux);
			z++;
		}

		free(reproduction);
		free(mutation);
		free(crossover);

		for (i = 0; i < s->m; i++)
			DestroyTree(&tmpTree[i]);

		EvaluateSearchSpace(s, _GP_, Evaluate, arg);

		fprintf(stderr, "OK (minimum fitness value %lf) -> Best tree: %d.", s->gfit, s->best);
		va_copy(arg, argtmp);
	}

	free(tmpTree);
	va_end(arg);
}
/*************************/

/* It executes the Genetic Programming for function minimization
Parameters:
s: search space
Evaluate: pointer to the function used to evaluate particles
arg: list of additional arguments */
void runGP(SearchSpace *s, prtFun Evaluate, ...)
{
	va_list arg, argtmp;
	int t, i, j, z, n_reproduction, n_mutation, n_crossover;
	int *reproduction = NULL, *mutation = NULL, *crossover = NULL;
	int father_cross_point, mother_crosspoint, ctr;
	double beta, prob;
	Node **tmpTree = NULL, **aux = NULL;

	va_start(arg, Evaluate);
	va_copy(argtmp, arg);

	if (!s)
	{
		fprintf(stderr, "\nSearch space not allocated @runGP.\n");
		exit(-1);
	}

	EvaluateSearchSpace(s, _GP_, Evaluate, arg); /* Initial evaluation */
	tmpTree = (Node **)malloc(s->m * sizeof(Node *));
	ShowSearchSpace(s, _GP_);

	for (t = 1; t <= s->iterations; t++)
	{
		fprintf(stderr, "\nRunning iteration %d/%d ... ", t, s->iterations);

		for (i = 0; i < s->m; i++)
			tmpTree[i] = CopyTree(s->T[i]);

		/* Calcultating the number of individuals to be reproducted */
		n_reproduction = round(s->m * s->pReproduction);
		reproduction = RouletteSelection(s, n_reproduction);

		/* Calcultating the number of individuals to be mutated */
		n_mutation = round(s->m * s->pMutation);
		mutation = RouletteSelection(s, n_mutation);

		/* Calcultating the number of individuals to perform the crossover */
		n_crossover = s->m - (n_reproduction + n_mutation);
		crossover = RouletteSelection(s, n_crossover);

		/* It performs the reproduction */
		for (i = 0; i < n_reproduction; i++)
		{
			DestroyTree(&s->T[i]);
			s->T[i] = CopyTree(tmpTree[reproduction[i]]);
		}

		/* It performs the mutation */
		z = 0;
		for (j = n_reproduction; j < n_reproduction + n_mutation; j++)
		{
			DestroyTree(&s->T[j]);
			if (getSizeTree(tmpTree[mutation[z]]) > 1)
				s->T[j] = Mutation(s, tmpTree[mutation[z]], PROB_MUTATION_FUNCTION);
			else
				s->T[j] = GROW(s, s->min_depth, s->max_depth);
			z++;
		}

		/* It performs the crossover */
		z = 0;
		for (j = n_reproduction + n_mutation; j < n_reproduction + n_mutation + n_crossover; j += 2)
		{
			ctr = 1;
			do
			{
				father_cross_point = GenerateUniformRandomNumber(0, n_crossover);
				mother_crosspoint = GenerateUniformRandomNumber(0, n_crossover);
				ctr++;
			} while ((father_cross_point == mother_crosspoint) && (ctr <= 10));

			if ((getSizeTree(tmpTree[crossover[father_cross_point]]) > 1) && (getSizeTree(tmpTree[crossover[mother_crosspoint]]) > 1))
			{
				aux = Crossover(tmpTree[crossover[father_cross_point]],
								tmpTree[crossover[mother_crosspoint]], PROB_CROSSOVER_FUNCTION);
				DestroyTree(&(s->T[j]));
				s->T[j] = CopyTree(aux[0]);
				if (j + 1 < n_reproduction + n_mutation + n_crossover)
				{
					DestroyTree(&(s->T[j + 1]));
					s->T[j + 1] = CopyTree(aux[1]); /* in case of an odd number of samples to do crossover */
				}
				DestroyTree(&aux[0]);
				DestroyTree(&aux[1]);
				free(aux);
			}
			else
			{
				DestroyTree(&(s->T[j]));
				s->T[j] = CopyTree(tmpTree[crossover[father_cross_point]]);
				if (j + 1 < n_reproduction + n_mutation + n_crossover)
				{
					DestroyTree(&(s->T[j + 1]));
					s->T[j + 1] = CopyTree(tmpTree[crossover[mother_crosspoint]]); /* in case of an odd number of samples to do crossover */
				}
			}
			z++;
		}

		free(reproduction);
		free(mutation);
		free(crossover);

		for (i = 0; i < s->m; i++)
			DestroyTree(&tmpTree[i]);

		EvaluateSearchSpace(s, _GP_, Evaluate, arg);

		fprintf(stderr, "OK (minimum fitness value %lf) -> Best tree: %d.", s->gfit, s->best);
		va_copy(arg, argtmp);
	}

	free(tmpTree);
	va_end(arg);
}
/*************************/

/* It executes the Tensor-based Genetic Programming for function minimization
Parameters:
s: search space
Evaluate: pointer to the function used to evaluate particles
arg: list of additional arguments */
void runTGP(SearchSpace *s, prtFun Evaluate, ...){
	va_list arg, argtmp;
	int t, i, j, z, n_reproduction, n_mutation, n_crossover;
	int *reproduction = NULL, *mutation = NULL, *crossover = NULL;
	int father_cross_point, mother_crosspoint, ctr;
	double beta, prob;
	Node **tmpTree = NULL, **aux = NULL;

	va_start(arg, Evaluate);
	va_copy(argtmp, arg);

	if (!s){
		fprintf(stderr, "\nSearch space not allocated @runTGP.\n");
		exit(-1);
	}

	EvaluateSearchSpace(s, _TGP_, Evaluate, arg); /* Initial evaluation */
	tmpTree = (Node **)malloc(s->m * sizeof(Node *));

	for (t = 1; t <= s->iterations; t++){
		fprintf(stderr, "\nRunning iteration %d/%d ... ", t, s->iterations);

		for (i = 0; i < s->m; i++)
			tmpTree[i] = CopyTree(s->T[i]);

		/* Calcultating the number of individuals to be reproducted */
		n_reproduction = round(s->m * s->pReproduction);
		reproduction = RouletteSelection(s, n_reproduction);

		/* Calcultating the number of individuals to be mutated */
		n_mutation = round(s->m * s->pMutation);
		mutation = RouletteSelection(s, n_mutation);

		/* Calcultating the number of individuals to perform the crossover */
		n_crossover = s->m - (n_reproduction + n_mutation);
		crossover = RouletteSelection(s, n_crossover);

		/* It performs the reproduction */
		for (i = 0; i < n_reproduction; i++){
			DestroyTree(&s->T[i]);
			s->T[i] = CopyTree(tmpTree[reproduction[i]]);
		}

		/* It performs the mutation */
		z = 0;
		for (j = n_reproduction; j < n_reproduction + n_mutation; j++){
			DestroyTree(&s->T[j]);
			if (getSizeTree(tmpTree[mutation[z]]) > 1)
				s->T[j] = Mutation(s, tmpTree[mutation[z]], PROB_MUTATION_FUNCTION);
			else
				s->T[j] = GROW(s, s->min_depth, s->max_depth);
			z++;
		}

		/* It performs the crossover */
		z = 0;
		for (j = n_reproduction + n_mutation; j < n_reproduction + n_mutation + n_crossover; j += 2){
			ctr = 1;
			do{
				father_cross_point = GenerateUniformRandomNumber(0, n_crossover);
				mother_crosspoint = GenerateUniformRandomNumber(0, n_crossover);
				ctr++;
			} while ((father_cross_point == mother_crosspoint) && (ctr <= 10));

			if ((getSizeTree(tmpTree[crossover[father_cross_point]]) > 1) && (getSizeTree(tmpTree[crossover[mother_crosspoint]]) > 1)){
				aux = Crossover(tmpTree[crossover[father_cross_point]],
								tmpTree[crossover[mother_crosspoint]], PROB_CROSSOVER_FUNCTION);
				DestroyTree(&(s->T[j]));
				s->T[j] = CopyTree(aux[0]);
				if (j + 1 < n_reproduction + n_mutation + n_crossover)
				{
					DestroyTree(&(s->T[j + 1]));
					s->T[j + 1] = CopyTree(aux[1]); /* in case of an odd number of samples to do crossover */
				}
				DestroyTree(&aux[0]);
				DestroyTree(&aux[1]);
				free(aux);
			}
			else{
				DestroyTree(&(s->T[j]));
				s->T[j] = CopyTree(tmpTree[crossover[father_cross_point]]);
				if (j + 1 < n_reproduction + n_mutation + n_crossover)
				{
					DestroyTree(&(s->T[j + 1]));
					s->T[j + 1] = CopyTree(tmpTree[crossover[mother_crosspoint]]); /* in case of an odd number of samples to do crossover */
				}
			}
			z++;
		}

		free(reproduction);
		free(mutation);
		free(crossover);

		for (i = 0; i < s->m; i++)
			DestroyTree(&tmpTree[i]);

		EvaluateSearchSpace(s, _TGP_, Evaluate, arg);

		fprintf(stderr, "OK (minimum fitness value %lf) -> Best tree: %d.", s->gfit, s->best);
		va_copy(arg, argtmp);
	}

	free(tmpTree);
	va_end(arg);
}
/*************************/

redpajama_set_name: RedPajamaGithub


text:
'''YABFD is Yet Another Brute Force Detector.

Copyright (c) 2008, 2009 Hraban Luyat

Search logfiles for hosts that are brute-forcing passwords on a server through
a daemon that allows remote login.

Inspired by Daniel Drown's SBFD: <http://dan.drown.org/sbfd/>.

'''
import collections
import ConfigParser
import csv
import datetime
import itertools
import logging
import optparse
import os
import re
import shutil
import sys
try:
    import threading as _threading
except ImportError:
    import dummy_threading as _threading

LOGFORMAT = '%(asctime)s %(levelname)s: %(message)s'
LOGDATEFMT = None

_logger = logging.getLogger('yabfd')

class _BacklogError(StandardError):
    pass

class Blacklist(object):
    '''Track failed login hits from hosts and ban them when appropriate.

    Ignore is a whitelist file, bantime is the number of days violators will be
    banned, threshold is the number of failed login attempts after which a host
    will be banned, backlog is a logfile that yabfd uses internally to keep
    track of when hosts must be unbanned.

    '''
    def __init__(self, backlog, ignore=None, bantime=7, threshold=10):
        self.backlog = backlog
        if ignore is not None:
            self.ignores = parse_whitelist(ignore)
        else:
            self.ignores = frozenset()
        _logger.debug('Whitelist contains %d hosts.', len(self.ignores))
        self.hits = collections.defaultdict(lambda: [0,
                                        datetime.date.fromtimestamp(0)])
        self.threshold = threshold
        self.bantime = datetime.timedelta(bantime)
        # Acquired once by self.done().
        self._done_lock = _threading.Lock()

    def __iter__(self):
        # Just noting: this is not thread-safe. One thread acquires the lock for
        # testing, another thread tries the same thing at the same time but sees
        # it is unlocked and passes the conditional, the former thread now
        # releases the lock and raises the exception, but the second thread is
        # already writing to the backlog. Would require a lock-testing-lock :)
        if self._done_lock.acquire(False):
            self._done_lock.release()
            raise RuntimeError, "Call a Blacklist's done() before __iter__()."
        blw = csv.writer(open(self.backlog, 'wb'))
        for host, (numhits, date) in self.hits.iteritems():
            tilld = date + self.bantime
            # This number of failed login attempts is allowed:
            if (numhits >= self.threshold and
                    # Most recent offense makes banning worthwile:
                    tilld > datetime.date.today() # profile. bottleneck? cache!
                    ):
                blw.writerow((host, tilld.isoformat()))
                yield (host, tilld)

    def _read_old_backlog(self):
        '''Read the old bans and reapply them if appropriate.

        If an error occurs somewhere in the middle the data that was
        succesfully read is not discarded. Reading is, at this point, stopped,
        though, and a _BacklogError is raised.

        If the file does not exist no exception is raised. If it does exist but
        reading it fails a _BacklogError is raised.

        '''
        try:
            r = csv.reader(open(self.backlog, 'rb'))
        except IOError, e:
            if not os.path.exists(self.backlog):
                # File did not exist yet, do not propagate exception.
                return
            else:
                raise _BacklogError('I/O Error: %s, continuing.' % e)
        try:
            for (host, till) in r:
                # Parse the ISO 8601 format into a datetime.date object.
                tilld = datetime.datetime.strptime(till, '%Y-%m-%d').date()
                # Only overwrite latest offense read if backlog has even more
                # recent data.
                date = max(tilld - self.bantime, self.hits[host][1])
                self.hits[host] = [self.threshold, date]
        except ValueError, e:
            raise _BacklogError('Corrupt backlog (line %d: %s), continuing '
                    'without reading the rest.' % (r.line_num, e))
        else:
            _logger.info('Read %d hosts from backlog.', r.line_num)

    def done(self):
        '''Called when all hits are recorded.'''
        if not self._done_lock.acquire(False):
            raise RuntimeError, 'Blacklist.done() can only be called once.'
        # Read all current bans.
        try:
            self._read_old_backlog()
        except _BacklogError, e:
            _logger.error('Reading backlog failed: %s', e)
            _logger.warning('Saving old (corrupt) backlog as "%s.corrupt"',
                    self.backlog)
            shutil.move(self.backlog, self.backlog + '.corrupt')
        # Remove all whitelisted hosts from the hitlog.
        for ignore in self.ignores:
            self.hits.pop(ignore, None)
        del self.ignores
        _logger.debug('Blacklist is done processing.')

    def record(self, date, host, weight=1):
        '''A failed login attempt from this host has been found.

        The weight operand is a multiplier for the encountered hit. It allows
        the caller to make some hits more severe than others without calling
        record() repeatedly.

        '''
        h = self.hits[host]
        h[0] += weight
        h[1] = max(h[1], date)

class Scanner(object):
    '''Handles the scanning and parsing of a logfile to extract bad hosts.'''
    def __init__(self, conffile):
        self._parsers = []
        self._printers = []
        try:
            self._read_config(conffile)
        except Exception, e:
            _logger.error('Reading configuration at %r failed. Details: %r',
                    conffile, e)
            # Continue as a generic error (hide underlying details from error
            # reporting higher up).
            raise RuntimeError, ('Scanner had trouble reading the configuration'
                                ' file.')
        else:
            _logger.debug('Scanner read configuration at %r.', conffile)

    def _read_config(self, conffile):
        config = ConfigParser.SafeConfigParser()
        # Using open() manually here will cause an exception if the file can not
        # be opened. This is wanted, as opposed to config.read's (not readfp())
        # default behaviour of silently ignoring files that can not be opened.
        config.readfp(open(conffile))
        for sec in config.sections():
            if sec.startswith('parser_'):
                ptype = config.get(sec, 'parser_type')
                config.remove_option(sec, 'parser_type')
                kwargs = dict(config.items(sec))
                kwargs['name'] = sec[7:]
                self.add_parser(ptype, kwargs)
            elif sec.startswith('printer_'):
                ptype = config.get(sec, 'printer_type')
                config.remove_option(sec, 'printer_type')
                kwargs = dict(config.items(sec))
                kwargs['name'] = sec[8:]
                self.add_printer(ptype, kwargs)
        kwargs = dict(config.items('blacklist'))
        # Transform all integer values to `int`s.
        for opt in ('bantime', 'threshold'):
            if opt in kwargs:
                try:
                    kwargs[opt] = config.getint('blacklist', opt)
                except ValueError:
                    _logger.error('Invalid %s: %r.', opt, kwargs[opt])
                    raise
        self._bl = Blacklist(**kwargs)

    def add_parser(self, parsertype, kwargs):
        p = getattr(__import__('parsers.' + parsertype),
                parsertype).Parser(**kwargs)
        self._parsers.append(p)

    def add_printer(self, printertype, kwargs):
        p = getattr(__import__('printers.' + printertype),
                printertype).Printer(**kwargs)
        self._printers.append(p)

    def scan(self):
        '''Parse and process all logfiles.

        If an error occurs with one of the printers, it is logged, then ignored
        while the other printers try to finish and finally re-raised at the end.

        '''
        error = None
        for p in self._parsers:
            for hit in p.parse():
                self._bl.record(*hit)
        self._bl.done()
        # Apply all output handlers to every blacklist entry.
        for entry in self._bl:
            _logger.info('Banning %s until %s.', entry[0], entry[1])
            for printer in self._printers:
                try:
                    printer.print_(*entry)
                except Exception, e:
                    _logger.error('Printer %s could not print %r. Details: %r',
                            printer, entry, e)
                    error = 'One or more printjobs failed.'
        # Clean up printers (as much as possible).
        for printer in self._printers:
            try:
                printer.close()
            except Exception, e:
                _logger.error('Closing printer %s failed. Details: %r', printer,
                        e)
                # Yes, this will override the other error, but the logs are OK.
                error = 'One or more printers did not close properly.'
        del self._printers
        if error is not None:
            raise RuntimeError, error

def parse_whitelist(fname):
    '''Parse a white-list (ignore) file.

    The syntax for this file is: one host per line, empty lines or lines
    starting with a hash (#) are ignored. The file must be encoded in ASCII.

    '''
    try:
        f = open(fname, 'r')
    except IOError, e:
        _logger.warning('Unable to open the whitelist (%s), continuing.', e)
        return frozenset()
    return frozenset(e for e in (l.strip() for l in f if l.strip()) if not
            e.startswith('#'))

def main():
    p = optparse.OptionParser()
    old_help = p.print_help
    def my_help():
        '''Print introduction before help message.'''
        print __doc__
        old_help()
    p.print_help = my_help
    p.set_defaults(file='/usr/local/etc/yabfd.conf', loglevel=logging.WARNING)
    p.add_option('-f', '--file', help='use specified configuration file '
            '[default: %default]')
    p.add_option('-q', '--quiet', action='store_const', const=logging.ERROR,
            dest='loglevel', help='only report critical errors')
    p.add_option('-v', '--verbose', action='store_const', const=logging.INFO,
            dest='loglevel', help='print informational messages')
    p.add_option('-d', '--debug', action='store_const', const=logging.DEBUG,
            dest='loglevel', help='print debugging info')
    (options, args) = p.parse_args()
    p.destroy()
    logging.basicConfig(level=options.loglevel, format=LOGFORMAT,
            datefmt=LOGDATEFMT)
    if options.loglevel <= logging.INFO:
        print >> sys.stderr, __doc__
    try:
        s = Scanner(options.file)
    except Exception, e:
        _logger.error('Creating the scanner failed, aborting. Details: %r', e)
        sys.exit('Aborting operation.')
    try:
        s.scan()
    except Exception, e:
        _logger.error('Scanner crashed half-way through. Details: %r', e)
        sys.exit('Halting operation.')

if __name__ == '__main__':
    main()


text:
// See http://www.boost.org/libs/iostreams for documentation.

#ifndef BOOST_IOSTREAMS_DETAIL_FSTREAM_HPP_INCLUDED
#define BOOST_IOSTREAMS_DETAIL_FSTREAM_HPP_INCLUDED

#if defined(_MSC_VER)
# pragma once
#endif

#include <boost/iostreams/detail/config/wide_streams.hpp>
#ifndef BOOST_IOSTREAMS_NO_STREAM_TEMPLATES
# include <fstream>
#else
# include <fstream.h>
#endif

#ifndef BOOST_IOSTREAMS_NO_STREAM_TEMPLATES
# define BOOST_IOSTREAMS_BASIC_IFSTREAM(Ch, Tr) std::basic_ifstream<Ch, Tr>
# define BOOST_IOSTREAMS_BASIC_OFSTREAM(Ch, Tr) std::basic_ofstream<Ch, Tr>
# define BOOST_IOSTREAMS_BASIC_FSTREAM(Ch, Tr) std::basic_fstream<Ch, Tr>
# define BOOST_IOSTREAMS_BASIC_FILEBUF(Ch) std::basic_filebuf<Ch>
#else
# define BOOST_IOSTREAMS_BASIC_IFSTREAM(Ch, Tr) std::ifstream
# define BOOST_IOSTREAMS_BASIC_OFSTREAM(Ch, Tr) std::ofstream
# define BOOST_IOSTREAMS_BASIC_FILEBUF(Ch) std::filebuf
#endif

#endif // #ifndef BOOST_IOSTREAMS_DETAIL_FSTREAM_HPP_INCLUDED


text:
import datetime
from decimal import Decimal

from constance.admin import get_values
from constance.management.commands.constance import _set_constance_value
from django.core.exceptions import ValidationError
from django.test import TestCase

class UtilsTestCase(TestCase):

    def test_set_value_validation(self):
        self.assertRaisesMessage(ValidationError, 'Enter a whole number.', _set_constance_value, 'INT_VALUE', 'foo')
        self.assertRaisesMessage(ValidationError, 'Enter a valid email address.', _set_constance_value, 'EMAIL_VALUE', 'not a valid email')
        self.assertRaisesMessage(ValidationError, 'Enter a valid date.', _set_constance_value, 'DATETIME_VALUE', ('2000-00-00', '99:99:99',))
        self.assertRaisesMessage(ValidationError, 'Enter a valid time.', _set_constance_value, 'DATETIME_VALUE', ('2016-01-01', '99:99:99',))

    def test_get_values(self):

        self.assertEqual(get_values(), {
            'FLOAT_VALUE': 3.1415926536,
            'BOOL_VALUE': True,
            'EMAIL_VALUE': 'test@example.com',
            'INT_VALUE': 1,
            'CHOICE_VALUE': 'yes',
            'TIME_VALUE': datetime.time(23, 59, 59),
            'DATE_VALUE': datetime.date(2010, 12, 24),
            'TIMEDELTA_VALUE': datetime.timedelta(days=1, hours=2, minutes=3),
            'LINEBREAK_VALUE': 'Spam spam',
            'DECIMAL_VALUE': Decimal('0.1'),
            'STRING_VALUE': 'Hello world',
            'DATETIME_VALUE': datetime.datetime(2010, 8, 23, 11, 29, 24),
        })


text:
import urllib.request
import os
import time
from bs4 import BeautifulSoup as bs
import re
import base64
import json

# user_ids = ['512194ec7d34941827001340', '526258e2c58a878d061e30cf']
user_ids = ['512194ec7d34941827001340']

USER_URL = 'http://www.weipai.cn/user/{user_id}'

VIDEOS_URL = 'http://www.weipai.cn/videos/{user_id}'

VIDEO_URL = 'http://www.weipai.cn/video/{video_id}'

VIDEO_INFO_URL = 'http://www.weipai.cn/video/play/id/{video_id}/type/theater/source/web?_={timestamp}'

MORE_VIDEOS = 'http://www.weipai.cn/user/moreOwnVideos/uid/{user_id}?page={page}'

REG = re.compile(r"s=(.*?)',")
REG1 = re.compile(r"p=(.*?)&")

headers = {
	'Host': 'www.weipai.cn',
	# 'Referer': 'http://www.weipai.cn/user/526258e2c58a878d061e30cf',
	# 'Referer': 'http://www.weipai.cn/videos/512194ec7d34941827001340',
	'Referer': 'http://www.weipai.cn/',
	'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36',
	# 'Cookie': 'weipai_token=mkom5ducaibsqdrs687qcu5tf4'
	# 'Cookie': 'weipai_token=0cp1ddfbei8k2l8ev2cf35olb7'
	'Cookie': 'weipai_token=0cp1ddfbei8k2l8ev2cf35olb7'
}

def analysis_video_list_info(bs_doc):
	video_list_doc = bs_doc.select('#container_div #full_column_div .wf_container .video')
	videos = []
	if len(video_list_doc) > 0:
		for video_info_doc in video_list_doc:
			id = video_info_doc.get('id')
			day = video_info_doc.select('.wrap .time .day')[0].text
			date = video_info_doc.select('.wrap .time .date')[0].contents[2]
			snaps = video_info_doc.select('.wrap .snaps .imgs img')[0].get('src')
			length = video_info_doc.select('.wrap .snaps .imgs .length')[0].text
			video_link = video_info_doc.select('.wrap .snaps .video_link')[0].get('href')
			like = video_info_doc.select('.wrap .details .details-like')[0].text
			view = video_info_doc.select('.wrap .details .details-view')[0].text
			comment = video_info_doc.select('.wrap .details .details-comment')[0].text
			desc = None
			desc_doc = video_info_doc.select('.wrap .desc')
			if len(desc_doc) > 0:
				desc = desc_doc[0].text
			date = date + '-' + day
			like = int(like)
			view = int(view)
			comment = int(comment)
			videos.append({
				'id': id,
				'date': date,
				'snaps': snaps,
				'length': length,
				# 'video_link': video_link,
				'like_count': like,
				'view_count': view,
				'comment_count': comment,
				'desc': desc
			})
	return videos

def get_user_info(id):
	user_info = {}
	req = urllib.request.Request(USER_URL.format(user_id = id), headers = headers)
	resp = urllib.request.urlopen(req)
	html_doc = resp.read().decode()
	bs_doc = bs(html_doc)
	user_info_box = bs_doc.select('#container_div #full_column_div .wf_container .info')
	if len(user_info_box) > 0:
		user_info_box = user_info_box[0]
		face = None
		face_doc = user_info_box.select('.wrap .imgs .face img')
		if len(face_doc) > 0:
			face = face_doc[0].get('src')
		name = user_info_box.select('.wrap .user .name')[0].text
		sex = 'female' if 'female' in user_info_box.select('.sex')[0].get('class') else 'male'
		follows = user_info_box.select('.wrap .follows span')[0].text
		fans = user_info_box.select('.wrap .fans span')[0].text
		videos = user_info_box.select('.wrap .videos span')[0].text
		follows = int(follows)
		fans = int(fans)
		videos = int(videos)
		# face_thumbnail = face.replace('/180/', '/50/')
		user_info = {
			'face': face,
			'name': name,
			'sex': sex,
			'follows_count': follows,
			'fans_count': fans,
			'videos_count': videos,
			'id': id,
			# 'face_thumbnail': face_thumbnail,
			'videos': analysis_video_list_info(bs_doc)
		}
	return user_info

def get_videos_info(id):
	user_info = {}
	req = urllib.request.Request(VIDEOS_URL.format(user_id = id), headers = headers)
	resp = urllib.request.urlopen(req)
	html_doc = resp.read().decode()
	bs_doc = bs(html_doc)
	user_info_box = bs_doc.select('#container_div #full_column_div .wf_container .info')
	if len(user_info_box) > 0:
		user_info_box = user_info_box[0]
		face = None
		face_doc = user_info_box.select('.wrap .imgs .face img')
		if len(face_doc) > 0:
			face = face_doc[0].get('src')
		name = user_info_box.select('.wrap .user .name')[0].text
		sex = 'female' if 'female' in user_info_box.select('.sex')[0].get('class') else 'male'
		follows = user_info_box.select('.wrap .follows span')[0].text
		fans = user_info_box.select('.wrap .fans span')[0].text
		videos = user_info_box.select('.wrap .videos span')[0].text
		follows = int(follows)
		fans = int(fans)
		videos = int(videos)
		# face_thumbnail = face.replace('/180/', '/50/')
		user_info = {
			'face': face,
			'name': name,
			'sex': sex,
			'follows_count': follows,
			'fans_count': fans,
			'videos_count': videos,
			'id': id,
			# 'face_thumbnail': face_thumbnail,
			'videos': analysis_video_list_info(bs_doc)
		}
	return user_info

def get_video_info(id):
	user_info = {}
	video_info = {}
	req = urllib.request.Request(VIDEO_URL.format(video_id = id), headers = headers)
	resp = urllib.request.urlopen(req)
	html_doc = resp.read().decode()
	bs_doc = bs(html_doc)
	user_info_box = bs_doc.select('.theater .theater-wrapper .left_div .info')
	if len(user_info_box) > 0:
		user_info_box = user_info_box[0]
		face = None
		face_doc = user_info_box.select('.wrap .imgs .face img')
		if len(face_doc) > 0:
			face = face_doc[0].get('src')
		name = user_info_box.select('.wrap .user .name')[0].text
		sex = 'female' if 'female' in user_info_box.select('.sex')[0].get('class') else 'male'
		follows = user_info_box.select('.wrap .follows span')[0].text
		fans = user_info_box.select('.wrap .fans span')[0].text
		videos = user_info_box.select('.wrap .videos span')[0].text
		follows = int(follows)
		fans = int(fans)
		videos = int(videos)
		# face_thumbnail = face.replace('/180/', '/50/')
		user_info = {
			'face': face,
			'name': name,
			'sex': sex,
			'follows_count': follows,
			'fans_count': fans,
			'videos_count': videos
			# 'id': id,
			# 'face_thumbnail': face_thumbnail
		}
	video_info_box = bs_doc.select('.theater .theater-stage .theater-wrapper #videos_div')
	if len(video_info_box) > 0:
		video_info_box = video_info_box[0]
		snaps = video_info_box.select('.video .video_player .snaps img')[0].get('src')
		day = video_info_box.select('.video .time .day')[0].text
		date = video_info_box.select('.video .time .date')[0].contents[2]
		length = video_info_box.select('.video .video_player .snaps .length')[0].text
		video_title = video_info_box.select('.video_info .video_title')[0].text
		video_detail = video_info_box.select('.video_info .video_details .video_detail')[0].text
		view = video_info_box.select('.video_info .video_details .details-view')[0].text
		like = video_info_box.select('.video_info .video_details .details-like')[0].text
		comment = video_info_box.select('.video .video_buttons .comment span')[0].text.replace('评论(', '').replace(')', '')
		date = date + '-' + day
		view = int(view)
		like = int(like)
		comment = int(comment)
		video_time = video_detail.split(' ')[1]
		video_info = {
			'id': id,
			'snaps': snaps,
			'date': date,
			'length': length,
			'like_count': like,
			'view_count': view,
			'comment_count': comment,
			'desc': video_title,
			'user': user_info,
			'time': video_time
		}
	return video_info

def get_video_url(id):
	video_url = None
	req = urllib.request.Request(VIDEO_INFO_URL.format(video_id = id, timestamp = int(time.time()*1000)), headers = headers)
	resp = urllib.request.urlopen(req)
	video_info = resp.read().decode()
	m = REG.search(video_info)
	if m:
		video_url_encrypted = m.group(1)
		video_params = base64.b64decode(video_url_encrypted).decode()
		m1 = REG1.search(video_params)
		if m1:
			video_url = m1.group(1)
			return video_url
	return video_url

def get_more_videos(id, page):
	videos = []
	req = urllib.request.Request(MORE_VIDEOS.format(user_id = id, page = page), headers = headers)
	resp = urllib.request.urlopen(req)
	html_doc = resp.read().decode()
	bs_doc = bs(html_doc)
	videos_doc = bs_doc.contents
	if len(bs_doc.contents) == 1 and bs_doc.contents[0].name == 'html':
		videos_doc = bs_doc.contents[0].select('.video')
	if len(videos_doc) > 0:
		for video_doc in videos_doc:
			id = video_doc.get('id')
			day = video_doc.select('.wrap .time .day')[0].text
			date = video_doc.select('.wrap .time .date')[0].contents[2]
			snaps = video_doc.select('.wrap .snaps .imgs img')[0].get('src')
			length = video_doc.select('.wrap .snaps .imgs .length')[0].text
			like = video_doc.select('.wrap .details .details-like')[0].text
			view = video_doc.select('.wrap .details .details-view')[0].text
			comment = video_doc.select('.wrap .details .details-comment')[0].text
			desc = None
			desc_doc = video_doc.select('.wrap .desc')
			if len(desc_doc) > 0:
				desc = desc_doc[0].text
			video_link = video_doc.select('.wrap .video_link')[0].get('href')
			date = date + '-' + day
			like = int(like)
			view = int(view)
			comment = int(comment)
			videos.append({
				'id': id,
				'snaps': snaps,
				'date': date,
				'length': length,
				'like_count': like,
				'view_count': view,
				'comment_count': comment,
				'desc': desc
			})
	return videos

def main():
	#print(get_video_url('5322d4beebeddbdd3d8b45a3'))
	#for id in user_ids:
	#	print(get_videos_info(id)['videos'][0])
	#	print(get_user_info(id)['videos'][0])
	print(get_more_videos('512194ec7d34941827001340', 1), open('c:/more_videos.txt', 'w'))
	print('done!')

if __name__ == '__main__':
	main()


text:
<?php

/**
 * Include required classes
 */
require_once 'LoginController.php';

/**
 * Dashboard controller
 * @name controller_dashboard
 */
class controller_projects extends LoginController
{
	/**#@+
	 * Permission constants
	 */
	const PERM_PROJECT_ADD	= 0x0C000000;
	const PERM_PROJECT_EDIT	= 0x04000000;
	/**#@-*/

	/**
	 * Action
	 * Shows all projects the user has access to
	 * @name actionDefault
	 * @access public
	 * @return void
	 */
	public function action()
	{
		// Get a list of all the projects the user has access to
		$aProjects	= $this->oUser->getProjects();

		// Pass them to the view
		$this->addViewVariable('projects', $aProjects);

		// Find out if the user can add or edit projects
		$this->addViewVariable('userCanAdd', (intval($this->oUser->getField('permissions')) & self::PERM_PROJECT_ADD) == self::PERM_PROJECT_ADD);
		$this->addViewVariable('userCanEdit', (intval($this->oUser->getField('permissions')) & self::PERM_PROJECT_EDIT) == self::PERM_PROJECT_EDIT);
	}

	/**
	 * Action Add
	 * Displays a form for creating a new project
	 * @name actionAdd
	 * @access public
	 * @return void
	 */
	public function actionAdd()
	{
		// Set the title
		$this->addViewVariable('title', 'Add new project - OuroborosTask');

		// Get the list of priorities and task types for the view
		$this->addViewVariable('priorities', table_Priority::all(array('return' => 'raw')));
		$this->addViewVariable('types', table_Type::all(array('return' => 'raw')));

		// Add page specific javascript
		$this->addJavaScript('jquery.customFormSelect.1.0.min.js');
		$this->addJavaScript('projects.js');
	}

	/**
	 * Action Add Submit
	 * Takes the form data and creates a new project record from it
	 * @name actionAddSubmit
	 * @access public
	 * @return void
	 */
	public function actionAddSubmit()
	{
		// If there's no priorities set
		if(!isset($_POST['priorities'])) {
			return $this->redirect('/projects/Add/', array('errorMsg' => 'Must specify at least one priority per project.'));
		}

		// If there's no types set
		if(!isset($_POST['types'])) {
			return $this->redirect('/projects/Add/', array('errorMsg' => 'Must specify at least one type per project.'));
		}

		// Add the creator of the project and the current date
		$_POST['project']['creator']	= $this->oUser->getField('id');
		$_POST['project']['created']	= strftime('%Y-%m-%d %H:%M:%S');

		// Create a new Project from the form data
		$oProject	= new table_Project($_POST['project']);

		// Insert it into the DB
		$oProject->insert();

		// Append the lists of priorities and types
		table_ProjectsPriorities::append($oProject->getField('id'), $_POST['priorities']);
		table_ProjectsTypes::append($oProject->getField('id'), $_POST['types']);

		// Create the user rights record
		table_UsersProjectAccess::append(
			$this->oUser->getField('id'),
			$oProject->getField('id'),
			array('permission' => table_UsersProjectAccess::PERMISSION_OWNER)
		);

		// Clear the user's project cache
		$this->oUser->clearProjects();

		// Go to the projects page
		return $this->redirect('/projects/', array('successMsg' => 'Successfully created new project ' . $_POST['project']['name']));
	}

	/**
	 * Action Edit
	 * Displays the project's settings in a form so they can be editted
	 * @name actionEdit
	 * @access public
	 * @return void
	 */
	public function actionEdit()
	{
		// If we don't have an ID and there's a value in '?'
		if(!isset($_REQUEST['id']) && isset($_REQUEST['?'])) {
			$_REQUEST['id']	= $_REQUEST['?'][0];
		}

		// Make sure the ID is there
		if(!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id']) || 0 > $_REQUEST['id']) {
			return $this->redirect('/projects/', array('errorMsg' => 'Must specify valid Project ID in order to edit it.'));
		}

		// Find the project as a raw record
		$aProject	= table_Project::find($_REQUEST['id'], array('return' => 'raw'));

		// If it's not found
		if(is_null($aProject)) {
			return $this->redirect('/projects/', array('errorMsg' => 'No project found with the ID ' . $_POST['id']));
		}

		// Get the list of priorities associated with the project
		$aProject['priorities']	= table_ProjectsPriorities::search($aProject['id']);
		$aProject['types']		= table_ProjectsTypes::search($aProject['id']);

		// Pass the project to the view
		$this->addViewVariable('project', $aProject);

		// Set the title of the page
		$this->addViewVariable('title', 'Edit project ' . $aProject['name'] . ' - OuroborosTask');

		// Get the global list of priorities and task types for the view
		$this->addViewVariable('priorities', table_Priority::all(array('return' => 'raw')));
		$this->addViewVariable('types', table_Type::all(array('return' => 'raw')));

		// Add page specific javascript
		$this->addJavaScript('jquery.customFormSelect.1.0.min.js');
		$this->addJavaScript('projects.js');
	}

	/**
	 * Action Edit Submit
	 * Takes the form data from actionEdit and updates the record for the project
	 * @name actionEditSubmit
	 * @access public
	 * @return void
	 */
	public function actionEditSubmit()
	{
		//echo '<pre>'; print_r($_POST); exit;

		// Make sure the ID is there
		if(!isset($_POST['id']) || !is_numeric($_POST['id']) || 0 > $_POST['id']) {
			return $this->redirect('/projects/', array('errorMsg' => 'Must specify valid Project ID in order to submit changes.'));
		}

		// If there's no priorities set
		if(!isset($_POST['priorities'])) {
			return $this->redirect('/projects/Edit/', array('id' => $_POST['id'], 'errorMsg' => 'Must specify at least one priority per project.'));
		}

		// If there's no types set
		if(!isset($_POST['types'])) {
			return $this->redirect('/projects/Edit/', array('id' => $_POST['id'], 'errorMsg' => 'Must specify at least one type per project.'));
		}

		// Find the project
		$oProject	= table_Project::find($_POST['id']);

		// Update the fields
		$oProject->setFields($_POST['project']);

		// Save the record
		$oProject->update();

		// Set the priorities and types
		table_ProjectsPriorities::replace($_POST['id'], $_POST['priorities']);
		table_ProjectsTypes::replace($_POST['id'], $_POST['types']);

		// Redirect the user
		$this->redirect('/projects/Edit/', array('id' => $_POST['id'], 'successMsg' => 'Successfully updated this project.'));
	}

	/**
	 * @see CLoginController::returnPermissions
	 */
	protected function returnPermissions(/*string*/ $action)
	{
		// Return based on the action
		switch($action)
		{
			case 'Add':
			case 'AddSubmit':
				return self::PERM_PROJECT_ADD;

			case 'Edit':
			case 'EditSubmit':
				return self::PERM_PROJECT_EDIT;
		}

		// By default allow all
		return 0;
	}
}


text:
import gym

def main():
    env = gym.make('CartPole-v0')
    print(env.action_space)

    averageScore = 0
    gamesPlayed = 1000

    for i_episode in range(gamesPlayed):
        observation = env.reset()
        for t in range(200):
            #env.render()
            #print(observation)
            action = 0
            if observation[3] > 0:
                action = 1
            observation, reward, done, info = env.step(action)
            if done:
                averageScore += t
                print("Episode finished after {} timesteps".format(t + 1))
                break
    print("Overall Score {} timestamps".format(averageScore/gamesPlayed))

main()


text:
using System;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerAccounts.Data;
using SFA.DAS.EmployerAccounts.Models.Account;
using SFA.DAS.EmployerAccounts.Queries.GetEmployerAccountDetail;
using SFA.DAS.Validation;

namespace SFA.DAS.EmployerAccounts.UnitTests.Queries.GetEmployerAccountDetailTests
{
    public class WhenIGetEmployerAccountDetailsByHashedId : QueryBaseTest<GetEmployerAccountDetailByHashedIdHandler, GetEmployerAccountDetailByHashedIdQuery, GetEmployerAccountDetailByHashedIdResponse>
    {
        private Mock<IEmployerAccountRepository> _employerAccountRepository;
        public override GetEmployerAccountDetailByHashedIdQuery Query { get; set; }
        public override GetEmployerAccountDetailByHashedIdHandler RequestHandler { get; set; }
        public override Mock<IValidator<GetEmployerAccountDetailByHashedIdQuery>> RequestValidator { get; set; }

        private const string ExpectedHashedAccountId = "MNBGBD";

        [SetUp]
        public void Arrange()
        {
            SetUp();

            _employerAccountRepository = new Mock<IEmployerAccountRepository>();
            _employerAccountRepository.Setup(x => x.GetAccountDetailByHashedId(ExpectedHashedAccountId)).ReturnsAsync(new AccountDetail { HashedId = ExpectedHashedAccountId });

            RequestHandler = new GetEmployerAccountDetailByHashedIdHandler(RequestValidator.Object, _employerAccountRepository.Object);
            Query = new GetEmployerAccountDetailByHashedIdQuery();
        }

        [Test]
        public override async Task ThenIfTheMessageIsValidTheRepositoryIsCalled()
        {
            //Act
            await RequestHandler.Handle(new GetEmployerAccountDetailByHashedIdQuery
            {
                HashedAccountId = ExpectedHashedAccountId
            });

            //Assert
            _employerAccountRepository.Verify(x => x.GetAccountDetailByHashedId(ExpectedHashedAccountId));
        }

        [Test]
        public override async Task ThenIfTheMessageIsValidTheValueIsReturnedInTheResponse()
        {
            //Act
            var result = await RequestHandler.Handle(new GetEmployerAccountDetailByHashedIdQuery
            {
                HashedAccountId = ExpectedHashedAccountId
            });

            //Assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Account);
        }
    }
}


text:
> The [sweetest](http://www.urbandictionary.com/define.php?term=cappi) [sbt](http://www.scala-sbt.org/) plugin your [microbenchmarks](https://code.google.com/p/caliper/wiki/JavaMicrobenchmarks) will ever meet.

Cappi runs [Caliper](https://code.google.com/p/caliper/) benchmarks

## Install

This project targets sbt version [0.13](http://www.scala-sbt.org/0.13.0/docs/home.html). If you should want 0.12 support [drop me an issue](https://github.com/softprops/cappi/issues/new?title=add%20support%20for%20sbt%200.12)

To install Cappi in your sbt project, add the following to your project's plugin configuration, typically in a `project/plugins.sbt` file.

```scala
resolvers += Resolver.url(
  "bintray-sbt-plugin-releases",
    url("http://dl.bintray.com/content/sbt/sbt-plugin-releases"))(
      Resolver.ivyStylePatterns)

addSbtPlugin("me.lessis" % "cappi" % "0.1.1")
```

Then mix `cappiSettings` into your build defintion, typically in a `build.sbt` file.

```scala
seq(cappiSettings:_*)
```

## Usage

Cappi will run your benchmarks, but it needs to know _what_ they are first. By default, Cappi defines two tasks to run your bench marks `benchmark` and `benchmarkOnly` both scoped to the `cappi` task.

### Resolving Benchmarks

In order to run `benchmarks` Cappi makes the assumption that you've named your benchmark in a source file with a name ending with "Benchmark.scala".
Cappi will look for this under your `src/test/scala` directory. It makes the assumption that you are packaging your benchmarks in folders that mirror
the scala package they are under.

For example, the class `foo.BarBenchmark`

```scala
package foo
class BarBenchmark extends com.google.caliper.SimpleBenchmark {
 // ...
}
```

would be expected to be located in a file named `src/test/scala/foo/BarBenchmark.scala`

You can see the full list of resolved benchmark class names by running the following the the sbt REPL

```scala
show cappi::benchmarks
```

Alternatively, you can override the `benchmarks` setting in your build definition

```scala
(cappi.Keys.benchmarks in cappi.Keys.cappi) := Seq("foo.BazBenchmark")
```

### Running Benchmarks

To run your benchmarks, simply run the following in the sbt REPL. This will run all benchmarks.

```scala
cappi::benchmark
```

Alternatively you can run just a target benchmark with `benchmarkOnly` providing a fully qualified Benchmark class name.

```scala
cappi::benchmarkOnly com.you.YourBenchmark
```

### Caliper on your classpath

To run benchmarks, you need to first write benchmarks. To write benchmarks you need caliper on your classpath.
To remove the need for you doing this yourself, Cappi will add caliper to your _test_ classpath. This make getting started
a much smoother process.

To override the calpier version in use, "0.5-rc1" by default, override the `caliperVersion` setting.

```scala
caliperVersion in cappi := Some("custom-version")
```

If you do not wish to have Cappi add this to your test classpath for some reason, say your benchmarks are not actually under
your test class path. Set the `caliperVersion` setting to `None`

```scala
caliperVersion in cappi := None
```

## props

This plugin continues on the path that [this plugin](https://github.com/alno/sbt-caliper) started.

Doug Tangren (softprops) 2013


text:
"""
2019, Daniel Probst, Reymond Group @ University of Bern
 @@ All Rights Reserved @@
This file is part of the RDKit.
The contents are covered by the terms of the BSD license
which is included in the file license.txt, found at the root
of the RDKit source tree.
"""

from rdkit import Chem
from rdkit.Chem import rdMHFPFingerprint
import unittest

class TestCase(unittest.TestCase):

  def setUp(self):
    pass

  def testMHFPFingerprint(self):
    s = "CN1C=NC2=C1C(=O)N(C(=O)N2C)C"
    t = "Cn1cnc2c1c(=O)[nH]c(=O)n2C"

    m = Chem.MolFromSmiles(s)
    enc = rdMHFPFingerprint.MHFPEncoder(128, 42)

    self.assertEqual(len(enc.CreateShinglingFromSmiles(s, rings=False)), 42)
    self.assertEqual(len(enc.CreateShinglingFromSmiles(s, min_radius=0)), 58)

    sh_a = enc.CreateShinglingFromSmiles(s)
    sh_b = enc.CreateShinglingFromMol(m)

    self.assertEqual(len(sh_a), 44)
    self.assertEqual(list(sh_a), list(sh_b))

    fp_a = enc.EncodeSmiles(s)
    fp_b = enc.EncodeMol(m)

    self.assertEqual(list(fp_a), list(fp_b))

    fp_c = enc.EncodeSmiles(t)
    dist = rdMHFPFingerprint.MHFPEncoder.Distance(fp_a, fp_c)
    self.assertEqual(dist, 0.4609375)

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


text:
/*
 * $Id: org.eclipse.jdt.ui.prefs 5004 2006-03-17 20:47:08 -0800 (Fri, 17 Mar 2006) eelco12 $
 * $Revision: 5004 $
 * $Date: 2006-03-17 20:47:08 -0800 (Fri, 17 Mar 2006) $
 *
 * ==============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.wicketstuff.gmap.event;

import org.apache.wicket.ajax.AjaxRequestTarget;

/**
 * See "maptypeid_changed" in the event section of <a href="https://developers.google.com/maps/documentation/javascript/reference#Map">
 * google.maps.Map class </a>.
 */
public abstract class MapTypeChangedListener extends GEventListenerBehavior
{

    private static final long serialVersionUID = 1L;

    /**
     * @see wicket.contrib.gmap.event.GEventListenerBehavior#getEvent()
     */
    @Override
    protected String getEvent()
    {
        return "maptypeid_changed";
    }

    /**
     * @see wicket.contrib.gmap.event.GEventListenerBehavior#onEvent(org.apache.wicket.ajax.AjaxRequestTarget)
     */
    @Override
    protected void onEvent(AjaxRequestTarget target)
    {
        onMapTypeChanged(target);
    }

    protected abstract void onMapTypeChanged(AjaxRequestTarget target);
}


text:
import MultipleChoiceWithOtherPage from '../multiple-choice.page'

class ConstrainingInnovationReferendumPage extends MultipleChoiceWithOtherPage {

  constructor() {
    super('constraining-innovation-referendum')
  }

  clickConstrainingInnovationReferendumAnswerHigh() {
    browser.element('[id="constraining-innovation-referendum-answer-1"]').click()
    return this
  }

  clickConstrainingInnovationReferendumAnswerMedium() {
    browser.element('[id="constraining-innovation-referendum-answer-2"]').click()
    return this
  }

  clickConstrainingInnovationReferendumAnswerLow() {
    browser.element('[id="constraining-innovation-referendum-answer-3"]').click()
    return this
  }

  clickConstrainingInnovationReferendumAnswerNotImportant() {
    browser.element('[id="constraining-innovation-referendum-answer-4"]').click()
    return this
  }

}

export default new ConstrainingInnovationReferendumPage()


text:
package wasr;

import java.awt.*;

/**
 * User: Jason Gillam
 * Date: 11/7/12
 * Time: 10:14 PM
 */
public class DetailLayoutManager implements LayoutManager {

    @Override
    public void addLayoutComponent(String s, Component component) {
        //ignore - not used by this layout manager
    }

    @Override
    public void removeLayoutComponent(Component component) {
        //ignore - not used by this layout manager
    }

    @Override
    public Dimension preferredLayoutSize(Container container) {
        int w = 0;
        int h = 0;

        int count = container.getComponentCount();

        for (int i = 0; i < count; i++) {
            Component c = container.getComponent(i);
            w = Math.max(w, c.getPreferredSize().width);
            h = h + c.getPreferredSize().height;
        }

        Insets i = container.getInsets();

        return new Dimension(w + i.left + i.right, h + i.top + i.bottom);
    }

    @Override
    public Dimension minimumLayoutSize(Container container) {
        int w = 0;
        int h = 0;

        int count = container.getComponentCount();

        for (int i = 0; i < count; i++) {
            Component c = container.getComponent(i);
            w = Math.max(w, c.getMinimumSize().width);
            h = h + c.getMinimumSize().height;
        }

        Insets i = container.getInsets();

        return new Dimension(w + i.left + i.right, h + i.top + i.bottom);
    }

    @Override
    public void layoutContainer(Container container) {
        Insets i = container.getInsets();

        int containerWidth = container.getSize().width - i.left - i.right;
        int y = i.top;

        int count = container.getComponentCount();

        for (int n = 0; n < count; n++) {
            Component c = container.getComponent(n);
            if (c.isVisible()) {
                int h = c.getPreferredSize().height;
                int w = Math.min(containerWidth, c.getMaximumSize().width);
                c.setBounds(i.left, y, w, h);
                y += h;
            }
        }
    }
}


text:
@implementation AFFBlock

#pragma mark - Dealloc
- (void)dealloc {

    if(_blockName) {
        [_blockName release];
    }

    _blockName = nil;

    [super dealloc];
}

@end


text:
using System;
using Pdelvo.Minecraft.Network;

namespace Pdelvo.Minecraft.Protocol.Packets
{
    /// <summary>
    /// </summary>
    /// <remarks>
    /// </remarks>
    [PacketUsage(PacketUsage.Both)]
    [LastSupportedVersion(50)]
    public class PickupSpawn : Packet, IEntityPacket
    {
        /// <summary>
        ///   Initializes a new instance of the <see cref="PickupSpawn" /> class.
        /// </summary>
        /// <remarks>
        /// </remarks>
        public PickupSpawn()
        {
            Code = 0x15;

            Item = new ItemStack ();
        }

        /// <summary>
        ///   Gets or sets the item.
        /// </summary>
        /// <value> The item. </value>
        /// <remarks>
        /// </remarks>
        public ItemStack Item { get; set; }

        /// <summary>
        ///   Gets or sets the X.
        /// </summary>
        /// <value> The X. </value>
        /// <remarks>
        /// </remarks>
        public int PositionX { get; set; }

        /// <summary>
        ///   Gets or sets the Y.
        /// </summary>
        /// <value> The Y. </value>
        /// <remarks>
        /// </remarks>
        public int PositionY { get; set; }

        /// <summary>
        ///   Gets or sets the Z.
        /// </summary>
        /// <value> The Z. </value>
        /// <remarks>
        /// </remarks>
        public int PositionZ { get; set; }

        /// <summary>
        ///   Gets or sets the rotation.
        /// </summary>
        /// <value> The rotation. </value>
        /// <remarks>
        /// </remarks>
        public byte Rotation { get; set; }

        /// <summary>
        ///   Gets or sets the pitch.
        /// </summary>
        /// <value> The pitch. </value>
        /// <remarks>
        /// </remarks>
        public byte Pitch { get; set; }

        /// <summary>
        ///   Gets or sets the roll.
        /// </summary>
        /// <value> The roll. </value>
        /// <remarks>
        /// </remarks>
        public byte Roll { get; set; }

        #region IEntityPacket Members

        /// <summary>
        ///   Gets or sets the entity Id.
        /// </summary>
        /// <value> The entity Id. </value>
        /// <remarks>
        /// </remarks>
        public int EntityId { get; set; }

        #endregion

        /// <summary>
        ///   Receives the specified reader.
        /// </summary>
        /// <param name="reader"> The reader. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnReceive(BigEndianStream reader, int version)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");
            EntityId = reader.ReadInt32 ();
            if (version >= 41)
                Item = ItemStack.Read(reader);
            else
            {
                Item = new ItemStack
                           {
                               ItemType = reader.ReadInt16 (),
                               Count = reader.ReadByte (),
                               Durability = reader.ReadInt16 (),
                               AdditionalData = new byte[0]
                           };
            }
            PositionX = reader.ReadInt32 ();
            PositionY = reader.ReadInt32 ();
            PositionZ = reader.ReadInt32 ();
            Rotation = reader.ReadByte ();
            Pitch = reader.ReadByte ();
            Roll = reader.ReadByte ();
        }

        /// <summary>
        ///   Sends the specified writer.
        /// </summary>
        /// <param name="writer"> The writer. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnSend(BigEndianStream writer, int version)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");
            writer.Write(Code);
            writer.Write(EntityId);
            if (version >= 41)
                writer.Write(Item);
            else
            {
                writer.Write(Item.ItemType);
                writer.Write(Item.Count);
                writer.Write(Item.Durability);
            }
            writer.Write(PositionX);
            writer.Write(PositionY);
            writer.Write(PositionZ);
            writer.Write(Rotation);
            writer.Write(Pitch);
            writer.Write(Roll);
        }
    }
}


text:
import { expect } from 'chai';
import { nativeTheme, systemPreferences, BrowserWindow, ipcMain } from 'electron/main';
import * as os from 'os';
import * as path from 'path';
import * as semver from 'semver';

import { delay, ifdescribe } from './spec-helpers';
import { emittedOnce } from './events-helpers';
import { closeAllWindows } from './window-helpers';

describe('nativeTheme module', () => {
  describe('nativeTheme.shouldUseDarkColors', () => {
    it('returns a boolean', () => {
      expect(nativeTheme.shouldUseDarkColors).to.be.a('boolean');
    });
  });

  describe('nativeTheme.themeSource', () => {
    afterEach(async () => {
      nativeTheme.themeSource = 'system';
      // Wait for any pending events to emit
      await delay(20);

      closeAllWindows();
    });

    it('is system by default', () => {
      expect(nativeTheme.themeSource).to.equal('system');
    });

    it('should override the value of shouldUseDarkColors', () => {
      nativeTheme.themeSource = 'dark';
      expect(nativeTheme.shouldUseDarkColors).to.equal(true);
      nativeTheme.themeSource = 'light';
      expect(nativeTheme.shouldUseDarkColors).to.equal(false);
    });

    it('should emit the "updated" event when it is set and the resulting "shouldUseDarkColors" value changes', async () => {
      let updatedEmitted = emittedOnce(nativeTheme, 'updated');
      nativeTheme.themeSource = 'dark';
      await updatedEmitted;
      updatedEmitted = emittedOnce(nativeTheme, 'updated');
      nativeTheme.themeSource = 'light';
      await updatedEmitted;
    });

    it('should not emit the "updated" event when it is set and the resulting "shouldUseDarkColors" value is the same', async () => {
      nativeTheme.themeSource = 'dark';
      // Wait a few ticks to allow an async events to flush
      await delay(20);
      let called = false;
      nativeTheme.once('updated', () => {
        called = true;
      });
      nativeTheme.themeSource = 'dark';
      // Wait a few ticks to allow an async events to flush
      await delay(20);
      expect(called).to.equal(false);
    });

    ifdescribe(process.platform === 'darwin' && semver.gte(os.release(), '18.0.0'))('on macOS 10.14', () => {
      it('should update appLevelAppearance when set', () => {
        nativeTheme.themeSource = 'dark';
        expect(systemPreferences.appLevelAppearance).to.equal('dark');
        nativeTheme.themeSource = 'light';
        expect(systemPreferences.appLevelAppearance).to.equal('light');
      });
    });

    const getPrefersColorSchemeIsDark = async (w: Electron.BrowserWindow) => {
      const isDark: boolean = await w.webContents.executeJavaScript(
        'matchMedia("(prefers-color-scheme: dark)").matches'
      );
      return isDark;
    };

    it('should override the result of prefers-color-scheme CSS media query', async () => {
      const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false, nodeIntegration: true } });
      await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
      await w.webContents.executeJavaScript(`
        window.matchMedia('(prefers-color-scheme: dark)')
          .addEventListener('change', () => require('electron').ipcRenderer.send('theme-change'))
      `);
      const originalSystemIsDark = await getPrefersColorSchemeIsDark(w);
      let changePromise: Promise<any[]> = emittedOnce(ipcMain, 'theme-change');
      nativeTheme.themeSource = 'dark';
      if (!originalSystemIsDark) await changePromise;
      expect(await getPrefersColorSchemeIsDark(w)).to.equal(true);
      changePromise = emittedOnce(ipcMain, 'theme-change');
      nativeTheme.themeSource = 'light';
      await changePromise;
      expect(await getPrefersColorSchemeIsDark(w)).to.equal(false);
      changePromise = emittedOnce(ipcMain, 'theme-change');
      nativeTheme.themeSource = 'system';
      if (originalSystemIsDark) await changePromise;
      expect(await getPrefersColorSchemeIsDark(w)).to.equal(originalSystemIsDark);
      w.close();
    });
  });

  describe('nativeTheme.shouldUseInvertedColorScheme', () => {
    it('returns a boolean', () => {
      expect(nativeTheme.shouldUseInvertedColorScheme).to.be.a('boolean');
    });
  });

  describe('nativeTheme.shouldUseHighContrastColors', () => {
    it('returns a boolean', () => {
      expect(nativeTheme.shouldUseHighContrastColors).to.be.a('boolean');
    });
  });
});


text:
"""
A dictionary is a mapping from keys to values. They're often used to store properties of an item or to
categorize things.
"""

# Create an empty dictionary
empty_dict = dict()

# Initalize a dictionary with some keys and values
example = dict([('spam', 1), ('eggs', 2)])
print(example)
print(example['spam'])
print(example['eggs'])

# A dictionary can also be constructed by zipping together an iterable of keys and an iterable of values
keys = 'spam', 'eggs'
values = 1, 2
example = dict(zip(keys, values))

"""
To see what I mean by 'unordered', run this script a bunch of times. You'll notice that sometimes line 13 prints
{'eggs': 2, 'spam': 1} instead of using the ordering I used when I defined the dictionary
"""

print()
# key,value pairs can be added on-the-fly
example['sausage'] = 'foobararino'
print(example)

# Iterating over a dictionary with a for loop produces its keys
print('\nsimple for loop:')
for item in example:
    print(item)

# If you want the key, value pairs you'll need
print('\niterating over keys and values:')
for key, value in example.items():
    print(key, value)

# You can also work with a dictionary's keys and values individually,
print('\njust the keys:')
print(example.keys())

print('\njust the values:')
print(example.values())

# Dictionaries are also useful for counting
targets = ['HD_10700', 'HD_172167', 'HD_10700', 'HD_10700', 'HD_172167', 'HD_4478']
counter = dict()
for target in targets:
    if target in counter:
        counter[target] += 1
    else:
        counter[target] = 1
print('\ncounting example:')
print(targets)
print(counter)

# We can actually get rid of the if statement above by using defaultdict
# defaultdict takes a function that is called with no arguments to provide a default value
# if you try to access a value that does not exist. Remember that x += y requires that we evaluate x + y first
from collections import defaultdict
counter = defaultdict(int)
for target in targets:
    counter[target] += 1
print('\ncounting with defaultdict')
print(counter)

# You can also use defaultdict with lists to keep track of categories of things, such as files based on header keywords
from astropy.io import fits

image_types = defaultdict(list)
for filename in ['sample_file.fits']:
    header = fits.open(filename)[0].header
    this_imtype = header['IMAGETYP']
    image_types[this_imtype].append(filename)


text:
package com.sigopt.net;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.HashMap;

import static org.junit.Assert.assertEquals;

public class PathBuilderTest {
    HashMap<String, String> mockParams;

    @Before
    public void setUpMockData() {
        mockParams = new HashMap<String, String>();
        mockParams.put("age", "100");
    }

    @Test
    public void buildWithNoValues() throws Exception {
        String expected = "/some/plain/path";
        String actual = PathBuilder.build(expected, mockParams);
        assertEquals(expected, actual);
    }

    @Test
    public void buildWithParamValues() throws Exception {
        String path = "/some/:age/path";
        String actual = PathBuilder.build(path, mockParams);
        assertEquals("/some/" + mockParams.get("age") + "/path", actual);
    }
}


text:
A purely PHP library for indexing and searching documents against an Apache Solr installation.

This project was formerly maintained at [http://code.google.com/p/solr-php-client](http://code.google.com/p/solr-php-client). Previous issues and downloads are still available for viewing there.

## Need Help?

Try starting with the [FAQ](https://github.com/PTCInc/solr-php-client/wiki/FAQ) and [Example Usage](https://github.com/PTCInc/solr-php-client/wiki/Example-Usage).

Also, feel free to search and ask questions on the google mailing list: [php-solr-client@googlegroups.com](mailto:php-solr-client@googlegroups.com) / [Group Page](https://groups.google.com/forum/?fromgroups#!forum/php-solr-client)

## License

Code is released under a 3-Clause BSD license, see [COPYING](https://github.com/PTCInc/solr-php-client/blob/master/COPYING) for full text.


text:
<?php

namespace LightSaml\SymfonyBridgeBundle\Tests\Bridge\Container;

use LightSaml\Provider\EntityDescriptor\EntityDescriptorProviderInterface;
use LightSaml\Store\Credential\CredentialStoreInterface;
use LightSaml\SymfonyBridgeBundle\Bridge\Container\OwnContainer;
use PHPUnit\Framework\TestCase;

class OwnContainerTest extends TestCase
{
    public function test_constructs_with_all_arguments()
    {
        new OwnContainer(
            $this->getMockBuilder(EntityDescriptorProviderInterface::class)->getMock(),
            $this->getMockBuilder(CredentialStoreInterface::class)->getMock(),
            "string"
        );
    }
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using Accidis.Apps.Preflight.Utils.Diagnostics;

namespace Accidis.Apps.Preflight.Utils.Web
{
	public abstract class WebDownloaderBase<TResult> where TResult : new()
	{
		const int _defaultTimeout = 30000;

		protected virtual int Timeout
		{
			get { return _defaultTimeout; }
		}

		protected virtual bool CloseResponse
		{
			get { return true; }
		}

		public event EventHandler DownloadStarted;
		public event EventHandler<UnhandledExceptionEventArgs> DownloadFailed;
		public event EventHandler DownloadCompleted;

		protected abstract void ReadResponse( Stream stream, TResult result );

		protected virtual void AfterDownloadCompleted( TResult result )
		{
		}

		protected void BeginDownload( string url )
		{
			if( null != DownloadStarted )
				DownloadStarted( this, EventArgs.Empty );

			var state = new RequestState
			            	{
			            		Timer = new LoggingTimer( "WebDownloaderBase.BeginDownload" ),
			            		Result = new TResult(),
			            		Request = WebRequest.CreateHttp( url )
			            	};

			state.Request.AllowReadStreamBuffering = true;
			state.Request.BeginGetResponse( OnWebRequestCompleted, state );
			ThreadPool.QueueUserWorkItem( HandleTimeout, state );
		}

		void HandleTimeout( object stateObj )
		{
			Thread.Sleep( Timeout );

			var state = (RequestState) stateObj;
			if( !state.Completed )
			{
				Debug.WriteLine( "Web request timed out!" );
				state.Request.Abort();
			}
		}

		void OnWebRequestCompleted( IAsyncResult asyncResult )
		{
			var state = (RequestState) asyncResult.AsyncState;
			state.Timer.Dispose();
			state.Completed = true;

			WebResponse response = null;

			try
			{
				using( new LoggingTimer( "WebDownloaderBase.OnWebRequestCompleted" ) )
				{
					response = state.Request.EndGetResponse( asyncResult );
					ReadResponse( response.GetResponseStream(), state.Result );
				}
			}
			catch( Exception ex )
			{
				Debug.WriteLine( "Exception during download of {0}", state.Request.RequestUri );
				Debug.WriteLine( ex );

				if( null != DownloadFailed )
					DownloadFailed( this, new UnhandledExceptionEventArgs( ex, false ) );

				return;
			}
			finally
			{
				if( CloseResponse && null != response )
					response.Close();
            }

            AfterDownloadCompleted( state.Result );

			if( null != DownloadCompleted )
				DownloadCompleted( this, EventArgs.Empty );
		}

		#region Nested type: RequestState

		sealed class RequestState
		{
			public HttpWebRequest Request { get; set; }
			public LoggingTimer Timer { get; set; }
			public TResult Result { get; set; }
			public bool Completed { get; set; }
		}

		#endregion
	}
}


text:
<?php

// Disallow direct access to this file
defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.controller' );

/**
 * JomSocial Component Controller
 */
class CommunityControllerMaintenance extends CommunityController
{
	public function __construct()
	{
		parent::__construct();
		$this->enableAzrulSystem();
	}

	public function display()
	{
		$viewName	= JRequest::getCmd( 'view' , 'community' );

		// Set the default layout and view name
		$layout		= JRequest::getCmd( 'layout' , 'default' );

		// Get the document object
		$document	= JFactory::getDocument();

		// Get the view type
		$viewType	= $document->getType();

		// Get the view
		$view		=& $this->getView( $viewName , $viewType );

		$model		=& $this->getModel( 'groups' );
		$userModel	=& $this->getModel( 'users' );

		if( $model && $userModel )
		{
			$view->setModel( $model , $viewName );
			$view->setModel( $userModel , $viewName );
		}

		// Set the layout
		$view->setLayout( $layout );

		// Display the view
		$view->display();

		// Display Toolbar. View must have setToolBar method
		if( method_exists( $view , 'setToolBar') )
		{
			$view->setToolBar();
		}
	}

	public function ajaxCheckHash(){

		$objResponse = new JAXResponse();

		$hashpath = JPATH_ROOT.'/administrator/components/com_community/hash.ini';
		if(!file_exists($hashpath)){
			$objResponse->addScriptCall('joms.jQuery("#no-progress").html("Sorry no files hash.ini file found");');
			return $objResponse->sendResponse();
		}
		$hashlist = parse_ini_file($hashpath);
		$stats = array();
		$objResponse->addScriptCall('joms.jQuery("#no-progress").html("Checking '.count($hashlist).' files");');
		foreach($hashlist as $path => $hash){
			if(!file_exists(JPATH_ROOT.$path)) {
				$stats['missing'][] = $path;
				continue;
			}

			if(md5(file_get_contents(JPATH_ROOT.$path)) != $hash){
				$stats['changed'][] = $path;
			}
		}
		$html = '
Check complete: Missing='.count($stats['missing']).' & Changed='.count($stats['changed']).'
';
		$html .= "
Changed files
".implode('
',$stats['changed']);
		$html .= "
Missing files
".implode('
',$stats['missing']);
		$objResponse->addScriptCall('joms.jQuery("#progress-status").html("'.$html.'");');
		return $objResponse->sendResponse();
	}

	public function ajaxPatchFriendTable()
	{
		$objResponse	= new JAXResponse();

		$db		= JFactory::getDBO();

		$model	=& $this->getModel( 'Users' );
		$fields = $model->_getFields();

		if(! array_key_exists( 'friendcount' , $fields ) )
		{
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_users' ) . ' '
					. 'ADD '. $db->quoteName('friendcount') . ' INT( 11 ) NOT NULL DEFAULT ' . $db->Quote('0') . ' AFTER ' . $db->quoteName('view');
			$db->setQuery( $query );
			$db->query();
		}

		$objResponse->addScriptCall( 'joms.jQuery("#progress-status").append("
Community User Table Updated
");' );

		return $objResponse->sendResponse();
	}

	public function ajaxPatchTable()
	{
		$objResponse	= new JAXResponse();

		$model	=& $this->getModel( 'Groups' );
		$fields = $model->_getFields();

		$db		= JFactory::getDBO();

		if((!array_key_exists( 'membercount' , $fields )) || (!array_key_exists( 'wallcount' , $fields )) || (!array_key_exists( 'discusscount' , $fields ))) {
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_groups' ) . ' '
					. 'ADD ' . $db->quoteName('discusscount') . ' INT( 11 ) NOT NULL DEFAULT '. $db->Quote(0) .' AFTER ' . $db->quoteName('thumb') . ' , '
					. 'ADD '. $db->quoteName('wallcount') . ' INT( 11 ) NOT NULL DEFAULT ' . $db->Quote(0) . ' AFTER ' . $db->quoteName('discusscount') . ' , '
					. 'ADD ' . $db->quoteName('membercount') . ' INT( 11 ) NOT NULL DEFAULT ' . $db->Quote(0) . ' AFTER ' . $db->quoteName('wallcount');
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_fields', 'fieldcode')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_fields' ) . ' ADD INDEX ('. $db->quoteName('fieldcode') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_fields_values', 'user_id')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_fields_values' ) . ' ADD INDEX (' . $db->quoteName('user_id') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_fields_values', 'field_id')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_fields_values') . ' ADD INDEX (' . $db->quoteName('field_id') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_apps', 'userid')){
			$query	= 'ALTER TABLE ' . $db->quoteName('#__community_apps') . ' ADD INDEX (' . $db->quoteName('userid') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_connection', 'connect_from')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_connection' ) . ' ADD INDEX (' . $db->quoteName('connect_from') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_connection', 'connect_to')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_connection' ) . ' ADD INDEX (' . $db->quoteName('connect_to') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_connection', 'status')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_connection' ) . ' ADD INDEX (' . $db->quoteName('status'). ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_groups_members', 'approved')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_groups_members' ) . ' ADD INDEX (' . $db->quoteName('approved') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_photos', 'creator')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_photos' ) . ' ADD INDEX (' . $db->quoteName('creator') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_activities', 'created')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_activities' ) . ' ADD INDEX (' . $db->quoteName('created') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		if(! $this->_isExistTableColumnIndex('#__community_activities', 'archived')){
			$query	= 'ALTER TABLE ' . $db->quoteName( '#__community_activities' ) . ' ADD INDEX (' . $db->quoteName('archived') . ')';
			$db->setQuery( $query );
			$db->query();
		}

		$objResponse->addScriptCall( 'joms.jQuery("#progress-status").append("
Tables Updated
");' );

		return $objResponse->sendResponse();
	}

	/*
	 * Check table column index whether exists or not.
	 * index name == column name.
	 */
	public function _isExistTableColumnIndex($tablename, $columnname){

		$db		= JFactory::getDBO();

		$query	= 'SHOW INDEX FROM ' . $db->quoteName( $tablename );

		$db->setQuery( $query );

		$indexes	= $db->loadObjectList();

		foreach( $indexes as $index )
		{
			$result[ $index->Key_name ]	= $index->Column_name;
		}

		if(array_key_exists($columnname, $result)){
			return true;
		}

		return false;
	}

	public function ajaxPatch()
	{
		$objResponse	= new JAXResponse();

		$model			=& $this->getModel( 'Groups' );
		$groups			= $model->getAllGroups();

		for( $i = 0; $i < count($groups); $i++ )
		{
			$objResponse->addScriptCall( 'jax.call("community","admin,maintenance,ajaxPatchGroup","' . $groups[$i]->id . '");');
		}

		//patch for user friend count.
		$uModel			=& $this->getModel( 'Users' );
		$users			= $uModel->getAllCommunityUsers();

		for( $i = 0; $i < count($users); $i++ )
		{
			$objResponse->addScriptCall( 'jax.call("community","admin,maintenance,ajaxPatchFriend","' . $users[$i]->userid . '");');
		}

		return $objResponse->sendResponse();
	}

	public function ajaxPatchFriend( $userId )
	{
		$objResponse	= new JAXResponse();

		$row		= JTable::getInstance( 'users', 'CommunityTable' );
		$row->load( $userId );

		$row->friendcount	= $row->getFriendCount();

		$row->store();

		$objResponse->addScriptCall( 'joms.jQuery("#progress-status").append("
User ID ' . $row->userid . ' Updated
");' );

		return $objResponse->sendResponse();
	}

	public function ajaxPatchGroup( $groupId )
	{
		$objResponse	= new JAXResponse();

		$row		= JTable::getInstance( 'groups', 'CommunityTable' );
		$row->load( $groupId );

		$row->discusscount	= $row->getDiscussCount();
		$row->membercount	= $row->getMembersCount();
		$row->wallcount		= $row->getWallCount();

		$row->store();

		$objResponse->addScriptCall( 'joms.jQuery("#progress-status").append("
Group ' . $row->name . ' Updated
");' );

		return $objResponse->sendResponse();
	}

	public function ajaxPatchPrivacy( $limit = 1 )
	{
		require_once( JPATH_ROOT . '/components/com_community/libraries/core.php' );

		$limitstart		= $limit - 1;

		$model			=& $this->getModel( 'users' );
		$userId			= $model->getSiteUsers( $limitstart , 1 );

		$objResponse	= new JAXResponse();

		$objResponse->addScriptCall( 'joms.jQuery("#no-progress").css("display","none");');
		$db				= JFactory::getDBO();

		if( !empty( $userId ) )
		{
			$user		= CFactory::getUser( $userId );

			$params		= $user->getParams();

			// Fix old privacy issues.
			if($params->get('privacyPhotoView') == 1 )
			{
				$params->set('privacyPhotoView' , 0);
			}

			$query = 'UPDATE ' . $db->quoteName( '#__community_photos' ) . ' '
					. 'SET ' . $db->quoteName( 'permissions' ) . '=' . $params->get('privacyPhotoView') . ' '
					. 'WHERE ' . $db->quoteName( 'creator' ) . '=' . $db->Quote( $user->id );
			$db->setQuery( $query );
			$db->query();

			$query = 'UPDATE ' . $db->quoteName( '#__community_photos_albums' ) . ' '
					. 'SET ' . $db->quoteName( 'permissions' ) . '=' . $params->get('privacyPhotoView') . ' '
					. 'WHERE ' . $db->quoteName( 'creator' ) . '=' . $db->Quote( $user->id );
			$db->setQuery( $query );
			$user->save('params');

			$status		= '';

			if( $db->query() )
			{
				$status	= '' . JText::_('COM_COMMUNITY_SUCCESS') . '';
			}
			else
			{
				$status	= '' . JText::_('COM_COMMUNITY_NOT_SUCCESS') . '';
			}

			$objResponse->addScriptCall( 'joms.jQuery("#progress-status").append("
' . JText::sprintf('Updating user id %1$s. %2$s' , $user->id , $status ) . '
");');
	 		$objResponse->addScriptCall( 'jax.call("community","admin,maintenance,ajaxPatchPrivacy" , "' . ( $limit + 1 ) . '");');
		}
		else
		{
			// Just to make sure that we remove all references to 'all' once the last ajax query is called.
			$query		= 'UPDATE ' . $db->quoteName( '#__community_photos' ) . ' '
						. 'SET ' . $db->quoteName( 'permissions' ) . '=' . $db->Quote( 0 ) . ' '
						. 'WHERE ' . $db->quoteName('permissions') . '=' . $db->Quote( 'all' );
			$db->setQuery( $query );
			$db->query();

			$query		= 'UPDATE ' . $db->quoteName( '#__community_photos_albums' ) . ' '
						. 'SET ' . $db->quoteName( 'permissions' ) . '=' . $db->Quote( '0' ) . ' '
						. 'WHERE ' . $db->quoteName('permissions') . '=' . $db->Quote( 'all' );
			$db->setQuery( $query );
			$db->query();

			$objResponse->addScriptCall( 'joms.jQuery("#progress-status").append("
' . JText::_('COM_COMMUNITY_UPDATED') . '
");');
		}

 		$objResponse->sendResponse();
	}

	public function enableAzrulSystem()
	{
		$db = JFactory::getDBO();

		$sql = ' UPDATE ' . $db->quoteName(PLUGIN_TABLE_NAME)
			 . ' SET ' . $db->quoteName(EXTENSION_ENABLE_COL_NAME) . ' = ' . $db->quote('1')
			 . ' WHERE ' . $db->quoteName('element') . ' = ' . $db->quote('azrul.system');

		$db->setQuery($sql);
		$db->Query();
		if($db->getErrorNum()){
			JError::raiseError( 500, $db->stderr());
		}

		return TRUE;
	}
}