def help
      puts
      print "Dev".green
      print " - available commands:\n"
      puts

      print "\tversion\t\t".limegreen
        print "Prints current version.\n"
        puts

      print "\tfeature\t\t".limegreen
        print "Opens or closes a feature for the current app.\n"
        print "\t\t\tWarning: the app is determined from the current working directory!\n"
        print "\t\t\tExample: "
        print "dev feature open my-new-feature".springgreen
        print " (opens a new feature for the current app)"
        print ".\n"
        print "\t\t\tExample: "
        print "dev feature close my-new-feature".springgreen
        print " (closes a developed new feature for the current app)"
        print ".\n"
        puts

      print "\thotfix\t\t".limegreen
        print "Opens or closes a hotfix for the current app.\n"
        print "\t\t\tWarning: the app is determined from the current working directory!\n"
        print "\t\t\tExample: "
        print "dev hotfix open 0.2.1".springgreen
        print " (opens a new hotfix for the current app)"
        print ".\n"
        print "\t\t\tExample: "
        print "dev hotfix close 0.2.1".springgreen
        print " (closes a developed new hotfix for the current app)"
        print ".\n"
        puts

      print "\trelease\t\t".limegreen
        print "Opens or closes a release for the current app.\n"
        print "\t\t\tWarning: the app is determined from the current working directory!\n"
        print "\t\t\tExample: "
        print "dev release open 0.2.0".springgreen
        print " (opens a new release for the current app)"
        print ".\n"
        print "\t\t\tExample: "
        print "dev release close 0.2.0".springgreen
        print " (closes a developed new release for the current app)"
        print ".\n"
        puts

      print "\tpull\t\t".limegreen
        print "Pulls specified app's git repository, or pulls all apps if none are specified.\n"
        print "\t\t\tWarning: the pulled branch is the one the app is currently on!\n"
        print "\t\t\tExample: "
        print "dev pull [myapp]".springgreen
        print ".\n"
        puts

      print "\tpush\t\t".limegreen
        print "Commits and pushes the specified app.\n"
        print "\t\t\tWarning: the pushed branch is the one the app is currently on!\n"
        print "\t\t\tExample: "
        print "dev push myapp \"commit message\"".springgreen
        print ".\n"
        puts

      print "\ttest\t\t".limegreen
        print "Runs the app's test suite. Tests must be written with rspec.\n"
        print "\t\t\tIt is possibile to specify which app's test suite to run.\n"
        print "\t\t\tIf nothing is specified, all main app's test suites are run.\n"
        print "\t\t\tExample: "
        print "dev test mymainapp myengine".springgreen
        print " (runs tests for 'mymainapp' and 'myengine')"
        print ".\n"
        print "\t\t\tExample: "
        print "dev test".springgreen
        print " (runs tests for all main apps and engines within this project)"
        print ".\n"
        puts
    end

Stampa i comandi possibili.

 @return [nil]


def add(objects, timestamp = @time)
      unless objects.kind_of? Array
        objects = [ objects ]
      end
      objects.each do |object|
        if object.instance_of? Hash
          timestamp = object[:ts] || 0
          object = object[:val]
        end
        token = prepare_token(object, timestamp)
        timestamp = token.timestamp
        if timestamp > @time
          add_to_waiting token
        else
          add_token token
        end
      end
    end

def add ( objects , timestamp = @time ) unless objects . kind_of? Array objects = [ objects ] end objects . each do | object | if object . instance_of? Hash timestamp = object [ :ts ] || 0 object = object [ :val ] end token = prepare_token ( object , timestamp ) timestamp = token . timestamp if timestamp > @time add_to_waiting token else add_token token end end end

Create a new TimedHashMarking
 Creates token with +object+ as its value and adds it to the marking.
 if no timestamp is given, current time will be used.

Create a new TimedHashMarking Creates token with + object + as its value and adds it to the marking . if no timestamp is given current time will be used .


def time=(time)
      if time < @time
        raise InvalidTime.new("You are trying to put back clock from #{@time} back to #{time}")
      end
      @time = time
      @waiting.keys.sort.each do |timestamp|
        if timestamp > @time
          @next_time = timestamp
          break
        end
        @waiting[timestamp].each { |token| add_token token }
        @waiting.delete timestamp
      end
      @next_time = 0 if @waiting.empty?
      @time
    end

