text:
=head1 LICENSE

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

=cut

package EnsEMBL::Web::Document::Panel;

use strict;

use HTML::Entities qw(encode_entities);

use EnsEMBL::Web::Document::Renderer::String;

use base qw(EnsEMBL::Web::Root);

sub new {
  my $class = shift;

  my $self = {
    _renderer       => undef,
    components      => {},
    component_order => [],
    @_
  };

  bless $self, $class;
  return $self;
}

sub renderer :lvalue  { $_[0]->{'_renderer'}; }
sub hub               { return $_[0]->{'hub'}; }
sub clear_components  { $_[0]{'components'} = {}; $_[0]->{'component_order'} = []; }
sub components        { return @{$_[0]{'component_order'}}; }
sub component         { return $_[0]->{'components'}->{$_[1]}; } # Given a component code, returns the component itself
sub params            { return $_[0]->{'params'}; }
sub status            { return $_[0]->{'status'}; }
sub code              { return $_[0]->{'code'};   }
sub print             { shift->renderer->print(@_);  }
sub printf            { shift->renderer->printf(@_); }
sub _is_ajax_request  { return $_[0]->renderer->can('r') && $_[0]->renderer->r->headers_in->{'X-Requested-With'} eq 'XMLHttpRequest'; }
sub ajax_is_available { return 1; }

sub caption {
  my $self = shift;
  $self->{'caption'} = shift if (@_);
  return $self->{'caption'};
}

sub _error {
  my ($self, $caption, $message) = @_;
  return "
$caption
$message";
}

sub parse {
  my $self   = shift;
  my $string = shift;
  $string =~ s/\[\[object->(\w+)\]\]/$self->{'object'}->$1/eg;
  return $string;
}

=head2 Panel options.

There are five functions which set, clear and read the options for the panel

=over 4

=item C<$panel-E<gt>clear_option( $key )>

resets the option C<$key>

=item C<$panel-E<gt>add_option( $key, $val )>

sets the value of option C<$key> to C<$val>

=item C<$panel-E<gt>option( $key )>

returns the value of option C<$key>

=item C<$panel-E<gt>clear_options>

resest the options list

=item C<$panel-E<gt>options>

returns an array of option keys.

=back

=cut

sub clear_options { $_[0]{'_options'} = {};            }
sub clear_option  { delete $_[0]->{'_options'}{$_[1]}; }
sub add_option    { $_[0]{'_options'}{$_[1]} = $_[2];  }
sub option        { return $_[0]{'_options'}{$_[1]};   }
sub options       { return keys %{$_[0]{'_options'}};  }

=head2 Panel components.

There are a number of functions which set, clear, modify the list of
components which make up the panel.

=over 4

=item C<$panel-E<gt>add_components(       $new_key, $function_name, [...] )>

Adds one or more components to the end of the component list

=item C<$panel-E<gt>remove_component(    $key )>

Removes the function called by the component named C<$key>

=item C<$panel-E<gt>replace_component(    $key,     $function_name )>

Replaces the function called by the component named C<$key> with a new function
named C<$function_name>

=item C<$panel-E<gt>prepend_to_component( $key,     $function_name )>

Extends a component, by adding another function call to the start of the list
keyed by name C<$key>. When the page is rendered each function for the component
will be called in turn (until one returns 0)

=item C<$panel-E<gt>add_to_component(     $key,     $function_name )>

Extends a component, by adding another function call to the end of the list
keyed by name C<$key>. When the page is rendered each function for the component
will be called in turn (until one returns 0)

=item C<$panel-E<gt>add_component_before( $key,     $new_key, $function_name )>

Adds a new component to the component list before the one
named C<$key>, and gives it the name C<$new_key>

=item C<$panel-E<gt>add_component_after(  $key,     $new_key, $function_name )>

Adds a new component to the component list after the one
named C<$key>, and gives it the name C<$new_key>

=item C<$panel-E<gt>add_component_first(  $new_key, $function_name )>

Adds a new component to the start of the component list and gives it the name C<$new_key>

=item C<$panel-E<gt>add_component_last(   $new_key, $function_name )>

Adds a new component to the end of the component list and gives it the name C<$new_key>

=item C<$panel-E<gt>add_component(        $new_key, $function_name )>

Adds a new component to the end of the component list and gives it the name C<$new_key>

=back

=cut

sub add_components {
  my $self = shift;

  while (my ($code, $function) = splice(@_, 0, 2)) {
    if (exists $self->{'components'}{$code}) {
      push @{$self->{'components'}{$code}}, $function;
    } else {
      push @{$self->{'component_order'}}, $code;
      $self->{'components'}{$code} = [ $function ];
    }
  }
}

sub replace_component {
  my ($self, $code, $function, $flag) = @_;

  if ($self->{'components'}{$code}) {
    $self->{'components'}{$code} = [ $function ];
  } elsif ($flag ne 'no') {
    $self->add_component_last($code, $function);
  }
}

sub prepend_to_component {
  my ($self, $code, $function) = @_;
  return $self->add_component_first($code, $function) unless exists $self->{'components'}{$code};
  unshift @{$self->{'components'}{$code}}, $function;
}

sub add_to_component {
  my ($self, $code, $function) = @_;
  return $self->add_component_last($code, $function) unless exists $self->{'components'}{$code};
  push @{$self->{'components'}{$code}}, $function;
}

sub add_component_before {
  my ($self, $oldcode, $code, $function) = @_;

  return $self->prepend_to_component($code, $function) if exists $self->{'components'}{$code};
  return $self->add_component_first($code, $function) unless exists $self->{'components'}{$oldcode};

  my $i = 0;

  foreach (@{$self->{'component_order'}}) {
    if ($_ eq $oldcode) {
      splice @{$self->{'component_order'}}, $i, 0, $code;
      $self->{'components'}{$code} = [ $function ];
      return;
    }

    $i++;
  }
}

sub add_component_first {
  my ($self, $code, $function) = @_;
  return $self->prepend_to_component($code, $function) if exists $self->{'components'}{$code};
  unshift @{$self->{'component_order'}}, $code;
  $self->{'components'}{$code} = [ $function ];
}

sub add_component { my $self = shift; $self->add_component_last( @_ ); }

sub add_component_last {
  my ($self, $code, $function) = @_;
  return $self->add_to_component($code, $function) if exists $self->{'components'}{$code};
  push @{$self->{'component_order'}}, $code;
  $self->{'components'}{$code} = [ $function ];
}

sub add_component_after {
  my ($self, $oldcode, $code, $function) = @_;

  return $self->add_to_component($code, $function) if exists $self->{'components'}{$code};
  return $self->add_component_first($code, $function) unless exists $self->{'components'}{$oldcode};

  my $i = 0;

  foreach (@{$self->{'component_order'}}) {
    if ($_ eq $oldcode) {
      splice @{$self->{'component_order'}}, $i+1, 0, $code;
      $self->{'components'}{$code} = [ $function ];
      return;
    }

    $i++;
  }

  $self->{'components'}{$code} = [ $function ];
}

sub remove_component {
  my ($self, $code) = @_;

  my $i = 0;

  foreach (@{$self->{'component_order'}}) {
    if ($_ eq $code) {
      splice @{$self->{'component_order'}}, $i, 1;
      delete $self->{'components'}{$code};
      return;
    }

    $i++;
  }
}

sub content_Text {
  my $self = shift;

  my $temp_renderer = $self->renderer;

  $self->renderer = EnsEMBL::Web::Document::Renderer::String->new;
  $self->content;

  my $value = $self->renderer->content;

  $self->renderer = $temp_renderer;
  $self->renderer->print($value)
}

sub _caption_h1 {
  my $self    = shift;
  my ($head, $subhead);
  my $html = '
';

  if (ref($self->{'caption'}) eq 'ARRAY') {
    my ($head, $subhead) = @{$self->{'caption'} || []};
    $html .= $head;
    if ($subhead) {
      $html .= ' '.$subhead.'';
    }
  }
  else {
    $html .= $self->{'caption'};
  }

  $html .= '
';
  return $html;
}

sub _caption_h2_with_helplink {
  my $self  = shift;
  my $id    = $self->{'help'};
  my $html  = '
';
     $html .= sprintf ' ', encode_entities($id) if $id;
     $html .= $self->{'caption'};
     $html .= '' if $id;
     $html .= '
';

  return $html;
}

