def get_listing opts = {}
      # Build the basic url
      url = "%s/%s.json" % [('/r/' + opts[:subreddit] if opts[:subreddit] ), (opts[:page] if opts[:page])]
      # Delete subreddit and page from the hash, they dont belong in the query
      [:subreddit, :page].each {|k| opts.delete k}
      query = opts
      # Make the request
      get(url, query: query)
    end

Gets a listing of links from reddit.

 @param (see LinksComments#info)
 @option opts [String] :subreddit The subreddit targeted. Can be psuedo-subreddits like `all` or `mod`. If blank, the front page
 @option opts [new, controversial, top, saved] :page The page to view.
 @option opts [new, rising] :sort The sorting method. Only relevant on the `new` page
 @option opts [hour, day, week, month, year] :t The timeframe. Only relevant on some pages, such as `top`. Leave empty for all time
 @option opts [1..100] :limit The number of things to return.
 @option opts [String] :after Get things *after* this thing id
 @option opts [String] :before Get things *before* this thing id
 @return (see #clear_sessions)


def distinguish id, how = "yes"
      logged_in?
      hows = %w{yes no admin special}
      post('/api/distinguish', body: {id: id, how: how, uh: @modhash, api_type: 'json'})
    end

def distinguish id , how = "yes" logged_in? hows = %w{ yes no admin special } post ( '/api/distinguish' , body : { id : id , how : how , uh : @modhash , api_type : 'json' } ) end

Distinguish a thing

 @param (see #approve)
 @param how [yes, no, admin, special] (yes) Determines how to distinguish something. Only works for the permissions you have.
 @return (see #clear_sessions)


def remove id, spam = false
      logged_in?
      post('/api/remove', body: {id: id, spam: spam, uh: @modhash, api_type: 'json'})
    end

def remove id , spam = false logged_in? post ( '/api/remove' , body : { id : id , spam : spam , uh : @modhash , api_type : 'json' } ) end

Removes a thing

 @param (see #approve)
 @param spam [true, false] Mark this removal as a spam removal (and train the spamfilter)
 @return (see #clear_sessions)


def get_modlog subreddit, opts = {}
      logged_in?
      options = {
        limit: 100
      }.merge opts
      data = Nokogiri::HTML.parse(get("/r/#{subreddit}/about/log", query: options).body).css('.modactionlisting tr')
      processed = {
        data:       [],
        first:      data[0]['data-fullname'],
        first_date: Time.parse(data[0].children[0].child['datetime']),
        last:       data[-1]['data-fullname'],
        last_date:  Time.parse(data[-1].children[0].child['datetime']),
      }
      data.each do |tr|
        processed[:data] << {
          fullname:     tr['data-fullname'],
          time:         Time.parse(tr.children[0].child['datetime']),
          author:       tr.children[1].child.content,
          action:       tr.children[2].child['class'].split[1],
          description:  tr.children[3].content,
          href:         tr.children[3].css('a').count == 0 ? nil : tr.children[3].css('a')[0]['href']
        }
      end
      return processed
    end

def
get_modlog
subreddit
,
opts
=
{
}
logged_in?
options
=
{
limit
:
100
}
.
merge
opts
data
=
Nokogiri
::
HTML
.
parse
(
get
(
"/r/#{subreddit}/about/log"
,
query
:
options
)
.
body
)
.
css
(
'.modactionlisting tr'
)
processed
=
{
data
:
[
]
,
first
:
data
[
0
]
[
'data-fullname'
]
,
first_date
:
Time
.
parse
(
data
[
0
]
.
children
[
0
]
.
child
[
'datetime'
]
)
,
last
:
data
[
1
]
[
'data-fullname'
]
,
last_date
:
Time
.
parse
(
data
[
1
]
.
children
[
0
]
.
child
[
'datetime'
]
)
,
}
data
.
each
do
|
tr
|
processed
[
:data
]
<<
{
fullname
:
tr
[
'data-fullname'
]
,
time
:
Time
.
parse
(
tr
.
children
[
0
]
.
child
[
'datetime'
]
)
,
author
:
tr
.
children
[
1
]
.
child
.
content
,
action
:
tr
.
children
[
2
]
.
child
[
'class'
]
.
split
[
1
]
,
description
:
tr
.
children
[
3
]
.
content
,
href
:
tr
.
children
[
3
]
.
css
(
'a'
)
.
count
==
0
:
tr
.
children
[
3
]
.
css
(
'a'
)
[
0
]
[
'href'
]
}
end
return
processed
end

Gets a moderation log
 This is a tricky function, and may break a lot.
 Blame the lack of a real api

 @param subreddit [String] The subreddit to fetch from
 @param opts [Hash] Options to pass to reddit
 @option opts [Fixnum] :limit (100) The number to get. Can't be higher than 100
 @option opts [String] :before The "fullname" to fetch before.
 @option opts [String] :after The "fullname" to fetch after (older than).
 @option opts [String] :type See [reddit API docs](http://www.reddit.com/dev/api#GET_moderationlog)
 @option opts [String] :mod The moderator to get. Name, not ID
 @return [Hash] A hash consisting of the data, first fullname, last fullname, first date, and last date

Gets a moderation log This is a tricky function and may break a lot . Blame the lack of a real api


def post(query_params)
      servers ||= SERVERS.map{|hostname| "https://#{hostname}/minfraud/chargeback"}
      url = URI.parse(servers.shift)

      req = Net::HTTP::Post.new(url.path, initheader = {'Content-Type' =>'application/json'})
      req.basic_auth Maxmind::user_id, Maxmind::license_key
      req.body = query_params

      h = Net::HTTP.new(url.host, url.port)
      h.use_ssl = true
      h.verify_mode = OpenSSL::SSL::VERIFY_NONE

      # set some timeouts
      h.open_timeout  = 60 # this blocks forever by default, lets be a bit less crazy.
      h.read_timeout  = self.class.timeout || DefaultTimeout
      h.ssl_timeout   = self.class.timeout || DefaultTimeout

      h.start { |http| http.request(req) }

    rescue Exception => e
      retry if servers.size > 0
      raise e
    end

Upon a failure at the first URL, will automatically retry with the
 second & third ones before finally raising an exception
 Returns an HTTPResponse object

Upon a failure at the first URL will automatically retry with the second & third ones before finally raising an exception Returns an HTTPResponse object


def lifespan=(lifespan)
      @lifespan = lifespan
      @@lifespans.each_with_index do |span, index|
        if span[0] == lifespan && lifespan != "Forever"
          self.expires = DateTime.now.advance(@@lifespans[index][1])
        end
      end
    end

def lifespan = ( lifespan ) @lifespan = lifespan @@lifespans . each_with_index do | span , index | if span [ 0 ] == lifespan && lifespan != "Forever" self . expires = DateTime . now . advance ( @@lifespans [ index ] [ 1 ] ) end end end

Setter to convert user's choice of 'A Week', etc. to an actual DateTime

Setter to convert user s choice of A Week etc . to an actual DateTime


def div
      cr_scanner = CodeRay.scan(self.clip, self.language)
      # Only show line numbers if its greater than 1
      if cr_scanner.loc <= 1
        return cr_scanner.div
      else
        return cr_scanner.div(:line_numbers => :table)
      end
    end


def set_variables(instance_variables)
      instance_variables.each { |name, value| instance_variable_set("@#{name}", value) }
      yield(self)
      instance_variables.each { |name, _| remove_instance_variable("@#{name}") }
      self
    end

def set_variables ( instance_variables ) instance_variables . each { | name , value | instance_variable_set ( "@#{name}" , value ) } yield ( self ) instance_variables . each { | name , _ | remove_instance_variable ( "@#{name}" ) } self end

sets instance variables when block is yielded
 @param [Hash{String => Object}] instance_variables hash of names and values to set
 @yield block when variables are set, variables are cleaned up afterwards


def render(object, method, *args, &block)
      object.__send__ method, self, *args, &block
      self
    end

def render ( object , method , * args , & block ) object . __send__ method , self , args , block self end

renders +object+ with +method+
 @param [Object] object an object to render
 @param [Symbol] method a method name which is used for rendering
 @param args arguments passed to rendering method
 @yield block passed to rendering method


def join(collection, glue = nil, &it)
      # TODO as helper? two block method call #join(collection, &item).with(&glue)
      glue_block = case glue
                     when String
                       lambda { text glue }
                     when Proc
                       glue
                     else
                       lambda {}
                   end

      collection.each_with_index do |obj, i|
        glue_block.call() if i > 0
        obj.is_a?(Proc) ? obj.call : it.call(obj)
      end
    end

joins and renders +collection+ with +glue+
 @param [Array<Proc, Object>] collection of objects or lambdas
 @param [Proc, String] glue can be String which is rendered with #text or block to render
 @yield how to render objects from +collection+, Proc in collection does not use this block
 @example
   join([1, 1.2], lambda { text ', ' }) {|o| text o }        # => "1, 1.2"
   join([1, 1.2], ', ') {|o| text o }                        # => "1, 1.2"
   join([->{ text 1 }, 1.2], ', ') {|o| text o }             # => "1, 1.2"

joins and renders + collection + with + glue +


def open_session(uri)
      validate_presence_of uri, 'Channel URI'

      response = @client.call(:open_publication_session, message: { 'ChannelURI' => uri })

      response.to_hash[:open_publication_session_response][:session_id].to_s
    end

def
open_session
(
uri
)
validate_presence_of
uri
,
'Channel URI'
response
=
@client
.
call
(
:open_publication_session
,
message
:
{
'ChannelURI'
=>
uri
}
)
response
.
to_hash
[
:open_publication_session_response
]
[
:session_id
]
.
to_s
end

Creates a new ISBM ProviderPublication client.

 @param endpoint [String] the SOAP endpoint URI
 @option options [Array<String>] :wsse_auth username and password, i.e. [username, password]
 @option options [Object] :logger (Rails.logger or $stdout) location where log should be output
 @option options [Boolean] :log (true) specify whether requests are logged
 @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted
 Opens a publication session for a channel.

 @param uri [String] the channel URI
 @return [String] the session id
 @raise [ArgumentError] if uri is blank

Creates a new ISBM ProviderPublication client .


def post_publication(session_id, content, topics, expiry = nil)
      validate_presence_of session_id, 'Session Id'
      validate_presence_of content, 'Content'
      validate_presence_of topics, 'Topics'
      validate_xml content

      topics = [topics].flatten

      # Use Builder to generate XML body as we need to concatenate XML message content
      xml = Builder::XmlMarkup.new
      xml.isbm :SessionID, session_id
      xml.isbm :MessageContent do
        xml << content
      end
      topics.each do |topic|
        xml.isbm :Topic, topic
      end
      duration = expiry.to_s
      xml.isbm :Expiry, duration unless duration.nil?

      response = @client.call(:post_publication, message: xml.target!)

      response.to_hash[:post_publication_response][:message_id].to_s
    end

Posts a publication message.

 @param session_id [String] the session id
 @param content [String] a valid XML string as message contents
 @param topics [Array<String>, String] a collection of topics or single topic
 @param expiry [Duration] when the message should expire
 @return [String] the message id
 @raise [ArgumentError] if session_id, content or topics are blank, or
   content is not valid XML


def expire_publication(session_id, message_id)
      validate_presence_of session_id, 'Session Id'
      validate_presence_of message_id, 'Message Id'

      @client.call(:expire_publication, message: { 'SessionID' => session_id, 'MessageID' => message_id })

      return true
    end

def
expire_publication
(
session_id
,
message_id
)
validate_presence_of
session_id
,
'Session Id'
validate_presence_of
message_id
,
'Message Id'
@client
.
call
(
:expire_publication
,
message
:
{
'SessionID'
=>
session_id
,
'MessageID'
=>
message_id
}
)
return
true
end

Expires a posted publication message.

 @param session_id [String] the session id used to post the publication
 @param message_id [String] the message id received after posting the publication
 @return [void]
 @raise [ArgumentError] if session_id or message_id are blank


def validate_presence_of(value, name)
      if value.respond_to?(:each)
        value.each do |v|
          if v.blank?
            raise ArgumentError, "Values in #{name} must not be blank"
          end
        end
      else
        if value.blank?
          raise ArgumentError, "#{name} must not be blank"
        end
      end
    end

def
validate_presence_of
(
value
,
name
)
if
value
.
respond_to?
(
:each
)
value
.
each
do
|
v
|
if
v
.
blank?
raise
ArgumentError
,
"Values in #{name} must not be blank"
end
end
else
if
value
.
blank?
raise
ArgumentError
,
"#{name} must not be blank"
end
end
end

Creates a new ISBM client.

 @param wsdl_file [String] the filename of the WSDL
 @param endpoint [String] the SOAP endpoint URI
 @option options [Object] :logger (Rails.logger or $stdout) location where log should be output
 @option options [Boolean] :log (true) specify whether requests are logged
 @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted
 Validates the presence of the passed value.

 @param value [Object] object to validate presence
 @param name [String] name of value to include in error message if not present
 @return [void]
 @raise [ArgumentError] if value is not present


def validate_xml(xml)
      doc = Nokogiri.XML(xml)
      raise ArgumentError, "XML is not well formed: #{xml}" unless doc.errors.empty?
    end

def
validate_xml
(
xml
)
doc
=
Nokogiri
.
XML
(
xml
)
raise
ArgumentError
,
"XML is not well formed: #{xml}"
unless
doc
.
errors
.
empty?
end

Validates the well formedness of the XML string and raises an error if
 any errors are encountered.

 @param xml [String] the XML string to parse
 @return [void]

Validates the well formedness of the XML string and raises an error if any errors are encountered .


def default_savon_options(options)
      options[:logger] = Rails.logger if options[:logger].nil? && defined?(Rails)
      options[:log] = false if options[:log].nil?
      options[:pretty_print_xml] = true if options[:pretty_print_xml].nil?
    end

def default_savon_options ( options ) options [ :logger ] = Rails . logger if options [ :logger ] . nil? && defined? ( Rails ) options [ :log ] = false if options [ :log ] . nil? options [ :pretty_print_xml ] = true if options [ :pretty_print_xml ] . nil? end

Sets default values for certain Savon options.

 @param options [Hash] the options to set defaults on
 @return [Hash] options hash with defaults set

Sets default values for certain Savon options .


def read_publication(session_id)
      validate_presence_of session_id, 'Session Id'

      response = @client.call(:read_publication, message: { 'SessionID' => session_id })

      extract_message(response)
    end

def
read_publication
(
session_id
)
validate_presence_of
session_id
,
'Session Id'
response
=
@client
.
call
(
:read_publication
,
message
:
{
'SessionID'
=>
session_id
}
)
extract_message
(
response
)
end

Reads the first message, if any, in the session queue.

 @param session_id [String] the session id
 @return [Message] first message in session queue. nil if no message.
 @raise [ArgumentError] if session_id is blank

Reads the first message if any in the session queue .


def open_session(uri, listener_url = nil)
      validate_presence_of uri, 'Channel URI'

      message = { 'ChannelURI' => uri }
      message['ListenerURL'] = listener_url if listener_url

      response = @client.call(:open_consumer_request_session, message: message)

      response.to_hash[:open_consumer_request_session_response][:session_id].to_s
    end

def
open_session
(
uri
,
listener_url
=
)
validate_presence_of
uri
,
'Channel URI'
message
=
{
'ChannelURI'
=>
uri
}
message
[
'ListenerURL'
]
=
listener_url
if
listener_url
response
=
@client
.
call
(
:open_consumer_request_session
,
message
:
message
)
response
.
to_hash
[
:open_consumer_request_session_response
]
[
:session_id
]
.
to_s
end

Creates a new ISBM ConsumerRequest client.

 @param endpoint [String] the SOAP endpoint URI
 @option options [Array<String>] :wsse_auth username and password, i.e. [username, password]
 @option options [Object] :logger (Rails.logger or $stdout) location where log should be output
 @option options [Boolean] :log (true) specify whether requests are logged
 @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted
 Opens a consumer request session for a channel for posting requests and
 reading responses.

 @param uri [String] the channel URI
 @param listener_url [String] the URL for notification callbacks
 @return [String] the session id
 @raise [ArgumentError] if uri is blank

Creates a new ISBM ConsumerRequest client .


def post_request(session_id, content, topic, expiry = nil)
      validate_presence_of session_id, 'Session Id'
      validate_presence_of content, 'Content'
      validate_presence_of topic, 'Topic'
      validate_xml content

      # Use Builder to generate XML body as we need to concatenate XML message content
      xml = Builder::XmlMarkup.new
      xml.isbm :SessionID, session_id
      xml.isbm :MessageContent do
        xml << content
      end
      xml.isbm :Topic, topic
      duration = expiry.to_s
      xml.isbm :Expiry, duration unless duration.nil?

      response = @client.call(:post_request, message: xml.target!)

      response.to_hash[:post_request_response][:message_id].to_s
    end

Posts a request message on a channel.

 @param session_id [String] the session id
 @param content [String] a valid XML string as message contents
 @param topic [String] the topic
 @param expiry [Duration] when the message should expire
 @return [String] the request message id
 @raise [ArgumentError] if session_id, content or topics are blank, or
   content is not valid XML


def expire_request(session_id, message_id)
      validate_presence_of session_id, 'Session Id'
      validate_presence_of message_id, 'Message Id'

      @client.call(:expire_request, message: { 'SessionID' => session_id, 'MessageID' => message_id })

      return true
    end

def
expire_request
(
session_id
,
message_id
)
validate_presence_of
session_id
,
'Session Id'
validate_presence_of
message_id
,
'Message Id'
@client
.
call
(
:expire_request
,
message
:
{
'SessionID'
=>
session_id
,
'MessageID'
=>
message_id
}
)
return
true
end

Expires a posted request message.

 @param session_id [String] the session id used to post the request
 @param message_id [String] the message id received after posting the request
 @return [void]
 @raise [ArgumentError] if session_id or message_id are blank


def read_response(session_id, request_message_id)
      validate_presence_of session_id, 'Session Id'
      validate_presence_of request_message_id, 'Request Message Id'

      message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }
      response = @client.call(:read_response, message: message)

      extract_message(response)
    end

def
read_response
(
session_id
,
request_message_id
)
validate_presence_of
session_id
,
'Session Id'
validate_presence_of
request_message_id
,
'Request Message Id'
message
=
{
'SessionID'
=>
session_id
,
'RequestMessageID'
=>
request_message_id
}
response
=
@client
.
call
(
:read_response
,
message
:
message
)
extract_message
(
response
)
end

Returns the first response message, if any, in the message queue
 associated with the request.

 @param session_id [String] the session id
 @param request_message_id [String] the id of the original request message
 @return [Message] the first message in the queue for the session.
   nil if no message.
 @raise [ArgumentError] if session_id or request_message_id are blank

Returns the first response message if any in the message queue associated with the request .


def remove_response(session_id, request_message_id)
      validate_presence_of session_id, 'Session Id'
      validate_presence_of request_message_id, 'Request Message Id'

      message = { 'SessionID' => session_id, 'RequestMessageID' => request_message_id }
      @client.call(:remove_response, message: message)

      return true
    end

def
remove_response
(
session_id
,
request_message_id
)
validate_presence_of
session_id
,
'Session Id'
validate_presence_of
request_message_id
,
'Request Message Id'
message
=
{
'SessionID'
=>
session_id
,
'RequestMessageID'
=>
request_message_id
}
@client
.
call
(
:remove_response
,
message
:
message
)
return
true
end

Deletes the first response message, if any, in the message queue
 associated with the request.

 @param session_id [String] the session id
 @param request_message_id [String] the id of the original request message
 @return [void]
 @raise [ArgumentError] if session_id is blank

Deletes the first response message if any in the message queue associated with the request .


def open_session(uri, topics, listener_url = nil, xpath_expression = nil, xpath_namespaces = [])
      validate_presence_of uri, 'Channel URI'
      validate_presence_of topics, 'Topics'
      validate_presence_of xpath_expression, 'XPath Expression' if xpath_namespaces.present?

      topics = [topics].flatten

      # Use Builder to generate XML body as we may have multiple Topic elements
      xml = Builder::XmlMarkup.new
      xml.isbm :ChannelURI, uri
      topics.each do |topic|
        xml.isbm :Topic, topic
      end
      xml.isbm :ListenerURL, listener_url unless listener_url.nil?
      xml.isbm :XPathExpression, xpath_expression unless xpath_expression.nil?
      xpath_namespaces.each do |prefix, name|
        xml.isbm :XPathNamespace do
          xml.isbm :NamespacePrefix, prefix
          xml.isbm :NamespaceName, name
        end
      end

      response = @client.call(:open_provider_request_session, message: xml.target!)

      response.to_hash[:open_provider_request_session_response][:session_id].to_s
    end

Creates a new ISBM ProviderRequest client.

 @param endpoint [String] the SOAP endpoint URI
 @option options [Array<String>] :wsse_auth username and password, i.e. [username, password]
 @option options [Object] :logger (Rails.logger or $stdout) location where log should be output
 @option options [Boolean] :log (true) specify whether requests are logged
 @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted
 Opens a provider request session for a channel for reading requests and
 posting responses.

 @param uri [String] the channel URI
 @param topics [Array<String>, String] a collection of topics or single topic
 @param listener_url [String] the URL for notification callbacks
 @param xpath_expression [String] the XPath filter expression
 @param xpath_namespaces [Array<Hash>] the prefixes and namespaces used by the XPath expression. The hash key
   represents the namespace prefix while the value represents the namespace name. For example,
   ["xs" => "http://www.w3.org/2001/XMLSchema", "isbm" => "http://www.openoandm.org/xml/ISBM/"]
 @return [String] the session id
 @raise [ArgumentError] if uri or topics are blank

Creates a new ISBM ProviderRequest client .


def post_response(session_id, request_message_id, content)
      validate_presence_of session_id, 'Session Id'
      validate_presence_of request_message_id, 'Request Message Id'
      validate_presence_of content, 'Content'
      validate_xml content

      # Use Builder to generate XML body as we need to concatenate XML message content
      xml = Builder::XmlMarkup.new
      xml.isbm :SessionID, session_id
      xml.isbm :RequestMessageID, request_message_id
      xml.isbm :MessageContent do
        xml << content
      end

      response = @client.call(:post_response, message: xml.target!)

      response.to_hash[:post_response_response][:message_id].to_s
    end

Posts a response message on a channel.

 @param session_id [String] the session id
 @param request_message_id [String] the id of the original request message
 @param content [String] a valid XML string as message contents
 @return [String] the response message id
 @raise [ArgumentError] if session_id, request_message_id or content are
   blank, or content is not valid XML


def create_channel(uri, type, description = nil, tokens = {})
      validate_presence_of uri, 'Channel URI'
      validate_presence_of type, 'Channel Type'
      channel_type = type.to_s.downcase.capitalize
      validate_inclusion_in channel_type, IsbmAdaptor::Channel::TYPES, 'Channel Type'

      message = { 'ChannelURI' => uri,
                  'ChannelType' => channel_type }
      message['ChannelDescription'] = description unless description.nil?
      message['SecurityToken'] = security_token_hash(tokens) if tokens.any?

      @client.call(:create_channel, message: message)

      return true
    end

def
create_channel
(
uri
,
type
,
description
=
,
tokens
=
{
}
)
validate_presence_of
uri
,
'Channel URI'
validate_presence_of
type
,
'Channel Type'
channel_type
=
type
.
to_s
.
downcase
.
capitalize
validate_inclusion_in
channel_type
,
IsbmAdaptor
::
Channel
::
TYPES
,
'Channel Type'
message
=
{
'ChannelURI'
=>
uri
,
'ChannelType'
=>
channel_type
}
message
[
'ChannelDescription'
]
=
description
unless
description
.
nil?
message
[
'SecurityToken'
]
=
security_token_hash
(
tokens
)
if
tokens
.
any?
@client
.
call
(
:create_channel
,
message
:
message
)
return
true
end

Creates a new ISBM ChannelManagement client.

 @param endpoint [String] the SOAP endpoint URI
 @option options [Array<String>] :wsse_auth username and password, i.e. [username, password]
 @option options [Object] :logger (Rails.logger or $stdout) location where log should be output
 @option options [Boolean] :log (true) specify whether requests are logged
 @option options [Boolean] :pretty_print_xml (false) specify whether request and response XML are formatted
 Creates a new channel.

 @param uri [String] the channel URI
 @param type [Symbol] the channel type, either publication or request (symbol or titleized string)
 @param description [String] the channel description, defaults to nil
 @param tokens [Hash] username password pairs, e.g. {'u1' => 'p1', 'u2' => 'p2'}
 @return [void]
 @raise [ArgumentError] if uri or type are blank or type is not a valid Symbol

Creates a new ISBM ChannelManagement client .


def add_security_tokens(uri, tokens = {})
      validate_presence_of uri, 'Channel URI'
      validate_presence_of tokens, 'Security Tokens'

      message = { 'ChannelURI' => uri,
                  'SecurityToken' => security_token_hash(tokens) }

      @client.call(:add_security_tokens, message: message)

      return true
    end

def
add_security_tokens
(
uri
,
tokens
=
{
}
)
validate_presence_of
uri
,
'Channel URI'
validate_presence_of
tokens
,
'Security Tokens'
message
=
{
'ChannelURI'
=>
uri
,
'SecurityToken'
=>
security_token_hash
(
tokens
)
}
@client
.
call
(
:add_security_tokens
,
message
:
message
)
return
true
end

Adds security tokens to a channel.

 @param uri [String] the channel URI
 @param tokens [Hash] username password pairs, e.g. {'u1' => 'p1', 'u2' => 'p2'}
 @return [void]
 @raise [ArgumentError] if uri is blank or no tokens are provided


def remove_security_tokens(uri, tokens = {})
      validate_presence_of uri, 'Channel URI'
      validate_presence_of tokens, 'Security Tokens'

      message = { 'ChannelURI' => uri,
                  'SecurityToken' => security_token_hash(tokens) }

      @client.call(:remove_security_tokens, message: message)

      return true
    end

def
remove_security_tokens
(
uri
,
tokens
=
{
}
)
validate_presence_of
uri
,
'Channel URI'
validate_presence_of
tokens
,
'Security Tokens'
message
=
{
'ChannelURI'
=>
uri
,
'SecurityToken'
=>
security_token_hash
(
tokens
)
}
@client
.
call
(
:remove_security_tokens
,
message
:
message
)
return
true
end

Removes security tokens from a channel.

 @param uri [String] the channel URI
 @param tokens [Hash] username password pairs, e.g. {'u1' => 'p1', 'u2' => 'p2'}
 @return [void]
 @raise [ArgumentError] if uri is blank or no tokens are provided

Removes security tokens from a channel .


def get_channel(uri, &block)
      validate_presence_of uri, 'Channel URI'

      response = @client.call(:get_channel, message: { 'ChannelURI' => uri }, &block)

      hash = response.to_hash[:get_channel_response][:channel]
      IsbmAdaptor::Channel.from_hash(hash)
    end

def
get_channel
(
uri
,
&
block
)
validate_presence_of
uri
,
'Channel URI'
response
=
@client
.
call
(
:get_channel
,
message
:
{
'ChannelURI'
=>
uri
}
,
block
)
hash
=
response
.
to_hash
[
:get_channel_response
]
[
:channel
]
IsbmAdaptor
::
Channel
.
from_hash
(
hash
)
end

Gets information about the specified channel.

 @param uri [String] the channel URI
 @yield locals local options, including :wsse_auth
 @return [Channel] the queried channel
 @raise [ArgumentError] if uri is blank

Gets information about the specified channel .


def get_channels(&block)
      response = @client.call(:get_channels, {}, &block)

      channels = response.to_hash[:get_channels_response][:channel]
      channels = [channels].compact unless channels.is_a?(Array)
      channels.map do |hash|
        IsbmAdaptor::Channel.from_hash(hash)
      end
    end

def get_channels ( & block ) response = @client . call ( :get_channels , { } , block ) channels = response . to_hash [ :get_channels_response ] [ :channel ] channels = [ channels ] . compact unless channels . is_a? ( Array ) channels . map do | hash | IsbmAdaptor :: Channel . from_hash ( hash ) end end

Gets information about all channels.

 @yield locals local options, including :wsse_auth
 @return [Array<Channel>] all authorized channels on the ISBM


def update_backend
      if Idioma.configuration.redis_backend
        if i18n_value.present?
          Idioma::RedisBackend.update_phrase(self)
        else
          Idioma::RedisBackend.delete_phrase(self)
        end
      end
    end

def update_backend if Idioma . configuration . redis_backend if i18n_value . present? Idioma :: RedisBackend . update_phrase ( self ) else Idioma :: RedisBackend . delete_phrase ( self ) end end end

Will update the i18n backend if it has been configured


def set_phrase
        @phrase = Phrase.find(params[:id])
      rescue ActiveRecord::RecordNotFound
        respond_to do |format|
          format.json { render json: {}.to_json, status: :not_found }
          format.html {
            flash[:error] = t('idioma.record_not_found')
            redirect_to phrases_path
          }
        end
      end

def set_phrase @phrase = Phrase . find ( params [ :id ] ) rescue ActiveRecord :: RecordNotFound respond_to do | format | format . json { render json : { } . to_json , status : :not_found } format . html { flash [ :error ] = t ( 'idioma.record_not_found' ) redirect_to phrases_path } end end

Use callbacks to share common setup or constraints between actions.

Use callbacks to share common setup or constraints between actions .


def to_s
      date = []
      date << "#{@years}Y" unless @years.nil?
      date << "#{@months}M" unless @months.nil?
      date << "#{@days}D" unless @days.nil?

      time = []
      time << "#{@hours}H" unless @hours.nil?
      time << "#{@minutes}M" unless @minutes.nil?
      time << "#{@seconds}S" unless @seconds.nil?

      result = nil

      if !date.empty? || !time.empty?
        result = 'P'
        result += date.join unless date.empty?
        result += 'T' + time.join unless time.empty?
      end

      result
    end

def to_s date = [ ] date << "#{@years}Y" unless @years . nil? date << "#{@months}M" unless @months . nil? date << "#{@days}D" unless @days . nil? time = [ ] time << "#{@hours}H" unless @hours . nil? time << "#{@minutes}M" unless @minutes . nil? time << "#{@seconds}S" unless @seconds . nil? result = nil if ! date . empty? || ! time . empty? result = 'P' result += date . join unless date . empty? result += 'T' + time . join unless time . empty? end result end

Creates a new Duration based on specified time components.

 @option duration [Numeric] :years duration in years
 @option duration [Numeric] :months duration in months
 @option duration [Numeric] :days duration in days
 @option duration [Numeric] :hours duration in hours
 @option duration [Numeric] :minutes duration in minutes
 @option duration [Numeric] :seconds duration in seconds
 @return [String] ISO 8601 formatted duration

Creates a new Duration based on specified time components .


def to_lat format = :dms, dp = 0
      return lat if !format
      GeoUnits::Converter.to_lat lat, format, dp
    end

def to_lat format = :dms , dp = 0 return lat if ! format GeoUnits :: Converter . to_lat lat , format , dp end

Returns the latitude of this point; signed numeric degrees if no format, otherwise format & dp

 @param [String] format: Return value as 'd', 'dm', 'dms'
 @param [Numeric] dp: No of decimal places to display (0|2|4)

 @return   [Numeric|String]: Numeric degrees if no format specified, otherwise deg/min/sec

Returns the latitude of this point ; signed numeric degrees if no format otherwise format & dp


def projects
      if @projects.nil?
        response = self.get("projects")
        @projects = response.collect { |project_json| Project.new(project_json) }
      end
      @projects
    end

def projects if @projects . nil? response = self . get ( "projects" ) @projects = response . collect { | project_json | Project . new ( project_json ) } end @projects end

Returns the list of projects available to the authenticated user.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  projects = optimizely.projects # Look up all projects.

Returns the list of projects available to the authenticated user .


def project(id)
      @url = "projects/#{id}"
      raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve the project." if id.nil?

      response = self.get(@url)
      Project.new(response)
    end

Returns the details for a specific project.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  project = optimizely.project(12345) # Look up the project.

Returns the details for a specific project .


def experiments(project_id)
      raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve experiments." if project_id.nil?

      response = self.get("projects/#{project_id}/experiments")
      response.collect { |response_json| Experiment.new(response_json) }
    end

Returns the list of experiments for a specified project.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  experiments = optimizely.experiments(12345) # Look up all experiments for a project.

Returns the list of experiments for a specified project .


def experiment(id)
      @url = "experiments/#{id}"
      raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve the experiment." if id.nil?

      response = self.get(@url)
      Experiment.new(response)
    end

Returns the details for a specific experiment.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  experiment = optimizely.experiment(12345) # Look up the experiment.

Returns the details for a specific experiment .


def stats(experiment_id)
      @url = "experiments/#{experiment_id}/stats"
      raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve the stats." if experiment_id.nil?

      response = self.get(@url)
      response.collect { |response_json| Stat.new(response_json) }
    end

Returns the stats for a specific experiment.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  stats = optimizely.stats(12345) # Look up the stats with the specific experiment.

Returns the stats for a specific experiment .


def variations(experiment_id)
      raise OptimizelyError::NoExperimentID, "An Experiment ID is required to retrieve variations." if experiment_id.nil?

      response = self.get("experiments/#{experiment_id}/variations")
      response.collect { |variation_json| Variation.new(variation_json) }
    end

Returns the list of variations for a specified experiment.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  variations = optimizely.variations(12345) # Look up all variations for an experiment.

Returns the list of variations for a specified experiment .


def variation(id)
      @url = "variations/#{id}"
      raise OptimizelyError::NoVariationID, "A Variation ID is required to retrieve the variation." if id.nil?

      response = self.get(@url)
      Variation.new(response)
    end

Returns the details for a specific variation.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  variation = optimizely.variation(12345) # Look up the variation.

Returns the details for a specific variation .


def audiences(project_id)
      raise OptimizelyError::NoProjectID, "A Project ID is required to retrieve audiences." if project_id.nil?

      response = self.get("projects/#{project_id}/audiences")
      response.collect { |audience_json| Audience.new(audience_json) }
    end

Returns the list of audiences for a specified project.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  audiences = optimizely.audiences(12345) # Look up all audiences for a project.

Returns the list of audiences for a specified project .


def audience(id)
      @url = "audiences/#{id}"
      raise OptimizelyError::NoAudienceID, "An Audience ID is required to retrieve the audience." if id.nil?

      response = self.get(@url)
      Audience.new(response)
    end

Returns the details for a specific audience.

 == Usage
  optimizely = Optimizely.new({ api_token: 'oauth2_token' })
  audience = optimizely.audience(12345) # Look up the audience.

Returns the details for a specific audience .


def get(url)
      uri      = URI.parse("#{BASE_URL}#{url}/")
      https    = Net::HTTP.new(uri.host, uri.port)
      https.read_timeout = @options[:timeout] if @options[:timeout]
      https.verify_mode = OpenSSL::SSL::VERIFY_NONE
      https.use_ssl = true
      request  = Net::HTTP::Get.new(uri.request_uri, @headers)
      response = https.request(request)

      # Response code error checking
      if response.code != '200'
        check_response(response.code, response.body)
      else
        parse_json(response.body)
      end
    end

def
get
(
url
)
uri
=
URI
.
parse
(
"#{BASE_URL}#{url}/"
)
https
=
Net
::
HTTP
.
new
(
uri
.
host
,
uri
.
port
)
https
.
read_timeout
=
@options
[
:timeout
]
if
@options
[
:timeout
]
https
.
verify_mode
=
OpenSSL
::
SSL
::
VERIFY_NONE
https
.
use_ssl
=
true
request
=
Net
::
HTTP
::
Get
.
new
(
uri
.
request_uri
,
@headers
)
response
=
https
.
request
(
request
)
# Response code error checking
if
response
.
code
!=
'200'
check_response
(
response
.
code
,
response
.
body
)
else
parse_json
(
response
.
body
)
end
end

Return the parsed JSON data for a request that is done to the Optimizely REST API.

Return the parsed JSON data for a request that is done to the Optimizely REST API .


def lget (*keys)

      h = keys.flatten.inject({}) { |hh, k| hh[k] = nil; hh }
      r = @db.mget(h)

      raise 'lget failure' if r == -1

      h
    end

def
lget
(
*
keys
)
h
=
keys
.
flatten
.
inject
(
{
}
)
{
|
hh
,
k
|
hh
[
k
]
=
;
hh
}
r
=
@db
.
mget
(
h
)
raise
'lget failure'
if
r
==
1
h
end

Connects to the Tyrant table listening at the given host and port.

 You start such a Tyrant with :

   ttserver -port 44502 data.tct

 and then :

   require 'rufus/edo/ntyrant'
   t = Rufus::Edo::NetTyrantTable.new('127.0.0.1', 44502)
   t['client0'] = { 'name' => 'Heike no Kyomori', 'country' => 'jp' }
   t.close

 You can start a Tokyo Tyrant and make it listen to a unix socket (not TCP)
 with :

   ttserver -host /tmp/table_socket -port 0 data.tct

 then :

   require 'rufus/edo/ntyrant'
   t = Rufus::Edo::NetTyrantTable.new('/tmp/table_socket')
   t['client0'] = { 'name' => 'Theodore Roosevelt', 'country' => 'usa' }
   t.close

 Gets multiple records in one sweep.

Connects to the Tyrant table listening at the given host and port .


def get_random_number(bytes)
      RbNaCl::Util.bin2hex(RbNaCl::Random.random_bytes(bytes).to_s).to_i(16)
    end

def get_random_number ( bytes ) RbNaCl :: Util . bin2hex ( RbNaCl :: Random . random_bytes ( bytes ) . to_s ) . to_i ( 16 ) end

Create a random number of a specified Byte length
 returns Bignum


def get_random_number_with_bitlength(bits)
      byte_length = (bits / 8.0).ceil + 10
      random_num = get_random_number(byte_length)
      random_num_bin_str = random_num.to_s(2) # Get 1's and 0's

      # Slice off only the bits we require, convert Bits to Numeric (Bignum)
      random_num_bin_str.slice(0, bits).to_i(2)
    end

Creates a random number of a exact bitlength
 returns Bignum


def add (colname, operator, val, affirmative=true, no_index=false)

      colname = colname.to_s
      val = val.to_s

      op = operator.is_a?(Fixnum) ? operator : OPERATORS[operator]
      op = op | TDBQCNEGATE unless affirmative
      op = op | TDBQCNOIDX if no_index

      @query.addcond(colname, op, val)
    end

def add ( colname , operator , val , affirmative = true , no_index = false ) colname = colname . to_s val = val . to_s op = operator . is_a? ( Fixnum ) ? operator : OPERATORS [ operator ] op = op | TDBQCNEGATE unless affirmative op = op | TDBQCNOIDX if no_index @query . addcond ( colname , op , val ) end

Adds a condition

   table.query { |q|
     q.add 'name', :equals, 'Oppenheimer'
     q.add 'age', :numgt, 35
   }

 Understood 'operators' :

   :streq # string equality
   :eq
   :eql
   :equals

   :strinc # string include
   :inc # string include
   :includes # string include

   :strbw # string begins with
   :bw
   :starts_with
   :strew # string ends with
   :ew
   :ends_with

   :strand # string which include all the tokens in the given exp
   :and

   :stror # string which include at least one of the tokens
   :or

   :stroreq # string which is equal to at least one token

   :strorrx # string which matches the given regex
   :regex
   :matches

   # numbers...

   :numeq # equal
   :numequals
   :numgt # greater than
   :gt
   :numge # greater or equal
   :ge
   :gte
   :numlt # greater or equal
   :lt
   :numle # greater or equal
   :le
   :lte
   :numbt # a number between two tokens in the given exp
   :bt
   :between

   :numoreq # number which is equal to at least one token

   :ftsph # full-text phrase search
   :ftsphrase
   :phrase
   :ftsand # full-text AND
   :ftsor # full-text OR
   :ftsex # full-text with 'compound' expression


def keys (options={})

      if @db.respond_to? :fwmkeys
        pref = options.fetch(:prefix, "")

        @db.fwmkeys(pref, options[:limit] || -1)
      elsif @db.respond_to? :range
        @db.range("[min,max]", nil)
      else
        raise NotImplementedError, "Database does not support keys()"
      end
    end

def
keys
(
options
=
{
}
)
if
@db
.
respond_to?
:fwmkeys
pref
=
options
.
fetch
(
:prefix
,
""
)
@db
.
fwmkeys
(
pref
,
options
[
:limit
]
||
1
)
elsif
@db
.
respond_to?
:range
@db
.
range
(
"[min,max]"
,
)
else
raise
NotImplementedError
,
"Database does not support keys()"
end
end

Returns an array of all the primary keys in the db.

 With no options given, this method will return all the keys (strings)
 in a Ruby array.

   :prefix --> returns only the keys who match a given string prefix

   :limit --> returns a limited number of keys

Returns an array of all the primary keys in the db .


def autocomplete_to_add_item(name, f, association, source, options = {})
      new_object              = f.object.send(association).klass.new
      options[:class]         = ["autocomplete add-item", options[:class]].compact.join " "
      options[:data]          ||= {}
      options[:data][:id]     = new_object.object_id
      options[:data][:source] = source
      options[:data][:item]   = f.fields_for(association, new_object, child_index: options[:data][:id]) do |builder|
        render(association.to_s.singularize + "_item", f: builder).gsub "\n", ""
      end

      text_field_tag "autocomplete_nested_content", nil, options
    end

def
autocomplete_to_add_item
(
name
,
f
,
association
,
source
,
options
=
{
}
)
new_object
=
f
.
object
.
send
(
association
)
.
klass
.
new
options
[
:class
]
=
[
"autocomplete add-item"
,
options
[
:class
]
]
.
compact
.
join
" "
options
[
:data
]
||=
{
}
options
[
:data
]
[
:id
]
=
new_object
.
object_id
options
[
:data
]
[
:source
]
=
source
options
[
:data
]
[
:item
]
=
f
.
fields_for
(
association
,
new_object
,
child_index
:
options
[
:data
]
[
:id
]
)
do
|
builder
|
render
(
association
.
to_s
.
singularize
+
"_item"
,
f
:
builder
)
.
gsub
"\n"
,
""
end
text_field_tag
"autocomplete_nested_content"
,
,
options
end

.nested-container
   .nested-autocomplete
   .nested-items
    .nested-item
     .nested-content
     .nested-value
     .remove-item

. nested - container . nested - autocomplete . nested - items . nested - item . nested - content . nested - value . remove - item


def fetch( id )
      r = nil
      begin
        r = lib.tcidbget( @db, id )
      rescue => e
        # if we have 'no record found' then return nil
        if lib.tcidbecode( @db ) == 22 then
          return nil
        else
          raise_error
        end
      end
      return r
    end

Return the document at the specified index


def search( expression )
      out_count = ::FFI::MemoryPointer.new :pointer
      out_list  = ::FFI::MemoryPointer.new :pointer
      out_list  = lib.tcidbsearch2( @db, expression, out_count )

      count = out_count.read_int
      results = out_list.get_array_of_uint64(0, count )
      return results
    end

def search ( expression ) out_count = :: FFI :: MemoryPointer . new :pointer out_list = :: FFI :: MemoryPointer . new :pointer out_list = lib . tcidbsearch2 ( @db , expression , out_count ) count = out_count . read_int results = out_list . get_array_of_uint64 ( 0 , count ) return results end

Return the document ids of the documents that matche the search expression

 http://tokyocabinet.sourceforge.net/dystopiadoc/#dystopiaapi and scroll
 down to 'Compound Expression of Search'


def char_freq(str)
      freqs = Hash.new(0)
      (1..4).each do |i|
        str.chars.each_cons(i).inject(freqs) do |freq, ngram|
          ngram = ngram.join
          freq[ngram] = freq[ngram] + 1
          freq
        end
      end
      freqs
    end

def char_freq ( str ) freqs = Hash . new ( 0 ) ( 1 .. 4 ) . each do | i | str . chars . each_cons ( i ) . inject ( freqs ) do | freq , ngram | ngram = ngram . join freq [ ngram ] = freq [ ngram ] + 1 freq end end freqs end


def top(n, scores)
      scores.sort {|a,b| a[1] <=> b[1]}.map{|x| x[0]}.first(n)
    end

def top ( n , scores ) scores . sort { | a , b | a [ 1 ] <=> b [ 1 ] } . map { | x | x [ 0 ] } . first ( n ) end


def recolor(bg: '#000', fg: '#fff', bg_opacity: "1.0", fg_opacity: "1.0")
      OptionalDeps.require_nokogiri
      bg.prepend('#') unless bg.start_with? '#'
      fg.prepend('#') unless fg.start_with? '#'
      doc     = Nokogiri::XML(self.string)
      doc.css('path')[0]['fill'] = bg # dark backdrop
      doc.css('path')[1]['fill'] = fg # light drawing
      doc.css('path')[0]['fill-opacity'] = bg_opacity.to_s # dark backdrop
      doc.css('path')[1]['fill-opacity'] = fg_opacity.to_s # light drawing
      @svgstr = doc.to_xml
      self
    end

def
recolor
(
bg
:
'#000'
,
fg
:
'#fff'
,
bg_opacity
:
"1.0"
,
fg_opacity
:
"1.0"
)
OptionalDeps
.
require_nokogiri
bg
.
prepend
(
'#'
)
unless
bg
.
start_with?
'#'
fg
.
prepend
(
'#'
)
unless
fg
.
start_with?
'#'
doc
=
Nokogiri
::
XML
(
self
.
string
)
doc
.
css
(
'path'
)
[
0
]
[
'fill'
]
=
bg
# dark backdrop
doc
.
css
(
'path'
)
[
1
]
[
'fill'
]
=
fg
# light drawing
doc
.
css
(
'path'
)
[
0
]
[
'fill-opacity'
]
=
bg_opacity
.
to_s
# dark backdrop
doc
.
css
(
'path'
)
[
1
]
[
'fill-opacity'
]
=
fg_opacity
.
to_s
# light drawing
@svgstr
=
doc
.
to_xml
self
end

Modify the background and foreground colors and their opacities


def compact_copy (target_path)

      @other_db = Cabinet.new(target_path)
      self.each { |k, v| @other_db[k] = v }
      @other_db.close
    end

def compact_copy ( target_path ) @other_db = Cabinet . new ( target_path ) self . each { | k , v | @other_db [ k ] = v } @other_db . close end

Copies the current cabinet to a new file.

 Does it by copying each entry afresh to the target file. Spares some
 space, hence the 'compact' label...

Copies the current cabinet to a new file .


def keys (options={})

      if @type == "tcf"
        min, max = "min", "max"
        l        = lib.tcfdbrange2( as_fixed, min, Rufus::Tokyo.blen(min),
                                              max, Rufus::Tokyo.blen(max), -1)
      else
        pre = options.fetch(:prefix, "")

        l = lib.abs_fwmkeys(
          @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)
      end

      l = Rufus::Tokyo::List.new(l)

      options[:native] ? l : l.release
    end

def keys ( options = { } ) if @type == "tcf" min , max = "min" , "max" l = lib . tcfdbrange2 ( as_fixed , min , Rufus :: Tokyo . blen ( min ) , max , Rufus :: Tokyo . blen ( max ) , - 1 ) else pre = options . fetch ( :prefix , "" ) l = lib . abs_fwmkeys ( @db , pre , Rufus :: Tokyo . blen ( pre ) , options [ :limit ] || - 1 ) end l = Rufus :: Tokyo :: List . new ( l ) options [ :native ] ? l : l . release end

Returns an array with all the keys in the databse

 With no options given, this method will return all the keys (strings)
 in a Ruby array.

   :prefix --> returns only the keys who match a given string prefix

   :limit --> returns a limited number of keys

   :native --> returns an instance of Rufus::Tokyo::List instead of
     a Ruby Hash, you have to call #free on that List when done with it !
     Else you're exposing yourself to a memory leak.


def get4 (k)

      l = lib.tcbdbget4(as_btree, k, Rufus::Tokyo.blen(k))
      Rufus::Tokyo::List.new(l).release
    end

def get4 ( k ) l = lib . tcbdbget4 ( as_btree , k , Rufus :: Tokyo . blen ( k ) ) Rufus :: Tokyo :: List . new ( l ) . release end

This is a B+ Tree method only, returns all the values for a given
 key.

This is a B + Tree method only returns all the values for a given key .


def []= (k, v)

      clib.tcmapput(pointer, k, Rufus::Tokyo::blen(k), v, Rufus::Tokyo::blen(v))

      v
    end

def []= ( k , v ) clib . tcmapput ( pointer , k , Rufus :: Tokyo :: blen ( k ) , v , Rufus :: Tokyo :: blen ( v ) ) v end

Creates an empty instance of a Tokyo Cabinet in-memory map

 (It's OK to pass the pointer of a C map directly, this is in fact
 used in rufus/tokyo/table when retrieving entries)

 Inserts key/value pair

Creates an empty instance of a Tokyo Cabinet in - memory map


def delete (k)

      v = self[k]
      return nil unless v

      clib.tcmapout(pointer_or_raise, k, Rufus::Tokyo::blen(k)) ||
        raise("failed to remove key '#{k}'")

      v
    end

def
delete
(
k
)
v
=
self
[
k
]
return
unless
v
clib
.
tcmapout
(
pointer_or_raise
,
k
,
Rufus
::
Tokyo
::
blen
(
k
)
)
||
raise
(
"failed to remove key '#{k}'"
)
v
end


def keys

      clib.tcmapiterinit(pointer_or_raise)
      a = []

      klen = FFI::MemoryPointer.new(:int)

      loop do
        k = clib.tcmapiternext(@pointer, klen)
        break if k.address == 0
        a << k.get_bytes(0, klen.get_int(0))
      end

      return a

    ensure

      klen.free
    end

def keys clib . tcmapiterinit ( pointer_or_raise ) a = [ ] klen = FFI :: MemoryPointer . new ( :int ) loop do k = clib . tcmapiternext ( @pointer , klen ) break if k . address == 0 a << k . get_bytes ( 0 , klen . get_int ( 0 ) ) end return a ensure klen . free end

Returns an array of all the keys in the map


def []= (a, b, c=nil)

      i, s = c.nil? ? [ a, b ] : [ [a, b], c ]

      range = if i.is_a?(Range)
        i
      elsif i.is_a?(Array)
        start, count = i
        (start..start + count - 1)
      else
        [ i ]
      end

      range = norm(range)

      values = s.is_a?(Array) ? s : [ s ]
      # not "values = Array(s)"

      range.each_with_index do |offset, index|
        val = values[index]
        if val
          clib.tclistover(@pointer, offset, val, Rufus::Tokyo.blen(val))
        else
          outlen_op(:tclistremove, values.size)
        end
      end

      self
    end

def
[]=
(
a
,
b
,
c
=
)
i
,
s
=
c
.
nil?
[
a
,
b
]
:
[
[
a
,
b
]
,
c
]
range
=
if
i
.
is_a?
(
Range
)
i
elsif
i
.
is_a?
(
Array
)
start
,
count
=
i
(
start
..
start
+
count
1
)
else
[
i
]
end
range
=
norm
(
range
)
values
=
s
.
is_a?
(
Array
)
s
:
[
s
]
# not "values = Array(s)"
range
.
each_with_index
do
|
offset
,
index
|
val
=
values
[
index
]
if
val
clib
.
tclistover
(
@pointer
,
offset
,
val
,
Rufus
::
Tokyo
.
blen
(
val
)
)
else
outlen_op
(
:tclistremove
,
values
.
size
)
end
end
self
end


def keys (options={})

      pre = options.fetch(:prefix, "")

      l = lib.tab_fwmkeys(
        @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)

      l = Rufus::Tokyo::List.new(l)

      options[:native] ? l : l.release
    end

def keys ( options = { } ) pre = options . fetch ( :prefix , "" ) l = lib . tab_fwmkeys ( @db , pre , Rufus :: Tokyo . blen ( pre ) , options [ :limit ] || - 1 ) l = Rufus :: Tokyo :: List . new ( l ) options [ :native ] ? l : l . release end

Returns an array of all the primary keys in the table

 With no options given, this method will return all the keys (strings)
 in a Ruby array.

   :prefix --> returns only the keys who match a given string prefix

   :limit --> returns a limited number of keys

   :native --> returns an instance of Rufus::Tokyo::List instead of
     a Ruby Hash, you have to call #free on that List when done with it !
     Else you're exposing yourself to a memory leak.


def lget (*keys)

      keys.flatten.inject({}) { |h, k|
        k = k.to_s
        v = self[k]
        h[k] = v if v
        h
      }
    end

def lget ( * keys ) keys . flatten . inject ( { } ) { | h , k | k = k . to_s v = self [ k ] h [ k ] = v if v h } end

No 'misc' methods for the table library, so this lget is equivalent
 to calling get for each key. Hoping later versions of TC will provide
 a mget method.

No misc methods for the table library so this lget is equivalent to calling get for each key . Hoping later versions of TC will provide a mget method .


def raise_error

      err_code = lib.tab_ecode(@db)
      err_msg = lib.tab_errmsg(err_code)

      raise TokyoError.new("(err #{err_code}) #{err_msg}")
    end

def
raise_error
err_code
=
lib
.
tab_ecode
(
@db
)
err_msg
=
lib
.
tab_errmsg
(
err_code
)
raise
TokyoError
.
new
(
"(err #{err_code}) #{err_msg}"
)
end

Obviously something got wrong, let's ask the db about it and raise
 a TokyoError

Obviously something got wrong let s ask the db about it and raise a TokyoError


def each

      (0..size-1).each do |i|
        pk = @list[i]
        if @opts[:pk_only]
          yield(pk)
        else
          val = @table[pk]
          val[:pk] = pk unless @opts[:no_pk]
          yield(val)
        end
      end
    end

def each ( 0 .. size - 1 ) . each do | i | pk = @list [ i ] if @opts [ :pk_only ] yield ( pk ) else val = @table [ pk ] val [ :pk ] = pk unless @opts [ :no_pk ] yield ( val ) end end end


def find(icon)
      str = icon.to_s.downcase
      file = DB.files[str] ||
               DB.files[str.sub(/\.svg$/,'')] ||
               not_found(str, icon)
      Icon.new(file)
    end

def find ( icon ) str = icon . to_s . downcase file = DB . files [ str ] || DB . files [ str . sub ( / \. / , '' ) ] || not_found ( str , icon ) Icon . new ( file ) end

Find the icon, possibly without the extension.
 @example Finder.new.find('glass-heart')
 Raises an error if the icon could not be found.

Find the icon possibly without the extension .


def get_columns(table_name)
			columns_arr = []
		    pst = @db.prepare "SELECT * FROM #{table_name} LIMIT 6"
		    pst.columns.each do |c|
		    	columns_arr.push(c)
		    end
		  columns_arr
		end

def
get_columns
(
table_name
)
columns_arr
=
[
]
pst
=
@db
.
prepare
"SELECT * FROM #{table_name} LIMIT 6"
pst
.
columns
.
each
do
|
c
|
columns_arr
.
push
(
c
)
end
columns_arr
end


def is_numeric(table_name, column_name)
			if @db.execute("SELECT #{column_name} from #{table_name} LIMIT 1").first.first.is_a? Numeric
				return true
			else
				return false
			end
		end

If the column type is nominal return true.

If the column type is nominal return true .


def deal_with_valid_option(temp_tables, temp_columns, temp_column_types, res)
			if !temp_tables.empty?
				check_given_tables_validity(temp_tables)
				temp_tables.each do |t|
					res << convert_table(t)
				end
			elsif !temp_columns.keys.empty?
				check_given_columns_validity(temp_columns)
				res << convert_from_columns_hash(temp_columns)
			elsif !temp_column_types.empty?
				check_given_columns_validity(temp_column_types)
				res << convert_from_column_types_hash(temp_column_types)
			end
		end

def deal_with_valid_option ( temp_tables , temp_columns , temp_column_types , res ) if ! temp_tables . empty? check_given_tables_validity ( temp_tables ) temp_tables . each do | t | res << convert_table ( t ) end elsif ! temp_columns . keys . empty? check_given_columns_validity ( temp_columns ) res << convert_from_columns_hash ( temp_columns ) elsif ! temp_column_types . empty? check_given_columns_validity ( temp_column_types ) res << convert_from_column_types_hash ( temp_column_types ) end end

If valid option was provided in convert method


def let_context(*args, &block)
      context_string, hash =
        case args.map(&:class)
        when [String, Hash] then ["#{args[0]} #{args[1]}", args[1]]
        when [Hash] then [args[0].inspect, args[0]]
        end

      context(context_string) do
        hash.each { |var, value| let(var) { value } }

        instance_eval(&block)
      end
    end

def
let_context
(
*
args
,
&
block
)
context_string
,
hash
=
case
args
.
map
(
:class
)
when
[
String
,
Hash
]
then
[
"#{args[0]} #{args[1]}"
,
args
[
1
]
]
when
[
Hash
]
then
[
args
[
0
]
.
inspect
,
args
[
0
]
]
end
context
(
context_string
)
do
hash
.
each
{
|
var
,
value
|
let
(
var
)
{
value
}
}
instance_eval
(
block
)
end
end

This allows us to simplify the case where we want to
 have a context which contains one or more `let` statements

 Supports giving either a Hash or a String and a Hash as arguments
 In both cases the Hash will be used to define `let` statements
 When a String is specified that becomes the context description
 If String isn't specified, Hash#inspect becomes the context description

 @example Defining a simple let variable
   # Before
   subject { a + 1 }
   context('a is 1') do
     let(:a) { 1 }
     it { should eq 2 }
   end

   # After
   subject { a + 1 }
   let_context(a: 1) { it { should eq 2 } }

 @example Giving a descriptive string
   subject { a + 1 }
   let_context('Negative number', a: -1) { it { should eq 0 } }

 @example Multiple variables
   subject { a + b }
   let_context(a: 1, b: 2) { it { should eq 3 } }

This allows us to simplify the case where we want to have a context which contains one or more let statements


def subject_should_raise(*args)
      error, message = args
      it_string = "subject should raise #{error}"
      it_string += " (#{message.inspect})" if message

      it it_string do
        expect { subject }.to raise_error error, message
      end
    end

def
subject_should_raise
(
*
args
)
error
,
message
=
args
it_string
=
"subject should raise #{error}"
it_string
+=
" (#{message.inspect})"
if
message
it
it_string
do
expect
{
subject
}
.
to
raise_error
error
,
message
end
end

Allows you to simply specify that the subject should raise an exception
 Takes no arguments or arguments of an exception class, a string, or both.

 As with RSpec's basic `to raise_error` matcher, if you don't give an error
 then the an unexpected error may cause your test to pass incorrectly

 @example Raising a string
   # Before
   subject { fail 'Test' }
   it "should raise 'Test'" do
     expect { subject }.to raise_error 'Test'
   end

   # After
   subject { fail 'Test' }
   subject_should_raise 'Test'

 @example Raising an exception class
   subject { fail ArgumentError }
   subject_should_raise ArgumentError

 @example Raising an exception class and string
   subject { fail ArgumentError, 'Test' }
   subject_should_raise ArgumentError, 'Test'

Allows you to simply specify that the subject should raise an exception Takes no arguments or arguments of an exception class a string or both .


def subject_should_not_raise(*args)
      error, message = args
      it_string = "subject should not raise #{error}"
      it_string += " (#{message.inspect})" if message

      it it_string do
        expect { subject }.not_to raise_error error, message
      end
    end

def
subject_should_not_raise
(
*
args
)
error
,
message
=
args
it_string
=
"subject should not raise #{error}"
it_string
+=
" (#{message.inspect})"
if
message
it
it_string
do
expect
{
subject
}
.
not_to
raise_error
error
,
message
end
end

Allows you to simply specify that the subject should not raise an exception.
 Takes no arguments or arguments of an exception class, a string, or both.

 As with RSpec's basic `not_to raise_error` matcher, if you give a specific error, other
 unexpected errors may be swallowed silently

 @example Subject does not raise an error
   # Before
   subject { 1 }
   it 'should not raise an exception' do
     expect { subject }.not_to raise_error
   end

   # After
   subject { 1 }
   subject_should_not_raise

Allows you to simply specify that the subject should not raise an exception . Takes no arguments or arguments of an exception class a string or both .


def login(user, options = {})
      options[:scope] ||= Janus.scope_for(user)
      set_user(user, options)
      Janus::Manager.run_callbacks(:login, user, self, options)
    end

def login ( user , options = { } ) options [ :scope ] ||= Janus . scope_for ( user ) set_user ( user , options ) Janus :: Manager . run_callbacks ( :login , user , self , options ) end

Logs a user in.

 FIXME: what should happen when a user signs in but a user is already signed in for the same scope?!


def logout(*scopes)
      scopes = janus_sessions.keys if scopes.empty?

      scopes.each do |scope|
        _user = user(scope)
        unset_user(scope)
        Janus::Manager.run_callbacks(:logout, _user, self, :scope => scope)
      end

      request.reset_session if janus_sessions.empty?
    end

def logout ( * scopes ) scopes = janus_sessions . keys if scopes . empty? scopes . each do | scope | _user = user ( scope ) unset_user ( scope ) Janus :: Manager . run_callbacks ( :logout , _user , self , :scope => scope ) end request . reset_session if janus_sessions . empty? end

Logs a user out from the given scopes or from all scopes at once
 if no scope is defined. If no scope is left after logout, then the
 whole session will be resetted.

Logs a user out from the given scopes or from all scopes at once if no scope is defined . If no scope is left after logout then the whole session will be resetted .


def set_user(user, options = {})
      scope = options[:scope] || Janus.scope_for(user)
      janus_sessions[scope.to_s] = { 'user_class' => user.class.name, 'user_id' => user.id }
    end

def set_user ( user , options = { } ) scope = options [ :scope ] || Janus . scope_for ( user ) janus_sessions [ scope . to_s ] = { 'user_class' => user . class . name , 'user_id' => user . id } end

Manually sets a user without going throught the whole login or
 authenticate process.

Manually sets a user without going throught the whole login or authenticate process .


def unset_user(scope)
      janus_sessions.delete(scope.to_s)
      @users.delete(scope.to_sym) unless @users.nil?
    end

def unset_user ( scope ) janus_sessions . delete ( scope . to_s ) @users . delete ( scope . to_sym ) unless @users . nil? end

Manually removes the user without going throught the whole logout process.

Manually removes the user without going throught the whole logout process .


def user(scope)
      scope = scope.to_sym
      @users ||= {}

      if authenticated?(scope)
        if @users[scope].nil?
          begin
          @users[scope] = user_class(scope).find(session(scope)['user_id'])
          rescue ActiveRecord::RecordNotFound
            unset_user(scope)
          else
            Janus::Manager.run_callbacks(:fetch, @users[scope], self, :scope => scope)
          end
        end

        @users[scope]
      end
    end

def user ( scope ) scope = scope . to_sym @users ||= { } if authenticated? ( scope ) if @users [ scope ] . nil? begin @users [ scope ] = user_class ( scope ) . find ( session ( scope ) [ 'user_id' ] ) rescue ActiveRecord :: RecordNotFound unset_user ( scope ) else Janus :: Manager . run_callbacks ( :fetch , @users [ scope ] , self , :scope => scope ) end end @users [ scope ] end end


def namespace
      return '#' if Tml.config.disabled?
      @namespace || Tml.config.cache[:namespace] || Tml.config.application[:key][0..5]
    end

def namespace return '#' if Tml . config . disabled? @namespace || Tml . config . cache [ :namespace ] || Tml . config . application [ :key ] [ 0 .. 5 ] end


def extract_version(app, version = nil)
      if version
        Tml.cache.version.set(version.to_s)
      else
        version_data = app.api_client.get_from_cdn('version', {t: Time.now.to_i}, {uncompressed: true})

        unless version_data
          Tml.logger.debug('No releases have been generated yet. Please visit your Dashboard and publish translations.')
          return
        end

        Tml.cache.version.set(version_data['version'])
      end
    end


def warmup(version = nil, cache_path = nil)
      if cache_path.nil?
        warmup_from_cdn(version)
      else
        warmup_from_files(version, cache_path)
      end
    end

def warmup ( version = nil , cache_path = nil ) if cache_path . nil? warmup_from_cdn ( version ) else warmup_from_files ( version , cache_path ) end end


def warmup_from_files(version = nil, cache_path = nil)
      t0 = Time.now
      Tml.logger = Logger.new(STDOUT)

      Tml.logger.debug('Starting cache warmup from local files...')
      version ||= Tml.config.cache[:version]
      cache_path ||= Tml.config.cache[:path]
      cache_path = "#{cache_path}/#{version}"

      Tml.cache.version.set(version.to_s)
      Tml.logger.debug("Warming Up Version: #{Tml.cache.version}")

      application = JSON.parse(File.read("#{cache_path}/application.json"))
      Tml.cache.store(Tml::Application.cache_key, application)

      sources = JSON.parse(File.read("#{cache_path}/sources.json"))

      application['languages'].each do |lang|
        locale = lang['locale']

        language = JSON.parse(File.read("#{cache_path}/#{locale}/language.json"))
        Tml.cache.store(Tml::Language.cache_key(locale), language)

        sources.each do |src|
          source = JSON.parse(File.read("#{cache_path}/#{locale}/sources/#{src}.json"))
          Tml.cache.store(Tml::Source.cache_key(locale, src), source)
        end
      end

      t1 = Time.now
      Tml.logger.debug("Cache warmup took #{t1-t0}s")
    end


def warmup_from_cdn(version = nil)
      t0 = Time.now
      Tml.logger = Logger.new(STDOUT)

      Tml.logger.debug('Starting cache warmup from CDN...')
      app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])
      extract_version(app, version)

      Tml.logger.debug("Warming Up Version: #{Tml.cache.version}")

      application = app.api_client.get_from_cdn('application', {t: Time.now.to_i})
      Tml.cache.store(Tml::Application.cache_key, application)

      sources = app.api_client.get_from_cdn('sources', {t: Time.now.to_i}, {uncompressed: true})

      application['languages'].each do |lang|
        locale = lang['locale']
        language = app.api_client.get_from_cdn("#{locale}/language", {t: Time.now.to_i})
        Tml.cache.store(Tml::Language.cache_key(locale), language)

        sources.each do |src|
          source = app.api_client.get_from_cdn("#{locale}/sources/#{src}", {t: Time.now.to_i})
          Tml.cache.store(Tml::Source.cache_key(locale, src), source)
        end
      end

      t1 = Time.now
      Tml.logger.debug("Cache warmup took #{t1-t0}s")
    end


def default_cache_path
      @cache_path ||= begin
        path = Tml.config.cache[:path]
        path ||= 'config/tml'
        FileUtils.mkdir_p(path)
        FileUtils.chmod(0777, path)
        path
      end
    end

def default_cache_path @cache_path ||= begin path = Tml . config . cache [ :path ] path ||= 'config/tml' FileUtils . mkdir_p ( path ) FileUtils . chmod ( 0777 , path ) path end end


def download(cache_path = default_cache_path, version = nil)
      t0 = Time.now
      Tml.logger = Logger.new(STDOUT)

      Tml.logger.debug('Starting cache download...')
      app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])
      extract_version(app, version)

      Tml.logger.debug("Downloading Version: #{Tml.cache.version}")

      archive_name = "#{Tml.cache.version}.tar.gz"
      path = "#{cache_path}/#{archive_name}"
      url = "#{app.cdn_host}/#{Tml.config.application[:key]}/#{archive_name}"

      Tml.logger.debug("Downloading cache file: #{url}")
      open(path, 'wb') do |file|
        file << open(url).read
      end

      Tml.logger.debug('Extracting cache file...')
      version_path = "#{cache_path}/#{Tml.cache.version}"
      Tml::Utils.untar(Tml::Utils.ungzip(File.new(path)), version_path)
      Tml.logger.debug("Cache has been stored in #{version_path}")

      File.unlink(path)

      begin
        current_path = 'current'
        FileUtils.chdir(cache_path)
        FileUtils.rm(current_path) if File.exist?(current_path)
        FileUtils.ln_s(Tml.cache.version.to_s, current_path)
        Tml.logger.debug("The new version #{Tml.cache.version} has been marked as current")
      rescue Exception => ex
        Tml.logger.debug("Could not generate current symlink to the cache path: #{ex.message}")
      end

      t1 = Time.now
      Tml.logger.debug("Cache download took #{t1-t0}s")
    end


def say(message, color=nil)
      @shell ||= Thor::Shell::Basic.new
      @shell.say message, color
    end

def say ( message , color = nil ) @shell ||= Thor :: Shell :: Basic . new @shell . say message , color end


def validate_cache_version(version)
      # if cache version is hardcoded, use it
      if Tml.config.cache[:version]
        return Tml.config.cache[:version]
      end

      return version unless version.is_a?(Hash)
      return 'undefined' unless version['t'].is_a?(Numeric)
      return version['version'] if cache.read_only?

      # if version check interval is disabled, don't try to check for the new
      # cache version on the CDN
      if version_check_interval == -1
        Tml.logger.debug('Cache version check is disabled')
        return version['version']
      end

      expires_at = version['t'] + version_check_interval
      if expires_at < Time.now.to_i
        Tml.logger.debug('Cache version is outdated, needs refresh')
        return 'undefined'
      end

      delta = expires_at - Time.now.to_i
      Tml.logger.debug("Cache version is up to date, expires in #{delta}s")
      version['version']
    end

validate that current cache version hasn't expired

validate that current cache version hasn t expired


def fetch
      self.version = begin
        ver = cache.fetch(CACHE_VERSION_KEY) do
          {'version' => Tml.config.cache[:version] || 'undefined', 't' => cache_timestamp}
        end
        validate_cache_version(ver)
      end
    end

def fetch self . version = begin ver = cache . fetch ( CACHE_VERSION_KEY ) do { 'version' => Tml . config . cache [ :version ] || 'undefined' , 't' => cache_timestamp } end validate_cache_version ( ver ) end end


def [] file, *ps, &exe
			opts = ::Hash === ps.last ? ps.pop : {}
			opts[:env] = self
			name, type, flg = ps[0] || opts[:name], ps[1] || opts[:type], ps[2] || opts[:flags]
			ps.push opts
			@dbs[ [file, name, flg | CREATE]] ||= (type || SBDB::Unknown).new file, *ps, &exe
		end

def [] file , * ps , & exe opts = :: Hash === ps . last ? ps . pop : { } opts [ :env ] = self name , type , flg = ps [ 0 ] || opts [ :name ] , ps [ 1 ] || opts [ :type ] , ps [ 2 ] || opts [ :flags ] ps . push opts @dbs [ [ file , name , flg | CREATE ] ] ||= ( type || SBDB :: Unknown ) . new file , ps , exe end

Returns the DB like open, but if it's already opened,
 it returns the old instance.
 If you use this, never use close. It's possible somebody else use it too.
 The Databases, which are opened, will close, if the Environment will close.

Returns the DB like open but if it s already opened it returns the old instance . If you use this never use close . It s possible somebody else use it too . The Databases which are opened will close if the Environment will close .


def run_strategies(scope)
      Janus::Manager.strategies.each { |name| break if run_strategy(name, scope) }
    end

def run_strategies ( scope ) Janus :: Manager . strategies . each { | name | break if run_strategy ( name , scope ) } end

Runs authentication strategies to log a user in.

Runs authentication strategies to log a user in .


def run_strategy(name, scope)
      strategy = "Janus::Strategies::#{name.to_s.camelize}".constantize.new(scope, self)

      if strategy.valid?
        strategy.authenticate!

        if strategy.success?
          send(strategy.auth_method, strategy.user, :scope => scope)
          Janus::Manager.run_callbacks(:authenticate, strategy.user, self, :scope => scope)
        end
      end

      strategy.success?
    end

Runs a given strategy and returns true if it succeeded.

Runs a given strategy and returns true if it succeeded .


def perform(script)
      export_variables = @params.reverse_merge("PARADUCT_JOB_ID" => @job_id, "PARADUCT_JOB_NAME" => job_name)
      variable_string = export_variables.map { |key, value| %(export #{key}="#{value}";) }.join(" ")

      Array.wrap(script).inject("") do |stdout, command|
        stdout << run_command("#{variable_string} #{command}")
        stdout
      end
    end

def
perform
(
script
)
export_variables
=
@params
.
reverse_merge
(
"PARADUCT_JOB_ID"
=>
@job_id
,
"PARADUCT_JOB_NAME"
=>
job_name
)
variable_string
=
export_variables
.
map
{
|
key
,
value
|
%(export #{key}="#{value}";)
}
.
join
(
" "
)
Array
.
wrap
(
script
)
.
inject
(
""
)
do
|
stdout
,
command
|
stdout
<<
run_command
(
"#{variable_string} #{command}"
)
stdout
end
end

run script with params
 @param script [String, Array<String>] script file, script(s)
 @return [String] stdout
 @raise [Paraduct::Errors::ProcessError] command exited error status


def print_hex(data, chunk_index, cols=80)
      case hex_style
      when 'lower', 'lowercase'
        # encode to lowercase hex with no newlines
        print Sixword::Hex.encode(data)
      when 'finger', 'fingerprint'
        # encode to GPG fingerprint like hex with newlines
        newlines_every = cols / 5
        if chunk_index != 0
          if chunk_index % newlines_every == 0
            print "\n"
          else
            print ' '
          end
        end
        print Sixword::Hex.encode_fingerprint(data)
      when 'colon', 'colons'
        # encode to SSL/SSH fingerprint like hex with colons
        print ':' unless chunk_index == 0
        print Sixword::Hex.encode_colons(data)
      end
    end


def read_input_by_6_words
      word_arr = []

      while true
        line = stream.gets
        if line.nil?
          break # EOF
        end

        line.scan(/\S+/) do |word|
          word_arr << word

          # return the array if we have accumulated 6 words
          if word_arr.length == 6
            yield word_arr
            word_arr.clear
          end
        end
      end

      # yield whatever we have left, if anything
      if !word_arr.empty?
        yield word_arr
      end
    end


def select(query, filters)
      where, *bind_values = conditions(query, filters)
      [
        [
          from(filters),
          where,
          order_by(filters),
          limits(filters)
        ].join(" "),
        *bind_values
      ]
    end

def
select
(
query
,
filters
)
where
,
*
bind_values
=
conditions
(
query
,
filters
)
[
[
from
(
filters
)
,
where
,
order_by
(
filters
)
,
limits
(
filters
)
]
.
join
(
" "
)
,
bind_values
]
end

Initialize a new QueryBuilder for +index_name+.

 @param [Symbol] index_name
   the name of the index being queried
 Build a SphinxQL query for the fulltext search +query+ and filters in +filters+.

 @param [String] query
   the fulltext query to execute (may be empty)

 @param [Hash] filters
   additional attribute filters and other options

 @return [String]
   a SphinxQL query

Initialize a new QueryBuilder for + index_name + .


def update(id, attributes)
      set_attrs, *bind_values = update_attributes(attributes)
      [
        [
          "UPDATE #{@index_name} SET",
          set_attrs,
          "WHERE id = ?"
        ].join(" "),
        *bind_values.push(id)
      ]
    end

def
update
(
id
,
attributes
)
set_attrs
,
*
bind_values
=
update_attributes
(
attributes
)
[
[
"UPDATE #{@index_name} SET"
,
set_attrs
,
"WHERE id = ?"
]
.
join
(
" "
)
,
bind_values
.
push
(
id
)
]
end

Build a SphinxQL query to update the record identified by +id+ with the given attributes.

 @param [Fixnum] id
   the unique ID of the document to update

 @param [Hash] attributes
   a Hash of attributes

 @return [String]
   the SphinxQL to update the record

Build a SphinxQL query to update the record identified by + id + with the given attributes .


def query(sql, *bind_values)
      @pool.acquire { |conn| conn.query(sql, *bind_values).first }
    end

def query ( sql , * bind_values ) @pool . acquire { | conn | conn . query ( sql , bind_values ) . first } end

Execute a single read query.

 @param [String] sql
   a single SphinxQL statement

 @param [Object...] bind_values
   values to be substituted in place of '?' in the query

 @return [Array]
   an array of Hashes containing the matched records

 Note that SphinxQL does not support prepared statements.


def method_missing(method, *args, &block)
      if method.to_s =~ /^asynch?_(.*)/
        if instance_methods(false).detect{|meth| meth.to_s == $1 }
          Woodhouse.dispatch(@worker_name, $1, args.first)
        else
          super
        end
      else
        super
      end
    end

def method_missing ( method , * args , & block ) if method . to_s =~ / / if instance_methods ( false ) . detect { | meth | meth . to_s == $1 } Woodhouse . dispatch ( @worker_name , $1 , args . first ) else super end else super end end

You can dispatch a job +baz+ on class +FooBar+ by calling FooBar.async_baz.

You can dispatch a job + baz + on class + FooBar + by calling FooBar . async_baz .


def add_node(node)
      if node.respond_to?(:to_sym)
        node = Woodhouse::Layout::Node.new(node.to_sym)
      end
      expect_arg :node, Woodhouse::Layout::Node, node
      @nodes << node
      node
    end

def add_node ( node ) if node . respond_to? ( :to_sym ) node = Woodhouse :: Layout :: Node . new ( node . to_sym ) end expect_arg :node , Woodhouse :: Layout :: Node , node @nodes << node node end

Adds a Node to this layout. If +node+ is a Symbol, a Node will be
 automatically created with that name.

   # Example:

   layout.add_node Woodhouse::Layout::Node.new(:isis)

   # Is equivalent to

   layout.add_node :isis

Adds a Node to this layout . If + node + is a Symbol a Node will be automatically created with that name .


def node(name)
      name = name.to_sym
      @nodes.detect{|node|
        node.name == name
      }
    end

def node ( name ) name = name . to_sym @nodes . detect { | node | node . name == name } end

Looks up a Node by name and returns it .


def canonical(attribute_list)
      case attribute_list
      when nil then {}
      when Hash then attribute_list
      when Array
        attribute_list.map do |attributes|
          case attributes
          when Symbol
            {attributes => AUTO}
          when Hash
            attributes
          else
            raise "Unexpected attributes #{attributes}"
          end
        end
        .inject({}, :merge)
      else
        raise "Unexpected attribute_list #{attribute_list}"
      end
    end

Converts an attribute_list to a single Hash;
 some of the values may be set to AUTO.

   canonical [:foo, {:bar => 42}]
    # => {:foo => AUTO, :bar => 42}

Converts an attribute_list to a single Hash ; some of the values may be set to AUTO .


def imagine(character_or_model, attributes = nil)
      character = to_character(character_or_model)
      prev, @building = @building, [] # because method might be re-entrant
      CharacterBuilder.new(character).build(attributes) do |ar|
        ar.save!
        # While errors on records associated with :has_many will prevent records
        # from being saved, they won't for :belongs_to, so:
        @building.each do |built|
          raise ActiveRecord::RecordInvalid, built unless built.persisted? || built.valid?
        end
        Scheherazade.log(:saving, character, ar)
        handle_callbacks(@building)
      end
    ensure
      @built.concat(@building)
      @building = prev
    end

Creates a character with the given attributes

 A character can be designated either by the model (e.g. `User`), the corresponding
 symbol (`:user`) or the symbol for a specialized type of character, defined using +fill+
 (e.g. `:admin`).

 The attributes can be nil, a list of symbols, a hash or a combination of both
 These, along with attributes passed to +fill+ for the current stories
 and the mandatory attributes for the model will be provided.

 If some fields generate validation errors, they will be provided also.

 For associations, the values can also be a character (Symbol or Model),
 integers (meaning the default Model * that integer) or arrays of characters.

    imagine(:user, :account, :company => :fortune_500_company, :emails => 3)

 Similarly:

    User.imagine(...)
    :user.imagine(...)

 This record (and any other imagined through associations) will become the
 current character in the current story:

    story.current[User] # => nil
    story.tell do
      :admin.imagine # => A User record
      story.current[:admin] # => same
      story.current[User]   # => same
    end
    story.current[User] # => nil


def with(temp_current)
      keys = temp_current.keys.map{|k| to_character(k)}
      previous_values = current.values_at(*keys)
      current.merge!(Hash[keys.zip(temp_current.values)])
      yield
    ensure
      current.merge!(Hash[keys.zip(previous_values)])
    end

def with ( temp_current ) keys = temp_current . keys . map { | k | to_character ( k ) } previous_values = current . values_at ( keys ) current . merge! ( Hash [ keys . zip ( temp_current . values ) ] ) yield ensure current . merge! ( Hash [ keys . zip ( previous_values ) ] ) end

Allows one to temporarily override the current characters while
 the given block executes


def failure(exception_class_or_message, message_or_nil = nil)
      blank.tap do |d|
        d.fail(
          case exception_class_or_message
          when Exception
            raise ArgumentError, "can't specify both exception and message" if message_or_nil
            exception_class_or_message
          when Class
            exception_class_or_message.new(message_or_nil)
          else
            RuntimeError.new(exception_class_or_message.to_s)
          end)
      end
    end

Return a Deferrable which immediately fails with an exception.

 @overload failure(message)
   Passes +RuntimeError.new(message)+ to errbacks.
 @overload failure(exception_class)
   Passes +exception_class.new+ to errbacks.
 @overload failure(exception_class, message)
   Passes +exception_class.new(message)+ to errbacks.
 @overload failure(exception)
   Passes +exception+ to errbacks.

Return a Deferrable which immediately fails with an exception .


def file_length
      if self.audio.is_a?(File) && self.audio.size > MAX_FILE_SIZE
        self.errors.add :audio, "It's length is excesive. #{MAX_FILE_SIZE} is the limit."
        return false
      end

      return true
    end

Function to check that the file size isn't excesive.

Function to check that the file size isn t excesive .


def api_call method, payload
      raise ArgumentError, "API method not specified." if method.blank?

      payload ||= {}

      res = @conn.post method.to_s, payload

      raise Faraday::Error, "Wrong response: #{res.inspect}" if (res.status != 200)

      return res
    end

def
api_call
method
,
payload
raise
ArgumentError
,
"API method not specified."
if
method
.
blank?
payload
||=
{
}
res
=
@conn
.
post
method
.
to_s
,
payload
raise
Faraday
::
Error
,
"Wrong response: #{res.inspect}"
if
(
res
.
status
!=
200
)
return
res
end


def multi_search(queries)
      unless queries.kind_of?(Hash)
        raise ArgumentError, "Argument must be a Hash of named queries (#{queries.class} given)"
      end

      stmts       = []
      bind_values = []

      queries.each do |key, args|
        str, *values = @builder.select(*extract_query_data(args))
        stmts.push(str, "SHOW META")
        bind_values.push(*values)
      end

      rs = @conn.multi_query(stmts.join(";\n"), *bind_values)

      Hash[].tap do |result|
        queries.keys.each do |key|
          records, meta = rs.shift, rs.shift
          result[key] = meta_to_hash(meta).tap do |r|
            r[:records] = records.map { |hash|
              hash.inject({}) { |o, (k, v)| o.merge!(k.to_sym => v) }
            }
          end
        end
      end
    end

Perform a a batch search on the index.

 A Hash of queries is passed, whose keys are used to collate the results in
 the return value.

 Each query may either by a string (fulltext search), a Hash (attribute search)
 or an array containing both.  In other words, the same arguments accepted by
 the #search method.

 @example
   index.multi_search(
     cat_results: ["cats", { author_id: 57 }],
     dog_results: ["dogs", { author_id: 57 }]
   )

 @param [Hash] queries
   a hash whose keys map to queries

 @return [Hash]
   a Hash whose keys map 1:1 with the input Hash, each element containing the
   same results as those returned by the #search method.


def has_whereabouts klass=:address, *args
      options = args.extract_options!
      # extend Address with class name if not defined.
      unless klass == :address || Object.const_defined?(klass.to_s.camelize)
        create_address_class(klass.to_s.camelize)
      end

      # Set the has_one relationship and accepts_nested_attributes_for.
      has_one klass, :as => :addressable, :dependent => :destroy
      accepts_nested_attributes_for klass

      # Define a singleton on the class that returns an array
      # that includes the address fields to validate presence of
      # or an empty array
      if options[:validate] && options[:validate].is_a?(Array)
        validators = options[:validate]
        set_validators(klass, validators)
      else
        validators = []
      end
      define_singleton_method validate_singleton_for(klass) do validators end

      # Check for geocode in options and confirm geocoder is defined.
      # Also defines a singleton to return a boolean about geocoding.
      if options[:geocode] && options[:geocode] == true && defined?(Geocoder)
        geocode = true
        set_geocoding(klass)
      else
        geocode = false
      end
      define_singleton_method geocode_singleton_for(klass) do geocode end
    end

Accepts a symbol that will define the inherited
 type of Address.  Defaults to the parent class.

Accepts a symbol that will define the inherited type of Address . Defaults to the parent class .


def set_validators klass, fields=[]
      _single = validate_singleton_for(klass)
      klass.to_s.camelize.constantize.class_eval do
        fields.each do |f|
          validates_presence_of f,
            :if => lambda {|a| a.addressable_type.constantize.send(_single).include?(f)}
        end
      end
    end

def set_validators klass , fields = [ ] _single = validate_singleton_for ( klass ) klass . to_s . camelize . constantize . class_eval do fields . each do | f | validates_presence_of f , :if => lambda { | a | a . addressable_type . constantize . send ( _single ) . include? ( f ) } end end end

Sets validates_presence_of fields for the Address based on the
 singleton method created on the Address addressable_type class.

Sets validates_presence_of fields for the Address based on the singleton method created on the Address addressable_type class .


def create_address_class(class_name, &block)
      klass = Class.new Address, &block
      Object.const_set class_name, klass
    end

def create_address_class ( class_name , & block ) klass = Class . new Address , block Object . const_set class_name , klass end

Generate a new class using Address as the superclass.
 Accepts a string defining the inherited type.

Generate a new class using Address as the superclass . Accepts a string defining the inherited type .


def event_loop
      Qwirk.logger.debug "#{self}: Starting receive loop"
      @start_worker_time = Time.now
      until @stopped || (config.stopped? && @impl.ready_to_stop?)
        Qwirk.logger.debug "#{self}: Waiting for read"
        @start_read_time = Time.now
        msg = @impl.receive_message
        if msg
          @start_processing_time = Time.now
          Qwirk.logger.debug {"#{self}: Done waiting for read in #{@start_processing_time - @start_read_time} seconds"}
          delta = config.timer.measure do
            @processing_mutex.synchronize do
              on_message(msg)
              @impl.acknowledge_message(msg)
            end
          end
          Qwirk.logger.info {"#{self}::on_message (#{'%.1f' % delta}ms)"} if self.config.log_times
          Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)
        end
      end
      Qwirk.logger.info "#{self}: Exiting"
    rescue Exception => e
      @status = "Terminated: #{e.message}"
      Qwirk.logger.error "#{self}: Exception, thread terminating: #{e.message}\n\t#{e.backtrace.join("\n\t")}"
    ensure
      @status = 'Stopped'
      Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)
      config.worker_stopped(self)
    end

Start the event loop for handling messages off the queue


def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
      attrs = {}
      attribute_names.each do |name|
        if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
          if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))
            value = read_attribute(name)
            if self.class.columns_hash[name].type == :hstore && value && value.is_a?(Hash)
              value = value.to_hstore # Done!
            elsif value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time) || value.is_a?(Hash) || value.is_a?(Array))
              value = value.to_yaml
            end
            attrs[self.class.arel_table[name]] = value
          end
        end
      end
      attrs
    end