Set current time for the marking.
 This will cause moving tokens from waiting to active list.
 Putting clock back will cause error.

Set current time for the marking . This will cause moving tokens from waiting to active list . Putting clock back will cause error .


def send_message data, binary=false
      if established?
        unless @closing
          @socket.send_data(@encoder.encode(data.to_s, binary ? BINARY_FRAME : TEXT_FRAME))
        end
      else
        raise WebSocketError.new "can't send on a closed channel"
      end
    end

def
send_message
data
,
binary
=
false
if
established?
unless
@closing
@socket
.
send_data
(
@encoder
.
encode
(
data
.
to_s
,
binary
BINARY_FRAME
:
TEXT_FRAME
)
)
end
else
raise
WebSocketError
.
new
"can't send on a closed channel"
end
end

Send a message to the remote host

 data - The string contents of your message

 Examples

   ws.onping do |data|
   end

 Returns nothing


def post(options)
    uri = new_uri
    params = merge_params(options)
    response = Net::HTTP.post_form(uri, params)
    unless response.is_a?(Net::HTTPSuccess)
      raise "#{response.code} #{response.message}\n#{response.body}"
    end
    response.body
  end

== instance methods
 Make a POST API call with the current path value and @options.
 Return a JSON string if successful, otherwise an Exception
   TODO - test AuthenticatedClient.post()


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

    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Delete.new(uri) # uri or uri.request_uri?
    response = http.request(request)
    unless response.is_a?(Net::HTTPSuccess)
      raise "#{response.code} #{response.message}\n#{response.body}"
    end
    true
  end

Make a DELETE API call with the current path value and @options.
 Return true if successful, otherwise an Exception
   TODO - test AuthenticatedClient.delete()


def instance_metadata(name)
      instance = instance(name)
      config = {}
      # annotate the raw config hash with data for puppet (and humans...)
      if instance.configured?
        config = instance.configfile_hash
        config["ensure"] = :present
      else
        # VM missing or damaged
        config["ensure"] = :absent
      end
      config["name"] = name

      config
    end

Return a has representing the named instance.  This is suitable for Puppet
 type and provider, or you can use the returned info for whatever you like

Return a has representing the named instance . This is suitable for Puppet type and provider or you can use the returned info for whatever you like


def instances_metadata()
      instance_wildcard = File.join(@vagrant_vm_dir, "*", ::Vagrantomatic::Instance::VAGRANTFILE)
      instances = {}
      Dir.glob(instance_wildcard).each { |f|
        elements = f.split(File::SEPARATOR)
        # /var/lib/vagrantomatic/mycoolvm/Vagrantfile
        # -----------------------^^^^^^^^------------
        name = elements[elements.size - 2]

        instances[name] = instance_metadata(name)
      }

      instances
    end


def csv_read(path)
      lines = begin
        if path =~ /\.gz$/
          Zlib::GzipReader.open(path) do |f|
            CSV.new(f).read
          end
        else
          CSV.read(path)
        end
      end
      keys = lines.shift.map(&:to_sym)
      klass = Struct.new(*keys)
      lines.map { |i| klass.new(*i) }
    end

def csv_read ( path ) lines = begin if path =~ / \. / Zlib :: GzipReader . open ( path ) do | f | CSV . new ( f ) . read end else CSV . read ( path ) end end keys = lines . shift . map ( :to_sym ) klass = Struct . new ( keys ) lines . map { | i | klass . new ( i ) } end

Read a csv from +path+. Returns an array of Structs, using the keys from
 the csv header row.

Read a csv from + path + . Returns an array of Structs using the keys from the csv header row .


def csv_write(path, rows, cols: nil)
      atomic_write(path) do |tmp|
        CSV.open(tmp.path, "wb") { |f| csv_write0(f, rows, cols: cols) }
      end
    end

def csv_write ( path , rows , cols : nil ) atomic_write ( path ) do | tmp | CSV . open ( tmp . path , "wb" ) { | f | csv_write0 ( f , rows , cols : cols ) } end end

Write +rows+ to +path+ as csv. Rows can be an array of hashes, Structs,
 OpenStructs, or anything else that responds to to_h. The keys from the
 first row are used as the csv header. If +cols+ is specified, it will be
 used as the column keys instead.

Write + rows + to + path + as csv . Rows can be an array of hashes Structs OpenStructs or anything else that responds to to_h . The keys from the first row are used as the csv header . If + cols + is specified it will be used as the column keys instead .


