text:
=head1 LICENSE

# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2018] EMBL-European Bioinformatics Institute
#
# 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.

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=cut

=head1 NAME

Bio::EnsEMBL::Analysis::Runnable::AlignmentNets -

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 METHODS

=cut

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _

=cut

# Let the code begin...

package Bio::EnsEMBL::Analysis::Runnable::AlignmentNets;

use warnings ;
use vars qw(@ISA);
use strict;

use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::Argument qw( rearrange );

use Bio::EnsEMBL::Analysis::Runnable;
use Bio::EnsEMBL::DnaDnaAlignFeature;

@ISA = qw(Bio::EnsEMBL::Analysis::Runnable);

sub new {
  my ($class,@args) = @_;

  my $self = $class->SUPER::new(@args);

  my ($chains,
      $chains_sorted,
      $query_lengths,
      $target_lengths,
      $chain_net,
      $net_syntenic,
      $net_filter,
      $filter_non_syntenic,
      $min_chain_score
      ) = rearrange([qw(
                        CHAINS
                        CHAINS_SORTED
                        QUERY_LENGTHS
                        TARGET_LENGTHS
                        CHAINNET
                        NETSYNTENIC
                        NETFILTER
                        FILTER_NON_SYNTENIC
                        MIN_CHAIN_SCORE
                        )],
                    @args);

  throw("You must supply a ref to array of alignment chains")
      if not defined $chains;
  throw("You must supply a reference to an hash of query seq. lengths")
      if not defined $query_lengths;
  throw("You must supply a reference to an hash of query seq. lengths")
      if not defined $target_lengths;
  throw("You must supply the chainNet executable")
      if not defined $chain_net;

  if (defined $filter_non_syntenic) {
    throw("You must supply the netSyntenic executable when doing synteny filtering")
        if not defined $net_syntenic;
    throw("You must supply the netFilter executable when doing synteny filtering")
        if not defined $net_filter;
  }

  $self->query_length_hash($query_lengths);
  $self->target_length_hash($target_lengths);

  $self->chainNet($chain_net);

  $self->filter_non_syntenic($filter_non_syntenic) if defined $filter_non_syntenic;
  $self->netSyntenic($net_syntenic) if defined $net_syntenic;
  $self->netFilter($net_filter) if defined $net_filter;

  $self->min_chain_score($min_chain_score) if defined $min_chain_score;
  $self->chains($chains);
  $self->chains_sorted(defined $chains_sorted ? $chains_sorted : 0 );

  return $self;
}

=head2 run

  Title   : run
  Usage   : $self->run()
  Function:
  Returns : none
  Args    :

=cut

sub run {
  my ($self) = @_;

  my $res_chains;

  my ($query_name) = keys %{$self->query_length_hash};
  my $work_dir = $self->workdir . "/$query_name.$$.ChainNet";
  while (-e $work_dir) {
    $work_dir .= ".$$";
  }

  my $chain_file = "$work_dir/$query_name.chain";
  my $query_length_file  = "$work_dir/$query_name.query.lengths";
  my $target_length_file = "$work_dir/$query_name.target.lengths";
  my $query_net_file     = "$work_dir/$query_name.query.net";
  my $target_net_file    = "$work_dir/$query_name.target.net";
  my $fh;

  mkdir $work_dir;

  ##############################
  # write the seq length files
  ##############################
  foreach my $el ([$query_length_file, $self->query_length_hash],
                  [$target_length_file, $self->target_length_hash]) {
    my ($file, $hash) = @$el;

    open $fh, ">$file" or
        throw("Could not open seq length file '$file' for writing");
    foreach my $k (keys %{$hash}) {
      print $fh $k, "\t", $hash->{$k}, "\n";
    }
    close($fh);
  }

  ##############################
  # sort chains, if necessary
  ##############################
  if (not $self->chains_sorted) {
    for(my $i=0; $i < @{$self->chains}; $i++) {
      if ($self->chains->[$i]->[0]->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
        $self->chains->[$i] = [
                               sort {
                                 $a->reference_genomic_align->dnafrag_start <=>
                                 $a->reference_genomic_align->dnafrag_end
                               } @{$self->chains->[$i]}
                               ];
      } else {
        $self->chains->[$i] = [
                               sort { $a->start <=> $b->start } @{$self->chains->[$i]}
                               ];
      }
    }
  }

  ##############################
  # write chains
  ##############################
  open $fh, ">$chain_file" or
      throw("could not open chain file '$chain_file' for writing\n");
  $self->write_chains($fh);
  close($fh);

  ##################################
  # Get the Nets from chainNet
  ##################################
  my @arg_list;
  if (defined $self->min_chain_score) {
    @arg_list = ("-minScore=" . $self->min_chain_score);
  }
  push @arg_list, ($chain_file,
                   $query_length_file,
                   $target_length_file,
                   $query_net_file,
                   $target_net_file);

  system($self->chainNet, @arg_list)
      and throw("Something went wrong with chainNet");

  ##################################
  # Apply the synteny filter if requested
  ##################################
  if ($self->filter_non_syntenic) {
    my $syntenic_net_file = "$work_dir/$query_name.query.synteny_annotated.net";
    my $filtered_net_file = "$work_dir/$query_name.query.synteny.net";

    system($self->netSyntenic, $query_net_file, $syntenic_net_file)
        and throw("Something went wrong with netSyntenic");
    open(FILTER, $self->netFilter . " -syn $syntenic_net_file |") or
        throw("Could not run netFilter");
    open(FILTERED,">$filtered_net_file")
        or throw("Could not open filtered net file for writing");
    while(<FILTER>) {
      print FILTERED $_;
    }
    close(FILTERED);
    close(FILTER) or throw("Something went wrong with netFilter");

    unlink $syntenic_net_file;
    unlink $query_net_file;
    $query_net_file = $filtered_net_file;
  }

  open $fh, $query_net_file or
      throw("Could not open net file '$query_net_file' for reading\n");
  $res_chains = $self->parse_Net_file($fh);
  close($fh);

  unlink $chain_file, $query_length_file, $target_length_file, $query_net_file, $target_net_file;
  rmdir $work_dir;
  $self->output($res_chains);

  return 1;
}

#####################################################

sub write_chains {
  my ($self, $fh) = @_;

  # in the absence of a chain score, we will take the score of the
  # first block in the chain to be the score

  for(my $chain_id=1; $chain_id <= @{$self->chains}; $chain_id++) {
    my $chain = $self->chains->[$chain_id-1];

    my (@ungapped_features,
        $chain_score,
        $query_name,
        $query_strand,
        $target_name,
        $target_strand);

    foreach my $gf (@$chain) {
      if (not defined $query_name) {
        # all members of the chain must come from the same
        # query and target, and be on the same strand on those
        # sequences, otherwise all bets are off

        if ($gf->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
          my $qga = $gf->reference_genomic_align;
          my ($tga) = @{$gf->get_all_non_reference_genomic_aligns};

          $query_name = $qga->dnafrag->name,
          $target_name = $tga->dnafrag->name,
          $query_strand = $qga->dnafrag_strand;
          $target_strand = $tga->dnafrag_strand;

        } else {
          # assume Bio::EnsEMBL::DnaDnaAlignFeature
          $query_name = $gf->seqname;
          $target_name = $gf->hseqname,
          $query_strand = $gf->strand;
          $target_strand = $gf->hstrand;
        }

        # the chain must be written with respect to the forward strand
        # of the query. Since we are dealing with the ungapped blocks below,
        # this can be achieved by swapping the strands if the query is reverse.
        if ($query_strand == -1) {
          $query_strand  *= -1;
          $target_strand *= -1;
        }
      }

      if (not defined $chain_score or $chain_score < $gf->score) {
        $chain_score = $gf->score;
      }

      if ($gf->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
        foreach my $uf (@{$gf->get_all_ungapped_GenomicAlignBlocks}) {
          my $qga = $uf->reference_genomic_align;
          my ($tga) = @{$uf->get_all_non_reference_genomic_aligns};

          my $sens_f = {
            q_start  => $qga->dnafrag_start,
            q_end    => $qga->dnafrag_end,
            t_start  => $tga->dnafrag_start,
            t_end    => $tga->dnafrag_end,
            len      => $qga->dnafrag_end - $qga->dnafrag_start + 1,
          };

          if ($target_strand == -1) {
            $sens_f->{t_start} = $self->target_length_hash->{$tga->dnafrag->name} - $tga->dnafrag_end + 1;
            $sens_f->{t_end}   = $self->target_length_hash->{$tga->dnafrag->name} - $tga->dnafrag_start + 1;
          }

          push @ungapped_features, $sens_f;
        }
      } else {
        foreach my $uf ($gf->ungapped_features) {

          my $sens_f = {
            q_start  => $uf->start,
            q_end    => $uf->end,
            t_start  => $uf->hstart,
            t_end    => $uf->hend,
            len      => $uf->end - $uf->start + 1,
          };

          if ($target_strand == -1) {
            $sens_f->{t_start} = $self->target_length_hash->{$uf->hseqname} - $uf->hend + 1;
            $sens_f->{t_end}   = $self->target_length_hash->{$uf->hseqname} - $uf->hstart + 1;
          }

          push @ungapped_features, $sens_f;
        }
      }
    }

    @ungapped_features = sort {$a->{q_start} <=> $b->{q_start}} @ungapped_features;

    # write chain header here
#    printf($fh "chain %d %s %d %s %d %d %s %d %s %s %s %d\n",
    print $fh join(" ",("chain",
           $chain_score,
           $query_name,
           $self->query_length_hash->{$query_name},
           $query_strand == -1 ? "-" : "+",
           $ungapped_features[0]->{q_start} - 1,
           $ungapped_features[-1]->{q_end},
           $target_name,
           $self->target_length_hash->{$target_name},
           $target_strand == -1 ? "-" : "+",
           $ungapped_features[0]->{t_start} - 1,
           $ungapped_features[-1]->{t_end},
           $chain_id)), "\n";

    for (my $i = 0; $i < @ungapped_features; $i++) {
      my $f = $ungapped_features[$i];

      print $fh $f->{len};

      if ($i == @ungapped_features - 1) {
        print $fh "\n";
      } else {
        my $next_f = $ungapped_features[$i+1];
        my $q_gap = $next_f->{q_start} - $f->{q_end} - 1;
        my $t_gap = $next_f->{t_start} - $f->{t_end} - 1;

        print $fh "\t$q_gap\t$t_gap\n";
      }
    }
    print $fh "\n";
  }
}

