def transform_text_part(part)
      type = part.part_type?
      text = part.body.decoded.strip
      transform_text(type, text)
    end

def transform_text_part ( part ) type = part . part_type? text = part . body . decoded . strip transform_text ( type , text ) end

Helper for process_media template method to transform text.

Helper for process_media template method to transform text .


def temp_file(part)
      file_name = filename?(part)
      File.expand_path(File.join(msg_tmp_dir(),File.basename(file_name)))
    end

def temp_file ( part ) file_name = filename? ( part ) File . expand_path ( File . join ( msg_tmp_dir ( ) , File . basename ( file_name ) ) ) end

Helper for process template method to name a temporary filepath based on
 information in the part.  This version attempts to honor the name of the
 media as labeled in the part header and creates a unique temporary
 directory for writing the file so filename collision does not occur.
 Consumers of this method expect the directory structure to the file
 exists, if the method is overridden it is mandatory that this behavior is
 retained.

Helper for process template method to name a temporary filepath based on information in the part . This version attempts to honor the name of the media as labeled in the part header and creates a unique temporary directory for writing the file so filename collision does not occur . Consumers of this method expect the directory structure to the file exists if the method is overridden it is mandatory that this behavior is retained .


def add_file(type, file)
      media[type] = [] unless media[type]
      media[type] << file
    end

def add_file ( type , file ) media [ type ] = [ ] unless media [ type ] media [ type ] << file end

Helper to add a file to the media hash .


def msg_tmp_dir
      @dir_count += 1
      dir = File.expand_path(File.join(@media_dir, "#{@dir_count}"))
      FileUtils.mkdir_p(dir)
      dir
    end

def msg_tmp_dir @dir_count += 1 dir = File . expand_path ( File . join ( @media_dir , "#{@dir_count}" ) ) FileUtils . mkdir_p ( dir ) dir end

Helper to temp_file to create a unique temporary directory that is a
 child of tmp_dir  This version is based on the message_id of the mail.

Helper to temp_file to create a unique temporary directory that is a child of tmp_dir This version is based on the message_id of the mail .


def filename?(part)
      name = part.filename
      if (name.nil? || name.empty?)
        if part.content_id && (matched = /^<(.+)>$/.match(part.content_id))
          name = matched[1]
        else
          name = "#{Time.now.to_f}.#{self.default_ext(part.part_type?)}"
        end
      end
      # FIXME FWIW, janky look for dot extension 1 to 4 chars long
      name = (name =~ /\..{1,4}$/ ? name : "#{name}.#{self.default_ext(part.part_type?)}").strip

      # handle excessively large filenames
      if name.size > 255
        ext = File.extname(name)
        base = File.basename(name, ext)
        name = "#{base[0, 255 - ext.size]}#{ext}"
      end

      name
    end

returns a filename declared for a part, or a default if its not defined

returns a filename declared for a part or a default if its not defined


def type_from_filename(filename)
      ext = filename.split('.').last
      ent = MMS2R::EXT.detect{|k,v| v == ext}
      ent.nil? ? nil : ent.first
    end

def type_from_filename ( filename ) ext = filename . split ( '.' ) . last ent = MMS2R :: EXT . detect { | k , v | v == ext } ent . nil? ? nil : ent . first end


def prefetch_primary_key?(table_name = nil)
      return true if table_name.nil?
      table_name = table_name.to_s
      primary_keys(table_name.to_s).size == 0
    end

If true, next_sequence_value is called before each insert statement
 to set the record's primary key.
 By default DB2 for i supports IDENTITY_VAL_LOCAL for tables that have
 one primary key.

If true next_sequence_value is called before each insert statement to set the record s primary key . By default DB2 for i supports IDENTITY_VAL_LOCAL for tables that have one primary key .


def execute_and_auto_confirm(sql, name = nil)

      begin
        execute_system_command('CHGJOB INQMSGRPY(*SYSRPYL)')
        execute_system_command("ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')")
      rescue Exception => e
        raise unauthorized_error_message("CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')", e)
      end

      begin
        result = execute(sql, name)
      rescue Exception
        raise
      else
        # Return if all work fine
        result
      ensure

        # Ensure default configuration restoration
        begin
          execute_system_command('CHGJOB INQMSGRPY(*DFT)')
          execute_system_command('RMVRPYLE SEQNBR(9876)')
        rescue Exception => e
          raise unauthorized_error_message('CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876)', e)
        end

      end
    end

Holy moly batman! all this to tell AS400 "yes i am sure"

Holy moly batman! all this to tell AS400 yes i am sure


def get_transfer(type)
      type = type[0].upcase + type[1..-1]
      try_require(type)
      Transfer.const_get(type).new(@options, @files)
    end

def get_transfer ( type ) type = type [ 0 ] . upcase + type [ 1 .. - 1 ] try_require ( type ) Transfer . const_get ( type ) . new ( @options , @files ) end

Creates an instance for the transfer type and return it

 type - the transfer type like sftp, ftp, etc.


def peek(aheadCount=1)
      history = []
      aheadCount.times { history << @input.getc }
      history.reverse.each { |chr| @input.ungetc(chr) }
      return history.last.chr
    end

def peek ( aheadCount = 1 ) history = [ ] aheadCount . times { history << @input . getc } history . reverse . each { | chr | @input . ungetc ( chr ) } return history . last . chr end

Get the next character without getting it.

Get the next character without getting it .


def captureOutput(output, didFinishProcessingPhoto: photo, error: error)
    if error
      error_callback.call(error)
    else
      @capture_callback.call(photo.fileDataRepresentation)
    end
  end

def captureOutput ( output , didFinishProcessingPhoto : photo , error : error ) if error error_callback . call ( error ) else @capture_callback . call ( photo . fileDataRepresentation ) end end

iOS 11+ AVCapturePhotoCaptureDelegate method

iOS 11 + AVCapturePhotoCaptureDelegate method


def captureOutput(output, didFinishProcessingPhotoSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer, resolvedSettings: resolved_settings, bracketSettings: bracket_settings, error: error)
    if error
      error_callback.call(error)
    else
      jpeg_data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(
        forJPEGSampleBuffer: photo_sample_buffer,
        previewPhotoSampleBuffer: preview_photo_sample_buffer
      )
      @capture_callback.call(jpeg_data)
    end
  end

def captureOutput ( output , didFinishProcessingPhotoSampleBuffer : photo_sample_buffer , previewPhotoSampleBuffer : preview_photo_sample_buffer , resolvedSettings : resolved_settings , bracketSettings : bracket_settings , error : error ) if error error_callback . call ( error ) else jpeg_data = AVCapturePhotoOutput . jpegPhotoDataRepresentation ( forJPEGSampleBuffer : photo_sample_buffer , previewPhotoSampleBuffer : preview_photo_sample_buffer ) @capture_callback . call ( jpeg_data ) end end

iOS 10 AVCapturePhotoCaptureDelegate method


def save_to_assets_library(jpeg_data, &block)
    assets_library.writeImageDataToSavedPhotosAlbum(jpeg_data, metadata: nil, completionBlock: -> (asset_url, error) {
      error ? error_callback.call(error) : block.call(asset_url)
    })
  end

def save_to_assets_library ( jpeg_data , & block ) assets_library . writeImageDataToSavedPhotosAlbum ( jpeg_data , metadata : nil , completionBlock : -> ( asset_url , error ) { error ? error_callback . call ( error ) : block . call ( asset_url ) } ) end


def save_to_photo_library(jpeg_data, &block)
    photo_library.performChanges(-> {
      image = UIImage.imageWithData(jpeg_data)
      PHAssetChangeRequest.creationRequestForAssetFromImage(image)
    }, completionHandler: -> (success, error) {
      if error
        error_callback.call(error)
      else
        block.call(nil) # asset url is not returned in completion block
      end
    })
  end

def save_to_photo_library ( jpeg_data , & block ) photo_library . performChanges ( -> { image = UIImage . imageWithData ( jpeg_data ) PHAssetChangeRequest . creationRequestForAssetFromImage ( image ) } , completionHandler : -> ( success , error ) { if error error_callback . call ( error ) else block . call ( nil ) end } ) end


def update_video_orientation!
    photo_output.connectionWithMediaType(AVMediaTypeVideo).tap do |connection|
      device_orientation = UIDevice.currentDevice.orientation
      video_orientation  = orientation_mapping.fetch(device_orientation, AVCaptureVideoOrientationPortrait)

      connection.setVideoOrientation(video_orientation) if connection.videoOrientationSupported?
    end
  end

def update_video_orientation! photo_output . connectionWithMediaType ( AVMediaTypeVideo ) . tap do | connection | device_orientation = UIDevice . currentDevice . orientation video_orientation = orientation_mapping . fetch ( device_orientation , AVCaptureVideoOrientationPortrait ) connection . setVideoOrientation ( video_orientation ) if connection . videoOrientationSupported? end end


def select_levels(data, backtrack, kmin, kmax)
      return kmin if kmin == kmax

      method = :normal # "uniform" or "normal"

      kopt = kmin

      base = 1 # The position of first element in x: 1 or 0.
      n = data.size - base

      max_bic = 0.0

      for k in kmin..kmax
        cluster_sizes = []
        kbacktrack = backtrack[0..k]
        backtrack(kbacktrack) do |cluster, left, right|
          cluster_sizes[cluster] = right - left + 1
        end

        index_left = base
        index_right = 0

        likelihood = 0
        bin_left, bin_right = 0
        for i in 0..(k-1)
          points_in_bin = cluster_sizes[i + base]
          index_right = index_left + points_in_bin - 1

          if data[index_left] < data[index_right]
            bin_left = data[index_left]
            bin_right = data[index_right]
          elsif data[index_left] == data[index_right]
            bin_left = index_left == base ? data[base] : (data[index_left-1] + data[index_left]) / 2
            bin_right = index_right < n-1+base ? (data[index_right] + data[index_right+1]) / 2 : data[n-1+base]
          else
            raise "ERROR: binLeft > binRight"
          end

          bin_width = bin_right - bin_left
          if method == :uniform
            likelihood += points_in_bin * Math.log(points_in_bin / bin_width / n)
          else
            mean = 0.0
            variance = 0.0

            for j in index_left..index_right
              mean += data[j]
              variance += data[j] ** 2
            end
            mean /= points_in_bin
            variance = (variance - points_in_bin * mean ** 2) / (points_in_bin - 1) if points_in_bin > 1

            if variance > 0
              for j in index_left..index_right
                likelihood += - (data[j] - mean) ** 2 / (2.0 * variance)
              end
              likelihood += points_in_bin * (Math.log(points_in_bin / Float(n))
                - 0.5 * Math.log( 2 * Math::PI * variance))
            else
              likelihood += points_in_bin * Math.log(1.0 / bin_width / n)
            end
          end

          index_left = index_right + 1
        end

        # Compute the Bayesian information criterion
        bic = 2 * likelihood - (3 * k - 1) * Math.log(Float(n))

        if k == kmin
          max_bic = bic
          kopt = kmin
        elsif bic > max_bic
          max_bic = bic
          kopt = k
        end

      end

      kopt
    end