sub content {
  my $self = shift;

  return $self->{'raw'} if exists $self->{'raw'};

  my $hub        = $self->hub;
  my $status     = $hub && $self->{'status'} ? $hub->param($self->{'status'}) : undef;
  my $content    = sprintf '%s
.
', $status ne 'off' ? sprintf('
%s
', $self->component_content) : '';
  my $panel_type = $self->renderer->{'_modal_dialog_'} ? 'ModalContent' : 'Content';

  if (!$self->{'omit_header'}) {

    my $caption = '';
    if ($self->{'caption'}) {
      my $summary = $self->{'code'} eq 'summary_panel' ? 1 : 0;
      if ($summary) {
        $caption = $self->_caption_h1;
      }
      else {
        $caption = $self->_caption_h2_with_helplink;
      }

      $content = qq{

          $caption

.

        $content
      };
    }
  }

  return qq{

      <input type="hidden" class="panel_type" value="$panel_type" />
      $content

  };
}

sub component_content {
  my $self    = shift;
  my $html    = $self->{'content'};
  my $builder = $self->{'builder'};
  my $hub     = $self->hub;

  return $html unless $builder;
  return $html unless scalar keys %{$self->{'components'}};

  my $modal        = $self->renderer->{'_modal_dialog_'};
  my $ajax_request = $self->_is_ajax_request;
  my $base_url     = $hub->species_defs->ENSEMBL_BASE_URL;
  my $function     = $hub->function;
  my $is_html      = ($hub->param('_format') || 'HTML') eq 'HTML';

  for (map [$_, $self->{'components'}{$_} || []], $self->components) {
    my ($code, $entry) = @$_;
    next unless @$entry;
    my ($module_name, $content_function) = split /\//, $entry->[0];
    next unless $module_name;
    my $component;

    ### Attempt to require the Component module
    if ($self->dynamic_use($module_name)) {
      eval {
        $component = $module_name->new($hub, $builder, $self->renderer, $code);
      };

      if ($@) {
        $html .= $self->component_failure($@, $entry->[0], $module_name);
        next;
      }
    } else {
      $html .= $self->component_failure($self->dynamic_use_failure($module_name), $entry->[0], $module_name);
      next;
    }

    ### If this component is configured to be loaded by an AJAX request, print just the div which the content will be loaded into
    my $ajaxable = $component->ajaxable;
    if ($ajaxable && !$ajax_request && $is_html) {

      my $url   = encode_entities($component->ajax_url($content_function)),
      my $class = 'initial_panel' . ($component->has_image == 1 ? ' image_panel' : ''); # classes required by the javascript

      # Safari requires a unique name on inputs when using browser-cached content (eq when the user presses the back button)
      # $panel_name is the memory location of the current object, so unique for each panel.
      # Without this, ajax panels don't load, or load the wrong content.
      my ($panel_name) = $self =~ /\((.+)\)$/;

      # If this is going to be a POST request, move all POST and GET params to hidden inputs (this is done because GET params are not read in a post request by hub->param)
      my $ajax_post = '';
      if ($ajaxable eq 'post') {
        my $input = $hub->input;
        my %inps  = map { $_ => $hub->param($_) } $hub->param; # all params
        exists $inps{$_} or $inps{$_} = $input->url_param($_) for $input->url_param; # any remaining GET params
        foreach my $param_name (keys %inps) {
          $inps{$param_name} = [ $inps{$param_name} ] unless ref $inps{$param_name};
          for (@{$inps{$param_name}}) {
            $ajax_post .= qq(<input class="ajax_post" type="hidden" name="$param_name" value="$_" />);
          }
        }
      }

      $html .= qq(
<input type="hidden" class="ajax_load" name="$panel_name" value="$url">$ajax_post
);

    } else {
      my $content;

      ### Try to call the required content function on the Component module
      eval {
        my $func = $ajax_request ? lc $function : $content_function;
        $func    = "content_$func" if $func;
        $content = $component->get_content($func);
      };

      if ($@) {
        $html .= $self->component_failure($@, $entry->[0], $module_name);
      } elsif ($content) {
        if ($ajax_request) {
          my $id         = $component->id;
          my $panel_type = $modal || $content =~ /panel_type/ ? '' : '<input type="hidden" class="panel_type" value="Content" />';

          # Only add the wrapper if $content is html, and the update_panel parameter isn't present
          $content = qq{
$panel_type$content
} if !$hub->param('update_panel') && $content =~ /^\s*<.+>\s*$/s;
        } else {
          my $caption = $component->caption;
          $html .= sprintf '
%s
', encode_entities($caption) if $caption;
        }

        $html .= $content;
      }
    }

  }

  $html .= sprintf '
more about %s ...
', $self->{'link'}, encode_entities($self->parse($self->{'caption'})) if $self->{'link'};

  return $html;
}

sub component_failure {
  my ($self, $error, $component, $module_name) = @_;

  warn $error;

  return $self->_error(
    qq{Runtime Error in component "$component [content]"},
    qq{
Function $module_name fails to execute due to the following error:
} . $self->_format_error($error)
  );
}

1;


text:
package org.apache.geronimo.mail;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;

/**
 * A GBean that provides for the configuration of a JavaMail POP3 message store
 * protocol.
 *

 * POP3 store properties that are common to all POP3 stores are
 * provided via member variables of this class.  Values that are set in the
 * individual member variables will override any of the corresponding values
 * that have been set in the properties set.
 *
 * @version $Rev$ $Date$
 * @see MailGBean
 */
public class POP3StoreGBean extends ProtocolGBean {

    private final Log log = LogFactory.getLog(POP3StoreGBean.class);

    private Integer port;
    private Integer connectionTimeout;
    private Integer timeout;
    private Boolean rsetBeforeQuit;
    private String messageClass;
    private String localaddress;
    private Integer localport;
    private Boolean apopEnable;
    private String socketFactoryClass;
    private Boolean socketFactoryFallback;
    private Integer socketFactoryPort;

    /**
     * Construct an instance of POP3StoreGBean
     *

     * Values that are set in the individual member variables will override any of
     * the corresponding values that have been set in the properties set.
     *
     * @param objectName            the object name of the protocol
     * @param properties            the set of default properties for the protocol
     * @param host                  the host the protocol connects to
     * @param user                  the default name for the protocol
     * @param port                  the POP3 server port
     * @param connectionTimeout     the socket connection timeout value in milliseconds
     * @param timeout               the socket I/O timeout value in milliseconds
     * @param rsetBeforeQuit        whether an attempt will be made send a POP3 RSET command when closing
     *                              the folder, before sending the QUIT command
     * @param messageClass          the class name of a subclass of com.sun.mail.pop3.POP3Message
     * @param localaddress          the local address (host name) to bind to when creating the POP3 socket
     * @param localport             the local port number to bind to when creating the POP3 socket
     * @param apopEnable            whether to use APOP instead of USER/PASS to login to the POP3 server,
     *                              if the POP3 server supports APOP
     * @param socketFactoryClass    the class that will be used to create POP3 sockets
     * @param socketFactoryFallback whether java.net.Socket class will be created if the specified
     *                              socket factory class cannot be created
     * @param socketFactoryPort     whether java.net.Socket class will be created if the specified
     *                              socket factory class cannot be created
     */
    public POP3StoreGBean(String objectName, Properties properties, String host, String user,
                          Integer port,
                          Integer connectionTimeout,
                          Integer timeout,
                          Boolean rsetBeforeQuit,
                          String messageClass,
                          String localaddress,
                          Integer localport,
                          Boolean apopEnable,
                          String socketFactoryClass,
                          Boolean socketFactoryFallback,
                          Integer socketFactoryPort) {
        super(objectName, "pop3", properties, host, user);

        setPort(port);
        setConnectionTimeout(connectionTimeout);
        setTimeout(timeout);
        setRsetBeforeQuit(rsetBeforeQuit);
        setMessageClass(messageClass);
        setLocaladdress(localaddress);
        setLocalport(localport);
        setApopEnable(apopEnable);
        setSocketFactoryClass(socketFactoryClass);
        setSocketFactoryFallback(socketFactoryFallback);
        setSocketFactoryPort(socketFactoryPort);
    }

    /**
     * Returns the POP3 server port to connect to, if the connect() method
     * doesn't explicitly specify one.
     *

     * Defaults to 110.
     */
    public Integer getPort() {
        return port;
    }

    /**
     * Sets the POP3 server port to connect to, if the connect() method
     * doesn't explicitly specify one.
     *

     * Defaults to 110.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param port the POP3 server port to connect to, if the connect() method
     *             doesn't explicitly specify one
     */
    public void setPort(Integer port) {
        this.port = port;
    }

    /**
     * Returns the socket connection timeout value in milliseconds.
     */
    public Integer getConnectionTimeout() {
        return connectionTimeout;
    }