sub parse_Net_file {
  my ($self, $fh) = @_;

  my (%new_chains, %new_chain_scores, @last_gap, @last_parent_chain);

  while(<$fh>) {

    /(\s+)fill\s+(\d+)\s+(\d+)\s+\S+\s+\S+\s+\d+\s+\d+\s+(.+)$/ and do {
      my $indent = length($1) - 1;
      my $level_id = int( $indent / 2 ) + 1;
      my $q_start  = $2 + 1;
      my $q_end    = $q_start + $3 - 1;
      my $rest     = $4;

      my ($score)    = $rest =~ /score\s+(\d+)/;
      my ($chain_id) = $rest =~ /id\s+(\d+)/;

      $new_chain_scores{$chain_id} += $score;

      next if (!defined $self->chains->[$chain_id-1]);

      my ($restricted_fps)
         = $self->restrict_between_positions($self->chains->[$chain_id-1],
                                            $q_start,
                                            $q_end);

      foreach my $fp (@$restricted_fps) {
        $fp->score($score);
	$fp->level_id($level_id);
      }

      if (@$restricted_fps) {
        push @{$new_chains{$chain_id}}, @$restricted_fps;

        if ($indent > 0) {
          # the new alignment has been inserted into the parent gap
          # need to split parent chain into two:
          #  begin -> $insert_start - 1,
          #  $insert_end + 1 -> end
          my $parent_chain = $new_chains{$last_parent_chain[$indent - 2]};

          my ($insert_start, $insert_end) = ($last_gap[$indent - 1]->[0],
                                             $last_gap[$indent - 1]->[1]);
          my ($left_start, $right_end);
          if ($parent_chain->[0]->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
            $left_start = $parent_chain->[0]->reference_genomic_align->dnafrag_start;
          } else {
            $left_start = $parent_chain->[0]->start;
          }
          if ($parent_chain->[-1]->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
            $right_end = $parent_chain->[-1]->reference_genomic_align->dnafrag_end;
          } else {
            $right_end = $parent_chain->[-1]->end;
          }

          my ($chain1) = $self->restrict_between_positions($parent_chain,
                                                         $left_start,
                                                         $insert_start - 1);
          my ($chain2) = $self->restrict_between_positions($parent_chain,
                                                         $insert_end + 1,
                                                         $right_end);

          $new_chains{$last_parent_chain[$indent - 2]} = [@$chain1, @$chain2];
        }
        $last_parent_chain[$indent] = $chain_id;
      }
    };
    /^(\s+)gap\s+(\d+)\s+(\d+)/ and do {
      my $indent = length($1) - 1;

      my $q_insert_start = $2 + 1;
      my $q_insert_end = $q_insert_start + $3 - 1;

      $last_gap[$indent] = [$q_insert_start, $q_insert_end];
    };

  }
  foreach my $cid (keys %new_chains) {
    my $chain_score = $new_chain_scores{$cid};
    foreach my $fp (@{$new_chains{$cid}}) {
      $fp->score($chain_score);
    }
  }
  return [values %new_chains];
}

sub restrict_between_positions {
  my ($self, $chain, $q_start, $q_end) = @_;

  #my @blocks = @$chain;

  my @new_chain;
  #my $chain_left = [];
  #my $chain_right = [];

  my $first_idx = $self->_bin_search_start($chain, $q_start);
  my $last_idx = $self->_bin_search_end($chain, $q_end);

  if ($first_idx < 0) {
    # all blocks to left of range

    #$chain_left = $chain;
    #$chain_right = [];
  } elsif ($last_idx < 0) {
    # all blocks to right of range

    #$chain_left = [];
    #$chain_right = $chain;
  } else {

    if ($first_idx > 0) {
      #@$chain_left = @{@$chain}[0..$first_idx-1];
    }
    if ($last_idx < scalar(@$chain) - 1) {
      #@$chain_right = @{@$chain}[$last_idx+1..scalar(@$chain)-1];
    }

    if ($first_idx <= $last_idx) {
      @new_chain = @{$chain}[$first_idx..$last_idx];
    }

    # may be necessary to cut the boundary blocks

    if (@new_chain) {
      my $block = shift @new_chain;
      my $b_start = $block->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")
          ? $block->reference_genomic_align->dnafrag_start
          : $block->start;
      my $b_end = $block->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")
          ? $block->reference_genomic_align->dnafrag_end
          : $block->end;

      if ($b_start < $q_start) {
        # need to cut the block;
        my $inside;
        # my $outside

        if ($block->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
          #$outside = $block->restrict_between_reference_positions($b_start, $q_start - 1);
          $inside  = $block->restrict_between_reference_positions($q_start, $b_end);
        } else {
          #$outside = $block->restrict_between_positions($b_start, $q_start - 1, "SEQ");
          $inside = $block->restrict_between_positions($q_start, $b_end, "SEQ");
        }

        #push @$chain_left, $outside;
        unshift @new_chain, $inside;
      } else {
        unshift @new_chain, $block;
      }

      $block = pop @new_chain;
      $b_start = $block->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")
          ? $block->reference_genomic_align->dnafrag_start
          : $block->start;
      $b_end = $block->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")
          ? $block->reference_genomic_align->dnafrag_end
          : $block->end;

      if ($b_end > $q_end) {
        # need to cut the block;
        my $inside;
        #my $outside;

        if ($block->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
          $inside  = $block->restrict_between_reference_positions($b_start, $q_end);
          #$outside = $block->restrict_between_reference_positions($q_end + 1, $b_end);
        } else {
          $inside  = $block->restrict_between_positions($b_start, $q_end, "SEQ");
          #$outside = $block->restrict_between_positions($q_end + 1, $b_end, "SEQ");
        }

        #unshift @$chain_right, $outside;
        push @new_chain, $inside;
      } else {
        push @new_chain, $block;
      }
    }
  }

  #return (\@new_chain,
  #        $chain_left,
  #        $chain_right);
  return (\@new_chain);

}

sub _bin_search_start {
  my ($self, $blocks, $position) = @_;

  # find index of left-most block that ends to the right of $position
  my ($left, $right) = (0, scalar(@$blocks));
  while ($right - $left > 0) {
    my $mid = int(($left + $right) / 2);

    my ($block_end, $block_start);
    if ($blocks->[0]->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
      $block_end   = $blocks->[$mid]->reference_genomic_align->dnafrag_end;
    } else {
      $block_end   = $blocks->[$mid]->end;
    }

    if ($block_end < $position) {
      $left = $mid + 1;
    } else {
      $right = $mid;
    }

  }

  if ($right > scalar(@$blocks)-1) {
    return -1;
  } else {
    return $right;
  }
}

