def mark_new_entries(response)
      digests = summary_digests

      # For each entry in the responses object, mark @_seen as false if the
      # digest of this entry doesn't exist in the cached object.
      response.entries.each do |e|
        seen = digests.include?(digest_for(e))
        e.instance_variable_set(:@_seen, seen)
      end

      response
    end

def mark_new_entries ( response ) digests = summary_digests response . entries . each do | e | seen = digests . include? ( digest_for ( e ) ) e . instance_variable_set ( :@_seen , seen ) end response end

Marks entries as either seen or not seen based on the unique signature of
 the entry, which is calculated by taking the MD5 of common attributes.

Marks entries as either seen or not seen based on the unique signature of the entry which is calculated by taking the MD5 of common attributes .


def set_header_options(curl)
      summary = summary_for_feed

      unless summary.nil?
        curl.headers['If-None-Match']     = summary[:etag] unless summary[:etag].nil?
        curl.headers['If-Modified-Since'] = summary[:last_modified] unless summary[:last_modified].nil?
      end

      curl
    end

def set_header_options ( curl ) summary = summary_for_feed unless summary . nil? curl . headers [ 'If-None-Match' ] = summary [ :etag ] unless summary [ :etag ] . nil? curl . headers [ 'If-Modified-Since' ] = summary [ :last_modified ] unless summary [ :last_modified ] . nil? end curl end

Sets the headers from the backend, if available

Sets the headers from the backend if available


def store_summary_to_backend(feed, curl)
      headers = HttpHeaders.new(curl.header_str)

      # Store info about HTTP retrieval
      summary = { }

      summary.merge!(:etag => headers.etag) unless headers.etag.nil?
      summary.merge!(:last_modified => headers.last_modified) unless headers.last_modified.nil?

      # Store digest for each feed entry so we can detect new feeds on the next
      # retrieval
      new_digest_set = feed.entries.map do |e|
        digest_for(e)
      end

      new_digest_set = summary_for_feed[:digests].unshift(new_digest_set)
      new_digest_set = new_digest_set[0..@options[:retained_digest_size]]

      summary.merge!( :digests => new_digest_set )
      set_summary(summary)
    end

def store_summary_to_backend ( feed , curl ) headers = HttpHeaders . new ( curl . header_str ) summary = { } summary . merge! ( :etag => headers . etag ) unless headers . etag . nil? summary . merge! ( :last_modified => headers . last_modified ) unless headers . last_modified . nil? new_digest_set = feed . entries . map do | e | digest_for ( e ) end new_digest_set = summary_for_feed [ :digests ] . unshift ( new_digest_set ) new_digest_set = new_digest_set [ 0 .. @options [ :retained_digest_size ] ] summary . merge! ( :digests => new_digest_set ) set_summary ( summary ) end

Stores information about the retrieval, including ETag, Last-Modified,
 and MD5 digests of all entries to the backend store.  This enables
 conditional GET usage on subsequent requests and marking of entries as
 either new or seen.

Stores information about the retrieval including ETag Last - Modified and MD5 digests of all entries to the backend store . This enables conditional GET usage on subsequent requests and marking of entries as either new or seen .


def error_manager(uri, response)
      case response
      when Net::HTTPSuccess then
        # This covers cases where the response may not validate as JSON.
        begin
          data = JSON.parse(response.body)
        rescue
          data = {}
        end
        ## Get the Headers out of the response object
        data['headers'] = response.to_hash()
        return data
      when Net::HTTPBadRequest
        raise Ropenstack::MalformedRequestError, response.body
      when Net::HTTPNotFound
        raise Ropenstack::NotFoundError, "URI: #{uri} \n" + response.body
      when Net::HTTPUnauthorized
        raise Ropenstack::UnauthorisedError, response.body
      else
        raise Ropenstack::RopenstackError, response.body
      end
    end

def
error_manager
(
uri
,
response
)
case
response
when
Net
::
HTTPSuccess
then
begin
data
=
JSON
.
parse
(
response
.
body
)
rescue
data
=
{
}
end
data
[
'headers'
]
=
response
.
to_hash
(
)
return
data
when
Net
::
HTTPBadRequest
raise
Ropenstack
::
MalformedRequestError
,
response
.
body
when
Net
::
HTTPNotFound
raise
Ropenstack
::
NotFoundError
,
"URI: #{uri} \n"
+
response
.
body
when
Net
::
HTTPUnauthorized
raise
Ropenstack
::
UnauthorisedError
,
response
.
body
else
raise
Ropenstack
::
RopenstackError
,
response
.
body
end
end

All responses from openstack where any errors need to be caught are passed through
 this function. Unless a successful response is passed it will throw a Ropenstack
 error.
 If successful returns a hash of response body, unless response body is nil then it
 returns an empty hash.

All responses from openstack where any errors need to be caught are passed through this function . Unless a successful response is passed it will throw a Ropenstack error . If successful returns a hash of response body unless response body is nil then it returns an empty hash .


def do_request(uri, request, manage_errors = true, timeout = 10)
      begin
        http = build_http(uri, timeout)
        if(manage_errors)
          return error_manager(uri, http.request(request))
        else
          http.request(request)
          return { "Success" => true }
        end
      rescue Timeout::Error
        raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}"
      rescue Errno::ECONNREFUSED
        raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}"
      end
    end

The function which you call to perform a http request
 using the request object given in the parameters. By
 default manage errors is true, so all responses are passed
 through the error manager which converts the into Ropenstack errors.

The function which you call to perform a http request using the request object given in the parameters . By default manage errors is true so all responses are passed through the error manager which converts the into Ropenstack errors .


def get_request(uri, token = nil, manage_errors = true)
      request = Net::HTTP::Get.new(uri.request_uri, initheader = build_headers(token))
      return do_request(uri, request, manage_errors)
    end

def get_request ( uri , token = nil , manage_errors = true ) request = Net :: HTTP :: Get . new ( uri . request_uri , initheader = build_headers ( token ) ) return do_request ( uri , request , manage_errors ) end

Wrapper function for a get request, just provide a uri
 and it will return you a hash with the result data.
 For authenticated transactions a token can be provided.
 Implemented using the do_request method.

Wrapper function for a get request just provide a uri and it will return you a hash with the result data . For authenticated transactions a token can be provided . Implemented using the do_request method .


def delete_request(uri, token = nil, manage_errors = true)
      request = Net::HTTP::Delete.new(uri.request_uri, initheader = build_headers(token))
      return do_request(uri, request, manage_errors)
    end

def delete_request ( uri , token = nil , manage_errors = true ) request = Net :: HTTP :: Delete . new ( uri . request_uri , initheader = build_headers ( token ) ) return do_request ( uri , request , manage_errors ) end

Wrapper function for delete requests, just provide a uri
 and it will return you a hash with the result data.
 For authenticated transactions a token can be provided.
 Implemented using the do_request method.

Wrapper function for delete requests just provide a uri and it will return you a hash with the result data . For authenticated transactions a token can be provided . Implemented using the do_request method .


def put_request(uri, body, token = nil, manage_errors = true)
      request = Net::HTTP::Put.new(uri.request_uri, initheader = build_headers(token))
      request.body = body.to_json
      return do_request(uri, request, manage_errors)
    end

def put_request ( uri , body , token = nil , manage_errors = true ) request = Net :: HTTP :: Put . new ( uri . request_uri , initheader = build_headers ( token ) ) request . body = body . to_json return do_request ( uri , request , manage_errors ) end

Wrapper function for a put request, just provide a uri
 and a hash of the data to send, then it will return you a hash
 with the result data.
 For authenticated transactions a token can be provided.
 Implemented using the do_request method

Wrapper function for a put request just provide a uri and a hash of the data to send then it will return you a hash with the result data . For authenticated transactions a token can be provided . Implemented using the do_request method


def post_request(uri, body, token = nil, manage_errors = true)
      request = Net::HTTP::Post.new(uri.request_uri, initheader = build_headers(token))
      request.body = body.to_json
      return do_request(uri, request, manage_errors)
    end

def post_request ( uri , body , token = nil , manage_errors = true ) request = Net :: HTTP :: Post . new ( uri . request_uri , initheader = build_headers ( token ) ) request . body = body . to_json return do_request ( uri , request , manage_errors ) end

Wrapper function for a put request, just provide a uri
 and a hash of the data to send, then it will return you a hash
 with the result data.
 For authenticated transactions a token can be provided.

Wrapper function for a put request just provide a uri and a hash of the data to send then it will return you a hash with the result data . For authenticated transactions a token can be provided .


def article(id)
      url = index.knowledgeManagement.articles.article
      url = url(url, ArticleID: id)
      decorate(get(url).body) { |o| autodefine(o) }
    end

def article ( id ) url = index . knowledgeManagement . articles . article url = url ( url , ArticleID : id ) decorate ( get ( url ) . body ) { | o | autodefine ( o ) } end


def upload_image_from_file(name, disk_format, container_format, minDisk, minRam, is_public, file)
      data = {
        "name" => name,
        "disk_format" => disk_format,
        "container_format" => container_format,
        "minDisk" => minDisk,
        "minRam" => minRam,
        "public" => is_public
      }
      imagesBefore = images()
      post_request(address("images"), data, @token, false)
      imagesAfter = images()
      foundNewImage = true
      image = nil
      imagesAfter.each do |imageA|
        imagesBefore.each do |imageB|
          if(imageA == imageB)
            foundNewImage = false
          end
        end
        if(foundNewImage)
          image = imageA
          break
        end
      end
      return put_octect(address(image["file"]), file.read, false)
    end