def
arel_attributes_values
(
include_primary_key
=
true
,
include_readonly_attributes
=
true
,
attribute_names
=
@attributes
.
keys
)
attrs
=
{
}
attribute_names
.
each
do
|
name
|
if
(
column
=
column_for_attribute
(
name
)
)
&&
(
include_primary_key
||
!
column
.
primary
)
if
include_readonly_attributes
||
(
!
include_readonly_attributes
&&
!
self
.
class
.
readonly_attributes
.
include?
(
name
)
)
value
=
read_attribute
(
name
)
if
self
.
class
.
columns_hash
[
name
]
.
type
==
:hstore
&&
value
&&
value
.
is_a?
(
Hash
)
value
=
value
.
to_hstore
# Done!
elsif
value
&&
self
.
class
.
serialized_attributes
.
has_key?
(
name
)
&&
(
value
.
acts_like?
(
:date
)
||
value
.
acts_like?
(
:time
)
||
value
.
is_a?
(
Hash
)
||
value
.
is_a?
(
Array
)
)
value
=
value
.
to_yaml
end
attrs
[
self
.
class
.
arel_table
[
name
]
]
=
value
end
end
end
attrs
end

This method is replaced for Rails 3 compatibility.
 All I do is add the condition when the field is a hash that converts the value
 to hstore format.
 IMHO this should be delegated to the column, so it won't be necessary to rewrite all
 this method.