    /**
     * Sets the socket connection timeout value in milliseconds.
     *

     * Default is infinite timeout.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param connectionTimeout the socket connection timeout value in milliseconds.
     */
    public void setConnectionTimeout(Integer connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    /**
     * Returns the socket I/O timeout value in milliseconds.
     */
    public Integer getTimeout() {
        return timeout;
    }

    /**
     * Sets the socket I/O timeout value in milliseconds.
     *

     * Default is infinite timeout.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param timeout the socket I/O timeout value in milliseconds
     */
    public void setTimeout(Integer timeout) {
        this.timeout = timeout;
    }

    /**
     * Returns whether an attempt will be made send a POP3 RSET command when
     * closing the folder, before sending the QUIT command.
     *

     * Send a POP3 RSET command when closing the folder, before sending the
     * QUIT command. Useful with POP3 servers that implicitly mark all
     * messages that are read as "deleted"; this will prevent such messages
     * from being deleted and expunged unless the client requests so. Default
     * is false.
     */
    public Boolean getRsetBeforeQuit() {
        return rsetBeforeQuit;
    }

    /**
     * Sets whether an attempt will be made send a POP3 RSET command when
     * closing the folder, before sending the QUIT command.
     *

     * Send a POP3 RSET command when closing the folder, before sending the
     * QUIT command. Useful with POP3 servers that implicitly mark all messages
     * that are read as "deleted"; this will prevent such messages from being
     * deleted and expunged unless the client requests so. Default is false.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param rsetBeforeQuit whether an attempt will be made send a POP3 RSET command when
     *                       closing the folder, before sending the QUIT command
     */
    public void setRsetBeforeQuit(Boolean rsetBeforeQuit) {
        this.rsetBeforeQuit = rsetBeforeQuit;
    }

    /**
     * Returns the class name of a subclass of com.sun.mail.pop3.POP3Message.
     *

     * Class name of a subclass of com.sun.mail.pop3.POP3Message. The subclass
     * can be used to handle (for example) non-standard Content-Type headers.
     * The subclass must have a public constructor of the form
     * MyPOP3Message(Folder f, int msgno) throws MessagingException.
     */
    public String getMessageClass() {
        return messageClass;
    }

    /**
     * Sets the class name of a subclass of com.sun.mail.pop3.POP3Message.
     *

     * Class name of a subclass of com.sun.mail.pop3.POP3Message. The subclass
     * can be used to handle (for example) non-standard Content-Type headers.
     * The subclass must have a public constructor of the form
     * MyPOP3Message(Folder f, int msgno) throws MessagingException.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param messageClass the class name of a subclass of com.sun.mail.pop3.POP3Message.
     */
    public void setMessageClass(String messageClass) {
        this.messageClass = messageClass;
    }

    /**
     * Returns the local address (host name) to bind to when creating the POP3 socket.
     */
    public String getLocaladdress() {
        return localaddress;
    }

    /**
     * Sets the local address (host name) to bind to when creating the POP3 socket.
     *

     * Local address (host name) to bind to when creating the POP3 socket.
     * Defaults to the address picked by the Socket class. Should not normally
     * need to be set, but useful with multi-homed hosts where it's important
     * to pick a particular local address to bind to.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param localaddress the local address (host name) to bind to when creating the POP3 socket
     */
    public void setLocaladdress(String localaddress) {
        this.localaddress = localaddress;
    }

    /**
     * Returns the local port number to bind to when creating the POP3 socket.
     */
    public Integer getLocalport() {
        return localport;
    }

    /**
     * Sets the local port number to bind to when creating the POP3 socket.
     *

     * Local port number to bind to when creating the POP3 socket. Defaults to
     * the port number picked by the Socket class.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param localport the local port number to bind to when creating the POP3 socket
     */
    public void setLocalport(Integer localport) {
        this.localport = localport;
    }

    /**
     * Returns whether to use APOP instead of USER/PASS to login to the POP3
     * server, if the POP3 server supports APOP.
     *

     * If set to true, use APOP instead of USER/PASS to login to the POP3
     * server, if the POP3 server supports APOP. APOP sends a digest of the
     * password rather than the clear text password. Defaults to false.
     */
    public Boolean isApopEnable() {
        return apopEnable;
    }

    /**
     * Sets whether to use APOP instead of USER/PASS to login to the POP3
     * server, if the POP3 server supports APOP.
     *

     * If set to true, use APOP instead of USER/PASS to login to the POP3
     * server, if the POP3 server supports APOP. APOP sends a digest of the
     * password rather than the clear text password. Defaults to false.
     *
     * @param apopEnable whether to use APOP instead of USER/PASS to login to the POP3
     *                   server, if the POP3 server supports APOP
     */
    public void setApopEnable(Boolean apopEnable) {
        this.apopEnable = apopEnable;
    }

    /**
     * Returns the class that will be used to create POP3 sockets.
     *

     * If set, specifies the name of a class that implements the
     * javax.net.SocketFactory interface. This class will be used to create POP3
     * sockets.
     */
    public String getSocketFactoryClass() {
        return socketFactoryClass;
    }

    /**
     * Sets the class that will be used to create POP3 sockets.
     *

     * If set, specifies the name of a class that implements the
     * javax.net.SocketFactory interface. This class will be used to create POP3
     * sockets.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param socketFactoryClass the class that will be used to create POP3 sockets
     */
    public void setSocketFactoryClass(String socketFactoryClass) {
        this.socketFactoryClass = socketFactoryClass;
    }

    /**
     * Returns whether java.net.Socket class will be created if the specified
     * socket factory class cannot be created.
     *

     * If set to true, failure to create a socket using the specified socket
     * factory class will cause the socket to be created using the
     * java.net.Socket class. Defaults to true.
     */
    public Boolean isSocketFactoryFallback() {
        return socketFactoryFallback;
    }

    /**
     * Sets whether java.net.Socket class will be created if the specified
     * socket factory class cannot be created.
     *

     * If set to true, failure to create a socket using the specified socket
     * factory class will cause the socket to be created using the
     * java.net.Socket class. Defaults to true.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param socketFactoryFallback whether java.net.Socket class will be created if the specified
     *                              socket factory class cannot be created
     */
    public void setSocketFactoryFallback(Boolean socketFactoryFallback) {
        this.socketFactoryFallback = socketFactoryFallback;
    }

    /**
     * Returns the port to connect to when using the specified socket factory.
     *

     * Specifies the port to connect to when using the specified socket
     * factory. If not set, the default port will be used.
     */
    public Integer getSocketFactoryPort() {
        return socketFactoryPort;
    }

    /**
     * Sets the port to connect to when using the specified socket factory.
     *

     * Specifies the port to connect to when using the specified socket
     * factory. If not set, the default port will be used.
     *

     * Values that are set here will override any of the corresponding value
     * that has been set in the properties.
     *
     * @param socketFactoryPort the port to connect to when using the specified socket factory
     */
    public void setSocketFactoryPort(Integer socketFactoryPort) {
        this.socketFactoryPort = socketFactoryPort;
    }

    /**
     * Add the overrides from the member variables to the properties file.
     */
    public void addOverrides(Properties props) {
        super.addOverrides(props);

        if (port != null) props.put("mail.pop3.port", port);
        if (connectionTimeout != null) props.put("mail.pop3.connectiontimeout", connectionTimeout);
        if (timeout != null) props.put("mail.pop3.timeout", timeout);
        if (rsetBeforeQuit != null) props.put("mail.pop3.rsetbeforequit", rsetBeforeQuit);
        if (messageClass != null) props.put("mail.pop3.message.class", messageClass);
        if (localaddress != null) props.put("mail.pop3.localaddress", localaddress);
        if (localport != null) props.put("mail.pop3.localport", localport);
        if (apopEnable != null) props.put("mail.pop3.apop.enable", apopEnable);
        if (socketFactoryClass != null) props.put("mail.pop3.socketFactory.class", socketFactoryClass);
        if (socketFactoryFallback != null) props.put("mail.pop3.socketFactory.fallback", socketFactoryFallback);
        if (socketFactoryPort != null) props.put("mail.pop3.socketFactory.port", socketFactoryPort);
    }

    public void doStart() throws Exception {
        log.debug("Started " + getObjectName());
    }

    public void doStop() throws Exception {
        log.debug("Stopped " + getObjectName());
    }

    public void doFail() {
        log.warn("Failed " + getObjectName());
    }

    public static final GBeanInfo GBEAN_INFO;

    static {
        GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(POP3StoreGBean.class, ProtocolGBean.GBEAN_INFO);

        infoFactory.addAttribute("port", Integer.class, true);
        infoFactory.addAttribute("connectionTimeout", Integer.class, true);
        infoFactory.addAttribute("timeout", Integer.class, true);
        infoFactory.addAttribute("rsetBeforeQuit", Boolean.class, true);
        infoFactory.addAttribute("messageClass", String.class, true);
        infoFactory.addAttribute("localaddress", String.class, true);
        infoFactory.addAttribute("localport", Integer.class, true);
        infoFactory.addAttribute("apopEnable", Boolean.class, true);
        infoFactory.addAttribute("socketFactoryClass", String.class, true);
        infoFactory.addAttribute("socketFactoryFallback", Boolean.class, true);
        infoFactory.addAttribute("socketFactoryPort", Integer.class, true);

        infoFactory.setConstructor(new String[]{"objectName", "properties", "host", "user",
                                                "port",
                                                "connectionTimeout",
                                                "timeout",
                                                "rsetBeforeQuit",
                                                "messageClass",
                                                "localaddress",
                                                "localport",
                                                "apopEnable",
                                                "socketFactoryClass",
                                                "socketFactoryFallback",
                                                "socketFactoryPort"});

        GBEAN_INFO = infoFactory.getBeanInfo();
    }

    public static GBeanInfo getGBeanInfo() {
        return GBEAN_INFO;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from . import exceptions, http, application
from .shield import ShieldHandler

def endpoint(url=None, authentication=None):
    def decorator(clazz):
        fixed_url = url.replace('/', '')
        clazz._endpoint_url = fixed_url
        application.add_endpoint(fixed_url, clazz, authentication)

        return clazz
    return decorator

class EndpointHandler(object):

    def __init__(self, request, fullpath):
        self.__request = request
        self.__url = fullpath
        self.__endpoint_data = self.get_endpoint_data()

    def process(self):
        logged_user = None

        if self.is_protected():
            logged_user = application.get_authentication().get_logged_user()
            if not logged_user:
                raise exceptions.NotAuthorized()

            self.__request.logged_user = logged_user

        return EndpointProcessor(self.__request, self.__endpoint_data['model'], logged_user).process()

    def get_endpoint_data(self):
        try:
            full_path = self.__url.split('/')
            model_url = full_path[-1] if len(full_path) == 3 else full_path[-2]
            return application.get_endpoint(model_url)
        except:
            raise exceptions.EndpointNotFound()

    def is_protected(self):
        return self.get_endpoint_data()['authentication'] is not None

    def endpoint_authentication(self):
        return self.get_endpoint_data()['authentication']

class EndpointProcessor(object):

    def __init__(self, request, model, user_data):
        self.__request = request
        self.__model = model
        self.__shield_class = ShieldHandler(user_data).get_shield(model)

    def process(self):
        methods = {'post': self.__process_post, 'get': self.__process_get,
                   'put': self.__process_put, 'delete': self.__process_delete}

        http_verb = self.__request.method.lower()
        return methods[http_verb]()

    def __process_put(self):
        self.__validate_shield('put')

        id_param = http.get_id(self.__request.path)
        entity_json = self.__request.json
        if not id_param:
            exceptions.PutRequiresIdOnJson()

        entity_json['id'] = id_param
        entity = self.__model.to_instance(entity_json)
        entity.update(entity_json).to_json()

    def __process_post(self):
        self.__validate_shield('post')

        entity = self.__model.to_instance(self.__request.json)
        return entity.put().to_json(), 201

    def __process_get(self):
        self.__validate_shield('get')

        id_param = http.get_id(self.__request.path)
        params = http.query_params_to_dict(self.__request)

        if not id_param:
            return [model.to_json() for model in self.__model.find(**params)]

        return self.__find_database(id_param).to_json()

    def __process_delete(self):
        self.__validate_shield('delete')

        id_param = http.get_id(self.__request.path)
        try:
            return self.__find_database(id_param).delete(id=id_param).to_json()
        except exceptions.HookException:
            raise exceptions.HookException()

    def __find_database(self, id_param):
        model = self.__model.get(id=id_param)
        if not model:
            raise exceptions.ModelNotFound()

        return model

    def __validate_shield(self, shield_method_name):
        shield_method = getattr(self.__shield_class, shield_method_name)

        model_id = http.get_id(self.__request.path)
        parameters = http.get_parameters(self.__request)
        logged_user = self.__request.logged_user if hasattr(self.__request, 'logged_user') else None

        if logged_user and not shield_method(self.__request.logged_user, model_id, parameters):
            raise exceptions.MethodUnderShieldProtection()

        return True


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _barPositioning = require("./barPositioning");

Object.keys(_barPositioning).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _barPositioning[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _barPositioning[key];
    }
  });
});