def csv_to_s(rows, cols: nil)
      string = ""
      f = CSV.new(StringIO.new(string))
      csv_write0(f, rows, cols: cols)
      string
    end

def csv_to_s ( rows , cols : nil ) string = "" f = CSV . new ( StringIO . new ( string ) ) csv_write0 ( f , rows , cols : cols ) string end

Returns a string containing +rows+ as a csv. Similar to csv_write.

Returns a string containing + rows + as a csv . Similar to csv_write .


def add_value(name, type, subtype = nil)
      if type.class == RustyJson::RustStruct || subtype.class == RustyJson::RustStruct
        if type.class == RustyJson::RustStruct
          t = type
          type = type.name
          struct = t
        elsif subtype.class == RustyJson::RustStruct
          s = subtype
          subtype = subtype.name
          struct = s
        end
        @structs << struct
        RustStruct.add_type(struct.name, struct.name)
      end
      @values[name] = [type, subtype]
      true
    end

def add_value ( name , type , subtype = nil ) if type . class == RustyJson :: RustStruct || subtype . class == RustyJson :: RustStruct if type . class == RustyJson :: RustStruct t = type type = type . name struct = t elsif subtype . class == RustyJson :: RustStruct s = subtype subtype = subtype . name struct = s end @structs << struct RustStruct . add_type ( struct . name , struct . name ) end @values [ name ] = [ type , subtype ] true end

Add Value is how we add keys to the resulting Struct
 We need a name and a type, and potentially a subtype

 For example:
 types could be String, Fixnum, or Array
 If the tyoe is Array, then we need the subtype of the array,
 is it an array of integers or strings?

 @param name [String] what is this key in the struct
 @param type [Class] What typs are we
 @param subtype [Class] What typs are we

 @return true

Add Value is how we add keys to the resulting Struct We need a name and a type and potentially a subtype


def rotate(hsh)
      current_ec2, new_ec2 = hsh.first

      cur_instances = EC2.by_tags("Name" => current_ec2.to_s)
      new_instances = EC2.by_tags("Name" => new_ec2.to_s)

      register_and_wait new_instances
      deregister        cur_instances
    end


def wait_for_state(instances, exp_state)

      time = 0
      all_good = false

      loop do
        all_good = instances.all? do |i|
          state = i.elb_health[:state]
          puts "#{i.id}: #{state}"

          exp_state == state
        end

        break if all_good || time > timeout

        sleep 1
        time += 1
      end

      # If timeout before all inservice, deregister and raise error
      unless all_good
        raise "Instances are out of service"
      end
    end

Wait for all the instances to become InService


def read(path)
      owconnect do |socket|
        owwrite(socket,:path => path, :function => READ)
        return to_number(owread(socket).data)
      end
    end

def read ( path ) owconnect do | socket | owwrite ( socket , :path => path , :function => READ ) return to_number ( owread ( socket ) . data ) end end


def write(path, value)
      owconnect do |socket|
        owwrite(socket, :path => path, :value => value.to_s, :function => WRITE)
        return owread(socket).return_value
      end
    end

def write ( path , value ) owconnect do | socket | owwrite ( socket , :path => path , :value => value . to_s , :function => WRITE ) return owread ( socket ) . return_value end end


def dir(path)
      owconnect do |socket|
        owwrite(socket,:path => path, :function => DIR)

        fields = []
        while true
          response = owread(socket)
          if response.data
            fields << response.data
          else
            break
          end
        end
        return fields
      end
    end

def dir ( path ) owconnect do | socket | owwrite ( socket , :path => path , :function => DIR ) fields = [ ] while true response = owread ( socket ) if response . data fields << response . data else break end end return fields end end


def sum_totals_by_model
      @sum_totals_by_model ||= begin
        totals = Hash.new { |hash, key| hash[key] = Hash.new(0) }

        @queries_by_model.each do |model, queries|
          totals[model][:query_count] = queries.length
          queries.each do |query|
            query.statistics.each do |stat, value|
              totals[model][stat] += value
            end
          end

          totals[model][:datastore_interaction_time] = totals[model][:datastore_interaction_time]
        end

        totals
      end
    end