This method is replaced for Rails 3 compatibility . All I do is add the condition when the field is a hash that converts the value to hstore format . IMHO this should be delegated to the column so it won t be necessary to rewrite all this method .


def requires_version(cmd, version_)
      v = check_version(version_)
      raise NoMethodError, format('%s is not supported in Bugzilla %s', cmd, v[1]) unless v[0]
    end

def
requires_version
(
cmd
,
version_
)
v
=
check_version
(
version_
)
raise
NoMethodError
,
format
(
'%s is not supported in Bugzilla %s'
,
cmd
,
v
[
1
]
)
unless
v
[
0
]
end

def check_version
 rdoc

 ==== Bugzilla::Bugzilla#requires_version(cmd, version_)

 Raise an exception if the Bugzilla doesn't satisfy
 the requirement of the _version_.


def run
      begin
        Clacks.logger.info "Clacks v#{Clacks::VERSION} started"
        if Clacks.config[:pop3]
          run_pop3
        elsif Clacks.config[:imap]
          run_imap
        else
          raise "Either a POP3 or an IMAP server must be configured"
        end
      rescue Exception => e
        fatal(e)
      end
    end


def imap_validate_options(options)
      options ||= {}
      options[:mailbox] ||= 'INBOX'
      options[:count]   ||= 5
      options[:order]   ||= :asc
      options[:what]    ||= :first
      options[:keys]    ||= 'ALL'
      options[:delete_after_find] ||= false
      options[:mailbox] = Net::IMAP.encode_utf7(options[:mailbox])
      if options[:archivebox]
        options[:archivebox] = Net::IMAP.encode_utf7(options[:archivebox])
      end
      options
    end

