id
int32 0
24.9k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
500 | dpla/KriKri | lib/krikri/search_index.rb | Krikri.SearchIndex.bulk_update_batches | def bulk_update_batches(aggregations)
en = Enumerator.new do |e|
i = 1
batch = []
aggregations.each do |agg|
batch << agg
if i % @bulk_update_size == 0
e.yield batch
batch = []
end
i += 1
end
e.yield batch if batch.count > 0 # last one
end
en.lazy
end | ruby | def bulk_update_batches(aggregations)
en = Enumerator.new do |e|
i = 1
batch = []
aggregations.each do |agg|
batch << agg
if i % @bulk_update_size == 0
e.yield batch
batch = []
end
i += 1
end
e.yield batch if batch.count > 0 # last one
end
en.lazy
end | [
"def",
"bulk_update_batches",
"(",
"aggregations",
")",
"en",
"=",
"Enumerator",
".",
"new",
"do",
"|",
"e",
"|",
"i",
"=",
"1",
"batch",
"=",
"[",
"]",
"aggregations",
".",
"each",
"do",
"|",
"agg",
"|",
"batch",
"<<",
"agg",
"if",
"i",
"%",
"@bulk_update_size",
"==",
"0",
"e",
".",
"yield",
"batch",
"batch",
"=",
"[",
"]",
"end",
"i",
"+=",
"1",
"end",
"e",
".",
"yield",
"batch",
"if",
"batch",
".",
"count",
">",
"0",
"# last one",
"end",
"en",
".",
"lazy",
"end"
] | Enumerate arrays of JSON strings, one array per batch that is supposed
to be loaded into the search index.
@param aggregations [Enumerator]
@return [Enumerator] Each array of JSON strings | [
"Enumerate",
"arrays",
"of",
"JSON",
"strings",
"one",
"array",
"per",
"batch",
"that",
"is",
"supposed",
"to",
"be",
"loaded",
"into",
"the",
"search",
"index",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/search_index.rb#L70-L85 |
501 | dpla/KriKri | lib/krikri/search_index.rb | Krikri.SearchIndex.incremental_update_from_activity | def incremental_update_from_activity(activity)
entities_as_json_hashes(activity).each do |h|
index_with_error_handling(activity) { add(h) }
end
end | ruby | def incremental_update_from_activity(activity)
entities_as_json_hashes(activity).each do |h|
index_with_error_handling(activity) { add(h) }
end
end | [
"def",
"incremental_update_from_activity",
"(",
"activity",
")",
"entities_as_json_hashes",
"(",
"activity",
")",
".",
"each",
"do",
"|",
"h",
"|",
"index_with_error_handling",
"(",
"activity",
")",
"{",
"add",
"(",
"h",
")",
"}",
"end",
"end"
] | Given an activity, load its revised entities into the search index one
at a time.
Any errors on individual record adds are caught and logged, and the
record is skipped.
@param activity [Krikri::Activity] | [
"Given",
"an",
"activity",
"load",
"its",
"revised",
"entities",
"into",
"the",
"search",
"index",
"one",
"at",
"a",
"time",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/search_index.rb#L95-L99 |
502 | dpla/KriKri | lib/krikri/search_index.rb | Krikri.QASearchIndex.schema_keys | def schema_keys
schema_file = File.join(Rails.root, 'solr_conf', 'schema.xml')
file = File.open(schema_file)
doc = Nokogiri::XML(file)
file.close
doc.xpath('//fields/field').map { |f| f.attr('name') }
end | ruby | def schema_keys
schema_file = File.join(Rails.root, 'solr_conf', 'schema.xml')
file = File.open(schema_file)
doc = Nokogiri::XML(file)
file.close
doc.xpath('//fields/field').map { |f| f.attr('name') }
end | [
"def",
"schema_keys",
"schema_file",
"=",
"File",
".",
"join",
"(",
"Rails",
".",
"root",
",",
"'solr_conf'",
",",
"'schema.xml'",
")",
"file",
"=",
"File",
".",
"open",
"(",
"schema_file",
")",
"doc",
"=",
"Nokogiri",
"::",
"XML",
"(",
"file",
")",
"file",
".",
"close",
"doc",
".",
"xpath",
"(",
"'//fields/field'",
")",
".",
"map",
"{",
"|",
"f",
"|",
"f",
".",
"attr",
"(",
"'name'",
")",
"}",
"end"
] | Get field names from Solr schema in host application.
Will raise exception if file not found.
@return [Array] | [
"Get",
"field",
"names",
"from",
"Solr",
"schema",
"in",
"host",
"application",
".",
"Will",
"raise",
"exception",
"if",
"file",
"not",
"found",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/search_index.rb#L230-L236 |
503 | dpla/KriKri | lib/krikri/search_index.rb | Krikri.QASearchIndex.flat_hash | def flat_hash(hash, keys = [])
new_hash = {}
hash.each do |key, val|
new_hash[format_key(keys + [key])] = val unless
val.is_a?(Array) || val.is_a?(Hash)
new_hash.merge!(flat_hash(val, keys + [key])) if val.is_a? Hash
if val.is_a? Array
val.each do |v|
if v.is_a? Hash
new_hash.merge!(flat_hash(v, keys + [key])) do |key, f, s|
Array(f) << s
end
else
formatted_key = format_key(keys + [key])
new_hash[formatted_key] =
new_hash[formatted_key] ? (Array(new_hash[formatted_key]) << v) : v
end
end
end
end
new_hash
end | ruby | def flat_hash(hash, keys = [])
new_hash = {}
hash.each do |key, val|
new_hash[format_key(keys + [key])] = val unless
val.is_a?(Array) || val.is_a?(Hash)
new_hash.merge!(flat_hash(val, keys + [key])) if val.is_a? Hash
if val.is_a? Array
val.each do |v|
if v.is_a? Hash
new_hash.merge!(flat_hash(v, keys + [key])) do |key, f, s|
Array(f) << s
end
else
formatted_key = format_key(keys + [key])
new_hash[formatted_key] =
new_hash[formatted_key] ? (Array(new_hash[formatted_key]) << v) : v
end
end
end
end
new_hash
end | [
"def",
"flat_hash",
"(",
"hash",
",",
"keys",
"=",
"[",
"]",
")",
"new_hash",
"=",
"{",
"}",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"new_hash",
"[",
"format_key",
"(",
"keys",
"+",
"[",
"key",
"]",
")",
"]",
"=",
"val",
"unless",
"val",
".",
"is_a?",
"(",
"Array",
")",
"||",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"new_hash",
".",
"merge!",
"(",
"flat_hash",
"(",
"val",
",",
"keys",
"+",
"[",
"key",
"]",
")",
")",
"if",
"val",
".",
"is_a?",
"Hash",
"if",
"val",
".",
"is_a?",
"Array",
"val",
".",
"each",
"do",
"|",
"v",
"|",
"if",
"v",
".",
"is_a?",
"Hash",
"new_hash",
".",
"merge!",
"(",
"flat_hash",
"(",
"v",
",",
"keys",
"+",
"[",
"key",
"]",
")",
")",
"do",
"|",
"key",
",",
"f",
",",
"s",
"|",
"Array",
"(",
"f",
")",
"<<",
"s",
"end",
"else",
"formatted_key",
"=",
"format_key",
"(",
"keys",
"+",
"[",
"key",
"]",
")",
"new_hash",
"[",
"formatted_key",
"]",
"=",
"new_hash",
"[",
"formatted_key",
"]",
"?",
"(",
"Array",
"(",
"new_hash",
"[",
"formatted_key",
"]",
")",
"<<",
"v",
")",
":",
"v",
"end",
"end",
"end",
"end",
"new_hash",
"end"
] | Flattens a nested hash
Joins keys with "_" and removes "@" symbols
Example:
flat_hash( {"a"=>"1", "b"=>{"c"=>"2", "d"=>"3"} )
=> {"a"=>"1", "b_c"=>"2", "b_d"=>"3"} | [
"Flattens",
"a",
"nested",
"hash",
"Joins",
"keys",
"with",
"_",
"and",
"removes"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/search_index.rb#L246-L270 |
504 | schrodingersbox/meter_cat | lib/meter_cat/calculator.rb | MeterCat.Calculator.dependencies | def dependencies(names)
names.each do |name|
calculation = fetch(name, nil)
next unless calculation
calculation.dependencies.each do |dependency|
names << dependency unless names.include?(dependency)
end
end
end | ruby | def dependencies(names)
names.each do |name|
calculation = fetch(name, nil)
next unless calculation
calculation.dependencies.each do |dependency|
names << dependency unless names.include?(dependency)
end
end
end | [
"def",
"dependencies",
"(",
"names",
")",
"names",
".",
"each",
"do",
"|",
"name",
"|",
"calculation",
"=",
"fetch",
"(",
"name",
",",
"nil",
")",
"next",
"unless",
"calculation",
"calculation",
".",
"dependencies",
".",
"each",
"do",
"|",
"dependency",
"|",
"names",
"<<",
"dependency",
"unless",
"names",
".",
"include?",
"(",
"dependency",
")",
"end",
"end",
"end"
] | Add any missing names required for calculations that are named | [
"Add",
"any",
"missing",
"names",
"required",
"for",
"calculations",
"that",
"are",
"named"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/lib/meter_cat/calculator.rb#L31-L40 |
505 | dpla/KriKri | lib/krikri/harvesters/couchdb_harvester.rb | Krikri::Harvesters.CouchdbHarvester.count | def count(opts = {})
view = opts[:view] || @opts[:view]
# The count that we want is the total documents in the database minus
# CouchDB design documents. Asking for the design documents will give us
# the total count in addition to letting us determine the number of
# design documents.
v = client.view(view,
include_docs: false,
stream: false,
startkey: '_design',
endkey: '_design0')
total = v.total_rows
design_doc_count = v.keys.size
total - design_doc_count
end | ruby | def count(opts = {})
view = opts[:view] || @opts[:view]
# The count that we want is the total documents in the database minus
# CouchDB design documents. Asking for the design documents will give us
# the total count in addition to letting us determine the number of
# design documents.
v = client.view(view,
include_docs: false,
stream: false,
startkey: '_design',
endkey: '_design0')
total = v.total_rows
design_doc_count = v.keys.size
total - design_doc_count
end | [
"def",
"count",
"(",
"opts",
"=",
"{",
"}",
")",
"view",
"=",
"opts",
"[",
":view",
"]",
"||",
"@opts",
"[",
":view",
"]",
"# The count that we want is the total documents in the database minus",
"# CouchDB design documents. Asking for the design documents will give us",
"# the total count in addition to letting us determine the number of",
"# design documents.",
"v",
"=",
"client",
".",
"view",
"(",
"view",
",",
"include_docs",
":",
"false",
",",
"stream",
":",
"false",
",",
"startkey",
":",
"'_design'",
",",
"endkey",
":",
"'_design0'",
")",
"total",
"=",
"v",
".",
"total_rows",
"design_doc_count",
"=",
"v",
".",
"keys",
".",
"size",
"total",
"-",
"design_doc_count",
"end"
] | Return the total number of documents reported by a CouchDB view.
@param opts [Hash] Analysand::Database#view options
- view: database view name
@return [Fixnum] | [
"Return",
"the",
"total",
"number",
"of",
"documents",
"reported",
"by",
"a",
"CouchDB",
"view",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/couchdb_harvester.rb#L54-L68 |
506 | dpla/KriKri | lib/krikri/harvesters/couchdb_harvester.rb | Krikri::Harvesters.CouchdbHarvester.records | def records(opts = {})
view = opts[:view] || @opts[:view]
limit = opts[:limit] || @opts[:limit]
record_rows(view, limit).map do |row|
@record_class.build(
mint_id(row['doc']['_id']),
row['doc'].to_json,
'application/json'
)
end
end | ruby | def records(opts = {})
view = opts[:view] || @opts[:view]
limit = opts[:limit] || @opts[:limit]
record_rows(view, limit).map do |row|
@record_class.build(
mint_id(row['doc']['_id']),
row['doc'].to_json,
'application/json'
)
end
end | [
"def",
"records",
"(",
"opts",
"=",
"{",
"}",
")",
"view",
"=",
"opts",
"[",
":view",
"]",
"||",
"@opts",
"[",
":view",
"]",
"limit",
"=",
"opts",
"[",
":limit",
"]",
"||",
"@opts",
"[",
":limit",
"]",
"record_rows",
"(",
"view",
",",
"limit",
")",
".",
"map",
"do",
"|",
"row",
"|",
"@record_class",
".",
"build",
"(",
"mint_id",
"(",
"row",
"[",
"'doc'",
"]",
"[",
"'_id'",
"]",
")",
",",
"row",
"[",
"'doc'",
"]",
".",
"to_json",
",",
"'application/json'",
")",
"end",
"end"
] | Makes requests to a CouchDB view to yield documents.
The following will only send requests to the endpoint until it
has 1000 records:
records.take(1000)
Batches of records are requested, in order to avoid using
`Analysand::StreamingViewResponse`, and the CouchDB `startkey` parameter
is used for greater efficiency than `skip` in locating the next page of
records.
@return [Enumerator]
@see Analysand::Viewing
@see http://docs.couchdb.org/en/latest/couchapp/views/collation.html#all-docs | [
"Makes",
"requests",
"to",
"a",
"CouchDB",
"view",
"to",
"yield",
"documents",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/couchdb_harvester.rb#L86-L96 |
507 | dpla/KriKri | lib/krikri/harvesters/couchdb_harvester.rb | Krikri::Harvesters.CouchdbHarvester.record_rows | def record_rows(view, limit)
en = Enumerator.new do |e|
view_opts = {include_docs: true, stream: false, limit: limit}
rows_retrieved = 0
total_rows = nil
loop do
v = client.view(view, view_opts)
total_rows ||= v.total_rows
rows_retrieved += v.rows.size
v.rows.each do |row|
next if row['id'].start_with?('_design')
e.yield row
end
break if rows_retrieved == total_rows
view_opts[:startkey] = v.rows.last['id'] + '0'
end
end
en.lazy
end | ruby | def record_rows(view, limit)
en = Enumerator.new do |e|
view_opts = {include_docs: true, stream: false, limit: limit}
rows_retrieved = 0
total_rows = nil
loop do
v = client.view(view, view_opts)
total_rows ||= v.total_rows
rows_retrieved += v.rows.size
v.rows.each do |row|
next if row['id'].start_with?('_design')
e.yield row
end
break if rows_retrieved == total_rows
view_opts[:startkey] = v.rows.last['id'] + '0'
end
end
en.lazy
end | [
"def",
"record_rows",
"(",
"view",
",",
"limit",
")",
"en",
"=",
"Enumerator",
".",
"new",
"do",
"|",
"e",
"|",
"view_opts",
"=",
"{",
"include_docs",
":",
"true",
",",
"stream",
":",
"false",
",",
"limit",
":",
"limit",
"}",
"rows_retrieved",
"=",
"0",
"total_rows",
"=",
"nil",
"loop",
"do",
"v",
"=",
"client",
".",
"view",
"(",
"view",
",",
"view_opts",
")",
"total_rows",
"||=",
"v",
".",
"total_rows",
"rows_retrieved",
"+=",
"v",
".",
"rows",
".",
"size",
"v",
".",
"rows",
".",
"each",
"do",
"|",
"row",
"|",
"next",
"if",
"row",
"[",
"'id'",
"]",
".",
"start_with?",
"(",
"'_design'",
")",
"e",
".",
"yield",
"row",
"end",
"break",
"if",
"rows_retrieved",
"==",
"total_rows",
"view_opts",
"[",
":startkey",
"]",
"=",
"v",
".",
"rows",
".",
"last",
"[",
"'id'",
"]",
"+",
"'0'",
"end",
"end",
"en",
".",
"lazy",
"end"
] | Return an enumerator that provides individual records from batched view
requests.
@return [Enumerator]
@see #records | [
"Return",
"an",
"enumerator",
"that",
"provides",
"individual",
"records",
"from",
"batched",
"view",
"requests",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/couchdb_harvester.rb#L104-L122 |
508 | dpla/KriKri | lib/krikri/harvesters/couchdb_harvester.rb | Krikri::Harvesters.CouchdbHarvester.get_record | def get_record(identifier)
doc = client.get!(CGI.escape(identifier)).body.to_json
@record_class.build(mint_id(identifier), doc, 'application/json')
end | ruby | def get_record(identifier)
doc = client.get!(CGI.escape(identifier)).body.to_json
@record_class.build(mint_id(identifier), doc, 'application/json')
end | [
"def",
"get_record",
"(",
"identifier",
")",
"doc",
"=",
"client",
".",
"get!",
"(",
"CGI",
".",
"escape",
"(",
"identifier",
")",
")",
".",
"body",
".",
"to_json",
"@record_class",
".",
"build",
"(",
"mint_id",
"(",
"identifier",
")",
",",
"doc",
",",
"'application/json'",
")",
"end"
] | Retrieves a specific document from CouchDB.
Uses Analysand::Database#get!, which raises an exception if the
document cannot be found.
@see Analysand::Database#get! | [
"Retrieves",
"a",
"specific",
"document",
"from",
"CouchDB",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/couchdb_harvester.rb#L131-L134 |
509 | aashishgarg/simple_notifications | lib/simple_notifications/base.rb | SimpleNotifications.Base.open_receiver_class | def open_receiver_class
# Define association for receiver model
[receivers_class(@@options[:receivers])].flatten.each do |base|
base.class_eval do
has_many :deliveries, class_name: 'SimpleNotifications::Delivery', as: :receiver
has_many :received_notifications, through: :deliveries, source: :simple_notification
end
end
end | ruby | def open_receiver_class
# Define association for receiver model
[receivers_class(@@options[:receivers])].flatten.each do |base|
base.class_eval do
has_many :deliveries, class_name: 'SimpleNotifications::Delivery', as: :receiver
has_many :received_notifications, through: :deliveries, source: :simple_notification
end
end
end | [
"def",
"open_receiver_class",
"# Define association for receiver model",
"[",
"receivers_class",
"(",
"@@options",
"[",
":receivers",
"]",
")",
"]",
".",
"flatten",
".",
"each",
"do",
"|",
"base",
"|",
"base",
".",
"class_eval",
"do",
"has_many",
":deliveries",
",",
"class_name",
":",
"'SimpleNotifications::Delivery'",
",",
"as",
":",
":receiver",
"has_many",
":received_notifications",
",",
"through",
":",
":deliveries",
",",
"source",
":",
":simple_notification",
"end",
"end",
"end"
] | Opening the classes which are defined as receivers. | [
"Opening",
"the",
"classes",
"which",
"are",
"defined",
"as",
"receivers",
"."
] | e804f5c127fb72d61262e8c1cc4110d69f039b2f | https://github.com/aashishgarg/simple_notifications/blob/e804f5c127fb72d61262e8c1cc4110d69f039b2f/lib/simple_notifications/base.rb#L36-L44 |
510 | aashishgarg/simple_notifications | lib/simple_notifications/base.rb | SimpleNotifications.Base.sender_class | def sender_class(sender)
if sender.kind_of? Symbol
reflections[sender.to_s].klass
elsif sender.kind_of? ActiveRecord::Base
sender.class
else
raise 'SimpleNotifications::SenderTypeError'
end
end | ruby | def sender_class(sender)
if sender.kind_of? Symbol
reflections[sender.to_s].klass
elsif sender.kind_of? ActiveRecord::Base
sender.class
else
raise 'SimpleNotifications::SenderTypeError'
end
end | [
"def",
"sender_class",
"(",
"sender",
")",
"if",
"sender",
".",
"kind_of?",
"Symbol",
"reflections",
"[",
"sender",
".",
"to_s",
"]",
".",
"klass",
"elsif",
"sender",
".",
"kind_of?",
"ActiveRecord",
"::",
"Base",
"sender",
".",
"class",
"else",
"raise",
"'SimpleNotifications::SenderTypeError'",
"end",
"end"
] | Provides the class of Sender | [
"Provides",
"the",
"class",
"of",
"Sender"
] | e804f5c127fb72d61262e8c1cc4110d69f039b2f | https://github.com/aashishgarg/simple_notifications/blob/e804f5c127fb72d61262e8c1cc4110d69f039b2f/lib/simple_notifications/base.rb#L168-L176 |
511 | aashishgarg/simple_notifications | lib/simple_notifications/base.rb | SimpleNotifications.Base.receivers_class | def receivers_class(receivers)
if receivers.kind_of? Symbol
reflections[receivers.to_s].klass
else
if receivers.kind_of? ActiveRecord::Base
receivers.class
elsif receivers.kind_of? ActiveRecord::Relation
receivers.klass
elsif receivers.kind_of? Array
receivers.flatten.collect {|receiver| receivers_class(receiver)}
else
raise 'SimpleNotifications::ReceiverTypeError'
end
end
end | ruby | def receivers_class(receivers)
if receivers.kind_of? Symbol
reflections[receivers.to_s].klass
else
if receivers.kind_of? ActiveRecord::Base
receivers.class
elsif receivers.kind_of? ActiveRecord::Relation
receivers.klass
elsif receivers.kind_of? Array
receivers.flatten.collect {|receiver| receivers_class(receiver)}
else
raise 'SimpleNotifications::ReceiverTypeError'
end
end
end | [
"def",
"receivers_class",
"(",
"receivers",
")",
"if",
"receivers",
".",
"kind_of?",
"Symbol",
"reflections",
"[",
"receivers",
".",
"to_s",
"]",
".",
"klass",
"else",
"if",
"receivers",
".",
"kind_of?",
"ActiveRecord",
"::",
"Base",
"receivers",
".",
"class",
"elsif",
"receivers",
".",
"kind_of?",
"ActiveRecord",
"::",
"Relation",
"receivers",
".",
"klass",
"elsif",
"receivers",
".",
"kind_of?",
"Array",
"receivers",
".",
"flatten",
".",
"collect",
"{",
"|",
"receiver",
"|",
"receivers_class",
"(",
"receiver",
")",
"}",
"else",
"raise",
"'SimpleNotifications::ReceiverTypeError'",
"end",
"end",
"end"
] | Provides the classes of Receivers | [
"Provides",
"the",
"classes",
"of",
"Receivers"
] | e804f5c127fb72d61262e8c1cc4110d69f039b2f | https://github.com/aashishgarg/simple_notifications/blob/e804f5c127fb72d61262e8c1cc4110d69f039b2f/lib/simple_notifications/base.rb#L179-L193 |
512 | dpla/KriKri | lib/krikri/harvesters/api_harvester.rb | Krikri::Harvesters.ApiHarvester.next_options | def next_options(opts, record_count)
old_start = opts['params'].fetch('start', 0)
opts['params']['start'] = old_start.to_i + record_count
opts
end | ruby | def next_options(opts, record_count)
old_start = opts['params'].fetch('start', 0)
opts['params']['start'] = old_start.to_i + record_count
opts
end | [
"def",
"next_options",
"(",
"opts",
",",
"record_count",
")",
"old_start",
"=",
"opts",
"[",
"'params'",
"]",
".",
"fetch",
"(",
"'start'",
",",
"0",
")",
"opts",
"[",
"'params'",
"]",
"[",
"'start'",
"]",
"=",
"old_start",
".",
"to_i",
"+",
"record_count",
"opts",
"end"
] | Given a current set of options and a number of records from the last
request, generate the options for the next request.
@param opts [Hash] an options hash from the previous request
@param record_count [#to_i]
@return [Hash] the next request's options hash | [
"Given",
"a",
"current",
"set",
"of",
"options",
"and",
"a",
"number",
"of",
"records",
"from",
"the",
"last",
"request",
"generate",
"the",
"options",
"for",
"the",
"next",
"request",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/api_harvester.rb#L128-L132 |
513 | 12spokes/tandem | app/models/tandem/page.rb | Tandem.Page.do_before_validation | def do_before_validation
prim_slug, i = slug, 0
prim_slug, i = $1, $2.to_i if slug =~ /^(.*)_([0-9]+)$/
return unless prim_slug.present?
attempts = 0
conditions = new_record? ? ['slug = ?',slug] : ['slug = ? AND id != ?',slug,id]
conditions[1] = "#{prim_slug}_#{i+=1}" while Page.where(conditions).first && (attempts += 1) < 20
write_attribute(:slug,conditions[1])
end | ruby | def do_before_validation
prim_slug, i = slug, 0
prim_slug, i = $1, $2.to_i if slug =~ /^(.*)_([0-9]+)$/
return unless prim_slug.present?
attempts = 0
conditions = new_record? ? ['slug = ?',slug] : ['slug = ? AND id != ?',slug,id]
conditions[1] = "#{prim_slug}_#{i+=1}" while Page.where(conditions).first && (attempts += 1) < 20
write_attribute(:slug,conditions[1])
end | [
"def",
"do_before_validation",
"prim_slug",
",",
"i",
"=",
"slug",
",",
"0",
"prim_slug",
",",
"i",
"=",
"$1",
",",
"$2",
".",
"to_i",
"if",
"slug",
"=~",
"/",
"/",
"return",
"unless",
"prim_slug",
".",
"present?",
"attempts",
"=",
"0",
"conditions",
"=",
"new_record?",
"?",
"[",
"'slug = ?'",
",",
"slug",
"]",
":",
"[",
"'slug = ? AND id != ?'",
",",
"slug",
",",
"id",
"]",
"conditions",
"[",
"1",
"]",
"=",
"\"#{prim_slug}_#{i+=1}\"",
"while",
"Page",
".",
"where",
"(",
"conditions",
")",
".",
"first",
"&&",
"(",
"attempts",
"+=",
"1",
")",
"<",
"20",
"write_attribute",
"(",
":slug",
",",
"conditions",
"[",
"1",
"]",
")",
"end"
] | auto increment slug until it is unique | [
"auto",
"increment",
"slug",
"until",
"it",
"is",
"unique"
] | 6ad1cd041158c721c84a8c27809c1ddac1dbf6ce | https://github.com/12spokes/tandem/blob/6ad1cd041158c721c84a8c27809c1ddac1dbf6ce/app/models/tandem/page.rb#L25-L35 |
514 | conjurinc/conjur-asset-policy | lib/conjur/policy/executor/create.rb | Conjur::Policy::Executor.CreateRecord.create_parameters | def create_parameters
{
record.id_attribute => record.id
}.tap do |params|
custom_attrs = attribute_names.inject({}) do |memo, attr|
value = record.send(attr)
memo[attr.to_s] = value if value
memo
end
params.merge! custom_attrs
params["ownerid"] = record.owner.roleid if record.owner
end
end | ruby | def create_parameters
{
record.id_attribute => record.id
}.tap do |params|
custom_attrs = attribute_names.inject({}) do |memo, attr|
value = record.send(attr)
memo[attr.to_s] = value if value
memo
end
params.merge! custom_attrs
params["ownerid"] = record.owner.roleid if record.owner
end
end | [
"def",
"create_parameters",
"{",
"record",
".",
"id_attribute",
"=>",
"record",
".",
"id",
"}",
".",
"tap",
"do",
"|",
"params",
"|",
"custom_attrs",
"=",
"attribute_names",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"memo",
",",
"attr",
"|",
"value",
"=",
"record",
".",
"send",
"(",
"attr",
")",
"memo",
"[",
"attr",
".",
"to_s",
"]",
"=",
"value",
"if",
"value",
"memo",
"end",
"params",
".",
"merge!",
"custom_attrs",
"params",
"[",
"\"ownerid\"",
"]",
"=",
"record",
".",
"owner",
".",
"roleid",
"if",
"record",
".",
"owner",
"end",
"end"
] | Each record is assumed to have an 'id' attribute required for creation.
In addition, other create parameters can be specified by the +custom_attribute_names+
method on the record. | [
"Each",
"record",
"is",
"assumed",
"to",
"have",
"an",
"id",
"attribute",
"required",
"for",
"creation",
".",
"In",
"addition",
"other",
"create",
"parameters",
"can",
"be",
"specified",
"by",
"the",
"+",
"custom_attribute_names",
"+",
"method",
"on",
"the",
"record",
"."
] | c7672cf99aea2c3c6f0699be94018834d35ad7f0 | https://github.com/conjurinc/conjur-asset-policy/blob/c7672cf99aea2c3c6f0699be94018834d35ad7f0/lib/conjur/policy/executor/create.rb#L37-L49 |
515 | stormbrew/http_parser | lib/http/native_parser.rb | Http.NativeParser.fill_rack_env | def fill_rack_env(env = {})
env["rack.input"] = @body || StringIO.new
env["REQUEST_METHOD"] = @method
env["SCRIPT_NAME"] = ""
env["REQUEST_URI"] = @path
env["PATH_INFO"], query = @path.split("?", 2)
env["QUERY_STRING"] = query || ""
if (@headers["HOST"] && !env["SERVER_NAME"])
env["SERVER_NAME"], port = @headers["HOST"].split(":", 2)
env["SERVER_PORT"] = port if port
end
@headers.each do |key, val|
if (key == 'CONTENT_LENGTH' || key == 'CONTENT_TYPE')
env[key] = val
else
env["HTTP_#{key}"] = val
end
end
return env
end | ruby | def fill_rack_env(env = {})
env["rack.input"] = @body || StringIO.new
env["REQUEST_METHOD"] = @method
env["SCRIPT_NAME"] = ""
env["REQUEST_URI"] = @path
env["PATH_INFO"], query = @path.split("?", 2)
env["QUERY_STRING"] = query || ""
if (@headers["HOST"] && !env["SERVER_NAME"])
env["SERVER_NAME"], port = @headers["HOST"].split(":", 2)
env["SERVER_PORT"] = port if port
end
@headers.each do |key, val|
if (key == 'CONTENT_LENGTH' || key == 'CONTENT_TYPE')
env[key] = val
else
env["HTTP_#{key}"] = val
end
end
return env
end | [
"def",
"fill_rack_env",
"(",
"env",
"=",
"{",
"}",
")",
"env",
"[",
"\"rack.input\"",
"]",
"=",
"@body",
"||",
"StringIO",
".",
"new",
"env",
"[",
"\"REQUEST_METHOD\"",
"]",
"=",
"@method",
"env",
"[",
"\"SCRIPT_NAME\"",
"]",
"=",
"\"\"",
"env",
"[",
"\"REQUEST_URI\"",
"]",
"=",
"@path",
"env",
"[",
"\"PATH_INFO\"",
"]",
",",
"query",
"=",
"@path",
".",
"split",
"(",
"\"?\"",
",",
"2",
")",
"env",
"[",
"\"QUERY_STRING\"",
"]",
"=",
"query",
"||",
"\"\"",
"if",
"(",
"@headers",
"[",
"\"HOST\"",
"]",
"&&",
"!",
"env",
"[",
"\"SERVER_NAME\"",
"]",
")",
"env",
"[",
"\"SERVER_NAME\"",
"]",
",",
"port",
"=",
"@headers",
"[",
"\"HOST\"",
"]",
".",
"split",
"(",
"\":\"",
",",
"2",
")",
"env",
"[",
"\"SERVER_PORT\"",
"]",
"=",
"port",
"if",
"port",
"end",
"@headers",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"if",
"(",
"key",
"==",
"'CONTENT_LENGTH'",
"||",
"key",
"==",
"'CONTENT_TYPE'",
")",
"env",
"[",
"key",
"]",
"=",
"val",
"else",
"env",
"[",
"\"HTTP_#{key}\"",
"]",
"=",
"val",
"end",
"end",
"return",
"env",
"end"
] | Given a basic rack environment, will properly fill it in
with the information gleaned from the parsed request. Note that
this only fills the subset that can be determined by the parser
library. Namely, the only rack. variable set is rack.input. You should also
have defaults in place for SERVER_NAME and SERVER_PORT, as they
are required. | [
"Given",
"a",
"basic",
"rack",
"environment",
"will",
"properly",
"fill",
"it",
"in",
"with",
"the",
"information",
"gleaned",
"from",
"the",
"parsed",
"request",
".",
"Note",
"that",
"this",
"only",
"fills",
"the",
"subset",
"that",
"can",
"be",
"determined",
"by",
"the",
"parser",
"library",
".",
"Namely",
"the",
"only",
"rack",
".",
"variable",
"set",
"is",
"rack",
".",
"input",
".",
"You",
"should",
"also",
"have",
"defaults",
"in",
"place",
"for",
"SERVER_NAME",
"and",
"SERVER_PORT",
"as",
"they",
"are",
"required",
"."
] | b2b0e755b075e7f92286017f0303f83e6d59063d | https://github.com/stormbrew/http_parser/blob/b2b0e755b075e7f92286017f0303f83e6d59063d/lib/http/native_parser.rb#L295-L314 |
516 | outcomesinsights/sequelizer | lib/sequelizer/monkey_patches/database_in_after_connect.rb | Sequel.ConnectionPool.make_new | def make_new(server)
begin
conn = @db.connect(server)
if ac = @after_connect
case ac.arity
when 3
ac.call(conn, server, @db)
when 2
ac.call(conn, server)
else
ac.call(conn)
end
end
rescue Exception=>exception
raise Sequel.convert_exception_class(exception, Sequel::DatabaseConnectionError)
end
raise(Sequel::DatabaseConnectionError, "Connection parameters not valid") unless conn
conn
end | ruby | def make_new(server)
begin
conn = @db.connect(server)
if ac = @after_connect
case ac.arity
when 3
ac.call(conn, server, @db)
when 2
ac.call(conn, server)
else
ac.call(conn)
end
end
rescue Exception=>exception
raise Sequel.convert_exception_class(exception, Sequel::DatabaseConnectionError)
end
raise(Sequel::DatabaseConnectionError, "Connection parameters not valid") unless conn
conn
end | [
"def",
"make_new",
"(",
"server",
")",
"begin",
"conn",
"=",
"@db",
".",
"connect",
"(",
"server",
")",
"if",
"ac",
"=",
"@after_connect",
"case",
"ac",
".",
"arity",
"when",
"3",
"ac",
".",
"call",
"(",
"conn",
",",
"server",
",",
"@db",
")",
"when",
"2",
"ac",
".",
"call",
"(",
"conn",
",",
"server",
")",
"else",
"ac",
".",
"call",
"(",
"conn",
")",
"end",
"end",
"rescue",
"Exception",
"=>",
"exception",
"raise",
"Sequel",
".",
"convert_exception_class",
"(",
"exception",
",",
"Sequel",
"::",
"DatabaseConnectionError",
")",
"end",
"raise",
"(",
"Sequel",
"::",
"DatabaseConnectionError",
",",
"\"Connection parameters not valid\"",
")",
"unless",
"conn",
"conn",
"end"
] | Return a new connection by calling the connection proc with the given server name,
and checking for connection errors. | [
"Return",
"a",
"new",
"connection",
"by",
"calling",
"the",
"connection",
"proc",
"with",
"the",
"given",
"server",
"name",
"and",
"checking",
"for",
"connection",
"errors",
"."
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/monkey_patches/database_in_after_connect.rb#L5-L23 |
517 | dpla/KriKri | lib/krikri/async_uri_getter.rb | Krikri.AsyncUriGetter.add_request | def add_request(uri: nil, headers: {}, opts: {})
fail ArgumentError, "uri must be a URI; got: #{uri}" unless uri.is_a?(URI)
Request.new(uri, headers, @default_opts.merge(opts))
end | ruby | def add_request(uri: nil, headers: {}, opts: {})
fail ArgumentError, "uri must be a URI; got: #{uri}" unless uri.is_a?(URI)
Request.new(uri, headers, @default_opts.merge(opts))
end | [
"def",
"add_request",
"(",
"uri",
":",
"nil",
",",
"headers",
":",
"{",
"}",
",",
"opts",
":",
"{",
"}",
")",
"fail",
"ArgumentError",
",",
"\"uri must be a URI; got: #{uri}\"",
"unless",
"uri",
".",
"is_a?",
"(",
"URI",
")",
"Request",
".",
"new",
"(",
"uri",
",",
"headers",
",",
"@default_opts",
".",
"merge",
"(",
"opts",
")",
")",
"end"
] | Create a new asynchronous URL fetcher.
@param opts [Hash] a hash of the supported options, which are:
@option opts [Boolean] :follow_redirects Whether to follow HTTP 3xx
redirects.
@option opts [Integer] :max_redirects Number of redirects to follow before
giving up. (default: 10)
@option opts [Boolean] :inline_exceptions If true, pass exceptions as a
5xx response with the exception string in the body. (default: false)
Run a request (in a new thread) and return a promise-like object for the
response.
@param uri [URI] the URI to be fetched
@param headers [Hash<String, String>] HTTP headers to include with the
request
@param opts [Hash] options to override the ones provided when
AsyncUriGetter was initialized. All supported options from `#initialize`
are available here as well. | [
"Create",
"a",
"new",
"asynchronous",
"URL",
"fetcher",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/async_uri_getter.rb#L70-L73 |
518 | chackoantony/exportable | lib/exportable/utils.rb | Exportable.Utils.get_export_options | def get_export_options(model, options)
default_options = { only: model.attribute_names.map(&:to_sym),
except: [],
methods: [],
header: true }
options = default_options.merge(options)
unless options[:only].is_a?(Array) && options[:except].is_a?(Array) && options[:methods].is_a?(Array)
raise ArgumentError, 'Exportable: Expecting Array type for field options'
end
fields = options[:only] - options[:except] + options[:methods]
{ fields: fields, header: options[:header] }
end | ruby | def get_export_options(model, options)
default_options = { only: model.attribute_names.map(&:to_sym),
except: [],
methods: [],
header: true }
options = default_options.merge(options)
unless options[:only].is_a?(Array) && options[:except].is_a?(Array) && options[:methods].is_a?(Array)
raise ArgumentError, 'Exportable: Expecting Array type for field options'
end
fields = options[:only] - options[:except] + options[:methods]
{ fields: fields, header: options[:header] }
end | [
"def",
"get_export_options",
"(",
"model",
",",
"options",
")",
"default_options",
"=",
"{",
"only",
":",
"model",
".",
"attribute_names",
".",
"map",
"(",
":to_sym",
")",
",",
"except",
":",
"[",
"]",
",",
"methods",
":",
"[",
"]",
",",
"header",
":",
"true",
"}",
"options",
"=",
"default_options",
".",
"merge",
"(",
"options",
")",
"unless",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"options",
"[",
":except",
"]",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"options",
"[",
":methods",
"]",
".",
"is_a?",
"(",
"Array",
")",
"raise",
"ArgumentError",
",",
"'Exportable: Expecting Array type for field options'",
"end",
"fields",
"=",
"options",
"[",
":only",
"]",
"-",
"options",
"[",
":except",
"]",
"+",
"options",
"[",
":methods",
"]",
"{",
"fields",
":",
"fields",
",",
"header",
":",
"options",
"[",
":header",
"]",
"}",
"end"
] | Compute exportable options after overriding preferences | [
"Compute",
"exportable",
"options",
"after",
"overriding",
"preferences"
] | fcfebfc80aa6a2c6f746dde23c4707dd289f76ff | https://github.com/chackoantony/exportable/blob/fcfebfc80aa6a2c6f746dde23c4707dd289f76ff/lib/exportable/utils.rb#L5-L16 |
519 | jntullo/ruby-docker-cloud | lib/docker_cloud/api/node_type_api.rb | DockerCloud.NodeTypeAPI.get | def get(provider_name, node_type_name)
name = "#{provider_name}/#{node_type_name}/"
response = http_get(resource_url(name))
format_object(response, TYPE)
end | ruby | def get(provider_name, node_type_name)
name = "#{provider_name}/#{node_type_name}/"
response = http_get(resource_url(name))
format_object(response, TYPE)
end | [
"def",
"get",
"(",
"provider_name",
",",
"node_type_name",
")",
"name",
"=",
"\"#{provider_name}/#{node_type_name}/\"",
"response",
"=",
"http_get",
"(",
"resource_url",
"(",
"name",
")",
")",
"format_object",
"(",
"response",
",",
"TYPE",
")",
"end"
] | Returns the details of a specific NodeType | [
"Returns",
"the",
"details",
"of",
"a",
"specific",
"NodeType"
] | ced8b8a7d7ed0fff2c158a555d0299cd27860721 | https://github.com/jntullo/ruby-docker-cloud/blob/ced8b8a7d7ed0fff2c158a555d0299cd27860721/lib/docker_cloud/api/node_type_api.rb#L17-L21 |
520 | Losant/losant-rest-ruby | lib/losant_rest/application_keys.rb | LosantRest.ApplicationKeys.get | def get(params = {})
params = Utils.symbolize_hash_keys(params)
query_params = { _actions: false, _links: true, _embedded: true }
headers = {}
body = nil
raise ArgumentError.new("applicationId is required") unless params.has_key?(:applicationId)
query_params[:sortField] = params[:sortField] if params.has_key?(:sortField)
query_params[:sortDirection] = params[:sortDirection] if params.has_key?(:sortDirection)
query_params[:page] = params[:page] if params.has_key?(:page)
query_params[:perPage] = params[:perPage] if params.has_key?(:perPage)
query_params[:filterField] = params[:filterField] if params.has_key?(:filterField)
query_params[:filter] = params[:filter] if params.has_key?(:filter)
headers[:losantdomain] = params[:losantdomain] if params.has_key?(:losantdomain)
query_params[:_actions] = params[:_actions] if params.has_key?(:_actions)
query_params[:_links] = params[:_links] if params.has_key?(:_links)
query_params[:_embedded] = params[:_embedded] if params.has_key?(:_embedded)
path = "/applications/#{params[:applicationId]}/keys"
@client.request(
method: :get,
path: path,
query: query_params,
headers: headers,
body: body)
end | ruby | def get(params = {})
params = Utils.symbolize_hash_keys(params)
query_params = { _actions: false, _links: true, _embedded: true }
headers = {}
body = nil
raise ArgumentError.new("applicationId is required") unless params.has_key?(:applicationId)
query_params[:sortField] = params[:sortField] if params.has_key?(:sortField)
query_params[:sortDirection] = params[:sortDirection] if params.has_key?(:sortDirection)
query_params[:page] = params[:page] if params.has_key?(:page)
query_params[:perPage] = params[:perPage] if params.has_key?(:perPage)
query_params[:filterField] = params[:filterField] if params.has_key?(:filterField)
query_params[:filter] = params[:filter] if params.has_key?(:filter)
headers[:losantdomain] = params[:losantdomain] if params.has_key?(:losantdomain)
query_params[:_actions] = params[:_actions] if params.has_key?(:_actions)
query_params[:_links] = params[:_links] if params.has_key?(:_links)
query_params[:_embedded] = params[:_embedded] if params.has_key?(:_embedded)
path = "/applications/#{params[:applicationId]}/keys"
@client.request(
method: :get,
path: path,
query: query_params,
headers: headers,
body: body)
end | [
"def",
"get",
"(",
"params",
"=",
"{",
"}",
")",
"params",
"=",
"Utils",
".",
"symbolize_hash_keys",
"(",
"params",
")",
"query_params",
"=",
"{",
"_actions",
":",
"false",
",",
"_links",
":",
"true",
",",
"_embedded",
":",
"true",
"}",
"headers",
"=",
"{",
"}",
"body",
"=",
"nil",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"applicationId is required\"",
")",
"unless",
"params",
".",
"has_key?",
"(",
":applicationId",
")",
"query_params",
"[",
":sortField",
"]",
"=",
"params",
"[",
":sortField",
"]",
"if",
"params",
".",
"has_key?",
"(",
":sortField",
")",
"query_params",
"[",
":sortDirection",
"]",
"=",
"params",
"[",
":sortDirection",
"]",
"if",
"params",
".",
"has_key?",
"(",
":sortDirection",
")",
"query_params",
"[",
":page",
"]",
"=",
"params",
"[",
":page",
"]",
"if",
"params",
".",
"has_key?",
"(",
":page",
")",
"query_params",
"[",
":perPage",
"]",
"=",
"params",
"[",
":perPage",
"]",
"if",
"params",
".",
"has_key?",
"(",
":perPage",
")",
"query_params",
"[",
":filterField",
"]",
"=",
"params",
"[",
":filterField",
"]",
"if",
"params",
".",
"has_key?",
"(",
":filterField",
")",
"query_params",
"[",
":filter",
"]",
"=",
"params",
"[",
":filter",
"]",
"if",
"params",
".",
"has_key?",
"(",
":filter",
")",
"headers",
"[",
":losantdomain",
"]",
"=",
"params",
"[",
":losantdomain",
"]",
"if",
"params",
".",
"has_key?",
"(",
":losantdomain",
")",
"query_params",
"[",
":_actions",
"]",
"=",
"params",
"[",
":_actions",
"]",
"if",
"params",
".",
"has_key?",
"(",
":_actions",
")",
"query_params",
"[",
":_links",
"]",
"=",
"params",
"[",
":_links",
"]",
"if",
"params",
".",
"has_key?",
"(",
":_links",
")",
"query_params",
"[",
":_embedded",
"]",
"=",
"params",
"[",
":_embedded",
"]",
"if",
"params",
".",
"has_key?",
"(",
":_embedded",
")",
"path",
"=",
"\"/applications/#{params[:applicationId]}/keys\"",
"@client",
".",
"request",
"(",
"method",
":",
":get",
",",
"path",
":",
"path",
",",
"query",
":",
"query_params",
",",
"headers",
":",
"headers",
",",
"body",
":",
"body",
")",
"end"
] | Returns the applicationKeys for an application
Authentication:
The client must be configured with a valid api
access token to call this action. The token
must include at least one of the following scopes:
all.Application, all.Application.read, all.Organization, all.Organization.read, all.User, all.User.read, applicationKeys.*, or applicationKeys.get.
Parameters:
* {string} applicationId - ID associated with the application
* {string} sortField - Field to sort the results by. Accepted values are: key, status, id, creationDate, lastUpdated
* {string} sortDirection - Direction to sort the results by. Accepted values are: asc, desc
* {string} page - Which page of results to return
* {string} perPage - How many items to return per page
* {string} filterField - Field to filter the results by. Blank or not provided means no filtering. Accepted values are: key, status
* {string} filter - Filter to apply against the filtered field. Supports globbing. Blank or not provided means no filtering.
* {string} losantdomain - Domain scope of request (rarely needed)
* {boolean} _actions - Return resource actions in response
* {boolean} _links - Return resource link in response
* {boolean} _embedded - Return embedded resources in response
Responses:
* 200 - Collection of applicationKeys (https://api.losant.com/#/definitions/applicationKeys)
Errors:
* 400 - Error if malformed request (https://api.losant.com/#/definitions/error)
* 404 - Error if application was not found (https://api.losant.com/#/definitions/error) | [
"Returns",
"the",
"applicationKeys",
"for",
"an",
"application"
] | 4a66a70180a0d907c2e50e1edf06cb8312d00260 | https://github.com/Losant/losant-rest-ruby/blob/4a66a70180a0d907c2e50e1edf06cb8312d00260/lib/losant_rest/application_keys.rb#L59-L86 |
521 | Losant/losant-rest-ruby | lib/losant_rest/application_keys.rb | LosantRest.ApplicationKeys.post | def post(params = {})
params = Utils.symbolize_hash_keys(params)
query_params = { _actions: false, _links: true, _embedded: true }
headers = {}
body = nil
raise ArgumentError.new("applicationId is required") unless params.has_key?(:applicationId)
raise ArgumentError.new("applicationKey is required") unless params.has_key?(:applicationKey)
body = params[:applicationKey] if params.has_key?(:applicationKey)
headers[:losantdomain] = params[:losantdomain] if params.has_key?(:losantdomain)
query_params[:_actions] = params[:_actions] if params.has_key?(:_actions)
query_params[:_links] = params[:_links] if params.has_key?(:_links)
query_params[:_embedded] = params[:_embedded] if params.has_key?(:_embedded)
path = "/applications/#{params[:applicationId]}/keys"
@client.request(
method: :post,
path: path,
query: query_params,
headers: headers,
body: body)
end | ruby | def post(params = {})
params = Utils.symbolize_hash_keys(params)
query_params = { _actions: false, _links: true, _embedded: true }
headers = {}
body = nil
raise ArgumentError.new("applicationId is required") unless params.has_key?(:applicationId)
raise ArgumentError.new("applicationKey is required") unless params.has_key?(:applicationKey)
body = params[:applicationKey] if params.has_key?(:applicationKey)
headers[:losantdomain] = params[:losantdomain] if params.has_key?(:losantdomain)
query_params[:_actions] = params[:_actions] if params.has_key?(:_actions)
query_params[:_links] = params[:_links] if params.has_key?(:_links)
query_params[:_embedded] = params[:_embedded] if params.has_key?(:_embedded)
path = "/applications/#{params[:applicationId]}/keys"
@client.request(
method: :post,
path: path,
query: query_params,
headers: headers,
body: body)
end | [
"def",
"post",
"(",
"params",
"=",
"{",
"}",
")",
"params",
"=",
"Utils",
".",
"symbolize_hash_keys",
"(",
"params",
")",
"query_params",
"=",
"{",
"_actions",
":",
"false",
",",
"_links",
":",
"true",
",",
"_embedded",
":",
"true",
"}",
"headers",
"=",
"{",
"}",
"body",
"=",
"nil",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"applicationId is required\"",
")",
"unless",
"params",
".",
"has_key?",
"(",
":applicationId",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"applicationKey is required\"",
")",
"unless",
"params",
".",
"has_key?",
"(",
":applicationKey",
")",
"body",
"=",
"params",
"[",
":applicationKey",
"]",
"if",
"params",
".",
"has_key?",
"(",
":applicationKey",
")",
"headers",
"[",
":losantdomain",
"]",
"=",
"params",
"[",
":losantdomain",
"]",
"if",
"params",
".",
"has_key?",
"(",
":losantdomain",
")",
"query_params",
"[",
":_actions",
"]",
"=",
"params",
"[",
":_actions",
"]",
"if",
"params",
".",
"has_key?",
"(",
":_actions",
")",
"query_params",
"[",
":_links",
"]",
"=",
"params",
"[",
":_links",
"]",
"if",
"params",
".",
"has_key?",
"(",
":_links",
")",
"query_params",
"[",
":_embedded",
"]",
"=",
"params",
"[",
":_embedded",
"]",
"if",
"params",
".",
"has_key?",
"(",
":_embedded",
")",
"path",
"=",
"\"/applications/#{params[:applicationId]}/keys\"",
"@client",
".",
"request",
"(",
"method",
":",
":post",
",",
"path",
":",
"path",
",",
"query",
":",
"query_params",
",",
"headers",
":",
"headers",
",",
"body",
":",
"body",
")",
"end"
] | Create a new applicationKey for an application
Authentication:
The client must be configured with a valid api
access token to call this action. The token
must include at least one of the following scopes:
all.Application, all.Organization, all.User, applicationKeys.*, or applicationKeys.post.
Parameters:
* {string} applicationId - ID associated with the application
* {hash} applicationKey - ApplicationKey information (https://api.losant.com/#/definitions/applicationKeyPost)
* {string} losantdomain - Domain scope of request (rarely needed)
* {boolean} _actions - Return resource actions in response
* {boolean} _links - Return resource link in response
* {boolean} _embedded - Return embedded resources in response
Responses:
* 201 - Successfully created applicationKey (https://api.losant.com/#/definitions/applicationKeyPostResponse)
Errors:
* 400 - Error if malformed request (https://api.losant.com/#/definitions/error)
* 404 - Error if application was not found (https://api.losant.com/#/definitions/error) | [
"Create",
"a",
"new",
"applicationKey",
"for",
"an",
"application"
] | 4a66a70180a0d907c2e50e1edf06cb8312d00260 | https://github.com/Losant/losant-rest-ruby/blob/4a66a70180a0d907c2e50e1edf06cb8312d00260/lib/losant_rest/application_keys.rb#L110-L133 |
522 | culturecode/spatial_features | lib/spatial_features/utils.rb | SpatialFeatures.Utils.class_of | def class_of(object)
case object
when ActiveRecord::Base
object.class
when ActiveRecord::Relation
object.klass
when String
object.constantize
else
object
end
end | ruby | def class_of(object)
case object
when ActiveRecord::Base
object.class
when ActiveRecord::Relation
object.klass
when String
object.constantize
else
object
end
end | [
"def",
"class_of",
"(",
"object",
")",
"case",
"object",
"when",
"ActiveRecord",
"::",
"Base",
"object",
".",
"class",
"when",
"ActiveRecord",
"::",
"Relation",
"object",
".",
"klass",
"when",
"String",
"object",
".",
"constantize",
"else",
"object",
"end",
"end"
] | Returns the class for the given, class, scope, or record | [
"Returns",
"the",
"class",
"for",
"the",
"given",
"class",
"scope",
"or",
"record"
] | 557a4b8a855129dd51a3c2cfcdad8312083fb73a | https://github.com/culturecode/spatial_features/blob/557a4b8a855129dd51a3c2cfcdad8312083fb73a/lib/spatial_features/utils.rb#L13-L24 |
523 | PRX/announce | lib/announce/subscriber.rb | Announce.Subscriber.delegate_event | def delegate_event(event)
@message = event.deep_symbolize_keys
@subject = message[:subject]
@action = message[:action]
if [message, subject, action].any? { |a| a.nil? }
raise "Message, subject, and action are not all specified for '#{event.inspect}'"
end
if respond_to?(delegate_method)
public_send(delegate_method, message[:body])
else
raise "`#{self.class.name}` is subscribed, but doesn't implement `#{delegate_method}` for '#{event.inspect}'"
end
end | ruby | def delegate_event(event)
@message = event.deep_symbolize_keys
@subject = message[:subject]
@action = message[:action]
if [message, subject, action].any? { |a| a.nil? }
raise "Message, subject, and action are not all specified for '#{event.inspect}'"
end
if respond_to?(delegate_method)
public_send(delegate_method, message[:body])
else
raise "`#{self.class.name}` is subscribed, but doesn't implement `#{delegate_method}` for '#{event.inspect}'"
end
end | [
"def",
"delegate_event",
"(",
"event",
")",
"@message",
"=",
"event",
".",
"deep_symbolize_keys",
"@subject",
"=",
"message",
"[",
":subject",
"]",
"@action",
"=",
"message",
"[",
":action",
"]",
"if",
"[",
"message",
",",
"subject",
",",
"action",
"]",
".",
"any?",
"{",
"|",
"a",
"|",
"a",
".",
"nil?",
"}",
"raise",
"\"Message, subject, and action are not all specified for '#{event.inspect}'\"",
"end",
"if",
"respond_to?",
"(",
"delegate_method",
")",
"public_send",
"(",
"delegate_method",
",",
"message",
"[",
":body",
"]",
")",
"else",
"raise",
"\"`#{self.class.name}` is subscribed, but doesn't implement `#{delegate_method}` for '#{event.inspect}'\"",
"end",
"end"
] | For use in adapters to delegate to method named receive_subject_action | [
"For",
"use",
"in",
"adapters",
"to",
"delegate",
"to",
"method",
"named",
"receive_subject_action"
] | fd9f6707059cf279411348ee4d5c6d1b1c6251d0 | https://github.com/PRX/announce/blob/fd9f6707059cf279411348ee4d5c6d1b1c6251d0/lib/announce/subscriber.rb#L23-L37 |
524 | mikemackintosh/ruby-easyrsa | lib/easyrsa/config.rb | EasyRSA.Config.load! | def load!(path)
settings = YAML.load(ERB.new(File.new(path).read).result)
if settings.present?
from_hash(settings)
end
end | ruby | def load!(path)
settings = YAML.load(ERB.new(File.new(path).read).result)
if settings.present?
from_hash(settings)
end
end | [
"def",
"load!",
"(",
"path",
")",
"settings",
"=",
"YAML",
".",
"load",
"(",
"ERB",
".",
"new",
"(",
"File",
".",
"new",
"(",
"path",
")",
".",
"read",
")",
".",
"result",
")",
"if",
"settings",
".",
"present?",
"from_hash",
"(",
"settings",
")",
"end",
"end"
] | Load the settings from a compliant easyrsa.yml file. This can be used for
easy setup with frameworks other than Rails.
@example Configure easyrsa.
easyrsa.load!("/path/to/easyrsa.yml")
@param [ String ] path The path to the file. | [
"Load",
"the",
"settings",
"from",
"a",
"compliant",
"easyrsa",
".",
"yml",
"file",
".",
"This",
"can",
"be",
"used",
"for",
"easy",
"setup",
"with",
"frameworks",
"other",
"than",
"Rails",
"."
] | a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a | https://github.com/mikemackintosh/ruby-easyrsa/blob/a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a/lib/easyrsa/config.rb#L30-L35 |
525 | dpla/KriKri | app/controllers/krikri/records_controller.rb | Krikri.RecordsController.records_by_provider | def records_by_provider(solr_params, user_params)
if @provider_id.present?
rdf_subject = Krikri::Provider.base_uri + @provider_id
solr_params[:fq] ||= []
solr_params[:fq] << "provider_id:\"#{rdf_subject}\""
end
end | ruby | def records_by_provider(solr_params, user_params)
if @provider_id.present?
rdf_subject = Krikri::Provider.base_uri + @provider_id
solr_params[:fq] ||= []
solr_params[:fq] << "provider_id:\"#{rdf_subject}\""
end
end | [
"def",
"records_by_provider",
"(",
"solr_params",
",",
"user_params",
")",
"if",
"@provider_id",
".",
"present?",
"rdf_subject",
"=",
"Krikri",
"::",
"Provider",
".",
"base_uri",
"+",
"@provider_id",
"solr_params",
"[",
":fq",
"]",
"||=",
"[",
"]",
"solr_params",
"[",
":fq",
"]",
"<<",
"\"provider_id:\\\"#{rdf_subject}\\\"\"",
"end",
"end"
] | Limit the records returned by a Solr request to those belonging to the
current provider.
@param [Hash] solr_parameters a hash of parameters to be sent to Solr.
@param [Hash] user_parameters a hash of user-supplied parameters. | [
"Limit",
"the",
"records",
"returned",
"by",
"a",
"Solr",
"request",
"to",
"those",
"belonging",
"to",
"the",
"current",
"provider",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/controllers/krikri/records_controller.rb#L168-L174 |
526 | Esri/geotrigger-ruby | lib/geotrigger/model.rb | Geotrigger.Model.post_list | def post_list models, params = {}, default_params = {}
model = models.sub /s$/, ''
params = default_params.merge params
post(model + '/list', params)[models].map do |data|
Geotrigger.const_get(model.capitalize).from_api data, @session
end
end | ruby | def post_list models, params = {}, default_params = {}
model = models.sub /s$/, ''
params = default_params.merge params
post(model + '/list', params)[models].map do |data|
Geotrigger.const_get(model.capitalize).from_api data, @session
end
end | [
"def",
"post_list",
"models",
",",
"params",
"=",
"{",
"}",
",",
"default_params",
"=",
"{",
"}",
"model",
"=",
"models",
".",
"sub",
"/",
"/",
",",
"''",
"params",
"=",
"default_params",
".",
"merge",
"params",
"post",
"(",
"model",
"+",
"'/list'",
",",
"params",
")",
"[",
"models",
"]",
".",
"map",
"do",
"|",
"data",
"|",
"Geotrigger",
".",
"const_get",
"(",
"model",
".",
"capitalize",
")",
".",
"from_api",
"data",
",",
"@session",
"end",
"end"
] | Create an instance and from given options +Hash+.
[:session] +Session+ underlying session to use when talking to the API
POST a request to this model's /list route, passing parameters. Returns
a new instance of the model object with populated data via
+Model.from_api+.
[models] +String+ name of the model to request listed data for
[params] +Hash+ parameters to send with the request
[default_params] +Hash+ default parameters to merge +params+ into | [
"Create",
"an",
"instance",
"and",
"from",
"given",
"options",
"+",
"Hash",
"+",
"."
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/model.rb#L49-L55 |
527 | Esri/geotrigger-ruby | lib/geotrigger/model.rb | Geotrigger.Model.method_missing | def method_missing meth, *args
meth_s = meth.to_s
if meth_s =~ /=$/ and args.length == 1
key = meth_s.sub(/=$/,'').camelcase
if @data and @data.key? key
@data[key] = args[0]
else
super meth, *args
end
else
key = meth_s.camelcase
if @data and @data.key? key
@data[key]
else
super meth, *args
end
end
end | ruby | def method_missing meth, *args
meth_s = meth.to_s
if meth_s =~ /=$/ and args.length == 1
key = meth_s.sub(/=$/,'').camelcase
if @data and @data.key? key
@data[key] = args[0]
else
super meth, *args
end
else
key = meth_s.camelcase
if @data and @data.key? key
@data[key]
else
super meth, *args
end
end
end | [
"def",
"method_missing",
"meth",
",",
"*",
"args",
"meth_s",
"=",
"meth",
".",
"to_s",
"if",
"meth_s",
"=~",
"/",
"/",
"and",
"args",
".",
"length",
"==",
"1",
"key",
"=",
"meth_s",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
".",
"camelcase",
"if",
"@data",
"and",
"@data",
".",
"key?",
"key",
"@data",
"[",
"key",
"]",
"=",
"args",
"[",
"0",
"]",
"else",
"super",
"meth",
",",
"args",
"end",
"else",
"key",
"=",
"meth_s",
".",
"camelcase",
"if",
"@data",
"and",
"@data",
".",
"key?",
"key",
"@data",
"[",
"key",
"]",
"else",
"super",
"meth",
",",
"args",
"end",
"end",
"end"
] | Allows snake_case accessor to top-level data values keyed by their
camelCase counterparts. An attempt to be moar Rubyish.
device.tracking_profile
#=> 'adaptive'
device.trackingProfile
#=> 'adaptive' | [
"Allows",
"snake_case",
"accessor",
"to",
"top",
"-",
"level",
"data",
"values",
"keyed",
"by",
"their",
"camelCase",
"counterparts",
".",
"An",
"attempt",
"to",
"be",
"moar",
"Rubyish",
"."
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/model.rb#L66-L83 |
528 | MYOB-Technology/http_event_logger | lib/http_event_logger/adapter/net_http.rb | Net.HTTP.request_body_from | def request_body_from(req, body)
req.body.nil? || req.body.size == 0 ? body : req.body
end | ruby | def request_body_from(req, body)
req.body.nil? || req.body.size == 0 ? body : req.body
end | [
"def",
"request_body_from",
"(",
"req",
",",
"body",
")",
"req",
".",
"body",
".",
"nil?",
"||",
"req",
".",
"body",
".",
"size",
"==",
"0",
"?",
"body",
":",
"req",
".",
"body",
"end"
] | A bit convoluted because post_form uses form_data= to assign the data, so in that case req.body will be empty | [
"A",
"bit",
"convoluted",
"because",
"post_form",
"uses",
"form_data",
"=",
"to",
"assign",
"the",
"data",
"so",
"in",
"that",
"case",
"req",
".",
"body",
"will",
"be",
"empty"
] | f222f75395e09260b274d6f85c05062f0a2c8e43 | https://github.com/MYOB-Technology/http_event_logger/blob/f222f75395e09260b274d6f85c05062f0a2c8e43/lib/http_event_logger/adapter/net_http.rb#L49-L51 |
529 | dpla/KriKri | lib/krikri/enrichments/language_to_lexvo.rb | Krikri::Enrichments.LanguageToLexvo.enrich_value | def enrich_value(value)
return enrich_node(value) if value.is_a?(ActiveTriples::Resource) &&
value.node?
return value if value.is_a?(DPLA::MAP::Controlled::Language)
return nil if value.is_a?(ActiveTriples::Resource)
enrich_literal(value)
end | ruby | def enrich_value(value)
return enrich_node(value) if value.is_a?(ActiveTriples::Resource) &&
value.node?
return value if value.is_a?(DPLA::MAP::Controlled::Language)
return nil if value.is_a?(ActiveTriples::Resource)
enrich_literal(value)
end | [
"def",
"enrich_value",
"(",
"value",
")",
"return",
"enrich_node",
"(",
"value",
")",
"if",
"value",
".",
"is_a?",
"(",
"ActiveTriples",
"::",
"Resource",
")",
"&&",
"value",
".",
"node?",
"return",
"value",
"if",
"value",
".",
"is_a?",
"(",
"DPLA",
"::",
"MAP",
"::",
"Controlled",
"::",
"Language",
")",
"return",
"nil",
"if",
"value",
".",
"is_a?",
"(",
"ActiveTriples",
"::",
"Resource",
")",
"enrich_literal",
"(",
"value",
")",
"end"
] | Runs the enrichment against a node. Can match literal values, and Language
values with a provided label.
@example with a matching value
lang = enrich_value('finnish')
#=> #<DPLA::MAP::Controlled::Language:0x3f(default)>
lang.providedLabel
#=> ['finnish']
lang.exactMatch.map(&:to_term)
#=> [#<RDF::Vocabulary::Term:0x9b URI:http://lexvo.org/id/iso639-3/fin>]
@example with no match
lang = enrich_value('moomin')
#=> #<DPLA::MAP::Controlled::Language:0x3f(default)>
lang.providedLabel
#=> ['moomin']
lang.exactMatch
#=> []
@param value [ActiveTriples::Resource, #to_s]
@return [DPLA::MAP::Controlled::Language, nil] a resource representing the
language match. | [
"Runs",
"the",
"enrichment",
"against",
"a",
"node",
".",
"Can",
"match",
"literal",
"values",
"and",
"Language",
"values",
"with",
"a",
"provided",
"label",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/language_to_lexvo.rb#L77-L83 |
530 | dpla/KriKri | lib/krikri/enrichments/language_to_lexvo.rb | Krikri::Enrichments.LanguageToLexvo.enrich_literal | def enrich_literal(label)
node = DPLA::MAP::Controlled::Language.new()
node.providedLabel = label
match = match_iso(label.to_s)
match = match_label(label.to_s) if match.node?
# if match is still a node, we didn't find anything
return node if match.node?
node.exactMatch = match
node.prefLabel = RDF::ISO_639_3[match.rdf_subject.qname[1]].label.last
node
end | ruby | def enrich_literal(label)
node = DPLA::MAP::Controlled::Language.new()
node.providedLabel = label
match = match_iso(label.to_s)
match = match_label(label.to_s) if match.node?
# if match is still a node, we didn't find anything
return node if match.node?
node.exactMatch = match
node.prefLabel = RDF::ISO_639_3[match.rdf_subject.qname[1]].label.last
node
end | [
"def",
"enrich_literal",
"(",
"label",
")",
"node",
"=",
"DPLA",
"::",
"MAP",
"::",
"Controlled",
"::",
"Language",
".",
"new",
"(",
")",
"node",
".",
"providedLabel",
"=",
"label",
"match",
"=",
"match_iso",
"(",
"label",
".",
"to_s",
")",
"match",
"=",
"match_label",
"(",
"label",
".",
"to_s",
")",
"if",
"match",
".",
"node?",
"# if match is still a node, we didn't find anything",
"return",
"node",
"if",
"match",
".",
"node?",
"node",
".",
"exactMatch",
"=",
"match",
"node",
".",
"prefLabel",
"=",
"RDF",
"::",
"ISO_639_3",
"[",
"match",
".",
"rdf_subject",
".",
"qname",
"[",
"1",
"]",
"]",
".",
"label",
".",
"last",
"node",
"end"
] | Runs the enrichment over a string.
@param label [#to_s] the string to match
@return [ActiveTriples::Resource] a blank node with a `dpla:providedLabel`
of `label` and a `skos:exactMatch` of the matching lexvo language,
if any | [
"Runs",
"the",
"enrichment",
"over",
"a",
"string",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/language_to_lexvo.rb#L106-L119 |
531 | fzxu/mongoid_order | lib/mongoid_order.rb | Mongoid.Orderable.move_above | def move_above(other)
if position > other.position
new_position = other.position
other.lower_siblings.where(:position.lt => self.position).each { |s| s.inc(:position, 1) }
other.inc(:position, 1)
self.position = new_position
save!
else
new_position = other.position - 1
other.higher_siblings.where(:position.gt => self.position).each { |s| s.inc(:position, -1) }
self.position = new_position
save!
end
end | ruby | def move_above(other)
if position > other.position
new_position = other.position
other.lower_siblings.where(:position.lt => self.position).each { |s| s.inc(:position, 1) }
other.inc(:position, 1)
self.position = new_position
save!
else
new_position = other.position - 1
other.higher_siblings.where(:position.gt => self.position).each { |s| s.inc(:position, -1) }
self.position = new_position
save!
end
end | [
"def",
"move_above",
"(",
"other",
")",
"if",
"position",
">",
"other",
".",
"position",
"new_position",
"=",
"other",
".",
"position",
"other",
".",
"lower_siblings",
".",
"where",
"(",
":position",
".",
"lt",
"=>",
"self",
".",
"position",
")",
".",
"each",
"{",
"|",
"s",
"|",
"s",
".",
"inc",
"(",
":position",
",",
"1",
")",
"}",
"other",
".",
"inc",
"(",
":position",
",",
"1",
")",
"self",
".",
"position",
"=",
"new_position",
"save!",
"else",
"new_position",
"=",
"other",
".",
"position",
"-",
"1",
"other",
".",
"higher_siblings",
".",
"where",
"(",
":position",
".",
"gt",
"=>",
"self",
".",
"position",
")",
".",
"each",
"{",
"|",
"s",
"|",
"s",
".",
"inc",
"(",
":position",
",",
"-",
"1",
")",
"}",
"self",
".",
"position",
"=",
"new_position",
"save!",
"end",
"end"
] | Move this node above the specified node
This method changes the node's parent if nescessary. | [
"Move",
"this",
"node",
"above",
"the",
"specified",
"node"
] | 803a80762a460c90f6cc6ad8e6ab123a6ab9c97d | https://github.com/fzxu/mongoid_order/blob/803a80762a460c90f6cc6ad8e6ab123a6ab9c97d/lib/mongoid_order.rb#L105-L118 |
532 | zdennis/yap-shell-parser | lib/yap/shell/parser/lexer.rb | Yap::Shell.Parser::Lexer.whitespace_token | def whitespace_token
if md=WHITESPACE.match(@chunk)
input = md.to_a[0]
input.length
else
did_not_match
end
end | ruby | def whitespace_token
if md=WHITESPACE.match(@chunk)
input = md.to_a[0]
input.length
else
did_not_match
end
end | [
"def",
"whitespace_token",
"if",
"md",
"=",
"WHITESPACE",
".",
"match",
"(",
"@chunk",
")",
"input",
"=",
"md",
".",
"to_a",
"[",
"0",
"]",
"input",
".",
"length",
"else",
"did_not_match",
"end",
"end"
] | Matches and consumes non-meaningful whitespace. | [
"Matches",
"and",
"consumes",
"non",
"-",
"meaningful",
"whitespace",
"."
] | b3f3d31dd5cd1b05b381709338f0e2e47e970add | https://github.com/zdennis/yap-shell-parser/blob/b3f3d31dd5cd1b05b381709338f0e2e47e970add/lib/yap/shell/parser/lexer.rb#L365-L372 |
533 | zdennis/yap-shell-parser | lib/yap/shell/parser/lexer.rb | Yap::Shell.Parser::Lexer.string_token | def string_token
if %w(' ").include?(@chunk[0])
result = process_string @chunk[0..-1], @chunk[0]
if @looking_for_args
token :Argument, result.str, attrs: { quoted_by: @chunk[0] }
else
token :Command, result.str
end
result.consumed_length
else
did_not_match
end
end | ruby | def string_token
if %w(' ").include?(@chunk[0])
result = process_string @chunk[0..-1], @chunk[0]
if @looking_for_args
token :Argument, result.str, attrs: { quoted_by: @chunk[0] }
else
token :Command, result.str
end
result.consumed_length
else
did_not_match
end
end | [
"def",
"string_token",
"if",
"%w(",
"'",
"\"",
")",
".",
"include?",
"(",
"@chunk",
"[",
"0",
"]",
")",
"result",
"=",
"process_string",
"@chunk",
"[",
"0",
"..",
"-",
"1",
"]",
",",
"@chunk",
"[",
"0",
"]",
"if",
"@looking_for_args",
"token",
":Argument",
",",
"result",
".",
"str",
",",
"attrs",
":",
"{",
"quoted_by",
":",
"@chunk",
"[",
"0",
"]",
"}",
"else",
"token",
":Command",
",",
"result",
".",
"str",
"end",
"result",
".",
"consumed_length",
"else",
"did_not_match",
"end",
"end"
] | Matches single and double quoted strings | [
"Matches",
"single",
"and",
"double",
"quoted",
"strings"
] | b3f3d31dd5cd1b05b381709338f0e2e47e970add | https://github.com/zdennis/yap-shell-parser/blob/b3f3d31dd5cd1b05b381709338f0e2e47e970add/lib/yap/shell/parser/lexer.rb#L481-L493 |
534 | dpla/KriKri | app/models/krikri/qa_report.rb | Krikri.QAReport.generate_field_report! | def generate_field_report!
report = field_queries.inject({}) do |report_hash, (k, v)|
report_hash[k] = solutions_to_hash(v.execute)
report_hash
end
update(field_report: report)
end | ruby | def generate_field_report!
report = field_queries.inject({}) do |report_hash, (k, v)|
report_hash[k] = solutions_to_hash(v.execute)
report_hash
end
update(field_report: report)
end | [
"def",
"generate_field_report!",
"report",
"=",
"field_queries",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"report_hash",
",",
"(",
"k",
",",
"v",
")",
"|",
"report_hash",
"[",
"k",
"]",
"=",
"solutions_to_hash",
"(",
"v",
".",
"execute",
")",
"report_hash",
"end",
"update",
"(",
"field_report",
":",
"report",
")",
"end"
] | Generates and saves the field report for the provider, sending SPARQL
queries as necessary.
@return [Hash] | [
"Generates",
"and",
"saves",
"the",
"field",
"report",
"for",
"the",
"provider",
"sending",
"SPARQL",
"queries",
"as",
"necessary",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/models/krikri/qa_report.rb#L46-L52 |
535 | dpla/KriKri | app/models/krikri/qa_report.rb | Krikri.QAReport.generate_count_report! | def generate_count_report!
report = count_queries.inject({}) do |report_hash, (k, v)|
report_hash[k] = solutions_to_counts(v.execute)
report_hash
end
update(count_report: report)
end | ruby | def generate_count_report!
report = count_queries.inject({}) do |report_hash, (k, v)|
report_hash[k] = solutions_to_counts(v.execute)
report_hash
end
update(count_report: report)
end | [
"def",
"generate_count_report!",
"report",
"=",
"count_queries",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"report_hash",
",",
"(",
"k",
",",
"v",
")",
"|",
"report_hash",
"[",
"k",
"]",
"=",
"solutions_to_counts",
"(",
"v",
".",
"execute",
")",
"report_hash",
"end",
"update",
"(",
"count_report",
":",
"report",
")",
"end"
] | Generates and saves the coun treport for the provider, sending SPARQL
queries as necessary.
@return [Hash] | [
"Generates",
"and",
"saves",
"the",
"coun",
"treport",
"for",
"the",
"provider",
"sending",
"SPARQL",
"queries",
"as",
"necessary",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/models/krikri/qa_report.rb#L59-L66 |
536 | outcomesinsights/sequelizer | lib/sequelizer/connection_maker.rb | Sequelizer.ConnectionMaker.connection | def connection
opts = options.to_hash
extensions = options.extensions
conn = if url = (opts.delete(:uri) || opts.delete(:url))
Sequel.connect(url, opts)
else
# Kerberos related options
realm = opts[:realm]
host_fqdn = opts[:host_fqdn] || opts[:host]
principal = opts[:principal]
adapter = opts[:adapter]
if adapter =~ /\Ajdbc_/
user = opts[:user]
password = opts[:password]
end
case opts[:adapter] && opts[:adapter].to_sym
when :jdbc_hive2
opts[:adapter] = :jdbc
auth = if realm
";principal=#{e principal}/#{e host_fqdn}@#{e realm}"
elsif user
";user=#{e user};password=#{e password}"
else
';auth=noSasl'
end
opts[:uri] = "jdbc:hive2://#{e opts[:host]}:#{opts.fetch(:port, 21050).to_i}/#{e(opts[:database] || 'default')}#{auth}"
when :jdbc_impala
opts[:adapter] = :jdbc
auth = if realm
";AuthMech=1;KrbServiceName=#{e principal};KrbAuthType=2;KrbHostFQDN=#{e host_fqdn};KrbRealm=#{e realm}"
elsif user
if password
";AuthMech=3;UID=#{e user};PWD=#{e password}"
else
";AuthMech=2;UID=#{e user}"
end
end
opts[:uri] = "jdbc:impala://#{e opts[:host]}:#{opts.fetch(:port, 21050).to_i}/#{e(opts[:database] || 'default')}#{auth}"
when :jdbc_postgres
opts[:adapter] = :jdbc
auth = "?user=#{user}#{"&password=#{password}" if password}" if user
opts[:uri] = "jdbc:postgresql://#{e opts[:host]}:#{opts.fetch(:port, 5432).to_i}/#{e(opts[:database])}#{auth}"
when :impala
opts[:database] ||= 'default'
opts[:port] ||= 21000
if principal
# realm doesn't seem to be used?
opts[:transport] = :sasl
opts[:sasl_params] = {
mechanism: "GSSAPI",
remote_host: host_fqdn,
remote_principal: principal
}
end
end
Sequel.connect(opts)
end
conn.extension(*extensions)
conn
end | ruby | def connection
opts = options.to_hash
extensions = options.extensions
conn = if url = (opts.delete(:uri) || opts.delete(:url))
Sequel.connect(url, opts)
else
# Kerberos related options
realm = opts[:realm]
host_fqdn = opts[:host_fqdn] || opts[:host]
principal = opts[:principal]
adapter = opts[:adapter]
if adapter =~ /\Ajdbc_/
user = opts[:user]
password = opts[:password]
end
case opts[:adapter] && opts[:adapter].to_sym
when :jdbc_hive2
opts[:adapter] = :jdbc
auth = if realm
";principal=#{e principal}/#{e host_fqdn}@#{e realm}"
elsif user
";user=#{e user};password=#{e password}"
else
';auth=noSasl'
end
opts[:uri] = "jdbc:hive2://#{e opts[:host]}:#{opts.fetch(:port, 21050).to_i}/#{e(opts[:database] || 'default')}#{auth}"
when :jdbc_impala
opts[:adapter] = :jdbc
auth = if realm
";AuthMech=1;KrbServiceName=#{e principal};KrbAuthType=2;KrbHostFQDN=#{e host_fqdn};KrbRealm=#{e realm}"
elsif user
if password
";AuthMech=3;UID=#{e user};PWD=#{e password}"
else
";AuthMech=2;UID=#{e user}"
end
end
opts[:uri] = "jdbc:impala://#{e opts[:host]}:#{opts.fetch(:port, 21050).to_i}/#{e(opts[:database] || 'default')}#{auth}"
when :jdbc_postgres
opts[:adapter] = :jdbc
auth = "?user=#{user}#{"&password=#{password}" if password}" if user
opts[:uri] = "jdbc:postgresql://#{e opts[:host]}:#{opts.fetch(:port, 5432).to_i}/#{e(opts[:database])}#{auth}"
when :impala
opts[:database] ||= 'default'
opts[:port] ||= 21000
if principal
# realm doesn't seem to be used?
opts[:transport] = :sasl
opts[:sasl_params] = {
mechanism: "GSSAPI",
remote_host: host_fqdn,
remote_principal: principal
}
end
end
Sequel.connect(opts)
end
conn.extension(*extensions)
conn
end | [
"def",
"connection",
"opts",
"=",
"options",
".",
"to_hash",
"extensions",
"=",
"options",
".",
"extensions",
"conn",
"=",
"if",
"url",
"=",
"(",
"opts",
".",
"delete",
"(",
":uri",
")",
"||",
"opts",
".",
"delete",
"(",
":url",
")",
")",
"Sequel",
".",
"connect",
"(",
"url",
",",
"opts",
")",
"else",
"# Kerberos related options",
"realm",
"=",
"opts",
"[",
":realm",
"]",
"host_fqdn",
"=",
"opts",
"[",
":host_fqdn",
"]",
"||",
"opts",
"[",
":host",
"]",
"principal",
"=",
"opts",
"[",
":principal",
"]",
"adapter",
"=",
"opts",
"[",
":adapter",
"]",
"if",
"adapter",
"=~",
"/",
"\\A",
"/",
"user",
"=",
"opts",
"[",
":user",
"]",
"password",
"=",
"opts",
"[",
":password",
"]",
"end",
"case",
"opts",
"[",
":adapter",
"]",
"&&",
"opts",
"[",
":adapter",
"]",
".",
"to_sym",
"when",
":jdbc_hive2",
"opts",
"[",
":adapter",
"]",
"=",
":jdbc",
"auth",
"=",
"if",
"realm",
"\";principal=#{e principal}/#{e host_fqdn}@#{e realm}\"",
"elsif",
"user",
"\";user=#{e user};password=#{e password}\"",
"else",
"';auth=noSasl'",
"end",
"opts",
"[",
":uri",
"]",
"=",
"\"jdbc:hive2://#{e opts[:host]}:#{opts.fetch(:port, 21050).to_i}/#{e(opts[:database] || 'default')}#{auth}\"",
"when",
":jdbc_impala",
"opts",
"[",
":adapter",
"]",
"=",
":jdbc",
"auth",
"=",
"if",
"realm",
"\";AuthMech=1;KrbServiceName=#{e principal};KrbAuthType=2;KrbHostFQDN=#{e host_fqdn};KrbRealm=#{e realm}\"",
"elsif",
"user",
"if",
"password",
"\";AuthMech=3;UID=#{e user};PWD=#{e password}\"",
"else",
"\";AuthMech=2;UID=#{e user}\"",
"end",
"end",
"opts",
"[",
":uri",
"]",
"=",
"\"jdbc:impala://#{e opts[:host]}:#{opts.fetch(:port, 21050).to_i}/#{e(opts[:database] || 'default')}#{auth}\"",
"when",
":jdbc_postgres",
"opts",
"[",
":adapter",
"]",
"=",
":jdbc",
"auth",
"=",
"\"?user=#{user}#{\"&password=#{password}\" if password}\"",
"if",
"user",
"opts",
"[",
":uri",
"]",
"=",
"\"jdbc:postgresql://#{e opts[:host]}:#{opts.fetch(:port, 5432).to_i}/#{e(opts[:database])}#{auth}\"",
"when",
":impala",
"opts",
"[",
":database",
"]",
"||=",
"'default'",
"opts",
"[",
":port",
"]",
"||=",
"21000",
"if",
"principal",
"# realm doesn't seem to be used?",
"opts",
"[",
":transport",
"]",
"=",
":sasl",
"opts",
"[",
":sasl_params",
"]",
"=",
"{",
"mechanism",
":",
"\"GSSAPI\"",
",",
"remote_host",
":",
"host_fqdn",
",",
"remote_principal",
":",
"principal",
"}",
"end",
"end",
"Sequel",
".",
"connect",
"(",
"opts",
")",
"end",
"conn",
".",
"extension",
"(",
"extensions",
")",
"conn",
"end"
] | Accepts an optional set of database options
If no options are provided, attempts to read options from
config/database.yml
If config/database.yml doesn't exist, Dotenv is used to try to load a
.env file, then uses any SEQUELIZER_* environment variables as
database options
Returns a Sequel connection to the database | [
"Accepts",
"an",
"optional",
"set",
"of",
"database",
"options"
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/connection_maker.rb#L25-L88 |
537 | salsify/avro_schema_registry-client | lib/avro_schema_registry/client.rb | AvroSchemaRegistry.Client.register | def register(subject, schema, **params)
lookup_subject_schema(subject, schema)
rescue Excon::Errors::NotFound
register_without_lookup(subject, schema, params)
end | ruby | def register(subject, schema, **params)
lookup_subject_schema(subject, schema)
rescue Excon::Errors::NotFound
register_without_lookup(subject, schema, params)
end | [
"def",
"register",
"(",
"subject",
",",
"schema",
",",
"**",
"params",
")",
"lookup_subject_schema",
"(",
"subject",
",",
"schema",
")",
"rescue",
"Excon",
"::",
"Errors",
"::",
"NotFound",
"register_without_lookup",
"(",
"subject",
",",
"schema",
",",
"params",
")",
"end"
] | Override register to first check if a schema is registered by fingerprint
Also, allow additional params to be passed to register. | [
"Override",
"register",
"to",
"first",
"check",
"if",
"a",
"schema",
"is",
"registered",
"by",
"fingerprint",
"Also",
"allow",
"additional",
"params",
"to",
"be",
"passed",
"to",
"register",
"."
] | ae34346995d98a91709093f013f371153bdbedbc | https://github.com/salsify/avro_schema_registry-client/blob/ae34346995d98a91709093f013f371153bdbedbc/lib/avro_schema_registry/client.rb#L23-L27 |
538 | salsify/avro_schema_registry-client | lib/avro_schema_registry/client.rb | AvroSchemaRegistry.Client.compatible? | def compatible?(subject, schema, version = 'latest', **params)
data = post("/compatibility/subjects/#{subject}/versions/#{version}",
expects: [200, 404],
body: { schema: schema.to_s }.merge!(params).to_json)
data.fetch('is_compatible', false) unless data.key?('error_code')
end | ruby | def compatible?(subject, schema, version = 'latest', **params)
data = post("/compatibility/subjects/#{subject}/versions/#{version}",
expects: [200, 404],
body: { schema: schema.to_s }.merge!(params).to_json)
data.fetch('is_compatible', false) unless data.key?('error_code')
end | [
"def",
"compatible?",
"(",
"subject",
",",
"schema",
",",
"version",
"=",
"'latest'",
",",
"**",
"params",
")",
"data",
"=",
"post",
"(",
"\"/compatibility/subjects/#{subject}/versions/#{version}\"",
",",
"expects",
":",
"[",
"200",
",",
"404",
"]",
",",
"body",
":",
"{",
"schema",
":",
"schema",
".",
"to_s",
"}",
".",
"merge!",
"(",
"params",
")",
".",
"to_json",
")",
"data",
".",
"fetch",
"(",
"'is_compatible'",
",",
"false",
")",
"unless",
"data",
".",
"key?",
"(",
"'error_code'",
")",
"end"
] | Override to add support for additional params | [
"Override",
"to",
"add",
"support",
"for",
"additional",
"params"
] | ae34346995d98a91709093f013f371153bdbedbc | https://github.com/salsify/avro_schema_registry-client/blob/ae34346995d98a91709093f013f371153bdbedbc/lib/avro_schema_registry/client.rb#L38-L43 |
539 | huffpostdata/ruby-pollster | lib/pollster/api_client.rb | Pollster.ApiClient.call_api_tsv | def call_api_tsv(http_method, path, opts = {})
request = build_request(http_method, path, opts)
response = request.run
if @config.debugging
@config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
if response.timed_out?
fail ApiError.new('Connection timed out')
elsif response.code == 0
# Errors from libcurl will be made visible here
fail ApiError.new(:code => 0,
:message => response.return_message)
else
fail ApiError.new(:code => response.code,
:response_headers => response.headers,
:response_body => response.body),
response.status_message
end
end
if opts[:return_type]
return_type = Pollster.const_get(opts[:return_type])
data = return_type.from_tsv(response.body)
else
data = nil
end
return data, response.code, response.headers
end | ruby | def call_api_tsv(http_method, path, opts = {})
request = build_request(http_method, path, opts)
response = request.run
if @config.debugging
@config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
if response.timed_out?
fail ApiError.new('Connection timed out')
elsif response.code == 0
# Errors from libcurl will be made visible here
fail ApiError.new(:code => 0,
:message => response.return_message)
else
fail ApiError.new(:code => response.code,
:response_headers => response.headers,
:response_body => response.body),
response.status_message
end
end
if opts[:return_type]
return_type = Pollster.const_get(opts[:return_type])
data = return_type.from_tsv(response.body)
else
data = nil
end
return data, response.code, response.headers
end | [
"def",
"call_api_tsv",
"(",
"http_method",
",",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"request",
"=",
"build_request",
"(",
"http_method",
",",
"path",
",",
"opts",
")",
"response",
"=",
"request",
".",
"run",
"if",
"@config",
".",
"debugging",
"@config",
".",
"logger",
".",
"debug",
"\"HTTP response body ~BEGIN~\\n#{response.body}\\n~END~\\n\"",
"end",
"unless",
"response",
".",
"success?",
"if",
"response",
".",
"timed_out?",
"fail",
"ApiError",
".",
"new",
"(",
"'Connection timed out'",
")",
"elsif",
"response",
".",
"code",
"==",
"0",
"# Errors from libcurl will be made visible here",
"fail",
"ApiError",
".",
"new",
"(",
":code",
"=>",
"0",
",",
":message",
"=>",
"response",
".",
"return_message",
")",
"else",
"fail",
"ApiError",
".",
"new",
"(",
":code",
"=>",
"response",
".",
"code",
",",
":response_headers",
"=>",
"response",
".",
"headers",
",",
":response_body",
"=>",
"response",
".",
"body",
")",
",",
"response",
".",
"status_message",
"end",
"end",
"if",
"opts",
"[",
":return_type",
"]",
"return_type",
"=",
"Pollster",
".",
"const_get",
"(",
"opts",
"[",
":return_type",
"]",
")",
"data",
"=",
"return_type",
".",
"from_tsv",
"(",
"response",
".",
"body",
")",
"else",
"data",
"=",
"nil",
"end",
"return",
"data",
",",
"response",
".",
"code",
",",
"response",
".",
"headers",
"end"
] | Call an API with given options, and parse the TSV response.
@return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
the data deserialized from response body (could be nil), response status code and response headers. | [
"Call",
"an",
"API",
"with",
"given",
"options",
"and",
"parse",
"the",
"TSV",
"response",
"."
] | 32fb81b58e7fb39787a7591b8ede579301cd2b8b | https://github.com/huffpostdata/ruby-pollster/blob/32fb81b58e7fb39787a7591b8ede579301cd2b8b/lib/pollster/api_client.rb#L72-L102 |
540 | arkes/sorting_table_for | lib/sorting_table_for/format_cell.rb | SortingTableFor.FormatCell.render_cell_tbody | def render_cell_tbody
if @type == :action
cell_value = action_link_to(@ask)
elsif @ask
cell_value = (@ask.is_a?(Symbol)) ? format_cell_value(@object[@ask], @ask) : format_cell_value(@ask)
else
cell_value = @block
end
cell_value = action_link_to(@options[:action], cell_value) if @type != :action and @options.has_key?(:action)
content_tag(:td, cell_value, @html_options)
end | ruby | def render_cell_tbody
if @type == :action
cell_value = action_link_to(@ask)
elsif @ask
cell_value = (@ask.is_a?(Symbol)) ? format_cell_value(@object[@ask], @ask) : format_cell_value(@ask)
else
cell_value = @block
end
cell_value = action_link_to(@options[:action], cell_value) if @type != :action and @options.has_key?(:action)
content_tag(:td, cell_value, @html_options)
end | [
"def",
"render_cell_tbody",
"if",
"@type",
"==",
":action",
"cell_value",
"=",
"action_link_to",
"(",
"@ask",
")",
"elsif",
"@ask",
"cell_value",
"=",
"(",
"@ask",
".",
"is_a?",
"(",
"Symbol",
")",
")",
"?",
"format_cell_value",
"(",
"@object",
"[",
"@ask",
"]",
",",
"@ask",
")",
":",
"format_cell_value",
"(",
"@ask",
")",
"else",
"cell_value",
"=",
"@block",
"end",
"cell_value",
"=",
"action_link_to",
"(",
"@options",
"[",
":action",
"]",
",",
"cell_value",
")",
"if",
"@type",
"!=",
":action",
"and",
"@options",
".",
"has_key?",
"(",
":action",
")",
"content_tag",
"(",
":td",
",",
"cell_value",
",",
"@html_options",
")",
"end"
] | Return a td with the formated value or action for columns | [
"Return",
"a",
"td",
"with",
"the",
"formated",
"value",
"or",
"action",
"for",
"columns"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_cell.rb#L21-L31 |
541 | arkes/sorting_table_for | lib/sorting_table_for/format_cell.rb | SortingTableFor.FormatCell.render_cell_thead | def render_cell_thead
if @ask
cell_value = (@ask.is_a?(Symbol)) ? I18n.t(@ask, {}, :header) : @ask
else
cell_value = @block
end
if @can_sort
sort_on = @options[:sort_as] || @ask
@html_options.merge!(:class => "#{@html_options[:class]} #{sorting_html_class(sort_on)}".strip)
content_tag(:th, sort_link_to(cell_value, sort_on), @html_options)
else
content_tag(:th, cell_value, @html_options)
end
end | ruby | def render_cell_thead
if @ask
cell_value = (@ask.is_a?(Symbol)) ? I18n.t(@ask, {}, :header) : @ask
else
cell_value = @block
end
if @can_sort
sort_on = @options[:sort_as] || @ask
@html_options.merge!(:class => "#{@html_options[:class]} #{sorting_html_class(sort_on)}".strip)
content_tag(:th, sort_link_to(cell_value, sort_on), @html_options)
else
content_tag(:th, cell_value, @html_options)
end
end | [
"def",
"render_cell_thead",
"if",
"@ask",
"cell_value",
"=",
"(",
"@ask",
".",
"is_a?",
"(",
"Symbol",
")",
")",
"?",
"I18n",
".",
"t",
"(",
"@ask",
",",
"{",
"}",
",",
":header",
")",
":",
"@ask",
"else",
"cell_value",
"=",
"@block",
"end",
"if",
"@can_sort",
"sort_on",
"=",
"@options",
"[",
":sort_as",
"]",
"||",
"@ask",
"@html_options",
".",
"merge!",
"(",
":class",
"=>",
"\"#{@html_options[:class]} #{sorting_html_class(sort_on)}\"",
".",
"strip",
")",
"content_tag",
"(",
":th",
",",
"sort_link_to",
"(",
"cell_value",
",",
"sort_on",
")",
",",
"@html_options",
")",
"else",
"content_tag",
"(",
":th",
",",
"cell_value",
",",
"@html_options",
")",
"end",
"end"
] | Return a td with the formated value or action for headers | [
"Return",
"a",
"td",
"with",
"the",
"formated",
"value",
"or",
"action",
"for",
"headers"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_cell.rb#L34-L47 |
542 | arkes/sorting_table_for | lib/sorting_table_for/format_cell.rb | SortingTableFor.FormatCell.action_link_to | def action_link_to(action, block = nil)
object_or_array = @@object_or_array.clone
object_or_array.push @object
return case action.to_sym
when :delete
create_link_to(block || I18n.t(:delete), object_or_array, @@options[:link_remote], :delete, I18n.t(:confirm_delete))
when :show
create_link_to(block || I18n.t(:show), object_or_array, @@options[:link_remote])
else
object_or_array.insert(0, action)
create_link_to(block || I18n.t(@ask), object_or_array, @@options[:link_remote])
end
end | ruby | def action_link_to(action, block = nil)
object_or_array = @@object_or_array.clone
object_or_array.push @object
return case action.to_sym
when :delete
create_link_to(block || I18n.t(:delete), object_or_array, @@options[:link_remote], :delete, I18n.t(:confirm_delete))
when :show
create_link_to(block || I18n.t(:show), object_or_array, @@options[:link_remote])
else
object_or_array.insert(0, action)
create_link_to(block || I18n.t(@ask), object_or_array, @@options[:link_remote])
end
end | [
"def",
"action_link_to",
"(",
"action",
",",
"block",
"=",
"nil",
")",
"object_or_array",
"=",
"@@object_or_array",
".",
"clone",
"object_or_array",
".",
"push",
"@object",
"return",
"case",
"action",
".",
"to_sym",
"when",
":delete",
"create_link_to",
"(",
"block",
"||",
"I18n",
".",
"t",
"(",
":delete",
")",
",",
"object_or_array",
",",
"@@options",
"[",
":link_remote",
"]",
",",
":delete",
",",
"I18n",
".",
"t",
"(",
":confirm_delete",
")",
")",
"when",
":show",
"create_link_to",
"(",
"block",
"||",
"I18n",
".",
"t",
"(",
":show",
")",
",",
"object_or_array",
",",
"@@options",
"[",
":link_remote",
"]",
")",
"else",
"object_or_array",
".",
"insert",
"(",
"0",
",",
"action",
")",
"create_link_to",
"(",
"block",
"||",
"I18n",
".",
"t",
"(",
"@ask",
")",
",",
"object_or_array",
",",
"@@options",
"[",
":link_remote",
"]",
")",
"end",
"end"
] | Create the link for actions
Set the I18n translation or the given block for the link's name | [
"Create",
"the",
"link",
"for",
"actions",
"Set",
"the",
"I18n",
"translation",
"or",
"the",
"given",
"block",
"for",
"the",
"link",
"s",
"name"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_cell.rb#L84-L96 |
543 | arkes/sorting_table_for | lib/sorting_table_for/format_cell.rb | SortingTableFor.FormatCell.create_link_to | def create_link_to(block, url, remote, method = nil, confirm = nil)
if remote
return link_to(block, url, :method => method, :confirm => confirm, :remote => true)
end
link_to(block, url, :method => method, :confirm => confirm)
end | ruby | def create_link_to(block, url, remote, method = nil, confirm = nil)
if remote
return link_to(block, url, :method => method, :confirm => confirm, :remote => true)
end
link_to(block, url, :method => method, :confirm => confirm)
end | [
"def",
"create_link_to",
"(",
"block",
",",
"url",
",",
"remote",
",",
"method",
"=",
"nil",
",",
"confirm",
"=",
"nil",
")",
"if",
"remote",
"return",
"link_to",
"(",
"block",
",",
"url",
",",
":method",
"=>",
"method",
",",
":confirm",
"=>",
"confirm",
",",
":remote",
"=>",
"true",
")",
"end",
"link_to",
"(",
"block",
",",
"url",
",",
":method",
"=>",
"method",
",",
":confirm",
"=>",
"confirm",
")",
"end"
] | Create the link based on object
Set an ajax link if option link_remote is set to true | [
"Create",
"the",
"link",
"based",
"on",
"object",
"Set",
"an",
"ajax",
"link",
"if",
"option",
"link_remote",
"is",
"set",
"to",
"true"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_cell.rb#L105-L110 |
544 | arkes/sorting_table_for | lib/sorting_table_for/format_cell.rb | SortingTableFor.FormatCell.format_cell_value | def format_cell_value(value, attribute = nil)
unless (ret_value = format_cell_value_as_ask(value)).nil?
return ret_value
end
format_cell_value_as_type(value, attribute)
end | ruby | def format_cell_value(value, attribute = nil)
unless (ret_value = format_cell_value_as_ask(value)).nil?
return ret_value
end
format_cell_value_as_type(value, attribute)
end | [
"def",
"format_cell_value",
"(",
"value",
",",
"attribute",
"=",
"nil",
")",
"unless",
"(",
"ret_value",
"=",
"format_cell_value_as_ask",
"(",
"value",
")",
")",
".",
"nil?",
"return",
"ret_value",
"end",
"format_cell_value_as_type",
"(",
"value",
",",
"attribute",
")",
"end"
] | Return the formated cell's value | [
"Return",
"the",
"formated",
"cell",
"s",
"value"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_cell.rb#L152-L157 |
545 | arkes/sorting_table_for | lib/sorting_table_for/format_cell.rb | SortingTableFor.FormatCell.format_cell_value_as_type | def format_cell_value_as_type(value, attribute)
if value.is_a?(Time) or value.is_a?(Date)
return ::I18n.l(value, :format => @options[:format] || TableBuilder.i18n_default_format_date)
elsif TableBuilder.currency_columns.include?(attribute)
return number_to_currency(value)
elsif value.is_a?(TrueClass)
return TableBuilder.default_boolean.first
elsif value.is_a?(FalseClass)
return TableBuilder.default_boolean.second
end
value
end | ruby | def format_cell_value_as_type(value, attribute)
if value.is_a?(Time) or value.is_a?(Date)
return ::I18n.l(value, :format => @options[:format] || TableBuilder.i18n_default_format_date)
elsif TableBuilder.currency_columns.include?(attribute)
return number_to_currency(value)
elsif value.is_a?(TrueClass)
return TableBuilder.default_boolean.first
elsif value.is_a?(FalseClass)
return TableBuilder.default_boolean.second
end
value
end | [
"def",
"format_cell_value_as_type",
"(",
"value",
",",
"attribute",
")",
"if",
"value",
".",
"is_a?",
"(",
"Time",
")",
"or",
"value",
".",
"is_a?",
"(",
"Date",
")",
"return",
"::",
"I18n",
".",
"l",
"(",
"value",
",",
":format",
"=>",
"@options",
"[",
":format",
"]",
"||",
"TableBuilder",
".",
"i18n_default_format_date",
")",
"elsif",
"TableBuilder",
".",
"currency_columns",
".",
"include?",
"(",
"attribute",
")",
"return",
"number_to_currency",
"(",
"value",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"TrueClass",
")",
"return",
"TableBuilder",
".",
"default_boolean",
".",
"first",
"elsif",
"value",
".",
"is_a?",
"(",
"FalseClass",
")",
"return",
"TableBuilder",
".",
"default_boolean",
".",
"second",
"end",
"value",
"end"
] | Format the value based on value's type | [
"Format",
"the",
"value",
"based",
"on",
"value",
"s",
"type"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_cell.rb#L171-L182 |
546 | dpla/KriKri | app/controllers/krikri/qa_reports_controller.rb | Krikri.QaReportsController.show | def show
@report = Krikri::QAReport.find(params[:id])
@type = params[:type] == 'count' ? :count : :field
respond_to do |format|
format.html
format.csv { render text: @report.send("#{@type}_csv".to_sym).to_csv }
end
end | ruby | def show
@report = Krikri::QAReport.find(params[:id])
@type = params[:type] == 'count' ? :count : :field
respond_to do |format|
format.html
format.csv { render text: @report.send("#{@type}_csv".to_sym).to_csv }
end
end | [
"def",
"show",
"@report",
"=",
"Krikri",
"::",
"QAReport",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@type",
"=",
"params",
"[",
":type",
"]",
"==",
"'count'",
"?",
":count",
":",
":field",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"format",
".",
"csv",
"{",
"render",
"text",
":",
"@report",
".",
"send",
"(",
"\"#{@type}_csv\"",
".",
"to_sym",
")",
".",
"to_csv",
"}",
"end",
"end"
] | Rendering the report as either a full `field` report or a `count` report.
Responds to format of `text/csv` with a CSV rendering of the requested
report type. | [
"Rendering",
"the",
"report",
"as",
"either",
"a",
"full",
"field",
"report",
"or",
"a",
"count",
"report",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/controllers/krikri/qa_reports_controller.rb#L18-L26 |
547 | outcomesinsights/sequelizer | lib/sequelizer/env_config.rb | Sequelizer.EnvConfig.options | def options
Dotenv.load
seq_config = ENV.keys.select { |key| key =~ /^SEQUELIZER_/ }.inject({}) do |config, key|
new_key = key.gsub(/^SEQUELIZER_/, '').downcase
config[new_key] = ENV[key]
config
end
db_config = ENV.keys.select { |key| key =~ /_DB_OPT_/ }.inject({}) do |config, key|
new_key = key.downcase
config[new_key] = ENV[key]
config
end
db_config.merge(seq_config)
end | ruby | def options
Dotenv.load
seq_config = ENV.keys.select { |key| key =~ /^SEQUELIZER_/ }.inject({}) do |config, key|
new_key = key.gsub(/^SEQUELIZER_/, '').downcase
config[new_key] = ENV[key]
config
end
db_config = ENV.keys.select { |key| key =~ /_DB_OPT_/ }.inject({}) do |config, key|
new_key = key.downcase
config[new_key] = ENV[key]
config
end
db_config.merge(seq_config)
end | [
"def",
"options",
"Dotenv",
".",
"load",
"seq_config",
"=",
"ENV",
".",
"keys",
".",
"select",
"{",
"|",
"key",
"|",
"key",
"=~",
"/",
"/",
"}",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"config",
",",
"key",
"|",
"new_key",
"=",
"key",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
".",
"downcase",
"config",
"[",
"new_key",
"]",
"=",
"ENV",
"[",
"key",
"]",
"config",
"end",
"db_config",
"=",
"ENV",
".",
"keys",
".",
"select",
"{",
"|",
"key",
"|",
"key",
"=~",
"/",
"/",
"}",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"config",
",",
"key",
"|",
"new_key",
"=",
"key",
".",
"downcase",
"config",
"[",
"new_key",
"]",
"=",
"ENV",
"[",
"key",
"]",
"config",
"end",
"db_config",
".",
"merge",
"(",
"seq_config",
")",
"end"
] | Any environment variables in the .env file are loaded and then
any environment variable starting with SEQUELIZER_ will be used
as an option for the database | [
"Any",
"environment",
"variables",
"in",
"the",
".",
"env",
"file",
"are",
"loaded",
"and",
"then",
"any",
"environment",
"variable",
"starting",
"with",
"SEQUELIZER_",
"will",
"be",
"used",
"as",
"an",
"option",
"for",
"the",
"database"
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/env_config.rb#L10-L26 |
548 | Tylerjd/minecraft-query | lib/rcon/rcon.rb | RCON.Query.cvar | def cvar(cvar_name)
response = command(cvar_name)
match = /^.+?\s(?:is|=)\s"([^"]+)".*$/.match response
match = match[1]
if /\D/.match match
return match
else
return match.to_i
end
end | ruby | def cvar(cvar_name)
response = command(cvar_name)
match = /^.+?\s(?:is|=)\s"([^"]+)".*$/.match response
match = match[1]
if /\D/.match match
return match
else
return match.to_i
end
end | [
"def",
"cvar",
"(",
"cvar_name",
")",
"response",
"=",
"command",
"(",
"cvar_name",
")",
"match",
"=",
"/",
"\\s",
"\\s",
"/",
".",
"match",
"response",
"match",
"=",
"match",
"[",
"1",
"]",
"if",
"/",
"\\D",
"/",
".",
"match",
"match",
"return",
"match",
"else",
"return",
"match",
".",
"to_i",
"end",
"end"
] | Convenience method to scrape input from cvar output and return that data.
Returns integers as a numeric type if possible.
ex: rcon.cvar("mp_friendlyfire") => 1
NOTE: This file has not been updated since previous version. Please be aware there may be outstanding Ruby2 bugs | [
"Convenience",
"method",
"to",
"scrape",
"input",
"from",
"cvar",
"output",
"and",
"return",
"that",
"data",
".",
"Returns",
"integers",
"as",
"a",
"numeric",
"type",
"if",
"possible",
"."
] | 41f369826a0364d5916dd5ea45ed28c10035e47d | https://github.com/Tylerjd/minecraft-query/blob/41f369826a0364d5916dd5ea45ed28c10035e47d/lib/rcon/rcon.rb#L13-L22 |
549 | Tylerjd/minecraft-query | lib/rcon/rcon.rb | RCON.Source.command | def command(command)
if ! @authed
raise NetworkException.new("You must authenticate the connection successfully before sending commands.")
end
@packet = Packet::Source.new
@packet.command(command)
@socket.print @packet.to_s
rpacket = build_response_packet
if rpacket.command_type != Packet::Source::RESPONSE_NORM
raise NetworkException.new("error sending command: #{rpacket.command_type}")
end
if @return_packets
return rpacket
else
return rpacket.string1
end
end | ruby | def command(command)
if ! @authed
raise NetworkException.new("You must authenticate the connection successfully before sending commands.")
end
@packet = Packet::Source.new
@packet.command(command)
@socket.print @packet.to_s
rpacket = build_response_packet
if rpacket.command_type != Packet::Source::RESPONSE_NORM
raise NetworkException.new("error sending command: #{rpacket.command_type}")
end
if @return_packets
return rpacket
else
return rpacket.string1
end
end | [
"def",
"command",
"(",
"command",
")",
"if",
"!",
"@authed",
"raise",
"NetworkException",
".",
"new",
"(",
"\"You must authenticate the connection successfully before sending commands.\"",
")",
"end",
"@packet",
"=",
"Packet",
"::",
"Source",
".",
"new",
"@packet",
".",
"command",
"(",
"command",
")",
"@socket",
".",
"print",
"@packet",
".",
"to_s",
"rpacket",
"=",
"build_response_packet",
"if",
"rpacket",
".",
"command_type",
"!=",
"Packet",
"::",
"Source",
"::",
"RESPONSE_NORM",
"raise",
"NetworkException",
".",
"new",
"(",
"\"error sending command: #{rpacket.command_type}\"",
")",
"end",
"if",
"@return_packets",
"return",
"rpacket",
"else",
"return",
"rpacket",
".",
"string1",
"end",
"end"
] | Sends a RCon command to the server. May be used multiple times
after an authentication is successful. | [
"Sends",
"a",
"RCon",
"command",
"to",
"the",
"server",
".",
"May",
"be",
"used",
"multiple",
"times",
"after",
"an",
"authentication",
"is",
"successful",
"."
] | 41f369826a0364d5916dd5ea45ed28c10035e47d | https://github.com/Tylerjd/minecraft-query/blob/41f369826a0364d5916dd5ea45ed28c10035e47d/lib/rcon/rcon.rb#L150-L171 |
550 | Tylerjd/minecraft-query | lib/rcon/rcon.rb | RCON.Source.auth | def auth(password)
establish_connection
@packet = Packet::Source.new
@packet.auth(password)
@socket.print @packet.to_s
# on auth, one junk packet is sent
rpacket = nil
2.times { rpacket = build_response_packet }
if rpacket.command_type != Packet::Source::RESPONSE_AUTH
raise NetworkException.new("error authenticating: #{rpacket.command_type}")
end
@authed = true
if @return_packets
return rpacket
else
return true
end
end | ruby | def auth(password)
establish_connection
@packet = Packet::Source.new
@packet.auth(password)
@socket.print @packet.to_s
# on auth, one junk packet is sent
rpacket = nil
2.times { rpacket = build_response_packet }
if rpacket.command_type != Packet::Source::RESPONSE_AUTH
raise NetworkException.new("error authenticating: #{rpacket.command_type}")
end
@authed = true
if @return_packets
return rpacket
else
return true
end
end | [
"def",
"auth",
"(",
"password",
")",
"establish_connection",
"@packet",
"=",
"Packet",
"::",
"Source",
".",
"new",
"@packet",
".",
"auth",
"(",
"password",
")",
"@socket",
".",
"print",
"@packet",
".",
"to_s",
"# on auth, one junk packet is sent\r",
"rpacket",
"=",
"nil",
"2",
".",
"times",
"{",
"rpacket",
"=",
"build_response_packet",
"}",
"if",
"rpacket",
".",
"command_type",
"!=",
"Packet",
"::",
"Source",
"::",
"RESPONSE_AUTH",
"raise",
"NetworkException",
".",
"new",
"(",
"\"error authenticating: #{rpacket.command_type}\"",
")",
"end",
"@authed",
"=",
"true",
"if",
"@return_packets",
"return",
"rpacket",
"else",
"return",
"true",
"end",
"end"
] | Requests authentication from the RCon server, given a
password. Is only expected to be used once. | [
"Requests",
"authentication",
"from",
"the",
"RCon",
"server",
"given",
"a",
"password",
".",
"Is",
"only",
"expected",
"to",
"be",
"used",
"once",
"."
] | 41f369826a0364d5916dd5ea45ed28c10035e47d | https://github.com/Tylerjd/minecraft-query/blob/41f369826a0364d5916dd5ea45ed28c10035e47d/lib/rcon/rcon.rb#L178-L199 |
551 | arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.add_cell | def add_cell(object, args, type = nil, block = nil)
@cells << FormatCell.new(object, args, type, block)
end | ruby | def add_cell(object, args, type = nil, block = nil)
@cells << FormatCell.new(object, args, type, block)
end | [
"def",
"add_cell",
"(",
"object",
",",
"args",
",",
"type",
"=",
"nil",
",",
"block",
"=",
"nil",
")",
"@cells",
"<<",
"FormatCell",
".",
"new",
"(",
"object",
",",
"args",
",",
"type",
",",
"block",
")",
"end"
] | Create a new cell with the class FormatCell
Add the object in @cells | [
"Create",
"a",
"new",
"cell",
"with",
"the",
"class",
"FormatCell",
"Add",
"the",
"object",
"in"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L15-L17 |
552 | arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.content_columns | def content_columns
model_name(@object).constantize.content_columns.collect { |c| c.name.to_sym }.compact rescue []
end | ruby | def content_columns
model_name(@object).constantize.content_columns.collect { |c| c.name.to_sym }.compact rescue []
end | [
"def",
"content_columns",
"model_name",
"(",
"@object",
")",
".",
"constantize",
".",
"content_columns",
".",
"collect",
"{",
"|",
"c",
"|",
"c",
".",
"name",
".",
"to_sym",
"}",
".",
"compact",
"rescue",
"[",
"]",
"end"
] | Return each column in the model's database table | [
"Return",
"each",
"column",
"in",
"the",
"model",
"s",
"database",
"table"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L38-L40 |
553 | arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.model_have_column? | def model_have_column?(column)
model_name(@object).constantize.content_columns.each do |model_column|
return true if model_column.name == column.to_s
end
false
end | ruby | def model_have_column?(column)
model_name(@object).constantize.content_columns.each do |model_column|
return true if model_column.name == column.to_s
end
false
end | [
"def",
"model_have_column?",
"(",
"column",
")",
"model_name",
"(",
"@object",
")",
".",
"constantize",
".",
"content_columns",
".",
"each",
"do",
"|",
"model_column",
"|",
"return",
"true",
"if",
"model_column",
".",
"name",
"==",
"column",
".",
"to_s",
"end",
"false",
"end"
] | Return true if the column is in the model's database table | [
"Return",
"true",
"if",
"the",
"column",
"is",
"in",
"the",
"model",
"s",
"database",
"table"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L43-L48 |
554 | arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.format_options_to_cell | def format_options_to_cell(ask, options = @column_options)
options.each do |key, value|
if only_cell_option?(key)
if ask.is_a? Hash
ask.merge!(key => value)
else
ask = [ask] unless ask.is_a? Array
(ask.last.is_a? Hash and ask.last.has_key? :html) ? ask.last[:html].merge!(key => value) : ask << { :html => { key => value }}
end
end
end
ask
end | ruby | def format_options_to_cell(ask, options = @column_options)
options.each do |key, value|
if only_cell_option?(key)
if ask.is_a? Hash
ask.merge!(key => value)
else
ask = [ask] unless ask.is_a? Array
(ask.last.is_a? Hash and ask.last.has_key? :html) ? ask.last[:html].merge!(key => value) : ask << { :html => { key => value }}
end
end
end
ask
end | [
"def",
"format_options_to_cell",
"(",
"ask",
",",
"options",
"=",
"@column_options",
")",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"only_cell_option?",
"(",
"key",
")",
"if",
"ask",
".",
"is_a?",
"Hash",
"ask",
".",
"merge!",
"(",
"key",
"=>",
"value",
")",
"else",
"ask",
"=",
"[",
"ask",
"]",
"unless",
"ask",
".",
"is_a?",
"Array",
"(",
"ask",
".",
"last",
".",
"is_a?",
"Hash",
"and",
"ask",
".",
"last",
".",
"has_key?",
":html",
")",
"?",
"ask",
".",
"last",
"[",
":html",
"]",
".",
"merge!",
"(",
"key",
"=>",
"value",
")",
":",
"ask",
"<<",
"{",
":html",
"=>",
"{",
"key",
"=>",
"value",
"}",
"}",
"end",
"end",
"end",
"ask",
"end"
] | Format ask to send options to cell | [
"Format",
"ask",
"to",
"send",
"options",
"to",
"cell"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L56-L68 |
555 | AnkurGel/dictionary-rb | lib/dictionary-rb/word.rb | DictionaryRB.Word.dictionary_meaning | def dictionary_meaning
if @dictionary_meaning.nil?
@dictionary = Dictionary.new(@word)
meanings = @dictionary.meanings
if meanings.is_a? Array and not meanings.empty?
@dictionary_meanings = meanings
@dictionary_meaning = @dictionary.meaning
end
end
@dictionary_meaning
end | ruby | def dictionary_meaning
if @dictionary_meaning.nil?
@dictionary = Dictionary.new(@word)
meanings = @dictionary.meanings
if meanings.is_a? Array and not meanings.empty?
@dictionary_meanings = meanings
@dictionary_meaning = @dictionary.meaning
end
end
@dictionary_meaning
end | [
"def",
"dictionary_meaning",
"if",
"@dictionary_meaning",
".",
"nil?",
"@dictionary",
"=",
"Dictionary",
".",
"new",
"(",
"@word",
")",
"meanings",
"=",
"@dictionary",
".",
"meanings",
"if",
"meanings",
".",
"is_a?",
"Array",
"and",
"not",
"meanings",
".",
"empty?",
"@dictionary_meanings",
"=",
"meanings",
"@dictionary_meaning",
"=",
"@dictionary",
".",
"meaning",
"end",
"end",
"@dictionary_meaning",
"end"
] | Gives dictionary meaning for the word
@example
word.dictionary_meaning
#or
word.meaning
@note This method will hit the {Dictionary::PREFIX ENDPOINT} and will consume some time to generate result
@return [String] containing meaning from Reference {Dictionary} for the word | [
"Gives",
"dictionary",
"meaning",
"for",
"the",
"word"
] | 92566325aee598f46b584817373017e6097300b4 | https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/word.rb#L39-L49 |
556 | AnkurGel/dictionary-rb | lib/dictionary-rb/word.rb | DictionaryRB.Word.urban_meaning | def urban_meaning
if @urban_meaning.nil?
@urban = Urban.new(@word)
meanings = @urban.meanings
if meanings.is_a?(Array) and not meanings.empty?
@urban_meanings = meanings
@urban_meaning = @urban.meaning
end
end
@urban_meaning
end | ruby | def urban_meaning
if @urban_meaning.nil?
@urban = Urban.new(@word)
meanings = @urban.meanings
if meanings.is_a?(Array) and not meanings.empty?
@urban_meanings = meanings
@urban_meaning = @urban.meaning
end
end
@urban_meaning
end | [
"def",
"urban_meaning",
"if",
"@urban_meaning",
".",
"nil?",
"@urban",
"=",
"Urban",
".",
"new",
"(",
"@word",
")",
"meanings",
"=",
"@urban",
".",
"meanings",
"if",
"meanings",
".",
"is_a?",
"(",
"Array",
")",
"and",
"not",
"meanings",
".",
"empty?",
"@urban_meanings",
"=",
"meanings",
"@urban_meaning",
"=",
"@urban",
".",
"meaning",
"end",
"end",
"@urban_meaning",
"end"
] | Fetches the first meaning from Urban Dictionary for the word.
@note This method will hit the {Urban::PREFIX ENDPOINT} and will consume some time to generate result
@example
word.urban_meaning
@see #urban_meanings
@return [String] containing meaning from {Urban} Dictionary for the word | [
"Fetches",
"the",
"first",
"meaning",
"from",
"Urban",
"Dictionary",
"for",
"the",
"word",
"."
] | 92566325aee598f46b584817373017e6097300b4 | https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/word.rb#L81-L91 |
557 | adhearsion/adhearsion-asr | lib/adhearsion-asr/controller_methods.rb | AdhearsionASR.ControllerMethods.ask | def ask(*args)
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
if block_given?
logger.warn "You passed a block to #ask, but this functionality is not available in adhearsion-asr. If you're looking for the block validator functionality, you should avoid using it in favour of grammars, and it is deprecated in Adhearsion Core."
end
options[:grammar] || options[:grammar_url] || options[:limit] || options[:terminator] || raise(ArgumentError, "You must specify at least one of limit, terminator or grammar")
grammars = AskGrammarBuilder.new(options).grammars
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
PromptBuilder.new(output_document, grammars, options).execute self
end | ruby | def ask(*args)
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
if block_given?
logger.warn "You passed a block to #ask, but this functionality is not available in adhearsion-asr. If you're looking for the block validator functionality, you should avoid using it in favour of grammars, and it is deprecated in Adhearsion Core."
end
options[:grammar] || options[:grammar_url] || options[:limit] || options[:terminator] || raise(ArgumentError, "You must specify at least one of limit, terminator or grammar")
grammars = AskGrammarBuilder.new(options).grammars
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
PromptBuilder.new(output_document, grammars, options).execute self
end | [
"def",
"ask",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"kind_of?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"prompts",
"=",
"args",
".",
"flatten",
".",
"compact",
"if",
"block_given?",
"logger",
".",
"warn",
"\"You passed a block to #ask, but this functionality is not available in adhearsion-asr. If you're looking for the block validator functionality, you should avoid using it in favour of grammars, and it is deprecated in Adhearsion Core.\"",
"end",
"options",
"[",
":grammar",
"]",
"||",
"options",
"[",
":grammar_url",
"]",
"||",
"options",
"[",
":limit",
"]",
"||",
"options",
"[",
":terminator",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"You must specify at least one of limit, terminator or grammar\"",
")",
"grammars",
"=",
"AskGrammarBuilder",
".",
"new",
"(",
"options",
")",
".",
"grammars",
"output_document",
"=",
"prompts",
".",
"empty?",
"?",
"nil",
":",
"output_formatter",
".",
"ssml_for_collection",
"(",
"prompts",
")",
"PromptBuilder",
".",
"new",
"(",
"output_document",
",",
"grammars",
",",
"options",
")",
".",
"execute",
"self",
"end"
] | Prompts for input, handling playback of prompts, DTMF grammar construction, and execution
@example A basic DTMF digit collection:
ask "Welcome, ", "/opt/sounds/menu-prompt.mp3",
timeout: 10, terminator: '#', limit: 3
The first arguments will be a list of sounds to play, as accepted by #play, including strings for TTS, Date and Time objects, and file paths.
:timeout, :terminator and :limit options may be specified to automatically construct a grammar, or grammars may be manually specified.
@param [Object, Array<Object>] args A list of outputs to play, as accepted by #play
@param [Hash] options Options to modify the grammar
@option options [Boolean] :interruptible If the prompt should be interruptible or not. Defaults to true
@option options [Integer] :limit Digit limit (causes collection to cease after a specified number of digits have been collected)
@option options [Integer] :timeout Timeout in seconds before the first and between each input digit
@option options [String] :terminator Digit to terminate input
@option options [RubySpeech::GRXML::Grammar, Array<RubySpeech::GRXML::Grammar>] :grammar One of a collection of grammars to execute
@option options [String, Array<String>] :grammar_url One of a collection of URLs for grammars to execute
@option options [Hash] :input_options A hash of options passed directly to the Punchblock Input constructor. See
@option options [Hash] :output_options A hash of options passed directly to the Punchblock Output constructor
@return [Result] a result object from which the details of the utterance may be established
@see Output#play
@see http://rdoc.info/gems/punchblock/Punchblock/Component/Input.new Punchblock::Component::Input.new
@see http://rdoc.info/gems/punchblock/Punchblock/Component/Output.new Punchblock::Component::Output.new | [
"Prompts",
"for",
"input",
"handling",
"playback",
"of",
"prompts",
"DTMF",
"grammar",
"construction",
"and",
"execution"
] | 66f966ee752433e382082570a5886a0fb3f8b169 | https://github.com/adhearsion/adhearsion-asr/blob/66f966ee752433e382082570a5886a0fb3f8b169/lib/adhearsion-asr/controller_methods.rb#L35-L50 |
558 | adhearsion/adhearsion-asr | lib/adhearsion-asr/controller_methods.rb | AdhearsionASR.ControllerMethods.menu | def menu(*args, &block)
raise ArgumentError, "You must specify a block to build the menu" unless block
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
menu_builder = MenuBuilder.new(options, &block)
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
menu_builder.execute output_document, self
end | ruby | def menu(*args, &block)
raise ArgumentError, "You must specify a block to build the menu" unless block
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
menu_builder = MenuBuilder.new(options, &block)
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
menu_builder.execute output_document, self
end | [
"def",
"menu",
"(",
"*",
"args",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"\"You must specify a block to build the menu\"",
"unless",
"block",
"options",
"=",
"args",
".",
"last",
".",
"kind_of?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"prompts",
"=",
"args",
".",
"flatten",
".",
"compact",
"menu_builder",
"=",
"MenuBuilder",
".",
"new",
"(",
"options",
",",
"block",
")",
"output_document",
"=",
"prompts",
".",
"empty?",
"?",
"nil",
":",
"output_formatter",
".",
"ssml_for_collection",
"(",
"prompts",
")",
"menu_builder",
".",
"execute",
"output_document",
",",
"self",
"end"
] | Creates and manages a multiple choice menu driven by DTMF, handling playback of prompts,
invalid input, retries and timeouts, and final failures.
@example A complete example of the method is as follows:
menu "Welcome, ", "/opt/sounds/menu-prompt.mp3", tries: 2, timeout: 10 do
match 1, OperatorController
match 10..19 do
pass DirectController
end
match 5, 6, 9 do |exten|
play "The #{exten} extension is currently not active"
end
match '7', OfficeController
invalid { play "Please choose a valid extension" }
timeout { play "Input timed out, try again." }
failure { pass OperatorController }
end
The first arguments will be a list of sounds to play, as accepted by #play, including strings for TTS, Date and Time objects, and file paths.
:tries and :timeout options respectively specify the number of tries before going into failure, and the timeout in seconds allowed on each digit input.
The most important part is the following block, which specifies how the menu will be constructed and handled.
#match handles connecting an input pattern to a payload.
The pattern can be one or more of: an integer, a Range, a string, an Array of the possible single types.
Input is matched against patterns, and the first exact match has it's payload executed.
Matched input is passed in to the associated block, or to the controller through #options.
Allowed payloads are the name of a controller class, in which case it is executed through its #run method, or a block, which is executed in the context of the current controller.
#invalid has its associated block executed when the input does not possibly match any pattern.
#timeout's block is run when timeout expires before receiving any input
#failure runs its block when the maximum number of tries is reached without an input match.
Execution of the current context resumes after #menu finishes. If you wish to jump to an entirely different controller, use #pass.
Menu will return :failed if failure was reached, or :done if a match was executed.
@param [Object] args A list of outputs to play, as accepted by #play
@param [Hash] options Options to use for the menu
@option options [Integer] :tries Number of tries allowed before failure
@option options [Integer] :timeout Timeout in seconds before the first and between each input digit
@option options [Boolean] :interruptible If the prompt should be interruptible or not. Defaults to true
@option options [String, Symbol] :mode Input mode to accept. May be :voice or :dtmf.
@option options [Hash] :input_options A hash of options passed directly to the Punchblock Input constructor
@option options [Hash] :output_options A hash of options passed directly to the Punchblock Output constructor
@return [Result] a result object from which the details of the utterance may be established
@see Output#play
@see CallController#pass | [
"Creates",
"and",
"manages",
"a",
"multiple",
"choice",
"menu",
"driven",
"by",
"DTMF",
"handling",
"playback",
"of",
"prompts",
"invalid",
"input",
"retries",
"and",
"timeouts",
"and",
"final",
"failures",
"."
] | 66f966ee752433e382082570a5886a0fb3f8b169 | https://github.com/adhearsion/adhearsion-asr/blob/66f966ee752433e382082570a5886a0fb3f8b169/lib/adhearsion-asr/controller_methods.rb#L106-L116 |
559 | culturecode/spatial_features | lib/spatial_features/has_spatial_features.rb | SpatialFeatures.ClassMethods.spatial_join | def spatial_join(other, buffer = 0, table_alias = 'features', other_alias = 'other_features', geom = 'geom_lowres')
scope = features_scope(self).select("#{geom} AS geom").select(:spatial_model_id)
other_scope = features_scope(other)
other_scope = other_scope.select("ST_Union(#{geom}) AS geom").select("ST_Buffer(ST_Union(#{geom}), #{buffer.to_i}) AS buffered_geom")
return joins(%Q(INNER JOIN (#{scope.to_sql}) AS #{table_alias} ON #{table_alias}.spatial_model_id = #{table_name}.id))
.joins(%Q(INNER JOIN (#{other_scope.to_sql}) AS #{other_alias} ON ST_Intersects(#{table_alias}.geom, #{other_alias}.buffered_geom)))
end | ruby | def spatial_join(other, buffer = 0, table_alias = 'features', other_alias = 'other_features', geom = 'geom_lowres')
scope = features_scope(self).select("#{geom} AS geom").select(:spatial_model_id)
other_scope = features_scope(other)
other_scope = other_scope.select("ST_Union(#{geom}) AS geom").select("ST_Buffer(ST_Union(#{geom}), #{buffer.to_i}) AS buffered_geom")
return joins(%Q(INNER JOIN (#{scope.to_sql}) AS #{table_alias} ON #{table_alias}.spatial_model_id = #{table_name}.id))
.joins(%Q(INNER JOIN (#{other_scope.to_sql}) AS #{other_alias} ON ST_Intersects(#{table_alias}.geom, #{other_alias}.buffered_geom)))
end | [
"def",
"spatial_join",
"(",
"other",
",",
"buffer",
"=",
"0",
",",
"table_alias",
"=",
"'features'",
",",
"other_alias",
"=",
"'other_features'",
",",
"geom",
"=",
"'geom_lowres'",
")",
"scope",
"=",
"features_scope",
"(",
"self",
")",
".",
"select",
"(",
"\"#{geom} AS geom\"",
")",
".",
"select",
"(",
":spatial_model_id",
")",
"other_scope",
"=",
"features_scope",
"(",
"other",
")",
"other_scope",
"=",
"other_scope",
".",
"select",
"(",
"\"ST_Union(#{geom}) AS geom\"",
")",
".",
"select",
"(",
"\"ST_Buffer(ST_Union(#{geom}), #{buffer.to_i}) AS buffered_geom\"",
")",
"return",
"joins",
"(",
"%Q(INNER JOIN (#{scope.to_sql}) AS #{table_alias} ON #{table_alias}.spatial_model_id = #{table_name}.id)",
")",
".",
"joins",
"(",
"%Q(INNER JOIN (#{other_scope.to_sql}) AS #{other_alias} ON ST_Intersects(#{table_alias}.geom, #{other_alias}.buffered_geom))",
")",
"end"
] | Returns a scope that includes the features for this record as the table_alias and the features for other as other_alias
Performs a spatial intersection between the two sets of features, within the buffer distance given in meters | [
"Returns",
"a",
"scope",
"that",
"includes",
"the",
"features",
"for",
"this",
"record",
"as",
"the",
"table_alias",
"and",
"the",
"features",
"for",
"other",
"as",
"other_alias",
"Performs",
"a",
"spatial",
"intersection",
"between",
"the",
"two",
"sets",
"of",
"features",
"within",
"the",
"buffer",
"distance",
"given",
"in",
"meters"
] | 557a4b8a855129dd51a3c2cfcdad8312083fb73a | https://github.com/culturecode/spatial_features/blob/557a4b8a855129dd51a3c2cfcdad8312083fb73a/lib/spatial_features/has_spatial_features.rb#L144-L152 |
560 | dpla/KriKri | lib/krikri/enricher.rb | Krikri.Enricher.chain_enrichments! | def chain_enrichments!(agg)
chain.keys.each do |e|
enrichment = enrichment_cache(e)
if enrichment.is_a? Audumbla::FieldEnrichment
agg = do_field_enrichment(agg, enrichment, chain[e])
else
agg = do_basic_enrichment(agg, enrichment, chain[e])
end
end
end | ruby | def chain_enrichments!(agg)
chain.keys.each do |e|
enrichment = enrichment_cache(e)
if enrichment.is_a? Audumbla::FieldEnrichment
agg = do_field_enrichment(agg, enrichment, chain[e])
else
agg = do_basic_enrichment(agg, enrichment, chain[e])
end
end
end | [
"def",
"chain_enrichments!",
"(",
"agg",
")",
"chain",
".",
"keys",
".",
"each",
"do",
"|",
"e",
"|",
"enrichment",
"=",
"enrichment_cache",
"(",
"e",
")",
"if",
"enrichment",
".",
"is_a?",
"Audumbla",
"::",
"FieldEnrichment",
"agg",
"=",
"do_field_enrichment",
"(",
"agg",
",",
"enrichment",
",",
"chain",
"[",
"e",
"]",
")",
"else",
"agg",
"=",
"do_basic_enrichment",
"(",
"agg",
",",
"enrichment",
",",
"chain",
"[",
"e",
"]",
")",
"end",
"end",
"end"
] | Given an aggregation, take each enrichment specified by the `chain'
given in our instantiation, and apply that enrichment, with the given
options, modifying the aggregation in-place. | [
"Given",
"an",
"aggregation",
"take",
"each",
"enrichment",
"specified",
"by",
"the",
"chain",
"given",
"in",
"our",
"instantiation",
"and",
"apply",
"that",
"enrichment",
"with",
"the",
"given",
"options",
"modifying",
"the",
"aggregation",
"in",
"-",
"place",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enricher.rb#L73-L82 |
561 | dpla/KriKri | lib/krikri/enricher.rb | Krikri.Enricher.deep_sym | def deep_sym(obj)
if obj.is_a? Hash
return obj.inject({}) do |memo, (k, v)|
memo[k.to_sym] = deep_sym(v)
memo
end
elsif obj.is_a? Array
return obj.inject([]) do |memo, el|
memo << deep_sym(el)
memo
end
elsif obj.respond_to? :to_sym
return obj.to_sym
else
return nil
end
end | ruby | def deep_sym(obj)
if obj.is_a? Hash
return obj.inject({}) do |memo, (k, v)|
memo[k.to_sym] = deep_sym(v)
memo
end
elsif obj.is_a? Array
return obj.inject([]) do |memo, el|
memo << deep_sym(el)
memo
end
elsif obj.respond_to? :to_sym
return obj.to_sym
else
return nil
end
end | [
"def",
"deep_sym",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"Hash",
"return",
"obj",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"memo",
",",
"(",
"k",
",",
"v",
")",
"|",
"memo",
"[",
"k",
".",
"to_sym",
"]",
"=",
"deep_sym",
"(",
"v",
")",
"memo",
"end",
"elsif",
"obj",
".",
"is_a?",
"Array",
"return",
"obj",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"memo",
",",
"el",
"|",
"memo",
"<<",
"deep_sym",
"(",
"el",
")",
"memo",
"end",
"elsif",
"obj",
".",
"respond_to?",
":to_sym",
"return",
"obj",
".",
"to_sym",
"else",
"return",
"nil",
"end",
"end"
] | Transform the given hash recursively by turning all of its string keys
and values into symbols.
Symbols are expected in the enrichment classes, and we will usually be
dealing with values that have been deserialized from JSON. | [
"Transform",
"the",
"given",
"hash",
"recursively",
"by",
"turning",
"all",
"of",
"its",
"string",
"keys",
"and",
"values",
"into",
"symbols",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enricher.rb#L126-L142 |
562 | schrodingersbox/meter_cat | app/models/meter_cat/meter.rb | MeterCat.Meter.add | def add
meter = nil
Meter.uncached { meter = Meter.find_by_name_and_created_on(name, created_on) }
meter ||= Meter.new(name: name, created_on: created_on)
meter.value += value
return meter.save
end | ruby | def add
meter = nil
Meter.uncached { meter = Meter.find_by_name_and_created_on(name, created_on) }
meter ||= Meter.new(name: name, created_on: created_on)
meter.value += value
return meter.save
end | [
"def",
"add",
"meter",
"=",
"nil",
"Meter",
".",
"uncached",
"{",
"meter",
"=",
"Meter",
".",
"find_by_name_and_created_on",
"(",
"name",
",",
"created_on",
")",
"}",
"meter",
"||=",
"Meter",
".",
"new",
"(",
"name",
":",
"name",
",",
"created_on",
":",
"created_on",
")",
"meter",
".",
"value",
"+=",
"value",
"return",
"meter",
".",
"save",
"end"
] | Instance methods
Create an object for this name+date in the db if one does not already exist.
Add the value from this object to the one in the DB.
Returns the result of the ActiveRecord save operation. | [
"Instance",
"methods",
"Create",
"an",
"object",
"for",
"this",
"name",
"+",
"date",
"in",
"the",
"db",
"if",
"one",
"does",
"not",
"already",
"exist",
".",
"Add",
"the",
"value",
"from",
"this",
"object",
"to",
"the",
"one",
"in",
"the",
"DB",
".",
"Returns",
"the",
"result",
"of",
"the",
"ActiveRecord",
"save",
"operation",
"."
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/models/meter_cat/meter.rb#L34-L40 |
563 | Esri/geotrigger-ruby | lib/geotrigger/tag.rb | Geotrigger.Tag.post_update | def post_update
raise StateError.new 'device access_token prohibited' if @session.device?
post_data = @data.dup
post_data['tags'] = post_data.delete 'name'
grok_self_from post 'tag/permissions/update', post_data
self
end | ruby | def post_update
raise StateError.new 'device access_token prohibited' if @session.device?
post_data = @data.dup
post_data['tags'] = post_data.delete 'name'
grok_self_from post 'tag/permissions/update', post_data
self
end | [
"def",
"post_update",
"raise",
"StateError",
".",
"new",
"'device access_token prohibited'",
"if",
"@session",
".",
"device?",
"post_data",
"=",
"@data",
".",
"dup",
"post_data",
"[",
"'tags'",
"]",
"=",
"post_data",
".",
"delete",
"'name'",
"grok_self_from",
"post",
"'tag/permissions/update'",
",",
"post_data",
"self",
"end"
] | POST the tag's +@data+ to the API via 'tag/permissions/update', and return
the same object with the new +@data+ returned from API call. | [
"POST",
"the",
"tag",
"s",
"+"
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/tag.rb#L64-L70 |
564 | Esri/geotrigger-ruby | lib/geotrigger/device.rb | Geotrigger.Device.post_update | def post_update
post_data = @data.dup
case @session.type
when :application
post_data['deviceIds'] = post_data.delete 'deviceId'
when :device
post_data.delete 'deviceId'
end
post_data.delete 'tags'
post_data.delete 'lastSeen'
grok_self_from post 'device/update', post_data
self
end | ruby | def post_update
post_data = @data.dup
case @session.type
when :application
post_data['deviceIds'] = post_data.delete 'deviceId'
when :device
post_data.delete 'deviceId'
end
post_data.delete 'tags'
post_data.delete 'lastSeen'
grok_self_from post 'device/update', post_data
self
end | [
"def",
"post_update",
"post_data",
"=",
"@data",
".",
"dup",
"case",
"@session",
".",
"type",
"when",
":application",
"post_data",
"[",
"'deviceIds'",
"]",
"=",
"post_data",
".",
"delete",
"'deviceId'",
"when",
":device",
"post_data",
".",
"delete",
"'deviceId'",
"end",
"post_data",
".",
"delete",
"'tags'",
"post_data",
".",
"delete",
"'lastSeen'",
"grok_self_from",
"post",
"'device/update'",
",",
"post_data",
"self",
"end"
] | POST the device's +@data+ to the API via 'device/update', and return
the same object with the new +@data+ returned from API call. | [
"POST",
"the",
"device",
"s",
"+"
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/device.rb#L44-L57 |
565 | AnkurGel/dictionary-rb | lib/dictionary-rb/urban.rb | DictionaryRB.Urban.meanings | def meanings
url = PREFIX + CGI::escape(@word)
@doc ||= Nokogiri::HTML(open(url))
#nodes = @doc.css('div#outer.container div.row.three_columns div.span6 div#content div.box div.inner div.meaning')
nodes = @doc.css('.meaning')
results = nodes.map(&:text).map(&:strip).reject(&:empty?)
@meaning = results.first
results
end | ruby | def meanings
url = PREFIX + CGI::escape(@word)
@doc ||= Nokogiri::HTML(open(url))
#nodes = @doc.css('div#outer.container div.row.three_columns div.span6 div#content div.box div.inner div.meaning')
nodes = @doc.css('.meaning')
results = nodes.map(&:text).map(&:strip).reject(&:empty?)
@meaning = results.first
results
end | [
"def",
"meanings",
"url",
"=",
"PREFIX",
"+",
"CGI",
"::",
"escape",
"(",
"@word",
")",
"@doc",
"||=",
"Nokogiri",
"::",
"HTML",
"(",
"open",
"(",
"url",
")",
")",
"#nodes = @doc.css('div#outer.container div.row.three_columns div.span6 div#content div.box div.inner div.meaning')",
"nodes",
"=",
"@doc",
".",
"css",
"(",
"'.meaning'",
")",
"results",
"=",
"nodes",
".",
"map",
"(",
":text",
")",
".",
"map",
"(",
":strip",
")",
".",
"reject",
"(",
":empty?",
")",
"@meaning",
"=",
"results",
".",
"first",
"results",
"end"
] | Fetches and gives meanings for the word from Urban Dictionary
@example
word.meanings
#=> ["A fuck, nothing more, just a fuck",
"Describes someone as being the sexiest beast alive. Anyone who is blessed with the name Krunal should get a medal.",..]
@see #meaning
@return [Array] containing the meanings for the word. | [
"Fetches",
"and",
"gives",
"meanings",
"for",
"the",
"word",
"from",
"Urban",
"Dictionary"
] | 92566325aee598f46b584817373017e6097300b4 | https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/urban.rb#L39-L48 |
566 | dpla/KriKri | lib/krikri/mapper.rb | Krikri.Mapper.define | def define(name, opts = {}, &block)
klass = opts.fetch(:class, DPLA::MAP::Aggregation)
parser = opts.fetch(:parser, Krikri::XmlParser)
parser_args = opts.fetch(:parser_args, nil)
map = Krikri::Mapping.new(klass, parser, *parser_args)
map.instance_eval(&block) if block_given?
Registry.register!(name, map)
end | ruby | def define(name, opts = {}, &block)
klass = opts.fetch(:class, DPLA::MAP::Aggregation)
parser = opts.fetch(:parser, Krikri::XmlParser)
parser_args = opts.fetch(:parser_args, nil)
map = Krikri::Mapping.new(klass, parser, *parser_args)
map.instance_eval(&block) if block_given?
Registry.register!(name, map)
end | [
"def",
"define",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"klass",
"=",
"opts",
".",
"fetch",
"(",
":class",
",",
"DPLA",
"::",
"MAP",
"::",
"Aggregation",
")",
"parser",
"=",
"opts",
".",
"fetch",
"(",
":parser",
",",
"Krikri",
"::",
"XmlParser",
")",
"parser_args",
"=",
"opts",
".",
"fetch",
"(",
":parser_args",
",",
"nil",
")",
"map",
"=",
"Krikri",
"::",
"Mapping",
".",
"new",
"(",
"klass",
",",
"parser",
",",
"parser_args",
")",
"map",
".",
"instance_eval",
"(",
"block",
")",
"if",
"block_given?",
"Registry",
".",
"register!",
"(",
"name",
",",
"map",
")",
"end"
] | Creates mappings and passes DSL methods through to them, then adds them to
a global registry.
@param name [Symbol] a unique name for the mapper in the registry.
@param opts [Hash] options to pass to the mapping instance, options are:
:class, :parser, and :parser_args
@yield A block passed through to the mapping instance containing the
mapping in the language specified by MappingDSL | [
"Creates",
"mappings",
"and",
"passes",
"DSL",
"methods",
"through",
"to",
"them",
"then",
"adds",
"them",
"to",
"a",
"global",
"registry",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/mapper.rb#L40-L47 |
567 | dpla/KriKri | lib/krikri/harvester.rb | Krikri.Harvester.run | def run(activity_uri = nil)
records.each do |rec|
next if rec.nil?
begin
process_record(rec, activity_uri)
rescue => e
Krikri::Logger.log :error, "Error harvesting record:\n" \
"#{rec.content}\n\twith message:\n"\
"#{e.message}"
next
end
end
true
end | ruby | def run(activity_uri = nil)
records.each do |rec|
next if rec.nil?
begin
process_record(rec, activity_uri)
rescue => e
Krikri::Logger.log :error, "Error harvesting record:\n" \
"#{rec.content}\n\twith message:\n"\
"#{e.message}"
next
end
end
true
end | [
"def",
"run",
"(",
"activity_uri",
"=",
"nil",
")",
"records",
".",
"each",
"do",
"|",
"rec",
"|",
"next",
"if",
"rec",
".",
"nil?",
"begin",
"process_record",
"(",
"rec",
",",
"activity_uri",
")",
"rescue",
"=>",
"e",
"Krikri",
"::",
"Logger",
".",
"log",
":error",
",",
"\"Error harvesting record:\\n\"",
"\"#{rec.content}\\n\\twith message:\\n\"",
"\"#{e.message}\"",
"next",
"end",
"end",
"true",
"end"
] | Run the harvest.
Individual records are processed through `#process_record` which is
delegated to the harvester's `@harvest_behavior` by default.
@return [Boolean]
@see Krirki::Harvesters:HarvestBehavior | [
"Run",
"the",
"harvest",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvester.rb#L131-L144 |
568 | dpla/KriKri | lib/krikri/provenance_query_client.rb | Krikri.ProvenanceQueryClient.find_by_activity | def find_by_activity(activity_uri, include_invalidated = false)
raise ArgumentError, 'activity_uri must be an RDF::URI' unless
activity_uri.respond_to? :to_term
query = SPARQL_CLIENT.select(:record)
.where([:record,
[RDF::PROV.wasGeneratedBy, '|', RDF::DPLA.wasRevisedBy],
activity_uri.to_term])
if include_invalidated
query
else
# We need to say "and if RDF::PROV.invalidatedAtTime is not set."
#
# The SPARQL query should be:
#
# PREFIX prov: <http://www.w3.org/ns/prov#>
# SELECT * WHERE {
# ?subject prov:wasGeneratedBy <http://xampl.org/ldp/activity/n> .
# FILTER NOT EXISTS { ?subject prov:invalidatedAtTime ?x }
# }
#
# ... However there doesn't appear to be a way of constructing
# 'FILTER NOT EXISTS' with SPARQL::Client. Instead, we've managed to
# hack the following solution together.
#
# SPARQL::Client#filter is labeled @private in its YARD comment (and
# has no other documentation) but it's not private, at least for
# now.
query.filter \
'NOT EXISTS ' \
'{ ?record <http://www.w3.org/ns/prov#invalidatedAtTime> ?x }'
end
end | ruby | def find_by_activity(activity_uri, include_invalidated = false)
raise ArgumentError, 'activity_uri must be an RDF::URI' unless
activity_uri.respond_to? :to_term
query = SPARQL_CLIENT.select(:record)
.where([:record,
[RDF::PROV.wasGeneratedBy, '|', RDF::DPLA.wasRevisedBy],
activity_uri.to_term])
if include_invalidated
query
else
# We need to say "and if RDF::PROV.invalidatedAtTime is not set."
#
# The SPARQL query should be:
#
# PREFIX prov: <http://www.w3.org/ns/prov#>
# SELECT * WHERE {
# ?subject prov:wasGeneratedBy <http://xampl.org/ldp/activity/n> .
# FILTER NOT EXISTS { ?subject prov:invalidatedAtTime ?x }
# }
#
# ... However there doesn't appear to be a way of constructing
# 'FILTER NOT EXISTS' with SPARQL::Client. Instead, we've managed to
# hack the following solution together.
#
# SPARQL::Client#filter is labeled @private in its YARD comment (and
# has no other documentation) but it's not private, at least for
# now.
query.filter \
'NOT EXISTS ' \
'{ ?record <http://www.w3.org/ns/prov#invalidatedAtTime> ?x }'
end
end | [
"def",
"find_by_activity",
"(",
"activity_uri",
",",
"include_invalidated",
"=",
"false",
")",
"raise",
"ArgumentError",
",",
"'activity_uri must be an RDF::URI'",
"unless",
"activity_uri",
".",
"respond_to?",
":to_term",
"query",
"=",
"SPARQL_CLIENT",
".",
"select",
"(",
":record",
")",
".",
"where",
"(",
"[",
":record",
",",
"[",
"RDF",
"::",
"PROV",
".",
"wasGeneratedBy",
",",
"'|'",
",",
"RDF",
"::",
"DPLA",
".",
"wasRevisedBy",
"]",
",",
"activity_uri",
".",
"to_term",
"]",
")",
"if",
"include_invalidated",
"query",
"else",
"# We need to say \"and if RDF::PROV.invalidatedAtTime is not set.\"",
"#",
"# The SPARQL query should be:",
"#",
"# PREFIX prov: <http://www.w3.org/ns/prov#>",
"# SELECT * WHERE {",
"# ?subject prov:wasGeneratedBy <http://xampl.org/ldp/activity/n> .",
"# FILTER NOT EXISTS { ?subject prov:invalidatedAtTime ?x }",
"# }",
"#",
"# ... However there doesn't appear to be a way of constructing",
"# 'FILTER NOT EXISTS' with SPARQL::Client. Instead, we've managed to",
"# hack the following solution together.",
"#",
"# SPARQL::Client#filter is labeled @private in its YARD comment (and",
"# has no other documentation) but it's not private, at least for",
"# now.",
"query",
".",
"filter",
"'NOT EXISTS '",
"'{ ?record <http://www.w3.org/ns/prov#invalidatedAtTime> ?x }'",
"end",
"end"
] | Finds all entities generated or revised by the activity whose URI is
given.
@param activity_uri [#to_uri] the URI of the activity to search
@param include_invalidated [Boolean] Whether to include entities that
have been invalidated with <http://www.w3.org/ns/prov#invalidatedAtTime>
@see https://www.w3.org/TR/prov-o/#invalidatedAtTime
@see Krikri::LDP::Invalidatable
@return [RDF::SPARQL::Query] a query object that, when executed, will
give solutions containing the URIs for the resources in `#record`. | [
"Finds",
"all",
"entities",
"generated",
"or",
"revised",
"by",
"the",
"activity",
"whose",
"URI",
"is",
"given",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/provenance_query_client.rb#L23-L55 |
569 | estiens/nanoleaf_ruby | lib/nanoleaf_ruby.rb | NanoleafRuby.Api.ct_increment | def ct_increment(increment = 1)
params = { ct: {} }
params[:ct][:increment] = increment
@requester.put(url: "#{@api_url}/state", params: params)
end | ruby | def ct_increment(increment = 1)
params = { ct: {} }
params[:ct][:increment] = increment
@requester.put(url: "#{@api_url}/state", params: params)
end | [
"def",
"ct_increment",
"(",
"increment",
"=",
"1",
")",
"params",
"=",
"{",
"ct",
":",
"{",
"}",
"}",
"params",
"[",
":ct",
"]",
"[",
":increment",
"]",
"=",
"increment",
"@requester",
".",
"put",
"(",
"url",
":",
"\"#{@api_url}/state\"",
",",
"params",
":",
"params",
")",
"end"
] | color temperature commands | [
"color",
"temperature",
"commands"
] | 3ab1d4646e01026c174084816e9642f16aedcca9 | https://github.com/estiens/nanoleaf_ruby/blob/3ab1d4646e01026c174084816e9642f16aedcca9/lib/nanoleaf_ruby.rb#L101-L105 |
570 | opentox/qsar-report | lib/qmrf-report.rb | OpenTox.QMRFReport.change_catalog | def change_catalog catalog, id, valuehash
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
valuehash.each do |key, value|
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]= value
end
else
cat = @report.at_css("#{catalog}")
newentry = Nokogiri::XML::Node.new("#{catalog.to_s.gsub(/s?_catalog/,'')}", self.report)
newentry["id"] = id
valuehash.each do |key, value|
newentry["#{key}"] = value
end
cat << newentry
end
end | ruby | def change_catalog catalog, id, valuehash
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
valuehash.each do |key, value|
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]= value
end
else
cat = @report.at_css("#{catalog}")
newentry = Nokogiri::XML::Node.new("#{catalog.to_s.gsub(/s?_catalog/,'')}", self.report)
newentry["id"] = id
valuehash.each do |key, value|
newentry["#{key}"] = value
end
cat << newentry
end
end | [
"def",
"change_catalog",
"catalog",
",",
"id",
",",
"valuehash",
"catalog_exists?",
"catalog",
"if",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"valuehash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"[",
"\"#{key}\"",
"]",
"=",
"value",
"end",
"else",
"cat",
"=",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
"newentry",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"(",
"\"#{catalog.to_s.gsub(/s?_catalog/,'')}\"",
",",
"self",
".",
"report",
")",
"newentry",
"[",
"\"id\"",
"]",
"=",
"id",
"valuehash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"newentry",
"[",
"\"#{key}\"",
"]",
"=",
"value",
"end",
"cat",
"<<",
"newentry",
"end",
"end"
] | Change a catalog
@param [String] catalog Name of the catalog - One of {OpenTox::QMRFReport::CATALOGS CATALOGS}.
@param [String] id Single entry node in the catalog e.G.: "<software contact='mycontact@mydomain.dom' description="My QSAR Software " id="software_catalog_2" name="MySoftware" number="" url="https://mydomain.dom"/>
@param [Hash] valuehash Key-Value Hash with attributes for a single catalog node
@return [Error] returns Error message if fails | [
"Change",
"a",
"catalog"
] | 2b1074342284fbaa5403dd95f970e089f1ace5a6 | https://github.com/opentox/qsar-report/blob/2b1074342284fbaa5403dd95f970e089f1ace5a6/lib/qmrf-report.rb#L89-L104 |
571 | opentox/qsar-report | lib/qmrf-report.rb | OpenTox.QMRFReport.get_catalog_value | def get_catalog_value catalog, id, key
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]
else
return false
end
end | ruby | def get_catalog_value catalog, id, key
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]
else
return false
end
end | [
"def",
"get_catalog_value",
"catalog",
",",
"id",
",",
"key",
"catalog_exists?",
"catalog",
"if",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"[",
"\"#{key}\"",
"]",
"else",
"return",
"false",
"end",
"end"
] | get an attribute from a catalog entry
@param [String] catalog Name of the catalog. One of {OpenTox::QMRFReport::CATALOGS CATALOGS}.
@param [String] id entry id in the catalog
@param [String] key returns value of a key in a catalog node
@return [String, false] returns value of a key in a catalog node or false if catalog entry do not exists. | [
"get",
"an",
"attribute",
"from",
"a",
"catalog",
"entry"
] | 2b1074342284fbaa5403dd95f970e089f1ace5a6 | https://github.com/opentox/qsar-report/blob/2b1074342284fbaa5403dd95f970e089f1ace5a6/lib/qmrf-report.rb#L132-L139 |
572 | dpla/KriKri | app/helpers/krikri/application_helper.rb | Krikri.ApplicationHelper.link_to_current_page_by_provider | def link_to_current_page_by_provider(provider)
provider = Krikri::Provider.find(provider) if provider.is_a? String
return link_to_provider_page(provider) if params[:controller] ==
'krikri/providers'
params[:provider] = provider.id
params[:session_provider] = provider.id
link_to provider_name(provider), params
end | ruby | def link_to_current_page_by_provider(provider)
provider = Krikri::Provider.find(provider) if provider.is_a? String
return link_to_provider_page(provider) if params[:controller] ==
'krikri/providers'
params[:provider] = provider.id
params[:session_provider] = provider.id
link_to provider_name(provider), params
end | [
"def",
"link_to_current_page_by_provider",
"(",
"provider",
")",
"provider",
"=",
"Krikri",
"::",
"Provider",
".",
"find",
"(",
"provider",
")",
"if",
"provider",
".",
"is_a?",
"String",
"return",
"link_to_provider_page",
"(",
"provider",
")",
"if",
"params",
"[",
":controller",
"]",
"==",
"'krikri/providers'",
"params",
"[",
":provider",
"]",
"=",
"provider",
".",
"id",
"params",
"[",
":session_provider",
"]",
"=",
"provider",
".",
"id",
"link_to",
"provider_name",
"(",
"provider",
")",
",",
"params",
"end"
] | Link to the current page, changing the session provider the given
value.
@param provider [String, nil] | [
"Link",
"to",
"the",
"current",
"page",
"changing",
"the",
"session",
"provider",
"the",
"given",
"value",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/helpers/krikri/application_helper.rb#L37-L45 |
573 | schrodingersbox/meter_cat | app/helpers/meter_cat/meters_helper.rb | MeterCat.MetersHelper.meter_description | def meter_description(name)
content_tag(:p) do
concat content_tag(:b, name)
concat ' - '
concat t(name, scope: :meter_cat)
end
end | ruby | def meter_description(name)
content_tag(:p) do
concat content_tag(:b, name)
concat ' - '
concat t(name, scope: :meter_cat)
end
end | [
"def",
"meter_description",
"(",
"name",
")",
"content_tag",
"(",
":p",
")",
"do",
"concat",
"content_tag",
"(",
":b",
",",
"name",
")",
"concat",
"' - '",
"concat",
"t",
"(",
"name",
",",
"scope",
":",
":meter_cat",
")",
"end",
"end"
] | Constructs a single meter description | [
"Constructs",
"a",
"single",
"meter",
"description"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/helpers/meter_cat/meters_helper.rb#L6-L12 |
574 | schrodingersbox/meter_cat | app/helpers/meter_cat/meters_helper.rb | MeterCat.MetersHelper.meter_descriptions | def meter_descriptions(meters)
content_tag(:ul) do
meters.keys.sort.each do |name|
concat content_tag(:li, meter_description(name))
end
end
end | ruby | def meter_descriptions(meters)
content_tag(:ul) do
meters.keys.sort.each do |name|
concat content_tag(:li, meter_description(name))
end
end
end | [
"def",
"meter_descriptions",
"(",
"meters",
")",
"content_tag",
"(",
":ul",
")",
"do",
"meters",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"name",
"|",
"concat",
"content_tag",
"(",
":li",
",",
"meter_description",
"(",
"name",
")",
")",
"end",
"end",
"end"
] | Constructs a list of meter descriptions | [
"Constructs",
"a",
"list",
"of",
"meter",
"descriptions"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/helpers/meter_cat/meters_helper.rb#L16-L22 |
575 | schrodingersbox/meter_cat | app/helpers/meter_cat/meters_helper.rb | MeterCat.MetersHelper.meter_form | def meter_form(date, days, names, all_names)
render partial: 'form', locals: { date: date, days: days, names: names, all_names: all_names }
end | ruby | def meter_form(date, days, names, all_names)
render partial: 'form', locals: { date: date, days: days, names: names, all_names: all_names }
end | [
"def",
"meter_form",
"(",
"date",
",",
"days",
",",
"names",
",",
"all_names",
")",
"render",
"partial",
":",
"'form'",
",",
"locals",
":",
"{",
"date",
":",
"date",
",",
"days",
":",
"days",
",",
"names",
":",
"names",
",",
"all_names",
":",
"all_names",
"}",
"end"
] | Renders the _form partial with locals | [
"Renders",
"the",
"_form",
"partial",
"with",
"locals"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/helpers/meter_cat/meters_helper.rb#L26-L28 |
576 | gurix/helena_administration | app/helpers/helena_administration/application_helper.rb | HelenaAdministration.ApplicationHelper.truncate_between | def truncate_between(str, after = 30)
str = '' if str.nil?
str.length > after ? "#{str[0..(after / 2) - 2]}...#{str[(str.length - ((after / 2) - 2))..str.length]}" : str
end | ruby | def truncate_between(str, after = 30)
str = '' if str.nil?
str.length > after ? "#{str[0..(after / 2) - 2]}...#{str[(str.length - ((after / 2) - 2))..str.length]}" : str
end | [
"def",
"truncate_between",
"(",
"str",
",",
"after",
"=",
"30",
")",
"str",
"=",
"''",
"if",
"str",
".",
"nil?",
"str",
".",
"length",
">",
"after",
"?",
"\"#{str[0..(after / 2) - 2]}...#{str[(str.length - ((after / 2) - 2))..str.length]}\"",
":",
"str",
"end"
] | adds ... in between like if you have to long names in apple finder so you can i.e see the beginning and the suffix | [
"adds",
"...",
"in",
"between",
"like",
"if",
"you",
"have",
"to",
"long",
"names",
"in",
"apple",
"finder",
"so",
"you",
"can",
"i",
".",
"e",
"see",
"the",
"beginning",
"and",
"the",
"suffix"
] | d7c5019b3c741a882a3d2192950cdfd92ab72faa | https://github.com/gurix/helena_administration/blob/d7c5019b3c741a882a3d2192950cdfd92ab72faa/app/helpers/helena_administration/application_helper.rb#L9-L12 |
577 | Esri/geotrigger-ruby | lib/geotrigger/session.rb | Geotrigger.Session.post | def post path, params = {}, other_headers = {}
r = @hc.post BASE_URL % path, params.to_json, headers(other_headers)
raise GeotriggerError.new r.body unless r.status == 200
h = JSON.parse r.body
raise_error h['error'] if h['error']
h
end | ruby | def post path, params = {}, other_headers = {}
r = @hc.post BASE_URL % path, params.to_json, headers(other_headers)
raise GeotriggerError.new r.body unless r.status == 200
h = JSON.parse r.body
raise_error h['error'] if h['error']
h
end | [
"def",
"post",
"path",
",",
"params",
"=",
"{",
"}",
",",
"other_headers",
"=",
"{",
"}",
"r",
"=",
"@hc",
".",
"post",
"BASE_URL",
"%",
"path",
",",
"params",
".",
"to_json",
",",
"headers",
"(",
"other_headers",
")",
"raise",
"GeotriggerError",
".",
"new",
"r",
".",
"body",
"unless",
"r",
".",
"status",
"==",
"200",
"h",
"=",
"JSON",
".",
"parse",
"r",
".",
"body",
"raise_error",
"h",
"[",
"'error'",
"]",
"if",
"h",
"[",
"'error'",
"]",
"h",
"end"
] | POST an API request to the given path, with optional params and
headers. Returns a normal Ruby +Hash+ of the response data.
[params] +Hash+ parameters to include in the request (will be converted to JSON)
[other_headers] +Hash+ headers to include in the request in addition to the defaults. | [
"POST",
"an",
"API",
"request",
"to",
"the",
"given",
"path",
"with",
"optional",
"params",
"and",
"headers",
".",
"Returns",
"a",
"normal",
"Ruby",
"+",
"Hash",
"+",
"of",
"the",
"response",
"data",
"."
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/session.rb#L125-L131 |
578 | Esri/geotrigger-ruby | lib/geotrigger/session.rb | Geotrigger.Session.raise_error | def raise_error error
ge = GeotriggerError.new error['message']
ge.code = error['code']
ge.headers = error['headers']
ge.message = error['message']
ge.parameters = error['parameters']
jj error
raise ge
end | ruby | def raise_error error
ge = GeotriggerError.new error['message']
ge.code = error['code']
ge.headers = error['headers']
ge.message = error['message']
ge.parameters = error['parameters']
jj error
raise ge
end | [
"def",
"raise_error",
"error",
"ge",
"=",
"GeotriggerError",
".",
"new",
"error",
"[",
"'message'",
"]",
"ge",
".",
"code",
"=",
"error",
"[",
"'code'",
"]",
"ge",
".",
"headers",
"=",
"error",
"[",
"'headers'",
"]",
"ge",
".",
"message",
"=",
"error",
"[",
"'message'",
"]",
"ge",
".",
"parameters",
"=",
"error",
"[",
"'parameters'",
"]",
"jj",
"error",
"raise",
"ge",
"end"
] | Creates and raises a +GeotriggerError+ from an API error response. | [
"Creates",
"and",
"raises",
"a",
"+",
"GeotriggerError",
"+",
"from",
"an",
"API",
"error",
"response",
"."
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/session.rb#L135-L143 |
579 | dpla/KriKri | lib/krikri/enrichments/split_coordinates.rb | Krikri::Enrichments.SplitCoordinates.coord_values | def coord_values(s)
coords = s.split(/ *, */)
return [nil, nil] if coords.size != 2
coords.map! { |c| c.to_f.to_s == c ? c : nil } # must be decimal ...
return [nil, nil] unless coords[0] && coords[1] # ... i.e. not nil
[coords[0], coords[1]]
end | ruby | def coord_values(s)
coords = s.split(/ *, */)
return [nil, nil] if coords.size != 2
coords.map! { |c| c.to_f.to_s == c ? c : nil } # must be decimal ...
return [nil, nil] unless coords[0] && coords[1] # ... i.e. not nil
[coords[0], coords[1]]
end | [
"def",
"coord_values",
"(",
"s",
")",
"coords",
"=",
"s",
".",
"split",
"(",
"/",
"/",
")",
"return",
"[",
"nil",
",",
"nil",
"]",
"if",
"coords",
".",
"size",
"!=",
"2",
"coords",
".",
"map!",
"{",
"|",
"c",
"|",
"c",
".",
"to_f",
".",
"to_s",
"==",
"c",
"?",
"c",
":",
"nil",
"}",
"# must be decimal ...",
"return",
"[",
"nil",
",",
"nil",
"]",
"unless",
"coords",
"[",
"0",
"]",
"&&",
"coords",
"[",
"1",
"]",
"# ... i.e. not nil",
"[",
"coords",
"[",
"0",
"]",
",",
"coords",
"[",
"1",
"]",
"]",
"end"
] | Given a String `s', return an array of two elements split on a comma
and any whitespace around the comma.
If the string does not split into two strings representing decimal
values, then return [nil, nil] because the string does not make sense as
coordinates.
@param s [String] String of, hopefully, comma-separated decimals
@return [Array] | [
"Given",
"a",
"String",
"s",
"return",
"an",
"array",
"of",
"two",
"elements",
"split",
"on",
"a",
"comma",
"and",
"any",
"whitespace",
"around",
"the",
"comma",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/split_coordinates.rb#L60-L66 |
580 | nofxx/rspec_spinner | lib/rspec_spinner/base.rb | RspecSpinner.RspecSpinnerBase.example_pending | def example_pending(example, message, deprecated_pending_location=nil)
immediately_dump_pending(example.description, message, example.location)
mark_error_state_pending
increment
end | ruby | def example_pending(example, message, deprecated_pending_location=nil)
immediately_dump_pending(example.description, message, example.location)
mark_error_state_pending
increment
end | [
"def",
"example_pending",
"(",
"example",
",",
"message",
",",
"deprecated_pending_location",
"=",
"nil",
")",
"immediately_dump_pending",
"(",
"example",
".",
"description",
",",
"message",
",",
"example",
".",
"location",
")",
"mark_error_state_pending",
"increment",
"end"
] | third param is optional, because earlier versions of rspec sent only two args | [
"third",
"param",
"is",
"optional",
"because",
"earlier",
"versions",
"of",
"rspec",
"sent",
"only",
"two",
"args"
] | eeea8961197e07ad46f71442fc0dd79c1ea26ed3 | https://github.com/nofxx/rspec_spinner/blob/eeea8961197e07ad46f71442fc0dd79c1ea26ed3/lib/rspec_spinner/base.rb#L46-L50 |
581 | dpla/KriKri | lib/krikri/ldp/resource.rb | Krikri::LDP.Resource.make_request | def make_request(method, body = nil, headers = {})
validate_subject
ldp_connection.send(method) do |request|
request.url rdf_subject
request.headers = headers if headers
request.body = body
end
end | ruby | def make_request(method, body = nil, headers = {})
validate_subject
ldp_connection.send(method) do |request|
request.url rdf_subject
request.headers = headers if headers
request.body = body
end
end | [
"def",
"make_request",
"(",
"method",
",",
"body",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
")",
"validate_subject",
"ldp_connection",
".",
"send",
"(",
"method",
")",
"do",
"|",
"request",
"|",
"request",
".",
"url",
"rdf_subject",
"request",
".",
"headers",
"=",
"headers",
"if",
"headers",
"request",
".",
"body",
"=",
"body",
"end",
"end"
] | Lightly wraps Faraday to manage requests of various types, their bodies
and headers.
@param method [Symbol] HTTP method/verb.
@param body [#to_s] the request body.
@param headers [Hash<String, String>] a hash of HTTP headers;
e.g. {'Content-Type' => 'text/plain'}.
@raise [Faraday::ClientError] if the server responds with an error status.
Faraday::ClientError#response contains the full response.
@return [Faraday::Response] the server's response | [
"Lightly",
"wraps",
"Faraday",
"to",
"manage",
"requests",
"of",
"various",
"types",
"their",
"bodies",
"and",
"headers",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/ldp/resource.rb#L154-L161 |
582 | dpla/KriKri | app/controllers/krikri/providers_controller.rb | Krikri.ProvidersController.show | def show
if params[:set_session]
session[:current_provider] = params[:id]
redirect_to :back, provider: params[:id]
elsif params[:clear_session]
session.delete :current_provider
redirect_to providers_path
end
@current_provider = Krikri::Provider.find(params[:id])
end | ruby | def show
if params[:set_session]
session[:current_provider] = params[:id]
redirect_to :back, provider: params[:id]
elsif params[:clear_session]
session.delete :current_provider
redirect_to providers_path
end
@current_provider = Krikri::Provider.find(params[:id])
end | [
"def",
"show",
"if",
"params",
"[",
":set_session",
"]",
"session",
"[",
":current_provider",
"]",
"=",
"params",
"[",
":id",
"]",
"redirect_to",
":back",
",",
"provider",
":",
"params",
"[",
":id",
"]",
"elsif",
"params",
"[",
":clear_session",
"]",
"session",
".",
"delete",
":current_provider",
"redirect_to",
"providers_path",
"end",
"@current_provider",
"=",
"Krikri",
"::",
"Provider",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end"
] | Renders the show view for the provider given by `id`. | [
"Renders",
"the",
"show",
"view",
"for",
"the",
"provider",
"given",
"by",
"id",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/controllers/krikri/providers_controller.rb#L16-L25 |
583 | Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.remove_unlikely_elements! | def remove_unlikely_elements!
search('*').each do |element|
idclass = "#{element['class']}#{element['id']}"
if idclass =~ UNLIKELY_IDENTIFIERS && !REMOVAL_WHITELIST.include?(element.name)
element.remove
end
end
end | ruby | def remove_unlikely_elements!
search('*').each do |element|
idclass = "#{element['class']}#{element['id']}"
if idclass =~ UNLIKELY_IDENTIFIERS && !REMOVAL_WHITELIST.include?(element.name)
element.remove
end
end
end | [
"def",
"remove_unlikely_elements!",
"search",
"(",
"'*'",
")",
".",
"each",
"do",
"|",
"element",
"|",
"idclass",
"=",
"\"#{element['class']}#{element['id']}\"",
"if",
"idclass",
"=~",
"UNLIKELY_IDENTIFIERS",
"&&",
"!",
"REMOVAL_WHITELIST",
".",
"include?",
"(",
"element",
".",
"name",
")",
"element",
".",
"remove",
"end",
"end",
"end"
] | Removes unlikely elements from the document. These are elements who have classes
that seem to indicate they are comments, headers, footers, nav, etc | [
"Removes",
"unlikely",
"elements",
"from",
"the",
"document",
".",
"These",
"are",
"elements",
"who",
"have",
"classes",
"that",
"seem",
"to",
"indicate",
"they",
"are",
"comments",
"headers",
"footers",
"nav",
"etc"
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L61-L69 |
584 | Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.score! | def score!
mark_scorable_elements!
scorable_elements.each do |element|
points = 1
points += element.text.split(',').length
points += [element.text.length / 100, 3].min
scores[element.path] = points
scores[element.parent.path] += points
scores[element.parent.parent.path] += points.to_f/2
end
augment_scores_by_link_weight!
end | ruby | def score!
mark_scorable_elements!
scorable_elements.each do |element|
points = 1
points += element.text.split(',').length
points += [element.text.length / 100, 3].min
scores[element.path] = points
scores[element.parent.path] += points
scores[element.parent.parent.path] += points.to_f/2
end
augment_scores_by_link_weight!
end | [
"def",
"score!",
"mark_scorable_elements!",
"scorable_elements",
".",
"each",
"do",
"|",
"element",
"|",
"points",
"=",
"1",
"points",
"+=",
"element",
".",
"text",
".",
"split",
"(",
"','",
")",
".",
"length",
"points",
"+=",
"[",
"element",
".",
"text",
".",
"length",
"/",
"100",
",",
"3",
"]",
".",
"min",
"scores",
"[",
"element",
".",
"path",
"]",
"=",
"points",
"scores",
"[",
"element",
".",
"parent",
".",
"path",
"]",
"+=",
"points",
"scores",
"[",
"element",
".",
"parent",
".",
"parent",
".",
"path",
"]",
"+=",
"points",
".",
"to_f",
"/",
"2",
"end",
"augment_scores_by_link_weight!",
"end"
] | Scores the document elements based on an algorithm to find elements which hold page
content. | [
"Scores",
"the",
"document",
"elements",
"based",
"on",
"an",
"algorithm",
"to",
"find",
"elements",
"which",
"hold",
"page",
"content",
"."
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L82-L96 |
585 | Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.distill! | def distill!(options = {})
remove_irrelevant_elements!
remove_unlikely_elements!
score!
clean_top_scoring_elements!(options) unless options.delete(:clean) == false
top_scoring_elements.map(&:inner_html).join("\n")
end | ruby | def distill!(options = {})
remove_irrelevant_elements!
remove_unlikely_elements!
score!
clean_top_scoring_elements!(options) unless options.delete(:clean) == false
top_scoring_elements.map(&:inner_html).join("\n")
end | [
"def",
"distill!",
"(",
"options",
"=",
"{",
"}",
")",
"remove_irrelevant_elements!",
"remove_unlikely_elements!",
"score!",
"clean_top_scoring_elements!",
"(",
"options",
")",
"unless",
"options",
".",
"delete",
"(",
":clean",
")",
"==",
"false",
"top_scoring_elements",
".",
"map",
"(",
":inner_html",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Distills the document down to just its content.
@param [Hash] options Distillation options
@option options [Symbol] :dirty Do not clean the content element HTML | [
"Distills",
"the",
"document",
"down",
"to",
"just",
"its",
"content",
"."
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L102-L110 |
586 | Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.clean_top_scoring_elements! | def clean_top_scoring_elements!(options = {})
keep_images = !!options[:images]
top_scoring_elements.each do |element|
element.search("*").each do |node|
if cleanable?(node, keep_images)
debugger if node.to_s =~ /maximum flavor/
node.remove
end
end
end
end | ruby | def clean_top_scoring_elements!(options = {})
keep_images = !!options[:images]
top_scoring_elements.each do |element|
element.search("*").each do |node|
if cleanable?(node, keep_images)
debugger if node.to_s =~ /maximum flavor/
node.remove
end
end
end
end | [
"def",
"clean_top_scoring_elements!",
"(",
"options",
"=",
"{",
"}",
")",
"keep_images",
"=",
"!",
"!",
"options",
"[",
":images",
"]",
"top_scoring_elements",
".",
"each",
"do",
"|",
"element",
"|",
"element",
".",
"search",
"(",
"\"*\"",
")",
".",
"each",
"do",
"|",
"node",
"|",
"if",
"cleanable?",
"(",
"node",
",",
"keep_images",
")",
"debugger",
"if",
"node",
".",
"to_s",
"=~",
"/",
"/",
"node",
".",
"remove",
"end",
"end",
"end",
"end"
] | Attempts to clean the top scoring node from non-page content items, such as
advertisements, widgets, etc | [
"Attempts",
"to",
"clean",
"the",
"top",
"scoring",
"node",
"from",
"non",
"-",
"page",
"content",
"items",
"such",
"as",
"advertisements",
"widgets",
"etc"
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L114-L125 |
587 | gurix/helena_administration | app/controllers/helena_administration/sessions_controller.rb | HelenaAdministration.SessionsController.unique_question_codes | def unique_question_codes
codes = @survey.versions.map(&:question_codes).flatten.uniq
codes.map do |code|
session_fields.include?(code) ? "answer_#{code}" : code
end
end | ruby | def unique_question_codes
codes = @survey.versions.map(&:question_codes).flatten.uniq
codes.map do |code|
session_fields.include?(code) ? "answer_#{code}" : code
end
end | [
"def",
"unique_question_codes",
"codes",
"=",
"@survey",
".",
"versions",
".",
"map",
"(",
":question_codes",
")",
".",
"flatten",
".",
"uniq",
"codes",
".",
"map",
"do",
"|",
"code",
"|",
"session_fields",
".",
"include?",
"(",
"code",
")",
"?",
"\"answer_#{code}\"",
":",
"code",
"end",
"end"
] | It could be possible that an answer code equals a session field. We add "answer_" in that case so that we get uniqe question codes for sure | [
"It",
"could",
"be",
"possible",
"that",
"an",
"answer",
"code",
"equals",
"a",
"session",
"field",
".",
"We",
"add",
"answer_",
"in",
"that",
"case",
"so",
"that",
"we",
"get",
"uniqe",
"question",
"codes",
"for",
"sure"
] | d7c5019b3c741a882a3d2192950cdfd92ab72faa | https://github.com/gurix/helena_administration/blob/d7c5019b3c741a882a3d2192950cdfd92ab72faa/app/controllers/helena_administration/sessions_controller.rb#L94-L99 |
588 | dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.records | def records(opts = {})
opts = @opts.merge(opts)
request_with_sets(opts) do |set_opts|
client.list_records(set_opts).full.lazy.flat_map do |rec|
begin
@record_class.build(mint_id(get_identifier(rec)),
record_xml(rec))
rescue => e
Krikri::Logger.log(:error, e.message)
next
end
end
end
end | ruby | def records(opts = {})
opts = @opts.merge(opts)
request_with_sets(opts) do |set_opts|
client.list_records(set_opts).full.lazy.flat_map do |rec|
begin
@record_class.build(mint_id(get_identifier(rec)),
record_xml(rec))
rescue => e
Krikri::Logger.log(:error, e.message)
next
end
end
end
end | [
"def",
"records",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"@opts",
".",
"merge",
"(",
"opts",
")",
"request_with_sets",
"(",
"opts",
")",
"do",
"|",
"set_opts",
"|",
"client",
".",
"list_records",
"(",
"set_opts",
")",
".",
"full",
".",
"lazy",
".",
"flat_map",
"do",
"|",
"rec",
"|",
"begin",
"@record_class",
".",
"build",
"(",
"mint_id",
"(",
"get_identifier",
"(",
"rec",
")",
")",
",",
"record_xml",
"(",
"rec",
")",
")",
"rescue",
"=>",
"e",
"Krikri",
"::",
"Logger",
".",
"log",
"(",
":error",
",",
"e",
".",
"message",
")",
"next",
"end",
"end",
"end",
"end"
] | Sends ListRecords requests lazily.
The following will only send requests to the endpoint until it
has 1000 records:
records.take(1000)
@param opts [Hash] opts to pass to OAI::Client
@see #expected_opts | [
"Sends",
"ListRecords",
"requests",
"lazily",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L91-L104 |
589 | dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.get_record | def get_record(identifier, opts = {})
opts[:identifier] = identifier
opts = @opts.merge(opts)
@record_class.build(mint_id(identifier),
record_xml(client.get_record(opts).record))
end | ruby | def get_record(identifier, opts = {})
opts[:identifier] = identifier
opts = @opts.merge(opts)
@record_class.build(mint_id(identifier),
record_xml(client.get_record(opts).record))
end | [
"def",
"get_record",
"(",
"identifier",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
":identifier",
"]",
"=",
"identifier",
"opts",
"=",
"@opts",
".",
"merge",
"(",
"opts",
")",
"@record_class",
".",
"build",
"(",
"mint_id",
"(",
"identifier",
")",
",",
"record_xml",
"(",
"client",
".",
"get_record",
"(",
"opts",
")",
".",
"record",
")",
")",
"end"
] | Gets a single record with the given identifier from the OAI endpoint
@param identifier [#to_s] the identifier of the record to get
@param opts [Hash] options to pass to the OAI client | [
"Gets",
"a",
"single",
"record",
"with",
"the",
"given",
"identifier",
"from",
"the",
"OAI",
"endpoint"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L111-L116 |
590 | dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.concat_enum | def concat_enum(enum_enum)
Enumerator.new do |yielder|
enum_enum.each do |enum|
enum.each { |i| yielder << i }
end
end
end | ruby | def concat_enum(enum_enum)
Enumerator.new do |yielder|
enum_enum.each do |enum|
enum.each { |i| yielder << i }
end
end
end | [
"def",
"concat_enum",
"(",
"enum_enum",
")",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"enum_enum",
".",
"each",
"do",
"|",
"enum",
"|",
"enum",
".",
"each",
"{",
"|",
"i",
"|",
"yielder",
"<<",
"i",
"}",
"end",
"end",
"end"
] | Concatinates two enumerators
@todo find a better home for this. Reopen Enumerable? or use the
`Enumerating` gem: https://github.com/mdub/enumerating | [
"Concatinates",
"two",
"enumerators"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L159-L165 |
591 | dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.request_with_sets | def request_with_sets(opts, &block)
sets = Array(opts.delete(:set))
if opts[:skip_set]
sets = self.sets(&:spec) if sets.empty?
skips = Array(opts.delete(:skip_set))
sets.reject! { |s| skips.include? s }
end
sets = [nil] if sets.empty?
set_enums = sets.lazy.map do |set|
set_opts = opts.dup
set_opts[:set] = set unless set.nil?
begin
yield(set_opts) if block_given?
rescue OAI::Exception => e
Krikri::Logger.log :warn, "Skipping set #{set} with error: #{e}"
[]
end
end
concat_enum(set_enums).lazy
end | ruby | def request_with_sets(opts, &block)
sets = Array(opts.delete(:set))
if opts[:skip_set]
sets = self.sets(&:spec) if sets.empty?
skips = Array(opts.delete(:skip_set))
sets.reject! { |s| skips.include? s }
end
sets = [nil] if sets.empty?
set_enums = sets.lazy.map do |set|
set_opts = opts.dup
set_opts[:set] = set unless set.nil?
begin
yield(set_opts) if block_given?
rescue OAI::Exception => e
Krikri::Logger.log :warn, "Skipping set #{set} with error: #{e}"
[]
end
end
concat_enum(set_enums).lazy
end | [
"def",
"request_with_sets",
"(",
"opts",
",",
"&",
"block",
")",
"sets",
"=",
"Array",
"(",
"opts",
".",
"delete",
"(",
":set",
")",
")",
"if",
"opts",
"[",
":skip_set",
"]",
"sets",
"=",
"self",
".",
"sets",
"(",
":spec",
")",
"if",
"sets",
".",
"empty?",
"skips",
"=",
"Array",
"(",
"opts",
".",
"delete",
"(",
":skip_set",
")",
")",
"sets",
".",
"reject!",
"{",
"|",
"s",
"|",
"skips",
".",
"include?",
"s",
"}",
"end",
"sets",
"=",
"[",
"nil",
"]",
"if",
"sets",
".",
"empty?",
"set_enums",
"=",
"sets",
".",
"lazy",
".",
"map",
"do",
"|",
"set",
"|",
"set_opts",
"=",
"opts",
".",
"dup",
"set_opts",
"[",
":set",
"]",
"=",
"set",
"unless",
"set",
".",
"nil?",
"begin",
"yield",
"(",
"set_opts",
")",
"if",
"block_given?",
"rescue",
"OAI",
"::",
"Exception",
"=>",
"e",
"Krikri",
"::",
"Logger",
".",
"log",
":warn",
",",
"\"Skipping set #{set} with error: #{e}\"",
"[",
"]",
"end",
"end",
"concat_enum",
"(",
"set_enums",
")",
".",
"lazy",
"end"
] | Runs the request in the given block against the sets specified in `opts`.
Results are concatenated into a single enumerator.
Sets that respond with an error (`OAI::Exception`) will return empty
and be skipped.
@param opts [Hash] the options to pass, including all sets to process.
@yield gives options to the block once for each set. The
block should run the harvest action with the options and give an
Enumerable.
@yieldparam set_opts [Hash]
@yieldreturn [Enumerable] a result set to wrap into the retured lazy
enumerator
@return [Enumerator::Lazy] A lazy enumerator concatenating the results
of the block with each set. | [
"Runs",
"the",
"request",
"in",
"the",
"given",
"block",
"against",
"the",
"sets",
"specified",
"in",
"opts",
".",
"Results",
"are",
"concatenated",
"into",
"a",
"single",
"enumerator",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L186-L206 |
592 | Esri/geotrigger-ruby | lib/geotrigger/trigger.rb | Geotrigger.Trigger.post_update | def post_update opts = {}
post_data = @data.dup
post_data['triggerIds'] = post_data.delete 'triggerId'
post_data.delete 'tags'
if circle?
post_data['condition']['geo'].delete 'geojson'
post_data['condition']['geo'].delete 'esrijson'
end
grok_self_from post 'trigger/update', post_data.merge(opts)
self
end | ruby | def post_update opts = {}
post_data = @data.dup
post_data['triggerIds'] = post_data.delete 'triggerId'
post_data.delete 'tags'
if circle?
post_data['condition']['geo'].delete 'geojson'
post_data['condition']['geo'].delete 'esrijson'
end
grok_self_from post 'trigger/update', post_data.merge(opts)
self
end | [
"def",
"post_update",
"opts",
"=",
"{",
"}",
"post_data",
"=",
"@data",
".",
"dup",
"post_data",
"[",
"'triggerIds'",
"]",
"=",
"post_data",
".",
"delete",
"'triggerId'",
"post_data",
".",
"delete",
"'tags'",
"if",
"circle?",
"post_data",
"[",
"'condition'",
"]",
"[",
"'geo'",
"]",
".",
"delete",
"'geojson'",
"post_data",
"[",
"'condition'",
"]",
"[",
"'geo'",
"]",
".",
"delete",
"'esrijson'",
"end",
"grok_self_from",
"post",
"'trigger/update'",
",",
"post_data",
".",
"merge",
"(",
"opts",
")",
"self",
"end"
] | POST the trigger's +@data+ to the API via 'trigger/update', and return
the same object with the new +@data+ returned from API call. | [
"POST",
"the",
"trigger",
"s",
"+"
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/trigger.rb#L58-L70 |
593 | outcomesinsights/sequelizer | lib/sequelizer/options.rb | Sequelizer.Options.fix_options | def fix_options(passed_options)
return passed_options unless passed_options.nil? || passed_options.is_a?(Hash)
sequelizer_options = db_config.merge(OptionsHash.new(passed_options || {}).to_hash)
if sequelizer_options[:adapter] =~ /^postgres/
sequelizer_options[:adapter] = 'postgres'
paths = %w(search_path schema_search_path schema).map { |key| sequelizer_options.delete(key) }.compact
unless paths.empty?
sequelizer_options[:search_path] = paths.first
sequelizer_options[:after_connect] = after_connect(paths.first)
end
end
if sequelizer_options[:timeout]
# I'm doing a merge! here because the indifferent access part
# of OptionsHash seemed to not work when I tried
# sequelizer_options[:timeout] = sequelizer_options[:timeout].to_i
sequelizer_options.merge!(timeout: sequelizer_options[:timeout].to_i)
end
sequelizer_options.merge(after_connect: make_ac(sequelizer_options))
end | ruby | def fix_options(passed_options)
return passed_options unless passed_options.nil? || passed_options.is_a?(Hash)
sequelizer_options = db_config.merge(OptionsHash.new(passed_options || {}).to_hash)
if sequelizer_options[:adapter] =~ /^postgres/
sequelizer_options[:adapter] = 'postgres'
paths = %w(search_path schema_search_path schema).map { |key| sequelizer_options.delete(key) }.compact
unless paths.empty?
sequelizer_options[:search_path] = paths.first
sequelizer_options[:after_connect] = after_connect(paths.first)
end
end
if sequelizer_options[:timeout]
# I'm doing a merge! here because the indifferent access part
# of OptionsHash seemed to not work when I tried
# sequelizer_options[:timeout] = sequelizer_options[:timeout].to_i
sequelizer_options.merge!(timeout: sequelizer_options[:timeout].to_i)
end
sequelizer_options.merge(after_connect: make_ac(sequelizer_options))
end | [
"def",
"fix_options",
"(",
"passed_options",
")",
"return",
"passed_options",
"unless",
"passed_options",
".",
"nil?",
"||",
"passed_options",
".",
"is_a?",
"(",
"Hash",
")",
"sequelizer_options",
"=",
"db_config",
".",
"merge",
"(",
"OptionsHash",
".",
"new",
"(",
"passed_options",
"||",
"{",
"}",
")",
".",
"to_hash",
")",
"if",
"sequelizer_options",
"[",
":adapter",
"]",
"=~",
"/",
"/",
"sequelizer_options",
"[",
":adapter",
"]",
"=",
"'postgres'",
"paths",
"=",
"%w(",
"search_path",
"schema_search_path",
"schema",
")",
".",
"map",
"{",
"|",
"key",
"|",
"sequelizer_options",
".",
"delete",
"(",
"key",
")",
"}",
".",
"compact",
"unless",
"paths",
".",
"empty?",
"sequelizer_options",
"[",
":search_path",
"]",
"=",
"paths",
".",
"first",
"sequelizer_options",
"[",
":after_connect",
"]",
"=",
"after_connect",
"(",
"paths",
".",
"first",
")",
"end",
"end",
"if",
"sequelizer_options",
"[",
":timeout",
"]",
"# I'm doing a merge! here because the indifferent access part",
"# of OptionsHash seemed to not work when I tried",
"# sequelizer_options[:timeout] = sequelizer_options[:timeout].to_i",
"sequelizer_options",
".",
"merge!",
"(",
"timeout",
":",
"sequelizer_options",
"[",
":timeout",
"]",
".",
"to_i",
")",
"end",
"sequelizer_options",
".",
"merge",
"(",
"after_connect",
":",
"make_ac",
"(",
"sequelizer_options",
")",
")",
"end"
] | If passed a hash, scans hash for certain options and sets up hash
to be fed to Sequel.connect
If fed anything, like a string that represents the URL for a DB,
the string is returned without modification | [
"If",
"passed",
"a",
"hash",
"scans",
"hash",
"for",
"certain",
"options",
"and",
"sets",
"up",
"hash",
"to",
"be",
"fed",
"to",
"Sequel",
".",
"connect"
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/options.rb#L40-L62 |
594 | outcomesinsights/sequelizer | lib/sequelizer/options.rb | Sequelizer.Options.after_connect | def after_connect(search_path)
Proc.new do |conn|
search_path.split(',').map(&:strip).each do |schema|
conn.execute("CREATE SCHEMA IF NOT EXISTS #{schema}")
end
conn.execute("SET search_path TO #{search_path}")
end
end | ruby | def after_connect(search_path)
Proc.new do |conn|
search_path.split(',').map(&:strip).each do |schema|
conn.execute("CREATE SCHEMA IF NOT EXISTS #{schema}")
end
conn.execute("SET search_path TO #{search_path}")
end
end | [
"def",
"after_connect",
"(",
"search_path",
")",
"Proc",
".",
"new",
"do",
"|",
"conn",
"|",
"search_path",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
":strip",
")",
".",
"each",
"do",
"|",
"schema",
"|",
"conn",
".",
"execute",
"(",
"\"CREATE SCHEMA IF NOT EXISTS #{schema}\"",
")",
"end",
"conn",
".",
"execute",
"(",
"\"SET search_path TO #{search_path}\"",
")",
"end",
"end"
] | Returns a proc that should be executed after Sequel connects to the
datebase.
Right now, the only thing that happens is if we're connecting to
PostgreSQL and the schema_search_path is defined, each schema
is created if it doesn't exist, then the search_path is set for
the connection. | [
"Returns",
"a",
"proc",
"that",
"should",
"be",
"executed",
"after",
"Sequel",
"connects",
"to",
"the",
"datebase",
"."
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/options.rb#L84-L91 |
595 | technoweenie/running_man | lib/running_man/block.rb | RunningMan.Block.run_once | def run_once(binding)
@ivars.clear
before = binding.instance_variables
binding.instance_eval(&@block)
(binding.instance_variables - before).each do |ivar|
@ivars[ivar] = binding.instance_variable_get(ivar)
end
end | ruby | def run_once(binding)
@ivars.clear
before = binding.instance_variables
binding.instance_eval(&@block)
(binding.instance_variables - before).each do |ivar|
@ivars[ivar] = binding.instance_variable_get(ivar)
end
end | [
"def",
"run_once",
"(",
"binding",
")",
"@ivars",
".",
"clear",
"before",
"=",
"binding",
".",
"instance_variables",
"binding",
".",
"instance_eval",
"(",
"@block",
")",
"(",
"binding",
".",
"instance_variables",
"-",
"before",
")",
".",
"each",
"do",
"|",
"ivar",
"|",
"@ivars",
"[",
"ivar",
"]",
"=",
"binding",
".",
"instance_variable_get",
"(",
"ivar",
")",
"end",
"end"
] | This runs the block and stores any new instance variables that were set.
binding - The same Object that is given to #run.
Returns nothing. | [
"This",
"runs",
"the",
"block",
"and",
"stores",
"any",
"new",
"instance",
"variables",
"that",
"were",
"set",
"."
] | 1e7a1b1d276dc7bbfb25f523de5c521e070854ab | https://github.com/technoweenie/running_man/blob/1e7a1b1d276dc7bbfb25f523de5c521e070854ab/lib/running_man/block.rb#L59-L66 |
596 | technoweenie/running_man | lib/running_man/active_record_block.rb | RunningMan.ActiveRecordBlock.setup | def setup(test_class)
block = self
test_class.setup { block.run(self) }
test_class.teardown { block.teardown_transaction }
end | ruby | def setup(test_class)
block = self
test_class.setup { block.run(self) }
test_class.teardown { block.teardown_transaction }
end | [
"def",
"setup",
"(",
"test_class",
")",
"block",
"=",
"self",
"test_class",
".",
"setup",
"{",
"block",
".",
"run",
"(",
"self",
")",
"}",
"test_class",
".",
"teardown",
"{",
"block",
".",
"teardown_transaction",
"}",
"end"
] | Ensure the block is setup to run first, and that the test run is wrapped
in a database transaction. | [
"Ensure",
"the",
"block",
"is",
"setup",
"to",
"run",
"first",
"and",
"that",
"the",
"test",
"run",
"is",
"wrapped",
"in",
"a",
"database",
"transaction",
"."
] | 1e7a1b1d276dc7bbfb25f523de5c521e070854ab | https://github.com/technoweenie/running_man/blob/1e7a1b1d276dc7bbfb25f523de5c521e070854ab/lib/running_man/active_record_block.rb#L48-L52 |
597 | technoweenie/running_man | lib/running_man/active_record_block.rb | RunningMan.ActiveRecordBlock.set_ivar | def set_ivar(binding, ivar, value)
if value.class.respond_to?(:find)
value = value.class.find(value.id)
end
super(binding, ivar, value)
end | ruby | def set_ivar(binding, ivar, value)
if value.class.respond_to?(:find)
value = value.class.find(value.id)
end
super(binding, ivar, value)
end | [
"def",
"set_ivar",
"(",
"binding",
",",
"ivar",
",",
"value",
")",
"if",
"value",
".",
"class",
".",
"respond_to?",
"(",
":find",
")",
"value",
"=",
"value",
".",
"class",
".",
"find",
"(",
"value",
".",
"id",
")",
"end",
"super",
"(",
"binding",
",",
"ivar",
",",
"value",
")",
"end"
] | reload any AR instances | [
"reload",
"any",
"AR",
"instances"
] | 1e7a1b1d276dc7bbfb25f523de5c521e070854ab | https://github.com/technoweenie/running_man/blob/1e7a1b1d276dc7bbfb25f523de5c521e070854ab/lib/running_man/active_record_block.rb#L67-L72 |
598 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.experts | def experts(q, options={})
options = set_window_or_default(options)
result = handle_response(get("/experts.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(result, Topsy::Author)
end | ruby | def experts(q, options={})
options = set_window_or_default(options)
result = handle_response(get("/experts.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(result, Topsy::Author)
end | [
"def",
"experts",
"(",
"q",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"set_window_or_default",
"(",
"options",
")",
"result",
"=",
"handle_response",
"(",
"get",
"(",
"\"/experts.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"result",
",",
"Topsy",
"::",
"Author",
")",
"end"
] | Returns list of authors that talk about the query. The list is sorted by frequency of posts and the influence of authors.
@param [String] q the search query string
@param [Hash] options method options
@option options [Symbol] :window Time window for results. (default: :all) Options: :dynamic most relevant, :hour last hour, :day last day, :week last week, :month last month, :all all time. You can also use the h6 (6 hours) d3 (3 days) syntax.
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Hashie::Mash] | [
"Returns",
"list",
"of",
"authors",
"that",
"talk",
"about",
"the",
"query",
".",
"The",
"list",
"is",
"sorted",
"by",
"frequency",
"of",
"posts",
"and",
"the",
"influence",
"of",
"authors",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L52-L56 |
599 | pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.link_posts | def link_posts(url, options={})
linkposts = handle_response(get("/linkposts.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(linkposts,Topsy::Linkpost)
end | ruby | def link_posts(url, options={})
linkposts = handle_response(get("/linkposts.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(linkposts,Topsy::Linkpost)
end | [
"def",
"link_posts",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"linkposts",
"=",
"handle_response",
"(",
"get",
"(",
"\"/linkposts.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"linkposts",
",",
"Topsy",
"::",
"Linkpost",
")",
"end"
] | Returns list of URLs posted by an author
@param [String] url URL string for the author.
@param [Hash] options method options
@option options [String] :contains Query string to filter results
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"URLs",
"posted",
"by",
"an",
"author"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L66-L69 |