def sum_totals_by_model @sum_totals_by_model ||= begin totals = Hash . new { | hash , key | hash [ key ] = Hash . new ( 0 ) } @queries_by_model . each do | model , queries | totals [ model ] [ :query_count ] = queries . length queries . each do | query | query . statistics . each do | stat , value | totals [ model ] [ stat ] += value end end totals [ model ] [ :datastore_interaction_time ] = totals [ model ] [ :datastore_interaction_time ] end totals end end

sums up statistics across all queries, indexed by model

sums up statistics across all queries indexed by model


def sum_totals
      @sum_totals ||= begin
        totals = Hash.new(0)

        sum_totals_by_model.each do |_, model_totals|
          model_totals.each do |stat, value|
            totals[stat] += value
          end
        end

        totals
      end
    end

def sum_totals @sum_totals ||= begin totals = Hash . new ( 0 ) sum_totals_by_model . each do | _ , model_totals | model_totals . each do | stat , value | totals [ stat ] += value end end totals end end

sums up statistics across all models and queries


def to_label
      s = '%016x%08x'
      sec = tai_second
      ts = if sec >= 0
        sec + EPOCH
      else
        EPOCH - sec
      end
      Label.new s % [ ts, tai_nanosecond ]
    end

def to_label s = '%016x%08x' sec = tai_second ts = if sec >= 0 sec + EPOCH else EPOCH - sec end Label . new s % [ ts , tai_nanosecond ] end

Warning, this will probably gain inappropriate accuracy - Ruby does not
 support the same level of timing accuracy as TAI64N and TA64NA can
 provide.

Warning this will probably gain inappropriate accuracy - Ruby does not support the same level of timing accuracy as TAI64N and TA64NA can provide .


def put(name, object)
      raise "This ObjectContext already has an instance or configuration for '#{name.to_s}'" if directly_has?(name)
      Conject.install_object_context(object, self)
      object.instance_variable_set(:@_conject_contextual_name, name.to_s)
      @cache[name.to_sym] = object
    end


def configure_objects(confs={})
      confs.each do |key,opts|
        key = key.to_sym
        @object_configs[key] ={} unless has_config?(key)
        @object_configs[key].merge!(opts)
      end
    end

def configure_objects ( confs = { } ) confs . each do | key , opts | key = key . to_sym @object_configs [ key ] = { } unless has_config? ( key ) @object_configs [ key ] . merge! ( opts ) end end

Allow configuration options to be set for named objects.

Allow configuration options to be set for named objects .


def httperf warm_up = false
      httperf_cmd = build_httperf_cmd
      if warm_up
        # Do a warm up run to setup any resources
        status "\n#{httperf_cmd} (warm up run)"
        IO.popen("#{httperf_cmd} 2>&1")
      else
        IO.popen("#{httperf_cmd} 2>&1") do |pipe|
          status "\n#{httperf_cmd}"
          @results << (httperf_result = HttperfResult.new({
              :rate         => @current_rate,
              :server       => @current_job.server,
              :port         => @current_job.port,
              :uri          => @current_job.uri,
              :num_conns    => @current_job.num_conns,
              :description  => @current_job.description
            }))
          HttperfResultParser.new(pipe).parse(httperf_result)
        end
      end
    end

Runs httperf with a given request rate. Parses the output and returns
 a hash with the results.

Runs httperf with a given request rate . Parses the output and returns a hash with the results .


def url(path, params = {})
      params = params.inject({}, &@@stringify)
      path = path.gsub(@@placeholder) { params.delete($1, &@@required) }
      params = params.inject('', &@@parameterize)
      [path, params].reject(&:nil?).reject(&:empty?).join('?')
    end

def url ( path , params = { } ) params = params . inject ( { } , @@stringify ) path = path . gsub ( @@placeholder ) { params . delete ( $1 , @@required ) } params = params . inject ( '' , @@parameterize ) [ path , params ] . reject ( :nil? ) . reject ( :empty? ) . join ( '?' ) end

Converts a path and params to a Salesforce-suitable URL.

Converts a path and params to a Salesforce - suitable URL .


def url?(string)
      return false unless string.to_s =~ url_pattern
      return false if     string.to_s =~ @@placeholder
      true
    end

def url? ( string ) return false unless string . to_s =~ url_pattern return false if string . to_s =~ @@placeholder true end

Identifies a valid URL for this REST instance


def assit_equal(expected, actual, message = "Object expected to be equal")
      if(expected != actual)
        message << " expected #{expected} but was #{actual}"
        assit(false, message)
      end
    end