var _chartConfigByType = require("./chartConfigByType");

Object.keys(_chartConfigByType).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _chartConfigByType[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _chartConfigByType[key];
    }
  });
});

var _dimensionSeriesColors = require("./dimensionSeriesColors");

Object.keys(_dimensionSeriesColors).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _dimensionSeriesColors[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _dimensionSeriesColors[key];
    }
  });
});

var _legendPosition = require("./legendPosition");

Object.keys(_legendPosition).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _legendPosition[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _legendPosition[key];
    }
  });
});

var _legendType = require("./legendType");

Object.keys(_legendType).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _legendType[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _legendType[key];
    }
  });
});

var _legendValue = require("./legendValue");

Object.keys(_legendValue).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _legendValue[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _legendValue[key];
    }
  });
});

var _linePositioning = require("./linePositioning");

Object.keys(_linePositioning).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _linePositioning[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _linePositioning[key];
    }
  });
});

var _normalizeChartTypes = require("./normalizeChartTypes");

Object.keys(_normalizeChartTypes).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _normalizeChartTypes[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _normalizeChartTypes[key];
    }
  });
});

var _renderNullValues = require("./renderNullValues");

Object.keys(_renderNullValues).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _renderNullValues[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _renderNullValues[key];
    }
  });
});

var _sanitizeSDKResponse = require("./sanitizeSDKResponse");

Object.keys(_sanitizeSDKResponse).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _sanitizeSDKResponse[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _sanitizeSDKResponse[key];
    }
  });
});

var _seriesCellVis = require("./seriesCellVis");

Object.keys(_seriesCellVis).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesCellVis[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesCellVis[key];
    }
  });
});

var _seriesColors = require("./seriesColors");

Object.keys(_seriesColors).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesColors[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesColors[key];
    }
  });
});

var _seriesLabels = require("./seriesLabels");

Object.keys(_seriesLabels).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesLabels[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesLabels[key];
    }
  });
});

var _seriesLineWidth = require("./seriesLineWidth");

Object.keys(_seriesLineWidth).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesLineWidth[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesLineWidth[key];
    }
  });
});

var _seriesPointShape = require("./seriesPointShape");

Object.keys(_seriesPointShape).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesPointShape[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesPointShape[key];
    }
  });
});

var _seriesPointStyle = require("./seriesPointStyle");

Object.keys(_seriesPointStyle).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesPointStyle[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesPointStyle[key];
    }
  });
});

var _seriesSize = require("./seriesSize");

Object.keys(_seriesSize).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesSize[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesSize[key];
    }
  });
});

var _seriesValueFormat = require("./seriesValueFormat");

Object.keys(_seriesValueFormat).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesValueFormat[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesValueFormat[key];
    }
  });
});

var _seriesVisible = require("./seriesVisible");

Object.keys(_seriesVisible).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _seriesVisible[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _seriesVisible[key];
    }
  });
});

var _showRowTotals = require("./showRowTotals");

Object.keys(_showRowTotals).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _showRowTotals[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _showRowTotals[key];
    }
  });
});

var _showTotals = require("./showTotals");

Object.keys(_showTotals).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _showTotals[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _showTotals[key];
    }
  });
});

var _tooltips = require("./tooltips");

Object.keys(_tooltips).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _tooltips[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _tooltips[key];
    }
  });
});

var _truncateHeader = require("./truncateHeader");

Object.keys(_truncateHeader).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _truncateHeader[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _truncateHeader[key];
    }
  });
});

var _truncateText = require("./truncateText");

Object.keys(_truncateText).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _truncateText[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _truncateText[key];
    }
  });
});

var _xAxis = require("./xAxis");

Object.keys(_xAxis).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _xAxis[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _xAxis[key];
    }
  });
});

var _yAxis = require("./yAxis");

Object.keys(_yAxis).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _yAxis[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _yAxis[key];
    }
  });
});