def
select_levels
(
data
,
backtrack
,
kmin
,
kmax
)
return
kmin
if
kmin
==
kmax
method
=
:normal
kopt
=
kmin
base
=
1
n
=
data
.
size
base
max_bic
=
0.0
for
k
in
kmin
..
kmax
cluster_sizes
=
[
]
kbacktrack
=
backtrack
[
0
..
k
]
backtrack
(
kbacktrack
)
do
|
cluster
,
left
,
right
|
cluster_sizes
[
cluster
]
=
right
left
+
1
end
index_left
=
base
index_right
=
0
likelihood
=
0
bin_left
,
bin_right
=
0
for
i
in
0
..
(
k
1
)
points_in_bin
=
cluster_sizes
[
i
+
base
]
index_right
=
index_left
+
points_in_bin
1
if
data
[
index_left
]
<
data
[
index_right
]
bin_left
=
data
[
index_left
]
bin_right
=
data
[
index_right
]
elsif
data
[
index_left
]
==
data
[
index_right
]
bin_left
=
index_left
==
base
data
[
base
]
:
(
data
[
index_left
1
]
+
data
[
index_left
]
)
/
2
bin_right
=
index_right
<
n
1
+
base
(
data
[
index_right
]
+
data
[
index_right
+
1
]
)
/
2
:
data
[
n
1
+
base
]
else
raise
"ERROR: binLeft > binRight"
end
bin_width
=
bin_right
bin_left
if
method
==
:uniform
likelihood
+=
points_in_bin
*
Math
.
log
(
points_in_bin
/
bin_width
/
n
)
else
mean
=
0.0
variance
=
0.0
for
j
in
index_left
..
index_right
mean
+=
data
[
j
]
variance
+=
data
[
j
]
**
2
end
mean
/=
points_in_bin
variance
=
(
variance
points_in_bin
*
mean
**
2
)
/
(
points_in_bin
1
)
if
points_in_bin
>
1
if
variance
>
0
for
j
in
index_left
..
index_right
likelihood
+=
(
data
[
j
]
mean
)
**
2
/
(
2.0
*
variance
)
end
likelihood
+=
points_in_bin
*
(
Math
.
log
(
points_in_bin
/
Float
(
n
)
)
0.5
*
Math
.
log
(
2
*
Math
::
PI
*
variance
)
)
else
likelihood
+=
points_in_bin
*
Math
.
log
(
1.0
/
bin_width
/
n
)
end
end
index_left
=
index_right
+
1
end
bic
=
2
*
likelihood
(
3
*
k
1
)
*
Math
.
log
(
Float
(
n
)
)
if
k
==
kmin
max_bic
=
bic
kopt
=
kmin
elsif
bic
>
max_bic
max_bic
=
bic
kopt
=
k
end
end
kopt
end

Choose an optimal number of levels between Kmin and Kmax


def full_feature(value=true)
      return unless value
      @config.formulize
      @config.event = (@config.event + [:call, :return]).uniq
      @config.import_return_to_call = true
      @config.show_additional_attrs = [:path, :lineno]
      # JSON serialize trigger many problems when handle complicated object(in rails?)
      # a Back Door to open more data. but be care it could trigger weird crash when Jsonify these vars
      if value == 10
        @config.include_instance_var = true
        @config.include_local_var = true
      end
    end

def full_feature ( value = true ) return unless value @config . formulize @config . event = ( @config . event + [ :call , :return ] ) . uniq @config . import_return_to_call = true @config . show_additional_attrs = [ :path , :lineno ] if value == 10 @config . include_instance_var = true @config . include_local_var = true end end

todo. value equal 10 may not be a good params

todo . value equal 10 may not be a good params


def stack(name = nil, opts = {})
      if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name]
        unless mw.stack == self
          mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup
        end
        mw
      else
        self::StackMiddleware.new(name, self, opts)
      end
    end

def stack ( name = nil , opts = { } ) if self :: StackMiddleware . _mwares [ name ] && mw = self :: StackMiddleware . _mwares [ name ] unless mw . stack == self mw = self :: StackMiddleware . _mwares [ name ] = self :: StackMiddleware . _mwares [ name ] . dup end mw else self :: StackMiddleware . new ( name , self , opts ) end end

Useful for adding additional information into your middleware stack  definition

 @param [Object] name
   The name of a given middleware.  Each piece of middleware has a name in the stack.
   By naming middleware we can refer to it later, swap it out for a different class or even just remove it from the stack.
 @param        [Hash] opts An options hash
 @option opts [Object] :before
   Sets this middlware to be run after the middleware named.  Name is either the name given to the
   middleware stack, or the Middleware class itself.
 @option opts [Object] :after
   Sets this middleware to be run after the middleware name.  Name is either the name given to the
   middleware stack or the Middleware class itself.

 @example Declaring un-named middleware via the stack
   MyClass.stack.use(MyMiddleware)

 This middleware will be named MyMiddleware, and can be specified with (:before | :after) => MyMiddleware

 @example Declaring a named middleware via the stack
   MyClass.stack(:foo).use(MyMiddleware)

 This middleware will be named :foo and can be specified with (:before | :after) => :foo

 @example Declaring a named middleware with a :before key
   MyClass.stack(:foo, :before => :bar).use(MyMiddleware)

 This middleware will be named :foo and will be run before the middleware named :bar
 If :bar is not run, :foo will not be run either

 @example Declaring a named middlware with an :after key
   MyClass.stack(:foo, :after => :bar).use(MyMiddleware)

 This middleware will be named :foo and will be run after the middleware named :bar
 If :bar is not run, :foo will not be run either

 @see Pancake::Middleware#use
 @api public
 @since 0.1.0
 @author Daniel Neighman


def use(middleware, *_args, &block)
      stack(middleware).use(middleware, *_args, &block)
    end

def use ( middleware , * _args , & block ) stack ( middleware ) . use ( middleware , * _args , & block ) end

