Result:
found more than 868 distributions - search limited to the first 2001 files matching your query ( run in 1.137 )


AI-ANN

 view release on metacpan or  search on metacpan

lib/AI/ANN.pm  view on Meta::CPAN


=head2 execute

$network->execute( [$input0, $input1, ...] )

Runs the network for as many iterations as necessary to achieve a stable
network, then returns the output. 
We store the current state of the network in two places - once in the object,
for persistence, and once in $neurons, for simplicity. This might be wrong, 
but I couldn't think of a better way.

 view all matches for this distribution


AI-ML

 view release on metacpan or  search on metacpan

lib/AI/ML/LinearRegression.pm  view on Meta::CPAN

    #Option
    #gradient => not use normal equation
    #plot => plot data and linear
    #cost => plot cost
    #alpha
    #n => number of iterations

=cut

sub train {
    my ($self, $x, $y) = @_;

 view all matches for this distribution


AI-MaxEntropy

 view release on metacpan or  search on metacpan

lib/AI/MaxEntropy.pm  view on Meta::CPAN


For GIS, the C<progress_cb> is supposed to have a prototype like

  progress_cb(i, lambda, d_lambda, lambda_norm, d_lambda_norm)

C<i> is the number of the iterations, C<lambda> is an array ref containing
the current lambda vector, C<d_lambda> is an array ref containing the
delta of the lambda vector in current iteration, C<lambda_norm> and
C<d_lambda_norm> are Euclid norms of C<lambda> and C<d_lambda> respectively.

For both L-BFGS and GIS, the client program can also pass a string

 view all matches for this distribution


AI-NeuralNet-BackProp

 view release on metacpan or  search on metacpan

BackProp.pm  view on Meta::CPAN

The first two arguments may be array refs (or now, strings), and they may be of different lengths.

Options should be written on hash form. There are three options:
	 
	 inc	=>	$learning_gradient
	 max	=>	$maximum_iterations
	 error	=>	$maximum_allowable_percentage_of_error
	 

$learning_gradient is an optional value used to adjust the weights of the internal
connections. If $learning_gradient is ommitted, it defaults to 0.20.
 
$maximum_iterations is the maximum numbers of iteration the loop should do.
It defaults to 1024.  Set it to 0 if you never want the loop to quit before
the pattern is perfectly learned.

$maximum_allowable_percentage_of_error is the maximum allowable error to have. If 
this is set, then learn() will return when the perecentage difference between the
actual results and desired results falls below $maximum_allowable_percentage_of_error.
If you do not include 'error', or $maximum_allowable_percentage_of_error is set to -1,
then learn() will not return until it gets an exact match for the desired result OR it
reaches $maximum_iterations.


=item $net->learn_set(\@set, [ options ]);

UPDATE: Inputs and outputs in the dataset can now be strings. See information on auto-crunching

 view all matches for this distribution


AI-NeuralNet-Kohonen

 view release on metacpan or  search on metacpan

lib/AI/NeuralNet/Kohonen.pm  view on Meta::CPAN


=over 4

=item time_constant

The number of iterations (epochs) to be completed, over the log of the map radius.

=item t

The current epoch, or moment in time.

 view all matches for this distribution


AI-NeuralNet-Mesh

 view release on metacpan or  search on metacpan

Mesh.pm  view on Meta::CPAN

of different lengths.

Options should be written on hash form. There are three options:
	 
	 inc      =>    $learning_gradient
	 max      =>    $maximum_iterations
	 error    =>    $maximum_allowable_percentage_of_error
	 degrade  =>    $degrade_increment_flag
	 

$learning_gradient is an optional value used to adjust the weights of the internal
connections. If $learning_gradient is ommitted, it defaults to 0.002.
 
$maximum_iterations is the maximum numbers of iteration the loop should do.
It defaults to 1024.  Set it to 0 if you never want the loop to quit before
the pattern is perfectly learned.

$maximum_allowable_percentage_of_error is the maximum allowable error to have. If 
this is set, then learn() will return when the perecentage difference between the
actual results and desired results falls below $maximum_allowable_percentage_of_error.
If you do not include 'error', or $maximum_allowable_percentage_of_error is set to -1,
then learn() will not return until it gets an exact match for the desired result OR it
reaches $maximum_iterations.

$degrade_increment_flag is a simple flag used to allow/dissalow increment degrading
during learning based on a product of the error difference with several other factors.
$degrade_increment_flag is off by default. Setting $degrade_increment_flag to a true
value turns increment degrading on. 

 view all matches for this distribution


AI-NeuralNet-SOM

 view release on metacpan or  search on metacpan

lib/AI/NeuralNet/SOM.pm  view on Meta::CPAN

=item C<learning_rate>: (optional, default C<0.1>)

This is a magic number which controls how strongly the vectors in the grid can be influenced. Stronger
movement can mean faster learning if the clusters are very pronounced. If not, then the movement is
like noise and the convergence is not good. To mediate that effect, the learning rate is reduced
over the iterations.

=item C<sigma0>: (optional, defaults to radius)

A non-negative number representing the start value for the learning radius. Practically, the value
should be chosen in such a way to cover a larger part of the map. During the learning process this

 view all matches for this distribution


AI-NeuralNet-Simple

 view release on metacpan or  search on metacpan

examples/game_ai.pl  view on Meta::CPAN


use constant YES     => 1.0;
use constant NO      => 0.0;

my $net = AI::NeuralNet::Simple->new(4,20,4);
$net->iterations(shift || 100000);
$net->train_set( [
#   health    knife gun  enemy
    [GOOD,    YES,  YES, 0],  WANDER,
    [GOOD,    YES,   NO, 2],  HIDE,
    [GOOD,    YES,   NO, 1],  ATTACK,

 view all matches for this distribution


AI-PSO

 view release on metacpan or  search on metacpan

lib/AI/PSO.pm  view on Meta::CPAN

my $numNeighbors  = 'null';            # This is the number of neighboring particles that each particle shares information with
                                       # which must obviously be less than the number of particles and greater than 0.
                                         # TODO: write code to preconstruct different topologies.  Such as fully connected, ring, star etc.
                                         #       Currently, neighbors are chosen by a simple hash function.  
                                         #       It would be fun (no theoretical benefit that I know of) to play with different topologies.
my $maxIterations = 'null';            # This is the maximum number of optimization iterations before exiting if the fitness goal is never reached.
my $exitFitness   = 'null';            # this is the exit criteria.  It must be a value between 0 and 1.
my $dimensions    = 'null';            # this is the number of variables the user is optimizing


#-#-# pso position parameters #-#-#

lib/AI/PSO.pm  view on Meta::CPAN

        }

    }

    #
    # at this point we have exceeded the maximum number of iterations, so let's at least print out the best result so far
    #
    print STDERR "MAX ITERATIONS REACHED WITHOUT MEETING EXIT CRITERION...printing best solution\n";
    my $bestFit = -1;
    my $bestPartIndex = -1;
    for(my $p = 0; $p < $numParticles; $p++) {

lib/AI/PSO.pm  view on Meta::CPAN

  use AI::PSO;

  my %params = (
      numParticles   => 4,     # total number of particles involved in search 
      numNeighbors   => 3,     # number of particles with which each particle will share its progress
      maxIterations  => 1000,  # maximum number of iterations before exiting with no solution found
      dimensions     => 4,     # number of parameters you want to optimize
      deltaMin       => -4.0,  # minimum change in velocity during PSO update
      deltaMax       =>  4.0,  # maximum change in velocity during PSO update
      meWeight       => 2.0,   # 'individuality' weighting constant (higher means more individuality)
      meMin          => 0.0,   # 'individuality' minimum random weight

lib/AI/PSO.pm  view on Meta::CPAN

  make my code nicely formatted and good looking :)).

=item pso_optimize()

  Runs the particle swarm optimization algorithm.  This consists of 
  running iterations of search and many calls to the fitness function 
  you registered with pso_register_fitness_function()

=item pso_get_solution_array()

  By default, pso_optimize() will print out to STDERR the first 
  solution, or the best solution so far if the max iterations were 
  reached.  This function will simply return an array of the winning 
  (or best so far) position of the entire swarm system.  It is an 
  array of floats to be used how you wish (like weights in a 
  neural network!).

 view all matches for this distribution


AI-ParticleSwarmOptimization-MCE

 view release on metacpan or  search on metacpan

example/PSOTest-MultiCore.pl  view on Meta::CPAN

#my $pso = AI::ParticleSwarmOptimization::Pmap->new(		# Multi-core	
my $pso = AI::ParticleSwarmOptimization::MCE->new(		# Multi-core	
#my $pso = AI::ParticleSwarmOptimization->new(			# Single-core
    -fitFunc    	=> \&calcFit,
    -dimensions 	=> 10,
    -iterations 	=> 10,
    -numParticles	=> 1000,
    
    # only for many-core version # the best if == $#cores of your system
    # selecting best value if undefined
    -workers		=> 4,							

example/PSOTest-MultiCore.pl  view on Meta::CPAN

my $fitValue         = $pso->optimize ();
my ( $best )         = $pso->getBestParticles (1);
my ( $fit, @values ) = $pso->getParticleBestPos ($best);
my $iters            = $pso->getIterationCount();

printf "Fit %.4f at (%s) after %d iterations\n", $fit, join (', ', map {sprintf '%.4f', $_} @values), $iters;
warn "\nTime: ", time - $beg, "\n\n";
#=======================================================================
exit 0;

 view all matches for this distribution


AI-ParticleSwarmOptimization-Pmap

 view release on metacpan or  search on metacpan

example/PSOTest-MultiCore.pl  view on Meta::CPAN

#my $pso = AI::ParticleSwarmOptimization->new(			# Single-core
#my $pso = AI::ParticleSwarmOptimization::MCE->new(		# Multi-core	
my $pso = AI::ParticleSwarmOptimization::Pmap->new(		# Multi-core	
    -fitFunc    	=> \&calcFit,
    -dimensions 	=> 10,
    -iterations 	=> 10,
    -numParticles	=> 1000,
    
    # only for many-core version # the best if == $#cores of your system
    # selecting best value if undefined
    -workers		=> 4,							

example/PSOTest-MultiCore.pl  view on Meta::CPAN

my $fitValue         = $pso->optimize ();
my ( $best )         = $pso->getBestParticles (1);
my ( $fit, @values ) = $pso->getParticleBestPos ($best);
my $iters            = $pso->getIterationCount();

printf "Fit %.4f at (%s) after %d iterations\n", $fit, join (', ', map {sprintf '%.4f', $_} @values), $iters;
warn "\nTime: ", time - $beg, "\n\n";
#=======================================================================
exit 0;

 view all matches for this distribution


AI-ParticleSwarmOptimization

 view release on metacpan or  search on metacpan

Samples/PSOPlatTest.pl  view on Meta::CPAN


++$|;
my $pso = AI::ParticleSwarmOptimization->new (
    -fitFunc           => \&calcFit,
    -dimensions        => 3,
    -iterations        => 500,
    -exitPlateau       => 1,
    -exitPlateauDP     => 3,
    -exitPlateauBurnin => 100,
    -exitPlateauWindow => 60,
);

Samples/PSOPlatTest.pl  view on Meta::CPAN

my ($best) = $pso->getBestParticles (1);
my ($fit, @values) = $pso->getParticleBestPos ($best);
my $iters = $pso->getIterationCount ();
print $pso->getSeed();

printf ",# Fit %.5f at (%s) after %d iterations\n",
    $fit, join (', ', map {sprintf '%.4f', $_} @values), $iters;


sub calcFit {
    my @values = @_;

 view all matches for this distribution


AI-Pathfinding-OptimizeMultiple

 view release on metacpan or  search on metacpan

lib/AI/Pathfinding/OptimizeMultiple.pm  view on Meta::CPAN

FLARES_LOOP:
    while ( my $q_more = $self->_get_next_quota() )
    {
        $iters_quota += $q_more;

        # Next number of iterations for each scan x scan combination.
        my $next_num_iters = (
            ( $ones_constant x $flares_num_iters ) + (
                PDL::MatrixOps::identity( $self->_get_num_scans() ) *
                    $iters_quota
            )

lib/AI/Pathfinding/OptimizeMultiple.pm  view on Meta::CPAN


    $obj->calc_meta_scan();

    foreach my $scan_alloc (@{$self->chosen_scans()})
    {
        printf "Run %s for %d iterations.\n",
            $scans[$scan_alloc->scan_idx], $scan_alloc->iters;
    }

=head1 DESCRIPTION

lib/AI/Pathfinding/OptimizeMultiple.pm  view on Meta::CPAN

scans are run one after the other and the shortest solutions of all
successful scans are being picked.

=head2 $calc_meta_scan->calc_board_iters($board_idx)

Calculates the iterations of the board $board_idx in all the scans.

Returns a hash_ref containing the key 'per_scan_iters' for the iterations
per scan, and 'board_iters' for the total board iterations when ran in the
scans.

=head2 my $status = $calc_meta_scan->get_final_status()

Returns the status as string:

lib/AI/Pathfinding/OptimizeMultiple.pm  view on Meta::CPAN

$args is an optional hash reference. It may contain a value with the key of
C<'chosen_scans'> that may specify an alternative scans to traverse.

=head2 my $n = $calc_meta_scan->get_total_iters()

Returns the total iterations count so far.

=head2 BUILD()

Moo leftover. B<INTERNAL USE>.

 view all matches for this distribution


AI-Perceptron

 view release on metacpan or  search on metacpan

lib/AI/Perceptron.pm  view on Meta::CPAN


 print "current output: $current, target: $target\n";

 $p->add_examples( [ $target, @inputs ] );

 $p->max_iterations( 10 )->train or
   warn "couldn't train in 10 iterations!";

 print "training until it gets it right\n";
 $p->max_iterations( -1 )->train; # watch out for infinite loops

=cut

package AI::Perceptron;

use strict;
use accessors qw( num_inputs learning_rate _weights threshold
		  training_examples max_iterations );

our $VERSION = '1.0';
our $Debug   = 0;

sub new {

lib/AI/Perceptron.pm  view on Meta::CPAN

    my $self = shift;
    my %args = @_;

    $self->num_inputs( $args{Inputs} || 1 )
         ->learning_rate( $args{N} || 0.05 )
	 ->max_iterations( -1 )
	 ->threshold( $args{T} || 0.0 )
	 ->training_examples( [] )
	 ->weights( [] );

    # DEPRECATED: backwards compat

lib/AI/Perceptron.pm  view on Meta::CPAN

    # adjust the weights for each training example until the output
    # function correctly classifies all the training examples.
    my $iter = 0;
    while(! $self->classifies_examples_correctly ) {

	if (($self->max_iterations > 0) and
	    ($iter >= $self->max_iterations)) {
	    $self->emit( "stopped training after $iter iterations" );
	    return;
	}

	$iter++;
	$self->emit( "Training iteration $iter" );

lib/AI/Perceptron.pm  view on Meta::CPAN

	    $self->adjust_threshold( $expected_output, $output )
	         ->adjust_weights( \@inputs, $expected_output, $output );
	}
    }

    $self->emit( "completed in $iter iterations." );

    return $self;
}

# return true unless all training examples are correctly classified

lib/AI/Perceptron.pm  view on Meta::CPAN


Which is know as a negative feedback loop - it uses the current output as an
input to determine what the next output will be.

Also, note that this means you can get stuck in an infinite loop.  It's not a
bad idea to set the maximum number of iterations to prevent that.

=head1 CONSTRUCTOR

=over 4

lib/AI/Perceptron.pm  view on Meta::CPAN

Set/get the perceptron's list of training examples.  This should be a list of
arrayrefs of the form:

    [ $expected_result => @inputs ]

=item max_iterations( [ $int ] )

Set/get the perceptron's number of inputs, a negative value implies no maximum.

=back

 view all matches for this distribution


AI-Termites

 view release on metacpan or  search on metacpan

lib/AI/Termites.pm  view on Meta::CPAN

    my $box_vol = 1;
    $box_vol *= $_ for @$box;

    my $n_termites = delete $opts{n_termites} // 50;
    my $n_wood = delete $opts{n_wood} // 200;
    my $iterations = delete $opts{iterations} // 0;
    my $termite_speed = delete $opts{termite_speed} // abs($box)/10;
    my $near = delete $opts{near} // abs($box)/50;
    %opts and croak "unknown parameter(s) ". join(", ", keys %opts);

    my @wood;

lib/AI/Termites.pm  view on Meta::CPAN


    bless $self, $class;

    push @wood, $self->new_wood for (1..$n_wood);
    push @termites, $self->new_termite for (1..$n_termites);
    $self->iterate for (1..$iterations);
    $self;
}

sub dim { shift->{dim} }

 view all matches for this distribution


AI-XGBoost

 view release on metacpan or  search on metacpan

lib/AI/XGBoost.pm  view on Meta::CPAN


AI::XGBoost::DMatrix object used for training

=item number_of_rounds

Number of boosting iterations

=back

=head1 ROADMAP

 view all matches for this distribution


ALBD

 view release on metacpan or  search on metacpan

utils/datasetCreator/makeOrderNotMatter.pl  view on Meta::CPAN

(exists $options{'outputFile'}) or die ("outputFile must be specified\n");
open OUT, '>'.$options{'outputFile'} or 
    die ("unable to open output file: $options{outputFile}\n");

#make order not matter
#...output every $outputLimit iterations to avoid too much IO
my %matrix = ();
while (my $line = <IN>) {
    #TODO use split instead of regex match
    $line =~ /([^\s]+)\t([^\s]+)\t([^\s]+)/;
    #$1 = row, $2 = col, $3 = val

 view all matches for this distribution


AWS-Lambda-Quick

 view release on metacpan or  search on metacpan

perltidyrc  view on Meta::CPAN

--blank-lines-before-packages=0
--iterations=2
--no-outdent-long-comments
-bar
-boc
-ci=4
-i=4

 view all matches for this distribution


Acme-CPANModules-Import-CPANRatings-User-stevenharyanto

 view release on metacpan or  search on metacpan

lib/Acme/CPANModules/Import/CPANRatings/User/stevenharyanto.pm  view on Meta::CPAN

our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2023-10-29'; # DATE
our $DIST = 'Acme-CPANModules-Import-CPANRatings-User-stevenharyanto'; # DIST
our $VERSION = '0.002'; # VERSION

our $LIST = {description=>"This list is generated by scraping CPANRatings (cpanratings.perl.org) user page.",entries=>[{description=>"\n(REMOVED)\n",module=>"Log::Any",rating=>undef},{description=>"\nProvides a thin/lightweight OO interface for \$?, ...

1;
# ABSTRACT: List of modules mentioned by CPANRatings user stevenharyanto

__END__

lib/Acme/CPANModules/Import/CPANRatings/User/stevenharyanto.pm  view on Meta::CPAN


<br><br>###
<br>
Benchmark: running dpath, dseek, dseek_cacheobj, jpath for at least 0.25 CPU seconds...
<br><br>dpath:  1 wallclock secs ( 0.27 usr +  0.00 sys =  0.27 CPU) @ 8292.59/s (n=2239)
<br><br>(warning: too few iterations for a reliable count)
<br><br>dseek:  1 wallclock secs ( 0.29 usr +  0.00 sys =  0.29 CPU) @ 37.93/s (n=11)
<br><br>(warning: too few iterations for a reliable count)
<br>
dseek_cacheobj:  0 wallclock secs ( 0.33 usr +  0.00 sys =  0.33 CPU) @ 42.42/s (n=14)
<br><br>(warning: too few iterations for a reliable count)
<br><br>jpath:  0 wallclock secs ( 0.27 usr +  0.00 sys =  0.27 CPU) @ 11711.11/s (n=3162)
<br><br>(warning: too few iterations for a reliable count)
<br>
=head2 #

<br><br>Also: 1) the syntax is rather inconsistent: ':n' for array index access, but '.@' (instead of ':@') for grabbing all elements. 2) currently cannot select subtree (must always select leaf node).
<br><br>As alternatives, I recommend the much simpler JSON::Path, or the more powerful Data::DPath.

 view all matches for this distribution


Acme-Dzil-Plugin-Tester

 view release on metacpan or  search on metacpan

perltidyrc  view on Meta::CPAN

-npro
-nsfs
--blank-lines-before-packages=0
--opening-hash-brace-right
--no-outdent-long-comments
--iterations=2
-wbb="% + - * / x != == >= <= =~ !~ < > | & >= < = **= += *= &= <<= &&= -= /= |= >>= ||= .= %= ^= x="

 view all matches for this distribution


Acme-HTTP

 view release on metacpan or  search on metacpan

lib/Acme/HTTP.pm  view on Meta::CPAN

    $Redir_act = 0;

    while (defined $url) {
        $Redir_act++;
        if ($Redir_act > $Redir_max) {
            $@ = 'Acme::HTTP - Runaway iterations ('.$Redir_max.')';
            return;
        }

        $Url_act = $url;

 view all matches for this distribution


Acme-Lingua-ZH-Remix

 view release on metacpan or  search on metacpan

lib/Acme/Lingua/ZH/Remix.pm  view on Meta::CPAN

values are invalidate, it is treated as if they are not passed.

The default values of min, max are 0 and 140, respectively.

The implementation random algorthm based, thus it needs indefinite time to
generate the result. If it takes more then 1000 iterations, it aborts and return
the results anyway, regardless the length constraint. This can happen when the
lengths of phrases from corpus do no adds up to a value within the given range.

The returned scalar is the generate sentence string of wide characters. (Which
makes Encode::is_utf8 return true.)

lib/Acme/Lingua/ZH/Remix.pm  view on Meta::CPAN


    unshift @phrases, $ending;

    my $l = length($ending);

    my $iterations = 0;
    my $max_iterations = 1000;
    my $average = ($options{min} + $options{max}) / 2;
    my $desired = int(rand($options{max} - $options{min}) + $options{min}) || $average || $options{max};

    while ($iterations++ < $max_iterations) {
        my $x;
        do {
            $x = random(',', '」', ')', '/')
        } while ($self->phrase_ratio($x) == 0);

lib/Acme/Lingua/ZH/Remix.pm  view on Meta::CPAN

            $l += length($p);
        }

        my $r = abs(1 - $l/$desired);
        last if $r < 0.1;
        last if $r < 0.2 && $iterations >= $max_iterations/2;
    }

    $str = join "", @phrases;
    $str =~ s/,$//;
    $str =~ s/^「(.+)」$/$1/;

 view all matches for this distribution


Acme-Loopy

 view release on metacpan or  search on metacpan

lib/Acme/Loopy.pm  view on Meta::CPAN

		my @row = get_data() or last;
		
		# First iteration only
		print table_headers(\@row) unless ${^LOOP};
		
		# All iterations
		print table_row(\@row);
	}

=head1 DESCRIPTION

 view all matches for this distribution


Acme-MetaSyntactic-Themes

 view release on metacpan or  search on metacpan

lib/Acme/MetaSyntactic/alphabet.pm  view on Meta::CPAN


=head1 DESCRIPTION

Various alphabets, transliterated if the latin alphabet doesn't fit.

I've found most of the transliterations on the Internet, which may
be wrong. Please correct me.

=head1 CONTRIBUTOR

Philippe "BooK" Bruhat.

 view all matches for this distribution


Acme-Parataxis

 view release on metacpan or  search on metacpan

eg/stress_fibers.pl  view on Meta::CPAN


# Stress Test 1: High Fiber Count & Rapid Lifecycle
# This tests the scheduler's ability to handle many short-lived fibers.
async {
    my $total_fibers = 1000;    # We increased MAX_FIBERS in the C code to 1024
    my $iterations   = 5;
    say "Starting Stress Test: $total_fibers fibers, $iterations iterations...";
    my $start_time = time();
    for my $iter ( 1 .. $iterations ) {
        my $iter_start = time();
        my @futures;

        # Spawn a batch of fibers
        for my $i ( 1 .. $total_fibers ) {

eg/stress_fibers.pl  view on Meta::CPAN

        }
        my $elapsed = time() - $iter_start;
        say sprintf '  Iteration %2d completed in %.4fs', $iter, $elapsed;
    }
    my $total_elapsed = time() - $start_time;
    say sprintf 'Total time for %d fibers across %d iterations: %.4fs', $total_fibers, $iterations, $total_elapsed;
    say 'Average time per fiber lifecycle: ' . ( $total_elapsed / ( $total_fibers * $iterations ) ) . 's';
};

 view all matches for this distribution


Acme-ProgressBar

 view release on metacpan or  search on metacpan

lib/Acme/ProgressBar.pm  view on Meta::CPAN

#pod  progress { while (<>) { $ua->get($_) } };
#pod  progress { sleep 5; }
#pod
#pod There is only one function exported by default, C<progress>.  This function
#pod takes a coderef as its lone argument.  It will execute this code and display a
#pod simple progress bar indicating the time required for ten iterations through the
#pod code.
#pod
#pod =cut

sub progress(&) { ## no critic Prototype

lib/Acme/ProgressBar.pm  view on Meta::CPAN

 progress { while (<>) { $ua->get($_) } };
 progress { sleep 5; }

There is only one function exported by default, C<progress>.  This function
takes a coderef as its lone argument.  It will execute this code and display a
simple progress bar indicating the time required for ten iterations through the
code.

=head1 TODO

=over 4

 view all matches for this distribution


Acme-Sort-Bogosort

 view release on metacpan or  search on metacpan

lib/Acme/Sort/Bogosort.pm  view on Meta::CPAN

finding a solution decline toward zero (assuming a good random number generator).  The average 
case is O( (n-1) * n! ).  The n! term signifies how many shuffles will be required to obtain 
a sorted result in the average case.  However, there is no guarantee that any particular sort 
will come in anywhere near average.

Keep in mind that a list of five items consumes an average of 5!, or 120 iterations.  10! is 
3,628,800 shuffles.  Also keep in mind that each shuffle itself is an O(n-1) operation.  
Unless you need to heat a cold office with your processor avoid sorts on large data sets.

=head1 EXPORT

lib/Acme/Sort/Bogosort.pm  view on Meta::CPAN

If the first parameter is a reference to a subroutine, it will be used as the
comparison function.

The Bogosort is probably mostly useful as a teaching example of a terrible sort 
algorithm.  There are approximately 1e80 atoms in the universe.  A sort list of 
59 elements will gain an average case solution of 1e80 iterations, with a worst 
case approaching infinite iterations to find a solution.  Anything beyond just a 
few items takes a considerable amount of work.

Each iteration checks first to see if the list is in order.  Here a comparatively 
minor optimization is that the first out-of-order element will short-circuit the 
check.  That step has a worst case of O(n), and average case of nearly O(1).  

lib/Acme/Sort/Bogosort.pm  view on Meta::CPAN

of order, the entire list is shuffled (an O(n) operation).  Then the test happens 
all over again, repeating until a solution is happened across by chance.

There is a potential for this sort to never finish, since a typical random number
synthesizer does not generate an infinitely non-repeating series.  Because this 
algorithm has the capability of producing O(INF) iterations, it would need an 
infinite source of random numbers to find a solution in any given dataset.  

Small datasets are unlikely to encounter this problem, but as the dataset grows, 
so does the propensity for running through the entire set of pseudo-random numbers 
generated by Perl's rand() for a given seed.  None of this really matters, of course, 

 view all matches for this distribution


Acme-Sort-Bozo

 view release on metacpan or  search on metacpan

lib/Acme/Sort/Bozo.pm  view on Meta::CPAN

results soon enough.  The average case is O( n * n! ).  However, there is no 
guarantee that any particular sort will come in anywhere near average.  Where the bogosort is a 'stateless'
sort, the bozo sort maintains a list state from one iteration to the next, but its decision mechanism for swaps I<is>
stateless; it blindly swaps any random two elements.

Keep in mind that a list of five items consumes an average of 5 * 5!, or 600 iterations.  10! is 
36,288,000 iterations on average.  The universe will either collapse or expand to the point that it cannot sustain
life long before the Bozo sort manages to sort a deck of cards, in the average case.  In the worst case, all of the
background radiation from our universe will have decayed to the point that there is no longer any trace of our 
existence before this sort manages to alphabetically sort your social networking friends list.

Test with short (4 to 7 element) lists, and be prepared to kill the process if you mistakenly hand it more elements

lib/Acme/Sort/Bozo.pm  view on Meta::CPAN

If the first parameter is a reference to a subroutine, it will be used as the
comparison function.

The Bozo is probably mostly useful as a teaching example of a "perversely awful"  sort 
algorithm.  There are approximately 1e80 atoms in the universe.  A sort list of 
59 elements will gain an average case solution of 5.9e81 iterations, with a worst 
case approaching infinite iterations to find a solution.  Anything beyond just a 
few items takes a considerable amount of work.

Each iteration checks first to see if the list is in order.  Here a comparatively 
minor optimization is that the first out-of-order element will short-circuit the 
check.  That step has a worst case of O(n), and average case of nearly O(1).  

lib/Acme/Sort/Bozo.pm  view on Meta::CPAN

of order, a pair of elements (not necessarily adjacent) are chosen at random, and swapped.
Then the test happens all over again, repeating until a solution is happened across by chance.

There is a potential for this sort to never finish, since a typical random number
synthesizer does not generate an infinitely non-repeating series.  Because this 
algorithm has the capability of producing O(INF) iterations, it would need an 
infinite source of random numbers to find a solution in any given dataset.  

Small datasets are unlikely to encounter this problem, but as the dataset grows, 
so does the propensity for running through the entire set of pseudo-random numbers 
generated by Perl's rand() for a given seed.  None of this really matters, of course, 

 view all matches for this distribution


Acme-Tie-Eleet

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

0.17  Fri Feb  1 17:37:48 CET 2002
 - new translitterations thanks to Moun's and
   http://www.google.com/intl/xx-hacker/

0.16  Fri Feb  1 16:57:23 CET 2002
 - new transliterations thanks to Moun's
 - spacer on by default

0.15  Wed Jan 30 17:16:10 CET 2002
 - some code cleaning

 view all matches for this distribution


Acme-Tools

 view release on metacpan or  search on metacpan

Tools.pm  view on Meta::CPAN

  harmonicavg
  stddev
  rstddev
  median
  percentile
  $Resolve_iterations
  $Resolve_last_estimate
  $Resolve_time
  resolve
  resolve_equation
  conv

Tools.pm  view on Meta::CPAN


Third argument: a start position for x. Default 0.

Fourth argument: a small delta value. Default 1e-4 (0.0001).

Fifth argument: a maximum number of iterations before resolve gives up
and carps. Default 100 (if fifth argument is not given or is
undef). The number 0 means infinite here.  If the derivative of the
start position is zero or close to zero more iterations are typically
needed.

Sixth argument: A number of seconds to run before giving up.  If both
fifth and sixth argument is given and > 0, C<resolve> stops at
whichever comes first.

Tools.pm  view on Meta::CPAN

The result of C<resolve> will depend on the start position:

 print resolve(sub{ $_**2 - 4*$_ - 21 });                     # -3 with $_ as your x
 print resolve(sub{ my $x=shift; $x**2 - 4*$x - 21 });        # -3 more elaborate call
 print resolve(sub{ my $x=shift; $x**2 - 4*$x - 21 },0,3);    # 7  with start position 3
 print "Iterations: $Acme::Tools::Resolve_iterations\n";      # 3 or larger, about 10-15 is normal

The variable C< $Acme::Tools::Resolve_iterations > (which is exported) will be set
to the last number of iterations C<resolve> used. Also if C<resolve> dies (carps).

The variable C< $Acme::Tools::Resolve_last_estimate > (which is exported) will be
set to the last estimate. This number will often be close to the solution and can
be used even if C<resolve> dies (carps).

Tools.pm  view on Meta::CPAN


L<http://en.wikipedia.org/wiki/Golden_ratio>

=cut

our $Resolve_iterations;
our $Resolve_last_estimate;
our $Resolve_time;

#sub resolve(\[&$]@) {
#sub resolve(&@) { <=0.17
#todo: perl -MAcme::Tools -le'print resolve(sub{$_[0]**2-9431**2});print$Acme::Tools::Resolve_iterations'
#todo: perl -MAcme::Tools -le'sub d{5.3*1.0094**$_[0]-10.2*1.0072**$_[0]} print resolve(\&d)' #err, pop norway vs sweden
#todo: perl -MAcme::Tools -le' print resolve(sub{5.3*1.0094**$_[0]-10.2*1.0072**$_[0]})' #err, pop norway vs sweden
#    =>Div by zero: df(x) = 0 at n'th iteration, n=0, delta=0.0001, fx=CODE(0xc81d470) at -e line 1
#todo: ren solve?
sub resolve {

Tools.pm  view on Meta::CPAN

  $delta=1e-4  if!defined$delta;
  $iters=100   if!defined$iters;
  $sec=0       if!defined$sec;
  $iters=13e13 if $iters==0;
  croak "Iterations ($iters) or seconds ($sec) can not be a negative number" if $iters<0 or $sec<0;
  $Resolve_iterations=undef;
  $Resolve_last_estimate=undef;
  croak "Should have at least 1 argument, a coderef" if !@_;
  croak "First argument should be a coderef" if ref($f) ne 'CODE';

  my @x=($start);

Tools.pm  view on Meta::CPAN

    $fd   = &$fx($x[$n]+$delta*0.2) - &$fx($x[$n]-$delta*0.8) if $fd==0;# and warn"wigle 2\n";
    croak "Div by zero: df(x) = $x[$n] at n'th iteration, n=$n, delta=$delta, fx=$fx" if $fd==0;
    $x[$n+1]=$x[$n]-(&$fx($x[$n])-$goal)/($fd/$delta);
    $Resolve_last_estimate=$x[$n+1];
    #warn "n=$n  fd=$fd  x=$x[$n+1]\n";
    $Resolve_iterations=$n;
    last if $n>3 and $x[$n+1]==$x[$n] and $x[$n]==$x[$n-1];
    last if $n>4 and $x[$n]!=0 and abs(1-$x[$n+1]/$x[$n])<1e-13; #sub{3*$_+$_**4-12}
    last if $n>3 and ref($x[$n+1]) eq 'Math::BigFloat' and substr($x[$n+1],0,$ds) eq substr($x[$n],0,$ds); #hm
    croak "Could not resolve, perhaps too little time given ($sec), iteratons=$n"
      if $sec>0 and ($Resolve_time=time_fp()-$time_start)>$sec;
    #warn "$n: ".$x[$n+1]."\n";
    $n++;
  }
  croak "Could not resolve, perhaps too few iterations ($iters)" if @x>=$iters;
  return $x[-1];
}

=head2 resolve_equation

 view all matches for this distribution


( run in 1.137 second using v1.01-cache-2.11-cpan-96521ef73a4 )