sub _bin_search_end {
  my ($self, $blocks, $position) = @_;

  # find index of rightmost block that starts before $position
  my ($left, $right) = (-1, scalar(@$blocks)-1);
  while ($right - $left > 0) {
    my $mid = int(($left + $right + 1) / 2);

    my ($block_end, $block_start);
    if ($blocks->[0]->isa("Bio::EnsEMBL::Compara::GenomicAlignBlock")) {
      $block_start = $blocks->[$mid]->reference_genomic_align->dnafrag_start;
    } else {
      $block_start = $blocks->[$mid]->start;
    }

    if ($block_start > $position) {
      $right = $mid - 1;
    } else {
      $left = $mid;
    }

  }

  # returns -1 if all blocks to right of $position
  return $right;
}

#####################
# instance vars
#####################

sub query_length_hash {
  my ($self, $val) = @_;

  if (defined $val) {
    $self->{_query_lengths_hashref} = $val;
  }
  return $self->{_query_lengths_hashref};
}

sub target_length_hash {
  my ($self, $hash_ref) = @_;

  if (defined $hash_ref) {
    $self->{_target_lengths_hashref} = $hash_ref;
  }
  return $self->{_target_lengths_hashref};
}

sub chains {
  my ($self, $val) = @_;

  if (defined $val) {
    $self->{_chains} = $val;
  }

  return $self->{_chains};
}

sub chains_sorted {
  my ($self, $val) = @_;

  if (defined $val) {
    $self->{_chains_sorted} = $val;
  }

  return $self->{_chains_sorted};
}

sub filter_non_syntenic {
  my ($self, $val) = @_;

  if (defined $val) {
    $self->{_filter_non_syntenic} = $val;
  }

  return $self->{_filter_non_syntenic};
}

sub min_chain_score {
  my ($self, $val) = @_;

  if (defined $val) {
    $self->{_min_chain_score} = $val;
  }

  if (not exists $self->{_min_chain_score}) {
    return undef;
  } else {
    return $self->{_min_chain_score};
  }
}

##############
#### programs
##############

sub chainNet {
  my ($self,$arg) = @_;

  if (defined($arg)) {
    $self->{_chainNet} = $arg;
  }

  return $self->{_chainNet};
}

sub netSyntenic {
  my ($self,$arg) = @_;

  if (defined($arg)) {
    $self->{_netSyntenic} = $arg;
  }

  return $self->{_netSyntenic};
}

sub netFilter {
  my ($self,$arg) = @_;

  if (defined($arg)) {
    $self->{_netFilter} = $arg;
  }

  return $self->{_netFilter};
}

1;


text:
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'

module Google
  module Apis
    module CloudresourcemanagerV1

      class Constraint
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Status
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListLiensResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Binding
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class GetOrgPolicyRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class RestoreDefault
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class UndeleteProjectRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ClearOrgPolicyRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ProjectCreationStatus
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class BooleanConstraint
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class GetIamPolicyRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class TestIamPermissionsResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class OrganizationOwner
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListProjectsResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Project
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class SearchOrganizationsResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListOrgPoliciesResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class FolderOperationError
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class OrgPolicy
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class BooleanPolicy
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Lien
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Ancestor
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListConstraint
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class SetOrgPolicyRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class SetIamPolicyRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Empty
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Organization
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListAvailableOrgPolicyConstraintsResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListPolicy
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class GetAncestryResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class AuditLogConfig
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class SearchOrganizationsRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class GetAncestryRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class TestIamPermissionsRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListAvailableOrgPolicyConstraintsRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Policy
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class FolderOperation
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ResourceId
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class GetEffectiveOrgPolicyRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListOrgPoliciesRequest
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Operation
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class AuditConfig
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Constraint
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :description, as: 'description'
          property :display_name, as: 'displayName'
          property :boolean_constraint, as: 'booleanConstraint', class: Google::Apis::CloudresourcemanagerV1::BooleanConstraint, decorator: Google::Apis::CloudresourcemanagerV1::BooleanConstraint::Representation

          property :constraint_default, as: 'constraintDefault'
          property :name, as: 'name'
          property :version, as: 'version'
          property :list_constraint, as: 'listConstraint', class: Google::Apis::CloudresourcemanagerV1::ListConstraint, decorator: Google::Apis::CloudresourcemanagerV1::ListConstraint::Representation

        end
      end

      class Status
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          collection :details, as: 'details'
          property :code, as: 'code'
          property :message, as: 'message'
        end
      end

      class ListLiensResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :next_page_token, as: 'nextPageToken'
          collection :liens, as: 'liens', class: Google::Apis::CloudresourcemanagerV1::Lien, decorator: Google::Apis::CloudresourcemanagerV1::Lien::Representation

        end
      end

      class Binding
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          collection :members, as: 'members'
          property :role, as: 'role'
        end
      end

      class GetOrgPolicyRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :constraint, as: 'constraint'
        end
      end

      class RestoreDefault
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
        end
      end

      class UndeleteProjectRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
        end
      end

      class ClearOrgPolicyRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :etag, :base64 => true, as: 'etag'
          property :constraint, as: 'constraint'
        end
      end

      class ProjectCreationStatus
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :ready, as: 'ready'
          property :create_time, as: 'createTime'
          property :gettable, as: 'gettable'
        end
      end

      class BooleanConstraint
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
        end
      end

      class GetIamPolicyRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
        end
      end

      class TestIamPermissionsResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          collection :permissions, as: 'permissions'
        end
      end

      class OrganizationOwner
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :directory_customer_id, as: 'directoryCustomerId'
        end
      end

      class ListProjectsResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :next_page_token, as: 'nextPageToken'
          collection :projects, as: 'projects', class: Google::Apis::CloudresourcemanagerV1::Project, decorator: Google::Apis::CloudresourcemanagerV1::Project::Representation

        end
      end

      class Project
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :lifecycle_state, as: 'lifecycleState'
          property :project_number, :numeric_string => true, as: 'projectNumber'
          property :parent, as: 'parent', class: Google::Apis::CloudresourcemanagerV1::ResourceId, decorator: Google::Apis::CloudresourcemanagerV1::ResourceId::Representation

          hash :labels, as: 'labels'
          property :create_time, as: 'createTime'
          property :name, as: 'name'
          property :project_id, as: 'projectId'
        end
      end

      class SearchOrganizationsResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :next_page_token, as: 'nextPageToken'
          collection :organizations, as: 'organizations', class: Google::Apis::CloudresourcemanagerV1::Organization, decorator: Google::Apis::CloudresourcemanagerV1::Organization::Representation

        end
      end

      class ListOrgPoliciesResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          collection :policies, as: 'policies', class: Google::Apis::CloudresourcemanagerV1::OrgPolicy, decorator: Google::Apis::CloudresourcemanagerV1::OrgPolicy::Representation

          property :next_page_token, as: 'nextPageToken'
        end
      end

      class FolderOperationError
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :error_message_id, as: 'errorMessageId'
        end
      end

      class OrgPolicy
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :version, as: 'version'
          property :restore_default, as: 'restoreDefault', class: Google::Apis::CloudresourcemanagerV1::RestoreDefault, decorator: Google::Apis::CloudresourcemanagerV1::RestoreDefault::Representation

          property :list_policy, as: 'listPolicy', class: Google::Apis::CloudresourcemanagerV1::ListPolicy, decorator: Google::Apis::CloudresourcemanagerV1::ListPolicy::Representation

          property :etag, :base64 => true, as: 'etag'
          property :constraint, as: 'constraint'
          property :boolean_policy, as: 'booleanPolicy', class: Google::Apis::CloudresourcemanagerV1::BooleanPolicy, decorator: Google::Apis::CloudresourcemanagerV1::BooleanPolicy::Representation

          property :update_time, as: 'updateTime'
        end
      end

      class BooleanPolicy
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :enforced, as: 'enforced'
        end
      end

      class Lien
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :parent, as: 'parent'
          property :create_time, as: 'createTime'
          property :name, as: 'name'
          property :reason, as: 'reason'
          property :origin, as: 'origin'
          collection :restrictions, as: 'restrictions'
        end
      end

      class Ancestor
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :resource_id, as: 'resourceId', class: Google::Apis::CloudresourcemanagerV1::ResourceId, decorator: Google::Apis::CloudresourcemanagerV1::ResourceId::Representation

        end
      end

      class ListConstraint
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :suggested_value, as: 'suggestedValue'
        end
      end

      class SetOrgPolicyRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :policy, as: 'policy', class: Google::Apis::CloudresourcemanagerV1::OrgPolicy, decorator: Google::Apis::CloudresourcemanagerV1::OrgPolicy::Representation

        end
      end

      class SetIamPolicyRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :update_mask, as: 'updateMask'
          property :policy, as: 'policy', class: Google::Apis::CloudresourcemanagerV1::Policy, decorator: Google::Apis::CloudresourcemanagerV1::Policy::Representation

        end
      end

      class Empty
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
        end
      end

      class Organization
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :creation_time, as: 'creationTime'
          property :owner, as: 'owner', class: Google::Apis::CloudresourcemanagerV1::OrganizationOwner, decorator: Google::Apis::CloudresourcemanagerV1::OrganizationOwner::Representation

          property :lifecycle_state, as: 'lifecycleState'
          property :name, as: 'name'
          property :display_name, as: 'displayName'
        end
      end

      class ListAvailableOrgPolicyConstraintsResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :next_page_token, as: 'nextPageToken'
          collection :constraints, as: 'constraints', class: Google::Apis::CloudresourcemanagerV1::Constraint, decorator: Google::Apis::CloudresourcemanagerV1::Constraint::Representation

        end
      end

      class ListPolicy
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :all_values, as: 'allValues'
          collection :allowed_values, as: 'allowedValues'
          property :suggested_value, as: 'suggestedValue'
          property :inherit_from_parent, as: 'inheritFromParent'
          collection :denied_values, as: 'deniedValues'
        end
      end

      class GetAncestryResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          collection :ancestor, as: 'ancestor', class: Google::Apis::CloudresourcemanagerV1::Ancestor, decorator: Google::Apis::CloudresourcemanagerV1::Ancestor::Representation

        end
      end

      class AuditLogConfig
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          collection :exempted_members, as: 'exemptedMembers'
          property :log_type, as: 'logType'
        end
      end

      class SearchOrganizationsRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :page_token, as: 'pageToken'
          property :page_size, as: 'pageSize'
          property :filter, as: 'filter'
        end
      end

      class GetAncestryRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
        end
      end

      class TestIamPermissionsRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          collection :permissions, as: 'permissions'
        end
      end

      class ListAvailableOrgPolicyConstraintsRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :page_token, as: 'pageToken'
          property :page_size, as: 'pageSize'
        end
      end

      class Policy
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :etag, :base64 => true, as: 'etag'
          property :version, as: 'version'
          collection :audit_configs, as: 'auditConfigs', class: Google::Apis::CloudresourcemanagerV1::AuditConfig, decorator: Google::Apis::CloudresourcemanagerV1::AuditConfig::Representation

          collection :bindings, as: 'bindings', class: Google::Apis::CloudresourcemanagerV1::Binding, decorator: Google::Apis::CloudresourcemanagerV1::Binding::Representation

        end
      end

      class FolderOperation
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :operation_type, as: 'operationType'
          property :display_name, as: 'displayName'
          property :source_parent, as: 'sourceParent'
          property :destination_parent, as: 'destinationParent'
        end
      end

      class ResourceId
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :type, as: 'type'
          property :id, as: 'id'
        end
      end

      class GetEffectiveOrgPolicyRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :constraint, as: 'constraint'
        end
      end

      class ListOrgPoliciesRequest
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :page_token, as: 'pageToken'
          property :page_size, as: 'pageSize'
        end
      end

      class Operation
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          hash :response, as: 'response'
          property :name, as: 'name'
          property :error, as: 'error', class: Google::Apis::CloudresourcemanagerV1::Status, decorator: Google::Apis::CloudresourcemanagerV1::Status::Representation

          hash :metadata, as: 'metadata'
          property :done, as: 'done'
        end
      end

      class AuditConfig
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :service, as: 'service'
          collection :audit_log_configs, as: 'auditLogConfigs', class: Google::Apis::CloudresourcemanagerV1::AuditLogConfig, decorator: Google::Apis::CloudresourcemanagerV1::AuditLogConfig::Representation

        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