Adds middleware to the current stack definition

 @param [Class] middleware  The middleware class to use in the stack
 @param [Hash]  opts        An options hash that is passed through to the middleware when it is instantiated

 @yield The block is provided to the middlewares #new method when it is initialized

 @example Bare use call
   MyApp.use(MyMiddleware, :some => :option){ # middleware initialization block here }

 @example Use call after a stack call
   MyApp.stack(:foo).use(MyMiddleware, :some => :option){ # middleware initialization block here }

 @see Pancake::Middleware#stack
 @api public
 @since 0.1.0
 @author Daniel Neighman


def attribute_lookup(assoc)
      group_data = @map[assoc.group.to_sym]
      return nil unless group_data

      attribute = group_data[assoc.type.to_sym]
      return attribute
    end

def attribute_lookup ( assoc ) group_data = @map [ assoc . group . to_sym ] return nil unless group_data attribute = group_data [ assoc . type . to_sym ] return attribute end

Extracts the attribute definition for a given association


def translate_association(assoc)
      attribute = attribute_lookup(assoc)
      return unless attribute

      # Make sure we properly handle destroyed values by forcing them to an
      # empty association.  We keep their state up to this point because the
      # caller may be using the prior value for something.
      if assoc.marked_for_destruction?
        assoc = @form.create_association
      end

      add_association_to_attribute_map(attribute, assoc)
    end

def translate_association ( assoc ) attribute = attribute_lookup ( assoc ) return unless attribute if assoc . marked_for_destruction? assoc = @form . create_association end add_association_to_attribute_map ( attribute , assoc ) end

Maps an association to the attribute its data will be tied


def add_association_to_attribute_map(attribute, assoc)
      current = @attributes[attribute]

      # If there's already a value, we can safely ignore the empty association
      return if current && assoc.blank?

      case current
        when nil    then @attributes[attribute] = [assoc]
        when Array  then @attributes[attribute].push(assoc)
      end
    end

def add_association_to_attribute_map ( attribute , assoc ) current = @attributes [ attribute ] return if current && assoc . blank? case current when nil then @attributes [ attribute ] = [ assoc ] when Array then @attributes [ attribute ] . push ( assoc ) end end

Adds the given association to an array of associations for the given
 attribute


def store_associations_on_object(object, attribute, associations)
      values = associations.collect do |assoc|
        assoc.internal.blank? ? assoc.value : assoc.internal
      end

      # Clean up values
      values.compact!
      case values.length
        when 0 then values = nil
        when 1 then values = values.first
      end

      object.send("#{attribute}=", values)
    end

def store_associations_on_object ( object , attribute , associations ) values = associations . collect do | assoc | assoc . internal . blank? ? assoc . value : assoc . internal end values . compact! case values . length when 0 then values = nil when 1 then values = values . first end object . send ( "#{attribute}=" , values ) end

Stores all association data on the object at the given attribute.
 Associations with internal data use that instead of value.  If only one
 association is present, it is extracted from the array and stored as-is.

Stores all association data on the object at the given attribute . Associations with internal data use that instead of value . If only one association is present it is extracted from the array and stored as - is .


def setup_form(group, type, attr_definition)
      attr_trans = single_attribute_translator.new(
        source: @source,
        form: @form,
        group: group,
        type: type,
        attribute_definition: attr_definition
      )

      attr_trans.add_associations_to_form
    end

def setup_form ( group , type , attr_definition ) attr_trans = single_attribute_translator . new ( source : @source , form : @form , group : group , type : type , attribute_definition : attr_definition ) attr_trans . add_associations_to_form end

Sets up translation state instance to hold various attributes that need to be passed around,
 and calls helpers to build the necessary associations and attach them to the form.

Sets up translation state instance to hold various attributes that need to be passed around and calls helpers to build the necessary associations and attach them to the form .


def mount(mounted_app, path, options = {})
      mounted_app = MountedApplication.new(mounted_app, path, options)
      self.class.mounted_applications << mounted_app
      mounted_app
    end

def mount ( mounted_app , path , options = { } ) mounted_app = MountedApplication . new ( mounted_app , path , options ) self . class . mounted_applications << mounted_app mounted_app end

Mounts an application in the router as a sub application in the
 url space.  This will route directly to the sub application and
 skip any middlewares etc defined on a stack

Mounts an application in the router as a sub application in the url space . This will route directly to the sub application and skip any middlewares etc defined on a stack


def assign_tp_self_caches(tp_ins)
      unless tp_self_caches.find { |tp_cache| tp_cache.object_id.equal? tp_ins.self.object_id }
        tp_self_caches.push tp_ins.self
      end
    end

def assign_tp_self_caches ( tp_ins ) unless tp_self_caches . find { | tp_cache | tp_cache . object_id . equal? tp_ins . self . object_id } tp_self_caches . push tp_ins . self end end

include? will evaluate @tp.self, if @tp.self is AR::Relation, it could cause problems
 So that's why I use object_id as replace


def set_log(stream = Pancake.configuration.log_stream,
      log_level  = Pancake.configuration.log_level,
      delimiter  = Pancake.configuration.log_delimiter,
      auto_flush = Pancake.configuration.log_auto_flush)

      @buffer                   = []
      @delimiter                = delimiter
      @auto_flush               = auto_flush

      if Levels[log_level]
        @level                  = Levels[log_level]
      else
        @level                  = log_level
      end

      @log                      = stream
      @log.sync                 = true
      @mutex = (@@mutex[@log] ||= Mutex.new)
    end

def set_log ( stream = Pancake . configuration . log_stream , log_level = Pancake . configuration . log_level , delimiter = Pancake . configuration . log_delimiter , auto_flush = Pancake . configuration . log_auto_flush ) @buffer = [ ] @delimiter = delimiter @auto_flush = auto_flush if Levels [ log_level ] @level = Levels [ log_level ] else @level = log_level end @log = stream @log . sync = true @mutex = ( @@mutex [ @log ] ||= Mutex . new ) end

To initialize the logger you create a new object, proxies to set_log.

 ==== Parameters
 *args:: Arguments to create the log from. See set_logs for specifics.
 Replaces an existing logger with a new one.

 ==== Parameters
 log<IO, String>:: Either an IO object or a name of a logfile.
 log_level<~to_sym>::
   The log level from, e.g. :fatal or :info. Defaults to :error in the
   production environment and :debug otherwise.
 delimiter<String>::
   Delimiter to use between message sections. Defaults to " ~ ".
 auto_flush<Boolean>::
   Whether the log should automatically flush after new messages are
   added. Defaults to false.

To initialize the logger you create a new object proxies to set_log .


def dirs_for(name, opts = {})
      if _load_paths[name].blank?
        []
      else
        result = []
        invert = !!opts[:invert]
        load_paths = invert ? _load_paths[name].reverse : _load_paths[name]
        roots.each do |root|
          load_paths.each do |paths, glob|
            paths = paths.reverse if invert
            result << paths.map{|p| File.join(root, p)}
          end
        end
        result.flatten
      end # if
    end

def dirs_for ( name , opts = { } ) if _load_paths [ name ] . blank? [ ] else result = [ ] invert = ! ! opts [ :invert ] load_paths = invert ? _load_paths [ name ] . reverse : _load_paths [ name ] roots . each do | root | load_paths . each do | paths , glob | paths = paths . reverse if invert result << paths . map { | p | File . join ( root , p ) } end end result . flatten end end

Provides the directories or raw paths that are associated with a given name.

 @param        [Symbol]    name  The name for the paths group
 @param        [Hash]      opts  An options hash
 @option opts  [Boolean]   :invert (false) inverts the order of the returned paths

 @example Read Directories:
   MyClass.dirs_for(:models)

 @example Inverted Read:
   MyClass.dirs_for(:models, :invert => true)

 @return [Array] An array of the paths
   Returned in declared order unless the :invert option is set
 @api public
 @since 0.1.1
 @author Daniel Neighman

Provides the directories or raw paths that are associated with a given name .


def paths_for(name, opts = {})
      result = []
      dirs_and_glob_for(name, opts).each do |path, glob|
        next if glob.nil?
        paths = Dir[File.join(path, glob)]
        paths = paths.reverse if opts[:invert]
        paths.each do |full_path|
          result << [path, full_path.gsub(path, "")]
        end
      end
      result
    end

def paths_for ( name , opts = { } ) result = [ ] dirs_and_glob_for ( name , opts ) . each do | path , glob | next if glob . nil? paths = Dir [ File . join ( path , glob ) ] paths = paths . reverse if opts [ :invert ] paths . each do | full_path | result << [ path , full_path . gsub ( path , "" ) ] end end result end

Provides an expanded, globbed list of paths and files for a given name.

 @param        [Symbol]  name    The name of the paths group
 @param        [Hash]    opts    An options hash
 @option opts  [Boolean] :invert (false) Inverts the order of the returned values

 @example
   MyClass.paths_for(:model)
   MyClass.paths_for(:model, :invert => true)

 @return [Array]
   An array of [path, file] arrays.  These may be joined to get the full path.
   All matched files for [paths, glob] will be returned in declared and then found order unless +:invert+ is true.
   Any path that has a +nil+ glob associated with it will be excluded.

 @api public
 @since 0.1.1
 @author Daniel Neighman

Provides an expanded globbed list of paths and files for a given name .


def unique_paths_for(name, opts = {})
      tally = {}
      output = []
      paths_for(name, opts).reverse.each do |ary|
        tally[ary[1]] ||= ary[0]
        output << ary if tally[ary[1]] == ary[0]
      end
      output.reverse
    end

def unique_paths_for ( name , opts = { } ) tally = { } output = [ ] paths_for ( name , opts ) . reverse . each do | ary | tally [ ary [ 1 ] ] ||= ary [ 0 ] output << ary if tally [ ary [ 1 ] ] == ary [ 0 ] end output . reverse end

Provides an expanded, globbed list of paths and files for a given name.
 The result includes only the last matched file of a given sub path and name.

 @param        [Symbol]    name    The name of the paths group
 @param        [Hash]      opts    An options hash
 @option opts  [Boolean]   :invert (false) Inverts the order of returned paths and files

 @example
   #Given the following:
   #  /path/one/file1.rb
   #  /path/one/file2.rb
   #  /path/two/file1.rb

     MyClass.push_path(:files, ["/path/one", "/path/two"], "**/*.rb")

   MyClass.unique_paths_for(:files)
   MyClass.unique_paths_for(:files, :invert => true)

 @return [Array]
   Returns an array of [path, file] arrays
   Results are retuned in declared order.  Only unique files are returned (the file part - the path)
   In the above example, the following would be returned for the standard call
     [
       ["#{root}/path/one", "/file2.rb"],
       ["#{root}/path/two", "/file1.rb"]
     ]
   For the inverted example the following is returned:
     [
       ["#{root}/path/one/file2.rb"],
       ["#{root}/path/one/file1.rb"]
     ]

 @api public
 @since 0.1.1
 @author Daniel Neighman

Provides an expanded globbed list of paths and files for a given name . The result includes only the last matched file of a given sub path and name .


def build_association(value)
    association = @form.create_association(
      group: @group.to_s,
      type: @type.to_s,
      value: value
    )

    # Since the associations are fake, we just set persistence to the parent
    # object's value
    association.persisted = @source.persisted?

    return association
  end

def build_association ( value ) association = @form . create_association ( group : @group . to_s , type : @type . to_s , value : value ) association . persisted = @source . persisted? return association end

Builds a single association with the given data


def block_it?(tp)
      if @cond.track_params
        return true if negative_check(tp)
        if positives_check(tp)
          return !tp.binding.eval('local_variables').any? do |v|
            tp.binding.local_variable_get(v).object_id == @cond.track_params
          end
        end
      else
        return true if negative_check(tp)
        return false if positives_check(tp)
      end
      true # default is blocked the tp
    end

def block_it? ( tp ) if @cond . track_params return true if negative_check ( tp ) if positives_check ( tp ) return ! tp . binding . eval ( 'local_variables' ) . any? do | v | tp . binding . local_variable_get ( v ) . object_id == @cond . track_params end end else return true if negative_check ( tp ) return false if positives_check ( tp ) end true end

to improve performance, we didnt assign tp as instance variable

to improve performance we didnt assign tp as instance variable


def classify(value)
      raise ArgumentError, "value: #{value} must be in data array" unless @data.include?(value)

      bounds[1..-1].index { |bound| value <= bound }
    end

def
classify
(
value
)
raise
ArgumentError
,
"value: #{value} must be in data array"
unless
@data
.
include?
(
value
)
bounds
[
1
..
1
]
.
index
{
|
bound
|
value
<=
bound
}
end

Returns zero based index of cluster which a value belongs to
 value must be in data array


def intervals
      first, *rest = bounds.each_cons(2).to_a
      [first, *rest.map {|lower, upper| [data[data.rindex(lower) + 1] , upper] }]
    end

def intervals first , * rest = bounds . each_cons ( 2 ) . to_a [ first , * rest . map { | lower , upper | [ data [ data . rindex ( lower ) + 1 ] , upper ] } ] end


def matrices
      rows = data.size
      cols = n_classes

      # in the original implementation, these matrices are referred to
      # as `LC` and `OP`
      # * lower_class_limits (LC): optimal lower class limits
      # * variance_combinations (OP): optimal variance combinations for all classes
      lower_class_limits = *Matrix.zero(rows + 1, cols + 1)
      variance_combinations = *Matrix.zero(rows + 1, cols + 1)

      # the variance, as computed at each step in the calculation
      variance = 0

      for i in 1..cols
        lower_class_limits[1][i]    = 1
        variance_combinations[1][i] = 0
        for j in 2..rows
          variance_combinations[j][i] = Float::INFINITY
        end
      end

      for l in 2..rows
        sum         = 0 # `SZ` originally. this is the sum of the values seen thus far when calculating variance.
        sum_squares = 0 # `ZSQ` originally. the sum of squares of values seen thus far
        w           = 0 # `WT` originally. This is the number of data points considered so far.

        for m in 1..l
          lower_class_limit = l - m + 1 # `III` originally
          val = data[lower_class_limit - 1]

          # here we're estimating variance for each potential classing
          # of the data, for each potential number of classes. `w`
          # is the number of data points considered so far.
          w += 1

          # increase the current sum and sum-of-squares
          sum += val
          sum_squares += (val ** 2)

          # the variance at this point in the sequence is the difference
          # between the sum of squares and the total x 2, over the number
          # of samples.
          variance = sum_squares - (sum ** 2) / w

          i4 = lower_class_limit - 1 # `IV` originally
          if i4 != 0
            for j in 2..cols
             # if adding this element to an existing class
             # will increase its variance beyond the limit, break
             # the class at this point, setting the lower_class_limit
             # at this point.
             if variance_combinations[l][j] >= (variance + variance_combinations[i4][j - 1])
               lower_class_limits[l][j] = lower_class_limit
               variance_combinations[l][j] = variance +
                 variance_combinations[i4][j - 1]
             end
            end
          end
        end

        lower_class_limits[l][1] = 1
        variance_combinations[l][1] = variance
      end

      [lower_class_limits, variance_combinations]
    end

def matrices rows = data . size cols = n_classes lower_class_limits = * Matrix . zero ( rows + 1 , cols + 1 ) variance_combinations = * Matrix . zero ( rows + 1 , cols + 1 ) variance = 0 for i in 1 .. cols lower_class_limits [ 1 ] [ i ] = 1 variance_combinations [ 1 ] [ i ] = 0 for j in 2 .. rows variance_combinations [ j ] [ i ] = Float :: INFINITY end end for l in 2 .. rows sum = 0 sum_squares = 0 w = 0 for m in 1 .. l lower_class_limit = l - m + 1 val = data [ lower_class_limit - 1 ] w += 1 sum += val sum_squares += ( val ** 2 ) variance = sum_squares - ( sum ** 2 ) / w i4 = lower_class_limit - 1 if i4 != 0 for j in 2 .. cols if variance_combinations [ l ] [ j ] >= ( variance + variance_combinations [ i4 ] [ j - 1 ] ) lower_class_limits [ l ] [ j ] = lower_class_limit variance_combinations [ l ] [ j ] = variance + variance_combinations [ i4 ] [ j - 1 ] end end end end lower_class_limits [ l ] [ 1 ] = 1 variance_combinations [ l ] [ 1 ] = variance end [ lower_class_limits , variance_combinations ] end

Compute the matrices required for Jenks breaks. These matrices
 can be used for any classing of data with `classes <= n_classes`

Compute the matrices required for Jenks breaks . These matrices can be used for any classing of data with classes < = n_classes


def fetch(title, year = "", tomatoes = false, plot = "short")
      res = network.call({ t: title, y: year, tomatoes: tomatoes, plot: plot })

      if res[:data]["Response"] == "False"
        { status: 404 }
      else
        { status: res[:code], movie: parse_movie(res[:data]) }
      end
    end

def fetch ( title , year = "" , tomatoes = false , plot = "short" ) res = network . call ( { t : title , y : year , tomatoes : tomatoes , plot : plot } ) if res [ :data ] [ "Response" ] == "False" { status : 404 } else { status : res [ :code ] , movie : parse_movie ( res [ :data ] ) } end end

fetchs a movie with a given title
 set tomatoes to true if you want to get the rotten tomatoes ranking
 set plot to full if you want to have the full, long plot

fetchs a movie with a given title set tomatoes to true if you want to get the rotten tomatoes ranking set plot to full if you want to have the full long plot


def find(id, tomatoes = false, plot = "short")
      res = network.call({ i: id, tomatoes: tomatoes, plot: plot })

      if res[:data]["Response"] == "False"
        { status: 404 }
      else
        { status: res[:code], movie: parse_movie(res[:data]) }
      end
    end

def find ( id , tomatoes = false , plot = "short" ) res = network . call ( { i : id , tomatoes : tomatoes , plot : plot } ) if res [ :data ] [ "Response" ] == "False" { status : 404 } else { status : res [ :code ] , movie : parse_movie ( res [ :data ] ) } end end

fetches a movie by IMDB id
 set tomatoes to true if you want to get the rotten tomatoes ranking
 set plot to full if you want to have the full, long plot

fetches a movie by IMDB id set tomatoes to true if you want to get the rotten tomatoes ranking set plot to full if you want to have the full long plot


def options
      VALID_CONFIG_OPTIONS.inject({}) do |option, key|
        option.merge!(key => send(key))
      end
    end

def options VALID_CONFIG_OPTIONS . inject ( { } ) do | option , key | option . merge! ( key => send ( key ) ) end end

Create a hash of configuration options and their
 values.

 @return [Hash<Symbol,Object>] the options hash

Create a hash of configuration options and their values .


def create_user(options={})
      user=User.new(options)
      user.validate_for_create!
      body = user_hash(user.to_hash)
      response=oauth_access_token.post('/v1/users', body: body)
      User.new(response.parsed)
    end

def create_user ( options = { } ) user = User . new ( options ) user . validate_for_create! body = user_hash ( user . to_hash ) response = oauth_access_token . post ( '/v1/users' , body : body ) User . new ( response . parsed ) end

Create a user from the options
 @param [Hash] options
 @option options [String] :email The new user's email address
 @option options [String] :password The new user's password
 @option options [String] :password_confirmation The new user's password confirmation string
 @return [G5AuthenticationClient::User]


def update_user(options={})
      user=User.new(options)
      user.validate!
      response=oauth_access_token.put("/v1/users/#{user.id}", body: user_hash(user.to_hash))
      User.new(response.parsed)
    end

def update_user ( options = { } ) user = User . new ( options ) user . validate! response = oauth_access_token . put ( "/v1/users/#{user.id}" , body : user_hash ( user . to_hash ) ) User . new ( response . parsed ) end

Update an existing user
 @param [Hash] options
 @option options [String] :email The new user's email address
 @option options [String] :password The new user's password
 @option options [String] :password_confirmation The new user's password confirmation string
 @return [G5AuthenticationClient::User]


def find_user_by_email(email)
      response = oauth_access_token.get('/v1/users', params: { email: email })
      user = response.parsed.first
      if user
        user=User.new(user)
      end
      user
    end

def find_user_by_email ( email ) response = oauth_access_token . get ( '/v1/users' , params : { email : email } ) user = response . parsed . first if user user = User . new ( user ) end user end

Find a user by email
 @param [String] email address
 @return [G5AuthenticationClient::User]


def sign_out_url(redirect_url=nil)
      auth_server_url = Addressable::URI.parse(endpoint)
      auth_server_url.path = '/users/sign_out'
      auth_server_url.query_values = {redirect_url: redirect_url} if redirect_url
      auth_server_url.to_s
    end

def sign_out_url ( redirect_url = nil ) auth_server_url = Addressable :: URI . parse ( endpoint ) auth_server_url . path = '/users/sign_out' auth_server_url . query_values = { redirect_url : redirect_url } if redirect_url auth_server_url . to_s end

Return the URL for signing out of the auth server.
 Clients should redirect to this URL to globally sign out.

 @param [String] redirect_url the URL that the auth server should redirect back to after sign out
 @return [String] the auth server endpoint for signing out

Return the URL for signing out of the auth server . Clients should redirect to this URL to globally sign out .


def list_users
      response=oauth_access_token.get("/v1/users")
      response.parsed.collect { |parsed_user| User.new(parsed_user) }
    end

def list_users response = oauth_access_token . get ( "/v1/users" ) response . parsed . collect { | parsed_user | User . new ( parsed_user ) } end

Return all users from the remote service
 @return [Array<G5AuthenticationClient::User>]


def list_roles
      response = oauth_access_token.get('/v1/roles')
      response.parsed.collect { |parsed_role| Role.new(parsed_role) }
    end

def list_roles response = oauth_access_token . get ( '/v1/roles' ) response . parsed . collect { | parsed_role | Role . new ( parsed_role ) } end

Return all user roles from the remote service
 @return [Array<G5AuthenticationClient::Role>]


def bookmark(*args)
      if args[0].is_a? Array
        Drop.create(:bookmarks, args)
      else
        url, name = args[0], (args[1] || "")
        Drop.create(:bookmark, {:name => name, :redirect_url => url})
      end
    end

def bookmark ( * args ) if args [ 0 ] . is_a? Array Drop . create ( :bookmarks , args ) else url , name = args [ 0 ] , ( args [ 1 ] || "" ) Drop . create ( :bookmark , { :name => name , :redirect_url => url } ) end end

Create one or more new bookmark drops.

 Requires authentication.

 @overload bookmark(url, name = "")
   @param [String] url url to bookmark
   @param [String] name name of bookmark
 @overload bookmark(opts)
   @param [Array] opts array of bookmark option parameters (containing +:name+ and +:redirect_url+)
 @return [CloudApp::Drop]


def rename(id, name = "")
      drop = Drop.find(id)
      drop.update(:name => name)
    end

def rename ( id , name = "" ) drop = Drop . find ( id ) drop . update ( :name => name ) end

Change the name of the drop.

 Finds the drop by it's slug id, for example "2wr4".

 Requires authentication.

 @param [String] id drop id
 @param [String] name new drop name
 @return [CloudApp::Drop]


def privacy(id, privacy = false)
      drop = Drop.find(id)
      drop.update(:private => privacy)
    end

def privacy ( id , privacy = false ) drop = Drop . find ( id ) drop . update ( :private => privacy ) end

Modify a drop with a private URL to have a public URL or vice versa.

 Finds the drop by it's slug id, for example "2wr4".

 Requires authentication.

 @param [String] id drop id
 @param [Boolean] privacy privacy setting
 @return [CloudApp::Drop]

Modify a drop with a private URL to have a public URL or vice versa .


def load(attributes = {})
      attributes.each do |key, val|
        if key =~ /^.*_at$/ and val
          # if this is a date/time key and it's not nil, try to parse it first
          # as DateTime, then as Date only
          begin
            dt = DateTime.strptime(val, "%Y-%m-%dT%H:%M:%SZ")
            newval = Time.utc(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec)
          rescue ArgumentError => ex
            newval = DateTime.strptime(val, "%Y-%m-%d")
          end
          self.instance_variable_set("@#{key}", newval)
        else
          self.instance_variable_set("@#{key}", val)
        end
      end
    end

def load ( attributes = { } ) attributes . each do | key , val | if key =~ / / and val begin dt = DateTime . strptime ( val , "%Y-%m-%dT%H:%M:%SZ" ) newval = Time . utc ( dt . year , dt . month , dt . day , dt . hour , dt . min , dt . sec ) rescue ArgumentError => ex newval = DateTime . strptime ( val , "%Y-%m-%d" ) end self . instance_variable_set ( "@#{key}" , newval ) else self . instance_variable_set ( "@#{key}" , val ) end end end

Sets the attributes for object.

 @param [Hash] attributes


def load_environment(env=RACK_ENV)
      # Load the default which can be overwritten or extended by specific
      # env config files.
      require File.join(root_path, 'config', 'environments', 'default.rb')
      env_file = File.join(root_path, "config", "environments", "#{env}.rb")
      if File.exist?(env_file)
        require env_file
      else
        debug_msg = "Environment file: #{env_file} couldn't be found, using only the default environment config instead." unless env == 'development'
      end
      # making sure we have a LOGGER constant defined.
      unless Object.const_defined?(:LOGGER)
        Object.const_set(:LOGGER, Logger.new($stdout))
      end
      LOGGER.debug(debug_msg) if debug_msg
    end

Loads an environment specific config if available, the config file is where the logger should be set
 if it was not, we are using stdout.

Loads an environment specific config if available the config file is where the logger should be set if it was not we are using stdout .


def load_apis
      Dir.glob(File.join(root_path, "api", "**", "*.rb")).each do |api|
        require api
      end
    end

def load_apis Dir . glob ( File . join ( root_path , "api" , "**" , "*.rb" ) ) . each do | api | require api end end

DSL routes are located in the api folder


def run
      status = Status.new(name)
      runner = (async ? AsyncRunner : SyncRunner).new do
        t = Time.now
        begin
          @check.call(status)
        rescue Exception => e
          status.fail("#{name} error: #{e.inspect}")
        end
        status.time = Time.now - t
      end
      runner.filter_status = status
      runner
    end

def
run
status
=
Status
.
new
(
name
)
runner
=
(
async
AsyncRunner
:
SyncRunner
)
.
new
do
t
=
Time
.
now
begin
@check
.
call
(
status
)
rescue
Exception
=>
e
status
.
fail
(
"#{name} error: #{e.inspect}"
)
end
status
.
time
=
Time
.
now
t
end
runner
.
filter_status
=
status
runner
end

Create a new filter to run a status check. The name is used for display purposes.
 Run a status the status check. This method keeps track of the time it took to run
 the check and will trap any unexpected exceptions and report them as failures.

Create a new filter to run a status check . The name is used for display purposes . Run a status the status check . This method keeps track of the time it took to run the check and will trap any unexpected exceptions and report them as failures .


def call(env)
      if @app.nil? || env[PATH_INFO] == @route_path
        statuses = []
        t = Time.now
        statuses = Filter.run_filters(@filters)
        render(statuses, Time.now - t)
      else
        @app.call(env)
      end
    end

def call ( env ) if @app . nil? || env [ PATH_INFO ] == @route_path statuses = [ ] t = Time . now statuses = Filter . run_filters ( @filters ) render ( statuses , Time . now - t ) else @app . call ( env ) end end

Create a new handler. This method can take a block which will yield itself so it can
 be configured.

 The handler can be set up in one of two ways. If no arguments are supplied, it will
 return a regular Rack handler that can be used with a rackup +run+ method or in a
 Rails 3+ routes.rb file. Otherwise, an application stack can be supplied in the first
 argument and a routing path in the second (defaults to <tt>/is_it_working</tt>) so
 it can be used with the rackup +use+ method or in Rails.middleware.

Create a new handler . This method can take a block which will yield itself so it can be configured .


def check (name, *options_or_check, &block)
      raise ArgumentError("Too many arguments to #{self.class.name}#check") if options_or_check.size > 2
      check = nil
      options = {:async => true}

      unless options_or_check.empty?
        if options_or_check[0].is_a?(Hash)
          options = options.merge(options_or_check[0])
        else
          check = options_or_check[0]
        end
        if options_or_check[1].is_a?(Hash)
          options = options.merge(options_or_check[1])
        end
      end

      unless check
        if block
          check = block
        else
          check = lookup_check(name, options)
        end
      end

      @filters << Filter.new(name, check, options[:async])
    end

Add a status check to the handler.

 If a block is given, it will be used as the status check and will be yielded to
 with a Status object.

 If the name matches one of the pre-defined status check classes, a new instance will
 be created using the rest of the arguments as the arguments to the initializer. The
 pre-defined classes are:

 * <tt>:action_mailer</tt> - Check if the send mail configuration used by ActionMailer is available
 * <tt>:active_record</tt> - Check if the database connection for an ActiveRecord class is up
 * <tt>:dalli</tt> - DalliCheck checks if all the servers in a MemCache cluster are available using dalli
 * <tt>:directory</tt> - DirectoryCheck checks for the accessibilty of a file system directory
 * <tt>:ping</tt> - Check if a host is reachable and accepting connections on a port
 * <tt>:url</tt> - Check if a getting a URL returns a success response


def lookup_check(name, options) #:nodoc:
        check_class_name = "#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check"
        check = nil
        if IsItWorking.const_defined?(check_class_name)
          check_class = IsItWorking.const_get(check_class_name)
          check = check_class.new(options)
        else
          raise ArgumentError.new("Check not defined #{check_class_name}")
        end
        check
      end

Lookup a status check filter from the name and arguments


def render(statuses, elapsed_time) #:nodoc:
        fail = statuses.all?{|s| s.success?}
        headers = {
          "Content-Type" => "text/plain; charset=utf8",
          "Cache-Control" => "no-cache",
          "Date" => Time.now.httpdate,
        }

        messages = []
        statuses.each do |status|
          status.messages.each do |m|
            messages << "#{m.ok? ? 'OK:  ' : 'FAIL:'} #{status.name} - #{m.message} (#{status.time ? sprintf('%0.000f', status.time * 1000) : '?'}ms)"
          end
        end

        info = []
        info << "Host: #{@hostname}" unless @hostname.size == 0
        info << "PID:  #{$$}"
        info << "Timestamp: #{Time.now.iso8601}"
        info << "Elapsed Time: #{(elapsed_time * 1000).round}ms"

        code = (fail ? 200 : 500)

        [code, headers, [info.join("\n"), "\n\n", messages.join("\n")]]
      end

Output the plain text response from calling all the filters.

Output the plain text response from calling all the filters .


def call(status)
      begin
        ping(@host, @port)
        status.ok("#{@alias} is accepting connections on port #{@port.inspect}")
      rescue Errno::ECONNREFUSED
        status.fail("#{@alias} is not accepting connections on port #{@port.inspect}")
      rescue SocketError => e
        status.fail("connection to #{@alias} on port #{@port.inspect} failed with '#{e.message}'")
      rescue Timeout::Error
        status.fail("#{@alias} did not respond on port #{@port.inspect} within #{@timeout} seconds")
      end
    end

Check if a host is reachable and accepting connections on a specified port.

 The host and port to ping are specified with the <tt>:host</tt> and <tt>:port</tt> options. The port
 can be either a port number or port name for a well known port (i.e. "smtp" and 25 are
 equivalent). The default timeout to wait for a response is 2 seconds. This can be
 changed with the <tt>:timeout</tt> option.

 By default, the host name will be included in the output. If this could pose a security
 risk by making the existence of the host known to the world, you can supply the <tt>:alias</tt>
 option which will be used for output purposes. In general, you should supply this option
 unless the host is on a private network behind a firewall.

 === Example

   IsItWorking::Handler.new do |h|
     h.check :ping, :host => "example.com", :port => "ftp", :timeout => 4
   end

Check if a host is reachable and accepting connections on a specified port .


def respond_to? method, include_private = false
      true if bootstrap_admin_config.respond_to? method
      super method, include_private
    end

def respond_to? method , include_private = false true if bootstrap_admin_config . respond_to? method super method , include_private end

self responds_to bootstrap_admin_config methods via method_missing!


def instantiate_http #:nodoc:
        http_class = nil

        if @proxy && @proxy[:host]
          http_class = Net::HTTP::Proxy(@proxy[:host], @proxy[:port], @proxy[:username], @proxy[:password])
        else
          http_class = Net::HTTP
        end

        http = http_class.new(@uri.host, @uri.port)
        if @uri.scheme == 'https'
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_PEER
        end
        http.open_timeout = @open_timeout
        http.read_timeout = @read_timeout

        return http
      end

def instantiate_http http_class = nil if @proxy && @proxy [ :host ] http_class = Net :: HTTP :: Proxy ( @proxy [ :host ] , @proxy [ :port ] , @proxy [ :username ] , @proxy [ :password ] ) else http_class = Net :: HTTP end http = http_class . new ( @uri . host , @uri . port ) if @uri . scheme == 'https' http . use_ssl = true http . verify_mode = OpenSSL :: SSL :: VERIFY_PEER end http . open_timeout = @open_timeout http . read_timeout = @read_timeout return http end

Create an HTTP object with the options set.

Create an HTTP object with the options set .


def perform_http_request #:nodoc:
        request = Net::HTTP::Get.new(@uri.request_uri, @headers)
        request.basic_auth(@username, @password) if @username || @password
        http = instantiate_http
        http.start do
          http.request(request)
        end
      end

def perform_http_request request = Net :: HTTP :: Get . new ( @uri . request_uri , @headers ) request . basic_auth ( @username , @password ) if @username || @password http = instantiate_http http . start do http . request ( request ) end end

Perform an HTTP request and return the response


def usb_open(vendor, product)
      raise ArgumentError.new('vendor should be Fixnum')  unless vendor.kind_of?(Fixnum)
      raise ArgumentError.new('product should be Fixnum')  unless product.kind_of?(Fixnum)
      check_result(Ftdi.ftdi_usb_open(ctx, vendor, product))
    end

def
usb_open
(
vendor
,
product
)
raise
ArgumentError
.
new
(
'vendor should be Fixnum'
)
unless
vendor
.
kind_of?
(
Fixnum
)
raise
ArgumentError
.
new
(
'product should be Fixnum'
)
unless
product
.
kind_of?
(
Fixnum
)
check_result
(
Ftdi
.
ftdi_usb_open
(
ctx
,
vendor
,
product
)
)
end

Opens the first device with a given vendor and product ids.
 @param [Fixnum] vendor Vendor id.
 @param [Fixnum] product Product id.
 @return [NilClass] nil
 @raise [StatusCodeError] libftdi reports error.
 @raise [ArgumentError] Bad arguments.

Opens the first device with a given vendor and product ids .


def usb_open_desc(vendor, product, description, serial)
      raise ArgumentError.new('vendor should be Fixnum')  unless vendor.kind_of?(Fixnum)
      raise ArgumentError.new('product should be Fixnum')  unless product.kind_of?(Fixnum)
      check_result(Ftdi.ftdi_usb_open_desc(ctx, vendor, product, description, serial))
    end

def
usb_open_desc
(
vendor
,
product
,
description
,
serial
)
raise
ArgumentError
.
new
(
'vendor should be Fixnum'
)
unless
vendor
.
kind_of?
(
Fixnum
)
raise
ArgumentError
.
new
(
'product should be Fixnum'
)
unless
product
.
kind_of?
(
Fixnum
)
check_result
(
Ftdi
.
ftdi_usb_open_desc
(
ctx
,
vendor
,
product
,
description
,
serial
)
)
end

Opens the first device with a given vendor and product ids, description and serial.
 @param [Fixnum] vendor Vendor id.
 @param [Fixnum] product Product id.
 @param [String] description Description to search for. Use nil if not needed.
 @param [String] serial Serial to search for. Use nil if not needed.
 @return [NilClass] nil
 @raise [StatusCodeError] libftdi reports error.
 @raise [ArgumentError] Bad arguments.

Opens the first device with a given vendor and product ids description and serial .


def usb_open_desc_index(vendor, product, description, serial, index)
      raise ArgumentError.new('vendor should be Fixnum')  unless vendor.kind_of?(Fixnum)
      raise ArgumentError.new('product should be Fixnum')  unless product.kind_of?(Fixnum)
      raise ArgumentError.new('index should be Fixnum')  unless index.kind_of?(Fixnum)
      raise ArgumentError.new('index should be greater than or equal to zero')  if index < 0
      check_result(Ftdi.ftdi_usb_open_desc_index(ctx, vendor, product, description, serial, index))
    end

Opens the index-th device with a given vendor and product ids, description and serial.
 @param [Fixnum] vendor Vendor id.
 @param [Fixnum] product Product id.
 @param [String] description Description to search for. Use nil if not needed.
 @param [String] serial Serial to search for. Use nil if not needed.
 @param [Fixnum] index Number of matching device to open if there are more than one, starts with 0.
 @return [NilClass] nil
 @raise [StatusCodeError] libftdi reports error.
 @raise [ArgumentError] Bad arguments.

Opens the index - th device with a given vendor and product ids description and serial .


def baudrate=(new_baudrate)
      raise ArgumentError.new('baudrate should be Fixnum')  unless new_baudrate.kind_of?(Fixnum)
      check_result(Ftdi.ftdi_set_baudrate(ctx, new_baudrate))
    end

def
baudrate
=
(
new_baudrate
)
raise
ArgumentError
.
new
(
'baudrate should be Fixnum'
)
unless
new_baudrate
.
kind_of?
(
Fixnum
)
check_result
(
Ftdi
.
ftdi_set_baudrate
(
ctx
,
new_baudrate
)
)
end

Sets the chip baud rate.
 @raise [StatusCodeError] libftdi reports error.
 @raise [ArgumentError] Bad arguments.
 @return [NilClass] nil


def write_data_chunksize
      p = FFI::MemoryPointer.new(:uint, 1)
      check_result(Ftdi.ftdi_write_data_get_chunksize(ctx, p))
      p.read_uint
    end

def write_data_chunksize p = FFI :: MemoryPointer . new ( :uint , 1 ) check_result ( Ftdi . ftdi_write_data_get_chunksize ( ctx , p ) ) p . read_uint end

Gets write buffer chunk size.
 @return [Fixnum] Write buffer chunk size.
 @raise [StatusCodeError] libftdi reports error.
 @see #write_data_chunksize=


def write_data(bytes)
      bytes = bytes.pack('c*')  if bytes.respond_to?(:pack)
      size = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.size
      mem_buf = FFI::MemoryPointer.new(:char, size)
      mem_buf.put_bytes(0, bytes)
      bytes_written = Ftdi.ftdi_write_data(ctx, mem_buf, size)
      check_result(bytes_written)
      bytes_written
    end

def write_data ( bytes ) bytes = bytes . pack ( 'c*' ) if bytes . respond_to? ( :pack ) size = bytes . respond_to? ( :bytesize ) ? bytes . bytesize : bytes . size mem_buf = FFI :: MemoryPointer . new ( :char , size ) mem_buf . put_bytes ( 0 , bytes ) bytes_written = Ftdi . ftdi_write_data ( ctx , mem_buf , size ) check_result ( bytes_written ) bytes_written end

Writes data.
 @param [String, Array] bytes String or array of integers that will be interpreted as bytes using pack('c*').
 @return [Fixnum] Number of written bytes.
 @raise [StatusCodeError] libftdi reports error.


def read_data_chunksize
      p = FFI::MemoryPointer.new(:uint, 1)
      check_result(Ftdi.ftdi_read_data_get_chunksize(ctx, p))
      p.read_uint
    end

def read_data_chunksize p = FFI :: MemoryPointer . new ( :uint , 1 ) check_result ( Ftdi . ftdi_read_data_get_chunksize ( ctx , p ) ) p . read_uint end

Gets read buffer chunk size.
 @return [Fixnum] Read buffer chunk size.
 @raise [StatusCodeError] libftdi reports error.
 @see #read_data_chunksize=


def read_data
      chunksize = read_data_chunksize
      p = FFI::MemoryPointer.new(:char, chunksize)
      bytes_read = Ftdi.ftdi_read_data(ctx, p, chunksize)
      check_result(bytes_read)
      r = p.read_bytes(bytes_read)
      r.force_encoding("ASCII-8BIT")  if r.respond_to?(:force_encoding)
      r
    end

def read_data chunksize = read_data_chunksize p = FFI :: MemoryPointer . new ( :char , chunksize ) bytes_read = Ftdi . ftdi_read_data ( ctx , p , chunksize ) check_result ( bytes_read ) r = p . read_bytes ( bytes_read ) r . force_encoding ( "ASCII-8BIT" ) if r . respond_to? ( :force_encoding ) r end

Reads data in chunks from the chip.
 Returns when at least one byte is available or when the latency timer has elapsed.
 Automatically strips the two modem status bytes transfered during every read.
 @return [String] Bytes read; Empty string if no bytes read.
 @see #read_data_chunksize
 @raise [StatusCodeError] libftdi reports error.

Reads data in chunks from the chip . Returns when at least one byte is available or when the latency timer has elapsed . Automatically strips the two modem status bytes transfered during every read .


def read_pins
      p = FFI::MemoryPointer.new(:uchar, 1)
      check_result(Ftdi.ftdi_read_pins(ctx, p))
      p.read_uchar
    end

def read_pins p = FFI :: MemoryPointer . new ( :uchar , 1 ) check_result ( Ftdi . ftdi_read_pins ( ctx , p ) ) p . read_uchar end

Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
 @return [Fixnum] Pins state
 @raise [StatusCodeError] libftdi reports error.
 @see #set_bitmode

Directly read pin state circumventing the read buffer . Useful for bitbang mode .


def to_g_marker_api2(marker_options = {}, options = {})
      klass = if options[:short_class]
        'GMarker'
      else
        'google.maps.Marker'
      end

      opts = Geos::Helper.camelize_keys(marker_options)

      "new #{klass}(#{self.centroid.to_g_lat_lng(options)}, #{opts.to_json})"
    end

Returns a new GMarker at the centroid of the geometry. The options
 Hash works the same as the Google Maps API GMarkerOptions class does,
 but allows for underscored Ruby-like options which are then converted
 to the appropriate camel-cased Javascript options.

Returns a new GMarker at the centroid of the geometry . The options Hash works the same as the Google Maps API GMarkerOptions class does but allows for underscored Ruby - like options which are then converted to the appropriate camel - cased Javascript options .


def to_g_polyline_api2(polyline_options = {}, options = {})
      klass = if options[:short_class]
        'GPolyline'
      else
        'google.maps.Polyline'
      end

      poly_opts = if polyline_options[:polyline_options]
        Geos::Helper.camelize_keys(polyline_options[:polyline_options])
      end

      args = [
        (polyline_options[:color] ? "'#{Geos::Helper.escape_javascript(polyline_options[:color])}'" : 'null'),
        (polyline_options[:weight] || 'null'),
        (polyline_options[:opacity] || 'null'),
        (poly_opts ? poly_opts.to_json : 'null')
      ].join(', ')

      "new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})"
    end

Returns a new GPolyline. Note that this GPolyline just uses whatever
 coordinates are found in the sequence in order, so it might not
 make much sense at all.

 The options Hash follows the Google Maps API arguments to the
 GPolyline constructor and include :color, :weight, :opacity and
 :options. 'null' is used in place of any unset options.

Returns a new GPolyline . Note that this GPolyline just uses whatever coordinates are found in the sequence in order so it might not make much sense at all .


def to_g_polygon_api2(polygon_options = {}, options = {})
      klass = if options[:short_class]
        'GPolygon'
      else
        'google.maps.Polygon'
      end

      poly_opts = if polygon_options[:polygon_options]
        Geos::Helper.camelize_keys(polygon_options[:polygon_options])
      end

      args = [
        (polygon_options[:stroke_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:stroke_color])}'" : 'null'),
        (polygon_options[:stroke_weight] || 'null'),
        (polygon_options[:stroke_opacity] || 'null'),
        (polygon_options[:fill_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:fill_color])}'" : 'null'),
        (polygon_options[:fill_opacity] || 'null'),
        (poly_opts ? poly_opts.to_json : 'null')
      ].join(', ')
      "new #{klass}([#{self.to_g_lat_lng_api2(options).join(', ')}], #{args})"
    end

