def copy_container_type_capacity
      return unless container_type and container_type.capacity
      self.capacity = cpc = container_type.capacity.copy(:rows, :columns)
      logger.debug { "Initialized #{qp} capacity from #{container_type.qp} capacity #{cpc}." }
      update_full_flag
      cpc
    end

Copies this Container's ContainerType capacity, if it exists, to the Container capacity.

 @quirk caTissue this method must be called by subclass initializers. The caTissue API
   does not make the reasonable assumption that the default Container capacity is the
   ContainerType capacity.

 @return [Capacity, nil] the initialized capacity, if any

Copies this Container s ContainerType capacity if it exists to the Container capacity .


def load
      data = api('user.get_prefs')
      self.attributes = data['result'].inject({}) do |result, (preference, value, *)|
        result[preference] = value
        result
      end
      super
    end

def load data = api ( 'user.get_prefs' ) self . attributes = data [ 'result' ] . inject ( { } ) do | result , ( preference , value , * ) | result [ preference ] = value result end super end

Loads the user's current Turntable preferences.

 @return [true]
 @raise [Turntabler::Error] if the command fails
 @example
   preferences.load        # => true
   preferences.notify_dj   # => false

Loads the user s current Turntable preferences .


def execute
      File.open(out_file, 'w') do |o|
        File.new(in_file, 'r').each_with_index do |line, index|
          extraction = col_filter.process(row_filter.process(line.chomp, row: index))
          o.puts extraction unless extraction.nil?
        end
      end
    end

def execute File . open ( out_file , 'w' ) do | o | File . new ( in_file , 'r' ) . each_with_index do | line , index | extraction = col_filter . process ( row_filter . process ( line . chomp , row : index ) ) o . puts extraction unless extraction . nil? end end end

Creates a new extractor
 Executes the extractor


def teams(summoner, optional={})
    region = optional[:region] || @sightstone.region
    id = if summoner.is_a? Summoner
      summoner.id
    else
      summoner
    end

    uri = "https://prod.api.pvp.net/api/lol/#{region}/v2.2/team/by-summoner/#{id}"

    response = _get_api_response(uri)
    _parse_response(response) { |resp|
      data = JSON.parse(resp)
      teams = []
      data.each do |team|
        teams << Team.new(team)
      end
      if block_given?
        yield teams
      else
        return teams
      end
    }
  end

call to receive all teams for a summoner
 @param [Summoner, Fixnum] summoner summoner object or id of a summoner
 @param optional [Hash] optional arguments: :region => replaces default region
 @ return [Array<Team>] An array containing all teams of the given summoner


def get_doctype(path)
      doc_type = nil
      begin
        metadata = YAML.load_file(path + 'template.yml')
        doc_type = metadata['type']
        if doc_type.nil?
          say 'Type value not found. Check template.yml in the document directory', :red
          say 'Make sure there is an entry `type: DOC_TYPE` in the file.'
          say "  #{path}"
          raise_error('DOC_TYPE not found in template.yml')
        end
      rescue Errno::ENOENT # File not found
        say 'No template.yml found in the document directory. Did you forget to add it?', :red
        say 'Did you run the command in the directory where the document is located?'
        say "  #{path}"
        raise_error('template.yml not found')
      end
      return doc_type
    end

Get the document type from the YAML file next to the document.

 @param [Pathname] The path to the location of the template.yml file.
 @return [String] the type of the document found in the YAML file.

Get the document type from the YAML file next to the document .


def execute
      allocation = {}
      File.open(infile).each_with_index do |line, index|
        row = row_filter.process(line, row: index)
        next if row.nil? or row.empty?
        key = key_filter.process(row)
        allocation[key] = [] if allocation[key].nil?
        allocation[key] << col_filter.process(row).split(';')
      end

      File.open(outfile, 'w') do |out|
        allocation.each do |key, values|
          out.puts "#{key};#{values.flatten.uniq.sort.join(';')}"
        end
      end
    end

Creates a new allocator. Options are infile, outfile, key, rows and columns to allocate to key
 Executes the allocator and assigns column values to the key

Creates a new allocator . Options are infile outfile key rows and columns to allocate to key Executes the allocator and assigns column values to the key


def span_to(spanner)
      Vector.new((@x - spanner.x).abs, (@y - spanner.y).abs)
    end

def span_to ( spanner ) Vector . new ( ( @x - spanner . x ) . abs , ( @y - spanner . y ) . abs ) end

Find the span between two Vectors

 * *Args*    :
   - +spanner+ -> Vector

 * *Returns* :
   - Vector


def build
      log_configuration_information

      if subscription_list.empty?
        Mako.logger.warn 'No feeds were found in your subscriptions file. Please add feeds and try again.'
        return
      end

      log_time do
        request_and_build_feeds
        renderers.each do |renderer|
          renderer_instance = renderer.new(bound: self)
          writer.new(renderer: renderer_instance,
                     destination: File.expand_path(renderer_instance.file_path, Mako.config.destination)).write
        end
      end
    end

Gets list of feed_urls, requests each of them and uses the constructor to
 make Feed and Article objects, then calls to the renderers to render
 the page and stylesheets.

Gets list of feed_urls requests each of them and uses the constructor to make Feed and Article objects then calls to the renderers to render the page and stylesheets .


def log_configuration_information
      Mako.logger.info "Configuration File: #{Mako.config.config_file}"
      Mako.logger.info "Theme: #{Mako.config.theme}"
      Mako.logger.info "Destination: #{Mako.config.destination}"
    end

Prints configuration file, source, and destination directory to STDOUT.

Prints configuration file source and destination directory to STDOUT .


def log_time
      Mako.logger.info 'Generating...'
      start_time = Time.now.to_f
      yield
      generation_time = Time.now.to_f - start_time
      Mako.logger.info "done in #{generation_time} seconds"
    end

def
log_time
Mako
.
logger
.
info
'Generating...'
start_time
=
Time
.
now
.
to_f
yield
generation_time
=
Time
.
now
.
to_f
start_time
Mako
.
logger
.
info
"done in #{generation_time} seconds"
end

Provides build time logging information and writes it to STDOUT.

Provides build time logging information and writes it to STDOUT .


def execute
      result = eval(operation)
      if outfile
        if result.is_a?(SpreadSheet)
          result.write(outfile)
        else
          puts
          puts "Warning: Result is no spread sheet and not written to file!"
          puts "         To view the result use -p flag" unless print
        end
      end

      if print
        puts
        puts "Operation"
        puts "---------"
        operation.split(';').each { |o| puts o }
        puts
        puts "Result"
        puts "------"
        if result.nil? || result.empty?
          puts result.inspect
        else
          puts result
        end
        puts
      end
    end

"         To view the result use -p flag"

Executes the operation and writes the result to the outfile


def create_operands(opts)
        files   = opts[:files].split(',')
        rlabels = opts[:rlabels].split(',').collect { |l| l.upcase == "TRUE" }
        clabels = opts[:clabels].split(',').collect { |l| l.upcase == "TRUE" }

        operands = {}
        opts[:aliases].split(',').each_with_index do |a,i|
          operands[a] = SpreadSheet.new(file: files[i], ds: opts[:ds],
                                        equalize: opts[:equalize],
                                        r: rlabels[i], c: clabels[i])
        end

        operands
      end

def create_operands ( opts ) files = opts [ :files ] . split ( ',' ) rlabels = opts [ :rlabels ] . split ( ',' ) . collect { | l | l . upcase == "TRUE" } clabels = opts [ :clabels ] . split ( ',' ) . collect { | l | l . upcase == "TRUE" } operands = { } opts [ :aliases ] . split ( ',' ) . each_with_index do | a , i | operands [ a ] = SpreadSheet . new ( file : files [ i ] , ds : opts [ :ds ] , equalize : opts [ :equalize ] , r : rlabels [ i ] , c : clabels [ i ] ) end operands end

Creates the spread sheet operands for the arithmetic operation


def publish(params)
      params[:msgid] = message_id = next_message_id
      params = @default_params.merge(params)

      logger.debug "Message sent: #{params.inspect}"

      if HTTP_APIS.include?(params[:api])
        publish_to_http(params)
      else
        publish_to_socket(params)
      end

      # Add timeout handler
      EventMachine.add_timer(@timeout) do
        dispatch('msgid' => message_id, 'command' => 'response_received', 'error' => 'timed out')
      end if @timeout

      message_id
    end

def
publish
(
params
)
params
[
:msgid
]
=
message_id
=
next_message_id
params
=
@default_params
.
merge
(
params
)
logger
.
debug
"Message sent: #{params.inspect}"
if
HTTP_APIS
.
include?
(
params
[
:api
]
)
publish_to_http
(
params
)
else
publish_to_socket
(
params
)
end
# Add timeout handler
EventMachine
.
add_timer
(
@timeout
)
do
dispatch
(
'msgid'
=>
message_id
,
'command'
=>
'response_received'
,
'error'
=>
'timed out'
)
end
if
@timeout
message_id
end

Publishes the given params to the underlying web socket.  The defaults
 initially configured as part of the connection will also be included in
 the message.

 @param [Hash] params The parameters to include in the message sent
 @return [Fixnum] The id of the message delivered

Publishes the given params to the underlying web socket . The defaults initially configured as part of the connection will also be included in the message .


def publish_to_socket(params)
      message = params.is_a?(String) ? params : params.to_json
      data = "~m~#{message.length}~m~#{message}"
      @socket.send(data)
    end

def publish_to_socket ( params ) message = params . is_a? ( String ) ? params : params . to_json data = "~m~#{message.length}~m~#{message}" @socket . send ( data ) end

Publishes the given params to the web socket


def publish_to_http(params)
      api = params.delete(:api)
      message_id = params[:msgid]

      http = EventMachine::HttpRequest.new("http://turntable.fm/api/#{api}").get(:query => params)
      if http.response_header.status == 200
        # Command executed properly: parse the results
        success, data = JSON.parse(http.response)
        data = {'result' => data} unless data.is_a?(Hash)
        message = data.merge('success' => success)
      else
        # Command failed to run
        message = {'success' => false, 'error' => http.error}
      end
      message.merge!('msgid' => message_id)

      # Run the message handler
      event = Faye::WebSocket::API::Event.new('message', :data => "~m~#{Time.now.to_i}~m~#{JSON.generate(message)}")
      on_message(event)
    end

Publishes the given params to the HTTP API


def on_message(event)
      data = event.data

      response = data.match(/~m~\d*~m~(.*)/)[1]
      message =
        case response
        when /no_session/
          {'command' => 'no_session'}
        when /(~h~[0-9]+)/
          # Send the heartbeat command back to the server
          publish_to_socket($1)
          {'command' => 'heartbeat'}
        else
          JSON.parse(response)
        end
      message['command'] = 'response_received' if message['msgid']

      logger.debug "Message received: #{message.inspect}"
      dispatch(message)
    end

Callback when a message has been received from the remote server on the
 open socket.

Callback when a message has been received from the remote server on the open socket .


def add_defaults_local
      super
      self.capacity ||= Capacity.new.add_defaults
      self.row_label ||= capacity.rows && capacity.rows > 0 ? 'Row' : 'Unused'
      self.column_label ||= capacity.columns && capacity.columns > 0 ? 'Column' : 'Unused'
    end

def add_defaults_local super self . capacity ||= Capacity . new . add_defaults self . row_label ||= capacity . rows && capacity . rows > 0 ? 'Row' : 'Unused' self . column_label ||= capacity . columns && capacity . columns > 0 ? 'Column' : 'Unused' end