var _yAxisRange = require("./yAxisRange");

Object.keys(_yAxisRange).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _yAxisRange[key]) return;
  Object.defineProperty(exports, key, {
    enumerable: true,
    get: function get() {
      return _yAxisRange[key];
    }
  });
});
//# sourceMappingURL=index.js.map


text:
/*
 * A tabbed application, consisting of multiple stacks of windows associated with tabs in a tab group.
 * A starting point for tab-based application with multiple top-level windows.
 *
 * In app.js, we generally take care of a few things:
 * - Bootstrap the application with any data we need
 * - Check for dependencies like device type, platform version or network connection
 * - Require and open our top-level UI component
 *
 */
var _ = require('/lib/underscore')._;
var log = require('/lib/log');
var app = require('/context');
var Network = require('/services/Network');
var AppTabGroup = require('ui/AppTabGroup');

log.info('---------------------'+app.appName+'---------------------');
log.mem();

var verifyInternet = function() {
	if(!Ti.Network.online) {
		var msg = Ti.UI.createAlertDialog({
			title: app.appName,
			message: 'Please connect to the Internet to use '+app.appName
		});
		msg.show();
	}
}
var reloadTabs = function(user){
    log.info('app.js -> [app:user:login] | loading tabs');

    appTabs.close();
	appTabs = new AppTabGroup();

	log.info('we made the new tabgroup: '+appTabs);
	appTabs.open();
	log.info('we opened the tabgroup')
}

app.settings.set('network.host', 'http://www.gobusybee.com'); // this can only be used in the simulator
Network.setBaseUrl(app.settings.get('network.host'));

var appTabs = new AppTabGroup();
appTabs.open();

verifyInternet();

Ti.App.addEventListener('app:user.login',  reloadTabs);
Ti.App.addEventListener('app:user.logout', reloadTabs);

Ti.App.addEventListener('resumed', function(){
	verifyInternet();
});


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="RhPuestoPerfil" table="rh_puesto_perfil">
    <indexes>
      <index name="fk_perfil_puesto_departamento_empresa1_idx" columns="ctl_departamento_empresa_id"/>
    </indexes>
    <id name="id" type="integer" column="id"/>
    <id name="ctlDepartamentoEmpresa" association-key="true"/>
    <field name="profesion" type="string" column="profesion" length="45" nullable="false"/>
    <field name="experiencia" type="integer" column="experiencia" nullable="false"/>
    <field name="conocimientos" type="string" column="conocimientos" length="45" nullable="false"/>
    <field name="habilidades" type="string" column="habilidades" length="45" nullable="false"/>
    <field name="nombrePuesto" type="string" column="nombre_puesto" length="45" nullable="false"/>
    <one-to-one field="ctlDepartamentoEmpresa" target-entity="CtlDepartamentoEmpresa">
      <join-columns>
        <join-column name="ctl_departamento_empresa_id" referenced-column-name="id"/>
      </join-columns>
    </one-to-one>
  </entity>
</doctrine-mapping>


text:
    <?php echo t("Vanilla Statistics are currently disabled"); ?>
    <?php
    if (!c('Garden.Analytics.Enabled', true)) {
        echo $this->Form->Hidden('Allow', array('value' => 1));
        echo "
".t("Garden.StatisticsDisabled", "You have specifically disabled Vanilla Statistics in your configuration file.")."
";
        echo $this->Form->button("Enable", array('class' => 'Button SliceSubmit'));
    } else if (Gdn_Statistics::CheckIsLocalhost() && !c('Garden.Analytics.AllowLocal', false)) {
        echo $this->Form->Hidden('AllowLocal', array('value' => 1));
        echo "
".t("Garden.StatisticsLocal.Explain", "This forum appears to be running in a test environment, or is otherwise reporting a private IP. By default, forums running on private IPs are not tracked.")."
";
        echo "
".t("Garden.StatisticsLocal.Resolve", "If you're sure your forum is accessible from the internet you can force it to report statistics here:")."
";
        echo $this->Form->button("Enable", array('class' => 'Button SliceSubmit'));
    } else if (!$this->data('ConfWritable')) {
        echo "
".t("Garden.StatisticsReadonly.Explain", "Your config.php file appears to be read-only. This means that Vanilla will be unable to automatically register your forum's InstallationID and InstallationSecret.")."
";
        echo "
".t("Garden.StatisticsReadonly.Resolve", "To solve this problem, assign file mode 777 to your conf/config.php file.")."
";
    }
    ?>


text:
package org.assertj.core.api.optionaldouble;

import static java.lang.Math.abs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import static org.assertj.core.error.OptionalDoubleShouldHaveValueCloseTo.shouldHaveValueCloseTo;
import static org.assertj.core.util.FailureMessages.actualIsNull;

import java.util.OptionalDouble;

import org.assertj.core.api.BaseTest;
import org.assertj.core.data.Offset;
import org.junit.Test;

public class OptionalDoubleAssert_hasValueCloseTo_Test extends BaseTest {

  @Test
  public void should_fail_when_optionaldouble_is_null() {
    thrown.expectAssertionError(actualIsNull());

    assertThat((OptionalDouble) null).hasValueCloseTo(10.0, within(2.0));
  }

  @Test
  public void should_fail_if_optionaldouble_is_empty() {
    double expectedValue = 10.0;

    thrown.expectAssertionError(shouldHaveValueCloseTo(expectedValue).create());

    assertThat(OptionalDouble.empty()).hasValueCloseTo(expectedValue, within(2.0));
  }

  @Test
  public void should_fail_if_actual_is_not_close_enough_to_expected_value() {
    double expectedValue = 10.0;
    Offset<Double> offset = within(1.0);
    OptionalDouble actual = OptionalDouble.of(1.0);

    thrown.expectAssertionError(
          shouldHaveValueCloseTo(actual, expectedValue, offset, abs(expectedValue - actual.getAsDouble()
                                 )).create());

    assertThat(actual).hasValueCloseTo(expectedValue, offset);
  }

  @Test(expected = NullPointerException.class)
  public void should_fail_if_offset_is_null() {
    double expectedValue = 10.0;
    assertThat(OptionalDouble.of(10.0)).hasValueCloseTo(expectedValue, null);
  }

  @Test
  public void should_pass_if_optionaldouble_has_expected_value_close_to() {
    assertThat(OptionalDouble.of(10.0)).hasValueCloseTo(10.0, within(2.0));
  }

  @Test
  public void should_pass_if_optionaldouble_has_expected_value_with_less_than_given_offset() {
    assertThat(OptionalDouble.of(1.0)).hasValueCloseTo(1.0, within(1.0));
    assertThat(OptionalDouble.of(1.0)).hasValueCloseTo(2.0, within(10.0));
  }

  @Test
  public void should_pass_if_optionaldouble_has_expected_value_equal_given_offset() {
    assertThat(OptionalDouble.of(1.0)).hasValueCloseTo(1.0, within(0.0));
    assertThat(OptionalDouble.of(1.0)).hasValueCloseTo(0.0, within(1.0));
    assertThat(OptionalDouble.of(1.0)).hasValueCloseTo(2.0, within(1.0));
  }
}


text:
<?php

namespace yii\test;

use Yii;
use yii\base\BaseObject;
use yii\db\Connection;
use yii\di\Instance;

/**
 * DbFixture is the base class for DB-related fixtures.
 *
 * DbFixture provides the [[db]] connection to be used by DB fixtures.
 *
 * For more details and usage information on DbFixture, see the [guide article on fixtures](guide:test-fixtures).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
abstract class DbFixture extends Fixture
{
    /**
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
     * After the DbFixture object is created, if you want to change this property, you should only assign it
     * with a DB connection object.
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
     */
    public $db = 'db';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->db = Instance::ensure($this->db, BaseObject::className());
    }
}


text:
package av.is.leveledstorage.storages.bukkit.meta;

import org.bukkit.Color;
import org.bukkit.inventory.meta.LeatherArmorMeta;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * Created by Avis Network on 2017-11-05.
 */
public class LeatherArmorMetaStorage extends ItemMetaStorage<LeatherArmorMeta> {

    public LeatherArmorMetaStorage(LeatherArmorMeta meta) {
        super(meta);
    }

    @Override
    public void read(DataInputStream input) throws IOException {
        super.read(input);

        getValue().setColor(Color.fromRGB(input.readInt(), input.readInt(), input.readInt()));
    }

    @Override
    public void write(DataOutputStream output) throws IOException {
        super.write(output);

        output.writeInt(getValue().getColor().getRed());
        output.writeInt(getValue().getColor().getGreen());
        output.writeInt(getValue().getColor().getBlue());
    }
}