Returns a new GPolygon. Note that this GPolygon just uses whatever
 coordinates are found in the sequence in order, so it might not
 make much sense at all.

 The options Hash follows the Google Maps API arguments to the
 GPolygon constructor and include :stroke_color, :stroke_weight,
 :stroke_opacity, :fill_color, :fill_opacity and :options. 'null' is
 used in place of any unset options.

Returns a new GPolygon . Note that this GPolygon just uses whatever coordinates are found in the sequence in order so it might not make much sense at all .


def to_bbox(long_or_short_names = :long)
      case long_or_short_names
        when :long
          {
            :north => self.north,
            :east => self.east,
            :south => self.south,
            :west => self.west
          }
        when :short
          {
            :n => self.north,
            :e => self.east,
            :s => self.south,
            :w => self.west
          }
        else
          raise ArgumentError.new("Expected either :long or :short for long_or_short_names argument")
      end
    end

Spits out a Hash containing the cardinal points that describe the
 Geometry's bbox.

Spits out a Hash containing the cardinal points that describe the Geometry s bbox .


def to_georss(*args)
      xml = Geos::Helper.xml_options(*args)[0]
      xml.georss(:where) do
        xml.gml(:Point) do
          xml.gml(:pos, "#{self.lat} #{self.lng}")
        end
      end
    end