@class TCKohonenNetwork;

@protocol TCKohonenNetworkDelegate <NSObject>

@end


text:
/**
 *
Title: IConnectionManager Interface>
 *
Description:	Pluggable IConnectionManager allows developer to select
 * ConnectionManager at run time.It handles all
 * hibernate specific operations like opening and closing of hibernate connection, session etc

 * @author kalpana_thakur
 * @version 1.0
 */
package edu.wustl.dao.connectionmanager;

import java.sql.Connection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import edu.wustl.dao.exception.DAOException;

/**
 * @author kalpana_thakur
 * Manages connection (session) with a specific
 * database.
 */
public interface IConnectionManager
{

	/**
	 * A connection (session) with a specific database
	 * having auto-commit mode as disabled.
	 * mandatory to call commit to update the changes.
	 * @return : the connection.
	 * @throws DAOException :database exception.
	 */
	Connection getConnection() throws DAOException;

	/**
	 * Releases a Connection's database and JDBC resources.
	 * @throws DAOException :database exception.
	 */
	void closeConnection() throws DAOException;
	/**
	 * End the session by releasing the JDBC connection and cleaning up.
	 * @throws DAOException : database exception.
	 */
	void closeSession() throws DAOException;

	/**
	 * Obtains the current session.
	 * connection associated to the session have auto-commit mode as disabled.
	 * mandatory to call commit to update the changes.
	 * @return : the session.
	 * @throws DAOException : database exception.
	 */
	Session getSession() throws DAOException;

	/**
	 * Set the application name.
	 * @param applicationName : Name of the Application
	 */
	void setApplicationName(String applicationName);

	/**
	 * @return This will return the application name.
	 */
	String getApplicationName();

	/**
	 * Set the sessionFactory.
	 * Application obtain Sessions from the factory.
	 * @param sessionFactory :sessionFactory
	 */
	void setSessionFactory(SessionFactory sessionFactory);

	/**
	 * It will returns the sessionFactory.
	 * @return SessionFactory
	 */
	SessionFactory getSessionFactory();

	/**
	 * Set the configuration.
	 * @param cfg : Configuration
	 */
	void setConfiguration(Configuration cfg);

	/**
	 * Get the configuration.
	 * @return Configuration.
	 */
	Configuration getConfiguration();

	/**
	 * This method will be called to get the data source.
	 * @return dataSource
	 */
	 String getDataSource();

	 /**
	 * This method will be called to set the data source.
	 * @param dataSource : JDBC connection name.
	 */
	 void setDataSource(String dataSource);

	 /**
	 * Makes all changes made since the previous
     * commit/rollback.
     * This method should be used only when auto-commit mode has been disabled.
	 * @throws DAOException : It will throw DAOException.
	 */
	 void commit() throws DAOException;

	 /**
	 * Undoes all changes made in the current transaction
	 * This method should be used only when auto-commit mode has been disabled.
	 * @throws DAOException : It will throw DAOException.
	 */
	 void rollback() throws DAOException;

	 /**
	 * This method will be called to begin new transaction.
	 * @throws DAOException : It will throw DAOException.
	 */
	void beginTransaction() throws DAOException;

}


text:
package com.xiaomi.miui.analyticstracker;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

// Referenced classes of package com.xiaomi.miui.analyticstracker:
//            j, a