def assit_kind_of(klass, object, message = "Object of wrong type")
      if(!object.kind_of?(klass))
        message << " (Expected #{klass} but was #{object.class})"
        assit(false, message)
      end
    end

Assert if something is of the right type


def assit_real_string(object, message = "Not a non-empty string.")
      unless(object && object.kind_of?(String) && object.strip != "")
        assit(false, message)
      end
    end

def
assit_real_string
(
object
,
message
=
"Not a non-empty string."
)
unless
(
object
&&
object
.
kind_of?
(
String
)
&&
object
.
strip
!=
""
)
assit
(
false
,
message
)
end
end

Asserts that the given element is a string that is not nil and not an
 empty string, or a string only containing whitspaces

Asserts that the given element is a string that is not nil and not an empty string or a string only containing whitspaces


def assit_block(&block)
      errors = []
      assit((block.call(errors) && errors.size == 0), errors.join(', '))
    end

def
assit_block
(
&
block
)
errors
=
[
]
assit
(
(
block
.
call
(
errors
)
&&
errors
.
size
==
0
)
,
errors
.
join
(
', '
)
)
end

Executes the given block and asserts if the result is true. This allows
 you to assert on complex, custom expressions and be able to disable
 those expressions together with the assertions. See the README for more.

 The block will be passed a single array, to which error messages can be
 append. The assertion will always fail if an error is appended to the
 array.

Executes the given block and asserts if the result is true . This allows you to assert on complex custom expressions and be able to disable those expressions together with the assertions . See the README for more .


def poll interval: 10, &block
      raise '#poll requires a block' unless block_given?

      response_id = 0

      loop do
        res = self.sync response_id

        if res
          response_id = res['rid']

          yield res
        end

        sleep interval
      end
    end

def
poll
interval
:
10
,
&
block
raise
'#poll requires a block'
unless
block_given?
response_id
=
0
loop
do
res
=
self
.
sync
response_id
if
res
response_id
=
res
[
'rid'
]
yield
res
end
sleep
interval
end
end

Polls the client for incremental changes.

 @param interval Update interval in seconds.

 @yield [Hash] the return result of #sync.

Polls the client for incremental changes .


def sync response_id = 0
      req = self.class.get '/sync/maindata', format: :json,
                           query: { rid: response_id }
      res = req.parsed_response

      if req.success?
        return res
      end
    end

def sync response_id = 0 req = self . class . get '/sync/maindata' , format : :json , query : { rid : response_id } res = req . parsed_response if req . success? return res end end

Requests partial data from the client.

 @param response_id [Integer] Response ID. Used to keep track of what has
   already been sent by qBittorrent.

 @return [Hash, nil] parsed json data on success, nil otherwise

 @note Read more about `response_id` at https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation#get-partial-data


def add_trackers torrent_hash, urls
      urls = Array(urls)
      # Ampersands in urls must be escaped.
      urls = urls.map { |url| url.gsub('&', '%26') }
      urls = urls.join('%0A')

      options = {
        body: "hash=#{torrent_hash}&urls=#{urls}"
      }

      self.class.post('/command/addTrackers', options)
    end

def
add_trackers
torrent_hash
,
urls
urls
=
Array
(
urls
)
# Ampersands in urls must be escaped.
urls
=
urls
.
map
{
|
url
|
url
.
gsub
(
'&'
,
'%26'
)
}
urls
=
urls
.
join
(
'%0A'
)
options
=
{
body
:
"hash=#{torrent_hash}&urls=#{urls}"
}
self
.
class
.
post
(
'/command/addTrackers'
,
options
)
end

Add one or more trackers to a torrent

 If passing mulitple urls, pass them as an array.


def download urls
      urls = Array(urls)
      urls = urls.join('%0A')

      options = {
        body: "urls=#{urls}"
      }

      self.class.post('/command/download', options)
    end

def download urls urls = Array ( urls ) urls = urls . join ( '%0A' ) options = { body : "urls=#{urls}" } self . class . post ( '/command/download' , options ) end

Begin downloading one or more torrents.

 If passing mulitple urls, pass them as an array.

Begin downloading one or more torrents .


def delete_torrent_and_data torrent_hashes
      torrent_hashes = Array(torrent_hashes)
      torrent_hashes = torrent_hashes.join('|')

      options = {
        body: "hashes=#{torrent_hashes}"
      }

      self.class.post('/command/deletePerm', options)
    end