def
to_georss
(
*
args
)
xml
=
Geos
::
Helper
.
xml_options
(
*
args
)
[
0
]
xml
.
georss
(
:where
)
do
xml
.
gml
(
:Point
)
do
xml
.
gml
(
:pos
,
"#{self.lat} #{self.lng}"
)
end
end
end

Build some XmlMarkup for GeoRSS. You should include the
 appropriate georss and gml XML namespaces in your document.

Build some XmlMarkup for GeoRSS . You should include the appropriate georss and gml XML namespaces in your document .


def to_g_marker_api3(marker_options = {}, options = {})
      options = {
        :escape => [],
        :lat_lng_options => {}
      }.merge(options)

      opts = Geos::Helper.camelize_keys(marker_options)
      opts[:position] = self.centroid.to_g_lat_lng(options[:lat_lng_options])
      json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_MARKER_OPTIONS - options[:escape])

      "new google.maps.Marker(#{json})"
    end

def
to_g_marker_api3
(
marker_options
=
{
}
,
options
=
{
}
)
options
=
{
:escape
=>
[
]
,
:lat_lng_options
=>
{
}
}
.
merge
(
options
)
opts
=
Geos
::
Helper
.
camelize_keys
(
marker_options
)
opts
[
:position
]
=
self
.
centroid
.
to_g_lat_lng
(
options
[
:lat_lng_options
]
)
json
=
Geos
::
Helper
.
escape_json
(
opts
,
Geos
::
GoogleMaps
::
Api3Constants
::
UNESCAPED_MARKER_OPTIONS
options
[
:escape
]
)
"new google.maps.Marker(#{json})"
end