class i
    implements j
{

    public static final String a = "ANALYTICS.SQLITESTORE";
    private static final String b = "analytics";
    private static final String c = "insert into %s values(null, ?, ?, ?, ?, ?)";
    private static final String d = "select * from analytics ";
    private static final String e = "delete from analytics ";
    private static final int f = 2;
    private SQLiteOpenHelper g;

    i()
    {
    }

    public Cursor a(String s)
    {
        SQLiteOpenHelper sqliteopenhelper = g;
        Cursor cursor = null;
        if (sqliteopenhelper == null)
        {
            break MISSING_BLOCK_LABEL_68;
        }
        String s1 = "select * from analytics ";
        if (s != null)
        {
            s1 = String.format("%s where %s", new Object[] {
                "select * from analytics ", s
            });
        }
        SQLiteDatabase sqlitedatabase;
        Cursor cursor1;
        try
        {
            sqlitedatabase = g.getReadableDatabase();
        }
        catch (SQLiteException sqliteexception)
        {
            Object aobj[] = new Object[1];
            aobj[0] = g.getDatabaseName();
            Log.e("ANALYTICS.SQLITESTORE", String.format("can't read database:%s", aobj));
            return null;
        }
        cursor = null;
        if (sqlitedatabase == null)
        {
            break MISSING_BLOCK_LABEL_68;
        }
        cursor1 = sqlitedatabase.rawQuery(s1, null);
        cursor = cursor1;
        return cursor;
    }

    public void a()
    {
        if (g != null)
        {
            g.close();
        }
    }

    public void a(Context context, String s)
    {
        g = new a(context, s, "analytics", 2);
    }

    public void a(Integer integer, String s, String s1, String s2, String s3)
    {
        if (g == null)
        {
            break MISSING_BLOCK_LABEL_66;
        }
        SQLiteDatabase sqlitedatabase;
        try
        {
            sqlitedatabase = g.getWritableDatabase();
        }
        catch (SQLiteException sqliteexception)
        {
            Object aobj[] = new Object[1];
            aobj[0] = g.getDatabaseName();
            Log.e("ANALYTICS.SQLITESTORE", String.format("database:%s is not writable!", aobj));
            return;
        }
        if (sqlitedatabase == null)
        {
            break MISSING_BLOCK_LABEL_66;
        }
        sqlitedatabase.execSQL(String.format("insert into %s values(null, ?, ?, ?, ?, ?)", new Object[] {
            "analytics"
        }), new Object[] {
            integer, s, s1, s2, s3
        });
    }

    public void b(String s)
    {
        if (g == null)
        {
            break MISSING_BLOCK_LABEL_53;
        }
        String s1 = "delete from analytics ";
        if (s != null)
        {
            s1 = String.format("%s where %s", new Object[] {
                "delete from analytics ", s
            });
        }
        SQLiteDatabase sqlitedatabase;
        try
        {
            sqlitedatabase = g.getWritableDatabase();
        }
        catch (SQLiteException sqliteexception)
        {
            Object aobj[] = new Object[1];
            aobj[0] = g.getDatabaseName();
            Log.e("ANALYTICS.SQLITESTORE", String.format("can't remove data from database:%s", aobj));
            return;
        }
        if (sqlitedatabase == null)
        {
            break MISSING_BLOCK_LABEL_53;
        }
        sqlitedatabase.execSQL(s1);
    }
}


text:
package com.veterinary.billing;

import com.veterinary.Animal;
import com.veterinary.Owner;
import com.veterinary.Patient;
import org.testng.annotations.Test;

import static com.veterinary.service.Procedure.REGULAR_CHECKUP;
import static com.veterinary.service.Procedure.SURGERY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

@Test
public class DistributeEvenlyBillTest {
    private static final Owner BOB = new Owner("BOB");
    private static final Owner JOHN = new Owner("JOHN");

    public void billDistributedEvenly() {
        Patient patient = new Patient(Animal.HORSE, "Blacky");

        patient.perform(REGULAR_CHECKUP);
        patient.perform(SURGERY);

        MultipleOwnerBill decoratedBill = new DistributeEvenlyBill(patient.bill(), BOB, JOHN);

        assertThat(decoratedBill.costOccurredFor(BOB), is(7500));
        assertThat(decoratedBill.costOccurredFor(JOHN), is(7500));
    }
}


text:
import {IUser } from '../../../services/IUser';
export interface IBirthdayState{
Users : IUser[] ;
showBirthdays: boolean;
}


text:
using content::WebContents;

namespace web_modal {

namespace {

const char kPopupManagerUserDataKey[] = "PopupManager";

// This class provides a hook to get a PopupManager from a WebContents.
// The PopupManager is browser-scoped, but will use a FromWebContents API
// to attach to each WebContents in that browser.
class PopupManagerRelay : public content::WebContentsUserData<PopupManager> {
 public:
  explicit PopupManagerRelay(base::WeakPtr<PopupManager> manager)
      : manager_(manager) {}

  ~PopupManagerRelay() override {}

  base::WeakPtr<PopupManager> manager_;
};

}  // namespace

PopupManager::PopupManager(WebContentsModalDialogHost* host)
    : host_(host),
      weak_factory_(this) {}

PopupManager::~PopupManager() {
}

void PopupManager::ShowPopup(scoped_ptr<SinglePopupManager> manager) {
  content::WebContents* web_contents = manager->GetBoundWebContents();
  // TODO(gbillock): get rid of this when we handle bubbles
  DCHECK(web_contents);

  // TODO(gbillock): remove when we port the popup management logic to this
  // class.
  NativeWebContentsModalDialog dialog =
      static_cast<NativeWebContentsModalDialog>(manager->popup());

  WebContentsModalDialogManager* wm_manager =
      WebContentsModalDialogManager::FromWebContents(web_contents);
  DCHECK(wm_manager);
  wm_manager->ShowModalDialog(dialog);
}

void PopupManager::ShowModalDialog(NativePopup popup,
                                   content::WebContents* web_contents) {
  // TODO make a new native popup manager and call ShowPopup.
  // For now just lay off to WCMDM.
  WebContentsModalDialogManager* manager =
      WebContentsModalDialogManager::FromWebContents(web_contents);
  manager->ShowModalDialog(popup);
}

bool PopupManager::IsWebModalDialogActive(
    const content::WebContents* web_contents) const {
  if (web_contents == NULL)
    return false;

  const WebContentsModalDialogManager* manager =
      WebContentsModalDialogManager::FromWebContents(web_contents);
  return manager && manager->IsDialogActive();
}

void PopupManager::WasFocused(const content::WebContents* web_contents) {
  if (!IsWebModalDialogActive(web_contents))
    return;

  const WebContentsModalDialogManager* manager =
      WebContentsModalDialogManager::FromWebContents(web_contents);
  if (manager)
    manager->FocusTopmostDialog();
}

void PopupManager::WillClose(NativePopup popup) {
}

void PopupManager::RegisterWith(content::WebContents* web_contents) {
  web_contents->SetUserData(kPopupManagerUserDataKey,
                            new PopupManagerRelay(weak_factory_.GetWeakPtr()));
  // TODO(gbillock): Need to do something more extreme here to manage changing
  // popup managers with popups in-flight?
}

void PopupManager::UnregisterWith(content::WebContents* web_contents) {
  web_contents->RemoveUserData(kPopupManagerUserDataKey);
  // TODO(gbillock): Need to do something more extreme here to manage changing
  // popup managers with popups in-flight?
}

PopupManager* PopupManager::FromWebContents(
    content::WebContents* web_contents) {
  PopupManagerRelay* relay = static_cast<PopupManagerRelay*>(
      web_contents->GetUserData(kPopupManagerUserDataKey));
  if (!relay)
    return NULL;

  return relay->manager_.get();
}

gfx::NativeView PopupManager::GetHostView() const {
  // TODO(gbillock): replace this with a PopupManagerHost or something.
  DCHECK(host_);
  return host_->GetHostView();
}

void PopupManager::CloseAllDialogsForTesting(
    content::WebContents* web_contents) {
  // TODO: re-implement, probably in terms of something in the host_,
  // or of owned WCMDMs.
  WebContentsModalDialogManager* manager =
      WebContentsModalDialogManager::FromWebContents(web_contents);
  manager->CloseAllDialogs();
}

}  // namespace web_modal


text:
<title>pcrelimits specification</title>

pcrelimits man page

Return to the PCRE index page.

This page is part of the PCRE HTML documentation. It was generated automatically
from the original man page. If there is any nonsense in it, please consult the
man page, in case the conversion went wrong.

SIZE AND OTHER LIMITATIONS

There are some size limitations in PCRE but it is hoped that they will never in
practice be relevant.

The maximum length of a compiled pattern is approximately 64K data units (bytes
for the 8-bit library, 16-bit units for the 16-bit library) if PCRE is compiled
with the default internal linkage size of 2 bytes. If you want to process
regular expressions that are truly enormous, you can compile PCRE with an
internal linkage size of 3 or 4 (when building the 16-bit library, 3 is rounded
up to 4). See the README file in the source distribution and the
pcrebuild
documentation for details. In these cases the limit is substantially larger.
However, the speed of execution is slower.

All values in repeating quantifiers must be less than 65536.

There is no limit to the number of parenthesized subpatterns, but there can be
no more than 65535 capturing subpatterns.

There is a limit to the number of forward references to subsequent subpatterns
of around 200,000. Repeated forward references with fixed upper limits, for
example, (?2){0,100} when subpattern number 2 is to the right, are included in
the count. There is no limit to the number of backward references.

The maximum length of name for a named subpattern is 32 characters, and the
maximum number of named subpatterns is 10000.