text:
<?php

class Rsc_Form_Rule_Required implements Rsc_Form_Rule_Interface
{

    /**
     * @var string
     */
    public $label;

    /**
     * @var null
     */
    public $parameters;

    /**
     * @var string
     */
    public $message;

    /**
     * Constructor
     * @param string $label Field label
     * @param null $parameters An array of parameters
     */
    public function __construct($label, $parameters = null)
    {
        $this->label = $label;
        $this->parameters = $parameters;
    }

    /**
     * Validate field data
     * @param mixed $field Field data
     * @return bool TRUE if field is valid, FALSE otherwise
     */
    public function validate($field)
    {
        if (is_array($field)) {
            return (count($field) >= 1);
        }

        if (extension_loaded('mbstring')) {
            return (mb_strlen(trim($field), strtoupper(get_bloginfo('charset'))) >= 1);
        }

        return (strlen(trim($field)) >= 1);
    }

    /**
     * Returns error message
     * @return string
     */
    public function getMessage()
    {
        if ($this->message !== null) {
            return sprintf($this->message, $this->label);
        }

        return sprintf(__('The %s field cannot be empty', 'rsc-framework'), $this->label);
    }

    /**
     * Set error message
     * @param string $message Error message
     */
    public function setMessage($message)
    {
        $this->message = (string)$message;
    }

    /**
     * Creates the new instance of the rule for chaining
     * <code>
     *      Rsc_Form_Rule_Required::create('Control label', $params)->setMessage('The field %s is required');
     * </code>
     * @param string $label Field label
     * @param null $parameters An array of parameters
     * @return Rsc_Form_Rule_Required
     */
    public static function create($label, $parameters = null)
    {
        return new self($label, $parameters);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.payler.paylergateapi.MainActivity"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:layout_gravity="center_horizontal"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:text="@string/onestep_payment"
            android:id="@+id/send" />

        <Button
            android:layout_gravity="center_horizontal"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:text="@string/recurrent_payment"
            android:id="@+id/recurrent" />

    </LinearLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/status_text"
                android:visibility="visible"
                android:text="@string/prompt_pay"
                android:layout_gravity="center"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <ProgressBar
                style="?android:attr/progressBarStyleLarge"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/progressBar"
                android:visibility="invisible"
                android:indeterminate="true" />

        </LinearLayout>

        <WebView
            android:visibility="invisible"
            tools:visibility="visible"
            android:id="@+id/web_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </FrameLayout>

</LinearLayout>


text:
$script:DSCModuleName      = 'LanguageDsc'
$script:DSCResourceName    = 'MSFT_LanguagePack'

#region HEADER
# Integration Test Template Version: 1.1.1
[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
     (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
    & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))
}

Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'DSCResource.Tests' -ChildPath 'TestHelper.psm1')) -Force
$TestEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $script:DSCModuleName `
    -DSCResourceName $script:DSCResourceName `
    -TestType Integration

#endregion

# TODO: Other Init Code Goes Here...

