repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
agoragames/amico | lib/amico/relationships.rb | Amico.Relationships.pending_page_count | def pending_page_count(id, page_size = Amico.page_size, scope = Amico.default_scope_key)
total_pages("#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{id}", page_size)
end | ruby | def pending_page_count(id, page_size = Amico.page_size, scope = Amico.default_scope_key)
total_pages("#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{id}", page_size)
end | [
"def",
"pending_page_count",
"(",
"id",
",",
"page_size",
"=",
"Amico",
".",
"page_size",
",",
"scope",
"=",
"Amico",
".",
"default_scope_key",
")",
"total_pages",
"(",
"\"#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{id}\"",
",",
"page_size",
")",
"end"
] | Count the number of pages of pending relationships for an individual.
@param id [String] ID of the individual.
@param page_size [int] Page size (default: Amico.page_size).
@param scope [String] Scope for the call.
Examples
Amico.follow(11, 1)
Amico.follow(12, 1)
Amico.pending_page_count(1) # 1
@return the number of pages of pending relationships for an individual. | [
"Count",
"the",
"number",
"of",
"pages",
"of",
"pending",
"relationships",
"for",
"an",
"individual",
"."
] | 60309bd2f9466bce3ec42235c44f4dae55f6f45e | https://github.com/agoragames/amico/blob/60309bd2f9466bce3ec42235c44f4dae55f6f45e/lib/amico/relationships.rb#L608-L610 | train |
agoragames/amico | lib/amico/relationships.rb | Amico.Relationships.pending_with_page_count | def pending_with_page_count(id, page_size = Amico.page_size, scope = Amico.default_scope_key)
total_pages("#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{id}", page_size)
end | ruby | def pending_with_page_count(id, page_size = Amico.page_size, scope = Amico.default_scope_key)
total_pages("#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{id}", page_size)
end | [
"def",
"pending_with_page_count",
"(",
"id",
",",
"page_size",
"=",
"Amico",
".",
"page_size",
",",
"scope",
"=",
"Amico",
".",
"default_scope_key",
")",
"total_pages",
"(",
"\"#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{id}\"",
",",
"page_size",
")",
"end"
] | Count the number of pages of individuals waiting to approve another individual.
@param id [String] ID of the individual.
@param page_size [int] Page size (default: Amico.page_size).
@param scope [String] Scope for the call.
Examples
Amico.follow(1, 11)
Amico.follow(1, 12)
Amico.pending_with_page_count(1) # 1
@return the number of pages of individuals waiting to approve another individual. | [
"Count",
"the",
"number",
"of",
"pages",
"of",
"individuals",
"waiting",
"to",
"approve",
"another",
"individual",
"."
] | 60309bd2f9466bce3ec42235c44f4dae55f6f45e | https://github.com/agoragames/amico/blob/60309bd2f9466bce3ec42235c44f4dae55f6f45e/lib/amico/relationships.rb#L625-L627 | train |
agoragames/amico | lib/amico/relationships.rb | Amico.Relationships.count | def count(id, type, scope = Amico.default_scope_key)
validate_relationship_type(type)
self.send("#{type.to_s}_count".to_sym, id, scope)
end | ruby | def count(id, type, scope = Amico.default_scope_key)
validate_relationship_type(type)
self.send("#{type.to_s}_count".to_sym, id, scope)
end | [
"def",
"count",
"(",
"id",
",",
"type",
",",
"scope",
"=",
"Amico",
".",
"default_scope_key",
")",
"validate_relationship_type",
"(",
"type",
")",
"self",
".",
"send",
"(",
"\"#{type.to_s}_count\"",
".",
"to_sym",
",",
"id",
",",
"scope",
")",
"end"
] | Retrieve a count of all of a given type of relationship for the specified id.
@param id [String] ID of the individual.
@param type [Symbol] One of :following, :followers, :reciprocated, :blocked, :blocked_by, :pending, :pending_with.
@param scope [String] Scope for the call.
@return Count of all of a given type of relationship for the specified id. | [
"Retrieve",
"a",
"count",
"of",
"all",
"of",
"a",
"given",
"type",
"of",
"relationship",
"for",
"the",
"specified",
"id",
"."
] | 60309bd2f9466bce3ec42235c44f4dae55f6f45e | https://github.com/agoragames/amico/blob/60309bd2f9466bce3ec42235c44f4dae55f6f45e/lib/amico/relationships.rb#L647-L650 | train |
agoragames/amico | lib/amico/relationships.rb | Amico.Relationships.page_count | def page_count(id, type, page_size = Amico.page_size, scope = Amico.default_scope_key)
validate_relationship_type(type)
self.send("#{type.to_s}_page_count".to_sym, id, page_size, scope)
end | ruby | def page_count(id, type, page_size = Amico.page_size, scope = Amico.default_scope_key)
validate_relationship_type(type)
self.send("#{type.to_s}_page_count".to_sym, id, page_size, scope)
end | [
"def",
"page_count",
"(",
"id",
",",
"type",
",",
"page_size",
"=",
"Amico",
".",
"page_size",
",",
"scope",
"=",
"Amico",
".",
"default_scope_key",
")",
"validate_relationship_type",
"(",
"type",
")",
"self",
".",
"send",
"(",
"\"#{type.to_s}_page_count\"",
".",
"to_sym",
",",
"id",
",",
"page_size",
",",
"scope",
")",
"end"
] | Retrieve a page count of a given type of relationship for the specified id.
@param id [String] ID of the individual.
@param type [Symbol] One of :following, :followers, :reciprocated, :blocked, :blocked_by, :pending, :pending_with.
@param page_size [int] Page size (default: Amico.page_size).
@param scope [String] Scope for the call.
@return Page count of a given type of relationship for the specified id. | [
"Retrieve",
"a",
"page",
"count",
"of",
"a",
"given",
"type",
"of",
"relationship",
"for",
"the",
"specified",
"id",
"."
] | 60309bd2f9466bce3ec42235c44f4dae55f6f45e | https://github.com/agoragames/amico/blob/60309bd2f9466bce3ec42235c44f4dae55f6f45e/lib/amico/relationships.rb#L660-L663 | train |
agoragames/amico | lib/amico/relationships.rb | Amico.Relationships.add_following_followers_reciprocated | def add_following_followers_reciprocated(from_id, to_id, scope)
Amico.redis.multi do
Amico.redis.zadd("#{Amico.namespace}:#{Amico.following_key}:#{scope}:#{from_id}", Time.now.to_i, to_id)
Amico.redis.zadd("#{Amico.namespace}:#{Amico.followers_key}:#{scope}:#{to_id}", Time.now.to_i, from_id)
Amico.redis.zrem("#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{to_id}", from_id)
Amico.redis.zrem("#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{from_id}", to_id)
end
if reciprocated?(from_id, to_id, scope)
Amico.redis.multi do
Amico.redis.zadd("#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{from_id}", Time.now.to_i, to_id)
Amico.redis.zadd("#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{to_id}", Time.now.to_i, from_id)
end
end
end | ruby | def add_following_followers_reciprocated(from_id, to_id, scope)
Amico.redis.multi do
Amico.redis.zadd("#{Amico.namespace}:#{Amico.following_key}:#{scope}:#{from_id}", Time.now.to_i, to_id)
Amico.redis.zadd("#{Amico.namespace}:#{Amico.followers_key}:#{scope}:#{to_id}", Time.now.to_i, from_id)
Amico.redis.zrem("#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{to_id}", from_id)
Amico.redis.zrem("#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{from_id}", to_id)
end
if reciprocated?(from_id, to_id, scope)
Amico.redis.multi do
Amico.redis.zadd("#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{from_id}", Time.now.to_i, to_id)
Amico.redis.zadd("#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{to_id}", Time.now.to_i, from_id)
end
end
end | [
"def",
"add_following_followers_reciprocated",
"(",
"from_id",
",",
"to_id",
",",
"scope",
")",
"Amico",
".",
"redis",
".",
"multi",
"do",
"Amico",
".",
"redis",
".",
"zadd",
"(",
"\"#{Amico.namespace}:#{Amico.following_key}:#{scope}:#{from_id}\"",
",",
"Time",
".",
"now",
".",
"to_i",
",",
"to_id",
")",
"Amico",
".",
"redis",
".",
"zadd",
"(",
"\"#{Amico.namespace}:#{Amico.followers_key}:#{scope}:#{to_id}\"",
",",
"Time",
".",
"now",
".",
"to_i",
",",
"from_id",
")",
"Amico",
".",
"redis",
".",
"zrem",
"(",
"\"#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{to_id}\"",
",",
"from_id",
")",
"Amico",
".",
"redis",
".",
"zrem",
"(",
"\"#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{from_id}\"",
",",
"to_id",
")",
"end",
"if",
"reciprocated?",
"(",
"from_id",
",",
"to_id",
",",
"scope",
")",
"Amico",
".",
"redis",
".",
"multi",
"do",
"Amico",
".",
"redis",
".",
"zadd",
"(",
"\"#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{from_id}\"",
",",
"Time",
".",
"now",
".",
"to_i",
",",
"to_id",
")",
"Amico",
".",
"redis",
".",
"zadd",
"(",
"\"#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{to_id}\"",
",",
"Time",
".",
"now",
".",
"to_i",
",",
"from_id",
")",
"end",
"end",
"end"
] | Add the following, followers and check for a reciprocated relationship. To be used from the
+follow+ and +accept+ methods.
@param from_id [String] The ID of the individual establishing the follow relationship.
@param to_id [String] The ID of the individual to be followed. | [
"Add",
"the",
"following",
"followers",
"and",
"check",
"for",
"a",
"reciprocated",
"relationship",
".",
"To",
"be",
"used",
"from",
"the",
"+",
"follow",
"+",
"and",
"+",
"accept",
"+",
"methods",
"."
] | 60309bd2f9466bce3ec42235c44f4dae55f6f45e | https://github.com/agoragames/amico/blob/60309bd2f9466bce3ec42235c44f4dae55f6f45e/lib/amico/relationships.rb#L690-L704 | train |
agoragames/amico | lib/amico/relationships.rb | Amico.Relationships.total_pages | def total_pages(key, page_size)
(Amico.redis.zcard(key) / page_size.to_f).ceil
end | ruby | def total_pages(key, page_size)
(Amico.redis.zcard(key) / page_size.to_f).ceil
end | [
"def",
"total_pages",
"(",
"key",
",",
"page_size",
")",
"(",
"Amico",
".",
"redis",
".",
"zcard",
"(",
"key",
")",
"/",
"page_size",
".",
"to_f",
")",
".",
"ceil",
"end"
] | Count the total number of pages for a given key in a Redis sorted set.
@param key [String] Redis key.
@param page_size [int] Page size from which to calculate total pages.
@return total number of pages for a given key in a Redis sorted set. | [
"Count",
"the",
"total",
"number",
"of",
"pages",
"for",
"a",
"given",
"key",
"in",
"a",
"Redis",
"sorted",
"set",
"."
] | 60309bd2f9466bce3ec42235c44f4dae55f6f45e | https://github.com/agoragames/amico/blob/60309bd2f9466bce3ec42235c44f4dae55f6f45e/lib/amico/relationships.rb#L727-L729 | train |
agoragames/amico | lib/amico/relationships.rb | Amico.Relationships.members | def members(key, options = default_paging_options)
options = default_paging_options.dup.merge!(options)
if options[:page] < 1
options[:page] = 1
end
if options[:page] > total_pages(key, options[:page_size])
options[:page] = total_pages(key, options[:page_size])
end
index_for_redis = options[:page] - 1
starting_offset = (index_for_redis * options[:page_size])
if starting_offset < 0
starting_offset = 0
end
ending_offset = (starting_offset + options[:page_size]) - 1
Amico.redis.zrevrange(key, starting_offset, ending_offset, :with_scores => false)
end | ruby | def members(key, options = default_paging_options)
options = default_paging_options.dup.merge!(options)
if options[:page] < 1
options[:page] = 1
end
if options[:page] > total_pages(key, options[:page_size])
options[:page] = total_pages(key, options[:page_size])
end
index_for_redis = options[:page] - 1
starting_offset = (index_for_redis * options[:page_size])
if starting_offset < 0
starting_offset = 0
end
ending_offset = (starting_offset + options[:page_size]) - 1
Amico.redis.zrevrange(key, starting_offset, ending_offset, :with_scores => false)
end | [
"def",
"members",
"(",
"key",
",",
"options",
"=",
"default_paging_options",
")",
"options",
"=",
"default_paging_options",
".",
"dup",
".",
"merge!",
"(",
"options",
")",
"if",
"options",
"[",
":page",
"]",
"<",
"1",
"options",
"[",
":page",
"]",
"=",
"1",
"end",
"if",
"options",
"[",
":page",
"]",
">",
"total_pages",
"(",
"key",
",",
"options",
"[",
":page_size",
"]",
")",
"options",
"[",
":page",
"]",
"=",
"total_pages",
"(",
"key",
",",
"options",
"[",
":page_size",
"]",
")",
"end",
"index_for_redis",
"=",
"options",
"[",
":page",
"]",
"-",
"1",
"starting_offset",
"=",
"(",
"index_for_redis",
"*",
"options",
"[",
":page_size",
"]",
")",
"if",
"starting_offset",
"<",
"0",
"starting_offset",
"=",
"0",
"end",
"ending_offset",
"=",
"(",
"starting_offset",
"+",
"options",
"[",
":page_size",
"]",
")",
"-",
"1",
"Amico",
".",
"redis",
".",
"zrevrange",
"(",
"key",
",",
"starting_offset",
",",
"ending_offset",
",",
":with_scores",
"=>",
"false",
")",
"end"
] | Retrieve a page of items from a Redis sorted set without scores.
@param key [String] Redis key.
@param options [Hash] Default options for paging.
@return a page of items from a Redis sorted set without scores. | [
"Retrieve",
"a",
"page",
"of",
"items",
"from",
"a",
"Redis",
"sorted",
"set",
"without",
"scores",
"."
] | 60309bd2f9466bce3ec42235c44f4dae55f6f45e | https://github.com/agoragames/amico/blob/60309bd2f9466bce3ec42235c44f4dae55f6f45e/lib/amico/relationships.rb#L737-L756 | train |
weenhanceit/gaapi | lib/gaapi/response.rb | GAAPI.Response.csv | def csv
@csv ||= CSV.generate do |csv|
reports.each(&:report).each do |report|
# If there are no dimensions, but totals, we need to put an extra
# column at the start for the word "Total".
# I don't see how totals will be different than the metrics if you
# don't specify dimensions, but whatever.
totals_column = report.totals? && !report.dimensions? ? [nil] : []
csv << totals_column + report.headers
report.rows.each { |row| csv << totals_column + row.to_a }
next unless report.totals? # Rubocop did this. Not sure I like it.
csv << ["Totals"] + if !report.dimensions?
report.totals
else
report.totals[1..-1]
end
end
end
end | ruby | def csv
@csv ||= CSV.generate do |csv|
reports.each(&:report).each do |report|
# If there are no dimensions, but totals, we need to put an extra
# column at the start for the word "Total".
# I don't see how totals will be different than the metrics if you
# don't specify dimensions, but whatever.
totals_column = report.totals? && !report.dimensions? ? [nil] : []
csv << totals_column + report.headers
report.rows.each { |row| csv << totals_column + row.to_a }
next unless report.totals? # Rubocop did this. Not sure I like it.
csv << ["Totals"] + if !report.dimensions?
report.totals
else
report.totals[1..-1]
end
end
end
end | [
"def",
"csv",
"@csv",
"||=",
"CSV",
".",
"generate",
"do",
"|",
"csv",
"|",
"reports",
".",
"each",
"(",
"&",
":report",
")",
".",
"each",
"do",
"|",
"report",
"|",
"totals_column",
"=",
"report",
".",
"totals?",
"&&",
"!",
"report",
".",
"dimensions?",
"?",
"[",
"nil",
"]",
":",
"[",
"]",
"csv",
"<<",
"totals_column",
"+",
"report",
".",
"headers",
"report",
".",
"rows",
".",
"each",
"{",
"|",
"row",
"|",
"csv",
"<<",
"totals_column",
"+",
"row",
".",
"to_a",
"}",
"next",
"unless",
"report",
".",
"totals?",
"csv",
"<<",
"[",
"\"Totals\"",
"]",
"+",
"if",
"!",
"report",
".",
"dimensions?",
"report",
".",
"totals",
"else",
"report",
".",
"totals",
"[",
"1",
"..",
"-",
"1",
"]",
"end",
"end",
"end",
"end"
] | Convert a response from Google Analytics into a comma-separated values
format file.
@return [String] The result of the query formatted as a comma-separated
values string. | [
"Convert",
"a",
"response",
"from",
"Google",
"Analytics",
"into",
"a",
"comma",
"-",
"separated",
"values",
"format",
"file",
"."
] | 20d25bd06b2e0cccc86ca1ea1baaac6be045355a | https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/response.rb#L25-L43 | train |
drish/hyperb | lib/hyperb/containers/containers.rb | Hyperb.Containers.containers | def containers(params = {})
path = '/containers/json'
query = {}
query.merge!(params)
response = JSON.parse(Hyperb::Request.new(self, path, query, 'get').perform)
response.map { |container| Hyperb::Container.new(container) }
end | ruby | def containers(params = {})
path = '/containers/json'
query = {}
query.merge!(params)
response = JSON.parse(Hyperb::Request.new(self, path, query, 'get').perform)
response.map { |container| Hyperb::Container.new(container) }
end | [
"def",
"containers",
"(",
"params",
"=",
"{",
"}",
")",
"path",
"=",
"'/containers/json'",
"query",
"=",
"{",
"}",
"query",
".",
"merge!",
"(",
"params",
")",
"response",
"=",
"JSON",
".",
"parse",
"(",
"Hyperb",
"::",
"Request",
".",
"new",
"(",
"self",
",",
"path",
",",
"query",
",",
"'get'",
")",
".",
"perform",
")",
"response",
".",
"map",
"{",
"|",
"container",
"|",
"Hyperb",
"::",
"Container",
".",
"new",
"(",
"container",
")",
"}",
"end"
] | list existing containers
@see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Container/list.html
@raise [Hyperb::Error::Unauthorized] raised when credentials are not valid.
@raise [Hyperb::Error::InternalServerError] raised when 5xx is returned from hyper.
@return [Hyperb::Container] Array of Hyperb::Container.
@param params [Hash] A customizable set of params.
@option params [Boolean] :all show all containers, false by default
@option params [Boolean] :size show containers size
@option params [String] :limit show `limit` last created containers.
@option params [String] :since show only containers created since Id.
@option params [String] :before only containers created before Id.
TODO: @option params [Hash] :filters JSON encoded value of the filters. | [
"list",
"existing",
"containers"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/containers/containers.rb#L31-L37 | train |
drish/hyperb | lib/hyperb/containers/containers.rb | Hyperb.Containers.remove_container | def remove_container(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'id')
path = '/containers/' + params[:id]
query = {}
query[:v] = params[:v] if params.key?(:v)
query[:force] = params[:force] if params.key?(:force)
response = JSON.parse(Hyperb::Request.new(self, path, query, 'delete').perform)
downcase_symbolize(response)
end | ruby | def remove_container(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'id')
path = '/containers/' + params[:id]
query = {}
query[:v] = params[:v] if params.key?(:v)
query[:force] = params[:force] if params.key?(:force)
response = JSON.parse(Hyperb::Request.new(self, path, query, 'delete').perform)
downcase_symbolize(response)
end | [
"def",
"remove_container",
"(",
"params",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'Invalid arguments.'",
"unless",
"check_arguments",
"(",
"params",
",",
"'id'",
")",
"path",
"=",
"'/containers/'",
"+",
"params",
"[",
":id",
"]",
"query",
"=",
"{",
"}",
"query",
"[",
":v",
"]",
"=",
"params",
"[",
":v",
"]",
"if",
"params",
".",
"key?",
"(",
":v",
")",
"query",
"[",
":force",
"]",
"=",
"params",
"[",
":force",
"]",
"if",
"params",
".",
"key?",
"(",
":force",
")",
"response",
"=",
"JSON",
".",
"parse",
"(",
"Hyperb",
"::",
"Request",
".",
"new",
"(",
"self",
",",
"path",
",",
"query",
",",
"'delete'",
")",
".",
"perform",
")",
"downcase_symbolize",
"(",
"response",
")",
"end"
] | remove the container id
@see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Container/remove.html
@raise [Hyperb::Error::Unauthorized] raised when credentials are not valid.
@raise [Hyperb::Error::NotFound] raised when container can't be found.
@raise [Hyperb::Error::Conflict] raised when container is running and can't be removed.
@raise [Hyperb::Error::InternalServerError] raised when a 5xx is returned.
@return [Hash] downcased symbolized json response.
@param params [Hash] A customizable set of params.
@option params [Boolean] :v remove volumes attached. default false
@option params [Boolean] :force force remove. default false | [
"remove",
"the",
"container",
"id"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/containers/containers.rb#L74-L82 | train |
drish/hyperb | lib/hyperb/containers/containers.rb | Hyperb.Containers.create_container | def create_container(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'image')
path = '/containers/create'
query = {}
# set default size, otherwise container can't be started
body = { labels: { sh_hyper_instancetype: 's1' } }
# parse host_config options
if params.key?(:host_config)
body[camelize(:host_config)] = setup_host_config(params)
params.delete(:host_config)
end
query[:name] = params[:name] if params.key?(:name)
params.delete(:name)
body.merge!(params)
downcase_symbolize(JSON.parse(Hyperb::Request.new(self, path, query, 'post', body).perform))
end | ruby | def create_container(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'image')
path = '/containers/create'
query = {}
# set default size, otherwise container can't be started
body = { labels: { sh_hyper_instancetype: 's1' } }
# parse host_config options
if params.key?(:host_config)
body[camelize(:host_config)] = setup_host_config(params)
params.delete(:host_config)
end
query[:name] = params[:name] if params.key?(:name)
params.delete(:name)
body.merge!(params)
downcase_symbolize(JSON.parse(Hyperb::Request.new(self, path, query, 'post', body).perform))
end | [
"def",
"create_container",
"(",
"params",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'Invalid arguments.'",
"unless",
"check_arguments",
"(",
"params",
",",
"'image'",
")",
"path",
"=",
"'/containers/create'",
"query",
"=",
"{",
"}",
"body",
"=",
"{",
"labels",
":",
"{",
"sh_hyper_instancetype",
":",
"'s1'",
"}",
"}",
"if",
"params",
".",
"key?",
"(",
":host_config",
")",
"body",
"[",
"camelize",
"(",
":host_config",
")",
"]",
"=",
"setup_host_config",
"(",
"params",
")",
"params",
".",
"delete",
"(",
":host_config",
")",
"end",
"query",
"[",
":name",
"]",
"=",
"params",
"[",
":name",
"]",
"if",
"params",
".",
"key?",
"(",
":name",
")",
"params",
".",
"delete",
"(",
":name",
")",
"body",
".",
"merge!",
"(",
"params",
")",
"downcase_symbolize",
"(",
"JSON",
".",
"parse",
"(",
"Hyperb",
"::",
"Request",
".",
"new",
"(",
"self",
",",
"path",
",",
"query",
",",
"'post'",
",",
"body",
")",
".",
"perform",
")",
")",
"end"
] | create a container
@see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Container/create.html
@raise [Hyperb::Error::Unauthorized] raised when credentials are not valid.
@raise [Hyperb::Error::Conflict] raised container with the same name is already created.
@raise [Hyperb::Error::InternalServerError] raised when a 5xx is returned
@return [Hash] hash containing downcased symbolized json response.
@param params [Hash] A customizable set of params.
@option params [String] :name container name
@option params [String] :image image to be used
@option params [String] :hostname container hostname
@option params [String] :entrypoint container entrypoint
@option params [String] :cmd container command
@option params [String] :user add user to container
@option params [String] :workingdir working directory for commands to run in.
@option params [Array] :mounts array of strings with mount directories.
@option params [String] :networkmode network mode, ie 'bridge'.
@option params [Hash] :exposedports ports to expose.
@option params [Hash] :exposedports ports to expose.
@option params [Hash] :labels hash containing key: value
@option params labels [String] :sh_hyper_instancetype container size: s1, s2, s3 ... | [
"create",
"a",
"container"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/containers/containers.rb#L111-L129 | train |
drish/hyperb | lib/hyperb/containers/containers.rb | Hyperb.Containers.rename_container | def rename_container(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name', 'id')
path = '/containers/' + params[:id] + '/rename'
query = {}
query[:name] = params[:name] if params.key?(:name)
Hyperb::Request.new(self, path, query, 'post').perform
end | ruby | def rename_container(params = {})
raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name', 'id')
path = '/containers/' + params[:id] + '/rename'
query = {}
query[:name] = params[:name] if params.key?(:name)
Hyperb::Request.new(self, path, query, 'post').perform
end | [
"def",
"rename_container",
"(",
"params",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'Invalid arguments.'",
"unless",
"check_arguments",
"(",
"params",
",",
"'name'",
",",
"'id'",
")",
"path",
"=",
"'/containers/'",
"+",
"params",
"[",
":id",
"]",
"+",
"'/rename'",
"query",
"=",
"{",
"}",
"query",
"[",
":name",
"]",
"=",
"params",
"[",
":name",
"]",
"if",
"params",
".",
"key?",
"(",
":name",
")",
"Hyperb",
"::",
"Request",
".",
"new",
"(",
"self",
",",
"path",
",",
"query",
",",
"'post'",
")",
".",
"perform",
"end"
] | rename a container
@see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Container/rename.html
@raise [Hyperb::Error::Unauthorized] raised when credentials are not valid.
@raise [Hyperb::Error::NotFound] raised when the container can't be found.
@raise [Hyperb::Error::InternalServerError] raised when 5xx is returned.
@param params [Hash] A customizable set of params.
@option params [String] :id new name
@option params [String] :name new name | [
"rename",
"a",
"container"
] | 637de68dc304d8d07470a771f499e33f227955f4 | https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/containers/containers.rb#L251-L257 | train |
egonbraun/logmsg | lib/logmsg.rb | Logmsg.LogMsg.load | def load
close if @loaded
@path.each do |file|
next unless File.exist?(file)
@settings = Psych.load_file(file)
next unless @settings.include?(@namespace)
parse(@settings[@namespace])
@loaded = true
break
end
fail unless @loaded
end | ruby | def load
close if @loaded
@path.each do |file|
next unless File.exist?(file)
@settings = Psych.load_file(file)
next unless @settings.include?(@namespace)
parse(@settings[@namespace])
@loaded = true
break
end
fail unless @loaded
end | [
"def",
"load",
"close",
"if",
"@loaded",
"@path",
".",
"each",
"do",
"|",
"file",
"|",
"next",
"unless",
"File",
".",
"exist?",
"(",
"file",
")",
"@settings",
"=",
"Psych",
".",
"load_file",
"(",
"file",
")",
"next",
"unless",
"@settings",
".",
"include?",
"(",
"@namespace",
")",
"parse",
"(",
"@settings",
"[",
"@namespace",
"]",
")",
"@loaded",
"=",
"true",
"break",
"end",
"fail",
"unless",
"@loaded",
"end"
] | Load the configuration file
@private | [
"Load",
"the",
"configuration",
"file"
] | 7ca139edb856ada08cb7465acd68bd60bc2837fa | https://github.com/egonbraun/logmsg/blob/7ca139edb856ada08cb7465acd68bd60bc2837fa/lib/logmsg.rb#L59-L72 | train |
egonbraun/logmsg | lib/logmsg.rb | Logmsg.LogMsg.parse | def parse(settings, logfile = nil)
settings.each do |key, value|
if value.is_a?(Hash)
logfile = Logmsg::LogFile.new(key)
logfiles[key.to_sym] = logfile
parse(value, logfile)
logfile.register
else
logfile.public_send("#{key}=", value)
end
end
end | ruby | def parse(settings, logfile = nil)
settings.each do |key, value|
if value.is_a?(Hash)
logfile = Logmsg::LogFile.new(key)
logfiles[key.to_sym] = logfile
parse(value, logfile)
logfile.register
else
logfile.public_send("#{key}=", value)
end
end
end | [
"def",
"parse",
"(",
"settings",
",",
"logfile",
"=",
"nil",
")",
"settings",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"logfile",
"=",
"Logmsg",
"::",
"LogFile",
".",
"new",
"(",
"key",
")",
"logfiles",
"[",
"key",
".",
"to_sym",
"]",
"=",
"logfile",
"parse",
"(",
"value",
",",
"logfile",
")",
"logfile",
".",
"register",
"else",
"logfile",
".",
"public_send",
"(",
"\"#{key}=\"",
",",
"value",
")",
"end",
"end",
"end"
] | Recursively parses the loaded settings and creating log file destinations
@param [Hash] the loaded settings
@param [LogFile] the logfile object
@see Logmsg:LogFile
@private | [
"Recursively",
"parses",
"the",
"loaded",
"settings",
"and",
"creating",
"log",
"file",
"destinations"
] | 7ca139edb856ada08cb7465acd68bd60bc2837fa | https://github.com/egonbraun/logmsg/blob/7ca139edb856ada08cb7465acd68bd60bc2837fa/lib/logmsg.rb#L155-L166 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.addFriend | def addFriend(user)
method = 'addFriend'
type = true
args = {:user=>user}
return_object type,method,args,true
end | ruby | def addFriend(user)
method = 'addFriend'
type = true
args = {:user=>user}
return_object type,method,args,true
end | [
"def",
"addFriend",
"(",
"user",
")",
"method",
"=",
"'addFriend'",
"type",
"=",
"true",
"args",
"=",
"{",
":user",
"=>",
"user",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Add a friend to the current user. | [
"Add",
"a",
"friend",
"to",
"the",
"current",
"user",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L25-L30 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.addToCollection | def addToCollection(objs)
method = 'addToCollection'
type = true
args = {:keys=>Rdio::keys(objs)}
return_object type,method,args,true
end | ruby | def addToCollection(objs)
method = 'addToCollection'
type = true
args = {:keys=>Rdio::keys(objs)}
return_object type,method,args,true
end | [
"def",
"addToCollection",
"(",
"objs",
")",
"method",
"=",
"'addToCollection'",
"type",
"=",
"true",
"args",
"=",
"{",
":keys",
"=>",
"Rdio",
"::",
"keys",
"(",
"objs",
")",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Add tracks or playlists to the current user's collection. | [
"Add",
"tracks",
"or",
"playlists",
"to",
"the",
"current",
"user",
"s",
"collection",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L33-L38 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.addToPlaylist | def addToPlaylist(playlist,tracks)
method = 'addToPlaylist'
type = true
args = {:playlist=>playlist, :tracks=>Rdio::keys(tracks)}
return_object type,method,args,true
end | ruby | def addToPlaylist(playlist,tracks)
method = 'addToPlaylist'
type = true
args = {:playlist=>playlist, :tracks=>Rdio::keys(tracks)}
return_object type,method,args,true
end | [
"def",
"addToPlaylist",
"(",
"playlist",
",",
"tracks",
")",
"method",
"=",
"'addToPlaylist'",
"type",
"=",
"true",
"args",
"=",
"{",
":playlist",
"=>",
"playlist",
",",
":tracks",
"=>",
"Rdio",
"::",
"keys",
"(",
"tracks",
")",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Add a track to a playlist. | [
"Add",
"a",
"track",
"to",
"a",
"playlist",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L41-L46 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.createPlaylist | def createPlaylist(name,description,tracks,extras=nil)
method = 'createPlaylist'
type = Playlist
args = {:name=>name,:description=>description,
:tracks=>Rdio::keys(tracks)}
args[:extras] = extras if extras
return_object type,method,args,true
end | ruby | def createPlaylist(name,description,tracks,extras=nil)
method = 'createPlaylist'
type = Playlist
args = {:name=>name,:description=>description,
:tracks=>Rdio::keys(tracks)}
args[:extras] = extras if extras
return_object type,method,args,true
end | [
"def",
"createPlaylist",
"(",
"name",
",",
"description",
",",
"tracks",
",",
"extras",
"=",
"nil",
")",
"method",
"=",
"'createPlaylist'",
"type",
"=",
"Playlist",
"args",
"=",
"{",
":name",
"=>",
"name",
",",
":description",
"=>",
"description",
",",
":tracks",
"=>",
"Rdio",
"::",
"keys",
"(",
"tracks",
")",
"}",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Create a new playlist in the current user's collection. The new
playlist will be returned if the creation is successful, otherwise
null will be returned. | [
"Create",
"a",
"new",
"playlist",
"in",
"the",
"current",
"user",
"s",
"collection",
".",
"The",
"new",
"playlist",
"will",
"be",
"returned",
"if",
"the",
"creation",
"is",
"successful",
"otherwise",
"null",
"will",
"be",
"returned",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L51-L58 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.currentUser | def currentUser(extras=nil)
method = 'currentUser'
type = User
args = {}
args[:extras] = extras if extras
return_object type,method,args,true
end | ruby | def currentUser(extras=nil)
method = 'currentUser'
type = User
args = {}
args[:extras] = extras if extras
return_object type,method,args,true
end | [
"def",
"currentUser",
"(",
"extras",
"=",
"nil",
")",
"method",
"=",
"'currentUser'",
"type",
"=",
"User",
"args",
"=",
"{",
"}",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Get information about the currently logged in user. | [
"Get",
"information",
"about",
"the",
"currently",
"logged",
"in",
"user",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L61-L67 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.deletePlaylist | def deletePlaylist(playlist)
method = 'deletePlaylist'
type = Boolean
args = {:playlist=>playlist}
return_object type,method,args,true
end | ruby | def deletePlaylist(playlist)
method = 'deletePlaylist'
type = Boolean
args = {:playlist=>playlist}
return_object type,method,args,true
end | [
"def",
"deletePlaylist",
"(",
"playlist",
")",
"method",
"=",
"'deletePlaylist'",
"type",
"=",
"Boolean",
"args",
"=",
"{",
":playlist",
"=>",
"playlist",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Delete a playlist. | [
"Delete",
"a",
"playlist",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L70-L75 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getActivityStream | def getActivityStream(user,scope,last_id=nil)
method = 'getActivityStream'
type = ActivityStream
args = {:user=>user,:scope=>scope}
args[:last_id] = last_id if last_id
auth = user
return_object type,method,args,auth
end | ruby | def getActivityStream(user,scope,last_id=nil)
method = 'getActivityStream'
type = ActivityStream
args = {:user=>user,:scope=>scope}
args[:last_id] = last_id if last_id
auth = user
return_object type,method,args,auth
end | [
"def",
"getActivityStream",
"(",
"user",
",",
"scope",
",",
"last_id",
"=",
"nil",
")",
"method",
"=",
"'getActivityStream'",
"type",
"=",
"ActivityStream",
"args",
"=",
"{",
":user",
"=>",
"user",
",",
":scope",
"=>",
"scope",
"}",
"args",
"[",
":last_id",
"]",
"=",
"last_id",
"if",
"last_id",
"auth",
"=",
"user",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"auth",
"end"
] | Get the activity events for a user, a user's friends, or
everyone on Rdio. | [
"Get",
"the",
"activity",
"events",
"for",
"a",
"user",
"a",
"user",
"s",
"friends",
"or",
"everyone",
"on",
"Rdio",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L113-L120 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getAlbumsForArtistInCollection | def getAlbumsForArtistInCollection(artist,user=nil,extras=nil)
method = 'getAlbumsForArtistInCollection'
type = Album
args = {:artist=>artist}
args[:user] = user if user
args[:extras] = extras if extras
auth = !!user
return_object type,method,args,auth
end | ruby | def getAlbumsForArtistInCollection(artist,user=nil,extras=nil)
method = 'getAlbumsForArtistInCollection'
type = Album
args = {:artist=>artist}
args[:user] = user if user
args[:extras] = extras if extras
auth = !!user
return_object type,method,args,auth
end | [
"def",
"getAlbumsForArtistInCollection",
"(",
"artist",
",",
"user",
"=",
"nil",
",",
"extras",
"=",
"nil",
")",
"method",
"=",
"'getAlbumsForArtistInCollection'",
"type",
"=",
"Album",
"args",
"=",
"{",
":artist",
"=>",
"artist",
"}",
"args",
"[",
":user",
"]",
"=",
"user",
"if",
"user",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"auth",
"=",
"!",
"!",
"user",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"auth",
"end"
] | Get the albums in the user's collection by a particular artist. | [
"Get",
"the",
"albums",
"in",
"the",
"user",
"s",
"collection",
"by",
"a",
"particular",
"artist",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L135-L143 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getHeavyRotation | def getHeavyRotation(user=nil,type=nil,friends=nil,limit=nil,extras=nil)
method = 'getHeavyRotation'
cls = TODO
if type == 'artist'
cls = Artist
elsif type == 'album'
cls = Album
end
args = {}
args[:user] = user if user
args[:type] = type if type
args[:friends] = friends if friends
args[:limit] = limit if limit
args[:extras] = extras if extras
return_object cls,method,args
end | ruby | def getHeavyRotation(user=nil,type=nil,friends=nil,limit=nil,extras=nil)
method = 'getHeavyRotation'
cls = TODO
if type == 'artist'
cls = Artist
elsif type == 'album'
cls = Album
end
args = {}
args[:user] = user if user
args[:type] = type if type
args[:friends] = friends if friends
args[:limit] = limit if limit
args[:extras] = extras if extras
return_object cls,method,args
end | [
"def",
"getHeavyRotation",
"(",
"user",
"=",
"nil",
",",
"type",
"=",
"nil",
",",
"friends",
"=",
"nil",
",",
"limit",
"=",
"nil",
",",
"extras",
"=",
"nil",
")",
"method",
"=",
"'getHeavyRotation'",
"cls",
"=",
"TODO",
"if",
"type",
"==",
"'artist'",
"cls",
"=",
"Artist",
"elsif",
"type",
"==",
"'album'",
"cls",
"=",
"Album",
"end",
"args",
"=",
"{",
"}",
"args",
"[",
":user",
"]",
"=",
"user",
"if",
"user",
"args",
"[",
":type",
"]",
"=",
"type",
"if",
"type",
"args",
"[",
":friends",
"]",
"=",
"friends",
"if",
"friends",
"args",
"[",
":limit",
"]",
"=",
"limit",
"if",
"limit",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"cls",
",",
"method",
",",
"args",
"end"
] | Find the most popular artists or albums for a user, their friends
or the whole site. | [
"Find",
"the",
"most",
"popular",
"artists",
"or",
"albums",
"for",
"a",
"user",
"their",
"friends",
"or",
"the",
"whole",
"site",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L179-L194 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getNewReleases | def getNewReleases(time=nil,start=nil,count=nil,extras=nil)
method = 'getNewReleases'
type = Album
args = {}
args[:time] = time if time
args[:start] = start if start
args[:count] = count if count
args[:extras] = extras if extras
return_object type,method,args
end | ruby | def getNewReleases(time=nil,start=nil,count=nil,extras=nil)
method = 'getNewReleases'
type = Album
args = {}
args[:time] = time if time
args[:start] = start if start
args[:count] = count if count
args[:extras] = extras if extras
return_object type,method,args
end | [
"def",
"getNewReleases",
"(",
"time",
"=",
"nil",
",",
"start",
"=",
"nil",
",",
"count",
"=",
"nil",
",",
"extras",
"=",
"nil",
")",
"method",
"=",
"'getNewReleases'",
"type",
"=",
"Album",
"args",
"=",
"{",
"}",
"args",
"[",
":time",
"]",
"=",
"time",
"if",
"time",
"args",
"[",
":start",
"]",
"=",
"start",
"if",
"start",
"args",
"[",
":count",
"]",
"=",
"count",
"if",
"count",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"type",
",",
"method",
",",
"args",
"end"
] | Return new albums released across a timeframe. | [
"Return",
"new",
"albums",
"released",
"across",
"a",
"timeframe",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L197-L206 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getObjectFromShortCode | def getObjectFromShortCode(short_code,type=nil)
method = 'getObjectFromShortCode'
type = BaseObj if not type
args = {:short_code=>short_code}
return_object type,method,args,true
end | ruby | def getObjectFromShortCode(short_code,type=nil)
method = 'getObjectFromShortCode'
type = BaseObj if not type
args = {:short_code=>short_code}
return_object type,method,args,true
end | [
"def",
"getObjectFromShortCode",
"(",
"short_code",
",",
"type",
"=",
"nil",
")",
"method",
"=",
"'getObjectFromShortCode'",
"type",
"=",
"BaseObj",
"if",
"not",
"type",
"args",
"=",
"{",
":short_code",
"=>",
"short_code",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Return the object that the supplied Rdio short-code is a
representation of, or null if the short-code is invalid. | [
"Return",
"the",
"object",
"that",
"the",
"supplied",
"Rdio",
"short",
"-",
"code",
"is",
"a",
"representation",
"of",
"or",
"null",
"if",
"the",
"short",
"-",
"code",
"is",
"invalid",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L210-L215 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getObjectFromUrl | def getObjectFromUrl(url,type=nil)
method = 'getObjectFromUrl'
type = BaseObj if not type
args = {:url=>url}
return_object type,method,args,true
end | ruby | def getObjectFromUrl(url,type=nil)
method = 'getObjectFromUrl'
type = BaseObj if not type
args = {:url=>url}
return_object type,method,args,true
end | [
"def",
"getObjectFromUrl",
"(",
"url",
",",
"type",
"=",
"nil",
")",
"method",
"=",
"'getObjectFromUrl'",
"type",
"=",
"BaseObj",
"if",
"not",
"type",
"args",
"=",
"{",
":url",
"=>",
"url",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Return the object that the supplied Rdio url is a representation
of, or null if the url doesn't represent an object. | [
"Return",
"the",
"object",
"that",
"the",
"supplied",
"Rdio",
"url",
"is",
"a",
"representation",
"of",
"or",
"null",
"if",
"the",
"url",
"doesn",
"t",
"represent",
"an",
"object",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L219-L224 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getPlaybackToken | def getPlaybackToken(domain=nil)
method = 'getPlaybackToken'
type = String
args = {}
args[:domain] = domain if domain
return_object type,method,args,true
end | ruby | def getPlaybackToken(domain=nil)
method = 'getPlaybackToken'
type = String
args = {}
args[:domain] = domain if domain
return_object type,method,args,true
end | [
"def",
"getPlaybackToken",
"(",
"domain",
"=",
"nil",
")",
"method",
"=",
"'getPlaybackToken'",
"type",
"=",
"String",
"args",
"=",
"{",
"}",
"args",
"[",
":domain",
"]",
"=",
"domain",
"if",
"domain",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Get an playback token. If you are using this for web playback you
must supply a domain. | [
"Get",
"an",
"playback",
"token",
".",
"If",
"you",
"are",
"using",
"this",
"for",
"web",
"playback",
"you",
"must",
"supply",
"a",
"domain",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L228-L234 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getPlaylists | def getPlaylists(extras=nil)
method = 'getPlaylists'
type = Playlist
args = {}
args[:extras] = extras if extras
return_object type,method,args,true
end | ruby | def getPlaylists(extras=nil)
method = 'getPlaylists'
type = Playlist
args = {}
args[:extras] = extras if extras
return_object type,method,args,true
end | [
"def",
"getPlaylists",
"(",
"extras",
"=",
"nil",
")",
"method",
"=",
"'getPlaylists'",
"type",
"=",
"Playlist",
"args",
"=",
"{",
"}",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Get the current user's playlists. | [
"Get",
"the",
"current",
"user",
"s",
"playlists",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L237-L243 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getTopCharts | def getTopCharts(type,start=nil,count=nil,extras=nil)
method = 'getTopCharts'
cls = TODO
case type
when 'Artist'
cls = Artist
when 'Album'
cls = Album
when 'Track'
cls = Track
when 'Playlist'
cls = Playlist
end
args = {:type=>type}
return_object cls,method,args
end | ruby | def getTopCharts(type,start=nil,count=nil,extras=nil)
method = 'getTopCharts'
cls = TODO
case type
when 'Artist'
cls = Artist
when 'Album'
cls = Album
when 'Track'
cls = Track
when 'Playlist'
cls = Playlist
end
args = {:type=>type}
return_object cls,method,args
end | [
"def",
"getTopCharts",
"(",
"type",
",",
"start",
"=",
"nil",
",",
"count",
"=",
"nil",
",",
"extras",
"=",
"nil",
")",
"method",
"=",
"'getTopCharts'",
"cls",
"=",
"TODO",
"case",
"type",
"when",
"'Artist'",
"cls",
"=",
"Artist",
"when",
"'Album'",
"cls",
"=",
"Album",
"when",
"'Track'",
"cls",
"=",
"Track",
"when",
"'Playlist'",
"cls",
"=",
"Playlist",
"end",
"args",
"=",
"{",
":type",
"=>",
"type",
"}",
"return_object",
"cls",
",",
"method",
",",
"args",
"end"
] | Return the site-wide most popular items for a given type. | [
"Return",
"the",
"site",
"-",
"wide",
"most",
"popular",
"items",
"for",
"a",
"given",
"type",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L246-L261 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getTracksForAlbumInCollection | def getTracksForAlbumInCollection(album,user=nil,extras=nil)
method = 'getTracksForAlbumInCollection'
type = Track
args = {:album=>album}
args[:user] = user if user
args[:extras] = extras if extras
return_object type,method,args
end | ruby | def getTracksForAlbumInCollection(album,user=nil,extras=nil)
method = 'getTracksForAlbumInCollection'
type = Track
args = {:album=>album}
args[:user] = user if user
args[:extras] = extras if extras
return_object type,method,args
end | [
"def",
"getTracksForAlbumInCollection",
"(",
"album",
",",
"user",
"=",
"nil",
",",
"extras",
"=",
"nil",
")",
"method",
"=",
"'getTracksForAlbumInCollection'",
"type",
"=",
"Track",
"args",
"=",
"{",
":album",
"=>",
"album",
"}",
"args",
"[",
":user",
"]",
"=",
"user",
"if",
"user",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"type",
",",
"method",
",",
"args",
"end"
] | Which tracks on the given album are in the user's collection. | [
"Which",
"tracks",
"on",
"the",
"given",
"album",
"are",
"in",
"the",
"user",
"s",
"collection",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L264-L271 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.getTracksForArtistInCollection | def getTracksForArtistInCollection(artist,user=nil,extras=nil)
method = 'getTracksForArtistInCollection'
type = Track
args = {:artist=>artist}
args[:user] = user if user
args[:extras] = extras if extras
return_object type,method,args
end | ruby | def getTracksForArtistInCollection(artist,user=nil,extras=nil)
method = 'getTracksForArtistInCollection'
type = Track
args = {:artist=>artist}
args[:user] = user if user
args[:extras] = extras if extras
return_object type,method,args
end | [
"def",
"getTracksForArtistInCollection",
"(",
"artist",
",",
"user",
"=",
"nil",
",",
"extras",
"=",
"nil",
")",
"method",
"=",
"'getTracksForArtistInCollection'",
"type",
"=",
"Track",
"args",
"=",
"{",
":artist",
"=>",
"artist",
"}",
"args",
"[",
":user",
"]",
"=",
"user",
"if",
"user",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"type",
",",
"method",
",",
"args",
"end"
] | Which tracks from the given artist are in the user's collection. | [
"Which",
"tracks",
"from",
"the",
"given",
"artist",
"are",
"in",
"the",
"user",
"s",
"collection",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L286-L293 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.removeFriend | def removeFriend(user)
method = 'removeFriend'
type = Boolean
args = {:user=>user}
return_object type,method,args,true
end | ruby | def removeFriend(user)
method = 'removeFriend'
type = Boolean
args = {:user=>user}
return_object type,method,args,true
end | [
"def",
"removeFriend",
"(",
"user",
")",
"method",
"=",
"'removeFriend'",
"type",
"=",
"Boolean",
"args",
"=",
"{",
":user",
"=>",
"user",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Remove a friend from the current user. | [
"Remove",
"a",
"friend",
"from",
"the",
"current",
"user",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L310-L315 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.removeFromCollection | def removeFromCollection(objs)
method = 'removeFromCollection'
type = Boolean
args = {:keys=>Rdio::keys(objs)}
return_object type,method,args
end | ruby | def removeFromCollection(objs)
method = 'removeFromCollection'
type = Boolean
args = {:keys=>Rdio::keys(objs)}
return_object type,method,args
end | [
"def",
"removeFromCollection",
"(",
"objs",
")",
"method",
"=",
"'removeFromCollection'",
"type",
"=",
"Boolean",
"args",
"=",
"{",
":keys",
"=>",
"Rdio",
"::",
"keys",
"(",
"objs",
")",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
"end"
] | Remove tracks or playlists from the current user's collection. | [
"Remove",
"tracks",
"or",
"playlists",
"from",
"the",
"current",
"user",
"s",
"collection",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L318-L323 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.removeFromPlaylist | def removeFromPlaylist(playlist,index,count,tracks)
method = 'removeFromPlaylist'
type = TODO
args = {:playlist=>playlist,:index=>index,
:count=>count,:tracks=>Rdio::keys(tracks)}
return_object type,method,args,true
end | ruby | def removeFromPlaylist(playlist,index,count,tracks)
method = 'removeFromPlaylist'
type = TODO
args = {:playlist=>playlist,:index=>index,
:count=>count,:tracks=>Rdio::keys(tracks)}
return_object type,method,args,true
end | [
"def",
"removeFromPlaylist",
"(",
"playlist",
",",
"index",
",",
"count",
",",
"tracks",
")",
"method",
"=",
"'removeFromPlaylist'",
"type",
"=",
"TODO",
"args",
"=",
"{",
":playlist",
"=>",
"playlist",
",",
":index",
"=>",
"index",
",",
":count",
"=>",
"count",
",",
":tracks",
"=>",
"Rdio",
"::",
"keys",
"(",
"tracks",
")",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Remove an item from a playlist by its position in the playlist. | [
"Remove",
"an",
"item",
"from",
"a",
"playlist",
"by",
"its",
"position",
"in",
"the",
"playlist",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L326-L332 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.setPlaylistFields | def setPlaylistFields(playlist,name,description)
method = 'setPlaylistFields'
type = Boolean
args = {:playlist=>playlist,:name=>name,:description=>description}
return_object type,method,args,true
end | ruby | def setPlaylistFields(playlist,name,description)
method = 'setPlaylistFields'
type = Boolean
args = {:playlist=>playlist,:name=>name,:description=>description}
return_object type,method,args,true
end | [
"def",
"setPlaylistFields",
"(",
"playlist",
",",
"name",
",",
"description",
")",
"method",
"=",
"'setPlaylistFields'",
"type",
"=",
"Boolean",
"args",
"=",
"{",
":playlist",
"=>",
"playlist",
",",
":name",
"=>",
"name",
",",
":description",
"=>",
"description",
"}",
"return_object",
"type",
",",
"method",
",",
"args",
",",
"true",
"end"
] | Sets the name and description for a playlist. | [
"Sets",
"the",
"name",
"and",
"description",
"for",
"a",
"playlist",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L361-L366 | train |
spudtrooper/rdiorb | lib/rdio/api.rb | Rdio.Api.searchSuggestions | def searchSuggestions(query,extras)
method = 'searchSuggestions'
type = TODO
args = {:query=>query}
args[:extras] = extras if extras
return_object type,method,args
end | ruby | def searchSuggestions(query,extras)
method = 'searchSuggestions'
type = TODO
args = {:query=>query}
args[:extras] = extras if extras
return_object type,method,args
end | [
"def",
"searchSuggestions",
"(",
"query",
",",
"extras",
")",
"method",
"=",
"'searchSuggestions'",
"type",
"=",
"TODO",
"args",
"=",
"{",
":query",
"=>",
"query",
"}",
"args",
"[",
":extras",
"]",
"=",
"extras",
"if",
"extras",
"return_object",
"type",
",",
"method",
",",
"args",
"end"
] | Match the supplied prefix against artists, albums, tracks and
people in the Rdio system. Return the first ten matches. | [
"Match",
"the",
"supplied",
"prefix",
"against",
"artists",
"albums",
"tracks",
"and",
"people",
"in",
"the",
"Rdio",
"system",
".",
"Return",
"the",
"first",
"ten",
"matches",
"."
] | e137fd016bfba42d9e50f421b009b2ad3c41baaf | https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/api.rb#L398-L404 | train |
rudical/linkshare-oauth2-api | lib/linkshare/strategy.rb | Linkshare.Strategy.get_token | def get_token(username, password, sid, params = {}, opts = {})
request_body = opts.delete('auth_scheme') == 'request_body'
params = {'grant_type' => 'password',
'username' => username,
'password' => password,
'scope' => sid
}.merge(client_params).merge(params)
params.merge!('client_params' => {
:headers => {
'Authorization' => authorization(client_params['client_id'], client_params['client_secret']),
'Accept' => 'application/xml'}
})
# params.merge(:parse => :xml)
@client.get_token(params, opts)
end | ruby | def get_token(username, password, sid, params = {}, opts = {})
request_body = opts.delete('auth_scheme') == 'request_body'
params = {'grant_type' => 'password',
'username' => username,
'password' => password,
'scope' => sid
}.merge(client_params).merge(params)
params.merge!('client_params' => {
:headers => {
'Authorization' => authorization(client_params['client_id'], client_params['client_secret']),
'Accept' => 'application/xml'}
})
# params.merge(:parse => :xml)
@client.get_token(params, opts)
end | [
"def",
"get_token",
"(",
"username",
",",
"password",
",",
"sid",
",",
"params",
"=",
"{",
"}",
",",
"opts",
"=",
"{",
"}",
")",
"request_body",
"=",
"opts",
".",
"delete",
"(",
"'auth_scheme'",
")",
"==",
"'request_body'",
"params",
"=",
"{",
"'grant_type'",
"=>",
"'password'",
",",
"'username'",
"=>",
"username",
",",
"'password'",
"=>",
"password",
",",
"'scope'",
"=>",
"sid",
"}",
".",
"merge",
"(",
"client_params",
")",
".",
"merge",
"(",
"params",
")",
"params",
".",
"merge!",
"(",
"'client_params'",
"=>",
"{",
":headers",
"=>",
"{",
"'Authorization'",
"=>",
"authorization",
"(",
"client_params",
"[",
"'client_id'",
"]",
",",
"client_params",
"[",
"'client_secret'",
"]",
")",
",",
"'Accept'",
"=>",
"'application/xml'",
"}",
"}",
")",
"@client",
".",
"get_token",
"(",
"params",
",",
"opts",
")",
"end"
] | Retrieve an access token given the specified End User username, password and Linkshare AccountID.
@param [String] username the End User username
@param [String] password the End User password
@param [String] sid the Account ID
@param [Hash] params additional params | [
"Retrieve",
"an",
"access",
"token",
"given",
"the",
"specified",
"End",
"User",
"username",
"password",
"and",
"Linkshare",
"AccountID",
"."
] | f135ed40f38de9add1c4bba34b85fe7083a66c0e | https://github.com/rudical/linkshare-oauth2-api/blob/f135ed40f38de9add1c4bba34b85fe7083a66c0e/lib/linkshare/strategy.rb#L11-L27 | train |
socialcast/socialcast-git-extensions | lib/socialcast-git-extensions.rb | Socialcast.Gitx.run_cmd | def run_cmd(cmd)
raise "Unstubbed git command #{cmd}" if ENV['SCGITX_TEST'] == 'true'
say "\n$ "
say cmd.gsub("'", ''), :red
raise "#{cmd} failed" unless system cmd
end | ruby | def run_cmd(cmd)
raise "Unstubbed git command #{cmd}" if ENV['SCGITX_TEST'] == 'true'
say "\n$ "
say cmd.gsub("'", ''), :red
raise "#{cmd} failed" unless system cmd
end | [
"def",
"run_cmd",
"(",
"cmd",
")",
"raise",
"\"Unstubbed git command #{cmd}\"",
"if",
"ENV",
"[",
"'SCGITX_TEST'",
"]",
"==",
"'true'",
"say",
"\"\\n$ \"",
"say",
"cmd",
".",
"gsub",
"(",
"\"'\"",
",",
"''",
")",
",",
":red",
"raise",
"\"#{cmd} failed\"",
"unless",
"system",
"cmd",
"end"
] | execute a shell command and raise an error if non-zero exit code is returned | [
"execute",
"a",
"shell",
"command",
"and",
"raise",
"an",
"error",
"if",
"non",
"-",
"zero",
"exit",
"code",
"is",
"returned"
] | d2c6dfc88b2683de90011127c7d3787a4561bfa1 | https://github.com/socialcast/socialcast-git-extensions/blob/d2c6dfc88b2683de90011127c7d3787a4561bfa1/lib/socialcast-git-extensions.rb#L17-L22 | train |
fabn/google_authentication | lib/google_authentication/acts_as_google_user.rb | GoogleAuthentication.ActsAsGoogleUser.acts_as_google_user | def acts_as_google_user *modules
# assign devise modules to module variable
if modules.empty?
self.devise_modules_to_include = [:omniauthable]
else
# restrict modules given to devise
self.devise_modules_to_include = (modules + [:omniauthable] - FORBIDDEN_MODULES) & ALLOWED_MODULES
end
# include model methods
include ActsAsGoogleUser::Model
end | ruby | def acts_as_google_user *modules
# assign devise modules to module variable
if modules.empty?
self.devise_modules_to_include = [:omniauthable]
else
# restrict modules given to devise
self.devise_modules_to_include = (modules + [:omniauthable] - FORBIDDEN_MODULES) & ALLOWED_MODULES
end
# include model methods
include ActsAsGoogleUser::Model
end | [
"def",
"acts_as_google_user",
"*",
"modules",
"if",
"modules",
".",
"empty?",
"self",
".",
"devise_modules_to_include",
"=",
"[",
":omniauthable",
"]",
"else",
"self",
".",
"devise_modules_to_include",
"=",
"(",
"modules",
"+",
"[",
":omniauthable",
"]",
"-",
"FORBIDDEN_MODULES",
")",
"&",
"ALLOWED_MODULES",
"end",
"include",
"ActsAsGoogleUser",
"::",
"Model",
"end"
] | Configure a model to be used with devise and google authentication
@param [Array] modules a list of symbols used with a devise call | [
"Configure",
"a",
"model",
"to",
"be",
"used",
"with",
"devise",
"and",
"google",
"authentication"
] | 4f2277faeaea778a3ad2b066628ca25f8fa1f6ab | https://github.com/fabn/google_authentication/blob/4f2277faeaea778a3ad2b066628ca25f8fa1f6ab/lib/google_authentication/acts_as_google_user.rb#L20-L30 | train |
stvvan/hoiio-ruby | lib/hoiio-ruby/client.rb | Hoiio.Client.set_up_resources | def set_up_resources
@user = Hoiio::User.new self
@sms = Hoiio::SMS.new self
@voice = Hoiio::Voice.new self
@fax = Hoiio::Fax.new self
@number = Hoiio::Number.new self
@ivr = Hoiio::IVR.new self
end | ruby | def set_up_resources
@user = Hoiio::User.new self
@sms = Hoiio::SMS.new self
@voice = Hoiio::Voice.new self
@fax = Hoiio::Fax.new self
@number = Hoiio::Number.new self
@ivr = Hoiio::IVR.new self
end | [
"def",
"set_up_resources",
"@user",
"=",
"Hoiio",
"::",
"User",
".",
"new",
"self",
"@sms",
"=",
"Hoiio",
"::",
"SMS",
".",
"new",
"self",
"@voice",
"=",
"Hoiio",
"::",
"Voice",
".",
"new",
"self",
"@fax",
"=",
"Hoiio",
"::",
"Fax",
".",
"new",
"self",
"@number",
"=",
"Hoiio",
"::",
"Number",
".",
"new",
"self",
"@ivr",
"=",
"Hoiio",
"::",
"IVR",
".",
"new",
"self",
"end"
] | Set up sub resources to be used to call Hoiio API
This method passes the @client object to the initialize block of all API request. | [
"Set",
"up",
"sub",
"resources",
"to",
"be",
"used",
"to",
"call",
"Hoiio",
"API",
"This",
"method",
"passes",
"the"
] | 7f6840b94c5f61c221619ca069bc008d502dd339 | https://github.com/stvvan/hoiio-ruby/blob/7f6840b94c5f61c221619ca069bc008d502dd339/lib/hoiio-ruby/client.rb#L61-L68 | train |
lmullen/omeka_client | lib/omeka_client/client.rb | OmekaClient.Client.put_item | def put_item(omeka_item)
self.put("items", omeka_item.data.id, omeka_item.data.to_h.to_json)
end | ruby | def put_item(omeka_item)
self.put("items", omeka_item.data.id, omeka_item.data.to_h.to_json)
end | [
"def",
"put_item",
"(",
"omeka_item",
")",
"self",
".",
"put",
"(",
"\"items\"",
",",
"omeka_item",
".",
"data",
".",
"id",
",",
"omeka_item",
".",
"data",
".",
"to_h",
".",
"to_json",
")",
"end"
] | Update an item using an OmekaItem instance
@param omeka_item [OmekaItem] An instance of OmekaItem
@since 0.0.4 | [
"Update",
"an",
"item",
"using",
"an",
"OmekaItem",
"instance"
] | abd7e8d38d91b1a5904eb7e068b066f0ac8b1074 | https://github.com/lmullen/omeka_client/blob/abd7e8d38d91b1a5904eb7e068b066f0ac8b1074/lib/omeka_client/client.rb#L167-L169 | train |
lmullen/omeka_client | lib/omeka_client/client.rb | OmekaClient.Client.build_request | def build_request(method, resource = nil, id = nil, body =nil, query = {})
url = self.endpoint
url += "/" + resource unless resource.nil?
url += "/" + id.to_s unless id.nil?
query[:key] = self.api_key unless self.api_key.nil?
case method
when "get"
self.connection.get(url, :params => query)
when "post"
self.connection.post(url, :body => body, :params => query)
when "put"
self.connection.put(url, :body => body, :params => query)
when "delete"
begin
self.connection.delete(url, :params => query)
rescue TypeError
# Not putting the error to stdout
end
end
end | ruby | def build_request(method, resource = nil, id = nil, body =nil, query = {})
url = self.endpoint
url += "/" + resource unless resource.nil?
url += "/" + id.to_s unless id.nil?
query[:key] = self.api_key unless self.api_key.nil?
case method
when "get"
self.connection.get(url, :params => query)
when "post"
self.connection.post(url, :body => body, :params => query)
when "put"
self.connection.put(url, :body => body, :params => query)
when "delete"
begin
self.connection.delete(url, :params => query)
rescue TypeError
# Not putting the error to stdout
end
end
end | [
"def",
"build_request",
"(",
"method",
",",
"resource",
"=",
"nil",
",",
"id",
"=",
"nil",
",",
"body",
"=",
"nil",
",",
"query",
"=",
"{",
"}",
")",
"url",
"=",
"self",
".",
"endpoint",
"url",
"+=",
"\"/\"",
"+",
"resource",
"unless",
"resource",
".",
"nil?",
"url",
"+=",
"\"/\"",
"+",
"id",
".",
"to_s",
"unless",
"id",
".",
"nil?",
"query",
"[",
":key",
"]",
"=",
"self",
".",
"api_key",
"unless",
"self",
".",
"api_key",
".",
"nil?",
"case",
"method",
"when",
"\"get\"",
"self",
".",
"connection",
".",
"get",
"(",
"url",
",",
":params",
"=>",
"query",
")",
"when",
"\"post\"",
"self",
".",
"connection",
".",
"post",
"(",
"url",
",",
":body",
"=>",
"body",
",",
":params",
"=>",
"query",
")",
"when",
"\"put\"",
"self",
".",
"connection",
".",
"put",
"(",
"url",
",",
":body",
"=>",
"body",
",",
":params",
"=>",
"query",
")",
"when",
"\"delete\"",
"begin",
"self",
".",
"connection",
".",
"delete",
"(",
"url",
",",
":params",
"=>",
"query",
")",
"rescue",
"TypeError",
"end",
"end",
"end"
] | Helper method to build an API request
@param method [String] The type of REST request to make: "get", "post",
"put", or "delete".
@param resource [String] The type of resource to request from the Omeka
site, e.g., "items" or "site".
@param id [Integer] The id of the resource to request from the Omeka
site.
@param body [] The body of a request in a PUT or POST request.
@param query [Hash] Additional query parameters for the request.
@return [NetHttpPersistentResponseWrapper] A wrapper around the API's
response, containing the HTTP code and the response body.
@since 1.0.0 | [
"Helper",
"method",
"to",
"build",
"an",
"API",
"request"
] | abd7e8d38d91b1a5904eb7e068b066f0ac8b1074 | https://github.com/lmullen/omeka_client/blob/abd7e8d38d91b1a5904eb7e068b066f0ac8b1074/lib/omeka_client/client.rb#L203-L225 | train |
luikore/markascend | lib/markascend/line_unit.rb | Markascend.LineUnit.parse_inline_code | def parse_inline_code
if s = @src.scan(/
(`{1,})(\ ?)
.*?
\2\1
/x)
s =~ /^
(`{1,})(\ ?)
(.*?)
\2\1
$/x
@out << (::Markascend.hilite $3, env.hi, true)
true
end
end | ruby | def parse_inline_code
if s = @src.scan(/
(`{1,})(\ ?)
.*?
\2\1
/x)
s =~ /^
(`{1,})(\ ?)
(.*?)
\2\1
$/x
@out << (::Markascend.hilite $3, env.hi, true)
true
end
end | [
"def",
"parse_inline_code",
"if",
"s",
"=",
"@src",
".",
"scan",
"(",
"/",
"\\ ",
"\\2",
"\\1",
"/x",
")",
"s",
"=~",
"/",
"\\ ",
"\\2",
"\\1",
"/x",
"@out",
"<<",
"(",
"::",
"Markascend",
".",
"hilite",
"$3",
",",
"env",
".",
"hi",
",",
"true",
")",
"true",
"end",
"end"
] | the same as markdown | [
"the",
"same",
"as",
"markdown"
] | 58a7d9c18bf764dba537f7b4bf52ac550bbccb50 | https://github.com/luikore/markascend/blob/58a7d9c18bf764dba537f7b4bf52ac550bbccb50/lib/markascend/line_unit.rb#L22-L36 | train |
norman/phonology | lib/phonology/sound.rb | Phonology.Sound.<< | def <<(*args)
args.to_a.flatten.each do |feature|
features.subtract Features.set(feature).to_a
add! feature
end
self
end | ruby | def <<(*args)
args.to_a.flatten.each do |feature|
features.subtract Features.set(feature).to_a
add! feature
end
self
end | [
"def",
"<<",
"(",
"*",
"args",
")",
"args",
".",
"to_a",
".",
"flatten",
".",
"each",
"do",
"|",
"feature",
"|",
"features",
".",
"subtract",
"Features",
".",
"set",
"(",
"feature",
")",
".",
"to_a",
"add!",
"feature",
"end",
"self",
"end"
] | Add a feature, replacing either the place or manner of articulation,
or the height or backness. Returns self. | [
"Add",
"a",
"feature",
"replacing",
"either",
"the",
"place",
"or",
"manner",
"of",
"articulation",
"or",
"the",
"height",
"or",
"backness",
".",
"Returns",
"self",
"."
] | 910207237aecbcd8e1a464a9148d9b3fd4d1f3e4 | https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/sound.rb#L131-L137 | train |
norman/phonology | lib/phonology/sound.rb | Phonology.Sound.>> | def >>(*args)
args.to_a.flatten.each do |feature|
features.delete feature.to_sym
end
self
end | ruby | def >>(*args)
args.to_a.flatten.each do |feature|
features.delete feature.to_sym
end
self
end | [
"def",
">>",
"(",
"*",
"args",
")",
"args",
".",
"to_a",
".",
"flatten",
".",
"each",
"do",
"|",
"feature",
"|",
"features",
".",
"delete",
"feature",
".",
"to_sym",
"end",
"self",
"end"
] | Remove a feature, and return self. | [
"Remove",
"a",
"feature",
"and",
"return",
"self",
"."
] | 910207237aecbcd8e1a464a9148d9b3fd4d1f3e4 | https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/sound.rb#L147-L152 | train |
mrwillihog/unified | lib/unified/chunk.rb | Unified.Chunk.each_line | def each_line
original_line_number = @original_line_number
modified_line_number = @modified_line_number
@lines.each do |line|
if line.addition?
yield line, nil, modified_line_number
modified_line_number += 1
elsif line.deletion?
yield line, original_line_number, nil
original_line_number += 1
elsif line.unchanged?
yield line, original_line_number, modified_line_number
original_line_number += 1
modified_line_number += 1
else
yield line
end
end
end | ruby | def each_line
original_line_number = @original_line_number
modified_line_number = @modified_line_number
@lines.each do |line|
if line.addition?
yield line, nil, modified_line_number
modified_line_number += 1
elsif line.deletion?
yield line, original_line_number, nil
original_line_number += 1
elsif line.unchanged?
yield line, original_line_number, modified_line_number
original_line_number += 1
modified_line_number += 1
else
yield line
end
end
end | [
"def",
"each_line",
"original_line_number",
"=",
"@original_line_number",
"modified_line_number",
"=",
"@modified_line_number",
"@lines",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"line",
".",
"addition?",
"yield",
"line",
",",
"nil",
",",
"modified_line_number",
"modified_line_number",
"+=",
"1",
"elsif",
"line",
".",
"deletion?",
"yield",
"line",
",",
"original_line_number",
",",
"nil",
"original_line_number",
"+=",
"1",
"elsif",
"line",
".",
"unchanged?",
"yield",
"line",
",",
"original_line_number",
",",
"modified_line_number",
"original_line_number",
"+=",
"1",
"modified_line_number",
"+=",
"1",
"else",
"yield",
"line",
"end",
"end",
"end"
] | Iterator for lines passing |line, original_line_number, modified_line_number| as block arguments | [
"Iterator",
"for",
"lines",
"passing",
"|line",
"original_line_number",
"modified_line_number|",
"as",
"block",
"arguments"
] | a1e13d3f865dc89277d7cb11d5f8b1216096ac34 | https://github.com/mrwillihog/unified/blob/a1e13d3f865dc89277d7cb11d5f8b1216096ac34/lib/unified/chunk.rb#L56-L75 | train |
SwagDevOps/sys-proc | lib/sys/proc/concern/static_instance.rb | Sys::Proc::Concern::StaticInstance.ClassMethods.method_missing | def method_missing(method, *args, &block)
if respond_to_missing?(method)
new.public_send(method, *args, &block)
else
super
end
end | ruby | def method_missing(method, *args, &block)
if respond_to_missing?(method)
new.public_send(method, *args, &block)
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"respond_to_missing?",
"(",
"method",
")",
"new",
".",
"public_send",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"else",
"super",
"end",
"end"
] | Provides access to instance methods | [
"Provides",
"access",
"to",
"instance",
"methods"
] | d0a6d8259ccb63dd7a501dbdef4a501d2cafec27 | https://github.com/SwagDevOps/sys-proc/blob/d0a6d8259ccb63dd7a501dbdef4a501d2cafec27/lib/sys/proc/concern/static_instance.rb#L22-L28 | train |
fabiokr/manageable | app/helpers/manageable/application_helper.rb | Manageable.ApplicationHelper.manageable_content_box | def manageable_content_box(options = {}, &block)
box_buffer = Helpers::BoxBuilder.new(self)
box_content = capture(box_buffer, &block)
options = {
:id => nil,
:class => []
}.merge(options)
block_class = ([ "block" ] + [ options[:class] ].flatten).join(" ")
content_tag(:div, :class => block_class, :id => options[:id]) do
block_out = box_buffer.buffers[:block_header].html_safe
block_out << content_tag(:div, :class => "content") do
content_out = ''.html_safe
content_out = content_tag(:h2, options[:headline]) if options[:headline]
content_out << content_tag(:div, box_content, :class => 'inner')
end
block_out << box_buffer.buffers[:block_footer].html_safe
end
end | ruby | def manageable_content_box(options = {}, &block)
box_buffer = Helpers::BoxBuilder.new(self)
box_content = capture(box_buffer, &block)
options = {
:id => nil,
:class => []
}.merge(options)
block_class = ([ "block" ] + [ options[:class] ].flatten).join(" ")
content_tag(:div, :class => block_class, :id => options[:id]) do
block_out = box_buffer.buffers[:block_header].html_safe
block_out << content_tag(:div, :class => "content") do
content_out = ''.html_safe
content_out = content_tag(:h2, options[:headline]) if options[:headline]
content_out << content_tag(:div, box_content, :class => 'inner')
end
block_out << box_buffer.buffers[:block_footer].html_safe
end
end | [
"def",
"manageable_content_box",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"box_buffer",
"=",
"Helpers",
"::",
"BoxBuilder",
".",
"new",
"(",
"self",
")",
"box_content",
"=",
"capture",
"(",
"box_buffer",
",",
"&",
"block",
")",
"options",
"=",
"{",
":id",
"=>",
"nil",
",",
":class",
"=>",
"[",
"]",
"}",
".",
"merge",
"(",
"options",
")",
"block_class",
"=",
"(",
"[",
"\"block\"",
"]",
"+",
"[",
"options",
"[",
":class",
"]",
"]",
".",
"flatten",
")",
".",
"join",
"(",
"\" \"",
")",
"content_tag",
"(",
":div",
",",
":class",
"=>",
"block_class",
",",
":id",
"=>",
"options",
"[",
":id",
"]",
")",
"do",
"block_out",
"=",
"box_buffer",
".",
"buffers",
"[",
":block_header",
"]",
".",
"html_safe",
"block_out",
"<<",
"content_tag",
"(",
":div",
",",
":class",
"=>",
"\"content\"",
")",
"do",
"content_out",
"=",
"''",
".",
"html_safe",
"content_out",
"=",
"content_tag",
"(",
":h2",
",",
"options",
"[",
":headline",
"]",
")",
"if",
"options",
"[",
":headline",
"]",
"content_out",
"<<",
"content_tag",
"(",
":div",
",",
"box_content",
",",
":class",
"=>",
"'inner'",
")",
"end",
"block_out",
"<<",
"box_buffer",
".",
"buffers",
"[",
":block_footer",
"]",
".",
"html_safe",
"end",
"end"
] | Create a content box.
options - A hash of options to apply to the box.
&block - The content of the box, passed an instance of Helpers::BoxBuilder.
Valid options:
* :headline -- The headline to show in the box.
* :class -- A class to apply to the box.
* :id -- The ID to apply to the box.
Example:
<% content_box :headline => "My Box", :class => "alert", :id => "my_box" do |box| %>
<% box.navigation do |nav| %>
<% nav.item "List People", people_path, :active => true %>
<% nav.item "New Person", new_person_path %>
<% nav.item "Search", search_path(:type => "people") %>
<% end %>
<% box.breadcrumbs do |crumbs| %>
<% crumbs.item "Home", root_path %>
<% crumbs.item "People", people_path %>
<% crumbs.item "Bob Jones", person_path(@person), :active => true %>
<% end %>
<p>This is a really neat box, which will be displayed with a headline and navigation.</p>
<% end %>
Returns the completed box, yields an instance of Helpers::BoxBuilder. | [
"Create",
"a",
"content",
"box",
"."
] | 9db47dea0e2e73e164923de23be20109fe1cf35f | https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/helpers/manageable/application_helper.rb#L32-L52 | train |
fabiokr/manageable | app/helpers/manageable/application_helper.rb | Manageable.ApplicationHelper.manageable_icon | def manageable_icon(name, size = :small, options = {})
return "" if name.nil?
dimension = ( (size == :small) ? "16" : "32" ).html_safe
options[:alt] ||= name.capitalize.gsub("_", " ")
image_tag(asset_path("manageable/icons/#{dimension}x#{dimension}/#{name}.png"), {
:alt => options[:alt]
})
end | ruby | def manageable_icon(name, size = :small, options = {})
return "" if name.nil?
dimension = ( (size == :small) ? "16" : "32" ).html_safe
options[:alt] ||= name.capitalize.gsub("_", " ")
image_tag(asset_path("manageable/icons/#{dimension}x#{dimension}/#{name}.png"), {
:alt => options[:alt]
})
end | [
"def",
"manageable_icon",
"(",
"name",
",",
"size",
"=",
":small",
",",
"options",
"=",
"{",
"}",
")",
"return",
"\"\"",
"if",
"name",
".",
"nil?",
"dimension",
"=",
"(",
"(",
"size",
"==",
":small",
")",
"?",
"\"16\"",
":",
"\"32\"",
")",
".",
"html_safe",
"options",
"[",
":alt",
"]",
"||=",
"name",
".",
"capitalize",
".",
"gsub",
"(",
"\"_\"",
",",
"\" \"",
")",
"image_tag",
"(",
"asset_path",
"(",
"\"manageable/icons/#{dimension}x#{dimension}/#{name}.png\"",
")",
",",
"{",
":alt",
"=>",
"options",
"[",
":alt",
"]",
"}",
")",
"end"
] | Display an icon
name - The icon to display
size - One of :small or :large (optional)
options - A hash to be passed to the image_tag helper (optional)
Example:
manageable_icon("add")
# => image_tag("/assets/manageable/icons/16x16/add.png", :alt => "Add")
manageable_icon("new_item", :large)
# => image_tag("/assets/manageable/icons/32x32/new_item.png, :alt => "New Item")
Returns an image tag, ready to be displayed in a template. | [
"Display",
"an",
"icon"
] | 9db47dea0e2e73e164923de23be20109fe1cf35f | https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/helpers/manageable/application_helper.rb#L83-L92 | train |
fabiokr/manageable | app/helpers/manageable/application_helper.rb | Manageable.ApplicationHelper.manageable_controls | def manageable_controls(options = {})
options[:class] ||= ""
options[:class] << " control"
options[:class].strip!
items = Helpers::NavigationBuilder.new
yield items if block_given?
content_tag("div", options) do
items.collect { |item|
manageable_button(item[:label], item[:href], item[:link_options].merge(:icon => item[:icon]))
}.join("").html_safe
end
end | ruby | def manageable_controls(options = {})
options[:class] ||= ""
options[:class] << " control"
options[:class].strip!
items = Helpers::NavigationBuilder.new
yield items if block_given?
content_tag("div", options) do
items.collect { |item|
manageable_button(item[:label], item[:href], item[:link_options].merge(:icon => item[:icon]))
}.join("").html_safe
end
end | [
"def",
"manageable_controls",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":class",
"]",
"||=",
"\"\"",
"options",
"[",
":class",
"]",
"<<",
"\" control\"",
"options",
"[",
":class",
"]",
".",
"strip!",
"items",
"=",
"Helpers",
"::",
"NavigationBuilder",
".",
"new",
"yield",
"items",
"if",
"block_given?",
"content_tag",
"(",
"\"div\"",
",",
"options",
")",
"do",
"items",
".",
"collect",
"{",
"|",
"item",
"|",
"manageable_button",
"(",
"item",
"[",
":label",
"]",
",",
"item",
"[",
":href",
"]",
",",
"item",
"[",
":link_options",
"]",
".",
"merge",
"(",
":icon",
"=>",
"item",
"[",
":icon",
"]",
")",
")",
"}",
".",
"join",
"(",
"\"\"",
")",
".",
"html_safe",
"end",
"end"
] | Creates a set of buttons
options - A hash of attributes to apply to the wrapping div tag
Example:
<div class="block">
<div class="content">
<%= controls do |c|
c.item "Copy", copy_person_path(person), :icon => "copy_person"
c.item "Delete", person_path(person), :method => :delete
end %>
</div>
</div>
Returns a set of controls to be displayed. | [
"Creates",
"a",
"set",
"of",
"buttons"
] | 9db47dea0e2e73e164923de23be20109fe1cf35f | https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/helpers/manageable/application_helper.rb#L154-L167 | train |
fabiokr/manageable | app/helpers/manageable/application_helper.rb | Manageable.ApplicationHelper.manageable_breadcrumbs | def manageable_breadcrumbs(options = {})
items = Helpers::NavigationBuilder.new
yield items if block_given?
options[:class] ||= ""
options[:class] << " breadcrumb"
options[:class].strip!
content_tag("div", options) do
content_tag("ul") do
items.collect { |item|
content_tag("li", :class => item[:class]) do
if item[:active]
item[:label]
else
link_to(item[:label], item[:href])
end
end
}.join("").html_safe
end
end
end | ruby | def manageable_breadcrumbs(options = {})
items = Helpers::NavigationBuilder.new
yield items if block_given?
options[:class] ||= ""
options[:class] << " breadcrumb"
options[:class].strip!
content_tag("div", options) do
content_tag("ul") do
items.collect { |item|
content_tag("li", :class => item[:class]) do
if item[:active]
item[:label]
else
link_to(item[:label], item[:href])
end
end
}.join("").html_safe
end
end
end | [
"def",
"manageable_breadcrumbs",
"(",
"options",
"=",
"{",
"}",
")",
"items",
"=",
"Helpers",
"::",
"NavigationBuilder",
".",
"new",
"yield",
"items",
"if",
"block_given?",
"options",
"[",
":class",
"]",
"||=",
"\"\"",
"options",
"[",
":class",
"]",
"<<",
"\" breadcrumb\"",
"options",
"[",
":class",
"]",
".",
"strip!",
"content_tag",
"(",
"\"div\"",
",",
"options",
")",
"do",
"content_tag",
"(",
"\"ul\"",
")",
"do",
"items",
".",
"collect",
"{",
"|",
"item",
"|",
"content_tag",
"(",
"\"li\"",
",",
":class",
"=>",
"item",
"[",
":class",
"]",
")",
"do",
"if",
"item",
"[",
":active",
"]",
"item",
"[",
":label",
"]",
"else",
"link_to",
"(",
"item",
"[",
":label",
"]",
",",
"item",
"[",
":href",
"]",
")",
"end",
"end",
"}",
".",
"join",
"(",
"\"\"",
")",
".",
"html_safe",
"end",
"end",
"end"
] | Displays a breadcrumb trail
options - A hash of attributes to apply to the wrapping div tag
Example:
<div class="block">
<div class="content">
<h2><%= @news_item.title %></h2>
<p><%= @news_item.content %></p>
</div>
<%= breadcrumbs do |b|
b.item "Home", root_path
b.item "News", news_path
b.item "Awesome New Things", news_path(@news_item), :active => true
%>
</div>
Returns the breadcrumb trail. | [
"Displays",
"a",
"breadcrumb",
"trail"
] | 9db47dea0e2e73e164923de23be20109fe1cf35f | https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/helpers/manageable/application_helper.rb#L187-L208 | train |
fabiokr/manageable | app/helpers/manageable/application_helper.rb | Manageable.ApplicationHelper.manageable_button | def manageable_button(body, url, html_options = {})
html_options[:class] = [html_options[:class], "button"].compact.join(" ")
icon = manageable_icon(html_options.delete(:icon), :small, :alt => body) if html_options[:icon]
link_to url, html_options do
[icon, body].compact.join(" ").html_safe
end
end | ruby | def manageable_button(body, url, html_options = {})
html_options[:class] = [html_options[:class], "button"].compact.join(" ")
icon = manageable_icon(html_options.delete(:icon), :small, :alt => body) if html_options[:icon]
link_to url, html_options do
[icon, body].compact.join(" ").html_safe
end
end | [
"def",
"manageable_button",
"(",
"body",
",",
"url",
",",
"html_options",
"=",
"{",
"}",
")",
"html_options",
"[",
":class",
"]",
"=",
"[",
"html_options",
"[",
":class",
"]",
",",
"\"button\"",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"icon",
"=",
"manageable_icon",
"(",
"html_options",
".",
"delete",
"(",
":icon",
")",
",",
":small",
",",
":alt",
"=>",
"body",
")",
"if",
"html_options",
"[",
":icon",
"]",
"link_to",
"url",
",",
"html_options",
"do",
"[",
"icon",
",",
"body",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
".",
"html_safe",
"end",
"end"
] | Creates a link_to button | [
"Creates",
"a",
"link_to",
"button"
] | 9db47dea0e2e73e164923de23be20109fe1cf35f | https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/helpers/manageable/application_helper.rb#L229-L236 | train |
fabiokr/manageable | app/helpers/manageable/application_helper.rb | Manageable.ApplicationHelper.manageable_attributes | def manageable_attributes(record, options = {}, &block)
options[:html] ||= {}
html_class = [ "attrtastic", record.class.to_s.underscore, options[:html][:class] ].compact.join(" ")
output = tag(:div, { :class => html_class}, true)
if block_given?
output << capture(Helpers::AttributesBuilder.new(record, self), &block)
else
output << capture(Helpers::AttributesBuilder.new(record, self)) do |attr|
attr.attributes
end
end
output.safe_concat("</div>")
end | ruby | def manageable_attributes(record, options = {}, &block)
options[:html] ||= {}
html_class = [ "attrtastic", record.class.to_s.underscore, options[:html][:class] ].compact.join(" ")
output = tag(:div, { :class => html_class}, true)
if block_given?
output << capture(Helpers::AttributesBuilder.new(record, self), &block)
else
output << capture(Helpers::AttributesBuilder.new(record, self)) do |attr|
attr.attributes
end
end
output.safe_concat("</div>")
end | [
"def",
"manageable_attributes",
"(",
"record",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"[",
":html",
"]",
"||=",
"{",
"}",
"html_class",
"=",
"[",
"\"attrtastic\"",
",",
"record",
".",
"class",
".",
"to_s",
".",
"underscore",
",",
"options",
"[",
":html",
"]",
"[",
":class",
"]",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"output",
"=",
"tag",
"(",
":div",
",",
"{",
":class",
"=>",
"html_class",
"}",
",",
"true",
")",
"if",
"block_given?",
"output",
"<<",
"capture",
"(",
"Helpers",
"::",
"AttributesBuilder",
".",
"new",
"(",
"record",
",",
"self",
")",
",",
"&",
"block",
")",
"else",
"output",
"<<",
"capture",
"(",
"Helpers",
"::",
"AttributesBuilder",
".",
"new",
"(",
"record",
",",
"self",
")",
")",
"do",
"|",
"attr",
"|",
"attr",
".",
"attributes",
"end",
"end",
"output",
".",
"safe_concat",
"(",
"\"</div>\"",
")",
"end"
] | Helper for custom attrtastic like builder | [
"Helper",
"for",
"custom",
"attrtastic",
"like",
"builder"
] | 9db47dea0e2e73e164923de23be20109fe1cf35f | https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/helpers/manageable/application_helper.rb#L309-L323 | train |
glejeune/soap-lc | lib/soap/lc/request.rb | SOAP.Request.call | def call( methodName, args )
args = (args || {}) #.keys_to_sym!
# Get Binding
binding = @wsdl.bindings.getBindingForOperationName( @binding, methodName )
if binding.size == 0
raise SOAP::LCNoMethodError, "Undefined method `#{methodName}'"
elsif binding.size > 1
raise SOAP::LCError, "Ambigous method name `#{methodName}', please, specify a binding name"
else
binding = binding[0]
@binding = binding.name
end
# Get Binding Operation
binding_operation = binding.operations[methodName]
# Get PortType
portType = @wsdl.portTypes[binding.type.nns]
portType_operation = portType.operations[methodName]
# Get message for input operation
input_message = @wsdl.messages[portType_operation[:input][:message].nns]
# Create method
soap_method = "<#{methodName} xmlns=\"#{@wsdl.targetNamespace}\">\n"
input_message.parts.each do |_, attrs|
case attrs[:mode]
when :type
if SOAP::XSD::ANY_SIMPLE_TYPE.include?( attrs[attrs[:mode]].nns )
# Part refer to a builtin SimpleType
soap_method << SOAP::XSD.displayBuiltinType( attrs[:name], args, 1, 1 )
else
# Part refer to an XSD simpleType or complexType defined in types
element = @wsdl.types[attrs[attrs[:mode]].nns][:value]
case element[:type]
when :simpleType
soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ##########
when :complexType
soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ##########
else
raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}"
end
end
when :element
# Part refer to an XSD element
element = @wsdl.types[attrs[attrs[:mode]].nns][:value]
case element[:type]
when :simpleType
soap_method << element[element[:type]].display( @wsdl.types, args )
when :complexType
soap_method << element[element[:type]].display( @wsdl.types, args )
else
raise SOAL::LCWSDLError, "Malformated element `#{attrs[attrs[:mode]]}'"
end
## TODO ---------- USE element[:key]
else
raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}"
end
end
soap_method += "</#{methodName}>\n"
# Create SOAP Envelope
envelope = soap_envelop do
soap_header + soap_body( soap_method )
end
# Create headers
headers = Hash.new
# Add SOAPAction to headers (if exist)
action = begin
binding_operation[:soapAction]
rescue
nil
end
headers['SOAPAction'] = action unless action.nil? or action.length == 0
# Search URI
service_port = @wsdl.services.getServicePortForBindingName( binding.name )
address = service_port[:address]
# Complete request
@request = {
:headers => make_header( envelope, headers ),
:envelope => envelope,
:uri => address,
:wsdl => @wsdl,
:response => @wsdl.messages[portType_operation[:output][:message].nns].name,
:binding => @binding,
:method => methodName
}
return self
end | ruby | def call( methodName, args )
args = (args || {}) #.keys_to_sym!
# Get Binding
binding = @wsdl.bindings.getBindingForOperationName( @binding, methodName )
if binding.size == 0
raise SOAP::LCNoMethodError, "Undefined method `#{methodName}'"
elsif binding.size > 1
raise SOAP::LCError, "Ambigous method name `#{methodName}', please, specify a binding name"
else
binding = binding[0]
@binding = binding.name
end
# Get Binding Operation
binding_operation = binding.operations[methodName]
# Get PortType
portType = @wsdl.portTypes[binding.type.nns]
portType_operation = portType.operations[methodName]
# Get message for input operation
input_message = @wsdl.messages[portType_operation[:input][:message].nns]
# Create method
soap_method = "<#{methodName} xmlns=\"#{@wsdl.targetNamespace}\">\n"
input_message.parts.each do |_, attrs|
case attrs[:mode]
when :type
if SOAP::XSD::ANY_SIMPLE_TYPE.include?( attrs[attrs[:mode]].nns )
# Part refer to a builtin SimpleType
soap_method << SOAP::XSD.displayBuiltinType( attrs[:name], args, 1, 1 )
else
# Part refer to an XSD simpleType or complexType defined in types
element = @wsdl.types[attrs[attrs[:mode]].nns][:value]
case element[:type]
when :simpleType
soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ##########
when :complexType
soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ##########
else
raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}"
end
end
when :element
# Part refer to an XSD element
element = @wsdl.types[attrs[attrs[:mode]].nns][:value]
case element[:type]
when :simpleType
soap_method << element[element[:type]].display( @wsdl.types, args )
when :complexType
soap_method << element[element[:type]].display( @wsdl.types, args )
else
raise SOAL::LCWSDLError, "Malformated element `#{attrs[attrs[:mode]]}'"
end
## TODO ---------- USE element[:key]
else
raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}"
end
end
soap_method += "</#{methodName}>\n"
# Create SOAP Envelope
envelope = soap_envelop do
soap_header + soap_body( soap_method )
end
# Create headers
headers = Hash.new
# Add SOAPAction to headers (if exist)
action = begin
binding_operation[:soapAction]
rescue
nil
end
headers['SOAPAction'] = action unless action.nil? or action.length == 0
# Search URI
service_port = @wsdl.services.getServicePortForBindingName( binding.name )
address = service_port[:address]
# Complete request
@request = {
:headers => make_header( envelope, headers ),
:envelope => envelope,
:uri => address,
:wsdl => @wsdl,
:response => @wsdl.messages[portType_operation[:output][:message].nns].name,
:binding => @binding,
:method => methodName
}
return self
end | [
"def",
"call",
"(",
"methodName",
",",
"args",
")",
"args",
"=",
"(",
"args",
"||",
"{",
"}",
")",
"binding",
"=",
"@wsdl",
".",
"bindings",
".",
"getBindingForOperationName",
"(",
"@binding",
",",
"methodName",
")",
"if",
"binding",
".",
"size",
"==",
"0",
"raise",
"SOAP",
"::",
"LCNoMethodError",
",",
"\"Undefined method `#{methodName}'\"",
"elsif",
"binding",
".",
"size",
">",
"1",
"raise",
"SOAP",
"::",
"LCError",
",",
"\"Ambigous method name `#{methodName}', please, specify a binding name\"",
"else",
"binding",
"=",
"binding",
"[",
"0",
"]",
"@binding",
"=",
"binding",
".",
"name",
"end",
"binding_operation",
"=",
"binding",
".",
"operations",
"[",
"methodName",
"]",
"portType",
"=",
"@wsdl",
".",
"portTypes",
"[",
"binding",
".",
"type",
".",
"nns",
"]",
"portType_operation",
"=",
"portType",
".",
"operations",
"[",
"methodName",
"]",
"input_message",
"=",
"@wsdl",
".",
"messages",
"[",
"portType_operation",
"[",
":input",
"]",
"[",
":message",
"]",
".",
"nns",
"]",
"soap_method",
"=",
"\"<#{methodName} xmlns=\\\"#{@wsdl.targetNamespace}\\\">\\n\"",
"input_message",
".",
"parts",
".",
"each",
"do",
"|",
"_",
",",
"attrs",
"|",
"case",
"attrs",
"[",
":mode",
"]",
"when",
":type",
"if",
"SOAP",
"::",
"XSD",
"::",
"ANY_SIMPLE_TYPE",
".",
"include?",
"(",
"attrs",
"[",
"attrs",
"[",
":mode",
"]",
"]",
".",
"nns",
")",
"soap_method",
"<<",
"SOAP",
"::",
"XSD",
".",
"displayBuiltinType",
"(",
"attrs",
"[",
":name",
"]",
",",
"args",
",",
"1",
",",
"1",
")",
"else",
"element",
"=",
"@wsdl",
".",
"types",
"[",
"attrs",
"[",
"attrs",
"[",
":mode",
"]",
"]",
".",
"nns",
"]",
"[",
":value",
"]",
"case",
"element",
"[",
":type",
"]",
"when",
":simpleType",
"soap_method",
"<<",
"\"<#{attrs[:name]}>\\n#{element.display( @wsdl.types, args )}\\n</#{attrs[:name]}>\\n\"",
"when",
":complexType",
"soap_method",
"<<",
"\"<#{attrs[:name]}>\\n#{element.display( @wsdl.types, args )}\\n</#{attrs[:name]}>\\n\"",
"else",
"raise",
"SOAP",
"::",
"LCWSDLError",
",",
"\"Malformated part #{attrs[:name]}\"",
"end",
"end",
"when",
":element",
"element",
"=",
"@wsdl",
".",
"types",
"[",
"attrs",
"[",
"attrs",
"[",
":mode",
"]",
"]",
".",
"nns",
"]",
"[",
":value",
"]",
"case",
"element",
"[",
":type",
"]",
"when",
":simpleType",
"soap_method",
"<<",
"element",
"[",
"element",
"[",
":type",
"]",
"]",
".",
"display",
"(",
"@wsdl",
".",
"types",
",",
"args",
")",
"when",
":complexType",
"soap_method",
"<<",
"element",
"[",
"element",
"[",
":type",
"]",
"]",
".",
"display",
"(",
"@wsdl",
".",
"types",
",",
"args",
")",
"else",
"raise",
"SOAL",
"::",
"LCWSDLError",
",",
"\"Malformated element `#{attrs[attrs[:mode]]}'\"",
"end",
"else",
"raise",
"SOAP",
"::",
"LCWSDLError",
",",
"\"Malformated part #{attrs[:name]}\"",
"end",
"end",
"soap_method",
"+=",
"\"</#{methodName}>\\n\"",
"envelope",
"=",
"soap_envelop",
"do",
"soap_header",
"+",
"soap_body",
"(",
"soap_method",
")",
"end",
"headers",
"=",
"Hash",
".",
"new",
"action",
"=",
"begin",
"binding_operation",
"[",
":soapAction",
"]",
"rescue",
"nil",
"end",
"headers",
"[",
"'SOAPAction'",
"]",
"=",
"action",
"unless",
"action",
".",
"nil?",
"or",
"action",
".",
"length",
"==",
"0",
"service_port",
"=",
"@wsdl",
".",
"services",
".",
"getServicePortForBindingName",
"(",
"binding",
".",
"name",
")",
"address",
"=",
"service_port",
"[",
":address",
"]",
"@request",
"=",
"{",
":headers",
"=>",
"make_header",
"(",
"envelope",
",",
"headers",
")",
",",
":envelope",
"=>",
"envelope",
",",
":uri",
"=>",
"address",
",",
":wsdl",
"=>",
"@wsdl",
",",
":response",
"=>",
"@wsdl",
".",
"messages",
"[",
"portType_operation",
"[",
":output",
"]",
"[",
":message",
"]",
".",
"nns",
"]",
".",
"name",
",",
":binding",
"=>",
"@binding",
",",
":method",
"=>",
"methodName",
"}",
"return",
"self",
"end"
] | Call a method for the current Request
Example:
wsdl = SOAP::LC.new( ).wsdl( "http://..." )
request = wsdl.request( )
response = request.call( "myMethod", :param1 => "hello" )
# => #<SOAP::Response:0xNNNNNN> | [
"Call",
"a",
"method",
"for",
"the",
"current",
"Request"
] | dfb5b56494289f40dc92cff737b37ee2f418ae2b | https://github.com/glejeune/soap-lc/blob/dfb5b56494289f40dc92cff737b37ee2f418ae2b/lib/soap/lc/request.rb#L75-L169 | train |
IUBLibTech/ldap_groups_lookup | lib/ldap_groups_lookup/search.rb | LDAPGroupsLookup.Search.lookup_dn | def lookup_dn(cn)
service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'dn').first&.dn
end | ruby | def lookup_dn(cn)
service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'dn').first&.dn
end | [
"def",
"lookup_dn",
"(",
"cn",
")",
"service",
".",
"search",
"(",
"base",
":",
"tree",
",",
"filter",
":",
"Net",
"::",
"LDAP",
"::",
"Filter",
".",
"equals",
"(",
"'cn'",
",",
"cn",
")",
",",
"attributes",
":",
"'dn'",
")",
".",
"first",
"&.",
"dn",
"end"
] | Returns the DN for the given CN attribute | [
"Returns",
"the",
"DN",
"for",
"the",
"given",
"CN",
"attribute"
] | 430ff8e1dd084fdc7113fbfe85b6422900b39184 | https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L32-L34 | train |
IUBLibTech/ldap_groups_lookup | lib/ldap_groups_lookup/search.rb | LDAPGroupsLookup.Search.lookup_mail | def lookup_mail(cn)
service&.search(base: tree,
filter: Net::LDAP::Filter.equals('cn', cn),
attributes: 'mail')&.first&.mail&.first.to_s
end | ruby | def lookup_mail(cn)
service&.search(base: tree,
filter: Net::LDAP::Filter.equals('cn', cn),
attributes: 'mail')&.first&.mail&.first.to_s
end | [
"def",
"lookup_mail",
"(",
"cn",
")",
"service",
"&.",
"search",
"(",
"base",
":",
"tree",
",",
"filter",
":",
"Net",
"::",
"LDAP",
"::",
"Filter",
".",
"equals",
"(",
"'cn'",
",",
"cn",
")",
",",
"attributes",
":",
"'mail'",
")",
"&.",
"first",
"&.",
"mail",
"&.",
"first",
".",
"to_s",
"end"
] | Returns the mail for a given CN attribute | [
"Returns",
"the",
"mail",
"for",
"a",
"given",
"CN",
"attribute"
] | 430ff8e1dd084fdc7113fbfe85b6422900b39184 | https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L37-L41 | train |
IUBLibTech/ldap_groups_lookup | lib/ldap_groups_lookup/search.rb | LDAPGroupsLookup.Search.walk_ldap_members | def walk_ldap_members(groups, dn, seen = [])
groups.each do |g|
members = ldap_members(g)
return true if members.include? dn
next if seen.include? g
seen << g
member_groups = members.collect do |mg|
dn_to_cn(mg) if (mg.include?('OU=Groups') || mg.include?('OU=Applications'))
end
member_groups.compact!
return true if walk_ldap_members(member_groups, dn, seen)
end
return false
end | ruby | def walk_ldap_members(groups, dn, seen = [])
groups.each do |g|
members = ldap_members(g)
return true if members.include? dn
next if seen.include? g
seen << g
member_groups = members.collect do |mg|
dn_to_cn(mg) if (mg.include?('OU=Groups') || mg.include?('OU=Applications'))
end
member_groups.compact!
return true if walk_ldap_members(member_groups, dn, seen)
end
return false
end | [
"def",
"walk_ldap_members",
"(",
"groups",
",",
"dn",
",",
"seen",
"=",
"[",
"]",
")",
"groups",
".",
"each",
"do",
"|",
"g",
"|",
"members",
"=",
"ldap_members",
"(",
"g",
")",
"return",
"true",
"if",
"members",
".",
"include?",
"dn",
"next",
"if",
"seen",
".",
"include?",
"g",
"seen",
"<<",
"g",
"member_groups",
"=",
"members",
".",
"collect",
"do",
"|",
"mg",
"|",
"dn_to_cn",
"(",
"mg",
")",
"if",
"(",
"mg",
".",
"include?",
"(",
"'OU=Groups'",
")",
"||",
"mg",
".",
"include?",
"(",
"'OU=Applications'",
")",
")",
"end",
"member_groups",
".",
"compact!",
"return",
"true",
"if",
"walk_ldap_members",
"(",
"member_groups",
",",
"dn",
",",
"seen",
")",
"end",
"return",
"false",
"end"
] | Searches a group and its nested member groups for a member DN
@param [Array] groups CNs to search
@param [String] dn the DN to search for
@param [Array] seen groups that have already been traversed
@return [Boolean] true if dn was seen in groups | [
"Searches",
"a",
"group",
"and",
"its",
"nested",
"member",
"groups",
"for",
"a",
"member",
"DN"
] | 430ff8e1dd084fdc7113fbfe85b6422900b39184 | https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L53-L66 | train |
IUBLibTech/ldap_groups_lookup | lib/ldap_groups_lookup/search.rb | LDAPGroupsLookup.Search.ldap_members | def ldap_members(cn, start=0)
return [] if service.nil?
# print "Getting members of #{cn} at index #{start}\n"
entry = service.search(base: tree,
filter: Net::LDAP::Filter.equals('cn', cn),
attributes: ["member;range=#{start}-*"]).first
return [] if entry.nil?
field_name = entry.attribute_names[1] # Is this always ordered [dn, member]?
return [] if field_name.nil? # Sometimes member is not present.
range_end = field_name.to_s.match(/^member;range=\d+-([0-9*]+)$/)[1]
# print "#{start}-#{range_end}\n"
members = entry[field_name]#.collect { |mo| mo.split(',').first.split('=')[1] }
members.concat ldap_members(cn, range_end.to_i+1) unless range_end == '*'
return members
end | ruby | def ldap_members(cn, start=0)
return [] if service.nil?
# print "Getting members of #{cn} at index #{start}\n"
entry = service.search(base: tree,
filter: Net::LDAP::Filter.equals('cn', cn),
attributes: ["member;range=#{start}-*"]).first
return [] if entry.nil?
field_name = entry.attribute_names[1] # Is this always ordered [dn, member]?
return [] if field_name.nil? # Sometimes member is not present.
range_end = field_name.to_s.match(/^member;range=\d+-([0-9*]+)$/)[1]
# print "#{start}-#{range_end}\n"
members = entry[field_name]#.collect { |mo| mo.split(',').first.split('=')[1] }
members.concat ldap_members(cn, range_end.to_i+1) unless range_end == '*'
return members
end | [
"def",
"ldap_members",
"(",
"cn",
",",
"start",
"=",
"0",
")",
"return",
"[",
"]",
"if",
"service",
".",
"nil?",
"entry",
"=",
"service",
".",
"search",
"(",
"base",
":",
"tree",
",",
"filter",
":",
"Net",
"::",
"LDAP",
"::",
"Filter",
".",
"equals",
"(",
"'cn'",
",",
"cn",
")",
",",
"attributes",
":",
"[",
"\"member;range=#{start}-*\"",
"]",
")",
".",
"first",
"return",
"[",
"]",
"if",
"entry",
".",
"nil?",
"field_name",
"=",
"entry",
".",
"attribute_names",
"[",
"1",
"]",
"return",
"[",
"]",
"if",
"field_name",
".",
"nil?",
"range_end",
"=",
"field_name",
".",
"to_s",
".",
"match",
"(",
"/",
"\\d",
"/",
")",
"[",
"1",
"]",
"members",
"=",
"entry",
"[",
"field_name",
"]",
"members",
".",
"concat",
"ldap_members",
"(",
"cn",
",",
"range_end",
".",
"to_i",
"+",
"1",
")",
"unless",
"range_end",
"==",
"'*'",
"return",
"members",
"end"
] | Gets the entire list of members for a CN.
Handles range results.
@param [String] cn of the entry to fetch.
@param [Integer] start index of range result
@return [Array] list of member CNs | [
"Gets",
"the",
"entire",
"list",
"of",
"members",
"for",
"a",
"CN",
".",
"Handles",
"range",
"results",
"."
] | 430ff8e1dd084fdc7113fbfe85b6422900b39184 | https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L73-L89 | train |
offers/singularity-cli | lib/singularity/request.rb | Singularity.Request.deploy | def deploy
if is_paused
puts ' PAUSED, SKIPPING.'
return
else
@data['requestId'] = @data['id']
@data['id'] = "#{@release}.#{Time.now.to_i}"
@data['containerInfo']['docker']['image'] =
File.exist?('dcos-deploy/config.yml') ?
YAML.load_file(File.join(Dir.pwd, 'dcos-deploy/config.yml'))['repo']+":#{@release}" :
"#{JSON.parse(File.read('.mescal.json'))['image'].split(':').first}:#{@release}"
@deploy = {
'deploy' => @data,
'user' => `whoami`.chomp,
'unpauseOnSuccessfulDeploy' => false
}
# deploy the request
RestClient.post "#{@uri}/api/deploys", @deploy.to_json, :content_type => :json
puts ' Deploy succeeded: '.green + @data['requestId'].light_blue
end
end | ruby | def deploy
if is_paused
puts ' PAUSED, SKIPPING.'
return
else
@data['requestId'] = @data['id']
@data['id'] = "#{@release}.#{Time.now.to_i}"
@data['containerInfo']['docker']['image'] =
File.exist?('dcos-deploy/config.yml') ?
YAML.load_file(File.join(Dir.pwd, 'dcos-deploy/config.yml'))['repo']+":#{@release}" :
"#{JSON.parse(File.read('.mescal.json'))['image'].split(':').first}:#{@release}"
@deploy = {
'deploy' => @data,
'user' => `whoami`.chomp,
'unpauseOnSuccessfulDeploy' => false
}
# deploy the request
RestClient.post "#{@uri}/api/deploys", @deploy.to_json, :content_type => :json
puts ' Deploy succeeded: '.green + @data['requestId'].light_blue
end
end | [
"def",
"deploy",
"if",
"is_paused",
"puts",
"' PAUSED, SKIPPING.'",
"return",
"else",
"@data",
"[",
"'requestId'",
"]",
"=",
"@data",
"[",
"'id'",
"]",
"@data",
"[",
"'id'",
"]",
"=",
"\"#{@release}.#{Time.now.to_i}\"",
"@data",
"[",
"'containerInfo'",
"]",
"[",
"'docker'",
"]",
"[",
"'image'",
"]",
"=",
"File",
".",
"exist?",
"(",
"'dcos-deploy/config.yml'",
")",
"?",
"YAML",
".",
"load_file",
"(",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"'dcos-deploy/config.yml'",
")",
")",
"[",
"'repo'",
"]",
"+",
"\":#{@release}\"",
":",
"\"#{JSON.parse(File.read('.mescal.json'))['image'].split(':').first}:#{@release}\"",
"@deploy",
"=",
"{",
"'deploy'",
"=>",
"@data",
",",
"'user'",
"=>",
"`",
"`",
".",
"chomp",
",",
"'unpauseOnSuccessfulDeploy'",
"=>",
"false",
"}",
"RestClient",
".",
"post",
"\"#{@uri}/api/deploys\"",
",",
"@deploy",
".",
"to_json",
",",
":content_type",
"=>",
":json",
"puts",
"' Deploy succeeded: '",
".",
"green",
"+",
"@data",
"[",
"'requestId'",
"]",
".",
"light_blue",
"end",
"end"
] | deploys a request in singularity | [
"deploys",
"a",
"request",
"in",
"singularity"
] | c0c769880d06da7b23d0220166e56914e2190d61 | https://github.com/offers/singularity-cli/blob/c0c769880d06da7b23d0220166e56914e2190d61/lib/singularity/request.rb#L28-L48 | train |
localmed/outbox | lib/outbox/message.rb | Outbox.Message.body | def body(value)
each_message_type do |_, message|
next if message.nil?
message.body = value
end
end | ruby | def body(value)
each_message_type do |_, message|
next if message.nil?
message.body = value
end
end | [
"def",
"body",
"(",
"value",
")",
"each_message_type",
"do",
"|",
"_",
",",
"message",
"|",
"next",
"if",
"message",
".",
"nil?",
"message",
".",
"body",
"=",
"value",
"end",
"end"
] | Make a new message. Every message can be created using a hash,
block, or direct assignment.
message = Message.new do
email do
subject 'Subject'
end
end
message = Message.new email: { subject: 'Subject' }
message = Message.new
message.email = Email.new subject: 'Subject'
Loops through each registered message type and sets the content body. | [
"Make",
"a",
"new",
"message",
".",
"Every",
"message",
"can",
"be",
"created",
"using",
"a",
"hash",
"block",
"or",
"direct",
"assignment",
"."
] | 4c7bd2129df7d2bbb49e464699afed9eb8396a5f | https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message.rb#L36-L41 | train |
localmed/outbox | lib/outbox/message.rb | Outbox.Message.deliver | def deliver(audience)
audience = Outbox::Accessor.new(audience)
each_message_type do |message_type, message|
next if message.nil?
recipient = audience[message_type]
message.deliver(recipient) if recipient
end
end | ruby | def deliver(audience)
audience = Outbox::Accessor.new(audience)
each_message_type do |message_type, message|
next if message.nil?
recipient = audience[message_type]
message.deliver(recipient) if recipient
end
end | [
"def",
"deliver",
"(",
"audience",
")",
"audience",
"=",
"Outbox",
"::",
"Accessor",
".",
"new",
"(",
"audience",
")",
"each_message_type",
"do",
"|",
"message_type",
",",
"message",
"|",
"next",
"if",
"message",
".",
"nil?",
"recipient",
"=",
"audience",
"[",
"message_type",
"]",
"message",
".",
"deliver",
"(",
"recipient",
")",
"if",
"recipient",
"end",
"end"
] | Delivers all of the messages to the given 'audience'. An 'audience'
object can be a hash or an object that responds to the current message
types. Only the message types specified in the 'audience' object will
be sent to.
message.deliver email: '[email protected]', sms: '+15555555555'
audience = OpenStruct.new
audience.email = '[email protected]'
audience.sms = '+15555555555'
message.deliver(audience) | [
"Delivers",
"all",
"of",
"the",
"messages",
"to",
"the",
"given",
"audience",
".",
"An",
"audience",
"object",
"can",
"be",
"a",
"hash",
"or",
"an",
"object",
"that",
"responds",
"to",
"the",
"current",
"message",
"types",
".",
"Only",
"the",
"message",
"types",
"specified",
"in",
"the",
"audience",
"object",
"will",
"be",
"sent",
"to",
"."
] | 4c7bd2129df7d2bbb49e464699afed9eb8396a5f | https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message.rb#L54-L63 | train |
tecfoundary/hicube | app/controllers/hicube/application_controller.rb | Hicube.ApplicationController.notify | def notify(type, message, options = {})
options[:now] ||= false
# Convert and cleanup.
type = type.to_s.downcase.to_sym
# Sanity check for type.
unless FLASH_TYPES.include?(type)
raise ArgumentError, "Invalid value for argument type: #{type}, expected one of: #{FLASH_TYPES.to_sentence}."
end
logger.info("FLASH (#{options.inspect}) #{type.to_s.upcase}: #{message}")
if options[:now] == true
flash.now[type] ||= []
flash.now[type] << message
else
flash[type] ||= []
flash[type] << message
end
logger.debug("DEBUG: FLASH #{flash.inspect}")
return true
end | ruby | def notify(type, message, options = {})
options[:now] ||= false
# Convert and cleanup.
type = type.to_s.downcase.to_sym
# Sanity check for type.
unless FLASH_TYPES.include?(type)
raise ArgumentError, "Invalid value for argument type: #{type}, expected one of: #{FLASH_TYPES.to_sentence}."
end
logger.info("FLASH (#{options.inspect}) #{type.to_s.upcase}: #{message}")
if options[:now] == true
flash.now[type] ||= []
flash.now[type] << message
else
flash[type] ||= []
flash[type] << message
end
logger.debug("DEBUG: FLASH #{flash.inspect}")
return true
end | [
"def",
"notify",
"(",
"type",
",",
"message",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":now",
"]",
"||=",
"false",
"type",
"=",
"type",
".",
"to_s",
".",
"downcase",
".",
"to_sym",
"unless",
"FLASH_TYPES",
".",
"include?",
"(",
"type",
")",
"raise",
"ArgumentError",
",",
"\"Invalid value for argument type: #{type}, expected one of: #{FLASH_TYPES.to_sentence}.\"",
"end",
"logger",
".",
"info",
"(",
"\"FLASH (#{options.inspect}) #{type.to_s.upcase}: #{message}\"",
")",
"if",
"options",
"[",
":now",
"]",
"==",
"true",
"flash",
".",
"now",
"[",
"type",
"]",
"||=",
"[",
"]",
"flash",
".",
"now",
"[",
"type",
"]",
"<<",
"message",
"else",
"flash",
"[",
"type",
"]",
"||=",
"[",
"]",
"flash",
"[",
"type",
"]",
"<<",
"message",
"end",
"logger",
".",
"debug",
"(",
"\"DEBUG: FLASH #{flash.inspect}\"",
")",
"return",
"true",
"end"
] | Generate a notification message. | [
"Generate",
"a",
"notification",
"message",
"."
] | 57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe | https://github.com/tecfoundary/hicube/blob/57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe/app/controllers/hicube/application_controller.rb#L46-L70 | train |
JavonDavis/parallel_appium | lib/parallel_appium/android.rb | ParallelAppium.Android.start_emulators | def start_emulators
emulators = `emulator -list-avds`.split("\n")
emulators = emulators[0, ENV['THREADS'].to_i]
Parallel.map(emulators, in_threads: emulators.size) do |emulator|
spawn("emulator -avd #{emulator} -no-snapshot-load -scale 100dpi -no-boot-anim -no-audio -accel on &", out: '/dev/null')
end
emulators
end | ruby | def start_emulators
emulators = `emulator -list-avds`.split("\n")
emulators = emulators[0, ENV['THREADS'].to_i]
Parallel.map(emulators, in_threads: emulators.size) do |emulator|
spawn("emulator -avd #{emulator} -no-snapshot-load -scale 100dpi -no-boot-anim -no-audio -accel on &", out: '/dev/null')
end
emulators
end | [
"def",
"start_emulators",
"emulators",
"=",
"`",
"`",
".",
"split",
"(",
"\"\\n\"",
")",
"emulators",
"=",
"emulators",
"[",
"0",
",",
"ENV",
"[",
"'THREADS'",
"]",
".",
"to_i",
"]",
"Parallel",
".",
"map",
"(",
"emulators",
",",
"in_threads",
":",
"emulators",
".",
"size",
")",
"do",
"|",
"emulator",
"|",
"spawn",
"(",
"\"emulator -avd #{emulator} -no-snapshot-load -scale 100dpi -no-boot-anim -no-audio -accel on &\"",
",",
"out",
":",
"'/dev/null'",
")",
"end",
"emulators",
"end"
] | Fire up the Android emulators | [
"Fire",
"up",
"the",
"Android",
"emulators"
] | 2e92bf6f4cf6142909080f471dda196ee12c41ea | https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/android.rb#L5-L13 | train |
henkm/shake-the-counter | lib/shake_the_counter/section.rb | ShakeTheCounter.Section.make_reservation | def make_reservation(price_type_list: {}, affiliate: '', first_name: '', last_name: '', email: '')
# step 1: make the reservation
path = "event/#{performance.event.key}/performance/#{performance.key}/section/#{performance_section_key}/reservation/#{performance.event.client.language_code}"
body = {
PriceTypeList: price_type_list
}
result = performance.event.client.call(path, http_method: :post, body: body.to_json)
reservation = ShakeTheCounter::Reservation.new(result)
# step 2: create a contact
path = "contact/#{performance.event.client.language_code}"
body = {
FirstName: first_name,
LastName: last_name,
MailAddress: email,
LanguageCode: performance.event.client.language_code
}
result = performance.event.client.call(path, http_method: :post, body: body.to_json)
contact = ShakeTheCounter::Contact.new(result)
# step 3: link contact to the reservation
path = "reservation/#{reservation.key}/contact"
body = {
ContactKey: contact.key
}
result = performance.event.client.call(path, http_method: :post, body: body.to_json)
return reservation
end | ruby | def make_reservation(price_type_list: {}, affiliate: '', first_name: '', last_name: '', email: '')
# step 1: make the reservation
path = "event/#{performance.event.key}/performance/#{performance.key}/section/#{performance_section_key}/reservation/#{performance.event.client.language_code}"
body = {
PriceTypeList: price_type_list
}
result = performance.event.client.call(path, http_method: :post, body: body.to_json)
reservation = ShakeTheCounter::Reservation.new(result)
# step 2: create a contact
path = "contact/#{performance.event.client.language_code}"
body = {
FirstName: first_name,
LastName: last_name,
MailAddress: email,
LanguageCode: performance.event.client.language_code
}
result = performance.event.client.call(path, http_method: :post, body: body.to_json)
contact = ShakeTheCounter::Contact.new(result)
# step 3: link contact to the reservation
path = "reservation/#{reservation.key}/contact"
body = {
ContactKey: contact.key
}
result = performance.event.client.call(path, http_method: :post, body: body.to_json)
return reservation
end | [
"def",
"make_reservation",
"(",
"price_type_list",
":",
"{",
"}",
",",
"affiliate",
":",
"''",
",",
"first_name",
":",
"''",
",",
"last_name",
":",
"''",
",",
"email",
":",
"''",
")",
"path",
"=",
"\"event/#{performance.event.key}/performance/#{performance.key}/section/#{performance_section_key}/reservation/#{performance.event.client.language_code}\"",
"body",
"=",
"{",
"PriceTypeList",
":",
"price_type_list",
"}",
"result",
"=",
"performance",
".",
"event",
".",
"client",
".",
"call",
"(",
"path",
",",
"http_method",
":",
":post",
",",
"body",
":",
"body",
".",
"to_json",
")",
"reservation",
"=",
"ShakeTheCounter",
"::",
"Reservation",
".",
"new",
"(",
"result",
")",
"path",
"=",
"\"contact/#{performance.event.client.language_code}\"",
"body",
"=",
"{",
"FirstName",
":",
"first_name",
",",
"LastName",
":",
"last_name",
",",
"MailAddress",
":",
"email",
",",
"LanguageCode",
":",
"performance",
".",
"event",
".",
"client",
".",
"language_code",
"}",
"result",
"=",
"performance",
".",
"event",
".",
"client",
".",
"call",
"(",
"path",
",",
"http_method",
":",
":post",
",",
"body",
":",
"body",
".",
"to_json",
")",
"contact",
"=",
"ShakeTheCounter",
"::",
"Contact",
".",
"new",
"(",
"result",
")",
"path",
"=",
"\"reservation/#{reservation.key}/contact\"",
"body",
"=",
"{",
"ContactKey",
":",
"contact",
".",
"key",
"}",
"result",
"=",
"performance",
".",
"event",
".",
"client",
".",
"call",
"(",
"path",
",",
"http_method",
":",
":post",
",",
"body",
":",
"body",
".",
"to_json",
")",
"return",
"reservation",
"end"
] | Sets up a new section
Makes a reservation for this section
POST /api/v1/event/{eventKey}/performance/{performanceKey}/section/{performanceSectionKey}/reservation/{languageCode}
@param email: '' [type] [description]
@return Reservation | [
"Sets",
"up",
"a",
"new",
"section"
] | 094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e | https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/section.rb#L36-L64 | train |
G5/modelish | lib/modelish/base.rb | Modelish.Base.to_hash | def to_hash
out = {}
self.class.properties.each { |p| out[hash_key(p)] = hash_value(p) }
out
end | ruby | def to_hash
out = {}
self.class.properties.each { |p| out[hash_key(p)] = hash_value(p) }
out
end | [
"def",
"to_hash",
"out",
"=",
"{",
"}",
"self",
".",
"class",
".",
"properties",
".",
"each",
"{",
"|",
"p",
"|",
"out",
"[",
"hash_key",
"(",
"p",
")",
"]",
"=",
"hash_value",
"(",
"p",
")",
"}",
"out",
"end"
] | Convert this Modelish object into a vanilla Hash with stringified keys.
@return [Hash] the hash of properties | [
"Convert",
"this",
"Modelish",
"object",
"into",
"a",
"vanilla",
"Hash",
"with",
"stringified",
"keys",
"."
] | 42cb6e07dafd794e0180b858a36fb7b5a8e424b6 | https://github.com/G5/modelish/blob/42cb6e07dafd794e0180b858a36fb7b5a8e424b6/lib/modelish/base.rb#L27-L31 | train |
cknadler/git-feats | lib/git-feats/checker.rb | GitFeats.Checker.check | def check(args)
# Load history and completed
Completed.unserialize
History.unserialize
# request flag
upload = false
# Check for feats and update history
Feats.all.each do |pattern, feats|
if args.match?(pattern)
History.add(pattern)
feats.each do |feat, value|
if History.count(pattern) >= value[:count]
unless Completed.exists?(feat)
Completed.add(feat)
Reporter.report(value)
upload = true
end
end
end
end
end
# upload feats if the request flag is set
upload_feats if upload
# Write out history and completed feats
Completed.serialize
History.serialize
end | ruby | def check(args)
# Load history and completed
Completed.unserialize
History.unserialize
# request flag
upload = false
# Check for feats and update history
Feats.all.each do |pattern, feats|
if args.match?(pattern)
History.add(pattern)
feats.each do |feat, value|
if History.count(pattern) >= value[:count]
unless Completed.exists?(feat)
Completed.add(feat)
Reporter.report(value)
upload = true
end
end
end
end
end
# upload feats if the request flag is set
upload_feats if upload
# Write out history and completed feats
Completed.serialize
History.serialize
end | [
"def",
"check",
"(",
"args",
")",
"Completed",
".",
"unserialize",
"History",
".",
"unserialize",
"upload",
"=",
"false",
"Feats",
".",
"all",
".",
"each",
"do",
"|",
"pattern",
",",
"feats",
"|",
"if",
"args",
".",
"match?",
"(",
"pattern",
")",
"History",
".",
"add",
"(",
"pattern",
")",
"feats",
".",
"each",
"do",
"|",
"feat",
",",
"value",
"|",
"if",
"History",
".",
"count",
"(",
"pattern",
")",
">=",
"value",
"[",
":count",
"]",
"unless",
"Completed",
".",
"exists?",
"(",
"feat",
")",
"Completed",
".",
"add",
"(",
"feat",
")",
"Reporter",
".",
"report",
"(",
"value",
")",
"upload",
"=",
"true",
"end",
"end",
"end",
"end",
"end",
"upload_feats",
"if",
"upload",
"Completed",
".",
"serialize",
"History",
".",
"serialize",
"end"
] | Main interface for checking feats | [
"Main",
"interface",
"for",
"checking",
"feats"
] | a2425c2c5998b0c5f817d8a80efc8c2bd053786e | https://github.com/cknadler/git-feats/blob/a2425c2c5998b0c5f817d8a80efc8c2bd053786e/lib/git-feats/checker.rb#L7-L39 | train |
pjaspers/shack | lib/shack/stamp.rb | Shack.Stamp.rounded_corner | def rounded_corner(horizontal, vertical)
css = [] << "border"
attrs = {
top: "bottom", bottom: "top",
left: "right", right: "left" }
css << attrs.fetch(vertical)
css << attrs.fetch(horizontal)
css << "radius"
css.join("-")
end | ruby | def rounded_corner(horizontal, vertical)
css = [] << "border"
attrs = {
top: "bottom", bottom: "top",
left: "right", right: "left" }
css << attrs.fetch(vertical)
css << attrs.fetch(horizontal)
css << "radius"
css.join("-")
end | [
"def",
"rounded_corner",
"(",
"horizontal",
",",
"vertical",
")",
"css",
"=",
"[",
"]",
"<<",
"\"border\"",
"attrs",
"=",
"{",
"top",
":",
"\"bottom\"",
",",
"bottom",
":",
"\"top\"",
",",
"left",
":",
"\"right\"",
",",
"right",
":",
"\"left\"",
"}",
"css",
"<<",
"attrs",
".",
"fetch",
"(",
"vertical",
")",
"css",
"<<",
"attrs",
".",
"fetch",
"(",
"horizontal",
")",
"css",
"<<",
"\"radius\"",
"css",
".",
"join",
"(",
"\"-\"",
")",
"end"
] | Returns the CSS needed to round the correct corner
`border-top-left-radius` | [
"Returns",
"the",
"CSS",
"needed",
"to",
"round",
"the",
"correct",
"corner"
] | bc65001fcd375e6da0c3c4b2f234766a3c0e6e22 | https://github.com/pjaspers/shack/blob/bc65001fcd375e6da0c3c4b2f234766a3c0e6e22/lib/shack/stamp.rb#L50-L59 | train |
Chris911/imgurr | lib/imgurr/storage.rb | Imgurr.Storage.bootstrap | def bootstrap
return if File.exist?(json_file)
FileUtils.touch json_file
File.open(json_file, 'w') {|f| f.write(to_json) }
save
end | ruby | def bootstrap
return if File.exist?(json_file)
FileUtils.touch json_file
File.open(json_file, 'w') {|f| f.write(to_json) }
save
end | [
"def",
"bootstrap",
"return",
"if",
"File",
".",
"exist?",
"(",
"json_file",
")",
"FileUtils",
".",
"touch",
"json_file",
"File",
".",
"open",
"(",
"json_file",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"to_json",
")",
"}",
"save",
"end"
] | Takes care of bootstrapping the Json file, both in terms of creating the
file and in terms of creating a skeleton Json schema.
Return true if successfully saved. | [
"Takes",
"care",
"of",
"bootstrapping",
"the",
"Json",
"file",
"both",
"in",
"terms",
"of",
"creating",
"the",
"file",
"and",
"in",
"terms",
"of",
"creating",
"a",
"skeleton",
"Json",
"schema",
"."
] | 09a492a80b9ec1ddf827501e6da6ad3dfa6d224d | https://github.com/Chris911/imgurr/blob/09a492a80b9ec1ddf827501e6da6ad3dfa6d224d/lib/imgurr/storage.rb#L91-L96 | train |
neo4j-examples/graph_starter | app/helpers/graph_starter/application_helper.rb | GraphStarter.ApplicationHelper.asset_icon | def asset_icon(asset, image = (image_unspecified = true; nil))
image_url = if !image_unspecified
image.source.url if image.present?
elsif (asset.class.has_images? || asset.class.has_image?) && asset.first_image_source_url.present?
asset.first_image_source_url
end
if image_url
image_tag image_url, class: 'ui avatar image'
else
content_tag :i, '', class: [asset.class.icon_class || 'folder', 'large', 'icon']
end
end | ruby | def asset_icon(asset, image = (image_unspecified = true; nil))
image_url = if !image_unspecified
image.source.url if image.present?
elsif (asset.class.has_images? || asset.class.has_image?) && asset.first_image_source_url.present?
asset.first_image_source_url
end
if image_url
image_tag image_url, class: 'ui avatar image'
else
content_tag :i, '', class: [asset.class.icon_class || 'folder', 'large', 'icon']
end
end | [
"def",
"asset_icon",
"(",
"asset",
",",
"image",
"=",
"(",
"image_unspecified",
"=",
"true",
";",
"nil",
")",
")",
"image_url",
"=",
"if",
"!",
"image_unspecified",
"image",
".",
"source",
".",
"url",
"if",
"image",
".",
"present?",
"elsif",
"(",
"asset",
".",
"class",
".",
"has_images?",
"||",
"asset",
".",
"class",
".",
"has_image?",
")",
"&&",
"asset",
".",
"first_image_source_url",
".",
"present?",
"asset",
".",
"first_image_source_url",
"end",
"if",
"image_url",
"image_tag",
"image_url",
",",
"class",
":",
"'ui avatar image'",
"else",
"content_tag",
":i",
",",
"''",
",",
"class",
":",
"[",
"asset",
".",
"class",
".",
"icon_class",
"||",
"'folder'",
",",
"'large'",
",",
"'icon'",
"]",
"end",
"end"
] | I know, right? | [
"I",
"know",
"right?"
] | 3c3d28c3df3513ed6ddb3037b245d6c66d0fc05a | https://github.com/neo4j-examples/graph_starter/blob/3c3d28c3df3513ed6ddb3037b245d6c66d0fc05a/app/helpers/graph_starter/application_helper.rb#L38-L50 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.get_platform_project | def get_platform_project(name)
if name =~ /debian/
return DEBIAN_PROJECT
elsif name =~ /centos/
return CENTOS_PROJECT
elsif name =~ /rhel/
return RHEL_PROJECT
elsif name =~ /sles/
return SLES_PROJECT
else
raise "Unsupported platform for Google Compute Engine: #{name}"
end
end | ruby | def get_platform_project(name)
if name =~ /debian/
return DEBIAN_PROJECT
elsif name =~ /centos/
return CENTOS_PROJECT
elsif name =~ /rhel/
return RHEL_PROJECT
elsif name =~ /sles/
return SLES_PROJECT
else
raise "Unsupported platform for Google Compute Engine: #{name}"
end
end | [
"def",
"get_platform_project",
"(",
"name",
")",
"if",
"name",
"=~",
"/",
"/",
"return",
"DEBIAN_PROJECT",
"elsif",
"name",
"=~",
"/",
"/",
"return",
"CENTOS_PROJECT",
"elsif",
"name",
"=~",
"/",
"/",
"return",
"RHEL_PROJECT",
"elsif",
"name",
"=~",
"/",
"/",
"return",
"SLES_PROJECT",
"else",
"raise",
"\"Unsupported platform for Google Compute Engine: #{name}\"",
"end",
"end"
] | Determines the Google Compute project which contains bases instances of
type name
@param [String] name The platform type to search for
@return The Google Compute project name
@raise [Exception] If the provided platform type name is unsupported | [
"Determines",
"the",
"Google",
"Compute",
"project",
"which",
"contains",
"bases",
"instances",
"of",
"type",
"name"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L106-L118 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.set_compute_api | def set_compute_api version, start, attempts
try = (Time.now - start)/SLEEPWAIT
while try <= attempts
begin
@compute = @client.discovered_api('compute', version)
@logger.debug("Google Compute API discovered")
return
rescue => e
@logger.debug("Failed to discover Google Compute API")
if try >= attempts
raise e
end
end
try += 1
end
end | ruby | def set_compute_api version, start, attempts
try = (Time.now - start)/SLEEPWAIT
while try <= attempts
begin
@compute = @client.discovered_api('compute', version)
@logger.debug("Google Compute API discovered")
return
rescue => e
@logger.debug("Failed to discover Google Compute API")
if try >= attempts
raise e
end
end
try += 1
end
end | [
"def",
"set_compute_api",
"version",
",",
"start",
",",
"attempts",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"try",
"<=",
"attempts",
"begin",
"@compute",
"=",
"@client",
".",
"discovered_api",
"(",
"'compute'",
",",
"version",
")",
"@logger",
".",
"debug",
"(",
"\"Google Compute API discovered\"",
")",
"return",
"rescue",
"=>",
"e",
"@logger",
".",
"debug",
"(",
"\"Failed to discover Google Compute API\"",
")",
"if",
"try",
">=",
"attempts",
"raise",
"e",
"end",
"end",
"try",
"+=",
"1",
"end",
"end"
] | Discover the currently active Google Compute API
@param [String] version The version of the Google Compute API to discover
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail to discover the Google Compute API,
either through errors or running out of attempts | [
"Discover",
"the",
"currently",
"active",
"Google",
"Compute",
"API"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L141-L156 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.authenticate | def authenticate(keyfile, password, email, start, attempts)
# OAuth authentication, using the service account
key = ::Google::APIClient::PKCS12.load_key(keyfile, password)
service_account = ::Google::APIClient::JWTAsserter.new(
email,
AUTH_URL,
key)
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
@client.authorization = service_account.authorize
@logger.debug("Authorized to use Google Compute")
return
rescue => e
@logger.debug("Failed to authorize to use Google Compute")
if try >= attempts
raise e
end
end
try += 1
end
end | ruby | def authenticate(keyfile, password, email, start, attempts)
# OAuth authentication, using the service account
key = ::Google::APIClient::PKCS12.load_key(keyfile, password)
service_account = ::Google::APIClient::JWTAsserter.new(
email,
AUTH_URL,
key)
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
@client.authorization = service_account.authorize
@logger.debug("Authorized to use Google Compute")
return
rescue => e
@logger.debug("Failed to authorize to use Google Compute")
if try >= attempts
raise e
end
end
try += 1
end
end | [
"def",
"authenticate",
"(",
"keyfile",
",",
"password",
",",
"email",
",",
"start",
",",
"attempts",
")",
"key",
"=",
"::",
"Google",
"::",
"APIClient",
"::",
"PKCS12",
".",
"load_key",
"(",
"keyfile",
",",
"password",
")",
"service_account",
"=",
"::",
"Google",
"::",
"APIClient",
"::",
"JWTAsserter",
".",
"new",
"(",
"email",
",",
"AUTH_URL",
",",
"key",
")",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"try",
"<=",
"attempts",
"begin",
"@client",
".",
"authorization",
"=",
"service_account",
".",
"authorize",
"@logger",
".",
"debug",
"(",
"\"Authorized to use Google Compute\"",
")",
"return",
"rescue",
"=>",
"e",
"@logger",
".",
"debug",
"(",
"\"Failed to authorize to use Google Compute\"",
")",
"if",
"try",
">=",
"attempts",
"raise",
"e",
"end",
"end",
"try",
"+=",
"1",
"end",
"end"
] | Creates an authenticated connection to the Google Compute Engine API
@param [String] keyfile The location of the Google Compute Service
Account keyfile to use for authentication
@param [String] password The password for the provided Google Compute
Service Account key
@param [String] email The email address of the Google Compute Service
Account we are using to connect
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail to create an authenticated
connection to the Google Compute API, either through errors or running
out of attempts | [
"Creates",
"an",
"authenticated",
"connection",
"to",
"the",
"Google",
"Compute",
"Engine",
"API"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L179-L200 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.execute | def execute req, start, attempts
last_error = parsed = nil
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
result = @client.execute(req)
parsed = JSON.parse(result.body)
if not result.success?
error_code = parsed["error"] ? parsed["error"]["code"] : 0
if error_code == 404
raise GoogleComputeError, "Resource Not Found: #{result.body}"
elsif error_code == 400
raise GoogleComputeError, "Bad Request: #{result.body}"
else
raise GoogleComputeError, "Error attempting Google Compute API execute: #{result.body}"
end
end
return parsed
# retry errors
rescue Faraday::Error::ConnectionFailed => e
@logger.debug "ConnectionFailed attempting Google Compute execute command"
try += 1
last_error = e
end
end
# we only get down here if we've used up all our tries
raise last_error
end | ruby | def execute req, start, attempts
last_error = parsed = nil
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
result = @client.execute(req)
parsed = JSON.parse(result.body)
if not result.success?
error_code = parsed["error"] ? parsed["error"]["code"] : 0
if error_code == 404
raise GoogleComputeError, "Resource Not Found: #{result.body}"
elsif error_code == 400
raise GoogleComputeError, "Bad Request: #{result.body}"
else
raise GoogleComputeError, "Error attempting Google Compute API execute: #{result.body}"
end
end
return parsed
# retry errors
rescue Faraday::Error::ConnectionFailed => e
@logger.debug "ConnectionFailed attempting Google Compute execute command"
try += 1
last_error = e
end
end
# we only get down here if we've used up all our tries
raise last_error
end | [
"def",
"execute",
"req",
",",
"start",
",",
"attempts",
"last_error",
"=",
"parsed",
"=",
"nil",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"try",
"<=",
"attempts",
"begin",
"result",
"=",
"@client",
".",
"execute",
"(",
"req",
")",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")",
"if",
"not",
"result",
".",
"success?",
"error_code",
"=",
"parsed",
"[",
"\"error\"",
"]",
"?",
"parsed",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
":",
"0",
"if",
"error_code",
"==",
"404",
"raise",
"GoogleComputeError",
",",
"\"Resource Not Found: #{result.body}\"",
"elsif",
"error_code",
"==",
"400",
"raise",
"GoogleComputeError",
",",
"\"Bad Request: #{result.body}\"",
"else",
"raise",
"GoogleComputeError",
",",
"\"Error attempting Google Compute API execute: #{result.body}\"",
"end",
"end",
"return",
"parsed",
"rescue",
"Faraday",
"::",
"Error",
"::",
"ConnectionFailed",
"=>",
"e",
"@logger",
".",
"debug",
"\"ConnectionFailed attempting Google Compute execute command\"",
"try",
"+=",
"1",
"last_error",
"=",
"e",
"end",
"end",
"raise",
"last_error",
"end"
] | Executes a provided Google Compute request using a previously configured
and authenticated Google Compute client connection
@param [Hash] req A correctly formatted Google Compute request object
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail to execute the request, either
through errors or running out of attempts | [
"Executes",
"a",
"provided",
"Google",
"Compute",
"request",
"using",
"a",
"previously",
"configured",
"and",
"authenticated",
"Google",
"Compute",
"client",
"connection"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L215-L242 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.list_firewalls | def list_firewalls(start, attempts)
result = execute( firewall_list_req(), start, attempts )
firewalls = result["items"]
firewalls.delete_if{|f| f['name'] =~ /default-allow-internal|default-ssh/}
firewalls
end | ruby | def list_firewalls(start, attempts)
result = execute( firewall_list_req(), start, attempts )
firewalls = result["items"]
firewalls.delete_if{|f| f['name'] =~ /default-allow-internal|default-ssh/}
firewalls
end | [
"def",
"list_firewalls",
"(",
"start",
",",
"attempts",
")",
"result",
"=",
"execute",
"(",
"firewall_list_req",
"(",
")",
",",
"start",
",",
"attempts",
")",
"firewalls",
"=",
"result",
"[",
"\"items\"",
"]",
"firewalls",
".",
"delete_if",
"{",
"|",
"f",
"|",
"f",
"[",
"'name'",
"]",
"=~",
"/",
"/",
"}",
"firewalls",
"end"
] | Determines a list of existing Google Compute firewalls
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@return [Array[Hash]] The firewalls array of hashes
@raise [Exception] Raised if we fail determine the list of existing
firewalls, either through errors or running out of attempts | [
"Determines",
"a",
"list",
"of",
"existing",
"Google",
"Compute",
"firewalls"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L363-L368 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.create_firewall | def create_firewall(name, network, start, attempts)
execute( firewall_insert_req( name, network['selfLink'] ), start, attempts )
end | ruby | def create_firewall(name, network, start, attempts)
execute( firewall_insert_req( name, network['selfLink'] ), start, attempts )
end | [
"def",
"create_firewall",
"(",
"name",
",",
"network",
",",
"start",
",",
"attempts",
")",
"execute",
"(",
"firewall_insert_req",
"(",
"name",
",",
"network",
"[",
"'selfLink'",
"]",
")",
",",
"start",
",",
"attempts",
")",
"end"
] | Create a Google Compute firewall on the current connection
@param [String] name The name of the firewall to create
@param [Hash] network The Google Compute network hash in which to create
the firewall
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail create the firewall, either through
errors or running out of attempts | [
"Create",
"a",
"Google",
"Compute",
"firewall",
"on",
"the",
"current",
"connection"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L386-L388 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.create_disk | def create_disk(name, img, start, attempts)
#create a new boot disk for this instance
disk = execute( disk_insert_req( name, img['selfLink'] ), start, attempts )
status = ''
try = (Time.now - start) / SLEEPWAIT
while status !~ /READY/ and try <= attempts
begin
disk = execute( disk_get_req( name ), start, attempts )
status = disk['status']
rescue GoogleComputeError => e
@logger.debug("Waiting for #{name} disk creation")
sleep(SLEEPWAIT)
end
try += 1
end
if status == ''
raise "Unable to create disk #{name}"
end
disk
end | ruby | def create_disk(name, img, start, attempts)
#create a new boot disk for this instance
disk = execute( disk_insert_req( name, img['selfLink'] ), start, attempts )
status = ''
try = (Time.now - start) / SLEEPWAIT
while status !~ /READY/ and try <= attempts
begin
disk = execute( disk_get_req( name ), start, attempts )
status = disk['status']
rescue GoogleComputeError => e
@logger.debug("Waiting for #{name} disk creation")
sleep(SLEEPWAIT)
end
try += 1
end
if status == ''
raise "Unable to create disk #{name}"
end
disk
end | [
"def",
"create_disk",
"(",
"name",
",",
"img",
",",
"start",
",",
"attempts",
")",
"disk",
"=",
"execute",
"(",
"disk_insert_req",
"(",
"name",
",",
"img",
"[",
"'selfLink'",
"]",
")",
",",
"start",
",",
"attempts",
")",
"status",
"=",
"''",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"status",
"!~",
"/",
"/",
"and",
"try",
"<=",
"attempts",
"begin",
"disk",
"=",
"execute",
"(",
"disk_get_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"status",
"=",
"disk",
"[",
"'status'",
"]",
"rescue",
"GoogleComputeError",
"=>",
"e",
"@logger",
".",
"debug",
"(",
"\"Waiting for #{name} disk creation\"",
")",
"sleep",
"(",
"SLEEPWAIT",
")",
"end",
"try",
"+=",
"1",
"end",
"if",
"status",
"==",
"''",
"raise",
"\"Unable to create disk #{name}\"",
"end",
"disk",
"end"
] | Create a Google Compute disk on the current connection
@param [String] name The name of the disk to create
@param [Hash] img The Google Compute image to use for instance creation
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail create the disk, either through
errors or running out of attempts | [
"Create",
"a",
"Google",
"Compute",
"disk",
"on",
"the",
"current",
"connection"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L405-L425 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.create_instance | def create_instance(name, img, machineType, disk, start, attempts)
#add a new instance of the image
instance = execute( instance_insert_req( name, img['selfLink'], machineType['selfLink'], disk['selfLink'] ), start, attempts)
status = ''
try = (Time.now - start) / SLEEPWAIT
while status !~ /RUNNING/ and try <= attempts
begin
instance = execute( instance_get_req( name ), start, attempts )
status = instance['status']
rescue GoogleComputeError => e
@logger.debug("Waiting for #{name} instance creation")
sleep(SLEEPWAIT)
end
try += 1
end
if status == ''
raise "Unable to create instance #{name}"
end
instance
end | ruby | def create_instance(name, img, machineType, disk, start, attempts)
#add a new instance of the image
instance = execute( instance_insert_req( name, img['selfLink'], machineType['selfLink'], disk['selfLink'] ), start, attempts)
status = ''
try = (Time.now - start) / SLEEPWAIT
while status !~ /RUNNING/ and try <= attempts
begin
instance = execute( instance_get_req( name ), start, attempts )
status = instance['status']
rescue GoogleComputeError => e
@logger.debug("Waiting for #{name} instance creation")
sleep(SLEEPWAIT)
end
try += 1
end
if status == ''
raise "Unable to create instance #{name}"
end
instance
end | [
"def",
"create_instance",
"(",
"name",
",",
"img",
",",
"machineType",
",",
"disk",
",",
"start",
",",
"attempts",
")",
"instance",
"=",
"execute",
"(",
"instance_insert_req",
"(",
"name",
",",
"img",
"[",
"'selfLink'",
"]",
",",
"machineType",
"[",
"'selfLink'",
"]",
",",
"disk",
"[",
"'selfLink'",
"]",
")",
",",
"start",
",",
"attempts",
")",
"status",
"=",
"''",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"status",
"!~",
"/",
"/",
"and",
"try",
"<=",
"attempts",
"begin",
"instance",
"=",
"execute",
"(",
"instance_get_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"status",
"=",
"instance",
"[",
"'status'",
"]",
"rescue",
"GoogleComputeError",
"=>",
"e",
"@logger",
".",
"debug",
"(",
"\"Waiting for #{name} instance creation\"",
")",
"sleep",
"(",
"SLEEPWAIT",
")",
"end",
"try",
"+=",
"1",
"end",
"if",
"status",
"==",
"''",
"raise",
"\"Unable to create instance #{name}\"",
"end",
"instance",
"end"
] | Create a Google Compute instance on the current connection
@param [String] name The name of the instance to create
@param [Hash] img The Google Compute image to use for instance creation
@param [Hash] machineType The Google Compute machineType
@param [Hash] disk The Google Compute disk to attach to the newly created
instance
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail create the instance, either through
errors or running out of attempts | [
"Create",
"a",
"Google",
"Compute",
"instance",
"on",
"the",
"current",
"connection"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L447-L466 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.delete_instance | def delete_instance(name, start, attempts)
result = execute( instance_delete_req( name ), start, attempts )
# Ensure deletion of instance
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
result = execute( instance_get_req( name ), start, attempts )
@logger.debug("Waiting for #{name} instance deletion")
sleep(SLEEPWAIT)
rescue GoogleComputeError => e
@logger.debug("#{name} instance deleted!")
return
end
try += 1
end
@logger.debug("#{name} instance was not removed before timeout, may still exist")
end | ruby | def delete_instance(name, start, attempts)
result = execute( instance_delete_req( name ), start, attempts )
# Ensure deletion of instance
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
result = execute( instance_get_req( name ), start, attempts )
@logger.debug("Waiting for #{name} instance deletion")
sleep(SLEEPWAIT)
rescue GoogleComputeError => e
@logger.debug("#{name} instance deleted!")
return
end
try += 1
end
@logger.debug("#{name} instance was not removed before timeout, may still exist")
end | [
"def",
"delete_instance",
"(",
"name",
",",
"start",
",",
"attempts",
")",
"result",
"=",
"execute",
"(",
"instance_delete_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"try",
"<=",
"attempts",
"begin",
"result",
"=",
"execute",
"(",
"instance_get_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"@logger",
".",
"debug",
"(",
"\"Waiting for #{name} instance deletion\"",
")",
"sleep",
"(",
"SLEEPWAIT",
")",
"rescue",
"GoogleComputeError",
"=>",
"e",
"@logger",
".",
"debug",
"(",
"\"#{name} instance deleted!\"",
")",
"return",
"end",
"try",
"+=",
"1",
"end",
"@logger",
".",
"debug",
"(",
"\"#{name} instance was not removed before timeout, may still exist\"",
")",
"end"
] | Delete a Google Compute instance on the current connection
@param [String] name The name of the instance to delete
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail delete the instance, either through
errors or running out of attempts | [
"Delete",
"a",
"Google",
"Compute",
"instance",
"on",
"the",
"current",
"connection"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L521-L538 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.delete_disk | def delete_disk(name, start, attempts)
result = execute( disk_delete_req( name ), start, attempts )
# Ensure deletion of disk
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
disk = execute( disk_get_req( name ), start, attempts )
@logger.debug("Waiting for #{name} disk deletion")
sleep(SLEEPWAIT)
rescue GoogleComputeError => e
@logger.debug("#{name} disk deleted!")
return
end
try += 1
end
@logger.debug("#{name} disk was not removed before timeout, may still exist")
end | ruby | def delete_disk(name, start, attempts)
result = execute( disk_delete_req( name ), start, attempts )
# Ensure deletion of disk
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
disk = execute( disk_get_req( name ), start, attempts )
@logger.debug("Waiting for #{name} disk deletion")
sleep(SLEEPWAIT)
rescue GoogleComputeError => e
@logger.debug("#{name} disk deleted!")
return
end
try += 1
end
@logger.debug("#{name} disk was not removed before timeout, may still exist")
end | [
"def",
"delete_disk",
"(",
"name",
",",
"start",
",",
"attempts",
")",
"result",
"=",
"execute",
"(",
"disk_delete_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"try",
"<=",
"attempts",
"begin",
"disk",
"=",
"execute",
"(",
"disk_get_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"@logger",
".",
"debug",
"(",
"\"Waiting for #{name} disk deletion\"",
")",
"sleep",
"(",
"SLEEPWAIT",
")",
"rescue",
"GoogleComputeError",
"=>",
"e",
"@logger",
".",
"debug",
"(",
"\"#{name} disk deleted!\"",
")",
"return",
"end",
"try",
"+=",
"1",
"end",
"@logger",
".",
"debug",
"(",
"\"#{name} disk was not removed before timeout, may still exist\"",
")",
"end"
] | Delete a Google Compute disk on the current connection
@param [String] name The name of the disk to delete
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail delete the disk, either through
errors or running out of attempts | [
"Delete",
"a",
"Google",
"Compute",
"disk",
"on",
"the",
"current",
"connection"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L553-L570 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.delete_firewall | def delete_firewall(name, start, attempts)
result = execute( firewall_delete_req( name ), start, attempts )
#ensure deletion of disk
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
firewall = execute( firewall_get_req( name ), start, attempts )
@logger.debug("Waiting for #{name} firewall deletion")
sleep(SLEEPWAIT)
rescue GoogleComputeError => e
@logger.debug("#{name} firewall deleted!")
return
end
try += 1
end
@logger.debug("#{name} firewall was not removed before timeout, may still exist")
end | ruby | def delete_firewall(name, start, attempts)
result = execute( firewall_delete_req( name ), start, attempts )
#ensure deletion of disk
try = (Time.now - start) / SLEEPWAIT
while try <= attempts
begin
firewall = execute( firewall_get_req( name ), start, attempts )
@logger.debug("Waiting for #{name} firewall deletion")
sleep(SLEEPWAIT)
rescue GoogleComputeError => e
@logger.debug("#{name} firewall deleted!")
return
end
try += 1
end
@logger.debug("#{name} firewall was not removed before timeout, may still exist")
end | [
"def",
"delete_firewall",
"(",
"name",
",",
"start",
",",
"attempts",
")",
"result",
"=",
"execute",
"(",
"firewall_delete_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"try",
"=",
"(",
"Time",
".",
"now",
"-",
"start",
")",
"/",
"SLEEPWAIT",
"while",
"try",
"<=",
"attempts",
"begin",
"firewall",
"=",
"execute",
"(",
"firewall_get_req",
"(",
"name",
")",
",",
"start",
",",
"attempts",
")",
"@logger",
".",
"debug",
"(",
"\"Waiting for #{name} firewall deletion\"",
")",
"sleep",
"(",
"SLEEPWAIT",
")",
"rescue",
"GoogleComputeError",
"=>",
"e",
"@logger",
".",
"debug",
"(",
"\"#{name} firewall deleted!\"",
")",
"return",
"end",
"try",
"+=",
"1",
"end",
"@logger",
".",
"debug",
"(",
"\"#{name} firewall was not removed before timeout, may still exist\"",
")",
"end"
] | Delete a Google Compute firewall on the current connection
@param [String] name The name of the firewall to delete
@param [Integer] start The time when we started code execution, it is
compared to Time.now to determine how many further code execution
attempts remain
@param [Integer] attempts The total amount of attempts to execute that we
are willing to allow
@raise [Exception] Raised if we fail delete the firewall, either through
errors or running out of attempts | [
"Delete",
"a",
"Google",
"Compute",
"firewall",
"on",
"the",
"current",
"connection"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L585-L601 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.instance_setMetadata_req | def instance_setMetadata_req(name, fingerprint, data)
{ :api_method => @compute.instances.set_metadata,
:parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME, 'instance' => name },
:body_object => { 'kind' => 'compute#metadata',
'fingerprint' => fingerprint,
'items' => data }
}
end | ruby | def instance_setMetadata_req(name, fingerprint, data)
{ :api_method => @compute.instances.set_metadata,
:parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME, 'instance' => name },
:body_object => { 'kind' => 'compute#metadata',
'fingerprint' => fingerprint,
'items' => data }
}
end | [
"def",
"instance_setMetadata_req",
"(",
"name",
",",
"fingerprint",
",",
"data",
")",
"{",
":api_method",
"=>",
"@compute",
".",
"instances",
".",
"set_metadata",
",",
":parameters",
"=>",
"{",
"'project'",
"=>",
"@options",
"[",
":gce_project",
"]",
",",
"'zone'",
"=>",
"DEFAULT_ZONE_NAME",
",",
"'instance'",
"=>",
"name",
"}",
",",
":body_object",
"=>",
"{",
"'kind'",
"=>",
"'compute#metadata'",
",",
"'fingerprint'",
"=>",
"fingerprint",
",",
"'items'",
"=>",
"data",
"}",
"}",
"end"
] | Set tags on a Google Compute instance
@param [Array<String>] data An array of tags to be added to an instance
@return [Hash] A correctly formatted Google Compute request hash | [
"Set",
"tags",
"on",
"a",
"Google",
"Compute",
"instance"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L726-L733 | train |
puppetlabs/beaker-google | lib/beaker/hypervisor/google_compute_helper.rb | Beaker.GoogleComputeHelper.instance_insert_req | def instance_insert_req(name, image, machineType, disk)
{ :api_method => @compute.instances.insert,
:parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME },
:body_object => { 'name' => name,
'image' => image,
'zone' => default_zone,
'machineType' => machineType,
'disks' => [ { 'source' => disk,
'type' => 'PERSISTENT', 'boot' => 'true'} ],
'networkInterfaces' => [ { 'accessConfigs' => [{ 'type' => 'ONE_TO_ONE_NAT', 'name' => 'External NAT' }],
'network' => default_network } ] } }
end | ruby | def instance_insert_req(name, image, machineType, disk)
{ :api_method => @compute.instances.insert,
:parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME },
:body_object => { 'name' => name,
'image' => image,
'zone' => default_zone,
'machineType' => machineType,
'disks' => [ { 'source' => disk,
'type' => 'PERSISTENT', 'boot' => 'true'} ],
'networkInterfaces' => [ { 'accessConfigs' => [{ 'type' => 'ONE_TO_ONE_NAT', 'name' => 'External NAT' }],
'network' => default_network } ] } }
end | [
"def",
"instance_insert_req",
"(",
"name",
",",
"image",
",",
"machineType",
",",
"disk",
")",
"{",
":api_method",
"=>",
"@compute",
".",
"instances",
".",
"insert",
",",
":parameters",
"=>",
"{",
"'project'",
"=>",
"@options",
"[",
":gce_project",
"]",
",",
"'zone'",
"=>",
"DEFAULT_ZONE_NAME",
"}",
",",
":body_object",
"=>",
"{",
"'name'",
"=>",
"name",
",",
"'image'",
"=>",
"image",
",",
"'zone'",
"=>",
"default_zone",
",",
"'machineType'",
"=>",
"machineType",
",",
"'disks'",
"=>",
"[",
"{",
"'source'",
"=>",
"disk",
",",
"'type'",
"=>",
"'PERSISTENT'",
",",
"'boot'",
"=>",
"'true'",
"}",
"]",
",",
"'networkInterfaces'",
"=>",
"[",
"{",
"'accessConfigs'",
"=>",
"[",
"{",
"'type'",
"=>",
"'ONE_TO_ONE_NAT'",
",",
"'name'",
"=>",
"'External NAT'",
"}",
"]",
",",
"'network'",
"=>",
"default_network",
"}",
"]",
"}",
"}",
"end"
] | Create a Google Compute instance create request
@param [String] name The name of the instance to create
@param [String] image The link to the image to use for instance create
@param [String] machineType The link to the type of Google Compute
instance to create (indicates cpus and memory size)
@param [String] disk The link to the disk to be used by the newly created
instance
@return [Hash] A correctly formatted Google Compute request hash | [
"Create",
"a",
"Google",
"Compute",
"instance",
"create",
"request"
] | 3d7927f718447547293559d4631e26fcbdbf78e3 | https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L776-L787 | train |
schneems/let_it_go | lib/let_it_go/method_call.rb | LetItGo.MethodCall.method_array | def method_array
@parser = nil
@caller_lines.each do |kaller|
code = Ripper.sexp(kaller.contents)
code ||= Ripper.sexp(kaller.contents.sub(/^\W*(if|unless)/, ''.freeze)) # if and unless "block" statements aren't valid one line ruby code
code ||= Ripper.sexp(kaller.contents.sub(/do \|.*\|$/, ''.freeze)) # remove trailing do |thing| to make valid code
code ||= Ripper.sexp(kaller.contents.sub(/(and|or)\W*$/, ''.freeze))# trailing and || or
code ||= Ripper.sexp(kaller.contents.sub(/:\W*$/, ''.freeze)) # multi line ternary statements
code ||= Ripper.sexp(kaller.contents.sub(/(^\W*)|({ \|?.*\|?)}/, ''.freeze)) # multi line blocks using {}
puts "LetItGoFailed parse (#{kaller.file_name}:#{kaller.line_number}: \n \033[0;31m"+ kaller.contents.strip + "\e[0m".freeze if ENV['LET_IT_GO_RECORD_FAILED_CODE'] && code.nil? && kaller.contents.match(/"|'/)
parser = ::LetItGo::WTFParser.new(code, contents: kaller.contents)
if parser.each_method.any? { |m| m.method_name == method_name }
@line_number = kaller.line_number
@file_name = kaller.file_name
@parser = parser
parser.each_method.each(&:arg_types)
break
else
next
end
end
@parser || []
end | ruby | def method_array
@parser = nil
@caller_lines.each do |kaller|
code = Ripper.sexp(kaller.contents)
code ||= Ripper.sexp(kaller.contents.sub(/^\W*(if|unless)/, ''.freeze)) # if and unless "block" statements aren't valid one line ruby code
code ||= Ripper.sexp(kaller.contents.sub(/do \|.*\|$/, ''.freeze)) # remove trailing do |thing| to make valid code
code ||= Ripper.sexp(kaller.contents.sub(/(and|or)\W*$/, ''.freeze))# trailing and || or
code ||= Ripper.sexp(kaller.contents.sub(/:\W*$/, ''.freeze)) # multi line ternary statements
code ||= Ripper.sexp(kaller.contents.sub(/(^\W*)|({ \|?.*\|?)}/, ''.freeze)) # multi line blocks using {}
puts "LetItGoFailed parse (#{kaller.file_name}:#{kaller.line_number}: \n \033[0;31m"+ kaller.contents.strip + "\e[0m".freeze if ENV['LET_IT_GO_RECORD_FAILED_CODE'] && code.nil? && kaller.contents.match(/"|'/)
parser = ::LetItGo::WTFParser.new(code, contents: kaller.contents)
if parser.each_method.any? { |m| m.method_name == method_name }
@line_number = kaller.line_number
@file_name = kaller.file_name
@parser = parser
parser.each_method.each(&:arg_types)
break
else
next
end
end
@parser || []
end | [
"def",
"method_array",
"@parser",
"=",
"nil",
"@caller_lines",
".",
"each",
"do",
"|",
"kaller",
"|",
"code",
"=",
"Ripper",
".",
"sexp",
"(",
"kaller",
".",
"contents",
")",
"code",
"||=",
"Ripper",
".",
"sexp",
"(",
"kaller",
".",
"contents",
".",
"sub",
"(",
"/",
"\\W",
"/",
",",
"''",
".",
"freeze",
")",
")",
"code",
"||=",
"Ripper",
".",
"sexp",
"(",
"kaller",
".",
"contents",
".",
"sub",
"(",
"/",
"\\|",
"\\|",
"/",
",",
"''",
".",
"freeze",
")",
")",
"code",
"||=",
"Ripper",
".",
"sexp",
"(",
"kaller",
".",
"contents",
".",
"sub",
"(",
"/",
"\\W",
"/",
",",
"''",
".",
"freeze",
")",
")",
"code",
"||=",
"Ripper",
".",
"sexp",
"(",
"kaller",
".",
"contents",
".",
"sub",
"(",
"/",
"\\W",
"/",
",",
"''",
".",
"freeze",
")",
")",
"code",
"||=",
"Ripper",
".",
"sexp",
"(",
"kaller",
".",
"contents",
".",
"sub",
"(",
"/",
"\\W",
"\\|",
"\\|",
"/",
",",
"''",
".",
"freeze",
")",
")",
"puts",
"\"LetItGoFailed parse (#{kaller.file_name}:#{kaller.line_number}: \\n \\033[0;31m\"",
"+",
"kaller",
".",
"contents",
".",
"strip",
"+",
"\"\\e[0m\"",
".",
"freeze",
"if",
"ENV",
"[",
"'LET_IT_GO_RECORD_FAILED_CODE'",
"]",
"&&",
"code",
".",
"nil?",
"&&",
"kaller",
".",
"contents",
".",
"match",
"(",
"/",
"/",
")",
"parser",
"=",
"::",
"LetItGo",
"::",
"WTFParser",
".",
"new",
"(",
"code",
",",
"contents",
":",
"kaller",
".",
"contents",
")",
"if",
"parser",
".",
"each_method",
".",
"any?",
"{",
"|",
"m",
"|",
"m",
".",
"method_name",
"==",
"method_name",
"}",
"@line_number",
"=",
"kaller",
".",
"line_number",
"@file_name",
"=",
"kaller",
".",
"file_name",
"@parser",
"=",
"parser",
"parser",
".",
"each_method",
".",
"each",
"(",
"&",
":arg_types",
")",
"break",
"else",
"next",
"end",
"end",
"@parser",
"||",
"[",
"]",
"end"
] | Loop through each line in the caller and see if the method we're watching is being called
This is needed due to the way TracePoint deals with inheritance | [
"Loop",
"through",
"each",
"line",
"in",
"the",
"caller",
"and",
"see",
"if",
"the",
"method",
"we",
"re",
"watching",
"is",
"being",
"called",
"This",
"is",
"needed",
"due",
"to",
"the",
"way",
"TracePoint",
"deals",
"with",
"inheritance"
] | 13557936b35b59d6b222287fd08d5421ce488f10 | https://github.com/schneems/let_it_go/blob/13557936b35b59d6b222287fd08d5421ce488f10/lib/let_it_go/method_call.rb#L30-L56 | train |
schneems/let_it_go | lib/let_it_go/method_call.rb | LetItGo.MethodCall.called_with_string_literal? | def called_with_string_literal?
@string_allocation_count = 0
method_array.each do |m|
positions.each {|position| @string_allocation_count += 1 if m.arg_types[position] == :string_literal }
end
!@string_allocation_count.zero?
end | ruby | def called_with_string_literal?
@string_allocation_count = 0
method_array.each do |m|
positions.each {|position| @string_allocation_count += 1 if m.arg_types[position] == :string_literal }
end
!@string_allocation_count.zero?
end | [
"def",
"called_with_string_literal?",
"@string_allocation_count",
"=",
"0",
"method_array",
".",
"each",
"do",
"|",
"m",
"|",
"positions",
".",
"each",
"{",
"|",
"position",
"|",
"@string_allocation_count",
"+=",
"1",
"if",
"m",
".",
"arg_types",
"[",
"position",
"]",
"==",
":string_literal",
"}",
"end",
"!",
"@string_allocation_count",
".",
"zero?",
"end"
] | Parses original method call location
Determines if a string literal was used or not | [
"Parses",
"original",
"method",
"call",
"location",
"Determines",
"if",
"a",
"string",
"literal",
"was",
"used",
"or",
"not"
] | 13557936b35b59d6b222287fd08d5421ce488f10 | https://github.com/schneems/let_it_go/blob/13557936b35b59d6b222287fd08d5421ce488f10/lib/let_it_go/method_call.rb#L72-L78 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.refine | def refine(data)
@task ||= ''
data = parse_data(data)
return puts data if data.is_a?(String)
evaluate_severities(data)
puts summarize
if @config.is_dev?
puts dev_format(data)
ceiling_warning
else
# Because this should be returned in the format it was received
@output[:raw_data] = data.to_json
end
@output
end | ruby | def refine(data)
@task ||= ''
data = parse_data(data)
return puts data if data.is_a?(String)
evaluate_severities(data)
puts summarize
if @config.is_dev?
puts dev_format(data)
ceiling_warning
else
# Because this should be returned in the format it was received
@output[:raw_data] = data.to_json
end
@output
end | [
"def",
"refine",
"(",
"data",
")",
"@task",
"||=",
"''",
"data",
"=",
"parse_data",
"(",
"data",
")",
"return",
"puts",
"data",
"if",
"data",
".",
"is_a?",
"(",
"String",
")",
"evaluate_severities",
"(",
"data",
")",
"puts",
"summarize",
"if",
"@config",
".",
"is_dev?",
"puts",
"dev_format",
"(",
"data",
")",
"ceiling_warning",
"else",
"@output",
"[",
":raw_data",
"]",
"=",
"data",
".",
"to_json",
"end",
"@output",
"end"
] | Perform a lint of relevant code
All defined lints require a "result" method
@example the result method in the child class
def result
@task = __method__.to_s
@path ||= 'path/or/**/glob/to/files''
lint_data = JSON.parse(`some-command-line-linter`)
@output[:files_inspected] ||= files_inspected(extension, delimiter, base_path_replacement)
refine data_from_output
end
Inherits settings from {Config#initialize}
@see Config#initialize
@param opts [Hash] ({}) options passed directly to the lint
@option opts [Hash] :git_files filename: file location
@see GitControl#lints_and_stats
@option opts [Array, String] :file_paths lint only specific files or directories
Accepts globs too
which is used to define paths from the URL
@option opts [Config object] :config custom Maximus::Config object
@return [void] this method is used to set up instance variables
Convert raw data into warnings, errors, conventions or refactors. Use this wisely.
@param data [Hash] unfiltered lint data
@return [Hash] refined lint data and all the other bells and whistles | [
"Perform",
"a",
"lint",
"of",
"relevant",
"code"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L51-L69 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.files_inspected | def files_inspected(ext, delimiter = ',', remove = @config.working_dir)
@path.is_a?(Array) ? @path.split(delimiter) : file_list(@path, ext, remove)
end | ruby | def files_inspected(ext, delimiter = ',', remove = @config.working_dir)
@path.is_a?(Array) ? @path.split(delimiter) : file_list(@path, ext, remove)
end | [
"def",
"files_inspected",
"(",
"ext",
",",
"delimiter",
"=",
"','",
",",
"remove",
"=",
"@config",
".",
"working_dir",
")",
"@path",
".",
"is_a?",
"(",
"Array",
")",
"?",
"@path",
".",
"split",
"(",
"delimiter",
")",
":",
"file_list",
"(",
"@path",
",",
"ext",
",",
"remove",
")",
"end"
] | List all files inspected
@param ext [String] extension to search for
@param delimiter [String] comma or space separated
@param remove [String] remove from all file names
@return all_files [Array<string>] list of file names | [
"List",
"all",
"files",
"inspected"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L79-L81 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.relevant_output | def relevant_output(lint, files)
all_files = {}
files.each do |file|
# sometimes data will be blank but this is good - it means no errors were raised in the lint
next if lint.blank? || file.blank? || !file.is_a?(Hash) || !file.key?(:filename)
lint_file = lint[file[:filename]]
next if lint_file.blank?
expanded = lines_added_to_range(file)
revert_name = strip_working_dir(file[:filename])
all_files[revert_name] = []
lint_file.each do |l|
if expanded.include?(l['line'].to_i)
all_files[revert_name] << l
end
end
# If there's nothing there, then it definitely isn't a relevant lint
all_files.delete(revert_name) if all_files[revert_name].blank?
end
@output[:files_linted] = all_files.keys
all_files
end | ruby | def relevant_output(lint, files)
all_files = {}
files.each do |file|
# sometimes data will be blank but this is good - it means no errors were raised in the lint
next if lint.blank? || file.blank? || !file.is_a?(Hash) || !file.key?(:filename)
lint_file = lint[file[:filename]]
next if lint_file.blank?
expanded = lines_added_to_range(file)
revert_name = strip_working_dir(file[:filename])
all_files[revert_name] = []
lint_file.each do |l|
if expanded.include?(l['line'].to_i)
all_files[revert_name] << l
end
end
# If there's nothing there, then it definitely isn't a relevant lint
all_files.delete(revert_name) if all_files[revert_name].blank?
end
@output[:files_linted] = all_files.keys
all_files
end | [
"def",
"relevant_output",
"(",
"lint",
",",
"files",
")",
"all_files",
"=",
"{",
"}",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"next",
"if",
"lint",
".",
"blank?",
"||",
"file",
".",
"blank?",
"||",
"!",
"file",
".",
"is_a?",
"(",
"Hash",
")",
"||",
"!",
"file",
".",
"key?",
"(",
":filename",
")",
"lint_file",
"=",
"lint",
"[",
"file",
"[",
":filename",
"]",
"]",
"next",
"if",
"lint_file",
".",
"blank?",
"expanded",
"=",
"lines_added_to_range",
"(",
"file",
")",
"revert_name",
"=",
"strip_working_dir",
"(",
"file",
"[",
":filename",
"]",
")",
"all_files",
"[",
"revert_name",
"]",
"=",
"[",
"]",
"lint_file",
".",
"each",
"do",
"|",
"l",
"|",
"if",
"expanded",
".",
"include?",
"(",
"l",
"[",
"'line'",
"]",
".",
"to_i",
")",
"all_files",
"[",
"revert_name",
"]",
"<<",
"l",
"end",
"end",
"all_files",
".",
"delete",
"(",
"revert_name",
")",
"if",
"all_files",
"[",
"revert_name",
"]",
".",
"blank?",
"end",
"@output",
"[",
":files_linted",
"]",
"=",
"all_files",
".",
"keys",
"all_files",
"end"
] | Compare lint output with lines changed in commit
@param lint [Hash] output lint data
@param files [Hash<String: String>] filename: filepath
@return [Array] lints that match the lines in commit | [
"Compare",
"lint",
"output",
"with",
"lines",
"changed",
"in",
"commit"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L87-L113 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.evaluate_severities | def evaluate_severities(data)
@output[:lint_warnings] = []
@output[:lint_errors] = []
@output[:lint_conventions] = []
@output[:lint_refactors] = []
@output[:lint_fatals] = []
return if data.blank?
data.each do |filename, error_list|
error_list.each do |message|
# so that :raw_data remains unaffected
message = message.clone
message.delete('length')
message['filename'] = filename.nil? ? '' : strip_working_dir(filename)
severity = "lint_#{message['severity']}s".to_sym
message.delete('severity')
@output[severity] << message if @output.key?(severity)
end
end
@output
end | ruby | def evaluate_severities(data)
@output[:lint_warnings] = []
@output[:lint_errors] = []
@output[:lint_conventions] = []
@output[:lint_refactors] = []
@output[:lint_fatals] = []
return if data.blank?
data.each do |filename, error_list|
error_list.each do |message|
# so that :raw_data remains unaffected
message = message.clone
message.delete('length')
message['filename'] = filename.nil? ? '' : strip_working_dir(filename)
severity = "lint_#{message['severity']}s".to_sym
message.delete('severity')
@output[severity] << message if @output.key?(severity)
end
end
@output
end | [
"def",
"evaluate_severities",
"(",
"data",
")",
"@output",
"[",
":lint_warnings",
"]",
"=",
"[",
"]",
"@output",
"[",
":lint_errors",
"]",
"=",
"[",
"]",
"@output",
"[",
":lint_conventions",
"]",
"=",
"[",
"]",
"@output",
"[",
":lint_refactors",
"]",
"=",
"[",
"]",
"@output",
"[",
":lint_fatals",
"]",
"=",
"[",
"]",
"return",
"if",
"data",
".",
"blank?",
"data",
".",
"each",
"do",
"|",
"filename",
",",
"error_list",
"|",
"error_list",
".",
"each",
"do",
"|",
"message",
"|",
"message",
"=",
"message",
".",
"clone",
"message",
".",
"delete",
"(",
"'length'",
")",
"message",
"[",
"'filename'",
"]",
"=",
"filename",
".",
"nil?",
"?",
"''",
":",
"strip_working_dir",
"(",
"filename",
")",
"severity",
"=",
"\"lint_#{message['severity']}s\"",
".",
"to_sym",
"message",
".",
"delete",
"(",
"'severity'",
")",
"@output",
"[",
"severity",
"]",
"<<",
"message",
"if",
"@output",
".",
"key?",
"(",
"severity",
")",
"end",
"end",
"@output",
"end"
] | Add severities to @output
@since 0.1.5
@param data [Hash] | [
"Add",
"severities",
"to"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L127-L148 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.summarize | def summarize
success = @task.color(:green)
success << ": "
success << "[#{@output[:lint_warnings].length}]".color(:yellow)
success << " [#{@output[:lint_errors].length}]".color(:red)
if @task == 'rubocop'
success << " [#{@output[:lint_conventions].length}]".color(:cyan)
success << " [#{@output[:lint_refactors].length}]".color(:white)
success << " [#{@output[:lint_fatals].length}]".color(:magenta)
end
success << "\n#{'Warning'.color(:red)}: #{@output[:lint_errors].length} errors found in #{@task}" if @output[:lint_errors].length > 0
success
end | ruby | def summarize
success = @task.color(:green)
success << ": "
success << "[#{@output[:lint_warnings].length}]".color(:yellow)
success << " [#{@output[:lint_errors].length}]".color(:red)
if @task == 'rubocop'
success << " [#{@output[:lint_conventions].length}]".color(:cyan)
success << " [#{@output[:lint_refactors].length}]".color(:white)
success << " [#{@output[:lint_fatals].length}]".color(:magenta)
end
success << "\n#{'Warning'.color(:red)}: #{@output[:lint_errors].length} errors found in #{@task}" if @output[:lint_errors].length > 0
success
end | [
"def",
"summarize",
"success",
"=",
"@task",
".",
"color",
"(",
":green",
")",
"success",
"<<",
"\": \"",
"success",
"<<",
"\"[#{@output[:lint_warnings].length}]\"",
".",
"color",
"(",
":yellow",
")",
"success",
"<<",
"\" [#{@output[:lint_errors].length}]\"",
".",
"color",
"(",
":red",
")",
"if",
"@task",
"==",
"'rubocop'",
"success",
"<<",
"\" [#{@output[:lint_conventions].length}]\"",
".",
"color",
"(",
":cyan",
")",
"success",
"<<",
"\" [#{@output[:lint_refactors].length}]\"",
".",
"color",
"(",
":white",
")",
"success",
"<<",
"\" [#{@output[:lint_fatals].length}]\"",
".",
"color",
"(",
":magenta",
")",
"end",
"success",
"<<",
"\"\\n#{'Warning'.color(:red)}: #{@output[:lint_errors].length} errors found in #{@task}\"",
"if",
"@output",
"[",
":lint_errors",
"]",
".",
"length",
">",
"0",
"success",
"end"
] | Send abbreviated results to console or to the log
@return [String] console message to display | [
"Send",
"abbreviated",
"results",
"to",
"console",
"or",
"to",
"the",
"log"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L172-L185 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.ceiling_warning | def ceiling_warning
lint_length = (@output[:lint_errors].length + @output[:lint_warnings].length + @output[:lint_conventions].length + @output[:lint_refactors].length + @output[:lint_fatals].length)
return unless lint_length > 100
failed_task = @task.color(:green)
errors = "#{lint_length} failures.".color(:red)
errormsg = [
"You wouldn't stand a chance in Rome.\nResolve thy errors and train with #{failed_task} again.",
"The gods frown upon you, mortal.\n#{failed_task}. Again.",
"Do not embarrass the city. Fight another day. Use #{failed_task}.",
"You are without honor. Replenish it with another #{failed_task}.",
"You will never claim the throne with a performance like that.",
"Pompeii has been lost.",
"A wise choice. Do not be discouraged from another #{failed_task}."
].sample
errormsg << "\n\n"
go_on = prompt "\n#{errors} Continue? (y/n) "
abort errormsg unless truthy?(go_on)
end | ruby | def ceiling_warning
lint_length = (@output[:lint_errors].length + @output[:lint_warnings].length + @output[:lint_conventions].length + @output[:lint_refactors].length + @output[:lint_fatals].length)
return unless lint_length > 100
failed_task = @task.color(:green)
errors = "#{lint_length} failures.".color(:red)
errormsg = [
"You wouldn't stand a chance in Rome.\nResolve thy errors and train with #{failed_task} again.",
"The gods frown upon you, mortal.\n#{failed_task}. Again.",
"Do not embarrass the city. Fight another day. Use #{failed_task}.",
"You are without honor. Replenish it with another #{failed_task}.",
"You will never claim the throne with a performance like that.",
"Pompeii has been lost.",
"A wise choice. Do not be discouraged from another #{failed_task}."
].sample
errormsg << "\n\n"
go_on = prompt "\n#{errors} Continue? (y/n) "
abort errormsg unless truthy?(go_on)
end | [
"def",
"ceiling_warning",
"lint_length",
"=",
"(",
"@output",
"[",
":lint_errors",
"]",
".",
"length",
"+",
"@output",
"[",
":lint_warnings",
"]",
".",
"length",
"+",
"@output",
"[",
":lint_conventions",
"]",
".",
"length",
"+",
"@output",
"[",
":lint_refactors",
"]",
".",
"length",
"+",
"@output",
"[",
":lint_fatals",
"]",
".",
"length",
")",
"return",
"unless",
"lint_length",
">",
"100",
"failed_task",
"=",
"@task",
".",
"color",
"(",
":green",
")",
"errors",
"=",
"\"#{lint_length} failures.\"",
".",
"color",
"(",
":red",
")",
"errormsg",
"=",
"[",
"\"You wouldn't stand a chance in Rome.\\nResolve thy errors and train with #{failed_task} again.\"",
",",
"\"The gods frown upon you, mortal.\\n#{failed_task}. Again.\"",
",",
"\"Do not embarrass the city. Fight another day. Use #{failed_task}.\"",
",",
"\"You are without honor. Replenish it with another #{failed_task}.\"",
",",
"\"You will never claim the throne with a performance like that.\"",
",",
"\"Pompeii has been lost.\"",
",",
"\"A wise choice. Do not be discouraged from another #{failed_task}.\"",
"]",
".",
"sample",
"errormsg",
"<<",
"\"\\n\\n\"",
"go_on",
"=",
"prompt",
"\"\\n#{errors} Continue? (y/n) \"",
"abort",
"errormsg",
"unless",
"truthy?",
"(",
"go_on",
")",
"end"
] | If there's just too much to handle, through a warning.
@param lint_length [Integer] count of how many lints
@return [String] console message to display | [
"If",
"there",
"s",
"just",
"too",
"much",
"to",
"handle",
"through",
"a",
"warning",
"."
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L190-L209 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.dev_format | def dev_format(errors = @output[:raw_data])
return if errors.blank?
pretty_output = ''
errors.each do |filename, error_list|
filename = strip_working_dir(filename)
pretty_output << "\n#{filename.color(:cyan).underline} \n"
error_list.each do |message|
pretty_output << severity_color(message['severity'])
pretty_output << " #{message['line'].to_s.color(:blue)} #{message['linter'].color(:green)}: #{message['reason']} \n"
end
end
pretty_output << "-----\n\n"
pretty_output
end | ruby | def dev_format(errors = @output[:raw_data])
return if errors.blank?
pretty_output = ''
errors.each do |filename, error_list|
filename = strip_working_dir(filename)
pretty_output << "\n#{filename.color(:cyan).underline} \n"
error_list.each do |message|
pretty_output << severity_color(message['severity'])
pretty_output << " #{message['line'].to_s.color(:blue)} #{message['linter'].color(:green)}: #{message['reason']} \n"
end
end
pretty_output << "-----\n\n"
pretty_output
end | [
"def",
"dev_format",
"(",
"errors",
"=",
"@output",
"[",
":raw_data",
"]",
")",
"return",
"if",
"errors",
".",
"blank?",
"pretty_output",
"=",
"''",
"errors",
".",
"each",
"do",
"|",
"filename",
",",
"error_list",
"|",
"filename",
"=",
"strip_working_dir",
"(",
"filename",
")",
"pretty_output",
"<<",
"\"\\n#{filename.color(:cyan).underline} \\n\"",
"error_list",
".",
"each",
"do",
"|",
"message",
"|",
"pretty_output",
"<<",
"severity_color",
"(",
"message",
"[",
"'severity'",
"]",
")",
"pretty_output",
"<<",
"\" #{message['line'].to_s.color(:blue)} #{message['linter'].color(:green)}: #{message['reason']} \\n\"",
"end",
"end",
"pretty_output",
"<<",
"\"-----\\n\\n\"",
"pretty_output",
"end"
] | Dev display, executed only when called from command line
@param errors [Hash] data from lint
@return [String] console message to display | [
"Dev",
"display",
"executed",
"only",
"when",
"called",
"from",
"command",
"line"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L214-L228 | train |
wearefine/maximus | lib/maximus/lint.rb | Maximus.Lint.parse_data | def parse_data(data)
# Prevent abortive empty JSON.parse error
data = '{}' if data.blank?
return "Error from #{@task}: #{data}" if data.is_a?(String) && data.include?('No such')
data = JSON.parse(data) if data.is_a?(String)
@output[:relevant_output] = relevant_output( data, @git_files ) unless @git_files.blank?
data = @output[:relevant_output] unless @settings[:commit].blank?
data
end | ruby | def parse_data(data)
# Prevent abortive empty JSON.parse error
data = '{}' if data.blank?
return "Error from #{@task}: #{data}" if data.is_a?(String) && data.include?('No such')
data = JSON.parse(data) if data.is_a?(String)
@output[:relevant_output] = relevant_output( data, @git_files ) unless @git_files.blank?
data = @output[:relevant_output] unless @settings[:commit].blank?
data
end | [
"def",
"parse_data",
"(",
"data",
")",
"data",
"=",
"'{}'",
"if",
"data",
".",
"blank?",
"return",
"\"Error from #{@task}: #{data}\"",
"if",
"data",
".",
"is_a?",
"(",
"String",
")",
"&&",
"data",
".",
"include?",
"(",
"'No such'",
")",
"data",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
"if",
"data",
".",
"is_a?",
"(",
"String",
")",
"@output",
"[",
":relevant_output",
"]",
"=",
"relevant_output",
"(",
"data",
",",
"@git_files",
")",
"unless",
"@git_files",
".",
"blank?",
"data",
"=",
"@output",
"[",
":relevant_output",
"]",
"unless",
"@settings",
"[",
":commit",
"]",
".",
"blank?",
"data",
"end"
] | Handle data and generate relevant_output if appropriate
@since 0.1.6
@see #refine
@param data [String, Hash]
@return [String, Hash] String if error, Hash if success | [
"Handle",
"data",
"and",
"generate",
"relevant_output",
"if",
"appropriate"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L243-L254 | train |
tevren/biffbot | lib/biffbot/bulk.rb | Biffbot.Bulk.generate_post_body | def generate_post_body name, api_url, urls = [], options = {}
post_body = {token: @token, name: name, apiUrl: api_url, urls: urls}
options.each do |key, value|
next unless %w(notifyEmail maxRounds notifyWebHook pageProcessPattern).include?(key.to_s)
post_body[key] = value
end
post_body
end | ruby | def generate_post_body name, api_url, urls = [], options = {}
post_body = {token: @token, name: name, apiUrl: api_url, urls: urls}
options.each do |key, value|
next unless %w(notifyEmail maxRounds notifyWebHook pageProcessPattern).include?(key.to_s)
post_body[key] = value
end
post_body
end | [
"def",
"generate_post_body",
"name",
",",
"api_url",
",",
"urls",
"=",
"[",
"]",
",",
"options",
"=",
"{",
"}",
"post_body",
"=",
"{",
"token",
":",
"@token",
",",
"name",
":",
"name",
",",
"apiUrl",
":",
"api_url",
",",
"urls",
":",
"urls",
"}",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"next",
"unless",
"%w(",
"notifyEmail",
"maxRounds",
"notifyWebHook",
"pageProcessPattern",
")",
".",
"include?",
"(",
"key",
".",
"to_s",
")",
"post_body",
"[",
"key",
"]",
"=",
"value",
"end",
"post_body",
"end"
] | generate the POST body required for bulk job creation
@param name [String] Desired name for bulk job
@param api_url [String] Desired API url to use for urls
@param urls [Array] An array of input urls to pass to bulk job
@param options [Hash] An hash of options
@return [Hash] | [
"generate",
"the",
"POST",
"body",
"required",
"for",
"bulk",
"job",
"creation"
] | bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3 | https://github.com/tevren/biffbot/blob/bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3/lib/biffbot/bulk.rb#L40-L47 | train |
tevren/biffbot | lib/biffbot/bulk.rb | Biffbot.Bulk.retrieve_data | def retrieve_data jobName, _options = {}
# TODO: add support for csv
endpoint = "http://api.diffbot.com/v3/bulk/download/#{@token}-#{jobName}_data.json"
JSON.parse(HTTParty.get(endpoint).body).each_pair do |key, value|
self[key] = value
end
end | ruby | def retrieve_data jobName, _options = {}
# TODO: add support for csv
endpoint = "http://api.diffbot.com/v3/bulk/download/#{@token}-#{jobName}_data.json"
JSON.parse(HTTParty.get(endpoint).body).each_pair do |key, value|
self[key] = value
end
end | [
"def",
"retrieve_data",
"jobName",
",",
"_options",
"=",
"{",
"}",
"endpoint",
"=",
"\"http://api.diffbot.com/v3/bulk/download/#{@token}-#{jobName}_data.json\"",
"JSON",
".",
"parse",
"(",
"HTTParty",
".",
"get",
"(",
"endpoint",
")",
".",
"body",
")",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"self",
"[",
"key",
"]",
"=",
"value",
"end",
"end"
] | retrieve data per given jobName
@param jobName [String] Name of bulk job
@param _options [Hash] An hash of options
@return [Hash] | [
"retrieve",
"data",
"per",
"given",
"jobName"
] | bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3 | https://github.com/tevren/biffbot/blob/bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3/lib/biffbot/bulk.rb#L71-L77 | train |
wearefine/maximus | lib/maximus/config.rb | Maximus.Config.evaluate_settings | def evaluate_settings(settings_data = @settings)
settings_data.each do |key, value|
next if value.is_a?(FalseClass)
value = {} if value.is_a?(TrueClass)
case key
when :jshint, :JSHint, :JShint
value = load_config(value)
jshint_ignore settings_data[key]
@settings[:jshint] = temp_it('jshint.json', value.to_json)
when :scsslint, :SCSSlint
value = load_config(value)
@settings[:scsslint] = temp_it('scsslint.yml', value.to_yaml)
when :rubocop, :Rubocop, :RuboCop
value = load_config(value)
@settings[:rubocop] = temp_it('rubocop.yml', value.to_yaml)
when :brakeman
@settings[:brakeman] = settings_data[key]
when :rails_best_practice, :railsbp
@settings[:railsbp] = settings_data[key]
when :stylestats, :Stylestats
value = load_config(value)
@settings[:stylestats] = temp_it('stylestats.json', value.to_json)
when :phantomas, :Phantomas
value = load_config(value)
@settings[:phantomas] = temp_it('phantomas.json', value.to_json)
when :wraith, :Wraith
value = load_config(value)
evaluate_for_wraith(value)
# Configuration important to all of maximus
when :is_dev, :log, :root_dir, :domain, :port, :paths, :commit
@settings[key] = settings_data[key]
end
end
@settings
end | ruby | def evaluate_settings(settings_data = @settings)
settings_data.each do |key, value|
next if value.is_a?(FalseClass)
value = {} if value.is_a?(TrueClass)
case key
when :jshint, :JSHint, :JShint
value = load_config(value)
jshint_ignore settings_data[key]
@settings[:jshint] = temp_it('jshint.json', value.to_json)
when :scsslint, :SCSSlint
value = load_config(value)
@settings[:scsslint] = temp_it('scsslint.yml', value.to_yaml)
when :rubocop, :Rubocop, :RuboCop
value = load_config(value)
@settings[:rubocop] = temp_it('rubocop.yml', value.to_yaml)
when :brakeman
@settings[:brakeman] = settings_data[key]
when :rails_best_practice, :railsbp
@settings[:railsbp] = settings_data[key]
when :stylestats, :Stylestats
value = load_config(value)
@settings[:stylestats] = temp_it('stylestats.json', value.to_json)
when :phantomas, :Phantomas
value = load_config(value)
@settings[:phantomas] = temp_it('phantomas.json', value.to_json)
when :wraith, :Wraith
value = load_config(value)
evaluate_for_wraith(value)
# Configuration important to all of maximus
when :is_dev, :log, :root_dir, :domain, :port, :paths, :commit
@settings[key] = settings_data[key]
end
end
@settings
end | [
"def",
"evaluate_settings",
"(",
"settings_data",
"=",
"@settings",
")",
"settings_data",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"next",
"if",
"value",
".",
"is_a?",
"(",
"FalseClass",
")",
"value",
"=",
"{",
"}",
"if",
"value",
".",
"is_a?",
"(",
"TrueClass",
")",
"case",
"key",
"when",
":jshint",
",",
":JSHint",
",",
":JShint",
"value",
"=",
"load_config",
"(",
"value",
")",
"jshint_ignore",
"settings_data",
"[",
"key",
"]",
"@settings",
"[",
":jshint",
"]",
"=",
"temp_it",
"(",
"'jshint.json'",
",",
"value",
".",
"to_json",
")",
"when",
":scsslint",
",",
":SCSSlint",
"value",
"=",
"load_config",
"(",
"value",
")",
"@settings",
"[",
":scsslint",
"]",
"=",
"temp_it",
"(",
"'scsslint.yml'",
",",
"value",
".",
"to_yaml",
")",
"when",
":rubocop",
",",
":Rubocop",
",",
":RuboCop",
"value",
"=",
"load_config",
"(",
"value",
")",
"@settings",
"[",
":rubocop",
"]",
"=",
"temp_it",
"(",
"'rubocop.yml'",
",",
"value",
".",
"to_yaml",
")",
"when",
":brakeman",
"@settings",
"[",
":brakeman",
"]",
"=",
"settings_data",
"[",
"key",
"]",
"when",
":rails_best_practice",
",",
":railsbp",
"@settings",
"[",
":railsbp",
"]",
"=",
"settings_data",
"[",
"key",
"]",
"when",
":stylestats",
",",
":Stylestats",
"value",
"=",
"load_config",
"(",
"value",
")",
"@settings",
"[",
":stylestats",
"]",
"=",
"temp_it",
"(",
"'stylestats.json'",
",",
"value",
".",
"to_json",
")",
"when",
":phantomas",
",",
":Phantomas",
"value",
"=",
"load_config",
"(",
"value",
")",
"@settings",
"[",
":phantomas",
"]",
"=",
"temp_it",
"(",
"'phantomas.json'",
",",
"value",
".",
"to_json",
")",
"when",
":wraith",
",",
":Wraith",
"value",
"=",
"load_config",
"(",
"value",
")",
"evaluate_for_wraith",
"(",
"value",
")",
"when",
":is_dev",
",",
":log",
",",
":root_dir",
",",
":domain",
",",
":port",
",",
":paths",
",",
":commit",
"@settings",
"[",
"key",
"]",
"=",
"settings_data",
"[",
"key",
"]",
"end",
"end",
"@settings",
"end"
] | Global options for all of maximus
@param opts [Hash] options passed directly to config
@option opts [Boolean] :is_dev (false) whether or not the class was initialized from the command line
@option opts [String, Boolean, nil] :log ('log/maximus_git.log') path to log file
If not set, logger outputs to STDOUT
@option opts [String, Boolean] :git_log (false) path to log file or don't log
The git gem is very noisey
@option opts [String] :root_dir base directory
@option opts [String] :domain ('http://localhost') the host - used for Statistics
@option opts [String, Integer] :port ('') port number - used for Statistics
and appended to domain. If blank (false, empty string, etc.), will not
append to domain
@option opts [String, Array] :file_paths ('') path to files. Accepts glob notation
@option opts [Hash] :paths ({home: '/'}) labeled relative path to URLs. Statistics only
@option opts [String] :commit accepts sha, "working", "last", or "master".
@option opts [String] :config_file ('maximus.yml') path to config file
@option opts [Boolean] :compile_assets (true) compile and destroy assets automagically
@option opts [String] :framework (nil) accepts 'rails' and 'middleman' (should only be used
when calling Maximus from a Ruby script)
@return [#load_config_file #group_families #evaluate_settings] this method is used to set up instance variables
Set global options or generate appropriate config files for lints or statistics
@param settings_data [Hash] (@settings) loaded data from the discovered maximus config file
@return [Hash] paths to temp config files and static options
These should be deleted with destroy_temp after read and loaded | [
"Global",
"options",
"for",
"all",
"of",
"maximus"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L72-L120 | train |
wearefine/maximus | lib/maximus/config.rb | Maximus.Config.destroy_temp | def destroy_temp(filename = nil)
if filename.nil?
@temp_files.each { |filename, file| file.unlink }
@temp_files = {}
else
return if @temp_files[filename.to_sym].blank?
@temp_files[filename.to_sym].unlink
@temp_files.delete(filename.to_sym)
end
end | ruby | def destroy_temp(filename = nil)
if filename.nil?
@temp_files.each { |filename, file| file.unlink }
@temp_files = {}
else
return if @temp_files[filename.to_sym].blank?
@temp_files[filename.to_sym].unlink
@temp_files.delete(filename.to_sym)
end
end | [
"def",
"destroy_temp",
"(",
"filename",
"=",
"nil",
")",
"if",
"filename",
".",
"nil?",
"@temp_files",
".",
"each",
"{",
"|",
"filename",
",",
"file",
"|",
"file",
".",
"unlink",
"}",
"@temp_files",
"=",
"{",
"}",
"else",
"return",
"if",
"@temp_files",
"[",
"filename",
".",
"to_sym",
"]",
".",
"blank?",
"@temp_files",
"[",
"filename",
".",
"to_sym",
"]",
".",
"unlink",
"@temp_files",
".",
"delete",
"(",
"filename",
".",
"to_sym",
")",
"end",
"end"
] | Remove all or one created temporary config file
@see temp_it
@param filename [String] (nil) file to destroy
If nil, destroy all temp files | [
"Remove",
"all",
"or",
"one",
"created",
"temporary",
"config",
"file"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L139-L148 | train |
wearefine/maximus | lib/maximus/config.rb | Maximus.Config.load_config_file | def load_config_file(file_path, root)
conf_location = if file_path.present? && File.exist?(file_path)
file_path
else
config_exists('.maximus.yml', root) || config_exists('maximus.yml', root) || config_exists('config/maximus.yml', root)
end
return {} if conf_location.is_a?(FalseClass)
yaml = YAML.load_file conf_location
yaml = {} if yaml.blank?
yaml.symbolize_keys
end | ruby | def load_config_file(file_path, root)
conf_location = if file_path.present? && File.exist?(file_path)
file_path
else
config_exists('.maximus.yml', root) || config_exists('maximus.yml', root) || config_exists('config/maximus.yml', root)
end
return {} if conf_location.is_a?(FalseClass)
yaml = YAML.load_file conf_location
yaml = {} if yaml.blank?
yaml.symbolize_keys
end | [
"def",
"load_config_file",
"(",
"file_path",
",",
"root",
")",
"conf_location",
"=",
"if",
"file_path",
".",
"present?",
"&&",
"File",
".",
"exist?",
"(",
"file_path",
")",
"file_path",
"else",
"config_exists",
"(",
"'.maximus.yml'",
",",
"root",
")",
"||",
"config_exists",
"(",
"'maximus.yml'",
",",
"root",
")",
"||",
"config_exists",
"(",
"'config/maximus.yml'",
",",
"root",
")",
"end",
"return",
"{",
"}",
"if",
"conf_location",
".",
"is_a?",
"(",
"FalseClass",
")",
"yaml",
"=",
"YAML",
".",
"load_file",
"conf_location",
"yaml",
"=",
"{",
"}",
"if",
"yaml",
".",
"blank?",
"yaml",
".",
"symbolize_keys",
"end"
] | Look for a maximus config file
Checks ./maximus.yml, ./.maximus.yml, ./config/maximus.yml in order.
If there hasn't been a file discovered yet, checks ./config/maximus.yml
and if there still isn't a file, load the default one included with the
maximus gem.
@since 0.1.4
@param file_path [String]
@param root [String] file path to root directory
@return @settings [Hash] | [
"Look",
"for",
"a",
"maximus",
"config",
"file"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L170-L184 | train |
wearefine/maximus | lib/maximus/config.rb | Maximus.Config.set_families | def set_families(head_of_house, family)
if @settings.key?(head_of_house)
family.each { |f| @settings[f] ||= @settings[head_of_house].is_a?(TrueClass) }
end
end | ruby | def set_families(head_of_house, family)
if @settings.key?(head_of_house)
family.each { |f| @settings[f] ||= @settings[head_of_house].is_a?(TrueClass) }
end
end | [
"def",
"set_families",
"(",
"head_of_house",
",",
"family",
")",
"if",
"@settings",
".",
"key?",
"(",
"head_of_house",
")",
"family",
".",
"each",
"{",
"|",
"f",
"|",
"@settings",
"[",
"f",
"]",
"||=",
"@settings",
"[",
"head_of_house",
"]",
".",
"is_a?",
"(",
"TrueClass",
")",
"}",
"end",
"end"
] | Allow shorthand to be declared for groups Maximus executions
@example disable statistics
@settings[:statistics] = false
set_families('statistics', ['phantomas', 'stylestats', 'wraith'])
Sets as Boolean based on whether or not the queried label is `true`
@param head_of_house [String] @settings key and group label
@param family [Array] group of other @settings keys to be disabled
@return [void] modified @settings | [
"Allow",
"shorthand",
"to",
"be",
"declared",
"for",
"groups",
"Maximus",
"executions"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L196-L200 | train |
wearefine/maximus | lib/maximus/config.rb | Maximus.Config.load_config | def load_config(value)
return value unless value.is_a?(String)
if value =~ /^http/
begin open(value)
YAML.load open(value).read
rescue
puts "#{value} not accessible"
{}
end
elsif File.exist?(value)
YAML.load_file(value)
else
puts "#{value} not found"
{}
end
end | ruby | def load_config(value)
return value unless value.is_a?(String)
if value =~ /^http/
begin open(value)
YAML.load open(value).read
rescue
puts "#{value} not accessible"
{}
end
elsif File.exist?(value)
YAML.load_file(value)
else
puts "#{value} not found"
{}
end
end | [
"def",
"load_config",
"(",
"value",
")",
"return",
"value",
"unless",
"value",
".",
"is_a?",
"(",
"String",
")",
"if",
"value",
"=~",
"/",
"/",
"begin",
"open",
"(",
"value",
")",
"YAML",
".",
"load",
"open",
"(",
"value",
")",
".",
"read",
"rescue",
"puts",
"\"#{value} not accessible\"",
"{",
"}",
"end",
"elsif",
"File",
".",
"exist?",
"(",
"value",
")",
"YAML",
".",
"load_file",
"(",
"value",
")",
"else",
"puts",
"\"#{value} not found\"",
"{",
"}",
"end",
"end"
] | Load config files if filename supplied
@param value [Mixed] value from base config file
@param [Hash] return blank hash if file not found so
the reset of the process doesn't break | [
"Load",
"config",
"files",
"if",
"filename",
"supplied"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L207-L224 | train |
wearefine/maximus | lib/maximus/config.rb | Maximus.Config.temp_it | def temp_it(filename, data)
ext = filename.split('.')
file = Tempfile.new([filename, ".#{ext[1]}"]).tap do |f|
f.rewind
f.write(data)
f.close
end
@temp_files[ext[0].to_sym] = file
file.path
end | ruby | def temp_it(filename, data)
ext = filename.split('.')
file = Tempfile.new([filename, ".#{ext[1]}"]).tap do |f|
f.rewind
f.write(data)
f.close
end
@temp_files[ext[0].to_sym] = file
file.path
end | [
"def",
"temp_it",
"(",
"filename",
",",
"data",
")",
"ext",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"[",
"filename",
",",
"\".#{ext[1]}\"",
"]",
")",
".",
"tap",
"do",
"|",
"f",
"|",
"f",
".",
"rewind",
"f",
".",
"write",
"(",
"data",
")",
"f",
".",
"close",
"end",
"@temp_files",
"[",
"ext",
"[",
"0",
"]",
".",
"to_sym",
"]",
"=",
"file",
"file",
".",
"path",
"end"
] | Create a temp file with config data
Stores all temp files in @temp_files or self.temp_files
In Hash with filename minus extension as the key.
@param filename [String] the preferred name/identifier of the file
@param data [Mixed] config data important to each lint or statistic
@return [String] absolute path to new config file | [
"Create",
"a",
"temp",
"file",
"with",
"config",
"data"
] | d3a6ad1826694c98a5e6a5a3175b78e69aac7945 | https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L234-L243 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.