def imap_validate_options ( options ) options ||= { } options [ :mailbox ] ||= 'INBOX' options [ :count ] ||= 5 options [ :order ] ||= :asc options [ :what ] ||= :first options [ :keys ] ||= 'ALL' options [ :delete_after_find ] ||= false options [ :mailbox ] = Net :: IMAP . encode_utf7 ( options [ :mailbox ] ) if options [ :archivebox ] options [ :archivebox ] = Net :: IMAP . encode_utf7 ( options [ :archivebox ] ) end options end

Follows mostly the defaults from the Mail gem


def imap_find(imap)
      options = Clacks.config[:find_options]
      delete_after_find = options[:delete_after_find]
      begin
        break if stopping?
        uids = imap.uid_search(options[:keys] || 'ALL')
        uids.reverse! if options[:what].to_sym == :last
        uids = uids.first(options[:count]) if options[:count].is_a?(Integer)
        uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||
                         (options[:what].to_sym != :last && options[:order].to_sym == :desc)
        processed = 0
        expunge = false
        uids.each do |uid|
          break if stopping?
          source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']
          mail = nil
          begin
            mail = Mail.new(source)
            mail.mark_for_delete = true if delete_after_find
            Clacks.config[:on_mail].call(mail)
          rescue StandardError => e
            Clacks.logger.error(e.message)
            Clacks.logger.error(e.backtrace)
          end
          begin
            imap.uid_copy(uid, options[:archivebox]) if options[:archivebox]
            if delete_after_find && (mail.nil? || mail.is_marked_for_delete?)
              expunge = true
              imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED])
            end
          rescue StandardError => e
            Clacks.logger.error(e.message)
          end
          processed += 1
        end
        imap.expunge if expunge
      end while uids.any? && processed == uids.length
    end