Returns a new Marker at the centroid of the geometry. The options
 Hash works the same as the Google Maps API MarkerOptions class does,
 but allows for underscored Ruby-like options which are then converted
 to the appropriate camel-cased Javascript options.

Returns a new Marker at the centroid of the geometry . The options Hash works the same as the Google Maps API MarkerOptions class does but allows for underscored Ruby - like options which are then converted to the appropriate camel - cased Javascript options .


def to_g_polyline_api3(polyline_options = {}, options = {})
      options = {
        :escape => [],
        :lat_lng_options => {}
      }.merge(options)

      opts = Geos::Helper.camelize_keys(polyline_options)
      opts[:path] = "[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]"
      json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape])

      "new google.maps.Polyline(#{json})"
    end

Returns a new Polyline. Note that this Polyline just uses whatever
 coordinates are found in the sequence in order, so it might not
 make much sense at all.

 The polyline_options Hash follows the Google Maps API arguments to the
 Polyline constructor and include :clickable, :geodesic, :map, etc. See
 the Google Maps API documentation for details.

 The options Hash allows you to specify if certain arguments should be
 escaped on output. Usually the options in UNESCAPED_POLY_OPTIONS are
 escaped, but if for some reason you want some other options to be
 escaped, pass them along in options[:escape]. The options Hash also
 passes along options to to_g_lat_lng_api3.

Returns a new Polyline . Note that this Polyline just uses whatever coordinates are found in the sequence in order so it might not make much sense at all .


def to_georss(*args)
      xml = Geos::Helper.xml_options(*args)[0]

      xml.georss(:where) do
        xml.gml(:LineString) do
          xml.gml(:posList) do
            xml << self.to_a.collect do |p|
              "#{p[1]} #{p[0]}"
            end.join(' ')
          end
        end
      end
    end

def
to_georss
(
*
args
)
xml
=
Geos
::
Helper
.
xml_options
(
*
args
)
[
0
]
xml
.
georss
(
:where
)
do
xml
.
gml
(
:LineString
)
do
xml
.
gml
(
:posList
)
do
xml
<<
self
.
to_a
.
collect
do
|
p
|
"#{p[1]} #{p[0]}"
end
.
join
(
' '
)
end
end
end
end

Build some XmlMarkup for GeoRSS GML. You should include the
 appropriate georss and gml XML namespaces in your document.

Build some XmlMarkup for GeoRSS GML . You should include the appropriate georss and gml XML namespaces in your document .


def convert_to_price(price_str)
      raise SolidusImportProducts::Exception::InvalidPrice unless price_str
      punt = price_str.index('.')
      coma = price_str.index(',')
      if !coma.nil? && !punt.nil?
        price_str.gsub!(punt < coma ? '.' : ',', '')
      end
      price_str.tr(',', '.').to_f
    end

def convert_to_price ( price_str ) raise SolidusImportProducts :: Exception :: InvalidPrice unless price_str punt = price_str . index ( '.' ) coma = price_str . index ( ',' ) if ! coma . nil? && ! punt . nil? price_str . gsub! ( punt < coma ? '.' : ',' , '' ) end price_str . tr ( ',' , '.' ) . to_f end

Special process of prices because of locales and different decimal separator characters.
 We want to get a format with dot as decimal separator and without thousand separator

Special process of prices because of locales and different decimal separator characters . We want to get a format with dot as decimal separator and without thousand separator


def matches(regexp, word)
      if regexp.respond_to?(:match?)
        regexp.match?(word)
      else
        regexp.match(word)
      end
    end

def matches ( regexp , word ) if regexp . respond_to? ( :match? ) regexp . match? ( word ) else regexp . match ( word ) end end

`match?` was added in Ruby 2.4 this allows us to be backwards
 compatible with older Ruby versions

match? was added in Ruby 2 . 4 this allows us to be backwards compatible with older Ruby versions


def dump_points(cur_path = [])
      points = [ self.exterior_ring.dump_points ]

      self.interior_rings.each do |ring|
        points.push(ring.dump_points)
      end

      cur_path.concat(points)
    end

def dump_points ( cur_path = [ ] ) points = [ self . exterior_ring . dump_points ] self . interior_rings . each do | ring | points . push ( ring . dump_points ) end cur_path . concat ( points ) end

Dumps points similarly to the PostGIS `ST_DumpPoints` function.

Dumps points similarly to the PostGIS ST_DumpPoints function .


def generate_belongs_to_foreign_key_name(assoc)
      source = assoc.source_table[0..7]
      column = assoc.foreign_key_column[0..7]
      destination = assoc.destination_table[0..7]
      "fk_#{source}_#{column}_#{destination}_#{SecureRandom.hex}"
    end


def raw_exchange_rates
      req = Net::HTTP::Post.new(@uri, 'Content-Type' => 'application/json')
      req.body = { lang: :en }.to_json
      response = Net::HTTP.start(@uri.hostname, @uri.port) do |http|
        http.request(req)
      end
      fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess
      response = JSON.parse(response.body)

      # CIB provide 6 currencies only
      unless response['d'] && response['d'].size >= 6
        fail ResponseError, "Unknown JSON #{response}"
      end

      response
    rescue JSON::ParserError
      raise ResponseError, "Unknown JSON: #{response.body}"
    end

def
raw_exchange_rates
req
=
Net
::
HTTP
::
Post
.
new
(
@uri
,
'Content-Type'
=>
'application/json'
)
req
.
body
=
{
lang
:
:en
}
.
to_json
response
=
Net
::
HTTP
.
start
(
@uri
.
hostname
,
@uri
.
port
)
do
|
http
|
http
.
request
(
req
)
end
fail
ResponseError
,
response
.
code
unless
response
.
is_a?
Net
::
HTTPSuccess
response
=
JSON
.
parse
(
response
.
body
)
unless
response
[
'd'
]
&&
response
[
'd'
]
.
size
>=
6
fail
ResponseError
,
"Unknown JSON #{response}"
end
response
rescue
JSON
::
ParserError
raise
ResponseError
,
"Unknown JSON: #{response.body}"
end