def delete_torrent_and_data torrent_hashes torrent_hashes = Array ( torrent_hashes ) torrent_hashes = torrent_hashes . join ( '|' ) options = { body : "hashes=#{torrent_hashes}" } self . class . post ( '/command/deletePerm' , options ) end

Delete one or more torrents AND THEIR DATA

 If passing multiple torrent hashes, pass them as an array.


def set_location(torrent_hashes, path)
      torrent_hashes = Array(torrent_hashes)
      torrent_hashes = torrent_hashes.join('|')

      options = {
        body: { "hashes" => torrent_hashes, "location" => path },
      }

      self.class.post('/command/setLocation', options)
    end

def set_location ( torrent_hashes , path ) torrent_hashes = Array ( torrent_hashes ) torrent_hashes = torrent_hashes . join ( '|' ) options = { body : { "hashes" => torrent_hashes , "location" => path } , } self . class . post ( '/command/setLocation' , options ) end


def increase_priority torrent_hashes
      torrent_hashes = Array(torrent_hashes)
      torrent_hashes = torrent_hashes.join('|')

      options = {
        body: "hashes=#{torrent_hashes}"
      }

      self.class.post('/command/increasePrio', options)
    end

def increase_priority torrent_hashes torrent_hashes = Array ( torrent_hashes ) torrent_hashes = torrent_hashes . join ( '|' ) options = { body : "hashes=#{torrent_hashes}" } self . class . post ( '/command/increasePrio' , options ) end

Increase the priority of one or more torrents

 If passing multiple torrent hashes, pass them as an array.
 Note: This does nothing unless queueing has been enabled
 via preferences.


def decrease_priority torrent_hashes
      torrent_hashes = Array(torrent_hashes)
      torrent_hashes = torrent_hashes.join('|')

      options = {
        body: "hashes=#{torrent_hashes}"
      }

      self.class.post('/command/decreasePrio', options)
    end

def decrease_priority torrent_hashes torrent_hashes = Array ( torrent_hashes ) torrent_hashes = torrent_hashes . join ( '|' ) options = { body : "hashes=#{torrent_hashes}" } self . class . post ( '/command/decreasePrio' , options ) end

Decrease the priority of one or more torrents

 If passing multiple torrent hashes, pass them as an array.
 Note: This does nothing unless queueing has been enabled
 via preferences.


def maximize_priority torrent_hashes
      torrent_hashes = Array(torrent_hashes)
      torrent_hashes = torrent_hashes.join('|')

      options = {
        body: "hashes=#{torrent_hashes}"
      }

      self.class.post('/command/topPrio', options)
    end

def maximize_priority torrent_hashes torrent_hashes = Array ( torrent_hashes ) torrent_hashes = torrent_hashes . join ( '|' ) options = { body : "hashes=#{torrent_hashes}" } self . class . post ( '/command/topPrio' , options ) end

Increase the priority of one or more torrents to the maximum value

 If passing multiple torrent hashes, pass them as an array.
 Note: This does nothing unless queueing has been enabled
 via preferences.


def minimize_priority torrent_hashes
      torrent_hashes = Array(torrent_hashes)
      torrent_hashes = torrent_hashes.join('|')

      options = {
        body: "hashes=#{torrent_hashes}"
      }

      self.class.post('/command/bottomPrio', options)
    end

def minimize_priority torrent_hashes torrent_hashes = Array ( torrent_hashes ) torrent_hashes = torrent_hashes . join ( '|' ) options = { body : "hashes=#{torrent_hashes}" } self . class . post ( '/command/bottomPrio' , options ) end

Decrease the priority of one or more torrents to the minimum value

 If passing multiple torrent hashes, pass them as an array.
 Note: This does nothing unless queueing has been enabled
 via preferences.


def set_file_priority torrent_hash, file_id, priority
      query = ["hash=#{torrent_hash}", "id=#{file_id}", "priority=#{priority}"]

      options = {
        body: query.join('&')
      }

      self.class.post('/command/setFilePrio', options)
    end

def set_file_priority torrent_hash , file_id , priority query = [ "hash=#{torrent_hash}" , "id=#{file_id}" , "priority=#{priority}" ] options = { body : query . join ( '&' ) } self . class . post ( '/command/setFilePrio' , options ) end