# Using try/finally to always cleanup.
try
{
    #region Integration Tests
    $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1"
    . $configFile

    Describe "$($script:DSCResourceName)_Integration" -Tag "Integration" {
        #region DEFAULT TESTS
        It 'Should compile and apply the MOF without throwing' {
            {
                & "$($script:DSCResourceName)_Config" -OutputPath $TestDrive
                Start-DscConfiguration -Path $TestDrive `
                    -ComputerName localhost -Wait -Verbose -Force
            } | Should not throw
        }

        It 'Should be able to call Get-DscConfiguration without throwing' {
            { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
        }
        #endregion
        InModuleScope 'MSFT_Language' {
            It 'Should have set the resource and all the parameters should match' {
                $currentConfig = Get-TargetResource -LanguagePackName "en-GB" -Verbose
                $currentConfig.Ensure | Should Be $true
            }
        }
    }
    #endregion

}
finally
{
    #region FOOTER

    Restore-TestEnvironment -TestEnvironment $TestEnvironment

    #endregion

    # TODO: Other Optional Cleanup Code Goes Here...
}


text:
//================================================================
/**
 * @packageDocumentation
 * @module std.internal
 */
//================================================================
export interface IFront<T> {
    /**
     * Get the first element.
     *
     * @return The first element.
     */
    front(): T;

    /**
     * Change the first element.
     *
     * @param val The value to change.
     */
    front(val: T): void;
}


text:
import {PieceTranslationTable} from "../shared/PieceTranslationTable"

export class PieceImageTranslationTable implements PieceTranslationTable {
	readonly WHITE_PAWN = "wp.png";
	readonly WHITE_ROOK = "wr.png";
	readonly WHITE_KNIGHT = "wn.png";
	readonly WHITE_BISHOP = "wb.png";
	readonly WHITE_QUEEN = "wq.png";
	readonly WHITE_KING = "wk.png";

	readonly BLACK_PAWN = "bp.png";
	readonly BLACK_ROOK = "br.png";
	readonly BLACK_KNIGHT = "bn.png";
	readonly BLACK_BISHOP = "bb.png";
	readonly BLACK_QUEEN = "bq.png";
	readonly BLACK_KING = "bk.png";
}


text:
package com.thin.downloadmanager;

public interface DownloadManager {

	/**
	 * Status when the download is currently pending.
	 */
	int STATUS_PENDING = 1 << 0;

	/**
	 * Status when the download is currently pending.
	 */
	int STATUS_STARTED = 1 << 1;

	/**
	 * Status when the download network call is connecting to destination.
	 */
	int STATUS_CONNECTING = 1 << 2;

	/**
	 * Status when the download is currently running.
	 */
	int STATUS_RUNNING = 1 << 3;

	/**
	 * Status when the download has successfully completed.
	 */
	int STATUS_SUCCESSFUL = 1 << 4;

	/**
	 * Status when the download has failed.
	 */
	int STATUS_FAILED = 1 << 5;

	/**
	 * Status when the download has failed due to broken url or invalid download url
	 */
	int STATUS_NOT_FOUND = 1 << 6;

    /**
     * Status when the download is attempted for retry due to connection timeouts.
     */
	int STATUS_RETRYING = 1 << 7;

    /**
	 * Error code when writing download content to the destination file.
	 */
	int ERROR_FILE_ERROR = 1001;

	/**
	 * Error code when an HTTP code was received that download manager can't
	 * handle.
	 */
	int ERROR_UNHANDLED_HTTP_CODE = 1002;

	/**
	 * Error code when an error receiving or processing data occurred at the
	 * HTTP level.
	 */
	int ERROR_HTTP_DATA_ERROR = 1004;

	/**
	 * Error code when there were too many redirects.
	 */
	int ERROR_TOO_MANY_REDIRECTS = 1005;

	/**
	 * Error code when size of the file is unknown.
	 */
	int ERROR_DOWNLOAD_SIZE_UNKNOWN = 1006;

	/**
	 * Error code when passed URI is malformed.
	 */
	int ERROR_MALFORMED_URI = 1007;

	/**
	 * Error code when download is cancelled.
	 */
	int ERROR_DOWNLOAD_CANCELLED = 1008;

	/**
	 * Error code when there is connection timeout after maximum retries
	 */
	int ERROR_CONNECTION_TIMEOUT_AFTER_RETRIES = 1009;

	int add(DownloadRequest request);

	int cancel(int downloadId);

	void cancelAll();

	int query(int downloadId);

	void release();
}


text:
from django import forms

class ExampleForm(forms.Form):
    non_blank_field = forms.CharField(max_length=100,
        widget=forms.TextInput(attrs={
            'placeholder': "Must not be blank!",
        }),
    )


text:
package onion.compiler.tools

import onion.tools.Shell
import org.scalatest._

class HelloWorldSpec extends AbstractShellSpec {
  describe("HelloWorld class") {
    it("shows 'Hello, World'") {
      val resultHelloWorld = shell.run(
        """
          |class HelloWorld {
          |public:
          |  static def main(args: String[]): String {
          |    return "Hello, World";
          |  }
          |}
          |""".stripMargin,
        "None",
        Array()
      )
      assert(Shell.Success("Hello, World") == resultHelloWorld)
    }
  }
}


text:
package org.apache.nifi.distributed.cache.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

/**
 * Utility class to abstract serialization logic from network byte stream operations.
 */
public class CacheClientSerde {

    /**
     * Serialize a value of the given type.
     *
     * @param value      the value to be serialized
     * @param serializer the serializer for the input value
     * @param <T>        the value type
     * @return the byte stream representation of the input value
     * @throws IOException on serialization failure
     */
    public static <T> byte[] serialize(final T value, final Serializer<T> serializer) throws IOException {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        serializer.serialize(value, os);
        return os.toByteArray();
    }

    /**
     * Serialize a collection of values of the given type.
     *
     * @param values     the values to be serialized
     * @param serializer the serializer for the input values
     * @param <T>        the value type
     * @return a collection of the byte stream representations of the input values
     * @throws IOException on serialization failure
     */
    public static <T> Collection<byte[]> serialize(final Set<T> values, final Serializer<T> serializer) throws IOException {
        final Collection<byte[]> bytesValues = new ArrayList<>();
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        for (T value : values) {
            serializer.serialize(value, os);
            bytesValues.add(os.toByteArray());
            os.reset();
        }
        return bytesValues;
    }
}


text:
""" Bertology: this script shows how you can explore the internals of the models in the library to:
    - compute the entropy of the head attentions
    - compute the importance of each head
    - prune (remove) the low importance head.
    Some parts of this script are adapted from the code of Michel et al. (http://arxiv.org/abs/1905.10650)
    which is available at https://github.com/pmichel31415/are-16-heads-really-better-than-1
"""
import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process

logger = logging.getLogger(__name__)

def entropy(p):
    """Compute the entropy of a probability distribution"""
    plogp = p * torch.log(p)
    plogp[p == 0] = 0
    return -plogp.sum(dim=-1)

def print_2d_tensor(tensor):
    """Print a 2D tensor"""
    logger.info("lv, h >\t" + "\t".join(f"{x + 1}" for x in range(len(tensor))))
    for row in range(len(tensor)):
        if tensor.dtype != torch.long:
            logger.info(f"layer {row + 1}:\t" + "\t".join(f"{x:.5f}" for x in tensor[row].cpu().data))
        else:
            logger.info(f"layer {row + 1}:\t" + "\t".join(f"{x:d}" for x in tensor[row].cpu().data))

def compute_heads_importance(
    args, model, eval_dataloader, compute_entropy=True, compute_importance=True, head_mask=None, actually_pruned=False
):
    """This method shows how to compute:
    - head attention entropy
    - head importance scores according to http://arxiv.org/abs/1905.10650
    """
    # Prepare our tensors
    n_layers, n_heads = model.config.num_hidden_layers, model.config.num_attention_heads
    head_importance = torch.zeros(n_layers, n_heads).to(args.device)
    attn_entropy = torch.zeros(n_layers, n_heads).to(args.device)

    if head_mask is None:
        head_mask = torch.ones(n_layers, n_heads).to(args.device)

    head_mask.requires_grad_(requires_grad=True)
    # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
    if actually_pruned:
        head_mask = None

    preds = None
    labels = None
    tot_tokens = 0.0

    for step, inputs in enumerate(tqdm(eval_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])):
        for k, v in inputs.items():
            inputs[k] = v.to(args.device)

        # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
        outputs = model(**inputs, head_mask=head_mask)
        loss, logits, all_attentions = (
            outputs[0],
            outputs[1],
            outputs[-1],
        )  # Loss and logits are the first, attention the last
        loss.backward()  # Backpropagate to populate the gradients in the head mask

        if compute_entropy:
            for layer, attn in enumerate(all_attentions):
                masked_entropy = entropy(attn.detach()) * inputs["attention_mask"].float().unsqueeze(1)
                attn_entropy[layer] += masked_entropy.sum(-1).sum(0).detach()

        if compute_importance:
            head_importance += head_mask.grad.abs().detach()

        # Also store our logits/labels if we want to compute metrics afterwards
        if preds is None:
            preds = logits.detach().cpu().numpy()
            labels = inputs["labels"].detach().cpu().numpy()
        else:
            preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)
            labels = np.append(labels, inputs["labels"].detach().cpu().numpy(), axis=0)

        tot_tokens += inputs["attention_mask"].float().detach().sum().data

    # Normalize
    attn_entropy /= tot_tokens
    head_importance /= tot_tokens
    # Layerwise importance normalization
    if not args.dont_normalize_importance_by_layer:
        exponent = 2
        norm_by_layer = torch.pow(torch.pow(head_importance, exponent).sum(-1), 1 / exponent)
        head_importance /= norm_by_layer.unsqueeze(-1) + 1e-20

    if not args.dont_normalize_global_importance:
        head_importance = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

    # Print/save matrices
    np.save(os.path.join(args.output_dir, "attn_entropy.npy"), attn_entropy.detach().cpu().numpy())
    np.save(os.path.join(args.output_dir, "head_importance.npy"), head_importance.detach().cpu().numpy())

    logger.info("Attention entropies")
    print_2d_tensor(attn_entropy)
    logger.info("Head importance scores")
    print_2d_tensor(head_importance)
    logger.info("Head ranked by importance scores")
    head_ranks = torch.zeros(head_importance.numel(), dtype=torch.long, device=args.device)
    head_ranks[head_importance.view(-1).sort(descending=True)[1]] = torch.arange(
        head_importance.numel(), device=args.device
    )
    head_ranks = head_ranks.view_as(head_importance)
    print_2d_tensor(head_ranks)

    return attn_entropy, head_importance, preds, labels

def mask_heads(args, model, eval_dataloader):
    """This method shows how to mask head (set some heads to zero), to test the effect on the network,
    based on the head importance scores, as described in Michel et al. (http://arxiv.org/abs/1905.10650)
    """
    _, head_importance, preds, labels = compute_heads_importance(args, model, eval_dataloader, compute_entropy=False)
    preds = np.argmax(preds, axis=1) if args.output_mode == "classification" else np.squeeze(preds)
    original_score = glue_compute_metrics(args.task_name, preds, labels)[args.metric_name]
    logger.info("Pruning: original score: %f, threshold: %f", original_score, original_score * args.masking_threshold)

    new_head_mask = torch.ones_like(head_importance)
    num_to_mask = max(1, int(new_head_mask.numel() * args.masking_amount))

    current_score = original_score
    while current_score >= original_score * args.masking_threshold:
        head_mask = new_head_mask.clone()  # save current head mask
        # heads from least important to most - keep only not-masked heads
        head_importance[head_mask == 0.0] = float("Inf")
        current_heads_to_mask = head_importance.view(-1).sort()[1]

        if len(current_heads_to_mask) <= num_to_mask:
            break

        # mask heads
        current_heads_to_mask = current_heads_to_mask[:num_to_mask]
        logger.info("Heads to mask: %s", str(current_heads_to_mask.tolist()))
        new_head_mask = new_head_mask.view(-1)
        new_head_mask[current_heads_to_mask] = 0.0
        new_head_mask = new_head_mask.view_as(head_mask)
        new_head_mask = new_head_mask.clone().detach()
        print_2d_tensor(new_head_mask)

        # Compute metric and head importance again
        _, head_importance, preds, labels = compute_heads_importance(
            args, model, eval_dataloader, compute_entropy=False, head_mask=new_head_mask
        )
        preds = np.argmax(preds, axis=1) if args.output_mode == "classification" else np.squeeze(preds)
        current_score = glue_compute_metrics(args.task_name, preds, labels)[args.metric_name]
        logger.info(
            "Masking: current score: %f, remaining heads %d (%.1f percents)",
            current_score,
            new_head_mask.sum(),
            new_head_mask.sum() / new_head_mask.numel() * 100,
        )

    logger.info("Final head mask")
    print_2d_tensor(head_mask)
    np.save(os.path.join(args.output_dir, "head_mask.npy"), head_mask.detach().cpu().numpy())

    return head_mask

def prune_heads(args, model, eval_dataloader, head_mask):
    """This method shows how to prune head (remove heads weights) based on
    the head importance scores as described in Michel et al. (http://arxiv.org/abs/1905.10650)
    """
    # Try pruning and test time speedup
    # Pruning is like masking but we actually remove the masked weights
    before_time = datetime.now()
    _, _, preds, labels = compute_heads_importance(
        args, model, eval_dataloader, compute_entropy=False, compute_importance=False, head_mask=head_mask
    )
    preds = np.argmax(preds, axis=1) if args.output_mode == "classification" else np.squeeze(preds)
    score_masking = glue_compute_metrics(args.task_name, preds, labels)[args.metric_name]
    original_time = datetime.now() - before_time

    original_num_params = sum(p.numel() for p in model.parameters())
    heads_to_prune = dict(
        (layer, (1 - head_mask[layer].long()).nonzero().squeeze().tolist()) for layer in range(len(head_mask))
    )

    assert sum(len(h) for h in heads_to_prune.values()) == (1 - head_mask.long()).sum().item()
    model.prune_heads(heads_to_prune)
    pruned_num_params = sum(p.numel() for p in model.parameters())

    before_time = datetime.now()
    _, _, preds, labels = compute_heads_importance(
        args,
        model,
        eval_dataloader,
        compute_entropy=False,
        compute_importance=False,
        head_mask=None,
        actually_pruned=True,
    )
    preds = np.argmax(preds, axis=1) if args.output_mode == "classification" else np.squeeze(preds)
    score_pruning = glue_compute_metrics(args.task_name, preds, labels)[args.metric_name]
    new_time = datetime.now() - before_time

    logger.info(
        "Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)",
        original_num_params,
        pruned_num_params,
        pruned_num_params / original_num_params * 100,
    )
    logger.info("Pruning: score with masking: %f score with pruning: %f", score_masking, score_pruning)
    logger.info("Pruning: speed ratio (new timing / original timing): %f percents", original_time / new_time * 100)

def main():
    parser = argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        "--data_dir",
        default=None,
        type=str,
        required=True,
        help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
    )
    parser.add_argument(
        "--model_name_or_path",
        default=None,
        type=str,
        required=True,
        help="Path to pretrained model or model identifier from huggingface.co/models",
    )
    parser.add_argument(
        "--task_name",
        default=None,
        type=str,
        required=True,
        help="The name of the task to train selected in the list: " + ", ".join(glue_processors.keys()),
    )
    parser.add_argument(
        "--output_dir",
        default=None,
        type=str,
        required=True,
        help="The output directory where the model predictions and checkpoints will be written.",
    )

    # Other parameters
    parser.add_argument(
        "--config_name",
        default="",
        type=str,
        help="Pretrained config name or path if not the same as model_name_or_path",
    )
    parser.add_argument(
        "--tokenizer_name",
        default="",
        type=str,
        help="Pretrained tokenizer name or path if not the same as model_name_or_path",
    )
    parser.add_argument(
        "--cache_dir",
        default=None,
        type=str,
        help="Where do you want to store the pre-trained models downloaded from huggingface.co",
    )
    parser.add_argument(
        "--data_subset", type=int, default=-1, help="If > 0: limit the data to a subset of data_subset instances."
    )
    parser.add_argument(
        "--overwrite_output_dir", action="store_true", help="Whether to overwrite data in output directory"
    )
    parser.add_argument(
        "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
    )

    parser.add_argument(
        "--dont_normalize_importance_by_layer", action="store_true", help="Don't normalize importance score by layers"
    )
    parser.add_argument(
        "--dont_normalize_global_importance",
        action="store_true",
        help="Don't normalize all importance scores between 0 and 1",
    )

    parser.add_argument(
        "--try_masking", action="store_true", help="Whether to try to mask head until a threshold of accuracy."
    )
    parser.add_argument(
        "--masking_threshold",
        default=0.9,
        type=float,
        help="masking threshold in term of metrics (stop masking when metric < threshold * original metric value).",
    )
    parser.add_argument(
        "--masking_amount", default=0.1, type=float, help="Amount to heads to masking at each masking step."
    )
    parser.add_argument("--metric_name", default="acc", type=str, help="Metric to use for head masking.")

    parser.add_argument(
        "--max_seq_length",
        default=128,
        type=int,
        help=(
            "The maximum total input sequence length after WordPiece tokenization. \n"
            "Sequences longer than this will be truncated, sequences shorter padded."
        ),
    )
    parser.add_argument("--batch_size", default=1, type=int, help="Batch size.")

    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--local_rank", type=int, default=-1, help="local_rank for distributed training on gpus")
    parser.add_argument("--no_cuda", action="store_true", help="Whether not to use CUDA when available")
    parser.add_argument("--server_ip", type=str, default="", help="Can be used for distant debugging.")
    parser.add_argument("--server_port", type=str, default="", help="Can be used for distant debugging.")
    args = parser.parse_args()

    if args.server_ip and args.server_port:
        # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
        import ptvsd

        print("Waiting for debugger attach")
        ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
        ptvsd.wait_for_attach()

    # Setup devices and distributed training
    if args.local_rank == -1 or args.no_cuda:
        args.device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
        args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
    else:
        torch.cuda.set_device(args.local_rank)
        args.device = torch.device("cuda", args.local_rank)
        args.n_gpu = 1
        torch.distributed.init_process_group(backend="nccl")  # Initializes the distributed backend

    # Setup logging
    logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
    logger.info("device: {} n_gpu: {}, distributed: {}".format(args.device, args.n_gpu, bool(args.local_rank != -1)))
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(args.local_rank):
        transformers.utils.logging.set_verbosity_info()
        transformers.utils.logging.enable_default_handler()
        transformers.utils.logging.enable_explicit_format()

    # Set seeds
    set_seed(args.seed)

    # Prepare GLUE task
    args.task_name = args.task_name.lower()
    if args.task_name not in glue_processors:
        raise ValueError("Task not found: %s" % (args.task_name))
    processor = glue_processors[args.task_name]()
    args.output_mode = glue_output_modes[args.task_name]
    label_list = processor.get_labels()
    num_labels = len(label_list)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    config = AutoConfig.from_pretrained(
        args.config_name if args.config_name else args.model_name_or_path,
        num_labels=num_labels,
        finetuning_task=args.task_name,
        output_attentions=True,
        cache_dir=args.cache_dir,
    )
    tokenizer = AutoTokenizer.from_pretrained(
        args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
        cache_dir=args.cache_dir,
    )
    model = AutoModelForSequenceClassification.from_pretrained(
        args.model_name_or_path,
        from_tf=bool(".ckpt" in args.model_name_or_path),
        config=config,
        cache_dir=args.cache_dir,
    )

    # Distributed and parallel training
    model.to(args.device)
    if args.local_rank != -1:
        model = nn.parallel.DistributedDataParallel(
            model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
        )
    elif args.n_gpu > 1:
        model = nn.DataParallel(model)

    # Print/save training arguments
    os.makedirs(args.output_dir, exist_ok=True)
    torch.save(args, os.path.join(args.output_dir, "run_args.bin"))
    logger.info("Training/evaluation parameters %s", args)

    # Prepare dataset for the GLUE task
    eval_dataset = GlueDataset(args, tokenizer=tokenizer, mode="dev")
    if args.data_subset > 0:
        eval_dataset = Subset(eval_dataset, list(range(min(args.data_subset, len(eval_dataset)))))
    eval_sampler = SequentialSampler(eval_dataset) if args.local_rank == -1 else DistributedSampler(eval_dataset)
    eval_dataloader = DataLoader(
        eval_dataset, sampler=eval_sampler, batch_size=args.batch_size, collate_fn=default_data_collator
    )

    # Compute head entropy and importance score
    compute_heads_importance(args, model, eval_dataloader)

    # Try head masking (set heads to zero until the score goes under a threshole)
    # and head pruning (remove masked heads and see the effect on the network)
    if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
        head_mask = mask_heads(args, model, eval_dataloader)
        prune_heads(args, model, eval_dataloader, head_mask)

if __name__ == "__main__":
    main()


text:
export const createLogsMatcher = output => {
  return {
    // Useful for debugging
    logOutput() {
      console.log(output)
    },

    should: {
      contain: match => {
        // ink will auto wrap things, so we need to get rid of any whitespace specific checks
        // and let it just make sure there is whitespace

        expect(output).toMatch(
          new RegExp(
            match
              .replace(/\s+/g, `\\s+`)
              .replace(/\(/g, `\\(`)
              .replace(/\)/g, `\\)`)
          )
        )
      },
    },
  }
}


text:
\begin{center}

\chapter*{Equipe}

Camila Ferreira \\
\textbf{Charles Daniel} \\
Gabriela Navarro \\
José Alberto \\
José Alisson \\
Julio Cezar do Nascimento \\
Lucas Kanashiro \\
Luiz Fernando Gomes de Oliveira \\
Macartur Sousa \\
Priscila Pires \\
Tatiana Dias \\
Thiago Ferreira Gomes

\vspace{3cm}

\let\clearpage\relax
\chapter*{Professores Coordenadores}

Alessandro Borges de Sousa Oliveira \\
Edson Mintsu Hung \\
Juliana Petrocchi Rodrigues \\
Ricardo Ajax Dias Kosloski \\
Ricardo Matos Chaim  \\
Suélia de Siqueira Rodrigues Fleury Rosa

\end{center}

\newpage