id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
23,600 | instructure/moodle2cc | lib/moodle2cc/moodle2converter/migrator.rb | Moodle2CC::Moodle2Converter.Migrator.convert_question_banks | def convert_question_banks(question_categories)
bank_converter = Moodle2CC::Moodle2Converter::QuestionBankConverter.new
question_categories.map { |category| bank_converter.convert(category) }
end | ruby | def convert_question_banks(question_categories)
bank_converter = Moodle2CC::Moodle2Converter::QuestionBankConverter.new
question_categories.map { |category| bank_converter.convert(category) }
end | [
"def",
"convert_question_banks",
"(",
"question_categories",
")",
"bank_converter",
"=",
"Moodle2CC",
"::",
"Moodle2Converter",
"::",
"QuestionBankConverter",
".",
"new",
"question_categories",
".",
"map",
"{",
"|",
"category",
"|",
"bank_converter",
".",
"convert",
"(",
"category",
")",
"}",
"end"
] | convert question categories to question banks | [
"convert",
"question",
"categories",
"to",
"question",
"banks"
] | cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/moodle2converter/migrator.rb#L125-L128 |
23,601 | zl4bv/packer-client | lib/packer/client.rb | Packer.Client.build | def build(template, options = {})
args = ['build', '-machine-readable']
args << '-force' if options.key?(:force)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-parallel=#{options[:parallel]}" if options.key?(:parallel)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Build.new(
command(args, options[:live_stream]))
end | ruby | def build(template, options = {})
args = ['build', '-machine-readable']
args << '-force' if options.key?(:force)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-parallel=#{options[:parallel]}" if options.key?(:parallel)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Build.new(
command(args, options[:live_stream]))
end | [
"def",
"build",
"(",
"template",
",",
"options",
"=",
"{",
"}",
")",
"args",
"=",
"[",
"'build'",
",",
"'-machine-readable'",
"]",
"args",
"<<",
"'-force'",
"if",
"options",
".",
"key?",
"(",
":force",
")",
"args",
"<<",
"\"-except=#{options[:except].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":except",
")",
"args",
"<<",
"\"-only=#{options[:only].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":only",
")",
"args",
"<<",
"\"-parallel=#{options[:parallel]}\"",
"if",
"options",
".",
"key?",
"(",
":parallel",
")",
"args",
"<<",
"\"-var-file=#{options[:var_file]}\"",
"if",
"options",
".",
"key?",
"(",
":var_file",
")",
"vars",
"=",
"options",
"[",
":vars",
"]",
"||",
"{",
"}",
"vars",
".",
"each",
"{",
"|",
"key",
",",
"val",
"|",
"args",
"<<",
"\"-var '#{key}=#{val}'\"",
"}",
"args",
"<<",
"template",
"Packer",
"::",
"Output",
"::",
"Build",
".",
"new",
"(",
"command",
"(",
"args",
",",
"options",
"[",
":live_stream",
"]",
")",
")",
"end"
] | Executes +packer build+.
Will execute multiple builds in parallel as defined in the template.
The various artifacts created by the template will be outputted.
@param [String,Packer::Template] template the Packer template
@param [Hash] options
@option options [Boolean] :force force a build to continue if artifacts
exist, deletes existing artifacts
@option options [Array<String>] :except build all builds other than
these
@option options [Array<String>] :only only build the given builds by
name
@option options [Boolean] :parallel disable parallelization (on by
default)
@option options [Hash] :vars variables for templates
@option options [String] :var_file path to JSON file containing user
variables
@option options [IO] :live_stream an IO object to stream packer output to
in addition to saving output in the output object.
@return [Packer::Output::Build] | [
"Executes",
"+",
"packer",
"build",
"+",
"."
] | e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L32-L47 |
23,602 | zl4bv/packer-client | lib/packer/client.rb | Packer.Client.inspect_template | def inspect_template(template)
args = ['inspect', '-machine-readable', template]
Packer::Output::Inspect.new(command(args))
end | ruby | def inspect_template(template)
args = ['inspect', '-machine-readable', template]
Packer::Output::Inspect.new(command(args))
end | [
"def",
"inspect_template",
"(",
"template",
")",
"args",
"=",
"[",
"'inspect'",
",",
"'-machine-readable'",
",",
"template",
"]",
"Packer",
"::",
"Output",
"::",
"Inspect",
".",
"new",
"(",
"command",
"(",
"args",
")",
")",
"end"
] | Excutes +packer inspect+
Inspects a template, parsing and outputting the components a template
defines. This does not validate the contents of a template (other than
basic syntax by necessity).
@param [String,Packer::Template] template the Packer template
@return [Packer::Output::Inspect] | [
"Excutes",
"+",
"packer",
"inspect",
"+"
] | e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L108-L112 |
23,603 | zl4bv/packer-client | lib/packer/client.rb | Packer.Client.push | def push(template, options = {})
args = ['push']
args << "-message=#{options[:message]}" if options.key?(:message)
args << "-name=#{options[:name]}" if options.key?(:name)
args << "-token=#{options[:token]}" if options.key?(:token)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Push.new(command(args, options[:live_stream]))
end | ruby | def push(template, options = {})
args = ['push']
args << "-message=#{options[:message]}" if options.key?(:message)
args << "-name=#{options[:name]}" if options.key?(:name)
args << "-token=#{options[:token]}" if options.key?(:token)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Push.new(command(args, options[:live_stream]))
end | [
"def",
"push",
"(",
"template",
",",
"options",
"=",
"{",
"}",
")",
"args",
"=",
"[",
"'push'",
"]",
"args",
"<<",
"\"-message=#{options[:message]}\"",
"if",
"options",
".",
"key?",
"(",
":message",
")",
"args",
"<<",
"\"-name=#{options[:name]}\"",
"if",
"options",
".",
"key?",
"(",
":name",
")",
"args",
"<<",
"\"-token=#{options[:token]}\"",
"if",
"options",
".",
"key?",
"(",
":token",
")",
"args",
"<<",
"\"-var-file=#{options[:var_file]}\"",
"if",
"options",
".",
"key?",
"(",
":var_file",
")",
"vars",
"=",
"options",
"[",
":vars",
"]",
"||",
"{",
"}",
"vars",
".",
"each",
"{",
"|",
"key",
",",
"val",
"|",
"args",
"<<",
"\"-var '#{key}=#{val}'\"",
"}",
"args",
"<<",
"template",
"Packer",
"::",
"Output",
"::",
"Push",
".",
"new",
"(",
"command",
"(",
"args",
",",
"options",
"[",
":live_stream",
"]",
")",
")",
"end"
] | Executes +packer push+.
Push the given template and supporting files to a Packer build service
such as Atlas.
If a build configuration for the given template does not exist, it will
be created automatically. If the build configuration already exists, a
new version will be created with this template and the supporting files.
Additional configuration options (such as Atlas server URL and files to
include) may be specified in the "push" section of the Packer template.
Please see the online documentation about these configurables.
@param [String,Packer::Template] template the Packer template
@param [Hash] options
@option options [String] :message a message to identify the purpose of
changes in this Packer template much like a VCS commit message
@option options [String] :name the destination build in Atlas. This is
in a format "username/name".
@option options [String] :token the access token to use when uploading
@option options [Hash] :vars variables for templates
@option options [String] :var_file path to JSON file containing user
variables
@option options [IO] :live_stream an IO object to stream packer output to
in addition to saving output in the output object.
@return [Packer::Output::Push] | [
"Executes",
"+",
"packer",
"push",
"+",
"."
] | e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L140-L153 |
23,604 | zl4bv/packer-client | lib/packer/client.rb | Packer.Client.validate | def validate(template, options = {})
args = ['validate']
args << '-syntax-only' if options.key?(:syntax_only)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Validate.new(command(args, options[:live_stream]))
end | ruby | def validate(template, options = {})
args = ['validate']
args << '-syntax-only' if options.key?(:syntax_only)
args << "-except=#{options[:except].join(',')}" if options.key?(:except)
args << "-only=#{options[:only].join(',')}" if options.key?(:only)
args << "-var-file=#{options[:var_file]}" if options.key?(:var_file)
vars = options[:vars] || {}
vars.each { |key, val| args << "-var '#{key}=#{val}'" }
args << template
Packer::Output::Validate.new(command(args, options[:live_stream]))
end | [
"def",
"validate",
"(",
"template",
",",
"options",
"=",
"{",
"}",
")",
"args",
"=",
"[",
"'validate'",
"]",
"args",
"<<",
"'-syntax-only'",
"if",
"options",
".",
"key?",
"(",
":syntax_only",
")",
"args",
"<<",
"\"-except=#{options[:except].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":except",
")",
"args",
"<<",
"\"-only=#{options[:only].join(',')}\"",
"if",
"options",
".",
"key?",
"(",
":only",
")",
"args",
"<<",
"\"-var-file=#{options[:var_file]}\"",
"if",
"options",
".",
"key?",
"(",
":var_file",
")",
"vars",
"=",
"options",
"[",
":vars",
"]",
"||",
"{",
"}",
"vars",
".",
"each",
"{",
"|",
"key",
",",
"val",
"|",
"args",
"<<",
"\"-var '#{key}=#{val}'\"",
"}",
"args",
"<<",
"template",
"Packer",
"::",
"Output",
"::",
"Validate",
".",
"new",
"(",
"command",
"(",
"args",
",",
"options",
"[",
":live_stream",
"]",
")",
")",
"end"
] | Executes +packer validate+
Checks the template is valid by parsing the template and also checking
the configuration with the various builders, provisioners, etc.
If it is not valid, the errors will be shown and the command will exit
with a non-zero exit status. If it is valid, it will exist with a zero
exist status.
@param [String,Packer::Template] template the Packer template
@param [Hash] options
@option options [Boolean] :syntax_only only check syntax. Do not verify
config of the template.
@option options [Array<String>] :except validate all builds other than
these
@option options [Array<String>] :only validate only these builds
@option options [Hash] :vars variables for templates
@option options [String] :var_file path to JSON file containing user
@option options [IO] :live_stream an IO object to stream packer output to
in addition to saving output in the output object.
variables
@return [Packer::Output::Validate] | [
"Executes",
"+",
"packer",
"validate",
"+"
] | e925f03572425ffeaa9901d8014b445cdea64f9f | https://github.com/zl4bv/packer-client/blob/e925f03572425ffeaa9901d8014b445cdea64f9f/lib/packer/client.rb#L177-L190 |
23,605 | cloudfoundry-attic/vcap-services-base | lib/base/snapshot_v2/snapshot_client.rb | VCAP::Services::Base::SnapshotV2.SnapshotClient.update_name | def update_name(service_id, snapshot_id, name)
return unless service_id && snapshot_id && name
verify_input_name(name)
key = self.class.redis_key(service_id)
# NOTE: idealy should watch on combination of (service_id, snapshot_id)
# but current design doesn't support such fine-grained watching.
client.watch(key)
snapshot = client.hget(redis_key(service_id), snapshot_id)
return nil unless snapshot
snapshot = Yajl::Parser.parse(snapshot)
snapshot["name"] = name
res = client.multi do
save_snapshot(service_id, snapshot)
end
unless res
raise ServiceError.new(ServiceError::REDIS_CONCURRENT_UPDATE)
end
true
end | ruby | def update_name(service_id, snapshot_id, name)
return unless service_id && snapshot_id && name
verify_input_name(name)
key = self.class.redis_key(service_id)
# NOTE: idealy should watch on combination of (service_id, snapshot_id)
# but current design doesn't support such fine-grained watching.
client.watch(key)
snapshot = client.hget(redis_key(service_id), snapshot_id)
return nil unless snapshot
snapshot = Yajl::Parser.parse(snapshot)
snapshot["name"] = name
res = client.multi do
save_snapshot(service_id, snapshot)
end
unless res
raise ServiceError.new(ServiceError::REDIS_CONCURRENT_UPDATE)
end
true
end | [
"def",
"update_name",
"(",
"service_id",
",",
"snapshot_id",
",",
"name",
")",
"return",
"unless",
"service_id",
"&&",
"snapshot_id",
"&&",
"name",
"verify_input_name",
"(",
"name",
")",
"key",
"=",
"self",
".",
"class",
".",
"redis_key",
"(",
"service_id",
")",
"# NOTE: idealy should watch on combination of (service_id, snapshot_id)",
"# but current design doesn't support such fine-grained watching.",
"client",
".",
"watch",
"(",
"key",
")",
"snapshot",
"=",
"client",
".",
"hget",
"(",
"redis_key",
"(",
"service_id",
")",
",",
"snapshot_id",
")",
"return",
"nil",
"unless",
"snapshot",
"snapshot",
"=",
"Yajl",
"::",
"Parser",
".",
"parse",
"(",
"snapshot",
")",
"snapshot",
"[",
"\"name\"",
"]",
"=",
"name",
"res",
"=",
"client",
".",
"multi",
"do",
"save_snapshot",
"(",
"service_id",
",",
"snapshot",
")",
"end",
"unless",
"res",
"raise",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"REDIS_CONCURRENT_UPDATE",
")",
"end",
"true",
"end"
] | Update the name of given snapshot.
This function is not protected by redis lock so a optimistic lock
is applied to prevent concurrent update. | [
"Update",
"the",
"name",
"of",
"given",
"snapshot",
".",
"This",
"function",
"is",
"not",
"protected",
"by",
"redis",
"lock",
"so",
"a",
"optimistic",
"lock",
"is",
"applied",
"to",
"prevent",
"concurrent",
"update",
"."
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/snapshot_v2/snapshot_client.rb#L77-L99 |
23,606 | maetl/calyx | lib/calyx/modifiers.rb | Calyx.Modifiers.transform | def transform(name, value)
if respond_to?(name)
send(name, value)
elsif value.respond_to?(name)
value.send(name)
else
value
end
end | ruby | def transform(name, value)
if respond_to?(name)
send(name, value)
elsif value.respond_to?(name)
value.send(name)
else
value
end
end | [
"def",
"transform",
"(",
"name",
",",
"value",
")",
"if",
"respond_to?",
"(",
"name",
")",
"send",
"(",
"name",
",",
"value",
")",
"elsif",
"value",
".",
"respond_to?",
"(",
"name",
")",
"value",
".",
"send",
"(",
"name",
")",
"else",
"value",
"end",
"end"
] | Transforms an output string by delegating to the given output function.
If a registered modifier method is not found, then delegate to the given
string function.
If an invalid modifier function is given, returns the raw input string.
@param [Symbol] name
@param [String] value
@return [String] | [
"Transforms",
"an",
"output",
"string",
"by",
"delegating",
"to",
"the",
"given",
"output",
"function",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/modifiers.rb#L14-L22 |
23,607 | norman/squirm | lib/squirm/procedure.rb | Squirm.Procedure.load | def load
query = (arguments or self).info_sql
Squirm.exec(query, [name, schema]) do |result|
validate result
set_values_from result
end
self
end | ruby | def load
query = (arguments or self).info_sql
Squirm.exec(query, [name, schema]) do |result|
validate result
set_values_from result
end
self
end | [
"def",
"load",
"query",
"=",
"(",
"arguments",
"or",
"self",
")",
".",
"info_sql",
"Squirm",
".",
"exec",
"(",
"query",
",",
"[",
"name",
",",
"schema",
"]",
")",
"do",
"|",
"result",
"|",
"validate",
"result",
"set_values_from",
"result",
"end",
"self",
"end"
] | Loads meta info about the stored procedure.
This action is not performed in the constructor to allow instances to
be created before a database connection has been established.
@return [Squirm::Procedure] The instance | [
"Loads",
"meta",
"info",
"about",
"the",
"stored",
"procedure",
"."
] | bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/procedure.rb#L63-L70 |
23,608 | norman/squirm | lib/squirm/procedure.rb | Squirm.Procedure.call | def call(*args, &block)
Squirm.exec query, arguments.format(*args) do |result|
if block_given?
yield result
elsif return_type =~ /\ASETOF/
result.to_a
else
result.getvalue(0,0)
end
end
end | ruby | def call(*args, &block)
Squirm.exec query, arguments.format(*args) do |result|
if block_given?
yield result
elsif return_type =~ /\ASETOF/
result.to_a
else
result.getvalue(0,0)
end
end
end | [
"def",
"call",
"(",
"*",
"args",
",",
"&",
"block",
")",
"Squirm",
".",
"exec",
"query",
",",
"arguments",
".",
"format",
"(",
"args",
")",
"do",
"|",
"result",
"|",
"if",
"block_given?",
"yield",
"result",
"elsif",
"return_type",
"=~",
"/",
"\\A",
"/",
"result",
".",
"to_a",
"else",
"result",
".",
"getvalue",
"(",
"0",
",",
"0",
")",
"end",
"end",
"end"
] | Invokes the procedure. | [
"Invokes",
"the",
"procedure",
"."
] | bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/procedure.rb#L80-L90 |
23,609 | norman/squirm | lib/squirm/procedure.rb | Squirm.Procedure.validate | def validate(result)
if result.ntuples == 0
raise NotFound
elsif result.ntuples > 1
raise TooManyChoices
end
end | ruby | def validate(result)
if result.ntuples == 0
raise NotFound
elsif result.ntuples > 1
raise TooManyChoices
end
end | [
"def",
"validate",
"(",
"result",
")",
"if",
"result",
".",
"ntuples",
"==",
"0",
"raise",
"NotFound",
"elsif",
"result",
".",
"ntuples",
">",
"1",
"raise",
"TooManyChoices",
"end",
"end"
] | Checks the number of values returned when looking up meta info about
the procedure.
@see #load
@see #info_sql | [
"Checks",
"the",
"number",
"of",
"values",
"returned",
"when",
"looking",
"up",
"meta",
"info",
"about",
"the",
"procedure",
"."
] | bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/procedure.rb#L103-L109 |
23,610 | m104/interpolate | lib/interpolate/base.rb | Interpolate.Points.merge! | def merge!(points = {})
# points must be a Hash
raise ArgumentError, "key points must be a Hash object" unless points.is_a? Hash
# ensure the points are all keyed Numeric-ally
points.each do |key, value|
raise ArgumentError, "found a point key that is not a Numeric object: #{key.inspect}" unless key.is_a? Numeric
end
@points.merge!(points)
normalize_data
self
end | ruby | def merge!(points = {})
# points must be a Hash
raise ArgumentError, "key points must be a Hash object" unless points.is_a? Hash
# ensure the points are all keyed Numeric-ally
points.each do |key, value|
raise ArgumentError, "found a point key that is not a Numeric object: #{key.inspect}" unless key.is_a? Numeric
end
@points.merge!(points)
normalize_data
self
end | [
"def",
"merge!",
"(",
"points",
"=",
"{",
"}",
")",
"# points must be a Hash",
"raise",
"ArgumentError",
",",
"\"key points must be a Hash object\"",
"unless",
"points",
".",
"is_a?",
"Hash",
"# ensure the points are all keyed Numeric-ally",
"points",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"raise",
"ArgumentError",
",",
"\"found a point key that is not a Numeric object: #{key.inspect}\"",
"unless",
"key",
".",
"is_a?",
"Numeric",
"end",
"@points",
".",
"merge!",
"(",
"points",
")",
"normalize_data",
"self",
"end"
] | merges the given key points with the original points | [
"merges",
"the",
"given",
"key",
"points",
"with",
"the",
"original",
"points"
] | 4f22c0237b7a08df94fb3f7e297a2c1d98188a16 | https://github.com/m104/interpolate/blob/4f22c0237b7a08df94fb3f7e297a2c1d98188a16/lib/interpolate/base.rb#L80-L91 |
23,611 | m104/interpolate | lib/interpolate/base.rb | Interpolate.Points.at | def at(point, &block)
# obvious cases first
if @sorted.empty?
# no key points
return nil
elsif @sorted.size == 1
# one key point
return @sorted.first.last
end
# out-of-bounds cases next
if point <= @min_point
# lower than lowest key point
return @sorted.first.last
elsif point >= @max_point
# higher than highest key point
return @sorted.last.last
end
# binary search to find the right interpolation key point/value interval
left = 0
right = @sorted.length - 2 # highest point will be included
low_point = nil
low_value = nil
high_point = nil
high_value = nil
while left <= right
middle = (right - left) / 2 + left
(low_point, low_value) = @sorted[middle]
(high_point, high_value) = @sorted[middle + 1]
break if low_point <= point and point <= high_point
if point < low_point
right = middle - 1
else
left = middle + 1
end
end
# determine the balance ratio
span = high_point - low_point
balance = (point.to_f - low_point) / span
# choose and call the blending function
blend = block || @blend_with || DEFAULT_BLEND
blend.call(low_value, high_value, balance)
end | ruby | def at(point, &block)
# obvious cases first
if @sorted.empty?
# no key points
return nil
elsif @sorted.size == 1
# one key point
return @sorted.first.last
end
# out-of-bounds cases next
if point <= @min_point
# lower than lowest key point
return @sorted.first.last
elsif point >= @max_point
# higher than highest key point
return @sorted.last.last
end
# binary search to find the right interpolation key point/value interval
left = 0
right = @sorted.length - 2 # highest point will be included
low_point = nil
low_value = nil
high_point = nil
high_value = nil
while left <= right
middle = (right - left) / 2 + left
(low_point, low_value) = @sorted[middle]
(high_point, high_value) = @sorted[middle + 1]
break if low_point <= point and point <= high_point
if point < low_point
right = middle - 1
else
left = middle + 1
end
end
# determine the balance ratio
span = high_point - low_point
balance = (point.to_f - low_point) / span
# choose and call the blending function
blend = block || @blend_with || DEFAULT_BLEND
blend.call(low_value, high_value, balance)
end | [
"def",
"at",
"(",
"point",
",",
"&",
"block",
")",
"# obvious cases first",
"if",
"@sorted",
".",
"empty?",
"# no key points",
"return",
"nil",
"elsif",
"@sorted",
".",
"size",
"==",
"1",
"# one key point",
"return",
"@sorted",
".",
"first",
".",
"last",
"end",
"# out-of-bounds cases next",
"if",
"point",
"<=",
"@min_point",
"# lower than lowest key point",
"return",
"@sorted",
".",
"first",
".",
"last",
"elsif",
"point",
">=",
"@max_point",
"# higher than highest key point",
"return",
"@sorted",
".",
"last",
".",
"last",
"end",
"# binary search to find the right interpolation key point/value interval",
"left",
"=",
"0",
"right",
"=",
"@sorted",
".",
"length",
"-",
"2",
"# highest point will be included",
"low_point",
"=",
"nil",
"low_value",
"=",
"nil",
"high_point",
"=",
"nil",
"high_value",
"=",
"nil",
"while",
"left",
"<=",
"right",
"middle",
"=",
"(",
"right",
"-",
"left",
")",
"/",
"2",
"+",
"left",
"(",
"low_point",
",",
"low_value",
")",
"=",
"@sorted",
"[",
"middle",
"]",
"(",
"high_point",
",",
"high_value",
")",
"=",
"@sorted",
"[",
"middle",
"+",
"1",
"]",
"break",
"if",
"low_point",
"<=",
"point",
"and",
"point",
"<=",
"high_point",
"if",
"point",
"<",
"low_point",
"right",
"=",
"middle",
"-",
"1",
"else",
"left",
"=",
"middle",
"+",
"1",
"end",
"end",
"# determine the balance ratio",
"span",
"=",
"high_point",
"-",
"low_point",
"balance",
"=",
"(",
"point",
".",
"to_f",
"-",
"low_point",
")",
"/",
"span",
"# choose and call the blending function",
"blend",
"=",
"block",
"||",
"@blend_with",
"||",
"DEFAULT_BLEND",
"blend",
".",
"call",
"(",
"low_value",
",",
"high_value",
",",
"balance",
")",
"end"
] | returns the interpolated value at the Numeric point specified, optionally
using a given block as the blending function
if no key points have been specified, the return value is +nil+
if one key point has been specified, the return value is the value
of that key point
if the given point falls outside the interpolation key range (lower than
the lowest key point or higher than the highest key point), the nearest
point value is used; in other words, no extrapolation is performed
otherwise, the interpolated value is calculated in accordance with the
first of:
* the given block
* the stored blending function, :blend_with
* a call to :interpolate on a key value object | [
"returns",
"the",
"interpolated",
"value",
"at",
"the",
"Numeric",
"point",
"specified",
"optionally",
"using",
"a",
"given",
"block",
"as",
"the",
"blending",
"function"
] | 4f22c0237b7a08df94fb3f7e297a2c1d98188a16 | https://github.com/m104/interpolate/blob/4f22c0237b7a08df94fb3f7e297a2c1d98188a16/lib/interpolate/base.rb#L112-L161 |
23,612 | instructure/moodle2cc | lib/moodle2cc/canvas_cc/models/question_bank.rb | Moodle2CC::CanvasCC::Models.QuestionBank.find_children_banks | def find_children_banks(all_banks, visited_banks=[])
visited_banks << self
children = []
sub_children = []
all_banks.each do |bank|
children << bank if bank.parent_id && bank.parent_id == self.original_id && !visited_banks.include?(bank)
end
children.each do |child|
sub_children += child.find_children_banks(all_banks, visited_banks)
end
return children + sub_children
end | ruby | def find_children_banks(all_banks, visited_banks=[])
visited_banks << self
children = []
sub_children = []
all_banks.each do |bank|
children << bank if bank.parent_id && bank.parent_id == self.original_id && !visited_banks.include?(bank)
end
children.each do |child|
sub_children += child.find_children_banks(all_banks, visited_banks)
end
return children + sub_children
end | [
"def",
"find_children_banks",
"(",
"all_banks",
",",
"visited_banks",
"=",
"[",
"]",
")",
"visited_banks",
"<<",
"self",
"children",
"=",
"[",
"]",
"sub_children",
"=",
"[",
"]",
"all_banks",
".",
"each",
"do",
"|",
"bank",
"|",
"children",
"<<",
"bank",
"if",
"bank",
".",
"parent_id",
"&&",
"bank",
".",
"parent_id",
"==",
"self",
".",
"original_id",
"&&",
"!",
"visited_banks",
".",
"include?",
"(",
"bank",
")",
"end",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"sub_children",
"+=",
"child",
".",
"find_children_banks",
"(",
"all_banks",
",",
"visited_banks",
")",
"end",
"return",
"children",
"+",
"sub_children",
"end"
] | recursively find all banks that belong to this one | [
"recursively",
"find",
"all",
"banks",
"that",
"belong",
"to",
"this",
"one"
] | cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/canvas_cc/models/question_bank.rb#L29-L40 |
23,613 | ruby-ore/ore | lib/ore/naming.rb | Ore.Naming.module_of | def module_of(word)
if COMMON_NAMESPACES.has_key?(word)
COMMON_NAMESPACES[word]
elsif COMMON_ABBREVIATIONS.has_key?(word)
COMMON_ABBREVIATIONS[word]
else
word.capitalize
end
end | ruby | def module_of(word)
if COMMON_NAMESPACES.has_key?(word)
COMMON_NAMESPACES[word]
elsif COMMON_ABBREVIATIONS.has_key?(word)
COMMON_ABBREVIATIONS[word]
else
word.capitalize
end
end | [
"def",
"module_of",
"(",
"word",
")",
"if",
"COMMON_NAMESPACES",
".",
"has_key?",
"(",
"word",
")",
"COMMON_NAMESPACES",
"[",
"word",
"]",
"elsif",
"COMMON_ABBREVIATIONS",
".",
"has_key?",
"(",
"word",
")",
"COMMON_ABBREVIATIONS",
"[",
"word",
"]",
"else",
"word",
".",
"capitalize",
"end",
"end"
] | Guesses the module name for a word within a project name.
@param [String] word
The word within a project name.
@return [String]
The module name.
@since 0.1.1 | [
"Guesses",
"the",
"module",
"name",
"for",
"a",
"word",
"within",
"a",
"project",
"name",
"."
] | 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/naming.rb#L74-L82 |
23,614 | ruby-ore/ore | lib/ore/naming.rb | Ore.Naming.modules_of | def modules_of(name)
names_in(name).map do |words|
words.split('_').map { |word| module_of(word) }.join
end
end | ruby | def modules_of(name)
names_in(name).map do |words|
words.split('_').map { |word| module_of(word) }.join
end
end | [
"def",
"modules_of",
"(",
"name",
")",
"names_in",
"(",
"name",
")",
".",
"map",
"do",
"|",
"words",
"|",
"words",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"{",
"|",
"word",
"|",
"module_of",
"(",
"word",
")",
"}",
".",
"join",
"end",
"end"
] | Guesses the module names from a project name.
@param [String] name
The name of the project.
@return [Array<String>]
The module names for a project. | [
"Guesses",
"the",
"module",
"names",
"from",
"a",
"project",
"name",
"."
] | 585c98027771fd118041e90bb38295983d67166c | https://github.com/ruby-ore/ore/blob/585c98027771fd118041e90bb38295983d67166c/lib/ore/naming.rb#L93-L97 |
23,615 | janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.convert | def convert
@assets.each do |asset|
# Convert asset multiple times if more than one converter is found
finished = false
while finished == false
# Find a converter to use
klass = JAPR::Converter.klass(asset.filename)
# Convert asset if converter is found
if klass.nil?
finished = true
else
convert_asset(klass, asset)
end
end
end
end | ruby | def convert
@assets.each do |asset|
# Convert asset multiple times if more than one converter is found
finished = false
while finished == false
# Find a converter to use
klass = JAPR::Converter.klass(asset.filename)
# Convert asset if converter is found
if klass.nil?
finished = true
else
convert_asset(klass, asset)
end
end
end
end | [
"def",
"convert",
"@assets",
".",
"each",
"do",
"|",
"asset",
"|",
"# Convert asset multiple times if more than one converter is found",
"finished",
"=",
"false",
"while",
"finished",
"==",
"false",
"# Find a converter to use",
"klass",
"=",
"JAPR",
"::",
"Converter",
".",
"klass",
"(",
"asset",
".",
"filename",
")",
"# Convert asset if converter is found",
"if",
"klass",
".",
"nil?",
"finished",
"=",
"true",
"else",
"convert_asset",
"(",
"klass",
",",
"asset",
")",
"end",
"end",
"end",
"end"
] | Convert assets based on the file extension if converter is defined | [
"Convert",
"assets",
"based",
"on",
"the",
"file",
"extension",
"if",
"converter",
"is",
"defined"
] | fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L129-L145 |
23,616 | janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.bundle | def bundle
content = @assets.map(&:content).join("\n")
hash = JAPR::Pipeline.hash(@source, @manifest, @options)
@assets = [JAPR::Asset.new(content, "#{@prefix}-#{hash}#{@type}")]
end | ruby | def bundle
content = @assets.map(&:content).join("\n")
hash = JAPR::Pipeline.hash(@source, @manifest, @options)
@assets = [JAPR::Asset.new(content, "#{@prefix}-#{hash}#{@type}")]
end | [
"def",
"bundle",
"content",
"=",
"@assets",
".",
"map",
"(",
":content",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"hash",
"=",
"JAPR",
"::",
"Pipeline",
".",
"hash",
"(",
"@source",
",",
"@manifest",
",",
"@options",
")",
"@assets",
"=",
"[",
"JAPR",
"::",
"Asset",
".",
"new",
"(",
"content",
",",
"\"#{@prefix}-#{hash}#{@type}\"",
")",
"]",
"end"
] | Bundle multiple assets into a single asset | [
"Bundle",
"multiple",
"assets",
"into",
"a",
"single",
"asset"
] | fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L167-L172 |
23,617 | janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.write_asset_file | def write_asset_file(directory, asset)
FileUtils.mkpath(directory) unless File.directory?(directory)
begin
# Save file to disk
File.open(File.join(directory, asset.filename), 'w') do |file|
file.write(asset.content)
end
rescue StandardError => se
puts "Asset Pipeline: Failed to save '#{asset.filename}' to " \
"disk: #{se.message}"
raise se
end
end | ruby | def write_asset_file(directory, asset)
FileUtils.mkpath(directory) unless File.directory?(directory)
begin
# Save file to disk
File.open(File.join(directory, asset.filename), 'w') do |file|
file.write(asset.content)
end
rescue StandardError => se
puts "Asset Pipeline: Failed to save '#{asset.filename}' to " \
"disk: #{se.message}"
raise se
end
end | [
"def",
"write_asset_file",
"(",
"directory",
",",
"asset",
")",
"FileUtils",
".",
"mkpath",
"(",
"directory",
")",
"unless",
"File",
".",
"directory?",
"(",
"directory",
")",
"begin",
"# Save file to disk",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"directory",
",",
"asset",
".",
"filename",
")",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"asset",
".",
"content",
")",
"end",
"rescue",
"StandardError",
"=>",
"se",
"puts",
"\"Asset Pipeline: Failed to save '#{asset.filename}' to \"",
"\"disk: #{se.message}\"",
"raise",
"se",
"end",
"end"
] | Write asset file to disk | [
"Write",
"asset",
"file",
"to",
"disk"
] | fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L220-L232 |
23,618 | janosrusiczki/japr | lib/japr/pipeline.rb | JAPR.Pipeline.markup | def markup
# Use display_path if defined, otherwise use output_path in url
display_path = @options['display_path'] || @options['output_path']
@html = @assets.map do |asset|
klass = JAPR::Template.klass(asset.filename)
html = klass.new(display_path, asset.filename).html unless klass.nil?
html
end.join
end | ruby | def markup
# Use display_path if defined, otherwise use output_path in url
display_path = @options['display_path'] || @options['output_path']
@html = @assets.map do |asset|
klass = JAPR::Template.klass(asset.filename)
html = klass.new(display_path, asset.filename).html unless klass.nil?
html
end.join
end | [
"def",
"markup",
"# Use display_path if defined, otherwise use output_path in url",
"display_path",
"=",
"@options",
"[",
"'display_path'",
"]",
"||",
"@options",
"[",
"'output_path'",
"]",
"@html",
"=",
"@assets",
".",
"map",
"do",
"|",
"asset",
"|",
"klass",
"=",
"JAPR",
"::",
"Template",
".",
"klass",
"(",
"asset",
".",
"filename",
")",
"html",
"=",
"klass",
".",
"new",
"(",
"display_path",
",",
"asset",
".",
"filename",
")",
".",
"html",
"unless",
"klass",
".",
"nil?",
"html",
"end",
".",
"join",
"end"
] | Generate html markup pointing to assets | [
"Generate",
"html",
"markup",
"pointing",
"to",
"assets"
] | fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee | https://github.com/janosrusiczki/japr/blob/fc458bc4edfa73d70cc3f6c86b57872bbf62a0ee/lib/japr/pipeline.rb#L235-L245 |
23,619 | mycolorway/SeventeenMon | lib/seventeen_mon/ip.rb | SeventeenMon.IP.four_number | def four_number
@four_number ||= begin
fn = ip.split(".").map(&:to_i)
raise "ip is no valid" if fn.length != 4 || fn.any?{ |d| d < 0 || d > 255}
fn
end
end | ruby | def four_number
@four_number ||= begin
fn = ip.split(".").map(&:to_i)
raise "ip is no valid" if fn.length != 4 || fn.any?{ |d| d < 0 || d > 255}
fn
end
end | [
"def",
"four_number",
"@four_number",
"||=",
"begin",
"fn",
"=",
"ip",
".",
"split",
"(",
"\".\"",
")",
".",
"map",
"(",
":to_i",
")",
"raise",
"\"ip is no valid\"",
"if",
"fn",
".",
"length",
"!=",
"4",
"||",
"fn",
".",
"any?",
"{",
"|",
"d",
"|",
"d",
"<",
"0",
"||",
"d",
">",
"255",
"}",
"fn",
"end",
"end"
] | Initialize IP object
== parameters:
params::
Might contain address(hostname) and protocol, or just IP
== Returns:
self | [
"Initialize",
"IP",
"object"
] | 152e90efa4cb267dea013f31cbca24d9278185ed | https://github.com/mycolorway/SeventeenMon/blob/152e90efa4cb267dea013f31cbca24d9278185ed/lib/seventeen_mon/ip.rb#L19-L25 |
23,620 | instructure/moodle2cc | lib/moodle2cc/cc/assignment.rb | Moodle2CC::CC.Assignment.build_meta_fields | def build_meta_fields(mod)
fields = {}
%w{mod_type assignment_type}.each do |key|
fields[key] = mod.send(key) if mod.respond_to?(key)
end
if mod.grade_item
Moodle2CC::Moodle::GradeItem::PROPERTIES.each do |key|
fields[key] = mod.grade_item.send(key) if mod.grade_item.respond_to?(key)
end
end
fields
end | ruby | def build_meta_fields(mod)
fields = {}
%w{mod_type assignment_type}.each do |key|
fields[key] = mod.send(key) if mod.respond_to?(key)
end
if mod.grade_item
Moodle2CC::Moodle::GradeItem::PROPERTIES.each do |key|
fields[key] = mod.grade_item.send(key) if mod.grade_item.respond_to?(key)
end
end
fields
end | [
"def",
"build_meta_fields",
"(",
"mod",
")",
"fields",
"=",
"{",
"}",
"%w{",
"mod_type",
"assignment_type",
"}",
".",
"each",
"do",
"|",
"key",
"|",
"fields",
"[",
"key",
"]",
"=",
"mod",
".",
"send",
"(",
"key",
")",
"if",
"mod",
".",
"respond_to?",
"(",
"key",
")",
"end",
"if",
"mod",
".",
"grade_item",
"Moodle2CC",
"::",
"Moodle",
"::",
"GradeItem",
"::",
"PROPERTIES",
".",
"each",
"do",
"|",
"key",
"|",
"fields",
"[",
"key",
"]",
"=",
"mod",
".",
"grade_item",
".",
"send",
"(",
"key",
")",
"if",
"mod",
".",
"grade_item",
".",
"respond_to?",
"(",
"key",
")",
"end",
"end",
"fields",
"end"
] | Common Cartridge doesn't have anywhere to put assignment meta data like this
So add them as HTML meta fields in the HTML file | [
"Common",
"Cartridge",
"doesn",
"t",
"have",
"anywhere",
"to",
"put",
"assignment",
"meta",
"data",
"like",
"this",
"So",
"add",
"them",
"as",
"HTML",
"meta",
"fields",
"in",
"the",
"HTML",
"file"
] | cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/cc/assignment.rb#L18-L30 |
23,621 | norman/squirm | lib/squirm/core.rb | Squirm.Core.connect | def connect(options = {})
return @pool = options[:pool] if options[:pool]
options = options.dup
timeout = options.delete(:timeout) || 5
pool_size = options.delete(:pool_size) || 1
@pool = Squirm::Pool.new(timeout)
pool_size.times do
conn = PGconn.open(options)
yield conn if block_given?
@pool.checkin conn
end
end | ruby | def connect(options = {})
return @pool = options[:pool] if options[:pool]
options = options.dup
timeout = options.delete(:timeout) || 5
pool_size = options.delete(:pool_size) || 1
@pool = Squirm::Pool.new(timeout)
pool_size.times do
conn = PGconn.open(options)
yield conn if block_given?
@pool.checkin conn
end
end | [
"def",
"connect",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"@pool",
"=",
"options",
"[",
":pool",
"]",
"if",
"options",
"[",
":pool",
"]",
"options",
"=",
"options",
".",
"dup",
"timeout",
"=",
"options",
".",
"delete",
"(",
":timeout",
")",
"||",
"5",
"pool_size",
"=",
"options",
".",
"delete",
"(",
":pool_size",
")",
"||",
"1",
"@pool",
"=",
"Squirm",
"::",
"Pool",
".",
"new",
"(",
"timeout",
")",
"pool_size",
".",
"times",
"do",
"conn",
"=",
"PGconn",
".",
"open",
"(",
"options",
")",
"yield",
"conn",
"if",
"block_given?",
"@pool",
".",
"checkin",
"conn",
"end",
"end"
] | Establishes a connection pool.
@param [Hash] options The connection options
@option options [String] :pool Use the given pool rather than Squirm's.
@option options [Fixnum] :timeout The pool timeout.
@option options [Fixnum] :pool_size The pool size. | [
"Establishes",
"a",
"connection",
"pool",
"."
] | bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/core.rb#L16-L27 |
23,622 | norman/squirm | lib/squirm/core.rb | Squirm.Core.exec | def exec(*args, &block)
if current = Thread.current[:squirm_connection]
current.exec(*args, &block)
else
use {|conn| conn.exec(*args, &block)}
end
end | ruby | def exec(*args, &block)
if current = Thread.current[:squirm_connection]
current.exec(*args, &block)
else
use {|conn| conn.exec(*args, &block)}
end
end | [
"def",
"exec",
"(",
"*",
"args",
",",
"&",
"block",
")",
"if",
"current",
"=",
"Thread",
".",
"current",
"[",
":squirm_connection",
"]",
"current",
".",
"exec",
"(",
"args",
",",
"block",
")",
"else",
"use",
"{",
"|",
"conn",
"|",
"conn",
".",
"exec",
"(",
"args",
",",
"block",
")",
"}",
"end",
"end"
] | Executes the query and passes the result to the block you specify. | [
"Executes",
"the",
"query",
"and",
"passes",
"the",
"result",
"to",
"the",
"block",
"you",
"specify",
"."
] | bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/core.rb#L37-L43 |
23,623 | norman/squirm | lib/squirm/core.rb | Squirm.Core.use | def use(conn = nil)
conn_given = !!conn
conn = conn_given ? conn : @pool.checkout
begin
yield Thread.current[:squirm_connection] = conn
ensure
Thread.current[:squirm_connection] = nil
@pool.checkin conn unless conn_given
end
end | ruby | def use(conn = nil)
conn_given = !!conn
conn = conn_given ? conn : @pool.checkout
begin
yield Thread.current[:squirm_connection] = conn
ensure
Thread.current[:squirm_connection] = nil
@pool.checkin conn unless conn_given
end
end | [
"def",
"use",
"(",
"conn",
"=",
"nil",
")",
"conn_given",
"=",
"!",
"!",
"conn",
"conn",
"=",
"conn_given",
"?",
"conn",
":",
"@pool",
".",
"checkout",
"begin",
"yield",
"Thread",
".",
"current",
"[",
":squirm_connection",
"]",
"=",
"conn",
"ensure",
"Thread",
".",
"current",
"[",
":squirm_connection",
"]",
"=",
"nil",
"@pool",
".",
"checkin",
"conn",
"unless",
"conn_given",
"end",
"end"
] | Uses a connection for all database access inside the given block. If no
connection is given, then one will be checked out from the pool for use
inside the block, and then checked back in when the method returns. | [
"Uses",
"a",
"connection",
"for",
"all",
"database",
"access",
"inside",
"the",
"given",
"block",
".",
"If",
"no",
"connection",
"is",
"given",
"then",
"one",
"will",
"be",
"checked",
"out",
"from",
"the",
"pool",
"for",
"use",
"inside",
"the",
"block",
"and",
"then",
"checked",
"back",
"in",
"when",
"the",
"method",
"returns",
"."
] | bbe38ebb27d0a43c5738213aab1c41bfa7e357ea | https://github.com/norman/squirm/blob/bbe38ebb27d0a43c5738213aab1c41bfa7e357ea/lib/squirm/core.rb#L72-L81 |
23,624 | cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.manifest= | def manifest=(hash)
return unless hash
raise "Input should be Hash" unless hash.is_a? Hash
@manifest.merge! VCAP.symbolize_keys(hash)
end | ruby | def manifest=(hash)
return unless hash
raise "Input should be Hash" unless hash.is_a? Hash
@manifest.merge! VCAP.symbolize_keys(hash)
end | [
"def",
"manifest",
"=",
"(",
"hash",
")",
"return",
"unless",
"hash",
"raise",
"\"Input should be Hash\"",
"unless",
"hash",
".",
"is_a?",
"Hash",
"@manifest",
".",
"merge!",
"VCAP",
".",
"symbolize_keys",
"(",
"hash",
")",
"end"
] | add +hash+ to manifest file. | [
"add",
"+",
"hash",
"+",
"to",
"manifest",
"file",
"."
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L42-L46 |
23,625 | cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.pack | def pack(force=nil)
if File.exists? @zipfile
if force
File.delete @zipfile
else
raise "File #{@zipfile} already exists."
end
end
dirname = File.dirname(@zipfile)
raise "Dir #{dirname} is not exists." unless File.exists? dirname
raise "Dir #{dirname} is not writable." unless File.writable? dirname
Zip::ZipFile.open(@zipfile, Zip::ZipFile::CREATE) do |zf|
# manifest file
zf.get_output_stream(MANIFEST_FILE) {|o| o << Yajl::Encoder.encode(@manifest)}
@files.each do |f, path|
zf.add("#{CONTENT_FOLDER}/#{f}", path)
end
end
begin
File.chmod(@filemode, @zipfile)
rescue => e
raise "Fail to change the mode of #{@zipfile} to #{@filemode.to_s(8)}: #{e}"
end
end | ruby | def pack(force=nil)
if File.exists? @zipfile
if force
File.delete @zipfile
else
raise "File #{@zipfile} already exists."
end
end
dirname = File.dirname(@zipfile)
raise "Dir #{dirname} is not exists." unless File.exists? dirname
raise "Dir #{dirname} is not writable." unless File.writable? dirname
Zip::ZipFile.open(@zipfile, Zip::ZipFile::CREATE) do |zf|
# manifest file
zf.get_output_stream(MANIFEST_FILE) {|o| o << Yajl::Encoder.encode(@manifest)}
@files.each do |f, path|
zf.add("#{CONTENT_FOLDER}/#{f}", path)
end
end
begin
File.chmod(@filemode, @zipfile)
rescue => e
raise "Fail to change the mode of #{@zipfile} to #{@filemode.to_s(8)}: #{e}"
end
end | [
"def",
"pack",
"(",
"force",
"=",
"nil",
")",
"if",
"File",
".",
"exists?",
"@zipfile",
"if",
"force",
"File",
".",
"delete",
"@zipfile",
"else",
"raise",
"\"File #{@zipfile} already exists.\"",
"end",
"end",
"dirname",
"=",
"File",
".",
"dirname",
"(",
"@zipfile",
")",
"raise",
"\"Dir #{dirname} is not exists.\"",
"unless",
"File",
".",
"exists?",
"dirname",
"raise",
"\"Dir #{dirname} is not writable.\"",
"unless",
"File",
".",
"writable?",
"dirname",
"Zip",
"::",
"ZipFile",
".",
"open",
"(",
"@zipfile",
",",
"Zip",
"::",
"ZipFile",
"::",
"CREATE",
")",
"do",
"|",
"zf",
"|",
"# manifest file",
"zf",
".",
"get_output_stream",
"(",
"MANIFEST_FILE",
")",
"{",
"|",
"o",
"|",
"o",
"<<",
"Yajl",
"::",
"Encoder",
".",
"encode",
"(",
"@manifest",
")",
"}",
"@files",
".",
"each",
"do",
"|",
"f",
",",
"path",
"|",
"zf",
".",
"add",
"(",
"\"#{CONTENT_FOLDER}/#{f}\"",
",",
"path",
")",
"end",
"end",
"begin",
"File",
".",
"chmod",
"(",
"@filemode",
",",
"@zipfile",
")",
"rescue",
"=>",
"e",
"raise",
"\"Fail to change the mode of #{@zipfile} to #{@filemode.to_s(8)}: #{e}\"",
"end",
"end"
] | package files and manifest in +zipfile+. If +force+ is true, we'll try to delete the target +zipfile+ if it already exists. | [
"package",
"files",
"and",
"manifest",
"in",
"+",
"zipfile",
"+",
".",
"If",
"+",
"force",
"+",
"is",
"true",
"we",
"ll",
"try",
"to",
"delete",
"the",
"target",
"+",
"zipfile",
"+",
"if",
"it",
"already",
"exists",
"."
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L49-L76 |
23,626 | cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.unpack | def unpack path
raise "File #{@zipfile} not exists." unless File.exists? @zipfile
raise "unpack path: #{path} not found." unless Dir.exists? path
raise "unpack path: #{path} is not writable." unless File.writable? path
files = []
Zip::ZipFile.foreach(@zipfile) do |entry|
next if entry.to_s == MANIFEST_FILE
entry_name = File.basename entry.to_s
dst_path = File.join(path, entry_name)
dirname = File.dirname(dst_path)
FileUtils.mkdir_p(dirname) unless File.exists? dirname
files << dst_path
entry.extract(dst_path)
end
files.freeze
yield files if block_given?
files
rescue => e
# auto cleanup if error raised.
files.each{|f| File.delete f if File.exists? f} if files
raise ServiceError.new(ServiceError::FILE_CORRUPTED) if e.is_a? Zlib::DataError
raise e
end | ruby | def unpack path
raise "File #{@zipfile} not exists." unless File.exists? @zipfile
raise "unpack path: #{path} not found." unless Dir.exists? path
raise "unpack path: #{path} is not writable." unless File.writable? path
files = []
Zip::ZipFile.foreach(@zipfile) do |entry|
next if entry.to_s == MANIFEST_FILE
entry_name = File.basename entry.to_s
dst_path = File.join(path, entry_name)
dirname = File.dirname(dst_path)
FileUtils.mkdir_p(dirname) unless File.exists? dirname
files << dst_path
entry.extract(dst_path)
end
files.freeze
yield files if block_given?
files
rescue => e
# auto cleanup if error raised.
files.each{|f| File.delete f if File.exists? f} if files
raise ServiceError.new(ServiceError::FILE_CORRUPTED) if e.is_a? Zlib::DataError
raise e
end | [
"def",
"unpack",
"path",
"raise",
"\"File #{@zipfile} not exists.\"",
"unless",
"File",
".",
"exists?",
"@zipfile",
"raise",
"\"unpack path: #{path} not found.\"",
"unless",
"Dir",
".",
"exists?",
"path",
"raise",
"\"unpack path: #{path} is not writable.\"",
"unless",
"File",
".",
"writable?",
"path",
"files",
"=",
"[",
"]",
"Zip",
"::",
"ZipFile",
".",
"foreach",
"(",
"@zipfile",
")",
"do",
"|",
"entry",
"|",
"next",
"if",
"entry",
".",
"to_s",
"==",
"MANIFEST_FILE",
"entry_name",
"=",
"File",
".",
"basename",
"entry",
".",
"to_s",
"dst_path",
"=",
"File",
".",
"join",
"(",
"path",
",",
"entry_name",
")",
"dirname",
"=",
"File",
".",
"dirname",
"(",
"dst_path",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"dirname",
")",
"unless",
"File",
".",
"exists?",
"dirname",
"files",
"<<",
"dst_path",
"entry",
".",
"extract",
"(",
"dst_path",
")",
"end",
"files",
".",
"freeze",
"yield",
"files",
"if",
"block_given?",
"files",
"rescue",
"=>",
"e",
"# auto cleanup if error raised.",
"files",
".",
"each",
"{",
"|",
"f",
"|",
"File",
".",
"delete",
"f",
"if",
"File",
".",
"exists?",
"f",
"}",
"if",
"files",
"raise",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"FILE_CORRUPTED",
")",
"if",
"e",
".",
"is_a?",
"Zlib",
"::",
"DataError",
"raise",
"e",
"end"
] | unpack the content to +path+ and return extraced file list. | [
"unpack",
"the",
"content",
"to",
"+",
"path",
"+",
"and",
"return",
"extraced",
"file",
"list",
"."
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L79-L102 |
23,627 | cloudfoundry-attic/vcap-services-base | lib/base/job/package.rb | VCAP::Services::Base::AsyncJob.Package.load_manifest | def load_manifest
zf = Zip::ZipFile.open(@zipfile)
@manifest = VCAP.symbolize_keys(Yajl::Parser.parse(zf.read(MANIFEST_FILE)))
rescue Errno::ENOENT => e
raise ServiceError.new(ServiceError::BAD_SERIALIZED_DATAFILE, "request. Missing manifest.")
end | ruby | def load_manifest
zf = Zip::ZipFile.open(@zipfile)
@manifest = VCAP.symbolize_keys(Yajl::Parser.parse(zf.read(MANIFEST_FILE)))
rescue Errno::ENOENT => e
raise ServiceError.new(ServiceError::BAD_SERIALIZED_DATAFILE, "request. Missing manifest.")
end | [
"def",
"load_manifest",
"zf",
"=",
"Zip",
"::",
"ZipFile",
".",
"open",
"(",
"@zipfile",
")",
"@manifest",
"=",
"VCAP",
".",
"symbolize_keys",
"(",
"Yajl",
"::",
"Parser",
".",
"parse",
"(",
"zf",
".",
"read",
"(",
"MANIFEST_FILE",
")",
")",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"=>",
"e",
"raise",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"BAD_SERIALIZED_DATAFILE",
",",
"\"request. Missing manifest.\"",
")",
"end"
] | read manifest in a zip file | [
"read",
"manifest",
"in",
"a",
"zip",
"file"
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/package.rb#L105-L110 |
23,628 | maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.filter | def filter(name, callable=nil, &block)
if block_given?
transforms[name.to_sym] = block
else
transforms[name.to_sym] = callable
end
end | ruby | def filter(name, callable=nil, &block)
if block_given?
transforms[name.to_sym] = block
else
transforms[name.to_sym] = callable
end
end | [
"def",
"filter",
"(",
"name",
",",
"callable",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"block_given?",
"transforms",
"[",
"name",
".",
"to_sym",
"]",
"=",
"block",
"else",
"transforms",
"[",
"name",
".",
"to_sym",
"]",
"=",
"callable",
"end",
"end"
] | Registers the given block as a string filter.
@param [Symbol] name
@yield [String]
@yieldreturn [String] | [
"Registers",
"the",
"given",
"block",
"as",
"a",
"string",
"filter",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L41-L47 |
23,629 | maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.define_rule | def define_rule(name, trace, productions)
rules[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | ruby | def define_rule(name, trace, productions)
rules[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | [
"def",
"define_rule",
"(",
"name",
",",
"trace",
",",
"productions",
")",
"rules",
"[",
"name",
".",
"to_sym",
"]",
"=",
"Rule",
".",
"new",
"(",
"name",
".",
"to_sym",
",",
"construct_rule",
"(",
"productions",
")",
",",
"trace",
")",
"end"
] | Defines a static rule in the grammar.
@param [Symbol] name
@param [Array] productions | [
"Defines",
"a",
"static",
"rule",
"in",
"the",
"grammar",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L69-L71 |
23,630 | maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.define_context_rule | def define_context_rule(name, trace, productions)
productions = [productions] unless productions.is_a?(Enumerable)
context[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | ruby | def define_context_rule(name, trace, productions)
productions = [productions] unless productions.is_a?(Enumerable)
context[name.to_sym] = Rule.new(name.to_sym, construct_rule(productions), trace)
end | [
"def",
"define_context_rule",
"(",
"name",
",",
"trace",
",",
"productions",
")",
"productions",
"=",
"[",
"productions",
"]",
"unless",
"productions",
".",
"is_a?",
"(",
"Enumerable",
")",
"context",
"[",
"name",
".",
"to_sym",
"]",
"=",
"Rule",
".",
"new",
"(",
"name",
".",
"to_sym",
",",
"construct_rule",
"(",
"productions",
")",
",",
"trace",
")",
"end"
] | Defines a rule in the temporary evaluation context.
@param [Symbol] name
@param [Array] productions | [
"Defines",
"a",
"rule",
"in",
"the",
"temporary",
"evaluation",
"context",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L77-L80 |
23,631 | maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.expand | def expand(symbol)
expansion = rules[symbol] || context[symbol]
if expansion.nil?
if @options.strict?
raise Errors::UndefinedRule.new(@last_expansion, symbol)
else
expansion = Production::Terminal.new('')
end
end
@last_expansion = expansion
expansion
end | ruby | def expand(symbol)
expansion = rules[symbol] || context[symbol]
if expansion.nil?
if @options.strict?
raise Errors::UndefinedRule.new(@last_expansion, symbol)
else
expansion = Production::Terminal.new('')
end
end
@last_expansion = expansion
expansion
end | [
"def",
"expand",
"(",
"symbol",
")",
"expansion",
"=",
"rules",
"[",
"symbol",
"]",
"||",
"context",
"[",
"symbol",
"]",
"if",
"expansion",
".",
"nil?",
"if",
"@options",
".",
"strict?",
"raise",
"Errors",
"::",
"UndefinedRule",
".",
"new",
"(",
"@last_expansion",
",",
"symbol",
")",
"else",
"expansion",
"=",
"Production",
"::",
"Terminal",
".",
"new",
"(",
"''",
")",
"end",
"end",
"@last_expansion",
"=",
"expansion",
"expansion",
"end"
] | Expands the given symbol to its rule.
@param [Symbol] symbol
@return [Calyx::Rule] | [
"Expands",
"the",
"given",
"symbol",
"to",
"its",
"rule",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L86-L99 |
23,632 | maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.transform | def transform(name, value)
if transforms.key?(name)
transforms[name].call(value)
else
modifiers.transform(name, value)
end
end | ruby | def transform(name, value)
if transforms.key?(name)
transforms[name].call(value)
else
modifiers.transform(name, value)
end
end | [
"def",
"transform",
"(",
"name",
",",
"value",
")",
"if",
"transforms",
".",
"key?",
"(",
"name",
")",
"transforms",
"[",
"name",
"]",
".",
"call",
"(",
"value",
")",
"else",
"modifiers",
".",
"transform",
"(",
"name",
",",
"value",
")",
"end",
"end"
] | Applies the given modifier function to the given value to transform it.
@param [Symbol] name
@param [String] value
@return [String] | [
"Applies",
"the",
"given",
"modifier",
"function",
"to",
"the",
"given",
"value",
"to",
"transform",
"it",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L106-L112 |
23,633 | maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.unique_expansion | def unique_expansion(symbol)
pending = true
uniques[symbol] = [] if uniques[symbol].nil?
while pending
if uniques[symbol].size == expand(symbol).size
uniques[symbol] = []
pending = false
end
result = expand(symbol).evaluate(@options)
unless uniques[symbol].include?(result)
uniques[symbol] << result
pending = false
end
end
result
end | ruby | def unique_expansion(symbol)
pending = true
uniques[symbol] = [] if uniques[symbol].nil?
while pending
if uniques[symbol].size == expand(symbol).size
uniques[symbol] = []
pending = false
end
result = expand(symbol).evaluate(@options)
unless uniques[symbol].include?(result)
uniques[symbol] << result
pending = false
end
end
result
end | [
"def",
"unique_expansion",
"(",
"symbol",
")",
"pending",
"=",
"true",
"uniques",
"[",
"symbol",
"]",
"=",
"[",
"]",
"if",
"uniques",
"[",
"symbol",
"]",
".",
"nil?",
"while",
"pending",
"if",
"uniques",
"[",
"symbol",
"]",
".",
"size",
"==",
"expand",
"(",
"symbol",
")",
".",
"size",
"uniques",
"[",
"symbol",
"]",
"=",
"[",
"]",
"pending",
"=",
"false",
"end",
"result",
"=",
"expand",
"(",
"symbol",
")",
".",
"evaluate",
"(",
"@options",
")",
"unless",
"uniques",
"[",
"symbol",
"]",
".",
"include?",
"(",
"result",
")",
"uniques",
"[",
"symbol",
"]",
"<<",
"result",
"pending",
"=",
"false",
"end",
"end",
"result",
"end"
] | Expands a unique rule symbol by evaluating it and checking that it hasn't
previously been selected.
@param [Symbol] symbol | [
"Expands",
"a",
"unique",
"rule",
"symbol",
"by",
"evaluating",
"it",
"and",
"checking",
"that",
"it",
"hasn",
"t",
"previously",
"been",
"selected",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L126-L145 |
23,634 | maetl/calyx | lib/calyx/registry.rb | Calyx.Registry.evaluate | def evaluate(start_symbol=:start, rules_map={})
reset_evaluation_context
rules_map.each do |key, value|
if rules.key?(key.to_sym)
raise Errors::DuplicateRule.new(key)
end
define_context_rule(key, caller_locations.last, value)
end
[start_symbol, expand(start_symbol).evaluate(@options)]
end | ruby | def evaluate(start_symbol=:start, rules_map={})
reset_evaluation_context
rules_map.each do |key, value|
if rules.key?(key.to_sym)
raise Errors::DuplicateRule.new(key)
end
define_context_rule(key, caller_locations.last, value)
end
[start_symbol, expand(start_symbol).evaluate(@options)]
end | [
"def",
"evaluate",
"(",
"start_symbol",
"=",
":start",
",",
"rules_map",
"=",
"{",
"}",
")",
"reset_evaluation_context",
"rules_map",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"rules",
".",
"key?",
"(",
"key",
".",
"to_sym",
")",
"raise",
"Errors",
"::",
"DuplicateRule",
".",
"new",
"(",
"key",
")",
"end",
"define_context_rule",
"(",
"key",
",",
"caller_locations",
".",
"last",
",",
"value",
")",
"end",
"[",
"start_symbol",
",",
"expand",
"(",
"start_symbol",
")",
".",
"evaluate",
"(",
"@options",
")",
"]",
"end"
] | Evaluates the grammar defined in this registry, combining it with rules
from the passed in context.
Produces a syntax tree of nested list nodes.
@param [Symbol] start_symbol
@param [Hash] rules_map
@return [Array] | [
"Evaluates",
"the",
"grammar",
"defined",
"in",
"this",
"registry",
"combining",
"it",
"with",
"rules",
"from",
"the",
"passed",
"in",
"context",
"."
] | 5011cd4b948792bdfd22ae1d3eaac9ff529e3861 | https://github.com/maetl/calyx/blob/5011cd4b948792bdfd22ae1d3eaac9ff529e3861/lib/calyx/registry.rb#L165-L177 |
23,635 | cloudfoundry-attic/vcap-services-base | lib/base/job/lock.rb | VCAP::Services::Base::AsyncJob.Lock.make_logger | def make_logger
logger = Logger.new(STDOUT)
logger.level = Logger::ERROR
logger
end | ruby | def make_logger
logger = Logger.new(STDOUT)
logger.level = Logger::ERROR
logger
end | [
"def",
"make_logger",
"logger",
"=",
"Logger",
".",
"new",
"(",
"STDOUT",
")",
"logger",
".",
"level",
"=",
"Logger",
"::",
"ERROR",
"logger",
"end"
] | Options for lock
name - The uuid of the lock
timeout - The time that waits to acquire the lock, default 20 seconds
expiration - Lock expires in given seconds if not refreshed, default 10 seconds
logger - The logger..
ttl - The max time that a thread can acquire the lock, default 600 seconds. Lock raise +JOB_TIMEOUT+ error once the ttl is exceeded. | [
"Options",
"for",
"lock",
"name",
"-",
"The",
"uuid",
"of",
"the",
"lock",
"timeout",
"-",
"The",
"time",
"that",
"waits",
"to",
"acquire",
"the",
"lock",
"default",
"20",
"seconds",
"expiration",
"-",
"Lock",
"expires",
"in",
"given",
"seconds",
"if",
"not",
"refreshed",
"default",
"10",
"seconds",
"logger",
"-",
"The",
"logger",
"..",
"ttl",
"-",
"The",
"max",
"time",
"that",
"a",
"thread",
"can",
"acquire",
"the",
"lock",
"default",
"600",
"seconds",
".",
"Lock",
"raise",
"+",
"JOB_TIMEOUT",
"+",
"error",
"once",
"the",
"ttl",
"is",
"exceeded",
"."
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/job/lock.rb#L33-L37 |
23,636 | cloudfoundry-attic/vcap-services-base | lib/base/asynchronous_service_gateway.rb | VCAP::Services.AsynchronousServiceGateway.validate_incoming_request | def validate_incoming_request
unless request.media_type == Rack::Mime.mime_type('.json')
error_msg = ServiceError.new(ServiceError::INVALID_CONTENT).to_hash
logger.error("Validation failure: #{error_msg.inspect}, request media type: #{request.media_type} is not json")
abort_request(error_msg)
end
unless auth_token && (auth_token == @token)
error_msg = ServiceError.new(ServiceError::NOT_AUTHORIZED).to_hash
logger.error("Validation failure: #{error_msg.inspect}, expected token: #{@token}, specified token: #{auth_token}")
abort_request(error_msg)
end
unless @handle_fetched
error_msg = ServiceError.new(ServiceError::SERVICE_UNAVAILABLE).to_hash
logger.error("Validation failure: #{error_msg.inspect}, handles not fetched")
abort_request(error_msg)
end
end | ruby | def validate_incoming_request
unless request.media_type == Rack::Mime.mime_type('.json')
error_msg = ServiceError.new(ServiceError::INVALID_CONTENT).to_hash
logger.error("Validation failure: #{error_msg.inspect}, request media type: #{request.media_type} is not json")
abort_request(error_msg)
end
unless auth_token && (auth_token == @token)
error_msg = ServiceError.new(ServiceError::NOT_AUTHORIZED).to_hash
logger.error("Validation failure: #{error_msg.inspect}, expected token: #{@token}, specified token: #{auth_token}")
abort_request(error_msg)
end
unless @handle_fetched
error_msg = ServiceError.new(ServiceError::SERVICE_UNAVAILABLE).to_hash
logger.error("Validation failure: #{error_msg.inspect}, handles not fetched")
abort_request(error_msg)
end
end | [
"def",
"validate_incoming_request",
"unless",
"request",
".",
"media_type",
"==",
"Rack",
"::",
"Mime",
".",
"mime_type",
"(",
"'.json'",
")",
"error_msg",
"=",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"INVALID_CONTENT",
")",
".",
"to_hash",
"logger",
".",
"error",
"(",
"\"Validation failure: #{error_msg.inspect}, request media type: #{request.media_type} is not json\"",
")",
"abort_request",
"(",
"error_msg",
")",
"end",
"unless",
"auth_token",
"&&",
"(",
"auth_token",
"==",
"@token",
")",
"error_msg",
"=",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"NOT_AUTHORIZED",
")",
".",
"to_hash",
"logger",
".",
"error",
"(",
"\"Validation failure: #{error_msg.inspect}, expected token: #{@token}, specified token: #{auth_token}\"",
")",
"abort_request",
"(",
"error_msg",
")",
"end",
"unless",
"@handle_fetched",
"error_msg",
"=",
"ServiceError",
".",
"new",
"(",
"ServiceError",
"::",
"SERVICE_UNAVAILABLE",
")",
".",
"to_hash",
"logger",
".",
"error",
"(",
"\"Validation failure: #{error_msg.inspect}, handles not fetched\"",
")",
"abort_request",
"(",
"error_msg",
")",
"end",
"end"
] | Validate the incoming request | [
"Validate",
"the",
"incoming",
"request"
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/asynchronous_service_gateway.rb#L113-L129 |
23,637 | cloudfoundry-attic/vcap-services-base | lib/base/snapshot_v2/snapshot.rb | VCAP::Services::Base::SnapshotV2.BaseRollbackSnapshotJob.perform | def perform
begin
required_options :service_id, :snapshot_id
@name = options["service_id"]
@snapshot_id = options["snapshot_id"]
@logger.info("Launch job: #{self.class} for #{name}")
lock = create_lock
@snapshot_files = []
lock.lock do
# extract origin files from package
dump_path = get_dump_path(name, snapshot_id)
package_file = "#{snapshot_id}.zip"
package = Package.load(File.join(dump_path, package_file))
@manifest = package.manifest
@snapshot_files = package.unpack(dump_path)
@logger.debug("Unpack files from #{package_file}: #{@snapshot_files}")
raise "Package file doesn't contain snapshot file." if @snapshot_files.empty?
result = execute
@logger.info("Results of rollback snapshot: #{result}")
completed(Yajl::Encoder.encode({:result => :ok}))
@logger.info("Complete job: #{self.class} for #{name}")
end
rescue => e
handle_error(e)
ensure
set_status({:complete_time => Time.now.to_s})
@snapshot_files.each{|f| File.delete(f) if File.exists? f} if @snapshot_files
end
end | ruby | def perform
begin
required_options :service_id, :snapshot_id
@name = options["service_id"]
@snapshot_id = options["snapshot_id"]
@logger.info("Launch job: #{self.class} for #{name}")
lock = create_lock
@snapshot_files = []
lock.lock do
# extract origin files from package
dump_path = get_dump_path(name, snapshot_id)
package_file = "#{snapshot_id}.zip"
package = Package.load(File.join(dump_path, package_file))
@manifest = package.manifest
@snapshot_files = package.unpack(dump_path)
@logger.debug("Unpack files from #{package_file}: #{@snapshot_files}")
raise "Package file doesn't contain snapshot file." if @snapshot_files.empty?
result = execute
@logger.info("Results of rollback snapshot: #{result}")
completed(Yajl::Encoder.encode({:result => :ok}))
@logger.info("Complete job: #{self.class} for #{name}")
end
rescue => e
handle_error(e)
ensure
set_status({:complete_time => Time.now.to_s})
@snapshot_files.each{|f| File.delete(f) if File.exists? f} if @snapshot_files
end
end | [
"def",
"perform",
"begin",
"required_options",
":service_id",
",",
":snapshot_id",
"@name",
"=",
"options",
"[",
"\"service_id\"",
"]",
"@snapshot_id",
"=",
"options",
"[",
"\"snapshot_id\"",
"]",
"@logger",
".",
"info",
"(",
"\"Launch job: #{self.class} for #{name}\"",
")",
"lock",
"=",
"create_lock",
"@snapshot_files",
"=",
"[",
"]",
"lock",
".",
"lock",
"do",
"# extract origin files from package",
"dump_path",
"=",
"get_dump_path",
"(",
"name",
",",
"snapshot_id",
")",
"package_file",
"=",
"\"#{snapshot_id}.zip\"",
"package",
"=",
"Package",
".",
"load",
"(",
"File",
".",
"join",
"(",
"dump_path",
",",
"package_file",
")",
")",
"@manifest",
"=",
"package",
".",
"manifest",
"@snapshot_files",
"=",
"package",
".",
"unpack",
"(",
"dump_path",
")",
"@logger",
".",
"debug",
"(",
"\"Unpack files from #{package_file}: #{@snapshot_files}\"",
")",
"raise",
"\"Package file doesn't contain snapshot file.\"",
"if",
"@snapshot_files",
".",
"empty?",
"result",
"=",
"execute",
"@logger",
".",
"info",
"(",
"\"Results of rollback snapshot: #{result}\"",
")",
"completed",
"(",
"Yajl",
"::",
"Encoder",
".",
"encode",
"(",
"{",
":result",
"=>",
":ok",
"}",
")",
")",
"@logger",
".",
"info",
"(",
"\"Complete job: #{self.class} for #{name}\"",
")",
"end",
"rescue",
"=>",
"e",
"handle_error",
"(",
"e",
")",
"ensure",
"set_status",
"(",
"{",
":complete_time",
"=>",
"Time",
".",
"now",
".",
"to_s",
"}",
")",
"@snapshot_files",
".",
"each",
"{",
"|",
"f",
"|",
"File",
".",
"delete",
"(",
"f",
")",
"if",
"File",
".",
"exists?",
"f",
"}",
"if",
"@snapshot_files",
"end",
"end"
] | workflow template
Subclass implement execute method which returns true for a successful rollback | [
"workflow",
"template",
"Subclass",
"implement",
"execute",
"method",
"which",
"returns",
"true",
"for",
"a",
"successful",
"rollback"
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/snapshot_v2/snapshot.rb#L193-L225 |
23,638 | cloudfoundry-attic/vcap-services-base | lib/base/simple_aop.rb | Before.ClassMethods.enhance_method | def enhance_method(method, callbacks)
_method = (PREFIX + method.to_s).to_sym
alias_method _method, method
self.send(:define_method, method) do |*args, &blk|
[callbacks, _method].flatten.each do |callback|
break unless self.send(callback, *args, &blk)
end
end
end | ruby | def enhance_method(method, callbacks)
_method = (PREFIX + method.to_s).to_sym
alias_method _method, method
self.send(:define_method, method) do |*args, &blk|
[callbacks, _method].flatten.each do |callback|
break unless self.send(callback, *args, &blk)
end
end
end | [
"def",
"enhance_method",
"(",
"method",
",",
"callbacks",
")",
"_method",
"=",
"(",
"PREFIX",
"+",
"method",
".",
"to_s",
")",
".",
"to_sym",
"alias_method",
"_method",
",",
"method",
"self",
".",
"send",
"(",
":define_method",
",",
"method",
")",
"do",
"|",
"*",
"args",
",",
"&",
"blk",
"|",
"[",
"callbacks",
",",
"_method",
"]",
".",
"flatten",
".",
"each",
"do",
"|",
"callback",
"|",
"break",
"unless",
"self",
".",
"send",
"(",
"callback",
",",
"args",
",",
"blk",
")",
"end",
"end",
"end"
] | enhance single method with callbacks | [
"enhance",
"single",
"method",
"with",
"callbacks"
] | bde81300391cb27e1c531148d15bde696ebf4da0 | https://github.com/cloudfoundry-attic/vcap-services-base/blob/bde81300391cb27e1c531148d15bde696ebf4da0/lib/base/simple_aop.rb#L52-L61 |
23,639 | instructure/moodle2cc | lib/moodle2cc/moodle2converter/questionnaire_converter.rb | Moodle2CC::Moodle2Converter.QuestionnaireConverter.convert_rating_question | def convert_rating_question(moodle_question, canvas_question)
choices = create_rating_choices(moodle_question)
canvas_question.responses = []
moodle_question.choices.each_with_index do |answer, answer_idx|
response = {:id => "response#{answer_idx + 1}", :choices => []}
# add dropdown to the question text
canvas_question.material = canvas_question.material.to_s + "<p>#{answer[:content]} [#{response[:id]}]</p>"
choices.each_with_index do |choice, choice_idx|
response[:choices] << {:id => "#{moodle_question.id}_choice_#{answer_idx}_#{choice_idx}", :text => choice}
end
canvas_question.responses << response
end
end | ruby | def convert_rating_question(moodle_question, canvas_question)
choices = create_rating_choices(moodle_question)
canvas_question.responses = []
moodle_question.choices.each_with_index do |answer, answer_idx|
response = {:id => "response#{answer_idx + 1}", :choices => []}
# add dropdown to the question text
canvas_question.material = canvas_question.material.to_s + "<p>#{answer[:content]} [#{response[:id]}]</p>"
choices.each_with_index do |choice, choice_idx|
response[:choices] << {:id => "#{moodle_question.id}_choice_#{answer_idx}_#{choice_idx}", :text => choice}
end
canvas_question.responses << response
end
end | [
"def",
"convert_rating_question",
"(",
"moodle_question",
",",
"canvas_question",
")",
"choices",
"=",
"create_rating_choices",
"(",
"moodle_question",
")",
"canvas_question",
".",
"responses",
"=",
"[",
"]",
"moodle_question",
".",
"choices",
".",
"each_with_index",
"do",
"|",
"answer",
",",
"answer_idx",
"|",
"response",
"=",
"{",
":id",
"=>",
"\"response#{answer_idx + 1}\"",
",",
":choices",
"=>",
"[",
"]",
"}",
"# add dropdown to the question text",
"canvas_question",
".",
"material",
"=",
"canvas_question",
".",
"material",
".",
"to_s",
"+",
"\"<p>#{answer[:content]} [#{response[:id]}]</p>\"",
"choices",
".",
"each_with_index",
"do",
"|",
"choice",
",",
"choice_idx",
"|",
"response",
"[",
":choices",
"]",
"<<",
"{",
":id",
"=>",
"\"#{moodle_question.id}_choice_#{answer_idx}_#{choice_idx}\"",
",",
":text",
"=>",
"choice",
"}",
"end",
"canvas_question",
".",
"responses",
"<<",
"response",
"end",
"end"
] | For l..x rating questions | [
"For",
"l",
"..",
"x",
"rating",
"questions"
] | cdb1666a76b22e87e8853d4045e31439244cce4b | https://github.com/instructure/moodle2cc/blob/cdb1666a76b22e87e8853d4045e31439244cce4b/lib/moodle2cc/moodle2converter/questionnaire_converter.rb#L72-L88 |
23,640 | greysteil/spot-gps | lib/spot-gps/paginator.rb | SPOT.Paginator.enumerator | def enumerator
Enumerator.new do |yielder|
response = get_initial_response
loop do
items = response.records
# If there are no records, we're done
break if items.empty?
# Otherwise, iterate through the records...
items.each { |item| yielder << item }
# ...and fetch the next page
@params ||= {}
@params[:page] ||= 1
@params[:page] += 1
response = @service.list(**@params)
end
end.lazy
end | ruby | def enumerator
Enumerator.new do |yielder|
response = get_initial_response
loop do
items = response.records
# If there are no records, we're done
break if items.empty?
# Otherwise, iterate through the records...
items.each { |item| yielder << item }
# ...and fetch the next page
@params ||= {}
@params[:page] ||= 1
@params[:page] += 1
response = @service.list(**@params)
end
end.lazy
end | [
"def",
"enumerator",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"response",
"=",
"get_initial_response",
"loop",
"do",
"items",
"=",
"response",
".",
"records",
"# If there are no records, we're done",
"break",
"if",
"items",
".",
"empty?",
"# Otherwise, iterate through the records...",
"items",
".",
"each",
"{",
"|",
"item",
"|",
"yielder",
"<<",
"item",
"}",
"# ...and fetch the next page",
"@params",
"||=",
"{",
"}",
"@params",
"[",
":page",
"]",
"||=",
"1",
"@params",
"[",
":page",
"]",
"+=",
"1",
"response",
"=",
"@service",
".",
"list",
"(",
"**",
"@params",
")",
"end",
"end",
".",
"lazy",
"end"
] | Get a lazy enumerable for listing data from the API | [
"Get",
"a",
"lazy",
"enumerable",
"for",
"listing",
"data",
"from",
"the",
"API"
] | 808367da20dd9976f06cf281324566e25d6a3b35 | https://github.com/greysteil/spot-gps/blob/808367da20dd9976f06cf281324566e25d6a3b35/lib/spot-gps/paginator.rb#L10-L31 |
23,641 | kristianmandrup/troles | lib/troles/common/api/write.rb | Troles::Common::Api.Write.static_role! | def static_role! role_name
raise ArgumentError, "Take a single role name, was: #{role_name}" if !role_name || !role_name.kind_of_label?
troles_config.add_valid_roles role_name
if set_roles role_name
define_method :static_roles? do
true
end
end
end | ruby | def static_role! role_name
raise ArgumentError, "Take a single role name, was: #{role_name}" if !role_name || !role_name.kind_of_label?
troles_config.add_valid_roles role_name
if set_roles role_name
define_method :static_roles? do
true
end
end
end | [
"def",
"static_role!",
"role_name",
"raise",
"ArgumentError",
",",
"\"Take a single role name, was: #{role_name}\"",
"if",
"!",
"role_name",
"||",
"!",
"role_name",
".",
"kind_of_label?",
"troles_config",
".",
"add_valid_roles",
"role_name",
"if",
"set_roles",
"role_name",
"define_method",
":static_roles?",
"do",
"true",
"end",
"end",
"end"
] | Do we need a static_roles! method? I think so! | [
"Do",
"we",
"need",
"a",
"static_roles!",
"method?",
"I",
"think",
"so!"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/api/write.rb#L9-L17 |
23,642 | kristianmandrup/troles | lib/troles/common/api/write.rb | Troles::Common::Api.Write.set_roles | def set_roles *roles
roles_to_set = make_valid_roles(*roles).flat_uniq
return false if !roles_to_set || roles_to_set.empty?
store.set_roles(roles_to_set)
end | ruby | def set_roles *roles
roles_to_set = make_valid_roles(*roles).flat_uniq
return false if !roles_to_set || roles_to_set.empty?
store.set_roles(roles_to_set)
end | [
"def",
"set_roles",
"*",
"roles",
"roles_to_set",
"=",
"make_valid_roles",
"(",
"roles",
")",
".",
"flat_uniq",
"return",
"false",
"if",
"!",
"roles_to_set",
"||",
"roles_to_set",
".",
"empty?",
"store",
".",
"set_roles",
"(",
"roles_to_set",
")",
"end"
] | Sets new roles for the subject
@param [Array<Symbol>] list of role names
@return [true, false, Error] true if set ok, false if any roles were invalid, Error on some error | [
"Sets",
"new",
"roles",
"for",
"the",
"subject"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/api/write.rb#L51-L55 |
23,643 | arashm/PoParser | lib/poparser/entry.rb | PoParser.Entry.untranslated? | def untranslated?
return false if obsolete? || fuzzy?
return @msgstr.map(&:str).join.empty? if @msgstr.is_a? Array
@msgstr.nil? || @msgstr.str.empty?
end | ruby | def untranslated?
return false if obsolete? || fuzzy?
return @msgstr.map(&:str).join.empty? if @msgstr.is_a? Array
@msgstr.nil? || @msgstr.str.empty?
end | [
"def",
"untranslated?",
"return",
"false",
"if",
"obsolete?",
"||",
"fuzzy?",
"return",
"@msgstr",
".",
"map",
"(",
":str",
")",
".",
"join",
".",
"empty?",
"if",
"@msgstr",
".",
"is_a?",
"Array",
"@msgstr",
".",
"nil?",
"||",
"@msgstr",
".",
"str",
".",
"empty?",
"end"
] | Checks if the entry is untraslated
@return [Boolean] | [
"Checks",
"if",
"the",
"entry",
"is",
"untraslated"
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/entry.rb#L30-L35 |
23,644 | arashm/PoParser | lib/poparser/entry.rb | PoParser.Entry.to_h | def to_h
instance_variables.each_with_object({}) do |label, hash|
object = instance_variable_get(label)
# If it's a plural msgstr
if object.is_a?(Array)
object.each do |entry|
hash[entry.type] = entry.to_s unless entry.nil?
end
else
hash[object.type] = object.to_s unless object.nil?
end
end
end | ruby | def to_h
instance_variables.each_with_object({}) do |label, hash|
object = instance_variable_get(label)
# If it's a plural msgstr
if object.is_a?(Array)
object.each do |entry|
hash[entry.type] = entry.to_s unless entry.nil?
end
else
hash[object.type] = object.to_s unless object.nil?
end
end
end | [
"def",
"to_h",
"instance_variables",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"label",
",",
"hash",
"|",
"object",
"=",
"instance_variable_get",
"(",
"label",
")",
"# If it's a plural msgstr",
"if",
"object",
".",
"is_a?",
"(",
"Array",
")",
"object",
".",
"each",
"do",
"|",
"entry",
"|",
"hash",
"[",
"entry",
".",
"type",
"]",
"=",
"entry",
".",
"to_s",
"unless",
"entry",
".",
"nil?",
"end",
"else",
"hash",
"[",
"object",
".",
"type",
"]",
"=",
"object",
".",
"to_s",
"unless",
"object",
".",
"nil?",
"end",
"end",
"end"
] | Convert entry to a hash key value
@return [Hash] | [
"Convert",
"entry",
"to",
"a",
"hash",
"key",
"value"
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/entry.rb#L82-L94 |
23,645 | arashm/PoParser | lib/poparser/entry.rb | PoParser.Entry.to_s | def to_s
LABELS.each_with_object([]) do |label, arr|
object = instance_variable_get("@#{label}".to_sym)
# If it's a plural msgstr
if object.is_a?(Array)
arr.push(*object.map { |entry| entry.to_s(true) }.compact)
else
arr << object.to_s(true) unless object.nil?
end
end.join
end | ruby | def to_s
LABELS.each_with_object([]) do |label, arr|
object = instance_variable_get("@#{label}".to_sym)
# If it's a plural msgstr
if object.is_a?(Array)
arr.push(*object.map { |entry| entry.to_s(true) }.compact)
else
arr << object.to_s(true) unless object.nil?
end
end.join
end | [
"def",
"to_s",
"LABELS",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"label",
",",
"arr",
"|",
"object",
"=",
"instance_variable_get",
"(",
"\"@#{label}\"",
".",
"to_sym",
")",
"# If it's a plural msgstr",
"if",
"object",
".",
"is_a?",
"(",
"Array",
")",
"arr",
".",
"push",
"(",
"object",
".",
"map",
"{",
"|",
"entry",
"|",
"entry",
".",
"to_s",
"(",
"true",
")",
"}",
".",
"compact",
")",
"else",
"arr",
"<<",
"object",
".",
"to_s",
"(",
"true",
")",
"unless",
"object",
".",
"nil?",
"end",
"end",
".",
"join",
"end"
] | Convert entry to a string
@return [String] | [
"Convert",
"entry",
"to",
"a",
"string"
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/entry.rb#L99-L109 |
23,646 | OnlinetoursGit/qiwi-pay | lib/qiwi-pay/payment_operation.rb | QiwiPay.PaymentOperation.params_hash | def params_hash
%i[opcode].push(*ATTRIBUTES)
.map { |a| [a, send(a).to_s] }
.to_h
.reject { |_k, v| v.nil? || v.empty? }
end | ruby | def params_hash
%i[opcode].push(*ATTRIBUTES)
.map { |a| [a, send(a).to_s] }
.to_h
.reject { |_k, v| v.nil? || v.empty? }
end | [
"def",
"params_hash",
"%i[",
"opcode",
"]",
".",
"push",
"(",
"ATTRIBUTES",
")",
".",
"map",
"{",
"|",
"a",
"|",
"[",
"a",
",",
"send",
"(",
"a",
")",
".",
"to_s",
"]",
"}",
".",
"to_h",
".",
"reject",
"{",
"|",
"_k",
",",
"v",
"|",
"v",
".",
"nil?",
"||",
"v",
".",
"empty?",
"}",
"end"
] | Builds hash with meaningful params only
@return [Hash] | [
"Builds",
"hash",
"with",
"meaningful",
"params",
"only"
] | 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/payment_operation.rb#L88-L93 |
23,647 | OnlinetoursGit/qiwi-pay | lib/qiwi-pay/payment_operation.rb | QiwiPay.PaymentOperation.request_params | def request_params
params_hash.tap do |params|
params[:sign] = Signature.new(params, credentials.secret).sign
end
end | ruby | def request_params
params_hash.tap do |params|
params[:sign] = Signature.new(params, credentials.secret).sign
end
end | [
"def",
"request_params",
"params_hash",
".",
"tap",
"do",
"|",
"params",
"|",
"params",
"[",
":sign",
"]",
"=",
"Signature",
".",
"new",
"(",
"params",
",",
"credentials",
".",
"secret",
")",
".",
"sign",
"end",
"end"
] | Builds and signs request parameters
@return [Hash] | [
"Builds",
"and",
"signs",
"request",
"parameters"
] | 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/payment_operation.rb#L97-L101 |
23,648 | kristianmandrup/troles | lib/trole/storage/base_one.rb | Trole::Storage.BaseOne.set_roles | def set_roles *roles
raise ArgumentError, "A single role strategy can only allow setting a single role, was: #{roles}" if (roles.size > 1)
set_role roles.flat_uniq.first
end | ruby | def set_roles *roles
raise ArgumentError, "A single role strategy can only allow setting a single role, was: #{roles}" if (roles.size > 1)
set_role roles.flat_uniq.first
end | [
"def",
"set_roles",
"*",
"roles",
"raise",
"ArgumentError",
",",
"\"A single role strategy can only allow setting a single role, was: #{roles}\"",
"if",
"(",
"roles",
".",
"size",
">",
"1",
")",
"set_role",
"roles",
".",
"flat_uniq",
".",
"first",
"end"
] | saves the role for the user in the data store | [
"saves",
"the",
"role",
"for",
"the",
"user",
"in",
"the",
"data",
"store"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole/storage/base_one.rb#L36-L39 |
23,649 | kristianmandrup/troles | lib/trole/storage/bit_one.rb | Trole::Storage.BitOne.set_role | def set_role role
num = bitmask.write role
set_ds_field(num == 1 ? false : true) # boolean field in Data store
end | ruby | def set_role role
num = bitmask.write role
set_ds_field(num == 1 ? false : true) # boolean field in Data store
end | [
"def",
"set_role",
"role",
"num",
"=",
"bitmask",
".",
"write",
"role",
"set_ds_field",
"(",
"num",
"==",
"1",
"?",
"false",
":",
"true",
")",
"# boolean field in Data store",
"end"
] | saves the role for the role subject in the data store
@param [Symbol] role name | [
"saves",
"the",
"role",
"for",
"the",
"role",
"subject",
"in",
"the",
"data",
"store"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole/storage/bit_one.rb#L27-L30 |
23,650 | OnlinetoursGit/qiwi-pay | lib/qiwi-pay/confirmation.rb | QiwiPay.Confirmation.to_h | def to_h
{}.tap do |h|
ALLOWED_PARAMS.each { |p| h[p] = send(p) }
h[:txn_status_message] = txn_status_message
h[:txn_type_message] = txn_type_message
end
end | ruby | def to_h
{}.tap do |h|
ALLOWED_PARAMS.each { |p| h[p] = send(p) }
h[:txn_status_message] = txn_status_message
h[:txn_type_message] = txn_type_message
end
end | [
"def",
"to_h",
"{",
"}",
".",
"tap",
"do",
"|",
"h",
"|",
"ALLOWED_PARAMS",
".",
"each",
"{",
"|",
"p",
"|",
"h",
"[",
"p",
"]",
"=",
"send",
"(",
"p",
")",
"}",
"h",
"[",
":txn_status_message",
"]",
"=",
"txn_status_message",
"h",
"[",
":txn_type_message",
"]",
"=",
"txn_type_message",
"end",
"end"
] | Converts confirmation data to hash | [
"Converts",
"confirmation",
"data",
"to",
"hash"
] | 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/confirmation.rb#L128-L134 |
23,651 | OnlinetoursGit/qiwi-pay | lib/qiwi-pay/confirmation.rb | QiwiPay.Confirmation.calculated_sign | def calculated_sign
params = SIGN_PARAMS.each_with_object({}) do |p, h|
h[p] = send(p).tap { |v| v ? v.to_s : nil }
end
Signature.new(params, @secret).sign.upcase
end | ruby | def calculated_sign
params = SIGN_PARAMS.each_with_object({}) do |p, h|
h[p] = send(p).tap { |v| v ? v.to_s : nil }
end
Signature.new(params, @secret).sign.upcase
end | [
"def",
"calculated_sign",
"params",
"=",
"SIGN_PARAMS",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"p",
",",
"h",
"|",
"h",
"[",
"p",
"]",
"=",
"send",
"(",
"p",
")",
".",
"tap",
"{",
"|",
"v",
"|",
"v",
"?",
"v",
".",
"to_s",
":",
"nil",
"}",
"end",
"Signature",
".",
"new",
"(",
"params",
",",
"@secret",
")",
".",
"sign",
".",
"upcase",
"end"
] | Calculates signature for parameters | [
"Calculates",
"signature",
"for",
"parameters"
] | 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/confirmation.rb#L139-L144 |
23,652 | kristianmandrup/troles | lib/trole/api/write.rb | Trole::Api.Write.set_role | def set_role new_role
value = make_valid_role new_role
return false if !value
store.set_role(value)
end | ruby | def set_role new_role
value = make_valid_role new_role
return false if !value
store.set_role(value)
end | [
"def",
"set_role",
"new_role",
"value",
"=",
"make_valid_role",
"new_role",
"return",
"false",
"if",
"!",
"value",
"store",
".",
"set_role",
"(",
"value",
")",
"end"
] | Set the role of the subject to a new role
@param [Symbol] the role to set
@return [true, false, Error] true if ok, false if not valid, Error on some error | [
"Set",
"the",
"role",
"of",
"the",
"subject",
"to",
"a",
"new",
"role"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole/api/write.rb#L12-L16 |
23,653 | jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.to_hex | def to_hex(sep_bytes=false)
hx = @bytes.unpack('H*')[0].upcase
if sep_bytes
sep = ""
(0...hx.size).step(2) do |i|
sep << " " unless i==0
sep << hx[i,2]
end
hx = sep
end
hx
end | ruby | def to_hex(sep_bytes=false)
hx = @bytes.unpack('H*')[0].upcase
if sep_bytes
sep = ""
(0...hx.size).step(2) do |i|
sep << " " unless i==0
sep << hx[i,2]
end
hx = sep
end
hx
end | [
"def",
"to_hex",
"(",
"sep_bytes",
"=",
"false",
")",
"hx",
"=",
"@bytes",
".",
"unpack",
"(",
"'H*'",
")",
"[",
"0",
"]",
".",
"upcase",
"if",
"sep_bytes",
"sep",
"=",
"\"\"",
"(",
"0",
"...",
"hx",
".",
"size",
")",
".",
"step",
"(",
"2",
")",
"do",
"|",
"i",
"|",
"sep",
"<<",
"\" \"",
"unless",
"i",
"==",
"0",
"sep",
"<<",
"hx",
"[",
"i",
",",
"2",
"]",
"end",
"hx",
"=",
"sep",
"end",
"hx",
"end"
] | return an hex representation of a byte string | [
"return",
"an",
"hex",
"representation",
"of",
"a",
"byte",
"string"
] | e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L154-L165 |
23,654 | jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.reverse_byte_nibbles! | def reverse_byte_nibbles!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
@bytes.each_byte do |b|
w << ((b >> 4)|((b&0xF)<<4))
end
@bytes = w
__setobj__ @bytes
self
end | ruby | def reverse_byte_nibbles!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
@bytes.each_byte do |b|
w << ((b >> 4)|((b&0xF)<<4))
end
@bytes = w
__setobj__ @bytes
self
end | [
"def",
"reverse_byte_nibbles!",
"w",
"=",
"\"\"",
"w",
".",
"force_encoding",
"(",
"\"BINARY\"",
")",
"if",
"w",
".",
"respond_to?",
"(",
":force_encoding",
")",
"@bytes",
".",
"each_byte",
"do",
"|",
"b",
"|",
"w",
"<<",
"(",
"(",
"b",
">>",
"4",
")",
"|",
"(",
"(",
"b",
"0xF",
")",
"<<",
"4",
")",
")",
"end",
"@bytes",
"=",
"w",
"__setobj__",
"@bytes",
"self",
"end"
] | Reverse the order of the nibbles in each byte. | [
"Reverse",
"the",
"order",
"of",
"the",
"nibbles",
"in",
"each",
"byte",
"."
] | e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L185-L194 |
23,655 | jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.reverse_byte_pairs! | def reverse_byte_pairs!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
([email protected]).step(2) do |i|
w << @bytes[i+1]
w << @bytes[i]
end
@bytes = w
__setobj__ @bytes
self
end | ruby | def reverse_byte_pairs!
w = ""
w.force_encoding("BINARY") if w.respond_to?(:force_encoding)
([email protected]).step(2) do |i|
w << @bytes[i+1]
w << @bytes[i]
end
@bytes = w
__setobj__ @bytes
self
end | [
"def",
"reverse_byte_pairs!",
"w",
"=",
"\"\"",
"w",
".",
"force_encoding",
"(",
"\"BINARY\"",
")",
"if",
"w",
".",
"respond_to?",
"(",
":force_encoding",
")",
"(",
"0",
"...",
"@bytes",
".",
"size",
")",
".",
"step",
"(",
"2",
")",
"do",
"|",
"i",
"|",
"w",
"<<",
"@bytes",
"[",
"i",
"+",
"1",
"]",
"w",
"<<",
"@bytes",
"[",
"i",
"]",
"end",
"@bytes",
"=",
"w",
"__setobj__",
"@bytes",
"self",
"end"
] | reverse the order of bytes in 16-bit words | [
"reverse",
"the",
"order",
"of",
"bytes",
"in",
"16",
"-",
"bit",
"words"
] | e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L200-L210 |
23,656 | jgoizueta/float-formats | lib/float-formats/bytes.rb | Flt.Bytes.to_bitfields | def to_bitfields(lens,byte_endianness=:little_endian, bits_little_endian=false)
fields = []
i = to_i(byte_endianness,bits_little_endian)
for len in lens
mask = (1<<len)-1
fields << (i&mask)
i >>= len
end
fields
end | ruby | def to_bitfields(lens,byte_endianness=:little_endian, bits_little_endian=false)
fields = []
i = to_i(byte_endianness,bits_little_endian)
for len in lens
mask = (1<<len)-1
fields << (i&mask)
i >>= len
end
fields
end | [
"def",
"to_bitfields",
"(",
"lens",
",",
"byte_endianness",
"=",
":little_endian",
",",
"bits_little_endian",
"=",
"false",
")",
"fields",
"=",
"[",
"]",
"i",
"=",
"to_i",
"(",
"byte_endianness",
",",
"bits_little_endian",
")",
"for",
"len",
"in",
"lens",
"mask",
"=",
"(",
"1",
"<<",
"len",
")",
"-",
"1",
"fields",
"<<",
"(",
"i",
"mask",
")",
"i",
">>=",
"len",
"end",
"fields",
"end"
] | convert a byte string to separate fixed-width bit-fields as integers | [
"convert",
"a",
"byte",
"string",
"to",
"separate",
"fixed",
"-",
"width",
"bit",
"-",
"fields",
"as",
"integers"
] | e73790e0439141b34e16caa779421fe1d481e0a2 | https://github.com/jgoizueta/float-formats/blob/e73790e0439141b34e16caa779421fe1d481e0a2/lib/float-formats/bytes.rb#L280-L289 |
23,657 | dark-panda/activerecord-postgresql-cursors | lib/activerecord-postgresql-cursors.rb | ActiveRecord.PostgreSQLCursor.each | def each
@model.transaction do
begin
declare_cursor
if @join_dependency
rows = Array.new
last_id = nil
while row = fetch_forward
instantiated_row = @join_dependency.instantiate([row], @join_dependency.aliases).first
current_id = instantiated_row[@join_dependency.join_root.primary_key]
last_id ||= current_id
if last_id == current_id
rows << row
last_id = current_id
else
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
rows = [ row ]
end
last_id = current_id
end
if !rows.empty?
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
end
else
while row = fetch_forward
yield @model.instantiate(row)
end
end
ensure
close_cursor
end
end
nil
end | ruby | def each
@model.transaction do
begin
declare_cursor
if @join_dependency
rows = Array.new
last_id = nil
while row = fetch_forward
instantiated_row = @join_dependency.instantiate([row], @join_dependency.aliases).first
current_id = instantiated_row[@join_dependency.join_root.primary_key]
last_id ||= current_id
if last_id == current_id
rows << row
last_id = current_id
else
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
rows = [ row ]
end
last_id = current_id
end
if !rows.empty?
yield @join_dependency.instantiate(rows, @join_dependency.aliases).first
end
else
while row = fetch_forward
yield @model.instantiate(row)
end
end
ensure
close_cursor
end
end
nil
end | [
"def",
"each",
"@model",
".",
"transaction",
"do",
"begin",
"declare_cursor",
"if",
"@join_dependency",
"rows",
"=",
"Array",
".",
"new",
"last_id",
"=",
"nil",
"while",
"row",
"=",
"fetch_forward",
"instantiated_row",
"=",
"@join_dependency",
".",
"instantiate",
"(",
"[",
"row",
"]",
",",
"@join_dependency",
".",
"aliases",
")",
".",
"first",
"current_id",
"=",
"instantiated_row",
"[",
"@join_dependency",
".",
"join_root",
".",
"primary_key",
"]",
"last_id",
"||=",
"current_id",
"if",
"last_id",
"==",
"current_id",
"rows",
"<<",
"row",
"last_id",
"=",
"current_id",
"else",
"yield",
"@join_dependency",
".",
"instantiate",
"(",
"rows",
",",
"@join_dependency",
".",
"aliases",
")",
".",
"first",
"rows",
"=",
"[",
"row",
"]",
"end",
"last_id",
"=",
"current_id",
"end",
"if",
"!",
"rows",
".",
"empty?",
"yield",
"@join_dependency",
".",
"instantiate",
"(",
"rows",
",",
"@join_dependency",
".",
"aliases",
")",
".",
"first",
"end",
"else",
"while",
"row",
"=",
"fetch_forward",
"yield",
"@model",
".",
"instantiate",
"(",
"row",
")",
"end",
"end",
"ensure",
"close_cursor",
"end",
"end",
"nil",
"end"
] | Calls block once for each record in the cursor, passing that
record as a parameter. | [
"Calls",
"block",
"once",
"for",
"each",
"record",
"in",
"the",
"cursor",
"passing",
"that",
"record",
"as",
"a",
"parameter",
"."
] | bb727b30a853402a72ddc9c49cdd529c9b17aee2 | https://github.com/dark-panda/activerecord-postgresql-cursors/blob/bb727b30a853402a72ddc9c49cdd529c9b17aee2/lib/activerecord-postgresql-cursors.rb#L35-L71 |
23,658 | OnlinetoursGit/qiwi-pay | lib/qiwi-pay/signature.rb | QiwiPay.Signature.map_sorted | def map_sorted(hash)
hash.keys
.sort_by(&:to_sym)
.map { |k| yield k, hash[k] }
end | ruby | def map_sorted(hash)
hash.keys
.sort_by(&:to_sym)
.map { |k| yield k, hash[k] }
end | [
"def",
"map_sorted",
"(",
"hash",
")",
"hash",
".",
"keys",
".",
"sort_by",
"(",
":to_sym",
")",
".",
"map",
"{",
"|",
"k",
"|",
"yield",
"k",
",",
"hash",
"[",
"k",
"]",
"}",
"end"
] | Maps hash yielding key-value pairs ordered by key | [
"Maps",
"hash",
"yielding",
"key",
"-",
"value",
"pairs",
"ordered",
"by",
"key"
] | 142116667248a29de523bfc0a0fd7c0224776401 | https://github.com/OnlinetoursGit/qiwi-pay/blob/142116667248a29de523bfc0a0fd7c0224776401/lib/qiwi-pay/signature.rb#L35-L39 |
23,659 | arashm/PoParser | lib/poparser/header.rb | PoParser.Header.merge_to_previous_string | def merge_to_previous_string(array)
array.each_with_index do |key, index|
next unless key.length == 1
array[index - 1][1] += key[0]
array.delete_at(index)
end
end | ruby | def merge_to_previous_string(array)
array.each_with_index do |key, index|
next unless key.length == 1
array[index - 1][1] += key[0]
array.delete_at(index)
end
end | [
"def",
"merge_to_previous_string",
"(",
"array",
")",
"array",
".",
"each_with_index",
"do",
"|",
"key",
",",
"index",
"|",
"next",
"unless",
"key",
".",
"length",
"==",
"1",
"array",
"[",
"index",
"-",
"1",
"]",
"[",
"1",
"]",
"+=",
"key",
"[",
"0",
"]",
"array",
".",
"delete_at",
"(",
"index",
")",
"end",
"end"
] | Sometimes long lines are wrapped into new lines, this function
join them back
[['a', 'b'], ['c']] #=> [['a', 'bc']] | [
"Sometimes",
"long",
"lines",
"are",
"wrapped",
"into",
"new",
"lines",
"this",
"function",
"join",
"them",
"back"
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/header.rb#L111-L118 |
23,660 | greysteil/spot-gps | lib/spot-gps/api_service.rb | SPOT.ApiService.get | def get(path:, params: {})
params ||= {}
if feed_password && !feed_password.empty?
params = params.merge(feedPassword: feed_password)
end
response = make_request(:get, path, params)
SPOT::ApiResponse.new(response)
end | ruby | def get(path:, params: {})
params ||= {}
if feed_password && !feed_password.empty?
params = params.merge(feedPassword: feed_password)
end
response = make_request(:get, path, params)
SPOT::ApiResponse.new(response)
end | [
"def",
"get",
"(",
"path",
":",
",",
"params",
":",
"{",
"}",
")",
"params",
"||=",
"{",
"}",
"if",
"feed_password",
"&&",
"!",
"feed_password",
".",
"empty?",
"params",
"=",
"params",
".",
"merge",
"(",
"feedPassword",
":",
"feed_password",
")",
"end",
"response",
"=",
"make_request",
"(",
":get",
",",
"path",
",",
"params",
")",
"SPOT",
"::",
"ApiResponse",
".",
"new",
"(",
"response",
")",
"end"
] | Make a GET request to the SPOT API | [
"Make",
"a",
"GET",
"request",
"to",
"the",
"SPOT",
"API"
] | 808367da20dd9976f06cf281324566e25d6a3b35 | https://github.com/greysteil/spot-gps/blob/808367da20dd9976f06cf281324566e25d6a3b35/lib/spot-gps/api_service.rb#L21-L31 |
23,661 | kristianmandrup/troles | lib/troles/common/config.rb | Troles::Common.Config.auto_config? | def auto_config? name
return auto_config[name] if !auto_config[name].nil?
Troles::Config.auto_config?(name)
end | ruby | def auto_config? name
return auto_config[name] if !auto_config[name].nil?
Troles::Config.auto_config?(name)
end | [
"def",
"auto_config?",
"name",
"return",
"auto_config",
"[",
"name",
"]",
"if",
"!",
"auto_config",
"[",
"name",
"]",
".",
"nil?",
"Troles",
"::",
"Config",
".",
"auto_config?",
"(",
"name",
")",
"end"
] | is a certain type of auto configuration enabled? | [
"is",
"a",
"certain",
"type",
"of",
"auto",
"configuration",
"enabled?"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/config.rb#L53-L56 |
23,662 | kristianmandrup/troles | lib/troles/common/config.rb | Troles::Common.Config.main_field= | def main_field= field_name
name = field_name.to_s.alpha_numeric.to_sym
raise ArgumentException, "Not a valid field name: #{field_name}" if !valid_field_name?(name)
@main_field ||= name
end | ruby | def main_field= field_name
name = field_name.to_s.alpha_numeric.to_sym
raise ArgumentException, "Not a valid field name: #{field_name}" if !valid_field_name?(name)
@main_field ||= name
end | [
"def",
"main_field",
"=",
"field_name",
"name",
"=",
"field_name",
".",
"to_s",
".",
"alpha_numeric",
".",
"to_sym",
"raise",
"ArgumentException",
",",
"\"Not a valid field name: #{field_name}\"",
"if",
"!",
"valid_field_name?",
"(",
"name",
")",
"@main_field",
"||=",
"name",
"end"
] | Set the main field of the behavior | [
"Set",
"the",
"main",
"field",
"of",
"the",
"behavior"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/common/config.rb#L67-L71 |
23,663 | kristianmandrup/troles | lib/troles/adapters/mongoid/config.rb | Troles::Mongoid.Config.configure_relation | def configure_relation
case strategy
when :ref_many
has_many_for subject_class, :role, :through => join_key
belongs_to_for join_model, subject_class
belongs_to_for join_model, object_model
has_many_for role, subject_class, :through => join_key
when :embed_many
embeds_many subject_class, object_model
end
end | ruby | def configure_relation
case strategy
when :ref_many
has_many_for subject_class, :role, :through => join_key
belongs_to_for join_model, subject_class
belongs_to_for join_model, object_model
has_many_for role, subject_class, :through => join_key
when :embed_many
embeds_many subject_class, object_model
end
end | [
"def",
"configure_relation",
"case",
"strategy",
"when",
":ref_many",
"has_many_for",
"subject_class",
",",
":role",
",",
":through",
"=>",
"join_key",
"belongs_to_for",
"join_model",
",",
"subject_class",
"belongs_to_for",
"join_model",
",",
"object_model",
"has_many_for",
"role",
",",
"subject_class",
",",
":through",
"=>",
"join_key",
"when",
":embed_many",
"embeds_many",
"subject_class",
",",
"object_model",
"end",
"end"
] | more likely, strategy should be part of configuration options directly when Config object is created! | [
"more",
"likely",
"strategy",
"should",
"be",
"part",
"of",
"configuration",
"options",
"directly",
"when",
"Config",
"object",
"is",
"created!"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/troles/adapters/mongoid/config.rb#L9-L22 |
23,664 | kristianmandrup/troles | lib/trole_groups/api/write.rb | TroleGroups::Api.Write.set_rolegroups | def set_rolegroups *rolegroups
rolegroups_to_set = make_valid_rolegroups(*rolegroups).flat_uniq
return false if !rolegroups_to_set || rolegroups_to_set.empty?
group_store.set_rolegroups(rolegroups_to_set)
end | ruby | def set_rolegroups *rolegroups
rolegroups_to_set = make_valid_rolegroups(*rolegroups).flat_uniq
return false if !rolegroups_to_set || rolegroups_to_set.empty?
group_store.set_rolegroups(rolegroups_to_set)
end | [
"def",
"set_rolegroups",
"*",
"rolegroups",
"rolegroups_to_set",
"=",
"make_valid_rolegroups",
"(",
"rolegroups",
")",
".",
"flat_uniq",
"return",
"false",
"if",
"!",
"rolegroups_to_set",
"||",
"rolegroups_to_set",
".",
"empty?",
"group_store",
".",
"set_rolegroups",
"(",
"rolegroups_to_set",
")",
"end"
] | Sets new rolegroups for the subject
@param [Array<Symbol>] list of rolegroup names
@return [true, false, Error] true if set ok, false if any rolegroups were invalid, Error on some error | [
"Sets",
"new",
"rolegroups",
"for",
"the",
"subject"
] | c2d1458c705bcafadccc69bf43856e5be59fb2a9 | https://github.com/kristianmandrup/troles/blob/c2d1458c705bcafadccc69bf43856e5be59fb2a9/lib/trole_groups/api/write.rb#L35-L39 |
23,665 | arashm/PoParser | lib/poparser/po.rb | PoParser.Po.add | def add(entry)
return import_hash(entry) if entry.is_a?(Hash)
return import_array(entry) if entry.is_a?(Array)
raise ArgumentError, 'Must be a hash or an array of hashes'
end | ruby | def add(entry)
return import_hash(entry) if entry.is_a?(Hash)
return import_array(entry) if entry.is_a?(Array)
raise ArgumentError, 'Must be a hash or an array of hashes'
end | [
"def",
"add",
"(",
"entry",
")",
"return",
"import_hash",
"(",
"entry",
")",
"if",
"entry",
".",
"is_a?",
"(",
"Hash",
")",
"return",
"import_array",
"(",
"entry",
")",
"if",
"entry",
".",
"is_a?",
"(",
"Array",
")",
"raise",
"ArgumentError",
",",
"'Must be a hash or an array of hashes'",
"end"
] | add new entries to po file
@example
entry = {
translator_comment: 'comment',
reference: 'reference comment',
flag: 'fuzzy',
msgid: 'translatable string',
msgstr: 'translation'
}
add(entry)
@param entry [Hash, Array] a hash of entry contents or an array of hashes
@return [Po] | [
"add",
"new",
"entries",
"to",
"po",
"file"
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L29-L34 |
23,666 | arashm/PoParser | lib/poparser/po.rb | PoParser.Po.delete | def delete(entry)
raise(ArgumentError, 'Must be an Entry') unless entry.is_a?(PoParser::Entry)
@entries.delete(entry)
end | ruby | def delete(entry)
raise(ArgumentError, 'Must be an Entry') unless entry.is_a?(PoParser::Entry)
@entries.delete(entry)
end | [
"def",
"delete",
"(",
"entry",
")",
"raise",
"(",
"ArgumentError",
",",
"'Must be an Entry'",
")",
"unless",
"entry",
".",
"is_a?",
"(",
"PoParser",
"::",
"Entry",
")",
"@entries",
".",
"delete",
"(",
"entry",
")",
"end"
] | Delete entry from po file
@example
delete(entry)
@param entry [Entry] to be deleted
@return [Entry] | [
"Delete",
"entry",
"from",
"po",
"file"
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L45-L49 |
23,667 | arashm/PoParser | lib/poparser/po.rb | PoParser.Po.stats | def stats
untranslated_size = untranslated.size
translated_size = translated.size
fuzzy_size = fuzzy.size
{
translated: percentage(translated_size),
untranslated: percentage(untranslated_size),
fuzzy: percentage(fuzzy_size),
}
end | ruby | def stats
untranslated_size = untranslated.size
translated_size = translated.size
fuzzy_size = fuzzy.size
{
translated: percentage(translated_size),
untranslated: percentage(untranslated_size),
fuzzy: percentage(fuzzy_size),
}
end | [
"def",
"stats",
"untranslated_size",
"=",
"untranslated",
".",
"size",
"translated_size",
"=",
"translated",
".",
"size",
"fuzzy_size",
"=",
"fuzzy",
".",
"size",
"{",
"translated",
":",
"percentage",
"(",
"translated_size",
")",
",",
"untranslated",
":",
"percentage",
"(",
"untranslated_size",
")",
",",
"fuzzy",
":",
"percentage",
"(",
"fuzzy_size",
")",
",",
"}",
"end"
] | Shows statistics and status of the provided file in percentage.
@return [Hash] a hash of translated, untranslated and fuzzy percentages | [
"Shows",
"statistics",
"and",
"status",
"of",
"the",
"provided",
"file",
"in",
"percentage",
"."
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L116-L126 |
23,668 | arashm/PoParser | lib/poparser/po.rb | PoParser.Po.save_file | def save_file
raise ArgumentError, 'Need a Path to save the file' if @path.nil?
File.open(@path, 'w') { |file| file.write(to_s) }
end | ruby | def save_file
raise ArgumentError, 'Need a Path to save the file' if @path.nil?
File.open(@path, 'w') { |file| file.write(to_s) }
end | [
"def",
"save_file",
"raise",
"ArgumentError",
",",
"'Need a Path to save the file'",
"if",
"@path",
".",
"nil?",
"File",
".",
"open",
"(",
"@path",
",",
"'w'",
")",
"{",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"to_s",
")",
"}",
"end"
] | Saves the file to the provided path | [
"Saves",
"the",
"file",
"to",
"the",
"provided",
"path"
] | e84afdabbd15cc2d5e1d38101d44f8a49992b9f9 | https://github.com/arashm/PoParser/blob/e84afdabbd15cc2d5e1d38101d44f8a49992b9f9/lib/poparser/po.rb#L148-L152 |
23,669 | etagwerker/dinero_mail_ipn | lib/dinero_mail_ipn/notification_parser.rb | DineroMailIpn.NotificationParser.xsd_file | def xsd_file(filename)
xsd_file_location = File.join(DineroMailIpn.resources_path, "/validation/xsd/#{filename}")
xsd_file = File.read(xsd_file_location)
xsd_file
end | ruby | def xsd_file(filename)
xsd_file_location = File.join(DineroMailIpn.resources_path, "/validation/xsd/#{filename}")
xsd_file = File.read(xsd_file_location)
xsd_file
end | [
"def",
"xsd_file",
"(",
"filename",
")",
"xsd_file_location",
"=",
"File",
".",
"join",
"(",
"DineroMailIpn",
".",
"resources_path",
",",
"\"/validation/xsd/#{filename}\"",
")",
"xsd_file",
"=",
"File",
".",
"read",
"(",
"xsd_file_location",
")",
"xsd_file",
"end"
] | Locates an XSD file.
@param filename [String] the XSD filename | [
"Locates",
"an",
"XSD",
"file",
"."
] | 50d6932e5db99e34b8e521cc494e19599c009e18 | https://github.com/etagwerker/dinero_mail_ipn/blob/50d6932e5db99e34b8e521cc494e19599c009e18/lib/dinero_mail_ipn/notification_parser.rb#L53-L57 |
23,670 | rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.execute | def execute(cmd, options = {})
options = {
:directory => nil,
:outstream => nil,
:raise_on_failure => true,
:set_env_vars => nil,
:clear_env_vars => nil,
:logger => default_logger,
:timeout => nil,
:keep_alive_interval => nil,
:keep_alive_timeout => nil
}.merge(options)
outstream = options[:outstream]
logger = options[:logger]
if keep_alive_interval = options[:keep_alive_interval]
keep_alive_wake_time = ::Time.now + keep_alive_interval
else
keep_alive_wake_time = nil
end
if keep_alive_timeout = options[:keep_alive_timeout]
unless keep_alive_interval
raise ::ArgumentError,
':keep_alive_interval is required when using :keep_alive_timeout'
end
keep_alive_stop_time = ::Time.now + keep_alive_timeout
else
keep_alive_stop_time = nil
end
# build initial popener.
exitstatus = nil
popener = lambda do |output|
output.sync = true
loop do
# note stdout remains selectable after process dies.
if (::IO.select([output], nil, nil, 0.1) rescue nil)
if data = output.gets
if outstream
outstream << data
else
data = data.strip
unless data.empty?
logger.info(data)
# reset keep alive timer whenever we have normal output.
if keep_alive_wake_time
keep_alive_wake_time = ::Time.now + keep_alive_interval
end
end
end
else
break
end
elsif keep_alive_wake_time
now = ::Time.now
if keep_alive_stop_time && now >= keep_alive_stop_time
keep_alive_wake_time = nil
elsif now >= keep_alive_wake_time
# keep-alives go to logger, not the outstream, if any.
logger.info('.')
keep_alive_wake_time = now + keep_alive_interval
end
now = nil
end
end
end
# timeout optionally wraps popener. the timeout must happen inside of the
# IO.popen block or else it has no good effect.
if timeout = options[:timeout]
popener = lambda do |p|
lambda do |o|
::Timeout.timeout(timeout) { p.call(o) }
end
end.call(popener)
end
# build initial executioner in terms of popener.
executioner = lambda do
logger.info("+ #{cmd}")
error_msg = nil
::IO.popen("#{cmd} 2>&1", 'r') do |output|
begin
popener.call(output)
rescue ::EOFError
# done
rescue ::Timeout::Error
# kill still-running process or else popen's ensure will hang.
::Process.kill('KILL', output.pid)
# intentionally not reading last data as that could still block
# due to a child of created process inheriting stdout.
error_msg = "Execution timed out after #{options[:timeout]} seconds."
end
end
# note that a killed process may exit 0 under Windows.
exitstatus = $?.exitstatus
if 0 == exitstatus && error_msg
exitstatus = 1
end
if (exitstatus != 0 && options[:raise_on_failure])
error_msg ||= "Execution failed with exitstatus #{exitstatus}"
raise ShellError, error_msg
end
end
# configure executioner (by options) and then invoke executioner.
configure_executioner(executioner, options).call
return exitstatus
end | ruby | def execute(cmd, options = {})
options = {
:directory => nil,
:outstream => nil,
:raise_on_failure => true,
:set_env_vars => nil,
:clear_env_vars => nil,
:logger => default_logger,
:timeout => nil,
:keep_alive_interval => nil,
:keep_alive_timeout => nil
}.merge(options)
outstream = options[:outstream]
logger = options[:logger]
if keep_alive_interval = options[:keep_alive_interval]
keep_alive_wake_time = ::Time.now + keep_alive_interval
else
keep_alive_wake_time = nil
end
if keep_alive_timeout = options[:keep_alive_timeout]
unless keep_alive_interval
raise ::ArgumentError,
':keep_alive_interval is required when using :keep_alive_timeout'
end
keep_alive_stop_time = ::Time.now + keep_alive_timeout
else
keep_alive_stop_time = nil
end
# build initial popener.
exitstatus = nil
popener = lambda do |output|
output.sync = true
loop do
# note stdout remains selectable after process dies.
if (::IO.select([output], nil, nil, 0.1) rescue nil)
if data = output.gets
if outstream
outstream << data
else
data = data.strip
unless data.empty?
logger.info(data)
# reset keep alive timer whenever we have normal output.
if keep_alive_wake_time
keep_alive_wake_time = ::Time.now + keep_alive_interval
end
end
end
else
break
end
elsif keep_alive_wake_time
now = ::Time.now
if keep_alive_stop_time && now >= keep_alive_stop_time
keep_alive_wake_time = nil
elsif now >= keep_alive_wake_time
# keep-alives go to logger, not the outstream, if any.
logger.info('.')
keep_alive_wake_time = now + keep_alive_interval
end
now = nil
end
end
end
# timeout optionally wraps popener. the timeout must happen inside of the
# IO.popen block or else it has no good effect.
if timeout = options[:timeout]
popener = lambda do |p|
lambda do |o|
::Timeout.timeout(timeout) { p.call(o) }
end
end.call(popener)
end
# build initial executioner in terms of popener.
executioner = lambda do
logger.info("+ #{cmd}")
error_msg = nil
::IO.popen("#{cmd} 2>&1", 'r') do |output|
begin
popener.call(output)
rescue ::EOFError
# done
rescue ::Timeout::Error
# kill still-running process or else popen's ensure will hang.
::Process.kill('KILL', output.pid)
# intentionally not reading last data as that could still block
# due to a child of created process inheriting stdout.
error_msg = "Execution timed out after #{options[:timeout]} seconds."
end
end
# note that a killed process may exit 0 under Windows.
exitstatus = $?.exitstatus
if 0 == exitstatus && error_msg
exitstatus = 1
end
if (exitstatus != 0 && options[:raise_on_failure])
error_msg ||= "Execution failed with exitstatus #{exitstatus}"
raise ShellError, error_msg
end
end
# configure executioner (by options) and then invoke executioner.
configure_executioner(executioner, options).call
return exitstatus
end | [
"def",
"execute",
"(",
"cmd",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":directory",
"=>",
"nil",
",",
":outstream",
"=>",
"nil",
",",
":raise_on_failure",
"=>",
"true",
",",
":set_env_vars",
"=>",
"nil",
",",
":clear_env_vars",
"=>",
"nil",
",",
":logger",
"=>",
"default_logger",
",",
":timeout",
"=>",
"nil",
",",
":keep_alive_interval",
"=>",
"nil",
",",
":keep_alive_timeout",
"=>",
"nil",
"}",
".",
"merge",
"(",
"options",
")",
"outstream",
"=",
"options",
"[",
":outstream",
"]",
"logger",
"=",
"options",
"[",
":logger",
"]",
"if",
"keep_alive_interval",
"=",
"options",
"[",
":keep_alive_interval",
"]",
"keep_alive_wake_time",
"=",
"::",
"Time",
".",
"now",
"+",
"keep_alive_interval",
"else",
"keep_alive_wake_time",
"=",
"nil",
"end",
"if",
"keep_alive_timeout",
"=",
"options",
"[",
":keep_alive_timeout",
"]",
"unless",
"keep_alive_interval",
"raise",
"::",
"ArgumentError",
",",
"':keep_alive_interval is required when using :keep_alive_timeout'",
"end",
"keep_alive_stop_time",
"=",
"::",
"Time",
".",
"now",
"+",
"keep_alive_timeout",
"else",
"keep_alive_stop_time",
"=",
"nil",
"end",
"# build initial popener.",
"exitstatus",
"=",
"nil",
"popener",
"=",
"lambda",
"do",
"|",
"output",
"|",
"output",
".",
"sync",
"=",
"true",
"loop",
"do",
"# note stdout remains selectable after process dies.",
"if",
"(",
"::",
"IO",
".",
"select",
"(",
"[",
"output",
"]",
",",
"nil",
",",
"nil",
",",
"0.1",
")",
"rescue",
"nil",
")",
"if",
"data",
"=",
"output",
".",
"gets",
"if",
"outstream",
"outstream",
"<<",
"data",
"else",
"data",
"=",
"data",
".",
"strip",
"unless",
"data",
".",
"empty?",
"logger",
".",
"info",
"(",
"data",
")",
"# reset keep alive timer whenever we have normal output.",
"if",
"keep_alive_wake_time",
"keep_alive_wake_time",
"=",
"::",
"Time",
".",
"now",
"+",
"keep_alive_interval",
"end",
"end",
"end",
"else",
"break",
"end",
"elsif",
"keep_alive_wake_time",
"now",
"=",
"::",
"Time",
".",
"now",
"if",
"keep_alive_stop_time",
"&&",
"now",
">=",
"keep_alive_stop_time",
"keep_alive_wake_time",
"=",
"nil",
"elsif",
"now",
">=",
"keep_alive_wake_time",
"# keep-alives go to logger, not the outstream, if any.",
"logger",
".",
"info",
"(",
"'.'",
")",
"keep_alive_wake_time",
"=",
"now",
"+",
"keep_alive_interval",
"end",
"now",
"=",
"nil",
"end",
"end",
"end",
"# timeout optionally wraps popener. the timeout must happen inside of the",
"# IO.popen block or else it has no good effect.",
"if",
"timeout",
"=",
"options",
"[",
":timeout",
"]",
"popener",
"=",
"lambda",
"do",
"|",
"p",
"|",
"lambda",
"do",
"|",
"o",
"|",
"::",
"Timeout",
".",
"timeout",
"(",
"timeout",
")",
"{",
"p",
".",
"call",
"(",
"o",
")",
"}",
"end",
"end",
".",
"call",
"(",
"popener",
")",
"end",
"# build initial executioner in terms of popener.",
"executioner",
"=",
"lambda",
"do",
"logger",
".",
"info",
"(",
"\"+ #{cmd}\"",
")",
"error_msg",
"=",
"nil",
"::",
"IO",
".",
"popen",
"(",
"\"#{cmd} 2>&1\"",
",",
"'r'",
")",
"do",
"|",
"output",
"|",
"begin",
"popener",
".",
"call",
"(",
"output",
")",
"rescue",
"::",
"EOFError",
"# done",
"rescue",
"::",
"Timeout",
"::",
"Error",
"# kill still-running process or else popen's ensure will hang.",
"::",
"Process",
".",
"kill",
"(",
"'KILL'",
",",
"output",
".",
"pid",
")",
"# intentionally not reading last data as that could still block",
"# due to a child of created process inheriting stdout.",
"error_msg",
"=",
"\"Execution timed out after #{options[:timeout]} seconds.\"",
"end",
"end",
"# note that a killed process may exit 0 under Windows.",
"exitstatus",
"=",
"$?",
".",
"exitstatus",
"if",
"0",
"==",
"exitstatus",
"&&",
"error_msg",
"exitstatus",
"=",
"1",
"end",
"if",
"(",
"exitstatus",
"!=",
"0",
"&&",
"options",
"[",
":raise_on_failure",
"]",
")",
"error_msg",
"||=",
"\"Execution failed with exitstatus #{exitstatus}\"",
"raise",
"ShellError",
",",
"error_msg",
"end",
"end",
"# configure executioner (by options) and then invoke executioner.",
"configure_executioner",
"(",
"executioner",
",",
"options",
")",
".",
"call",
"return",
"exitstatus",
"end"
] | Implements execute interface. | [
"Implements",
"execute",
"interface",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L44-L157 |
23,671 | rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.output_for | def output_for(cmd, options = {})
output = StringIO.new
execute(cmd, options.merge(:outstream => output))
output.string
end | ruby | def output_for(cmd, options = {})
output = StringIO.new
execute(cmd, options.merge(:outstream => output))
output.string
end | [
"def",
"output_for",
"(",
"cmd",
",",
"options",
"=",
"{",
"}",
")",
"output",
"=",
"StringIO",
".",
"new",
"execute",
"(",
"cmd",
",",
"options",
".",
"merge",
"(",
":outstream",
"=>",
"output",
")",
")",
"output",
".",
"string",
"end"
] | Implements output_for interface. | [
"Implements",
"output_for",
"interface",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L160-L164 |
23,672 | rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.configure_executioner | def configure_executioner(executioner, options)
# set specific environment variables, if requested.
sev = options[:set_env_vars]
if (sev && !sev.empty?)
executioner = lambda do |e|
lambda { set_env_vars(sev) { e.call } }
end.call(executioner)
end
# clear specific environment variables, if requested.
cev = options[:clear_env_vars]
if (cev && !cev.empty?)
executioner = lambda do |e|
lambda { clear_env_vars(cev) { e.call } }
end.call(executioner)
end
# working directory.
if directory = options[:directory]
executioner = lambda do |e, d|
lambda { ::Dir.chdir(d) { e.call } }
end.call(executioner, directory)
end
executioner
end | ruby | def configure_executioner(executioner, options)
# set specific environment variables, if requested.
sev = options[:set_env_vars]
if (sev && !sev.empty?)
executioner = lambda do |e|
lambda { set_env_vars(sev) { e.call } }
end.call(executioner)
end
# clear specific environment variables, if requested.
cev = options[:clear_env_vars]
if (cev && !cev.empty?)
executioner = lambda do |e|
lambda { clear_env_vars(cev) { e.call } }
end.call(executioner)
end
# working directory.
if directory = options[:directory]
executioner = lambda do |e, d|
lambda { ::Dir.chdir(d) { e.call } }
end.call(executioner, directory)
end
executioner
end | [
"def",
"configure_executioner",
"(",
"executioner",
",",
"options",
")",
"# set specific environment variables, if requested.",
"sev",
"=",
"options",
"[",
":set_env_vars",
"]",
"if",
"(",
"sev",
"&&",
"!",
"sev",
".",
"empty?",
")",
"executioner",
"=",
"lambda",
"do",
"|",
"e",
"|",
"lambda",
"{",
"set_env_vars",
"(",
"sev",
")",
"{",
"e",
".",
"call",
"}",
"}",
"end",
".",
"call",
"(",
"executioner",
")",
"end",
"# clear specific environment variables, if requested.",
"cev",
"=",
"options",
"[",
":clear_env_vars",
"]",
"if",
"(",
"cev",
"&&",
"!",
"cev",
".",
"empty?",
")",
"executioner",
"=",
"lambda",
"do",
"|",
"e",
"|",
"lambda",
"{",
"clear_env_vars",
"(",
"cev",
")",
"{",
"e",
".",
"call",
"}",
"}",
"end",
".",
"call",
"(",
"executioner",
")",
"end",
"# working directory.",
"if",
"directory",
"=",
"options",
"[",
":directory",
"]",
"executioner",
"=",
"lambda",
"do",
"|",
"e",
",",
"d",
"|",
"lambda",
"{",
"::",
"Dir",
".",
"chdir",
"(",
"d",
")",
"{",
"e",
".",
"call",
"}",
"}",
"end",
".",
"call",
"(",
"executioner",
",",
"directory",
")",
"end",
"executioner",
"end"
] | Encapsulates the given executioner with child-process-modifying behavior
based on options. Builds the executioner as a series of callbacks.
@param [Proc] executioner to configure
@param [Hash] options for execution
@return [Proc] configured executioner | [
"Encapsulates",
"the",
"given",
"executioner",
"with",
"child",
"-",
"process",
"-",
"modifying",
"behavior",
"based",
"on",
"options",
".",
"Builds",
"the",
"executioner",
"as",
"a",
"series",
"of",
"callbacks",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L173-L197 |
23,673 | rightscale/right_git | lib/right_git/shell/default.rb | RightGit::Shell.Default.set_env_vars | def set_env_vars(variables)
save_vars = {}
variables.each do |k, v|
k = k.to_s
save_vars[k] = ENV[k]
ENV[k] = v.nil? ? v : v.to_s
end
begin
yield
ensure
variables.each_key do |k|
k = k.to_s
ENV[k] = save_vars[k]
end
end
true
end | ruby | def set_env_vars(variables)
save_vars = {}
variables.each do |k, v|
k = k.to_s
save_vars[k] = ENV[k]
ENV[k] = v.nil? ? v : v.to_s
end
begin
yield
ensure
variables.each_key do |k|
k = k.to_s
ENV[k] = save_vars[k]
end
end
true
end | [
"def",
"set_env_vars",
"(",
"variables",
")",
"save_vars",
"=",
"{",
"}",
"variables",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"k",
"=",
"k",
".",
"to_s",
"save_vars",
"[",
"k",
"]",
"=",
"ENV",
"[",
"k",
"]",
"ENV",
"[",
"k",
"]",
"=",
"v",
".",
"nil?",
"?",
"v",
":",
"v",
".",
"to_s",
"end",
"begin",
"yield",
"ensure",
"variables",
".",
"each_key",
"do",
"|",
"k",
"|",
"k",
"=",
"k",
".",
"to_s",
"ENV",
"[",
"k",
"]",
"=",
"save_vars",
"[",
"k",
"]",
"end",
"end",
"true",
"end"
] | Sets the given list of environment variables while
executing the given block.
=== Parameters
@param [Hash] variables to set
=== Yield
@yield [] called with environment set
=== Return
@return [TrueClass] always true | [
"Sets",
"the",
"given",
"list",
"of",
"environment",
"variables",
"while",
"executing",
"the",
"given",
"block",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/shell/default.rb#L210-L226 |
23,674 | noprompt/vic | lib/vic/highlight.rb | Vic.Highlight.bg= | def bg=(color)
color = Color.new(color)
@ctermbg, @guibg = color.to_cterm, color.to_gui
self
end | ruby | def bg=(color)
color = Color.new(color)
@ctermbg, @guibg = color.to_cterm, color.to_gui
self
end | [
"def",
"bg",
"=",
"(",
"color",
")",
"color",
"=",
"Color",
".",
"new",
"(",
"color",
")",
"@ctermbg",
",",
"@guibg",
"=",
"color",
".",
"to_cterm",
",",
"color",
".",
"to_gui",
"self",
"end"
] | Set both ctermbg and guibg simultaneously
@param [String] color
the color to use
@return [Vic::Highlight]
the updated highlight
@api public | [
"Set",
"both",
"ctermbg",
"and",
"guibg",
"simultaneously"
] | 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/highlight.rb#L88-L92 |
23,675 | noprompt/vic | lib/vic/highlight.rb | Vic.Highlight.fg= | def fg=(color)
color = Color.new(color)
@ctermfg, @guifg = color.to_cterm, color.to_gui
self
end | ruby | def fg=(color)
color = Color.new(color)
@ctermfg, @guifg = color.to_cterm, color.to_gui
self
end | [
"def",
"fg",
"=",
"(",
"color",
")",
"color",
"=",
"Color",
".",
"new",
"(",
"color",
")",
"@ctermfg",
",",
"@guifg",
"=",
"color",
".",
"to_cterm",
",",
"color",
".",
"to_gui",
"self",
"end"
] | Set both ctermfg and guifg simultaneously
@param [String] color
the color to use
@return [Vic::Highlight]
the updated highlight
@api public | [
"Set",
"both",
"ctermfg",
"and",
"guifg",
"simultaneously"
] | 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/highlight.rb#L103-L107 |
23,676 | noprompt/vic | lib/vic/highlight.rb | Vic.Highlight.select_styles | def select_styles(*styles)
styles.tap(&:compact).flatten!
if styles.empty? or styles.length == 1 && /\Anone\z/io.match(styles[0])
return :NONE
end
styles.select { |s| FONT_STYLE.match(s) }
end | ruby | def select_styles(*styles)
styles.tap(&:compact).flatten!
if styles.empty? or styles.length == 1 && /\Anone\z/io.match(styles[0])
return :NONE
end
styles.select { |s| FONT_STYLE.match(s) }
end | [
"def",
"select_styles",
"(",
"*",
"styles",
")",
"styles",
".",
"tap",
"(",
":compact",
")",
".",
"flatten!",
"if",
"styles",
".",
"empty?",
"or",
"styles",
".",
"length",
"==",
"1",
"&&",
"/",
"\\A",
"\\z",
"/io",
".",
"match",
"(",
"styles",
"[",
"0",
"]",
")",
"return",
":NONE",
"end",
"styles",
".",
"select",
"{",
"|",
"s",
"|",
"FONT_STYLE",
".",
"match",
"(",
"s",
")",
"}",
"end"
] | Selcect valid styles from a list
@param [Mixed] styles
the list of styles
@return [Array,Symbol]
the list of valid styles or "NONE"
@api private | [
"Selcect",
"valid",
"styles",
"from",
"a",
"list"
] | 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/highlight.rb#L222-L228 |
23,677 | aidistan/ruby-biotcm | lib/biotcm/databases/hgnc/parser.rb | BioTCM::Databases::HGNC.Parser.parse | def parse(fin)
# Headline
names = fin.gets.chomp.split("\t")
index2identifier = {}
index_hgncid = nil
BioTCM::Databases::HGNC::IDENTIFIERS.each do |identifer, name|
if identifer == :hgncid
index_hgncid = names.index(name)
elsif name.is_a?(String)
index2identifier[names.index(name)] = identifer if names.index(name)
else
name.each_with_index do |n, i|
next unless names.index(n)
index2identifier[names.index(n)] = (i == 0 ? identifer : identifer.to_s)
end
end
end
# Dynamically bulid a line processor
process_one_line = index2identifier.collect do |index, identifer|
# Symbol will be mapped to single item
if identifer.is_a?(Symbol)
%(
unless column[#{index}] == nil || column[#{index}] == "" || column[#{index}] == "-"
@#{identifer}2hgncid[column[#{index}]] = column[#{index_hgncid}]
@hgncid2#{identifer}[column[#{index_hgncid}]] = column[#{index}]
end
)
# Others will be mapped to list item
else
%{
unless column[#{index}] == nil
column[#{index}].split(", ").each do |id|
} +
if identifer == 'symbol'
%(
if @ambiguous_symbol[id]
@ambiguous_symbol[id] << @hgncid2symbol[column[#{index_hgncid}]]
elsif @symbol2hgncid[id].nil?
@symbol2hgncid[id] = column[#{index_hgncid}]
else
@ambiguous_symbol[id] = [@hgncid2symbol[column[#{index_hgncid}]]]
unless @hgncid2symbol[@symbol2hgncid[id]] == id
@ambiguous_symbol[id] << @hgncid2symbol[@symbol2hgncid[id]]
@symbol2hgncid.delete(id)
end
end
)
else
%(
@#{identifer}2hgncid[id] = column[#{index_hgncid}] if @#{identifer}2hgncid[id].nil?
)
end +
%(
end
end
)
end
end.join
# Process the content
eval %{fin.each do |line|\n column = line.chomp.split("\\t", -1)} + process_one_line + 'end' # rubocop:disable Lint/Eval
end | ruby | def parse(fin)
# Headline
names = fin.gets.chomp.split("\t")
index2identifier = {}
index_hgncid = nil
BioTCM::Databases::HGNC::IDENTIFIERS.each do |identifer, name|
if identifer == :hgncid
index_hgncid = names.index(name)
elsif name.is_a?(String)
index2identifier[names.index(name)] = identifer if names.index(name)
else
name.each_with_index do |n, i|
next unless names.index(n)
index2identifier[names.index(n)] = (i == 0 ? identifer : identifer.to_s)
end
end
end
# Dynamically bulid a line processor
process_one_line = index2identifier.collect do |index, identifer|
# Symbol will be mapped to single item
if identifer.is_a?(Symbol)
%(
unless column[#{index}] == nil || column[#{index}] == "" || column[#{index}] == "-"
@#{identifer}2hgncid[column[#{index}]] = column[#{index_hgncid}]
@hgncid2#{identifer}[column[#{index_hgncid}]] = column[#{index}]
end
)
# Others will be mapped to list item
else
%{
unless column[#{index}] == nil
column[#{index}].split(", ").each do |id|
} +
if identifer == 'symbol'
%(
if @ambiguous_symbol[id]
@ambiguous_symbol[id] << @hgncid2symbol[column[#{index_hgncid}]]
elsif @symbol2hgncid[id].nil?
@symbol2hgncid[id] = column[#{index_hgncid}]
else
@ambiguous_symbol[id] = [@hgncid2symbol[column[#{index_hgncid}]]]
unless @hgncid2symbol[@symbol2hgncid[id]] == id
@ambiguous_symbol[id] << @hgncid2symbol[@symbol2hgncid[id]]
@symbol2hgncid.delete(id)
end
end
)
else
%(
@#{identifer}2hgncid[id] = column[#{index_hgncid}] if @#{identifer}2hgncid[id].nil?
)
end +
%(
end
end
)
end
end.join
# Process the content
eval %{fin.each do |line|\n column = line.chomp.split("\\t", -1)} + process_one_line + 'end' # rubocop:disable Lint/Eval
end | [
"def",
"parse",
"(",
"fin",
")",
"# Headline",
"names",
"=",
"fin",
".",
"gets",
".",
"chomp",
".",
"split",
"(",
"\"\\t\"",
")",
"index2identifier",
"=",
"{",
"}",
"index_hgncid",
"=",
"nil",
"BioTCM",
"::",
"Databases",
"::",
"HGNC",
"::",
"IDENTIFIERS",
".",
"each",
"do",
"|",
"identifer",
",",
"name",
"|",
"if",
"identifer",
"==",
":hgncid",
"index_hgncid",
"=",
"names",
".",
"index",
"(",
"name",
")",
"elsif",
"name",
".",
"is_a?",
"(",
"String",
")",
"index2identifier",
"[",
"names",
".",
"index",
"(",
"name",
")",
"]",
"=",
"identifer",
"if",
"names",
".",
"index",
"(",
"name",
")",
"else",
"name",
".",
"each_with_index",
"do",
"|",
"n",
",",
"i",
"|",
"next",
"unless",
"names",
".",
"index",
"(",
"n",
")",
"index2identifier",
"[",
"names",
".",
"index",
"(",
"n",
")",
"]",
"=",
"(",
"i",
"==",
"0",
"?",
"identifer",
":",
"identifer",
".",
"to_s",
")",
"end",
"end",
"end",
"# Dynamically bulid a line processor",
"process_one_line",
"=",
"index2identifier",
".",
"collect",
"do",
"|",
"index",
",",
"identifer",
"|",
"# Symbol will be mapped to single item",
"if",
"identifer",
".",
"is_a?",
"(",
"Symbol",
")",
"%(\n unless column[#{index}] == nil || column[#{index}] == \"\" || column[#{index}] == \"-\"\n @#{identifer}2hgncid[column[#{index}]] = column[#{index_hgncid}]\n @hgncid2#{identifer}[column[#{index_hgncid}]] = column[#{index}]\n end\n )",
"# Others will be mapped to list item",
"else",
"%{\n unless column[#{index}] == nil\n column[#{index}].split(\", \").each do |id|\n }",
"+",
"if",
"identifer",
"==",
"'symbol'",
"%(\n if @ambiguous_symbol[id]\n @ambiguous_symbol[id] << @hgncid2symbol[column[#{index_hgncid}]]\n elsif @symbol2hgncid[id].nil?\n @symbol2hgncid[id] = column[#{index_hgncid}]\n else\n @ambiguous_symbol[id] = [@hgncid2symbol[column[#{index_hgncid}]]]\n unless @hgncid2symbol[@symbol2hgncid[id]] == id\n @ambiguous_symbol[id] << @hgncid2symbol[@symbol2hgncid[id]]\n @symbol2hgncid.delete(id)\n end\n end\n )",
"else",
"%(\n @#{identifer}2hgncid[id] = column[#{index_hgncid}] if @#{identifer}2hgncid[id].nil?\n )",
"end",
"+",
"%(\n end\n end\n )",
"end",
"end",
".",
"join",
"# Process the content",
"eval",
"%{fin.each do |line|\\n column = line.chomp.split(\"\\\\t\", -1)}",
"+",
"process_one_line",
"+",
"'end'",
"# rubocop:disable Lint/Eval",
"end"
] | Load an HGNC table from IO
@param fin [#gets, #each] Typically a File or IO
@private | [
"Load",
"an",
"HGNC",
"table",
"from",
"IO"
] | 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/databases/hgnc/parser.rb#L17-L79 |
23,678 | rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.retrieve | def retrieve
raise RetrieverError.new("git retriever is unavailable") unless available?
private_key = @repository.first_credential
private_key = nil if private_key && private_key.empty?
if is_windows?
if private_key
with_private_key_windows(private_key) { super }
else
super
end
else
# always start the ssh agent in Linux so we can disable strict host name
# checking, regardless of credentials.
::RightScraper::Processes::SSHAgent.with do |agent|
agent.add_key(private_key) if private_key
super
end
end
true
end | ruby | def retrieve
raise RetrieverError.new("git retriever is unavailable") unless available?
private_key = @repository.first_credential
private_key = nil if private_key && private_key.empty?
if is_windows?
if private_key
with_private_key_windows(private_key) { super }
else
super
end
else
# always start the ssh agent in Linux so we can disable strict host name
# checking, regardless of credentials.
::RightScraper::Processes::SSHAgent.with do |agent|
agent.add_key(private_key) if private_key
super
end
end
true
end | [
"def",
"retrieve",
"raise",
"RetrieverError",
".",
"new",
"(",
"\"git retriever is unavailable\"",
")",
"unless",
"available?",
"private_key",
"=",
"@repository",
".",
"first_credential",
"private_key",
"=",
"nil",
"if",
"private_key",
"&&",
"private_key",
".",
"empty?",
"if",
"is_windows?",
"if",
"private_key",
"with_private_key_windows",
"(",
"private_key",
")",
"{",
"super",
"}",
"else",
"super",
"end",
"else",
"# always start the ssh agent in Linux so we can disable strict host name",
"# checking, regardless of credentials.",
"::",
"RightScraper",
"::",
"Processes",
"::",
"SSHAgent",
".",
"with",
"do",
"|",
"agent",
"|",
"agent",
".",
"add_key",
"(",
"private_key",
")",
"if",
"private_key",
"super",
"end",
"end",
"true",
"end"
] | In addition to normal retriever initialization, if the
underlying repository has a credential we need to initialize a
fresh SSHAgent and add the credential to it. | [
"In",
"addition",
"to",
"normal",
"retriever",
"initialization",
"if",
"the",
"underlying",
"repository",
"has",
"a",
"credential",
"we",
"need",
"to",
"initialize",
"a",
"fresh",
"SSHAgent",
"and",
"add",
"the",
"credential",
"to",
"it",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L66-L85 |
23,679 | rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.do_clean_all | def do_clean_all(git_repo)
old_initial_directory = git_repo.repo_dir
clean_all_options = {
:directories => true,
:gitignored => true,
:submodules => true
}
relative_paths = [
'.',
git_repo.submodule_paths(:recursive => true)
].flatten
relative_paths.each do |relative_path|
subdir_path = ::File.expand_path(::File.join(@repo_dir, relative_path))
if ::File.directory?(subdir_path)
# reuse shell with any watch parameters already set but vary the
# initial directory for each submodule.
git_repo.shell.initial_directory = subdir_path
git_repo.clean_all(clean_all_options)
end
end
true
rescue ::RightGit::RightGitError => e
@logger.note_warning(e.message)
false
ensure
git_repo.shell.initial_directory = old_initial_directory
end | ruby | def do_clean_all(git_repo)
old_initial_directory = git_repo.repo_dir
clean_all_options = {
:directories => true,
:gitignored => true,
:submodules => true
}
relative_paths = [
'.',
git_repo.submodule_paths(:recursive => true)
].flatten
relative_paths.each do |relative_path|
subdir_path = ::File.expand_path(::File.join(@repo_dir, relative_path))
if ::File.directory?(subdir_path)
# reuse shell with any watch parameters already set but vary the
# initial directory for each submodule.
git_repo.shell.initial_directory = subdir_path
git_repo.clean_all(clean_all_options)
end
end
true
rescue ::RightGit::RightGitError => e
@logger.note_warning(e.message)
false
ensure
git_repo.shell.initial_directory = old_initial_directory
end | [
"def",
"do_clean_all",
"(",
"git_repo",
")",
"old_initial_directory",
"=",
"git_repo",
".",
"repo_dir",
"clean_all_options",
"=",
"{",
":directories",
"=>",
"true",
",",
":gitignored",
"=>",
"true",
",",
":submodules",
"=>",
"true",
"}",
"relative_paths",
"=",
"[",
"'.'",
",",
"git_repo",
".",
"submodule_paths",
"(",
":recursive",
"=>",
"true",
")",
"]",
".",
"flatten",
"relative_paths",
".",
"each",
"do",
"|",
"relative_path",
"|",
"subdir_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"::",
"File",
".",
"join",
"(",
"@repo_dir",
",",
"relative_path",
")",
")",
"if",
"::",
"File",
".",
"directory?",
"(",
"subdir_path",
")",
"# reuse shell with any watch parameters already set but vary the",
"# initial directory for each submodule.",
"git_repo",
".",
"shell",
".",
"initial_directory",
"=",
"subdir_path",
"git_repo",
".",
"clean_all",
"(",
"clean_all_options",
")",
"end",
"end",
"true",
"rescue",
"::",
"RightGit",
"::",
"RightGitError",
"=>",
"e",
"@logger",
".",
"note_warning",
"(",
"e",
".",
"message",
")",
"false",
"ensure",
"git_repo",
".",
"shell",
".",
"initial_directory",
"=",
"old_initial_directory",
"end"
] | Cleans anything that is currently untracked in the repo directory and
any submodules. the idea is to prevent untracked items interfering with
the normal behavior that would result if checkout were always to a clean
directory. just switching between branches and updating submodules can
leave untracked artifacts that affect behavior. | [
"Cleans",
"anything",
"that",
"is",
"currently",
"untracked",
"in",
"the",
"repo",
"directory",
"and",
"any",
"submodules",
".",
"the",
"idea",
"is",
"to",
"prevent",
"untracked",
"items",
"interfering",
"with",
"the",
"normal",
"behavior",
"that",
"would",
"result",
"if",
"checkout",
"were",
"always",
"to",
"a",
"clean",
"directory",
".",
"just",
"switching",
"between",
"branches",
"and",
"updating",
"submodules",
"can",
"leave",
"untracked",
"artifacts",
"that",
"affect",
"behavior",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L222-L248 |
23,680 | rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.validate_revision | def validate_revision(git_repo, revision)
branches = git_repo.branches(:all => true)
local_branches = branches.local
remote_branches = branches.remote
by_name = lambda { |item| item.name == revision }
# determine if revision is a tag.
remote_name = nil
if git_repo.tags.any?(&by_name)
if remote_branches.any?(&by_name)
# note that git has some resolution scheme for ambiguous SHA, tag,
# branch names but we do not support ambiguity.
raise RetrieverError, "Ambiguous name is both a remote branch and a tag: #{revision.inspect}"
elsif local_branches.any?(&by_name)
# odd corner case of a name that once was a remote branch (now
# deleted) that has become a tag instead. the user is not exactly
# at fault here (aside from being indecisive) so let's attempt to
# clean up after him. try switching to another local branch
# (i.e. master) and then deleting the obsolete local branch.
error_message = "Ambiguous name is both a local branch and a tag: #{revision.inspect}"
if revision == DEFAULT_BRANCH_NAME
# Darwin Awards winner; scraping with a tag named 'master' :@
raise RetrieverError, error_message
else
begin
# checkout master and delete obsolete local branch.
git_repo.checkout_to(DEFAULT_BRANCH_NAME, :force => true)
git_repo.spit_output("branch -D #{revision}")
rescue ::RightGit::RightGitError
# ignore failed attempt to recover; raise original error.
raise RetrieverError, error_message
end
end
end
else
# not a tag; SHA or branch.
#
# note that we could try to trivially determine if revision was a
# SHA by matching the SHA1 pattern except that:
# 1) git accepts partial SHAs so long as they uniquely distinguish
# a commit for checkout.
# 2) a branch or tag could name could match the SHA pattern (i.e.
# 40 hexadecimal characters) with no warnings from git. git will
# even allow a user to use a SHA as a tag name when that SHA
# exists (and may represent a different commit).
# confusing tags with SHAs should be universally discouraged but we
# need to be flexible here.
#
# a local branch may no longer exist remotely or may be behind or
# have diverged from remote branch. handle all cases.
remotes = remote_branches.select(&by_name)
if remotes.size > 1
# multiple remote branches exist (from different origins); branch
# name is ambiguous.
raise RetrieverError, "Ambiguous remote branch name: #{revision.inspect}"
elsif remotes.size == 1
# a remote branch exists.
remote_name = remotes.first.fullname
elsif local_branches.any?(&by_name)
# local branch only; failure due to missing remote branch.
#
# note that obsolete local branches are not supported by retrieval
# only because it would give the user a false positive.
raise RetrieverError, "Missing remote branch: #{revision.inspect}."
end # else a full or partial SHA or unknown revision
end
remote_name
end | ruby | def validate_revision(git_repo, revision)
branches = git_repo.branches(:all => true)
local_branches = branches.local
remote_branches = branches.remote
by_name = lambda { |item| item.name == revision }
# determine if revision is a tag.
remote_name = nil
if git_repo.tags.any?(&by_name)
if remote_branches.any?(&by_name)
# note that git has some resolution scheme for ambiguous SHA, tag,
# branch names but we do not support ambiguity.
raise RetrieverError, "Ambiguous name is both a remote branch and a tag: #{revision.inspect}"
elsif local_branches.any?(&by_name)
# odd corner case of a name that once was a remote branch (now
# deleted) that has become a tag instead. the user is not exactly
# at fault here (aside from being indecisive) so let's attempt to
# clean up after him. try switching to another local branch
# (i.e. master) and then deleting the obsolete local branch.
error_message = "Ambiguous name is both a local branch and a tag: #{revision.inspect}"
if revision == DEFAULT_BRANCH_NAME
# Darwin Awards winner; scraping with a tag named 'master' :@
raise RetrieverError, error_message
else
begin
# checkout master and delete obsolete local branch.
git_repo.checkout_to(DEFAULT_BRANCH_NAME, :force => true)
git_repo.spit_output("branch -D #{revision}")
rescue ::RightGit::RightGitError
# ignore failed attempt to recover; raise original error.
raise RetrieverError, error_message
end
end
end
else
# not a tag; SHA or branch.
#
# note that we could try to trivially determine if revision was a
# SHA by matching the SHA1 pattern except that:
# 1) git accepts partial SHAs so long as they uniquely distinguish
# a commit for checkout.
# 2) a branch or tag could name could match the SHA pattern (i.e.
# 40 hexadecimal characters) with no warnings from git. git will
# even allow a user to use a SHA as a tag name when that SHA
# exists (and may represent a different commit).
# confusing tags with SHAs should be universally discouraged but we
# need to be flexible here.
#
# a local branch may no longer exist remotely or may be behind or
# have diverged from remote branch. handle all cases.
remotes = remote_branches.select(&by_name)
if remotes.size > 1
# multiple remote branches exist (from different origins); branch
# name is ambiguous.
raise RetrieverError, "Ambiguous remote branch name: #{revision.inspect}"
elsif remotes.size == 1
# a remote branch exists.
remote_name = remotes.first.fullname
elsif local_branches.any?(&by_name)
# local branch only; failure due to missing remote branch.
#
# note that obsolete local branches are not supported by retrieval
# only because it would give the user a false positive.
raise RetrieverError, "Missing remote branch: #{revision.inspect}."
end # else a full or partial SHA or unknown revision
end
remote_name
end | [
"def",
"validate_revision",
"(",
"git_repo",
",",
"revision",
")",
"branches",
"=",
"git_repo",
".",
"branches",
"(",
":all",
"=>",
"true",
")",
"local_branches",
"=",
"branches",
".",
"local",
"remote_branches",
"=",
"branches",
".",
"remote",
"by_name",
"=",
"lambda",
"{",
"|",
"item",
"|",
"item",
".",
"name",
"==",
"revision",
"}",
"# determine if revision is a tag.",
"remote_name",
"=",
"nil",
"if",
"git_repo",
".",
"tags",
".",
"any?",
"(",
"by_name",
")",
"if",
"remote_branches",
".",
"any?",
"(",
"by_name",
")",
"# note that git has some resolution scheme for ambiguous SHA, tag,",
"# branch names but we do not support ambiguity.",
"raise",
"RetrieverError",
",",
"\"Ambiguous name is both a remote branch and a tag: #{revision.inspect}\"",
"elsif",
"local_branches",
".",
"any?",
"(",
"by_name",
")",
"# odd corner case of a name that once was a remote branch (now",
"# deleted) that has become a tag instead. the user is not exactly",
"# at fault here (aside from being indecisive) so let's attempt to",
"# clean up after him. try switching to another local branch",
"# (i.e. master) and then deleting the obsolete local branch.",
"error_message",
"=",
"\"Ambiguous name is both a local branch and a tag: #{revision.inspect}\"",
"if",
"revision",
"==",
"DEFAULT_BRANCH_NAME",
"# Darwin Awards winner; scraping with a tag named 'master' :@",
"raise",
"RetrieverError",
",",
"error_message",
"else",
"begin",
"# checkout master and delete obsolete local branch.",
"git_repo",
".",
"checkout_to",
"(",
"DEFAULT_BRANCH_NAME",
",",
":force",
"=>",
"true",
")",
"git_repo",
".",
"spit_output",
"(",
"\"branch -D #{revision}\"",
")",
"rescue",
"::",
"RightGit",
"::",
"RightGitError",
"# ignore failed attempt to recover; raise original error.",
"raise",
"RetrieverError",
",",
"error_message",
"end",
"end",
"end",
"else",
"# not a tag; SHA or branch.",
"#",
"# note that we could try to trivially determine if revision was a",
"# SHA by matching the SHA1 pattern except that:",
"# 1) git accepts partial SHAs so long as they uniquely distinguish",
"# a commit for checkout.",
"# 2) a branch or tag could name could match the SHA pattern (i.e.",
"# 40 hexadecimal characters) with no warnings from git. git will",
"# even allow a user to use a SHA as a tag name when that SHA",
"# exists (and may represent a different commit).",
"# confusing tags with SHAs should be universally discouraged but we",
"# need to be flexible here.",
"#",
"# a local branch may no longer exist remotely or may be behind or",
"# have diverged from remote branch. handle all cases.",
"remotes",
"=",
"remote_branches",
".",
"select",
"(",
"by_name",
")",
"if",
"remotes",
".",
"size",
">",
"1",
"# multiple remote branches exist (from different origins); branch",
"# name is ambiguous.",
"raise",
"RetrieverError",
",",
"\"Ambiguous remote branch name: #{revision.inspect}\"",
"elsif",
"remotes",
".",
"size",
"==",
"1",
"# a remote branch exists.",
"remote_name",
"=",
"remotes",
".",
"first",
".",
"fullname",
"elsif",
"local_branches",
".",
"any?",
"(",
"by_name",
")",
"# local branch only; failure due to missing remote branch.",
"#",
"# note that obsolete local branches are not supported by retrieval",
"# only because it would give the user a false positive.",
"raise",
"RetrieverError",
",",
"\"Missing remote branch: #{revision.inspect}.\"",
"end",
"# else a full or partial SHA or unknown revision",
"end",
"remote_name",
"end"
] | Validates the given revision string to ensure it is safe and sane before
attempting to use it.
@param [::RightGit::Git::Repository] git_repo for validation
@param [String] revision for validation
@return [String] remote_name (for branch reset) or nil
@raise [RetrieverError] on validation failure | [
"Validates",
"the",
"given",
"revision",
"string",
"to",
"ensure",
"it",
"is",
"safe",
"and",
"sane",
"before",
"attempting",
"to",
"use",
"it",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L264-L331 |
23,681 | rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.without_size_limit | def without_size_limit(git_repo)
old_max_bytes = git_repo.shell.max_bytes
begin
git_repo.shell.max_bytes = nil
yield
ensure
git_repo.shell.max_bytes = old_max_bytes
end
end | ruby | def without_size_limit(git_repo)
old_max_bytes = git_repo.shell.max_bytes
begin
git_repo.shell.max_bytes = nil
yield
ensure
git_repo.shell.max_bytes = old_max_bytes
end
end | [
"def",
"without_size_limit",
"(",
"git_repo",
")",
"old_max_bytes",
"=",
"git_repo",
".",
"shell",
".",
"max_bytes",
"begin",
"git_repo",
".",
"shell",
".",
"max_bytes",
"=",
"nil",
"yield",
"ensure",
"git_repo",
".",
"shell",
".",
"max_bytes",
"=",
"old_max_bytes",
"end",
"end"
] | Temporarily disables checking the size of the repo_dir against the
configured size limit. This permits performing git queries against a repo
on disk that would normally exceed the size limit if it hadn't already
been fully checked out in the past. If a repo has been scraped in the past
and does not have any new commits, then it is acceptable even if it
would exceed the current size limit. | [
"Temporarily",
"disables",
"checking",
"the",
"size",
"of",
"the",
"repo_dir",
"against",
"the",
"configured",
"size",
"limit",
".",
"This",
"permits",
"performing",
"git",
"queries",
"against",
"a",
"repo",
"on",
"disk",
"that",
"would",
"normally",
"exceed",
"the",
"size",
"limit",
"if",
"it",
"hadn",
"t",
"already",
"been",
"fully",
"checked",
"out",
"in",
"the",
"past",
".",
"If",
"a",
"repo",
"has",
"been",
"scraped",
"in",
"the",
"past",
"and",
"does",
"not",
"have",
"any",
"new",
"commits",
"then",
"it",
"is",
"acceptable",
"even",
"if",
"it",
"would",
"exceed",
"the",
"current",
"size",
"limit",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L339-L347 |
23,682 | rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.without_host_key_checking_linux | def without_host_key_checking_linux
tmpdir = ::Dir.mktmpdir
ssh_cmd = ::File.join(tmpdir, 'ssh')
::File.open(ssh_cmd, 'w') do |cmd|
cmd.puts "#!/bin/bash"
cmd.puts "exec ssh -o StrictHostKeyChecking=no ${@}"
end
::FileUtils.chmod(0700, ssh_cmd)
old_env = ::ENV['GIT_SSH']
::ENV['GIT_SSH'] = ssh_cmd
yield
ensure
::FileUtils.rm_rf(tmpdir)
::ENV['GIT_SSH'] = old_env
end | ruby | def without_host_key_checking_linux
tmpdir = ::Dir.mktmpdir
ssh_cmd = ::File.join(tmpdir, 'ssh')
::File.open(ssh_cmd, 'w') do |cmd|
cmd.puts "#!/bin/bash"
cmd.puts "exec ssh -o StrictHostKeyChecking=no ${@}"
end
::FileUtils.chmod(0700, ssh_cmd)
old_env = ::ENV['GIT_SSH']
::ENV['GIT_SSH'] = ssh_cmd
yield
ensure
::FileUtils.rm_rf(tmpdir)
::ENV['GIT_SSH'] = old_env
end | [
"def",
"without_host_key_checking_linux",
"tmpdir",
"=",
"::",
"Dir",
".",
"mktmpdir",
"ssh_cmd",
"=",
"::",
"File",
".",
"join",
"(",
"tmpdir",
",",
"'ssh'",
")",
"::",
"File",
".",
"open",
"(",
"ssh_cmd",
",",
"'w'",
")",
"do",
"|",
"cmd",
"|",
"cmd",
".",
"puts",
"\"#!/bin/bash\"",
"cmd",
".",
"puts",
"\"exec ssh -o StrictHostKeyChecking=no ${@}\"",
"end",
"::",
"FileUtils",
".",
"chmod",
"(",
"0700",
",",
"ssh_cmd",
")",
"old_env",
"=",
"::",
"ENV",
"[",
"'GIT_SSH'",
"]",
"::",
"ENV",
"[",
"'GIT_SSH'",
"]",
"=",
"ssh_cmd",
"yield",
"ensure",
"::",
"FileUtils",
".",
"rm_rf",
"(",
"tmpdir",
")",
"::",
"ENV",
"[",
"'GIT_SSH'",
"]",
"=",
"old_env",
"end"
] | Temporarily disable SSH host-key checking for SSH clients invoked by Git, for the duration of the
block that is passed to this method.
@yield after disabling strict host key checking, yields to caller | [
"Temporarily",
"disable",
"SSH",
"host",
"-",
"key",
"checking",
"for",
"SSH",
"clients",
"invoked",
"by",
"Git",
"for",
"the",
"duration",
"of",
"the",
"block",
"that",
"is",
"passed",
"to",
"this",
"method",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L365-L381 |
23,683 | rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.with_replaced_file | def with_replaced_file(filepath, contents)
::Dir.mktmpdir do |temp_dir|
begin
temp_path = ::File.join(temp_dir, ::File.basename(filepath))
::FileUtils.mkdir_p(::File.dirname(filepath))
if ::File.file?(filepath)
::FileUtils.mv(filepath, temp_path, :force => true)
end
::File.open(filepath, 'w') { |f| f.write(contents) }
yield
ensure
begin
if ::File.file?(temp_path)
::FileUtils.mv(temp_path, filepath, :force => true)
elsif ::File.file?(filepath)
::File.unlink(filepath)
end
rescue ::Exception => e
@logger.note_warning("Failed to restore #{filepath.inspect}: #{e.message}")
end
end
end
end | ruby | def with_replaced_file(filepath, contents)
::Dir.mktmpdir do |temp_dir|
begin
temp_path = ::File.join(temp_dir, ::File.basename(filepath))
::FileUtils.mkdir_p(::File.dirname(filepath))
if ::File.file?(filepath)
::FileUtils.mv(filepath, temp_path, :force => true)
end
::File.open(filepath, 'w') { |f| f.write(contents) }
yield
ensure
begin
if ::File.file?(temp_path)
::FileUtils.mv(temp_path, filepath, :force => true)
elsif ::File.file?(filepath)
::File.unlink(filepath)
end
rescue ::Exception => e
@logger.note_warning("Failed to restore #{filepath.inspect}: #{e.message}")
end
end
end
end | [
"def",
"with_replaced_file",
"(",
"filepath",
",",
"contents",
")",
"::",
"Dir",
".",
"mktmpdir",
"do",
"|",
"temp_dir",
"|",
"begin",
"temp_path",
"=",
"::",
"File",
".",
"join",
"(",
"temp_dir",
",",
"::",
"File",
".",
"basename",
"(",
"filepath",
")",
")",
"::",
"FileUtils",
".",
"mkdir_p",
"(",
"::",
"File",
".",
"dirname",
"(",
"filepath",
")",
")",
"if",
"::",
"File",
".",
"file?",
"(",
"filepath",
")",
"::",
"FileUtils",
".",
"mv",
"(",
"filepath",
",",
"temp_path",
",",
":force",
"=>",
"true",
")",
"end",
"::",
"File",
".",
"open",
"(",
"filepath",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"contents",
")",
"}",
"yield",
"ensure",
"begin",
"if",
"::",
"File",
".",
"file?",
"(",
"temp_path",
")",
"::",
"FileUtils",
".",
"mv",
"(",
"temp_path",
",",
"filepath",
",",
":force",
"=>",
"true",
")",
"elsif",
"::",
"File",
".",
"file?",
"(",
"filepath",
")",
"::",
"File",
".",
"unlink",
"(",
"filepath",
")",
"end",
"rescue",
"::",
"Exception",
"=>",
"e",
"@logger",
".",
"note_warning",
"(",
"\"Failed to restore #{filepath.inspect}: #{e.message}\"",
")",
"end",
"end",
"end",
"end"
] | Utility for replacing a file temporarily within a scope and ensuring it is
restored afterward.
@param [String] filepath to replace
@param [String] contents to substitute
@yield after replacing file | [
"Utility",
"for",
"replacing",
"a",
"file",
"temporarily",
"within",
"a",
"scope",
"and",
"ensuring",
"it",
"is",
"restored",
"afterward",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L411-L433 |
23,684 | rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.fetch_all | def fetch_all(options = {})
options = { :prune => false }.merge(options)
git_args = ['--all']
git_args << '--prune' if options[:prune]
fetch(git_args)
fetch('--tags') # need a separate call for tags or else you don't get all the tags
true
end | ruby | def fetch_all(options = {})
options = { :prune => false }.merge(options)
git_args = ['--all']
git_args << '--prune' if options[:prune]
fetch(git_args)
fetch('--tags') # need a separate call for tags or else you don't get all the tags
true
end | [
"def",
"fetch_all",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":prune",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'--all'",
"]",
"git_args",
"<<",
"'--prune'",
"if",
"options",
"[",
":prune",
"]",
"fetch",
"(",
"git_args",
")",
"fetch",
"(",
"'--tags'",
")",
"# need a separate call for tags or else you don't get all the tags",
"true",
"end"
] | Fetches branch and tag information from remote origin.
@param [Hash] options for fetch all
@option options [TrueClass|FalseClass] :prune as true to prune dead branches
@return [TrueClass] always true | [
"Fetches",
"branch",
"and",
"tag",
"information",
"from",
"remote",
"origin",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L111-L118 |
23,685 | rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.log | def log(revision, options = {})
options = {
:skip => nil,
:tail => 10_000,
:merges => false,
:no_merges => false,
:full_hashes => false,
}.merge(options)
skip = options[:skip]
git_args = [
'log',
"-n#{options[:tail]}",
"--format=\"#{options[:full_hashes] ? Commit::LOG_FORMAT_LONG : Commit::LOG_FORMAT}\"" # double-quotes are Windows friendly
]
git_args << "--skip #{skip}" if skip
git_args << "--merges" if options[:merges]
git_args << "--no-merges" if options[:no_merges]
git_args << revision if revision
git_output(git_args).lines.map { |line| Commit.new(self, line.strip) }
end | ruby | def log(revision, options = {})
options = {
:skip => nil,
:tail => 10_000,
:merges => false,
:no_merges => false,
:full_hashes => false,
}.merge(options)
skip = options[:skip]
git_args = [
'log',
"-n#{options[:tail]}",
"--format=\"#{options[:full_hashes] ? Commit::LOG_FORMAT_LONG : Commit::LOG_FORMAT}\"" # double-quotes are Windows friendly
]
git_args << "--skip #{skip}" if skip
git_args << "--merges" if options[:merges]
git_args << "--no-merges" if options[:no_merges]
git_args << revision if revision
git_output(git_args).lines.map { |line| Commit.new(self, line.strip) }
end | [
"def",
"log",
"(",
"revision",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":skip",
"=>",
"nil",
",",
":tail",
"=>",
"10_000",
",",
":merges",
"=>",
"false",
",",
":no_merges",
"=>",
"false",
",",
":full_hashes",
"=>",
"false",
",",
"}",
".",
"merge",
"(",
"options",
")",
"skip",
"=",
"options",
"[",
":skip",
"]",
"git_args",
"=",
"[",
"'log'",
",",
"\"-n#{options[:tail]}\"",
",",
"\"--format=\\\"#{options[:full_hashes] ? Commit::LOG_FORMAT_LONG : Commit::LOG_FORMAT}\\\"\"",
"# double-quotes are Windows friendly",
"]",
"git_args",
"<<",
"\"--skip #{skip}\"",
"if",
"skip",
"git_args",
"<<",
"\"--merges\"",
"if",
"options",
"[",
":merges",
"]",
"git_args",
"<<",
"\"--no-merges\"",
"if",
"options",
"[",
":no_merges",
"]",
"git_args",
"<<",
"revision",
"if",
"revision",
"git_output",
"(",
"git_args",
")",
".",
"lines",
".",
"map",
"{",
"|",
"line",
"|",
"Commit",
".",
"new",
"(",
"self",
",",
"line",
".",
"strip",
")",
"}",
"end"
] | Generates a list of commits using the given 'git log' arguments.
@param [String] revision to log or nil
@param [Hash] options for log
@option options [Integer] :skip as lines of most recent history to skip (Default = include most recent)
@option options [Integer] :tail as max history of log
@option options [TrueClass|FalseClass] :merges as true to exclude non-merge commits
@option options [TrueClass|FalseClass] :no_merges as true to exclude merge commits
@option options [TrueClass|FalseClass] :full_hashes as true show full hashes, false for (7-character) abbreviations
@return [Array] list of commits | [
"Generates",
"a",
"list",
"of",
"commits",
"using",
"the",
"given",
"git",
"log",
"arguments",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L180-L199 |
23,686 | rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.clean_all | def clean_all(options = {})
options = {
:directories => false,
:gitignored => false,
:submodules => false,
}.merge(options)
git_args = ['-f'] # force is required or else -n only lists files.
git_args << '-f' if options[:submodules] # double-tap -f to kill untracked submodules
git_args << '-d' if options[:directories]
git_args << '-x' if options[:gitignored]
clean(git_args)
true
end | ruby | def clean_all(options = {})
options = {
:directories => false,
:gitignored => false,
:submodules => false,
}.merge(options)
git_args = ['-f'] # force is required or else -n only lists files.
git_args << '-f' if options[:submodules] # double-tap -f to kill untracked submodules
git_args << '-d' if options[:directories]
git_args << '-x' if options[:gitignored]
clean(git_args)
true
end | [
"def",
"clean_all",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":directories",
"=>",
"false",
",",
":gitignored",
"=>",
"false",
",",
":submodules",
"=>",
"false",
",",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'-f'",
"]",
"# force is required or else -n only lists files.",
"git_args",
"<<",
"'-f'",
"if",
"options",
"[",
":submodules",
"]",
"# double-tap -f to kill untracked submodules",
"git_args",
"<<",
"'-d'",
"if",
"options",
"[",
":directories",
"]",
"git_args",
"<<",
"'-x'",
"if",
"options",
"[",
":gitignored",
"]",
"clean",
"(",
"git_args",
")",
"true",
"end"
] | Cleans everything and optionally cleans .gitignored files.
@param [Hash] options for checkout
@option options [TrueClass|FalseClass] :directories as true to clean untracked directories (but not untracked submodules)
@option options [TrueClass|FalseClass] :gitignored as true to clean gitignored (untracked) files
@option options [TrueClass|FalseClass] :submodules as true to clean untracked submodules (requires force)
@return [TrueClass] always true | [
"Cleans",
"everything",
"and",
"optionally",
"cleans",
".",
"gitignored",
"files",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L220-L232 |
23,687 | rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.submodule_paths | def submodule_paths(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'status']
git_args << '--recursive' if options[:recursive]
git_output(git_args).lines.map do |line|
data = line.chomp
if matched = SUBMODULE_STATUS_REGEX.match(data)
matched[3]
else
raise GitError,
"Unexpected output from submodule status: #{data.inspect}"
end
end
end | ruby | def submodule_paths(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'status']
git_args << '--recursive' if options[:recursive]
git_output(git_args).lines.map do |line|
data = line.chomp
if matched = SUBMODULE_STATUS_REGEX.match(data)
matched[3]
else
raise GitError,
"Unexpected output from submodule status: #{data.inspect}"
end
end
end | [
"def",
"submodule_paths",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":recursive",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'submodule'",
",",
"'status'",
"]",
"git_args",
"<<",
"'--recursive'",
"if",
"options",
"[",
":recursive",
"]",
"git_output",
"(",
"git_args",
")",
".",
"lines",
".",
"map",
"do",
"|",
"line",
"|",
"data",
"=",
"line",
".",
"chomp",
"if",
"matched",
"=",
"SUBMODULE_STATUS_REGEX",
".",
"match",
"(",
"data",
")",
"matched",
"[",
"3",
"]",
"else",
"raise",
"GitError",
",",
"\"Unexpected output from submodule status: #{data.inspect}\"",
"end",
"end",
"end"
] | Queries the recursive list of submodule paths for the current workspace.
@param [Hash] options for submodules
@option options [TrueClass|FalseClass] :recursive as true to recursively get submodule paths
@return [Array] list of submodule paths or empty | [
"Queries",
"the",
"recursive",
"list",
"of",
"submodule",
"paths",
"for",
"the",
"current",
"workspace",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L270-L285 |
23,688 | rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.update_submodules | def update_submodules(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'update', '--init']
git_args << '--recursive' if options[:recursive]
spit_output(git_args)
true
end | ruby | def update_submodules(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'update', '--init']
git_args << '--recursive' if options[:recursive]
spit_output(git_args)
true
end | [
"def",
"update_submodules",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":recursive",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'submodule'",
",",
"'update'",
",",
"'--init'",
"]",
"git_args",
"<<",
"'--recursive'",
"if",
"options",
"[",
":recursive",
"]",
"spit_output",
"(",
"git_args",
")",
"true",
"end"
] | Updates submodules for the current workspace.
@param [Hash] options for submodules
@option options [TrueClass|FalseClass] :recursive as true to recursively update submodules
@return [TrueClass] always true | [
"Updates",
"submodules",
"for",
"the",
"current",
"workspace",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L293-L301 |
23,689 | rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.sha_for | def sha_for(revision)
# note that 'git show-ref' produces easier-to-parse output but it matches
# both local and remote branch to a simple branch name whereas 'git show'
# matches at-most-one and requires origin/ for remote branches.
git_args = ['show', revision].compact
result = nil
git_output(git_args).lines.each do |line|
if matched = COMMIT_SHA1_REGEX.match(line.strip)
result = matched[1]
break
end
end
unless result
raise GitError, 'Unable to locate commit in show output.'
end
result
end | ruby | def sha_for(revision)
# note that 'git show-ref' produces easier-to-parse output but it matches
# both local and remote branch to a simple branch name whereas 'git show'
# matches at-most-one and requires origin/ for remote branches.
git_args = ['show', revision].compact
result = nil
git_output(git_args).lines.each do |line|
if matched = COMMIT_SHA1_REGEX.match(line.strip)
result = matched[1]
break
end
end
unless result
raise GitError, 'Unable to locate commit in show output.'
end
result
end | [
"def",
"sha_for",
"(",
"revision",
")",
"# note that 'git show-ref' produces easier-to-parse output but it matches",
"# both local and remote branch to a simple branch name whereas 'git show'",
"# matches at-most-one and requires origin/ for remote branches.",
"git_args",
"=",
"[",
"'show'",
",",
"revision",
"]",
".",
"compact",
"result",
"=",
"nil",
"git_output",
"(",
"git_args",
")",
".",
"lines",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"matched",
"=",
"COMMIT_SHA1_REGEX",
".",
"match",
"(",
"line",
".",
"strip",
")",
"result",
"=",
"matched",
"[",
"1",
"]",
"break",
"end",
"end",
"unless",
"result",
"raise",
"GitError",
",",
"'Unable to locate commit in show output.'",
"end",
"result",
"end"
] | Determines the SHA referenced by the given revision. Raises on failure.
@param [String] revision or nil for current SHA
@return [String] SHA for revision | [
"Determines",
"the",
"SHA",
"referenced",
"by",
"the",
"given",
"revision",
".",
"Raises",
"on",
"failure",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L308-L324 |
23,690 | rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.vet_output | def vet_output(*args)
last_output = git_output(*args).strip
logger.info(last_output) unless last_output.empty?
if last_output.downcase =~ /^(error|fatal):/
raise GitError, "Git exited zero but an error was detected in output."
end
true
end | ruby | def vet_output(*args)
last_output = git_output(*args).strip
logger.info(last_output) unless last_output.empty?
if last_output.downcase =~ /^(error|fatal):/
raise GitError, "Git exited zero but an error was detected in output."
end
true
end | [
"def",
"vet_output",
"(",
"*",
"args",
")",
"last_output",
"=",
"git_output",
"(",
"args",
")",
".",
"strip",
"logger",
".",
"info",
"(",
"last_output",
")",
"unless",
"last_output",
".",
"empty?",
"if",
"last_output",
".",
"downcase",
"=~",
"/",
"/",
"raise",
"GitError",
",",
"\"Git exited zero but an error was detected in output.\"",
"end",
"true",
"end"
] | msysgit on Windows exits zero even when checkout|reset|fetch fails so we
need to scan the output for error or fatal messages. it does no harm to do
the same on Linux even though the exit code works properly there.
@param [String|Array] args to execute
@return [TrueClass] always true | [
"msysgit",
"on",
"Windows",
"exits",
"zero",
"even",
"when",
"checkout|reset|fetch",
"fails",
"so",
"we",
"need",
"to",
"scan",
"the",
"output",
"for",
"error",
"or",
"fatal",
"messages",
".",
"it",
"does",
"no",
"harm",
"to",
"do",
"the",
"same",
"on",
"Linux",
"even",
"though",
"the",
"exit",
"code",
"works",
"properly",
"there",
"."
] | 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L351-L358 |
23,691 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.end | def end(resource)
@logger.operation(:metadata_parsing) do
if @read_blk
metadata = ::JSON.parse(@read_blk.call)
resource.metadata = metadata
# check for undefined cookbook name.
#
# note that many specs in right_scraper use badly formed metadata
# that is not even a hash so, to avoid having to fix all of them
# (and also in case the user's metadata.json is not a hash) check
# for the has_key? method.
#
# if real metadata is not a hash then that should cause failure
# at a higher level. if the cookbook name is actually defined as
# being 'undefined' then the user gets a warning anyway.
if (metadata.respond_to?(:has_key?) &&
metadata['name'] == UNDEFINED_COOKBOOK_NAME)
message =
'Cookbook name appears to be undefined and has been' +
' supplied automatically.'
@logger.note_warning(message)
end
else
# should not be scanning at all unless one of the metadata files was
# detected before starting scan.
fail 'Unexpected missing metadata'
end
end
true
ensure
@read_blk = nil
@cookbook = nil
end | ruby | def end(resource)
@logger.operation(:metadata_parsing) do
if @read_blk
metadata = ::JSON.parse(@read_blk.call)
resource.metadata = metadata
# check for undefined cookbook name.
#
# note that many specs in right_scraper use badly formed metadata
# that is not even a hash so, to avoid having to fix all of them
# (and also in case the user's metadata.json is not a hash) check
# for the has_key? method.
#
# if real metadata is not a hash then that should cause failure
# at a higher level. if the cookbook name is actually defined as
# being 'undefined' then the user gets a warning anyway.
if (metadata.respond_to?(:has_key?) &&
metadata['name'] == UNDEFINED_COOKBOOK_NAME)
message =
'Cookbook name appears to be undefined and has been' +
' supplied automatically.'
@logger.note_warning(message)
end
else
# should not be scanning at all unless one of the metadata files was
# detected before starting scan.
fail 'Unexpected missing metadata'
end
end
true
ensure
@read_blk = nil
@cookbook = nil
end | [
"def",
"end",
"(",
"resource",
")",
"@logger",
".",
"operation",
"(",
":metadata_parsing",
")",
"do",
"if",
"@read_blk",
"metadata",
"=",
"::",
"JSON",
".",
"parse",
"(",
"@read_blk",
".",
"call",
")",
"resource",
".",
"metadata",
"=",
"metadata",
"# check for undefined cookbook name.",
"#",
"# note that many specs in right_scraper use badly formed metadata",
"# that is not even a hash so, to avoid having to fix all of them",
"# (and also in case the user's metadata.json is not a hash) check",
"# for the has_key? method.",
"#",
"# if real metadata is not a hash then that should cause failure",
"# at a higher level. if the cookbook name is actually defined as",
"# being 'undefined' then the user gets a warning anyway.",
"if",
"(",
"metadata",
".",
"respond_to?",
"(",
":has_key?",
")",
"&&",
"metadata",
"[",
"'name'",
"]",
"==",
"UNDEFINED_COOKBOOK_NAME",
")",
"message",
"=",
"'Cookbook name appears to be undefined and has been'",
"+",
"' supplied automatically.'",
"@logger",
".",
"note_warning",
"(",
"message",
")",
"end",
"else",
"# should not be scanning at all unless one of the metadata files was",
"# detected before starting scan.",
"fail",
"'Unexpected missing metadata'",
"end",
"end",
"true",
"ensure",
"@read_blk",
"=",
"nil",
"@cookbook",
"=",
"nil",
"end"
] | Complete a scan for the given resource.
=== Parameters ===
resource(RightScraper::Resources::Base):: resource to scan | [
"Complete",
"a",
"scan",
"for",
"the",
"given",
"resource",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L83-L116 |
23,692 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.finish | def finish
begin
::FileUtils.remove_entry_secure(tls[:tmpdir]) if tls[:tmpdir]
rescue ::Exception => e
@logger.note_warning(e.message)
end
ensure
# Cleanup thread-local storage
tls.clear
end | ruby | def finish
begin
::FileUtils.remove_entry_secure(tls[:tmpdir]) if tls[:tmpdir]
rescue ::Exception => e
@logger.note_warning(e.message)
end
ensure
# Cleanup thread-local storage
tls.clear
end | [
"def",
"finish",
"begin",
"::",
"FileUtils",
".",
"remove_entry_secure",
"(",
"tls",
"[",
":tmpdir",
"]",
")",
"if",
"tls",
"[",
":tmpdir",
"]",
"rescue",
"::",
"Exception",
"=>",
"e",
"@logger",
".",
"note_warning",
"(",
"e",
".",
"message",
")",
"end",
"ensure",
"# Cleanup thread-local storage",
"tls",
".",
"clear",
"end"
] | All done scanning this repository. | [
"All",
"done",
"scanning",
"this",
"repository",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L120-L129 |
23,693 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.generate_metadata_json | def generate_metadata_json
@logger.operation(:metadata_generation) do
# note we will use the same tmpdir path inside and outside the
# container only because it is non-trivial to invoke mktmpdir inside
# the container.
tmpdir, created = create_tmpdir
# path constants
src_knife_script_path = ::File.expand_path(
::File.join(__FILE__, '../../../../scripts', KNIFE_METADATA_SCRIPT_NAME))
dst_knife_script_dir = tmpdir
dst_knife_script_path = ::File.join(dst_knife_script_dir, KNIFE_METADATA_SCRIPT_NAME)
jailed_repo_dir = ::File.join(tmpdir, UNDEFINED_COOKBOOK_NAME)
jailed_cookbook_dir = (@cookbook.pos == '.' && jailed_repo_dir) || ::File.join(jailed_repo_dir, @cookbook.pos)
jailed_metadata_json_path = ::File.join(jailed_cookbook_dir, JSON_METADATA)
freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos)
freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA)
# in the multi-pass case we will run this scanner only on the first pass
# so the 'metadata.json' file should not exist. the read-only scanner,
# which is safe outside of containment, should be used subsequently.
# the entire 'freed' directory should have been removed upon the next
# successful retrieval so that this scanner will succeed.
if ::File.file?(freed_metadata_json_path)
raise MetadataError, "Refused to overwrite already-generated metadata file: #{freed_metadata_json_path}"
end
# jail the repo using the legacy semantics for copying files in and out
# of jail.
copy_out = { jailed_metadata_json_path => freed_metadata_json_path }
# copy files into the jail once per repository (i.e. not once per
# cookbook within the repository).
if created
copy_in = generate_copy_in(@cookbook.repo_dir, jailed_repo_dir)
copy_in[src_knife_script_path] = dst_knife_script_path
# note that at this point we previously used Warden as a container
# for the copied-in files but now we assume that the current process
# is already in a container (i.e. Docker) and so this copying is
# more about creating a writable directory for knife than about
# containment. the checked-out repo should be read-only to this
# contained process due to running with limited privileges.
do_copy_in(copy_in)
end
# HACK: support ad-hoc testing in dev-mode by using the current version
# for rbenv shell.
if ::ENV['RBENV_VERSION'].to_s.empty?
ruby = 'ruby'
else
ruby = `which ruby`.chomp
end
# execute knife as a child process. any constraints are assumed to be
# imposed on the current process by a container (timeout, memory, etc.)
shell = ::RightGit::Shell::Default
output = StringIO.new
begin
shell.execute(
"#{ruby} #{dst_knife_script_path.inspect} #{jailed_cookbook_dir.inspect} 2>&1",
directory: dst_knife_script_dir,
outstream: output,
raise_on_failure: true,
set_env_vars: { LC_ALL: 'en_US.UTF-8' }, # character encoding for emitted JSON
clear_env_vars: %w{BUNDLE_BIN_PATH BUNDLE_GEMFILE},
timeout: KNIFE_METADATA_TIMEOUT)
output = output.string
rescue ::RightGit::Shell::ShellError => e
output = output.string
raise MetadataError, "Failed to run chef knife: #{e.message}\n#{output[0, 1024]}"
end
# free files from jail.
do_copy_out(copy_out)
# load and return freed metadata.
return ::File.read(freed_metadata_json_path)
end
end | ruby | def generate_metadata_json
@logger.operation(:metadata_generation) do
# note we will use the same tmpdir path inside and outside the
# container only because it is non-trivial to invoke mktmpdir inside
# the container.
tmpdir, created = create_tmpdir
# path constants
src_knife_script_path = ::File.expand_path(
::File.join(__FILE__, '../../../../scripts', KNIFE_METADATA_SCRIPT_NAME))
dst_knife_script_dir = tmpdir
dst_knife_script_path = ::File.join(dst_knife_script_dir, KNIFE_METADATA_SCRIPT_NAME)
jailed_repo_dir = ::File.join(tmpdir, UNDEFINED_COOKBOOK_NAME)
jailed_cookbook_dir = (@cookbook.pos == '.' && jailed_repo_dir) || ::File.join(jailed_repo_dir, @cookbook.pos)
jailed_metadata_json_path = ::File.join(jailed_cookbook_dir, JSON_METADATA)
freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos)
freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA)
# in the multi-pass case we will run this scanner only on the first pass
# so the 'metadata.json' file should not exist. the read-only scanner,
# which is safe outside of containment, should be used subsequently.
# the entire 'freed' directory should have been removed upon the next
# successful retrieval so that this scanner will succeed.
if ::File.file?(freed_metadata_json_path)
raise MetadataError, "Refused to overwrite already-generated metadata file: #{freed_metadata_json_path}"
end
# jail the repo using the legacy semantics for copying files in and out
# of jail.
copy_out = { jailed_metadata_json_path => freed_metadata_json_path }
# copy files into the jail once per repository (i.e. not once per
# cookbook within the repository).
if created
copy_in = generate_copy_in(@cookbook.repo_dir, jailed_repo_dir)
copy_in[src_knife_script_path] = dst_knife_script_path
# note that at this point we previously used Warden as a container
# for the copied-in files but now we assume that the current process
# is already in a container (i.e. Docker) and so this copying is
# more about creating a writable directory for knife than about
# containment. the checked-out repo should be read-only to this
# contained process due to running with limited privileges.
do_copy_in(copy_in)
end
# HACK: support ad-hoc testing in dev-mode by using the current version
# for rbenv shell.
if ::ENV['RBENV_VERSION'].to_s.empty?
ruby = 'ruby'
else
ruby = `which ruby`.chomp
end
# execute knife as a child process. any constraints are assumed to be
# imposed on the current process by a container (timeout, memory, etc.)
shell = ::RightGit::Shell::Default
output = StringIO.new
begin
shell.execute(
"#{ruby} #{dst_knife_script_path.inspect} #{jailed_cookbook_dir.inspect} 2>&1",
directory: dst_knife_script_dir,
outstream: output,
raise_on_failure: true,
set_env_vars: { LC_ALL: 'en_US.UTF-8' }, # character encoding for emitted JSON
clear_env_vars: %w{BUNDLE_BIN_PATH BUNDLE_GEMFILE},
timeout: KNIFE_METADATA_TIMEOUT)
output = output.string
rescue ::RightGit::Shell::ShellError => e
output = output.string
raise MetadataError, "Failed to run chef knife: #{e.message}\n#{output[0, 1024]}"
end
# free files from jail.
do_copy_out(copy_out)
# load and return freed metadata.
return ::File.read(freed_metadata_json_path)
end
end | [
"def",
"generate_metadata_json",
"@logger",
".",
"operation",
"(",
":metadata_generation",
")",
"do",
"# note we will use the same tmpdir path inside and outside the",
"# container only because it is non-trivial to invoke mktmpdir inside",
"# the container.",
"tmpdir",
",",
"created",
"=",
"create_tmpdir",
"# path constants",
"src_knife_script_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"::",
"File",
".",
"join",
"(",
"__FILE__",
",",
"'../../../../scripts'",
",",
"KNIFE_METADATA_SCRIPT_NAME",
")",
")",
"dst_knife_script_dir",
"=",
"tmpdir",
"dst_knife_script_path",
"=",
"::",
"File",
".",
"join",
"(",
"dst_knife_script_dir",
",",
"KNIFE_METADATA_SCRIPT_NAME",
")",
"jailed_repo_dir",
"=",
"::",
"File",
".",
"join",
"(",
"tmpdir",
",",
"UNDEFINED_COOKBOOK_NAME",
")",
"jailed_cookbook_dir",
"=",
"(",
"@cookbook",
".",
"pos",
"==",
"'.'",
"&&",
"jailed_repo_dir",
")",
"||",
"::",
"File",
".",
"join",
"(",
"jailed_repo_dir",
",",
"@cookbook",
".",
"pos",
")",
"jailed_metadata_json_path",
"=",
"::",
"File",
".",
"join",
"(",
"jailed_cookbook_dir",
",",
"JSON_METADATA",
")",
"freed_metadata_dir",
"=",
"(",
"@cookbook",
".",
"pos",
"==",
"'.'",
"&&",
"freed_dir",
")",
"||",
"::",
"File",
".",
"join",
"(",
"freed_dir",
",",
"@cookbook",
".",
"pos",
")",
"freed_metadata_json_path",
"=",
"::",
"File",
".",
"join",
"(",
"freed_metadata_dir",
",",
"JSON_METADATA",
")",
"# in the multi-pass case we will run this scanner only on the first pass",
"# so the 'metadata.json' file should not exist. the read-only scanner,",
"# which is safe outside of containment, should be used subsequently.",
"# the entire 'freed' directory should have been removed upon the next",
"# successful retrieval so that this scanner will succeed.",
"if",
"::",
"File",
".",
"file?",
"(",
"freed_metadata_json_path",
")",
"raise",
"MetadataError",
",",
"\"Refused to overwrite already-generated metadata file: #{freed_metadata_json_path}\"",
"end",
"# jail the repo using the legacy semantics for copying files in and out",
"# of jail.",
"copy_out",
"=",
"{",
"jailed_metadata_json_path",
"=>",
"freed_metadata_json_path",
"}",
"# copy files into the jail once per repository (i.e. not once per",
"# cookbook within the repository).",
"if",
"created",
"copy_in",
"=",
"generate_copy_in",
"(",
"@cookbook",
".",
"repo_dir",
",",
"jailed_repo_dir",
")",
"copy_in",
"[",
"src_knife_script_path",
"]",
"=",
"dst_knife_script_path",
"# note that at this point we previously used Warden as a container",
"# for the copied-in files but now we assume that the current process",
"# is already in a container (i.e. Docker) and so this copying is",
"# more about creating a writable directory for knife than about",
"# containment. the checked-out repo should be read-only to this",
"# contained process due to running with limited privileges.",
"do_copy_in",
"(",
"copy_in",
")",
"end",
"# HACK: support ad-hoc testing in dev-mode by using the current version",
"# for rbenv shell.",
"if",
"::",
"ENV",
"[",
"'RBENV_VERSION'",
"]",
".",
"to_s",
".",
"empty?",
"ruby",
"=",
"'ruby'",
"else",
"ruby",
"=",
"`",
"`",
".",
"chomp",
"end",
"# execute knife as a child process. any constraints are assumed to be",
"# imposed on the current process by a container (timeout, memory, etc.)",
"shell",
"=",
"::",
"RightGit",
"::",
"Shell",
"::",
"Default",
"output",
"=",
"StringIO",
".",
"new",
"begin",
"shell",
".",
"execute",
"(",
"\"#{ruby} #{dst_knife_script_path.inspect} #{jailed_cookbook_dir.inspect} 2>&1\"",
",",
"directory",
":",
"dst_knife_script_dir",
",",
"outstream",
":",
"output",
",",
"raise_on_failure",
":",
"true",
",",
"set_env_vars",
":",
"{",
"LC_ALL",
":",
"'en_US.UTF-8'",
"}",
",",
"# character encoding for emitted JSON",
"clear_env_vars",
":",
"%w{",
"BUNDLE_BIN_PATH",
"BUNDLE_GEMFILE",
"}",
",",
"timeout",
":",
"KNIFE_METADATA_TIMEOUT",
")",
"output",
"=",
"output",
".",
"string",
"rescue",
"::",
"RightGit",
"::",
"Shell",
"::",
"ShellError",
"=>",
"e",
"output",
"=",
"output",
".",
"string",
"raise",
"MetadataError",
",",
"\"Failed to run chef knife: #{e.message}\\n#{output[0, 1024]}\"",
"end",
"# free files from jail.",
"do_copy_out",
"(",
"copy_out",
")",
"# load and return freed metadata.",
"return",
"::",
"File",
".",
"read",
"(",
"freed_metadata_json_path",
")",
"end",
"end"
] | Executes the 'metadata.rb' file from a cookbook. Because we don't want
to evaluate arbitrary Ruby code, we need to sandbox it first.
in order for knife metadata to succeed in the general case we need to
copy some (but not all) of the cookbook directory AND its ancestors (if
any) into the container. we will try and restrict copying to what might
plausibly be referenced by 'metadata.rb' but this could be anything like
a LICENSE, README, etc. the best heuristic seems to be to copy any file
whose size is small (less than 128K) because 'metadata.rb' should not be
executing binaries and should only consume text files of a reasonable
size. if these restrictions cause a problem then the user is free to
pre-knife his own 'metadata.json' file and check it into the repo.
note the selection of the jailed cookbook dir is specific to the
behavior of knife metadata. the cookbook name is defined when the
'metadata.rb' declares the name attribute, but the name attribute is
optional. when no name attribute is declared, the metadata automagically
uses the parent directory name. this works okay so long as the parent
directory name is actually the cookbook name. in the case of a repo with
'metadata.rb' at the root (i.e. no checked-in parent directory) then the
cookbook name is undefined. in this case, we want the cookbook name to
be 'undefined' to remind the user to declare the name explicitly.
=== Returns
@return [String] metadata JSON text | [
"Executes",
"the",
"metadata",
".",
"rb",
"file",
"from",
"a",
"cookbook",
".",
"Because",
"we",
"don",
"t",
"want",
"to",
"evaluate",
"arbitrary",
"Ruby",
"code",
"we",
"need",
"to",
"sandbox",
"it",
"first",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L192-L271 |
23,694 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.do_copy_in | def do_copy_in(path_map)
path_map.each do |src_path, dst_path|
if src_path != dst_path
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
end
end
true
end | ruby | def do_copy_in(path_map)
path_map.each do |src_path, dst_path|
if src_path != dst_path
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
end
end
true
end | [
"def",
"do_copy_in",
"(",
"path_map",
")",
"path_map",
".",
"each",
"do",
"|",
"src_path",
",",
"dst_path",
"|",
"if",
"src_path",
"!=",
"dst_path",
"::",
"FileUtils",
".",
"mkdir_p",
"(",
"::",
"File",
".",
"dirname",
"(",
"dst_path",
")",
")",
"::",
"FileUtils",
".",
"cp",
"(",
"src_path",
",",
"dst_path",
")",
"end",
"end",
"true",
"end"
] | copies files into jail. we no longer start a new container so this is only
a local file copying operation. we still need files to appear in a
writable directory location because knife will write to the directory. | [
"copies",
"files",
"into",
"jail",
".",
"we",
"no",
"longer",
"start",
"a",
"new",
"container",
"so",
"this",
"is",
"only",
"a",
"local",
"file",
"copying",
"operation",
".",
"we",
"still",
"need",
"files",
"to",
"appear",
"in",
"a",
"writable",
"directory",
"location",
"because",
"knife",
"will",
"write",
"to",
"the",
"directory",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L276-L284 |
23,695 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.do_copy_out | def do_copy_out(path_map)
path_map.each do |src_path, dst_path|
# constraining the generated 'metadata.json' size is debatable, but
# our UI attempts to load metadata JSON into memory far too often to
# be blasé about generating multi-megabyte JSON files.
unless ::File.file?(src_path)
raise MetadataError, "Expected generated file was not found: #{src_path}"
end
src_size = ::File.stat(src_path).size
if src_size <= FREED_FILE_SIZE_CONSTRAINT
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
else
raise MetadataError,
"Generated file size of" +
" #{src_size / 1024} KB" +
" exceeded the allowed limit of" +
" #{FREED_FILE_SIZE_CONSTRAINT / 1024} KB"
end
end
true
end | ruby | def do_copy_out(path_map)
path_map.each do |src_path, dst_path|
# constraining the generated 'metadata.json' size is debatable, but
# our UI attempts to load metadata JSON into memory far too often to
# be blasé about generating multi-megabyte JSON files.
unless ::File.file?(src_path)
raise MetadataError, "Expected generated file was not found: #{src_path}"
end
src_size = ::File.stat(src_path).size
if src_size <= FREED_FILE_SIZE_CONSTRAINT
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
else
raise MetadataError,
"Generated file size of" +
" #{src_size / 1024} KB" +
" exceeded the allowed limit of" +
" #{FREED_FILE_SIZE_CONSTRAINT / 1024} KB"
end
end
true
end | [
"def",
"do_copy_out",
"(",
"path_map",
")",
"path_map",
".",
"each",
"do",
"|",
"src_path",
",",
"dst_path",
"|",
"# constraining the generated 'metadata.json' size is debatable, but",
"# our UI attempts to load metadata JSON into memory far too often to",
"# be blasé about generating multi-megabyte JSON files.",
"unless",
"::",
"File",
".",
"file?",
"(",
"src_path",
")",
"raise",
"MetadataError",
",",
"\"Expected generated file was not found: #{src_path}\"",
"end",
"src_size",
"=",
"::",
"File",
".",
"stat",
"(",
"src_path",
")",
".",
"size",
"if",
"src_size",
"<=",
"FREED_FILE_SIZE_CONSTRAINT",
"::",
"FileUtils",
".",
"mkdir_p",
"(",
"::",
"File",
".",
"dirname",
"(",
"dst_path",
")",
")",
"::",
"FileUtils",
".",
"cp",
"(",
"src_path",
",",
"dst_path",
")",
"else",
"raise",
"MetadataError",
",",
"\"Generated file size of\"",
"+",
"\" #{src_size / 1024} KB\"",
"+",
"\" exceeded the allowed limit of\"",
"+",
"\" #{FREED_FILE_SIZE_CONSTRAINT / 1024} KB\"",
"end",
"end",
"true",
"end"
] | copies files out of jail by mapping of jail to free path. | [
"copies",
"files",
"out",
"of",
"jail",
"by",
"mapping",
"of",
"jail",
"to",
"free",
"path",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L287-L308 |
23,696 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.generate_copy_in | def generate_copy_in(src_base_path, dst_base_path)
src_base_path = ::File.expand_path(src_base_path)
dst_base_path = ::File.expand_path(dst_base_path)
copy_in = []
recursive_generate_copy_in(copy_in, src_base_path)
src_base_path += '/'
src_base_path_len = src_base_path.length
dst_base_path += '/'
copy_in.inject({}) do |h, src_path|
h[src_path] = ::File.join(dst_base_path, src_path[src_base_path_len..-1])
h
end
end | ruby | def generate_copy_in(src_base_path, dst_base_path)
src_base_path = ::File.expand_path(src_base_path)
dst_base_path = ::File.expand_path(dst_base_path)
copy_in = []
recursive_generate_copy_in(copy_in, src_base_path)
src_base_path += '/'
src_base_path_len = src_base_path.length
dst_base_path += '/'
copy_in.inject({}) do |h, src_path|
h[src_path] = ::File.join(dst_base_path, src_path[src_base_path_len..-1])
h
end
end | [
"def",
"generate_copy_in",
"(",
"src_base_path",
",",
"dst_base_path",
")",
"src_base_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"src_base_path",
")",
"dst_base_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"dst_base_path",
")",
"copy_in",
"=",
"[",
"]",
"recursive_generate_copy_in",
"(",
"copy_in",
",",
"src_base_path",
")",
"src_base_path",
"+=",
"'/'",
"src_base_path_len",
"=",
"src_base_path",
".",
"length",
"dst_base_path",
"+=",
"'/'",
"copy_in",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"h",
",",
"src_path",
"|",
"h",
"[",
"src_path",
"]",
"=",
"::",
"File",
".",
"join",
"(",
"dst_base_path",
",",
"src_path",
"[",
"src_base_path_len",
"..",
"-",
"1",
"]",
")",
"h",
"end",
"end"
] | need to enumerate files relative to the cookbook directory because we
have no idea what the metadata script will attempt to consume from the
files available in its repository. it may even attempt to manipulate
files in the system or go out to the network, which may or may not be
allowed by the conditions of the jail.
some cookbooks (for Windows, especially) will have large binaries
included in the repository. we don't want to spend time copying these
files into jail so limit the files that metadata can reference by size.
presumably the jail would also be limiting disk space so it is important
to avoid this source of failure.
again, the user can work around these contraints by generating his own
metadata and checking it into the repository.
@return [Hash] path_map as map of source to destination file paths | [
"need",
"to",
"enumerate",
"files",
"relative",
"to",
"the",
"cookbook",
"directory",
"because",
"we",
"have",
"no",
"idea",
"what",
"the",
"metadata",
"script",
"will",
"attempt",
"to",
"consume",
"from",
"the",
"files",
"available",
"in",
"its",
"repository",
".",
"it",
"may",
"even",
"attempt",
"to",
"manipulate",
"files",
"in",
"the",
"system",
"or",
"go",
"out",
"to",
"the",
"network",
"which",
"may",
"or",
"may",
"not",
"be",
"allowed",
"by",
"the",
"conditions",
"of",
"the",
"jail",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L326-L339 |
23,697 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.recursive_generate_copy_in | def recursive_generate_copy_in(copy_in, current_path)
limited_files_of(current_path) { |file| copy_in << file }
directories_of(current_path) do |dir|
recursive_generate_copy_in(copy_in, ::File.join(dir))
end
true
end | ruby | def recursive_generate_copy_in(copy_in, current_path)
limited_files_of(current_path) { |file| copy_in << file }
directories_of(current_path) do |dir|
recursive_generate_copy_in(copy_in, ::File.join(dir))
end
true
end | [
"def",
"recursive_generate_copy_in",
"(",
"copy_in",
",",
"current_path",
")",
"limited_files_of",
"(",
"current_path",
")",
"{",
"|",
"file",
"|",
"copy_in",
"<<",
"file",
"}",
"directories_of",
"(",
"current_path",
")",
"do",
"|",
"dir",
"|",
"recursive_generate_copy_in",
"(",
"copy_in",
",",
"::",
"File",
".",
"join",
"(",
"dir",
")",
")",
"end",
"true",
"end"
] | recursive part of generate_copy_in | [
"recursive",
"part",
"of",
"generate_copy_in"
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L342-L348 |
23,698 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.limited_files_of | def limited_files_of(parent)
::Dir["#{parent}/*"].each do |item|
if ::File.file?(item)
if ::File.stat(item).size <= JAILED_FILE_SIZE_CONSTRAINT
yield item
else
if ::File.basename(item) == RUBY_METADATA
raise MetadataError,
'Metadata source file' +
" #{relative_to_repo_dir(item).inspect}" +
' in repository exceeded size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB"
else
message = 'Ignored a repository file during metadata' +
' generation due to exceeding size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB:" +
" #{relative_to_repo_dir(item).inspect}"
@logger.info(message)
end
end
end
end
end | ruby | def limited_files_of(parent)
::Dir["#{parent}/*"].each do |item|
if ::File.file?(item)
if ::File.stat(item).size <= JAILED_FILE_SIZE_CONSTRAINT
yield item
else
if ::File.basename(item) == RUBY_METADATA
raise MetadataError,
'Metadata source file' +
" #{relative_to_repo_dir(item).inspect}" +
' in repository exceeded size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB"
else
message = 'Ignored a repository file during metadata' +
' generation due to exceeding size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB:" +
" #{relative_to_repo_dir(item).inspect}"
@logger.info(message)
end
end
end
end
end | [
"def",
"limited_files_of",
"(",
"parent",
")",
"::",
"Dir",
"[",
"\"#{parent}/*\"",
"]",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"::",
"File",
".",
"file?",
"(",
"item",
")",
"if",
"::",
"File",
".",
"stat",
"(",
"item",
")",
".",
"size",
"<=",
"JAILED_FILE_SIZE_CONSTRAINT",
"yield",
"item",
"else",
"if",
"::",
"File",
".",
"basename",
"(",
"item",
")",
"==",
"RUBY_METADATA",
"raise",
"MetadataError",
",",
"'Metadata source file'",
"+",
"\" #{relative_to_repo_dir(item).inspect}\"",
"+",
"' in repository exceeded size constraint of'",
"+",
"\" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB\"",
"else",
"message",
"=",
"'Ignored a repository file during metadata'",
"+",
"' generation due to exceeding size constraint of'",
"+",
"\" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB:\"",
"+",
"\" #{relative_to_repo_dir(item).inspect}\"",
"@logger",
".",
"info",
"(",
"message",
")",
"end",
"end",
"end",
"end",
"end"
] | yields files in parent meeting size criteria. | [
"yields",
"files",
"in",
"parent",
"meeting",
"size",
"criteria",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L351-L373 |
23,699 | rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.directories_of | def directories_of(parent)
::Dir["#{parent}/*"].each do |item|
case item
when '.', '..'
# do nothing
else
yield item if ::File.directory?(item)
end
end
end | ruby | def directories_of(parent)
::Dir["#{parent}/*"].each do |item|
case item
when '.', '..'
# do nothing
else
yield item if ::File.directory?(item)
end
end
end | [
"def",
"directories_of",
"(",
"parent",
")",
"::",
"Dir",
"[",
"\"#{parent}/*\"",
"]",
".",
"each",
"do",
"|",
"item",
"|",
"case",
"item",
"when",
"'.'",
",",
"'..'",
"# do nothing",
"else",
"yield",
"item",
"if",
"::",
"File",
".",
"directory?",
"(",
"item",
")",
"end",
"end",
"end"
] | yields directories of parent. | [
"yields",
"directories",
"of",
"parent",
"."
] | 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L376-L385 |
Subsets and Splits