def imap_find ( imap ) options = Clacks . config [ :find_options ] delete_after_find = options [ :delete_after_find ] begin break if stopping? uids = imap . uid_search ( options [ :keys ] || 'ALL' ) uids . reverse! if options [ :what ] . to_sym == :last uids = uids . first ( options [ :count ] ) if options [ :count ] . is_a? ( Integer ) uids . reverse! if ( options [ :what ] . to_sym == :last && options [ :order ] . to_sym == :asc ) || ( options [ :what ] . to_sym != :last && options [ :order ] . to_sym == :desc ) processed = 0 expunge = false uids . each do | uid | break if stopping? source = imap . uid_fetch ( uid , [ 'RFC822' ] ) . first . attr [ 'RFC822' ] mail = nil begin mail = Mail . new ( source ) mail . mark_for_delete = true if delete_after_find Clacks . config [ :on_mail ] . call ( mail ) rescue StandardError => e Clacks . logger . error ( e . message ) Clacks . logger . error ( e . backtrace ) end begin imap . uid_copy ( uid , options [ :archivebox ] ) if options [ :archivebox ] if delete_after_find && ( mail . nil? || mail . is_marked_for_delete? ) expunge = true imap . uid_store ( uid , "+FLAGS" , [ Net :: IMAP :: DELETED ] ) end rescue StandardError => e Clacks . logger . error ( e . message ) end processed += 1 end imap . expunge if expunge end while uids . any? && processed == uids . length end