Send the request to URL and return the JSON response
 @return [Hash] JSON response of the exchange rates
   {
     "d"=> [
       {
         "__type"=>"LINKDev.CIB.CurrenciesFunds.CIBFund.CurrencyObject",
         "CurrencyID"=>"USD",
         "BuyRate"=>15.9,
         "SellRate"=>16.05
       }, {
         "__type"=>"LINKDev.CIB.CurrenciesFunds.CIBFund.CurrencyObject",
         "CurrencyID"=>"EUR",
         "BuyRate"=>17.1904,
         "SellRate"=>17.5234
       }, {
         ...
       }
     ]
   }


def validate_ipv4_addr(value)
      ipaddr = IPAddr.new(value)
      unless ipaddr.ipv4?
        raise ValidationError, "IP address '#{value}' is not IPv4"
      end
      ipaddr
    rescue ArgumentError => e
      raise ValidationError, "invalid IPv4 address '#{value}' - #{e.message}"
    end

Validate IPV4 using the standard "ipaddr" ruby module.

Validate IPV4 using the standard ipaddr ruby module .


def validate_ipv6_addr(value)
      ipaddr = IPAddr.new(value)
      unless ipaddr.ipv6?
        raise ValidationError, "IP address '#{value}' is not IPv6"
      end
      ipaddr
    rescue ArgumentError => e
      raise ValidationError, "invalid IPv6 address '#{value}' - #{e.message}"
    end

Validate that the given string _value_ describes a well-formed
 IPV6 network address using the standard "ipaddr" ruby module.

Validate that the given string _value_ describes a well - formed IPV6 network address using the standard ipaddr ruby module .


def to_h(strict: false)
      todo = @key_metadata.keys - @cache.keys
      todo.each_with_object({}) do |key, hsh|
        loaded_key = (strict ? load_key_strict(key) : load_key_lenient(key))
        hsh[key] = loaded_key if exists_locally?(key)
      end
    end

def to_h ( strict : false ) todo = @key_metadata . keys - @cache . keys todo . each_with_object ( { } ) do | key , hsh | loaded_key = ( strict ? load_key_strict ( key ) : load_key_lenient ( key ) ) hsh [ key ] = loaded_key if exists_locally? ( key ) end end

Create an internal model with a reference to a public model.
 @param key_metadata [KeyMetadataStore] a reference to a metadata store
 @param parent [LazyLazer] a reference to a LazyLazer model
 Converts all unconverted keys and packages them as a hash.
 @return [Hash] the converted hash

Create an internal model with a reference to a public model .


def exists_locally?(key_name)
      return true if @cache.key?(key_name) || @writethrough.key?(key_name)
      meta = ensure_metadata_exists(key_name)
      @source.key?(meta.source_key)
    end

def exists_locally? ( key_name ) return true if @cache . key? ( key_name ) || @writethrough . key? ( key_name ) meta = ensure_metadata_exists ( key_name ) @source . key? ( meta . source_key ) end

Whether the key doesn't need to be lazily loaded.
 @param key_name [Symbol] the key to check
 @return [Boolean] whether the key exists locally.

Whether the key doesn t need to be lazily loaded .


def write_attribute(key_name, new_value)
      meta = ensure_metadata_exists(key_name)
      @source.delete(meta.source_key)
      @writethrough[key_name] = @cache[key_name] = new_value
    end

Update an attribute.
 @param key_name [Symbol] the attribute to update
 @param new_value [Object] the new value
 @return [Object] the written value


def delete_attribute(key_name)
      key_name_sym = key_name.to_sym
      meta = ensure_metadata_exists(key_name_sym)
      @cache.delete(key_name)
      @writethrough.delete(key_name)
      @source.delete(meta.source_key)
      nil
    end

Delete an attribute
 @param key_name [Symbol] the name of the key
 @return [void]


def verify_required!
      @key_metadata.required_properties.each do |key_name|
        next if @source.key?(@key_metadata.get(key_name).source_key)
        raise RequiredAttribute, "#{@parent} requires `#{key_name}`"
      end
    end

def
verify_required!
@key_metadata
.
required_properties
.
each
do
|
key_name
|
next
if
@source
.
key?
(
@key_metadata
.
get
(
key_name
)
.
source_key
)
raise
RequiredAttribute
,
"#{@parent} requires `#{key_name}`"
end
end

Verify that all the keys marked as required are present.
 @api private
 @raise RequiredAttribute if a required attribute is missing
 @return [void]

Verify that all the keys marked as required are present .


def transform_value(value, transform)
      case transform
      when nil
        value
      when Proc
        @parent.instance_exec(value, &transform)
      when Symbol
        value.public_send(transform)
      end
    end

def transform_value ( value , transform ) case transform when nil value when Proc @parent . instance_exec ( value , & transform ) when Symbol value . public_send ( transform ) end end

Apply a transformation to a value.
 @param value [Object] a value
 @param transform [nil, Proc, Symbol] a transform type
 @return [Object] the transformed value


def response
      response = Net::HTTP.get_response(@uri)
      if response.is_a? Net::HTTPRedirection
        response = Net::HTTP.get_response(URI.parse(response['location']))
      end
      fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess
      response
    end

def response response = Net :: HTTP . get_response ( @uri ) if response . is_a? Net :: HTTPRedirection response = Net :: HTTP . get_response ( URI . parse ( response [ 'location' ] ) ) end fail ResponseError , response . code unless response . is_a? Net :: HTTPSuccess response end

Make a call to the @uri to get the raw_response
 @return [Net::HTTPSuccess] of the raw response
 @raises [ResponseError] if response is not 200 OK


def currencies(table_rows)
      table_rows.lazy.map do |e|
        e.css('img').map { |img| img.attribute('src').value }
      end.force.flatten
    end

def currencies ( table_rows ) table_rows . lazy . map do | e | e . css ( 'img' ) . map { | img | img . attribute ( 'src' ) . value } end . force . flatten end

Extract the currencies from the image components src attribute
 @return [Array<String>] containing the URL to image of the currency


def add(key, meta)
      @collection[key] = meta
      if meta.required?
        @required_properties << key
      else
        @required_properties.delete(key)
      end
      meta
    end

def add ( key , meta ) @collection [ key ] = meta if meta . required? @required_properties << key else @required_properties . delete ( key ) end meta end

Add a KeyMetadata to the store.
 @param key [Symbol] the key
 @param meta [KeyMetadata] the key metadata
 @return [KeyMetadata] the provided meta


def validate_constraints(value)
      options.each do |option, arg|
        if validator_class = Respect.validator_for(option)
          validator_class.new(arg).validate(value)
        end
      end
    end

def validate_constraints ( value ) options . each do | option , arg | if validator_class = Respect . validator_for ( option ) validator_class . new ( arg ) . validate ( value ) end end end

Validate all the constraints listed in +options+ to the
 given +value+.

Validate all the constraints listed in + options + to the given + value + .


def validate(object)
      sanitized_object = validate_type(object)
      validate_constraints(sanitized_object) unless sanitized_object.nil? && allow_nil?
      self.sanitized_object = sanitized_object
      true
    rescue ValidationError => e
      # Reset sanitized object.
      self.sanitized_object = nil
      raise e
    end

def validate ( object ) sanitized_object = validate_type ( object ) validate_constraints ( sanitized_object ) unless sanitized_object . nil? && allow_nil? self . sanitized_object = sanitized_object true rescue ValidationError => e self . sanitized_object = nil raise e end

Call +validate_type+ with the given +object+, apply the constraints
 and assign the sanitized object.

Call + validate_type + with the given + object + apply the constraints and assign the sanitized object .


def []=(name, schema)
      case name
      when Symbol, String, Regexp
        if @properties.has_key?(name)
          raise InvalidSchemaError, "property '#{name}' already defined"
        end
        @properties[name] = schema
      else
        raise InvalidSchemaError, "unsupported property name type #{name}:#{name.class}"
      end
    end

Set the given +schema+ for the given property +name+. A name can be
 a Symbol, a String or a Regexp.

Set the given + schema + for the given property + name + . A name can be a Symbol a String or a Regexp .


def []=(key, value)
      case value
      when String
        string(key, equal_to: value.to_s)
      else
        any(key, equal_to: value.to_s)
      end
    end

def []= ( key , value ) case value when String string ( key , equal_to : value . to_s ) else any ( key , equal_to : value . to_s ) end end

Shortcut to say a schema +key+ must be equal to a given +value+. When it
 does not recognize the value type it creates a "any" schema.

 Example:
   HashSchema.define do |s|
     s["a_string"] = "value"       # equivalent to: s.string("a_string", equal_to: "value")
     s["a_key"] = 0..5             # equivalent to: s.any("a_key", equal_to: "0..5")
   end

Shortcut to say a schema + key + must be equal to a given + value + . When it does not recognize the value type it creates a any schema .


def holiday?(arg)
      date = to_date(arg)
      holidays(start_date: date, end_date: date + 1.day, limit: 1).length > 0
    end

def holiday? ( arg ) date = to_date ( arg ) holidays ( start_date : date , end_date : date + 1 . day , limit : 1 ) . length > 0 end