Set the download priority of a file within a torrent

 file_id is a 0 based position of the file within the torrent


def set_download_limit torrent_hash, limit
      query = ["hashes=#{torrent_hash}", "limit=#{limit}"]

      options = {
        body: query.join('&')
      }

      self.class.post('/command/setTorrentsDlLimit', options)
    end

def set_download_limit torrent_hash , limit query = [ "hashes=#{torrent_hash}" , "limit=#{limit}" ] options = { body : query . join ( '&' ) } self . class . post ( '/command/setTorrentsDlLimit' , options ) end

Set a torrent's download limit

 A limit of 0 means unlimited.

 torrent_hash: string
 limit: integer (bytes)


def set_upload_limit torrent_hash, limit
      query = ["hashes=#{torrent_hash}", "limit=#{limit}"]

      options = {
        body: query.join('&')
      }

      self.class.post('/command/setTorrentsUpLimit', options)
    end

def set_upload_limit torrent_hash , limit query = [ "hashes=#{torrent_hash}" , "limit=#{limit}" ] options = { body : query . join ( '&' ) } self . class . post ( '/command/setTorrentsUpLimit' , options ) end

Set a torrent's upload limit

 A limit of 0 means unlimited.

 torrent_hash: string
 limit: integer (bytes)


def md5_file(path)
      File.open(path) do |f|
        digest, buf = Digest::MD5.new, ""
        while f.read(4096, buf)
          digest.update(buf)
        end
        digest.hexdigest
      end
    end

def md5_file ( path ) File . open ( path ) do | f | digest , buf = Digest :: MD5 . new , "" while f . read ( 4096 , buf ) digest . update ( buf ) end digest . hexdigest end end

Return the md5 checksum for the file at +path+.

Return the md5 checksum for the file at + path + .


def keys(*a)
      if block_given?
        bucket.keys(*a) do |keys|
          # This API is currently inconsistent from protobuffs to http
          if keys.kind_of? Array
            keys.each do |key|
              yield key
            end
          else
            yield keys
          end
        end
      else
        bucket.keys(*a)
      end
    end


def each
      bucket.keys do |keys|
        keys.each do |key|
          if x = self[key]
            yield x
          end
        end
      end
    end

def each bucket . keys do | keys | keys . each do | key | if x = self [ key ] yield x end end end end

Iterate over all items using key streaming.

Iterate over all items using key streaming .


def run(command, args = nil)
      cmd = CommandLine.new(command, args)
      vputs(cmd)
      cmd.run
    end

def run ( command , args = nil ) cmd = CommandLine . new ( command , args ) vputs ( cmd ) cmd . run end

Run an external command. Raise Error if something goes wrong. The
 command will be echoed if verbose?.

 Usage is similar to Kernel#system. If +args+ is nil, +command+ will be
 passed to the shell. If +args+ are included, the +command+ and +args+
 will be run directly without the shell.

Run an external command . Raise Error if something goes wrong . The command will be echoed if verbose? .


def clicks(options = {})
      options = update_by_expire_time options
      if clicks_not_latest?(options)
        @rsqoot_clicks = get('clicks', options, SqootClick)
        @rsqoot_clicks = @rsqoot_clicks.clicks if @rsqoot_clicks
        @rsqoot_clicks = @rsqoot_clicks.clicks.map(&:click) if @rsqoot_clicks.clicks
      end
      logger(uri: sqoot_query_uri, records: @rsqoot_clicks, type: 'clicks', opts: options)
      @rsqoot_clicks
    end

def clicks ( options = { } ) options = update_by_expire_time options if clicks_not_latest? ( options ) @rsqoot_clicks = get ( 'clicks' , options , SqootClick ) @rsqoot_clicks = @rsqoot_clicks . clicks if @rsqoot_clicks @rsqoot_clicks = @rsqoot_clicks . clicks . map ( :click ) if @rsqoot_clicks . clicks end logger ( uri : sqoot_query_uri , records : @rsqoot_clicks , type : 'clicks' , opts : options ) @rsqoot_clicks end

Retrieve a list of clicks based on the following parameters

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

 @return [RSqoot::SqootClick]


def build_instances(template = nil)
      build_args =
        if template == :template
          [build_options.first.merge(count: 1)]
        else
          build_options
        end

      build_args.map do |args|
        instances = create_instance args
        apply_tags(instances)
        instances
      end.flatten
    end