def upload_image_from_file ( name , disk_format , container_format , minDisk , minRam , is_public , file ) data = { "name" => name , "disk_format" => disk_format , "container_format" => container_format , "minDisk" => minDisk , "minRam" => minRam , "public" => is_public } imagesBefore = images ( ) post_request ( address ( "images" ) , data , @token , false ) imagesAfter = images ( ) foundNewImage = true image = nil imagesAfter . each do | imageA | imagesBefore . each do | imageB | if ( imageA == imageB ) foundNewImage = false end end if ( foundNewImage ) image = imageA break end end return put_octect ( address ( image [ "file" ] ) , file . read , false ) end

BELOW HERE IS OLD CODE THAT MAY OR MAYNOT WORK, THAR BE DRAGONS

 Upload an image to the Image Service from a file, takes in a ruby file object.
 More convoluted than it should be because for a bug in Quantum
 which just returns an error no matter the outcome.

BELOW HERE IS OLD CODE THAT MAY OR MAYNOT WORK THAR BE DRAGONS


def put_octect(uri, data, manage_errors)
      headers = build_headers(@token)
      headers["Content-Type"] = 'application/octet-stream'
      req = Net::HTTP::Put.new(uri.request_uri, initheader = headers)
      req.body = data
      return do_request(uri, req, manage_errors, 0)
    end

def put_octect ( uri , data , manage_errors ) headers = build_headers ( @token ) headers [ "Content-Type" ] = 'application/octet-stream' req = Net :: HTTP :: Put . new ( uri . request_uri , initheader = headers ) req . body = data return do_request ( uri , req , manage_errors , 0 ) end

Special rest call for sending a file stream using an octet-stream
 main change is just custom headers.
 Still implemented using do_request function.

Special rest call for sending a file stream using an octet - stream main change is just custom headers . Still implemented using do_request function .


def relative_path(path)
      path = File.expand_path(path)
      root = full_path("")
      if path.size >= root.size && path[0...root.size] == root
        path[0...root.size] = ""
        path = "/" if path.size == 0
        path
      end
    end

def relative_path ( path ) path = File . expand_path ( path ) root = full_path ( "" ) if path . size >= root . size && path [ 0 ... root . size ] == root path [ 0 ... root . size ] = "" path = "/" if path . size == 0 path end end

Returns a path relative to the base path, given the full path. This is the inverse of
 full_path.

Returns a path relative to the base path given the full path . This is the inverse of full_path .


def index(path)
      @entries = []
      Dir.entries(path).each do |entry|
        relative_path = relative_path(File.join(path, entry))
        if entry != "." && relative_path
          @entries << {:name => entry, :href => relative_path}
        end
      end
      @path = path
      haml :index
    end

def index ( path ) @entries = [ ] Dir . entries ( path ) . each do | entry | relative_path = relative_path ( File . join ( path , entry ) ) if entry != "." && relative_path @entries << { :name => entry , :href => relative_path } end end @path = path haml :index end

Renders an index page for the specified directory.

Renders an index page for the specified directory .


def accessors_from_headers!
      raise "Can't define accessors from headers in a table without headers" unless @has_headers

      self.accessors = headers.map { |val| (val && !val.empty?) ? val.to_s.downcase.tr('^a-z0-9_', '_').squeeze('_').gsub(/\A_|_\z/, '').to_sym : nil }
    end

Create a new table.

 @param [Hash] options
   A list of options. Mostly identical to {Table#initialize}'s options
   hash, but with the additional options :file_type and :table_class.

 @option options [String] :name
   The name of the table
 @option options [Array<Symbol>, Hash<Symbol => Integer>, nil] :accessors
   A list of accessors for the columns. Allows accessing columns by that accessor.
 @option options [Symbol] :data
   An array of arrays with the table data. Mutually exclusive with
   :header, :body and :footer.
 @option options [Symbol] :header
   An array with the header values. To be used together with :body and :footer.
   Mutually exclusive with :data.
   Automatically sets :has_headers to true.
 @option options [Symbol] :body
   An array with the header values. To be used together with :header and :footer.
   Mutually exclusive with :data.
   Automatically sets :has_headers to false if :header is not also present.
   Automatically sets :has_footer to false if :footer is not also present.
 @option options [Symbol] :footer
   An array with the header values. To be used together with :header and :body.
   Mutually exclusive with :data.
   Automatically sets :has_footer to true.
 @option options [true, false] :has_headers
   Whether the table has a header, defaults to true
 @option options [true, false] :has_footer
   Whether the table has a footer, defaults to false

 Automatically create accessors from the headers of the table.
 It does that by downcasing the headers, replace everything which is not in [a-z0-9_] with an _,
 replace all repeated occurrences of _ with a single _.

 @note
   The actual transformation algorithm might change in the future.


def <<(row)
      index  = @data.size
      begin
        row = row.to_ary
      rescue NoMethodError
        raise ArgumentError, "Row must be provided as Array or respond to `to_ary`, but got #{row.class} in row #{index}" unless row.respond_to?(:to_ary)
        raise
      end
      raise InvalidColumnCount.new(index, row.size, column_count) if @data.first && row.size != @data.first.size

      @data << row
      @rows << Row.new(self, index, row)

      self
    end

Append a row to the table.

 @param [Array, #to_ary] row
   The row to append to the table

 @return [self]


def html(id, time)
      inline_footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "inline-footnote-number")
      Build.tag("a", inline_footnote_label, :href => "#footnote#{id}#{time}")
    end

def html ( id , time ) inline_footnote_label = Build . tag ( "span" , Build . tag ( "sup" , id . to_s ) , :class => "inline-footnote-number" ) Build . tag ( "a" , inline_footnote_label , :href => "#footnote#{id}#{time}" ) end

This is the method that will place the anchor tag and id of the
 footnote within the paragraph body itself.

 I'm passing in a time variable here to make links unique. You see,
 if you parse many of these entries on a single HTML page you'll end up
 with multiple #footnote1 divs. To make them unique, we'll pass down
 a time variable from above to seed them.

This is the method that will place the anchor tag and id of the footnote within the paragraph body itself .


def footnote_html(id, time)
      footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "footnote-number")
      footnote_content = sequence.elements.map { |s| s.html }.join
      Build.tag("div", footnote_label + footnote_content, :id => "footnote#{id}#{time}", :class => "footnote")
    end

def footnote_html ( id , time ) footnote_label = Build . tag ( "span" , Build . tag ( "sup" , id . to_s ) , :class => "footnote-number" ) footnote_content = sequence . elements . map { | s | s . html } . join Build . tag ( "div" , footnote_label + footnote_content , :id => "footnote#{id}#{time}" , :class => "footnote" ) end

This is the method that will actually spit out the div that the
 footnote's content is in. This will generally be called after all of the
 paragraph's text has been spit out so that the footnotes can be appended
 after. Note that it needs to be passed an id from the caller so that it
 can be linked to corretly with an anchor tag in the body of the main text.

 I'm passing in a time variable here to make links unique. You see,
 if you parse many of these entries on a single HTML page you'll end up
 with multiple #footnote1 divs. To make them unique, we'll pass down
 a time variable from above to seed them.

This is the method that will actually spit out the div that the footnote s content is in . This will generally be called after all of the paragraph s text has been spit out so that the footnotes can be appended after . Note that it needs to be passed an id from the caller so that it can be linked to corretly with an anchor tag in the body of the main text .


def instance_action(id, action, param)
      case action
      when "RESTART"
        post_request(address("/instances/" + id + "/action"), {:restart => {}}, @token)
      when "RESIZE"
        if param.is_a? String
          post_request(address("/instances/" + id + "/action"), {:resize => {:flavorRef => param }}, @token)
        elsif param.is_a? Int
          post_request(address("/instances/" + id + "/action"), {:resize => {:volume => {:size => param }}}, @token)
        else
          raise Ropenstack::RopenstackError, "Invalid Parameter Passed"
        end
      else
        raise Ropenstack::RopenstackError, "Invalid Action Passed"
      end
    end

def
instance_action
(
id
,
action
,
param
)
case
action
when
"RESTART"
post_request
(
address
(
"/instances/"
+
id
+
"/action"
)
,
{
:restart
=>
{
}
}
,
@token
)
when
"RESIZE"
if
param
.
is_a?
String
post_request
(
address
(
"/instances/"
+
id
+
"/action"
)
,
{
:resize
=>
{
:flavorRef
=>
param
}
}
,
@token
)
elsif
param
.
is_a?
Int
post_request
(
address
(
"/instances/"
+
id
+
"/action"
)
,
{
:resize
=>
{
:volume
=>
{
:size
=>
param
}
}
}
,
@token
)
else
raise
Ropenstack
::
RopenstackError
,
"Invalid Parameter Passed"
end
else
raise
Ropenstack
::
RopenstackError
,
"Invalid Action Passed"
end
end