The maximum length of a subject string is the largest positive number that an
integer variable can hold. However, when using the traditional matching
function, PCRE uses recursion to handle subpatterns and indefinite repetition.
This means that the available stack space may limit the size of a subject
string that can be processed by certain patterns. For a discussion of stack
issues, see the
pcrestack
documentation.

AUTHOR

Philip Hazel

University Computing Service

Cambridge CB2 3QH, England.

REVISION

Last updated: 08 January 2012

Copyright © 1997-2012 University of Cambridge.

Return to the PCRE index page.


text:
using UnityEngine;
using System.Collections;

namespace HutongGames.PlayMaker.Actions
{
	[ActionCategory("Photon")]
	[Tooltip("Delete the owner custom property of a GameObject.\n A PhotonView component is required on the gameObject")]
	[HelpUrl("https://hutonggames.fogbugz.com/default.asp?W1117")]
	public class PhotonViewDeleteOwnerCustomProperty : FsmStateAction
	{

		[RequiredField]
		[CheckForComponent(typeof(PhotonView))]
		[Tooltip("The Game Object with the PhotonView attached.")]
		public FsmOwnerDefault gameObject;

		[Tooltip("The custom property key to delete")]
		public FsmString customPropertyKey;

		[Tooltip("Send this event if the custom property was deleted")]
		public FsmEvent successEvent;

		[Tooltip("Send this event if the custom property deletion failed")]
		public FsmEvent failureEvent;

		private GameObject go;

		private PhotonView _networkView;

		private void _getNetworkView()
		{
			GameObject go = Fsm.GetOwnerDefaultTarget(gameObject);
			if (go == null)
			{
				return;
			}

			_networkView =  go.GetComponent<PhotonView>();
		}

		public override void Reset()
		{
			customPropertyKey = "My Property";
			successEvent = null;
			failureEvent = null;
		}

		public override void OnEnter()
		{
			_getNetworkView();

			if (DeleteOwnerProperty())
			{
				Fsm.Event(successEvent);
			}else{
				Fsm.Event(failureEvent);
			}

			Finish();
		}

		private bool DeleteOwnerProperty()
		{
			if (_networkView==null)
			{
				return false;
			}

			PhotonPlayer _player = _networkView.owner;
			if (_player==null)
			{
				return false;
			}

			Hashtable _prop = new Hashtable();

			_prop[customPropertyKey.Value] = null;
			_player.SetCustomProperties(_prop);

			return true;
		}

	}
}


text:
package com.github.zabbixjavaclient;

import static org.apache.commons.lang3.StringUtils.endsWith;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import com.github.zabbixjavaclient.ex.ZbxApiException;
import com.github.zabbixjavaclient.proxy.ZabbixApiHandler;
import com.google.common.collect.ImmutableMap;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;

@Slf4j
public class ZabbixApiFactory {

	private static final String API_RESOURCE = "api_jsonrpc.php";
	private JsonRpcHttpClient rpcClient;
	private ZbxRequestListener requestListener;
	private String apiVersion;
	private String authToken;
	private String zbxUrl;
	private String user;
	private String password;

	private ZabbixApiFactory(String zbxUrl, String user, String password) {
		super();
		this.zbxUrl = zbxUrl;
		this.user = user;
		this.password = password;
		requestListener = new ZbxRequestListener();
	}

	public static ZabbixApi getZabbixApi(String zbxUrl, String user, String password) {
		ZabbixApiFactory factory = new ZabbixApiFactory(zbxUrl, user, password);
		factory.initRpcClient();
		factory.login();
		return factory.getApi();

	}

