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
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
BlockScore/blockscore-ruby | lib/blockscore/collection.rb | BlockScore.Collection.register_to_parent | def register_to_parent(item)
fail Error, 'None belonging' unless parent_id?(item)
ids << item.id
self << item
item
end | ruby | def register_to_parent(item)
fail Error, 'None belonging' unless parent_id?(item)
ids << item.id
self << item
item
end | [
"def",
"register_to_parent",
"(",
"item",
")",
"fail",
"Error",
",",
"'None belonging'",
"unless",
"parent_id?",
"(",
"item",
")",
"ids",
"<<",
"item",
".",
"id",
"self",
"<<",
"item",
"item",
"end"
]
| Register a resource in collection
@param item [BlockScore::Base] a resource
@raise [BlockScore::Error] if no `parent_id`
@return [BlockScore::Base] otherwise
@api private | [
"Register",
"a",
"resource",
"in",
"collection"
]
| 3f837729f9997d92468966e4478ea2f4aaea0156 | https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L206-L211 | train |
pluginaweek/table_helper | lib/table_helper/body.rb | TableHelper.Body.build_row | def build_row(object, index = table.collection.index(object))
row = BodyRow.new(object, self)
row.alternate = alternate ? index.send("#{alternate}?") : false
@builder.call(row.builder, object, index) if @builder
row.html
end | ruby | def build_row(object, index = table.collection.index(object))
row = BodyRow.new(object, self)
row.alternate = alternate ? index.send("#{alternate}?") : false
@builder.call(row.builder, object, index) if @builder
row.html
end | [
"def",
"build_row",
"(",
"object",
",",
"index",
"=",
"table",
".",
"collection",
".",
"index",
"(",
"object",
")",
")",
"row",
"=",
"BodyRow",
".",
"new",
"(",
"object",
",",
"self",
")",
"row",
".",
"alternate",
"=",
"alternate",
"?",
"index",
".",
"send",
"(",
"\"#{alternate}?\"",
")",
":",
"false",
"@builder",
".",
"call",
"(",
"row",
".",
"builder",
",",
"object",
",",
"index",
")",
"if",
"@builder",
"row",
".",
"html",
"end"
]
| Builds a row for an object in the table.
The provided block should set the values for each cell in the row. | [
"Builds",
"a",
"row",
"for",
"an",
"object",
"in",
"the",
"table",
"."
]
| 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/body.rb#L79-L84 | train |
kanevk/poker-engine | lib/poker_engine/cards.rb | PokerEngine.Cards.values_desc_by_occurency | def values_desc_by_occurency
values = cards.map(&:value)
values.sort do |a, b|
coefficient_occurency = (values.count(a) <=> values.count(b))
coefficient_occurency.zero? ? -(a <=> b) : -coefficient_occurency
end
end | ruby | def values_desc_by_occurency
values = cards.map(&:value)
values.sort do |a, b|
coefficient_occurency = (values.count(a) <=> values.count(b))
coefficient_occurency.zero? ? -(a <=> b) : -coefficient_occurency
end
end | [
"def",
"values_desc_by_occurency",
"values",
"=",
"cards",
".",
"map",
"(",
"&",
":value",
")",
"values",
".",
"sort",
"do",
"|",
"a",
",",
"b",
"|",
"coefficient_occurency",
"=",
"(",
"values",
".",
"count",
"(",
"a",
")",
"<=>",
"values",
".",
"count",
"(",
"b",
")",
")",
"coefficient_occurency",
".",
"zero?",
"?",
"-",
"(",
"a",
"<=>",
"b",
")",
":",
"-",
"coefficient_occurency",
"end",
"end"
]
| Make descending order primary by occurency and secondary by value | [
"Make",
"descending",
"order",
"primary",
"by",
"occurency",
"and",
"secondary",
"by",
"value"
]
| 83a4fbf459281225df074f276efe6fb123bb8d69 | https://github.com/kanevk/poker-engine/blob/83a4fbf459281225df074f276efe6fb123bb8d69/lib/poker_engine/cards.rb#L54-L62 | train |
pluginaweek/table_helper | lib/table_helper/body_row.rb | TableHelper.BodyRow.content | def content
number_to_skip = 0 # Keeps track of the # of columns to skip
html = ''
table.header.column_names.each do |column|
number_to_skip -= 1 and next if number_to_skip > 0
if cell = @cells[column]
number_to_skip = (cell[:colspan] || 1) - 1
else
cell = Cell.new(column, nil)
end
html << cell.html
end
html
end | ruby | def content
number_to_skip = 0 # Keeps track of the # of columns to skip
html = ''
table.header.column_names.each do |column|
number_to_skip -= 1 and next if number_to_skip > 0
if cell = @cells[column]
number_to_skip = (cell[:colspan] || 1) - 1
else
cell = Cell.new(column, nil)
end
html << cell.html
end
html
end | [
"def",
"content",
"number_to_skip",
"=",
"0",
"html",
"=",
"''",
"table",
".",
"header",
".",
"column_names",
".",
"each",
"do",
"|",
"column",
"|",
"number_to_skip",
"-=",
"1",
"and",
"next",
"if",
"number_to_skip",
">",
"0",
"if",
"cell",
"=",
"@cells",
"[",
"column",
"]",
"number_to_skip",
"=",
"(",
"cell",
"[",
":colspan",
"]",
"||",
"1",
")",
"-",
"1",
"else",
"cell",
"=",
"Cell",
".",
"new",
"(",
"column",
",",
"nil",
")",
"end",
"html",
"<<",
"cell",
".",
"html",
"end",
"html",
"end"
]
| Builds the row's cells based on the order of the columns in the
header. If a cell cannot be found for a specific column, then a blank
cell is rendered. | [
"Builds",
"the",
"row",
"s",
"cells",
"based",
"on",
"the",
"order",
"of",
"the",
"columns",
"in",
"the",
"header",
".",
"If",
"a",
"cell",
"cannot",
"be",
"found",
"for",
"a",
"specific",
"column",
"then",
"a",
"blank",
"cell",
"is",
"rendered",
"."
]
| 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/body_row.rb#L55-L72 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.kill_instances | def kill_instances(instances)
running_instances = instances.compact.select do |instance|
instance_by_id(instance.instance_id).state.name == 'running'
end
instance_ids = running_instances.map(&:instance_id)
return nil if instance_ids.empty?
@logger.notify("aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}")
client.terminate_instances(:instance_ids => instance_ids)
nil
end | ruby | def kill_instances(instances)
running_instances = instances.compact.select do |instance|
instance_by_id(instance.instance_id).state.name == 'running'
end
instance_ids = running_instances.map(&:instance_id)
return nil if instance_ids.empty?
@logger.notify("aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}")
client.terminate_instances(:instance_ids => instance_ids)
nil
end | [
"def",
"kill_instances",
"(",
"instances",
")",
"running_instances",
"=",
"instances",
".",
"compact",
".",
"select",
"do",
"|",
"instance",
"|",
"instance_by_id",
"(",
"instance",
".",
"instance_id",
")",
".",
"state",
".",
"name",
"==",
"'running'",
"end",
"instance_ids",
"=",
"running_instances",
".",
"map",
"(",
"&",
":instance_id",
")",
"return",
"nil",
"if",
"instance_ids",
".",
"empty?",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}\"",
")",
"client",
".",
"terminate_instances",
"(",
":instance_ids",
"=>",
"instance_ids",
")",
"nil",
"end"
]
| Kill all instances.
@param instances [Enumerable<Aws::EC2::Types::Instance>]
@return [void] | [
"Kill",
"all",
"instances",
"."
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L106-L118 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.kill_zombie_volumes | def kill_zombie_volumes
# Occasionaly, tearing down ec2 instances leaves orphaned EBS volumes behind -- these stack up quickly.
# This simply looks for EBS volumes that are not in use
@logger.notify("aws-sdk: Kill Zombie Volumes!")
volume_count = 0
regions.each do |region|
@logger.debug "Reviewing: #{region}"
available_volumes = client(region).describe_volumes(
:filters => [
{ :name => 'status', :values => ['available'], }
]
).volumes
available_volumes.each do |volume|
begin
client(region).delete_volume(:volume_id => volume.id)
volume_count += 1
rescue Aws::EC2::Errors::InvalidVolume::NotFound => e
@logger.debug "Failed to remove volume: #{volume.id} #{e}"
end
end
end
@logger.notify "Freed #{volume_count} volume(s)"
end | ruby | def kill_zombie_volumes
# Occasionaly, tearing down ec2 instances leaves orphaned EBS volumes behind -- these stack up quickly.
# This simply looks for EBS volumes that are not in use
@logger.notify("aws-sdk: Kill Zombie Volumes!")
volume_count = 0
regions.each do |region|
@logger.debug "Reviewing: #{region}"
available_volumes = client(region).describe_volumes(
:filters => [
{ :name => 'status', :values => ['available'], }
]
).volumes
available_volumes.each do |volume|
begin
client(region).delete_volume(:volume_id => volume.id)
volume_count += 1
rescue Aws::EC2::Errors::InvalidVolume::NotFound => e
@logger.debug "Failed to remove volume: #{volume.id} #{e}"
end
end
end
@logger.notify "Freed #{volume_count} volume(s)"
end | [
"def",
"kill_zombie_volumes",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Kill Zombie Volumes!\"",
")",
"volume_count",
"=",
"0",
"regions",
".",
"each",
"do",
"|",
"region",
"|",
"@logger",
".",
"debug",
"\"Reviewing: #{region}\"",
"available_volumes",
"=",
"client",
"(",
"region",
")",
".",
"describe_volumes",
"(",
":filters",
"=>",
"[",
"{",
":name",
"=>",
"'status'",
",",
":values",
"=>",
"[",
"'available'",
"]",
",",
"}",
"]",
")",
".",
"volumes",
"available_volumes",
".",
"each",
"do",
"|",
"volume",
"|",
"begin",
"client",
"(",
"region",
")",
".",
"delete_volume",
"(",
":volume_id",
"=>",
"volume",
".",
"id",
")",
"volume_count",
"+=",
"1",
"rescue",
"Aws",
"::",
"EC2",
"::",
"Errors",
"::",
"InvalidVolume",
"::",
"NotFound",
"=>",
"e",
"@logger",
".",
"debug",
"\"Failed to remove volume: #{volume.id} #{e}\"",
"end",
"end",
"end",
"@logger",
".",
"notify",
"\"Freed #{volume_count} volume(s)\"",
"end"
]
| Destroy any volumes marked 'available', INCLUDING THOSE YOU DON'T OWN! Use with care. | [
"Destroy",
"any",
"volumes",
"marked",
"available",
"INCLUDING",
"THOSE",
"YOU",
"DON",
"T",
"OWN!",
"Use",
"with",
"care",
"."
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L241-L266 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.launch_all_nodes | def launch_all_nodes
@logger.notify("aws-sdk: launch all hosts in configuration")
ami_spec = YAML.load_file(@options[:ec2_yaml])["AMI"]
global_subnet_id = @options['subnet_id']
global_subnets = @options['subnet_ids']
if global_subnet_id and global_subnets
raise RuntimeError, 'Config specifies both subnet_id and subnet_ids'
end
no_subnet_hosts = []
specific_subnet_hosts = []
some_subnet_hosts = []
@hosts.each do |host|
if global_subnet_id or host['subnet_id']
specific_subnet_hosts.push(host)
elsif global_subnets
some_subnet_hosts.push(host)
else
no_subnet_hosts.push(host)
end
end
instances = [] # Each element is {:instance => i, :host => h}
begin
@logger.notify("aws-sdk: launch instances not particular about subnet")
launch_nodes_on_some_subnet(some_subnet_hosts, global_subnets, ami_spec,
instances)
@logger.notify("aws-sdk: launch instances requiring a specific subnet")
specific_subnet_hosts.each do |host|
subnet_id = host['subnet_id'] || global_subnet_id
instance = create_instance(host, ami_spec, subnet_id)
instances.push({:instance => instance, :host => host})
end
@logger.notify("aws-sdk: launch instances requiring no subnet")
no_subnet_hosts.each do |host|
instance = create_instance(host, ami_spec, nil)
instances.push({:instance => instance, :host => host})
end
wait_for_status(:running, instances)
rescue Exception => ex
@logger.notify("aws-sdk: exception #{ex.class}: #{ex}")
kill_instances(instances.map{|x| x[:instance]})
raise ex
end
# At this point, all instances should be running since wait
# either returns on success or throws an exception.
if instances.empty?
raise RuntimeError, "Didn't manage to launch any EC2 instances"
end
# Assign the now known running instances to their hosts.
instances.each {|x| x[:host]['instance'] = x[:instance]}
nil
end | ruby | def launch_all_nodes
@logger.notify("aws-sdk: launch all hosts in configuration")
ami_spec = YAML.load_file(@options[:ec2_yaml])["AMI"]
global_subnet_id = @options['subnet_id']
global_subnets = @options['subnet_ids']
if global_subnet_id and global_subnets
raise RuntimeError, 'Config specifies both subnet_id and subnet_ids'
end
no_subnet_hosts = []
specific_subnet_hosts = []
some_subnet_hosts = []
@hosts.each do |host|
if global_subnet_id or host['subnet_id']
specific_subnet_hosts.push(host)
elsif global_subnets
some_subnet_hosts.push(host)
else
no_subnet_hosts.push(host)
end
end
instances = [] # Each element is {:instance => i, :host => h}
begin
@logger.notify("aws-sdk: launch instances not particular about subnet")
launch_nodes_on_some_subnet(some_subnet_hosts, global_subnets, ami_spec,
instances)
@logger.notify("aws-sdk: launch instances requiring a specific subnet")
specific_subnet_hosts.each do |host|
subnet_id = host['subnet_id'] || global_subnet_id
instance = create_instance(host, ami_spec, subnet_id)
instances.push({:instance => instance, :host => host})
end
@logger.notify("aws-sdk: launch instances requiring no subnet")
no_subnet_hosts.each do |host|
instance = create_instance(host, ami_spec, nil)
instances.push({:instance => instance, :host => host})
end
wait_for_status(:running, instances)
rescue Exception => ex
@logger.notify("aws-sdk: exception #{ex.class}: #{ex}")
kill_instances(instances.map{|x| x[:instance]})
raise ex
end
# At this point, all instances should be running since wait
# either returns on success or throws an exception.
if instances.empty?
raise RuntimeError, "Didn't manage to launch any EC2 instances"
end
# Assign the now known running instances to their hosts.
instances.each {|x| x[:host]['instance'] = x[:instance]}
nil
end | [
"def",
"launch_all_nodes",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch all hosts in configuration\"",
")",
"ami_spec",
"=",
"YAML",
".",
"load_file",
"(",
"@options",
"[",
":ec2_yaml",
"]",
")",
"[",
"\"AMI\"",
"]",
"global_subnet_id",
"=",
"@options",
"[",
"'subnet_id'",
"]",
"global_subnets",
"=",
"@options",
"[",
"'subnet_ids'",
"]",
"if",
"global_subnet_id",
"and",
"global_subnets",
"raise",
"RuntimeError",
",",
"'Config specifies both subnet_id and subnet_ids'",
"end",
"no_subnet_hosts",
"=",
"[",
"]",
"specific_subnet_hosts",
"=",
"[",
"]",
"some_subnet_hosts",
"=",
"[",
"]",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"if",
"global_subnet_id",
"or",
"host",
"[",
"'subnet_id'",
"]",
"specific_subnet_hosts",
".",
"push",
"(",
"host",
")",
"elsif",
"global_subnets",
"some_subnet_hosts",
".",
"push",
"(",
"host",
")",
"else",
"no_subnet_hosts",
".",
"push",
"(",
"host",
")",
"end",
"end",
"instances",
"=",
"[",
"]",
"begin",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch instances not particular about subnet\"",
")",
"launch_nodes_on_some_subnet",
"(",
"some_subnet_hosts",
",",
"global_subnets",
",",
"ami_spec",
",",
"instances",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch instances requiring a specific subnet\"",
")",
"specific_subnet_hosts",
".",
"each",
"do",
"|",
"host",
"|",
"subnet_id",
"=",
"host",
"[",
"'subnet_id'",
"]",
"||",
"global_subnet_id",
"instance",
"=",
"create_instance",
"(",
"host",
",",
"ami_spec",
",",
"subnet_id",
")",
"instances",
".",
"push",
"(",
"{",
":instance",
"=>",
"instance",
",",
":host",
"=>",
"host",
"}",
")",
"end",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch instances requiring no subnet\"",
")",
"no_subnet_hosts",
".",
"each",
"do",
"|",
"host",
"|",
"instance",
"=",
"create_instance",
"(",
"host",
",",
"ami_spec",
",",
"nil",
")",
"instances",
".",
"push",
"(",
"{",
":instance",
"=>",
"instance",
",",
":host",
"=>",
"host",
"}",
")",
"end",
"wait_for_status",
"(",
":running",
",",
"instances",
")",
"rescue",
"Exception",
"=>",
"ex",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: exception #{ex.class}: #{ex}\"",
")",
"kill_instances",
"(",
"instances",
".",
"map",
"{",
"|",
"x",
"|",
"x",
"[",
":instance",
"]",
"}",
")",
"raise",
"ex",
"end",
"if",
"instances",
".",
"empty?",
"raise",
"RuntimeError",
",",
"\"Didn't manage to launch any EC2 instances\"",
"end",
"instances",
".",
"each",
"{",
"|",
"x",
"|",
"x",
"[",
":host",
"]",
"[",
"'instance'",
"]",
"=",
"x",
"[",
":instance",
"]",
"}",
"nil",
"end"
]
| Create EC2 instances for all hosts, tag them, and wait until
they're running. When a host provides a subnet_id, create the
instance in that subnet, otherwise prefer a CONFIG subnet_id.
If neither are set but there is a CONFIG subnet_ids list,
attempt to create the host in each specified subnet, which might
fail due to capacity constraints, for example. Specifying both
a CONFIG subnet_id and subnet_ids will provoke an error.
@return [void]
@api private | [
"Create",
"EC2",
"instances",
"for",
"all",
"hosts",
"tag",
"them",
"and",
"wait",
"until",
"they",
"re",
"running",
".",
"When",
"a",
"host",
"provides",
"a",
"subnet_id",
"create",
"the",
"instance",
"in",
"that",
"subnet",
"otherwise",
"prefer",
"a",
"CONFIG",
"subnet_id",
".",
"If",
"neither",
"are",
"set",
"but",
"there",
"is",
"a",
"CONFIG",
"subnet_ids",
"list",
"attempt",
"to",
"create",
"the",
"host",
"in",
"each",
"specified",
"subnet",
"which",
"might",
"fail",
"due",
"to",
"capacity",
"constraints",
"for",
"example",
".",
"Specifying",
"both",
"a",
"CONFIG",
"subnet_id",
"and",
"subnet_ids",
"will",
"provoke",
"an",
"error",
"."
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L432-L482 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.wait_for_status_netdev | def wait_for_status_netdev()
@hosts.each do |host|
if host['platform'] =~ /f5-|netscaler/
wait_for_status(:running, @hosts)
wait_for_status(nil, @hosts) do |instance|
instance_status_collection = client.describe_instance_status({:instance_ids => [instance.instance_id]})
first_instance = instance_status_collection.first[:instance_statuses].first
first_instance[:instance_status][:status] == "ok" if first_instance
end
break
end
end
end | ruby | def wait_for_status_netdev()
@hosts.each do |host|
if host['platform'] =~ /f5-|netscaler/
wait_for_status(:running, @hosts)
wait_for_status(nil, @hosts) do |instance|
instance_status_collection = client.describe_instance_status({:instance_ids => [instance.instance_id]})
first_instance = instance_status_collection.first[:instance_statuses].first
first_instance[:instance_status][:status] == "ok" if first_instance
end
break
end
end
end | [
"def",
"wait_for_status_netdev",
"(",
")",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"if",
"host",
"[",
"'platform'",
"]",
"=~",
"/",
"/",
"wait_for_status",
"(",
":running",
",",
"@hosts",
")",
"wait_for_status",
"(",
"nil",
",",
"@hosts",
")",
"do",
"|",
"instance",
"|",
"instance_status_collection",
"=",
"client",
".",
"describe_instance_status",
"(",
"{",
":instance_ids",
"=>",
"[",
"instance",
".",
"instance_id",
"]",
"}",
")",
"first_instance",
"=",
"instance_status_collection",
".",
"first",
"[",
":instance_statuses",
"]",
".",
"first",
"first_instance",
"[",
":instance_status",
"]",
"[",
":status",
"]",
"==",
"\"ok\"",
"if",
"first_instance",
"end",
"break",
"end",
"end",
"end"
]
| Handles special checks needed for netdev platforms.
@note if any host is an netdev one, these checks will happen once across all
of the hosts, and then we'll exit
@return [void]
@api private | [
"Handles",
"special",
"checks",
"needed",
"for",
"netdev",
"platforms",
"."
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L539-L553 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.add_tags | def add_tags
@hosts.each do |host|
instance = host['instance']
# Define tags for the instance
@logger.notify("aws-sdk: Add tags for #{host.name}")
tags = [
{
:key => 'jenkins_build_url',
:value => @options[:jenkins_build_url],
},
{
:key => 'Name',
:value => host.name,
},
{
:key => 'department',
:value => @options[:department],
},
{
:key => 'project',
:value => @options[:project],
},
{
:key => 'created_by',
:value => @options[:created_by],
},
]
host[:host_tags].each do |name, val|
tags << { :key => name.to_s, :value => val }
end
client.create_tags(
:resources => [instance.instance_id],
:tags => tags.reject { |r| r[:value].nil? },
)
end
nil
end | ruby | def add_tags
@hosts.each do |host|
instance = host['instance']
# Define tags for the instance
@logger.notify("aws-sdk: Add tags for #{host.name}")
tags = [
{
:key => 'jenkins_build_url',
:value => @options[:jenkins_build_url],
},
{
:key => 'Name',
:value => host.name,
},
{
:key => 'department',
:value => @options[:department],
},
{
:key => 'project',
:value => @options[:project],
},
{
:key => 'created_by',
:value => @options[:created_by],
},
]
host[:host_tags].each do |name, val|
tags << { :key => name.to_s, :value => val }
end
client.create_tags(
:resources => [instance.instance_id],
:tags => tags.reject { |r| r[:value].nil? },
)
end
nil
end | [
"def",
"add_tags",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"instance",
"=",
"host",
"[",
"'instance'",
"]",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Add tags for #{host.name}\"",
")",
"tags",
"=",
"[",
"{",
":key",
"=>",
"'jenkins_build_url'",
",",
":value",
"=>",
"@options",
"[",
":jenkins_build_url",
"]",
",",
"}",
",",
"{",
":key",
"=>",
"'Name'",
",",
":value",
"=>",
"host",
".",
"name",
",",
"}",
",",
"{",
":key",
"=>",
"'department'",
",",
":value",
"=>",
"@options",
"[",
":department",
"]",
",",
"}",
",",
"{",
":key",
"=>",
"'project'",
",",
":value",
"=>",
"@options",
"[",
":project",
"]",
",",
"}",
",",
"{",
":key",
"=>",
"'created_by'",
",",
":value",
"=>",
"@options",
"[",
":created_by",
"]",
",",
"}",
",",
"]",
"host",
"[",
":host_tags",
"]",
".",
"each",
"do",
"|",
"name",
",",
"val",
"|",
"tags",
"<<",
"{",
":key",
"=>",
"name",
".",
"to_s",
",",
":value",
"=>",
"val",
"}",
"end",
"client",
".",
"create_tags",
"(",
":resources",
"=>",
"[",
"instance",
".",
"instance_id",
"]",
",",
":tags",
"=>",
"tags",
".",
"reject",
"{",
"|",
"r",
"|",
"r",
"[",
":value",
"]",
".",
"nil?",
"}",
",",
")",
"end",
"nil",
"end"
]
| Add metadata tags to all instances
@return [void]
@api private | [
"Add",
"metadata",
"tags",
"to",
"all",
"instances"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L559-L600 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.modify_network_interface | def modify_network_interface
@hosts.each do |host|
instance = host['instance']
host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0';
sg_cidr_ips = host['sg_cidr_ips'].split(',')
# Define tags for the instance
@logger.notify("aws-sdk: Update network_interface for #{host.name}")
security_group = ensure_group(instance[:network_interfaces].first, Beaker::EC2Helper.amiports(host), sg_cidr_ips)
ping_security_group = ensure_ping_group(instance[:network_interfaces].first, sg_cidr_ips)
client.modify_network_interface_attribute(
:network_interface_id => "#{instance[:network_interfaces].first[:network_interface_id]}",
:groups => [security_group.group_id, ping_security_group.group_id],
)
end
nil
end | ruby | def modify_network_interface
@hosts.each do |host|
instance = host['instance']
host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0';
sg_cidr_ips = host['sg_cidr_ips'].split(',')
# Define tags for the instance
@logger.notify("aws-sdk: Update network_interface for #{host.name}")
security_group = ensure_group(instance[:network_interfaces].first, Beaker::EC2Helper.amiports(host), sg_cidr_ips)
ping_security_group = ensure_ping_group(instance[:network_interfaces].first, sg_cidr_ips)
client.modify_network_interface_attribute(
:network_interface_id => "#{instance[:network_interfaces].first[:network_interface_id]}",
:groups => [security_group.group_id, ping_security_group.group_id],
)
end
nil
end | [
"def",
"modify_network_interface",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"instance",
"=",
"host",
"[",
"'instance'",
"]",
"host",
"[",
"'sg_cidr_ips'",
"]",
"=",
"host",
"[",
"'sg_cidr_ips'",
"]",
"||",
"'0.0.0.0/0'",
";",
"sg_cidr_ips",
"=",
"host",
"[",
"'sg_cidr_ips'",
"]",
".",
"split",
"(",
"','",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Update network_interface for #{host.name}\"",
")",
"security_group",
"=",
"ensure_group",
"(",
"instance",
"[",
":network_interfaces",
"]",
".",
"first",
",",
"Beaker",
"::",
"EC2Helper",
".",
"amiports",
"(",
"host",
")",
",",
"sg_cidr_ips",
")",
"ping_security_group",
"=",
"ensure_ping_group",
"(",
"instance",
"[",
":network_interfaces",
"]",
".",
"first",
",",
"sg_cidr_ips",
")",
"client",
".",
"modify_network_interface_attribute",
"(",
":network_interface_id",
"=>",
"\"#{instance[:network_interfaces].first[:network_interface_id]}\"",
",",
":groups",
"=>",
"[",
"security_group",
".",
"group_id",
",",
"ping_security_group",
".",
"group_id",
"]",
",",
")",
"end",
"nil",
"end"
]
| Add correct security groups to hosts network_interface
as during the create_instance stage it is too early in process
to configure
@return [void]
@api private | [
"Add",
"correct",
"security",
"groups",
"to",
"hosts",
"network_interface",
"as",
"during",
"the",
"create_instance",
"stage",
"it",
"is",
"too",
"early",
"in",
"process",
"to",
"configure"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L608-L627 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.populate_dns | def populate_dns
# Obtain the IP addresses and dns_name for each host
@hosts.each do |host|
@logger.notify("aws-sdk: Populate DNS for #{host.name}")
instance = host['instance']
host['ip'] = instance.public_ip_address || instance.private_ip_address
host['private_ip'] = instance.private_ip_address
host['dns_name'] = instance.public_dns_name || instance.private_dns_name
@logger.notify("aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}")
end
nil
end | ruby | def populate_dns
# Obtain the IP addresses and dns_name for each host
@hosts.each do |host|
@logger.notify("aws-sdk: Populate DNS for #{host.name}")
instance = host['instance']
host['ip'] = instance.public_ip_address || instance.private_ip_address
host['private_ip'] = instance.private_ip_address
host['dns_name'] = instance.public_dns_name || instance.private_dns_name
@logger.notify("aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}")
end
nil
end | [
"def",
"populate_dns",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Populate DNS for #{host.name}\"",
")",
"instance",
"=",
"host",
"[",
"'instance'",
"]",
"host",
"[",
"'ip'",
"]",
"=",
"instance",
".",
"public_ip_address",
"||",
"instance",
".",
"private_ip_address",
"host",
"[",
"'private_ip'",
"]",
"=",
"instance",
".",
"private_ip_address",
"host",
"[",
"'dns_name'",
"]",
"=",
"instance",
".",
"public_dns_name",
"||",
"instance",
".",
"private_dns_name",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}\"",
")",
"end",
"nil",
"end"
]
| Populate the hosts IP address from the EC2 dns_name
@return [void]
@api private | [
"Populate",
"the",
"hosts",
"IP",
"address",
"from",
"the",
"EC2",
"dns_name"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L633-L645 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.enable_root | def enable_root(host)
if host['user'] != 'root'
if host['platform'] =~ /f5-/
enable_root_f5(host)
elsif host['platform'] =~ /netscaler/
enable_root_netscaler(host)
else
copy_ssh_to_root(host, @options)
enable_root_login(host, @options)
host['user'] = 'root'
end
host.close
end
end | ruby | def enable_root(host)
if host['user'] != 'root'
if host['platform'] =~ /f5-/
enable_root_f5(host)
elsif host['platform'] =~ /netscaler/
enable_root_netscaler(host)
else
copy_ssh_to_root(host, @options)
enable_root_login(host, @options)
host['user'] = 'root'
end
host.close
end
end | [
"def",
"enable_root",
"(",
"host",
")",
"if",
"host",
"[",
"'user'",
"]",
"!=",
"'root'",
"if",
"host",
"[",
"'platform'",
"]",
"=~",
"/",
"/",
"enable_root_f5",
"(",
"host",
")",
"elsif",
"host",
"[",
"'platform'",
"]",
"=~",
"/",
"/",
"enable_root_netscaler",
"(",
"host",
")",
"else",
"copy_ssh_to_root",
"(",
"host",
",",
"@options",
")",
"enable_root_login",
"(",
"host",
",",
"@options",
")",
"host",
"[",
"'user'",
"]",
"=",
"'root'",
"end",
"host",
".",
"close",
"end",
"end"
]
| Enables root access for a host when username is not root
@return [void]
@api private | [
"Enables",
"root",
"access",
"for",
"a",
"host",
"when",
"username",
"is",
"not",
"root"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L697-L710 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.ensure_key_pair | def ensure_key_pair(region)
pair_name = key_name()
delete_key_pair(region, pair_name)
create_new_key_pair(region, pair_name)
end | ruby | def ensure_key_pair(region)
pair_name = key_name()
delete_key_pair(region, pair_name)
create_new_key_pair(region, pair_name)
end | [
"def",
"ensure_key_pair",
"(",
"region",
")",
"pair_name",
"=",
"key_name",
"(",
")",
"delete_key_pair",
"(",
"region",
",",
"pair_name",
")",
"create_new_key_pair",
"(",
"region",
",",
"pair_name",
")",
"end"
]
| Creates the KeyPair for this test run
@param region [Aws::EC2::Region] region to create the key pair in
@return [Aws::EC2::KeyPair] created key_pair
@api private | [
"Creates",
"the",
"KeyPair",
"for",
"this",
"test",
"run"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L876-L880 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.delete_key_pair_all_regions | def delete_key_pair_all_regions(keypair_name_filter=nil)
region_keypairs_hash = my_key_pairs(keypair_name_filter)
region_keypairs_hash.each_pair do |region, keypair_name_array|
keypair_name_array.each do |keypair_name|
delete_key_pair(region, keypair_name)
end
end
end | ruby | def delete_key_pair_all_regions(keypair_name_filter=nil)
region_keypairs_hash = my_key_pairs(keypair_name_filter)
region_keypairs_hash.each_pair do |region, keypair_name_array|
keypair_name_array.each do |keypair_name|
delete_key_pair(region, keypair_name)
end
end
end | [
"def",
"delete_key_pair_all_regions",
"(",
"keypair_name_filter",
"=",
"nil",
")",
"region_keypairs_hash",
"=",
"my_key_pairs",
"(",
"keypair_name_filter",
")",
"region_keypairs_hash",
".",
"each_pair",
"do",
"|",
"region",
",",
"keypair_name_array",
"|",
"keypair_name_array",
".",
"each",
"do",
"|",
"keypair_name",
"|",
"delete_key_pair",
"(",
"region",
",",
"keypair_name",
")",
"end",
"end",
"end"
]
| Deletes key pairs from all regions
@param [String] keypair_name_filter if given, will get all keypairs that match
a simple {::String#start_with?} filter. If no filter is given, the basic key
name returned by {#key_name} will be used.
@return nil
@api private | [
"Deletes",
"key",
"pairs",
"from",
"all",
"regions"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L890-L897 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.my_key_pairs | def my_key_pairs(name_filter=nil)
keypairs_by_region = {}
key_name_filter = name_filter ? "#{name_filter}-*" : key_name
regions.each do |region|
keypairs_by_region[region] = client(region).describe_key_pairs(
:filters => [{ :name => 'key-name', :values => [key_name_filter] }]
).key_pairs.map(&:key_name)
end
keypairs_by_region
end | ruby | def my_key_pairs(name_filter=nil)
keypairs_by_region = {}
key_name_filter = name_filter ? "#{name_filter}-*" : key_name
regions.each do |region|
keypairs_by_region[region] = client(region).describe_key_pairs(
:filters => [{ :name => 'key-name', :values => [key_name_filter] }]
).key_pairs.map(&:key_name)
end
keypairs_by_region
end | [
"def",
"my_key_pairs",
"(",
"name_filter",
"=",
"nil",
")",
"keypairs_by_region",
"=",
"{",
"}",
"key_name_filter",
"=",
"name_filter",
"?",
"\"#{name_filter}-*\"",
":",
"key_name",
"regions",
".",
"each",
"do",
"|",
"region",
"|",
"keypairs_by_region",
"[",
"region",
"]",
"=",
"client",
"(",
"region",
")",
".",
"describe_key_pairs",
"(",
":filters",
"=>",
"[",
"{",
":name",
"=>",
"'key-name'",
",",
":values",
"=>",
"[",
"key_name_filter",
"]",
"}",
"]",
")",
".",
"key_pairs",
".",
"map",
"(",
"&",
":key_name",
")",
"end",
"keypairs_by_region",
"end"
]
| Gets the Beaker user's keypairs by region
@param [String] name_filter if given, will get all keypairs that match
a simple {::String#start_with?} filter. If no filter is given, the basic key
name returned by {#key_name} will be used.
@return [Hash{String=>Array[String]}] a hash of region name to
an array of the keypair names that match for the filter
@api private | [
"Gets",
"the",
"Beaker",
"user",
"s",
"keypairs",
"by",
"region"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L908-L919 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.delete_key_pair | def delete_key_pair(region, pair_name)
kp = client(region).describe_key_pairs(:key_names => [pair_name]).key_pairs.first
unless kp.nil?
@logger.debug("aws-sdk: delete key pair in region: #{region}")
client(region).delete_key_pair(:key_name => pair_name)
end
rescue Aws::EC2::Errors::InvalidKeyPairNotFound
nil
end | ruby | def delete_key_pair(region, pair_name)
kp = client(region).describe_key_pairs(:key_names => [pair_name]).key_pairs.first
unless kp.nil?
@logger.debug("aws-sdk: delete key pair in region: #{region}")
client(region).delete_key_pair(:key_name => pair_name)
end
rescue Aws::EC2::Errors::InvalidKeyPairNotFound
nil
end | [
"def",
"delete_key_pair",
"(",
"region",
",",
"pair_name",
")",
"kp",
"=",
"client",
"(",
"region",
")",
".",
"describe_key_pairs",
"(",
":key_names",
"=>",
"[",
"pair_name",
"]",
")",
".",
"key_pairs",
".",
"first",
"unless",
"kp",
".",
"nil?",
"@logger",
".",
"debug",
"(",
"\"aws-sdk: delete key pair in region: #{region}\"",
")",
"client",
"(",
"region",
")",
".",
"delete_key_pair",
"(",
":key_name",
"=>",
"pair_name",
")",
"end",
"rescue",
"Aws",
"::",
"EC2",
"::",
"Errors",
"::",
"InvalidKeyPairNotFound",
"nil",
"end"
]
| Deletes a given key pair
@param [Aws::EC2::Region] region the region the key belongs to
@param [String] pair_name the name of the key to be deleted
@api private | [
"Deletes",
"a",
"given",
"key",
"pair"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L927-L935 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.create_new_key_pair | def create_new_key_pair(region, pair_name)
@logger.debug("aws-sdk: importing new key pair: #{pair_name}")
client(region).import_key_pair(:key_name => pair_name, :public_key_material => public_key)
begin
client(region).wait_until(:key_pair_exists, { :key_names => [pair_name] }, :max_attempts => 5, :delay => 2)
rescue Aws::Waiters::Errors::WaiterFailed
raise RuntimeError, "AWS key pair #{pair_name} can not be queried, even after import"
end
end | ruby | def create_new_key_pair(region, pair_name)
@logger.debug("aws-sdk: importing new key pair: #{pair_name}")
client(region).import_key_pair(:key_name => pair_name, :public_key_material => public_key)
begin
client(region).wait_until(:key_pair_exists, { :key_names => [pair_name] }, :max_attempts => 5, :delay => 2)
rescue Aws::Waiters::Errors::WaiterFailed
raise RuntimeError, "AWS key pair #{pair_name} can not be queried, even after import"
end
end | [
"def",
"create_new_key_pair",
"(",
"region",
",",
"pair_name",
")",
"@logger",
".",
"debug",
"(",
"\"aws-sdk: importing new key pair: #{pair_name}\"",
")",
"client",
"(",
"region",
")",
".",
"import_key_pair",
"(",
":key_name",
"=>",
"pair_name",
",",
":public_key_material",
"=>",
"public_key",
")",
"begin",
"client",
"(",
"region",
")",
".",
"wait_until",
"(",
":key_pair_exists",
",",
"{",
":key_names",
"=>",
"[",
"pair_name",
"]",
"}",
",",
":max_attempts",
"=>",
"5",
",",
":delay",
"=>",
"2",
")",
"rescue",
"Aws",
"::",
"Waiters",
"::",
"Errors",
"::",
"WaiterFailed",
"raise",
"RuntimeError",
",",
"\"AWS key pair #{pair_name} can not be queried, even after import\"",
"end",
"end"
]
| Create a new key pair for a given Beaker run
@param [Aws::EC2::Region] region the region the key pair will be imported into
@param [String] pair_name the name of the key to be created
@return [Aws::EC2::KeyPair] key pair created
@raise [RuntimeError] raised if AWS keypair not created | [
"Create",
"a",
"new",
"key",
"pair",
"for",
"a",
"given",
"Beaker",
"run"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L944-L953 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.group_id | def group_id(ports)
if ports.nil? or ports.empty?
raise ArgumentError, "Ports list cannot be nil or empty"
end
unless ports.is_a? Set
ports = Set.new(ports)
end
# Lolwut, #hash is inconsistent between ruby processes
"Beaker-#{Zlib.crc32(ports.inspect)}"
end | ruby | def group_id(ports)
if ports.nil? or ports.empty?
raise ArgumentError, "Ports list cannot be nil or empty"
end
unless ports.is_a? Set
ports = Set.new(ports)
end
# Lolwut, #hash is inconsistent between ruby processes
"Beaker-#{Zlib.crc32(ports.inspect)}"
end | [
"def",
"group_id",
"(",
"ports",
")",
"if",
"ports",
".",
"nil?",
"or",
"ports",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Ports list cannot be nil or empty\"",
"end",
"unless",
"ports",
".",
"is_a?",
"Set",
"ports",
"=",
"Set",
".",
"new",
"(",
"ports",
")",
"end",
"\"Beaker-#{Zlib.crc32(ports.inspect)}\"",
"end"
]
| Return a reproducable security group identifier based on input ports
@param ports [Array<Number>] array of port numbers
@return [String] group identifier
@api private | [
"Return",
"a",
"reproducable",
"security",
"group",
"identifier",
"based",
"on",
"input",
"ports"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L960-L971 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.create_ping_group | def create_ping_group(region_or_vpc, sg_cidr_ips = ['0.0.0.0/0'])
@logger.notify("aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => 'Custom Beaker security group to enable ping',
:group_name => PING_SECURITY_GROUP_NAME,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
sg_cidr_ips.each do |cidr_ip|
add_ingress_rule(
cl,
group,
cidr_ip,
'8', # 8 == ICMPv4 ECHO request
'-1', # -1 == All ICMP codes
'icmp',
)
end
group
end | ruby | def create_ping_group(region_or_vpc, sg_cidr_ips = ['0.0.0.0/0'])
@logger.notify("aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => 'Custom Beaker security group to enable ping',
:group_name => PING_SECURITY_GROUP_NAME,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
sg_cidr_ips.each do |cidr_ip|
add_ingress_rule(
cl,
group,
cidr_ip,
'8', # 8 == ICMPv4 ECHO request
'-1', # -1 == All ICMP codes
'icmp',
)
end
group
end | [
"def",
"create_ping_group",
"(",
"region_or_vpc",
",",
"sg_cidr_ips",
"=",
"[",
"'0.0.0.0/0'",
"]",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}\"",
")",
"cl",
"=",
"region_or_vpc",
".",
"is_a?",
"(",
"String",
")",
"?",
"client",
"(",
"region_or_vpc",
")",
":",
"client",
"params",
"=",
"{",
":description",
"=>",
"'Custom Beaker security group to enable ping'",
",",
":group_name",
"=>",
"PING_SECURITY_GROUP_NAME",
",",
"}",
"params",
"[",
":vpc_id",
"]",
"=",
"region_or_vpc",
".",
"vpc_id",
"if",
"region_or_vpc",
".",
"is_a?",
"(",
"Aws",
"::",
"EC2",
"::",
"Types",
"::",
"Vpc",
")",
"group",
"=",
"cl",
".",
"create_security_group",
"(",
"params",
")",
"sg_cidr_ips",
".",
"each",
"do",
"|",
"cidr_ip",
"|",
"add_ingress_rule",
"(",
"cl",
",",
"group",
",",
"cidr_ip",
",",
"'8'",
",",
"'-1'",
",",
"'icmp'",
",",
")",
"end",
"group",
"end"
]
| Create a new ping enabled security group
Accepts a region or VPC for group creation.
@param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object
@param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
@return [Aws::EC2::SecurityGroup] created security group
@api private | [
"Create",
"a",
"new",
"ping",
"enabled",
"security",
"group"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1033-L1057 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.create_group | def create_group(region_or_vpc, ports, sg_cidr_ips = ['0.0.0.0/0'])
name = group_id(ports)
@logger.notify("aws-sdk: Creating group #{name} for ports #{ports.to_s}")
@logger.notify("aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => "Custom Beaker security group for #{ports.to_a}",
:group_name => name,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
unless ports.is_a? Set
ports = Set.new(ports)
end
sg_cidr_ips.each do |cidr_ip|
ports.each do |port|
add_ingress_rule(cl, group, cidr_ip, port, port)
end
end
group
end | ruby | def create_group(region_or_vpc, ports, sg_cidr_ips = ['0.0.0.0/0'])
name = group_id(ports)
@logger.notify("aws-sdk: Creating group #{name} for ports #{ports.to_s}")
@logger.notify("aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => "Custom Beaker security group for #{ports.to_a}",
:group_name => name,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
unless ports.is_a? Set
ports = Set.new(ports)
end
sg_cidr_ips.each do |cidr_ip|
ports.each do |port|
add_ingress_rule(cl, group, cidr_ip, port, port)
end
end
group
end | [
"def",
"create_group",
"(",
"region_or_vpc",
",",
"ports",
",",
"sg_cidr_ips",
"=",
"[",
"'0.0.0.0/0'",
"]",
")",
"name",
"=",
"group_id",
"(",
"ports",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Creating group #{name} for ports #{ports.to_s}\"",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}\"",
")",
"cl",
"=",
"region_or_vpc",
".",
"is_a?",
"(",
"String",
")",
"?",
"client",
"(",
"region_or_vpc",
")",
":",
"client",
"params",
"=",
"{",
":description",
"=>",
"\"Custom Beaker security group for #{ports.to_a}\"",
",",
":group_name",
"=>",
"name",
",",
"}",
"params",
"[",
":vpc_id",
"]",
"=",
"region_or_vpc",
".",
"vpc_id",
"if",
"region_or_vpc",
".",
"is_a?",
"(",
"Aws",
"::",
"EC2",
"::",
"Types",
"::",
"Vpc",
")",
"group",
"=",
"cl",
".",
"create_security_group",
"(",
"params",
")",
"unless",
"ports",
".",
"is_a?",
"Set",
"ports",
"=",
"Set",
".",
"new",
"(",
"ports",
")",
"end",
"sg_cidr_ips",
".",
"each",
"do",
"|",
"cidr_ip",
"|",
"ports",
".",
"each",
"do",
"|",
"port",
"|",
"add_ingress_rule",
"(",
"cl",
",",
"group",
",",
"cidr_ip",
",",
"port",
",",
"port",
")",
"end",
"end",
"group",
"end"
]
| Create a new security group
Accepts a region or VPC for group creation.
@param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object
@param ports [Array<Number>] an array of port numbers
@param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
@return [Aws::EC2::SecurityGroup] created security group
@api private | [
"Create",
"a",
"new",
"security",
"group"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1068-L1094 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.add_ingress_rule | def add_ingress_rule(cl, sg_group, cidr_ip, from_port, to_port, protocol = 'tcp')
cl.authorize_security_group_ingress(
:cidr_ip => cidr_ip,
:ip_protocol => protocol,
:from_port => from_port,
:to_port => to_port,
:group_id => sg_group.group_id,
)
end | ruby | def add_ingress_rule(cl, sg_group, cidr_ip, from_port, to_port, protocol = 'tcp')
cl.authorize_security_group_ingress(
:cidr_ip => cidr_ip,
:ip_protocol => protocol,
:from_port => from_port,
:to_port => to_port,
:group_id => sg_group.group_id,
)
end | [
"def",
"add_ingress_rule",
"(",
"cl",
",",
"sg_group",
",",
"cidr_ip",
",",
"from_port",
",",
"to_port",
",",
"protocol",
"=",
"'tcp'",
")",
"cl",
".",
"authorize_security_group_ingress",
"(",
":cidr_ip",
"=>",
"cidr_ip",
",",
":ip_protocol",
"=>",
"protocol",
",",
":from_port",
"=>",
"from_port",
",",
":to_port",
"=>",
"to_port",
",",
":group_id",
"=>",
"sg_group",
".",
"group_id",
",",
")",
"end"
]
| Authorizes connections from certain CIDR to a range of ports
@param cl [Aws::EC2::Client]
@param sg_group [Aws::EC2::SecurityGroup] the AWS security group
@param cidr_ip [String] CIDR used for outbound security group rule
@param from_port [String] Starting Port number in the range
@param to_port [String] Ending Port number in the range
@return [void]
@api private | [
"Authorizes",
"connections",
"from",
"certain",
"CIDR",
"to",
"a",
"range",
"of",
"ports"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1105-L1113 | train |
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.load_fog_credentials | def load_fog_credentials(dot_fog = '.fog')
default = get_fog_credentials(dot_fog)
raise "You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_access_key_id]
raise "You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_secret_access_key]
Aws::Credentials.new(
default[:aws_access_key_id],
default[:aws_secret_access_key],
default[:aws_session_token]
)
end | ruby | def load_fog_credentials(dot_fog = '.fog')
default = get_fog_credentials(dot_fog)
raise "You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_access_key_id]
raise "You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_secret_access_key]
Aws::Credentials.new(
default[:aws_access_key_id],
default[:aws_secret_access_key],
default[:aws_session_token]
)
end | [
"def",
"load_fog_credentials",
"(",
"dot_fog",
"=",
"'.fog'",
")",
"default",
"=",
"get_fog_credentials",
"(",
"dot_fog",
")",
"raise",
"\"You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!\"",
"unless",
"default",
"[",
":aws_access_key_id",
"]",
"raise",
"\"You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!\"",
"unless",
"default",
"[",
":aws_secret_access_key",
"]",
"Aws",
"::",
"Credentials",
".",
"new",
"(",
"default",
"[",
":aws_access_key_id",
"]",
",",
"default",
"[",
":aws_secret_access_key",
"]",
",",
"default",
"[",
":aws_session_token",
"]",
")",
"end"
]
| Return a hash containing the fog credentials for EC2
@param dot_fog [String] dot fog path
@return [Aws::Credentials] ec2 credentials
@api private | [
"Return",
"a",
"hash",
"containing",
"the",
"fog",
"credentials",
"for",
"EC2"
]
| f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1142-L1153 | train |
terry90/rails_api_benchmark | lib/rails_api_benchmark/result_set.rb | RailsApiBenchmark.ResultSet.compute_relative_speed | def compute_relative_speed
@results = @results.map do |r|
avgs = averages
res = r[:results]
avg_rt = avgs[:response_time]
avg_rps = avgs[:req_per_sec]
f_rt = ((res[:response_time].to_f - avg_rt) / avg_rt * 100).round(1)
f_rps = ((res[:req_per_sec].to_f - avg_rps) / avg_rps * 100).round(1)
r.merge(factors: { response_time: f_rt, req_per_sec: f_rps })
end
end | ruby | def compute_relative_speed
@results = @results.map do |r|
avgs = averages
res = r[:results]
avg_rt = avgs[:response_time]
avg_rps = avgs[:req_per_sec]
f_rt = ((res[:response_time].to_f - avg_rt) / avg_rt * 100).round(1)
f_rps = ((res[:req_per_sec].to_f - avg_rps) / avg_rps * 100).round(1)
r.merge(factors: { response_time: f_rt, req_per_sec: f_rps })
end
end | [
"def",
"compute_relative_speed",
"@results",
"=",
"@results",
".",
"map",
"do",
"|",
"r",
"|",
"avgs",
"=",
"averages",
"res",
"=",
"r",
"[",
":results",
"]",
"avg_rt",
"=",
"avgs",
"[",
":response_time",
"]",
"avg_rps",
"=",
"avgs",
"[",
":req_per_sec",
"]",
"f_rt",
"=",
"(",
"(",
"res",
"[",
":response_time",
"]",
".",
"to_f",
"-",
"avg_rt",
")",
"/",
"avg_rt",
"*",
"100",
")",
".",
"round",
"(",
"1",
")",
"f_rps",
"=",
"(",
"(",
"res",
"[",
":req_per_sec",
"]",
".",
"to_f",
"-",
"avg_rps",
")",
"/",
"avg_rps",
"*",
"100",
")",
".",
"round",
"(",
"1",
")",
"r",
".",
"merge",
"(",
"factors",
":",
"{",
"response_time",
":",
"f_rt",
",",
"req_per_sec",
":",
"f_rps",
"}",
")",
"end",
"end"
]
| Returns only the results with the relative speed | [
"Returns",
"only",
"the",
"results",
"with",
"the",
"relative",
"speed"
]
| 2991765ff639b2efdf4aa1a56587247ed5ee22d0 | https://github.com/terry90/rails_api_benchmark/blob/2991765ff639b2efdf4aa1a56587247ed5ee22d0/lib/rails_api_benchmark/result_set.rb#L24-L36 | train |
jetrockets/attrio | lib/attrio/helpers.rb | Attrio.Helpers.symbolize_hash_keys | def symbolize_hash_keys(hash)
hash.inject({}) do |new_hash, (key, value)|
new_hash[(key.to_sym rescue key) || key] = value
new_hash
end
hash
end | ruby | def symbolize_hash_keys(hash)
hash.inject({}) do |new_hash, (key, value)|
new_hash[(key.to_sym rescue key) || key] = value
new_hash
end
hash
end | [
"def",
"symbolize_hash_keys",
"(",
"hash",
")",
"hash",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"new_hash",
",",
"(",
"key",
",",
"value",
")",
"|",
"new_hash",
"[",
"(",
"key",
".",
"to_sym",
"rescue",
"key",
")",
"||",
"key",
"]",
"=",
"value",
"new_hash",
"end",
"hash",
"end"
]
| note that returning hash without symbolizing anything
does not cause this to fail | [
"note",
"that",
"returning",
"hash",
"without",
"symbolizing",
"anything",
"does",
"not",
"cause",
"this",
"to",
"fail"
]
| 4e3abd7ac120d53483fcdcd15f89b01c57b22fd8 | https://github.com/jetrockets/attrio/blob/4e3abd7ac120d53483fcdcd15f89b01c57b22fd8/lib/attrio/helpers.rb#L17-L23 | train |
cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.start | def start
extract_and_configure
if config.managed?
@pid = spawn(config.env, *process_arguments)
# Wait for fcrepo to start
while !status
sleep 1
end
end
end | ruby | def start
extract_and_configure
if config.managed?
@pid = spawn(config.env, *process_arguments)
# Wait for fcrepo to start
while !status
sleep 1
end
end
end | [
"def",
"start",
"extract_and_configure",
"if",
"config",
".",
"managed?",
"@pid",
"=",
"spawn",
"(",
"config",
".",
"env",
",",
"*",
"process_arguments",
")",
"while",
"!",
"status",
"sleep",
"1",
"end",
"end",
"end"
]
| Start fcrepo and wait for it to become available | [
"Start",
"fcrepo",
"and",
"wait",
"for",
"it",
"to",
"become",
"available"
]
| 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L55-L65 | train |
cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.stop | def stop
if config.managed? && started?
Process.kill 'HUP', pid
# Wait for fcrepo to stop
while status
sleep 1
end
Process.waitpid(pid)
end
@pid = nil
end | ruby | def stop
if config.managed? && started?
Process.kill 'HUP', pid
# Wait for fcrepo to stop
while status
sleep 1
end
Process.waitpid(pid)
end
@pid = nil
end | [
"def",
"stop",
"if",
"config",
".",
"managed?",
"&&",
"started?",
"Process",
".",
"kill",
"'HUP'",
",",
"pid",
"while",
"status",
"sleep",
"1",
"end",
"Process",
".",
"waitpid",
"(",
"pid",
")",
"end",
"@pid",
"=",
"nil",
"end"
]
| Stop fcrepo and wait for it to finish exiting | [
"Stop",
"fcrepo",
"and",
"wait",
"for",
"it",
"to",
"finish",
"exiting"
]
| 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L69-L82 | train |
cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.status | def status
return true unless config.managed?
return false if pid.nil?
begin
Process.getpgid(pid)
rescue Errno::ESRCH
return false
end
begin
TCPSocket.new(host, port).close
Net::HTTP.start(host, port) do |http|
http.request(Net::HTTP::Get.new('/'))
end
true
rescue Errno::ECONNREFUSED, Errno::EINVAL
false
end
end | ruby | def status
return true unless config.managed?
return false if pid.nil?
begin
Process.getpgid(pid)
rescue Errno::ESRCH
return false
end
begin
TCPSocket.new(host, port).close
Net::HTTP.start(host, port) do |http|
http.request(Net::HTTP::Get.new('/'))
end
true
rescue Errno::ECONNREFUSED, Errno::EINVAL
false
end
end | [
"def",
"status",
"return",
"true",
"unless",
"config",
".",
"managed?",
"return",
"false",
"if",
"pid",
".",
"nil?",
"begin",
"Process",
".",
"getpgid",
"(",
"pid",
")",
"rescue",
"Errno",
"::",
"ESRCH",
"return",
"false",
"end",
"begin",
"TCPSocket",
".",
"new",
"(",
"host",
",",
"port",
")",
".",
"close",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"host",
",",
"port",
")",
"do",
"|",
"http",
"|",
"http",
".",
"request",
"(",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"'/'",
")",
")",
"end",
"true",
"rescue",
"Errno",
"::",
"ECONNREFUSED",
",",
"Errno",
"::",
"EINVAL",
"false",
"end",
"end"
]
| Check the status of a managed fcrepo service | [
"Check",
"the",
"status",
"of",
"a",
"managed",
"fcrepo",
"service"
]
| 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L95-L116 | train |
cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.clean! | def clean!
stop
remove_instance_dir!
FileUtils.remove_entry(config.download_path) if File.exists?(config.download_path)
FileUtils.remove_entry(config.tmp_save_dir, true) if File.exists? config.tmp_save_dir
md5.clean!
FileUtils.remove_entry(config.version_file) if File.exists? config.version_file
end | ruby | def clean!
stop
remove_instance_dir!
FileUtils.remove_entry(config.download_path) if File.exists?(config.download_path)
FileUtils.remove_entry(config.tmp_save_dir, true) if File.exists? config.tmp_save_dir
md5.clean!
FileUtils.remove_entry(config.version_file) if File.exists? config.version_file
end | [
"def",
"clean!",
"stop",
"remove_instance_dir!",
"FileUtils",
".",
"remove_entry",
"(",
"config",
".",
"download_path",
")",
"if",
"File",
".",
"exists?",
"(",
"config",
".",
"download_path",
")",
"FileUtils",
".",
"remove_entry",
"(",
"config",
".",
"tmp_save_dir",
",",
"true",
")",
"if",
"File",
".",
"exists?",
"config",
".",
"tmp_save_dir",
"md5",
".",
"clean!",
"FileUtils",
".",
"remove_entry",
"(",
"config",
".",
"version_file",
")",
"if",
"File",
".",
"exists?",
"config",
".",
"version_file",
"end"
]
| Clean up any files fcrepo_wrapper may have downloaded | [
"Clean",
"up",
"any",
"files",
"fcrepo_wrapper",
"may",
"have",
"downloaded"
]
| 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L154-L161 | train |
cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.remove_instance_dir! | def remove_instance_dir!
FileUtils.remove_entry(config.instance_dir, true) if File.exists? config.instance_dir
end | ruby | def remove_instance_dir!
FileUtils.remove_entry(config.instance_dir, true) if File.exists? config.instance_dir
end | [
"def",
"remove_instance_dir!",
"FileUtils",
".",
"remove_entry",
"(",
"config",
".",
"instance_dir",
",",
"true",
")",
"if",
"File",
".",
"exists?",
"config",
".",
"instance_dir",
"end"
]
| Clean up any files in the fcrepo instance dir | [
"Clean",
"up",
"any",
"files",
"in",
"the",
"fcrepo",
"instance",
"dir"
]
| 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L165-L167 | train |
cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.extract | def extract
return config.instance_dir if extracted?
jar_file = download
FileUtils.mkdir_p config.instance_dir
FileUtils.cp jar_file, config.binary_path
self.extracted_version = config.version
config.instance_dir
end | ruby | def extract
return config.instance_dir if extracted?
jar_file = download
FileUtils.mkdir_p config.instance_dir
FileUtils.cp jar_file, config.binary_path
self.extracted_version = config.version
config.instance_dir
end | [
"def",
"extract",
"return",
"config",
".",
"instance_dir",
"if",
"extracted?",
"jar_file",
"=",
"download",
"FileUtils",
".",
"mkdir_p",
"config",
".",
"instance_dir",
"FileUtils",
".",
"cp",
"jar_file",
",",
"config",
".",
"binary_path",
"self",
".",
"extracted_version",
"=",
"config",
".",
"version",
"config",
".",
"instance_dir",
"end"
]
| extract a copy of fcrepo to instance_dir
Does noting if fcrepo already exists at instance_dir
@return [String] instance_dir Directory where fcrepo has been installed | [
"extract",
"a",
"copy",
"of",
"fcrepo",
"to",
"instance_dir",
"Does",
"noting",
"if",
"fcrepo",
"already",
"exists",
"at",
"instance_dir"
]
| 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L182-L192 | train |
emonti/rbkb | lib/rbkb/cli.rb | Rbkb::Cli.Executable.exit | def exit(ret)
@exit_status = ret
if defined? Rbkb::Cli::TESTING
throw(((ret==0)? :exit_zero : :exit_err), ret)
else
Kernel.exit(ret)
end
end | ruby | def exit(ret)
@exit_status = ret
if defined? Rbkb::Cli::TESTING
throw(((ret==0)? :exit_zero : :exit_err), ret)
else
Kernel.exit(ret)
end
end | [
"def",
"exit",
"(",
"ret",
")",
"@exit_status",
"=",
"ret",
"if",
"defined?",
"Rbkb",
"::",
"Cli",
"::",
"TESTING",
"throw",
"(",
"(",
"(",
"ret",
"==",
"0",
")",
"?",
":exit_zero",
":",
":exit_err",
")",
",",
"ret",
")",
"else",
"Kernel",
".",
"exit",
"(",
"ret",
")",
"end",
"end"
]
| Instantiates a new Executable object.
The 'param' argument is a named value hash. The following keys are
significant:
:argv - An array of cli arguments (default ARGV)
:opts - executable/function options for use when running 'go'
:stdout, - IO redirection (mostly for unit tests)
:stderr,
:stdin
The above keys are deleted from the 'param' hash and stored as instance
variables with attr_accessors. All other parameters are ignored.
Wrapper for Kernel.exit() so we can unit test cli tools | [
"Instantiates",
"a",
"new",
"Executable",
"object",
"."
]
| a6d35c0fd785bae135034502b1d07ed626aebde5 | https://github.com/emonti/rbkb/blob/a6d35c0fd785bae135034502b1d07ed626aebde5/lib/rbkb/cli.rb#L48-L55 | train |
emonti/rbkb | lib/rbkb/cli.rb | Rbkb::Cli.Executable.add_range_opts | def add_range_opts(fkey, lkey)
@oparse.on("-r", "--range=START[:END]",
"Start and optional end range") do |r|
raise "-x and -r are mutually exclusive" if @parser_got_range
@parser_got_range=true
unless /^(-?[0-9]+)(?::(-?[0-9]+))?$/.match(r)
raise "invalid range #{r.inspect}"
end
@opts[fkey] = $1.to_i
@opts[lkey] = $2.to_i if $2
end
@oparse.on("-x", "--hexrange=START[:END]",
"Start and optional end range in hex") do |r|
raise "-x and -r are mutually exclusive" if @parser_got_range
@parser_got_range=true
unless /^(-?[0-9a-f]+)(?::(-?[0-9a-f]+))?$/i.match(r)
raise "invalid range #{r.inspect}"
end
@opts[fkey] =
if ($1[0,1] == '-')
($1[1..-1]).hex_to_num * -1
else
$1.hex_to_num
end
if $2
@opts[lkey] =
if($2[0,1] == '-')
$2[1..-1].hex_to_num * -1
else
$2.hex_to_num
end
end
end
end | ruby | def add_range_opts(fkey, lkey)
@oparse.on("-r", "--range=START[:END]",
"Start and optional end range") do |r|
raise "-x and -r are mutually exclusive" if @parser_got_range
@parser_got_range=true
unless /^(-?[0-9]+)(?::(-?[0-9]+))?$/.match(r)
raise "invalid range #{r.inspect}"
end
@opts[fkey] = $1.to_i
@opts[lkey] = $2.to_i if $2
end
@oparse.on("-x", "--hexrange=START[:END]",
"Start and optional end range in hex") do |r|
raise "-x and -r are mutually exclusive" if @parser_got_range
@parser_got_range=true
unless /^(-?[0-9a-f]+)(?::(-?[0-9a-f]+))?$/i.match(r)
raise "invalid range #{r.inspect}"
end
@opts[fkey] =
if ($1[0,1] == '-')
($1[1..-1]).hex_to_num * -1
else
$1.hex_to_num
end
if $2
@opts[lkey] =
if($2[0,1] == '-')
$2[1..-1].hex_to_num * -1
else
$2.hex_to_num
end
end
end
end | [
"def",
"add_range_opts",
"(",
"fkey",
",",
"lkey",
")",
"@oparse",
".",
"on",
"(",
"\"-r\"",
",",
"\"--range=START[:END]\"",
",",
"\"Start and optional end range\"",
")",
"do",
"|",
"r",
"|",
"raise",
"\"-x and -r are mutually exclusive\"",
"if",
"@parser_got_range",
"@parser_got_range",
"=",
"true",
"unless",
"/",
"/",
".",
"match",
"(",
"r",
")",
"raise",
"\"invalid range #{r.inspect}\"",
"end",
"@opts",
"[",
"fkey",
"]",
"=",
"$1",
".",
"to_i",
"@opts",
"[",
"lkey",
"]",
"=",
"$2",
".",
"to_i",
"if",
"$2",
"end",
"@oparse",
".",
"on",
"(",
"\"-x\"",
",",
"\"--hexrange=START[:END]\"",
",",
"\"Start and optional end range in hex\"",
")",
"do",
"|",
"r",
"|",
"raise",
"\"-x and -r are mutually exclusive\"",
"if",
"@parser_got_range",
"@parser_got_range",
"=",
"true",
"unless",
"/",
"/i",
".",
"match",
"(",
"r",
")",
"raise",
"\"invalid range #{r.inspect}\"",
"end",
"@opts",
"[",
"fkey",
"]",
"=",
"if",
"(",
"$1",
"[",
"0",
",",
"1",
"]",
"==",
"'-'",
")",
"(",
"$1",
"[",
"1",
"..",
"-",
"1",
"]",
")",
".",
"hex_to_num",
"*",
"-",
"1",
"else",
"$1",
".",
"hex_to_num",
"end",
"if",
"$2",
"@opts",
"[",
"lkey",
"]",
"=",
"if",
"(",
"$2",
"[",
"0",
",",
"1",
"]",
"==",
"'-'",
")",
"$2",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"hex_to_num",
"*",
"-",
"1",
"else",
"$2",
".",
"hex_to_num",
"end",
"end",
"end",
"end"
]
| Implements numeric and hex range options via '-r' and '-x'
Takes two arguments which are the @opts hash key names for
first and last parameters.
(Used commonly throughout several executables) | [
"Implements",
"numeric",
"and",
"hex",
"range",
"options",
"via",
"-",
"r",
"and",
"-",
"x"
]
| a6d35c0fd785bae135034502b1d07ed626aebde5 | https://github.com/emonti/rbkb/blob/a6d35c0fd785bae135034502b1d07ed626aebde5/lib/rbkb/cli.rb#L148-L189 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.create_transaction | def create_transaction(payment_method, transaction)
unless get_valid?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateTransactionResponse)
end
begin
case payment_method
when Enums::PaymentMethod::DIRECT
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransDirectPaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransDirectPaymentMsgProcess.make_result(response)
when Enums::PaymentMethod::RESPONSIVE_SHARED
url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransResponsiveSharedMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransResponsiveSharedMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransResponsiveSharedMsgProcess.make_result(response)
when Enums::PaymentMethod::TRANSPARENT_REDIRECT
url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransTransparentRedirectMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransTransparentRedirectMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransTransparentRedirectMsgProcess.make_result(response)
when Enums::PaymentMethod::WALLET
if transaction.capture
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransDirectPaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransDirectPaymentMsgProcess.make_result(response)
else
url = @web_url + Constants::CAPTURE_PAYMENT_METHOD
request = Message::TransactionProcess::CapturePaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::CapturePaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::CapturePaymentMsgProcess.make_result(response)
end
when Enums::PaymentMethod::AUTHORISATION
url = @web_url + Constants::CAPTURE_PAYMENT_METHOD
request = Message::TransactionProcess::CapturePaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::CapturePaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::CapturePaymentMsgProcess.make_result(response)
else
make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateTransactionResponse)
end
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, CreateTransactionResponse)
end
end | ruby | def create_transaction(payment_method, transaction)
unless get_valid?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateTransactionResponse)
end
begin
case payment_method
when Enums::PaymentMethod::DIRECT
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransDirectPaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransDirectPaymentMsgProcess.make_result(response)
when Enums::PaymentMethod::RESPONSIVE_SHARED
url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransResponsiveSharedMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransResponsiveSharedMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransResponsiveSharedMsgProcess.make_result(response)
when Enums::PaymentMethod::TRANSPARENT_REDIRECT
url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransTransparentRedirectMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransTransparentRedirectMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransTransparentRedirectMsgProcess.make_result(response)
when Enums::PaymentMethod::WALLET
if transaction.capture
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::TransactionProcess::TransDirectPaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::TransDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::TransDirectPaymentMsgProcess.make_result(response)
else
url = @web_url + Constants::CAPTURE_PAYMENT_METHOD
request = Message::TransactionProcess::CapturePaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::CapturePaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::CapturePaymentMsgProcess.make_result(response)
end
when Enums::PaymentMethod::AUTHORISATION
url = @web_url + Constants::CAPTURE_PAYMENT_METHOD
request = Message::TransactionProcess::CapturePaymentMsgProcess.create_request(transaction)
response = Message::TransactionProcess::CapturePaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::TransactionProcess::CapturePaymentMsgProcess.make_result(response)
else
make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateTransactionResponse)
end
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, CreateTransactionResponse)
end
end | [
"def",
"create_transaction",
"(",
"payment_method",
",",
"transaction",
")",
"unless",
"get_valid?",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'API key, password or Rapid endpoint missing or invalid'",
")",
",",
"CreateTransactionResponse",
")",
"end",
"begin",
"case",
"payment_method",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"DIRECT",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"DIRECT_PAYMENT_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransDirectPaymentMsgProcess",
".",
"create_request",
"(",
"transaction",
")",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransDirectPaymentMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"TransactionProcess",
"::",
"TransDirectPaymentMsgProcess",
".",
"make_result",
"(",
"response",
")",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"RESPONSIVE_SHARED",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"RESPONSIVE_SHARED_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransResponsiveSharedMsgProcess",
".",
"create_request",
"(",
"transaction",
")",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransResponsiveSharedMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"TransactionProcess",
"::",
"TransResponsiveSharedMsgProcess",
".",
"make_result",
"(",
"response",
")",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"TRANSPARENT_REDIRECT",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"TRANSPARENT_REDIRECT_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransTransparentRedirectMsgProcess",
".",
"create_request",
"(",
"transaction",
")",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransTransparentRedirectMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"TransactionProcess",
"::",
"TransTransparentRedirectMsgProcess",
".",
"make_result",
"(",
"response",
")",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"WALLET",
"if",
"transaction",
".",
"capture",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"DIRECT_PAYMENT_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransDirectPaymentMsgProcess",
".",
"create_request",
"(",
"transaction",
")",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransDirectPaymentMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"TransactionProcess",
"::",
"TransDirectPaymentMsgProcess",
".",
"make_result",
"(",
"response",
")",
"else",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"CAPTURE_PAYMENT_METHOD",
"request",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"CapturePaymentMsgProcess",
".",
"create_request",
"(",
"transaction",
")",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"CapturePaymentMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"TransactionProcess",
"::",
"CapturePaymentMsgProcess",
".",
"make_result",
"(",
"response",
")",
"end",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"AUTHORISATION",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"CAPTURE_PAYMENT_METHOD",
"request",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"CapturePaymentMsgProcess",
".",
"create_request",
"(",
"transaction",
")",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"CapturePaymentMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"TransactionProcess",
"::",
"CapturePaymentMsgProcess",
".",
"make_result",
"(",
"response",
")",
"else",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"ParameterInvalidException",
".",
"new",
"(",
"'Unsupported payment type'",
")",
",",
"CreateTransactionResponse",
")",
"end",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"(",
"e",
".",
"to_s",
")",
"if",
"@logger",
"make_response_with_exception",
"(",
"e",
",",
"CreateTransactionResponse",
")",
"end",
"end"
]
| Creates a transaction either using an authorisation, the responsive shared
page, transparent redirect, or direct as the source of funds
@param [Enums::PaymentMethod] payment_method Describes where the card details will be coming from for this transaction (Direct, Responsive Shared, Transparent Redirect etc)
@param [Models::Transaction] transaction Request containing the transaction details
@return [CreateTransactionResponse] CreateTransactionResponse | [
"Creates",
"a",
"transaction",
"either",
"using",
"an",
"authorisation",
"the",
"responsive",
"shared",
"page",
"transparent",
"redirect",
"or",
"direct",
"as",
"the",
"source",
"of",
"funds"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L48-L99 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.query_transaction_by_filter | def query_transaction_by_filter(filter)
index_of_value = filter.calculate_index_of_value
if index_of_value.nil?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('Invalid transaction filter'), QueryTransactionResponse)
end
case index_of_value
when Enums::TransactionFilter::TRANSACTION_ID_INDEX
query_transaction_by_id(filter.transaction_id.to_s)
when Enums::TransactionFilter::ACCESS_CODE_INDEX
query_transaction_by_access_code(filter.access_code)
when Enums::TransactionFilter::INVOICE_NUMBER_INDEX
query_transaction_with_path(filter.invoice_number, Constants::TRANSACTION_METHOD + '/' + Constants::TRANSACTION_QUERY_WITH_INVOICE_NUM_METHOD)
when Enums::TransactionFilter::INVOICE_REFERENCE_INDEX
query_transaction_with_path(filter.invoice_reference, Constants::TRANSACTION_METHOD + '/' + Constants::TRANSACTION_QUERY_WITH_INVOICE_REF_METHOD)
else
make_response_with_exception(Exceptions::APIKeyInvalidException.new('Invalid transaction filter'), QueryTransactionResponse)
end
end | ruby | def query_transaction_by_filter(filter)
index_of_value = filter.calculate_index_of_value
if index_of_value.nil?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('Invalid transaction filter'), QueryTransactionResponse)
end
case index_of_value
when Enums::TransactionFilter::TRANSACTION_ID_INDEX
query_transaction_by_id(filter.transaction_id.to_s)
when Enums::TransactionFilter::ACCESS_CODE_INDEX
query_transaction_by_access_code(filter.access_code)
when Enums::TransactionFilter::INVOICE_NUMBER_INDEX
query_transaction_with_path(filter.invoice_number, Constants::TRANSACTION_METHOD + '/' + Constants::TRANSACTION_QUERY_WITH_INVOICE_NUM_METHOD)
when Enums::TransactionFilter::INVOICE_REFERENCE_INDEX
query_transaction_with_path(filter.invoice_reference, Constants::TRANSACTION_METHOD + '/' + Constants::TRANSACTION_QUERY_WITH_INVOICE_REF_METHOD)
else
make_response_with_exception(Exceptions::APIKeyInvalidException.new('Invalid transaction filter'), QueryTransactionResponse)
end
end | [
"def",
"query_transaction_by_filter",
"(",
"filter",
")",
"index_of_value",
"=",
"filter",
".",
"calculate_index_of_value",
"if",
"index_of_value",
".",
"nil?",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'Invalid transaction filter'",
")",
",",
"QueryTransactionResponse",
")",
"end",
"case",
"index_of_value",
"when",
"Enums",
"::",
"TransactionFilter",
"::",
"TRANSACTION_ID_INDEX",
"query_transaction_by_id",
"(",
"filter",
".",
"transaction_id",
".",
"to_s",
")",
"when",
"Enums",
"::",
"TransactionFilter",
"::",
"ACCESS_CODE_INDEX",
"query_transaction_by_access_code",
"(",
"filter",
".",
"access_code",
")",
"when",
"Enums",
"::",
"TransactionFilter",
"::",
"INVOICE_NUMBER_INDEX",
"query_transaction_with_path",
"(",
"filter",
".",
"invoice_number",
",",
"Constants",
"::",
"TRANSACTION_METHOD",
"+",
"'/'",
"+",
"Constants",
"::",
"TRANSACTION_QUERY_WITH_INVOICE_NUM_METHOD",
")",
"when",
"Enums",
"::",
"TransactionFilter",
"::",
"INVOICE_REFERENCE_INDEX",
"query_transaction_with_path",
"(",
"filter",
".",
"invoice_reference",
",",
"Constants",
"::",
"TRANSACTION_METHOD",
"+",
"'/'",
"+",
"Constants",
"::",
"TRANSACTION_QUERY_WITH_INVOICE_REF_METHOD",
")",
"else",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'Invalid transaction filter'",
")",
",",
"QueryTransactionResponse",
")",
"end",
"end"
]
| Query a transaction by one of four properties transaction id, access
code, invoice number, invoice reference
@param [Enums::TransactionFilter] filter Filter definition for searching
@return [QueryTransactionResponse] | [
"Query",
"a",
"transaction",
"by",
"one",
"of",
"four",
"properties",
"transaction",
"id",
"access",
"code",
"invoice",
"number",
"invoice",
"reference"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L122-L140 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.refund | def refund(refund)
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), RefundResponse)
end
begin
url = @web_url + Constants::TRANSACTION_METHOD
request = Message::RefundProcess::RefundMsgProcess.create_request(refund)
response = Message::RefundProcess::RefundMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::RefundProcess::RefundMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, RefundResponse)
end
end | ruby | def refund(refund)
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), RefundResponse)
end
begin
url = @web_url + Constants::TRANSACTION_METHOD
request = Message::RefundProcess::RefundMsgProcess.create_request(refund)
response = Message::RefundProcess::RefundMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::RefundProcess::RefundMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, RefundResponse)
end
end | [
"def",
"refund",
"(",
"refund",
")",
"unless",
"@is_valid",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'API key, password or Rapid endpoint missing or invalid'",
")",
",",
"RefundResponse",
")",
"end",
"begin",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"TRANSACTION_METHOD",
"request",
"=",
"Message",
"::",
"RefundProcess",
"::",
"RefundMsgProcess",
".",
"create_request",
"(",
"refund",
")",
"response",
"=",
"Message",
"::",
"RefundProcess",
"::",
"RefundMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"RefundProcess",
"::",
"RefundMsgProcess",
".",
"make_result",
"(",
"response",
")",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"(",
"e",
".",
"to_s",
")",
"if",
"@logger",
"make_response_with_exception",
"(",
"e",
",",
"RefundResponse",
")",
"end",
"end"
]
| Refunds all or part of a transaction
@param [Models::Refund] refund contains information to refund
@return [RefundResponse] | [
"Refunds",
"all",
"or",
"part",
"of",
"a",
"transaction"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L146-L161 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.create_customer | def create_customer(payment_method, customer)
unless get_valid?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateCustomerResponse)
end
begin
case payment_method
when Enums::PaymentMethod::DIRECT
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustDirectPaymentMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustDirectPaymentMsgProcess.make_result(response)
when Enums::PaymentMethod::RESPONSIVE_SHARED
url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustResponsiveSharedMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustResponsiveSharedMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustResponsiveSharedMsgProcess.make_result(response)
when Enums::PaymentMethod::TRANSPARENT_REDIRECT
url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustTransparentRedirectMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustTransparentRedirectMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustTransparentRedirectMsgProcess.make_result(response)
else
make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateCustomerResponse)
end
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, CreateCustomerResponse)
end
end | ruby | def create_customer(payment_method, customer)
unless get_valid?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateCustomerResponse)
end
begin
case payment_method
when Enums::PaymentMethod::DIRECT
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustDirectPaymentMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustDirectPaymentMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustDirectPaymentMsgProcess.make_result(response)
when Enums::PaymentMethod::RESPONSIVE_SHARED
url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustResponsiveSharedMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustResponsiveSharedMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustResponsiveSharedMsgProcess.make_result(response)
when Enums::PaymentMethod::TRANSPARENT_REDIRECT
url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustTransparentRedirectMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustTransparentRedirectMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustTransparentRedirectMsgProcess.make_result(response)
else
make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateCustomerResponse)
end
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, CreateCustomerResponse)
end
end | [
"def",
"create_customer",
"(",
"payment_method",
",",
"customer",
")",
"unless",
"get_valid?",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'API key, password or Rapid endpoint missing or invalid'",
")",
",",
"CreateCustomerResponse",
")",
"end",
"begin",
"case",
"payment_method",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"DIRECT",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"DIRECT_PAYMENT_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustDirectPaymentMsgProcess",
".",
"create_request",
"(",
"customer",
")",
"response",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustDirectPaymentMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"CustomerProcess",
"::",
"CustDirectPaymentMsgProcess",
".",
"make_result",
"(",
"response",
")",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"RESPONSIVE_SHARED",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"RESPONSIVE_SHARED_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustResponsiveSharedMsgProcess",
".",
"create_request",
"(",
"customer",
")",
"response",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustResponsiveSharedMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"CustomerProcess",
"::",
"CustResponsiveSharedMsgProcess",
".",
"make_result",
"(",
"response",
")",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"TRANSPARENT_REDIRECT",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"TRANSPARENT_REDIRECT_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustTransparentRedirectMsgProcess",
".",
"create_request",
"(",
"customer",
")",
"response",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustTransparentRedirectMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"CustomerProcess",
"::",
"CustTransparentRedirectMsgProcess",
".",
"make_result",
"(",
"response",
")",
"else",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"ParameterInvalidException",
".",
"new",
"(",
"'Unsupported payment type'",
")",
",",
"CreateCustomerResponse",
")",
"end",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"(",
"e",
".",
"to_s",
")",
"if",
"@logger",
"make_response_with_exception",
"(",
"e",
",",
"CreateCustomerResponse",
")",
"end",
"end"
]
| Creates a token customer to store card details in the secure eWAY Vault
for charging later
@param [Enums::PaymentMethod] payment_method Describes where the card details will be coming from for this transaction (Direct, Responsive Shared, Transparent Redirect etc).
@param [Models::Customer] customer The customer's details
@return [CreateCustomerResponse] | [
"Creates",
"a",
"token",
"customer",
"to",
"store",
"card",
"details",
"in",
"the",
"secure",
"eWAY",
"Vault",
"for",
"charging",
"later"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L189-L220 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.update_customer | def update_customer(payment_method, customer)
unless get_valid?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateCustomerResponse)
end
begin
case payment_method
when Enums::PaymentMethod::DIRECT
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustDirectUpdateMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustDirectUpdateMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustDirectUpdateMsgProcess.make_result(response)
when Enums::PaymentMethod::RESPONSIVE_SHARED
url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustResponsiveUpdateMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustResponsiveUpdateMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustResponsiveUpdateMsgProcess.make_result(response)
when Enums::PaymentMethod::TRANSPARENT_REDIRECT
url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustTransparentUpdateMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustTransparentUpdateMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustTransparentUpdateMsgProcess.make_result(response)
else
return make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateCustomerResponse)
end
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, CreateCustomerResponse)
end
end | ruby | def update_customer(payment_method, customer)
unless get_valid?
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), CreateCustomerResponse)
end
begin
case payment_method
when Enums::PaymentMethod::DIRECT
url = @web_url + Constants::DIRECT_PAYMENT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustDirectUpdateMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustDirectUpdateMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustDirectUpdateMsgProcess.make_result(response)
when Enums::PaymentMethod::RESPONSIVE_SHARED
url = @web_url + Constants::RESPONSIVE_SHARED_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustResponsiveUpdateMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustResponsiveUpdateMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustResponsiveUpdateMsgProcess.make_result(response)
when Enums::PaymentMethod::TRANSPARENT_REDIRECT
url = @web_url + Constants::TRANSPARENT_REDIRECT_METHOD_NAME + Constants::JSON_SUFFIX
request = Message::CustomerProcess::CustTransparentUpdateMsgProcess.create_request(customer)
response = Message::CustomerProcess::CustTransparentUpdateMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::CustTransparentUpdateMsgProcess.make_result(response)
else
return make_response_with_exception(Exceptions::ParameterInvalidException.new('Unsupported payment type'), CreateCustomerResponse)
end
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, CreateCustomerResponse)
end
end | [
"def",
"update_customer",
"(",
"payment_method",
",",
"customer",
")",
"unless",
"get_valid?",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'API key, password or Rapid endpoint missing or invalid'",
")",
",",
"CreateCustomerResponse",
")",
"end",
"begin",
"case",
"payment_method",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"DIRECT",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"DIRECT_PAYMENT_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustDirectUpdateMsgProcess",
".",
"create_request",
"(",
"customer",
")",
"response",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustDirectUpdateMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"CustomerProcess",
"::",
"CustDirectUpdateMsgProcess",
".",
"make_result",
"(",
"response",
")",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"RESPONSIVE_SHARED",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"RESPONSIVE_SHARED_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustResponsiveUpdateMsgProcess",
".",
"create_request",
"(",
"customer",
")",
"response",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustResponsiveUpdateMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"CustomerProcess",
"::",
"CustResponsiveUpdateMsgProcess",
".",
"make_result",
"(",
"response",
")",
"when",
"Enums",
"::",
"PaymentMethod",
"::",
"TRANSPARENT_REDIRECT",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"TRANSPARENT_REDIRECT_METHOD_NAME",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"request",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustTransparentUpdateMsgProcess",
".",
"create_request",
"(",
"customer",
")",
"response",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"CustTransparentUpdateMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"CustomerProcess",
"::",
"CustTransparentUpdateMsgProcess",
".",
"make_result",
"(",
"response",
")",
"else",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"ParameterInvalidException",
".",
"new",
"(",
"'Unsupported payment type'",
")",
",",
"CreateCustomerResponse",
")",
"end",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"(",
"e",
".",
"to_s",
")",
"if",
"@logger",
"make_response_with_exception",
"(",
"e",
",",
"CreateCustomerResponse",
")",
"end",
"end"
]
| Updates an existing token customer for the merchant in their eWAY account.
@param [Enums::PaymentMethod] payment_method Describes where the card details will be coming from for this transaction (Direct, Responsive Shared, Transparent Redirect etc).
@param [Models::Customer] customer The customer's details
@return [CreateCustomerResponse] | [
"Updates",
"an",
"existing",
"token",
"customer",
"for",
"the",
"merchant",
"in",
"their",
"eWAY",
"account",
"."
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L227-L257 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.query_customer | def query_customer(token_customer_id)
@logger.debug('Query customer with id:' + token_customer_id.to_s) if @logger
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryCustomerResponse)
end
begin
url = @web_url + Constants::DIRECT_CUSTOMER_SEARCH_METHOD + Constants::JSON_SUFFIX
url = URI.encode(url)
request = Message::CustomerProcess::QueryCustomerMsgProcess.create_request(token_customer_id.to_s)
response = Message::CustomerProcess::QueryCustomerMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::QueryCustomerMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, QueryCustomerResponse)
end
end | ruby | def query_customer(token_customer_id)
@logger.debug('Query customer with id:' + token_customer_id.to_s) if @logger
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryCustomerResponse)
end
begin
url = @web_url + Constants::DIRECT_CUSTOMER_SEARCH_METHOD + Constants::JSON_SUFFIX
url = URI.encode(url)
request = Message::CustomerProcess::QueryCustomerMsgProcess.create_request(token_customer_id.to_s)
response = Message::CustomerProcess::QueryCustomerMsgProcess.send_request(url, @api_key, @password, @version, request)
Message::CustomerProcess::QueryCustomerMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, QueryCustomerResponse)
end
end | [
"def",
"query_customer",
"(",
"token_customer_id",
")",
"@logger",
".",
"debug",
"(",
"'Query customer with id:'",
"+",
"token_customer_id",
".",
"to_s",
")",
"if",
"@logger",
"unless",
"@is_valid",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'API key, password or Rapid endpoint missing or invalid'",
")",
",",
"QueryCustomerResponse",
")",
"end",
"begin",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"DIRECT_CUSTOMER_SEARCH_METHOD",
"+",
"Constants",
"::",
"JSON_SUFFIX",
"url",
"=",
"URI",
".",
"encode",
"(",
"url",
")",
"request",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"QueryCustomerMsgProcess",
".",
"create_request",
"(",
"token_customer_id",
".",
"to_s",
")",
"response",
"=",
"Message",
"::",
"CustomerProcess",
"::",
"QueryCustomerMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
",",
"request",
")",
"Message",
"::",
"CustomerProcess",
"::",
"QueryCustomerMsgProcess",
".",
"make_result",
"(",
"response",
")",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"(",
"e",
".",
"to_s",
")",
"if",
"@logger",
"make_response_with_exception",
"(",
"e",
",",
"QueryCustomerResponse",
")",
"end",
"end"
]
| Returns the details of a Token Customer. This includes the masked card information
for displaying in a UI
@param [Integer] token_customer_id eWAY Token Customer ID to look up.
@return [QueryCustomerResponse] | [
"Returns",
"the",
"details",
"of",
"a",
"Token",
"Customer",
".",
"This",
"includes",
"the",
"masked",
"card",
"information",
"for",
"displaying",
"in",
"a",
"UI"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L264-L280 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.settlement_search | def settlement_search(search_request)
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryCustomerResponse)
end
begin
request = Message::TransactionProcess::SettlementSearchMsgProcess.create_request(search_request)
url = @web_url + Constants::SETTLEMENT_SEARCH_METHOD + request
response = Message::TransactionProcess::SettlementSearchMsgProcess.send_request(url, @api_key, @password, @version)
Message::TransactionProcess::SettlementSearchMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, SettlementSearchResponse)
end
end | ruby | def settlement_search(search_request)
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryCustomerResponse)
end
begin
request = Message::TransactionProcess::SettlementSearchMsgProcess.create_request(search_request)
url = @web_url + Constants::SETTLEMENT_SEARCH_METHOD + request
response = Message::TransactionProcess::SettlementSearchMsgProcess.send_request(url, @api_key, @password, @version)
Message::TransactionProcess::SettlementSearchMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, SettlementSearchResponse)
end
end | [
"def",
"settlement_search",
"(",
"search_request",
")",
"unless",
"@is_valid",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'API key, password or Rapid endpoint missing or invalid'",
")",
",",
"QueryCustomerResponse",
")",
"end",
"begin",
"request",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"SettlementSearchMsgProcess",
".",
"create_request",
"(",
"search_request",
")",
"url",
"=",
"@web_url",
"+",
"Constants",
"::",
"SETTLEMENT_SEARCH_METHOD",
"+",
"request",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"SettlementSearchMsgProcess",
".",
"send_request",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
")",
"Message",
"::",
"TransactionProcess",
"::",
"SettlementSearchMsgProcess",
".",
"make_result",
"(",
"response",
")",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"(",
"e",
".",
"to_s",
")",
"if",
"@logger",
"make_response_with_exception",
"(",
"e",
",",
"SettlementSearchResponse",
")",
"end",
"end"
]
| Performs a search of settlements
@param [SettlementSearch]
@return [SettlementSearchResponse] | [
"Performs",
"a",
"search",
"of",
"settlements"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L286-L302 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.query_transaction_with_path | def query_transaction_with_path(request, request_path)
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryTransactionResponse)
end
begin
if request.nil? || request == ''
url = @web_url + request_path + '/' + '0'
else
url = @web_url + request_path + '/' + request
end
url = URI.encode(url)
response = Message::TransactionProcess::TransQueryMsgProcess.process_post_msg(url, @api_key, @password, @version)
Message::TransactionProcess::TransQueryMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, QueryTransactionResponse)
end
end | ruby | def query_transaction_with_path(request, request_path)
unless @is_valid
return make_response_with_exception(Exceptions::APIKeyInvalidException.new('API key, password or Rapid endpoint missing or invalid'), QueryTransactionResponse)
end
begin
if request.nil? || request == ''
url = @web_url + request_path + '/' + '0'
else
url = @web_url + request_path + '/' + request
end
url = URI.encode(url)
response = Message::TransactionProcess::TransQueryMsgProcess.process_post_msg(url, @api_key, @password, @version)
Message::TransactionProcess::TransQueryMsgProcess.make_result(response)
rescue => e
@logger.error(e.to_s) if @logger
make_response_with_exception(e, QueryTransactionResponse)
end
end | [
"def",
"query_transaction_with_path",
"(",
"request",
",",
"request_path",
")",
"unless",
"@is_valid",
"return",
"make_response_with_exception",
"(",
"Exceptions",
"::",
"APIKeyInvalidException",
".",
"new",
"(",
"'API key, password or Rapid endpoint missing or invalid'",
")",
",",
"QueryTransactionResponse",
")",
"end",
"begin",
"if",
"request",
".",
"nil?",
"||",
"request",
"==",
"''",
"url",
"=",
"@web_url",
"+",
"request_path",
"+",
"'/'",
"+",
"'0'",
"else",
"url",
"=",
"@web_url",
"+",
"request_path",
"+",
"'/'",
"+",
"request",
"end",
"url",
"=",
"URI",
".",
"encode",
"(",
"url",
")",
"response",
"=",
"Message",
"::",
"TransactionProcess",
"::",
"TransQueryMsgProcess",
".",
"process_post_msg",
"(",
"url",
",",
"@api_key",
",",
"@password",
",",
"@version",
")",
"Message",
"::",
"TransactionProcess",
"::",
"TransQueryMsgProcess",
".",
"make_result",
"(",
"response",
")",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"(",
"e",
".",
"to_s",
")",
"if",
"@logger",
"make_response_with_exception",
"(",
"e",
",",
"QueryTransactionResponse",
")",
"end",
"end"
]
| Perform a transaction query with the given path
@param [String] request the transaction identifier to query
@param [String] request_path the path to use for the query
@return [QueryTransactionResponse] | [
"Perform",
"a",
"transaction",
"query",
"with",
"the",
"given",
"path"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L334-L352 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.validate_api_param | def validate_api_param
set_valid(true)
if @api_key.nil? || @api_key.empty? || @password.nil? || @password.empty?
add_error_code(Constants::API_KEY_INVALID_ERROR_CODE)
set_valid(false)
end
if @rapid_endpoint.nil? || @rapid_endpoint.empty?
add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE)
set_valid(false)
end
if @is_valid
begin
parser_endpoint_to_web_url
unless @list_error.nil?
@list_error.clear
end
set_valid(true)
@logger.info "Initiate client using [#{@web_url}] successful!" if @logger
rescue => e
@logger.error "Error setting Rapid endpoint #{e.backtrace.inspect}" if @logger
set_valid(false)
add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE)
end
else
@logger.warn 'Invalid parameter passed to Rapid client' if @logger
end
end | ruby | def validate_api_param
set_valid(true)
if @api_key.nil? || @api_key.empty? || @password.nil? || @password.empty?
add_error_code(Constants::API_KEY_INVALID_ERROR_CODE)
set_valid(false)
end
if @rapid_endpoint.nil? || @rapid_endpoint.empty?
add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE)
set_valid(false)
end
if @is_valid
begin
parser_endpoint_to_web_url
unless @list_error.nil?
@list_error.clear
end
set_valid(true)
@logger.info "Initiate client using [#{@web_url}] successful!" if @logger
rescue => e
@logger.error "Error setting Rapid endpoint #{e.backtrace.inspect}" if @logger
set_valid(false)
add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE)
end
else
@logger.warn 'Invalid parameter passed to Rapid client' if @logger
end
end | [
"def",
"validate_api_param",
"set_valid",
"(",
"true",
")",
"if",
"@api_key",
".",
"nil?",
"||",
"@api_key",
".",
"empty?",
"||",
"@password",
".",
"nil?",
"||",
"@password",
".",
"empty?",
"add_error_code",
"(",
"Constants",
"::",
"API_KEY_INVALID_ERROR_CODE",
")",
"set_valid",
"(",
"false",
")",
"end",
"if",
"@rapid_endpoint",
".",
"nil?",
"||",
"@rapid_endpoint",
".",
"empty?",
"add_error_code",
"(",
"Constants",
"::",
"LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE",
")",
"set_valid",
"(",
"false",
")",
"end",
"if",
"@is_valid",
"begin",
"parser_endpoint_to_web_url",
"unless",
"@list_error",
".",
"nil?",
"@list_error",
".",
"clear",
"end",
"set_valid",
"(",
"true",
")",
"@logger",
".",
"info",
"\"Initiate client using [#{@web_url}] successful!\"",
"if",
"@logger",
"rescue",
"=>",
"e",
"@logger",
".",
"error",
"\"Error setting Rapid endpoint #{e.backtrace.inspect}\"",
"if",
"@logger",
"set_valid",
"(",
"false",
")",
"add_error_code",
"(",
"Constants",
"::",
"LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE",
")",
"end",
"else",
"@logger",
".",
"warn",
"'Invalid parameter passed to Rapid client'",
"if",
"@logger",
"end",
"end"
]
| Validates the Rapid API key, password and endpoint | [
"Validates",
"the",
"Rapid",
"API",
"key",
"password",
"and",
"endpoint"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L375-L401 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.parser_endpoint_to_web_url | def parser_endpoint_to_web_url
# @type [String]
prop_name = nil
if Constants::RAPID_ENDPOINT_PRODUCTION.casecmp(@rapid_endpoint).zero?
prop_name = Constants::GLOBAL_RAPID_PRODUCTION_REST_URL_PARAM
elsif Constants::RAPID_ENDPOINT_SANDBOX.casecmp(@rapid_endpoint).zero?
prop_name = Constants::GLOBAL_RAPID_SANDBOX_REST_URL_PARAM
end
if prop_name.nil?
set_web_url(@rapid_endpoint)
else
property_array = YAML.load_file(File.join(File.dirname(__FILE__), 'resources', 'rapid-api.yml'))
property_array.each do |h|
if prop_name.casecmp(h.keys.first).zero?
set_web_url(h[h.keys.first])
end
end
if @web_url.nil?
fail Exception, "The endpoint #{prop_name} is invalid."
end
end
# verify_endpoint_url(@web_url) # this is unreliable
end | ruby | def parser_endpoint_to_web_url
# @type [String]
prop_name = nil
if Constants::RAPID_ENDPOINT_PRODUCTION.casecmp(@rapid_endpoint).zero?
prop_name = Constants::GLOBAL_RAPID_PRODUCTION_REST_URL_PARAM
elsif Constants::RAPID_ENDPOINT_SANDBOX.casecmp(@rapid_endpoint).zero?
prop_name = Constants::GLOBAL_RAPID_SANDBOX_REST_URL_PARAM
end
if prop_name.nil?
set_web_url(@rapid_endpoint)
else
property_array = YAML.load_file(File.join(File.dirname(__FILE__), 'resources', 'rapid-api.yml'))
property_array.each do |h|
if prop_name.casecmp(h.keys.first).zero?
set_web_url(h[h.keys.first])
end
end
if @web_url.nil?
fail Exception, "The endpoint #{prop_name} is invalid."
end
end
# verify_endpoint_url(@web_url) # this is unreliable
end | [
"def",
"parser_endpoint_to_web_url",
"prop_name",
"=",
"nil",
"if",
"Constants",
"::",
"RAPID_ENDPOINT_PRODUCTION",
".",
"casecmp",
"(",
"@rapid_endpoint",
")",
".",
"zero?",
"prop_name",
"=",
"Constants",
"::",
"GLOBAL_RAPID_PRODUCTION_REST_URL_PARAM",
"elsif",
"Constants",
"::",
"RAPID_ENDPOINT_SANDBOX",
".",
"casecmp",
"(",
"@rapid_endpoint",
")",
".",
"zero?",
"prop_name",
"=",
"Constants",
"::",
"GLOBAL_RAPID_SANDBOX_REST_URL_PARAM",
"end",
"if",
"prop_name",
".",
"nil?",
"set_web_url",
"(",
"@rapid_endpoint",
")",
"else",
"property_array",
"=",
"YAML",
".",
"load_file",
"(",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"'resources'",
",",
"'rapid-api.yml'",
")",
")",
"property_array",
".",
"each",
"do",
"|",
"h",
"|",
"if",
"prop_name",
".",
"casecmp",
"(",
"h",
".",
"keys",
".",
"first",
")",
".",
"zero?",
"set_web_url",
"(",
"h",
"[",
"h",
".",
"keys",
".",
"first",
"]",
")",
"end",
"end",
"if",
"@web_url",
".",
"nil?",
"fail",
"Exception",
",",
"\"The endpoint #{prop_name} is invalid.\"",
"end",
"end",
"end"
]
| Converts an endpoint string to a URL | [
"Converts",
"an",
"endpoint",
"string",
"to",
"a",
"URL"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L404-L426 | train |
eWAYPayment/eway-rapid-ruby | lib/eway_rapid/rapid_client.rb | EwayRapid.RapidClient.verify_endpoint_url | def verify_endpoint_url(web_url)
begin
resource = RestClient::Resource.new web_url
resource.get
rescue RestClient::Exception => e
if e.http_code == 404
set_valid(false)
end
end
end | ruby | def verify_endpoint_url(web_url)
begin
resource = RestClient::Resource.new web_url
resource.get
rescue RestClient::Exception => e
if e.http_code == 404
set_valid(false)
end
end
end | [
"def",
"verify_endpoint_url",
"(",
"web_url",
")",
"begin",
"resource",
"=",
"RestClient",
"::",
"Resource",
".",
"new",
"web_url",
"resource",
".",
"get",
"rescue",
"RestClient",
"::",
"Exception",
"=>",
"e",
"if",
"e",
".",
"http_code",
"==",
"404",
"set_valid",
"(",
"false",
")",
"end",
"end",
"end"
]
| Checks the Rapid endpoint url
@param [String] web_url | [
"Checks",
"the",
"Rapid",
"endpoint",
"url"
]
| 49b0e3845e442dff58466c06cef01b5f8f037990 | https://github.com/eWAYPayment/eway-rapid-ruby/blob/49b0e3845e442dff58466c06cef01b5f8f037990/lib/eway_rapid/rapid_client.rb#L431-L440 | train |
wepay/Ruby-SDK | lib/wepay.rb | WePay.Client.call | def call(call, access_token = false, params = {}, risk_token = false, client_ip = false)
path = call.start_with?('/') ? call : call.prepend('/')
url = URI.parse(api_endpoint + path)
call = Net::HTTP::Post.new(url.path, {
'Content-Type' => 'application/json',
'User-Agent' => 'WePay Ruby SDK'
})
unless params.empty?
call.body = params.to_json
end
if access_token then call.add_field('Authorization', "Bearer #{access_token}"); end
if @api_version then call.add_field('Api-Version', @api_version); end
if risk_token then call.add_field('WePay-Risk-Token', risk_token); end
if client_ip then call.add_field('Client-IP', client_ip); end
make_request(call, url)
end | ruby | def call(call, access_token = false, params = {}, risk_token = false, client_ip = false)
path = call.start_with?('/') ? call : call.prepend('/')
url = URI.parse(api_endpoint + path)
call = Net::HTTP::Post.new(url.path, {
'Content-Type' => 'application/json',
'User-Agent' => 'WePay Ruby SDK'
})
unless params.empty?
call.body = params.to_json
end
if access_token then call.add_field('Authorization', "Bearer #{access_token}"); end
if @api_version then call.add_field('Api-Version', @api_version); end
if risk_token then call.add_field('WePay-Risk-Token', risk_token); end
if client_ip then call.add_field('Client-IP', client_ip); end
make_request(call, url)
end | [
"def",
"call",
"(",
"call",
",",
"access_token",
"=",
"false",
",",
"params",
"=",
"{",
"}",
",",
"risk_token",
"=",
"false",
",",
"client_ip",
"=",
"false",
")",
"path",
"=",
"call",
".",
"start_with?",
"(",
"'/'",
")",
"?",
"call",
":",
"call",
".",
"prepend",
"(",
"'/'",
")",
"url",
"=",
"URI",
".",
"parse",
"(",
"api_endpoint",
"+",
"path",
")",
"call",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"url",
".",
"path",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
",",
"'User-Agent'",
"=>",
"'WePay Ruby SDK'",
"}",
")",
"unless",
"params",
".",
"empty?",
"call",
".",
"body",
"=",
"params",
".",
"to_json",
"end",
"if",
"access_token",
"then",
"call",
".",
"add_field",
"(",
"'Authorization'",
",",
"\"Bearer #{access_token}\"",
")",
";",
"end",
"if",
"@api_version",
"then",
"call",
".",
"add_field",
"(",
"'Api-Version'",
",",
"@api_version",
")",
";",
"end",
"if",
"risk_token",
"then",
"call",
".",
"add_field",
"(",
"'WePay-Risk-Token'",
",",
"risk_token",
")",
";",
"end",
"if",
"client_ip",
"then",
"call",
".",
"add_field",
"(",
"'Client-IP'",
",",
"client_ip",
")",
";",
"end",
"make_request",
"(",
"call",
",",
"url",
")",
"end"
]
| Execute a call to the WePay API. | [
"Execute",
"a",
"call",
"to",
"the",
"WePay",
"API",
"."
]
| ebb6d27ac6eeb00362c2fe044709317f3d7162d8 | https://github.com/wepay/Ruby-SDK/blob/ebb6d27ac6eeb00362c2fe044709317f3d7162d8/lib/wepay.rb#L59-L78 | train |
wepay/Ruby-SDK | lib/wepay.rb | WePay.Client.make_request | def make_request(call, url)
request = Net::HTTP.new(url.host, url.port)
request.read_timeout = 30
request.use_ssl = true
response = request.start { |http| http.request(call) }
JSON.parse(response.body)
end | ruby | def make_request(call, url)
request = Net::HTTP.new(url.host, url.port)
request.read_timeout = 30
request.use_ssl = true
response = request.start { |http| http.request(call) }
JSON.parse(response.body)
end | [
"def",
"make_request",
"(",
"call",
",",
"url",
")",
"request",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"url",
".",
"host",
",",
"url",
".",
"port",
")",
"request",
".",
"read_timeout",
"=",
"30",
"request",
".",
"use_ssl",
"=",
"true",
"response",
"=",
"request",
".",
"start",
"{",
"|",
"http",
"|",
"http",
".",
"request",
"(",
"call",
")",
"}",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"end"
]
| Make the HTTP request to the endpoint. | [
"Make",
"the",
"HTTP",
"request",
"to",
"the",
"endpoint",
"."
]
| ebb6d27ac6eeb00362c2fe044709317f3d7162d8 | https://github.com/wepay/Ruby-SDK/blob/ebb6d27ac6eeb00362c2fe044709317f3d7162d8/lib/wepay.rb#L119-L126 | train |
terry90/rails_api_benchmark | lib/rails_api_benchmark.rb | RailsApiBenchmark.Configuration.all | def all
instance_variables.inject({}) do |h, v|
var = v.to_s.sub('@', '')
h.merge(var.to_sym => send(var))
end
end | ruby | def all
instance_variables.inject({}) do |h, v|
var = v.to_s.sub('@', '')
h.merge(var.to_sym => send(var))
end
end | [
"def",
"all",
"instance_variables",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"h",
",",
"v",
"|",
"var",
"=",
"v",
".",
"to_s",
".",
"sub",
"(",
"'@'",
",",
"''",
")",
"h",
".",
"merge",
"(",
"var",
".",
"to_sym",
"=>",
"send",
"(",
"var",
")",
")",
"end",
"end"
]
| Default values, INSANE. Must be refactored
Maybe create a yaml or json file to import for default values | [
"Default",
"values",
"INSANE",
".",
"Must",
"be",
"refactored",
"Maybe",
"create",
"a",
"yaml",
"or",
"json",
"file",
"to",
"import",
"for",
"default",
"values"
]
| 2991765ff639b2efdf4aa1a56587247ed5ee22d0 | https://github.com/terry90/rails_api_benchmark/blob/2991765ff639b2efdf4aa1a56587247ed5ee22d0/lib/rails_api_benchmark.rb#L50-L55 | train |
manorie/textoken | lib/textoken/searcher.rb | Textoken.Searcher.match_keys | def match_keys
values.each do |v|
Textoken.expression_err("#{v}: is not permitted.") unless yaml.key?(v)
add_regexps(yaml[v])
end
end | ruby | def match_keys
values.each do |v|
Textoken.expression_err("#{v}: is not permitted.") unless yaml.key?(v)
add_regexps(yaml[v])
end
end | [
"def",
"match_keys",
"values",
".",
"each",
"do",
"|",
"v",
"|",
"Textoken",
".",
"expression_err",
"(",
"\"#{v}: is not permitted.\"",
")",
"unless",
"yaml",
".",
"key?",
"(",
"v",
")",
"add_regexps",
"(",
"yaml",
"[",
"v",
"]",
")",
"end",
"end"
]
| here we do check for option values user supplied
option values has to be declared at option_values.yml | [
"here",
"we",
"do",
"check",
"for",
"option",
"values",
"user",
"supplied",
"option",
"values",
"has",
"to",
"be",
"declared",
"at",
"option_values",
".",
"yml"
]
| e66b0c34217e8c3cfab70f1d4e6abf26f876555f | https://github.com/manorie/textoken/blob/e66b0c34217e8c3cfab70f1d4e6abf26f876555f/lib/textoken/searcher.rb#L34-L39 | train |
ekosz/Plex-Ruby | lib/plex-ruby/season.rb | Plex.Season.episode | def episode(number)
episodes.detect { |epi| epi.index.to_i == number.to_i }
end | ruby | def episode(number)
episodes.detect { |epi| epi.index.to_i == number.to_i }
end | [
"def",
"episode",
"(",
"number",
")",
"episodes",
".",
"detect",
"{",
"|",
"epi",
"|",
"epi",
".",
"index",
".",
"to_i",
"==",
"number",
".",
"to_i",
"}",
"end"
]
| Select a particular episode
@param [Fixnum, String] episode index number
@return [Episode] episode with the index of number | [
"Select",
"a",
"particular",
"episode"
]
| 981dd175d674c74cad7ea8daf8b52c266c12df29 | https://github.com/ekosz/Plex-Ruby/blob/981dd175d674c74cad7ea8daf8b52c266c12df29/lib/plex-ruby/season.rb#L42-L44 | train |
petethepig/marmot | lib/marmot/client.rb | Marmot.Client.convert | def convert input_io, options={}
@exception = nil
#1
iam "Retrieving cookies... ", false do
response = self.class.get '/tools/webfont-generator'
@cookies = (response.headers.get_fields("Set-Cookie") || []).join(";")
fail "Failed to retrieve cookies" if @cookies.empty?
self.class.headers({"Cookie" => @cookies})
@@headers_set = true
response
end unless @@headers_set
#2
iam "Uploading font... " do
response = self.class.post '/uploadify/fontfacegen_uploadify.php', :query => {
"Filedata" => File.new(input_io)
}
@path_data = response.body
@id, @original_filename = @path_data.split("|")
fail "Failed to upload the file. Is it a valid font?" if @id.nil? || @original_filename.nil?
response
end
#3
iam "Confirming upload... " do
response = self.class.post "/tools/insert", :query => {
"original_filename" => @original_filename,
"path_data" => @path_data
}
json = JSON.parse response.body
fail (json["message"] || "Failed to confirm the upload. Is it a valid font?") if !json["name"] || !json["id"]
response
end
#4
iam "Generating webfont... " do
custom_options = options.delete :custom_options
options[:id] = @id
@params = OptionsSanitizer.sanitize(options, custom_options)
logger.debug "HTTP Params:\n#{@params.collect{|k,v| "#{k}: #{v.inspect}" }.join("\n")}"
response = self.class.post "/tools/generate", :query => @params
fail "Failed to generate webfont kit" if !response.body.empty?
response
end
#5
counter = 0
while response = self.class.get("/tools/progress/#{@id}") do
p = JSON.parse(response.body)["progress"].to_i
logger.info "Progress: #{p} "
if p == 100
break
elsif p == 0
fail "Progress timeout" if (counter += 1) > 10
end
sleep 2
end
#6
iam "Downloading fonts... ", false do
response = self.class.post "/tools/download", :query => @params
end
#7
if !options[:output_io]
filename = response.headers["Content-Disposition"].gsub(/attachment; filename=\"(.*)\"/,'\1')
options[:output_io] = File.new(filename, "wb")
end
options[:output_io] << response.response.body
end | ruby | def convert input_io, options={}
@exception = nil
#1
iam "Retrieving cookies... ", false do
response = self.class.get '/tools/webfont-generator'
@cookies = (response.headers.get_fields("Set-Cookie") || []).join(";")
fail "Failed to retrieve cookies" if @cookies.empty?
self.class.headers({"Cookie" => @cookies})
@@headers_set = true
response
end unless @@headers_set
#2
iam "Uploading font... " do
response = self.class.post '/uploadify/fontfacegen_uploadify.php', :query => {
"Filedata" => File.new(input_io)
}
@path_data = response.body
@id, @original_filename = @path_data.split("|")
fail "Failed to upload the file. Is it a valid font?" if @id.nil? || @original_filename.nil?
response
end
#3
iam "Confirming upload... " do
response = self.class.post "/tools/insert", :query => {
"original_filename" => @original_filename,
"path_data" => @path_data
}
json = JSON.parse response.body
fail (json["message"] || "Failed to confirm the upload. Is it a valid font?") if !json["name"] || !json["id"]
response
end
#4
iam "Generating webfont... " do
custom_options = options.delete :custom_options
options[:id] = @id
@params = OptionsSanitizer.sanitize(options, custom_options)
logger.debug "HTTP Params:\n#{@params.collect{|k,v| "#{k}: #{v.inspect}" }.join("\n")}"
response = self.class.post "/tools/generate", :query => @params
fail "Failed to generate webfont kit" if !response.body.empty?
response
end
#5
counter = 0
while response = self.class.get("/tools/progress/#{@id}") do
p = JSON.parse(response.body)["progress"].to_i
logger.info "Progress: #{p} "
if p == 100
break
elsif p == 0
fail "Progress timeout" if (counter += 1) > 10
end
sleep 2
end
#6
iam "Downloading fonts... ", false do
response = self.class.post "/tools/download", :query => @params
end
#7
if !options[:output_io]
filename = response.headers["Content-Disposition"].gsub(/attachment; filename=\"(.*)\"/,'\1')
options[:output_io] = File.new(filename, "wb")
end
options[:output_io] << response.response.body
end | [
"def",
"convert",
"input_io",
",",
"options",
"=",
"{",
"}",
"@exception",
"=",
"nil",
"iam",
"\"Retrieving cookies... \"",
",",
"false",
"do",
"response",
"=",
"self",
".",
"class",
".",
"get",
"'/tools/webfont-generator'",
"@cookies",
"=",
"(",
"response",
".",
"headers",
".",
"get_fields",
"(",
"\"Set-Cookie\"",
")",
"||",
"[",
"]",
")",
".",
"join",
"(",
"\";\"",
")",
"fail",
"\"Failed to retrieve cookies\"",
"if",
"@cookies",
".",
"empty?",
"self",
".",
"class",
".",
"headers",
"(",
"{",
"\"Cookie\"",
"=>",
"@cookies",
"}",
")",
"@@headers_set",
"=",
"true",
"response",
"end",
"unless",
"@@headers_set",
"iam",
"\"Uploading font... \"",
"do",
"response",
"=",
"self",
".",
"class",
".",
"post",
"'/uploadify/fontfacegen_uploadify.php'",
",",
":query",
"=>",
"{",
"\"Filedata\"",
"=>",
"File",
".",
"new",
"(",
"input_io",
")",
"}",
"@path_data",
"=",
"response",
".",
"body",
"@id",
",",
"@original_filename",
"=",
"@path_data",
".",
"split",
"(",
"\"|\"",
")",
"fail",
"\"Failed to upload the file. Is it a valid font?\"",
"if",
"@id",
".",
"nil?",
"||",
"@original_filename",
".",
"nil?",
"response",
"end",
"iam",
"\"Confirming upload... \"",
"do",
"response",
"=",
"self",
".",
"class",
".",
"post",
"\"/tools/insert\"",
",",
":query",
"=>",
"{",
"\"original_filename\"",
"=>",
"@original_filename",
",",
"\"path_data\"",
"=>",
"@path_data",
"}",
"json",
"=",
"JSON",
".",
"parse",
"response",
".",
"body",
"fail",
"(",
"json",
"[",
"\"message\"",
"]",
"||",
"\"Failed to confirm the upload. Is it a valid font?\"",
")",
"if",
"!",
"json",
"[",
"\"name\"",
"]",
"||",
"!",
"json",
"[",
"\"id\"",
"]",
"response",
"end",
"iam",
"\"Generating webfont... \"",
"do",
"custom_options",
"=",
"options",
".",
"delete",
":custom_options",
"options",
"[",
":id",
"]",
"=",
"@id",
"@params",
"=",
"OptionsSanitizer",
".",
"sanitize",
"(",
"options",
",",
"custom_options",
")",
"logger",
".",
"debug",
"\"HTTP Params:\\n#{@params.collect{|k,v| \"#{k}: #{v.inspect}\" }.join(\"\\n\")}\"",
"response",
"=",
"self",
".",
"class",
".",
"post",
"\"/tools/generate\"",
",",
":query",
"=>",
"@params",
"fail",
"\"Failed to generate webfont kit\"",
"if",
"!",
"response",
".",
"body",
".",
"empty?",
"response",
"end",
"counter",
"=",
"0",
"while",
"response",
"=",
"self",
".",
"class",
".",
"get",
"(",
"\"/tools/progress/#{@id}\"",
")",
"do",
"p",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"[",
"\"progress\"",
"]",
".",
"to_i",
"logger",
".",
"info",
"\"Progress: #{p} \"",
"if",
"p",
"==",
"100",
"break",
"elsif",
"p",
"==",
"0",
"fail",
"\"Progress timeout\"",
"if",
"(",
"counter",
"+=",
"1",
")",
">",
"10",
"end",
"sleep",
"2",
"end",
"iam",
"\"Downloading fonts... \"",
",",
"false",
"do",
"response",
"=",
"self",
".",
"class",
".",
"post",
"\"/tools/download\"",
",",
":query",
"=>",
"@params",
"end",
"if",
"!",
"options",
"[",
":output_io",
"]",
"filename",
"=",
"response",
".",
"headers",
"[",
"\"Content-Disposition\"",
"]",
".",
"gsub",
"(",
"/",
"\\\"",
"\\\"",
"/",
",",
"'\\1'",
")",
"options",
"[",
":output_io",
"]",
"=",
"File",
".",
"new",
"(",
"filename",
",",
"\"wb\"",
")",
"end",
"options",
"[",
":output_io",
"]",
"<<",
"response",
".",
"response",
".",
"body",
"end"
]
| Convert a font file to a webfont kit
@param [String] input_io Input IO. Examples: File.new("font.ttf"), STDOUT
@param [Hash] options Options
@option options
[String] :output_io
Output IO
Default is a File with the name like "webfontkit-20130312-200144.zip"
@option options
[Hash] :custom_options
Options that will bypass sanitization. Make sure you know what you do before trying it out.
@option options [Array or String] :formats
Allowed values are: "ttf", "woff", "svg", "eotz", "eot". Default is ["ttf","woff","svg","eotz"]
@option options
[String] :mode
Generator mode: "optimal", "basic", "expert". Default is "optimal"
@option options
[String] :tt_instructor
Truetype hinting: "default", "keep"
@option options
[Boolean] :fix_vertical_metrics
Rendering option. Fix Vertical Metrics (Normalize across browsers). Default is true
@option options
[Boolean] :fix_gasp
Rendering option. Fix GASP Table (Better DirectWrite Rendering). Default is true
@option options
[Boolean] :remove_kerning
Rendering option. Remove Kerning (Strip kerning data). Default is false
@option options
[Boolean] :add_spaces
Fix missing glyphs option. Fix spaces. Default is true
@option options
[Boolean] :add_hyphens
Fix missing glyphs option. Fix hyphens. Default is true
@option options
[String] :fallback
X-height matching: "none", "arial", "verdana", "trebuchet", "georgia", "times", "courier", "custom"
@option options
[String] :fallback_custom
Custom x-height matching, in percents. Default is "100%". Only applies when :fallback is "custom"
@option options
[Boolean] :webonly
Disable desktop use. Default is false
@option options
[String] :options_subset
Subsetting options: "basic", "advanced", "none". Default is "basic"
@option options
[Array] :subset_range
Custom subsetting options. Only applies when :options_subset is "advanced".
Allowed values are: "macroman", "lowercase", "uppercase", "numbers", "punctuation", "currency",
"typographics", "math", "altpunctuation", "accentedlower", "accentedupper", "diacriticals",
"albanian", "bosnian", "catalan", "croatian", "cyrillic", "czech", "danish", "dutch", "english",
"esperanto", "estonian", "faroese", "french", "german", "greek", "hebrew", "hungarian", "icelandic",
"italian", "latvian", "lithuanian", "malagasy", "maltese", "norwegian", "polish", "portuguese",
"romanian", "serbian", "slovak", "slovenian", "spanish", "swedish", "turkish", "ubasic", "ulatin1",
"ucurrency", "upunctuation", "ulatina", "ulatinb", "ulatinaddl"
@option options
[String] :subset_custom
Single characters. Only applies when :options_subset is "advanced". Default is ""
@option options
[String] :subset_custom_range
Unicode Ranges. Only applies when :options_subset is "advanced".
Comma separated values. Can be single hex values and/or ranges separated with hyphens.
Example: "0021-007E,00E7,00EB,00C7,00CB"
@option options
[Boolean] :base64
CSS option. Base64 encode (Embed font in CSS). Default is false
@option options
[Boolean] :style_link
CSS option. Style link (Family support in CSS). Default is false
@option options
[String] :css_stylesheet
CSS Filename. Default is "stylesheet.css"
@option options
[String] :ot_features
OpenType Options. If the features are available, the generator will fold them into the font.
Allowed values: "onum", "lnum", "tnum", "pnum", "zero", "ss01", "ss02", "ss03", "ss04", "ss05"
@option options
[String] :filename_suffix
Filename suffix. Default is "-webfont"
@option options
[String] :emsquare
Em Square Value. In units of the em square. Default is 2048
@option options
[String] :spacing_adjustment
Adjust Glyph Spacing. In units of the em square. Default is 0
@option options
[Boolean] :agreement
Agreement option. The fonts You're uploading are legally eligible for web embedding. Default is true.
@see http://www.fontsquirrel.com/tools/webfont-generator more info about parameters @ www.fontsquirrel.com
@return [String] | [
"Convert",
"a",
"font",
"file",
"to",
"a",
"webfont",
"kit"
]
| dd4877fbe1eb40cbbfe49b3a2d2f143aa6db2c58 | https://github.com/petethepig/marmot/blob/dd4877fbe1eb40cbbfe49b3a2d2f143aa6db2c58/lib/marmot/client.rb#L137-L207 | train |
ekosz/Plex-Ruby | lib/plex-ruby/client.rb | Plex.Client.play_media | def play_media(key, user_agent = nil, http_cookies = nil, view_offset = nil)
if !key.is_a?(String) && key.respond_to?(:key)
key = key.key
end
url = player_url+'/application/playMedia?'
url += "path=#{CGI::escape(server.url+key)}"
url += "&key=#{CGI::escape(key)}"
url += "&userAgent=#{user_agent}" if user_agent
url += "&httpCookies=#{http_cookies}" if http_cookies
url += "&viewOffset=#{view_offset}" if view_offset
ping url
end | ruby | def play_media(key, user_agent = nil, http_cookies = nil, view_offset = nil)
if !key.is_a?(String) && key.respond_to?(:key)
key = key.key
end
url = player_url+'/application/playMedia?'
url += "path=#{CGI::escape(server.url+key)}"
url += "&key=#{CGI::escape(key)}"
url += "&userAgent=#{user_agent}" if user_agent
url += "&httpCookies=#{http_cookies}" if http_cookies
url += "&viewOffset=#{view_offset}" if view_offset
ping url
end | [
"def",
"play_media",
"(",
"key",
",",
"user_agent",
"=",
"nil",
",",
"http_cookies",
"=",
"nil",
",",
"view_offset",
"=",
"nil",
")",
"if",
"!",
"key",
".",
"is_a?",
"(",
"String",
")",
"&&",
"key",
".",
"respond_to?",
"(",
":key",
")",
"key",
"=",
"key",
".",
"key",
"end",
"url",
"=",
"player_url",
"+",
"'/application/playMedia?'",
"url",
"+=",
"\"path=#{CGI::escape(server.url+key)}\"",
"url",
"+=",
"\"&key=#{CGI::escape(key)}\"",
"url",
"+=",
"\"&userAgent=#{user_agent}\"",
"if",
"user_agent",
"url",
"+=",
"\"&httpCookies=#{http_cookies}\"",
"if",
"http_cookies",
"url",
"+=",
"\"&viewOffset=#{view_offset}\"",
"if",
"view_offset",
"ping",
"url",
"end"
]
| Plays a video that is in the library
@param [String, Object] the key of the video that we want to play. Or an
Object that responds to :key (see Episode#key) (see Movie#key)
@param [String] no clue what this does, its the Plex Remote Command API though
@param [String] no clue what this does, its the Plex Remote Command API though
@param [String] no clue what this does, its the Plex Remote Command API though
@return [True, nil] true if it worked, nil if something went wrong check
the console for the error message | [
"Plays",
"a",
"video",
"that",
"is",
"in",
"the",
"library"
]
| 981dd175d674c74cad7ea8daf8b52c266c12df29 | https://github.com/ekosz/Plex-Ruby/blob/981dd175d674c74cad7ea8daf8b52c266c12df29/lib/plex-ruby/client.rb#L64-L78 | train |
ekosz/Plex-Ruby | lib/plex-ruby/client.rb | Plex.Client.screenshot | def screenshot(width, height, quality)
url = player_url+'/application/screenshot?'
url += "width=#{width}"
url += "&height=#{height}"
url += "&quality=#{quality}"
ping url
end | ruby | def screenshot(width, height, quality)
url = player_url+'/application/screenshot?'
url += "width=#{width}"
url += "&height=#{height}"
url += "&quality=#{quality}"
ping url
end | [
"def",
"screenshot",
"(",
"width",
",",
"height",
",",
"quality",
")",
"url",
"=",
"player_url",
"+",
"'/application/screenshot?'",
"url",
"+=",
"\"width=#{width}\"",
"url",
"+=",
"\"&height=#{height}\"",
"url",
"+=",
"\"&quality=#{quality}\"",
"ping",
"url",
"end"
]
| Take a screenshot of whats on the Plex Client
@param [String, Fixnum] width of the screenshot
@param [String, Fixnum] height of the screenshot
@param [String, Fixnum] quality of the screenshot
@return [True, nil] true if it worked, nil if something went wrong check
the console for the error message | [
"Take",
"a",
"screenshot",
"of",
"whats",
"on",
"the",
"Plex",
"Client"
]
| 981dd175d674c74cad7ea8daf8b52c266c12df29 | https://github.com/ekosz/Plex-Ruby/blob/981dd175d674c74cad7ea8daf8b52c266c12df29/lib/plex-ruby/client.rb#L87-L94 | train |
ekosz/Plex-Ruby | lib/plex-ruby/show.rb | Plex.Show.season | def season(number)
seasons.detect { |sea| sea.index.to_i == number.to_i }
end | ruby | def season(number)
seasons.detect { |sea| sea.index.to_i == number.to_i }
end | [
"def",
"season",
"(",
"number",
")",
"seasons",
".",
"detect",
"{",
"|",
"sea",
"|",
"sea",
".",
"index",
".",
"to_i",
"==",
"number",
".",
"to_i",
"}",
"end"
]
| Select a particular season
@param [Fixnum, String] season index number
@return [Season] season with the index of number | [
"Select",
"a",
"particular",
"season"
]
| 981dd175d674c74cad7ea8daf8b52c266c12df29 | https://github.com/ekosz/Plex-Ruby/blob/981dd175d674c74cad7ea8daf8b52c266c12df29/lib/plex-ruby/show.rb#L42-L44 | train |
ekosz/Plex-Ruby | lib/plex-ruby/show.rb | Plex.Show.first_season | def first_season
seasons.inject { |a, b| a.index.to_i < b.index.to_i && a.index.to_i > 0 ? a : b }
end | ruby | def first_season
seasons.inject { |a, b| a.index.to_i < b.index.to_i && a.index.to_i > 0 ? a : b }
end | [
"def",
"first_season",
"seasons",
".",
"inject",
"{",
"|",
"a",
",",
"b",
"|",
"a",
".",
"index",
".",
"to_i",
"<",
"b",
".",
"index",
".",
"to_i",
"&&",
"a",
".",
"index",
".",
"to_i",
">",
"0",
"?",
"a",
":",
"b",
"}",
"end"
]
| Selects the first season of this show that is on the Plex Server
Does not select season 0
@return [Season] season with the lowest index (but not 0) | [
"Selects",
"the",
"first",
"season",
"of",
"this",
"show",
"that",
"is",
"on",
"the",
"Plex",
"Server",
"Does",
"not",
"select",
"season",
"0"
]
| 981dd175d674c74cad7ea8daf8b52c266c12df29 | https://github.com/ekosz/Plex-Ruby/blob/981dd175d674c74cad7ea8daf8b52c266c12df29/lib/plex-ruby/show.rb#L59-L61 | train |
manorie/textoken | lib/textoken/base.rb | Textoken.Base.tokens | def tokens
options.collection.each do |option|
if @findings.nil?
@findings = option.tokenize(self)
else
@findings &= option.tokenize(self)
end
end
Tokenizer.new(self).tokens
end | ruby | def tokens
options.collection.each do |option|
if @findings.nil?
@findings = option.tokenize(self)
else
@findings &= option.tokenize(self)
end
end
Tokenizer.new(self).tokens
end | [
"def",
"tokens",
"options",
".",
"collection",
".",
"each",
"do",
"|",
"option",
"|",
"if",
"@findings",
".",
"nil?",
"@findings",
"=",
"option",
".",
"tokenize",
"(",
"self",
")",
"else",
"@findings",
"&=",
"option",
".",
"tokenize",
"(",
"self",
")",
"end",
"end",
"Tokenizer",
".",
"new",
"(",
"self",
")",
".",
"tokens",
"end"
]
| we do take intersection array of results
returning from multiple options | [
"we",
"do",
"take",
"intersection",
"array",
"of",
"results",
"returning",
"from",
"multiple",
"options"
]
| e66b0c34217e8c3cfab70f1d4e6abf26f876555f | https://github.com/manorie/textoken/blob/e66b0c34217e8c3cfab70f1d4e6abf26f876555f/lib/textoken/base.rb#L15-L25 | train |
veny/orientdb4r | lib/orientdb4r/rest/client.rb | Orientdb4r.RestClient.gremlin | def gremlin(gremlin)
raise ArgumentError, 'gremlin query is blank' if blank? gremlin
response = call_server(:method => :post, :uri => "command/#{@database}/gremlin/#{CGI::escape(gremlin)}")
entries = process_response(response) do
raise NotFoundError, 'record not found' if response.body =~ /ORecordNotFoundException/
end
rslt = entries['result']
# mixin all document entries (they have '@class' attribute)
rslt.each { |doc| doc.extend Orientdb4r::DocumentMetadata unless doc['@class'].nil? }
rslt
end | ruby | def gremlin(gremlin)
raise ArgumentError, 'gremlin query is blank' if blank? gremlin
response = call_server(:method => :post, :uri => "command/#{@database}/gremlin/#{CGI::escape(gremlin)}")
entries = process_response(response) do
raise NotFoundError, 'record not found' if response.body =~ /ORecordNotFoundException/
end
rslt = entries['result']
# mixin all document entries (they have '@class' attribute)
rslt.each { |doc| doc.extend Orientdb4r::DocumentMetadata unless doc['@class'].nil? }
rslt
end | [
"def",
"gremlin",
"(",
"gremlin",
")",
"raise",
"ArgumentError",
",",
"'gremlin query is blank'",
"if",
"blank?",
"gremlin",
"response",
"=",
"call_server",
"(",
":method",
"=>",
":post",
",",
":uri",
"=>",
"\"command/#{@database}/gremlin/#{CGI::escape(gremlin)}\"",
")",
"entries",
"=",
"process_response",
"(",
"response",
")",
"do",
"raise",
"NotFoundError",
",",
"'record not found'",
"if",
"response",
".",
"body",
"=~",
"/",
"/",
"end",
"rslt",
"=",
"entries",
"[",
"'result'",
"]",
"rslt",
".",
"each",
"{",
"|",
"doc",
"|",
"doc",
".",
"extend",
"Orientdb4r",
"::",
"DocumentMetadata",
"unless",
"doc",
"[",
"'@class'",
"]",
".",
"nil?",
"}",
"rslt",
"end"
]
| Executes a Gremlin command against the database. | [
"Executes",
"a",
"Gremlin",
"command",
"against",
"the",
"database",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/client.rb#L300-L311 | train |
veny/orientdb4r | lib/orientdb4r/rest/client.rb | Orientdb4r.RestClient.process_response | def process_response(response)
raise ArgumentError, 'response is null' if response.nil?
if block_given?
yield
end
# return code
if 401 == response.code
raise UnauthorizedError, compose_error_message(response)
elsif 500 == response.code
raise ServerError, compose_error_message(response)
elsif 2 != (response.code / 100)
raise OrientdbError, "unexpected return code, code=#{response.code}, body=#{compose_error_message(response)}"
end
content_type = response.headers[:content_type] if connection_library == :restclient
content_type = response.headers['Content-Type'] if connection_library == :excon
content_type ||= 'text/plain'
rslt = case
when content_type.start_with?('text/plain')
response.body
when content_type.start_with?('application/x-gzip')
response.body
when content_type.start_with?('application/json')
::JSON.parse(response.body)
else
raise OrientdbError, "unsuported content type: #{content_type}"
end
rslt
end | ruby | def process_response(response)
raise ArgumentError, 'response is null' if response.nil?
if block_given?
yield
end
# return code
if 401 == response.code
raise UnauthorizedError, compose_error_message(response)
elsif 500 == response.code
raise ServerError, compose_error_message(response)
elsif 2 != (response.code / 100)
raise OrientdbError, "unexpected return code, code=#{response.code}, body=#{compose_error_message(response)}"
end
content_type = response.headers[:content_type] if connection_library == :restclient
content_type = response.headers['Content-Type'] if connection_library == :excon
content_type ||= 'text/plain'
rslt = case
when content_type.start_with?('text/plain')
response.body
when content_type.start_with?('application/x-gzip')
response.body
when content_type.start_with?('application/json')
::JSON.parse(response.body)
else
raise OrientdbError, "unsuported content type: #{content_type}"
end
rslt
end | [
"def",
"process_response",
"(",
"response",
")",
"raise",
"ArgumentError",
",",
"'response is null'",
"if",
"response",
".",
"nil?",
"if",
"block_given?",
"yield",
"end",
"if",
"401",
"==",
"response",
".",
"code",
"raise",
"UnauthorizedError",
",",
"compose_error_message",
"(",
"response",
")",
"elsif",
"500",
"==",
"response",
".",
"code",
"raise",
"ServerError",
",",
"compose_error_message",
"(",
"response",
")",
"elsif",
"2",
"!=",
"(",
"response",
".",
"code",
"/",
"100",
")",
"raise",
"OrientdbError",
",",
"\"unexpected return code, code=#{response.code}, body=#{compose_error_message(response)}\"",
"end",
"content_type",
"=",
"response",
".",
"headers",
"[",
":content_type",
"]",
"if",
"connection_library",
"==",
":restclient",
"content_type",
"=",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"if",
"connection_library",
"==",
":excon",
"content_type",
"||=",
"'text/plain'",
"rslt",
"=",
"case",
"when",
"content_type",
".",
"start_with?",
"(",
"'text/plain'",
")",
"response",
".",
"body",
"when",
"content_type",
".",
"start_with?",
"(",
"'application/x-gzip'",
")",
"response",
".",
"body",
"when",
"content_type",
".",
"start_with?",
"(",
"'application/json'",
")",
"::",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"else",
"raise",
"OrientdbError",
",",
"\"unsuported content type: #{content_type}\"",
"end",
"rslt",
"end"
]
| Processes a HTTP response. | [
"Processes",
"a",
"HTTP",
"response",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/client.rb#L417-L450 | train |
veny/orientdb4r | lib/orientdb4r/rest/client.rb | Orientdb4r.RestClient.compose_error_message | def compose_error_message(http_response, max_len=200)
msg = http_response.body.gsub("\n", ' ')
msg = "#{msg[0..max_len]} ..." if msg.size > max_len
msg
end | ruby | def compose_error_message(http_response, max_len=200)
msg = http_response.body.gsub("\n", ' ')
msg = "#{msg[0..max_len]} ..." if msg.size > max_len
msg
end | [
"def",
"compose_error_message",
"(",
"http_response",
",",
"max_len",
"=",
"200",
")",
"msg",
"=",
"http_response",
".",
"body",
".",
"gsub",
"(",
"\"\\n\"",
",",
"' '",
")",
"msg",
"=",
"\"#{msg[0..max_len]} ...\"",
"if",
"msg",
".",
"size",
">",
"max_len",
"msg",
"end"
]
| Composes message of an error raised if the HTTP response doesn't
correspond with expectation. | [
"Composes",
"message",
"of",
"an",
"error",
"raised",
"if",
"the",
"HTTP",
"response",
"doesn",
"t",
"correspond",
"with",
"expectation",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/client.rb#L456-L460 | train |
blambeau/wlang | lib/wlang/dialect.rb | WLang.Dialect.dialects_for | def dialects_for(symbols)
info = self.class.tag_dispatching_name(symbols, "_diatag")
raise ArgumentError, "No tag for #{symbols}" unless respond_to?(info)
send(info)
end | ruby | def dialects_for(symbols)
info = self.class.tag_dispatching_name(symbols, "_diatag")
raise ArgumentError, "No tag for #{symbols}" unless respond_to?(info)
send(info)
end | [
"def",
"dialects_for",
"(",
"symbols",
")",
"info",
"=",
"self",
".",
"class",
".",
"tag_dispatching_name",
"(",
"symbols",
",",
"\"_diatag\"",
")",
"raise",
"ArgumentError",
",",
"\"No tag for #{symbols}\"",
"unless",
"respond_to?",
"(",
"info",
")",
"send",
"(",
"info",
")",
"end"
]
| Returns the dialects used to parse the blocks associated with `symbols`, as
previously installed by `define_tag_method`. | [
"Returns",
"the",
"dialects",
"used",
"to",
"parse",
"the",
"blocks",
"associated",
"with",
"symbols",
"as",
"previously",
"installed",
"by",
"define_tag_method",
"."
]
| 6e45f0c2ae2c8ff27accfab42e4af8ce6d1ff051 | https://github.com/blambeau/wlang/blob/6e45f0c2ae2c8ff27accfab42e4af8ce6d1ff051/lib/wlang/dialect.rb#L120-L124 | train |
blambeau/wlang | lib/wlang/dialect.rb | WLang.Dialect.render | def render(fn, scope = nil, buffer = "")
if scope.nil?
case fn
when String then buffer << fn
when Proc then fn.call(self, buffer)
when Template then fn.call(@scope, buffer)
when TiltTemplate then buffer << fn.render(@scope)
else
raise ArgumentError, "Unable to render `#{fn}`"
end
buffer
else
with_scope(scope){ render(fn, nil, buffer) }
end
end | ruby | def render(fn, scope = nil, buffer = "")
if scope.nil?
case fn
when String then buffer << fn
when Proc then fn.call(self, buffer)
when Template then fn.call(@scope, buffer)
when TiltTemplate then buffer << fn.render(@scope)
else
raise ArgumentError, "Unable to render `#{fn}`"
end
buffer
else
with_scope(scope){ render(fn, nil, buffer) }
end
end | [
"def",
"render",
"(",
"fn",
",",
"scope",
"=",
"nil",
",",
"buffer",
"=",
"\"\"",
")",
"if",
"scope",
".",
"nil?",
"case",
"fn",
"when",
"String",
"then",
"buffer",
"<<",
"fn",
"when",
"Proc",
"then",
"fn",
".",
"call",
"(",
"self",
",",
"buffer",
")",
"when",
"Template",
"then",
"fn",
".",
"call",
"(",
"@scope",
",",
"buffer",
")",
"when",
"TiltTemplate",
"then",
"buffer",
"<<",
"fn",
".",
"render",
"(",
"@scope",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Unable to render `#{fn}`\"",
"end",
"buffer",
"else",
"with_scope",
"(",
"scope",
")",
"{",
"render",
"(",
"fn",
",",
"nil",
",",
"buffer",
")",
"}",
"end",
"end"
]
| rendering
Renders `fn` to a `buffer`, optionally extending the current scope.
`fn` can either be a String (immediately pushed on the buffer), a Proc (taken as a
tag block to render further), or a Template (taken as a partial to render in the
current scope).
Is `scope` is specified, the current scope is first branched to use to new one in
priority, then rendering applies and the newly created scope if then poped.
Returns the buffer. | [
"rendering",
"Renders",
"fn",
"to",
"a",
"buffer",
"optionally",
"extending",
"the",
"current",
"scope",
"."
]
| 6e45f0c2ae2c8ff27accfab42e4af8ce6d1ff051 | https://github.com/blambeau/wlang/blob/6e45f0c2ae2c8ff27accfab42e4af8ce6d1ff051/lib/wlang/dialect.rb#L139-L153 | train |
blambeau/wlang | lib/wlang/dialect.rb | WLang.Dialect.evaluate | def evaluate(expr, *default, &bl)
case expr
when Symbol, String
catch(:fail) do
return scope.evaluate(expr, self, *default, &bl)
end
raise NameError, "Unable to find `#{expr}` on #{scope}"
else
evaluate(render(expr), *default, &bl)
end
end | ruby | def evaluate(expr, *default, &bl)
case expr
when Symbol, String
catch(:fail) do
return scope.evaluate(expr, self, *default, &bl)
end
raise NameError, "Unable to find `#{expr}` on #{scope}"
else
evaluate(render(expr), *default, &bl)
end
end | [
"def",
"evaluate",
"(",
"expr",
",",
"*",
"default",
",",
"&",
"bl",
")",
"case",
"expr",
"when",
"Symbol",
",",
"String",
"catch",
"(",
":fail",
")",
"do",
"return",
"scope",
".",
"evaluate",
"(",
"expr",
",",
"self",
",",
"*",
"default",
",",
"&",
"bl",
")",
"end",
"raise",
"NameError",
",",
"\"Unable to find `#{expr}` on #{scope}\"",
"else",
"evaluate",
"(",
"render",
"(",
"expr",
")",
",",
"*",
"default",
",",
"&",
"bl",
")",
"end",
"end"
]
| Evaluates `expr` in the current scope. `expr` can be either
* a Symbol or a String, taken as a dot expression to evaluate
* a Proc or a Template, first rendered and then evaluated
Evaluation is delegated to the scope (@see Scope#evaluate) and the result returned
by this method. | [
"Evaluates",
"expr",
"in",
"the",
"current",
"scope",
".",
"expr",
"can",
"be",
"either"
]
| 6e45f0c2ae2c8ff27accfab42e4af8ce6d1ff051 | https://github.com/blambeau/wlang/blob/6e45f0c2ae2c8ff27accfab42e4af8ce6d1ff051/lib/wlang/dialect.rb#L183-L193 | train |
tongueroo/forger | lib/forger/network.rb | Forger.Network.security_group_id | def security_group_id
resp = ec2.describe_security_groups(filters: [
{name: "vpc-id", values: [vpc_id]},
{name: "group-name", values: ["default"]}
])
resp.security_groups.first.group_id
end | ruby | def security_group_id
resp = ec2.describe_security_groups(filters: [
{name: "vpc-id", values: [vpc_id]},
{name: "group-name", values: ["default"]}
])
resp.security_groups.first.group_id
end | [
"def",
"security_group_id",
"resp",
"=",
"ec2",
".",
"describe_security_groups",
"(",
"filters",
":",
"[",
"{",
"name",
":",
"\"vpc-id\"",
",",
"values",
":",
"[",
"vpc_id",
"]",
"}",
",",
"{",
"name",
":",
"\"group-name\"",
",",
"values",
":",
"[",
"\"default\"",
"]",
"}",
"]",
")",
"resp",
".",
"security_groups",
".",
"first",
".",
"group_id",
"end"
]
| default security group | [
"default",
"security",
"group"
]
| 4146215b144bfd40874dfd0db3ad33ab0cc5f7a9 | https://github.com/tongueroo/forger/blob/4146215b144bfd40874dfd0db3ad33ab0cc5f7a9/lib/forger/network.rb#L39-L45 | train |
bdurand/sunspot_index_queue | lib/sunspot/index_queue.rb | Sunspot.IndexQueue.process | def process
count = 0
loop do
entries = Entry.next_batch!(self)
if entries.nil? || entries.empty?
break if Entry.ready_count(self) == 0
else
batch = Batch.new(self, entries)
if defined?(@batch_handler) && @batch_handler
@batch_handler.call(batch)
else
batch.submit!
end
count += entries.select{|e| e.processed? }.size
end
end
count
end | ruby | def process
count = 0
loop do
entries = Entry.next_batch!(self)
if entries.nil? || entries.empty?
break if Entry.ready_count(self) == 0
else
batch = Batch.new(self, entries)
if defined?(@batch_handler) && @batch_handler
@batch_handler.call(batch)
else
batch.submit!
end
count += entries.select{|e| e.processed? }.size
end
end
count
end | [
"def",
"process",
"count",
"=",
"0",
"loop",
"do",
"entries",
"=",
"Entry",
".",
"next_batch!",
"(",
"self",
")",
"if",
"entries",
".",
"nil?",
"||",
"entries",
".",
"empty?",
"break",
"if",
"Entry",
".",
"ready_count",
"(",
"self",
")",
"==",
"0",
"else",
"batch",
"=",
"Batch",
".",
"new",
"(",
"self",
",",
"entries",
")",
"if",
"defined?",
"(",
"@batch_handler",
")",
"&&",
"@batch_handler",
"@batch_handler",
".",
"call",
"(",
"batch",
")",
"else",
"batch",
".",
"submit!",
"end",
"count",
"+=",
"entries",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"processed?",
"}",
".",
"size",
"end",
"end",
"count",
"end"
]
| Process the queue. Exits when there are no more entries to process at the current time.
Returns the number of entries processed.
If any errors are encountered while processing the queue, they will be logged with the errors so they can
be fixed and tried again later. However, if Solr is refusing connections, the processing is stopped right
away and a Sunspot::IndexQueue::SolrNotResponding exception is raised. | [
"Process",
"the",
"queue",
".",
"Exits",
"when",
"there",
"are",
"no",
"more",
"entries",
"to",
"process",
"at",
"the",
"current",
"time",
".",
"Returns",
"the",
"number",
"of",
"entries",
"processed",
"."
]
| 11c2846d0f0f6164de3fdde5202089823e7b9d78 | https://github.com/bdurand/sunspot_index_queue/blob/11c2846d0f0f6164de3fdde5202089823e7b9d78/lib/sunspot/index_queue.rb#L138-L155 | train |
veny/orientdb4r | lib/orientdb4r/rest/model.rb | Orientdb4r.HashExtension.get_mandatory_attribute | def get_mandatory_attribute(name)
key = name.to_s
raise ::ArgumentError, "unknown attribute, name=#{key}" unless self.include? key
self[key]
end | ruby | def get_mandatory_attribute(name)
key = name.to_s
raise ::ArgumentError, "unknown attribute, name=#{key}" unless self.include? key
self[key]
end | [
"def",
"get_mandatory_attribute",
"(",
"name",
")",
"key",
"=",
"name",
".",
"to_s",
"raise",
"::",
"ArgumentError",
",",
"\"unknown attribute, name=#{key}\"",
"unless",
"self",
".",
"include?",
"key",
"self",
"[",
"key",
"]",
"end"
]
| Gets an attribute value that has to be presented. | [
"Gets",
"an",
"attribute",
"value",
"that",
"has",
"to",
"be",
"presented",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/model.rb#L10-L14 | train |
veny/orientdb4r | lib/orientdb4r/rest/model.rb | Orientdb4r.OClass.property | def property(name)
raise ArgumentError, 'no properties defined on class' if properties.nil?
props = properties.select { |i| i['name'] == name.to_s }
raise ::ArgumentError, "unknown property, name=#{name}" if props.empty?
raise ::ArgumentError, "too many properties found, name=#{name}" if props.size > 1 # just to be sure
props[0]
end | ruby | def property(name)
raise ArgumentError, 'no properties defined on class' if properties.nil?
props = properties.select { |i| i['name'] == name.to_s }
raise ::ArgumentError, "unknown property, name=#{name}" if props.empty?
raise ::ArgumentError, "too many properties found, name=#{name}" if props.size > 1 # just to be sure
props[0]
end | [
"def",
"property",
"(",
"name",
")",
"raise",
"ArgumentError",
",",
"'no properties defined on class'",
"if",
"properties",
".",
"nil?",
"props",
"=",
"properties",
".",
"select",
"{",
"|",
"i",
"|",
"i",
"[",
"'name'",
"]",
"==",
"name",
".",
"to_s",
"}",
"raise",
"::",
"ArgumentError",
",",
"\"unknown property, name=#{name}\"",
"if",
"props",
".",
"empty?",
"raise",
"::",
"ArgumentError",
",",
"\"too many properties found, name=#{name}\"",
"if",
"props",
".",
"size",
">",
"1",
"props",
"[",
"0",
"]",
"end"
]
| Gets a property with the given name. | [
"Gets",
"a",
"property",
"with",
"the",
"given",
"name",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/model.rb#L38-L44 | train |
veny/orientdb4r | lib/orientdb4r/utils.rb | Orientdb4r.Utils.blank? | def blank?(str)
str.nil? or (str.is_a? String and str.strip.empty?)
end | ruby | def blank?(str)
str.nil? or (str.is_a? String and str.strip.empty?)
end | [
"def",
"blank?",
"(",
"str",
")",
"str",
".",
"nil?",
"or",
"(",
"str",
".",
"is_a?",
"String",
"and",
"str",
".",
"strip",
".",
"empty?",
")",
"end"
]
| Checks if a given string is either 'nil' or empty string. | [
"Checks",
"if",
"a",
"given",
"string",
"is",
"either",
"nil",
"or",
"empty",
"string",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/utils.rb#L39-L41 | train |
tongueroo/forger | lib/forger/template/context.rb | Forger::Template.Context.load_custom_helpers | def load_custom_helpers
Dir.glob("#{Forger.root}/app/helpers/**/*_helper.rb").each do |path|
filename = path.sub(%r{.*/},'').sub('.rb','')
module_name = filename.classify
# Prepend a period so require works FORGER_ROOT is set to a relative path
# without a period.
#
# Example: FORGER_ROOT=tmp/project
first_char = path[0..0]
path = "./#{path}" unless %w[. /].include?(first_char)
require path
self.class.send :include, module_name.constantize
end
end | ruby | def load_custom_helpers
Dir.glob("#{Forger.root}/app/helpers/**/*_helper.rb").each do |path|
filename = path.sub(%r{.*/},'').sub('.rb','')
module_name = filename.classify
# Prepend a period so require works FORGER_ROOT is set to a relative path
# without a period.
#
# Example: FORGER_ROOT=tmp/project
first_char = path[0..0]
path = "./#{path}" unless %w[. /].include?(first_char)
require path
self.class.send :include, module_name.constantize
end
end | [
"def",
"load_custom_helpers",
"Dir",
".",
"glob",
"(",
"\"#{Forger.root}/app/helpers/**/*_helper.rb\"",
")",
".",
"each",
"do",
"|",
"path",
"|",
"filename",
"=",
"path",
".",
"sub",
"(",
"%r{",
"}",
",",
"''",
")",
".",
"sub",
"(",
"'.rb'",
",",
"''",
")",
"module_name",
"=",
"filename",
".",
"classify",
"first_char",
"=",
"path",
"[",
"0",
"..",
"0",
"]",
"path",
"=",
"\"./#{path}\"",
"unless",
"%w[",
".",
"/",
"]",
".",
"include?",
"(",
"first_char",
")",
"require",
"path",
"self",
".",
"class",
".",
"send",
":include",
",",
"module_name",
".",
"constantize",
"end",
"end"
]
| Load custom helper methods from project | [
"Load",
"custom",
"helper",
"methods",
"from",
"project"
]
| 4146215b144bfd40874dfd0db3ad33ab0cc5f7a9 | https://github.com/tongueroo/forger/blob/4146215b144bfd40874dfd0db3ad33ab0cc5f7a9/lib/forger/template/context.rb#L16-L30 | train |
XOlator/wayback_gem | lib/wayback/base.rb | Wayback.Base.attrs | def attrs
@attrs.inject({}) do |attrs, (key, value)|
attrs.merge!(key => respond_to?(key) ? send(key) : value)
end
end | ruby | def attrs
@attrs.inject({}) do |attrs, (key, value)|
attrs.merge!(key => respond_to?(key) ? send(key) : value)
end
end | [
"def",
"attrs",
"@attrs",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"attrs",
",",
"(",
"key",
",",
"value",
")",
"|",
"attrs",
".",
"merge!",
"(",
"key",
"=>",
"respond_to?",
"(",
"key",
")",
"?",
"send",
"(",
"key",
")",
":",
"value",
")",
"end",
"end"
]
| Retrieve the attributes of an object
@return [Hash] | [
"Retrieve",
"the",
"attributes",
"of",
"an",
"object"
]
| 1f4cdf3e8d023f34abffbce7ff46bc11b2ab8073 | https://github.com/XOlator/wayback_gem/blob/1f4cdf3e8d023f34abffbce7ff46bc11b2ab8073/lib/wayback/base.rb#L95-L99 | train |
veny/orientdb4r | lib/orientdb4r/client.rb | Orientdb4r.Client.database_exists? | def database_exists?(options)
rslt = true
begin
get_database options
rescue OrientdbError
rslt = false
end
rslt
end | ruby | def database_exists?(options)
rslt = true
begin
get_database options
rescue OrientdbError
rslt = false
end
rslt
end | [
"def",
"database_exists?",
"(",
"options",
")",
"rslt",
"=",
"true",
"begin",
"get_database",
"options",
"rescue",
"OrientdbError",
"rslt",
"=",
"false",
"end",
"rslt",
"end"
]
| Checks existence of a given database.
Client has not to be connected to see databases suitable to connect. | [
"Checks",
"existence",
"of",
"a",
"given",
"database",
".",
"Client",
"has",
"not",
"to",
"be",
"connected",
"to",
"see",
"databases",
"suitable",
"to",
"connect",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/client.rb#L92-L100 | train |
veny/orientdb4r | lib/orientdb4r/client.rb | Orientdb4r.Client.class_exists? | def class_exists?(name)
rslt = true
begin
get_class name
rescue OrientdbError => e
raise e if e.is_a? ConnectionError and e.message == 'not connected' # workaround for AOP2 (unable to decorate already existing methods)
rslt = false
end
rslt
end | ruby | def class_exists?(name)
rslt = true
begin
get_class name
rescue OrientdbError => e
raise e if e.is_a? ConnectionError and e.message == 'not connected' # workaround for AOP2 (unable to decorate already existing methods)
rslt = false
end
rslt
end | [
"def",
"class_exists?",
"(",
"name",
")",
"rslt",
"=",
"true",
"begin",
"get_class",
"name",
"rescue",
"OrientdbError",
"=>",
"e",
"raise",
"e",
"if",
"e",
".",
"is_a?",
"ConnectionError",
"and",
"e",
".",
"message",
"==",
"'not connected'",
"rslt",
"=",
"false",
"end",
"rslt",
"end"
]
| Checks existence of a given class. | [
"Checks",
"existence",
"of",
"a",
"given",
"class",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/client.rb#L208-L217 | train |
veny/orientdb4r | lib/orientdb4r/client.rb | Orientdb4r.Client.drop_class | def drop_class(name, options={})
raise ArgumentError, 'class name is blank' if blank?(name)
# :mode=>:strict forbids to drop a class that is a super class for other one
opt_pattern = { :mode => :nil }
verify_options(options, opt_pattern)
if :strict == options[:mode]
response = get_database
children = response['classes'].select { |i| i['superClass'] == name }
unless children.empty?
raise OrientdbError, "class is super-class, cannot be deleted, name=#{name}"
end
end
command "DROP CLASS #{name}"
end | ruby | def drop_class(name, options={})
raise ArgumentError, 'class name is blank' if blank?(name)
# :mode=>:strict forbids to drop a class that is a super class for other one
opt_pattern = { :mode => :nil }
verify_options(options, opt_pattern)
if :strict == options[:mode]
response = get_database
children = response['classes'].select { |i| i['superClass'] == name }
unless children.empty?
raise OrientdbError, "class is super-class, cannot be deleted, name=#{name}"
end
end
command "DROP CLASS #{name}"
end | [
"def",
"drop_class",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'class name is blank'",
"if",
"blank?",
"(",
"name",
")",
"opt_pattern",
"=",
"{",
":mode",
"=>",
":nil",
"}",
"verify_options",
"(",
"options",
",",
"opt_pattern",
")",
"if",
":strict",
"==",
"options",
"[",
":mode",
"]",
"response",
"=",
"get_database",
"children",
"=",
"response",
"[",
"'classes'",
"]",
".",
"select",
"{",
"|",
"i",
"|",
"i",
"[",
"'superClass'",
"]",
"==",
"name",
"}",
"unless",
"children",
".",
"empty?",
"raise",
"OrientdbError",
",",
"\"class is super-class, cannot be deleted, name=#{name}\"",
"end",
"end",
"command",
"\"DROP CLASS #{name}\"",
"end"
]
| Removes a class from the schema. | [
"Removes",
"a",
"class",
"from",
"the",
"schema",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/client.rb#L222-L237 | train |
veny/orientdb4r | lib/orientdb4r/client.rb | Orientdb4r.Client.create_property | def create_property(clazz, property, type, options={})
raise ArgumentError, "class name is blank" if blank?(clazz)
raise ArgumentError, "property name is blank" if blank?(property)
opt_pattern = {
:mandatory => :optional , :notnull => :optional, :min => :optional, :max => :optional,
:readonly => :optional, :linked_class => :optional
}
verify_options(options, opt_pattern)
cmd = "CREATE PROPERTY #{clazz}.#{property} #{type.to_s}"
# link?
if [:link, :linklist, :linkset, :linkmap].include? type.to_s.downcase.to_sym
raise ArgumentError, "defined linked-type, but not linked-class" unless options.include? :linked_class
cmd << " #{options[:linked_class]}"
end
command cmd
# ALTER PROPERTY ...
options.delete :linked_class # it's not option for ALTER
unless options.empty?
options.each do |k,v|
command "ALTER PROPERTY #{clazz}.#{property} #{k.to_s.upcase} #{v}"
end
end
end | ruby | def create_property(clazz, property, type, options={})
raise ArgumentError, "class name is blank" if blank?(clazz)
raise ArgumentError, "property name is blank" if blank?(property)
opt_pattern = {
:mandatory => :optional , :notnull => :optional, :min => :optional, :max => :optional,
:readonly => :optional, :linked_class => :optional
}
verify_options(options, opt_pattern)
cmd = "CREATE PROPERTY #{clazz}.#{property} #{type.to_s}"
# link?
if [:link, :linklist, :linkset, :linkmap].include? type.to_s.downcase.to_sym
raise ArgumentError, "defined linked-type, but not linked-class" unless options.include? :linked_class
cmd << " #{options[:linked_class]}"
end
command cmd
# ALTER PROPERTY ...
options.delete :linked_class # it's not option for ALTER
unless options.empty?
options.each do |k,v|
command "ALTER PROPERTY #{clazz}.#{property} #{k.to_s.upcase} #{v}"
end
end
end | [
"def",
"create_property",
"(",
"clazz",
",",
"property",
",",
"type",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"class name is blank\"",
"if",
"blank?",
"(",
"clazz",
")",
"raise",
"ArgumentError",
",",
"\"property name is blank\"",
"if",
"blank?",
"(",
"property",
")",
"opt_pattern",
"=",
"{",
":mandatory",
"=>",
":optional",
",",
":notnull",
"=>",
":optional",
",",
":min",
"=>",
":optional",
",",
":max",
"=>",
":optional",
",",
":readonly",
"=>",
":optional",
",",
":linked_class",
"=>",
":optional",
"}",
"verify_options",
"(",
"options",
",",
"opt_pattern",
")",
"cmd",
"=",
"\"CREATE PROPERTY #{clazz}.#{property} #{type.to_s}\"",
"if",
"[",
":link",
",",
":linklist",
",",
":linkset",
",",
":linkmap",
"]",
".",
"include?",
"type",
".",
"to_s",
".",
"downcase",
".",
"to_sym",
"raise",
"ArgumentError",
",",
"\"defined linked-type, but not linked-class\"",
"unless",
"options",
".",
"include?",
":linked_class",
"cmd",
"<<",
"\" #{options[:linked_class]}\"",
"end",
"command",
"cmd",
"options",
".",
"delete",
":linked_class",
"unless",
"options",
".",
"empty?",
"options",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"command",
"\"ALTER PROPERTY #{clazz}.#{property} #{k.to_s.upcase} #{v}\"",
"end",
"end",
"end"
]
| Creates a new property in the schema.
You need to create the class before. | [
"Creates",
"a",
"new",
"property",
"in",
"the",
"schema",
".",
"You",
"need",
"to",
"create",
"the",
"class",
"before",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/client.rb#L243-L267 | train |
veny/orientdb4r | lib/orientdb4r/client.rb | Orientdb4r.Client.time_around | def time_around(&block)
start = Time.now
rslt = block.call
query_log("#{aop_context[:class].name}##{aop_context[:method]}", "elapsed time = #{Time.now - start} [s]")
rslt
end | ruby | def time_around(&block)
start = Time.now
rslt = block.call
query_log("#{aop_context[:class].name}##{aop_context[:method]}", "elapsed time = #{Time.now - start} [s]")
rslt
end | [
"def",
"time_around",
"(",
"&",
"block",
")",
"start",
"=",
"Time",
".",
"now",
"rslt",
"=",
"block",
".",
"call",
"query_log",
"(",
"\"#{aop_context[:class].name}##{aop_context[:method]}\"",
",",
"\"elapsed time = #{Time.now - start} [s]\"",
")",
"rslt",
"end"
]
| Around advice to meassure and print the method time. | [
"Around",
"advice",
"to",
"meassure",
"and",
"print",
"the",
"method",
"time",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/client.rb#L350-L355 | train |
fromAtoB/awesome_xml | lib/awesome_xml/class_methods.rb | AwesomeXML.ClassMethods.constant_node | def constant_node(name, value, options = {})
attr_reader name.to_sym
define_method("parse_#{name}".to_sym) do
instance_variable_set("@#{name}", value)
end
register(name, options[:private])
end | ruby | def constant_node(name, value, options = {})
attr_reader name.to_sym
define_method("parse_#{name}".to_sym) do
instance_variable_set("@#{name}", value)
end
register(name, options[:private])
end | [
"def",
"constant_node",
"(",
"name",
",",
"value",
",",
"options",
"=",
"{",
"}",
")",
"attr_reader",
"name",
".",
"to_sym",
"define_method",
"(",
"\"parse_#{name}\"",
".",
"to_sym",
")",
"do",
"instance_variable_set",
"(",
"\"@#{name}\"",
",",
"value",
")",
"end",
"register",
"(",
"name",
",",
"options",
"[",
":private",
"]",
")",
"end"
]
| Defines a method on your class returning a constant. | [
"Defines",
"a",
"method",
"on",
"your",
"class",
"returning",
"a",
"constant",
"."
]
| 4011f0553cd0a62579f5ef4eae6d9ce64142aff0 | https://github.com/fromAtoB/awesome_xml/blob/4011f0553cd0a62579f5ef4eae6d9ce64142aff0/lib/awesome_xml/class_methods.rb#L31-L37 | train |
fromAtoB/awesome_xml | lib/awesome_xml/class_methods.rb | AwesomeXML.ClassMethods.node | def node(name, type, options = {}, &block)
attr_reader name.to_sym
options[:local_context] = @local_context
xpath = NodeXPath.new(name, options).xpath
define_method("parse_#{name}".to_sym) do
evaluate_args = [xpath, AwesomeXML::Type.for(type, self.class.name), options]
instance_variable_set(
"@#{name}",
evaluate_nodes(*evaluate_args, &block)
)
end
register(name, options[:private])
end | ruby | def node(name, type, options = {}, &block)
attr_reader name.to_sym
options[:local_context] = @local_context
xpath = NodeXPath.new(name, options).xpath
define_method("parse_#{name}".to_sym) do
evaluate_args = [xpath, AwesomeXML::Type.for(type, self.class.name), options]
instance_variable_set(
"@#{name}",
evaluate_nodes(*evaluate_args, &block)
)
end
register(name, options[:private])
end | [
"def",
"node",
"(",
"name",
",",
"type",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"attr_reader",
"name",
".",
"to_sym",
"options",
"[",
":local_context",
"]",
"=",
"@local_context",
"xpath",
"=",
"NodeXPath",
".",
"new",
"(",
"name",
",",
"options",
")",
".",
"xpath",
"define_method",
"(",
"\"parse_#{name}\"",
".",
"to_sym",
")",
"do",
"evaluate_args",
"=",
"[",
"xpath",
",",
"AwesomeXML",
"::",
"Type",
".",
"for",
"(",
"type",
",",
"self",
".",
"class",
".",
"name",
")",
",",
"options",
"]",
"instance_variable_set",
"(",
"\"@#{name}\"",
",",
"evaluate_nodes",
"(",
"*",
"evaluate_args",
",",
"&",
"block",
")",
")",
"end",
"register",
"(",
"name",
",",
"options",
"[",
":private",
"]",
")",
"end"
]
| Defines a method on your class returning a parsed value | [
"Defines",
"a",
"method",
"on",
"your",
"class",
"returning",
"a",
"parsed",
"value"
]
| 4011f0553cd0a62579f5ef4eae6d9ce64142aff0 | https://github.com/fromAtoB/awesome_xml/blob/4011f0553cd0a62579f5ef4eae6d9ce64142aff0/lib/awesome_xml/class_methods.rb#L47-L59 | train |
davidesantangelo/webinspector | lib/web_inspector/inspector.rb | WebInspector.Inspector.validate_url_domain | def validate_url_domain(u)
# Enforce a few bare standards before proceeding
u = "#{u}"
u = "/" if u.empty?
begin
# Look for evidence of a host. If this is a relative link
# like '/contact', add the page host.
domained_url = @host + u unless (u.split("/").first || "").match(/(\:|\.)/)
domained_url ||= u
# http the URL if it is missing
httpped_url = "http://" + domained_url unless domained_url[0..3] == 'http'
httpped_url ||= domained_url
# Make sure the URL parses
uri = URI.parse(httpped_url)
# Make sure the URL passes ICANN rules.
# The PublicSuffix object splits the domain and subdomain
# (unlike URI), which allows more liberal URL matching.
return PublicSuffix.parse(uri.host)
rescue URI::InvalidURIError, PublicSuffix::DomainInvalid
return false
end
end | ruby | def validate_url_domain(u)
# Enforce a few bare standards before proceeding
u = "#{u}"
u = "/" if u.empty?
begin
# Look for evidence of a host. If this is a relative link
# like '/contact', add the page host.
domained_url = @host + u unless (u.split("/").first || "").match(/(\:|\.)/)
domained_url ||= u
# http the URL if it is missing
httpped_url = "http://" + domained_url unless domained_url[0..3] == 'http'
httpped_url ||= domained_url
# Make sure the URL parses
uri = URI.parse(httpped_url)
# Make sure the URL passes ICANN rules.
# The PublicSuffix object splits the domain and subdomain
# (unlike URI), which allows more liberal URL matching.
return PublicSuffix.parse(uri.host)
rescue URI::InvalidURIError, PublicSuffix::DomainInvalid
return false
end
end | [
"def",
"validate_url_domain",
"(",
"u",
")",
"u",
"=",
"\"#{u}\"",
"u",
"=",
"\"/\"",
"if",
"u",
".",
"empty?",
"begin",
"domained_url",
"=",
"@host",
"+",
"u",
"unless",
"(",
"u",
".",
"split",
"(",
"\"/\"",
")",
".",
"first",
"||",
"\"\"",
")",
".",
"match",
"(",
"/",
"\\:",
"\\.",
"/",
")",
"domained_url",
"||=",
"u",
"httpped_url",
"=",
"\"http://\"",
"+",
"domained_url",
"unless",
"domained_url",
"[",
"0",
"..",
"3",
"]",
"==",
"'http'",
"httpped_url",
"||=",
"domained_url",
"uri",
"=",
"URI",
".",
"parse",
"(",
"httpped_url",
")",
"return",
"PublicSuffix",
".",
"parse",
"(",
"uri",
".",
"host",
")",
"rescue",
"URI",
"::",
"InvalidURIError",
",",
"PublicSuffix",
"::",
"DomainInvalid",
"return",
"false",
"end",
"end"
]
| Normalize and validate the URLs on the page for comparison | [
"Normalize",
"and",
"validate",
"the",
"URLs",
"on",
"the",
"page",
"for",
"comparison"
]
| 430f4e74d7a4977736b99fd0989c5acfd3a57b1d | https://github.com/davidesantangelo/webinspector/blob/430f4e74d7a4977736b99fd0989c5acfd3a57b1d/lib/web_inspector/inspector.rb#L79-L104 | train |
Antondomashnev/danger-missed_localizable_strings | lib/missed_localizable_strings/plugin.rb | Danger.DangerMissedLocalizableStrings.check_localizable_omissions | def check_localizable_omissions
localizable_files = not_deleted_localizable_files
keys_by_file = extract_keys_from_files(localizable_files)
entries = localizable_strings_missed_entries(keys_by_file)
print_missed_entries entries unless entries.empty?
end | ruby | def check_localizable_omissions
localizable_files = not_deleted_localizable_files
keys_by_file = extract_keys_from_files(localizable_files)
entries = localizable_strings_missed_entries(keys_by_file)
print_missed_entries entries unless entries.empty?
end | [
"def",
"check_localizable_omissions",
"localizable_files",
"=",
"not_deleted_localizable_files",
"keys_by_file",
"=",
"extract_keys_from_files",
"(",
"localizable_files",
")",
"entries",
"=",
"localizable_strings_missed_entries",
"(",
"keys_by_file",
")",
"print_missed_entries",
"entries",
"unless",
"entries",
".",
"empty?",
"end"
]
| Checks whether there are any missed entries in
all Localizable.strings from PR's changeset
files and prints out any found entries.
@return [void] | [
"Checks",
"whether",
"there",
"are",
"any",
"missed",
"entries",
"in",
"all",
"Localizable",
".",
"strings",
"from",
"PR",
"s",
"changeset",
"files",
"and",
"prints",
"out",
"any",
"found",
"entries",
"."
]
| 5f149ff97616a3bce53522842685e29571075b97 | https://github.com/Antondomashnev/danger-missed_localizable_strings/blob/5f149ff97616a3bce53522842685e29571075b97/lib/missed_localizable_strings/plugin.rb#L24-L29 | train |
Antondomashnev/danger-missed_localizable_strings | lib/missed_localizable_strings/plugin.rb | Danger.DangerMissedLocalizableStrings.extract_keys_from_files | def extract_keys_from_files(localizable_files)
keys_from_file = {}
localizable_files.each do |file|
lines = File.readlines(file)
# Grab just the keys, we don't need the translation
keys = lines.map { |e| e.split("=").first }
# Filter newlines and comments
keys = keys.select do |e|
e != "\n" && !e.start_with?("/*") && !e.start_with?("//")
end
keys_from_file[file] = keys
end
keys_from_file
end | ruby | def extract_keys_from_files(localizable_files)
keys_from_file = {}
localizable_files.each do |file|
lines = File.readlines(file)
# Grab just the keys, we don't need the translation
keys = lines.map { |e| e.split("=").first }
# Filter newlines and comments
keys = keys.select do |e|
e != "\n" && !e.start_with?("/*") && !e.start_with?("//")
end
keys_from_file[file] = keys
end
keys_from_file
end | [
"def",
"extract_keys_from_files",
"(",
"localizable_files",
")",
"keys_from_file",
"=",
"{",
"}",
"localizable_files",
".",
"each",
"do",
"|",
"file",
"|",
"lines",
"=",
"File",
".",
"readlines",
"(",
"file",
")",
"keys",
"=",
"lines",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"split",
"(",
"\"=\"",
")",
".",
"first",
"}",
"keys",
"=",
"keys",
".",
"select",
"do",
"|",
"e",
"|",
"e",
"!=",
"\"\\n\"",
"&&",
"!",
"e",
".",
"start_with?",
"(",
"\"/*\"",
")",
"&&",
"!",
"e",
".",
"start_with?",
"(",
"\"//\"",
")",
"end",
"keys_from_file",
"[",
"file",
"]",
"=",
"keys",
"end",
"keys_from_file",
"end"
]
| A hash with keyes - Localizable.strings file and
values - modified keys from file | [
"A",
"hash",
"with",
"keyes",
"-",
"Localizable",
".",
"strings",
"file",
"and",
"values",
"-",
"modified",
"keys",
"from",
"file"
]
| 5f149ff97616a3bce53522842685e29571075b97 | https://github.com/Antondomashnev/danger-missed_localizable_strings/blob/5f149ff97616a3bce53522842685e29571075b97/lib/missed_localizable_strings/plugin.rb#L82-L96 | train |
caseyscarborough/omdbapi | lib/omdbapi/client.rb | OMDB.Client.title | def title(title, options = {})
options.merge!(title: title)
params = build_params(options)
get '/', params
end | ruby | def title(title, options = {})
options.merge!(title: title)
params = build_params(options)
get '/', params
end | [
"def",
"title",
"(",
"title",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"merge!",
"(",
"title",
":",
"title",
")",
"params",
"=",
"build_params",
"(",
"options",
")",
"get",
"'/'",
",",
"params",
"end"
]
| Retrieves a movie or show based on its title.
@param title [String] The title of the movie or show.
@param options [Hash] Options for the title, plot or year.
@option options [Integer] :year The year of the movie.
@option options [String] :plot 'short' (default), 'full'
@option options [Integer] :season The season to retrieve.
@option options [Integer] :episode The episode to retrieve. Requires the season parameter.
@option options [Boolean] :tomatoes Include Rotten Tomatoes ratings.
@return [Hash]
@example
OMDB.title('Game of Thrones') | [
"Retrieves",
"a",
"movie",
"or",
"show",
"based",
"on",
"its",
"title",
"."
]
| 3061e8edc8aed5ed1f278b1162b1461fb53893be | https://github.com/caseyscarborough/omdbapi/blob/3061e8edc8aed5ed1f278b1162b1461fb53893be/lib/omdbapi/client.rb#L23-L27 | train |
caseyscarborough/omdbapi | lib/omdbapi/client.rb | OMDB.Client.id | def id(imdb_id, options = {})
options.merge!(id: imdb_id)
params = build_params(options)
get '/', params
end | ruby | def id(imdb_id, options = {})
options.merge!(id: imdb_id)
params = build_params(options)
get '/', params
end | [
"def",
"id",
"(",
"imdb_id",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"merge!",
"(",
"id",
":",
"imdb_id",
")",
"params",
"=",
"build_params",
"(",
"options",
")",
"get",
"'/'",
",",
"params",
"end"
]
| Retrieves a movie or show based on its IMDb ID.
@param imdb_id [String] The IMDb ID of the movie or show.
@option options [Boolean] :tomatoes Include Rotten Tomatoes ratings.
@return [Hash]
@example
OMDB.id('tt0944947') | [
"Retrieves",
"a",
"movie",
"or",
"show",
"based",
"on",
"its",
"IMDb",
"ID",
"."
]
| 3061e8edc8aed5ed1f278b1162b1461fb53893be | https://github.com/caseyscarborough/omdbapi/blob/3061e8edc8aed5ed1f278b1162b1461fb53893be/lib/omdbapi/client.rb#L36-L40 | train |
caseyscarborough/omdbapi | lib/omdbapi/client.rb | OMDB.Client.search | def search(title)
results = get '/', { s: title }
if results[:search]
# Return the title if there is only one result, otherwise return the seach results
search = results.search
search.size == 1 ? title(search[0].title) : search
else
results
end
end | ruby | def search(title)
results = get '/', { s: title }
if results[:search]
# Return the title if there is only one result, otherwise return the seach results
search = results.search
search.size == 1 ? title(search[0].title) : search
else
results
end
end | [
"def",
"search",
"(",
"title",
")",
"results",
"=",
"get",
"'/'",
",",
"{",
"s",
":",
"title",
"}",
"if",
"results",
"[",
":search",
"]",
"search",
"=",
"results",
".",
"search",
"search",
".",
"size",
"==",
"1",
"?",
"title",
"(",
"search",
"[",
"0",
"]",
".",
"title",
")",
":",
"search",
"else",
"results",
"end",
"end"
]
| Search for a movie by its title.
@param title [String] The title of the movie or show to search for.
@return [Array, Hash]
@example
OMDB.find('Star Wars') | [
"Search",
"for",
"a",
"movie",
"by",
"its",
"title",
"."
]
| 3061e8edc8aed5ed1f278b1162b1461fb53893be | https://github.com/caseyscarborough/omdbapi/blob/3061e8edc8aed5ed1f278b1162b1461fb53893be/lib/omdbapi/client.rb#L48-L57 | train |
caseyscarborough/omdbapi | lib/omdbapi/client.rb | OMDB.Client.convert_hash_keys | def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [k.to_snake_case.to_sym, convert_hash_keys(v)] }]
else
value
end
end | ruby | def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [k.to_snake_case.to_sym, convert_hash_keys(v)] }]
else
value
end
end | [
"def",
"convert_hash_keys",
"(",
"value",
")",
"case",
"value",
"when",
"Array",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"convert_hash_keys",
"(",
"v",
")",
"}",
"when",
"Hash",
"Hash",
"[",
"value",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"to_snake_case",
".",
"to_sym",
",",
"convert_hash_keys",
"(",
"v",
")",
"]",
"}",
"]",
"else",
"value",
"end",
"end"
]
| Performs a method on all hash keys.
@param value [Array, Hash, Object]
@return [Array, Hash, Object] | [
"Performs",
"a",
"method",
"on",
"all",
"hash",
"keys",
"."
]
| 3061e8edc8aed5ed1f278b1162b1461fb53893be | https://github.com/caseyscarborough/omdbapi/blob/3061e8edc8aed5ed1f278b1162b1461fb53893be/lib/omdbapi/client.rb#L67-L76 | train |
caseyscarborough/omdbapi | lib/omdbapi/client.rb | OMDB.Client.build_params | def build_params(options)
params = {}
params[:t] = options[:title] if options[:title]
params[:i] = options[:id] if options[:id]
params[:y] = options[:year] if options[:year]
params[:plot] = options[:plot] if options[:plot]
params[:season] = options[:season] if options[:season]
params[:episode] = options[:episode] if options[:episode]
params[:type] = options[:type] if options[:type]
params[:tomatoes] = options[:tomatoes] if options[:tomatoes]
params
end | ruby | def build_params(options)
params = {}
params[:t] = options[:title] if options[:title]
params[:i] = options[:id] if options[:id]
params[:y] = options[:year] if options[:year]
params[:plot] = options[:plot] if options[:plot]
params[:season] = options[:season] if options[:season]
params[:episode] = options[:episode] if options[:episode]
params[:type] = options[:type] if options[:type]
params[:tomatoes] = options[:tomatoes] if options[:tomatoes]
params
end | [
"def",
"build_params",
"(",
"options",
")",
"params",
"=",
"{",
"}",
"params",
"[",
":t",
"]",
"=",
"options",
"[",
":title",
"]",
"if",
"options",
"[",
":title",
"]",
"params",
"[",
":i",
"]",
"=",
"options",
"[",
":id",
"]",
"if",
"options",
"[",
":id",
"]",
"params",
"[",
":y",
"]",
"=",
"options",
"[",
":year",
"]",
"if",
"options",
"[",
":year",
"]",
"params",
"[",
":plot",
"]",
"=",
"options",
"[",
":plot",
"]",
"if",
"options",
"[",
":plot",
"]",
"params",
"[",
":season",
"]",
"=",
"options",
"[",
":season",
"]",
"if",
"options",
"[",
":season",
"]",
"params",
"[",
":episode",
"]",
"=",
"options",
"[",
":episode",
"]",
"if",
"options",
"[",
":episode",
"]",
"params",
"[",
":type",
"]",
"=",
"options",
"[",
":type",
"]",
"if",
"options",
"[",
":type",
"]",
"params",
"[",
":tomatoes",
"]",
"=",
"options",
"[",
":tomatoes",
"]",
"if",
"options",
"[",
":tomatoes",
"]",
"params",
"end"
]
| Build parameters for a request.
@param options [Hash] The optional parameters.
@return [Hash] | [
"Build",
"parameters",
"for",
"a",
"request",
"."
]
| 3061e8edc8aed5ed1f278b1162b1461fb53893be | https://github.com/caseyscarborough/omdbapi/blob/3061e8edc8aed5ed1f278b1162b1461fb53893be/lib/omdbapi/client.rb#L82-L93 | train |
veny/orientdb4r | lib/orientdb4r/rest/restclient_node.rb | Orientdb4r.RestClientNode.transform_error2_response | def transform_error2_response(error)
response = ["#{error.message}: #{error.http_body}", error.http_code]
def response.body
self[0]
end
def response.code
self[1]
end
response
end | ruby | def transform_error2_response(error)
response = ["#{error.message}: #{error.http_body}", error.http_code]
def response.body
self[0]
end
def response.code
self[1]
end
response
end | [
"def",
"transform_error2_response",
"(",
"error",
")",
"response",
"=",
"[",
"\"#{error.message}: #{error.http_body}\"",
",",
"error",
".",
"http_code",
"]",
"def",
"response",
".",
"body",
"self",
"[",
"0",
"]",
"end",
"def",
"response",
".",
"code",
"self",
"[",
"1",
"]",
"end",
"response",
"end"
]
| Fakes an error thrown by the library into a response object with methods
'code' and 'body'. | [
"Fakes",
"an",
"error",
"thrown",
"by",
"the",
"library",
"into",
"a",
"response",
"object",
"with",
"methods",
"code",
"and",
"body",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/restclient_node.rb#L64-L73 | train |
veny/orientdb4r | lib/orientdb4r/rest/excon_node.rb | Orientdb4r.ExconNode.connection | def connection
return @connection unless @connection.nil?
options = {}
options[:proxy] = proxy unless proxy.nil?
options[:scheme], options[:host], options[:port]=url.scan(/(.*):\/\/(.*):([0-9]*)/).first
@connection ||= Excon::Connection.new(options)
#:read_timeout => self.class.read_timeout,
#:write_timeout => self.class.write_timeout,
#:connect_timeout => self.class.connect_timeout
end | ruby | def connection
return @connection unless @connection.nil?
options = {}
options[:proxy] = proxy unless proxy.nil?
options[:scheme], options[:host], options[:port]=url.scan(/(.*):\/\/(.*):([0-9]*)/).first
@connection ||= Excon::Connection.new(options)
#:read_timeout => self.class.read_timeout,
#:write_timeout => self.class.write_timeout,
#:connect_timeout => self.class.connect_timeout
end | [
"def",
"connection",
"return",
"@connection",
"unless",
"@connection",
".",
"nil?",
"options",
"=",
"{",
"}",
"options",
"[",
":proxy",
"]",
"=",
"proxy",
"unless",
"proxy",
".",
"nil?",
"options",
"[",
":scheme",
"]",
",",
"options",
"[",
":host",
"]",
",",
"options",
"[",
":port",
"]",
"=",
"url",
".",
"scan",
"(",
"/",
"\\/",
"\\/",
"/",
")",
".",
"first",
"@connection",
"||=",
"Excon",
"::",
"Connection",
".",
"new",
"(",
"options",
")",
"end"
]
| Gets Excon connection. | [
"Gets",
"Excon",
"connection",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/excon_node.rb#L83-L94 | train |
veny/orientdb4r | lib/orientdb4r/rest/excon_node.rb | Orientdb4r.ExconNode.headers | def headers(options)
rslt = {'Authorization' => basic_auth_header(options[:user], options[:password])}
rslt['Cookie'] = "#{SESSION_COOKIE_NAME}=#{session_id}" if !session_id.nil? and !options[:no_session]
rslt['Content-Type'] = options[:content_type] if options.include? :content_type
rslt['User-Agent'] = user_agent unless user_agent.nil?
rslt
end | ruby | def headers(options)
rslt = {'Authorization' => basic_auth_header(options[:user], options[:password])}
rslt['Cookie'] = "#{SESSION_COOKIE_NAME}=#{session_id}" if !session_id.nil? and !options[:no_session]
rslt['Content-Type'] = options[:content_type] if options.include? :content_type
rslt['User-Agent'] = user_agent unless user_agent.nil?
rslt
end | [
"def",
"headers",
"(",
"options",
")",
"rslt",
"=",
"{",
"'Authorization'",
"=>",
"basic_auth_header",
"(",
"options",
"[",
":user",
"]",
",",
"options",
"[",
":password",
"]",
")",
"}",
"rslt",
"[",
"'Cookie'",
"]",
"=",
"\"#{SESSION_COOKIE_NAME}=#{session_id}\"",
"if",
"!",
"session_id",
".",
"nil?",
"and",
"!",
"options",
"[",
":no_session",
"]",
"rslt",
"[",
"'Content-Type'",
"]",
"=",
"options",
"[",
":content_type",
"]",
"if",
"options",
".",
"include?",
":content_type",
"rslt",
"[",
"'User-Agent'",
"]",
"=",
"user_agent",
"unless",
"user_agent",
".",
"nil?",
"rslt",
"end"
]
| Get request headers prepared with session ID and Basic Auth. | [
"Get",
"request",
"headers",
"prepared",
"with",
"session",
"ID",
"and",
"Basic",
"Auth",
"."
]
| d02d0d27e6ed19c5c5ff377a642355f617c785d7 | https://github.com/veny/orientdb4r/blob/d02d0d27e6ed19c5c5ff377a642355f617c785d7/lib/orientdb4r/rest/excon_node.rb#L98-L104 | train |
OSC/ood_appkit | lib/ood_appkit/configuration.rb | OodAppkit.Configuration.set_default_configuration | def set_default_configuration
ActiveSupport::Deprecation.warn("The environment variable RAILS_DATAROOT will be deprecated in an upcoming release, please use OOD_DATAROOT instead.") if ENV['RAILS_DATAROOT']
self.dataroot = ENV['OOD_DATAROOT'] || ENV['RAILS_DATAROOT']
self.dataroot ||= "~/#{ENV['OOD_PORTAL'] || "ondemand"}/data/#{ENV['APP_TOKEN']}" if ENV['APP_TOKEN']
# Add markdown template support
self.markdown = Redcarpet::Markdown.new(
Redcarpet::Render::HTML,
autolink: true,
tables: true,
strikethrough: true,
fenced_code_blocks: true,
no_intra_emphasis: true
)
# Initialize URL handlers for system apps
self.public = Urls::Public.new(
title: ENV['OOD_PUBLIC_TITLE'] || 'Public Assets',
base_url: ENV['OOD_PUBLIC_URL'] || '/public'
)
self.dashboard = Urls::Dashboard.new(
title: ENV['OOD_DASHBOARD_TITLE'] || 'Open OnDemand',
base_url: ENV['OOD_DASHBOARD_URL'] || '/pun/sys/dashboard'
)
self.shell = Urls::Shell.new(
title: ENV['OOD_SHELL_TITLE'] || 'Shell',
base_url: ENV['OOD_SHELL_URL'] || '/pun/sys/shell'
)
self.files = Urls::Files.new(
title: ENV['OOD_FILES_TITLE'] || 'Files',
base_url: ENV['OOD_FILES_URL'] || '/pun/sys/files'
)
self.editor = Urls::Editor.new(
title: ENV['OOD_EDITOR_TITLE'] || 'Editor',
base_url: ENV['OOD_EDITOR_URL'] || '/pun/sys/file-editor'
)
# Add routes for useful features
self.routes = OpenStruct.new(
files_rack_app: true,
wiki: true
)
# Override Bootstrap SASS variables
self.bootstrap = OpenStruct.new(
navbar_inverse_bg: '#53565a',
navbar_inverse_link_color: '#fff',
navbar_inverse_color: '$navbar-inverse-link-color',
navbar_inverse_link_hover_color: 'darken($navbar-inverse-link-color, 20%)',
navbar_inverse_brand_color: '$navbar-inverse-link-color',
navbar_inverse_brand_hover_color: '$navbar-inverse-link-hover-color'
)
ENV.each {|k, v| /^BOOTSTRAP_(?<name>.+)$/ =~ k ? self.bootstrap[name.downcase] = v : nil}
self.enable_log_formatter = ::Rails.env.production?
end | ruby | def set_default_configuration
ActiveSupport::Deprecation.warn("The environment variable RAILS_DATAROOT will be deprecated in an upcoming release, please use OOD_DATAROOT instead.") if ENV['RAILS_DATAROOT']
self.dataroot = ENV['OOD_DATAROOT'] || ENV['RAILS_DATAROOT']
self.dataroot ||= "~/#{ENV['OOD_PORTAL'] || "ondemand"}/data/#{ENV['APP_TOKEN']}" if ENV['APP_TOKEN']
# Add markdown template support
self.markdown = Redcarpet::Markdown.new(
Redcarpet::Render::HTML,
autolink: true,
tables: true,
strikethrough: true,
fenced_code_blocks: true,
no_intra_emphasis: true
)
# Initialize URL handlers for system apps
self.public = Urls::Public.new(
title: ENV['OOD_PUBLIC_TITLE'] || 'Public Assets',
base_url: ENV['OOD_PUBLIC_URL'] || '/public'
)
self.dashboard = Urls::Dashboard.new(
title: ENV['OOD_DASHBOARD_TITLE'] || 'Open OnDemand',
base_url: ENV['OOD_DASHBOARD_URL'] || '/pun/sys/dashboard'
)
self.shell = Urls::Shell.new(
title: ENV['OOD_SHELL_TITLE'] || 'Shell',
base_url: ENV['OOD_SHELL_URL'] || '/pun/sys/shell'
)
self.files = Urls::Files.new(
title: ENV['OOD_FILES_TITLE'] || 'Files',
base_url: ENV['OOD_FILES_URL'] || '/pun/sys/files'
)
self.editor = Urls::Editor.new(
title: ENV['OOD_EDITOR_TITLE'] || 'Editor',
base_url: ENV['OOD_EDITOR_URL'] || '/pun/sys/file-editor'
)
# Add routes for useful features
self.routes = OpenStruct.new(
files_rack_app: true,
wiki: true
)
# Override Bootstrap SASS variables
self.bootstrap = OpenStruct.new(
navbar_inverse_bg: '#53565a',
navbar_inverse_link_color: '#fff',
navbar_inverse_color: '$navbar-inverse-link-color',
navbar_inverse_link_hover_color: 'darken($navbar-inverse-link-color, 20%)',
navbar_inverse_brand_color: '$navbar-inverse-link-color',
navbar_inverse_brand_hover_color: '$navbar-inverse-link-hover-color'
)
ENV.each {|k, v| /^BOOTSTRAP_(?<name>.+)$/ =~ k ? self.bootstrap[name.downcase] = v : nil}
self.enable_log_formatter = ::Rails.env.production?
end | [
"def",
"set_default_configuration",
"ActiveSupport",
"::",
"Deprecation",
".",
"warn",
"(",
"\"The environment variable RAILS_DATAROOT will be deprecated in an upcoming release, please use OOD_DATAROOT instead.\"",
")",
"if",
"ENV",
"[",
"'RAILS_DATAROOT'",
"]",
"self",
".",
"dataroot",
"=",
"ENV",
"[",
"'OOD_DATAROOT'",
"]",
"||",
"ENV",
"[",
"'RAILS_DATAROOT'",
"]",
"self",
".",
"dataroot",
"||=",
"\"~/#{ENV['OOD_PORTAL'] || \"ondemand\"}/data/#{ENV['APP_TOKEN']}\"",
"if",
"ENV",
"[",
"'APP_TOKEN'",
"]",
"self",
".",
"markdown",
"=",
"Redcarpet",
"::",
"Markdown",
".",
"new",
"(",
"Redcarpet",
"::",
"Render",
"::",
"HTML",
",",
"autolink",
":",
"true",
",",
"tables",
":",
"true",
",",
"strikethrough",
":",
"true",
",",
"fenced_code_blocks",
":",
"true",
",",
"no_intra_emphasis",
":",
"true",
")",
"self",
".",
"public",
"=",
"Urls",
"::",
"Public",
".",
"new",
"(",
"title",
":",
"ENV",
"[",
"'OOD_PUBLIC_TITLE'",
"]",
"||",
"'Public Assets'",
",",
"base_url",
":",
"ENV",
"[",
"'OOD_PUBLIC_URL'",
"]",
"||",
"'/public'",
")",
"self",
".",
"dashboard",
"=",
"Urls",
"::",
"Dashboard",
".",
"new",
"(",
"title",
":",
"ENV",
"[",
"'OOD_DASHBOARD_TITLE'",
"]",
"||",
"'Open OnDemand'",
",",
"base_url",
":",
"ENV",
"[",
"'OOD_DASHBOARD_URL'",
"]",
"||",
"'/pun/sys/dashboard'",
")",
"self",
".",
"shell",
"=",
"Urls",
"::",
"Shell",
".",
"new",
"(",
"title",
":",
"ENV",
"[",
"'OOD_SHELL_TITLE'",
"]",
"||",
"'Shell'",
",",
"base_url",
":",
"ENV",
"[",
"'OOD_SHELL_URL'",
"]",
"||",
"'/pun/sys/shell'",
")",
"self",
".",
"files",
"=",
"Urls",
"::",
"Files",
".",
"new",
"(",
"title",
":",
"ENV",
"[",
"'OOD_FILES_TITLE'",
"]",
"||",
"'Files'",
",",
"base_url",
":",
"ENV",
"[",
"'OOD_FILES_URL'",
"]",
"||",
"'/pun/sys/files'",
")",
"self",
".",
"editor",
"=",
"Urls",
"::",
"Editor",
".",
"new",
"(",
"title",
":",
"ENV",
"[",
"'OOD_EDITOR_TITLE'",
"]",
"||",
"'Editor'",
",",
"base_url",
":",
"ENV",
"[",
"'OOD_EDITOR_URL'",
"]",
"||",
"'/pun/sys/file-editor'",
")",
"self",
".",
"routes",
"=",
"OpenStruct",
".",
"new",
"(",
"files_rack_app",
":",
"true",
",",
"wiki",
":",
"true",
")",
"self",
".",
"bootstrap",
"=",
"OpenStruct",
".",
"new",
"(",
"navbar_inverse_bg",
":",
"'#53565a'",
",",
"navbar_inverse_link_color",
":",
"'#fff'",
",",
"navbar_inverse_color",
":",
"'$navbar-inverse-link-color'",
",",
"navbar_inverse_link_hover_color",
":",
"'darken($navbar-inverse-link-color, 20%)'",
",",
"navbar_inverse_brand_color",
":",
"'$navbar-inverse-link-color'",
",",
"navbar_inverse_brand_hover_color",
":",
"'$navbar-inverse-link-hover-color'",
")",
"ENV",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"/",
"/",
"=~",
"k",
"?",
"self",
".",
"bootstrap",
"[",
"name",
".",
"downcase",
"]",
"=",
"v",
":",
"nil",
"}",
"self",
".",
"enable_log_formatter",
"=",
"::",
"Rails",
".",
"env",
".",
"production?",
"end"
]
| Sets the default configuration for this object.
@return [void] | [
"Sets",
"the",
"default",
"configuration",
"for",
"this",
"object",
"."
]
| ea1435d4bbff47cd1786f84096f415441089a7f5 | https://github.com/OSC/ood_appkit/blob/ea1435d4bbff47cd1786f84096f415441089a7f5/lib/ood_appkit/configuration.rb#L68-L123 | train |
OSC/ood_appkit | lib/ood_appkit/configuration.rb | OodAppkit.Configuration.parse_clusters | def parse_clusters(config)
OodCore::Clusters.load_file(config || '/etc/ood/config/clusters.d')
rescue OodCore::ConfigurationNotFound
OodCore::Clusters.new([])
end | ruby | def parse_clusters(config)
OodCore::Clusters.load_file(config || '/etc/ood/config/clusters.d')
rescue OodCore::ConfigurationNotFound
OodCore::Clusters.new([])
end | [
"def",
"parse_clusters",
"(",
"config",
")",
"OodCore",
"::",
"Clusters",
".",
"load_file",
"(",
"config",
"||",
"'/etc/ood/config/clusters.d'",
")",
"rescue",
"OodCore",
"::",
"ConfigurationNotFound",
"OodCore",
"::",
"Clusters",
".",
"new",
"(",
"[",
"]",
")",
"end"
]
| Read in cluster config and parse it | [
"Read",
"in",
"cluster",
"config",
"and",
"parse",
"it"
]
| ea1435d4bbff47cd1786f84096f415441089a7f5 | https://github.com/OSC/ood_appkit/blob/ea1435d4bbff47cd1786f84096f415441089a7f5/lib/ood_appkit/configuration.rb#L127-L131 | train |
limarka/pandoc_abnt | lib/pandoc_abnt/quadro_filter.rb | PandocAbnt.QuadroFilter.convert_to_latex | def convert_to_latex(node)
latex_code = nil
Open3.popen3("pandoc -f json -t latex --wrap=none") {|stdin, stdout, stderr, wait_thr|
stdin.write(node.to_json)
stdin.close # stdin, stdout and stderr should be closed explicitly in this form.
latex_code = stdout.read
pid = wait_thr.pid # pid of the started process.
exit_status = wait_thr.value # Process::Status object returned.
}
latex_code
end | ruby | def convert_to_latex(node)
latex_code = nil
Open3.popen3("pandoc -f json -t latex --wrap=none") {|stdin, stdout, stderr, wait_thr|
stdin.write(node.to_json)
stdin.close # stdin, stdout and stderr should be closed explicitly in this form.
latex_code = stdout.read
pid = wait_thr.pid # pid of the started process.
exit_status = wait_thr.value # Process::Status object returned.
}
latex_code
end | [
"def",
"convert_to_latex",
"(",
"node",
")",
"latex_code",
"=",
"nil",
"Open3",
".",
"popen3",
"(",
"\"pandoc -f json -t latex --wrap=none\"",
")",
"{",
"|",
"stdin",
",",
"stdout",
",",
"stderr",
",",
"wait_thr",
"|",
"stdin",
".",
"write",
"(",
"node",
".",
"to_json",
")",
"stdin",
".",
"close",
"latex_code",
"=",
"stdout",
".",
"read",
"pid",
"=",
"wait_thr",
".",
"pid",
"exit_status",
"=",
"wait_thr",
".",
"value",
"}",
"latex_code",
"end"
]
| Converte node para latex | [
"Converte",
"node",
"para",
"latex"
]
| fe623465b4956db6cddfe6cffffa0cd8ed445a18 | https://github.com/limarka/pandoc_abnt/blob/fe623465b4956db6cddfe6cffffa0cd8ed445a18/lib/pandoc_abnt/quadro_filter.rb#L108-L119 | train |
mguymon/naether | src/main/ruby/naether/maven.rb | Naether.Maven.dependencies | def dependencies( scopes = nil)
if scopes
unless scopes.is_a? Array
scopes = [scopes]
end
end
if Naether.platform == 'java'
if scopes.nil?
deps = @project.getDependenciesNotation()
else
deps = @project.getDependenciesNotation( scopes )
end
elsif scopes
list = Naether::Java.convert_to_java_list( scopes )
deps = @project._invoke('getDependenciesNotation', 'Ljava.util.List;', list)
else
deps = @project.getDependenciesNotation()
end
Naether::Java.convert_to_ruby_array( deps, true )
end | ruby | def dependencies( scopes = nil)
if scopes
unless scopes.is_a? Array
scopes = [scopes]
end
end
if Naether.platform == 'java'
if scopes.nil?
deps = @project.getDependenciesNotation()
else
deps = @project.getDependenciesNotation( scopes )
end
elsif scopes
list = Naether::Java.convert_to_java_list( scopes )
deps = @project._invoke('getDependenciesNotation', 'Ljava.util.List;', list)
else
deps = @project.getDependenciesNotation()
end
Naether::Java.convert_to_ruby_array( deps, true )
end | [
"def",
"dependencies",
"(",
"scopes",
"=",
"nil",
")",
"if",
"scopes",
"unless",
"scopes",
".",
"is_a?",
"Array",
"scopes",
"=",
"[",
"scopes",
"]",
"end",
"end",
"if",
"Naether",
".",
"platform",
"==",
"'java'",
"if",
"scopes",
".",
"nil?",
"deps",
"=",
"@project",
".",
"getDependenciesNotation",
"(",
")",
"else",
"deps",
"=",
"@project",
".",
"getDependenciesNotation",
"(",
"scopes",
")",
"end",
"elsif",
"scopes",
"list",
"=",
"Naether",
"::",
"Java",
".",
"convert_to_java_list",
"(",
"scopes",
")",
"deps",
"=",
"@project",
".",
"_invoke",
"(",
"'getDependenciesNotation'",
",",
"'Ljava.util.List;'",
",",
"list",
")",
"else",
"deps",
"=",
"@project",
".",
"getDependenciesNotation",
"(",
")",
"end",
"Naether",
"::",
"Java",
".",
"convert_to_ruby_array",
"(",
"deps",
",",
"true",
")",
"end"
]
| Get dependences for Project as notations
@param [Array<String>] scopes valid options are compile,test,runtime | [
"Get",
"dependences",
"for",
"Project",
"as",
"notations"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/maven.rb#L71-L95 | train |
mguymon/naether | src/main/ruby/naether/maven.rb | Naether.Maven.invoke | def invoke( *opts )
#defaults
config = {
# Checks ENV for maven home, otherwise defaults /usr/share/maven
# XXX: Reuse Eng.getMavenHome?
:maven_home => ENV['maven.home'] || ENV['MAVEN_HOME'] || '/usr/share/maven',
:local_repo => File.expand_path('~/.m2/repository')
}
if opts.last.is_a? Hash
config = config.merge( opts.pop )
end
goals = opts
pom = @project.getPomFile().getAbsolutePath()
invoker = Naether::Java.create("com.tobedevoured.naether.maven.Invoker", config[:local_repo], config[:maven_home] )
java_list = Naether::Java.convert_to_java_list(goals)
if Naether.platform == 'java'
invoker.execute( pom, java_list )
else
invoker._invoke('execute', 'Ljava.lang.String;Ljava.util.List;', pom, java_list)
end
end | ruby | def invoke( *opts )
#defaults
config = {
# Checks ENV for maven home, otherwise defaults /usr/share/maven
# XXX: Reuse Eng.getMavenHome?
:maven_home => ENV['maven.home'] || ENV['MAVEN_HOME'] || '/usr/share/maven',
:local_repo => File.expand_path('~/.m2/repository')
}
if opts.last.is_a? Hash
config = config.merge( opts.pop )
end
goals = opts
pom = @project.getPomFile().getAbsolutePath()
invoker = Naether::Java.create("com.tobedevoured.naether.maven.Invoker", config[:local_repo], config[:maven_home] )
java_list = Naether::Java.convert_to_java_list(goals)
if Naether.platform == 'java'
invoker.execute( pom, java_list )
else
invoker._invoke('execute', 'Ljava.lang.String;Ljava.util.List;', pom, java_list)
end
end | [
"def",
"invoke",
"(",
"*",
"opts",
")",
"config",
"=",
"{",
":maven_home",
"=>",
"ENV",
"[",
"'maven.home'",
"]",
"||",
"ENV",
"[",
"'MAVEN_HOME'",
"]",
"||",
"'/usr/share/maven'",
",",
":local_repo",
"=>",
"File",
".",
"expand_path",
"(",
"'~/.m2/repository'",
")",
"}",
"if",
"opts",
".",
"last",
".",
"is_a?",
"Hash",
"config",
"=",
"config",
".",
"merge",
"(",
"opts",
".",
"pop",
")",
"end",
"goals",
"=",
"opts",
"pom",
"=",
"@project",
".",
"getPomFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
"invoker",
"=",
"Naether",
"::",
"Java",
".",
"create",
"(",
"\"com.tobedevoured.naether.maven.Invoker\"",
",",
"config",
"[",
":local_repo",
"]",
",",
"config",
"[",
":maven_home",
"]",
")",
"java_list",
"=",
"Naether",
"::",
"Java",
".",
"convert_to_java_list",
"(",
"goals",
")",
"if",
"Naether",
".",
"platform",
"==",
"'java'",
"invoker",
".",
"execute",
"(",
"pom",
",",
"java_list",
")",
"else",
"invoker",
".",
"_invoke",
"(",
"'execute'",
",",
"'Ljava.lang.String;Ljava.util.List;'",
",",
"pom",
",",
"java_list",
")",
"end",
"end"
]
| Invoke a Maven goal
@params [Array] Goals names | [
"Invoke",
"a",
"Maven",
"goal"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/maven.rb#L152-L176 | train |
abenari/rbovirt | lib/rbovirt.rb | OVIRT.Client.api_version | def api_version
return @api_version unless @api_version.nil?
xml = http_get("/")/'/api/product_info/version'
major = (xml/'version').first[:major]
minor = (xml/'version').first[:minor]
build = (xml/'version').first[:build]
revision = (xml/'version').first[:revision]
@api_version = "#{major}.#{minor}.#{build}.#{revision}"
end | ruby | def api_version
return @api_version unless @api_version.nil?
xml = http_get("/")/'/api/product_info/version'
major = (xml/'version').first[:major]
minor = (xml/'version').first[:minor]
build = (xml/'version').first[:build]
revision = (xml/'version').first[:revision]
@api_version = "#{major}.#{minor}.#{build}.#{revision}"
end | [
"def",
"api_version",
"return",
"@api_version",
"unless",
"@api_version",
".",
"nil?",
"xml",
"=",
"http_get",
"(",
"\"/\"",
")",
"/",
"'/api/product_info/version'",
"major",
"=",
"(",
"xml",
"/",
"'version'",
")",
".",
"first",
"[",
":major",
"]",
"minor",
"=",
"(",
"xml",
"/",
"'version'",
")",
".",
"first",
"[",
":minor",
"]",
"build",
"=",
"(",
"xml",
"/",
"'version'",
")",
".",
"first",
"[",
":build",
"]",
"revision",
"=",
"(",
"xml",
"/",
"'version'",
")",
".",
"first",
"[",
":revision",
"]",
"@api_version",
"=",
"\"#{major}.#{minor}.#{build}.#{revision}\"",
"end"
]
| Construct a new ovirt client class.
mandatory parameters
username, password, api_entrypoint - for example 'me@internal', 'secret', 'https://example.com/api'
optional parameters
datacenter_id, cluster_id and filtered_api can be sent in this order for backward
compatibility, or as a hash in the 4th parameter.
datacenter_id - setting the datacenter at initialization will add a default scope to any subsequent call
to the client to the specified datacenter.
cluster_id - setting the cluster at initialization will add a default scope to any subsequent call
to the client to the specified cluster.
filtered_api - when set to false (default) will use ovirt administrator api, else it will use the user
api mode. | [
"Construct",
"a",
"new",
"ovirt",
"client",
"class",
".",
"mandatory",
"parameters",
"username",
"password",
"api_entrypoint",
"-",
"for",
"example",
"me"
]
| e88ffd2ef7470c164a34dd4229cbb8f5a7257265 | https://github.com/abenari/rbovirt/blob/e88ffd2ef7470c164a34dd4229cbb8f5a7257265/lib/rbovirt.rb#L86-L94 | train |
south37/rucc | lib/rucc/gen.rb | Rucc.Gen.emit_builtin_reg_class | def emit_builtin_reg_class(node)
arg = node.args[0]
Util.assert!{ arg.ty.kind == Kind::PTR }
ty = arg.ty.ptr
if ty.kind == Kind::STRUCT
emit("mov $2, #eax")
elsif Type.is_flotype(ty)
emit("mov $1, #eax")
else
emit("mov $0, #eax")
end
end | ruby | def emit_builtin_reg_class(node)
arg = node.args[0]
Util.assert!{ arg.ty.kind == Kind::PTR }
ty = arg.ty.ptr
if ty.kind == Kind::STRUCT
emit("mov $2, #eax")
elsif Type.is_flotype(ty)
emit("mov $1, #eax")
else
emit("mov $0, #eax")
end
end | [
"def",
"emit_builtin_reg_class",
"(",
"node",
")",
"arg",
"=",
"node",
".",
"args",
"[",
"0",
"]",
"Util",
".",
"assert!",
"{",
"arg",
".",
"ty",
".",
"kind",
"==",
"Kind",
"::",
"PTR",
"}",
"ty",
"=",
"arg",
".",
"ty",
".",
"ptr",
"if",
"ty",
".",
"kind",
"==",
"Kind",
"::",
"STRUCT",
"emit",
"(",
"\"mov $2, #eax\"",
")",
"elsif",
"Type",
".",
"is_flotype",
"(",
"ty",
")",
"emit",
"(",
"\"mov $1, #eax\"",
")",
"else",
"emit",
"(",
"\"mov $0, #eax\"",
")",
"end",
"end"
]
| Set the register class for parameter passing to RAX.
0 is INTEGER, 1 is SSE, 2 is MEMORY.
@param [Node] node | [
"Set",
"the",
"register",
"class",
"for",
"parameter",
"passing",
"to",
"RAX",
".",
"0",
"is",
"INTEGER",
"1",
"is",
"SSE",
"2",
"is",
"MEMORY",
"."
]
| 11743d10eb2fcf0834b4f4a34bb5b8a109b32558 | https://github.com/south37/rucc/blob/11743d10eb2fcf0834b4f4a34bb5b8a109b32558/lib/rucc/gen.rb#L1240-L1251 | train |
BookingSync/synced | lib/synced/model.rb | Synced.Model.synced | def synced(strategy: :updated_since, **options)
options.assert_valid_keys(:associations, :data_key, :fields, :globalized_attributes,
:id_key, :include, :initial_sync_since, :local_attributes, :mapper, :only_updated,
:remove, :auto_paginate, :transaction_per_page, :delegate_attributes, :query_params,
:timestamp_strategy, :handle_processed_objects_proc, :tolerance, :endpoint)
class_attribute :synced_id_key, :synced_data_key,
:synced_local_attributes, :synced_associations, :synced_only_updated,
:synced_mapper, :synced_remove, :synced_include, :synced_fields, :synced_auto_paginate, :synced_transaction_per_page,
:synced_globalized_attributes, :synced_initial_sync_since, :synced_delegate_attributes,
:synced_query_params, :synced_timestamp_strategy, :synced_strategy, :synced_handle_processed_objects_proc,
:synced_tolerance, :synced_endpoint
self.synced_strategy = strategy
self.synced_id_key = options.fetch(:id_key, :synced_id)
self.synced_data_key = options.fetch(:data_key) { synced_column_presence(:synced_data) }
self.synced_local_attributes = options.fetch(:local_attributes, [])
self.synced_associations = options.fetch(:associations, [])
self.synced_only_updated = options.fetch(:only_updated, synced_strategy == :updated_since)
self.synced_mapper = options.fetch(:mapper, nil)
self.synced_remove = options.fetch(:remove, false)
self.synced_include = options.fetch(:include, [])
self.synced_fields = options.fetch(:fields, [])
self.synced_globalized_attributes = options.fetch(:globalized_attributes,
[])
self.synced_initial_sync_since = options.fetch(:initial_sync_since,
nil)
self.synced_delegate_attributes = options.fetch(:delegate_attributes, [])
self.synced_query_params = options.fetch(:query_params, {})
self.synced_timestamp_strategy = options.fetch(:timestamp_strategy, nil)
self.synced_auto_paginate = options.fetch(:auto_paginate, true)
self.synced_transaction_per_page = options.fetch(:transaction_per_page, false)
self.synced_handle_processed_objects_proc = options.fetch(:handle_processed_objects_proc, nil)
self.synced_tolerance = options.fetch(:tolerance, 0).to_i.abs
self.synced_endpoint = options.fetch(:endpoint) { self.to_s.tableize }
include Synced::DelegateAttributes
include Synced::HasSyncedData
end | ruby | def synced(strategy: :updated_since, **options)
options.assert_valid_keys(:associations, :data_key, :fields, :globalized_attributes,
:id_key, :include, :initial_sync_since, :local_attributes, :mapper, :only_updated,
:remove, :auto_paginate, :transaction_per_page, :delegate_attributes, :query_params,
:timestamp_strategy, :handle_processed_objects_proc, :tolerance, :endpoint)
class_attribute :synced_id_key, :synced_data_key,
:synced_local_attributes, :synced_associations, :synced_only_updated,
:synced_mapper, :synced_remove, :synced_include, :synced_fields, :synced_auto_paginate, :synced_transaction_per_page,
:synced_globalized_attributes, :synced_initial_sync_since, :synced_delegate_attributes,
:synced_query_params, :synced_timestamp_strategy, :synced_strategy, :synced_handle_processed_objects_proc,
:synced_tolerance, :synced_endpoint
self.synced_strategy = strategy
self.synced_id_key = options.fetch(:id_key, :synced_id)
self.synced_data_key = options.fetch(:data_key) { synced_column_presence(:synced_data) }
self.synced_local_attributes = options.fetch(:local_attributes, [])
self.synced_associations = options.fetch(:associations, [])
self.synced_only_updated = options.fetch(:only_updated, synced_strategy == :updated_since)
self.synced_mapper = options.fetch(:mapper, nil)
self.synced_remove = options.fetch(:remove, false)
self.synced_include = options.fetch(:include, [])
self.synced_fields = options.fetch(:fields, [])
self.synced_globalized_attributes = options.fetch(:globalized_attributes,
[])
self.synced_initial_sync_since = options.fetch(:initial_sync_since,
nil)
self.synced_delegate_attributes = options.fetch(:delegate_attributes, [])
self.synced_query_params = options.fetch(:query_params, {})
self.synced_timestamp_strategy = options.fetch(:timestamp_strategy, nil)
self.synced_auto_paginate = options.fetch(:auto_paginate, true)
self.synced_transaction_per_page = options.fetch(:transaction_per_page, false)
self.synced_handle_processed_objects_proc = options.fetch(:handle_processed_objects_proc, nil)
self.synced_tolerance = options.fetch(:tolerance, 0).to_i.abs
self.synced_endpoint = options.fetch(:endpoint) { self.to_s.tableize }
include Synced::DelegateAttributes
include Synced::HasSyncedData
end | [
"def",
"synced",
"(",
"strategy",
":",
":updated_since",
",",
"**",
"options",
")",
"options",
".",
"assert_valid_keys",
"(",
":associations",
",",
":data_key",
",",
":fields",
",",
":globalized_attributes",
",",
":id_key",
",",
":include",
",",
":initial_sync_since",
",",
":local_attributes",
",",
":mapper",
",",
":only_updated",
",",
":remove",
",",
":auto_paginate",
",",
":transaction_per_page",
",",
":delegate_attributes",
",",
":query_params",
",",
":timestamp_strategy",
",",
":handle_processed_objects_proc",
",",
":tolerance",
",",
":endpoint",
")",
"class_attribute",
":synced_id_key",
",",
":synced_data_key",
",",
":synced_local_attributes",
",",
":synced_associations",
",",
":synced_only_updated",
",",
":synced_mapper",
",",
":synced_remove",
",",
":synced_include",
",",
":synced_fields",
",",
":synced_auto_paginate",
",",
":synced_transaction_per_page",
",",
":synced_globalized_attributes",
",",
":synced_initial_sync_since",
",",
":synced_delegate_attributes",
",",
":synced_query_params",
",",
":synced_timestamp_strategy",
",",
":synced_strategy",
",",
":synced_handle_processed_objects_proc",
",",
":synced_tolerance",
",",
":synced_endpoint",
"self",
".",
"synced_strategy",
"=",
"strategy",
"self",
".",
"synced_id_key",
"=",
"options",
".",
"fetch",
"(",
":id_key",
",",
":synced_id",
")",
"self",
".",
"synced_data_key",
"=",
"options",
".",
"fetch",
"(",
":data_key",
")",
"{",
"synced_column_presence",
"(",
":synced_data",
")",
"}",
"self",
".",
"synced_local_attributes",
"=",
"options",
".",
"fetch",
"(",
":local_attributes",
",",
"[",
"]",
")",
"self",
".",
"synced_associations",
"=",
"options",
".",
"fetch",
"(",
":associations",
",",
"[",
"]",
")",
"self",
".",
"synced_only_updated",
"=",
"options",
".",
"fetch",
"(",
":only_updated",
",",
"synced_strategy",
"==",
":updated_since",
")",
"self",
".",
"synced_mapper",
"=",
"options",
".",
"fetch",
"(",
":mapper",
",",
"nil",
")",
"self",
".",
"synced_remove",
"=",
"options",
".",
"fetch",
"(",
":remove",
",",
"false",
")",
"self",
".",
"synced_include",
"=",
"options",
".",
"fetch",
"(",
":include",
",",
"[",
"]",
")",
"self",
".",
"synced_fields",
"=",
"options",
".",
"fetch",
"(",
":fields",
",",
"[",
"]",
")",
"self",
".",
"synced_globalized_attributes",
"=",
"options",
".",
"fetch",
"(",
":globalized_attributes",
",",
"[",
"]",
")",
"self",
".",
"synced_initial_sync_since",
"=",
"options",
".",
"fetch",
"(",
":initial_sync_since",
",",
"nil",
")",
"self",
".",
"synced_delegate_attributes",
"=",
"options",
".",
"fetch",
"(",
":delegate_attributes",
",",
"[",
"]",
")",
"self",
".",
"synced_query_params",
"=",
"options",
".",
"fetch",
"(",
":query_params",
",",
"{",
"}",
")",
"self",
".",
"synced_timestamp_strategy",
"=",
"options",
".",
"fetch",
"(",
":timestamp_strategy",
",",
"nil",
")",
"self",
".",
"synced_auto_paginate",
"=",
"options",
".",
"fetch",
"(",
":auto_paginate",
",",
"true",
")",
"self",
".",
"synced_transaction_per_page",
"=",
"options",
".",
"fetch",
"(",
":transaction_per_page",
",",
"false",
")",
"self",
".",
"synced_handle_processed_objects_proc",
"=",
"options",
".",
"fetch",
"(",
":handle_processed_objects_proc",
",",
"nil",
")",
"self",
".",
"synced_tolerance",
"=",
"options",
".",
"fetch",
"(",
":tolerance",
",",
"0",
")",
".",
"to_i",
".",
"abs",
"self",
".",
"synced_endpoint",
"=",
"options",
".",
"fetch",
"(",
":endpoint",
")",
"{",
"self",
".",
"to_s",
".",
"tableize",
"}",
"include",
"Synced",
"::",
"DelegateAttributes",
"include",
"Synced",
"::",
"HasSyncedData",
"end"
]
| Enables synced for ActiveRecord model.
@param options [Hash] Configuration options for synced. They are inherited
by subclasses, but can be overwritten in the subclass.
@option options [Symbol] strategy: synchronization strategy, one of :full, :updated_since, :check.
Defaults to :updated_since
@option options [Symbol] id_key: attribute name under which
remote object's ID is stored, default is :synced_id.
@option options [Boolean] only_updated: If true requests to API will take
advantage of updated_since param and fetch only created/changed/deleted
remote objects
@option options [Symbol] data_key: attribute name under which remote
object's data is stored.
@option options [Array|Hash] local_attributes: Array of attributes in the remote
object which will be mapped to local object attributes.
@option options [Boolean|Symbol] remove: If it's true all local objects
within current scope which are not present in the remote array will be
destroyed.
If only_updated is enabled, ids of objects to be deleted will be taken
from the meta part. By default if cancel_at column is present, all
missing local objects will be canceled with cancel_all,
if it's missing, all will be destroyed with destroy_all.
You can also force method to remove local objects by passing it
to remove: :mark_as_missing.
@option options [Array|Hash] globalized_attributes: A list of attributes
which will be mapped with their translations.
@option options [Time|Proc] initial_sync_since: A point in time from which
objects will be synchronized on first synchronization.
Works only for partial (updated_since param) synchronizations.
@option options [Array|Hash] delegate_attributes: Given attributes will be defined
on synchronized object and delegated to synced_data Hash
@option options [Hash] query_params: Given attributes and their values
which will be passed to api client to perform search
@option options [Boolean] auto_paginate: If true (default) will fetch and save all
records at once. If false will fetch and save records in batches.
@option options transaction_per_page [Boolean]: If false (default) all fetched records
will be persisted within single transaction. If true the transaction will be per page
of fetched records
@option options [Proc] handle_processed_objects_proc: Proc taking one argument (persisted remote objects).
Called after persisting remote objects (once in case of auto_paginate, after each batch
when paginating with block).
@option options [Integer] tolerance: amount of seconds subtracted from last_request timestamp.
Used to ensure records are up to date in case request has been made in the middle of transaction.
Defaults to 0. | [
"Enables",
"synced",
"for",
"ActiveRecord",
"model",
"."
]
| 4a79eee67497c7b7954b0a8dd6ac832fa06c112b | https://github.com/BookingSync/synced/blob/4a79eee67497c7b7954b0a8dd6ac832fa06c112b/lib/synced/model.rb#L49-L84 | train |
BookingSync/synced | lib/synced/model.rb | Synced.Model.synchronize | def synchronize(scope: scope_from_relation, strategy: synced_strategy, **options)
options.assert_valid_keys(:api, :fields, :include, :remote, :remove, :query_params, :association_sync, :auto_paginate, :transaction_per_page)
options[:remove] = synced_remove unless options.has_key?(:remove)
options[:include] = Array.wrap(synced_include) unless options.has_key?(:include)
options[:fields] = Array.wrap(synced_fields) unless options.has_key?(:fields)
options[:query_params] = synced_query_params unless options.has_key?(:query_params)
options[:auto_paginate] = synced_auto_paginate unless options.has_key?(:auto_paginate)
options[:transaction_per_page] = synced_transaction_per_page unless options.has_key?(:transaction_per_page)
options.merge!({
scope: scope,
strategy: strategy,
id_key: synced_id_key,
synced_data_key: synced_data_key,
data_key: synced_data_key,
local_attributes: synced_local_attributes,
associations: synced_associations,
only_updated: synced_only_updated,
mapper: synced_mapper,
globalized_attributes: synced_globalized_attributes,
initial_sync_since: synced_initial_sync_since,
timestamp_strategy: synced_timestamp_strategy,
handle_processed_objects_proc: synced_handle_processed_objects_proc,
tolerance: synced_tolerance,
synced_endpoint: synced_endpoint
})
Synced::Synchronizer.new(self, options).perform
end | ruby | def synchronize(scope: scope_from_relation, strategy: synced_strategy, **options)
options.assert_valid_keys(:api, :fields, :include, :remote, :remove, :query_params, :association_sync, :auto_paginate, :transaction_per_page)
options[:remove] = synced_remove unless options.has_key?(:remove)
options[:include] = Array.wrap(synced_include) unless options.has_key?(:include)
options[:fields] = Array.wrap(synced_fields) unless options.has_key?(:fields)
options[:query_params] = synced_query_params unless options.has_key?(:query_params)
options[:auto_paginate] = synced_auto_paginate unless options.has_key?(:auto_paginate)
options[:transaction_per_page] = synced_transaction_per_page unless options.has_key?(:transaction_per_page)
options.merge!({
scope: scope,
strategy: strategy,
id_key: synced_id_key,
synced_data_key: synced_data_key,
data_key: synced_data_key,
local_attributes: synced_local_attributes,
associations: synced_associations,
only_updated: synced_only_updated,
mapper: synced_mapper,
globalized_attributes: synced_globalized_attributes,
initial_sync_since: synced_initial_sync_since,
timestamp_strategy: synced_timestamp_strategy,
handle_processed_objects_proc: synced_handle_processed_objects_proc,
tolerance: synced_tolerance,
synced_endpoint: synced_endpoint
})
Synced::Synchronizer.new(self, options).perform
end | [
"def",
"synchronize",
"(",
"scope",
":",
"scope_from_relation",
",",
"strategy",
":",
"synced_strategy",
",",
"**",
"options",
")",
"options",
".",
"assert_valid_keys",
"(",
":api",
",",
":fields",
",",
":include",
",",
":remote",
",",
":remove",
",",
":query_params",
",",
":association_sync",
",",
":auto_paginate",
",",
":transaction_per_page",
")",
"options",
"[",
":remove",
"]",
"=",
"synced_remove",
"unless",
"options",
".",
"has_key?",
"(",
":remove",
")",
"options",
"[",
":include",
"]",
"=",
"Array",
".",
"wrap",
"(",
"synced_include",
")",
"unless",
"options",
".",
"has_key?",
"(",
":include",
")",
"options",
"[",
":fields",
"]",
"=",
"Array",
".",
"wrap",
"(",
"synced_fields",
")",
"unless",
"options",
".",
"has_key?",
"(",
":fields",
")",
"options",
"[",
":query_params",
"]",
"=",
"synced_query_params",
"unless",
"options",
".",
"has_key?",
"(",
":query_params",
")",
"options",
"[",
":auto_paginate",
"]",
"=",
"synced_auto_paginate",
"unless",
"options",
".",
"has_key?",
"(",
":auto_paginate",
")",
"options",
"[",
":transaction_per_page",
"]",
"=",
"synced_transaction_per_page",
"unless",
"options",
".",
"has_key?",
"(",
":transaction_per_page",
")",
"options",
".",
"merge!",
"(",
"{",
"scope",
":",
"scope",
",",
"strategy",
":",
"strategy",
",",
"id_key",
":",
"synced_id_key",
",",
"synced_data_key",
":",
"synced_data_key",
",",
"data_key",
":",
"synced_data_key",
",",
"local_attributes",
":",
"synced_local_attributes",
",",
"associations",
":",
"synced_associations",
",",
"only_updated",
":",
"synced_only_updated",
",",
"mapper",
":",
"synced_mapper",
",",
"globalized_attributes",
":",
"synced_globalized_attributes",
",",
"initial_sync_since",
":",
"synced_initial_sync_since",
",",
"timestamp_strategy",
":",
"synced_timestamp_strategy",
",",
"handle_processed_objects_proc",
":",
"synced_handle_processed_objects_proc",
",",
"tolerance",
":",
"synced_tolerance",
",",
"synced_endpoint",
":",
"synced_endpoint",
"}",
")",
"Synced",
"::",
"Synchronizer",
".",
"new",
"(",
"self",
",",
"options",
")",
".",
"perform",
"end"
]
| Performs synchronization of given remote objects to local database.
@param remote [Array] - Remote objects to be synchronized with local db. If
it's nil then synchronizer will make request on it's own.
@param model_class [Class] - ActiveRecord model class to which remote objects
will be synchronized.
@param scope [ActiveRecord::Base] - Within this object scope local objects
will be synchronized. By default it's model_class. Can be infered from active record association scope.
@param remove [Boolean] - If it's true all local objects within
current scope which are not present in the remote array will be destroyed.
If only_updated is enabled, ids of objects to be deleted will be taken
from the meta part. By default if cancel_at column is present, all
missing local objects will be canceled with cancel_all,
if it's missing, all will be destroyed with destroy_all.
You can also force method to remove local objects by passing it
to remove: :mark_as_missing. This option can be defined in the model
and then overwritten in the synchronize method.
@param auto_paginate [Boolean] - If true (default) will fetch and save all
records at once. If false will fetch and save records in batches.
@param transaction_per_page [Boolean] - If false (default) all fetched records
will be persisted within single transaction. If true the transaction will be per page
of fetched records
@param api [BookingSync::API::Client] - API client to be used for fetching
remote objects
@example Synchronizing amenities
Amenity.synchronize(remote: [remote_amenity1, remote_amenity2])
@example Synchronizing rentals within given website. This will
create/remove/update rentals only within website.
It requires relation website.rentals to exist.
website.rentals.synchronize(remote: remote_rentals) | [
"Performs",
"synchronization",
"of",
"given",
"remote",
"objects",
"to",
"local",
"database",
"."
]
| 4a79eee67497c7b7954b0a8dd6ac832fa06c112b | https://github.com/BookingSync/synced/blob/4a79eee67497c7b7954b0a8dd6ac832fa06c112b/lib/synced/model.rb#L120-L146 | train |
BookingSync/synced | lib/synced/model.rb | Synced.Model.reset_synced | def reset_synced(scope: scope_from_relation)
options = {
scope: scope,
strategy: synced_strategy,
only_updated: synced_only_updated,
initial_sync_since: synced_initial_sync_since,
timestamp_strategy: synced_timestamp_strategy,
synced_endpoint: synced_endpoint
}
Synced::Synchronizer.new(self, options).reset_synced
end | ruby | def reset_synced(scope: scope_from_relation)
options = {
scope: scope,
strategy: synced_strategy,
only_updated: synced_only_updated,
initial_sync_since: synced_initial_sync_since,
timestamp_strategy: synced_timestamp_strategy,
synced_endpoint: synced_endpoint
}
Synced::Synchronizer.new(self, options).reset_synced
end | [
"def",
"reset_synced",
"(",
"scope",
":",
"scope_from_relation",
")",
"options",
"=",
"{",
"scope",
":",
"scope",
",",
"strategy",
":",
"synced_strategy",
",",
"only_updated",
":",
"synced_only_updated",
",",
"initial_sync_since",
":",
"synced_initial_sync_since",
",",
"timestamp_strategy",
":",
"synced_timestamp_strategy",
",",
"synced_endpoint",
":",
"synced_endpoint",
"}",
"Synced",
"::",
"Synchronizer",
".",
"new",
"(",
"self",
",",
"options",
")",
".",
"reset_synced",
"end"
]
| Reset last sync timestamp for given scope, this forces synced to sync
all the records on the next sync. Useful for cases when you add
a new column to be synced and you use updated since strategy for faster
synchronization. | [
"Reset",
"last",
"sync",
"timestamp",
"for",
"given",
"scope",
"this",
"forces",
"synced",
"to",
"sync",
"all",
"the",
"records",
"on",
"the",
"next",
"sync",
".",
"Useful",
"for",
"cases",
"when",
"you",
"add",
"a",
"new",
"column",
"to",
"be",
"synced",
"and",
"you",
"use",
"updated",
"since",
"strategy",
"for",
"faster",
"synchronization",
"."
]
| 4a79eee67497c7b7954b0a8dd6ac832fa06c112b | https://github.com/BookingSync/synced/blob/4a79eee67497c7b7954b0a8dd6ac832fa06c112b/lib/synced/model.rb#L152-L162 | train |
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.add_remote_repository | def add_remote_repository( url, username = nil, password = nil )
if username
@resolver.addRemoteRepositoryByUrl( url, username, password )
else
@resolver.addRemoteRepositoryByUrl( url )
end
end | ruby | def add_remote_repository( url, username = nil, password = nil )
if username
@resolver.addRemoteRepositoryByUrl( url, username, password )
else
@resolver.addRemoteRepositoryByUrl( url )
end
end | [
"def",
"add_remote_repository",
"(",
"url",
",",
"username",
"=",
"nil",
",",
"password",
"=",
"nil",
")",
"if",
"username",
"@resolver",
".",
"addRemoteRepositoryByUrl",
"(",
"url",
",",
"username",
",",
"password",
")",
"else",
"@resolver",
".",
"addRemoteRepositoryByUrl",
"(",
"url",
")",
"end",
"end"
]
| Add remote repository
@param [String] url of remote repo
@param [String] username optional
@param [String] password optioanl | [
"Add",
"remote",
"repository"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L46-L52 | train |
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.build_artifacts= | def build_artifacts=( artifacts )
@resolver.clearBuildArtifacts()
unless artifacts.is_a? Array
artifacts = [artifacts]
end
artifacts.each do |artifact|
# Hash of notation => path or notation => { :path =>, :pom => }
if artifact.is_a? Hash
notation, opts = artifact.shift
if opts.is_a? Hash
@resolver.add_build_artifact( notation, opts[:path], opts[:pom] )
else
@resolver.add_build_artifact( notation, opts )
end
else
raise "invalid build_artifacts format"
end
end
end | ruby | def build_artifacts=( artifacts )
@resolver.clearBuildArtifacts()
unless artifacts.is_a? Array
artifacts = [artifacts]
end
artifacts.each do |artifact|
# Hash of notation => path or notation => { :path =>, :pom => }
if artifact.is_a? Hash
notation, opts = artifact.shift
if opts.is_a? Hash
@resolver.add_build_artifact( notation, opts[:path], opts[:pom] )
else
@resolver.add_build_artifact( notation, opts )
end
else
raise "invalid build_artifacts format"
end
end
end | [
"def",
"build_artifacts",
"=",
"(",
"artifacts",
")",
"@resolver",
".",
"clearBuildArtifacts",
"(",
")",
"unless",
"artifacts",
".",
"is_a?",
"Array",
"artifacts",
"=",
"[",
"artifacts",
"]",
"end",
"artifacts",
".",
"each",
"do",
"|",
"artifact",
"|",
"if",
"artifact",
".",
"is_a?",
"Hash",
"notation",
",",
"opts",
"=",
"artifact",
".",
"shift",
"if",
"opts",
".",
"is_a?",
"Hash",
"@resolver",
".",
"add_build_artifact",
"(",
"notation",
",",
"opts",
"[",
":path",
"]",
",",
"opts",
"[",
":pom",
"]",
")",
"else",
"@resolver",
".",
"add_build_artifact",
"(",
"notation",
",",
"opts",
")",
"end",
"else",
"raise",
"\"invalid build_artifacts format\"",
"end",
"end",
"end"
]
| Set local Build Artifacts, that will be used in the Dependency Resolution
@param [Array<Hash>] artifacts of Hashs with { notation => path } or { notation => { :path => path, :pom => pom_path } | [
"Set",
"local",
"Build",
"Artifacts",
"that",
"will",
"be",
"used",
"in",
"the",
"Dependency",
"Resolution"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L98-L121 | train |
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.add_pom_dependencies | def add_pom_dependencies( pom_path, scopes=['compile'] )
if Naether.platform == 'java'
@resolver.addDependencies( pom_path, scopes )
else
list = Naether::Java.convert_to_java_list( scopes )
@resolver._invoke( 'addDependencies', 'Ljava.lang.String;Ljava.util.List;', pom_path, list )
end
end | ruby | def add_pom_dependencies( pom_path, scopes=['compile'] )
if Naether.platform == 'java'
@resolver.addDependencies( pom_path, scopes )
else
list = Naether::Java.convert_to_java_list( scopes )
@resolver._invoke( 'addDependencies', 'Ljava.lang.String;Ljava.util.List;', pom_path, list )
end
end | [
"def",
"add_pom_dependencies",
"(",
"pom_path",
",",
"scopes",
"=",
"[",
"'compile'",
"]",
")",
"if",
"Naether",
".",
"platform",
"==",
"'java'",
"@resolver",
".",
"addDependencies",
"(",
"pom_path",
",",
"scopes",
")",
"else",
"list",
"=",
"Naether",
"::",
"Java",
".",
"convert_to_java_list",
"(",
"scopes",
")",
"@resolver",
".",
"_invoke",
"(",
"'addDependencies'",
",",
"'Ljava.lang.String;Ljava.util.List;'",
",",
"pom_path",
",",
"list",
")",
"end",
"end"
]
| Add dependencies from a Maven POM
@param [String] pom_path
@param [Array<String>] scopes valid options are compile,test,runtime | [
"Add",
"dependencies",
"from",
"a",
"Maven",
"POM"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L145-L152 | train |
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.dependencies= | def dependencies=(dependencies)
@resolver.clearDependencies()
unless dependencies.is_a? Array
dependencies = [dependencies]
end
dependencies.each do |dependent|
# Hash of notation => scope
if dependent.is_a? Hash
key = dependent.keys.first
# Add pom dependencies with scopes
if key =~ /\.xml$/i
scopes = nil
if dependent[key].is_a? Array
scopes = dependent[key]
else
scopes = [dependent[key]]
end
add_pom_dependencies( key, scopes )
# Add a dependency notation with scopes
else
add_notation_dependency( key, dependent[key] )
end
elsif dependent.is_a? String
# Add pom dependencies with default scopes
if dependent =~ /\.xml$/i
add_pom_dependencies( dependent )
# Add a dependency notation with compile scope
else
add_notation_dependency( dependent, 'compile' )
end
# Add an Aether dependency
else
add_dependency( dependent )
end
end
end | ruby | def dependencies=(dependencies)
@resolver.clearDependencies()
unless dependencies.is_a? Array
dependencies = [dependencies]
end
dependencies.each do |dependent|
# Hash of notation => scope
if dependent.is_a? Hash
key = dependent.keys.first
# Add pom dependencies with scopes
if key =~ /\.xml$/i
scopes = nil
if dependent[key].is_a? Array
scopes = dependent[key]
else
scopes = [dependent[key]]
end
add_pom_dependencies( key, scopes )
# Add a dependency notation with scopes
else
add_notation_dependency( key, dependent[key] )
end
elsif dependent.is_a? String
# Add pom dependencies with default scopes
if dependent =~ /\.xml$/i
add_pom_dependencies( dependent )
# Add a dependency notation with compile scope
else
add_notation_dependency( dependent, 'compile' )
end
# Add an Aether dependency
else
add_dependency( dependent )
end
end
end | [
"def",
"dependencies",
"=",
"(",
"dependencies",
")",
"@resolver",
".",
"clearDependencies",
"(",
")",
"unless",
"dependencies",
".",
"is_a?",
"Array",
"dependencies",
"=",
"[",
"dependencies",
"]",
"end",
"dependencies",
".",
"each",
"do",
"|",
"dependent",
"|",
"if",
"dependent",
".",
"is_a?",
"Hash",
"key",
"=",
"dependent",
".",
"keys",
".",
"first",
"if",
"key",
"=~",
"/",
"\\.",
"/i",
"scopes",
"=",
"nil",
"if",
"dependent",
"[",
"key",
"]",
".",
"is_a?",
"Array",
"scopes",
"=",
"dependent",
"[",
"key",
"]",
"else",
"scopes",
"=",
"[",
"dependent",
"[",
"key",
"]",
"]",
"end",
"add_pom_dependencies",
"(",
"key",
",",
"scopes",
")",
"else",
"add_notation_dependency",
"(",
"key",
",",
"dependent",
"[",
"key",
"]",
")",
"end",
"elsif",
"dependent",
".",
"is_a?",
"String",
"if",
"dependent",
"=~",
"/",
"\\.",
"/i",
"add_pom_dependencies",
"(",
"dependent",
")",
"else",
"add_notation_dependency",
"(",
"dependent",
",",
"'compile'",
")",
"end",
"else",
"add_dependency",
"(",
"dependent",
")",
"end",
"end",
"end"
]
| Set the dependencies
The dependencies param takes an [Array] of mixed dependencies:
* [String] Artifact notation, such as groupId:artifactId:version, e.g. 'junit:junit:4.7'
* [Hash] of a single artifaction notation => scope - { 'junit:junit:4.7' => 'test' }
* [String] path to a local pom - 'lib/pom.xml'
* [Hash] of a single path to a local pom => scope - { 'lib/pom.xml' => ['compile','test'] }
@param [Array] dependencies
@see https://github.com/mguymon/naether/wiki/Notations | [
"Set",
"the",
"dependencies"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L176-L220 | train |
mguymon/naether | src/main/ruby/naether/runtime.rb | Naether.Runtime.dependencies_graph | def dependencies_graph(nodes=nil)
nodes = @resolver.getDependenciesGraph() unless nodes
graph = {}
if Naether.platform == 'java'
nodes.each do |k,v|
deps = dependencies_graph(v)
graph[k] = Naether::Java.convert_to_ruby_hash( deps )
end
else
iterator = nodes.entrySet().iterator();
while iterator.hasNext()
entry = iterator.next()
deps = dependencies_graph(entry.getValue())
graph[entry.getKey().toString()] = Naether::Java.convert_to_ruby_hash( deps )
end
end
graph
end | ruby | def dependencies_graph(nodes=nil)
nodes = @resolver.getDependenciesGraph() unless nodes
graph = {}
if Naether.platform == 'java'
nodes.each do |k,v|
deps = dependencies_graph(v)
graph[k] = Naether::Java.convert_to_ruby_hash( deps )
end
else
iterator = nodes.entrySet().iterator();
while iterator.hasNext()
entry = iterator.next()
deps = dependencies_graph(entry.getValue())
graph[entry.getKey().toString()] = Naether::Java.convert_to_ruby_hash( deps )
end
end
graph
end | [
"def",
"dependencies_graph",
"(",
"nodes",
"=",
"nil",
")",
"nodes",
"=",
"@resolver",
".",
"getDependenciesGraph",
"(",
")",
"unless",
"nodes",
"graph",
"=",
"{",
"}",
"if",
"Naether",
".",
"platform",
"==",
"'java'",
"nodes",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"deps",
"=",
"dependencies_graph",
"(",
"v",
")",
"graph",
"[",
"k",
"]",
"=",
"Naether",
"::",
"Java",
".",
"convert_to_ruby_hash",
"(",
"deps",
")",
"end",
"else",
"iterator",
"=",
"nodes",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"iterator",
".",
"hasNext",
"(",
")",
"entry",
"=",
"iterator",
".",
"next",
"(",
")",
"deps",
"=",
"dependencies_graph",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
"graph",
"[",
"entry",
".",
"getKey",
"(",
")",
".",
"toString",
"(",
")",
"]",
"=",
"Naether",
"::",
"Java",
".",
"convert_to_ruby_hash",
"(",
"deps",
")",
"end",
"end",
"graph",
"end"
]
| Dependencies as a Graph of nested Hashes
@return [Hash] | [
"Dependencies",
"as",
"a",
"Graph",
"of",
"nested",
"Hashes"
]
| 218d8fd36c0b8b6e16d66e5715975570b4560ec4 | https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/ruby/naether/runtime.rb#L254-L273 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.