Keep processing emails until nothing is found anymore,
 or until a QUIT signal is received to stop the process.

Keep processing emails until nothing is found anymore or until a QUIT signal is received to stop the process .


def rainbow(str)
    i=0
    ret = ''
    str=str.to_s
    while(i < str.length)
      ch = str[i]
      palette = $color_db[0][i % $color_db[0].length ]
      ret << (colora(palette,str[i,1]))
      i += 1
    end
    ret
  end

def rainbow ( str ) i = 0 ret = '' str = str . to_s while ( i < str . length ) ch = str [ i ] palette = $color_db [ 0 ] [ i % $color_db [ 0 ] . length ] ret << ( colora ( palette , str [ i , 1 ] ) ) i += 1 end ret end


def large_enough_prime(input)
      standard_primes.each do |prime|
        return prime if prime > input
      end
      fail CannotFindLargeEnoughPrime, "Input too large"
    end

def
large_enough_prime
(
input
)
standard_primes
.
each
do
|
prime
|
return
prime
if
prime
>
input
end
fail
CannotFindLargeEnoughPrime
,
"Input too large"
end

Retrieves the next largest prime for the largest number in batch

 Example

   Prime.large_enough_prime 4
   # => 7

 @param input [Integer] the integer to find the next largest prime for
 @return [Integer] the next largest prime
 @raise [CannotFindLargeEnoughPrime] raised when input is too large and
   no large enough prime can be found


def enhance_content(value, separator = ', ')
      value.is_a?(Array) ? value.join(separator) : value
    end

def
enhance_content
(
value
,
separator
=
', '
)
value
.
is_a?
(
Array
)
value
.
join
(
separator
)
:
value
end

Combines array into a string with given separator