	private void initRpcClient() {
		if (!endsWith(zbxUrl, "/")) {
			zbxUrl = zbxUrl + "/";
		}
		URL serverURL = null;
		try {
			serverURL = new URL(zbxUrl + API_RESOURCE);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
		rpcClient = new JsonRpcHttpClient(serverURL);
		rpcClient.setRequestListener(requestListener);
	}

	public void login() {
		try {
			apiVersion = rpcClient.invoke("apiinfo.version", null, String.class);
			log.info("Zabbix api version : [{}]", apiVersion);
			Map<String, String> params = ImmutableMap.of("user", user, "password", password);
			authToken = rpcClient.invoke("user.login", params, String.class);
			requestListener.setAuthToken(authToken);
			log.debug("Authentication successful for login : [{}]", user);
		} catch (Throwable e) {
			throw new ZbxApiException("Error during authentication step for login :[" + user + "].", e);
		}
	}

	public ZabbixApi getApi() {
		return (ZabbixApi) java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(),
				new Class<?>[] { ZabbixApi.class }, new ZabbixApiHandler(rpcClient));
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Main where
--import              FPGrowth.Parser
import              FPGrowth.Types
import              FPGrowth.Tree
import              FPGrowth.Mine
import              FPGrowth.Transaction
import              FPGrowth.AssociationRule
import              Parser

import              Control.Monad.Trans.Resource
import              Data.Monoid ((<>))
import qualified    Data.ByteString.Lazy as BL
import              Data.ByteString (ByteString)
import              Data.Conduit
import qualified    Data.Conduit.Binary as CB
import qualified    Data.Conduit.List as CL
import              System.Environment
import              System.IO (stdin, stdout)

toByteString :: Conduit Rule (ResourceT IO) ByteString
toByteString = do
    a <- await
    case a of
        Just b -> do
            yield $ BL.toStrict (showRule b) <> "\n"
            toByteString
        Nothing -> return ()

main :: IO ()
main = do

    args <- getArgs

    if length args == 3 then do
        let sup = read $ args !! 0
        let conf = read $ args !! 1
        let k = read $ args !! 2
        go sup conf k
    else do
        putStrLn "\nusage:"
        putStrLn "  ./dist/build/homework2-hs/homework2-hs <support : Double> <confidence : Double> <k : Int>"
        putStrLn "e.g."
        putStrLn "  cat <dataset> | ./dist/build/homework2-hs/homework2-hs 0.01 0.5 10 +RTS -K1000m -H500m -RTS\n"

go :: Support -> Confidence -> Int -> IO ()
go sup conf k = do

    transactions <- runResourceT $ CB.sourceHandle stdin $$ parseTransactionC =$ CL.consume

    let minsup = ceiling (fromIntegral (length transactions) * sup)

    let forest = growForest . permuteTransaction minsup $ transactions

    let freqSet = mine minsup forest

    let rules = take k $ genRule (length transactions) conf freqSet

    runResourceT $ CL.sourceList rules $$ toByteString =$ CB.sinkHandle stdout
    --runResourceT $ CL.sourceList rules $$ toByteString =$ CB.sinkFile "output"


text:
code: true
type: page
title: startQueuing
description: Kuzzle:startQueuing
---

# startQueuing

Starts the requests queuing. Works only in offline mode, and if the [autoQueue](/sdk/android/3/core-classes/kuzzle#properties) option is set to `false`.

---

## Return Value

Returns the `Kuzzle` SDK object to allow chaining.

## Usage

<<< ./snippets/start-queuing-1.java


text:
/**
 * Support and FAQ: visit Atmel Support
 */
#include "event.h"

// Internal counter for the QTouch library
volatile uint32_t event_qtouch_sensors_idle_count = 0u;
// Push button PB0 event
volatile bool event_pbEvent = false;
// Boolean value to detect if the QTouch button is pressed or not
bool event_qTouchButtonPressed = false;

static void wdt_clear(void);

/**
 *  \brief Asynchronous timer (ASF) handler for the QTouch acquisition.
 *  and clear Watchdog counter - generates interrupt every 100ms
 */
static void ast_per_callback(void)
{
	touch_sensors_update_time();
	event_qtouch_sensors_idle_count++;
	ast_clear_interrupt_flag(AST, AST_INTERRUPT_PER);
	wdt_clear();
}

/**
 *  \brief External interrupt handler, used by PB0 push button
 */
static void eic5_callback(void)
{
	sysclk_enable_peripheral_clock(EIC);

	if(eic_line_interrupt_is_pending(EIC,GPIO_PUSH_BUTTON_EIC_LINE))
	{
		eic_line_clear_interrupt(EIC,GPIO_PUSH_BUTTON_EIC_LINE);
		event_pbEvent = true;
	}
	sysclk_disable_peripheral_clock(EIC);
}

/**
 *  \brief Set Control register function for WDT
 */
static void wdt_set_ctrl(uint32_t ctrl)
{
	WDT->WDT_CTRL = ctrl | WDT_CTRL_KEY((uint32_t)0x55);
	WDT->WDT_CTRL = ctrl | WDT_CTRL_KEY((uint32_t)0xAA);
}

/**
 *  \brief Clear WDT
 */
static void wdt_clear(void)
{
	while (!(WDT->WDT_SR & WDT_SR_CLEARED));
	WDT->WDT_CLR = WDT_CLR_WDTCLR | WDT_CLR_KEY((uint32_t)0x55);
	WDT->WDT_CLR = WDT_CLR_WDTCLR | WDT_CLR_KEY((uint32_t)0xAA);
}

/**
 *  \brief Enable WDT
 */
static void enable_wdt(void)
{
	wdt_set_ctrl(WDT_CTRL_EN | WDT_CTRL_CEN | WDT_CTRL_PSEL(17) );
}

/**
 * \brief Event Manager QTouch Init.
 */
void event_qtouch_init(void)
{
	struct ast_config ast_conf;
	// Enable Osc32
	osc_enable(OSC_ID_OSC32);
	while(!osc_is_ready(OSC_ID_OSC32));

	// Initialize AST Controller
	ast_enable(AST);

	ast_conf.mode = AST_COUNTER_MODE;
	ast_conf.osc_type = AST_OSC_32KHZ;
	ast_conf.psel = AST_PSEL_32KHZ_1HZ;
	ast_conf.counter = 0;
	ast_set_config(AST, &ast_conf);

	ast_clear_interrupt_flag(AST, AST_INTERRUPT_PER);
	ast_write_periodic0_value(AST, 9);

	ast_set_callback(AST, AST_INTERRUPT_PER, ast_per_callback,
		AST_PER_IRQn, 0);

	//CATB & Related clocks - for QTouch Sensors
	sysclk_enable_peripheral_clock(CATB);
	sysclk_enable_peripheral_clock(PDCA);

	// Initialize QTouch Library.
	touch_sensors_init();
}
/**
 * \brief Event Button Init.
 */
void event_button_init(void)
{
	// Structure holding the configuration parameters
	// of the EIC module.
	struct eic_line_config eic_line_conf;

	// Initialize EIC Controller
	sysclk_enable_peripheral_clock(EIC);

	// Enable level-triggered interrupt.
	eic_line_conf.eic_mode   = EIC_MODE_EDGE_TRIGGERED;
	// Interrupt will trigger on low-level.
	eic_line_conf.eic_level  = EIC_LEVEL_LOW_LEVEL;
	// Edge on falling edge
	eic_line_conf.eic_edge = EIC_EDGE_FALLING_EDGE;
	// Enable filter.
	eic_line_conf.eic_filter = EIC_FILTER_DISABLED;
	// For Wake Up mode, initialize in asynchronous mode
	eic_line_conf.eic_async  = EIC_ASYNCH_MODE;

	// Enable clock for EIC controller
	eic_enable(EIC);
	// Init the EIC controller with the options
	eic_line_set_config(EIC, GPIO_PUSH_BUTTON_EIC_LINE,
		&eic_line_conf);
	// Init the callback
	eic_line_set_callback(EIC, GPIO_PUSH_BUTTON_EIC_LINE, eic5_callback,
		EIC_5_IRQn, 1);
	// Enable the EIC line
	eic_line_enable(EIC, GPIO_PUSH_BUTTON_EIC_LINE);

	// EIC can wake the device from backup mode
	bpm_enable_wakeup_source(BPM, BPM_BKUP_WAKEUP_SRC_EIC
		| BPM_BKUP_WAKEUP_SRC_AST);
	// EIC can wake the device from backup mode
	bpm_enable_backup_pin(BPM, 1 << GPIO_PUSH_BUTTON_EIC_LINE);
	// Retain I/O lines after wakeup from backup
	bpm_disable_io_retention(BPM);
	bpm_enable_io_retention(BPM);
	bpm_enable_fast_wakeup(BPM);
	sysclk_disable_peripheral_clock(EIC);

	event_pbEvent = false;

	// Initialize WDT Controller
	sysclk_enable_peripheral_clock(WDT);
	enable_wdt();
}
/**
 * \brief Return QTouch Slider State.
 * \param event_qtouch_position returned slider position.
 */
bool event_qtouch_get_slider_state( uint8_t* event_qtouch_position )
{
	bool event_qtouch_slider_state = false;

	// Use Rotor/Slider Position.
	if (GET_QT_SENSOR_STATE(1) || GET_QT_SENSOR_STATE(2)
		|| GET_QT_SENSOR_STATE(3) ) {
		*event_qtouch_position = GET_QT_ROTOR_SLIDER_POSITION(0);
		*event_qtouch_position = 255 - *event_qtouch_position;
		event_qtouch_slider_state = true;
	}
	else {
		event_qtouch_slider_state = false;
	}

	return event_qtouch_slider_state;
}

/**
 * \brief Return QTouch Button State.
 */
bool event_qtouch_get_button_state(void)
{
	bool event_qtouch_button_state = false;

	// Use QTouch button status
	if (GET_QT_SENSOR_STATE(0)&&(event_qTouchButtonPressed==false)) {
		event_qTouchButtonPressed = true;
		event_qtouch_button_state = false;
	}
	else if (!GET_QT_SENSOR_STATE(0)&&(event_qTouchButtonPressed==true)) {
		event_qTouchButtonPressed = false;
		event_qtouch_button_state = true;
	}
	return event_qtouch_button_state;
}

/**
 * \brief Check if push button is pressed or not.
 */
bool event_is_push_button_pressed(void)
{
	bool event_button_state = false;
	event_button_state = event_pbEvent;
	if (event_pbEvent == true) {
		event_pbEvent = false;
	}
	return event_button_state;
}


text:
<?php

namespace Hal\Component\OOP\Extractor;

/**
 * ResultMap
 *
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
 */
class ClassMap {

    /**
     * @var array
     */
    private $classes = array();

    /**
     * Associates result and filename
     *
     * @param $filename
     * @param Result $result
     * @return $this
     */
    public function push($filename, Result $result) {
        $this->classes[$filename] = $result;;
        return $this;
    }

    /**
     * Get for filename
     *
     * @param string $filename
     * @return Result|null
     */
    public function getClassesIn($filename) {
        return isset($this->classes[$filename]) ? $this->classes[$filename] : null;
    }

    /**
     * All classes
     *
     * @return array
     */
    public function all() {
        return $this->classes;
    }
};


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

  // Menu Dropdown
  $('.main-navigation li ul').hide(); //Hide all sub menus
  $('.main-navigation li.active a').parent().find('ul').slideToggle('slow'); // Slide down the current sub menu
  $('.main-navigation li a').click(
    function () {
      $(this).parent().siblings().find('ul').slideUp('normal'); // Slide up all menus except the one clicked
      $(this).parent().find('ul').slideToggle('normal'); // Slide down the clicked sub menu
      return false;
    }
  );
  $('.main-navigation li a.no-submenu, .main-navigation li li a').click(
    function () {
      window.location.href=(this.href); // Open link instead of a sub menu
      return false;
    }
  );

});


text:
d16bunny
========

d16bunny is an assembler for the DCPU-16, written in coffeescript, and
licensed via the apache 2 open-source license (included in the LICENSE file).

it can be built into a node library suitable for command-line tools, or a
single javascript file for inclusion in online web app. my goal is to make a
powerful assembler so all of the web-based assembler/emulators and CLI tools
can share a large feature set and reduce bugs.

the assembler engine is based on deNULL's javascript assembler, with a lot of
refactoring, and some new features. it also comes with a suite of unit tests
and integration tests.

build
-----

- "cake test" to run tests
- "cake build" to build node-style javascript
- "cake web" to build a single web-friendly javascript file
- "cake clean" to clean up

use
---

a sample CLI assembler is included. it can build 128KB DCPU-16 image files,
or "dat" files that consist of only ORG and DAT lines, suitable for pasting
into a less intelligent assembler. it responds to help:

    ./bin/d16basm --help

the library API is optimized for interactive compiling. to use it, create a
new Assembler, pass in a logger function, and call "compile" with an array of
the source lines. the logger will be used to send back warnings and errors.
each warning/error will have the line number and horizontal position (both
counting from 0) attached.