def build_instances ( template = nil ) build_args = if template == :template [ build_options . first . merge ( count : 1 ) ] else build_options end build_args . map do | args | instances = create_instance args apply_tags ( instances ) instances end . flatten end

Build instances using build options

 if :template is passed, only build on, used as a template for a new image


def scope(scope_name, scope_enum_keys)
      target_enum = @record_class.defined_enums[@enum_name.to_s]
      sub_enum_values = target_enum.values_at(*scope_enum_keys)

      if @record_class.defined_enum_scopes.has_key?(scope_name)
        fail ArgumentError,
             "Conflicting scope names. A scope named #{scope_name} has already been defined"
      elsif sub_enum_values.include?(nil)
        unknown_key = scope_enum_keys[sub_enum_values.index(nil)]
        fail ArgumentError, "Unknown key - #{unknown_key} for enum #{@enum_name}"
      elsif @record_class.respond_to?(scope_name.to_s.pluralize)
        fail ArgumentError,
             "Scope name - #{scope_name} conflicts with a class method of the same name"
      elsif @record_class.instance_methods.include?("#{scope_name}?".to_sym)
        fail ArgumentError,
             "Scope name - #{scope_name} conflicts with the instance method - #{scope_name}?"
      end

      sub_enum_entries = target_enum.slice(*scope_enum_keys)
      @record_class.defined_enum_scopes[scope_name] = sub_enum_entries

      # 1. Instance method <scope_name>?
      @record_class.send(:define_method, "#{scope_name}?") { sub_enum_entries.include? self.role }

      # 2. The class scope with the scope name
      @record_class.scope scope_name.to_s.pluralize,
                          -> { @record_class.where("#{@enum_name}" => sub_enum_entries.values) }

      @scope_names << scope_name
    end

Initialize a new ScopeCreator object
 @param [ActiveRecord]
 @param [String, Symbol]
 Add a scope of the enum to the class. It creates an instance method - <scope_name>? and a
 ActiveRecord class scope with the same name as the enum scope.
 @param [String, Symbol] The name of the enum scope
 @param [Array<String>, Array<Symbol>] The list of keys of the enum


def configure

      # config file default options
      configuration = {
                        :options => {
                          :verbose => false,
                          :coloring => 'AUTO'
                        },
                        :mount => {
                          :source => {
                            :name => nil
                          },
                          :mountpoint => {
                            :name => nil
                          },
                          :passphrasefile => {
                            :name => 'passphrase'
                          },
                          :keyfile => {
                            :name => 'encfs6.xml'
                          },
                          :cmd => nil,
                          :executable => nil
                        },
                        :unmount => {
                          :mountpoint => {
                            :name => nil
                          },
                          :cmd => nil,
                          :executable => nil
                        },
                        :copy => {
                          :source => {
                            :name => nil
                          },
                          :destination => {
                            :name => nil
                          },
                          :cmd => nil,
                          :executable => nil
                        }
                      }

      # set default config if not given on command line
      config = @options[:config]
      unless config
        config = [
                   File.join(@working_dir, "revenc.conf"),
                   File.join(@working_dir, ".revenc.conf"),
                   File.join(@working_dir, "config", "revenc.conf"),
                   File.expand_path(File.join("~", ".revenc.conf"))
                 ].detect { |filename| File.exists?(filename) }
      end

      if config && File.exists?(config)
        # rewrite options full path for config for later use
        @options[:config] = config

        # load options from the config file, overwriting hard-coded defaults
        config_contents = YAML::load(File.open(config))
        configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash)
      else
        # user specified a config file?, no error if user did not specify config file
        raise "config file not found" if @options[:config]
      end

      # the command line options override options read from the config file
      @options = configuration[:options].merge!(@options)
      @options.symbolize_keys!

      # mount, unmount and copy configuration hashes
      @options[:mount] = configuration[:mount].recursively_symbolize_keys! if configuration[:mount]
      @options[:unmount] = configuration[:unmount].recursively_symbolize_keys! if configuration[:unmount]
      @options[:copy] = configuration[:copy].recursively_symbolize_keys! if configuration[:copy]
    end


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

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

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

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"
)
# 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
(
/
/
,
''
)
.
strip
#error_on_str = error_on_str.capitalize
@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

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

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"
,
# 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

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? .