def add(error_on, message = "Unknown error")

       # humanize error_on
       if error_on.is_a?(Symbol)
         error_on_str = error_on.to_s
       else
         error_on_str = underscore(error_on.class.name)
       end
       error_on_str = error_on_str.gsub(/\//, '_')
       error_on_str = error_on_str.gsub(/_/, ' ')
       error_on_str = error_on_str.gsub(/^revenc/, '').strip
       #error_on_str = error_on_str.capitalize

       @errors[error_on_str] ||= []
       @errors[error_on_str] << message.to_s
    end

def
add
(
error_on
,
message
=
"Unknown error"
)
if
error_on
.
is_a?
(
Symbol
)
error_on_str
=
error_on
.
to_s
else
error_on_str
=
underscore
(
error_on
.
class
.
name
)
end
error_on_str
=
error_on_str
.
gsub
(
/
\/
/
,
'_'
)
error_on_str
=
error_on_str
.
gsub
(
/
/
,
' '
)
error_on_str
=
error_on_str
.
gsub
(
/
/
,
''
)
.
strip
@errors
[
error_on_str
]
||=
[
]
@errors
[
error_on_str
]
<<
message
.
to_s
end

add errors, error_on can be a symbol or object instance

add errors error_on can be a symbol or object instance


def coords_of_neighbors(x, y)
        coords_of_neighbors = []
        (x - 1).upto(x + 1).each do |neighbors_x|
          (y - 1).upto(y + 1).each do |neighbors_y|
            next if (x == neighbors_x) && (y == neighbors_y)
            coords_of_neighbors << [neighbors_x, neighbors_y]
          end
        end
        coords_of_neighbors
      end

def coords_of_neighbors ( x , y ) coords_of_neighbors = [ ] ( x - 1 ) . upto ( x + 1 ) . each do | neighbors_x | ( y - 1 ) . upto ( y + 1 ) . each do | neighbors_y | next if ( x == neighbors_x ) && ( y == neighbors_y ) coords_of_neighbors << [ neighbors_x , neighbors_y ] end end coords_of_neighbors end

Calculates the co-ordinates of neighbors of a given pair of co-ordinates.
 @param [Integer] x the x-coordinate
 @param [Integer] y the y-coordinate
 @return [Array<Integer, Integer>] the list of neighboring co-ordinates
 @example
   coords_of_neighbors(1,1) =>
     [
       [0, 0], [0, 1], [0, 2],
       [1, 0],         [1, 2],
       [2, 0], [2, 1], [2, 2],
     ]
 @note This method returns all possible co-ordinate pairs of neighbors,
   so it can contain coordinates of cells not in the board, or negative ones.
 @see #neighbors_of_cell_at

Calculates the co - ordinates of neighbors of a given pair of co - ordinates .


def merchant(id, options = {})
      options = update_by_expire_time options
      if merchant_not_latest?(id)
        @rsqoot_merchant = get("merchants/#{id}", options, SqootMerchant)
        @rsqoot_merchant = @rsqoot_merchant.merchant if @rsqoot_merchant
      end
      logger(uri: sqoot_query_uri, records: [@rsqoot_merchant], type: 'merchants', opts: options)
      @rsqoot_merchant
    end

def merchant ( id , options = { } ) options = update_by_expire_time options if merchant_not_latest? ( id ) @rsqoot_merchant = get ( "merchants/#{id}" , options , SqootMerchant ) @rsqoot_merchant = @rsqoot_merchant . merchant if @rsqoot_merchant end logger ( uri : sqoot_query_uri , records : [ @rsqoot_merchant ] , type : 'merchants' , opts : options ) @rsqoot_merchant end

Retrieve a list of merchants base on the following parameters

 @param [String] id (The merchant's ID, Use the Sqoot ID or ID for any supported namespace. Must supply namespace if we don't use Sqoot)
 @param [String] namespace (One of the supported namespaces. Factual, Foursquare, Facebook, Google, CitySearch, Yelp.)


def encode data, opcode=TEXT_FRAME
      frame = []
      frame << (opcode | 0x80)

      packr = "CC"

      if opcode == TEXT_FRAME
        data.force_encoding("UTF-8")

        if !data.valid_encoding?
          raise "Invalid UTF!"
        end
      end

      # append frame length and mask bit 0x80
      len = data ? data.bytesize : 0
      if len <= 125
        frame << (len | 0x80)
      elsif len < 65536
        frame << (126 | 0x80)
        frame << len
        packr << "n"
      else
        frame << (127 | 0x80)
        frame << len
        packr << "L!>"
      end

      # generate a masking key
      key = rand(2 ** 31)

      # mask each byte with the key
      frame << key
      packr << "N"

      #puts "op #{opcode} len #{len} bytes #{data}"
      # Apply the masking key to every byte
      len.times do |i|
        frame << ((data.getbyte(i) ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)
      end

      frame.pack("#{packr}C*")
    end

def
encode
data
,
opcode
=
TEXT_FRAME
frame
=
[
]
frame
<<
(
opcode
|
0x80
)
packr
=
"CC"
if
opcode
==
TEXT_FRAME
data
.
force_encoding
(
"UTF-8"
)
if
!
data
.
valid_encoding?
raise
"Invalid UTF!"
end
end
len
=
data
data
.
bytesize
:
0
if
len
<=
125
frame
<<
(
len
|
0x80
)
elsif
len
<
65536
frame
<<
(
126
|
0x80
)
frame
<<
len
packr
<<
"n"
else
frame
<<
(
127
|
0x80
)
frame
<<
len
packr
<<
"L!>"
end
key
=
rand
(
2
**
31
)
frame
<<
key
packr
<<
"N"
len
.
times
do
|
i
|
frame
<<
(
(
data
.
getbyte
(
i
)
^
(
key
>>
(
(
3
(
i
%
4
)
)
*
8
)
)
)
&
0xFF
)
end
frame
.
pack
(
"#{packr}C*"
)
end

Encode a standard payload to a hybi10
 WebSocket frame


def challah_permission
      unless included_modules.include?(InstanceMethods)
        include InstanceMethods
        extend ClassMethods
      end

      class_eval do
        validates_presence_of :name, :key
        validates_uniqueness_of :name, :key
        validates_format_of :key, :with => /^([a-z0-9_])*$/, :message => :invalid_key

        has_many :permission_roles, :dependent => :destroy
        has_many :roles, :through => :permission_roles, :order => 'roles.name'
        has_many :permission_users, :dependent => :destroy
        has_many :users, :through => :permission_users, :order => 'users.last_name, users.first_name'

        default_scope order('permissions.name')

        attr_accessible :name, :description, :key, :locked

        after_create :add_to_admin_role
      end
    end

def
challah_permission
unless
included_modules
.
include?
(
InstanceMethods
)
include
InstanceMethods
extend
ClassMethods
end
class_eval
do
validates_presence_of
:name
,
:key
validates_uniqueness_of
:name
,
:key
validates_format_of
:key
,
:with
=>
/
/
,
:message
=>
:invalid_key
has_many
:permission_roles
,
:dependent
=>
:destroy
has_many
:roles
,
:through
=>
:permission_roles
,
:order
=>
'roles.name'
has_many
:permission_users
,
:dependent
=>
:destroy
has_many
:users
,
:through
=>
:permission_users
,
:order
=>
'users.last_name, users.first_name'
default_scope
order
(
'permissions.name'
)
attr_accessible
:name
,
:description
,
:key
,
:locked
after_create
:add_to_admin_role
end
end

This method sets up the +Permission+ class with all baked in methods.

 A permission requires the presence of the +name+, +key+ and +description+

 Once this method has been called, the {InstanceMethods} module
 will be accessibile within the Permission model.

This method sets up the + Permission + class with all baked in methods .


def post hash={}, payload
      raise 'Payload cannot be blank' if payload.nil? || payload.empty?

      hash.symbolize_keys!
      call(:post, hash[:endpoint], (hash[:args]||{}).merge({:method => :post}), payload)
    end

def
post
hash
=
{
}
,
payload
raise
'Payload cannot be blank'
if
payload
.
nil?
||
payload
.
empty?
hash
.
symbolize_keys!
call
(
:post
,
hash
[
:endpoint
]
,
(
hash
[
:args
]
||
{
}
)
.
merge
(
{
:method
=>
:post
}
)
,
payload
)
end

makes a POST request

 ==== Attributes
 * +hash+ - Hash of parameters
 ** +endpoint+ - Url endpoint ex. /product/createOrUpdate
 ** +args+ - Request arguments, (add headers key for extra headers options) ex. hash[:headers] = { 'content-type' => 'xml' }
 * +payload+ - Data for the request ex. { merchantId: 'asdasdsadas', products: [{ ... },{ ...}...]}


def create_network(name, tenant, admin_state_up = true)
      data = {
        'network' => {
          'name' => name,
          'tenant_id' => tenant,
          'admin_state_up' => admin_state_up
        }
      }
      return post_request(address("networks"), data, @token)
    end

def create_network ( name , tenant , admin_state_up = true ) data = { 'network' => { 'name' => name , 'tenant_id' => tenant , 'admin_state_up' => admin_state_up } } return post_request ( address ( "networks" ) , data , @token ) end

Create a new network on Openstack given a name and tenant id.

Create a new network on Openstack given a name and tenant id .


def create_port(network, subnet = nil, device = nil, device_owner = nil)
      data = {
        'port' => {
          'network_id' => network,
        }
      }
      unless device_owner.nil?
        data['port']['device_owner'] = device_owner
      end
      unless device.nil?
        data['port']['device_id'] = device
      end
      unless subnet.nil?
        data['port']['fixed_ips'] = [{'subnet_id' => subnet}]
      end

      puts data

      return post_request(address("ports"), data, @token)
    end

def create_port ( network , subnet = nil , device = nil , device_owner = nil ) data = { 'port' => { 'network_id' => network , } } unless device_owner . nil? data [ 'port' ] [ 'device_owner' ] = device_owner end unless device . nil? data [ 'port' ] [ 'device_id' ] = device end unless subnet . nil? data [ 'port' ] [ 'fixed_ips' ] = [ { 'subnet_id' => subnet } ] end puts data return post_request ( address ( "ports" ) , data , @token ) end

Create a new port given network and device ids, optional
 parameter subnet id allows for scoping the port to a single subnet.

Create a new port given network and device ids optional parameter subnet id allows for scoping the port to a single subnet .


def move_port_to_subnets(port_id, subnet_ids)
      id_list = Array.new()
      subnet_ids.each do |id|
        id_list << { "subnet_id" => id }
      end
      return update_port(port_id, id_list)
    end

def move_port_to_subnets ( port_id , subnet_ids ) id_list = Array . new ( ) subnet_ids . each do | id | id_list << { "subnet_id" => id } end return update_port ( port_id , id_list ) end

Weird function for adding a port to multiple subnets if nessessary.

Weird function for adding a port to multiple subnets if nessessary .


def json(data={}, options={})
      response[CONTENT_TYPE] = APPLICATION_JSON
      response.status = options[:status] if options.has_key?(:status)
      response.write self.class.json_serializer.dump(data)
    end

def json ( data = { } , options = { } ) response [ CONTENT_TYPE ] = APPLICATION_JSON response . status = options [ :status ] if options . has_key? ( :status ) response . write self . class . json_serializer . dump ( data ) end

This is a convenience method that sets the Content-Type headers
 and writes the JSON String to the response.

 @param [Hash] data The data
 @param [Hash] options The options
 @option options [Fixnum] :status The response status code
 @return [String] The JSON

This is a convenience method that sets the Content - Type headers and writes the JSON String to the response .


def redirect_to(url, options={})
      full_url = absolute_url(url, options)
      response[LOCATION] = full_url
      respond_with 302
      full_url
    end

def redirect_to ( url , options = { } ) full_url = absolute_url ( url , options ) response [ LOCATION ] = full_url respond_with 302 full_url end

This is a convenience method that forms an absolute URL based on the
 url parameter, which can be a relative or absolute URL, and then
 sets the headers and the body appropriately to do a 302 redirect.

 @see #absolute_url
 @return [String] The absolute url

This is a convenience method that forms an absolute URL based on the url parameter which can be a relative or absolute URL and then sets the headers and the body appropriately to do a 302 redirect .


def servers(id)
      endpoint = "/servers"
      unless id.nil?
        endpoint = endpoint + "/" + id
      end
      return get_request(address(endpoint), @token)
    end

def servers ( id ) endpoint = "/servers" unless id . nil? endpoint = endpoint + "/" + id end return get_request ( address ( endpoint ) , @token ) end

Gets a list of servers from OpenStack

 :call-seq:
   servers(id) => A single server with the id matching the parameter
   servers() => All servers visible to the tenant making the request


def create_server(name, image, flavor, networks = nil, keypair = nil, security_group = nil, metadata = nil)
      data = {
        "server" => {
          "name" => name,
          "imageRef" => image,
          "flavorRef" => flavor,
        }
      }
      unless networks.nil?
        data["server"]["networks"] = networks
      end
      unless keypair.nil?
        data["server"]["key_name"] = keypair
      end
      unless security_group.nil?
        data["server"]["security_group"] = security_group
      end
      return post_request(address("/servers"), data, @token)
    end

def create_server ( name , image , flavor , networks = nil , keypair = nil , security_group = nil , metadata = nil ) data = { "server" => { "name" => name , "imageRef" => image , "flavorRef" => flavor , } } unless networks . nil? data [ "server" ] [ "networks" ] = networks end unless keypair . nil? data [ "server" ] [ "key_name" ] = keypair end unless security_group . nil? data [ "server" ] [ "security_group" ] = security_group end return post_request ( address ( "/servers" ) , data , @token ) end


def action(id, act, *args)
      data = case act
        when "reboot" then {'reboot' =>{"type" => args[0]}}
        when "vnc" then {'os-getVNCConsole' => { "type" => "novnc" }}
        when "stop" then {'os-stop' => 'null'}
        when "start" then {'os-start' => 'null'}
        when "pause" then {'pause' => 'null'}
        when "unpause" then {'unpause' => 'null'}
        when "suspend" then {'suspend' => 'null'}
        when "resume" then {'resume' => 'null'}
        when "create_image" then {'createImage' => {'name' => args[0], 'metadata' => args[1]}}
        else raise "Invalid Action"
        end
      return post_request(address("/servers/" + id + "/action"), data, @token)
    end

def
action
(
id
,
act
,
*
args
)
data
=
case
act
when
"reboot"
then
{
'reboot'
=>
{
"type"
=>
args
[
0
]
}
}
when
"vnc"
then
{
'os-getVNCConsole'
=>
{
"type"
=>
"novnc"
}
}
when
"stop"
then
{
'os-stop'
=>
'null'
}
when
"start"
then
{
'os-start'
=>
'null'
}
when
"pause"
then
{
'pause'
=>
'null'
}
when
"unpause"
then
{
'unpause'
=>
'null'
}
when
"suspend"
then
{
'suspend'
=>
'null'
}
when
"resume"
then
{
'resume'
=>
'null'
}
when
"create_image"
then
{
'createImage'
=>
{
'name'
=>
args
[
0
]
,
'metadata'
=>
args
[
1
]
}
}
else
raise
"Invalid Action"
end
return
post_request
(
address
(
"/servers/"
+
id
+
"/action"
)
,
data
,
@token
)
end

Perform an action on a server on Openstack, by passing an id,
 and an action, some actions require more data.

 E.g. action(id, "reboot", "hard")

Perform an action on a server on Openstack by passing an id and an action some actions require more data .


def delete_image(id)
      uri = URI.parse("http://" + @location.host + ":" + @location.port.to_s + "/v2/images/" + id)
      return delete_request(uri, @token)
    end

def delete_image ( id ) uri = URI . parse ( "http://" + @location . host + ":" + @location . port . to_s + "/v2/images/" + id ) return delete_request ( uri , @token ) end

Delete an image stored on Openstack through the nova endpoint


def get(path, opts = {}, wrapper = ::Hashie::Mash)
      uri, headers = url_generator(path, opts)
      begin
        json = JSON.parse uri.open(headers).read
        result = wrapper.new json
        @query_options = result.query
        result
      rescue => e
        logger(error: e)
        nil
      end
    end

def get ( path , opts = { } , wrapper = :: Hashie :: Mash ) uri , headers = url_generator ( path , opts ) begin json = JSON . parse uri . open ( headers ) . read result = wrapper . new json @query_options = result . query result rescue => e logger ( error : e ) nil end end

Get method, use by all other API qeury methods, fetch records
 from the Sqoot API V2 url, and provide wrapper functionality

Get method use by all other API qeury methods fetch records from the Sqoot API V2 url and provide wrapper functionality


def set_basepath
      if self.parent.nil?
        self.basepath = self.basename
        self.basedirpath ||= ''
      else
        self.basepath = self.parent.basepath+'/'+self.basename
        self.basedirpath ||= self.parent.basepath+'/'
      end

    end

def set_basepath if self . parent . nil? self . basepath = self . basename self . basedirpath ||= '' else self . basepath = self . parent . basepath + '/' + self . basename self . basedirpath ||= self . parent . basepath + '/' end end


def commissions(options = {})
      options = update_by_expire_time options
      if commissions_not_latest?(options)
        @rsqoot_commissions = get('commissions', options, SqootCommission)
        @rsqoot_commissions = @rsqoot_commissions.commissions if @rsqoot_commissions
      end
      logger(uri: sqoot_query_uri, records: @rsqoot_commissions, type: 'commissions', opts: options)
      @rsqoot_commissions
    end

def commissions ( options = { } ) options = update_by_expire_time options if commissions_not_latest? ( options ) @rsqoot_commissions = get ( 'commissions' , options , SqootCommission ) @rsqoot_commissions = @rsqoot_commissions . commissions if @rsqoot_commissions end logger ( uri : sqoot_query_uri , records : @rsqoot_commissions , type : 'commissions' , opts : options ) @rsqoot_commissions end

Retrieve information of commissions based on the following parameters

 @param [String] :to Start date
 @param [String] :from End date

 @return [RSqoot::SqootCommission]


def leagues(opts={})
      season = opts.fetch(:season) { Time.now.year }

      json_response get("competitions/?season=#{season}")
    end

def leagues ( opts = { } ) season = opts . fetch ( :season ) { Time . now . year } json_response get ( "competitions/?season=#{season}" ) end


def match(*args, &block)
      z = Module.new do
        include Ov
        extend self
        def try(*args, &block)
          let :anon_method, *args, &block
        end
        def otherwise(&block)
          let :otherwise, &block
        end
        instance_eval &block
      end
      begin
        z.anon_method(*args)
      rescue Ov::NotImplementError => e
        z.otherwise
      end
    end

def match ( * args , & block ) z = Module . new do include Ov extend self def try ( * args , & block ) let :anon_method , * args , & block end def otherwise ( & block ) let :otherwise , & block end instance_eval & block end begin z . anon_method ( * args ) rescue Ov :: NotImplementError => e z . otherwise end end

Add `match` method, which work like `case` statement but for types

 == Usage

    include Ov::Ext

    match("String", "dsa") do
      try(String, Array) {|str, arr| "#{str} #{arr}" }
      try(String) {|str| "#{str}"  }
      otherwise { "none" }
    end

Add match method which work like case statement but for types


def fetch(column, *default_value, &default_block)
      raise ArgumentError, "Must only provide at max one default value or one default block" if default_value.size > (block_given? ? 0 : 1)

      index = case column
        when Symbol then @table.index_for_accessor(column)
        when String then @table.index_for_header(column)
        when Integer then column
        else raise InvalidColumnSpecifier, "Invalid index type, expected Symbol, String or Integer, but got #{column.class}"
      end

      @data.fetch(index, *default_value, &default_block)
    end

Tries to return the value of the column identified by index, corresponding accessor or header.
 It throws an IndexError exception if the referenced index lies outside of the array bounds.
 This error can be prevented by supplying a second argument, which will act as a default value.

 Alternatively, if a block is given it will only be executed when an invalid
 index is referenced.  Negative values of index count from the end of the
 array.

Tries to return the value of the column identified by index corresponding accessor or header . It throws an IndexError exception if the referenced index lies outside of the array bounds . This error can be prevented by supplying a second argument which will act as a default value .


def at(column)
      case column
        when Symbol  then at_accessor(column)
        when String  then at_header(column)
        when Integer then at_index(column)
        when Range   then @data[column]
        else raise InvalidColumnSpecifier, "Invalid index type, expected Symbol, String or Integer, but got #{column.class}"
      end
    end

Access a single cell by either index, index-range, accessor or header-name.

 @example
     table = Tabledata.table header: %w[x y z], body: [[:a,:b,:c]], accessors: %i[foo bar baz]
     row   = table.row(1)
     row.at(0)    # => :a
     row.at(:foo) # => :a
     row.at("x")  # => :a

Access a single cell by either index index - range accessor or header - name .


def values_at(*columns)
      result = []
      columns.each do |column|
        data = at(column)
        if column.is_a?(Range)
          result.concat(data) if data
        else
          result << data
        end
      end

      result
    end

def values_at ( * columns ) result = [ ] columns . each do | column | data = at ( column ) if column . is_a? ( Range ) result . concat ( data ) if data else result << data end end result end

Access multiple values by either index, index-range, accessor or header-name.
 @example
     table = Tabledata.table header: %w[x y z], body: [[:a,:b,:c]], accessors: %i[foo bar baz]
     row   = table.row(1)
     row.values_at(2,1,0)    # => [:c, :b, :a]
     row.values_at(:foo,'z') # => [:a, :c]
     row.values_at(0..1, 2..-1) # => [:a, :b, :c]

Access multiple values by either index index - range accessor or header - name .


def method_missing(name, *args, &block)
      return super unless @table.accessors?

      name              =~ /^(\w+)(=)?$/
      name_mod, assign  = $1, $2
      index             = @table.index_for_accessor(name_mod)
      arg_count         = assign ? 1 : 0

      return super unless index

      raise ArgumentError, "Wrong number of arguments (#{args.size} for #{arg_count})" if args.size > arg_count

      if assign then
        @data[index] = args.first
      else
        @data[index]
      end
    end

Allow reading and writing cell values by their accessor name.

Allow reading and writing cell values by their accessor name .


def authorize(auth = {})
      @authentication ||= TaskMapper::Authenticator.new(auth)
      auth = @authentication
      if (auth.account.nil? and auth.subdomain.nil?) or auth.username.nil? or auth.password.nil?
        raise "Please provide at least an account (subdomain), username and password)"
      end
      UnfuddleAPI.protocol = auth.protocol if auth.protocol?
      UnfuddleAPI.account = auth.account || auth.subdomain
      UnfuddleAPI.authenticate(auth.username, auth.password)
    end

Providers must define an authorize method. This is used to initialize and set authentication
 parameters to access the API

Providers must define an authorize method . This is used to initialize and set authentication parameters to access the API


def routers(id = nil)
      endpoint = "routers"
      unless id.nil?
        endpoint = endpoint + "/" + id
      end
      return get_request(address(endpoint), @token)
    end

def routers ( id = nil ) endpoint = "routers" unless id . nil? endpoint = endpoint + "/" + id end return get_request ( address ( endpoint ) , @token ) end

Get a list of a tenants routers

 :call-seq:
   routers(id) => A single router with the id matching the parameter
   routers => All routers visible to the tenant making the request


def create_router(name, admin_state_up = true)
      data = {
        'router' =>{
          'name' => name,
          'admin_state_up' => admin_state_up,
        }
      }
      return post_request(address("routers"), data, @token)
    end

def create_router ( name , admin_state_up = true ) data = { 'router' => { 'name' => name , 'admin_state_up' => admin_state_up , } } return post_request ( address ( "routers" ) , data , @token ) end


def delete_router_interface(router, id, type)
      data = case type
        when 'port' then { 'port_id' => id }
        when 'subnet' then { 'subnet_id' => id }
        else raise "Invalid Interface Type"
        end
      return put_request(address("routers/" + router + "/remove_router_interface"), data, @token)
    end

def
delete_router_interface
(
router
,
id
,
type
)
data
=
case
type
when
'port'
then
{
'port_id'
=>
id
}
when
'subnet'
then
{
'subnet_id'
=>
id
}
else
raise
"Invalid Interface Type"
end
return
put_request
(
address
(
"routers/"
+
router
+
"/remove_router_interface"
)
,
data
,
@token
)
end

Delete a connection between a subnet and router given either port
 or subnet ids.

 :call-seq:
   delete_router_interface(router_id, subnet_id, "subnet")
   delete_router_interface(router_id, port_id, "port")

Delete a connection between a subnet and router given either port or subnet ids .


def where(method)
      @complete, @result = nil, nil
      z = find_or_next(method) { |method|
        self.find{|m| m.eql?(method) }
      }.find_or_next(method) { |method|
        self.find{|m| m.eql0?(method) }
      }.find_or_next(method) { |method|
        self.find{|m| m.like?(method) }
      }.find_or_next(method) {|method|
        self.find{|m| m.like0?(method) }
      }.get
    end

def where ( method ) @complete , @result = nil , nil z = find_or_next ( method ) { | method | self . find { | m | m . eql? ( method ) } } . find_or_next ( method ) { | method | self . find { | m | m . eql0? ( method ) } } . find_or_next ( method ) { | method | self . find { | m | m . like? ( method ) } } . find_or_next ( method ) { | method | self . find { | m | m . like0? ( method ) } } . get end

find in self
find in ancestors
find types
find any types


def load
      config_files.each do |file|
        config = YAML::load(File.open(file))
        @config.merge! config
      end
    end

def load config_files . each do | file | config = YAML :: load ( File . open ( file ) ) @config . merge! config end end


def providers(options = {})
      options = update_by_expire_time options
      query = options.delete(:query)
      if providers_not_latest?(options)
        @rsqoot_providers = get('providers', options, SqootProvider)
        @rsqoot_providers = @rsqoot_providers.providers.map(&:provider) if @rsqoot_providers
      end
      result = query.present? ? query_providers(query) : @rsqoot_providers
      logger(uri: sqoot_query_uri, records: result, type: 'providers', opts: options)
      result
    end

def providers ( options = { } ) options = update_by_expire_time options query = options . delete ( :query ) if providers_not_latest? ( options ) @rsqoot_providers = get ( 'providers' , options , SqootProvider ) @rsqoot_providers = @rsqoot_providers . providers . map ( & :provider ) if @rsqoot_providers end result = query . present? ? query_providers ( query ) : @rsqoot_providers logger ( uri : sqoot_query_uri , records : result , type : 'providers' , opts : options ) result end

Retrieve a list of providers base on the following parameters

 @return [RSqoot::SqootProvider]


def categories(options = {})
      options = update_by_expire_time options
      query = options.delete(:query)
      if categories_not_latest?(options)
        @rsqoot_categories = get('categories', options, SqootCategory)
        @rsqoot_categories = @rsqoot_categories.categories.map(&:category) if @rsqoot_categories
      end
      result = query.present? ? query_categories(query) : @rsqoot_categories
      logger(uri: sqoot_query_uri, records: result, type: 'categories', opts: options)
      result
    end

def categories ( options = { } ) options = update_by_expire_time options query = options . delete ( :query ) if categories_not_latest? ( options ) @rsqoot_categories = get ( 'categories' , options , SqootCategory ) @rsqoot_categories = @rsqoot_categories . categories . map ( & :category ) if @rsqoot_categories end result = query . present? ? query_categories ( query ) : @rsqoot_categories logger ( uri : sqoot_query_uri , records : result , type : 'categories' , opts : options ) result end

Retrieve a list of categories base on the following parameters

 @return [RSqoot::SqootCategory] category list


def challah_role
      unless included_modules.include?(InstanceMethods)
        include InstanceMethods
        extend ClassMethods
      end

      class_eval do
        # Validations
        ################################################################

        validates :name, :presence => true, :uniqueness => true

        # Relationships
        ################################################################

        has_many :permission_roles,   :dependent => :destroy

        has_many :permissions,        :through => :permission_roles,
                                      :order => 'permissions.name'

        has_many :users,              :order => 'users.first_name, users.last_name'

        # Scoped Finders
        ################################################################

        default_scope order('roles.name')

        # Callbacks
        ################################################################

        after_save :save_permission_keys

        # Attributes
        ################################################################

        attr_accessible :description, :default_path, :locked, :name
      end
    end

def
challah_role
unless
included_modules
.
include?
(
InstanceMethods
)
include
InstanceMethods
extend
ClassMethods
end
class_eval
do
validates
:name
,
:presence
=>
true
,
:uniqueness
=>
true
has_many
:permission_roles
,
:dependent
=>
:destroy
has_many
:permissions
,
:through
=>
:permission_roles
,
:order
=>
'permissions.name'
has_many
:users
,
:order
=>
'users.first_name, users.last_name'
default_scope
order
(
'roles.name'
)
after_save
:save_permission_keys
attr_accessible
:description
,
:default_path
,
:locked
,
:name
end
end

This method sets up the +Role+ class with all baked in methods.

 A role requires the presence of the +name+ and +default_path+ attributes.

 Once this method has been called, the {InstanceMethods} and {ClassMethods} modules
 will be accessibile within the Role model.

This method sets up the + Role + class with all baked in methods .


def check_for_upgrade
      if plan_id_changed?
        old_plan = Plan.find(plan_id_was) if plan_id_was.present?
        self.upgraded = true if old_plan.nil? || old_plan.order < plan.order
      end
    end

def check_for_upgrade if plan_id_changed? old_plan = Plan . find ( plan_id_was ) if plan_id_was . present? self . upgraded = true if old_plan . nil? || old_plan . order < plan . order end end

def nil_if_blank
   self.trial_end = nil if self.trial_end.blank?
 end

def nil_if_blank self . trial_end = nil if self . trial_end . blank? end


def method_missing(name, *args, &block)
      obj = __getobj__
      __substitute_self__(obj.__send__(name, *args, &block), obj)
    end

def method_missing ( name , * args , & block ) obj = __getobj__ __substitute_self__ ( obj . __send__ ( name , * args , & block ) , obj ) end

if chainable method or returns "self" for some other reason,
 return this proxy instead

if chainable method or returns self for some other reason return this proxy instead


def deals(options = {})
      options = update_by_expire_time options
      if deals_not_latest?(options)
        uniq = !!options.delete(:uniq)
        @rsqoot_deals = get('deals', options, SqootDeal) || []
        @rsqoot_deals = @rsqoot_deals.deals.map(&:deal) unless @rsqoot_deals.empty?
        @rsqoot_deals = uniq_deals(@rsqoot_deals) if uniq
      end
      logger(uri: sqoot_query_uri, records: @rsqoot_deals, type: 'deals', opts: options)
      @rsqoot_deals
    end

def deals ( options = { } ) options = update_by_expire_time options if deals_not_latest? ( options ) uniq = ! ! options . delete ( :uniq ) @rsqoot_deals = get ( 'deals' , options , SqootDeal ) || [ ] @rsqoot_deals = @rsqoot_deals . deals . map ( & :deal ) unless @rsqoot_deals . empty? @rsqoot_deals = uniq_deals ( @rsqoot_deals ) if uniq end logger ( uri : sqoot_query_uri , records : @rsqoot_deals , type : 'deals' , opts : options ) @rsqoot_deals end

Retrieve a list of deals based on the following parameters

 @param [String] query (Search deals by title, description, fine print, merchant name, provider, and category.)
 @param [String] location (Limit results to a particular area. We'll resolve whatever you pass us (including an IP address) to coordinates and search near there.)
 @param [Integer] radius (Measured in miles. Defaults to 10.)
 @param [Integer] page (Which page of result to return. Default to 1.)
 @param [Integer] per_page (Number of results to return at once. Defaults to 10.)


def deal(id, options = {})
      options = update_by_expire_time options
      if deal_not_latest?(id)
        @rsqoot_deal = get("deals/#{id}", options, SqootDeal)
        @rsqoot_deal = @rsqoot_deal.deal if @rsqoot_deal
      end
      logger(uri: sqoot_query_uri, records: [@rsqoot_deal], type: 'deal', opts: options)
      @rsqoot_deal
    end

def deal ( id , options = { } ) options = update_by_expire_time options if deal_not_latest? ( id ) @rsqoot_deal = get ( "deals/#{id}" , options , SqootDeal ) @rsqoot_deal = @rsqoot_deal . deal if @rsqoot_deal end logger ( uri : sqoot_query_uri , records : [ @rsqoot_deal ] , type : 'deal' , opts : options ) @rsqoot_deal end


def total_sqoot_deals(options = {})
      @total_deals  ||= []
      @cached_pages ||= []
      page = options[:page] || 1
      check_query_change options
      unless page_cached? page
        @total_deals += deals(options)
        @total_deals.uniq!
        @cached_pages << page.to_s
        @cached_pages.uniq!
      end
      @total_deals
    end

def total_sqoot_deals ( options = { } ) @total_deals ||= [ ] @cached_pages ||= [ ] page = options [ :page ] || 1 check_query_change options unless page_cached? page @total_deals += deals ( options ) @total_deals . uniq! @cached_pages << page . to_s @cached_pages . uniq! end @total_deals end


def uniq_deals(deals = [])
      titles = deals.map(&:title).uniq
      titles.map do |title|
        deals.map do |deal|
          deal if deal.try(:title) == title
        end.compact.last
      end.flatten
    end

def uniq_deals ( deals = [ ] ) titles = deals . map ( & :title ) . uniq titles . map do | title | deals . map do | deal | deal if deal . try ( :title ) == title end . compact . last end . flatten end

Uniq deals from Sqoot, because there are some many duplicated deals
 with different ids
 Simplely distinguish them by their titles

Uniq deals from Sqoot because there are some many duplicated deals with different ids Simplely distinguish them by their titles


def load_cookies(file)
      now = ::Time.now

      io = case file
      when String
        open(file)
      else
        file
      end

      io.each_line do |line|
        line.chomp!
        line.gsub!(/#.+/, '')
        fields = line.split("\t")

        next if fields.length != 7

        name, value, domain, for_domain, path, secure, version = fields[5], fields[6],
          fields[0], (fields[1] == "TRUE"), fields[2], (fields[3] == "TRUE"), 0

        expires_seconds = fields[4].to_i
        expires = (expires_seconds == 0) ? nil : ::Time.at(expires_seconds)
        next if expires and (expires < now)

        cookies.add(name, value, domain: domain, path: path, expires: expires, secure: secure)
      end

      io.close if String === file

      self
    end

def load_cookies ( file ) now = :: Time . now io = case file when String open ( file ) else file end io . each_line do | line | line . chomp! line . gsub! ( / / , '' ) fields = line . split ( "\t" ) next if fields . length != 7 name , value , domain , for_domain , path , secure , version = fields [ 5 ] , fields [ 6 ] , fields [ 0 ] , ( fields [ 1 ] == "TRUE" ) , fields [ 2 ] , ( fields [ 3 ] == "TRUE" ) , 0 expires_seconds = fields [ 4 ] . to_i expires = ( expires_seconds == 0 ) ? nil : :: Time . at ( expires_seconds ) next if expires and ( expires < now ) cookies . add ( name , value , domain : domain , path : path , expires : expires , secure : secure ) end io . close if String === file self end

Read cookies from Mozilla cookies.txt-style IO stream

 @param file [IO,String]

Read cookies from Mozilla cookies . txt - style IO stream


def dump_cookies(file)
      io = case file
      when String
        open(file, "w")
      else
        file
      end

      cookies.to_a.each do |cookie|
        io.puts([
          cookie[:domain],
          "FALSE", # for_domain
          cookie[:path],
          cookie[:secure] ? "TRUE" : "FALSE",
          cookie[:expires].to_i.to_s,
          cookie[:name],
          cookie[:value]
        ].join("\t"))
      end

      io.close if String === file

      self
    end

def dump_cookies ( file ) io = case file when String open ( file , "w" ) else file end cookies . to_a . each do | cookie | io . puts ( [ cookie [ :domain ] , "FALSE" , cookie [ :path ] , cookie [ :secure ] ? "TRUE" : "FALSE" , cookie [ :expires ] . to_i . to_s , cookie [ :name ] , cookie [ :value ] ] . join ( "\t" ) ) end io . close if String === file self end

Write cookies to Mozilla cookies.txt-style IO stream

 @param file [IO,String]

Write cookies to Mozilla cookies . txt - style IO stream


def set2(selector, value=nil)
      elem = element(xpath: selector).to_subtype

      case elem
      when Watir::Radio
        elem.set
      when Watir::Select
        elem.select value
      when Watir::Input
        elem.set value
      when Watir::TextArea
        elem.set value
      else
        elem.click
      end
    end

def set2 ( selector , value = nil ) elem = element ( xpath : selector ) . to_subtype case elem when Watir :: Radio elem . set when Watir :: Select elem . select value when Watir :: Input elem . set value when Watir :: TextArea elem . set value else elem . click end end

quick set value.

 @example

  form = browser.form(id: "foo")
  form.set2("//input[@name='value']", "hello")
  form.set2("//input[@name='check']", true)
  form.set2("//select[@name='foo']", "Bar")
  form.set2("//textarea[@name='foo']", "bar")


def update_by_expire_time(options = {})
      @expired_in = options[:expired_in] if options[:expired_in].present?
      time = Time.now.to_i / expired_in.to_i
      options.merge(expired_in: time)
    end

def update_by_expire_time ( options = { } ) @expired_in = options [ :expired_in ] if options [ :expired_in ] . present? time = Time . now . to_i / expired_in . to_i options . merge ( expired_in : time ) end

Add expired time functionality to this gem
 By default is 1.hour, and can be replaced anywhere

Add expired time functionality to this gem By default is 1 . hour and can be replaced anywhere


def get(options={})
    uri = new_uri
    params = merge_params(options)
    uri.query = URI.encode_www_form(params)

    Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
      request = Net::HTTP::Get.new(uri)
      response = http.request(request)
      unless response.is_a?(Net::HTTPSuccess)
        raise "#{response.code} #{response.message}\n#{response.body}"
      end
      return response.body
    end
  end

Make a GET API call with the current path value and @options.
 Return a JSON string if successful, otherwise an Exception


def images(id, tenant_id)
      if id.nil?
        return get_request(address(tenant_id, "images/detail"), @token)
      else
        return get_request(address(tenant_id, "images/" + id), @token)
      end
    end

def images ( id , tenant_id ) if id . nil? return get_request ( address ( tenant_id , "images/detail" ) , @token ) else return get_request ( address ( tenant_id , "images/" + id ) , @token ) end end

No ID provided - Lists details for available images.
 ID provided - Shows the image details as headers and the image binary in the body.

No ID provided - Lists details for available images . ID provided - Shows the image details as headers and the image binary in the body .


def image_create(name, disk_format, container_format, create_image, tenant_id)
      data = {
        :name => name,
        :disk_format => disk_format,
        :container_format => container_format
      }
      unless create_image.nil?
        data[:create_image] = create_image
      end

      post_request(address(tenant_id, "images"), data, @token)
    end

def image_create ( name , disk_format , container_format , create_image , tenant_id ) data = { :name => name , :disk_format => disk_format , :container_format => container_format } unless create_image . nil? data [ :create_image ] = create_image end post_request ( address ( tenant_id , "images" ) , data , @token ) end


def replace_memberships(id, memberships, tenant_id)
      data = {
        :memberships => memberships
      }
      put_request(address(tenant_id, "images/" + id + "/members"), data, @token)
    end

def replace_memberships ( id , memberships , tenant_id ) data = { :memberships => memberships } put_request ( address ( tenant_id , "images/" + id + "/members" ) , data , @token ) end

Replaces the membership list for an image.
 @param memberships List of memberships in format [{'member_id': 'tenant1', 'can_share': 'false'}]

Replaces the membership list for an image .


def add_member(id, member_id, can_share, tenant_id)
      if can_share.nil?
        data = {
          :member => {:can_share => false}
        }
      else
        data = {
          :member => {:can_share => can_share}
        }
      end
      put_request(address(tenant_id, "images/" + id + "/members/" + member_id), data, @token)
    end

def add_member ( id , member_id , can_share , tenant_id ) if can_share . nil? data = { :member => { :can_share => false } } else data = { :member => { :can_share => can_share } } end put_request ( address ( tenant_id , "images/" + id + "/members/" + member_id ) , data , @token ) end

Adds a member to an image.
 @param member_id The member to be added
 @param can_share Optional boolean specifiying can_share value. Will default to false.


def mkdir(dir, owner: nil, mode: nil)
      FileUtils.mkdir_p(dir, verbose: verbose?)
      chown(dir, owner) if owner
      chmod(dir, mode) if mode
    end

def mkdir ( dir , owner : nil , mode : nil ) FileUtils . mkdir_p ( dir , verbose : verbose? ) chown ( dir , owner ) if owner chmod ( dir , mode ) if mode end

Like mkdir -p +dir+. If +owner+ is specified, the directory will be
 chowned to owner. If +mode+ is specified, the directory will be chmodded
 to mode. Like all file commands, the operation will be printed out if
 verbose?.

Like mkdir - p + dir + . If + owner + is specified the directory will be chowned to owner . If + mode + is specified the directory will be chmodded to mode . Like all file commands the operation will be printed out if verbose? .


def cp(src, dst, mkdir: false, owner: nil, mode: nil)
      mkdir_if_necessary(File.dirname(dst)) if mkdir
      FileUtils.cp_r(src, dst, preserve: true, verbose: verbose?)
      chown(dst, owner) if owner && !File.symlink?(dst)
      chmod(dst, mode) if mode
    end

def cp ( src , dst , mkdir : false , owner : nil , mode : nil ) mkdir_if_necessary ( File . dirname ( dst ) ) if mkdir FileUtils . cp_r ( src , dst , preserve : true , verbose : verbose? ) chown ( dst , owner ) if owner && ! File . symlink? ( dst ) chmod ( dst , mode ) if mode end

Like cp -pr +src+ +dst. If +mkdir+ is true, the dst directoy will be
 created if necessary before the copy. If +owner+ is specified, the
 directory will be chowned to owner. If +mode+ is specified, the
 directory will be chmodded to mode. Like all file commands, the
 operation will be printed out if verbose?.

Like cp - pr + src + + dst . If + mkdir + is true the dst directoy will be created if necessary before the copy . If + owner + is specified the directory will be chowned to owner . If + mode + is specified the directory will be chmodded to mode . Like all file commands the operation will be printed out if verbose? .


def mv(src, dst, mkdir: false)
      mkdir_if_necessary(File.dirname(dst)) if mkdir
      FileUtils.mv(src, dst, verbose: verbose?)
    end

def mv ( src , dst , mkdir : false ) mkdir_if_necessary ( File . dirname ( dst ) ) if mkdir FileUtils . mv ( src , dst , verbose : verbose? ) end

Like mv +src+ +dst. If +mkdir+ is true, the dst directoy will be created
 if necessary before the copy. Like all file commands, the operation will
 be printed out if verbose?.

Like mv + src + + dst . If + mkdir + is true the dst directoy will be created if necessary before the copy . Like all file commands the operation will be printed out if verbose? .


def ln(src, dst)
      FileUtils.ln_sf(src, dst, verbose: verbose?)
    rescue Errno::EEXIST => e
      # It's a race - this can occur because ln_sf removes the old
      # dst, then creates the symlink. Raise if they don't match.
      raise e if !(File.symlink?(dst) && src == File.readlink(dst))
    end

def ln ( src , dst ) FileUtils . ln_sf ( src , dst , verbose : verbose? ) rescue Errno :: EEXIST => e raise e if ! ( File . symlink? ( dst ) && src == File . readlink ( dst ) ) end

Like ln -sf +src+ +dst. The command will be printed out if
 verbose?.

Like ln - sf + src + + dst . The command will be printed out if verbose? .


def chmod(file, mode)
      return if File.stat(file).mode == mode
      FileUtils.chmod(mode, file, verbose: verbose?)
    end

def chmod ( file , mode ) return if File . stat ( file ) . mode == mode FileUtils . chmod ( mode , file , verbose : verbose? ) end

Like chmod mode file. Like all file commands, the operation will be
 printed out if verbose?.

Like chmod mode file . Like all file commands the operation will be printed out if verbose? .


def rm_and_mkdir(dir)
      raise "don't do this" if dir == ""
      FileUtils.rm_rf(dir, verbose: verbose?)
      mkdir(dir)
    end

def
rm_and_mkdir
(
dir
)
raise
"don't do this"
if
dir
==
""
FileUtils
.
rm_rf
(
dir
,
verbose
:
verbose?
)
mkdir
(
dir
)
end

Like rm -rf && mkdir -p. Like all file commands, the operation will be
 printed out if verbose?.

Like rm - rf && mkdir - p . Like all file commands the operation will be printed out if verbose? .


def copy_metadata(src, dst)
      stat = File.stat(src)
      File.chmod(stat.mode, dst)
      File.utime(stat.atime, stat.mtime, dst)
    end

def copy_metadata ( src , dst ) stat = File . stat ( src ) File . chmod ( stat . mode , dst ) File . utime ( stat . atime , stat . mtime , dst ) end

Copy mode, atime and mtime from +src+ to +dst+. This one is rarely used
 and doesn't echo.

Copy mode atime and mtime from + src + to + dst + . This one is rarely used and doesn t echo .


def atomic_write(path)
      tmp = Tempfile.new(File.basename(path))
      yield(tmp)
      tmp.close
      chmod(tmp.path, 0o644)
      mv(tmp.path, path)
    ensure
      rm_if_necessary(tmp.path)
    end

def atomic_write ( path ) tmp = Tempfile . new ( File . basename ( path ) ) yield ( tmp ) tmp . close chmod ( tmp . path , 0o644 ) mv ( tmp . path , path ) ensure rm_if_necessary ( tmp . path ) end

Atomically write to +path+. An open temp file is yielded.

Atomically write to + path + . An open temp file is yielded .


def handle_requests
      until @requestmq.empty?
        request = @requestmq.deq(true)
        begin
          request.response = @app.call(request.env)
        rescue Exception => e
          request.exception = e
        ensure
          body = request.response.try(:last)
          body.close  if body.respond_to? :close
        end
      end
    end

def handle_requests until @requestmq . empty? request = @requestmq . deq ( true ) begin request . response = @app . call ( request . env ) rescue Exception => e request . exception = e ensure body = request . response . try ( :last ) body . close if body . respond_to? :close end end end

Should be run by another thread - respond to all queued requests


def configfile_hash

      config  = {}
      begin
        json    = File.read(configfile)
        config  = JSON.parse(json)
      rescue Errno::ENOENT
        # depending on whether the instance has been saved or not, we may not
        # yet have a configfile - allow to proceed
        @logger.debug "#{configfile} does not exist"
        @force_save = true
      rescue JSON::ParserError
        # swallow parse errors so that we can destroy and recreate automatically
        @logger.debug "JSON parse error in #{configfile}"
        @force_save = true
      end
      config
    end

def
configfile_hash
config
=
{
}
begin
json
=
File
.
read
(
configfile
)
config
=
JSON
.
parse
(
json
)
rescue
Errno
::
ENOENT
@logger
.
debug
"#{configfile} does not exist"
@force_save
=
true
rescue
JSON
::
ParserError
@logger
.
debug
"JSON parse error in #{configfile}"
@force_save
=
true
end
config
end

return a hash of the configfile or empty hash if error encountered


def email_addresses(text)
      text.gsub(@regex[:mail]) do
        text = $&
        if auto_linked?($`, $')
          text
        else
          display_text = (block_given?) ? yield(text) : text
          # mail_to text, display_text
          "#{display_text}"
        end
      end
    end

Turns all email addresses into clickable links.  If a block is given,
 each email is yielded and the result is used as the link text.

Turns all email addresses into clickable links . If a block is given each email is yielded and the result is used as the link text .


def plural(rule, replacement)
      @uncountables.delete(rule) if rule.is_a?(String)
      @uncountables.delete(replacement)
      @plurals.insert(0, [rule, replacement])
    end

def plural ( rule , replacement ) @uncountables . delete ( rule ) if rule . is_a? ( String ) @uncountables . delete ( replacement ) @plurals . insert ( 0 , [ rule , replacement ] ) end

Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
 The replacement should always be a string that may include references to the matched data from the rule.

Specifies a new pluralization rule and its replacement . The rule can either be a string or a regular expression . The replacement should always be a string that may include references to the matched data from the rule .


def singular(rule, replacement)
      @uncountables.delete(rule) if rule.is_a?(String)
      @uncountables.delete(replacement)
      @singulars.insert(0, [rule, replacement])
    end

def singular ( rule , replacement ) @uncountables . delete ( rule ) if rule . is_a? ( String ) @uncountables . delete ( replacement ) @singulars . insert ( 0 , [ rule , replacement ] ) end

Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
 The replacement should always be a string that may include references to the matched data from the rule.

Specifies a new singularization rule and its replacement . The rule can either be a string or a regular expression . The replacement should always be a string that may include references to the matched data from the rule .


def irregular(singular, plural)
      @uncountables.delete(singular)
      @uncountables.delete(plural)
      if singular[0,1].upcase == plural[0,1].upcase
        plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
        singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
      else
        plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
        plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
        singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1])
        singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1])
      end
    end

Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
 for strings, not regular expressions. You simply pass the irregular in singular and plural form.

 Examples:
   irregular 'octopus', 'octopi'
   irregular 'person', 'people'

Specifies a new irregular that applies to both pluralization and singularization at the same time . This can only be used for strings not regular expressions . You simply pass the irregular in singular and plural form .


def execute
      raise errors.to_sentences unless valid?

      # default failing command
      result = false

      # protect command from recursion
      mutex = Mutagem::Mutex.new('revenc.lck')
      lock_successful = mutex.execute do
        result = system_cmd(cmd)
      end

      raise "action failed, lock file present" unless lock_successful
      result
    end

def
execute
raise
errors
.
to_sentences
unless
valid?
result
=
false
mutex
=
Mutagem
::
Mutex
.
new
(
'revenc.lck'
)
lock_successful
=
mutex
.
execute
do
result
=
system_cmd
(
cmd
)
end
raise
"action failed, lock file present"
unless
lock_successful
result
end

run the action if valid and return true if successful


def output
      opts = options
      if opts.format
        FileUtils.mkdir_p opts.output_dir
        formatted_output
      end
      @results.clear
    end

def output opts = options if opts . format FileUtils . mkdir_p opts . output_dir formatted_output end @results . clear end

Output the results based on the requested output format


def run
      while @jobs.length > 0 do
        # do a warm up run first with the highest connection rate
        @current_job = @jobs.pop
        @current_rate = @current_job.high_rate.to_i
        httperf true

        (@current_job.low_rate.to_i..@current_job.high_rate.to_i).
            step(@current_job.rate_step.to_i) do |rate|
          @current_rate = rate
          httperf
        end
        output
      end
    end

def run while @jobs . length > 0 do @current_job = @jobs . pop @current_rate = @current_job . high_rate . to_i httperf true ( @current_job . low_rate . to_i .. @current_job . high_rate . to_i ) . step ( @current_job . rate_step . to_i ) do | rate | @current_rate = rate httperf end output end end

Run httperf from low_rate to high_rate, stepping by rate_step

Run httperf from low_rate to high_rate stepping by rate_step


def authenticate(username, password, tenant = nil)
                  data = {
                          "auth" => {
                                  "passwordCredentials" => {
                                          "username" => username,
                                          "password" => password
                                  }
                          }
                  }
                  unless tenant.nil?
                          data["auth"]["tenantName"] = tenant
                  end
                  @data = post_request(address("/tokens"), data, @token)
          end

def authenticate ( username , password , tenant = nil ) data = { "auth" => { "passwordCredentials" => { "username" => username , "password" => password } } } unless tenant . nil? data [ "auth" ] [ "tenantName" ] = tenant end @data = post_request ( address ( "/tokens" ) , data , @token ) end

Authenticate via keystone, unless a token and tenant are defined then a unscoped
 token is returned with all associated data and stored in the @data variable.
 Does not return anything, but all data is accessible through accessor methods.

Authenticate via keystone unless a token and tenant are defined then a unscoped token is returned with all associated data and stored in the


def add_to_services(name, type, description)
                  data = {
                          'OS-KSADM:service' => {
                                   'name' => name,
                                   'type' => type,
                                   'description' => description
                          }
                  }
                  return post_request(address("/OS-KSADM/services"), data, token())
          end

def add_to_services ( name , type , description ) data = { 'OS-KSADM:service' => { 'name' => name , 'type' => type , 'description' => description } } return post_request ( address ( "/OS-KSADM/services" ) , data , token ( ) ) end

Add a service to the keystone services directory


def add_endpoint(region, service_id, publicurl, adminurl, internalurl)
                  data = {
                          'endpoint' => {
                                  'region' => region,
                                  'service_id' => service_id,
                                  'publicurl' => publicurl,
                                  'adminurl' => adminurl,
                                  'internalurl' => internalurl
                          }
                  }
                  return post_request(address("/endpoints"), data, token())
          end

def add_endpoint ( region , service_id , publicurl , adminurl , internalurl ) data = { 'endpoint' => { 'region' => region , 'service_id' => service_id , 'publicurl' => publicurl , 'adminurl' => adminurl , 'internalurl' => internalurl } } return post_request ( address ( "/endpoints" ) , data , token ( ) ) end


def get_endpoints(token = nil)
                  if token.nil?
                          return get_request(address("/endpoints"), token())
                  else
                          return get_request(address("/tokens/#{token}/endpoints"), token())
                  end
          end

def get_endpoints ( token = nil ) if token . nil? return get_request ( address ( "/endpoints" ) , token ( ) ) else return get_request ( address ( "/tokens/#{token}/endpoints" ) , token ( ) ) end end


def disable_method(method_name, message = nil)
      disabled_methods[method_name] ||= DisabledMethod.new(self, method_name, message)
      disabled_methods[method_name].disable!
    end

def disable_method ( method_name , message = nil ) disabled_methods [ method_name ] ||= DisabledMethod . new ( self , method_name , message ) disabled_methods [ method_name ] . disable! end

Disables an instance method.

 @param [Symbol,String]  method_name   The name of the method to disable.
 @param [String]         message       An error message. Defaults to "Class#method is disabled".


def to_proc
      disabled_method = self

      # This proc will be evaluated with "self" set to the original object.
      Proc.new do |*args, &block|
        disabled_method.execute(self, *args, &block)
      end
    end

def to_proc disabled_method = self Proc . new do | * args , & block | disabled_method . execute ( self , * args , & block ) end end

Returns a Proc that acts as a replacement for the disabled method.

Returns a Proc that acts as a replacement for the disabled method .


def execute(object, *args, &block)
      if disabled?
        raise NoMethodError, message
      else
        object.send(aliased_name, *args, &block)
      end
    end

def execute ( object , * args , & block ) if disabled? raise NoMethodError , message else object . send ( aliased_name , * args , & block ) end end

The replacement for the original method. It will raise a NoMethodError if the method is
 disabled. Otherwise, it will execute the original method.

 @param [Object] object  The "self" object of the method being called.
 @param [Array]  args    The arguments that were passed to the method.
 @param [Proc]   block   The block that was passed to the method.

 @return Whatever the original method returns.

The replacement for the original method . It will raise a NoMethodError if the method is disabled . Otherwise it will execute the original method .


def alias_method!
      klass.send(:define_method, replacement_name, &self)
      klass.send(:alias_method, aliased_name, method_name)
      klass.send(:alias_method, method_name, replacement_name)
    end

def alias_method! klass . send ( :define_method , replacement_name , & self ) klass . send ( :alias_method , aliased_name , method_name ) klass . send ( :alias_method , method_name , replacement_name ) end

Replaces the original implementation of the method with an implementation that allows
 disabling.

Replaces the original implementation of the method with an implementation that allows disabling .


def secret_to_public(secret, form=:byte)
      publickey = p_secret_to_public( change_argument_format(secret, form) )
      return change_result_format( publickey, form )
    end

def secret_to_public ( secret , form = :byte ) publickey = p_secret_to_public ( change_argument_format ( secret , form ) ) return change_result_format ( publickey , form ) end


def point_equal(pa, pb)
      # x1 / z1 == x2 / z2  <==>  x1 * z2 == x2 * z1
      return false if (pa[0] * pb[2] - pb[0] * pa[2]) % @@p != 0
      return false if (pa[1] * pb[2] - pb[1] * pa[2]) % @@p != 0
      return true
    end

def point_equal ( pa , pb ) return false if ( pa [ 0 ] * pb [ 2 ] - pb [ 0 ] * pa [ 2 ] ) % @@p != 0 return false if ( pa [ 1 ] * pb [ 2 ] - pb [ 1 ] * pa [ 2 ] ) % @@p != 0 return true end


def recover_x(y, sign)
      return nil if y >= @@p
      # x2 means x^2
      x2 = (y*y-1) * modp_inv(@@d*y*y+1)
      # when x2==0 and sign!=0, these combination of arguments is illegal
      if x2.equal? 0 then
        unless sign.equal? 0 then
          return nil
        else
          return 0
        end
      end
      # Compute square root of x2
      x = pow_mod(x2 , ((@@p+3) / 8) , @@p)
      x = x * @@modp_sqrt_m1 % @@p unless ((x*x - x2) % @@p).equal? 0
      return nil unless ((x*x - x2) % @@p).equal? 0
      x = @@p - x  unless (x & 1).equal? sign
      return x
    end

def recover_x ( y , sign ) return nil if y >= @@p x2 = ( y * y - 1 ) * modp_inv ( @@d * y * y + 1 ) if x2 . equal? 0 then unless sign . equal? 0 then return nil else return 0 end end x = pow_mod ( x2 , ( ( @@p + 3 ) / 8 ) , @@p ) x = x * @@modp_sqrt_m1 % @@p unless ( ( x * x - x2 ) % @@p ) . equal? 0 return nil unless ( ( x * x - x2 ) % @@p ) . equal? 0 x = @@p - x unless ( x & 1 ) . equal? sign return x end

region point manipulation
 Compute corresponding x-coordinate, with low bit corresponding to
 sign, or return nil on failure

region point manipulation Compute corresponding x - coordinate with low bit corresponding to sign or return nil on failure


def point_decompress(s)
      # check argument
      raise ArgumentError , "Invalid input length for decompression" unless s.length.equal? 32

      y = int_form_bytes(s)
      sign = y >> 255
      y &= (1 << 255) - 1
      x = recover_x(y, sign)
      if x.nil? then
        return nil
      else
        return [x, y, 1, x*y % @@p]
      end
    end

decompress point that is compressed into 32bytes


def p_secret_to_public(secret)
      expanded = secret_expand(secret)
      a = expanded.first
      return point_compress(point_mul(a, @@G))
    end

def p_secret_to_public ( secret ) expanded = secret_expand ( secret ) a = expanded . first return point_compress ( point_mul ( a , @@G ) ) end

public_keyKey = aG
 "a" is generated form a secret

public_keyKey = aG a is generated form a secret


def part(name)
      parts.select {|p| p.name.downcase == name.to_s.downcase }.first
    end

def part ( name ) parts . select { | p | p . name . downcase == name . to_s . downcase } . first end

get part by its name
 param
 @return Part