Adds an empty capacity and default dimension labels, if necessary.
 The default +one_dimension_label+ is 'Column' if there is a non-zero dimension capacity, 'Unused' otherwise.
 The default +two_dimension_label+ is 'Row' if there is a non-zero dimension capacity, 'Unused' otherwise.

 @quirk JRuby See {#merge_container_type_attributes}. Work-around is that each ContainerType
   subclass must alias +add_defaults_local+ to this method.

Adds an empty capacity and default dimension labels if necessary . The default + one_dimension_label + is Column if there is a non - zero dimension capacity Unused otherwise . The default + two_dimension_label + is Row if there is a non - zero dimension capacity Unused otherwise .


def ping ()
      log.debug "Pinging"
      Timeout.timeout(1) do
        TCPSocket.new(address, 22).close
      end
      true
    rescue Timeout::Error, Errno::ECONNREFUSED
      fail "Failed to ping #{self}"
    end

def
ping
(
)
log
.
debug
"Pinging"
Timeout
.
timeout
(
1
)
do
TCPSocket
.
new
(
address
,
22
)
.
close
end
true
rescue
Timeout
::
Error
,
Errno
::
ECONNREFUSED
fail
"Failed to ping #{self}"
end

Attempt to connect to port 22 on the host.
 @return +true+
 @raise If it doesn't connect within 1 second.
 @api private

Attempt to connect to port 22 on the host .


def cp (froms, to, as: nil, quiet: false)
      as ||= @user
      output = ""
      synchronize do
        [froms].flatten.each do |from|
          if from.is_a?(String)
            to += "/" if to[-1] != "/" && from.is_a?(Array)
            command = ["rsync", "-e", ssh_command, "-r"]
            command += [*from, "#{as}@#{@address}:#{to}"]
            log.trace command.shelljoin, quiet: quiet
            IO.popen(command, in: :close, err: %i(child out)) do |io|
              until io.eof?
                begin
                  output << io.read_nonblock(100)
                rescue IO::WaitReadable
                  IO.select([io])
                  retry
                end
              end
              io.close
              if !$?.success?
                log.fatal "exit status #{$?.exitstatus}: #{command}", quiet: quiet
                log.fatal output, quiet: quiet
                fail "failed to copy files"
              end
            end
          elsif from.respond_to?(:read)
            cmd = "echo #{Base64.strict_encode64(from.read).shellescape} | base64 -d > #{to.shellescape}"
            sh cmd, quiet: quiet
          else
            fail "Don't know how to copy a #{from.class}: #{from}"
          end
        end
      end
      true
    end

Copy files or directories to the host.
 @api private


def write (string, to, as: nil, quiet: false)
      cp StringIO.new(string), to, as: as, quiet: quiet
    end

def write ( string , to , as : nil , quiet : false ) cp StringIO . new ( string ) , to , as : as , quiet : quiet end

Write a string to a host file.
 @api private


def read (filename, as: nil, quiet: false)
      Base64.decode64 sh("cat #{filename.shellescape} | base64", as: as, quiet: quiet)
    end

def
read
(
filename
,
as
:
,
quiet
:
false
)
Base64
.
decode64
sh
(
"cat #{filename.shellescape} | base64"
,
as
:
as
,
quiet
:
quiet
)
end


def sh (command, as: nil, quiet: false)
      as ||= @user
      output = ""
      synchronize do
        log.debug "sh #{command}", quiet: quiet
        result = nil
        ch = ssh(as).open_channel do |ch|
          ch.request_pty do |ch, success|
            "failed to acquire pty" unless success
            ch.exec(command) do |_, success|
              fail "failed to execute command" unless success
              ch.on_data do |_, data|
                log.trace "received #{data.bytesize} bytes stdout", quiet: quiet
                output << data
              end
              ch.on_extended_data do |_, _, data|
                log.trace "received #{data.bytesize} bytes stderr", quiet: quiet
                output << data.colorize(:red)
              end
              ch.on_request("exit-status") do |_, data|
                result = data.read_long
                log.trace "received exit-status #{result}", quiet: quiet
              end
            end
          end
        end
        ch.wait
        fail FailedCommand, output if result != 0
        output
      end
    end

Execute a command on the host and return its output.
 @api private

Execute a command on the host and return its output .


def can_hold_child?(storable)
      Specimen === storable and storable.specimen_class == specimen_class and specimen_types.include?(storable.specimen_type)
    end

def can_hold_child? ( storable ) Specimen === storable and storable . specimen_class == specimen_class and specimen_types . include? ( storable . specimen_type ) end

Returns true if Storable is a Specimen and supported by this SpecimenArrayType.

Returns true if Storable is a Specimen and supported by this SpecimenArrayType .


def process_aggregation
      File.new(infile).each_with_index do |line, index|
        result = col_filter.process(row_filter.process(line.chomp, row: index))
        unless result.nil? or result.empty?
          if heading.empty? and not headerless
            heading << result.split(';')
            next
          else
            @sum_col = [result.split(';').size, sum_col].max
          end
          key_values[result]  += 1
          sums[sum_col_title] += 1
        end
      end
      heading.flatten!
      heading[sum_col] = sum_col_title
    end

def process_aggregation File . new ( infile ) . each_with_index do | line , index | result = col_filter . process ( row_filter . process ( line . chomp , row : index ) ) unless result . nil? or result . empty? if heading . empty? and not headerless heading << result . split ( ';' ) next else @sum_col = [ result . split ( ';' ) . size , sum_col ] . max end key_values [ result ] += 1 sums [ sum_col_title ] += 1 end end heading . flatten! heading [ sum_col ] = sum_col_title end

Process the aggregation of the key values. The result will be written to
 _outfile_

Process the aggregation of the key values . The result will be written to _outfile_


def write_result
      sum_line = [sum_row_title]
      (heading.size - 2).times { sum_line << "" }
      sum_line << sums[sum_col_title]
      row = 0;
      File.open(outfile, 'w') do |out|
        out.puts sum_line.join(';') if row == sum_row ; row += 1
        out.puts heading.join(';')
        key_values.each do |k, v|
          out.puts sum_line.join(';') if row == sum_row ; row += 1
          out.puts [k, v].join(';')
        end
      end
    end

def write_result sum_line = [ sum_row_title ] ( heading . size - 2 ) . times { sum_line << "" } sum_line << sums [ sum_col_title ] row = 0 ; File . open ( outfile , 'w' ) do | out | out . puts sum_line . join ( ';' ) if row == sum_row ; row += 1 out . puts heading . join ( ';' ) key_values . each do | k , v | out . puts sum_line . join ( ';' ) if row == sum_row ; row += 1 out . puts [ k , v ] . join ( ';' ) end end end


def init_sum_scheme(sum_scheme)
        row_scheme, col_scheme = sum_scheme.split(',') unless sum_scheme.nil?

        unless row_scheme.nil?
          @sum_row_title, @sum_row = row_scheme.split(':') unless row_scheme.empty?
        end

        @sum_row.nil? ? @sum_row = 0 : @sum_row = @sum_row.to_i
        @sum_row_title = 'Total' if @sum_row_title.nil?

        col_scheme.nil? ? @sum_col_title = 'Total' : @sum_col_title = col_scheme
        @sum_col = 0
      end

Initializes the sum row title an positions as well as the sum column
 title and position


def attributes(&block)
      raise ArgumentError, "You should provide block" unless block_given?

      attributes = Morf::AttributesParser.parse(&block)
      self.class_variable_set(:@@attributes, attributes)
    end

def
attributes
(
&
block
)
raise
ArgumentError
,
"You should provide block"
unless
block_given?
attributes
=
Morf
::
AttributesParser
.
parse
(
block
)
self
.
class_variable_set
(
:@@attributes
,
attributes
)
end

Defines casting rules
 @example
  attributes do
    string   :first_name
    string   :last_name
    integer  :age, optional: true
  end


def resolve(dep_hashes, repos)
      logger.info 'resolving dependencies'

      session = MavenRepositorySystemSession.new
      local_repo = LocalRepository.new(local_repository_path)
      local_manager = @system.newLocalRepositoryManager(local_repo)
      session.setLocalRepositoryManager(local_manager)

      collect_req = CollectRequest.new

      dep_hashes.each do |hash|
        dep = Dependency.new new_artifact(hash), 'compile'
        collect_req.addDependency dep
        logger.debug 'requested {}', dep
      end

      repos.each do |uri|
        repo = RemoteRepository.new(uri.object_id.to_s, 'default', uri)
        collect_req.addRepository repo
        logger.info 'added repository {}', repo.getUrl
        enabled = []
        enabled << 'releases' if repo.getPolicy(false).isEnabled
        enabled << 'snapshots' if repo.getPolicy(true).isEnabled
        logger.debug '{}', enabled.join('+')
      end

      node = @system.collectDependencies(session, collect_req).getRoot

      dependency_req = DependencyRequest.new(node, nil)
      @system.resolveDependencies(session, dependency_req)

      nlg = PreorderNodeListGenerator.new
      node.accept nlg

      if logger.isDebugEnabled
        total_size = 0
        nlg.getArtifacts(false).each do |artifact|
          file = artifact.file
          size = File.stat(artifact.file.absolute_path).size
          total_size += size

          logger.debug("Using %0.2f %s" % [size/MiB_PER_BYTE, artifact])
        end
        logger.debug('      -----')
        logger.debug("      %0.2f MiB total" % [total_size/MiB_PER_BYTE])
      else
        nlg.getArtifacts(false).each do |artifact|
          logger.info 'Using {}', artifact
        end
      end

      nlg.getFiles.map{|e| e.to_s }
    end

def
resolve
(
dep_hashes
,
repos
)
logger
.
info
'resolving dependencies'
session
=
MavenRepositorySystemSession
.
new
local_repo
=
LocalRepository
.
new
(
local_repository_path
)
local_manager
=
@system
.
newLocalRepositoryManager
(
local_repo
)
session
.
setLocalRepositoryManager
(
local_manager
)
collect_req
=
CollectRequest
.
new
dep_hashes
.
each
do
|
hash
|
dep
=
Dependency
.
new
new_artifact
(
hash
)
,
'compile'
collect_req
.
addDependency
dep
logger
.
debug
'requested {}'
,
dep
end
repos
.
each
do
|
uri
|
repo
=
RemoteRepository
.
new
(
uri
.
object_id
.
to_s
,
'default'
,
uri
)
collect_req
.
addRepository
repo
logger
.
info
'added repository {}'
,
repo
.
getUrl
enabled
=
[
]
enabled
<<
'releases'
if
repo
.
getPolicy
(
false
)
.
isEnabled
enabled
<<
'snapshots'
if
repo
.
getPolicy
(
true
)
.
isEnabled
logger
.
debug
'{}'
,
enabled
.
join
(
'+'
)
end
node
=
@system
.
collectDependencies
(
session
,
collect_req
)
.
getRoot
dependency_req
=
DependencyRequest
.
new
(
node
,
)
@system
.
resolveDependencies
(
session
,
dependency_req
)
nlg
=
PreorderNodeListGenerator
.
new
node
.
accept
nlg
if
logger
.
isDebugEnabled
total_size
=
0
nlg
.
getArtifacts
(
false
)
.
each
do
|
artifact
|
file
=
artifact
.
file
size
=
File
.
stat
(
artifact
.
file
.
absolute_path
)
.
size
total_size
+=
size
logger
.
debug
(
"Using %0.2f %s"
%
[
size
/
MiB_PER_BYTE
,
artifact
]
)
end
logger
.
debug
(
'      -----'
)
logger
.
debug
(
"      %0.2f MiB total"
%
[
total_size
/
MiB_PER_BYTE
]
)
else
nlg
.
getArtifacts
(
false
)
.
each
do
|
artifact
|
logger
.
info
'Using {}'
,
artifact
end
end
nlg
.
getFiles
.
map
{
|
e
|
e
.
to_s
}
end

Resolve a set of dependencies +dep_hashes+ from repositories
 +repos+.

 @param [Array<Hash>] dep_hashes

 @option dep_hash [String] :group_id the groupId of the artifact
 @option dep_hash [String] :artifact_id the artifactId of the artifact
 @option dep_hash [String] :version the version (or range of versions) of the artifact
 @option dep_hash [String] :extension default to 'jar'

 @param [Array<String>] repos urls to maven2 repositories

 @return [Array<String>] list of files

Resolve a set of dependencies + dep_hashes + from repositories + repos + .


def place(stone)
      x, y = stone.to_coord

      internal_board[y][x] = stone
    end

def place ( stone ) x , y = stone . to_coord internal_board [ y ] [ x ] = stone end


def parse(argv)
      OptionParser.new do |options|
        usage_and_help options
        assign_text_file options
        assign_weights_file options
        assign_output_file options

        begin
          options.parse argv
        rescue OptionParser::ParseError => error
          STDERR.puts error.message, "\n", options
          exit(-1)
        end
      end
    end

def parse ( argv ) OptionParser . new do | options | usage_and_help options assign_text_file options assign_weights_file options assign_output_file options begin options . parse argv rescue OptionParser :: ParseError => error STDERR . puts error . message , "\n" , options exit ( - 1 ) end end end

Parse given arguments

 @param [Array] argv


def execute(command, params)
      params[:Bugzilla_login]    ||= username
      params[:Bugzilla_password] ||= password

      self.last_command = command_string(command, params)
      xmlrpc_client.call(command, params)
    end

def execute ( command , params ) params [ :Bugzilla_login ] ||= username params [ :Bugzilla_password ] ||= password self . last_command = command_string ( command , params ) xmlrpc_client . call ( command , params ) end

Clone of an existing bug

 Example:
   # Perform a clone of an existing bug, and return the new bug ID.
   bz.clone(948970)

 @param bug_id [String, Fixnum] A single bug id to process.
 @param overrides [Hash] The properties to change from the source bug. Some properties include
   * <tt>:target_release</tt> - The target release for the new cloned bug.
   * <tt>:assigned_to</tt> - The person to assign the new cloned bug to.
 @return [Fixnum] The bug id to the new, cloned, bug.


def leagues(summoner, optional={})
    region = optional[:region] || @sightstone.region
    id = if summoner.is_a? Summoner
      summoner.id
    else
      summoner
    end

    uri = "https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}"
    response = _get_api_response(uri)
    _parse_response(response) { |resp|
      data = JSON.parse(resp)
      leagues = []
      data.each do |league|
        leagues << League.new(league)
      end
      if block_given?
        yield leagues
      else
        return leagues
      end
    }
  end

Provides league information of a summoner
 @param [Summoner, Integer] summoner
 @param optional [Hash] optional arguments: :region => replaces default region
 @return [Array<League>] an array of all leagues the summoner and his teams are in


def league_entries(summoner, optional={})
    region = optional[:region] || @sightstone.region
    id = if summoner.is_a? Summoner
      summoner.id
    else
      summoner
    end

    uri = "https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}/entry"
    response = _get_api_response(uri)
    _parse_response(response) { |resp|
      data = JSON.parse(resp)
      entries = []
      data.each do |entry|
        entries << LeagueItem.new(entry)
      end
      if block_given?
        yield entries
      else
        return entries
      end
    }
  end

Get all entries for the given summoner
 @param [Summoner, Integer] summoner or summoner id
 @param optional [Hash] optional arguments: :region => replaces default region
 @return [Array<LeagueItem>] an array of all entries for that given summoner


def place(top, left, angle)
      api('sticker.place', :placement => [:sticker_id => id, :top => top, :left => left, :angle => angle], :is_dj => client.user.dj?, :roomid => room.id, :section => room.section)
      true
    end

def place ( top , left , angle ) api ( 'sticker.place' , :placement => [ :sticker_id => id , :top => top , :left => left , :angle => angle ] , :is_dj => client . user . dj? , :roomid => room . id , :section => room . section ) true end

Sets the current user's stickers.

 @param [Fixnum] top The y-coordinate of the sticker
 @param [Fixnum] left The x-coordinate of the sticker
 @param [Float] angle The degree at which the sticker is angled
 @return [true]
 @raise [Turntabler::Error] if the command fails
 @example
   sticker.place(126, 78, -23)   # => true


def find
      request_uris.map do |request|
        if request[:body].nil?
          request[:uri]
        else
          html = Nokogiri::HTML(request[:body])
          potential_feed_uris = html.xpath(XPATHS.detect { |path| !html.xpath(path).empty? })
          if potential_feed_uris.empty?
            Mako.errors.add_error "Could not find feed for #{request[:uri]}"
            next
          end
          uri_string = potential_feed_uris.first.value
          feed_uri = URI.parse(uri_string)
          feed_uri.absolutize!(request[:uri])
        end
      end.compact
    end

From an array of supplied URIs, will request each one and attempt to
 find a feed URI on the page.  If one is found, it will be added to
 an array and returned.

 @return [Array]

From an array of supplied URIs will request each one and attempt to find a feed URI on the page . If one is found it will be added to an array and returned .


def collection_status=(value)
      if value == 'Complete' then
        specimens.each { |spc| spc.collection_status = 'Collected' if spc.pending? }
      end
      setCollectionStatus(value)
    end

def collection_status = ( value ) if value == 'Complete' then specimens . each { | spc | spc . collection_status = 'Collected' if spc . pending? } end setCollectionStatus ( value ) end

Sets the collection status for this SCG.
 If the SCG status is set to +Complete+, then the status of each of the SCG Specimens with
 status +Pending+ is reset to +Collected+.

 @param [String] value a permissible SCG status

Sets the collection status for this SCG . If the SCG status is set to + Complete + then the status of each of the SCG Specimens with status + Pending + is reset to + Collected + .


def make_default_consent_tier_statuses
      return if registration.nil? or registration.consent_tier_responses.empty?

      # the consent tiers
      ctses = consent_tier_statuses.map { |cts| cts.consent_tier }
      # ensure that there is a CT status for each consent tier
      registration.consent_tier_responses.each do |ctr|
        ct = ctr.consent_tier
        # skip if there is a status for the response tier
        next if ctses.include?(ct)
        # make a new status
        cts = CaTissue::ConsentTierStatus.new(:consent_tier => ct)
        cts.add_defaults
        consent_tier_statuses << cts
        logger.debug { "Made default #{qp} #{cts.qp} for consent tier #{ct.qp}." }
      end
    end

Makes a consent status for each registration consent.

 @quirk caTissue Bug #156: SCG without consent status displays error.
   A SCG consent tier status is required for each consent tier in the SCG registration.

Makes a consent status for each registration consent .


def default_collection_event
      return if registration.nil?
      pcl = registration.protocol || return
      # if no protocol event, then add the default event
      pcl.add_defaults if pcl.events.empty?
      ev = pcl.sorted_events.first || return
      logger.debug { "Default #{qp} collection event is the registration protocol #{pcl.qp} first event #{ev.qp}." }
      ev
    end

Returns the first event in the protocol registered with this SCG.

Returns the first event in the protocol registered with this SCG .


def default_receiver
      cep = collection_event_parameters
      cltr = cep.user if cep
      return cltr if cltr
      cp = collection_protocol || return
      rcv = cp.coordinators.first
      return rcv if rcv or cp.fetched?
      # Try to fetch the CP coordinator
      return cp.coordinators.first if cp.find
      # CP does not exist; add the CP defaults and retry
      cp.add_defaults
      cp.coordinators.first
    end

Returns the collection protocol coordinator. Fetches the CP if necessary and possible.
 Adds defaults to the CP if necessary, which sets a default coordinator if possible.

 @return [CaTissue::User] the default receiver

Returns the collection protocol coordinator . Fetches the CP if necessary and possible . Adds defaults to the CP if necessary which sets a default coordinator if possible .


def decrement_derived_quantity(child)
      return unless specimen_type == child.specimen_type and child.initial_quantity
      if available_quantity.nil? then
        raise Jinx::ValidationError.new("Derived specimen has an initial quantity #{child.initial_quantity} but the parent is missing an available quantity")
      elsif (available_quantity - child.initial_quantity).abs < 0.00000001 then
        # rounding error
        self.available_quantity = 0.0
      elsif child.initial_quantity <= available_quantity then
        self.available_quantity -= child.initial_quantity
      else
        raise Jinx::ValidationError.new("Derived specimen initial quantity #{child.initial_quantity} exceeds parent available quantity #{available_quantity}")
      end
    end

Decrements this parent's available quantity by the given child's initial quantity, if the specimen types are the same and there
 are the relevant quantities.

Decrements this parent s available quantity by the given child s initial quantity if the specimen types are the same and there are the relevant quantities .


def update_changed_dependent(owner, property, dependent, autogenerated)
      # Save the changed collectible event parameters directly rather than via a cascade.
      if CollectibleEventParameters === dependent then
        logger.debug { "Work around a caTissue bug by resaving the collected #{owner} #{dependent} directly rather than via a cascade..." }
        update_from_template(dependent)
      elsif CaTissue::User === owner and property.attribute == :address then
        update_user_address(owner, dependent)
      elsif CaTissue::Specimen === owner and CaTissue::Specimen === dependent then
        logger.debug { "Work around caTissue bug to update #{dependent} separately after the parent #{owner} update..." }
        prepare_specimen_for_update(dependent)
        update_from_template(dependent)
        logger.debug { "Updated the #{owner} child #{dependent}." }
      elsif CaTissue::ConsentTierStatus === dependent then
          update_from_template(owner)
      else
        super
      end
    end

Updates the given dependent.

 @quirk caTissue 1.2 user address update results in authorization error. Work-around is to
   create a new address record.

 @quirk caTissue Specimen update cascades to child update according to Hibernate, but
   caTissue somehow circumvents the child update. The child database content is not changed
   to reflect the update argument. Work-around is to update the child independently after
   the parent update.

 @quirk caTissue The aforementioned {#save_with_template} caTissue collectible event parameters
   dependent bug implies that the dependent must be saved directly rather than via a cascade
   from the Specimen or SCG owner to the referenced event parameters. The direct save avoids
   a tangled nest of obscure caTissue bugs described in the {#save_with_template} rubydoc.

 @quirk caTissue A SCG or Specimen consent tier status is not necessarily cascaded.
 @param (see CaRuby::Writer#update_changed_dependent)


def update_user_address(user, address)
      logger.debug { "Work around caTissue prohibition of #{user} address #{address} update by creating a new address record for a dummy user..." }
      address.identifier = nil
      perform(:create, address) { create_object(address) }
      logger.debug { "Worked around caTissue address update bug by swizzling the #{user} address #{address} identifier." }
      perform(:update, user) { update_object(user) }
      user
    end

Updates the given user address.

 @param [CaTissue::User] the user owner
 @param [CaTissue::Address] the address to update
 @return [CaTissue::User] the updated user


def add_position_to_specimen_template(specimen, template)
      pos = specimen.position
      # the non-domain position attributes
      pas = pos.class.nondomain_attributes
      # the template position reflects the old values, if available
      ss = pos.snapshot
      # the attribute => value hash
      vh = ss ? pas.to_compact_hash { |pas| ss[pas] } : pos.value_hash(pas)
      vh[:specimen] = template
      vh[:storage_container] = pos.storage_container.copy
      # the template position reflects the old values
      template.position = pos.class.new(vh)
      logger.debug { "Work around #{specimen} update anomaly by copying position #{template.position.qp} to update template #{template.qp} as #{template.position.qp} with values #{vh.qp}..." }
    end

Adds the specimen position to its save template.

 @param [CaTissue::Specimen] specimen the existing specimen with an existing position
 @param template (see #save_with_template)
 @see {#save_with_template}

Adds the specimen position to its save template .


def ensure_primary_annotation_has_hook(annotation)
      hook = annotation.hook
      if hook.nil? then
        raise CaRuby::DatabaseError.new("Cannot save annotation #{annotation} since it does not reference a hook entity")
      end
      if hook.identifier.nil? then
        logger.debug { "Ensuring that the annotation #{annotation.qp} hook entity #{hook.qp} exists in the database..." }
        ensure_exists(hook)
      end
    end

Ensures that a primary annotation hook exists.

 @param (see #prepare_annotation_for_save)
 @raise [CaRuby::DatabaseError] if the annotation does not reference a hook entity

Ensures that a primary annotation hook exists .


def copy_annotation_proxy_owner_to_template(obj, template)
      prop = obj.class.proxy_property
      # Ignore the proxy attribute if it is defined by caRuby rather than caTissue.
      return unless prop and prop.java_property?
      rdr, wtr = prop.java_accessors
      pxy = obj.send(rdr)
      logger.debug { "Setting #{obj.qp} template #{template.qp} proxy owner to #{pxy}..." }
      template.send(wtr, pxy)
    end

The annotation proxy is not copied because the attribute redirects to the hook rather
 than the proxy. Set the template copy source proxy to the target object proxy using
 the low-level Java property methods instead.

 @param [Annotation] obj the copy source
 @param [Annotation] template the copy target

The annotation proxy is not copied because the attribute redirects to the hook rather than the proxy . Set the template copy source proxy to the target object proxy using the low - level Java property methods instead .


def create_table_data
      processed_header = false

      File.open(infile).each_with_index do |line, index|
        line = line.chomp

        next if line.empty?

        line = unstring(line).chomp

        header.process line, processed_header

        unless processed_header
          processed_header = true
          next
        end

        next if row_filter.process(line, row: index).nil?

        @columns = line.split(';')

        create_row(create_key, line)
      end

    end

def create_table_data processed_header = false File . open ( infile ) . each_with_index do | line , index | line = line . chomp next if line . empty? line = unstring ( line ) . chomp header . process line , processed_header unless processed_header processed_header = true next end next if row_filter . process ( line , row : index ) . nil? @columns = line . split ( ';' ) create_row ( create_key , line ) end end


def write_to_file
      File.open(outfile, 'w') do |out|
        out.puts header.to_s
        out.puts create_sum_row if @sum_row_pos == 'TOP'
        rows.each do |key, row|
          line = [] << row[:key]
          header.clear_header_cols.each_with_index do |col, index|
            next if index < row[:key].size
            line << row[:cols][col]
          end
          out.puts line.flatten.join(';')
        end
        out.puts create_sum_row if @sum_row_pos == 'EOF'
      end
    end

def write_to_file File . open ( outfile , 'w' ) do | out | out . puts header . to_s out . puts create_sum_row if @sum_row_pos == 'TOP' rows . each do | key , row | line = [ ] << row [ :key ] header . clear_header_cols . each_with_index do | col , index | next if index < row [ :key ] . size line << row [ :cols ] [ col ] end out . puts line . flatten . join ( ';' ) end out . puts create_sum_row if @sum_row_pos == 'EOF' end end


def to_number(value)
        value = convert_to_en(value)
        return value.to_i unless value =~ /\./
        return value.to_f if     value =~ /\./
      end

def to_number ( value ) value = convert_to_en ( value ) return value . to_i unless value =~ / \. / return value . to_f if value =~ / \. / end

Casts a string to an integer or float depending whether the value has a
 decimal point


def prepare_sum_row(pattern)
        return if pattern.nil? || pattern.empty?
        @sum_row_pos, sum_row_pattern = pattern.split(/(?<=^top|^eof):/i)
        @sum_row_pos.upcase!
        @sum_row = Hash.new
        @sum_row_patterns = split_by_comma_regex(sum_row_pattern)
      end

def prepare_sum_row ( pattern ) return if pattern . nil? || pattern . empty? @sum_row_pos , sum_row_pattern = pattern . split ( / /i ) @sum_row_pos . upcase! @sum_row = Hash . new @sum_row_patterns = split_by_comma_regex ( sum_row_pattern ) end

Initializes sum_row_pos, sum_row and sum_row_patterns based on the
 provided sum option

Initializes sum_row_pos sum_row and sum_row_patterns based on the provided sum option


def add_to_sum_row(value, column)
        return unless @sum_row_patterns
        @sum_row_patterns.each do |pattern|
          if pattern =~ /^\(?c\d+[=~+.]/
            header_column = evaluate(pattern, "")
          else
            header_column = pattern
          end

          if header_column == column
            @sum_row[header_column] ||= 0
            @sum_row[header_column] += value
          end
        end
      end

def add_to_sum_row ( value , column ) return unless @sum_row_patterns @sum_row_patterns . each do | pattern | if pattern =~ / \( \d / header_column = evaluate ( pattern , "" ) else header_column = pattern end if header_column == column @sum_row [ header_column ] ||= 0 @sum_row [ header_column ] += value end end end

Adds a value in the specified column to the sum_row


def create_sum_row
        line = []
        header.clear_header_cols.each do |col|
          line << @sum_row[col] || ""
        end
        line.flatten.join(';')
      end

def create_sum_row line = [ ] header . clear_header_cols . each do | col | line << @sum_row [ col ] || "" end line . flatten . join ( ';' ) end

Creates the sum_row when the file has been completely processed


def _rewrap_array(result)
      if @wrap_results
        newcoll = @collection.class.new(result)
        self.class.new(newcoll, @wrapfunc_in, @wrapfunc_out)
      else
        @collection.class.new(result.map(&@wrapfunc_out))
      end
    end

def _rewrap_array ( result ) if @wrap_results newcoll = @collection . class . new ( result ) self . class . new ( newcoll , @wrapfunc_in , @wrapfunc_out ) else @collection . class . new ( result . map ( @wrapfunc_out ) ) end end

Used to wrap results from various Enumerable methods that are defined
 to return an array


def add_dependency(key, dependencies = [])

      raise SelfDependencyError, "An object's dependencies cannot contain itself" if dependencies.include? key

      node = node_for_key_or_new key
      dependencies.each do |dependency|
        node.addEdge(node_for_key_or_new(dependency))
      end
      resolve_dependencies
    end

Add a new node, causing dependencies to be re-evaluated

Add a new node causing dependencies to be re - evaluated


def resolve_dependency(node)
      node.seen = true
      @seen_this_pass << node

      node.edges.each do |edge|
        unless @resolved.include? edge
          unless @seen_this_pass.include? edge
            unless edge.seen?
              resolve_dependency edge
            end
          else
            raise CircularDependencyError, "Circular reference detected: #{node.key.to_s} - #{edge.key.to_s}"
          end
        end
      end
      @resolved << node
    end


def with_friends
      data = api('room.directory_graph')
      data['rooms'].map do |(attrs, friends)|
        Room.new(client, attrs.merge(:friends => friends))
      end
    end

def with_friends data = api ( 'room.directory_graph' ) data [ 'rooms' ] . map do | ( attrs , friends ) | Room . new ( client , attrs . merge ( :friends => friends ) ) end end

Gets the rooms where the current user's friends are currently listening.

 @return [Array<Turntabler::Room>]
 @raise [Turntabler::Error] if the command fails
 @example
  rooms.with_friends   # => [#<Turntabler::Room ...>, ...]

Gets the rooms where the current user s friends are currently listening .


def find(query, options = {})
      assert_valid_keys(options, :limit, :skip)
      options = {:limit => 20, :skip => 0}.merge(options)

      data = api('room.search', :query => query, :skip => options[:skip])
      data['rooms'].map {|(attrs, *)| Room.new(client, attrs)}
    end

def find ( query , options = { } ) assert_valid_keys ( options , :limit , :skip ) options = { :limit => 20 , :skip => 0 } . merge ( options ) data = api ( 'room.search' , :query => query , :skip => options [ :skip ] ) data [ 'rooms' ] . map { | ( attrs , * ) | Room . new ( client , attrs ) } end

Finds rooms that match the given query string.

 @param [String] query The query string to search with
 @param [Hash] options The search options
 @option options [Fixnum] :limit (20) The maximum number of rooms to query for
 @option options [Fixnum] :skip (0) The number of rooms to skip when loading the results
 @return [Array<Turntabler::Room>]
 @raise [ArgumentError] if an invalid option is specified
 @raise [Turntabler::Error] if the command fails
   rooms.find('indie')   # => [#<Turntabler::Room ...>, ...]

Finds rooms that match the given query string .


def load(options = {})
      assert_valid_keys(options, :minimal)
      options = {:minimal => false}.merge(options)

      data = api('playlist.all', options)
      self.attributes = data
      super()
    end

def load ( options = { } ) assert_valid_keys ( options , :minimal ) options = { :minimal => false } . merge ( options ) data = api ( 'playlist.all' , options ) self . attributes = data super ( ) end

Loads the attributes for this playlist.  Attributes will automatically load
 when accessed, but this allows data to be forcefully loaded upfront.

 @param [Hash] options The configuration options
 @option options [Boolean] minimal (false) Whether to only include the identifiers for songs and not the entire metadata
 @return [true]
 @raise [Turntabler::Error] if the command fails
 @example
   playlist.load   # => true
   playlist.songs  # => [#<Turntabler::Song ...>, ...]

Loads the attributes for this playlist . Attributes will automatically load when accessed but this allows data to be forcefully loaded upfront .


def update(attributes = {})
      assert_valid_keys(attributes, :id)

      # Update id
      id = attributes.delete(:id)
      update_id(id) if id

      true
    end

def
update
(
attributes
=
{
}
)
assert_valid_keys
(
attributes
,
:id
)
# Update id
id
=
attributes
.
delete
(
:id
)
update_id
(
id
)
if
id
true
end

Updates this playlist's information.

 @param [Hash] attributes The attributes to update
 @option attributes [String] :id
 @return [true]
 @raise [ArgumentError] if an invalid attribute or value is specified
 @raise [Turntabler::Error] if the command fails
 @example
   playlist.update(:id => "rock")  # => true


def active
      @active = client.user.playlists.all.any? {|playlist| playlist == self && playlist.active?} if @active.nil?
      @active
    end

def active @active = client . user . playlists . all . any? { | playlist | playlist == self && playlist . active? } if @active . nil? @active end

Whether this is the currently active playlist

 @return [Boolean]
 @raise [Turntabler::Error] if the command fails
 @example
   playlist.active   # => true


def add(name, options = {}, &coercer)
      name  = name.to_sym
      value = Attribute.new(name, options, &coercer)
      clone_with do
        @attributes  = attributes.merge(name => value)
        @transformer = nil
      end
    end

def add ( name , options = { } , & coercer ) name = name . to_sym value = Attribute . new ( name , options , coercer ) clone_with do @attributes = attributes . merge ( name => value ) @transformer = nil end end

Initializes the attribute from given arguments
 and returns new immutable collection with the attribute

 @param (see Attribute#initialize)

 @return [AttributesDSL::Attributes]


def add_specimens(*args)
      hash = args.pop
      spcs = args
      # validate arguments
      unless Hash === hash then
        raise ArgumentError.new("Collection parameters are missing when adding specimens to protocol #{self}")
      end
      # Make the default registration, if necessary.
      unless hash.has_key?(:registration) || hash.has_key?(:collection_protocol_registration) then
        # the participant
        pnt = hash.delete(:participant)
        unless pnt then
          raise ArgumentError.new("Registration or participant missing from collection parameters: #{hash.qp}")
        end
        hash[:registration] = registration(pnt) || make_cpr(pnt)
      end
      # the new SCG
      scg = SpecimenCollectionGroup.new(hash)
      # set each Specimen SCG
      spcs.each { |spc| spc.specimen_collection_group = scg }
      scg
    end

Adds specimens to this protocol. The argumentes includes the
 specimens to add followed by a Hash with parameters and options.
 If the SCG registration parameter is not set, then a default registration
 is created which registers the given participant to this protocol.

 @example
   protocol.add_specimens(tumor, normal, :participant => pnt, :collector => srg)
   #=> a new SCG for the given participant with a matched pair of samples
   #=> collected by the given surgeon.

 @param [(<Specimen>, {Symbol => Object})] args the specimens to add followed
   by the parameters and options hash
 @option args [CaTissue::Participant] :participant the person from whom the
   specimen is collected
 @return [CaTissue::SpecimenCollectionGroup] the new SCG
 @raise [ArgumentError] if the options do not include either a participant or a registration

Adds specimens to this protocol . The argumentes includes the specimens to add followed by a Hash with parameters and options . If the SCG registration parameter is not set then a default registration is created which registers the given participant to this protocol .


def summoner(name_or_id, optional={})
    region = optional[:region] || @sightstone.region
    uri = if name_or_id.is_a? Integer
      "https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{name_or_id}"
    else
      "https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/by-name/#{URI::encode(name_or_id)}"
    end

    response = _get_api_response(uri)
    _parse_response(response) { |resp|
      data = JSON.parse(resp)
      s = Summoner.new(data.values[0])
      if block_given?
        yield s
      else
        return s
      end
    }
  end

returns a summoner object
 @param name_or_id [Integer, String] name or id of the summoner
 @param optional [Hash] optional arguments: :region => replaces default region
 @ return [Summoner] summoner


def names(ids, optional={})
    region = optional[:region] || @sightstone.region
    ids = ids.join(',')
    uri = "https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids}/name"
    response = _get_api_response(uri)
    _parse_response(response) { |resp|
      data = JSON.parse(resp)

      names_hash = Hash.new
      data.each do |id, name|
        names_hash[id.to_i] = name
      end
      if block_given?
        yield names_hash
      else
        return names_hash
      end
    }
  end

returns the names for the ids
 @param ids [Array<Numeric>] ids
 @param optional [Hash<Symbol, String>] optional arguments: :region => replaces default region
 @return [Hash<Numeric, String>] a hash matching each id to the summoners name


def runebook(summoner, optional={})
    region = optional[:region] || @sightstone.region
    id = if summoner.is_a? Summoner
      summoner.id
    else
      summoner
    end
    uri = "https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{id}/runes"
    response = _get_api_response(uri)
    _parse_response(response) { |resp|
      data = JSON.parse(resp)
      book = RuneBook.new(data.values[0])
      if block_given?
        yield book
      else
        return book
      end
    }
  end

returns the runebook of a summoner
 @param summoner [Summoner, id] summoner object or id of a summoner
 @param optional [Hash<Symbol, String>] optional arguments: :region => replaces default region
 @return [Runebook] runebook of the summoner


def runebooks(summoners, optional={})
    return {} if summoners.empty?

    region = optional[:region] || @sightstone.region
    ids = summoners.collect { |summoner|
      if summoner.is_a? Summoner
        summoner.id
      else
        summoner
      end
    }
    uri = "https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids.join(',')}/runes"
    response = _get_api_response(uri)
    _parse_response(response) { |resp|
      data = JSON.parse(resp)
      books = {}
      data.each do |key, raw_book|
        books[key] = RuneBook.new(raw_book)
      end
      if block_given?
        yield books
      else
        return books
      end
    }
  end

returns the runebook for multiple summoners
 @param summoners [Array<(Summoner, Integer)>] list of summoner objects or ids of summoners
 @param optional [Hash<Symbol, String>] optional arguments: :region => replaces default region
 @return [Hash<Integer, Runebook>] A hash mapping runebooks to the ids of summoners


def write
            buffer = create_zip(@entries, @ignore_entries)

            puts "\nwrite file #{@output_file}"
            File.open(@output_file, "wb") {|f| f.write buffer.string }
        end

def
write
buffer
=
create_zip
(
@entries
,
@ignore_entries
)
puts
"\nwrite file #{@output_file}"
File
.
open
(
@output_file
,
"wb"
)
{
|
f
|
f
.
write
buffer
.
string
}
end

Initialize with the json config.
 Zip the input entries.

Initialize with the json config . Zip the input entries .


def collect(opts)
      raise Jinx::ValidationError.new("#{self} is already collected") if received?
      specimen_event_parameters.merge!(extract_event_parameters(opts))
    end

def
collect
(
opts
)
raise
Jinx
::
ValidationError
.
new
(
"#{self} is already collected"
)
if
received?
specimen_event_parameters
.
merge!
(
extract_event_parameters
(
opts
)
)
end

Collects and receives this Collectible with the given options.

 @param (see #extract_event_parameters)
 @option opts (see #extract_event_parameters)
 @raise [Jinx::ValidationError] if this Collectible has already been received

Collects and receives this Collectible with the given options .


def method_missing ( id , * args , & block ) boolean_row_regex = %r{ \( \d \. \( \) \d \) \| \| \( \d \. \( \) \d \) }xi return boolean_row ( $1 , args , block ) if id =~ boolean_row_regex return equal ( $1 , args , block ) if id =~ / \d / return equal_type ( $1 , $2 , args , block ) if id =~ / \d / return range ( $1 , $2 , args , block ) if id =~ / \d \d / return range_type ( $1 , $2 , $3 , args , block ) if id =~ / \d \d / return regex ( $1 , args , block ) if id =~ / \/ \/ / return col_regex ( $1 , $2 , args , block ) if id =~ / \d \/ \/ / return date ( $1 , $2 , $3 , args , block ) if id =~ / \d \d \d \d / return date_range ( $1 , $2 , $3 , args , block ) if id =~ / \d \d \d \d \d \d \d / return number ( $1 , $2 , $3 , args , block ) if id =~ / \d \d / return number_range ( $1 , $2 , $3 , args , block ) if id =~ / \d \d \d / super end

Creates a new filter
 Creates the filters based on the given patterns


def match_boolean_filter?(values=[])
      return false if boolean_filter.empty? or values.empty?
      expression = boolean_filter
      columns = expression.scan(/(([nsd])(\d+))([<!=~>]{1,2})(.*?)(?:[\|&]{2}|$)/)
      columns.each do |c|
        value = case c[1]
        when 'n'
          values[c[2].to_i].empty? ? '0' : values[c[2].to_i]
        when 's'
          "\"#{values[c[2].to_i]}\""
        when 'd'
          begin
            Date.strptime(values[c[2].to_i], date_format)
          rescue Exception => e
            case c[3]
            when '<', '<=', '=='
              "#{c[4]}+1"
            when '>', '>='
              '0'
            when '!='
              c[4]
            end
          else
            "Date.strptime('#{values[c[2].to_i]}', '#{date_format}')"
          end
        end
        expression = expression.gsub(c[0], value)
      end
      eval(expression)
    end

Checks whether the values match the boolean filter


def pivot_each_column(values=[])
      pivot.each do |column, parameters|
        value = values[parameters[:col].to_i]
        value = value.strip.gsub(/^"|"$/, "") unless value.nil?
        match = false
        begin
          match = eval(parameters[:operation].gsub('[value]', value))
        rescue Exception => e

        end
        yield column, match
      end
    end

def pivot_each_column ( values = [ ] ) pivot . each do | column , parameters | value = values [ parameters [ :col ] . to_i ] value = value . strip . gsub ( / / , "" ) unless value . nil? match = false begin match = eval ( parameters [ :operation ] . gsub ( '[value]' , value ) ) rescue Exception => e end yield column , match end end

Yields the column value and whether the filter matches the column


def create_filter(values)
        values.scan(/(?<=,|^)(BEGIN.*?END|\/.*?\/|.*?)(?=,|$)/i).flatten.each do |value|
          send(value)
        end unless values.nil?
      end

def create_filter ( values ) values . scan ( / \/ \/ /i ) . flatten . each do | value | send ( value ) end unless values . nil? end

Creates a filter based on the provided rows and columns select criteria


def equal(value, args, block)
        filter << value.to_i unless filter.index(value.to_i)
      end

def equal ( value , args , block ) filter << value . to_i unless filter . index ( value . to_i ) end


def equal_type(type, value, args, block)
        filter_size_before = filter.size
        equal(value, args, block)
        types << type if filter_size_before < filter.size
      end

def equal_type ( type , value , args , block ) filter_size_before = filter . size equal ( value , args , block ) types << type if filter_size_before < filter . size end

Adds a single value and an associated type to the filter


def range(start_value, end_value, args, block)
        filter << (start_value.to_i..end_value.to_i).to_a
      end

def range ( start_value , end_value , args , block ) filter << ( start_value . to_i .. end_value . to_i ) . to_a end


def range_type(type, start_value, end_value, args, block)
        filter_size_before = filter.size
        range(start_value, end_value, args, block)
        (filter.size - filter_size_before).times { types << type }
      end

def range_type ( type , start_value , end_value , args , block ) filter_size_before = filter . size range ( start_value , end_value , args , block ) ( filter . size - filter_size_before ) . times { types << type } end

Adds a range and the associated types to the filter


def col_regex(col, r, args, block)
        operation = "'[value]' =~ Regexp.new('#{r}')"
        pivot[r] = { col: col, operation: operation }
      end

def
col_regex
(
col
,
r
,
args
,
block
)
operation
=
"'[value]' =~ Regexp.new('#{r}')"
pivot
[
r
]
=
{
col
:
col
,
operation
:
operation
}
end


def date(col, comparator, date, args, block)
        comparator = '==' if comparator == '='
        operation = "Date.strptime(\"[value]\", \"#{date_format}\") #{comparator} " +
                    "Date.strptime(\"#{date}\", \"#{date_format}\")"
        pivot["#{comparator}#{date}"] = { col: col, operation: operation }
      end


def date_range(col, start_date, end_date, args, block)
        operation = "   Date.strptime(\"#{start_date}\",  \"#{date_format}\") "    +
                    "<= Date.strptime(\"[value]\",        \"#{date_format}\") && " +
                    "   Date.strptime(\"[value]\",        \"#{date_format}\") "    +
                    "<= Date.strptime(\"#{end_date}\",    \"#{date_format}\")"
        pivot["#{start_date}-#{end_date}"] = { col: col, operation: operation }
      end


def number(col, comparator, number, args, block)
        comparator = '==' if comparator == '='
        operation = "[value] #{comparator} #{number}"
        pivot["#{comparator}#{number}"] = { col: col, operation: operation }
      end

def
number
(
col
,
comparator
,
number
,
args
,
block
)
comparator
=
'=='
if
comparator
==
'='
operation
=
"[value] #{comparator} #{number}"
pivot
[
"#{comparator}#{number}"
]
=
{
col
:
col
,
operation
:
operation
}
end


def number_range(col, start_number, end_number, arg, block)
        operation = " #{start_number} <= [value] && [value] <= #{end_number}"
        pivot["#{start_number}-#{end_number}"] = { col: col, operation: operation }
      end


def create_annotation(hook, annotation)
      # validate the arguments
      if hook.nil? then raise ArgumentError.new("Annotated caTissue object is missing") end
      if annotation.nil? then raise ArgumentError.new("Annotation caTissue object is missing") end
      # the annotated object must exist in the database
      unless hook.identifier then
        raise AnnotationError.new("Annotation writer does not support annotation of a caTissue object without an identifier: #{hook}")
      end
      # load the caRuby annotations if necessary
      hook.class.ensure_annotations_loaded
      # set the annotation hook reference
      annotation.hook = hook
      # create the annotation in the database
      annotation.create
    end

Creates a new annotation object in the caTissue database.

 @param [CaTissue::Resource] hook the existing static hook object to annotate
 @param [CaTissue::Annotation] annotation the annotation object to create
 @raise [AnnotationError] if the hook object does not have a database identifier

Creates a new annotation object in the caTissue database .


def join_as_series(options = {})
      if defined?(I18n)
        default_delimiter       = I18n.translate(:'series_joiner.default_delimiter',       :locale => options[:locale])
        default_final_delimiter = I18n.translate(:'series_joiner.default_final_delimiter', :locale => options[:locale])
        default_conjunction     = I18n.translate(:'series_joiner.default_conjunction',     :locale => options[:locale])
      else
        default_delimiter       = ', '
        default_final_delimiter = ''
        default_conjunction     = ' and '
      end

      delimiter = options[:delimiter] || default_delimiter
      final_delimiter = options[:final_delimiter] || default_final_delimiter
      conjunction = options[:conjunction] || default_conjunction

      sz = self.size
      if sz > 0
        r = self[0]
        if sz > 1
          if sz > 2
            for i in 1..(sz - 2)
              r += delimiter + self[i]
            end
            r += final_delimiter
          end
          r += conjunction + self[sz - 1]
        end
      end
      return r
    end

def
join_as_series
(
options
=
{
}
)
if
defined?
(
I18n
)
default_delimiter
=
I18n
.
translate
(
:'
'
,
:locale
=>
options
[
:locale
]
)
default_final_delimiter
=
I18n
.
translate
(
:'
'
,
:locale
=>
options
[
:locale
]
)
default_conjunction
=
I18n
.
translate
(
:'
'
,
:locale
=>
options
[
:locale
]
)
else
default_delimiter
=
', '
default_final_delimiter
=
''
default_conjunction
=
' and '
end
delimiter
=
options
[
:delimiter
]
||
default_delimiter
final_delimiter
=
options
[
:final_delimiter
]
||
default_final_delimiter
conjunction
=
options
[
:conjunction
]
||
default_conjunction
sz
=
self
.
size
if
sz
>
0
r
=
self
[
0
]
if
sz
>
1
if
sz
>
2
for
i
in
1
..
(
sz
2
)
r
+=
delimiter
+
self
[
i
]
end
r
+=
final_delimiter
end
r
+=
conjunction
+
self
[
sz
1
]
end
end
return
r
end

Joins items in an array together in a grammatically correct manner.

 Options:
 * `delimiter` - inserted between items, except for the final two (default: ', ')
 * `final_delimiter` - inserted between the final two items (if > 2), but before the conjunction (default: '')
 * `conjunction` - inserted between the final two items (default: ' and ')

Joins items in an array together in a grammatically correct manner .


def awesome_string(string)
      lexers = ::Rouge::Guessers::Source.new(string).filter(R_LEXERS)
      if !lexers.empty?
        format_syntax_string(string, lexers.first)
      elsif string =~ /(?:\r?\n)(?!\z)/
        format_multiline_string(string)
      else
        format_plain_string(string)
      end
    end

def awesome_string ( string ) lexers = :: Rouge :: Guessers :: Source . new ( string ) . filter ( R_LEXERS ) if ! lexers . empty? format_syntax_string ( string , lexers . first ) elsif string =~ / \r \n \z / format_multiline_string ( string ) else format_plain_string ( string ) end end

Format a String for awesome_print display.

 @param string [String] the String to format
 @return [String] the formatted String

Format a String for awesome_print display .


def meta=val
      val = JSON.parse(val) if val.is_a?(String)
      write_store_attribute(:data, :meta, val)
    end

def meta = val val = JSON . parse ( val ) if val . is_a? ( String ) write_store_attribute ( :data , :meta , val ) end

ensure meta always will be saved as json instead of json string


def execute
      File.new(infile).each_with_index do |line, index|
        row = row_filter.process(line, row: index)
        next if row.nil? or row.chomp.empty?
        collection.each do |category, elements|
          values = elements[:filter].process(row)
          values.chomp.split(';').each do |value|
            elements[:entries] << value.chomp if elements[:entries].index(value.chomp).nil?
          end
        end
      end

      File.open(outfile, 'w') do |out|
        collection.each do |category, elements|
          out.puts "[#{category}]"
          elements[:entries].sort.each { |c| out.puts c }
        end
      end
    end

def execute File . new ( infile ) . each_with_index do | line , index | row = row_filter . process ( line , row : index ) next if row . nil? or row . chomp . empty? collection . each do | category , elements | values = elements [ :filter ] . process ( row ) values . chomp . split ( ';' ) . each do | value | elements [ :entries ] << value . chomp if elements [ :entries ] . index ( value . chomp ) . nil? end end end File . open ( outfile , 'w' ) do | out | collection . each do | category , elements | out . puts "[#{category}]" elements [ :entries ] . sort . each { | c | out . puts c } end end end

Creates a new Collector
 Execute the collector


def init_collection(column_filter)
        column_filter.split('+').each do |f|
          category, filter = f.split(':')
          collection[category] = { entries: [], filter: ColumnFilter.new(filter) }
        end
      end

def init_collection ( column_filter ) column_filter . split ( '+' ) . each do | f | category , filter = f . split ( ':' ) collection [ category ] = { entries : [ ] , filter : ColumnFilter . new ( filter ) } end end


def log
      out.sync = true
      @log ||= Logger.new(out)

      @log.formatter = proc do |severity, datetime, progname, msg|
        if verbose
          string = "#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S.%2N')}]: "
        else
          string = "[#{datetime.strftime('%H:%M:%S')}]: "
        end

        string += "#{msg}\n"

        string
      end
      @log
    end

Initialize with default stdout output and verbose false
 Gets the logging object


def require_aether *deps
      @mini_aether_require_spec ||= MiniAether::Spec.new
      @mini_aether_require_resolver ||= MiniAether::Resolver.new

      spec = @mini_aether_require_spec
      resolver = @mini_aether_require_resolver

      if deps.last.kind_of?(Hash)
        hash = deps.pop
        [hash[:source], hash[:sources]].flatten.compact.each do |source|
          spec.source(source)
        end
      end

      deps.each {|coords| spec.jar(coords) }
      resolver.require(spec.dependencies, spec.sources)
      nil
    end

def require_aether * deps @mini_aether_require_spec ||= MiniAether :: Spec . new @mini_aether_require_resolver ||= MiniAether :: Resolver . new spec = @mini_aether_require_spec resolver = @mini_aether_require_resolver if deps . last . kind_of? ( Hash ) hash = deps . pop [ hash [ :source ] , hash [ :sources ] ] . flatten . compact . each do | source | spec . source ( source ) end end deps . each { | coords | spec . jar ( coords ) } resolver . require ( spec . dependencies , spec . sources ) nil end

Experimental 'require_aether' method for use in irb or just for
 convenience.  Not threadsafe.

 @overload require_aether(*coords)
   @param [Array<String>] coords one or more colon-separated maven coordinate strings

 @overload require_aether(*coords, sources)
   @param [Array<String>] coords one or more colon-separated maven coordinate strings
   @param [Hash] sources a hash with a key +:source+ or +:sources+
   and a value of a single string or an array of sources that will be
   permanently added to the list of sources

Experimental require_aether method for use in irb or just for convenience . Not threadsafe .


def create_lookup_table
        File.open(source).each_with_index do |line|
          next if line.chomp.empty?

          values = unstring(line).chomp.split(';')

          next if values.empty?

          @joiners.each do |joiner|
            key = values[joiner.join[0]]
            joiner.lookup[:rows][key] = []

            joiner.cols.each do |i|
              joiner.lookup[:rows][key] << values[i]
            end
          end

        end
      end

def create_lookup_table File . open ( source ) . each_with_index do | line | next if line . chomp . empty? values = unstring ( line ) . chomp . split ( ';' ) next if values . empty? @joiners . each do | joiner | key = values [ joiner . join [ 0 ] ] joiner . lookup [ :rows ] [ key ] = [ ] joiner . cols . each do | i | joiner . lookup [ :rows ] [ key ] << values [ i ] end end end end

Creates a lookup table from the source file values. The join column of
 the source file is the key

Creates a lookup table from the source file values . The join column of the source file is the key


def col_positions(pos, cols)
        if pos.nil? || pos.empty?
          pos = []
          cols.each { |c| pos << Array.new(c.size) { |c| c } }
          pos
        else
          pos.split(';').collect { |p| p.split(',').collect { |p| p.to_i } }
        end
      end

def col_positions ( pos , cols ) if pos . nil? || pos . empty? pos = [ ] cols . each { | c | pos << Array . new ( c . size ) { | c | c } } pos else pos . split ( ';' ) . collect { | p | p . split ( ',' ) . collect { | p | p . to_i } } end end

Initializes the column positions where the source file columns have to
 be inserted. If no column positions are provided the inserted columns
 are put at the beginning of the row

Initializes the column positions where the source file columns have to be inserted . If no column positions are provided the inserted columns are put at the beginning of the row


def create_joiners(j, c, p)
        js = j.split(';').collect { |j| j.split('=').collect { |j| j.to_i } }
        cs = c.split(';').collect { |c| c.split(',').collect { |c| c.to_i } }
        ps = col_positions(p, cs)

        @joiners = []
        (0...js.size).each do |i|
          @joiners << Joiner.new(js[i], ps[i], cs[i], { rows: { } })
        end

        ps.flatten
      end

def create_joiners ( j , c , p ) js = j . split ( ';' ) . collect { | j | j . split ( '=' ) . collect { | j | j . to_i } } cs = c . split ( ';' ) . collect { | c | c . split ( ',' ) . collect { | c | c . to_i } } ps = col_positions ( p , cs ) @joiners = [ ] ( 0 ... js . size ) . each do | i | @joiners << Joiner . new ( js [ i ] , ps [ i ] , cs [ i ] , { rows : { } } ) end ps . flatten end

Initializes joiners based on joins, positions and columns

 Possible input forms are:
 joins:: "4=0;4=1" or "4=1"
 positions:: "1,2;4,5" or "1,2"
 columns:: "1,2;3,4"

 This has the semantic of 'insert columns 1 and 2 at positions 1 and 2
 for key 0 and columns 3 and 4 at positions 4 and 5 for key 1. Key 4 is
 the corresponding value in the source file

 Return value:: positions where to insert values from source file

Initializes joiners based on joins positions and columns


def add_defaults_local
      super
      self.title ||= short_title
      self.short_title ||= title
      self.start_date ||= Java::JavaUtil::Date.new
    end

def add_defaults_local super self . title ||= short_title self . short_title ||= title self . start_date ||= Java :: JavaUtil :: Date . new end

Sets the defaults if necessary. The start date is set to now. The title is
 set to the short title.

Sets the defaults if necessary . The start date is set to now . The title is set to the short title .


def [](*range)
      r, c = range
      r ||= 0..(nrows-1)
      c ||= 0..(ncols-1)

      row_selection = rows.values_at(*r)
      col_selection = []

      if rows_are_arrays?(row_selection)
        row_selection.each do |row|
          values = row.values_at(*c)
          col_selection << (values.respond_to?(:to_ary) ? values : [values])
        end
      else
        col_selection << row_selection[*c]
      end

      SpreadSheet.new(*col_selection,
                      row_labels: row_labels.values_at(*r),
                      col_labels: col_labels.values_at(*c))
    end

def [] ( * range ) r , c = range r ||= 0 .. ( nrows - 1 ) c ||= 0 .. ( ncols - 1 ) row_selection = rows . values_at ( r ) col_selection = [ ] if rows_are_arrays? ( row_selection ) row_selection . each do | row | values = row . values_at ( c ) col_selection << ( values . respond_to? ( :to_ary ) ? values : [ values ] ) end else col_selection << row_selection [ c ] end SpreadSheet . new ( col_selection , row_labels : row_labels . values_at ( r ) , col_labels : col_labels . values_at ( c ) ) end

Returns a subset of the spread sheet and returns a new spread sheet with
 the result and the corresponding row and column labels


def column_collect(&block)
      result = []
      0.upto(ncols-1) { |i| result << block.call(self[nil,i]) }
      result
    end

def column_collect ( & block ) result = [ ] 0 . upto ( ncols - 1 ) { | i | result << block . call ( self [ nil , i ] ) } result end

Collects the operation on each column and returns the result in an array


def rename(opts = {})
      if opts[:rows]
        opts[:rows] = opts[:rows][0,nrows]
        opts[:rows] += row_labels[opts[:rows].size, nrows]
      end

      if opts[:cols]
        opts[:cols] = opts[:cols][0,ncols]
        opts[:cols] += col_labels[opts[:cols].size, ncols]
      end

      @row_labels = opts[:rows] if opts[:rows]
      @col_labels = opts[:cols] if opts[:cols]
    end

def rename ( opts = { } ) if opts [ :rows ] opts [ :rows ] = opts [ :rows ] [ 0 , nrows ] opts [ :rows ] += row_labels [ opts [ :rows ] . size , nrows ] end if opts [ :cols ] opts [ :cols ] = opts [ :cols ] [ 0 , ncols ] opts [ :cols ] += col_labels [ opts [ :cols ] . size , ncols ] end @row_labels = opts [ :rows ] if opts [ :rows ] @col_labels = opts [ :cols ] if opts [ :cols ] end

Renames the row and column labels

   sheet.rename(rows: ['Row 1', 'Row 2'], cols: ['Col 1', 'Col 2'])

 If the provided rows and columns are larger than the spread sheet's rows
 and columns then only the respective row and column values are used. If
 the row and column labels are fewer than the respective row and column
 sizes the old labels are left untouched for the missing new labels


def to_s
      col_label_sizes = col_labels.collect { |c| c.to_s.size + 2 }
      row_label_size = row_labels.collect { |r| r.to_s.size + 2 }.max

      row_col_sizes = rows.transpose.collect { |r| r.collect { |c| c.to_s.size } }

      i = -1
      col_sizes = col_label_sizes.collect do |s|
        i += 1
        [row_col_sizes[i],s].flatten.max + 1
      end

      s = (sprintf("%#{row_label_size}s", " "))
      col_labels.each_with_index { |l,i| s << (sprintf("%#{col_sizes[i]}s",
                                                       "[#{l}]"))           }
      s << "\n"

      rows.each_with_index do |row, i|
        s << (sprintf("%#{row_label_size}s", "[#{row_labels[i]}]"))
        row.each_with_index { |c,j| s << (sprintf("%#{col_sizes[j]}s", c)) }
        s << "\n"
      end

      s
    end

def
to_s
col_label_sizes
=
col_labels
.
collect
{
|
c
|
c
.
to_s
.
size
+
2
}
row_label_size
=
row_labels
.
collect
{
|
r
|
r
.
to_s
.
size
+
2
}
.
max
row_col_sizes
=
rows
.
transpose
.
collect
{
|
r
|
r
.
collect
{
|
c
|
c
.
to_s
.
size
}
}
i
=
1
col_sizes
=
col_label_sizes
.
collect
do
|
s
|
i
+=
1
[
row_col_sizes
[
i
]
,
s
]
.
flatten
.
max
+
1
end
s
=
(
sprintf
(
"%#{row_label_size}s"
,
" "
)
)
col_labels
.
each_with_index
{
|
l
,
i
|
s
<<
(
sprintf
(
"%#{col_sizes[i]}s"
,
"[#{l}]"
)
)
}
s
<<
"\n"
rows
.
each_with_index
do
|
row
,
i
|
s
<<
(
sprintf
(
"%#{row_label_size}s"
,
"[#{row_labels[i]}]"
)
)
row
.
each_with_index
{
|
c
,
j
|
s
<<
(
sprintf
(
"%#{col_sizes[j]}s"
,
c
)
)
}
s
<<
"\n"
end
s
end

Prints the spread sheet in a matrix with column labels and row labels. If
 no labels are available the column number and row number is printed

Prints the spread sheet in a matrix with column labels and row labels . If no labels are available the column number and row number is printed


def rows_from_params(opts)
        col_count = opts[:cols]
        row_count = opts[:rows]

        size = row_count * col_count if row_count && col_count

        rows = []

        if values = opts[:values]
          if size
            values += [NotAvailable] * (size - values.size)
          elsif col_count
            values += [NotAvailable] * ((col_count - values.size) % col_count)
          elsif row_count
            values += [NotAvailable] * ((row_count - values.size) % row_count)
            col_count = values.size / row_count
          else
            col_count = Math.sqrt(values.size).ceil
            values += [NotAvailable] * ((col_count - values.size) % col_count)
          end
          values.each_slice(col_count) { |row| rows << row }
        elsif opts[:file]
          File.foreach(opts[:file]) do |line|
            next if line.chomp.empty?
            values = line.split(SEMICOLON) rescue str2utf8(line).split(SEMICOLON)
            rows << values.collect { |v|
              v.strip.empty? ? NotAvailable : str2num(v.chomp, opts[:ds])
            }
          end
        end

        rows
      end

def rows_from_params ( opts ) col_count = opts [ :cols ] row_count = opts [ :rows ] size = row_count * col_count if row_count && col_count rows = [ ] if values = opts [ :values ] if size values += [ NotAvailable ] * ( size - values . size ) elsif col_count values += [ NotAvailable ] * ( ( col_count - values . size ) % col_count ) elsif row_count values += [ NotAvailable ] * ( ( row_count - values . size ) % row_count ) col_count = values . size / row_count else col_count = Math . sqrt ( values . size ) . ceil values += [ NotAvailable ] * ( ( col_count - values . size ) % col_count ) end values . each_slice ( col_count ) { | row | rows << row } elsif opts [ :file ] File . foreach ( opts [ :file ] ) do | line | next if line . chomp . empty? values = line . split ( SEMICOLON ) rescue str2utf8 ( line ) . split ( SEMICOLON ) rows << values . collect { | v | v . strip . empty? ? NotAvailable : str2num ( v . chomp , opts [ :ds ] ) } end end rows end

Creates rows from provided array or file. If array doesn't provide
 equal column sizes the array is extended with NotAvailable values

Creates rows from provided array or file . If array doesn t provide equal column sizes the array is extended with NotAvailable values


def equalize_rows(rows)
        column_sizes = rows.collect { |r| r.size }

        return rows if column_sizes.uniq.size == 1

        max_size = column_sizes.max
        small_rows = []
        column_sizes.each_with_index { |c,i| small_rows << i if c < max_size }

        small_rows.each do |i|
          rows[i] += [NotAvailable] * (max_size - rows[i].size)
        end

        rows
      end

def equalize_rows ( rows ) column_sizes = rows . collect { | r | r . size } return rows if column_sizes . uniq . size == 1 max_size = column_sizes . max small_rows = [ ] column_sizes . each_with_index { | c , i | small_rows << i if c < max_size } small_rows . each do | i | rows [ i ] += [ NotAvailable ] * ( max_size - rows [ i ] . size ) end rows end

If rows are of different column size the rows are equalized in column
 size by filling missing columns with NA


def same_column_size?(rows)
        offset = opts[:c] ? 1 : 0
        return true if rows.size == 1 + offset
        (0 + offset).upto(rows.size - 2) do |i|
          return false unless rows[i].size == rows[i+1].size
        end
        true
      end

def same_column_size? ( rows ) offset = opts [ :c ] ? 1 : 0 return true if rows . size == 1 + offset ( 0 + offset ) . upto ( rows . size - 2 ) do | i | return false unless rows [ i ] . size == rows [ i + 1 ] . size end true end

Checks whether all rows have the same column size. Returns true if
 all columns have the same column size

Checks whether all rows have the same column size . Returns true if all columns have the same column size


def coerce(value)
        return SpreadSheet.new([value]) if value.is_a?(Numeric)
        return SpreadSheet.new(value)   if value.is_a?(Array)
      end

def coerce ( value ) return SpreadSheet . new ( [ value ] ) if value . is_a? ( Numeric ) return SpreadSheet . new ( value ) if value . is_a? ( Array ) end

Coerces a number or an array to a spread sheet


def process(operator, s)
        s = coerce(s) || s
        raise "operand needs to be a SpreadSheet, "+
              "Numeric or Array" unless s.is_a?(SpreadSheet)
        result = []
        rlabel = []
        clabel = []
        s1_row_count, s1_col_count = dim
        s2_row_count, s2_col_count = s.dim
        row_count = [s1_row_count, s2_row_count].max
        col_count = [s1_col_count, s2_col_count].max
        0.upto(row_count - 1) do |r|
          r1 = r % s1_row_count
          r2 = r % s2_row_count
          rlabel << "#{row_labels[r1]}#{operator}#{s.row_labels[r2]}"
          element = []
          0.upto(col_count - 1) do |c|
            c1 = c % s1_col_count
            c2 = c % s2_col_count
            clabel << "#{col_labels[c1]}#{operator}#{s.col_labels[c2]}"
            element << rows[r1][c1].send(operator, s.rows[r2][c2])
          end
          result << element
        end
        SpreadSheet.new(*result, row_labels: rlabel, col_labels: clabel)
      end

Conducts the calculation of this spread sheet with the provided value
 based on the operator. It s is a number or an array it is coerced into
 a spread sheet

Conducts the calculation of this spread sheet with the provided value based on the operator . It s is a number or an array it is coerced into a spread sheet


def process_count
      File.new(infile).each_with_index do |line, index|
        result = col_filter.process(row_filter.process(line.chomp, row: index))
        unless result.nil? or result.empty?
          key = unstring(line).split(';').values_at(*key_columns)
          key_value = key_values[key] || key_values[key] = { name: key,
                                                             elements: Hash.new(0),
                                                             sum: 0 }
          result.chomp.split(';').each do |column|
            heading << column if heading.index(column).nil?
            key_value[:elements][column] += 1
            key_value[:sum] += 1
            sums[column] += 1
          end
        end
      end
    end

def process_count File . new ( infile ) . each_with_index do | line , index | result = col_filter . process ( row_filter . process ( line . chomp , row : index ) ) unless result . nil? or result . empty? key = unstring ( line ) . split ( ';' ) . values_at ( key_columns ) key_value = key_values [ key ] || key_values [ key ] = { name : key , elements : Hash . new ( 0 ) , sum : 0 } result . chomp . split ( ';' ) . each do | column | heading << column if heading . index ( column ) . nil? key_value [ :elements ] [ column ] += 1 key_value [ :sum ] += 1 sums [ column ] += 1 end end end end


def write_result
      sum_line = [sum_row_title] + [''] * (key_titles.size - 1)
      headline = heading_sort ? heading.sort : original_pivot_sequence_heading
      headline << add_sum_col unless sum_col_title.nil?
      headline.each do |h|
        sum_line << sums[h]
      end
      row = 0;
      File.open(outfile, 'w') do |out|
        out.puts sum_line.join(';') if row == sum_row ; row += 1
        out.puts (key_titles + headline).join(';')
        key_values.each do |k,v|
          out.puts sum_line.join(';') if row == sum_row ; row += 1
          line = [k]
          headline.each do |h|
            line << v[:elements][h] unless h == sum_col_title
          end
          line << v[:sum] unless sum_col_title.nil?
          out.puts line.join(';')
        end
      end
    end

def write_result sum_line = [ sum_row_title ] + [ '' ] * ( key_titles . size - 1 ) headline = heading_sort ? heading . sort : original_pivot_sequence_heading headline << add_sum_col unless sum_col_title . nil? headline . each do | h | sum_line << sums [ h ] end row = 0 ; File . open ( outfile , 'w' ) do | out | out . puts sum_line . join ( ';' ) if row == sum_row ; row += 1 out . puts ( key_titles + headline ) . join ( ';' ) key_values . each do | k , v | out . puts sum_line . join ( ';' ) if row == sum_row ; row += 1 line = [ k ] headline . each do | h | line << v [ :elements ] [ h ] unless h == sum_col_title end line << v [ :sum ] unless sum_col_title . nil? out . puts line . join ( ';' ) end end end


def init_sum_scheme(sum_scheme)

        return if sum_scheme.nil?

        re = /(\w+):(\d+)|(\w+)/

        sum_scheme.scan(re).each do |part|
          if part.compact.size == 2
            @sum_row_title = part[0]
            @sum_row       = part[1].to_i
          else
            @sum_col_title = part[2]
          end
        end

      end

def init_sum_scheme ( sum_scheme ) return if sum_scheme . nil? re = / \w \d \w / sum_scheme . scan ( re ) . each do | part | if part . compact . size == 2 @sum_row_title = part [ 0 ] @sum_row = part [ 1 ] . to_i else @sum_col_title = part [ 2 ] end end end

Initializes the sum row title an positions as well as the sum column
 title


def init_key_columns(key_scheme)

        @key_titles  = []
        @key_columns = []

        keys = key_scheme.scan(/(\d+):(\w+)/)

        keys.each do |key|
          @key_titles  << key[1]
          @key_columns << key[0].to_i
        end

      end

def init_key_columns ( key_scheme ) @key_titles = [ ] @key_columns = [ ] keys = key_scheme . scan ( / \d \w / ) keys . each do | key | @key_titles << key [ 1 ] @key_columns << key [ 0 ] . to_i end end


def original_pivot_sequence_heading
        (heading.sort - col_filter.pivot.keys << col_filter.pivot.keys).flatten
      end

def original_pivot_sequence_heading ( heading . sort - col_filter . pivot . keys << col_filter . pivot . keys ) . flatten end

Arrange heading in the original sequence regarding conditional column
 filters


def process(object, options={})
      object = unstring(object)
      return object unless has_filter?
      filtered = !filter.flatten.uniq.index(options[:row]).nil?
      pattern.each do |p|
        filtered = (filtered or !(object =~ Regexp.new(p)).nil?)
      end
      filtered = (filtered or match_boolean_filter?(object.split(';')))
      filtered ? object : nil
    end

def process ( object , options = { } ) object = unstring ( object ) return object unless has_filter? filtered = ! filter . flatten . uniq . index ( options [ :row ] ) . nil? pattern . each do | p | filtered = ( filtered or ! ( object =~ Regexp . new ( p ) ) . nil? ) end filtered = ( filtered or match_boolean_filter? ( object . split ( ';' ) ) ) filtered ? object : nil end


def messages
      data = api('pm.history', :receiverid => id)
      data['history'].map {|attrs| Message.new(client, attrs)}
    end

def messages data = api ( 'pm.history' , :receiverid => id ) data [ 'history' ] . map { | attrs | Message . new ( client , attrs ) } end

Gets the private conversation history with this user.

 @return [Array<Turntabler::Message>]
 @raise [Turntabler::Error] if the command fails
 @example
   user.messages   # => [#<Turntabler::Message ...>, ...]

Gets the private conversation history with this user .


def stalk
      become_fan unless client.user.fan_of.include?(self)
      client.rooms.with_friends.detect do |room|
        room.listener(id)
      end
    end

def stalk become_fan unless client . user . fan_of . include? ( self ) client . rooms . with_friends . detect do | room | room . listener ( id ) end end

Gets the location of the user.

 @note This will make the current user a fan of this user
 @return [Turntabler::Room]
 @raise [Turntabler::Error] if the command fails
 @example
   user.stalk    # => #<Turntabler::Room ...>


def boot(reason = '')
      api('room.boot_user', :roomid => room.id, :section => room.section, :target_userid => id, :reason => reason)
      true
    end

def boot ( reason = '' ) api ( 'room.boot_user' , :roomid => room . id , :section => room . section , :target_userid => id , :reason => reason ) true end

Boots the user for the specified reason.

 @param [String] reason The reason why the user is being booted
 @return [true]
 @raise [Turntabler::Error] if the command fails
 @example
   user.boot('Broke rules')    # => true

Boots the user for the specified reason .


def report(reason = '')
      api('room.report_user', :roomid => room.id, :section => room.section, :reported => id, :reason => reason)
      true
    end

def report ( reason = '' ) api ( 'room.report_user' , :roomid => room . id , :section => room . section , :reported => id , :reason => reason ) true end

Reports abuse by a user.

 @param [String] reason The reason the user is being reported
 @return [true]
 @raise [Turntabler::Error] if the command fails
 @example
   user.report('Verbal abuse ...')  # => true


def default_derived_characteristics
      chrs = specimen_characteristics || return
      pas = chrs.class.nondomain_attributes.reject { |pa| pa == :identifier }
      chrs.copy(pas)
    end

def default_derived_characteristics chrs = specimen_characteristics || return pas = chrs . class . nondomain_attributes . reject { | pa | pa == :identifier } chrs . copy ( pas ) end

Returns characteristics to use for a derived specimen. The new characteristics is copied from this
 parent specimen's characteristics, without the identifier.

 @return [CaTissue::SpecimenCharacteristics, nil] a copy of this Specimen's specimen_characteristics, or nil if none

Returns characteristics to use for a derived specimen . The new characteristics is copied from this parent specimen s characteristics without the identifier .


def region=(args)
      case args
        when Hash
          self.setRegion(CoordinateRegion.new(args[:region]).api, animated: args[:animated])
        else
          self.setRegion(CoordinateRegion.new(args).api, animated: false)
      end
    end

def region = ( args ) case args when Hash self . setRegion ( CoordinateRegion . new ( args [ :region ] ) . api , animated : args [ :animated ] ) else self . setRegion ( CoordinateRegion . new ( args ) . api , animated : false ) end end

Set the maps region

 * *Args*    :
    region = CoordinateRegion.new([56, 10.6], [3.1, 3.1])
    region = {:region => CoordinateRegion.new([56, 10.6], [3.1, 3.1]), :animated => false}


def collection_site
      return unless medical_identifiers.size == 1
      site = medical_identifiers.first.site
      return if site.nil?
      site.site_type == Site::SiteType::COLLECTION ? site : nil
    end

def collection_site return unless medical_identifiers . size == 1 site = medical_identifiers . first . site return if site . nil? site . site_type == Site :: SiteType :: COLLECTION ? site : nil end

Returns the collection site for which this participant has a MRN. If there is not exactly one
 such site, then this method returns nil. This method is a convenience for the common situation
 where a participant is enrolled at one site.

 @return [CaTissue::Site] the collection site

Returns the collection site for which this participant has a MRN . If there is not exactly one such site then this method returns nil . This method is a convenience for the common situation where a participant is enrolled at one site .


def match_characteristics(other)
      chr = characteristics
      ochr = other.characteristics
      chr and ochr and chr.tissue_side == ochr.tissue_side and chr.tissue_site == ochr.tissue_site
    end

def match_characteristics ( other ) chr = characteristics ochr = other . characteristics chr and ochr and chr . tissue_side == ochr . tissue_side and chr . tissue_site == ochr . tissue_site end

Returns whether this SpecimenRequirement characteristics matches the other SpecimenRequirement characteristics
 on the tissue site and tissue side.

Returns whether this SpecimenRequirement characteristics matches the other SpecimenRequirement characteristics on the tissue site and tissue side .


def default_user
      scg = specimen_collection_group || (specimen.specimen_collection_group if specimen) || return
      cp = scg.collection_protocol || return
      cp.coordinators.first || (cp.sites.first.coordinator if cp.sites.size === 1)
    end

def default_user scg = specimen_collection_group || ( specimen . specimen_collection_group if specimen ) || return cp = scg . collection_protocol || return cp . coordinators . first || ( cp . sites . first . coordinator if cp . sites . size === 1 ) end

Returns the first SCG CP coordinator, if any.

Returns the first SCG CP coordinator if any .


def export!
      puts "Exporting translations:\n"
      if config[:split]
        translations.keys.each do |locale|
          if translations[:en].nil?
            puts 'Missing english translation'
            exit
          end
          puts "\nLocale: #{locale}"
          fallback_english_hash = flat_hash(translations[:en])
          translations_hash = flat_hash(translations[locale])
          if locale != :en
            translations_hash.each do |key, value|
              english_fallback = fallback_english_hash[key]
              if value == nil || value == ""
                puts "  #{key} missing!"
                puts "     taking english default: '#{english_fallback}'"
                translations_hash[key] = english_fallback
              end
            end
          end
          save(translations_hash, File.join(export_dir, "translations_#{locale}.js"))
        end
      else
        save(flat_hash(translations), File.join(export_dir, 'translations.js'))
      end
    end

Export translations to JavaScript, considering settings
 from configuration file

Export translations to JavaScript considering settings from configuration file


def save(translations, file)
      file = ::Rails.root.join(file)
      FileUtils.mkdir_p File.dirname(file)

      variable_to_assign = config.fetch(:variable, 'Ember.I18n.translations')

      File.open(file, 'w+') do |f|
        f << variable_to_assign
        f << ' = '
        f << JSON.pretty_generate(translations).html_safe
        f << ';'
      end
    end

def
save
(
translations
,
file
)
file
=
::
Rails
.
root
.
join
(
file
)
FileUtils
.
mkdir_p
File
.
dirname
(
file
)
variable_to_assign
=
config
.
fetch
(
:variable
,
'Ember.I18n.translations'
)
File
.
open
(
file
,
'w+'
)
do
|
f
|
f
<<
variable_to_assign
f
<<
' = '
f
<<
JSON
.
pretty_generate
(
translations
)
.
html_safe
f
<<
';'
end
end

Convert translations to JSON string and save file.

Convert translations to JSON string and save file .


def translations
      ::I18n.load_path = default_locales_path
      ::I18n.backend.instance_eval do
        init_translations unless initialized?
        translations
      end
    end

def translations :: I18n . load_path = default_locales_path :: I18n . backend . instance_eval do init_translations unless initialized? translations end end


def load_properties
      # the properties file
      file = default_properties_file
      # the access properties
      props = file && File.exists?(file) ? load_properties_file(file) : {}
      # Load the Java application jar path.
      path = props[:classpath] || props[:path] || infer_classpath
      Java.expand_to_class_path(path) if path
      # Get the application login properties from the remoteService.xml, if necessary.
      unless props.has_key?(:host) or props.has_key?(:port) then
        url = remote_service_url
        if url then
          host, port = url.split(':')
          props[:host] = host
          props[:port] = port
        end
      end
      unless props.has_key?(:database) then
        props.merge(infer_database_properties)
      end
      props
    end

Loads the caTissue classpath and connection properties.

Loads the caTissue classpath and connection properties .