whether arg is holiday
 @param arg [#to_date, String] {Date}, {Time}, or date like String (ex. "YYYY-MM-DD")


def arrayize_arguments(args)
      # Go through trailing arguments and suck them in if they don't seem
      # to have an owner.
      array = []
      until args.empty? || args.first.match(/^-/)
        array << args.shift
      end
      array
    end

def arrayize_arguments ( args ) array = [ ] until args . empty? || args . first . match ( / / ) array << args . shift end array end

Turns trailing command line arguments into an array for an arrayed value


def to_a
      [
        required,
        short,
        long,
        desc,
        default,
        filter,
        action,
        cast,
        valid,
        validate
      ].compact
    end

def to_a [ required , short , long , desc , default , filter , action , cast , valid , validate ] . compact end


def to_h
      {
        "required" => required,
        "short" => short,
        "long" => long,
        "desc" => desc,
        "default" => default,
        "filter" => filter,
        "action" => action,
        "cast" => cast,
        "valid" => valid,
        "validate" => validate
      }.reject {|k, v| v.nil? }
    end

def to_h { "required" => required , "short" => short , "long" => long , "desc" => desc , "default" => default , "filter" => filter , "action" => action , "cast" => cast , "valid" => valid , "validate" => validate } . reject { | k , v | v . nil? } end


def parse_options(argv = ARGV)
      @config_file = File.join(Dir.getwd, 'config', "#{@name}.json")

      OptionParser.new do |opts|
        note = 'Define environment'
        opts.on('-e', '--environment ENVIRONMENT', note) do |environment|
          @environment = environment
        end

        opts.on('-d', '--detached', 'Run processor detached as a daemon') do
          @detached = true
        end

        note = 'Define configuration file'
        opts.on('-c', '--config CONFIG', note) do |config|
          @config_file = config
        end
      end.parse!(argv)

      true
    rescue OptionParser::InvalidOption => e
      EventHub.logger.warn("Argument Parsing: #{e}")
      false
    rescue OptionParser::MissingArgument => e
      EventHub.logger.warn("Argument Parsing: #{e}")
      false
    end

def
parse_options
(
argv
=
ARGV
)
@config_file
=
File
.
join
(
Dir
.
getwd
,
'config'
,
"#{@name}.json"
)
OptionParser
.
new
do
|
opts
|
note
=
'Define environment'
opts
.
on
(
'-e'
,
'--environment ENVIRONMENT'
,
note
)
do
|
environment
|
@environment
=
environment
end
opts
.
on
(
'-d'
,
'--detached'
,
'Run processor detached as a daemon'
)
do
@detached
=
true
end
note
=
'Define configuration file'
opts
.
on
(
'-c'
,
'--config CONFIG'
,
note
)
do
|
config
|
@config_file
=
config
end
end
.
parse!
(
argv
)
true
rescue
OptionParser
::
InvalidOption
=>
e
EventHub
.
logger
.
warn
(
"Argument Parsing: #{e}"
)
false
rescue
OptionParser
::
MissingArgument
=>
e
EventHub
.
logger
.
warn
(
"Argument Parsing: #{e}"
)
false
end


def load!(args = {})
      # for better rspec testing
      @config_file = args[:config_file] if args[:config_file]
      @environment = args[:environment] if args[:environment]

      new_data = {}
      begin
        new_data = JSON.parse(File.read(@config_file), symbolize_names: true)
      rescue => e
        EventHub.logger.warn("Exception while loading configuration file: #{e}")
        EventHub.logger.info('Using default configuration values')
      end

      deep_merge!(@config_data, default_configuration)
      new_data = new_data[@environment.to_sym]
      deep_merge!(@config_data, new_data)
    end


def keywords(limit = 20)
      @keywords ||= {}
      @keywords[limit] ||= begin
        list = []
        count = 0
        _stopwords = Vidibus::Words.stopwords(*locales)
        for word in sort
          clean = word.permalink.gsub('-','')
          unless _stopwords.include?(clean)
            list << word
            count += 1
            break if count >= limit
          end
        end
        list
      end
    end

def keywords ( limit = 20 ) @keywords ||= { } @keywords [ limit ] ||= begin list = [ ] count = 0 _stopwords = Vidibus :: Words . stopwords ( * locales ) for word in sort clean = word . permalink . gsub ( '-' , '' ) unless _stopwords . include? ( clean ) list << word count += 1 break if count >= limit end end list end end

Returns top keywords from input string .


def next_tempfile
      p = nil
      Tempfile.open("onix") do |tf|
        p = tf.path
        tf.close!
      end
      p
    end

def next_tempfile p = nil Tempfile . open ( "onix" ) do | tf | p = tf . path tf . close! end p end


def each(&block)
      @reader.each do |node|
        if @reader.node_type == 1 && @reader.name == "Product"
          str = @reader.outer_xml
          if str.nil?
            yield @product_klass.new
          else
            yield @product_klass.from_xml(str)
          end
        end
      end
    end

def each ( & block ) @reader . each do | node | if @reader . node_type == 1 && @reader . name == "Product" str = @reader . outer_xml if str . nil? yield @product_klass . new else yield @product_klass . from_xml ( str ) end end end end

Iterate over all the products in an ONIX file


def title
      composite = product.titles.first
      if composite.nil?
        nil
      else
        composite.title_text || composite.title_without_prefix
      end
    end

def title composite = product . titles . first if composite . nil? nil else composite . title_text || composite . title_without_prefix end end


def title=(str)
      composite = product.titles.first
      if composite.nil?
        composite =  ONIX::Title.new
        composite.title_type = 1
        product.titles << composite
      end
      composite.title_text = str
    end

def title = ( str ) composite = product . titles . first if composite . nil? composite = ONIX :: Title . new composite . title_type = 1 product . titles << composite end composite . title_text = str end


def subtitle=(str)
      composite = product.titles.first
      if composite.nil?
        composite =  ONIX::Title.new
        composite.title_type = 1
        product.titles << composite
      end
      composite.subtitle = str
    end

def subtitle = ( str ) composite = product . titles . first if composite . nil? composite = ONIX :: Title . new composite . title_type = 1 product . titles << composite end composite . subtitle = str end


def bic_subjects
      subjects = product.subjects.select { |sub| sub.subject_scheme_id.to_i == 12 }
      subjects.collect { |sub| sub.subject_code}
    end

def bic_subjects subjects = product . subjects . select { | sub | sub . subject_scheme_id . to_i == 12 } subjects . collect { | sub | sub . subject_code } end

return an array of BIC subjects for this title
 could be version 1 or version 2, most ONIX files don't
 specifiy

return an array of BIC subjects for this title could be version 1 or version 2 most ONIX files don t specifiy


def imprint=(str)
      composite = product.imprints.first
      if composite.nil?
        composite =  ONIX::Imprint.new
        product.imprints << composite
      end
      composite.imprint_name = str
    end

def imprint = ( str ) composite = product . imprints . first if composite . nil? composite = ONIX :: Imprint . new product . imprints << composite end composite . imprint_name = str end


def sales_restriction_type=(type)
      composite = product.sales_restrictions.first
      if composite.nil?
        composite =  ONIX::SalesRestriction.new
        product.sales_restrictions << composite
      end
      composite.sales_restriction_type = type
    end

def sales_restriction_type = ( type ) composite = product . sales_restrictions . first if composite . nil? composite = ONIX :: SalesRestriction . new product . sales_restrictions << composite end composite . sales_restriction_type = type end


def on_order
      supply = find_or_create_supply_detail
      composite = supply.stock.first
      if composite.nil?
        composite = ONIX::Stock.new
        supply.stock << composite
      end
      composite.on_order
    end

def on_order supply = find_or_create_supply_detail composite = supply . stock . first if composite . nil? composite = ONIX :: Stock . new supply . stock << composite end composite . on_order end


def proprietry_discount_code_for_rrp
      price    = price_get(2)
      return nil if price.nil?

      discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }
      discount.andand.discount_code
    end

def proprietry_discount_code_for_rrp price = price_get ( 2 ) return nil if price . nil? discount = price . discounts_coded . find { | disc | disc . discount_code_type == 2 } discount . andand . discount_code end

retrieve the discount code that describes the rrp in this file


def proprietry_discount_code_for_rrp=(code)
      price    = price_get(2)
      if price.nil?
        self.rrp_inc_sales_tax = 0
        price    = price_get(2)
      end

      discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }

      if discount.nil?
        discount = ONIX::DiscountCoded.new
        discount.discount_code_type = 2
        price.discounts_coded << discount
      end
      discount.discount_code = code
    end

def proprietry_discount_code_for_rrp = ( code ) price = price_get ( 2 ) if price . nil? self . rrp_inc_sales_tax = 0 price = price_get ( 2 ) end discount = price . discounts_coded . find { | disc | disc . discount_code_type == 2 } if discount . nil? discount = ONIX :: DiscountCoded . new discount . discount_code_type = 2 price . discounts_coded << discount end discount . discount_code = code end

set the discount code that describes the rrp in this file


def add_subject(str, type = "12")
      subject = ::ONIX::Subject.new
      subject.subject_scheme_id = type.to_i
      subject.subject_code = str
      product.subjects << subject
    end

def add_subject ( str , type = "12" ) subject = :: ONIX :: Subject . new subject . subject_scheme_id = type . to_i subject . subject_code = str product . subjects << subject end

add a new subject to this product
 str should be the subject code
 type should be the code for the subject scheme you're using. See ONIX codelist 27.
 12 is BIC

add a new subject to this product str should be the subject code type should be the code for the subject scheme you re using . See ONIX codelist 27 . 12 is BIC


def measurement_set(type, value, unit)
      measure = measurement(type)

      # create a new isbn record if we need to
      if measure.nil?
        measure = ONIX::Measure.new
        measure.measure_type_code = type
        product.measurements << measure
      end

      # store the new value
      measure.measurement = value
      measure.measure_unit_code = unit.to_s
    end

def measurement_set ( type , value , unit ) measure = measurement ( type ) if measure . nil? measure = ONIX :: Measure . new measure . measure_type_code = type product . measurements << measure end measure . measurement = value measure . measure_unit_code = unit . to_s end

set the value of a particular measurement


def price_get(type)
      supply = find_or_create_supply_detail
      if type.nil?
        supply.prices.first
      else
        supply.prices.find { |p| p.price_type_code == type }
      end
    end

def price_get ( type ) supply = find_or_create_supply_detail if type . nil? supply . prices . first else supply . prices . find { | p | p . price_type_code == type } end end

retrieve the value of a particular price


def price_set(type, num)
      p = price_get(type)

      # create a new isbn record if we need to
      if p.nil?
        supply = find_or_create_supply_detail
        p = ONIX::Price.new
        p.price_type_code = type
        supply.prices << p
      end

      # store the new value
      p.price_amount = num
    end

def price_set ( type , num ) p = price_get ( type ) if p . nil? supply = find_or_create_supply_detail p = ONIX :: Price . new p . price_type_code = type supply . prices << p end p . price_amount = num end


def other_text_set(type, value)
      text = other_text(type)

      if text.nil?
        text = ONIX::OtherText.new
        text.text_type_code = type
        product.text << text
      end

      # store the new value
      text.text = value.to_s
    end

def other_text_set ( type , value ) text = other_text ( type ) if text . nil? text = ONIX :: OtherText . new text . text_type_code = type product . text << text end text . text = value . to_s end

set the value of a particular other text value


def website_set(type, value)
      site = website(type)

      # create a new website record if we need to
      if site.nil?
        site = ONIX::Website.new
        site.website_role = type
        product.websites << site
      end

      site.website_link = value.to_s
    end

def website_set ( type , value ) site = website ( type ) if site . nil? site = ONIX :: Website . new site . website_role = type product . websites << site end site . website_link = value . to_s end


def befriend new_friend
      run_callbacks :befriend do
        friendships.create friend_id: new_friend.id, friend_type: new_friend.class.name
      end
    end

def befriend new_friend run_callbacks :befriend do friendships . create friend_id : new_friend . id , friend_type : new_friend . class . name end end

Adds a friend to an instance's friend's list

 @param [Object] new_friend a popular_model that the instance is not already friends with

 @example
   user = User.create name: "Justin"
   other_user = User.create name: "Jenny"
   user.befriend other_user

   user.friends_with? other_user #=> true

Adds a friend to an instance s friend s list


def befriend! new_friend
      run_callbacks :befriend do
        friendships.create! friend_id: new_friend.id, friend_type: new_friend.class.name
      end
    end

def befriend! new_friend run_callbacks :befriend do friendships . create! friend_id : new_friend . id , friend_type : new_friend . class . name end end

Adds a friend to an instance's friend's list
 Similar to .befriend, but will raise an error if the operation is not successful

 @param [Object] new_friend a popular_model that the instance is not already friends with

 @example
   user = User.create name: "Justin"
   other_user = User.create name: "Jenny"
   user.befriend! other_user

   user.friends_with? other_user # => true

Adds a friend to an instance s friend s list Similar to . befriend but will raise an error if the operation is not successful


def unfriend friend
      run_callbacks :unfriend do
        friendships
        .where( friend_type: friend.class.name )
        .where( friend_id: friend.id )
        .first.destroy
      end
    end

def unfriend friend run_callbacks :unfriend do friendships . where ( friend_type : friend . class . name ) . where ( friend_id : friend . id ) . first . destroy end end

Removes a friend from an instance's friend's list

 @param [Object] friend a popular_model in this instance's friends list

 @example
   user = User.create name: "Justin"
   other_user = User.create name: "Jenny"
   user.befriend other_user
   user.unfriend other_user

   user.friends_with? other_user # => false

Removes a friend from an instance s friend s list


def handle_timecop_offset
      # Establish now
      if session[TimecopConsole::SESSION_KEY_NAME].present?
        Rails.logger.debug "[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}"
        Timecop.travel(session[TimecopConsole::SESSION_KEY_NAME])
      else
        Timecop.return
      end

      # Run the intended action
      yield

      if session[TimecopConsole::SESSION_KEY_NAME].present?
        # we want to continue to slide time forward, even if it's only 3 seconds at a time.
        # this ensures that subsequent calls during the same "time travel" actually pass time
        adjusted_time = Time.now + 3
        Rails.logger.debug "[timecop-console] Resetting session to: #{adjusted_time}"
        session[TimecopConsole::SESSION_KEY_NAME] = adjusted_time
      end
    end