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 |
---|---|---|---|---|---|---|---|---|---|---|---|
stevenhaddox/cert_munger | lib/cert_munger/formatter.rb | CertMunger.ClassMethods.multi_line_contents | def multi_line_contents(raw_cert)
cert_contents = raw_cert.split(/[-](.*)[-]/)[2]
cert_contents.lines.map do |line|
line.lstrip.squeeze(' ').split(' ')
end
end | ruby | def multi_line_contents(raw_cert)
cert_contents = raw_cert.split(/[-](.*)[-]/)[2]
cert_contents.lines.map do |line|
line.lstrip.squeeze(' ').split(' ')
end
end | [
"def",
"multi_line_contents",
"(",
"raw_cert",
")",
"cert_contents",
"=",
"raw_cert",
".",
"split",
"(",
"/",
"/",
")",
"[",
"2",
"]",
"cert_contents",
".",
"lines",
".",
"map",
"do",
"|",
"line",
"|",
"line",
".",
"lstrip",
".",
"squeeze",
"(",
"' '",
")",
".",
"split",
"(",
"' '",
")",
"end",
"end"
] | Attempts to reformat multi-line certificate bodies
@param raw_cert [String] The string of text you wish to parse into a cert
@return [String] reformatted certificate body | [
"Attempts",
"to",
"reformat",
"multi",
"-",
"line",
"certificate",
"bodies"
] | 48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee | https://github.com/stevenhaddox/cert_munger/blob/48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee/lib/cert_munger/formatter.rb#L96-L101 | train |
wvanbergen/love | lib/love.rb | Love.ResourceURI.append_query | def append_query(base_uri, added_params = {})
base_params = base_uri.query ? CGI.parse(base_uri.query) : {}
get_params = base_params.merge(added_params.stringify_keys)
base_uri.dup.tap do |uri|
assignments = get_params.map do |k, v|
case v
when Array; v.map { |val| "#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}" }.join('&')
else "#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}"
end
end
uri.query = assignments.join('&')
end
end | ruby | def append_query(base_uri, added_params = {})
base_params = base_uri.query ? CGI.parse(base_uri.query) : {}
get_params = base_params.merge(added_params.stringify_keys)
base_uri.dup.tap do |uri|
assignments = get_params.map do |k, v|
case v
when Array; v.map { |val| "#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}" }.join('&')
else "#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}"
end
end
uri.query = assignments.join('&')
end
end | [
"def",
"append_query",
"(",
"base_uri",
",",
"added_params",
"=",
"{",
"}",
")",
"base_params",
"=",
"base_uri",
".",
"query",
"?",
"CGI",
".",
"parse",
"(",
"base_uri",
".",
"query",
")",
":",
"{",
"}",
"get_params",
"=",
"base_params",
".",
"merge",
"(",
"added_params",
".",
"stringify_keys",
")",
"base_uri",
".",
"dup",
".",
"tap",
"do",
"|",
"uri",
"|",
"assignments",
"=",
"get_params",
".",
"map",
"do",
"|",
"k",
",",
"v",
"|",
"case",
"v",
"when",
"Array",
";",
"v",
".",
"map",
"{",
"|",
"val",
"|",
"\"#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}\"",
"}",
".",
"join",
"(",
"'&'",
")",
"else",
"\"#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}\"",
"end",
"end",
"uri",
".",
"query",
"=",
"assignments",
".",
"join",
"(",
"'&'",
")",
"end",
"end"
] | Appends GET parameters to a URI instance. Duplicate parameters will
be replaced with the new value.
@param [URI] base_uri The original URI to work with (will not be modified)
@param [Hash] added_params To GET params to add.
@return [URI] The URI with appended GET parameters | [
"Appends",
"GET",
"parameters",
"to",
"a",
"URI",
"instance",
".",
"Duplicate",
"parameters",
"will",
"be",
"replaced",
"with",
"the",
"new",
"value",
"."
] | 14ed84c2fcc6b008879dd598328ab56d7dd4a053 | https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L108-L120 | train |
wvanbergen/love | lib/love.rb | Love.Client.connection | def connection
@connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http|
http.use_ssl = true
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
end
end | ruby | def connection
@connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http|
http.use_ssl = true
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
end
end | [
"def",
"connection",
"@connection",
"||=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"TENDER_API_HOST",
",",
"Net",
"::",
"HTTP",
".",
"https_default_port",
")",
".",
"tap",
"do",
"|",
"http",
"|",
"http",
".",
"use_ssl",
"=",
"true",
"# http.verify_mode = OpenSSL::SSL::VERIFY_NONE",
"http",
".",
"start",
"end",
"end"
] | Returns a persistent connection to the server, reusing a connection of it was
previously established.
This method is mainly used for internal use but can be used to do advanced
HTTP connectivity with the Tender API server.
@return [Net::HTTP] The net/http connection instance. | [
"Returns",
"a",
"persistent",
"connection",
"to",
"the",
"server",
"reusing",
"a",
"connection",
"of",
"it",
"was",
"previously",
"established",
"."
] | 14ed84c2fcc6b008879dd598328ab56d7dd4a053 | https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L239-L245 | train |
wvanbergen/love | lib/love.rb | Love.Client.paged_each | def paged_each(uri, list_key, options = {}, &block)
query_params = {}
query_params[:since] = options[:since].to_date.to_s(:db) if options[:since]
query_params[:page] = [options[:start_page].to_i, 1].max rescue 1
results = []
initial_result = get(append_query(uri, query_params))
# Determine the amount of pages that is going to be requested.
max_page = (initial_result['total'].to_f / initial_result['per_page'].to_f).ceil
end_page = options[:end_page].nil? ? max_page : [options[:end_page].to_i, max_page].min
# Print out some initial debugging information
Love.logger.debug "Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}." if Love.logger
# Handle first page of results
if initial_result[list_key].kind_of?(Array)
block_given? ? initial_result[list_key].each { |record| yield(record) } : results << initial_result[list_key]
sleep(sleep_between_requests) if sleep_between_requests
end
start_page = query_params[:page].to_i + 1
start_page.upto(end_page) do |page|
query_params[:page] = page
result = get(append_query(uri, query_params))
if result[list_key].kind_of?(Array)
block_given? ? result[list_key].each { |record| yield(record) } : results << result[list_key]
sleep(sleep_between_requests) if sleep_between_requests
end
end
results.flatten.map {|r| OpenStruct.new(r)} unless block_given?
end | ruby | def paged_each(uri, list_key, options = {}, &block)
query_params = {}
query_params[:since] = options[:since].to_date.to_s(:db) if options[:since]
query_params[:page] = [options[:start_page].to_i, 1].max rescue 1
results = []
initial_result = get(append_query(uri, query_params))
# Determine the amount of pages that is going to be requested.
max_page = (initial_result['total'].to_f / initial_result['per_page'].to_f).ceil
end_page = options[:end_page].nil? ? max_page : [options[:end_page].to_i, max_page].min
# Print out some initial debugging information
Love.logger.debug "Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}." if Love.logger
# Handle first page of results
if initial_result[list_key].kind_of?(Array)
block_given? ? initial_result[list_key].each { |record| yield(record) } : results << initial_result[list_key]
sleep(sleep_between_requests) if sleep_between_requests
end
start_page = query_params[:page].to_i + 1
start_page.upto(end_page) do |page|
query_params[:page] = page
result = get(append_query(uri, query_params))
if result[list_key].kind_of?(Array)
block_given? ? result[list_key].each { |record| yield(record) } : results << result[list_key]
sleep(sleep_between_requests) if sleep_between_requests
end
end
results.flatten.map {|r| OpenStruct.new(r)} unless block_given?
end | [
"def",
"paged_each",
"(",
"uri",
",",
"list_key",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"query_params",
"=",
"{",
"}",
"query_params",
"[",
":since",
"]",
"=",
"options",
"[",
":since",
"]",
".",
"to_date",
".",
"to_s",
"(",
":db",
")",
"if",
"options",
"[",
":since",
"]",
"query_params",
"[",
":page",
"]",
"=",
"[",
"options",
"[",
":start_page",
"]",
".",
"to_i",
",",
"1",
"]",
".",
"max",
"rescue",
"1",
"results",
"=",
"[",
"]",
"initial_result",
"=",
"get",
"(",
"append_query",
"(",
"uri",
",",
"query_params",
")",
")",
"# Determine the amount of pages that is going to be requested.",
"max_page",
"=",
"(",
"initial_result",
"[",
"'total'",
"]",
".",
"to_f",
"/",
"initial_result",
"[",
"'per_page'",
"]",
".",
"to_f",
")",
".",
"ceil",
"end_page",
"=",
"options",
"[",
":end_page",
"]",
".",
"nil?",
"?",
"max_page",
":",
"[",
"options",
"[",
":end_page",
"]",
".",
"to_i",
",",
"max_page",
"]",
".",
"min",
"# Print out some initial debugging information",
"Love",
".",
"logger",
".",
"debug",
"\"Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}.\"",
"if",
"Love",
".",
"logger",
"# Handle first page of results",
"if",
"initial_result",
"[",
"list_key",
"]",
".",
"kind_of?",
"(",
"Array",
")",
"block_given?",
"?",
"initial_result",
"[",
"list_key",
"]",
".",
"each",
"{",
"|",
"record",
"|",
"yield",
"(",
"record",
")",
"}",
":",
"results",
"<<",
"initial_result",
"[",
"list_key",
"]",
"sleep",
"(",
"sleep_between_requests",
")",
"if",
"sleep_between_requests",
"end",
"start_page",
"=",
"query_params",
"[",
":page",
"]",
".",
"to_i",
"+",
"1",
"start_page",
".",
"upto",
"(",
"end_page",
")",
"do",
"|",
"page",
"|",
"query_params",
"[",
":page",
"]",
"=",
"page",
"result",
"=",
"get",
"(",
"append_query",
"(",
"uri",
",",
"query_params",
")",
")",
"if",
"result",
"[",
"list_key",
"]",
".",
"kind_of?",
"(",
"Array",
")",
"block_given?",
"?",
"result",
"[",
"list_key",
"]",
".",
"each",
"{",
"|",
"record",
"|",
"yield",
"(",
"record",
")",
"}",
":",
"results",
"<<",
"result",
"[",
"list_key",
"]",
"sleep",
"(",
"sleep_between_requests",
")",
"if",
"sleep_between_requests",
"end",
"end",
"results",
".",
"flatten",
".",
"map",
"{",
"|",
"r",
"|",
"OpenStruct",
".",
"new",
"(",
"r",
")",
"}",
"unless",
"block_given?",
"end"
] | Iterates over a collection, issuing multiple requests to get all the paged results.
@option options [Date] :since Only include records updated since the provided date.
Caution: not supported by all resources.
@option options [Integer] :start_page The initial page number to request.
@option options [Integer] :end_page The final page number to request. | [
"Iterates",
"over",
"a",
"collection",
"issuing",
"multiple",
"requests",
"to",
"get",
"all",
"the",
"paged",
"results",
"."
] | 14ed84c2fcc6b008879dd598328ab56d7dd4a053 | https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L310-L340 | train |
IntegraCore/quick_dry | app/controllers/quick_dry/quick_dry_controller.rb | QuickDry.QuickDryController.serialize | def serialize stuff
if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation
json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key )
hash = JSON.parse(json)
temp = []
if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key
hash[get_model.model_name.route_key].each{|x| temp << x[get_model.model_name.route_key]}
hash[get_model.model_name.route_key] = temp
return hash.to_json
end
return json
elsif stuff.is_a? get_model
end
end | ruby | def serialize stuff
if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation
json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key )
hash = JSON.parse(json)
temp = []
if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key
hash[get_model.model_name.route_key].each{|x| temp << x[get_model.model_name.route_key]}
hash[get_model.model_name.route_key] = temp
return hash.to_json
end
return json
elsif stuff.is_a? get_model
end
end | [
"def",
"serialize",
"stuff",
"if",
"stuff",
".",
"is_a?",
"Array",
"or",
"stuff",
".",
"is_a?",
"ActiveRecord",
"::",
"Relation",
"json",
"=",
"render_to_string",
"json",
":",
"QuickDryArraySerializer",
".",
"new",
"(",
"stuff",
",",
"root",
":",
"get_model",
".",
"model_name",
".",
"route_key",
")",
"hash",
"=",
"JSON",
".",
"parse",
"(",
"json",
")",
"temp",
"=",
"[",
"]",
"if",
"hash",
"[",
"get_model",
".",
"model_name",
".",
"route_key",
"]",
".",
"first",
".",
"has_key?",
"get_model",
".",
"model_name",
".",
"route_key",
"hash",
"[",
"get_model",
".",
"model_name",
".",
"route_key",
"]",
".",
"each",
"{",
"|",
"x",
"|",
"temp",
"<<",
"x",
"[",
"get_model",
".",
"model_name",
".",
"route_key",
"]",
"}",
"hash",
"[",
"get_model",
".",
"model_name",
".",
"route_key",
"]",
"=",
"temp",
"return",
"hash",
".",
"to_json",
"end",
"return",
"json",
"elsif",
"stuff",
".",
"is_a?",
"get_model",
"end",
"end"
] | nasty hack until I can get an answer on the official way to remove the instance root keys in a list | [
"nasty",
"hack",
"until",
"I",
"can",
"get",
"an",
"answer",
"on",
"the",
"official",
"way",
"to",
"remove",
"the",
"instance",
"root",
"keys",
"in",
"a",
"list"
] | 5a488499497dd453dbd0d29d3a0511f1b99a2fdf | https://github.com/IntegraCore/quick_dry/blob/5a488499497dd453dbd0d29d3a0511f1b99a2fdf/app/controllers/quick_dry/quick_dry_controller.rb#L10-L24 | train |
IntegraCore/quick_dry | app/controllers/quick_dry/quick_dry_controller.rb | QuickDry.QuickDryController.get_paged_search_results | def get_paged_search_results(params,user:nil,model:nil)
params[:per_page] = 10 if params[:per_page].blank?
params[:page] = 1 if params[:page].blank?
# a ghetto user check, but for some reason a devise user is not a devise user...
user = User.new if user.blank? or !user.class.to_s == User.to_s
# get the model in question
# there has got to be a better way to do this... I just can't find it
# model = params[:controller].blank? ? self.class.name.gsub('Controller','').singularize.constantize : params[:controller].classify.constantize
if model.blank?
model = request.params[:table_name].classify.constantize unless request.params[:table_name].blank?
return nil if model.blank?
end
# initialize un-paged filtered result set
result_set = model.none
# create where clauses to filter result to just the customers the current user has access to
customer_filter = ""
user.customers.each do |cust|
if model.column_names.include? "cust_id"
customer_filter << "(cust_id = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank?
elsif model.attribute_alias? "cust_id"
customer_filter << "(#{model.attribute_alias "cust_id"} = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank?
elsif model.column_names.include? "order_number"
customer_filter << "(order_number like '#{cust.prefix}%') OR " unless cust.prefix.blank?
elsif model.attribute_alias? "order_number"
customer_filter << "(#{model.attribute_alias "order_number"} like '#{cust.prefix}%') OR " unless cust.prefix.blank?
end
end
customer_filter << " (1=0)"
# create where clauses for each search parameter
if params[:columns].blank?
result_set = model.where(customer_filter)
else
where_clause = ""
params[:columns].each do |name, value|
where_clause << "(#{model.table_name}.#{name} like '%#{value}%') AND " unless value.blank?
end
where_clause << " (1=1)"
result_set = model.where(customer_filter).where(where_clause)
end
instances = model.paginate(page: params[:page], per_page: params[:per_page]).merge(result_set).order(updated_at: :desc)
return {instances:instances,params:params}
end | ruby | def get_paged_search_results(params,user:nil,model:nil)
params[:per_page] = 10 if params[:per_page].blank?
params[:page] = 1 if params[:page].blank?
# a ghetto user check, but for some reason a devise user is not a devise user...
user = User.new if user.blank? or !user.class.to_s == User.to_s
# get the model in question
# there has got to be a better way to do this... I just can't find it
# model = params[:controller].blank? ? self.class.name.gsub('Controller','').singularize.constantize : params[:controller].classify.constantize
if model.blank?
model = request.params[:table_name].classify.constantize unless request.params[:table_name].blank?
return nil if model.blank?
end
# initialize un-paged filtered result set
result_set = model.none
# create where clauses to filter result to just the customers the current user has access to
customer_filter = ""
user.customers.each do |cust|
if model.column_names.include? "cust_id"
customer_filter << "(cust_id = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank?
elsif model.attribute_alias? "cust_id"
customer_filter << "(#{model.attribute_alias "cust_id"} = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank?
elsif model.column_names.include? "order_number"
customer_filter << "(order_number like '#{cust.prefix}%') OR " unless cust.prefix.blank?
elsif model.attribute_alias? "order_number"
customer_filter << "(#{model.attribute_alias "order_number"} like '#{cust.prefix}%') OR " unless cust.prefix.blank?
end
end
customer_filter << " (1=0)"
# create where clauses for each search parameter
if params[:columns].blank?
result_set = model.where(customer_filter)
else
where_clause = ""
params[:columns].each do |name, value|
where_clause << "(#{model.table_name}.#{name} like '%#{value}%') AND " unless value.blank?
end
where_clause << " (1=1)"
result_set = model.where(customer_filter).where(where_clause)
end
instances = model.paginate(page: params[:page], per_page: params[:per_page]).merge(result_set).order(updated_at: :desc)
return {instances:instances,params:params}
end | [
"def",
"get_paged_search_results",
"(",
"params",
",",
"user",
":",
"nil",
",",
"model",
":",
"nil",
")",
"params",
"[",
":per_page",
"]",
"=",
"10",
"if",
"params",
"[",
":per_page",
"]",
".",
"blank?",
"params",
"[",
":page",
"]",
"=",
"1",
"if",
"params",
"[",
":page",
"]",
".",
"blank?",
"# a ghetto user check, but for some reason a devise user is not a devise user...",
"user",
"=",
"User",
".",
"new",
"if",
"user",
".",
"blank?",
"or",
"!",
"user",
".",
"class",
".",
"to_s",
"==",
"User",
".",
"to_s",
"# get the model in question",
"# there has got to be a better way to do this... I just can't find it",
"# model = params[:controller].blank? ? self.class.name.gsub('Controller','').singularize.constantize : params[:controller].classify.constantize",
"if",
"model",
".",
"blank?",
"model",
"=",
"request",
".",
"params",
"[",
":table_name",
"]",
".",
"classify",
".",
"constantize",
"unless",
"request",
".",
"params",
"[",
":table_name",
"]",
".",
"blank?",
"return",
"nil",
"if",
"model",
".",
"blank?",
"end",
"# initialize un-paged filtered result set",
"result_set",
"=",
"model",
".",
"none",
"# create where clauses to filter result to just the customers the current user has access to",
"customer_filter",
"=",
"\"\"",
"user",
".",
"customers",
".",
"each",
"do",
"|",
"cust",
"|",
"if",
"model",
".",
"column_names",
".",
"include?",
"\"cust_id\"",
"customer_filter",
"<<",
"\"(cust_id = '#{cust.cust_id(true)}') OR \"",
"unless",
"cust",
".",
"cust_id",
".",
"blank?",
"elsif",
"model",
".",
"attribute_alias?",
"\"cust_id\"",
"customer_filter",
"<<",
"\"(#{model.attribute_alias \"cust_id\"} = '#{cust.cust_id(true)}') OR \"",
"unless",
"cust",
".",
"cust_id",
".",
"blank?",
"elsif",
"model",
".",
"column_names",
".",
"include?",
"\"order_number\"",
"customer_filter",
"<<",
"\"(order_number like '#{cust.prefix}%') OR \"",
"unless",
"cust",
".",
"prefix",
".",
"blank?",
"elsif",
"model",
".",
"attribute_alias?",
"\"order_number\"",
"customer_filter",
"<<",
"\"(#{model.attribute_alias \"order_number\"} like '#{cust.prefix}%') OR \"",
"unless",
"cust",
".",
"prefix",
".",
"blank?",
"end",
"end",
"customer_filter",
"<<",
"\" (1=0)\"",
"# create where clauses for each search parameter",
"if",
"params",
"[",
":columns",
"]",
".",
"blank?",
"result_set",
"=",
"model",
".",
"where",
"(",
"customer_filter",
")",
"else",
"where_clause",
"=",
"\"\"",
"params",
"[",
":columns",
"]",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"where_clause",
"<<",
"\"(#{model.table_name}.#{name} like '%#{value}%') AND \"",
"unless",
"value",
".",
"blank?",
"end",
"where_clause",
"<<",
"\" (1=1)\"",
"result_set",
"=",
"model",
".",
"where",
"(",
"customer_filter",
")",
".",
"where",
"(",
"where_clause",
")",
"end",
"instances",
"=",
"model",
".",
"paginate",
"(",
"page",
":",
"params",
"[",
":page",
"]",
",",
"per_page",
":",
"params",
"[",
":per_page",
"]",
")",
".",
"merge",
"(",
"result_set",
")",
".",
"order",
"(",
"updated_at",
":",
":desc",
")",
"return",
"{",
"instances",
":",
"instances",
",",
"params",
":",
"params",
"}",
"end"
] | Assumes the existance of a User model | [
"Assumes",
"the",
"existance",
"of",
"a",
"User",
"model"
] | 5a488499497dd453dbd0d29d3a0511f1b99a2fdf | https://github.com/IntegraCore/quick_dry/blob/5a488499497dd453dbd0d29d3a0511f1b99a2fdf/app/controllers/quick_dry/quick_dry_controller.rb#L176-L223 | train |
0000marcell/simple_commander | lib/simple_commander/user_interaction.rb | SimpleCommander.UI.converse | def converse(prompt, responses = {})
i, commands = 0, responses.map { |_key, value| value.inspect }.join(',')
statement = responses.inject '' do |inner_statement, (key, value)|
inner_statement <<
(
(i += 1) == 1 ?
%(if response is "#{value}" then\n) :
%(else if response is "#{value}" then\n)
) <<
%(do shell script "echo '#{key}'"\n)
end
applescript(
%(
tell application "SpeechRecognitionServer"
set response to listen for {#{commands}} with prompt "#{prompt}"
#{statement}
end if
end tell
),
).strip.to_sym
end | ruby | def converse(prompt, responses = {})
i, commands = 0, responses.map { |_key, value| value.inspect }.join(',')
statement = responses.inject '' do |inner_statement, (key, value)|
inner_statement <<
(
(i += 1) == 1 ?
%(if response is "#{value}" then\n) :
%(else if response is "#{value}" then\n)
) <<
%(do shell script "echo '#{key}'"\n)
end
applescript(
%(
tell application "SpeechRecognitionServer"
set response to listen for {#{commands}} with prompt "#{prompt}"
#{statement}
end if
end tell
),
).strip.to_sym
end | [
"def",
"converse",
"(",
"prompt",
",",
"responses",
"=",
"{",
"}",
")",
"i",
",",
"commands",
"=",
"0",
",",
"responses",
".",
"map",
"{",
"|",
"_key",
",",
"value",
"|",
"value",
".",
"inspect",
"}",
".",
"join",
"(",
"','",
")",
"statement",
"=",
"responses",
".",
"inject",
"''",
"do",
"|",
"inner_statement",
",",
"(",
"key",
",",
"value",
")",
"|",
"inner_statement",
"<<",
"(",
"(",
"i",
"+=",
"1",
")",
"==",
"1",
"?",
"%(if response is \"#{value}\" then\\n)",
":",
"%(else if response is \"#{value}\" then\\n)",
")",
"<<",
"%(do shell script \"echo '#{key}'\"\\n)",
"end",
"applescript",
"(",
"%(\n tell application \"SpeechRecognitionServer\"\n set response to listen for {#{commands}} with prompt \"#{prompt}\"\n #{statement}\n end if\n end tell\n )",
",",
")",
".",
"strip",
".",
"to_sym",
"end"
] | Converse with speech recognition.
Currently a "poorman's" DSL to utilize applescript and
the MacOS speech recognition server.
=== Examples
case converse 'What is the best food?', :cookies => 'Cookies', :unknown => 'Nothing'
when :cookies
speak 'o.m.g. you are awesome!'
else
case converse 'That is lame, shall I convince you cookies are the best?', :yes => 'Ok', :no => 'No', :maybe => 'Maybe another time'
when :yes
speak 'Well you see, cookies are just fantastic.'
else
speak 'Ok then, bye.'
end
end
=== Notes
* MacOS only | [
"Converse",
"with",
"speech",
"recognition",
"."
] | 337c2e0d9926c643ce131b1a1ebd3740241e4424 | https://github.com/0000marcell/simple_commander/blob/337c2e0d9926c643ce131b1a1ebd3740241e4424/lib/simple_commander/user_interaction.rb#L166-L186 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.authorized_for? | def authorized_for?(obj)
logger.debug("Checking to see if authorized to access object")
if @auth_user.nil?
# :nocov:
return false
# :nocov:
elsif @auth_user.role >= Roles::ADMIN
return true
elsif obj.is_a? User
return obj == @auth_user
else
return obj.try(:user) == @auth_user
end
end | ruby | def authorized_for?(obj)
logger.debug("Checking to see if authorized to access object")
if @auth_user.nil?
# :nocov:
return false
# :nocov:
elsif @auth_user.role >= Roles::ADMIN
return true
elsif obj.is_a? User
return obj == @auth_user
else
return obj.try(:user) == @auth_user
end
end | [
"def",
"authorized_for?",
"(",
"obj",
")",
"logger",
".",
"debug",
"(",
"\"Checking to see if authorized to access object\"",
")",
"if",
"@auth_user",
".",
"nil?",
"# :nocov:",
"return",
"false",
"# :nocov:",
"elsif",
"@auth_user",
".",
"role",
">=",
"Roles",
"::",
"ADMIN",
"return",
"true",
"elsif",
"obj",
".",
"is_a?",
"User",
"return",
"obj",
"==",
"@auth_user",
"else",
"return",
"obj",
".",
"try",
"(",
":user",
")",
"==",
"@auth_user",
"end",
"end"
] | Determines if the user is authorized for the object. The user must be
either the creator of the object or must be an admin or above. | [
"Determines",
"if",
"the",
"user",
"is",
"authorized",
"for",
"the",
"object",
".",
"The",
"user",
"must",
"be",
"either",
"the",
"creator",
"of",
"the",
"object",
"or",
"must",
"be",
"an",
"admin",
"or",
"above",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L124-L137 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_token_payload | def get_token_payload(token)
# Attempt to decode without verifying. May raise DecodeError.
decoded = JWT.decode token, nil, false
payload = decoded[0]
# At this point, we know that the token is not expired and
# well formatted. Find out if the payload is well defined.
if payload.nil?
# :nocov:
logger.error("Token payload is nil: #{token}")
raise UNAUTHORIZED_ERROR, "Invalid token"
# :nocov:
end
return payload
rescue JWT::DecodeError => e
logger.error("Token decode error: #{e.message}")
raise UNAUTHORIZED_ERROR, "Invalid token"
end | ruby | def get_token_payload(token)
# Attempt to decode without verifying. May raise DecodeError.
decoded = JWT.decode token, nil, false
payload = decoded[0]
# At this point, we know that the token is not expired and
# well formatted. Find out if the payload is well defined.
if payload.nil?
# :nocov:
logger.error("Token payload is nil: #{token}")
raise UNAUTHORIZED_ERROR, "Invalid token"
# :nocov:
end
return payload
rescue JWT::DecodeError => e
logger.error("Token decode error: #{e.message}")
raise UNAUTHORIZED_ERROR, "Invalid token"
end | [
"def",
"get_token_payload",
"(",
"token",
")",
"# Attempt to decode without verifying. May raise DecodeError.",
"decoded",
"=",
"JWT",
".",
"decode",
"token",
",",
"nil",
",",
"false",
"payload",
"=",
"decoded",
"[",
"0",
"]",
"# At this point, we know that the token is not expired and",
"# well formatted. Find out if the payload is well defined.",
"if",
"payload",
".",
"nil?",
"# :nocov:",
"logger",
".",
"error",
"(",
"\"Token payload is nil: #{token}\"",
")",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid token\"",
"# :nocov:",
"end",
"return",
"payload",
"rescue",
"JWT",
"::",
"DecodeError",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Token decode error: #{e.message}\"",
")",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid token\"",
"end"
] | Attempts to retrieve the payload encoded in the token. It checks if
the token is "valid" according to JWT definition and not expired.
A UNAUTHORIZED_ERROR is raised if token cannot be decoded. | [
"Attempts",
"to",
"retrieve",
"the",
"payload",
"encoded",
"in",
"the",
"token",
".",
"It",
"checks",
"if",
"the",
"token",
"is",
"valid",
"according",
"to",
"JWT",
"definition",
"and",
"not",
"expired",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L169-L189 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.verify_token | def verify_token(token)
logger.debug("Verifying token: #{token}")
# First get the payload of the token. This will also verify whether
# or not the token is welformed.
payload = get_token_payload(token)
# Next, the payload should define user UUID and session UUID.
user_uuid = payload["user_uuid"]
session_uuid = payload["session_uuid"]
if user_uuid.nil? || session_uuid.nil?
logger.error("User or session is not specified")
raise UNAUTHORIZED_ERROR, "Invalid token"
end
logger.debug("Token well defined: #{token}")
# But, the user UUID and session UUID better be valid too. That is,
# they must be real user and session, and the session must belong to
# the user.
auth_user = User.find_by_uuid(user_uuid)
if auth_user.nil?
# :nocov:
logger.error("Specified user doesn't exist #{user_uuid}")
raise UNAUTHORIZED_ERROR, "Invalid token"
# :nocov:
end
auth_session = Session.find_by_uuid(session_uuid)
if auth_session.nil? || auth_session.user != auth_user
logger.error("Specified session doesn't exist #{session_uuid}")
raise UNAUTHORIZED_ERROR, "Invalid token"
end
# Finally, decode the token using the secret. Also check expiration
# here too.
JWT.decode token, auth_session.secret, true
logger.debug("Token well formatted and verified. Set cache.")
# Return the corresponding session
return auth_session
rescue JWT::DecodeError => e
logger.error(e.message)
raise UNAUTHORIZED_ERROR, "Invalid token"
end | ruby | def verify_token(token)
logger.debug("Verifying token: #{token}")
# First get the payload of the token. This will also verify whether
# or not the token is welformed.
payload = get_token_payload(token)
# Next, the payload should define user UUID and session UUID.
user_uuid = payload["user_uuid"]
session_uuid = payload["session_uuid"]
if user_uuid.nil? || session_uuid.nil?
logger.error("User or session is not specified")
raise UNAUTHORIZED_ERROR, "Invalid token"
end
logger.debug("Token well defined: #{token}")
# But, the user UUID and session UUID better be valid too. That is,
# they must be real user and session, and the session must belong to
# the user.
auth_user = User.find_by_uuid(user_uuid)
if auth_user.nil?
# :nocov:
logger.error("Specified user doesn't exist #{user_uuid}")
raise UNAUTHORIZED_ERROR, "Invalid token"
# :nocov:
end
auth_session = Session.find_by_uuid(session_uuid)
if auth_session.nil? || auth_session.user != auth_user
logger.error("Specified session doesn't exist #{session_uuid}")
raise UNAUTHORIZED_ERROR, "Invalid token"
end
# Finally, decode the token using the secret. Also check expiration
# here too.
JWT.decode token, auth_session.secret, true
logger.debug("Token well formatted and verified. Set cache.")
# Return the corresponding session
return auth_session
rescue JWT::DecodeError => e
logger.error(e.message)
raise UNAUTHORIZED_ERROR, "Invalid token"
end | [
"def",
"verify_token",
"(",
"token",
")",
"logger",
".",
"debug",
"(",
"\"Verifying token: #{token}\"",
")",
"# First get the payload of the token. This will also verify whether",
"# or not the token is welformed.",
"payload",
"=",
"get_token_payload",
"(",
"token",
")",
"# Next, the payload should define user UUID and session UUID.",
"user_uuid",
"=",
"payload",
"[",
"\"user_uuid\"",
"]",
"session_uuid",
"=",
"payload",
"[",
"\"session_uuid\"",
"]",
"if",
"user_uuid",
".",
"nil?",
"||",
"session_uuid",
".",
"nil?",
"logger",
".",
"error",
"(",
"\"User or session is not specified\"",
")",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid token\"",
"end",
"logger",
".",
"debug",
"(",
"\"Token well defined: #{token}\"",
")",
"# But, the user UUID and session UUID better be valid too. That is,",
"# they must be real user and session, and the session must belong to",
"# the user.",
"auth_user",
"=",
"User",
".",
"find_by_uuid",
"(",
"user_uuid",
")",
"if",
"auth_user",
".",
"nil?",
"# :nocov:",
"logger",
".",
"error",
"(",
"\"Specified user doesn't exist #{user_uuid}\"",
")",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid token\"",
"# :nocov:",
"end",
"auth_session",
"=",
"Session",
".",
"find_by_uuid",
"(",
"session_uuid",
")",
"if",
"auth_session",
".",
"nil?",
"||",
"auth_session",
".",
"user",
"!=",
"auth_user",
"logger",
".",
"error",
"(",
"\"Specified session doesn't exist #{session_uuid}\"",
")",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid token\"",
"end",
"# Finally, decode the token using the secret. Also check expiration",
"# here too.",
"JWT",
".",
"decode",
"token",
",",
"auth_session",
".",
"secret",
",",
"true",
"logger",
".",
"debug",
"(",
"\"Token well formatted and verified. Set cache.\"",
")",
"# Return the corresponding session",
"return",
"auth_session",
"rescue",
"JWT",
"::",
"DecodeError",
"=>",
"e",
"logger",
".",
"error",
"(",
"e",
".",
"message",
")",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid token\"",
"end"
] | Truly verifies the token and its payload. It ensures the user and
session specified in the token payload are indeed valid. The
required role is also checked.
A UNAUTHORIZED_ERROR is thrown for all cases where token is
invalid. | [
"Truly",
"verifies",
"the",
"token",
"and",
"its",
"payload",
".",
"It",
"ensures",
"the",
"user",
"and",
"session",
"specified",
"in",
"the",
"token",
"payload",
"are",
"indeed",
"valid",
".",
"The",
"required",
"role",
"is",
"also",
"checked",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L199-L242 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_token | def get_token(required_role: Roles::PUBLIC)
token = params[:token]
# Look up the cache. If present, use it and skip the verification.
# Use token itself (and not a session UUID) as part of the key so
# it can be considered *verified*.
@auth_session = Cache.get(kind: :session, token: token)
# Cache miss. So proceed to verify the token and get user and
# session data from database. Then set the cache for later.
if @auth_session.nil?
@auth_session = verify_token(token)
@auth_session.role # NOTE: no-op
Cache.set({kind: :session, token: token}, @auth_session)
end
# Obtained session may not have enough permission. Check here.
if @auth_session.role < required_role
logger.error("Not enough permission (role: #{@auth_session.role})")
raise UNAUTHORIZED_ERROR, "Invalid token"
end
@auth_user = @auth_session.user
@token = @auth_session.token
return true
end | ruby | def get_token(required_role: Roles::PUBLIC)
token = params[:token]
# Look up the cache. If present, use it and skip the verification.
# Use token itself (and not a session UUID) as part of the key so
# it can be considered *verified*.
@auth_session = Cache.get(kind: :session, token: token)
# Cache miss. So proceed to verify the token and get user and
# session data from database. Then set the cache for later.
if @auth_session.nil?
@auth_session = verify_token(token)
@auth_session.role # NOTE: no-op
Cache.set({kind: :session, token: token}, @auth_session)
end
# Obtained session may not have enough permission. Check here.
if @auth_session.role < required_role
logger.error("Not enough permission (role: #{@auth_session.role})")
raise UNAUTHORIZED_ERROR, "Invalid token"
end
@auth_user = @auth_session.user
@token = @auth_session.token
return true
end | [
"def",
"get_token",
"(",
"required_role",
":",
"Roles",
"::",
"PUBLIC",
")",
"token",
"=",
"params",
"[",
":token",
"]",
"# Look up the cache. If present, use it and skip the verification.",
"# Use token itself (and not a session UUID) as part of the key so",
"# it can be considered *verified*.",
"@auth_session",
"=",
"Cache",
".",
"get",
"(",
"kind",
":",
":session",
",",
"token",
":",
"token",
")",
"# Cache miss. So proceed to verify the token and get user and",
"# session data from database. Then set the cache for later.",
"if",
"@auth_session",
".",
"nil?",
"@auth_session",
"=",
"verify_token",
"(",
"token",
")",
"@auth_session",
".",
"role",
"# NOTE: no-op",
"Cache",
".",
"set",
"(",
"{",
"kind",
":",
":session",
",",
"token",
":",
"token",
"}",
",",
"@auth_session",
")",
"end",
"# Obtained session may not have enough permission. Check here.",
"if",
"@auth_session",
".",
"role",
"<",
"required_role",
"logger",
".",
"error",
"(",
"\"Not enough permission (role: #{@auth_session.role})\"",
")",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid token\"",
"end",
"@auth_user",
"=",
"@auth_session",
".",
"user",
"@token",
"=",
"@auth_session",
".",
"token",
"return",
"true",
"end"
] | Attempt to get a token for the session. Token must be specified in
query string or part of the JSON object.
Raises a UNAUTHORIZED_ERROR if cached session has less role
than what's required. | [
"Attempt",
"to",
"get",
"a",
"token",
"for",
"the",
"session",
".",
"Token",
"must",
"be",
"specified",
"in",
"query",
"string",
"or",
"part",
"of",
"the",
"JSON",
"object",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L251-L275 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_api_key | def get_api_key(required_role: Roles::PUBLIC)
api_key = params[:api_key]
if api_key.nil?
# This case is not likely, but as a safeguard in case migration
# has not gone well.
# :nocov:
raise UNAUTHORIZED_ERROR, "Invalid api key"
# :nocov:
end
auth_user = User.find_by_api_key(api_key)
if auth_user.nil? || auth_user.role < required_role
raise UNAUTHORIZED_ERROR, "Invalid api key"
end
@auth_user = auth_user
@auth_session = nil
@token = nil
return true
end | ruby | def get_api_key(required_role: Roles::PUBLIC)
api_key = params[:api_key]
if api_key.nil?
# This case is not likely, but as a safeguard in case migration
# has not gone well.
# :nocov:
raise UNAUTHORIZED_ERROR, "Invalid api key"
# :nocov:
end
auth_user = User.find_by_api_key(api_key)
if auth_user.nil? || auth_user.role < required_role
raise UNAUTHORIZED_ERROR, "Invalid api key"
end
@auth_user = auth_user
@auth_session = nil
@token = nil
return true
end | [
"def",
"get_api_key",
"(",
"required_role",
":",
"Roles",
"::",
"PUBLIC",
")",
"api_key",
"=",
"params",
"[",
":api_key",
"]",
"if",
"api_key",
".",
"nil?",
"# This case is not likely, but as a safeguard in case migration",
"# has not gone well.",
"# :nocov:",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid api key\"",
"# :nocov:",
"end",
"auth_user",
"=",
"User",
".",
"find_by_api_key",
"(",
"api_key",
")",
"if",
"auth_user",
".",
"nil?",
"||",
"auth_user",
".",
"role",
"<",
"required_role",
"raise",
"UNAUTHORIZED_ERROR",
",",
"\"Invalid api key\"",
"end",
"@auth_user",
"=",
"auth_user",
"@auth_session",
"=",
"nil",
"@token",
"=",
"nil",
"return",
"true",
"end"
] | Get API key from the request.
Raises a UNAUTHORIZED_ERROR if API key is not valid (or not
provided). | [
"Get",
"API",
"key",
"from",
"the",
"request",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L283-L300 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_auth | def get_auth(required_role: Roles::USER)
if params[:token]
get_token(required_role: required_role)
else
get_api_key(required_role: required_role)
end
end | ruby | def get_auth(required_role: Roles::USER)
if params[:token]
get_token(required_role: required_role)
else
get_api_key(required_role: required_role)
end
end | [
"def",
"get_auth",
"(",
"required_role",
":",
"Roles",
"::",
"USER",
")",
"if",
"params",
"[",
":token",
"]",
"get_token",
"(",
"required_role",
":",
"required_role",
")",
"else",
"get_api_key",
"(",
"required_role",
":",
"required_role",
")",
"end",
"end"
] | Get auth data from the request. The token takes the precedence. | [
"Get",
"auth",
"data",
"from",
"the",
"request",
".",
"The",
"token",
"takes",
"the",
"precedence",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L305-L311 | train |
jeremyvdw/disqussion | lib/disqussion/client/reactions.rb | Disqussion.Reactions.details | def details(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:reaction => args[0])
options.merge!(:forum => args[1])
response = get('reactions/details', options)
else
puts "#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum"
end
end | ruby | def details(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:reaction => args[0])
options.merge!(:forum => args[1])
response = get('reactions/details', options)
else
puts "#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum"
end
end | [
"def",
"details",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"if",
"args",
".",
"length",
"==",
"2",
"options",
".",
"merge!",
"(",
":reaction",
"=>",
"args",
"[",
"0",
"]",
")",
"options",
".",
"merge!",
"(",
":forum",
"=>",
"args",
"[",
"1",
"]",
")",
"response",
"=",
"get",
"(",
"'reactions/details'",
",",
"options",
")",
"else",
"puts",
"\"#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum\"",
"end",
"end"
] | Returns reaction details
@accessibility: public key, secret key
@methods: GET
@format: json, jsonp
@authenticated: false
@limited: false
@param reaction [Integer] Looks up a reaction by ID.
@param forum [String] Looks up a forum by ID (aka shortname).
@return [Hashie::Rash] Reaction of the forum.
@example Message for post ID 12345678
Disqussion::Client.reactions.detail(12345678,"Hello")
@see: http://disqus.com/api/3.0/reactions/details.json | [
"Returns",
"reaction",
"details"
] | 5ad1b0325b7630daf41eb59fc8acbcb785cbc387 | https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/reactions.rb#L16-L25 | train |
biola/biola-logs | lib/biola_logs/controller_extensions.rb | BiolaLogs.ControllerExtensions.append_info_to_payload | def append_info_to_payload(payload)
super
payload[:session_id] = request.session_options[:id]
payload[:uuid] = request.uuid
payload[:host] = request.host
end | ruby | def append_info_to_payload(payload)
super
payload[:session_id] = request.session_options[:id]
payload[:uuid] = request.uuid
payload[:host] = request.host
end | [
"def",
"append_info_to_payload",
"(",
"payload",
")",
"super",
"payload",
"[",
":session_id",
"]",
"=",
"request",
".",
"session_options",
"[",
":id",
"]",
"payload",
"[",
":uuid",
"]",
"=",
"request",
".",
"uuid",
"payload",
"[",
":host",
"]",
"=",
"request",
".",
"host",
"end"
] | Custom attributes for lograge logging | [
"Custom",
"attributes",
"for",
"lograge",
"logging"
] | 614a0b9181c0c647ccf82d4fcb44d07fc2ab1829 | https://github.com/biola/biola-logs/blob/614a0b9181c0c647ccf82d4fcb44d07fc2ab1829/lib/biola_logs/controller_extensions.rb#L14-L19 | train |
irvingwashington/gem_footprint_analyzer | lib/gem_footprint_analyzer/child_context.rb | GemFootprintAnalyzer.ChildContext.start | def start
RequireSpy.spy_require(transport)
error = try_require(require_string)
return transport.done_and_wait_for_ack unless error
transport.exit_with_error(error)
exit(1)
end | ruby | def start
RequireSpy.spy_require(transport)
error = try_require(require_string)
return transport.done_and_wait_for_ack unless error
transport.exit_with_error(error)
exit(1)
end | [
"def",
"start",
"RequireSpy",
".",
"spy_require",
"(",
"transport",
")",
"error",
"=",
"try_require",
"(",
"require_string",
")",
"return",
"transport",
".",
"done_and_wait_for_ack",
"unless",
"error",
"transport",
".",
"exit_with_error",
"(",
"error",
")",
"exit",
"(",
"1",
")",
"end"
] | Prints the process pid, so it can be grabbed by the supervisor process, inits tranport fifos
and requires requested libraries.
Installs the require-spying code and starts requiring | [
"Prints",
"the",
"process",
"pid",
"so",
"it",
"can",
"be",
"grabbed",
"by",
"the",
"supervisor",
"process",
"inits",
"tranport",
"fifos",
"and",
"requires",
"requested",
"libraries",
".",
"Installs",
"the",
"require",
"-",
"spying",
"code",
"and",
"starts",
"requiring"
] | 19a8892f6baaeb16b1b166144c4f73852396220c | https://github.com/irvingwashington/gem_footprint_analyzer/blob/19a8892f6baaeb16b1b166144c4f73852396220c/lib/gem_footprint_analyzer/child_context.rb#L22-L29 | train |
mattmccray/gumdrop | lib/gumdrop/content.rb | Gumdrop.SpecialContentList.find | def find(uri)
_try_variations_of(uri) do |path|
content= get path
return [content] unless content.nil?
end unless uri.nil?
[]
end | ruby | def find(uri)
_try_variations_of(uri) do |path|
content= get path
return [content] unless content.nil?
end unless uri.nil?
[]
end | [
"def",
"find",
"(",
"uri",
")",
"_try_variations_of",
"(",
"uri",
")",
"do",
"|",
"path",
"|",
"content",
"=",
"get",
"path",
"return",
"[",
"content",
"]",
"unless",
"content",
".",
"nil?",
"end",
"unless",
"uri",
".",
"nil?",
"[",
"]",
"end"
] | Find isn't fuzzy for Special Content. It looks for full
uri or the uri's basename, optionally tacking on @ext | [
"Find",
"isn",
"t",
"fuzzy",
"for",
"Special",
"Content",
".",
"It",
"looks",
"for",
"full",
"uri",
"or",
"the",
"uri",
"s",
"basename",
"optionally",
"tacking",
"on"
] | 7c0998675dbc65e6c7fa0cd580ea0fc3167394fd | https://github.com/mattmccray/gumdrop/blob/7c0998675dbc65e6c7fa0cd580ea0fc3167394fd/lib/gumdrop/content.rb#L277-L283 | train |
chetan/bixby-common | lib/bixby-common/api/json_request.rb | Bixby.JsonRequest.to_s | def to_s(include_params=true)
s = []
s << "JsonRequest:#{self.object_id}"
s << " operation: #{self.operation}"
s << " params: " + MultiJson.dump(self.params) if include_params
s.join("\n")
end | ruby | def to_s(include_params=true)
s = []
s << "JsonRequest:#{self.object_id}"
s << " operation: #{self.operation}"
s << " params: " + MultiJson.dump(self.params) if include_params
s.join("\n")
end | [
"def",
"to_s",
"(",
"include_params",
"=",
"true",
")",
"s",
"=",
"[",
"]",
"s",
"<<",
"\"JsonRequest:#{self.object_id}\"",
"s",
"<<",
"\" operation: #{self.operation}\"",
"s",
"<<",
"\" params: \"",
"+",
"MultiJson",
".",
"dump",
"(",
"self",
".",
"params",
")",
"if",
"include_params",
"s",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Create a new JsonRequest
@param [String] operation Name of operation
@param [Array] params Array of parameters; must ve valid JSON types
Stringify, useful for debugging
@param [Boolean] include_params whether or not to include params in the output (default: true)
@return [String] | [
"Create",
"a",
"new",
"JsonRequest"
] | 3fb8829987b115fc53ec820d97a20b4a8c49b4a2 | https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/api/json_request.rb#L29-L35 | train |
zacscodingclub/balancing_act | lib/balancing_act/server.rb | BalancingAct.Server.valid_params? | def valid_params?(name, size)
return raise TypeError.new("A 'name' should be a string") if name.class != String
return raise TypeError.new("A 'size' should be an integer") if size.class != Integer
true
end | ruby | def valid_params?(name, size)
return raise TypeError.new("A 'name' should be a string") if name.class != String
return raise TypeError.new("A 'size' should be an integer") if size.class != Integer
true
end | [
"def",
"valid_params?",
"(",
"name",
",",
"size",
")",
"return",
"raise",
"TypeError",
".",
"new",
"(",
"\"A 'name' should be a string\"",
")",
"if",
"name",
".",
"class",
"!=",
"String",
"return",
"raise",
"TypeError",
".",
"new",
"(",
"\"A 'size' should be an integer\"",
")",
"if",
"size",
".",
"class",
"!=",
"Integer",
"true",
"end"
] | Validates the params by type. Could add in additional validations in
this method depending on requirements. Raises exception with invalid
types with early return or returns true if params are valid | [
"Validates",
"the",
"params",
"by",
"type",
".",
"Could",
"add",
"in",
"additional",
"validations",
"in",
"this",
"method",
"depending",
"on",
"requirements",
".",
"Raises",
"exception",
"with",
"invalid",
"types",
"with",
"early",
"return",
"or",
"returns",
"true",
"if",
"params",
"are",
"valid"
] | 5a8b86d03b1218192cef23c14533d1dd9264bdc1 | https://github.com/zacscodingclub/balancing_act/blob/5a8b86d03b1218192cef23c14533d1dd9264bdc1/lib/balancing_act/server.rb#L17-L22 | train |
rgeyer/rs_user_policy | lib/rs_user_policy/audit_log.rb | RsUserPolicy.AuditLog.add_entry | def add_entry(email, account, action, changes)
@audit_log[email] = [] unless audit_log[email]
@audit_log[email] << {
:account => account,
:action => action,
:changes => changes
}
end | ruby | def add_entry(email, account, action, changes)
@audit_log[email] = [] unless audit_log[email]
@audit_log[email] << {
:account => account,
:action => action,
:changes => changes
}
end | [
"def",
"add_entry",
"(",
"email",
",",
"account",
",",
"action",
",",
"changes",
")",
"@audit_log",
"[",
"email",
"]",
"=",
"[",
"]",
"unless",
"audit_log",
"[",
"email",
"]",
"@audit_log",
"[",
"email",
"]",
"<<",
"{",
":account",
"=>",
"account",
",",
":action",
"=>",
"action",
",",
":changes",
"=>",
"changes",
"}",
"end"
] | Initializes a new AuditLog
@param [Hash] options A hash of options that impact the audit log filename.
@option options [String] :timestamp The timestamp to append to the filename
@option options [Bool] :dry_run A boolean indicating if this is a dry run
@option options [String] :audit_dir The directory where the audit log should be created
Adds a new entry to the audit log
@param [String] email The email address of the user impacted by the change
@param [String] account The account name impacted by the change
@param [String] action The action performed. Expected options are ['update_permissions', 'created', 'deleted']
@param [String] changes A free form description of the changes | [
"Initializes",
"a",
"new",
"AuditLog"
] | bae3355f1471cc7d28de7992c5d5f4ac39fff68b | https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/audit_log.rb#L57-L64 | train |
mikemackintosh/slackdraft | lib/slackdraft/base.rb | Slackdraft.Base.send! | def send!
# Send the request
request = HTTParty.post(self.target, :body => {
:payload => generate_payload.to_json
})
unless request.code.eql? 200
false
end
true
end | ruby | def send!
# Send the request
request = HTTParty.post(self.target, :body => {
:payload => generate_payload.to_json
})
unless request.code.eql? 200
false
end
true
end | [
"def",
"send!",
"# Send the request",
"request",
"=",
"HTTParty",
".",
"post",
"(",
"self",
".",
"target",
",",
":body",
"=>",
"{",
":payload",
"=>",
"generate_payload",
".",
"to_json",
"}",
")",
"unless",
"request",
".",
"code",
".",
"eql?",
"200",
"false",
"end",
"true",
"end"
] | Send the message! | [
"Send",
"the",
"message!"
] | 4025fe370f468750fdf5a0dc9741871bca897c0a | https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/base.rb#L22-L35 | train |
culturecode/templatr | app/models/templatr/template.rb | Templatr.Template.common_fields_attributes= | def common_fields_attributes=(nested_attributes)
nested_attributes.values.each do |attributes|
common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build
assign_to_or_mark_for_destruction(common_field, attributes, true, {})
end
end | ruby | def common_fields_attributes=(nested_attributes)
nested_attributes.values.each do |attributes|
common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build
assign_to_or_mark_for_destruction(common_field, attributes, true, {})
end
end | [
"def",
"common_fields_attributes",
"=",
"(",
"nested_attributes",
")",
"nested_attributes",
".",
"values",
".",
"each",
"do",
"|",
"attributes",
"|",
"common_field",
"=",
"common_fields",
".",
"find",
"{",
"|",
"field",
"|",
"field",
".",
"id",
".",
"to_s",
"==",
"attributes",
"[",
":id",
"]",
"&&",
"attributes",
"[",
":id",
"]",
".",
"present?",
"}",
"||",
"common_fields",
".",
"build",
"assign_to_or_mark_for_destruction",
"(",
"common_field",
",",
"attributes",
",",
"true",
",",
"{",
"}",
")",
"end",
"end"
] | Ensure all nested attributes for common fields get saved as common fields, and not as template fields | [
"Ensure",
"all",
"nested",
"attributes",
"for",
"common",
"fields",
"get",
"saved",
"as",
"common",
"fields",
"and",
"not",
"as",
"template",
"fields"
] | 0bffb930736b4339fb8a9e8adc080404dc6860d8 | https://github.com/culturecode/templatr/blob/0bffb930736b4339fb8a9e8adc080404dc6860d8/app/models/templatr/template.rb#L25-L30 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.start_time | def start_time
@start_time ||= @events.select { |event|
event.is_a?(RequestWillBeSent)
}.select { |event|
event.request['url'] == @url
}.map { |event|
event.timestamp
}.first
end | ruby | def start_time
@start_time ||= @events.select { |event|
event.is_a?(RequestWillBeSent)
}.select { |event|
event.request['url'] == @url
}.map { |event|
event.timestamp
}.first
end | [
"def",
"start_time",
"@start_time",
"||=",
"@events",
".",
"select",
"{",
"|",
"event",
"|",
"event",
".",
"is_a?",
"(",
"RequestWillBeSent",
")",
"}",
".",
"select",
"{",
"|",
"event",
"|",
"event",
".",
"request",
"[",
"'url'",
"]",
"==",
"@url",
"}",
".",
"map",
"{",
"|",
"event",
"|",
"event",
".",
"timestamp",
"}",
".",
"first",
"end"
] | The seconds since epoch that the request for this document started | [
"The",
"seconds",
"since",
"epoch",
"that",
"the",
"request",
"for",
"this",
"document",
"started"
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L20-L28 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.encoded_bytes | def encoded_bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length }
end | ruby | def encoded_bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length }
end | [
"def",
"encoded_bytes",
"(",
"resource_type",
")",
"@events",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"is_a?",
"(",
"ResponseReceived",
")",
"&&",
"e",
".",
"resource_type",
"==",
"resource_type",
"}",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"request_id",
"}",
".",
"map",
"{",
"|",
"request_id",
"|",
"data_received_for_request",
"(",
"request_id",
")",
"}",
".",
"flatten",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"bytes_sum",
",",
"n",
"|",
"bytes_sum",
"+",
"n",
".",
"encoded_data_length",
"}",
"end"
] | The number of bytes downloaded for a particular resource type. If the
resource was gzipped during transfer then the gzipped size is reported.
The HTTP headers for the response are included in the byte count.
Possible resource types: 'Document','Script', 'Image', 'Stylesheet',
'Other'. | [
"The",
"number",
"of",
"bytes",
"downloaded",
"for",
"a",
"particular",
"resource",
"type",
".",
"If",
"the",
"resource",
"was",
"gzipped",
"during",
"transfer",
"then",
"the",
"gzipped",
"size",
"is",
"reported",
"."
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L60-L68 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.bytes | def bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length }
end | ruby | def bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length }
end | [
"def",
"bytes",
"(",
"resource_type",
")",
"@events",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"is_a?",
"(",
"ResponseReceived",
")",
"&&",
"e",
".",
"resource_type",
"==",
"resource_type",
"}",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"request_id",
"}",
".",
"map",
"{",
"|",
"request_id",
"|",
"data_received_for_request",
"(",
"request_id",
")",
"}",
".",
"flatten",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"bytes_sum",
",",
"n",
"|",
"bytes_sum",
"+",
"n",
".",
"data_length",
"}",
"end"
] | The number of bytes downloaded for a particular resource type. If the
resource was gzipped during transfer then the uncompressed size is
reported.
The HTTP headers for the response are NOT included in the byte count.
Possible resource types: 'Document','Script', 'Image', 'Stylesheet',
'Other'. | [
"The",
"number",
"of",
"bytes",
"downloaded",
"for",
"a",
"particular",
"resource",
"type",
".",
"If",
"the",
"resource",
"was",
"gzipped",
"during",
"transfer",
"then",
"the",
"uncompressed",
"size",
"is",
"reported",
"."
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L79-L87 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.request_count_by_resource | def request_count_by_resource(resource_type)
@events.select {|n|
n.is_a?(ResponseReceived) && n.resource_type == resource_type
}.size
end | ruby | def request_count_by_resource(resource_type)
@events.select {|n|
n.is_a?(ResponseReceived) && n.resource_type == resource_type
}.size
end | [
"def",
"request_count_by_resource",
"(",
"resource_type",
")",
"@events",
".",
"select",
"{",
"|",
"n",
"|",
"n",
".",
"is_a?",
"(",
"ResponseReceived",
")",
"&&",
"n",
".",
"resource_type",
"==",
"resource_type",
"}",
".",
"size",
"end"
] | the number of network requests of a particular resource
type that were required to load this document
Possible resource types: 'Document', 'Script', 'Image', 'Stylesheet',
'Other'. | [
"the",
"number",
"of",
"network",
"requests",
"of",
"a",
"particular",
"resource",
"type",
"that",
"were",
"required",
"to",
"load",
"this",
"document"
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L103-L107 | train |
noted/scholar | lib/scholar/search.rb | Scholar.Search.to_hash | def to_hash
hash = {}
instance_variables.each do |v|
hash[v.to_s[1..-1].to_sym] = instance_variable_get(v)
end
hash[:results].each do |c|
hash[:results][hash[:results].index(c)] = c.to_hash
end
hash
end | ruby | def to_hash
hash = {}
instance_variables.each do |v|
hash[v.to_s[1..-1].to_sym] = instance_variable_get(v)
end
hash[:results].each do |c|
hash[:results][hash[:results].index(c)] = c.to_hash
end
hash
end | [
"def",
"to_hash",
"hash",
"=",
"{",
"}",
"instance_variables",
".",
"each",
"do",
"|",
"v",
"|",
"hash",
"[",
"v",
".",
"to_s",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
"]",
"=",
"instance_variable_get",
"(",
"v",
")",
"end",
"hash",
"[",
":results",
"]",
".",
"each",
"do",
"|",
"c",
"|",
"hash",
"[",
":results",
"]",
"[",
"hash",
"[",
":results",
"]",
".",
"index",
"(",
"c",
")",
"]",
"=",
"c",
".",
"to_hash",
"end",
"hash",
"end"
] | Searches for sources in Google Books.
==== Attributes
* +query+ - The search term.
Return as hash. | [
"Searches",
"for",
"sources",
"in",
"Google",
"Books",
"."
] | 2bfface9d90307d7d3cecfa756f921087407d394 | https://github.com/noted/scholar/blob/2bfface9d90307d7d3cecfa756f921087407d394/lib/scholar/search.rb#L39-L51 | train |
betaworks/slack-bot-manager | lib/slack-bot-manager/client/commands.rb | SlackBotManager.Commands.on_close | def on_close(data, *args)
options = args.extract_options!
options[:code] ||= (data && data.code) || '1000'
disconnect
fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s)
end | ruby | def on_close(data, *args)
options = args.extract_options!
options[:code] ||= (data && data.code) || '1000'
disconnect
fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s)
end | [
"def",
"on_close",
"(",
"data",
",",
"*",
"args",
")",
"options",
"=",
"args",
".",
"extract_options!",
"options",
"[",
":code",
"]",
"||=",
"(",
"data",
"&&",
"data",
".",
"code",
")",
"||",
"'1000'",
"disconnect",
"fail",
"SlackBotManager",
"::",
"ConnectionRateLimited",
"if",
"%w(",
"1008",
"429",
")",
".",
"include?",
"(",
"options",
"[",
":code",
"]",
".",
"to_s",
")",
"end"
] | Handle when connection gets closed | [
"Handle",
"when",
"connection",
"gets",
"closed"
] | cb59bd1c80abd3ede0520017708891486f733e40 | https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/client/commands.rb#L4-L10 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.ox_attr | def ox_attr(name,o={},&block)
new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_attrs << new_attr
ox_accessor new_attr.accessor
end | ruby | def ox_attr(name,o={},&block)
new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_attrs << new_attr
ox_accessor new_attr.accessor
end | [
"def",
"ox_attr",
"(",
"name",
",",
"o",
"=",
"{",
"}",
",",
"&",
"block",
")",
"new_attr",
"=",
"Attr",
".",
"new",
"(",
"name",
",",
"o",
".",
"reverse_merge",
"(",
":tag_proc",
"=>",
"@tag_proc",
")",
",",
"block",
")",
"@ox_attrs",
"<<",
"new_attr",
"ox_accessor",
"new_attr",
".",
"accessor",
"end"
] | Declares a reference to a certain xml attribute.
== Sym Option
[sym] Symbol representing the name of the accessor
=== Default naming
This is what it will use to lookup the attribute if a name isn't defined in :from. For example:
ox_attr :bob
ox_attr :pony
are equivalent to:
ox_attr :bob, :from => 'bob'
ox_attr :pony, :from => 'pony'
=== Boolean attributes
If the name ends in a ?, OxMlk will attempt to coerce the value to true or false,
with true, yes, t and 1 mapping to true and false, no, f and 0 mapping
to false, as shown below:
ox_elem :desirable?
ox_attr :bizzare?, :from => 'BIZZARE'
x = #from_xml(%{
<object BIZZARE="1">
<desirable>False</desirable>
</object>
})
x.desirable?
=> false
x.bizzare?
=> true
When a block is provided the value will be passed to the block
where unexpected values can be handled. If no block is provided
the unexpected value will be returned.
#from_xml(%{
<object BIZZARE="Dunno"\>
}).desirable?
=> "Dunno"
ox_attr :bizzare? do |val|
val.upcase
end
#from_xml(%{
<object BIZZARE="Dunno"\>
}).strange?
=> "DUNNO"
== Blocks
You may also pass a block which manipulates the associated parsed value.
class Muffins
include OxMlk
ox_attr(:count, :from => 'bakers_dozens') {|val| val.to_i * 13 }
end
Blocks are always passed the value after being manipulated by the :as option
and are the last thing to manipulate the XML. This is different than the
ox_elem annotation that is passed an Array.
== Options
=== :as
==== Basic Types
Allows you to specify one of several basic types to return the value as. For example
ox_elem :count, :as => Integer
is equivalent to:
ox_elem(:count) {|val| Integer(val) unless val.empty?}
Such block shorthands for Integer, Float, String, Symbol and Time
are currently available.
If an Array is passed each Type in the array will be applied to the value in order.
=== :from
The name by which the xml value will be found in XML. Default is sym. | [
"Declares",
"a",
"reference",
"to",
"a",
"certain",
"xml",
"attribute",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L123-L127 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.ox_elem | def ox_elem(name,o={},&block)
new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_elems << new_elem
ox_accessor new_elem.accessor
end | ruby | def ox_elem(name,o={},&block)
new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_elems << new_elem
ox_accessor new_elem.accessor
end | [
"def",
"ox_elem",
"(",
"name",
",",
"o",
"=",
"{",
"}",
",",
"&",
"block",
")",
"new_elem",
"=",
"Elem",
".",
"new",
"(",
"name",
",",
"o",
".",
"reverse_merge",
"(",
":tag_proc",
"=>",
"@tag_proc",
")",
",",
"block",
")",
"@ox_elems",
"<<",
"new_elem",
"ox_accessor",
"new_elem",
".",
"accessor",
"end"
] | Declares a reference to a certain xml element or a typed collection of elements.
== Sym Option
[sym] Symbol representing the name of the accessor.
=== Default naming
This name will be the default node searched for, if no other is declared. For example:
ox_elem :bob
ox_elem :pony
are equivalent to:
ox_elem :bob, :from => 'bob'
ox_elem :pony, :from => 'pony'
=== Boolean attributes
If the name ends in a ?, OxMlk will attempt to coerce the value to true or false,
with true, yes, t and 1 mapping to true and false, no, f and 0 mapping
to false, as shown below:
ox_elem :desirable?
ox_attr :bizzare?, :from => 'BIZZARE'
x = #from_xml(%{
<object BIZZARE="1">
<desirable>False</desirable>
</object>
})
x.desirable?
=> false
x.bizzare?
=> true
When a block is provided the value will be passed to the block
where unexpected values can be handled. If no block is provided
the unexpected value will be returned.
#from_xml(%{
<object>
<desirable>Dunno</desirable>
</object>
}).desirable?
=> "Dunno"
ox_elem :strange? do |val|
val.upcase
end
#from_xml(%{
<object>
<strange>Dunno</strange>
</object>
}).strange?
=> "DUNNO"
== Blocks
You may also pass a block which manipulates the associated parsed value.
class Muffins
include OxMlk
ox_elem(:count, :from => 'bakers_dozens') {|val| val.first.to_i * 13 }
end
Blocks are always passed an Array and are the last thing to manipulate the XML.
The array will include all elements already manipulated by anything passed to
the :as option. If the :as option is an Array and no block is passed then the
Array is returned unmodified. If the :as option is nil or is not an Array then
only the first element is
== Options
=== :as
==== Basic Types
Allows you to specify one of several basic types to return the value as. For example
ox_elem :count, :as => Integer
is equivalent to:
ox_elem(:count) {|val| Integer(val.first) unless val.first.empty?}
Such block shorthands for Integer, Float, String, Symbol and Time
are currently available.
To reference many elements, put the desired type in a literal array. e.g.:
ox_elem :counts, :as => [Integer]
Even an array of text nodes can be specified with :as => []
ox_elem :quotes, :as => []
=== Other OxMlk Classes
Declares an accessor that represents another OxMlk class as child XML element
(one-to-one or composition) or array of child elements (one-to-many or
aggregation) of this type. Default is one-to-one. For one-to-many, simply pass the class
as the only element in an array. You can also put several OxMlk classes in an Array that
will act like a polymorphic one-to-many association.
Composition example:
<book>
<publisher>
<name>Pragmatic Bookshelf</name>
</publisher>
</book>
Can be mapped using the following code:
class Book
include OxMlk
ox_elem :publisher, :as => Publisher
end
Aggregation example:
<library>
<books>
<book/>
<book/>
</books>
</library>
Can be mapped using the following code:
class Library
include OxMlk
ox_elem :books, :as => [Book], :in => 'books'
end
If you don't have the <books> tag to wrap around the list of <book> tags:
<library>
<name>Ruby books</name>
<book/>
<book/>
</library>
You can skip the wrapper argument:
ox_elem :books, :as => [Book]
==== Hash
Unlike ROXML, OxMlk doesn't do anything special for hashes. However OxMlk
applies :as to each element and the block once to the Array of elements.
This means OxMlk can support setting hashes but it is more of a manual process.
I am looking for a easier method but for now here are a few examples:
===== Hash of element contents
For xml such as this:
<dictionary>
<definition>
<word/>
<meaning/>
</definition>
<definition>
<word/>
<meaning/>
</definition>
</dictionary>
This is actually one of the more complex ones. It uses the :raw keyword to pass the block an array of LibXML::XML::Nodes
ox_elem(:definitions, :from => 'definition', :as => [:raw]) do |vals|
Hash[*vals.map {}|val| [val.search('word').content,val.search('meaning').content]}.flatten]
end
===== Hash of :content
For xml such as this:
<dictionary>
<definition word="quaquaversally">adjective: (of a geological formation) sloping downward from the center in all directions.</definition>
<definition word="tergiversate">To use evasions or ambiguities; equivocate.</definition>
</dictionary>
This one can also be accomplished with the :raw keyword and a fancy block.
ox_elem(:definitions, :from => 'definition', :as => [:raw]) {|x| Hash[*x.map {|val| [val['word'],val.content] }.flatten]}
===== Hash of :name
For xml such as this:
<dictionary>
<quaquaversally>adjective: (of a geological formation) sloping downward from the center in all directions.</quaquaversally>
<tergiversate>To use evasions or ambiguities; equivocate.</tergiversate>
</dictionary>
This one requires some fancy xpath in :from to grab all the elements
ox_elem(:definitions, :from => './*', :as => [:raw]) {|x| Hash[*x.map {|val| [val.name,val.content] }.flatten]}
=== :from
The name by which the xml value will be found in XML. Default is sym.
This value may also include XPath notation.
==== :from => :content
When :from is set to :content, this refers to the content of the current node,
rather than a sub-node. It is equivalent to :from => '.'
Example:
class Contributor
ox_elem :name, :from => :content
ox_attr :role
end
To map:
<contributor role="editor">James Wick</contributor>
=== :in
An optional name of a wrapping tag for this XML accessor.
This can include other xpath values, which will be joined with :from with a '/' | [
"Declares",
"a",
"reference",
"to",
"a",
"certain",
"xml",
"element",
"or",
"a",
"typed",
"collection",
"of",
"elements",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L335-L339 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.ox_tag | def ox_tag(tag=nil,&block)
raise 'you can only set tag or a block, not both.' if tag && block
@base_tag ||= self.to_s.split('::').last
@ox_tag ||= case tag
when String
tag
when Proc, Symbol, nil
@tag_proc = (block || tag || :to_s).to_proc
@tag_proc.call(@base_tag) rescue tag.to_s
else
raise 'you passed something weird'
end
end | ruby | def ox_tag(tag=nil,&block)
raise 'you can only set tag or a block, not both.' if tag && block
@base_tag ||= self.to_s.split('::').last
@ox_tag ||= case tag
when String
tag
when Proc, Symbol, nil
@tag_proc = (block || tag || :to_s).to_proc
@tag_proc.call(@base_tag) rescue tag.to_s
else
raise 'you passed something weird'
end
end | [
"def",
"ox_tag",
"(",
"tag",
"=",
"nil",
",",
"&",
"block",
")",
"raise",
"'you can only set tag or a block, not both.'",
"if",
"tag",
"&&",
"block",
"@base_tag",
"||=",
"self",
".",
"to_s",
".",
"split",
"(",
"'::'",
")",
".",
"last",
"@ox_tag",
"||=",
"case",
"tag",
"when",
"String",
"tag",
"when",
"Proc",
",",
"Symbol",
",",
"nil",
"@tag_proc",
"=",
"(",
"block",
"||",
"tag",
"||",
":to_s",
")",
".",
"to_proc",
"@tag_proc",
".",
"call",
"(",
"@base_tag",
")",
"rescue",
"tag",
".",
"to_s",
"else",
"raise",
"'you passed something weird'",
"end",
"end"
] | Sets the name of the XML element that represents this class. Use this
to override the default camelcase class name.
Example:
class BookWithPublisher
ox_tag 'book'
end
Without the ox_tag annotation, the XML mapped tag would have been 'BookWithPublisher'.
Most xml documents have a consistent naming convention, for example, the node and
and attribute names might appear in CamelCase. ox_tag enables you to adapt
the oxmlk default names for this object to suit this convention. For example,
if I had a document like so:
<XmlDoc>
<MyPreciousData />
<MoreToSee />
</XmlDoc>
Then I could access it's contents by defining the following class:
class XmlDoc
include OxMlk
ox_tag :camelcase
ox_elem :my_precious_data
ox_elem :more_to_see
end
You may supply a block or any #to_proc-able object as the argument,
and it will be called against the default node and attribute names before searching
the document. Here are some example declaration:
ox_tag :upcase
ox_tag &:camelcase
ox_tag {|val| val.gsub('_', '').downcase }
See ActiveSupport::CoreExtensions::String::Inflections for more prepackaged formats | [
"Sets",
"the",
"name",
"of",
"the",
"XML",
"element",
"that",
"represents",
"this",
"class",
".",
"Use",
"this",
"to",
"override",
"the",
"default",
"camelcase",
"class",
"name",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L380-L393 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.from_xml | def from_xml(data)
xml = XML::Node.from(data)
raise 'invalid XML' unless xml.name == ox_tag
returning new do |ox|
(ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))}
ox.send(:after_parse) if ox.respond_to?(:after_parse)
end
end | ruby | def from_xml(data)
xml = XML::Node.from(data)
raise 'invalid XML' unless xml.name == ox_tag
returning new do |ox|
(ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))}
ox.send(:after_parse) if ox.respond_to?(:after_parse)
end
end | [
"def",
"from_xml",
"(",
"data",
")",
"xml",
"=",
"XML",
"::",
"Node",
".",
"from",
"(",
"data",
")",
"raise",
"'invalid XML'",
"unless",
"xml",
".",
"name",
"==",
"ox_tag",
"returning",
"new",
"do",
"|",
"ox",
"|",
"(",
"ox_attrs",
"+",
"ox_elems",
")",
".",
"each",
"{",
"|",
"e",
"|",
"ox",
".",
"send",
"(",
"e",
".",
"setter",
",",
"e",
".",
"from_xml",
"(",
"xml",
")",
")",
"}",
"ox",
".",
"send",
"(",
":after_parse",
")",
"if",
"ox",
".",
"respond_to?",
"(",
":after_parse",
")",
"end",
"end"
] | Returns a new instance from XML
@param [XML::Document,XML::Node,File,Pathname,URI,String] data
The xml data used to create a new instance.
@return New instance generated from xml data passed in.
Attr and Elem definitions are used to translate the xml to new object. | [
"Returns",
"a",
"new",
"instance",
"from",
"XML"
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L405-L413 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.to_xml | def to_xml(data)
ox = XML::Node.new(ox_tag)
wrappers = {}
ox_elems.each do |elem|
if elem.in
wrappers[elem.in] ||= XML::Node.new elem.in
elem.to_xml(data).each {|e| wrappers[elem.in] << e}
else
elem.to_xml(data).each {|e| ox << e}
end
end
wrappers.each {|k,v| ox << v}
ox_attrs.each do |a|
val = data.send(a.accessor).to_s
ox[a.tag]= val if val.present?
end
ox
end | ruby | def to_xml(data)
ox = XML::Node.new(ox_tag)
wrappers = {}
ox_elems.each do |elem|
if elem.in
wrappers[elem.in] ||= XML::Node.new elem.in
elem.to_xml(data).each {|e| wrappers[elem.in] << e}
else
elem.to_xml(data).each {|e| ox << e}
end
end
wrappers.each {|k,v| ox << v}
ox_attrs.each do |a|
val = data.send(a.accessor).to_s
ox[a.tag]= val if val.present?
end
ox
end | [
"def",
"to_xml",
"(",
"data",
")",
"ox",
"=",
"XML",
"::",
"Node",
".",
"new",
"(",
"ox_tag",
")",
"wrappers",
"=",
"{",
"}",
"ox_elems",
".",
"each",
"do",
"|",
"elem",
"|",
"if",
"elem",
".",
"in",
"wrappers",
"[",
"elem",
".",
"in",
"]",
"||=",
"XML",
"::",
"Node",
".",
"new",
"elem",
".",
"in",
"elem",
".",
"to_xml",
"(",
"data",
")",
".",
"each",
"{",
"|",
"e",
"|",
"wrappers",
"[",
"elem",
".",
"in",
"]",
"<<",
"e",
"}",
"else",
"elem",
".",
"to_xml",
"(",
"data",
")",
".",
"each",
"{",
"|",
"e",
"|",
"ox",
"<<",
"e",
"}",
"end",
"end",
"wrappers",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"ox",
"<<",
"v",
"}",
"ox_attrs",
".",
"each",
"do",
"|",
"a",
"|",
"val",
"=",
"data",
".",
"send",
"(",
"a",
".",
"accessor",
")",
".",
"to_s",
"ox",
"[",
"a",
".",
"tag",
"]",
"=",
"val",
"if",
"val",
".",
"present?",
"end",
"ox",
"end"
] | Returns XML generated from an instance based on Attr & Elem definitions.
@param [Object] data An instance used to populate XML
@return [XML::Node] Generated XML::Node | [
"Returns",
"XML",
"generated",
"from",
"an",
"instance",
"based",
"on",
"Attr",
"&",
"Elem",
"definitions",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L429-L450 | train |
urso/rb_prob | lib/prob.rb | Probably.Distribution.pick | def pick
tst = rand
sum = 0
@map.each do |value, prob|
sum += prob
return value,prob if tst < sum
end
return nil
end | ruby | def pick
tst = rand
sum = 0
@map.each do |value, prob|
sum += prob
return value,prob if tst < sum
end
return nil
end | [
"def",
"pick",
"tst",
"=",
"rand",
"sum",
"=",
"0",
"@map",
".",
"each",
"do",
"|",
"value",
",",
"prob",
"|",
"sum",
"+=",
"prob",
"return",
"value",
",",
"prob",
"if",
"tst",
"<",
"sum",
"end",
"return",
"nil",
"end"
] | randomly pick a key-value with respect to its probability
in given distribution | [
"randomly",
"pick",
"a",
"key",
"-",
"value",
"with",
"respect",
"to",
"its",
"probability",
"in",
"given",
"distribution"
] | f7c448a15a40c26ce9a4424151a0f4942e544389 | https://github.com/urso/rb_prob/blob/f7c448a15a40c26ce9a4424151a0f4942e544389/lib/prob.rb#L115-L123 | train |
urso/rb_prob | lib/prob.rb | Probably.Distribution.variance | def variance
expected = self.expectation
@map.reduce(0) {|sum, (value,p)|
tmp = (value.to_f - expectation)
sum + tmp * tmp * p
}
end | ruby | def variance
expected = self.expectation
@map.reduce(0) {|sum, (value,p)|
tmp = (value.to_f - expectation)
sum + tmp * tmp * p
}
end | [
"def",
"variance",
"expected",
"=",
"self",
".",
"expectation",
"@map",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"(",
"value",
",",
"p",
")",
"|",
"tmp",
"=",
"(",
"value",
".",
"to_f",
"-",
"expectation",
")",
"sum",
"+",
"tmp",
"*",
"tmp",
"*",
"p",
"}",
"end"
] | computes variance given that keys in distribution
are numeric | [
"computes",
"variance",
"given",
"that",
"keys",
"in",
"distribution",
"are",
"numeric"
] | f7c448a15a40c26ce9a4424151a0f4942e544389 | https://github.com/urso/rb_prob/blob/f7c448a15a40c26ce9a4424151a0f4942e544389/lib/prob.rb#L214-L220 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.transform | def transform(*keys)
raise ArgumentError, "requires a block" unless block_given?
keys.each do |key|
items.each do |item|
item[key] = yield(item[key]) || item[key]
end
end
end | ruby | def transform(*keys)
raise ArgumentError, "requires a block" unless block_given?
keys.each do |key|
items.each do |item|
item[key] = yield(item[key]) || item[key]
end
end
end | [
"def",
"transform",
"(",
"*",
"keys",
")",
"raise",
"ArgumentError",
",",
"\"requires a block\"",
"unless",
"block_given?",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"item",
"[",
"key",
"]",
"=",
"yield",
"(",
"item",
"[",
"key",
"]",
")",
"||",
"item",
"[",
"key",
"]",
"end",
"end",
"end"
] | Transform must be used inside an `emit` block.
It can be used to alter named keys within the item set
Usage:
emit do
transform :name, :description do |name|
name.gsub(/\302/, "")
end
end
In quasi-english: The result of the block is returned and set to each
of the :name and :description keys in the result set. | [
"Transform",
"must",
"be",
"used",
"inside",
"an",
"emit",
"block",
".",
"It",
"can",
"be",
"used",
"to",
"alter",
"named",
"keys",
"within",
"the",
"item",
"set"
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L87-L94 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.method_missing | def method_missing(symbol, *args, &block)
ivar = "@#{symbol}"
if args.empty?
return instance_variable_get(ivar) || super
else
instance_variable_set(ivar, args.pop)
end
return self
end | ruby | def method_missing(symbol, *args, &block)
ivar = "@#{symbol}"
if args.empty?
return instance_variable_get(ivar) || super
else
instance_variable_set(ivar, args.pop)
end
return self
end | [
"def",
"method_missing",
"(",
"symbol",
",",
"*",
"args",
",",
"&",
"block",
")",
"ivar",
"=",
"\"@#{symbol}\"",
"if",
"args",
".",
"empty?",
"return",
"instance_variable_get",
"(",
"ivar",
")",
"||",
"super",
"else",
"instance_variable_set",
"(",
"ivar",
",",
"args",
".",
"pop",
")",
"end",
"return",
"self",
"end"
] | Used to store or retreive variables that are used to query services.
Usage:
Smoke.twitter.username("benschwarz").output
As you can see, the method is chainable, many properties can be
set at once, although it may be cleaner to use the method argument method:
Demo:
Smoke.twitter(:username => "benschwarz").output | [
"Used",
"to",
"store",
"or",
"retreive",
"variables",
"that",
"are",
"used",
"to",
"query",
"services",
"."
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L145-L155 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.sort | def sort(key)
@items = @items.sort_by{|i| i[key] }
rescue NoMethodError => e
Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set"
end | ruby | def sort(key)
@items = @items.sort_by{|i| i[key] }
rescue NoMethodError => e
Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set"
end | [
"def",
"sort",
"(",
"key",
")",
"@items",
"=",
"@items",
".",
"sort_by",
"{",
"|",
"i",
"|",
"i",
"[",
"key",
"]",
"}",
"rescue",
"NoMethodError",
"=>",
"e",
"Smoke",
".",
"log",
".",
"info",
"\"You're trying to sort by \\\"#{key}\\\" but it does not exist in your item set\"",
"end"
] | Re-sort items by a particular key
Sort must be used inside an `emit` block. | [
"Re",
"-",
"sort",
"items",
"by",
"a",
"particular",
"key",
"Sort",
"must",
"be",
"used",
"inside",
"an",
"emit",
"block",
"."
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L159-L163 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.keep | def keep(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? false : true }
end | ruby | def keep(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? false : true }
end | [
"def",
"keep",
"(",
"key",
",",
"matcher",
")",
"@items",
".",
"reject!",
"{",
"|",
"i",
"|",
"(",
"i",
"[",
"key",
"]",
"=~",
"matcher",
")",
"?",
"false",
":",
"true",
"}",
"end"
] | Keep items that match the regex
Usage (block, during initialization):
Smoke.yql(:ruby) do
...
emit do
keep(:title, /tuesday/i)
end
end
Keep must be used inside an `emit` block. | [
"Keep",
"items",
"that",
"match",
"the",
"regex"
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L192-L194 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.discard | def discard(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? true : false }
end | ruby | def discard(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? true : false }
end | [
"def",
"discard",
"(",
"key",
",",
"matcher",
")",
"@items",
".",
"reject!",
"{",
"|",
"i",
"|",
"(",
"i",
"[",
"key",
"]",
"=~",
"matcher",
")",
"?",
"true",
":",
"false",
"}",
"end"
] | Discard items that do not match the regex
Usage (block, during initialization):
Smoke.yql(:ruby) do
...
emit do
discard(:title, /tuesday/i)
end
end
Discard must be used inside an `emit` block. | [
"Discard",
"items",
"that",
"do",
"not",
"match",
"the",
"regex"
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L206-L208 | train |
madx/roy | lib/roy/context.rb | Roy.Context.prepare! | def prepare!(env)
@env = env
@request = Rack::Request.new(env)
@response = Rack::Response.new
@headers = @response.header
@params = @request.GET.merge(@request.POST)
@params.default_proc = proc do |hash, key|
hash[key.to_s] if Symbol === key
end
end | ruby | def prepare!(env)
@env = env
@request = Rack::Request.new(env)
@response = Rack::Response.new
@headers = @response.header
@params = @request.GET.merge(@request.POST)
@params.default_proc = proc do |hash, key|
hash[key.to_s] if Symbol === key
end
end | [
"def",
"prepare!",
"(",
"env",
")",
"@env",
"=",
"env",
"@request",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"@response",
"=",
"Rack",
"::",
"Response",
".",
"new",
"@headers",
"=",
"@response",
".",
"header",
"@params",
"=",
"@request",
".",
"GET",
".",
"merge",
"(",
"@request",
".",
"POST",
")",
"@params",
".",
"default_proc",
"=",
"proc",
"do",
"|",
"hash",
",",
"key",
"|",
"hash",
"[",
"key",
".",
"to_s",
"]",
"if",
"Symbol",
"===",
"key",
"end",
"end"
] | Creates a new Context object.
@param app the context's application
Initializes the attributes based on an environment.
@param env the environment to use | [
"Creates",
"a",
"new",
"Context",
"object",
"."
] | 7f9d96b146c15c7b2d3f4019a8a2078475983186 | https://github.com/madx/roy/blob/7f9d96b146c15c7b2d3f4019a8a2078475983186/lib/roy/context.rb#L43-L52 | train |
mikemackintosh/slackdraft | lib/slackdraft/attachment.rb | Slackdraft.Attachment.generate_attachment | def generate_attachment
payload = {}
payload[:fallback] = self.fallback unless self.fallback.nil?
payload[:color] = self.color unless self.color.nil?
payload[:pretext] = self.pretext unless self.pretext.nil?
payload[:author_name] = self.author_name unless self.author_name.nil?
payload[:author_link] = self.author_link unless self.author_link.nil?
payload[:author_icon] = self.author_icon unless self.author_icon.nil?
payload[:title] = self.title unless self.title.nil?
payload[:title_link] = self.title_link unless self.title_link.nil?
payload[:text] = self.message unless self.message.nil?
unless self.fields.nil?
payload[:fields] = self.fields if self.fields.length > 0
end
payload[:image_url] = self.image_url unless self.image_url.nil?
payload
end | ruby | def generate_attachment
payload = {}
payload[:fallback] = self.fallback unless self.fallback.nil?
payload[:color] = self.color unless self.color.nil?
payload[:pretext] = self.pretext unless self.pretext.nil?
payload[:author_name] = self.author_name unless self.author_name.nil?
payload[:author_link] = self.author_link unless self.author_link.nil?
payload[:author_icon] = self.author_icon unless self.author_icon.nil?
payload[:title] = self.title unless self.title.nil?
payload[:title_link] = self.title_link unless self.title_link.nil?
payload[:text] = self.message unless self.message.nil?
unless self.fields.nil?
payload[:fields] = self.fields if self.fields.length > 0
end
payload[:image_url] = self.image_url unless self.image_url.nil?
payload
end | [
"def",
"generate_attachment",
"payload",
"=",
"{",
"}",
"payload",
"[",
":fallback",
"]",
"=",
"self",
".",
"fallback",
"unless",
"self",
".",
"fallback",
".",
"nil?",
"payload",
"[",
":color",
"]",
"=",
"self",
".",
"color",
"unless",
"self",
".",
"color",
".",
"nil?",
"payload",
"[",
":pretext",
"]",
"=",
"self",
".",
"pretext",
"unless",
"self",
".",
"pretext",
".",
"nil?",
"payload",
"[",
":author_name",
"]",
"=",
"self",
".",
"author_name",
"unless",
"self",
".",
"author_name",
".",
"nil?",
"payload",
"[",
":author_link",
"]",
"=",
"self",
".",
"author_link",
"unless",
"self",
".",
"author_link",
".",
"nil?",
"payload",
"[",
":author_icon",
"]",
"=",
"self",
".",
"author_icon",
"unless",
"self",
".",
"author_icon",
".",
"nil?",
"payload",
"[",
":title",
"]",
"=",
"self",
".",
"title",
"unless",
"self",
".",
"title",
".",
"nil?",
"payload",
"[",
":title_link",
"]",
"=",
"self",
".",
"title_link",
"unless",
"self",
".",
"title_link",
".",
"nil?",
"payload",
"[",
":text",
"]",
"=",
"self",
".",
"message",
"unless",
"self",
".",
"message",
".",
"nil?",
"unless",
"self",
".",
"fields",
".",
"nil?",
"payload",
"[",
":fields",
"]",
"=",
"self",
".",
"fields",
"if",
"self",
".",
"fields",
".",
"length",
">",
"0",
"end",
"payload",
"[",
":image_url",
"]",
"=",
"self",
".",
"image_url",
"unless",
"self",
".",
"image_url",
".",
"nil?",
"payload",
"end"
] | Generate the payload for slack attachments | [
"Generate",
"the",
"payload",
"for",
"slack",
"attachments"
] | 4025fe370f468750fdf5a0dc9741871bca897c0a | https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/attachment.rb#L34-L53 | train |
Deradon/Rdcpu16 | lib/dcpu16/screen.rb | DCPU16.Screen.frame | def frame
return @frame if @frame
chars = []
# 4 corners
chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft
chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight
chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) # BottomLeft
chars << Char.new(0x23, @x_offset + @width, @y_offset + @height) # BottomRight
# horiz
@width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset - 1) }
@width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset + @height) }
# vertical
@height.times { |y| chars << Char.new(0x7c, @x_offset - 1, y + @y_offset) }
@height.times { |y| chars << Char.new(0x7c, @x_offset + @width, y + @y_offset) }
@frame = ""
@frame << chars.join
end | ruby | def frame
return @frame if @frame
chars = []
# 4 corners
chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft
chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight
chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) # BottomLeft
chars << Char.new(0x23, @x_offset + @width, @y_offset + @height) # BottomRight
# horiz
@width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset - 1) }
@width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset + @height) }
# vertical
@height.times { |y| chars << Char.new(0x7c, @x_offset - 1, y + @y_offset) }
@height.times { |y| chars << Char.new(0x7c, @x_offset + @width, y + @y_offset) }
@frame = ""
@frame << chars.join
end | [
"def",
"frame",
"return",
"@frame",
"if",
"@frame",
"chars",
"=",
"[",
"]",
"# 4 corners",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x23",
",",
"@x_offset",
"-",
"1",
",",
"@y_offset",
"-",
"1",
")",
"# TopLeft",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x23",
",",
"@x_offset",
"+",
"@width",
",",
"@y_offset",
"-",
"1",
")",
"# TopRight",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x23",
",",
"@x_offset",
"-",
"1",
",",
"@y_offset",
"+",
"@height",
")",
"# BottomLeft",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x23",
",",
"@x_offset",
"+",
"@width",
",",
"@y_offset",
"+",
"@height",
")",
"# BottomRight",
"# horiz",
"@width",
".",
"times",
"{",
"|",
"x",
"|",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x2d",
",",
"x",
"+",
"@x_offset",
",",
"@y_offset",
"-",
"1",
")",
"}",
"@width",
".",
"times",
"{",
"|",
"x",
"|",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x2d",
",",
"x",
"+",
"@x_offset",
",",
"@y_offset",
"+",
"@height",
")",
"}",
"# vertical",
"@height",
".",
"times",
"{",
"|",
"y",
"|",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x7c",
",",
"@x_offset",
"-",
"1",
",",
"y",
"+",
"@y_offset",
")",
"}",
"@height",
".",
"times",
"{",
"|",
"y",
"|",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x7c",
",",
"@x_offset",
"+",
"@width",
",",
"y",
"+",
"@y_offset",
")",
"}",
"@frame",
"=",
"\"\"",
"@frame",
"<<",
"chars",
".",
"join",
"end"
] | Use a fancy border around console | [
"Use",
"a",
"fancy",
"border",
"around",
"console"
] | a4460927aa64c2a514c57993e8ea13f5b48377e9 | https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/screen.rb#L73-L92 | train |
Deradon/Rdcpu16 | lib/dcpu16/screen.rb | DCPU16.Screen.update | def update(offset, value)
return unless (memory_offset..memory_offset_end).include?(offset)
@to_s = nil
diff = offset - @memory_offset
h = diff / @width
w = diff % @width
@chars[diff] = Char.new(value, w + @x_offset, h + @y_offset)
print @chars[diff]
changed
notify_observers(self)
print @chars[diff]
end | ruby | def update(offset, value)
return unless (memory_offset..memory_offset_end).include?(offset)
@to_s = nil
diff = offset - @memory_offset
h = diff / @width
w = diff % @width
@chars[diff] = Char.new(value, w + @x_offset, h + @y_offset)
print @chars[diff]
changed
notify_observers(self)
print @chars[diff]
end | [
"def",
"update",
"(",
"offset",
",",
"value",
")",
"return",
"unless",
"(",
"memory_offset",
"..",
"memory_offset_end",
")",
".",
"include?",
"(",
"offset",
")",
"@to_s",
"=",
"nil",
"diff",
"=",
"offset",
"-",
"@memory_offset",
"h",
"=",
"diff",
"/",
"@width",
"w",
"=",
"diff",
"%",
"@width",
"@chars",
"[",
"diff",
"]",
"=",
"Char",
".",
"new",
"(",
"value",
",",
"w",
"+",
"@x_offset",
",",
"h",
"+",
"@y_offset",
")",
"print",
"@chars",
"[",
"diff",
"]",
"changed",
"notify_observers",
"(",
"self",
")",
"print",
"@chars",
"[",
"diff",
"]",
"end"
] | Callback from observed memory | [
"Callback",
"from",
"observed",
"memory"
] | a4460927aa64c2a514c57993e8ea13f5b48377e9 | https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/screen.rb#L95-L107 | train |
bumbleworks/bumbleworks | lib/bumbleworks/configuration.rb | Bumbleworks.Configuration.add_storage_adapter | def add_storage_adapter(adapter)
raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless
[:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) }
@storage_adapters << adapter
@storage_adapters
end | ruby | def add_storage_adapter(adapter)
raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless
[:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) }
@storage_adapters << adapter
@storage_adapters
end | [
"def",
"add_storage_adapter",
"(",
"adapter",
")",
"raise",
"ArgumentError",
",",
"\"#{adapter} is not a Bumbleworks storage adapter\"",
"unless",
"[",
":driver",
",",
":use?",
",",
":new_storage",
",",
":allow_history_storage?",
",",
":storage_class",
",",
":display_name",
"]",
".",
"all?",
"{",
"|",
"m",
"|",
"adapter",
".",
"respond_to?",
"(",
"m",
")",
"}",
"@storage_adapters",
"<<",
"adapter",
"@storage_adapters",
"end"
] | Add a storage adapter to the set of possible adapters. Takes an object
that responds to `driver`, `use?`, `storage_class`, and `display_name`. | [
"Add",
"a",
"storage",
"adapter",
"to",
"the",
"set",
"of",
"possible",
"adapters",
".",
"Takes",
"an",
"object",
"that",
"responds",
"to",
"driver",
"use?",
"storage_class",
"and",
"display_name",
"."
] | 6f63992e921dcf8371d4453ef9e7b4e3322cc360 | https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L263-L269 | train |
bumbleworks/bumbleworks | lib/bumbleworks/configuration.rb | Bumbleworks.Configuration.storage_adapter | def storage_adapter
@storage_adapter ||= begin
all_adapters = storage_adapters
raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty?
adapter = all_adapters.detect do |potential_adapter|
potential_adapter.use?(storage)
end
raise UndefinedSetting, "Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}" unless adapter
adapter
end
end | ruby | def storage_adapter
@storage_adapter ||= begin
all_adapters = storage_adapters
raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty?
adapter = all_adapters.detect do |potential_adapter|
potential_adapter.use?(storage)
end
raise UndefinedSetting, "Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}" unless adapter
adapter
end
end | [
"def",
"storage_adapter",
"@storage_adapter",
"||=",
"begin",
"all_adapters",
"=",
"storage_adapters",
"raise",
"UndefinedSetting",
",",
"\"No storage adapters configured\"",
"if",
"all_adapters",
".",
"empty?",
"adapter",
"=",
"all_adapters",
".",
"detect",
"do",
"|",
"potential_adapter",
"|",
"potential_adapter",
".",
"use?",
"(",
"storage",
")",
"end",
"raise",
"UndefinedSetting",
",",
"\"Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}\"",
"unless",
"adapter",
"adapter",
"end",
"end"
] | If storage_adapter is not explicitly set, find first registered adapter that
can use Bumbleworks.storage. | [
"If",
"storage_adapter",
"is",
"not",
"explicitly",
"set",
"find",
"first",
"registered",
"adapter",
"that",
"can",
"use",
"Bumbleworks",
".",
"storage",
"."
] | 6f63992e921dcf8371d4453ef9e7b4e3322cc360 | https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L274-L284 | train |
bumbleworks/bumbleworks | lib/bumbleworks/configuration.rb | Bumbleworks.Configuration.look_up_configured_path | def look_up_configured_path(path_type, options = {})
return @cached_paths[path_type] if @cached_paths.has_key?(path_type)
if user_defined_path = user_configured_path(path_type)
if path_resolves?(user_defined_path, :file => options[:file])
return user_defined_path
else
raise Bumbleworks::InvalidSetting, "#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})"
end
end
first_existing_default_path(options[:defaults], :file => options[:file])
end | ruby | def look_up_configured_path(path_type, options = {})
return @cached_paths[path_type] if @cached_paths.has_key?(path_type)
if user_defined_path = user_configured_path(path_type)
if path_resolves?(user_defined_path, :file => options[:file])
return user_defined_path
else
raise Bumbleworks::InvalidSetting, "#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})"
end
end
first_existing_default_path(options[:defaults], :file => options[:file])
end | [
"def",
"look_up_configured_path",
"(",
"path_type",
",",
"options",
"=",
"{",
"}",
")",
"return",
"@cached_paths",
"[",
"path_type",
"]",
"if",
"@cached_paths",
".",
"has_key?",
"(",
"path_type",
")",
"if",
"user_defined_path",
"=",
"user_configured_path",
"(",
"path_type",
")",
"if",
"path_resolves?",
"(",
"user_defined_path",
",",
":file",
"=>",
"options",
"[",
":file",
"]",
")",
"return",
"user_defined_path",
"else",
"raise",
"Bumbleworks",
"::",
"InvalidSetting",
",",
"\"#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})\"",
"end",
"end",
"first_existing_default_path",
"(",
"options",
"[",
":defaults",
"]",
",",
":file",
"=>",
"options",
"[",
":file",
"]",
")",
"end"
] | If the user explicitly declared a path, raises an exception if the
path was not found. Missing default paths do not raise an exception
since no paths are required. | [
"If",
"the",
"user",
"explicitly",
"declared",
"a",
"path",
"raises",
"an",
"exception",
"if",
"the",
"path",
"was",
"not",
"found",
".",
"Missing",
"default",
"paths",
"do",
"not",
"raise",
"an",
"exception",
"since",
"no",
"paths",
"are",
"required",
"."
] | 6f63992e921dcf8371d4453ef9e7b4e3322cc360 | https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L350-L361 | train |
ronen/hash_keyword_args | lib/hash_keyword_args/hash.rb | HashKeywordArgs.Hash.keyword_args | def keyword_args(*args)
argshash = args[-1].is_a?(Hash) ? args.pop : {}
argshash = args.hashify(:optional).merge(argshash)
others_OK = argshash.delete(:OTHERS)
ret = {}
# defaults, required, and checked
required = []
check = {}
argshash.each do |key, val|
# construct fleshed-out attribute hash for all args
attrs = case val
when Hash
val[:default] ||= [] if val[:enumerable]
val
when :required
{ :required => true }
when :optional
{}
when :enumerable
{ :enumerable => true, :default => [] }
when Array
{ :valid => val }
when Class, Module
{ :valid => val }
else
{ :default => val }
end
# extract required flag, validity checks, and default vlues from attribute hash
required << key if attrs[:required]
check[key] = case valid = attrs[:valid]
when Enumerable
[:one_of, valid]
when Class, Module
[:is_a, valid]
else
[:ok]
end
check[key][2] = [:allow_nil, :enumerable].select{|mod| attrs[mod]}
ret[key] = attrs[:default] if attrs.include?(:default)
end
# check validity of keys
unless others_OK or (others = self.keys - argshash.keys).empty?
raise ArgumentError, "Invalid keyword arg#{others.length>1 && "s" or ""} #{others.collect{|a| a.inspect}.join(', ')}", caller
end
# process values, checking validity
self.each do |key, val|
code, valid, mods = check[key]
mods ||= []
val = [ val ] unless mods.include?(:enumerable) and val.is_a?(Enumerable)
ok = val.all? { |v|
if mods.include?(:allow_nil) and v.nil?
true
else
case code
when nil then true # for OTHERS args, there's no code
when :ok then true
when :one_of then valid.include?(v)
when :is_a then v.is_a?(valid)
end
end
}
val = val.first unless mods.include?(:enumerable)
raise ArgumentError, "Invalid value for keyword arg #{key.inspect} => #{val.inspect}", caller unless ok
ret[key] = val
required.delete(key)
end
unless required.empty?
raise ArgumentError, "Missing required keyword arg#{required.length>1 && "s" or ""} #{required.collect{|a| a.inspect}.join(', ')}", caller
end
(class << ret ; self ; end).class_eval do
argshash.keys.each do |key|
define_method(key) do
self[key]
end
end
end
ret
end | ruby | def keyword_args(*args)
argshash = args[-1].is_a?(Hash) ? args.pop : {}
argshash = args.hashify(:optional).merge(argshash)
others_OK = argshash.delete(:OTHERS)
ret = {}
# defaults, required, and checked
required = []
check = {}
argshash.each do |key, val|
# construct fleshed-out attribute hash for all args
attrs = case val
when Hash
val[:default] ||= [] if val[:enumerable]
val
when :required
{ :required => true }
when :optional
{}
when :enumerable
{ :enumerable => true, :default => [] }
when Array
{ :valid => val }
when Class, Module
{ :valid => val }
else
{ :default => val }
end
# extract required flag, validity checks, and default vlues from attribute hash
required << key if attrs[:required]
check[key] = case valid = attrs[:valid]
when Enumerable
[:one_of, valid]
when Class, Module
[:is_a, valid]
else
[:ok]
end
check[key][2] = [:allow_nil, :enumerable].select{|mod| attrs[mod]}
ret[key] = attrs[:default] if attrs.include?(:default)
end
# check validity of keys
unless others_OK or (others = self.keys - argshash.keys).empty?
raise ArgumentError, "Invalid keyword arg#{others.length>1 && "s" or ""} #{others.collect{|a| a.inspect}.join(', ')}", caller
end
# process values, checking validity
self.each do |key, val|
code, valid, mods = check[key]
mods ||= []
val = [ val ] unless mods.include?(:enumerable) and val.is_a?(Enumerable)
ok = val.all? { |v|
if mods.include?(:allow_nil) and v.nil?
true
else
case code
when nil then true # for OTHERS args, there's no code
when :ok then true
when :one_of then valid.include?(v)
when :is_a then v.is_a?(valid)
end
end
}
val = val.first unless mods.include?(:enumerable)
raise ArgumentError, "Invalid value for keyword arg #{key.inspect} => #{val.inspect}", caller unless ok
ret[key] = val
required.delete(key)
end
unless required.empty?
raise ArgumentError, "Missing required keyword arg#{required.length>1 && "s" or ""} #{required.collect{|a| a.inspect}.join(', ')}", caller
end
(class << ret ; self ; end).class_eval do
argshash.keys.each do |key|
define_method(key) do
self[key]
end
end
end
ret
end | [
"def",
"keyword_args",
"(",
"*",
"args",
")",
"argshash",
"=",
"args",
"[",
"-",
"1",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"argshash",
"=",
"args",
".",
"hashify",
"(",
":optional",
")",
".",
"merge",
"(",
"argshash",
")",
"others_OK",
"=",
"argshash",
".",
"delete",
"(",
":OTHERS",
")",
"ret",
"=",
"{",
"}",
"# defaults, required, and checked",
"required",
"=",
"[",
"]",
"check",
"=",
"{",
"}",
"argshash",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"# construct fleshed-out attribute hash for all args",
"attrs",
"=",
"case",
"val",
"when",
"Hash",
"val",
"[",
":default",
"]",
"||=",
"[",
"]",
"if",
"val",
"[",
":enumerable",
"]",
"val",
"when",
":required",
"{",
":required",
"=>",
"true",
"}",
"when",
":optional",
"{",
"}",
"when",
":enumerable",
"{",
":enumerable",
"=>",
"true",
",",
":default",
"=>",
"[",
"]",
"}",
"when",
"Array",
"{",
":valid",
"=>",
"val",
"}",
"when",
"Class",
",",
"Module",
"{",
":valid",
"=>",
"val",
"}",
"else",
"{",
":default",
"=>",
"val",
"}",
"end",
"# extract required flag, validity checks, and default vlues from attribute hash",
"required",
"<<",
"key",
"if",
"attrs",
"[",
":required",
"]",
"check",
"[",
"key",
"]",
"=",
"case",
"valid",
"=",
"attrs",
"[",
":valid",
"]",
"when",
"Enumerable",
"[",
":one_of",
",",
"valid",
"]",
"when",
"Class",
",",
"Module",
"[",
":is_a",
",",
"valid",
"]",
"else",
"[",
":ok",
"]",
"end",
"check",
"[",
"key",
"]",
"[",
"2",
"]",
"=",
"[",
":allow_nil",
",",
":enumerable",
"]",
".",
"select",
"{",
"|",
"mod",
"|",
"attrs",
"[",
"mod",
"]",
"}",
"ret",
"[",
"key",
"]",
"=",
"attrs",
"[",
":default",
"]",
"if",
"attrs",
".",
"include?",
"(",
":default",
")",
"end",
"# check validity of keys",
"unless",
"others_OK",
"or",
"(",
"others",
"=",
"self",
".",
"keys",
"-",
"argshash",
".",
"keys",
")",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Invalid keyword arg#{others.length>1 && \"s\" or \"\"} #{others.collect{|a| a.inspect}.join(', ')}\"",
",",
"caller",
"end",
"# process values, checking validity",
"self",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"code",
",",
"valid",
",",
"mods",
"=",
"check",
"[",
"key",
"]",
"mods",
"||=",
"[",
"]",
"val",
"=",
"[",
"val",
"]",
"unless",
"mods",
".",
"include?",
"(",
":enumerable",
")",
"and",
"val",
".",
"is_a?",
"(",
"Enumerable",
")",
"ok",
"=",
"val",
".",
"all?",
"{",
"|",
"v",
"|",
"if",
"mods",
".",
"include?",
"(",
":allow_nil",
")",
"and",
"v",
".",
"nil?",
"true",
"else",
"case",
"code",
"when",
"nil",
"then",
"true",
"# for OTHERS args, there's no code",
"when",
":ok",
"then",
"true",
"when",
":one_of",
"then",
"valid",
".",
"include?",
"(",
"v",
")",
"when",
":is_a",
"then",
"v",
".",
"is_a?",
"(",
"valid",
")",
"end",
"end",
"}",
"val",
"=",
"val",
".",
"first",
"unless",
"mods",
".",
"include?",
"(",
":enumerable",
")",
"raise",
"ArgumentError",
",",
"\"Invalid value for keyword arg #{key.inspect} => #{val.inspect}\"",
",",
"caller",
"unless",
"ok",
"ret",
"[",
"key",
"]",
"=",
"val",
"required",
".",
"delete",
"(",
"key",
")",
"end",
"unless",
"required",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Missing required keyword arg#{required.length>1 && \"s\" or \"\"} #{required.collect{|a| a.inspect}.join(', ')}\"",
",",
"caller",
"end",
"(",
"class",
"<<",
"ret",
";",
"self",
";",
"end",
")",
".",
"class_eval",
"do",
"argshash",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"define_method",
"(",
"key",
")",
"do",
"self",
"[",
"key",
"]",
"end",
"end",
"end",
"ret",
"end"
] | given an argument hash and a description of acceptable keyword args and
their default values, checks validity of the arguments and raises any
errors, otherwise returns a new hash containing all arg values with
defaults filled in as needed.
args = hash.keyword_args(:a, :b, :c, # these are all optional args
:d => :optional, # same as listing it the arg up front
:e => :required, # raises an error if arg not provided
:f => "hello" # default value
:g => [:x,:y,:z] # valid values
:h => Integer # valid type
:i => :enumerable # expect/coerce an enumerable, check all items, default is []
:j => { :valid => Integer, :allow_nil => true} # Integer or nil
:j => { :valid => [:x,:y,:z], :default => :x, :required => true } # combo
)
by default this will raise an error if the hash contains any keys not
listed. however, if :OTHERS is specified as a keyword arg, that test
will be disabled and any other key/value pairs will be passed through.
Returns a Struct whose values are the | [
"given",
"an",
"argument",
"hash",
"and",
"a",
"description",
"of",
"acceptable",
"keyword",
"args",
"and",
"their",
"default",
"values",
"checks",
"validity",
"of",
"the",
"arguments",
"and",
"raises",
"any",
"errors",
"otherwise",
"returns",
"a",
"new",
"hash",
"containing",
"all",
"arg",
"values",
"with",
"defaults",
"filled",
"in",
"as",
"needed",
"."
] | 10b0b5d46b32afc0cf6129aa84b49b54ec44474a | https://github.com/ronen/hash_keyword_args/blob/10b0b5d46b32afc0cf6129aa84b49b54ec44474a/lib/hash_keyword_args/hash.rb#L27-L111 | train |
ryohashimoto/actionpager | lib/action_pager/pager.rb | ActionPager.Pager.near_pages | def near_pages
@near_pages ||= begin
if current_page <= near + 1
upper_page = shown_page_count >= last_page ? last_page : shown_page_count
1..upper_page
elsif current_page >= last_page - near - 1
bottom_page = last_page - shown_page_count + 1
(bottom_page > 1 ? bottom_page : 1)..last_page
else
bottom_page = current_page - near
upper_page = current_page + near
(bottom_page > 1 ? bottom_page : 1)..(upper_page < last_page ? upper_page : last_page)
end
end
end | ruby | def near_pages
@near_pages ||= begin
if current_page <= near + 1
upper_page = shown_page_count >= last_page ? last_page : shown_page_count
1..upper_page
elsif current_page >= last_page - near - 1
bottom_page = last_page - shown_page_count + 1
(bottom_page > 1 ? bottom_page : 1)..last_page
else
bottom_page = current_page - near
upper_page = current_page + near
(bottom_page > 1 ? bottom_page : 1)..(upper_page < last_page ? upper_page : last_page)
end
end
end | [
"def",
"near_pages",
"@near_pages",
"||=",
"begin",
"if",
"current_page",
"<=",
"near",
"+",
"1",
"upper_page",
"=",
"shown_page_count",
">=",
"last_page",
"?",
"last_page",
":",
"shown_page_count",
"1",
"..",
"upper_page",
"elsif",
"current_page",
">=",
"last_page",
"-",
"near",
"-",
"1",
"bottom_page",
"=",
"last_page",
"-",
"shown_page_count",
"+",
"1",
"(",
"bottom_page",
">",
"1",
"?",
"bottom_page",
":",
"1",
")",
"..",
"last_page",
"else",
"bottom_page",
"=",
"current_page",
"-",
"near",
"upper_page",
"=",
"current_page",
"+",
"near",
"(",
"bottom_page",
">",
"1",
"?",
"bottom_page",
":",
"1",
")",
"..",
"(",
"upper_page",
"<",
"last_page",
"?",
"upper_page",
":",
"last_page",
")",
"end",
"end",
"end"
] | pages that numbers are displayed | [
"pages",
"that",
"numbers",
"are",
"displayed"
] | 4ef4e3005748fae2d10a23a5ac5a191ca7a3f65f | https://github.com/ryohashimoto/actionpager/blob/4ef4e3005748fae2d10a23a5ac5a191ca7a3f65f/lib/action_pager/pager.rb#L112-L126 | train |
dmmalam/wall-leecher | lib/leecher.rb | WallLeecher.Leecher.prep_file | def prep_file(url, dir)
parts = url.split('/')
File.join(dir, parts[-1])
end | ruby | def prep_file(url, dir)
parts = url.split('/')
File.join(dir, parts[-1])
end | [
"def",
"prep_file",
"(",
"url",
",",
"dir",
")",
"parts",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"File",
".",
"join",
"(",
"dir",
",",
"parts",
"[",
"-",
"1",
"]",
")",
"end"
] | Pure function to create correct filename | [
"Pure",
"function",
"to",
"create",
"correct",
"filename"
] | c744ec6886db0dfd5f316ff59f410e10866e2e15 | https://github.com/dmmalam/wall-leecher/blob/c744ec6886db0dfd5f316ff59f410e10866e2e15/lib/leecher.rb#L38-L41 | train |
dmmalam/wall-leecher | lib/leecher.rb | WallLeecher.Fetcher.get | def get
schedule do
inc_io
@@log.info("Requesting: #{@url}")
http = EM::HttpRequest.new(@url).get :redirects => 5
http.callback do |h|
succeed http.response
dec_io
end
http.headers do |headers|
unless OK_ERROR_CODES.include?(headers.status)
fail("Error (#{headers.status}) with url:#{@url}")
dec_io
end
end
http.errback do
fail("Error downloading #{@url}")
dec_io
end
end
self # Fluent interface
end | ruby | def get
schedule do
inc_io
@@log.info("Requesting: #{@url}")
http = EM::HttpRequest.new(@url).get :redirects => 5
http.callback do |h|
succeed http.response
dec_io
end
http.headers do |headers|
unless OK_ERROR_CODES.include?(headers.status)
fail("Error (#{headers.status}) with url:#{@url}")
dec_io
end
end
http.errback do
fail("Error downloading #{@url}")
dec_io
end
end
self # Fluent interface
end | [
"def",
"get",
"schedule",
"do",
"inc_io",
"@@log",
".",
"info",
"(",
"\"Requesting: #{@url}\"",
")",
"http",
"=",
"EM",
"::",
"HttpRequest",
".",
"new",
"(",
"@url",
")",
".",
"get",
":redirects",
"=>",
"5",
"http",
".",
"callback",
"do",
"|",
"h",
"|",
"succeed",
"http",
".",
"response",
"dec_io",
"end",
"http",
".",
"headers",
"do",
"|",
"headers",
"|",
"unless",
"OK_ERROR_CODES",
".",
"include?",
"(",
"headers",
".",
"status",
")",
"fail",
"(",
"\"Error (#{headers.status}) with url:#{@url}\"",
")",
"dec_io",
"end",
"end",
"http",
".",
"errback",
"do",
"fail",
"(",
"\"Error downloading #{@url}\"",
")",
"dec_io",
"end",
"end",
"self",
"# Fluent interface",
"end"
] | Non blocking get url | [
"Non",
"blocking",
"get",
"url"
] | c744ec6886db0dfd5f316ff59f410e10866e2e15 | https://github.com/dmmalam/wall-leecher/blob/c744ec6886db0dfd5f316ff59f410e10866e2e15/lib/leecher.rb#L120-L144 | train |
npolar/npolar-api-client-ruby | lib/npolar/api/client/json_api_client.rb | Npolar::Api::Client.JsonApiClient.valid | def valid(condition=true)
all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)}
end | ruby | def valid(condition=true)
all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)}
end | [
"def",
"valid",
"(",
"condition",
"=",
"true",
")",
"all",
".",
"select",
"{",
"|",
"d",
"|",
"condition",
"==",
"valid?",
"(",
"d",
")",
"}",
".",
"map",
"{",
"|",
"d",
"|",
"model",
".",
"class",
".",
"new",
"(",
"d",
")",
"}",
"end"
] | All valid documents | [
"All",
"valid",
"documents"
] | e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb | https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/json_api_client.rb#L286-L288 | train |
npolar/npolar-api-client-ruby | lib/npolar/api/client/json_api_client.rb | Npolar::Api::Client.JsonApiClient.multi_request | def multi_request(method, paths, body=nil, param=nil, header=nil)
@multi = true
# Response storage, if not already set
if @responses.nil?
@responses = []
end
# Handle one or many paths
if paths.is_a? String or paths.is_a? URI
paths = [paths]
end
# Handle (URI) objects
paths = paths.map {|p| p.to_s }
log.debug "Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }"
paths.each do | path |
multi_request = request(path, method.downcase.to_sym, body, param, header)
multi_request.on_complete do | response |
log.debug "Multi-#{method} [#{paths.size}]: "+log_message(response)
@responses << response
end
hydra.queue(multi_request)
end
hydra
end | ruby | def multi_request(method, paths, body=nil, param=nil, header=nil)
@multi = true
# Response storage, if not already set
if @responses.nil?
@responses = []
end
# Handle one or many paths
if paths.is_a? String or paths.is_a? URI
paths = [paths]
end
# Handle (URI) objects
paths = paths.map {|p| p.to_s }
log.debug "Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }"
paths.each do | path |
multi_request = request(path, method.downcase.to_sym, body, param, header)
multi_request.on_complete do | response |
log.debug "Multi-#{method} [#{paths.size}]: "+log_message(response)
@responses << response
end
hydra.queue(multi_request)
end
hydra
end | [
"def",
"multi_request",
"(",
"method",
",",
"paths",
",",
"body",
"=",
"nil",
",",
"param",
"=",
"nil",
",",
"header",
"=",
"nil",
")",
"@multi",
"=",
"true",
"# Response storage, if not already set",
"if",
"@responses",
".",
"nil?",
"@responses",
"=",
"[",
"]",
"end",
"# Handle one or many paths",
"if",
"paths",
".",
"is_a?",
"String",
"or",
"paths",
".",
"is_a?",
"URI",
"paths",
"=",
"[",
"paths",
"]",
"end",
"# Handle (URI) objects",
"paths",
"=",
"paths",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"to_s",
"}",
"log",
".",
"debug",
"\"Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }\"",
"paths",
".",
"each",
"do",
"|",
"path",
"|",
"multi_request",
"=",
"request",
"(",
"path",
",",
"method",
".",
"downcase",
".",
"to_sym",
",",
"body",
",",
"param",
",",
"header",
")",
"multi_request",
".",
"on_complete",
"do",
"|",
"response",
"|",
"log",
".",
"debug",
"\"Multi-#{method} [#{paths.size}]: \"",
"+",
"log_message",
"(",
"response",
")",
"@responses",
"<<",
"response",
"end",
"hydra",
".",
"queue",
"(",
"multi_request",
")",
"end",
"hydra",
"end"
] | Prepare and queue a multi request
@return [#run] | [
"Prepare",
"and",
"queue",
"a",
"multi",
"request"
] | e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb | https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/json_api_client.rb#L496-L524 | train |
elifoster/fishbans-rb | lib/block_engine.rb | Fishbans.BlockEngine.get_block | def get_block(id, metadata = nil, size = 42)
url = "http://blocks.fishbans.com/#{id}"
url += "-#{metadata}" unless metadata.nil?
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | ruby | def get_block(id, metadata = nil, size = 42)
url = "http://blocks.fishbans.com/#{id}"
url += "-#{metadata}" unless metadata.nil?
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | [
"def",
"get_block",
"(",
"id",
",",
"metadata",
"=",
"nil",
",",
"size",
"=",
"42",
")",
"url",
"=",
"\"http://blocks.fishbans.com/#{id}\"",
"url",
"+=",
"\"-#{metadata}\"",
"unless",
"metadata",
".",
"nil?",
"url",
"+=",
"\"/#{size}\"",
"if",
"size",
"!=",
"42",
"response",
"=",
"get",
"(",
"url",
",",
"false",
")",
"ChunkyPNG",
"::",
"Image",
".",
"from_blob",
"(",
"response",
".",
"body",
")",
"end"
] | Gets a block image by its ID and Metadata. Unfortunately it uses the old
block IDs rather than the new ones, so you have to memorize those
pesky integers.
@param id [Integer] The (outdated) block ID number.
@param metadata [Integer] The metadata, if any, for the block.
@param size [Fixnum] The size of the image to get.
@return [ChunkyPNG::Image] The ChunkyPNG instance of that block image.
@raise see #get | [
"Gets",
"a",
"block",
"image",
"by",
"its",
"ID",
"and",
"Metadata",
".",
"Unfortunately",
"it",
"uses",
"the",
"old",
"block",
"IDs",
"rather",
"than",
"the",
"new",
"ones",
"so",
"you",
"have",
"to",
"memorize",
"those",
"pesky",
"integers",
"."
] | 652016694176ade8767ac6a3b4dea2dc631be747 | https://github.com/elifoster/fishbans-rb/blob/652016694176ade8767ac6a3b4dea2dc631be747/lib/block_engine.rb#L14-L20 | train |
elifoster/fishbans-rb | lib/block_engine.rb | Fishbans.BlockEngine.get_monster | def get_monster(id, three = false, size = 42)
id = id.to_s
url = 'http://blocks.fishbans.com'
url += "/#{id}" if id =~ /^m/
url += "/m#{id}" if id !~ /^m/
url += '-3d' if three
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | ruby | def get_monster(id, three = false, size = 42)
id = id.to_s
url = 'http://blocks.fishbans.com'
url += "/#{id}" if id =~ /^m/
url += "/m#{id}" if id !~ /^m/
url += '-3d' if three
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | [
"def",
"get_monster",
"(",
"id",
",",
"three",
"=",
"false",
",",
"size",
"=",
"42",
")",
"id",
"=",
"id",
".",
"to_s",
"url",
"=",
"'http://blocks.fishbans.com'",
"url",
"+=",
"\"/#{id}\"",
"if",
"id",
"=~",
"/",
"/",
"url",
"+=",
"\"/m#{id}\"",
"if",
"id",
"!~",
"/",
"/",
"url",
"+=",
"'-3d'",
"if",
"three",
"url",
"+=",
"\"/#{size}\"",
"if",
"size",
"!=",
"42",
"response",
"=",
"get",
"(",
"url",
",",
"false",
")",
"ChunkyPNG",
"::",
"Image",
".",
"from_blob",
"(",
"response",
".",
"body",
")",
"end"
] | Gets the monster image by its ID.
@param id [Any] The string ID. It will automatically prefix it with "m" if
that is omitted. It doesn't matter what type it is: String or Fixnum,
because it will automatically convert it to a String.
@param three [Boolean] Whether to get a three-dimensional monster image.
The three-dimensional image is of the full monster, while the
two-dimensional image is just its head.
@param size [Integer] The size of the image (width) to get. For 3D images
this will not be perfect just by nature of the API.
@return [ChunkyPNG::Image] The ChunkyPNG instance of that monster image.
@raise see #get | [
"Gets",
"the",
"monster",
"image",
"by",
"its",
"ID",
"."
] | 652016694176ade8767ac6a3b4dea2dc631be747 | https://github.com/elifoster/fishbans-rb/blob/652016694176ade8767ac6a3b4dea2dc631be747/lib/block_engine.rb#L33-L42 | train |
wparad/Osiris | lib/osiris/zip_file_generator.rb | Osiris.ZipFileGenerator.write | def write(inputDir, outputFile)
entries = Dir.entries(inputDir); entries.delete("."); entries.delete("..")
io = Zip::File.open(outputFile, Zip::File::CREATE);
writeEntries(entries, "", io, inputDir)
io.close();
end | ruby | def write(inputDir, outputFile)
entries = Dir.entries(inputDir); entries.delete("."); entries.delete("..")
io = Zip::File.open(outputFile, Zip::File::CREATE);
writeEntries(entries, "", io, inputDir)
io.close();
end | [
"def",
"write",
"(",
"inputDir",
",",
"outputFile",
")",
"entries",
"=",
"Dir",
".",
"entries",
"(",
"inputDir",
")",
";",
"entries",
".",
"delete",
"(",
"\".\"",
")",
";",
"entries",
".",
"delete",
"(",
"\"..\"",
")",
"io",
"=",
"Zip",
"::",
"File",
".",
"open",
"(",
"outputFile",
",",
"Zip",
"::",
"File",
"::",
"CREATE",
")",
";",
"writeEntries",
"(",
"entries",
",",
"\"\"",
",",
"io",
",",
"inputDir",
")",
"io",
".",
"close",
"(",
")",
";",
"end"
] | Initialize with the directory to zip and the location of the output archive.
Zip the input directory. | [
"Initialize",
"with",
"the",
"directory",
"to",
"zip",
"and",
"the",
"location",
"of",
"the",
"output",
"archive",
".",
"Zip",
"the",
"input",
"directory",
"."
] | efa61f3353674a01e813d9557016bd610277f7de | https://github.com/wparad/Osiris/blob/efa61f3353674a01e813d9557016bd610277f7de/lib/osiris/zip_file_generator.rb#L20-L26 | train |
pwnall/file_blobs_rails | lib/file_blobs_rails/active_record_fixture_set_extensions.rb | FileBlobs.ActiveRecordFixtureSetExtensions.file_blob_id | def file_blob_id(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
# This needs to be kept in sync with blob_model.rb.
Base64.urlsafe_encode64(Digest::SHA256.digest(blob_contents)).inspect
end | ruby | def file_blob_id(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
# This needs to be kept in sync with blob_model.rb.
Base64.urlsafe_encode64(Digest::SHA256.digest(blob_contents)).inspect
end | [
"def",
"file_blob_id",
"(",
"path",
")",
"file_path",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'test/fixtures'",
".",
"freeze",
")",
".",
"join",
"(",
"path",
")",
"blob_contents",
"=",
"File",
".",
"binread",
"file_path",
"# This needs to be kept in sync with blob_model.rb.",
"Base64",
".",
"urlsafe_encode64",
"(",
"Digest",
"::",
"SHA256",
".",
"digest",
"(",
"blob_contents",
")",
")",
".",
"inspect",
"end"
] | Computes the ID assigned to a blob.
@param [String] path the path of the file whose contents is used in the
fixture, relative to the Rails application's test/fixtures directory
@return [String] the ID used to represent the blob contents | [
"Computes",
"the",
"ID",
"assigned",
"to",
"a",
"blob",
"."
] | 688d43ec8547856f3572b0e6716e6faeff56345b | https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_fixture_set_extensions.rb#L14-L20 | train |
pwnall/file_blobs_rails | lib/file_blobs_rails/active_record_fixture_set_extensions.rb | FileBlobs.ActiveRecordFixtureSetExtensions.file_blob_data | def file_blob_data(path, options = {})
# The line with base64 data must be indented further than the current line.
indent = ' ' * ((options[:indent] || 2) + 2)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
base64_data = Base64.encode64 blob_contents
base64_data.gsub! "\n", "\n#{indent}"
base64_data.strip!
"!!binary |\n#{indent}#{base64_data}"
end | ruby | def file_blob_data(path, options = {})
# The line with base64 data must be indented further than the current line.
indent = ' ' * ((options[:indent] || 2) + 2)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
base64_data = Base64.encode64 blob_contents
base64_data.gsub! "\n", "\n#{indent}"
base64_data.strip!
"!!binary |\n#{indent}#{base64_data}"
end | [
"def",
"file_blob_data",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"# The line with base64 data must be indented further than the current line.",
"indent",
"=",
"' '",
"*",
"(",
"(",
"options",
"[",
":indent",
"]",
"||",
"2",
")",
"+",
"2",
")",
"file_path",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'test/fixtures'",
".",
"freeze",
")",
".",
"join",
"(",
"path",
")",
"blob_contents",
"=",
"File",
".",
"binread",
"file_path",
"base64_data",
"=",
"Base64",
".",
"encode64",
"blob_contents",
"base64_data",
".",
"gsub!",
"\"\\n\"",
",",
"\"\\n#{indent}\"",
"base64_data",
".",
"strip!",
"\"!!binary |\\n#{indent}#{base64_data}\"",
"end"
] | The contents of a blob, in a YAML-friendly format.
@param [String] path the path of the file whose contents is used in the
fixture, relative to the Rails application's test/fixtures directory
@param [Hash] options optionally specify the current indentation level
@option options [Integer] indent the number of spaces that the current line
in the YAML fixture file is indented by
@return [String] the base64-encoded blob contents | [
"The",
"contents",
"of",
"a",
"blob",
"in",
"a",
"YAML",
"-",
"friendly",
"format",
"."
] | 688d43ec8547856f3572b0e6716e6faeff56345b | https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_fixture_set_extensions.rb#L30-L41 | train |
pwnall/file_blobs_rails | lib/file_blobs_rails/active_record_fixture_set_extensions.rb | FileBlobs.ActiveRecordFixtureSetExtensions.file_blob_size | def file_blob_size(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
File.stat(file_path).size
end | ruby | def file_blob_size(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
File.stat(file_path).size
end | [
"def",
"file_blob_size",
"(",
"path",
")",
"file_path",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'test/fixtures'",
".",
"freeze",
")",
".",
"join",
"(",
"path",
")",
"File",
".",
"stat",
"(",
"file_path",
")",
".",
"size",
"end"
] | The number of bytes in a file.
@param [String] path the path of the file whose contents is used in the
fixture, relative to the Rails application's test/fixtures directory
@return [Integer] the nubmer of bytes in the file | [
"The",
"number",
"of",
"bytes",
"in",
"a",
"file",
"."
] | 688d43ec8547856f3572b0e6716e6faeff56345b | https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_fixture_set_extensions.rb#L48-L51 | train |
thriventures/storage_room_gem | lib/storage_room/embeddeds/file.rb | StorageRoom.File.set_with_filename | def set_with_filename(path)
return if path.blank?
self.filename = ::File.basename(path)
self.content_type = ::MIME::Types.type_for(path).first.content_type
self.data = ::Base64.encode64(::File.read(path))
end | ruby | def set_with_filename(path)
return if path.blank?
self.filename = ::File.basename(path)
self.content_type = ::MIME::Types.type_for(path).first.content_type
self.data = ::Base64.encode64(::File.read(path))
end | [
"def",
"set_with_filename",
"(",
"path",
")",
"return",
"if",
"path",
".",
"blank?",
"self",
".",
"filename",
"=",
"::",
"File",
".",
"basename",
"(",
"path",
")",
"self",
".",
"content_type",
"=",
"::",
"MIME",
"::",
"Types",
".",
"type_for",
"(",
"path",
")",
".",
"first",
".",
"content_type",
"self",
".",
"data",
"=",
"::",
"Base64",
".",
"encode64",
"(",
"::",
"File",
".",
"read",
"(",
"path",
")",
")",
"end"
] | Sets the filename, content_type and data attributes from a local filename so that a File can be uploaded through the API | [
"Sets",
"the",
"filename",
"content_type",
"and",
"data",
"attributes",
"from",
"a",
"local",
"filename",
"so",
"that",
"a",
"File",
"can",
"be",
"uploaded",
"through",
"the",
"API"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/embeddeds/file.rb#L20-L26 | train |
thriventures/storage_room_gem | lib/storage_room/embeddeds/file.rb | StorageRoom.File.download_to_directory | def download_to_directory(path)
Dir.mkdir(path) unless ::File.directory?(path)
download_file(self[:@url], ::File.join(path, local_filename))
true
end | ruby | def download_to_directory(path)
Dir.mkdir(path) unless ::File.directory?(path)
download_file(self[:@url], ::File.join(path, local_filename))
true
end | [
"def",
"download_to_directory",
"(",
"path",
")",
"Dir",
".",
"mkdir",
"(",
"path",
")",
"unless",
"::",
"File",
".",
"directory?",
"(",
"path",
")",
"download_file",
"(",
"self",
"[",
":@url",
"]",
",",
"::",
"File",
".",
"join",
"(",
"path",
",",
"local_filename",
")",
")",
"true",
"end"
] | Download the file to the local disk | [
"Download",
"the",
"file",
"to",
"the",
"local",
"disk"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/embeddeds/file.rb#L34-L38 | train |
sanichi/icu_tournament | lib/icu_tournament/tournament_spx.rb | ICU.Player.to_sp_text | def to_sp_text(rounds, columns, formats)
values = columns.inject([]) do |vals,col|
val = send(col).to_s
val.sub!(/\.0/, '') if col == :points
vals << val
end
(1..rounds).each do |r|
result = find_result(r)
values << (result ? result.to_sp_text : " : ")
end
formats % values
end | ruby | def to_sp_text(rounds, columns, formats)
values = columns.inject([]) do |vals,col|
val = send(col).to_s
val.sub!(/\.0/, '') if col == :points
vals << val
end
(1..rounds).each do |r|
result = find_result(r)
values << (result ? result.to_sp_text : " : ")
end
formats % values
end | [
"def",
"to_sp_text",
"(",
"rounds",
",",
"columns",
",",
"formats",
")",
"values",
"=",
"columns",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"vals",
",",
"col",
"|",
"val",
"=",
"send",
"(",
"col",
")",
".",
"to_s",
"val",
".",
"sub!",
"(",
"/",
"\\.",
"/",
",",
"''",
")",
"if",
"col",
"==",
":points",
"vals",
"<<",
"val",
"end",
"(",
"1",
"..",
"rounds",
")",
".",
"each",
"do",
"|",
"r",
"|",
"result",
"=",
"find_result",
"(",
"r",
")",
"values",
"<<",
"(",
"result",
"?",
"result",
".",
"to_sp_text",
":",
"\" : \"",
")",
"end",
"formats",
"%",
"values",
"end"
] | Format a player's record as it would appear in an SP export file. | [
"Format",
"a",
"player",
"s",
"record",
"as",
"it",
"would",
"appear",
"in",
"an",
"SP",
"export",
"file",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament_spx.rb#L364-L375 | train |
evansagge/numeric_array | lib/numeric_array.rb | NumericArray.InstanceMethods.variance | def variance(sample = false)
a = numerify
avg = a.average
sum = a.inject(0) { |sum, value| sum + (value - avg) ** 2}
(1 / (a.length.to_f - (sample ? 1 : 0)) * sum)
end | ruby | def variance(sample = false)
a = numerify
avg = a.average
sum = a.inject(0) { |sum, value| sum + (value - avg) ** 2}
(1 / (a.length.to_f - (sample ? 1 : 0)) * sum)
end | [
"def",
"variance",
"(",
"sample",
"=",
"false",
")",
"a",
"=",
"numerify",
"avg",
"=",
"a",
".",
"average",
"sum",
"=",
"a",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"value",
"|",
"sum",
"+",
"(",
"value",
"-",
"avg",
")",
"**",
"2",
"}",
"(",
"1",
"/",
"(",
"a",
".",
"length",
".",
"to_f",
"-",
"(",
"sample",
"?",
"1",
":",
"0",
")",
")",
"*",
"sum",
")",
"end"
] | variance of an array of numbers | [
"variance",
"of",
"an",
"array",
"of",
"numbers"
] | f5cbdd0c658631d42540f9251480e0d38ebb493a | https://github.com/evansagge/numeric_array/blob/f5cbdd0c658631d42540f9251480e0d38ebb493a/lib/numeric_array.rb#L25-L30 | train |
irvingwashington/gem_footprint_analyzer | lib/gem_footprint_analyzer/cli.rb | GemFootprintAnalyzer.CLI.run | def run(args = ARGV)
opts.parse!(args)
if !analyze_gemfile? && args.empty?
puts opts.parser
exit 1
end
print_requires(options, args)
end | ruby | def run(args = ARGV)
opts.parse!(args)
if !analyze_gemfile? && args.empty?
puts opts.parser
exit 1
end
print_requires(options, args)
end | [
"def",
"run",
"(",
"args",
"=",
"ARGV",
")",
"opts",
".",
"parse!",
"(",
"args",
")",
"if",
"!",
"analyze_gemfile?",
"&&",
"args",
".",
"empty?",
"puts",
"opts",
".",
"parser",
"exit",
"1",
"end",
"print_requires",
"(",
"options",
",",
"args",
")",
"end"
] | Sets default options, to be overwritten by option parser down the road
@param args [Array<String>] runs the analyzer with parsed args taken as options
@return [void] | [
"Sets",
"default",
"options",
"to",
"be",
"overwritten",
"by",
"option",
"parser",
"down",
"the",
"road"
] | 19a8892f6baaeb16b1b166144c4f73852396220c | https://github.com/irvingwashington/gem_footprint_analyzer/blob/19a8892f6baaeb16b1b166144c4f73852396220c/lib/gem_footprint_analyzer/cli.rb#L19-L28 | train |
gr4y/streambot | lib/streambot/tracker.rb | StreamBot.Tracker.start | def start
keywords = self.params["keywords"]
@thread = Thread.new do
@client.filter_by_keywords(keywords) do |status|
if retweet?(status)
before_retweet.trigger(status)
@retweet.retweet(status["id"])
after_retweet.trigger(status)
end
end
end
@thread.join
end | ruby | def start
keywords = self.params["keywords"]
@thread = Thread.new do
@client.filter_by_keywords(keywords) do |status|
if retweet?(status)
before_retweet.trigger(status)
@retweet.retweet(status["id"])
after_retweet.trigger(status)
end
end
end
@thread.join
end | [
"def",
"start",
"keywords",
"=",
"self",
".",
"params",
"[",
"\"keywords\"",
"]",
"@thread",
"=",
"Thread",
".",
"new",
"do",
"@client",
".",
"filter_by_keywords",
"(",
"keywords",
")",
"do",
"|",
"status",
"|",
"if",
"retweet?",
"(",
"status",
")",
"before_retweet",
".",
"trigger",
"(",
"status",
")",
"@retweet",
".",
"retweet",
"(",
"status",
"[",
"\"id\"",
"]",
")",
"after_retweet",
".",
"trigger",
"(",
"status",
")",
"end",
"end",
"end",
"@thread",
".",
"join",
"end"
] | initializes the tracker
start the tracker | [
"initializes",
"the",
"tracker",
"start",
"the",
"tracker"
] | 3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375 | https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/tracker.rb#L22-L34 | train |
gr4y/streambot | lib/streambot/tracker.rb | StreamBot.Tracker.load_filters | def load_filters
filters_config = self.params["filters_config" ]
if !filters_config.nil? && File.exists?(filters_config)
begin
YAML::load_file(filters_config)
rescue
on_error.trigger($!, $@)
end
end
end | ruby | def load_filters
filters_config = self.params["filters_config" ]
if !filters_config.nil? && File.exists?(filters_config)
begin
YAML::load_file(filters_config)
rescue
on_error.trigger($!, $@)
end
end
end | [
"def",
"load_filters",
"filters_config",
"=",
"self",
".",
"params",
"[",
"\"filters_config\"",
"]",
"if",
"!",
"filters_config",
".",
"nil?",
"&&",
"File",
".",
"exists?",
"(",
"filters_config",
")",
"begin",
"YAML",
"::",
"load_file",
"(",
"filters_config",
")",
"rescue",
"on_error",
".",
"trigger",
"(",
"$!",
",",
"$@",
")",
"end",
"end",
"end"
] | load the YAML file that is specified in the params | [
"load",
"the",
"YAML",
"file",
"that",
"is",
"specified",
"in",
"the",
"params"
] | 3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375 | https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/tracker.rb#L49-L58 | train |
gr4y/streambot | lib/streambot/tracker.rb | StreamBot.Tracker.retweet? | def retweet?(status)
filters = load_filters
retweet = true
if !filters.nil?
filters.each_pair do |path, value|
array = []
array << value
array.flatten.each do |filter_value|
path_value = StreamBot::ArrayPath.get_path(status, path)
if path_value.eql?(filter_value) || path_value.include?(filter_value)
on_match.trigger(status, path, filter_value)
retweet = false
end
end
end
end
retweet
end | ruby | def retweet?(status)
filters = load_filters
retweet = true
if !filters.nil?
filters.each_pair do |path, value|
array = []
array << value
array.flatten.each do |filter_value|
path_value = StreamBot::ArrayPath.get_path(status, path)
if path_value.eql?(filter_value) || path_value.include?(filter_value)
on_match.trigger(status, path, filter_value)
retweet = false
end
end
end
end
retweet
end | [
"def",
"retweet?",
"(",
"status",
")",
"filters",
"=",
"load_filters",
"retweet",
"=",
"true",
"if",
"!",
"filters",
".",
"nil?",
"filters",
".",
"each_pair",
"do",
"|",
"path",
",",
"value",
"|",
"array",
"=",
"[",
"]",
"array",
"<<",
"value",
"array",
".",
"flatten",
".",
"each",
"do",
"|",
"filter_value",
"|",
"path_value",
"=",
"StreamBot",
"::",
"ArrayPath",
".",
"get_path",
"(",
"status",
",",
"path",
")",
"if",
"path_value",
".",
"eql?",
"(",
"filter_value",
")",
"||",
"path_value",
".",
"include?",
"(",
"filter_value",
")",
"on_match",
".",
"trigger",
"(",
"status",
",",
"path",
",",
"filter_value",
")",
"retweet",
"=",
"false",
"end",
"end",
"end",
"end",
"retweet",
"end"
] | decide if the status is retweetable | [
"decide",
"if",
"the",
"status",
"is",
"retweetable"
] | 3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375 | https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/tracker.rb#L61-L78 | train |
jeffa/html-autotag-ruby | lib/HTML/AutoTag.rb | HTML.AutoTag.tag | def tag( params )
# TODO: make these method args if possible
tag = params['tag']
attr = params['attr']
cdata = params['cdata']
unless attr.kind_of?( HTML::AutoAttr )
attr = HTML::AutoAttr.new( attr, @sorted )
end
# emtpy tag
unless cdata and cdata.to_s.length
return ( @indent * @level ) + '<' + tag + attr.to_s + ' />' + @newline
end
rendered = ''
no_indent = 0
if cdata.kind_of?( Array )
if cdata[0].kind_of?( Hash )
@level += 1
rendered = @newline
cdata.each do |hash|
rendered += tag( hash )
end
@level -= 1
else
str = ''
cdata.each do |scalar|
str += tag( 'tag' => tag, 'attr' => attr, 'cdata' => scalar )
end
return str
end
elsif cdata.kind_of?( Hash )
@level += 1
rendered = @newline + tag( cdata )
@level -= 1
else
rendered = @encode ? @encoder.encode( cdata, @encodes ) : cdata
no_indent = 1
end
return (@indent * @level) \
+ '<' + tag + attr.to_s + '>' \
+ rendered.to_s + ( no_indent == 1 ? '' : ( @indent * @level ) ) \
+ '</' + tag + '>' + @newline
end | ruby | def tag( params )
# TODO: make these method args if possible
tag = params['tag']
attr = params['attr']
cdata = params['cdata']
unless attr.kind_of?( HTML::AutoAttr )
attr = HTML::AutoAttr.new( attr, @sorted )
end
# emtpy tag
unless cdata and cdata.to_s.length
return ( @indent * @level ) + '<' + tag + attr.to_s + ' />' + @newline
end
rendered = ''
no_indent = 0
if cdata.kind_of?( Array )
if cdata[0].kind_of?( Hash )
@level += 1
rendered = @newline
cdata.each do |hash|
rendered += tag( hash )
end
@level -= 1
else
str = ''
cdata.each do |scalar|
str += tag( 'tag' => tag, 'attr' => attr, 'cdata' => scalar )
end
return str
end
elsif cdata.kind_of?( Hash )
@level += 1
rendered = @newline + tag( cdata )
@level -= 1
else
rendered = @encode ? @encoder.encode( cdata, @encodes ) : cdata
no_indent = 1
end
return (@indent * @level) \
+ '<' + tag + attr.to_s + '>' \
+ rendered.to_s + ( no_indent == 1 ? '' : ( @indent * @level ) ) \
+ '</' + tag + '>' + @newline
end | [
"def",
"tag",
"(",
"params",
")",
"# TODO: make these method args if possible",
"tag",
"=",
"params",
"[",
"'tag'",
"]",
"attr",
"=",
"params",
"[",
"'attr'",
"]",
"cdata",
"=",
"params",
"[",
"'cdata'",
"]",
"unless",
"attr",
".",
"kind_of?",
"(",
"HTML",
"::",
"AutoAttr",
")",
"attr",
"=",
"HTML",
"::",
"AutoAttr",
".",
"new",
"(",
"attr",
",",
"@sorted",
")",
"end",
"# emtpy tag",
"unless",
"cdata",
"and",
"cdata",
".",
"to_s",
".",
"length",
"return",
"(",
"@indent",
"*",
"@level",
")",
"+",
"'<'",
"+",
"tag",
"+",
"attr",
".",
"to_s",
"+",
"' />'",
"+",
"@newline",
"end",
"rendered",
"=",
"''",
"no_indent",
"=",
"0",
"if",
"cdata",
".",
"kind_of?",
"(",
"Array",
")",
"if",
"cdata",
"[",
"0",
"]",
".",
"kind_of?",
"(",
"Hash",
")",
"@level",
"+=",
"1",
"rendered",
"=",
"@newline",
"cdata",
".",
"each",
"do",
"|",
"hash",
"|",
"rendered",
"+=",
"tag",
"(",
"hash",
")",
"end",
"@level",
"-=",
"1",
"else",
"str",
"=",
"''",
"cdata",
".",
"each",
"do",
"|",
"scalar",
"|",
"str",
"+=",
"tag",
"(",
"'tag'",
"=>",
"tag",
",",
"'attr'",
"=>",
"attr",
",",
"'cdata'",
"=>",
"scalar",
")",
"end",
"return",
"str",
"end",
"elsif",
"cdata",
".",
"kind_of?",
"(",
"Hash",
")",
"@level",
"+=",
"1",
"rendered",
"=",
"@newline",
"+",
"tag",
"(",
"cdata",
")",
"@level",
"-=",
"1",
"else",
"rendered",
"=",
"@encode",
"?",
"@encoder",
".",
"encode",
"(",
"cdata",
",",
"@encodes",
")",
":",
"cdata",
"no_indent",
"=",
"1",
"end",
"return",
"(",
"@indent",
"*",
"@level",
")",
"+",
"'<'",
"+",
"tag",
"+",
"attr",
".",
"to_s",
"+",
"'>'",
"+",
"rendered",
".",
"to_s",
"+",
"(",
"no_indent",
"==",
"1",
"?",
"''",
":",
"(",
"@indent",
"*",
"@level",
")",
")",
"+",
"'</'",
"+",
"tag",
"+",
"'>'",
"+",
"@newline",
"end"
] | Defaults to empty string which produces no encoding. | [
"Defaults",
"to",
"empty",
"string",
"which",
"produces",
"no",
"encoding",
"."
] | 994103cb2c73e0477077fc041e12c81b7ed6326c | https://github.com/jeffa/html-autotag-ruby/blob/994103cb2c73e0477077fc041e12c81b7ed6326c/lib/HTML/AutoTag.rb#L23-L75 | train |
ashrafuzzaman/chartify | lib/chartify/chart_base.rb | Chartify.ChartBase.darken_color | def darken_color(hex_color, amount=0.4)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = (rgb[0].to_i * amount).round
rgb[1] = (rgb[1].to_i * amount).round
rgb[2] = (rgb[2].to_i * amount).round
"#%02x%02x%02x" % rgb
end | ruby | def darken_color(hex_color, amount=0.4)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = (rgb[0].to_i * amount).round
rgb[1] = (rgb[1].to_i * amount).round
rgb[2] = (rgb[2].to_i * amount).round
"#%02x%02x%02x" % rgb
end | [
"def",
"darken_color",
"(",
"hex_color",
",",
"amount",
"=",
"0.4",
")",
"hex_color",
"=",
"hex_color",
".",
"gsub",
"(",
"'#'",
",",
"''",
")",
"rgb",
"=",
"hex_color",
".",
"scan",
"(",
"/",
"/",
")",
".",
"map",
"{",
"|",
"color",
"|",
"color",
".",
"hex",
"}",
"rgb",
"[",
"0",
"]",
"=",
"(",
"rgb",
"[",
"0",
"]",
".",
"to_i",
"*",
"amount",
")",
".",
"round",
"rgb",
"[",
"1",
"]",
"=",
"(",
"rgb",
"[",
"1",
"]",
".",
"to_i",
"*",
"amount",
")",
".",
"round",
"rgb",
"[",
"2",
"]",
"=",
"(",
"rgb",
"[",
"2",
"]",
".",
"to_i",
"*",
"amount",
")",
".",
"round",
"\"#%02x%02x%02x\"",
"%",
"rgb",
"end"
] | Amount should be a decimal between 0 and 1. Lower means darker | [
"Amount",
"should",
"be",
"a",
"decimal",
"between",
"0",
"and",
"1",
".",
"Lower",
"means",
"darker"
] | f791ffb20c10417619bec0afa7a355d9e5e499b6 | https://github.com/ashrafuzzaman/chartify/blob/f791ffb20c10417619bec0afa7a355d9e5e499b6/lib/chartify/chart_base.rb#L99-L106 | train |
ashrafuzzaman/chartify | lib/chartify/chart_base.rb | Chartify.ChartBase.lighten_color | def lighten_color(hex_color, amount=0.6)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = [(rgb[0].to_i + 255 * amount).round, 255].min
rgb[1] = [(rgb[1].to_i + 255 * amount).round, 255].min
rgb[2] = [(rgb[2].to_i + 255 * amount).round, 255].min
"#%02x%02x%02x" % rgb
end | ruby | def lighten_color(hex_color, amount=0.6)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = [(rgb[0].to_i + 255 * amount).round, 255].min
rgb[1] = [(rgb[1].to_i + 255 * amount).round, 255].min
rgb[2] = [(rgb[2].to_i + 255 * amount).round, 255].min
"#%02x%02x%02x" % rgb
end | [
"def",
"lighten_color",
"(",
"hex_color",
",",
"amount",
"=",
"0.6",
")",
"hex_color",
"=",
"hex_color",
".",
"gsub",
"(",
"'#'",
",",
"''",
")",
"rgb",
"=",
"hex_color",
".",
"scan",
"(",
"/",
"/",
")",
".",
"map",
"{",
"|",
"color",
"|",
"color",
".",
"hex",
"}",
"rgb",
"[",
"0",
"]",
"=",
"[",
"(",
"rgb",
"[",
"0",
"]",
".",
"to_i",
"+",
"255",
"*",
"amount",
")",
".",
"round",
",",
"255",
"]",
".",
"min",
"rgb",
"[",
"1",
"]",
"=",
"[",
"(",
"rgb",
"[",
"1",
"]",
".",
"to_i",
"+",
"255",
"*",
"amount",
")",
".",
"round",
",",
"255",
"]",
".",
"min",
"rgb",
"[",
"2",
"]",
"=",
"[",
"(",
"rgb",
"[",
"2",
"]",
".",
"to_i",
"+",
"255",
"*",
"amount",
")",
".",
"round",
",",
"255",
"]",
".",
"min",
"\"#%02x%02x%02x\"",
"%",
"rgb",
"end"
] | Amount should be a decimal between 0 and 1. Higher means lighter | [
"Amount",
"should",
"be",
"a",
"decimal",
"between",
"0",
"and",
"1",
".",
"Higher",
"means",
"lighter"
] | f791ffb20c10417619bec0afa7a355d9e5e499b6 | https://github.com/ashrafuzzaman/chartify/blob/f791ffb20c10417619bec0afa7a355d9e5e499b6/lib/chartify/chart_base.rb#L109-L116 | train |
jasonayre/trax_model | lib/trax/model.rb | Trax.Model.reverse_assign_attributes | def reverse_assign_attributes(attributes_hash)
attributes_to_assign = attributes_hash.keys.reject{|_attribute_name| attribute_present?(_attribute_name) }
assign_attributes(attributes_hash.slice(attributes_to_assign))
end | ruby | def reverse_assign_attributes(attributes_hash)
attributes_to_assign = attributes_hash.keys.reject{|_attribute_name| attribute_present?(_attribute_name) }
assign_attributes(attributes_hash.slice(attributes_to_assign))
end | [
"def",
"reverse_assign_attributes",
"(",
"attributes_hash",
")",
"attributes_to_assign",
"=",
"attributes_hash",
".",
"keys",
".",
"reject",
"{",
"|",
"_attribute_name",
"|",
"attribute_present?",
"(",
"_attribute_name",
")",
"}",
"assign_attributes",
"(",
"attributes_hash",
".",
"slice",
"(",
"attributes_to_assign",
")",
")",
"end"
] | like reverse merge, only assigns attributes which have not yet been assigned | [
"like",
"reverse",
"merge",
"only",
"assigns",
"attributes",
"which",
"have",
"not",
"yet",
"been",
"assigned"
] | 5e9b7b12f575a06306882440c147b70cca263d5c | https://github.com/jasonayre/trax_model/blob/5e9b7b12f575a06306882440c147b70cca263d5c/lib/trax/model.rb#L50-L54 | train |
mkulumadzi/mediawiki-keiki | lib/mediawiki-keiki/query.rb | MediaWiki.Query.pages | def pages
result_map = map_query_to_results
query_result["query"]["pages"].each do |key, value|
page_title = value["title"]
original_query = find_result_map_match_for_title(result_map, page_title)
@page_hash[original_query] = MediaWiki::Page.new(value)
end
@page_hash
end | ruby | def pages
result_map = map_query_to_results
query_result["query"]["pages"].each do |key, value|
page_title = value["title"]
original_query = find_result_map_match_for_title(result_map, page_title)
@page_hash[original_query] = MediaWiki::Page.new(value)
end
@page_hash
end | [
"def",
"pages",
"result_map",
"=",
"map_query_to_results",
"query_result",
"[",
"\"query\"",
"]",
"[",
"\"pages\"",
"]",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"page_title",
"=",
"value",
"[",
"\"title\"",
"]",
"original_query",
"=",
"find_result_map_match_for_title",
"(",
"result_map",
",",
"page_title",
")",
"@page_hash",
"[",
"original_query",
"]",
"=",
"MediaWiki",
"::",
"Page",
".",
"new",
"(",
"value",
")",
"end",
"@page_hash",
"end"
] | Returns a hash filled with Pages | [
"Returns",
"a",
"hash",
"filled",
"with",
"Pages"
] | 849338f643543f3a432d209f0413346d513c1e81 | https://github.com/mkulumadzi/mediawiki-keiki/blob/849338f643543f3a432d209f0413346d513c1e81/lib/mediawiki-keiki/query.rb#L32-L45 | train |
mkulumadzi/mediawiki-keiki | lib/mediawiki-keiki/query.rb | MediaWiki.Query.map_query_to_results | def map_query_to_results
#Initalize map
result_map = initialize_map
# Apply the normalization to the result map
normalized = get_query_map("normalized")
if normalized
result_map = get_normalizations_for(result_map, normalized)
end
# Apply the redirects to the result map
redirects = get_query_map("redirects")
if redirects
result_map = get_redirects_for(result_map, redirects)
end
result_map
end | ruby | def map_query_to_results
#Initalize map
result_map = initialize_map
# Apply the normalization to the result map
normalized = get_query_map("normalized")
if normalized
result_map = get_normalizations_for(result_map, normalized)
end
# Apply the redirects to the result map
redirects = get_query_map("redirects")
if redirects
result_map = get_redirects_for(result_map, redirects)
end
result_map
end | [
"def",
"map_query_to_results",
"#Initalize map",
"result_map",
"=",
"initialize_map",
"# Apply the normalization to the result map",
"normalized",
"=",
"get_query_map",
"(",
"\"normalized\"",
")",
"if",
"normalized",
"result_map",
"=",
"get_normalizations_for",
"(",
"result_map",
",",
"normalized",
")",
"end",
"# Apply the redirects to the result map",
"redirects",
"=",
"get_query_map",
"(",
"\"redirects\"",
")",
"if",
"redirects",
"result_map",
"=",
"get_redirects_for",
"(",
"result_map",
",",
"redirects",
")",
"end",
"result_map",
"end"
] | Maps original query to results | [
"Maps",
"original",
"query",
"to",
"results"
] | 849338f643543f3a432d209f0413346d513c1e81 | https://github.com/mkulumadzi/mediawiki-keiki/blob/849338f643543f3a432d209f0413346d513c1e81/lib/mediawiki-keiki/query.rb#L70-L89 | train |
alexdean/where_was_i | lib/where_was_i/track.rb | WhereWasI.Track.add_point | def add_point(lat:, lon:, elevation:, time:)
time = Time.parse(time) if ! time.is_a?(Time)
current = [lat, lon, elevation]
if @start_time.nil? || time < @start_time
@start_time = time
@start_location = current
end
if @end_time.nil? || time > @end_time
@end_time = time
@end_location = current
end
@points[time.to_i] = current
true
end | ruby | def add_point(lat:, lon:, elevation:, time:)
time = Time.parse(time) if ! time.is_a?(Time)
current = [lat, lon, elevation]
if @start_time.nil? || time < @start_time
@start_time = time
@start_location = current
end
if @end_time.nil? || time > @end_time
@end_time = time
@end_location = current
end
@points[time.to_i] = current
true
end | [
"def",
"add_point",
"(",
"lat",
":",
",",
"lon",
":",
",",
"elevation",
":",
",",
"time",
":",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"if",
"!",
"time",
".",
"is_a?",
"(",
"Time",
")",
"current",
"=",
"[",
"lat",
",",
"lon",
",",
"elevation",
"]",
"if",
"@start_time",
".",
"nil?",
"||",
"time",
"<",
"@start_time",
"@start_time",
"=",
"time",
"@start_location",
"=",
"current",
"end",
"if",
"@end_time",
".",
"nil?",
"||",
"time",
">",
"@end_time",
"@end_time",
"=",
"time",
"@end_location",
"=",
"current",
"end",
"@points",
"[",
"time",
".",
"to_i",
"]",
"=",
"current",
"true",
"end"
] | add a point to the track
@param [Float] lat latitude
@param [Float] lon longitude
@param [Float] elevation elevation
@param [Time] time time at the given location | [
"add",
"a",
"point",
"to",
"the",
"track"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/track.rb#L34-L52 | train |
alexdean/where_was_i | lib/where_was_i/track.rb | WhereWasI.Track.in_time_range? | def in_time_range?(time)
time = Time.parse(time) if ! time.is_a?(Time)
time_range.cover?(time)
end | ruby | def in_time_range?(time)
time = Time.parse(time) if ! time.is_a?(Time)
time_range.cover?(time)
end | [
"def",
"in_time_range?",
"(",
"time",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"if",
"!",
"time",
".",
"is_a?",
"(",
"Time",
")",
"time_range",
".",
"cover?",
"(",
"time",
")",
"end"
] | is the supplied time covered by this track?
@param time [Time]
@return Boolean | [
"is",
"the",
"supplied",
"time",
"covered",
"by",
"this",
"track?"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/track.rb#L65-L68 | train |
alexdean/where_was_i | lib/where_was_i/track.rb | WhereWasI.Track.at | def at(time)
if time.is_a?(String)
time = Time.parse(time)
end
if time.is_a?(Integer)
time = Time.at(time)
end
raise ArgumentError, "time must be a Time,String, or Fixnum" if ! time.is_a?(Time)
return nil if ! in_time_range?(time)
@interp ||= Interpolate::Points.new(@points)
data = @interp.at(time.to_i)
self.class.array_to_hash(data)
end | ruby | def at(time)
if time.is_a?(String)
time = Time.parse(time)
end
if time.is_a?(Integer)
time = Time.at(time)
end
raise ArgumentError, "time must be a Time,String, or Fixnum" if ! time.is_a?(Time)
return nil if ! in_time_range?(time)
@interp ||= Interpolate::Points.new(@points)
data = @interp.at(time.to_i)
self.class.array_to_hash(data)
end | [
"def",
"at",
"(",
"time",
")",
"if",
"time",
".",
"is_a?",
"(",
"String",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"end",
"if",
"time",
".",
"is_a?",
"(",
"Integer",
")",
"time",
"=",
"Time",
".",
"at",
"(",
"time",
")",
"end",
"raise",
"ArgumentError",
",",
"\"time must be a Time,String, or Fixnum\"",
"if",
"!",
"time",
".",
"is_a?",
"(",
"Time",
")",
"return",
"nil",
"if",
"!",
"in_time_range?",
"(",
"time",
")",
"@interp",
"||=",
"Interpolate",
"::",
"Points",
".",
"new",
"(",
"@points",
")",
"data",
"=",
"@interp",
".",
"at",
"(",
"time",
".",
"to_i",
")",
"self",
".",
"class",
".",
"array_to_hash",
"(",
"data",
")",
"end"
] | return the interpolated location for the given time
or nil if time is outside the track's start..end
@example
track.at(time) => {lat:48, lon:98, elevation: 2100}
@param time [String,Time,Fixnum]
@return [Hash,nil] | [
"return",
"the",
"interpolated",
"location",
"for",
"the",
"given",
"time",
"or",
"nil",
"if",
"time",
"is",
"outside",
"the",
"track",
"s",
"start",
"..",
"end"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/track.rb#L77-L92 | train |
rike422/loose-leaf | rakelib/task_helpers.rb | LooseLeaf.TaskHelpers.sh_in_dir | def sh_in_dir(dir, shell_commands)
shell_commands = [shell_commands] if shell_commands.is_a?(String)
shell_commands.each { |shell_command| sh %(cd #{dir} && #{shell_command.strip}) }
end | ruby | def sh_in_dir(dir, shell_commands)
shell_commands = [shell_commands] if shell_commands.is_a?(String)
shell_commands.each { |shell_command| sh %(cd #{dir} && #{shell_command.strip}) }
end | [
"def",
"sh_in_dir",
"(",
"dir",
",",
"shell_commands",
")",
"shell_commands",
"=",
"[",
"shell_commands",
"]",
"if",
"shell_commands",
".",
"is_a?",
"(",
"String",
")",
"shell_commands",
".",
"each",
"{",
"|",
"shell_command",
"|",
"sh",
"%(cd #{dir} && #{shell_command.strip})",
"}",
"end"
] | Executes a string or an array of strings in a shell in the given directory | [
"Executes",
"a",
"string",
"or",
"an",
"array",
"of",
"strings",
"in",
"a",
"shell",
"in",
"the",
"given",
"directory"
] | ea3cb93667f83e5f4abb3c7879fc0220157aeb81 | https://github.com/rike422/loose-leaf/blob/ea3cb93667f83e5f4abb3c7879fc0220157aeb81/rakelib/task_helpers.rb#L22-L25 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.create_deferred_indices | def create_deferred_indices(drop_existing = false)
@deferred_indices.each { |definition|
name = definition.index_name
if(drop_existing && self.indices.include?(name))
drop_index(name)
end
unless(self.indices.include?(name))
index = create_index(definition)
if(index.target_klass.respond_to?(:odba_extent))
index.fill(index.target_klass.odba_extent)
end
end
}
end | ruby | def create_deferred_indices(drop_existing = false)
@deferred_indices.each { |definition|
name = definition.index_name
if(drop_existing && self.indices.include?(name))
drop_index(name)
end
unless(self.indices.include?(name))
index = create_index(definition)
if(index.target_klass.respond_to?(:odba_extent))
index.fill(index.target_klass.odba_extent)
end
end
}
end | [
"def",
"create_deferred_indices",
"(",
"drop_existing",
"=",
"false",
")",
"@deferred_indices",
".",
"each",
"{",
"|",
"definition",
"|",
"name",
"=",
"definition",
".",
"index_name",
"if",
"(",
"drop_existing",
"&&",
"self",
".",
"indices",
".",
"include?",
"(",
"name",
")",
")",
"drop_index",
"(",
"name",
")",
"end",
"unless",
"(",
"self",
".",
"indices",
".",
"include?",
"(",
"name",
")",
")",
"index",
"=",
"create_index",
"(",
"definition",
")",
"if",
"(",
"index",
".",
"target_klass",
".",
"respond_to?",
"(",
":odba_extent",
")",
")",
"index",
".",
"fill",
"(",
"index",
".",
"target_klass",
".",
"odba_extent",
")",
"end",
"end",
"}",
"end"
] | Creates or recreates automatically defined indices | [
"Creates",
"or",
"recreates",
"automatically",
"defined",
"indices"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L130-L143 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.create_index | def create_index(index_definition, origin_module=Object)
transaction {
klass = if(index_definition.fulltext)
FulltextIndex
elsif(index_definition.resolve_search_term.is_a?(Hash))
ConditionIndex
else
Index
end
index = klass.new(index_definition, origin_module)
indices.store(index_definition.index_name, index)
indices.odba_store_unsaved
index
}
end | ruby | def create_index(index_definition, origin_module=Object)
transaction {
klass = if(index_definition.fulltext)
FulltextIndex
elsif(index_definition.resolve_search_term.is_a?(Hash))
ConditionIndex
else
Index
end
index = klass.new(index_definition, origin_module)
indices.store(index_definition.index_name, index)
indices.odba_store_unsaved
index
}
end | [
"def",
"create_index",
"(",
"index_definition",
",",
"origin_module",
"=",
"Object",
")",
"transaction",
"{",
"klass",
"=",
"if",
"(",
"index_definition",
".",
"fulltext",
")",
"FulltextIndex",
"elsif",
"(",
"index_definition",
".",
"resolve_search_term",
".",
"is_a?",
"(",
"Hash",
")",
")",
"ConditionIndex",
"else",
"Index",
"end",
"index",
"=",
"klass",
".",
"new",
"(",
"index_definition",
",",
"origin_module",
")",
"indices",
".",
"store",
"(",
"index_definition",
".",
"index_name",
",",
"index",
")",
"indices",
".",
"odba_store_unsaved",
"index",
"}",
"end"
] | Creates a new index according to IndexDefinition | [
"Creates",
"a",
"new",
"index",
"according",
"to",
"IndexDefinition"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L145-L159 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.delete | def delete(odba_object)
odba_id = odba_object.odba_id
name = odba_object.odba_name
odba_object.odba_notify_observers(:delete, odba_id, odba_object.object_id)
rows = ODBA.storage.retrieve_connected_objects(odba_id)
rows.each { |row|
id = row.first
# Self-Referencing objects don't have to be resaved
begin
if(connected_object = fetch(id, nil))
connected_object.odba_cut_connection(odba_object)
connected_object.odba_isolated_store
end
rescue OdbaError
warn "OdbaError ### deleting #{odba_object.class}:#{odba_id}"
warn " ### while looking for connected object #{id}"
end
}
delete_cache_entry(odba_id)
delete_cache_entry(name)
ODBA.storage.delete_persistable(odba_id)
delete_index_element(odba_object)
odba_object
end | ruby | def delete(odba_object)
odba_id = odba_object.odba_id
name = odba_object.odba_name
odba_object.odba_notify_observers(:delete, odba_id, odba_object.object_id)
rows = ODBA.storage.retrieve_connected_objects(odba_id)
rows.each { |row|
id = row.first
# Self-Referencing objects don't have to be resaved
begin
if(connected_object = fetch(id, nil))
connected_object.odba_cut_connection(odba_object)
connected_object.odba_isolated_store
end
rescue OdbaError
warn "OdbaError ### deleting #{odba_object.class}:#{odba_id}"
warn " ### while looking for connected object #{id}"
end
}
delete_cache_entry(odba_id)
delete_cache_entry(name)
ODBA.storage.delete_persistable(odba_id)
delete_index_element(odba_object)
odba_object
end | [
"def",
"delete",
"(",
"odba_object",
")",
"odba_id",
"=",
"odba_object",
".",
"odba_id",
"name",
"=",
"odba_object",
".",
"odba_name",
"odba_object",
".",
"odba_notify_observers",
"(",
":delete",
",",
"odba_id",
",",
"odba_object",
".",
"object_id",
")",
"rows",
"=",
"ODBA",
".",
"storage",
".",
"retrieve_connected_objects",
"(",
"odba_id",
")",
"rows",
".",
"each",
"{",
"|",
"row",
"|",
"id",
"=",
"row",
".",
"first",
"# Self-Referencing objects don't have to be resaved",
"begin",
"if",
"(",
"connected_object",
"=",
"fetch",
"(",
"id",
",",
"nil",
")",
")",
"connected_object",
".",
"odba_cut_connection",
"(",
"odba_object",
")",
"connected_object",
".",
"odba_isolated_store",
"end",
"rescue",
"OdbaError",
"warn",
"\"OdbaError ### deleting #{odba_object.class}:#{odba_id}\"",
"warn",
"\" ### while looking for connected object #{id}\"",
"end",
"}",
"delete_cache_entry",
"(",
"odba_id",
")",
"delete_cache_entry",
"(",
"name",
")",
"ODBA",
".",
"storage",
".",
"delete_persistable",
"(",
"odba_id",
")",
"delete_index_element",
"(",
"odba_object",
")",
"odba_object",
"end"
] | Permanently deletes _object_ from the database and deconnects all connected
Persistables | [
"Permanently",
"deletes",
"_object_",
"from",
"the",
"database",
"and",
"deconnects",
"all",
"connected",
"Persistables"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L162-L185 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.drop_index | def drop_index(index_name)
transaction {
ODBA.storage.drop_index(index_name)
self.delete(self.indices[index_name])
}
end | ruby | def drop_index(index_name)
transaction {
ODBA.storage.drop_index(index_name)
self.delete(self.indices[index_name])
}
end | [
"def",
"drop_index",
"(",
"index_name",
")",
"transaction",
"{",
"ODBA",
".",
"storage",
".",
"drop_index",
"(",
"index_name",
")",
"self",
".",
"delete",
"(",
"self",
".",
"indices",
"[",
"index_name",
"]",
")",
"}",
"end"
] | Permanently deletes the index named _index_name_ | [
"Permanently",
"deletes",
"the",
"index",
"named",
"_index_name_"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L199-L204 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.next_id | def next_id
if @file_lock
dbname = ODBA.storage.instance_variable_get('@dbi').dbi_args.first.split(/:/).last
id = new_id(dbname, ODBA.storage)
else
id = ODBA.storage.next_id
end
@peers.each do |peer|
peer.reserve_next_id id rescue DRb::DRbError
end
id
rescue OdbaDuplicateIdError
retry
end | ruby | def next_id
if @file_lock
dbname = ODBA.storage.instance_variable_get('@dbi').dbi_args.first.split(/:/).last
id = new_id(dbname, ODBA.storage)
else
id = ODBA.storage.next_id
end
@peers.each do |peer|
peer.reserve_next_id id rescue DRb::DRbError
end
id
rescue OdbaDuplicateIdError
retry
end | [
"def",
"next_id",
"if",
"@file_lock",
"dbname",
"=",
"ODBA",
".",
"storage",
".",
"instance_variable_get",
"(",
"'@dbi'",
")",
".",
"dbi_args",
".",
"first",
".",
"split",
"(",
"/",
"/",
")",
".",
"last",
"id",
"=",
"new_id",
"(",
"dbname",
",",
"ODBA",
".",
"storage",
")",
"else",
"id",
"=",
"ODBA",
".",
"storage",
".",
"next_id",
"end",
"@peers",
".",
"each",
"do",
"|",
"peer",
"|",
"peer",
".",
"reserve_next_id",
"id",
"rescue",
"DRb",
"::",
"DRbError",
"end",
"id",
"rescue",
"OdbaDuplicateIdError",
"retry",
"end"
] | Returns the next valid odba_id | [
"Returns",
"the",
"next",
"valid",
"odba_id"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L401-L414 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.retrieve_from_index | def retrieve_from_index(index_name, search_term, meta=nil)
index = indices.fetch(index_name)
ids = index.fetch_ids(search_term, meta)
if meta.respond_to?(:error_limit) && (limit = meta.error_limit) \
&& (size = ids.size) > limit.to_i
error = OdbaResultLimitError.new
error.limit = limit
error.size = size
error.index = index_name
error.search_term = search_term
error.meta = meta
raise error
end
bulk_fetch(ids, nil)
end | ruby | def retrieve_from_index(index_name, search_term, meta=nil)
index = indices.fetch(index_name)
ids = index.fetch_ids(search_term, meta)
if meta.respond_to?(:error_limit) && (limit = meta.error_limit) \
&& (size = ids.size) > limit.to_i
error = OdbaResultLimitError.new
error.limit = limit
error.size = size
error.index = index_name
error.search_term = search_term
error.meta = meta
raise error
end
bulk_fetch(ids, nil)
end | [
"def",
"retrieve_from_index",
"(",
"index_name",
",",
"search_term",
",",
"meta",
"=",
"nil",
")",
"index",
"=",
"indices",
".",
"fetch",
"(",
"index_name",
")",
"ids",
"=",
"index",
".",
"fetch_ids",
"(",
"search_term",
",",
"meta",
")",
"if",
"meta",
".",
"respond_to?",
"(",
":error_limit",
")",
"&&",
"(",
"limit",
"=",
"meta",
".",
"error_limit",
")",
"&&",
"(",
"size",
"=",
"ids",
".",
"size",
")",
">",
"limit",
".",
"to_i",
"error",
"=",
"OdbaResultLimitError",
".",
"new",
"error",
".",
"limit",
"=",
"limit",
"error",
".",
"size",
"=",
"size",
"error",
".",
"index",
"=",
"index_name",
"error",
".",
"search_term",
"=",
"search_term",
"error",
".",
"meta",
"=",
"meta",
"raise",
"error",
"end",
"bulk_fetch",
"(",
"ids",
",",
"nil",
")",
"end"
] | Find objects in an index | [
"Find",
"objects",
"in",
"an",
"index"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L457-L471 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.store | def store(object)
odba_id = object.odba_id
name = object.odba_name
object.odba_notify_observers(:store, odba_id, object.object_id)
if(ids = Thread.current[:txids])
ids.unshift([odba_id,name])
end
## get target_ids before anything else
target_ids = object.odba_target_ids
changes = store_collection_elements(object)
prefetchable = object.odba_prefetch?
dump = object.odba_isolated_dump
ODBA.storage.store(odba_id, dump, name, prefetchable, object.class)
store_object_connections(odba_id, target_ids)
update_references(target_ids, object)
object = store_cache_entry(odba_id, object, name)
update_indices(object)
@peers.each do |peer|
peer.invalidate! odba_id rescue DRb::DRbError
end
object
end | ruby | def store(object)
odba_id = object.odba_id
name = object.odba_name
object.odba_notify_observers(:store, odba_id, object.object_id)
if(ids = Thread.current[:txids])
ids.unshift([odba_id,name])
end
## get target_ids before anything else
target_ids = object.odba_target_ids
changes = store_collection_elements(object)
prefetchable = object.odba_prefetch?
dump = object.odba_isolated_dump
ODBA.storage.store(odba_id, dump, name, prefetchable, object.class)
store_object_connections(odba_id, target_ids)
update_references(target_ids, object)
object = store_cache_entry(odba_id, object, name)
update_indices(object)
@peers.each do |peer|
peer.invalidate! odba_id rescue DRb::DRbError
end
object
end | [
"def",
"store",
"(",
"object",
")",
"odba_id",
"=",
"object",
".",
"odba_id",
"name",
"=",
"object",
".",
"odba_name",
"object",
".",
"odba_notify_observers",
"(",
":store",
",",
"odba_id",
",",
"object",
".",
"object_id",
")",
"if",
"(",
"ids",
"=",
"Thread",
".",
"current",
"[",
":txids",
"]",
")",
"ids",
".",
"unshift",
"(",
"[",
"odba_id",
",",
"name",
"]",
")",
"end",
"## get target_ids before anything else",
"target_ids",
"=",
"object",
".",
"odba_target_ids",
"changes",
"=",
"store_collection_elements",
"(",
"object",
")",
"prefetchable",
"=",
"object",
".",
"odba_prefetch?",
"dump",
"=",
"object",
".",
"odba_isolated_dump",
"ODBA",
".",
"storage",
".",
"store",
"(",
"odba_id",
",",
"dump",
",",
"name",
",",
"prefetchable",
",",
"object",
".",
"class",
")",
"store_object_connections",
"(",
"odba_id",
",",
"target_ids",
")",
"update_references",
"(",
"target_ids",
",",
"object",
")",
"object",
"=",
"store_cache_entry",
"(",
"odba_id",
",",
"object",
",",
"name",
")",
"update_indices",
"(",
"object",
")",
"@peers",
".",
"each",
"do",
"|",
"peer",
"|",
"peer",
".",
"invalidate!",
"odba_id",
"rescue",
"DRb",
"::",
"DRbError",
"end",
"object",
"end"
] | Store a Persistable _object_ in the database | [
"Store",
"a",
"Persistable",
"_object_",
"in",
"the",
"database"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L500-L521 | train |
timotheeguerin/i18n_admin_utils | app/helpers/i18n_admin_utils/application_helper.rb | I18nAdminUtils.ApplicationHelper.translation_missing_icon | def translation_missing_icon(translation)
missing_translations = translation.missing_translations
color_id = (missing_translations.size.to_f/translation.translations.size.to_f*5).ceil-1
if missing_translations.size == 0
content_tag 'span', '', :class => 'glyphicon glyphicon-ok greentext',
:title => 'This key has been translated in all languages', :rel => 'tooltip'
else
content_tag 'span', "(#{missing_translations.size})", :class => "color-range-#{color_id} bold",
:title => missing_translations.keys.join(','), :rel => 'tooltip'
end
end | ruby | def translation_missing_icon(translation)
missing_translations = translation.missing_translations
color_id = (missing_translations.size.to_f/translation.translations.size.to_f*5).ceil-1
if missing_translations.size == 0
content_tag 'span', '', :class => 'glyphicon glyphicon-ok greentext',
:title => 'This key has been translated in all languages', :rel => 'tooltip'
else
content_tag 'span', "(#{missing_translations.size})", :class => "color-range-#{color_id} bold",
:title => missing_translations.keys.join(','), :rel => 'tooltip'
end
end | [
"def",
"translation_missing_icon",
"(",
"translation",
")",
"missing_translations",
"=",
"translation",
".",
"missing_translations",
"color_id",
"=",
"(",
"missing_translations",
".",
"size",
".",
"to_f",
"/",
"translation",
".",
"translations",
".",
"size",
".",
"to_f",
"5",
")",
".",
"ceil",
"-",
"1",
"if",
"missing_translations",
".",
"size",
"==",
"0",
"content_tag",
"'span'",
",",
"''",
",",
":class",
"=>",
"'glyphicon glyphicon-ok greentext'",
",",
":title",
"=>",
"'This key has been translated in all languages'",
",",
":rel",
"=>",
"'tooltip'",
"else",
"content_tag",
"'span'",
",",
"\"(#{missing_translations.size})\"",
",",
":class",
"=>",
"\"color-range-#{color_id} bold\"",
",",
":title",
"=>",
"missing_translations",
".",
"keys",
".",
"join",
"(",
"','",
")",
",",
":rel",
"=>",
"'tooltip'",
"end",
"end"
] | Show the number of translation missing with colorization | [
"Show",
"the",
"number",
"of",
"translation",
"missing",
"with",
"colorization"
] | c45c10e9707f3b876b8b37d120d77e46b25e1783 | https://github.com/timotheeguerin/i18n_admin_utils/blob/c45c10e9707f3b876b8b37d120d77e46b25e1783/app/helpers/i18n_admin_utils/application_helper.rb#L5-L15 | train |
cbrumelle/blueprintr | lib/blueprint-css/lib/blueprint/namespace.rb | Blueprint.Namespace.add_namespace | def add_namespace(html, namespace)
html.gsub!(/(class=")([a-zA-Z0-9\-_ ]*)(")/) do |m|
classes = m.to_s.split('"')[1].split(' ')
classes.map! { |c| c = namespace + c }
'class="' + classes.join(' ') + '"'
end
html
end | ruby | def add_namespace(html, namespace)
html.gsub!(/(class=")([a-zA-Z0-9\-_ ]*)(")/) do |m|
classes = m.to_s.split('"')[1].split(' ')
classes.map! { |c| c = namespace + c }
'class="' + classes.join(' ') + '"'
end
html
end | [
"def",
"add_namespace",
"(",
"html",
",",
"namespace",
")",
"html",
".",
"gsub!",
"(",
"/",
"\\-",
"/",
")",
"do",
"|",
"m",
"|",
"classes",
"=",
"m",
".",
"to_s",
".",
"split",
"(",
"'\"'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"' '",
")",
"classes",
".",
"map!",
"{",
"|",
"c",
"|",
"c",
"=",
"namespace",
"+",
"c",
"}",
"'class=\"'",
"+",
"classes",
".",
"join",
"(",
"' '",
")",
"+",
"'\"'",
"end",
"html",
"end"
] | Read html to string, remove namespace if any,
set the new namespace, and update the test file.
adds namespace to BP classes in a html file | [
"Read",
"html",
"to",
"string",
"remove",
"namespace",
"if",
"any",
"set",
"the",
"new",
"namespace",
"and",
"update",
"the",
"test",
"file",
".",
"adds",
"namespace",
"to",
"BP",
"classes",
"in",
"a",
"html",
"file"
] | b414436f614a8d97d77b47b588ddcf3f5e61b6bd | https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/namespace.rb#L14-L21 | train |
johnwunder/stix_schema_spy | lib/stix_schema_spy/models/simple_type.rb | StixSchemaSpy.SimpleType.enumeration_values | def enumeration_values
enumeration = @xml.xpath('./xs:restriction/xs:enumeration', {'xs' => 'http://www.w3.org/2001/XMLSchema'})
if enumeration.length > 0
return enumeration.map {|elem| [elem.attributes['value'].value, elem.xpath('./xs:annotation/xs:documentation', {'xs' => 'http://www.w3.org/2001/XMLSchema'}).text]}
else
raise "Not an enumeration"
end
end | ruby | def enumeration_values
enumeration = @xml.xpath('./xs:restriction/xs:enumeration', {'xs' => 'http://www.w3.org/2001/XMLSchema'})
if enumeration.length > 0
return enumeration.map {|elem| [elem.attributes['value'].value, elem.xpath('./xs:annotation/xs:documentation', {'xs' => 'http://www.w3.org/2001/XMLSchema'}).text]}
else
raise "Not an enumeration"
end
end | [
"def",
"enumeration_values",
"enumeration",
"=",
"@xml",
".",
"xpath",
"(",
"'./xs:restriction/xs:enumeration'",
",",
"{",
"'xs'",
"=>",
"'http://www.w3.org/2001/XMLSchema'",
"}",
")",
"if",
"enumeration",
".",
"length",
">",
"0",
"return",
"enumeration",
".",
"map",
"{",
"|",
"elem",
"|",
"[",
"elem",
".",
"attributes",
"[",
"'value'",
"]",
".",
"value",
",",
"elem",
".",
"xpath",
"(",
"'./xs:annotation/xs:documentation'",
",",
"{",
"'xs'",
"=>",
"'http://www.w3.org/2001/XMLSchema'",
"}",
")",
".",
"text",
"]",
"}",
"else",
"raise",
"\"Not an enumeration\"",
"end",
"end"
] | Returns the list of values for this enumeration | [
"Returns",
"the",
"list",
"of",
"values",
"for",
"this",
"enumeration"
] | 2d551c6854d749eb330340e69f73baee1c4b52d3 | https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/simple_type.rb#L16-L23 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/categories.rb | LatoBlog.Interface::Categories.blog__create_default_category | def blog__create_default_category
category_parent = LatoBlog::CategoryParent.find_by(meta_default: true)
return if category_parent
category_parent = LatoBlog::CategoryParent.new(meta_default: true)
throw 'Impossible to create default category parent' unless category_parent.save
languages = blog__get_languages_identifier
languages.each do |language|
category = LatoBlog::Category.new(
title: 'Default',
meta_permalink: "default_#{language}",
meta_language: language,
lato_core_superuser_creator_id: 1,
lato_blog_category_parent_id: category_parent.id
)
throw 'Impossible to create default category' unless category.save
end
end | ruby | def blog__create_default_category
category_parent = LatoBlog::CategoryParent.find_by(meta_default: true)
return if category_parent
category_parent = LatoBlog::CategoryParent.new(meta_default: true)
throw 'Impossible to create default category parent' unless category_parent.save
languages = blog__get_languages_identifier
languages.each do |language|
category = LatoBlog::Category.new(
title: 'Default',
meta_permalink: "default_#{language}",
meta_language: language,
lato_core_superuser_creator_id: 1,
lato_blog_category_parent_id: category_parent.id
)
throw 'Impossible to create default category' unless category.save
end
end | [
"def",
"blog__create_default_category",
"category_parent",
"=",
"LatoBlog",
"::",
"CategoryParent",
".",
"find_by",
"(",
"meta_default",
":",
"true",
")",
"return",
"if",
"category_parent",
"category_parent",
"=",
"LatoBlog",
"::",
"CategoryParent",
".",
"new",
"(",
"meta_default",
":",
"true",
")",
"throw",
"'Impossible to create default category parent'",
"unless",
"category_parent",
".",
"save",
"languages",
"=",
"blog__get_languages_identifier",
"languages",
".",
"each",
"do",
"|",
"language",
"|",
"category",
"=",
"LatoBlog",
"::",
"Category",
".",
"new",
"(",
"title",
":",
"'Default'",
",",
"meta_permalink",
":",
"\"default_#{language}\"",
",",
"meta_language",
":",
"language",
",",
"lato_core_superuser_creator_id",
":",
"1",
",",
"lato_blog_category_parent_id",
":",
"category_parent",
".",
"id",
")",
"throw",
"'Impossible to create default category'",
"unless",
"category",
".",
"save",
"end",
"end"
] | This function create the default category if it not exists. | [
"This",
"function",
"create",
"the",
"default",
"category",
"if",
"it",
"not",
"exists",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L7-L25 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/categories.rb | LatoBlog.Interface::Categories.blog__clean_category_parents | def blog__clean_category_parents
category_parents = LatoBlog::CategoryParent.all
category_parents.map { |cp| cp.destroy if cp.categories.empty? }
end | ruby | def blog__clean_category_parents
category_parents = LatoBlog::CategoryParent.all
category_parents.map { |cp| cp.destroy if cp.categories.empty? }
end | [
"def",
"blog__clean_category_parents",
"category_parents",
"=",
"LatoBlog",
"::",
"CategoryParent",
".",
"all",
"category_parents",
".",
"map",
"{",
"|",
"cp",
"|",
"cp",
".",
"destroy",
"if",
"cp",
".",
"categories",
".",
"empty?",
"}",
"end"
] | This function cleans all old category parents without any child. | [
"This",
"function",
"cleans",
"all",
"old",
"category",
"parents",
"without",
"any",
"child",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L28-L31 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/categories.rb | LatoBlog.Interface::Categories.blog__get_categories | def blog__get_categories(
order: nil,
language: nil,
search: nil,
page: nil,
per_page: nil
)
categories = LatoBlog::Category.all
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
categories = _categories_filter_by_order(categories, order)
categories = _categories_filter_by_language(categories, language)
categories = _categories_filter_search(categories, search)
# take categories uniqueness
categories = categories.uniq(&:id)
# save total categories
total = categories.length
# manage pagination
page = page&.to_i || 1
per_page = per_page&.to_i || 20
categories = core__paginate_array(categories, per_page, page)
# return result
{
categories: categories && !categories.empty? ? categories.map(&:serialize) : [],
page: page,
per_page: per_page,
order: order,
total: total
}
end | ruby | def blog__get_categories(
order: nil,
language: nil,
search: nil,
page: nil,
per_page: nil
)
categories = LatoBlog::Category.all
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
categories = _categories_filter_by_order(categories, order)
categories = _categories_filter_by_language(categories, language)
categories = _categories_filter_search(categories, search)
# take categories uniqueness
categories = categories.uniq(&:id)
# save total categories
total = categories.length
# manage pagination
page = page&.to_i || 1
per_page = per_page&.to_i || 20
categories = core__paginate_array(categories, per_page, page)
# return result
{
categories: categories && !categories.empty? ? categories.map(&:serialize) : [],
page: page,
per_page: per_page,
order: order,
total: total
}
end | [
"def",
"blog__get_categories",
"(",
"order",
":",
"nil",
",",
"language",
":",
"nil",
",",
"search",
":",
"nil",
",",
"page",
":",
"nil",
",",
"per_page",
":",
"nil",
")",
"categories",
"=",
"LatoBlog",
"::",
"Category",
".",
"all",
"# apply filters",
"order",
"=",
"order",
"&&",
"order",
"==",
"'ASC'",
"?",
"'ASC'",
":",
"'DESC'",
"categories",
"=",
"_categories_filter_by_order",
"(",
"categories",
",",
"order",
")",
"categories",
"=",
"_categories_filter_by_language",
"(",
"categories",
",",
"language",
")",
"categories",
"=",
"_categories_filter_search",
"(",
"categories",
",",
"search",
")",
"# take categories uniqueness",
"categories",
"=",
"categories",
".",
"uniq",
"(",
":id",
")",
"# save total categories",
"total",
"=",
"categories",
".",
"length",
"# manage pagination",
"page",
"=",
"page",
"&.",
"to_i",
"||",
"1",
"per_page",
"=",
"per_page",
"&.",
"to_i",
"||",
"20",
"categories",
"=",
"core__paginate_array",
"(",
"categories",
",",
"per_page",
",",
"page",
")",
"# return result",
"{",
"categories",
":",
"categories",
"&&",
"!",
"categories",
".",
"empty?",
"?",
"categories",
".",
"map",
"(",
":serialize",
")",
":",
"[",
"]",
",",
"page",
":",
"page",
",",
"per_page",
":",
"per_page",
",",
"order",
":",
"order",
",",
"total",
":",
"total",
"}",
"end"
] | This function returns an object with the list of categories with some filters. | [
"This",
"function",
"returns",
"an",
"object",
"with",
"the",
"list",
"of",
"categories",
"with",
"some",
"filters",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L34-L68 | train |
davidbarral/sugarfree-config | lib/sugarfree-config/config.rb | SugarfreeConfig.Config.fetch_config | def fetch_config
Rails.logger.debug "Loading #{@file}::#{@env}" if Object.const_defined?('Rails') && Rails.logger.present?
YAML::load_file(@file)[@env.to_s]
end | ruby | def fetch_config
Rails.logger.debug "Loading #{@file}::#{@env}" if Object.const_defined?('Rails') && Rails.logger.present?
YAML::load_file(@file)[@env.to_s]
end | [
"def",
"fetch_config",
"Rails",
".",
"logger",
".",
"debug",
"\"Loading #{@file}::#{@env}\"",
"if",
"Object",
".",
"const_defined?",
"(",
"'Rails'",
")",
"&&",
"Rails",
".",
"logger",
".",
"present?",
"YAML",
"::",
"load_file",
"(",
"@file",
")",
"[",
"@env",
".",
"to_s",
"]",
"end"
] | Fetch the config from the file | [
"Fetch",
"the",
"config",
"from",
"the",
"file"
] | 76b590627d50cd50b237c21fdf8ea3022ebbdf42 | https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L47-L50 | train |
davidbarral/sugarfree-config | lib/sugarfree-config/config.rb | SugarfreeConfig.Config.default_options | def default_options
if Object.const_defined?('Rails')
{
:file => Rails.root.join('config', 'config.yml'),
:reload => Rails.env.development?,
:env => Rails.env
}
else
{
:file => File.expand_path("config.yml"),
:reload => false,
:env => "development"
}
end
end | ruby | def default_options
if Object.const_defined?('Rails')
{
:file => Rails.root.join('config', 'config.yml'),
:reload => Rails.env.development?,
:env => Rails.env
}
else
{
:file => File.expand_path("config.yml"),
:reload => false,
:env => "development"
}
end
end | [
"def",
"default_options",
"if",
"Object",
".",
"const_defined?",
"(",
"'Rails'",
")",
"{",
":file",
"=>",
"Rails",
".",
"root",
".",
"join",
"(",
"'config'",
",",
"'config.yml'",
")",
",",
":reload",
"=>",
"Rails",
".",
"env",
".",
"development?",
",",
":env",
"=>",
"Rails",
".",
"env",
"}",
"else",
"{",
":file",
"=>",
"File",
".",
"expand_path",
"(",
"\"config.yml\"",
")",
",",
":reload",
"=>",
"false",
",",
":env",
"=>",
"\"development\"",
"}",
"end",
"end"
] | Default configuration options for Rails and non Rails applications | [
"Default",
"configuration",
"options",
"for",
"Rails",
"and",
"non",
"Rails",
"applications"
] | 76b590627d50cd50b237c21fdf8ea3022ebbdf42 | https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L55-L69 | train |
davidbarral/sugarfree-config | lib/sugarfree-config/config.rb | SugarfreeConfig.ConfigIterator.next | def next
if (value = @scoped_config[@path_elements.last]).nil?
raise ConfigKeyException.new(@path_elements)
elsif value.is_a?(Hash)
@scoped_config = value
self
else
value
end
end | ruby | def next
if (value = @scoped_config[@path_elements.last]).nil?
raise ConfigKeyException.new(@path_elements)
elsif value.is_a?(Hash)
@scoped_config = value
self
else
value
end
end | [
"def",
"next",
"if",
"(",
"value",
"=",
"@scoped_config",
"[",
"@path_elements",
".",
"last",
"]",
")",
".",
"nil?",
"raise",
"ConfigKeyException",
".",
"new",
"(",
"@path_elements",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"@scoped_config",
"=",
"value",
"self",
"else",
"value",
"end",
"end"
] | Iterate to the next element in the path
Algorithm:
1. Get the last element of the key path
2. Try to find it in the scoped config
3. If not present raise an error
4. If present and is a hash we are not in a config leaf, so the scoped
config is reset to this new value and self is returned
5. If present and is a value then return the value | [
"Iterate",
"to",
"the",
"next",
"element",
"in",
"the",
"path"
] | 76b590627d50cd50b237c21fdf8ea3022ebbdf42 | https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L117-L126 | train |
heelhook/class-proxy | lib/classproxy/classproxy.rb | ClassProxy.ClassMethods.proxy_methods | def proxy_methods(*methods)
@_methods ||= {}
methods.each do |method|
if method.is_a? Symbol
# If given a symbol, store as a method to overwrite and use the default loader
proxy_method method
elsif method.is_a? Hash
# If its a hash it will include methods to overwrite along with custom loaders
method.each { |method_name, proc| proxy_method method_name, proc }
end
end
end | ruby | def proxy_methods(*methods)
@_methods ||= {}
methods.each do |method|
if method.is_a? Symbol
# If given a symbol, store as a method to overwrite and use the default loader
proxy_method method
elsif method.is_a? Hash
# If its a hash it will include methods to overwrite along with custom loaders
method.each { |method_name, proc| proxy_method method_name, proc }
end
end
end | [
"def",
"proxy_methods",
"(",
"*",
"methods",
")",
"@_methods",
"||=",
"{",
"}",
"methods",
".",
"each",
"do",
"|",
"method",
"|",
"if",
"method",
".",
"is_a?",
"Symbol",
"# If given a symbol, store as a method to overwrite and use the default loader",
"proxy_method",
"method",
"elsif",
"method",
".",
"is_a?",
"Hash",
"# If its a hash it will include methods to overwrite along with custom loaders",
"method",
".",
"each",
"{",
"|",
"method_name",
",",
"proc",
"|",
"proxy_method",
"method_name",
",",
"proc",
"}",
"end",
"end",
"end"
] | Establish attributes to proxy along with an alternative proc of how
the attribute should be loaded
@example Load method using uppercase
class GithubUser
include ClassProxy
fallback_fetch { |args| Octokit.user(args[:login]) }
after_fallback_fetch { |obj| self.name = obj.name; self.login = obj.login }
attr_accessor :name, :followers :login
proxy_methods :name, :followers, uppercase_login: lambda { login.upcase }
end
user = GithubUser.find(login: 'heelhook')
user.login # -> 'heelhook'
user.uppercase_login # -> 'HEELHOOK' | [
"Establish",
"attributes",
"to",
"proxy",
"along",
"with",
"an",
"alternative",
"proc",
"of",
"how",
"the",
"attribute",
"should",
"be",
"loaded"
] | df69405274133a359aa65e393205c61d47dd5362 | https://github.com/heelhook/class-proxy/blob/df69405274133a359aa65e393205c61d47dd5362/lib/classproxy/classproxy.rb#L63-L75 | train |
heelhook/class-proxy | lib/classproxy/classproxy.rb | ClassProxy.ClassMethods.fetch | def fetch(args, options={})
@primary_fetch.is_a?(Proc) ? @primary_fetch[args] : (raise NotFound)
rescue NotFound
return nil if options[:skip_fallback]
run_fallback(args)
end | ruby | def fetch(args, options={})
@primary_fetch.is_a?(Proc) ? @primary_fetch[args] : (raise NotFound)
rescue NotFound
return nil if options[:skip_fallback]
run_fallback(args)
end | [
"def",
"fetch",
"(",
"args",
",",
"options",
"=",
"{",
"}",
")",
"@primary_fetch",
".",
"is_a?",
"(",
"Proc",
")",
"?",
"@primary_fetch",
"[",
"args",
"]",
":",
"(",
"raise",
"NotFound",
")",
"rescue",
"NotFound",
"return",
"nil",
"if",
"options",
"[",
":skip_fallback",
"]",
"run_fallback",
"(",
"args",
")",
"end"
] | Method to find a record using a hash as the criteria
@example
class GithubUser
include MongoMapper::Document
include ClassProxy
primary_fetch { |args| where(args).first or (raise NotFound) }
fallback_fetch { |args| Octokit.user(args[:login]) }
end
GithubUser.fetch(login: 'heelhook') # -> Uses primary_fetch
# -> and, if NotFound, fallback_fetch
@param [ Hash ] args The criteria to use
@options options [ true, false] :skip_fallback Don't use fallback methods | [
"Method",
"to",
"find",
"a",
"record",
"using",
"a",
"hash",
"as",
"the",
"criteria"
] | df69405274133a359aa65e393205c61d47dd5362 | https://github.com/heelhook/class-proxy/blob/df69405274133a359aa65e393205c61d47dd5362/lib/classproxy/classproxy.rb#L93-L99 | train |
dominikh/weechat-ruby | lib/weechat/plugin.rb | Weechat.Plugin.unload | def unload(force = false)
if name == "ruby" and !force
Weechat.puts "Won't unload the ruby plugin unless you force it."
false
else
Weechat.exec("/plugin unload #{name}")
true
end
end | ruby | def unload(force = false)
if name == "ruby" and !force
Weechat.puts "Won't unload the ruby plugin unless you force it."
false
else
Weechat.exec("/plugin unload #{name}")
true
end
end | [
"def",
"unload",
"(",
"force",
"=",
"false",
")",
"if",
"name",
"==",
"\"ruby\"",
"and",
"!",
"force",
"Weechat",
".",
"puts",
"\"Won't unload the ruby plugin unless you force it.\"",
"false",
"else",
"Weechat",
".",
"exec",
"(",
"\"/plugin unload #{name}\"",
")",
"true",
"end",
"end"
] | Unloads the plugin.
@param [Boolean] force If the plugin to be unloaded is "ruby",
+force+ has to be true.
@return [Boolean] true if we attempted to unload the plugin | [
"Unloads",
"the",
"plugin",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/plugin.rb#L70-L78 | train |
dominikh/weechat-ruby | lib/weechat/plugin.rb | Weechat.Plugin.scripts | def scripts
scripts = []
Infolist.parse("#{name}_script").each do |script|
scripts << Script.new(script[:pointer], self)
end
scripts
end | ruby | def scripts
scripts = []
Infolist.parse("#{name}_script").each do |script|
scripts << Script.new(script[:pointer], self)
end
scripts
end | [
"def",
"scripts",
"scripts",
"=",
"[",
"]",
"Infolist",
".",
"parse",
"(",
"\"#{name}_script\"",
")",
".",
"each",
"do",
"|",
"script",
"|",
"scripts",
"<<",
"Script",
".",
"new",
"(",
"script",
"[",
":pointer",
"]",
",",
"self",
")",
"end",
"scripts",
"end"
] | Returns an array of all scripts loaded by this plugin.
@return [Array<Script>] | [
"Returns",
"an",
"array",
"of",
"all",
"scripts",
"loaded",
"by",
"this",
"plugin",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/plugin.rb#L95-L101 | train |
whyarkadas/http_ping | lib/HttpPing/wmi.rb | HttpPing.HttpPing::WMI.ping | def ping(host = @host, options = {})
super(host)
lhost = Socket.gethostname
cs = "winmgmts:{impersonationLevel=impersonate}!//#{lhost}/root/cimv2"
wmi = WIN32OLE.connect(cs)
query = "select * from win32_pingstatus where address = '#{host}'"
unless options.empty?
options.each{ |key, value|
if value.is_a?(String)
query << " and #{key} = '#{value}'"
else
query << " and #{key} = #{value}"
end
}
end
status = Struct::PingStatus.new
wmi.execquery(query).each{ |obj|
status.address = obj.Address
status.buffer_size = obj.BufferSize
status.no_fragmentation = obj.NoFragmentation
status.primary_address_resolution_status = obj.PrimaryAddressResolutionStatus
status.protocol_address = obj.ProtocolAddress
status.protocol_address_resolved = obj.ProtocolAddressResolved
status.record_route = obj.RecordRoute
status.reply_inconsistency = obj.ReplyInconsistency
status.reply_size = obj.ReplySize
status.resolve_address_names = obj.ResolveAddressNames
status.response_time = obj.ResponseTime
status.response_time_to_live = obj.ResponseTimeToLive
status.route_record = obj.RouteRecord
status.route_record_resolved = obj.RouteRecordResolved
status.source_route = obj.SourceRoute
status.source_route_type = obj.SourceRouteType
status.status_code = obj.StatusCode
status.timeout = obj.Timeout
status.timestamp_record = obj.TimeStampRecord
status.timestamp_record_address = obj.TimeStampRecordAddress
status.timestamp_record_address_resolved = obj.TimeStampRecordAddressResolved
status.timestamp_route = obj.TimeStampRoute
status.time_to_live = obj.TimeToLive
status.type_of_service = obj.TypeOfService
}
status.freeze # Read-only data
end | ruby | def ping(host = @host, options = {})
super(host)
lhost = Socket.gethostname
cs = "winmgmts:{impersonationLevel=impersonate}!//#{lhost}/root/cimv2"
wmi = WIN32OLE.connect(cs)
query = "select * from win32_pingstatus where address = '#{host}'"
unless options.empty?
options.each{ |key, value|
if value.is_a?(String)
query << " and #{key} = '#{value}'"
else
query << " and #{key} = #{value}"
end
}
end
status = Struct::PingStatus.new
wmi.execquery(query).each{ |obj|
status.address = obj.Address
status.buffer_size = obj.BufferSize
status.no_fragmentation = obj.NoFragmentation
status.primary_address_resolution_status = obj.PrimaryAddressResolutionStatus
status.protocol_address = obj.ProtocolAddress
status.protocol_address_resolved = obj.ProtocolAddressResolved
status.record_route = obj.RecordRoute
status.reply_inconsistency = obj.ReplyInconsistency
status.reply_size = obj.ReplySize
status.resolve_address_names = obj.ResolveAddressNames
status.response_time = obj.ResponseTime
status.response_time_to_live = obj.ResponseTimeToLive
status.route_record = obj.RouteRecord
status.route_record_resolved = obj.RouteRecordResolved
status.source_route = obj.SourceRoute
status.source_route_type = obj.SourceRouteType
status.status_code = obj.StatusCode
status.timeout = obj.Timeout
status.timestamp_record = obj.TimeStampRecord
status.timestamp_record_address = obj.TimeStampRecordAddress
status.timestamp_record_address_resolved = obj.TimeStampRecordAddressResolved
status.timestamp_route = obj.TimeStampRoute
status.time_to_live = obj.TimeToLive
status.type_of_service = obj.TypeOfService
}
status.freeze # Read-only data
end | [
"def",
"ping",
"(",
"host",
"=",
"@host",
",",
"options",
"=",
"{",
"}",
")",
"super",
"(",
"host",
")",
"lhost",
"=",
"Socket",
".",
"gethostname",
"cs",
"=",
"\"winmgmts:{impersonationLevel=impersonate}!//#{lhost}/root/cimv2\"",
"wmi",
"=",
"WIN32OLE",
".",
"connect",
"(",
"cs",
")",
"query",
"=",
"\"select * from win32_pingstatus where address = '#{host}'\"",
"unless",
"options",
".",
"empty?",
"options",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"String",
")",
"query",
"<<",
"\" and #{key} = '#{value}'\"",
"else",
"query",
"<<",
"\" and #{key} = #{value}\"",
"end",
"}",
"end",
"status",
"=",
"Struct",
"::",
"PingStatus",
".",
"new",
"wmi",
".",
"execquery",
"(",
"query",
")",
".",
"each",
"{",
"|",
"obj",
"|",
"status",
".",
"address",
"=",
"obj",
".",
"Address",
"status",
".",
"buffer_size",
"=",
"obj",
".",
"BufferSize",
"status",
".",
"no_fragmentation",
"=",
"obj",
".",
"NoFragmentation",
"status",
".",
"primary_address_resolution_status",
"=",
"obj",
".",
"PrimaryAddressResolutionStatus",
"status",
".",
"protocol_address",
"=",
"obj",
".",
"ProtocolAddress",
"status",
".",
"protocol_address_resolved",
"=",
"obj",
".",
"ProtocolAddressResolved",
"status",
".",
"record_route",
"=",
"obj",
".",
"RecordRoute",
"status",
".",
"reply_inconsistency",
"=",
"obj",
".",
"ReplyInconsistency",
"status",
".",
"reply_size",
"=",
"obj",
".",
"ReplySize",
"status",
".",
"resolve_address_names",
"=",
"obj",
".",
"ResolveAddressNames",
"status",
".",
"response_time",
"=",
"obj",
".",
"ResponseTime",
"status",
".",
"response_time_to_live",
"=",
"obj",
".",
"ResponseTimeToLive",
"status",
".",
"route_record",
"=",
"obj",
".",
"RouteRecord",
"status",
".",
"route_record_resolved",
"=",
"obj",
".",
"RouteRecordResolved",
"status",
".",
"source_route",
"=",
"obj",
".",
"SourceRoute",
"status",
".",
"source_route_type",
"=",
"obj",
".",
"SourceRouteType",
"status",
".",
"status_code",
"=",
"obj",
".",
"StatusCode",
"status",
".",
"timeout",
"=",
"obj",
".",
"Timeout",
"status",
".",
"timestamp_record",
"=",
"obj",
".",
"TimeStampRecord",
"status",
".",
"timestamp_record_address",
"=",
"obj",
".",
"TimeStampRecordAddress",
"status",
".",
"timestamp_record_address_resolved",
"=",
"obj",
".",
"TimeStampRecordAddressResolved",
"status",
".",
"timestamp_route",
"=",
"obj",
".",
"TimeStampRoute",
"status",
".",
"time_to_live",
"=",
"obj",
".",
"TimeToLive",
"status",
".",
"type_of_service",
"=",
"obj",
".",
"TypeOfService",
"}",
"status",
".",
"freeze",
"# Read-only data",
"end"
] | Unlike the ping method for other Ping subclasses, this version returns
a PingStatus struct which contains various bits of information about
the results of the ping itself, such as response time.
In addition, this version allows you to pass certain options that are
then passed on to the underlying WQL query. See the MSDN documentation
on Win32_PingStatus for details.
Examples:
# Ping with no options
Ping::WMI.ping('www.perl.com')
# Ping with options
Ping::WMI.ping('www.perl.com', :BufferSize => 64, :NoFragmentation => true)
--
The PingStatus struct is a wrapper for the Win32_PingStatus WMI class. | [
"Unlike",
"the",
"ping",
"method",
"for",
"other",
"Ping",
"subclasses",
"this",
"version",
"returns",
"a",
"PingStatus",
"struct",
"which",
"contains",
"various",
"bits",
"of",
"information",
"about",
"the",
"results",
"of",
"the",
"ping",
"itself",
"such",
"as",
"response",
"time",
"."
] | 0a30dc5e10c56494d10ab270c64d76e085770bf8 | https://github.com/whyarkadas/http_ping/blob/0a30dc5e10c56494d10ab270c64d76e085770bf8/lib/HttpPing/wmi.rb#L60-L110 | train |
caruby/core | lib/caruby/database/sql_executor.rb | CaRuby.SQLExecutor.query | def query(sql, *args, &block)
fetched = nil
execute do |dbh|
result = dbh.execute(sql, *args)
if block_given? then
result.each(&block)
else
fetched = result.fetch(:all)
end
result.finish
end
fetched
end | ruby | def query(sql, *args, &block)
fetched = nil
execute do |dbh|
result = dbh.execute(sql, *args)
if block_given? then
result.each(&block)
else
fetched = result.fetch(:all)
end
result.finish
end
fetched
end | [
"def",
"query",
"(",
"sql",
",",
"*",
"args",
",",
"&",
"block",
")",
"fetched",
"=",
"nil",
"execute",
"do",
"|",
"dbh",
"|",
"result",
"=",
"dbh",
".",
"execute",
"(",
"sql",
",",
"args",
")",
"if",
"block_given?",
"then",
"result",
".",
"each",
"(",
"block",
")",
"else",
"fetched",
"=",
"result",
".",
"fetch",
"(",
":all",
")",
"end",
"result",
".",
"finish",
"end",
"fetched",
"end"
] | Runs the given query.
@param [String] sql the SQL to execute
@param [Array] args the SQL bindings
@yield [row] operate on the result
@yield [Array] the result row
@return [Array] the query result | [
"Runs",
"the",
"given",
"query",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/sql_executor.rb#L100-L112 | train |
caruby/core | lib/caruby/database/sql_executor.rb | CaRuby.SQLExecutor.transact | def transact(sql=nil, *args)
# Work-around for rcbi nil substitution.
if sql then
sql, *args = replace_nil_binds(sql, args)
transact { |dbh| dbh.execute(sql, *args) }
elsif block_given? then
execute { |dbh| dbh.transaction { yield dbh } }
else
raise ArgumentError.new("SQL executor is missing the required execution block")
end
end | ruby | def transact(sql=nil, *args)
# Work-around for rcbi nil substitution.
if sql then
sql, *args = replace_nil_binds(sql, args)
transact { |dbh| dbh.execute(sql, *args) }
elsif block_given? then
execute { |dbh| dbh.transaction { yield dbh } }
else
raise ArgumentError.new("SQL executor is missing the required execution block")
end
end | [
"def",
"transact",
"(",
"sql",
"=",
"nil",
",",
"*",
"args",
")",
"# Work-around for rcbi nil substitution.",
"if",
"sql",
"then",
"sql",
",",
"*",
"args",
"=",
"replace_nil_binds",
"(",
"sql",
",",
"args",
")",
"transact",
"{",
"|",
"dbh",
"|",
"dbh",
".",
"execute",
"(",
"sql",
",",
"args",
")",
"}",
"elsif",
"block_given?",
"then",
"execute",
"{",
"|",
"dbh",
"|",
"dbh",
".",
"transaction",
"{",
"yield",
"dbh",
"}",
"}",
"else",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"SQL executor is missing the required execution block\"",
")",
"end",
"end"
] | Runs the given SQL or block in a transaction. If SQL is provided, then that
SQL is executed. Otherwise, the block is called.
@quirk RDBI RDBI converts nil args to 12. Work-around this bug by embedding
+NULL+ in the SQL instead.
@param [String] sql the SQL to execute
@param [Array] args the SQL bindings
@yield [dbh] the transaction statements
@yieldparam [RDBI::Database] dbh the database handle | [
"Runs",
"the",
"given",
"SQL",
"or",
"block",
"in",
"a",
"transaction",
".",
"If",
"SQL",
"is",
"provided",
"then",
"that",
"SQL",
"is",
"executed",
".",
"Otherwise",
"the",
"block",
"is",
"called",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/sql_executor.rb#L124-L134 | train |
Subsets and Splits