    var logger = function (lineno, pos, message) {
      // append log message to UI element here.
    }
    var asm = new d16bunny.Assembler(logger);
    var output = asm.compile(lines);

the compiled output contains an error count, and a compiled object for each
source line. the compiled object contains the current PC and the compiled
data, so you could line up the compiled output next to the source if you
want. it also has functions for packing the result into a memory image, and
doing line number to memory address lookups, and memory address to line
number lookups. check out the comment block on "compile" for the details.

the assembler will try to continue even if it hits errors, but it will stop
trying after it hits a configured maximum number of errors (usually 10).

syntax
------

the basic notch syntax is supported:

- comments start with ";" and continue to the end of the line.
- labels are always at the beginning of a line and are prefixed by ":".
  labels may contain letters, digits, "_", and ".".
- constant (immediate) values can be decimal integers, hex integers if
  prefixed by "0x", binary integers if prefixed by "0b", or label names.
- operands can be arbitrarily nested expressions using the standard operators
  +, -, *, /, %, <<, >>, &, ^, and |, with their standard C precedence, and ()
  for precedence grouping. operand expressions must evaluate to constants at
  compile-time, but they can use forward references.

supported aliases:

- "JMP expr" for "SET PC, expr"
- "RET" for "SET PC, POP"
- "HLT" for "SUB PC, 1" (which some emulators use as a hint to pause
  execution until the next interrupt)
- "BRA addr" will perform a short (one-word) relative jump using "ADD PC, n"
  or "SUB PC, n". it will log an error if the address is too far away. the
  DCPU can only jump 30 words in either direction in this form.
- the special label "." (or "$") can always be used to refer to the PC of
  the current line being compiled.

directives
==========

assembler directives start with either "#" or ".". the following directives
are supported:

- `.ORG <addr>`
  move to a new target address for compilation (for compatibility, this
  directive may also be used without the "#" or ".").

- `.EQU <name> <expr>` or `.DEFINE <name> <expr>`
  assign a constant that can be used in expressions.

- `.MACRO <name>(<args...>)`
  define a macro which can be expanded by name elsewhere. for example:

      #macro swap(r1, r2) {
        set push, r1
        set r1, r2
        set r2, pop
      }

  which may be expanded later:

      swap(x, y)

data
====

the "DAT" instruction takes a comma-separated list of expressions, evaluates
them into words, and puts them directly into the compiled output. aside from
normal expressions that can be used in any instruction, "DAT" also supports:

- ASCII characters, in single quotes: 'c' (0x0063)
- fat strings (one word per character), in double quotes: "fat" (0x0066,
  0x0061, 0x0074)
- packed strings (one byte per character, big-endian), in double quotes
  prefixed by by "p": p"fat" (0x6661, 0x7400)
- rom strings (one byte per character, big-endian, with the high bit set on
  the last byte), in double quotes prefixed by "r": r"fat" (0x6661, 0xf400)

inside character and string data, the following escapes are supported:

    \n    linefeed (0x000a)
    \r    return (0x000d)
    \t    tab (0x0009)
    \z    null (0x0000)
    \e    escape (0x001b)
    \xNN  any single half-word (0x0000 - 0x00ff)

to-do
-----

- allow "label:"
- "#align"
- "#fill"?
- "#section"

thanks
------

- denis olshin (denull) wrote the original javascript assembler that i ran
  through a blender and then rewrote a few times in an OCD craze -- i
  basically learned javascript by reading his code.
- maximinus-thrax wrote the assembler validity checks that i turned ino
  integration tests because they revealed a lot of bugs.


text:
{% extends "cog/common/layout_left_center_right.html" %}

{% block main %}

    {% load cog_utils %}

	* indicates a required field

	    <form method="post" action="">

	       {% csrf_token %}

                    *Choose Folder

                        {{ form.folder }}{{ form.folder.errors }}
                           -OR-
                         Create New

                    *URL
                    {{ form.url }}{{ form.url.errors }}

                    *Name
                    {{ form.name }}{{ form.name.errors }}

                    Description (optional)
                    {{ form.description }}{{ form.description.errors }}

                    Please note: the characters {{ project|getInvalidCharacters }} are not allowed.

            {{ form.order.as_hidden }}

            		{% if form.instance.id %}

	            			 Edit Notes

            		{% endif %}

            			<input type="button" value="Cancel" onclick="window.location='{% url 'bookmark_list' project.short_name|lower %}'"/>
                		<input type="submit" value="Submit" />

	    </form>

{% endblock %}


text:
package org.osgi.service.zigbee;

import java.io.IOException;

/**
 * The {@link ZigBeeDataOutput} interface is designed for converting Java data
 * types into a series of bytes. The purpose of this interface is the same as
 * the DataOutput interface provided by Java, with the difference that in this
 * interface, the generated bytes ordering is little endian, whereas in the
 * DataOutput is big endian.
 *
 * @author $Id$
 */
public interface ZigBeeDataOutput {

	/**
	 * Appends a byte to the data output.
	 *
	 *

	 * To avoid losing information, the passed value must be in the range [-128,
	 * 127] for signed numbers and [0, 255] for unsigned numbers.
	 *
	 * @param value The value to append.
	 */
	public void writeByte(byte value);

	/**
	 * Appends an int value to the data output.
	 *
	 *

	 * To avoid losing information, according to the {@code size} argument, the
	 * passed {@code long} value if it represents a signed number must fit in
	 * the range [ -2^({@code size} * 8 - 1), -2^({@code size} * 8 - 1) - 1].
	 *
	 *

	 * For unsigned numbers it should fit in the range [ 0, -2^({@code size} *
	 * 8) - 1].
	 *
	 *

	 * For instance if {@code size} is 2 the correct range for signed numbers is
	 * [0xffff8000, 0x7fff] (that is, [-32768, +32767]), whereas for unsigned
	 * numbers is [0L, 0xffff].
	 *
	 *

	 * Although this method allows write even 1 byte of the passed {@code int}
	 * value, it is suggested to use the {@link #writeByte(byte)} because this
	 * latter could be implemented in a more efficient way.
	 *
	 * @param value The integer value to append
	 * @param size The size in bytes that have to be actually appended. The size
	 *        must be in the range [1,4].
	 *
	 * @throws IOException If an I/O error occurs.
	 *
	 * @throws IllegalArgumentException If the passed {@code size} is not within
	 *         the allowed range.
	 */
	public void writeInt(int value, int size) throws IOException;

	/**
	 * Appends a long to the data output.
	 *
	 *

	 * To avoid losing information, according to the {@code size} argument, the
	 * passed {@code long} value if it represents a signed number must fit in
	 * the range [ -2^({@code size} * 8 - 1), -2^({@code size} * 8 - 1) - 1].
	 *
	 *

	 * For unsigned numbers it should fit in the range [ 0, -2^({@code size} *
	 * 8) - 1].
	 *
	 *

	 * For instance if {@code size} is 3 the correct range for signed numbers is
	 * [0xffffffffff800000L, 0x7fffffL] (that is, [-21474836448, +2147483647]),
	 * whereas for unsigned numbers is [0L, 0xffffffL].
	 *
	 *

	 * Although this method allows write even 1 byte of the passed {@code long}
	 * value, it is suggested to use the {@link #writeByte(byte)} because this
	 * latter could be implemented in a more efficient way.
	 *
	 * @param value The {@code long} value to append
	 * @param size The size in bytes that have to be actually appended. The size
	 *        must be in the range [1,8].
	 *
	 * @throws IOException If an I/O error occurs.
	 *
	 * @throws IllegalArgumentException If the passed {@code size} is not within
	 *         the allowed range.
	 */
	public void writeLong(long value, int size) throws IOException;

	/**
	 * Appends on the Data Output Stream a float value.
	 *
	 * @param value The {@code float} value to append.
	 * @param size The size in bytes that have to be actually appended. The size
	 *        must be 2 for semi precision floats or 4 for standard precision
	 *        floats (see the ZigBee Cluster Library specifications).
	 *
	 * @throws IOException If an I/O error occurs.
	 *
	 * @throws IllegalArgumentException If the passed {@code size} is not within
	 *         the allowed range.
	 */
	public void writeFloat(float value, int size) throws IOException;

	/**
	 * Appends on the Data Output Stream a {@code double} value.
	 *
	 * @param value The {@code double} value to append.
	 *
	 * @throws IOException If an I/O error occurs.
	 */
	public void writeDouble(double value) throws IOException;

	/**
	 * Appends on the Data Output Stream a byte array.
	 *
	 * The byte array is written on the data output starting from the byte at
	 * index 0.
	 *
	 * @param bytes A buffer containing the bytes to append to the data output
	 *        stream.
	 * @param length The length in bytes that have to be actually appended.
	 *
	 * @throws IOException If an I/O error occurs.
	 *
	 * @throws IllegalArgumentException If the passed buffer is null or shorter
	 *         than {@code length} bytes.
	 */
	public void writeBytes(byte[] bytes, int length) throws IOException;

}