repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
kayagoban/echochamber | lib/echochamber/library_documents/client.rb | Echochamber.Client.library_combined_document | def library_combined_document(library_document_id, file_path=nil, auditReport=false)
response = Echochamber::Request.library_combined_document(token, library_document_id, auditReport)
unless file_path.nil?
file = File.new(file_path, 'wb')
file.write(response)
file.close
end
response
end | ruby | def library_combined_document(library_document_id, file_path=nil, auditReport=false)
response = Echochamber::Request.library_combined_document(token, library_document_id, auditReport)
unless file_path.nil?
file = File.new(file_path, 'wb')
file.write(response)
file.close
end
response
end | [
"def",
"library_combined_document",
"(",
"library_document_id",
",",
"file_path",
"=",
"nil",
",",
"auditReport",
"=",
"false",
")",
"response",
"=",
"Echochamber",
"::",
"Request",
".",
"library_combined_document",
"(",
"token",
",",
"library_document_id",
",",
"auditReport",
")",
"unless",
"file_path",
".",
"nil?",
"file",
"=",
"File",
".",
"new",
"(",
"file_path",
",",
"'wb'",
")",
"file",
".",
"write",
"(",
"response",
")",
"file",
".",
"close",
"end",
"response",
"end"
] | Retrieves library combined document file
@param library_document_id (REQUIRED)
@param file_path [String] File path for saving the document. If none is given, nothing will be saved to disk.
@param auditReport [Boolean] When set to YES attach an audit report to the library document PDF. Default value will be false.
@return [String] Raw library combined document file data | [
"Retrieves",
"library",
"combined",
"document",
"file"
] | a3665c6b78928e3efa7ba578b899c31aa5c893a4 | https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/library_documents/client.rb#L67-L75 | train |
bih/userq | lib/userq.rb | UserQ.Queue.enter_into_queue? | def enter_into_queue? # Check if enough space in queue
current_limit = queue_constraints[:capacity].to_i
current_usage = queue_constraints[:taken].to_i + UserQ::UserQueue.count_unexpired(queue_constraints[:context])
# Assess whether enough space left into queue
current_usage < current_limit
end | ruby | def enter_into_queue? # Check if enough space in queue
current_limit = queue_constraints[:capacity].to_i
current_usage = queue_constraints[:taken].to_i + UserQ::UserQueue.count_unexpired(queue_constraints[:context])
# Assess whether enough space left into queue
current_usage < current_limit
end | [
"def",
"enter_into_queue?",
"current_limit",
"=",
"queue_constraints",
"[",
":capacity",
"]",
".",
"to_i",
"current_usage",
"=",
"queue_constraints",
"[",
":taken",
"]",
".",
"to_i",
"+",
"UserQ",
"::",
"UserQueue",
".",
"count_unexpired",
"(",
"queue_constraints",
"[",
":context",
"]",
")",
"current_usage",
"<",
"current_limit",
"end"
] | Beautiful syntax. | [
"Beautiful",
"syntax",
"."
] | 0f7ebb8f789fdcd7c148b7984cb23fddc502167b | https://github.com/bih/userq/blob/0f7ebb8f789fdcd7c148b7984cb23fddc502167b/lib/userq.rb#L23-L29 | train |
kany/kairos-api | lib/kairos/client.rb | Kairos.Client.gallery_list_all | def gallery_list_all
# ToDo: Research why Typhoeus works better than Faraday for this endpoint
request = Typhoeus::Request.new(
"#{Kairos::Configuration::GALLERY_LIST_ALL}",
method: :post,
headers: { "Content-Type" => "application/x-www-form-urlencoded",
"app_id" => "#{@app_id}",
"app_key" => "#{@app_key}" }
)
response = request.run
JSON.parse(response.body) rescue "INVALID_JSON: #{response.body}"
end | ruby | def gallery_list_all
# ToDo: Research why Typhoeus works better than Faraday for this endpoint
request = Typhoeus::Request.new(
"#{Kairos::Configuration::GALLERY_LIST_ALL}",
method: :post,
headers: { "Content-Type" => "application/x-www-form-urlencoded",
"app_id" => "#{@app_id}",
"app_key" => "#{@app_key}" }
)
response = request.run
JSON.parse(response.body) rescue "INVALID_JSON: #{response.body}"
end | [
"def",
"gallery_list_all",
"request",
"=",
"Typhoeus",
"::",
"Request",
".",
"new",
"(",
"\"#{Kairos::Configuration::GALLERY_LIST_ALL}\"",
",",
"method",
":",
":post",
",",
"headers",
":",
"{",
"\"Content-Type\"",
"=>",
"\"application/x-www-form-urlencoded\"",
",",
"\"app_id\"",
"=>",
"\"#{@app_id}\"",
",",
"\"app_key\"",
"=>",
"\"#{@app_key}\"",
"}",
")",
"response",
"=",
"request",
".",
"run",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"rescue",
"\"INVALID_JSON: #{response.body}\"",
"end"
] | List all Galleries
Example Usage:
- require 'kairos'
- client = Kairos::Client.new(:app_id => '1234', :app_key => 'abcde1234')
- client.gallery_list_all | [
"List",
"all",
"Galleries"
] | f44eb07cd569dbe353f55b2acbf469dbb093b98b | https://github.com/kany/kairos-api/blob/f44eb07cd569dbe353f55b2acbf469dbb093b98b/lib/kairos/client.rb#L68-L79 | train |
jasonroelofs/rbgccxml | lib/rbgccxml/query_result.rb | RbGCCXML.QueryResult.method_missing | def method_missing(name, *args)
if self[0].respond_to?(name)
self.inject(QueryResult.new) do |memo, node|
ret = node.send(name, *args)
memo << ret if ret
memo
end
else
super
end
end | ruby | def method_missing(name, *args)
if self[0].respond_to?(name)
self.inject(QueryResult.new) do |memo, node|
ret = node.send(name, *args)
memo << ret if ret
memo
end
else
super
end
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
")",
"if",
"self",
"[",
"0",
"]",
".",
"respond_to?",
"(",
"name",
")",
"self",
".",
"inject",
"(",
"QueryResult",
".",
"new",
")",
"do",
"|",
"memo",
",",
"node",
"|",
"ret",
"=",
"node",
".",
"send",
"(",
"name",
",",
"*",
"args",
")",
"memo",
"<<",
"ret",
"if",
"ret",
"memo",
"end",
"else",
"super",
"end",
"end"
] | To facilitate the management of what could be many nodes found by a single query,
we forward off any unknown methods to each node in the results query.
We assume that if one node accepts the method, then all of them will. | [
"To",
"facilitate",
"the",
"management",
"of",
"what",
"could",
"be",
"many",
"nodes",
"found",
"by",
"a",
"single",
"query",
"we",
"forward",
"off",
"any",
"unknown",
"methods",
"to",
"each",
"node",
"in",
"the",
"results",
"query",
".",
"We",
"assume",
"that",
"if",
"one",
"node",
"accepts",
"the",
"method",
"then",
"all",
"of",
"them",
"will",
"."
] | f9051f46277a6b4f580dd779012c61e482d11410 | https://github.com/jasonroelofs/rbgccxml/blob/f9051f46277a6b4f580dd779012c61e482d11410/lib/rbgccxml/query_result.rb#L10-L20 | train |
reidmorrison/sync_attr | lib/sync_attr/attributes.rb | SyncAttr.Attributes.sync_attr_sync | def sync_attr_sync(attribute, &block)
mutex_var_name = "@sync_attr_#{attribute}".to_sym
instance_variable_set(mutex_var_name, Mutex.new) unless instance_variable_defined?(mutex_var_name)
instance_variable_get(mutex_var_name).synchronize(&block)
end | ruby | def sync_attr_sync(attribute, &block)
mutex_var_name = "@sync_attr_#{attribute}".to_sym
instance_variable_set(mutex_var_name, Mutex.new) unless instance_variable_defined?(mutex_var_name)
instance_variable_get(mutex_var_name).synchronize(&block)
end | [
"def",
"sync_attr_sync",
"(",
"attribute",
",",
"&",
"block",
")",
"mutex_var_name",
"=",
"\"@sync_attr_#{attribute}\"",
".",
"to_sym",
"instance_variable_set",
"(",
"mutex_var_name",
",",
"Mutex",
".",
"new",
")",
"unless",
"instance_variable_defined?",
"(",
"mutex_var_name",
")",
"instance_variable_get",
"(",
"mutex_var_name",
")",
".",
"synchronize",
"(",
"&",
"block",
")",
"end"
] | Thread safe way of creating the instance sync | [
"Thread",
"safe",
"way",
"of",
"creating",
"the",
"instance",
"sync"
] | 08ec85c1a3048fb671b25438ccbaa018bca87937 | https://github.com/reidmorrison/sync_attr/blob/08ec85c1a3048fb671b25438ccbaa018bca87937/lib/sync_attr/attributes.rb#L91-L95 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/helpers/ec2-helper.rb | BoxGrinder.EC2Helper.wait_for_instance_death | def wait_for_instance_death(instance, opts={})
wait_for_instance_status(:terminated, instance, opts) if instance.exists?
rescue AWS::EC2::Errors::InvalidInstanceID::NotFound
end | ruby | def wait_for_instance_death(instance, opts={})
wait_for_instance_status(:terminated, instance, opts) if instance.exists?
rescue AWS::EC2::Errors::InvalidInstanceID::NotFound
end | [
"def",
"wait_for_instance_death",
"(",
"instance",
",",
"opts",
"=",
"{",
"}",
")",
"wait_for_instance_status",
"(",
":terminated",
",",
"instance",
",",
"opts",
")",
"if",
"instance",
".",
"exists?",
"rescue",
"AWS",
"::",
"EC2",
"::",
"Errors",
"::",
"InvalidInstanceID",
"::",
"NotFound",
"end"
] | Being serial shouldn't be much slower as we are blocked by the slowest stopper anyway | [
"Being",
"serial",
"shouldn",
"t",
"be",
"much",
"slower",
"as",
"we",
"are",
"blocked",
"by",
"the",
"slowest",
"stopper",
"anyway"
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/ec2-helper.rb#L57-L60 | train |
kayagoban/echochamber | lib/echochamber/widget/client.rb | Echochamber.Client.get_widget_documents | def get_widget_documents(widget_id, version_id=nil, participant_email=nil)
Echochamber::Request.get_widget_documents(token, widget_id, version_id, participant_email)
end | ruby | def get_widget_documents(widget_id, version_id=nil, participant_email=nil)
Echochamber::Request.get_widget_documents(token, widget_id, version_id, participant_email)
end | [
"def",
"get_widget_documents",
"(",
"widget_id",
",",
"version_id",
"=",
"nil",
",",
"participant_email",
"=",
"nil",
")",
"Echochamber",
"::",
"Request",
".",
"get_widget_documents",
"(",
"token",
",",
"widget_id",
",",
"version_id",
",",
"participant_email",
")",
"end"
] | Retrieves the IDs of the documents associated with widget.
@param widget_id [String]
@param version_id [String] The version identifier of widget as provided by get_widget. If not provided then latest version will be used.
@param participant_email [String] The email address of the participant to be used to retrieve documents
@return [Hash] Info about widget documents | [
"Retrieves",
"the",
"IDs",
"of",
"the",
"documents",
"associated",
"with",
"widget",
"."
] | a3665c6b78928e3efa7ba578b899c31aa5c893a4 | https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/widget/client.rb#L54-L56 | train |
kayagoban/echochamber | lib/echochamber/widget/client.rb | Echochamber.Client.get_widget_document_file | def get_widget_document_file(widget_id, document_id, file_path=nil)
response = Echochamber::Request.get_widget_document_file(token, widget_id, document_id)
unless file_path.nil?
file = File.new(file_path, 'wb')
file.write(response)
file.close
end
response
end | ruby | def get_widget_document_file(widget_id, document_id, file_path=nil)
response = Echochamber::Request.get_widget_document_file(token, widget_id, document_id)
unless file_path.nil?
file = File.new(file_path, 'wb')
file.write(response)
file.close
end
response
end | [
"def",
"get_widget_document_file",
"(",
"widget_id",
",",
"document_id",
",",
"file_path",
"=",
"nil",
")",
"response",
"=",
"Echochamber",
"::",
"Request",
".",
"get_widget_document_file",
"(",
"token",
",",
"widget_id",
",",
"document_id",
")",
"unless",
"file_path",
".",
"nil?",
"file",
"=",
"File",
".",
"new",
"(",
"file_path",
",",
"'wb'",
")",
"file",
".",
"write",
"(",
"response",
")",
"file",
".",
"close",
"end",
"response",
"end"
] | Retrieves the file stream of a document of a widget
@param widget_id [String]
@param document_id [String]
@param file_path [String] File path where to save the document. If none is given, nothing will be saved to file.
@return [String] Raw file stream | [
"Retrieves",
"the",
"file",
"stream",
"of",
"a",
"document",
"of",
"a",
"widget"
] | a3665c6b78928e3efa7ba578b899c31aa5c893a4 | https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/widget/client.rb#L64-L72 | train |
huerlisi/i18n_rails_helpers | lib/i18n_rails_helpers/controller_helpers.rb | I18nRailsHelpers.ControllerHelpers.redirect_notice | def redirect_notice(record = nil)
{ notice: I18n.t("crud.notices.#{action_name}", model: helpers.t_model,
record: record.present? ? "#{record} " : '') }
end | ruby | def redirect_notice(record = nil)
{ notice: I18n.t("crud.notices.#{action_name}", model: helpers.t_model,
record: record.present? ? "#{record} " : '') }
end | [
"def",
"redirect_notice",
"(",
"record",
"=",
"nil",
")",
"{",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"crud.notices.#{action_name}\"",
",",
"model",
":",
"helpers",
".",
"t_model",
",",
"record",
":",
"record",
".",
"present?",
"?",
"\"#{record} \"",
":",
"''",
")",
"}",
"end"
] | returns a redirect notice for create, update and destroy actions
Example in ClientsController:
redirect_to some_path, redirect_notice # => 'Klient geändert.'
redirect_to some_path, redirect_notice(@client) # => 'Klient Example Client geändert.' | [
"returns",
"a",
"redirect",
"notice",
"for",
"create",
"update",
"and",
"destroy",
"actions"
] | 4faa6d84ebb4465798246d2bb6d6e353a21d5de8 | https://github.com/huerlisi/i18n_rails_helpers/blob/4faa6d84ebb4465798246d2bb6d6e353a21d5de8/lib/i18n_rails_helpers/controller_helpers.rb#L12-L15 | train |
kwi/i18n_routing | lib/i18n_routing_rails32.rb | I18nRouting.JourneyRoute.initialize_with_i18n_routing | def initialize_with_i18n_routing(name, app, path, constraints, defaults = {})
@locale = if constraints.key?(:i18n_locale)
c = constraints.delete(:i18n_locale)
# In rails 3.0 it's a regexp otherwise it's a string, so we need to call source on the regexp
(c.respond_to?(:source) ? c.source : c).to_sym
else
nil
end
initialize_without_i18n_routing(name, app, path, constraints, defaults)
end | ruby | def initialize_with_i18n_routing(name, app, path, constraints, defaults = {})
@locale = if constraints.key?(:i18n_locale)
c = constraints.delete(:i18n_locale)
# In rails 3.0 it's a regexp otherwise it's a string, so we need to call source on the regexp
(c.respond_to?(:source) ? c.source : c).to_sym
else
nil
end
initialize_without_i18n_routing(name, app, path, constraints, defaults)
end | [
"def",
"initialize_with_i18n_routing",
"(",
"name",
",",
"app",
",",
"path",
",",
"constraints",
",",
"defaults",
"=",
"{",
"}",
")",
"@locale",
"=",
"if",
"constraints",
".",
"key?",
"(",
":i18n_locale",
")",
"c",
"=",
"constraints",
".",
"delete",
"(",
":i18n_locale",
")",
"(",
"c",
".",
"respond_to?",
"(",
":source",
")",
"?",
"c",
".",
"source",
":",
"c",
")",
".",
"to_sym",
"else",
"nil",
"end",
"initialize_without_i18n_routing",
"(",
"name",
",",
"app",
",",
"path",
",",
"constraints",
",",
"defaults",
")",
"end"
] | During route initialization, if a condition i18n_locale is present
Delete it, store it in @locale, and add it to @defaults | [
"During",
"route",
"initialization",
"if",
"a",
"condition",
"i18n_locale",
"is",
"present",
"Delete",
"it",
"store",
"it",
"in"
] | edd30ac3445b928f34a97e3762df0ded3c136230 | https://github.com/kwi/i18n_routing/blob/edd30ac3445b928f34a97e3762df0ded3c136230/lib/i18n_routing_rails32.rb#L400-L409 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/core/response.rb | Wavefront.Response.raw_response | def raw_response(json, status)
json.empty? ? {} : JSON.parse(json, symbolize_names: true)
rescue StandardError
{ message: json, code: status }
end | ruby | def raw_response(json, status)
json.empty? ? {} : JSON.parse(json, symbolize_names: true)
rescue StandardError
{ message: json, code: status }
end | [
"def",
"raw_response",
"(",
"json",
",",
"status",
")",
"json",
".",
"empty?",
"?",
"{",
"}",
":",
"JSON",
".",
"parse",
"(",
"json",
",",
"symbolize_names",
":",
"true",
")",
"rescue",
"StandardError",
"{",
"message",
":",
"json",
",",
"code",
":",
"status",
"}",
"end"
] | Turn the API's JSON response and HTTP status code into a Ruby
object.
@return [Hash] | [
"Turn",
"the",
"API",
"s",
"JSON",
"response",
"and",
"HTTP",
"status",
"code",
"into",
"a",
"Ruby",
"object",
"."
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/response.rb#L126-L130 | train |
bih/userq | lib/generators/userq/install_generator.rb | Userq.InstallGenerator.do_migration | def do_migration
migration_exists = Dir["db/migrate/*_create_user_queues.rb"].count > 0
if migration_exists and installing?
puts "UserQ is already installed. Maybe a 'rake db:migrate' command might help?"
return
end
create_migration
puts "Success! UserQ is installed. You can now use it in your application." if installing?
puts "UserQ has already been uninstalled. Remember the 'user_queue' table needs to be manually destroyed." if destroying? and migration_exists == false
puts "Success! UserQ is uninstalled. The table 'userq_queue' needs to be destroyed manually to complete removal." if destroying? and migration_exists
end | ruby | def do_migration
migration_exists = Dir["db/migrate/*_create_user_queues.rb"].count > 0
if migration_exists and installing?
puts "UserQ is already installed. Maybe a 'rake db:migrate' command might help?"
return
end
create_migration
puts "Success! UserQ is installed. You can now use it in your application." if installing?
puts "UserQ has already been uninstalled. Remember the 'user_queue' table needs to be manually destroyed." if destroying? and migration_exists == false
puts "Success! UserQ is uninstalled. The table 'userq_queue' needs to be destroyed manually to complete removal." if destroying? and migration_exists
end | [
"def",
"do_migration",
"migration_exists",
"=",
"Dir",
"[",
"\"db/migrate/*_create_user_queues.rb\"",
"]",
".",
"count",
">",
"0",
"if",
"migration_exists",
"and",
"installing?",
"puts",
"\"UserQ is already installed. Maybe a 'rake db:migrate' command might help?\"",
"return",
"end",
"create_migration",
"puts",
"\"Success! UserQ is installed. You can now use it in your application.\"",
"if",
"installing?",
"puts",
"\"UserQ has already been uninstalled. Remember the 'user_queue' table needs to be manually destroyed.\"",
"if",
"destroying?",
"and",
"migration_exists",
"==",
"false",
"puts",
"\"Success! UserQ is uninstalled. The table 'userq_queue' needs to be destroyed manually to complete removal.\"",
"if",
"destroying?",
"and",
"migration_exists",
"end"
] | Setup and create the migration | [
"Setup",
"and",
"create",
"the",
"migration"
] | 0f7ebb8f789fdcd7c148b7984cb23fddc502167b | https://github.com/bih/userq/blob/0f7ebb8f789fdcd7c148b7984cb23fddc502167b/lib/generators/userq/install_generator.rb#L6-L19 | train |
kayagoban/echochamber | lib/echochamber/client.rb | Echochamber.Client.create_user | def create_user(user)
user_response = Echochamber::Request.create_user(user, token)
user_response.fetch("userId")
end | ruby | def create_user(user)
user_response = Echochamber::Request.create_user(user, token)
user_response.fetch("userId")
end | [
"def",
"create_user",
"(",
"user",
")",
"user_response",
"=",
"Echochamber",
"::",
"Request",
".",
"create_user",
"(",
"user",
",",
"token",
")",
"user_response",
".",
"fetch",
"(",
"\"userId\"",
")",
"end"
] | Initializes the Client object
@param credentials [Echochamber::Credentials] Initialized Echochamber::Credentials
@return [Echochamber::Client] Initialized Echochamber::Client
Creates a user for the current application
@param user [Echochamber::User]
@return [String] User ID of new Echosign user | [
"Initializes",
"the",
"Client",
"object"
] | a3665c6b78928e3efa7ba578b899c31aa5c893a4 | https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/client.rb#L23-L26 | train |
kayagoban/echochamber | lib/echochamber/client.rb | Echochamber.Client.create_transient_document | def create_transient_document(file_name, mime_type, file_handle)
transient_document_response = Echochamber::Request.create_transient_document(token, file_name, file_handle, mime_type)
transient_document_response.fetch("transientDocumentId")
end | ruby | def create_transient_document(file_name, mime_type, file_handle)
transient_document_response = Echochamber::Request.create_transient_document(token, file_name, file_handle, mime_type)
transient_document_response.fetch("transientDocumentId")
end | [
"def",
"create_transient_document",
"(",
"file_name",
",",
"mime_type",
",",
"file_handle",
")",
"transient_document_response",
"=",
"Echochamber",
"::",
"Request",
".",
"create_transient_document",
"(",
"token",
",",
"file_name",
",",
"file_handle",
",",
"mime_type",
")",
"transient_document_response",
".",
"fetch",
"(",
"\"transientDocumentId\"",
")",
"end"
] | Creates a transient document for later referral
@param file_name [String]
@param mime_type [String]
@param file_handle [File]
@return [String] Transient document ID | [
"Creates",
"a",
"transient",
"document",
"for",
"later",
"referral"
] | a3665c6b78928e3efa7ba578b899c31aa5c893a4 | https://github.com/kayagoban/echochamber/blob/a3665c6b78928e3efa7ba578b899c31aa5c893a4/lib/echochamber/client.rb#L42-L45 | train |
ddnexus/irt | lib/irt/extensions/rails_server.rb | IRT.Utils.ask_run_new_file | def ask_run_new_file(new_file_path, source_path, tmp)
return if tmp && IRT.rails_server
original_ask_run_new_file(new_file_path, source_path, tmp)
end | ruby | def ask_run_new_file(new_file_path, source_path, tmp)
return if tmp && IRT.rails_server
original_ask_run_new_file(new_file_path, source_path, tmp)
end | [
"def",
"ask_run_new_file",
"(",
"new_file_path",
",",
"source_path",
",",
"tmp",
")",
"return",
"if",
"tmp",
"&&",
"IRT",
".",
"rails_server",
"original_ask_run_new_file",
"(",
"new_file_path",
",",
"source_path",
",",
"tmp",
")",
"end"
] | skips asking to run the save file if it is a tmp file in a server session
because the server is exiting so no rerun is possible | [
"skips",
"asking",
"to",
"run",
"the",
"save",
"file",
"if",
"it",
"is",
"a",
"tmp",
"file",
"in",
"a",
"server",
"session",
"because",
"the",
"server",
"is",
"exiting",
"so",
"no",
"rerun",
"is",
"possible"
] | 6d6c5a7631abd6271dcec7def982ebcfc1aaf9e0 | https://github.com/ddnexus/irt/blob/6d6c5a7631abd6271dcec7def982ebcfc1aaf9e0/lib/irt/extensions/rails_server.rb#L62-L65 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/user.rb | Wavefront.User.response_shim | def response_shim(body, status)
items = JSON.parse(body, symbolize_names: true)
{ response: { items: items,
offset: 0,
limit: items.size,
totalItems: items.size,
modeItems: false },
status: { result: status == 200 ? 'OK' : 'ERROR',
message: extract_api_message(status, items),
code: status } }.to_json
end | ruby | def response_shim(body, status)
items = JSON.parse(body, symbolize_names: true)
{ response: { items: items,
offset: 0,
limit: items.size,
totalItems: items.size,
modeItems: false },
status: { result: status == 200 ? 'OK' : 'ERROR',
message: extract_api_message(status, items),
code: status } }.to_json
end | [
"def",
"response_shim",
"(",
"body",
",",
"status",
")",
"items",
"=",
"JSON",
".",
"parse",
"(",
"body",
",",
"symbolize_names",
":",
"true",
")",
"{",
"response",
":",
"{",
"items",
":",
"items",
",",
"offset",
":",
"0",
",",
"limit",
":",
"items",
".",
"size",
",",
"totalItems",
":",
"items",
".",
"size",
",",
"modeItems",
":",
"false",
"}",
",",
"status",
":",
"{",
"result",
":",
"status",
"==",
"200",
"?",
"'OK'",
":",
"'ERROR'",
",",
"message",
":",
"extract_api_message",
"(",
"status",
",",
"items",
")",
",",
"code",
":",
"status",
"}",
"}",
".",
"to_json",
"end"
] | Fake a response which looks like we get from all the other
paths. I'm expecting the user response model to be made
consistent with others in the future. | [
"Fake",
"a",
"response",
"which",
"looks",
"like",
"we",
"get",
"from",
"all",
"the",
"other",
"paths",
".",
"I",
"m",
"expecting",
"the",
"user",
"response",
"model",
"to",
"be",
"made",
"consistent",
"with",
"others",
"in",
"the",
"future",
"."
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/user.rb#L200-L211 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/helpers/aws-helper.rb | BoxGrinder.AWSHelper.parse_opts | def parse_opts(opts_in, opts_defaults)
diff_id = opts_in.keys - opts_defaults.keys
raise ArgumentError, "Unrecognised argument(s): #{diff_id.join(", ")}" if diff_id.any?
(opts_in.keys & opts_defaults.keys).each do |k|
raise ArgumentError, "Argument #{k.to_s} must not be nil" if opts_defaults[k] == nil and opts_in[k] == nil
end
(opts_defaults.keys - opts_in.keys).each do |k|
raise ArgumentError, "Argument #{k.to_s} must not be nil" if opts_defaults[k] == nil
opts_in.merge!(k => opts_defaults[k])
end
opts_in
end | ruby | def parse_opts(opts_in, opts_defaults)
diff_id = opts_in.keys - opts_defaults.keys
raise ArgumentError, "Unrecognised argument(s): #{diff_id.join(", ")}" if diff_id.any?
(opts_in.keys & opts_defaults.keys).each do |k|
raise ArgumentError, "Argument #{k.to_s} must not be nil" if opts_defaults[k] == nil and opts_in[k] == nil
end
(opts_defaults.keys - opts_in.keys).each do |k|
raise ArgumentError, "Argument #{k.to_s} must not be nil" if opts_defaults[k] == nil
opts_in.merge!(k => opts_defaults[k])
end
opts_in
end | [
"def",
"parse_opts",
"(",
"opts_in",
",",
"opts_defaults",
")",
"diff_id",
"=",
"opts_in",
".",
"keys",
"-",
"opts_defaults",
".",
"keys",
"raise",
"ArgumentError",
",",
"\"Unrecognised argument(s): #{diff_id.join(\", \")}\"",
"if",
"diff_id",
".",
"any?",
"(",
"opts_in",
".",
"keys",
"&",
"opts_defaults",
".",
"keys",
")",
".",
"each",
"do",
"|",
"k",
"|",
"raise",
"ArgumentError",
",",
"\"Argument #{k.to_s} must not be nil\"",
"if",
"opts_defaults",
"[",
"k",
"]",
"==",
"nil",
"and",
"opts_in",
"[",
"k",
"]",
"==",
"nil",
"end",
"(",
"opts_defaults",
".",
"keys",
"-",
"opts_in",
".",
"keys",
")",
".",
"each",
"do",
"|",
"k",
"|",
"raise",
"ArgumentError",
",",
"\"Argument #{k.to_s} must not be nil\"",
"if",
"opts_defaults",
"[",
"k",
"]",
"==",
"nil",
"opts_in",
".",
"merge!",
"(",
"k",
"=>",
"opts_defaults",
"[",
"k",
"]",
")",
"end",
"opts_in",
"end"
] | Setting value of a key to nil in opts_defaults forces non-nil value of key in opts_in | [
"Setting",
"value",
"of",
"a",
"key",
"to",
"nil",
"in",
"opts_defaults",
"forces",
"non",
"-",
"nil",
"value",
"of",
"key",
"in",
"opts_in"
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/aws-helper.rb#L24-L37 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb | BoxGrinder.LibvirtPlugin.determine_remotely | def determine_remotely
# Remove password field from URI, as libvirt doesn't support it directly. We can use it for passphrase if needed.
lv_uri = URI::Generic.build(:scheme => @connection_uri.scheme, :userinfo => @connection_uri.user,
:host => @connection_uri.host, :path => @connection_uri.path,
:query => @connection_uri.query)
# The authentication only pertains to libvirtd itself and _not_ the transport (e.g. SSH).
conn = Libvirt::open_auth(lv_uri.to_s, [Libvirt::CRED_AUTHNAME, Libvirt::CRED_PASSPHRASE]) do |cred|
case cred["type"]
when Libvirt::CRED_AUTHNAME
@connection_uri.user
when Libvirt::CRED_PASSPHRASE
@connection_uri.password
end
end
if dom = get_existing_domain(conn, @appliance_name)
unless @overwrite
@log.fatal("A domain already exists with the name #{@appliance_name}. Set overwrite:true to automatically destroy and undefine it.")
raise RuntimeError, "Domain '#{@appliance_name}' already exists" #Make better specific exception
end
@log.info("Undefining existing domain #{@appliance_name}")
undefine_domain(dom)
end
guest = @libvirt_capabilities.determine_capabilities(conn, @previous_plugin_info)
raise "Remote libvirt machine offered no viable guests!" if guest.nil?
xml = generate_xml(guest)
@log.info("Defining domain #{@appliance_name}")
conn.define_domain_xml(xml)
xml
ensure
if conn
conn.close unless conn.closed?
end
end | ruby | def determine_remotely
# Remove password field from URI, as libvirt doesn't support it directly. We can use it for passphrase if needed.
lv_uri = URI::Generic.build(:scheme => @connection_uri.scheme, :userinfo => @connection_uri.user,
:host => @connection_uri.host, :path => @connection_uri.path,
:query => @connection_uri.query)
# The authentication only pertains to libvirtd itself and _not_ the transport (e.g. SSH).
conn = Libvirt::open_auth(lv_uri.to_s, [Libvirt::CRED_AUTHNAME, Libvirt::CRED_PASSPHRASE]) do |cred|
case cred["type"]
when Libvirt::CRED_AUTHNAME
@connection_uri.user
when Libvirt::CRED_PASSPHRASE
@connection_uri.password
end
end
if dom = get_existing_domain(conn, @appliance_name)
unless @overwrite
@log.fatal("A domain already exists with the name #{@appliance_name}. Set overwrite:true to automatically destroy and undefine it.")
raise RuntimeError, "Domain '#{@appliance_name}' already exists" #Make better specific exception
end
@log.info("Undefining existing domain #{@appliance_name}")
undefine_domain(dom)
end
guest = @libvirt_capabilities.determine_capabilities(conn, @previous_plugin_info)
raise "Remote libvirt machine offered no viable guests!" if guest.nil?
xml = generate_xml(guest)
@log.info("Defining domain #{@appliance_name}")
conn.define_domain_xml(xml)
xml
ensure
if conn
conn.close unless conn.closed?
end
end | [
"def",
"determine_remotely",
"lv_uri",
"=",
"URI",
"::",
"Generic",
".",
"build",
"(",
":scheme",
"=>",
"@connection_uri",
".",
"scheme",
",",
":userinfo",
"=>",
"@connection_uri",
".",
"user",
",",
":host",
"=>",
"@connection_uri",
".",
"host",
",",
":path",
"=>",
"@connection_uri",
".",
"path",
",",
":query",
"=>",
"@connection_uri",
".",
"query",
")",
"conn",
"=",
"Libvirt",
"::",
"open_auth",
"(",
"lv_uri",
".",
"to_s",
",",
"[",
"Libvirt",
"::",
"CRED_AUTHNAME",
",",
"Libvirt",
"::",
"CRED_PASSPHRASE",
"]",
")",
"do",
"|",
"cred",
"|",
"case",
"cred",
"[",
"\"type\"",
"]",
"when",
"Libvirt",
"::",
"CRED_AUTHNAME",
"@connection_uri",
".",
"user",
"when",
"Libvirt",
"::",
"CRED_PASSPHRASE",
"@connection_uri",
".",
"password",
"end",
"end",
"if",
"dom",
"=",
"get_existing_domain",
"(",
"conn",
",",
"@appliance_name",
")",
"unless",
"@overwrite",
"@log",
".",
"fatal",
"(",
"\"A domain already exists with the name #{@appliance_name}. Set overwrite:true to automatically destroy and undefine it.\"",
")",
"raise",
"RuntimeError",
",",
"\"Domain '#{@appliance_name}' already exists\"",
"end",
"@log",
".",
"info",
"(",
"\"Undefining existing domain #{@appliance_name}\"",
")",
"undefine_domain",
"(",
"dom",
")",
"end",
"guest",
"=",
"@libvirt_capabilities",
".",
"determine_capabilities",
"(",
"conn",
",",
"@previous_plugin_info",
")",
"raise",
"\"Remote libvirt machine offered no viable guests!\"",
"if",
"guest",
".",
"nil?",
"xml",
"=",
"generate_xml",
"(",
"guest",
")",
"@log",
".",
"info",
"(",
"\"Defining domain #{@appliance_name}\"",
")",
"conn",
".",
"define_domain_xml",
"(",
"xml",
")",
"xml",
"ensure",
"if",
"conn",
"conn",
".",
"close",
"unless",
"conn",
".",
"closed?",
"end",
"end"
] | Interact with a libvirtd, attempt to determine optimal settings where possible.
Register the appliance as a new domain. | [
"Interact",
"with",
"a",
"libvirtd",
"attempt",
"to",
"determine",
"optimal",
"settings",
"where",
"possible",
".",
"Register",
"the",
"appliance",
"as",
"a",
"new",
"domain",
"."
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb#L160-L197 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb | BoxGrinder.LibvirtPlugin.determine_locally | def determine_locally
domain = @libvirt_capabilities.get_plugin(@previous_plugin_info).domain_rank.last
generate_xml(OpenStruct.new({
:domain_type => domain.name,
:os_type => domain.virt_rank.last,
:bus => domain.bus
}))
end | ruby | def determine_locally
domain = @libvirt_capabilities.get_plugin(@previous_plugin_info).domain_rank.last
generate_xml(OpenStruct.new({
:domain_type => domain.name,
:os_type => domain.virt_rank.last,
:bus => domain.bus
}))
end | [
"def",
"determine_locally",
"domain",
"=",
"@libvirt_capabilities",
".",
"get_plugin",
"(",
"@previous_plugin_info",
")",
".",
"domain_rank",
".",
"last",
"generate_xml",
"(",
"OpenStruct",
".",
"new",
"(",
"{",
":domain_type",
"=>",
"domain",
".",
"name",
",",
":os_type",
"=>",
"domain",
".",
"virt_rank",
".",
"last",
",",
":bus",
"=>",
"domain",
".",
"bus",
"}",
")",
")",
"end"
] | Make no external connections, just dump a basic XML skeleton and provide sensible defaults
where user provided values are not given. | [
"Make",
"no",
"external",
"connections",
"just",
"dump",
"a",
"basic",
"XML",
"skeleton",
"and",
"provide",
"sensible",
"defaults",
"where",
"user",
"provided",
"values",
"are",
"not",
"given",
"."
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb#L201-L208 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb | BoxGrinder.LibvirtPlugin.upload_image | def upload_image
uploader = SFTPHelper.new(:log => @log)
#SFTP library automagically uses keys registered with the OS first before trying a password.
uploader.connect(@image_delivery_uri.host,
(@image_delivery_uri.user || Etc.getlogin),
:password => @image_delivery_uri.password)
uploader.upload_files(@image_delivery_uri.path,
@default_permissions,
@overwrite,
File.basename(@previous_deliverables.disk) => @previous_deliverables.disk)
ensure
uploader.disconnect if uploader.connected?
end | ruby | def upload_image
uploader = SFTPHelper.new(:log => @log)
#SFTP library automagically uses keys registered with the OS first before trying a password.
uploader.connect(@image_delivery_uri.host,
(@image_delivery_uri.user || Etc.getlogin),
:password => @image_delivery_uri.password)
uploader.upload_files(@image_delivery_uri.path,
@default_permissions,
@overwrite,
File.basename(@previous_deliverables.disk) => @previous_deliverables.disk)
ensure
uploader.disconnect if uploader.connected?
end | [
"def",
"upload_image",
"uploader",
"=",
"SFTPHelper",
".",
"new",
"(",
":log",
"=>",
"@log",
")",
"uploader",
".",
"connect",
"(",
"@image_delivery_uri",
".",
"host",
",",
"(",
"@image_delivery_uri",
".",
"user",
"||",
"Etc",
".",
"getlogin",
")",
",",
":password",
"=>",
"@image_delivery_uri",
".",
"password",
")",
"uploader",
".",
"upload_files",
"(",
"@image_delivery_uri",
".",
"path",
",",
"@default_permissions",
",",
"@overwrite",
",",
"File",
".",
"basename",
"(",
"@previous_deliverables",
".",
"disk",
")",
"=>",
"@previous_deliverables",
".",
"disk",
")",
"ensure",
"uploader",
".",
"disconnect",
"if",
"uploader",
".",
"connected?",
"end"
] | Upload an image via SFTP | [
"Upload",
"an",
"image",
"via",
"SFTP"
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb#L211-L225 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb | BoxGrinder.LibvirtPlugin.build_xml | def build_xml(opts = {})
opts = {:bus => @bus, :os_type => :hvm}.merge!(opts)
builder = Builder::XmlMarkup.new(:indent => 2)
xml = builder.domain(:type => opts[:domain_type].to_s) do |domain|
domain.name(@appliance_name)
domain.description(@appliance_config.summary)
domain.memory(@appliance_config.hardware.memory * 1024) #KB
domain.vcpu(@appliance_config.hardware.cpus)
domain.os do |os|
os.type(opts[:os_type].to_s, :arch => @appliance_config.hardware.arch)
os.boot(:dev => 'hd')
end
domain.devices do |devices|
devices.disk(:type => 'file', :device => 'disk') do |disk|
disk.source(:file => "#{@libvirt_image_uri}/#{File.basename(@previous_deliverables.disk)}")
disk.target(:dev => 'hda', :bus => opts[:bus].to_s)
end
devices.interface(:type => 'network') do |interface|
interface.source(:network => @network)
interface.mac(:address => @mac) if @mac
end
devices.console(:type => 'pty') unless @noautoconsole
devices.graphics(:type => 'vnc', :port => -1) unless @novnc
end
domain.features do |features|
features.pae if @appliance_config.os.pae
end
end
@log.debug xml
# Let the user modify the XML specification to their requirements
if @script
@log.info "Attempting to run user provided script for modifying libVirt XML..."
xml = IO::popen("#{@script} --domain '#{xml}'").read
@log.debug "Response was: #{xml}"
end
xml
end | ruby | def build_xml(opts = {})
opts = {:bus => @bus, :os_type => :hvm}.merge!(opts)
builder = Builder::XmlMarkup.new(:indent => 2)
xml = builder.domain(:type => opts[:domain_type].to_s) do |domain|
domain.name(@appliance_name)
domain.description(@appliance_config.summary)
domain.memory(@appliance_config.hardware.memory * 1024) #KB
domain.vcpu(@appliance_config.hardware.cpus)
domain.os do |os|
os.type(opts[:os_type].to_s, :arch => @appliance_config.hardware.arch)
os.boot(:dev => 'hd')
end
domain.devices do |devices|
devices.disk(:type => 'file', :device => 'disk') do |disk|
disk.source(:file => "#{@libvirt_image_uri}/#{File.basename(@previous_deliverables.disk)}")
disk.target(:dev => 'hda', :bus => opts[:bus].to_s)
end
devices.interface(:type => 'network') do |interface|
interface.source(:network => @network)
interface.mac(:address => @mac) if @mac
end
devices.console(:type => 'pty') unless @noautoconsole
devices.graphics(:type => 'vnc', :port => -1) unless @novnc
end
domain.features do |features|
features.pae if @appliance_config.os.pae
end
end
@log.debug xml
# Let the user modify the XML specification to their requirements
if @script
@log.info "Attempting to run user provided script for modifying libVirt XML..."
xml = IO::popen("#{@script} --domain '#{xml}'").read
@log.debug "Response was: #{xml}"
end
xml
end | [
"def",
"build_xml",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"{",
":bus",
"=>",
"@bus",
",",
":os_type",
"=>",
":hvm",
"}",
".",
"merge!",
"(",
"opts",
")",
"builder",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":indent",
"=>",
"2",
")",
"xml",
"=",
"builder",
".",
"domain",
"(",
":type",
"=>",
"opts",
"[",
":domain_type",
"]",
".",
"to_s",
")",
"do",
"|",
"domain",
"|",
"domain",
".",
"name",
"(",
"@appliance_name",
")",
"domain",
".",
"description",
"(",
"@appliance_config",
".",
"summary",
")",
"domain",
".",
"memory",
"(",
"@appliance_config",
".",
"hardware",
".",
"memory",
"*",
"1024",
")",
"domain",
".",
"vcpu",
"(",
"@appliance_config",
".",
"hardware",
".",
"cpus",
")",
"domain",
".",
"os",
"do",
"|",
"os",
"|",
"os",
".",
"type",
"(",
"opts",
"[",
":os_type",
"]",
".",
"to_s",
",",
":arch",
"=>",
"@appliance_config",
".",
"hardware",
".",
"arch",
")",
"os",
".",
"boot",
"(",
":dev",
"=>",
"'hd'",
")",
"end",
"domain",
".",
"devices",
"do",
"|",
"devices",
"|",
"devices",
".",
"disk",
"(",
":type",
"=>",
"'file'",
",",
":device",
"=>",
"'disk'",
")",
"do",
"|",
"disk",
"|",
"disk",
".",
"source",
"(",
":file",
"=>",
"\"#{@libvirt_image_uri}/#{File.basename(@previous_deliverables.disk)}\"",
")",
"disk",
".",
"target",
"(",
":dev",
"=>",
"'hda'",
",",
":bus",
"=>",
"opts",
"[",
":bus",
"]",
".",
"to_s",
")",
"end",
"devices",
".",
"interface",
"(",
":type",
"=>",
"'network'",
")",
"do",
"|",
"interface",
"|",
"interface",
".",
"source",
"(",
":network",
"=>",
"@network",
")",
"interface",
".",
"mac",
"(",
":address",
"=>",
"@mac",
")",
"if",
"@mac",
"end",
"devices",
".",
"console",
"(",
":type",
"=>",
"'pty'",
")",
"unless",
"@noautoconsole",
"devices",
".",
"graphics",
"(",
":type",
"=>",
"'vnc'",
",",
":port",
"=>",
"-",
"1",
")",
"unless",
"@novnc",
"end",
"domain",
".",
"features",
"do",
"|",
"features",
"|",
"features",
".",
"pae",
"if",
"@appliance_config",
".",
"os",
".",
"pae",
"end",
"end",
"@log",
".",
"debug",
"xml",
"if",
"@script",
"@log",
".",
"info",
"\"Attempting to run user provided script for modifying libVirt XML...\"",
"xml",
"=",
"IO",
"::",
"popen",
"(",
"\"#{@script} --domain '#{xml}'\"",
")",
".",
"read",
"@log",
".",
"debug",
"\"Response was: #{xml}\"",
"end",
"xml",
"end"
] | Build the XML domain definition. If the user provides a script, it will be called after
the basic definition has been constructed with the XML as the sole parameter. The output
from stdout of the script will be used as the new domain definition. | [
"Build",
"the",
"XML",
"domain",
"definition",
".",
"If",
"the",
"user",
"provides",
"a",
"script",
"it",
"will",
"be",
"called",
"after",
"the",
"basic",
"definition",
"has",
"been",
"constructed",
"with",
"the",
"XML",
"as",
"the",
"sole",
"parameter",
".",
"The",
"output",
"from",
"stdout",
"of",
"the",
"script",
"will",
"be",
"used",
"as",
"the",
"new",
"domain",
"definition",
"."
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb#L237-L276 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb | BoxGrinder.LibvirtPlugin.get_existing_domain | def get_existing_domain(conn, name)
return conn.lookup_domain_by_name(name)
rescue Libvirt::Error => e
return nil if e.libvirt_code == 42 # If domain not defined
raise # Otherwise reraise
end | ruby | def get_existing_domain(conn, name)
return conn.lookup_domain_by_name(name)
rescue Libvirt::Error => e
return nil if e.libvirt_code == 42 # If domain not defined
raise # Otherwise reraise
end | [
"def",
"get_existing_domain",
"(",
"conn",
",",
"name",
")",
"return",
"conn",
".",
"lookup_domain_by_name",
"(",
"name",
")",
"rescue",
"Libvirt",
"::",
"Error",
"=>",
"e",
"return",
"nil",
"if",
"e",
".",
"libvirt_code",
"==",
"42",
"raise",
"end"
] | Look up a domain by name | [
"Look",
"up",
"a",
"domain",
"by",
"name"
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb#L281-L286 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb | BoxGrinder.LibvirtPlugin.undefine_domain | def undefine_domain(dom)
case dom.info.state
when Libvirt::Domain::RUNNING, Libvirt::Domain::PAUSED, Libvirt::Domain::BLOCKED
dom.destroy
end
dom.undefine
end | ruby | def undefine_domain(dom)
case dom.info.state
when Libvirt::Domain::RUNNING, Libvirt::Domain::PAUSED, Libvirt::Domain::BLOCKED
dom.destroy
end
dom.undefine
end | [
"def",
"undefine_domain",
"(",
"dom",
")",
"case",
"dom",
".",
"info",
".",
"state",
"when",
"Libvirt",
"::",
"Domain",
"::",
"RUNNING",
",",
"Libvirt",
"::",
"Domain",
"::",
"PAUSED",
",",
"Libvirt",
"::",
"Domain",
"::",
"BLOCKED",
"dom",
".",
"destroy",
"end",
"dom",
".",
"undefine",
"end"
] | Undefine a domain. The domain will be destroyed first if required. | [
"Undefine",
"a",
"domain",
".",
"The",
"domain",
"will",
"be",
"destroyed",
"first",
"if",
"required",
"."
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb#L289-L295 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb | BoxGrinder.LibvirtPlugin.write_xml | def write_xml(xml)
fname = "#{@appliance_name}.xml"
File.open("#{@dir.tmp}/#{fname}", 'w'){|f| f.write(xml)}
register_deliverable(:xml => fname)
end | ruby | def write_xml(xml)
fname = "#{@appliance_name}.xml"
File.open("#{@dir.tmp}/#{fname}", 'w'){|f| f.write(xml)}
register_deliverable(:xml => fname)
end | [
"def",
"write_xml",
"(",
"xml",
")",
"fname",
"=",
"\"#{@appliance_name}.xml\"",
"File",
".",
"open",
"(",
"\"#{@dir.tmp}/#{fname}\"",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"xml",
")",
"}",
"register_deliverable",
"(",
":xml",
"=>",
"fname",
")",
"end"
] | Write domain XML to file | [
"Write",
"domain",
"XML",
"to",
"file"
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/plugins/delivery/libvirt/libvirt-plugin.rb#L307-L311 | train |
duke-libraries/ddr-models | lib/ddr/models/with_content_file.rb | Ddr::Models.WithContentFile.with_temp_file | def with_temp_file
filename = original_filename || content.default_file_name
basename = [ File.basename(filename, ".*"), File.extname(filename) ]
infile = Tempfile.open(basename, Ddr::Models.tempdir, encoding: 'ascii-8bit')
begin
infile.write(content.content)
infile.close
verify_checksum!(infile)
yield infile.path
ensure
infile.close unless infile.closed?
File.unlink(infile)
end
end | ruby | def with_temp_file
filename = original_filename || content.default_file_name
basename = [ File.basename(filename, ".*"), File.extname(filename) ]
infile = Tempfile.open(basename, Ddr::Models.tempdir, encoding: 'ascii-8bit')
begin
infile.write(content.content)
infile.close
verify_checksum!(infile)
yield infile.path
ensure
infile.close unless infile.closed?
File.unlink(infile)
end
end | [
"def",
"with_temp_file",
"filename",
"=",
"original_filename",
"||",
"content",
".",
"default_file_name",
"basename",
"=",
"[",
"File",
".",
"basename",
"(",
"filename",
",",
"\".*\"",
")",
",",
"File",
".",
"extname",
"(",
"filename",
")",
"]",
"infile",
"=",
"Tempfile",
".",
"open",
"(",
"basename",
",",
"Ddr",
"::",
"Models",
".",
"tempdir",
",",
"encoding",
":",
"'ascii-8bit'",
")",
"begin",
"infile",
".",
"write",
"(",
"content",
".",
"content",
")",
"infile",
".",
"close",
"verify_checksum!",
"(",
"infile",
")",
"yield",
"infile",
".",
"path",
"ensure",
"infile",
".",
"close",
"unless",
"infile",
".",
"closed?",
"File",
".",
"unlink",
"(",
"infile",
")",
"end",
"end"
] | Yields path of tempfile containing content to block
@yield [String] the path to the tempfile containing content | [
"Yields",
"path",
"of",
"tempfile",
"containing",
"content",
"to",
"block"
] | 1555c436daf8a8370cd7220c65ba1d8008918795 | https://github.com/duke-libraries/ddr-models/blob/1555c436daf8a8370cd7220c65ba1d8008918795/lib/ddr/models/with_content_file.rb#L14-L27 | train |
duke-libraries/ddr-models | lib/ddr/auth/auth_context.rb | Ddr::Auth.AuthContext.member_of? | def member_of?(group)
if group.is_a? Group
groups.include? group
else
member_of? Group.new(group)
end
end | ruby | def member_of?(group)
if group.is_a? Group
groups.include? group
else
member_of? Group.new(group)
end
end | [
"def",
"member_of?",
"(",
"group",
")",
"if",
"group",
".",
"is_a?",
"Group",
"groups",
".",
"include?",
"group",
"else",
"member_of?",
"Group",
".",
"new",
"(",
"group",
")",
"end",
"end"
] | Is the user associated with the auth context a member of the group?
@param group [Group, String] group object or group id
@return [Boolean] | [
"Is",
"the",
"user",
"associated",
"with",
"the",
"auth",
"context",
"a",
"member",
"of",
"the",
"group?"
] | 1555c436daf8a8370cd7220c65ba1d8008918795 | https://github.com/duke-libraries/ddr-models/blob/1555c436daf8a8370cd7220c65ba1d8008918795/lib/ddr/auth/auth_context.rb#L69-L75 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/core/api_caller.rb | Wavefront.ApiCaller.post | def post(path, body = nil, ctype = 'text/plain')
body = body.to_json unless body.is_a?(String)
make_call(mk_conn(path, 'Content-Type': ctype,
'Accept': 'application/json'),
:post, nil, body)
end | ruby | def post(path, body = nil, ctype = 'text/plain')
body = body.to_json unless body.is_a?(String)
make_call(mk_conn(path, 'Content-Type': ctype,
'Accept': 'application/json'),
:post, nil, body)
end | [
"def",
"post",
"(",
"path",
",",
"body",
"=",
"nil",
",",
"ctype",
"=",
"'text/plain'",
")",
"body",
"=",
"body",
".",
"to_json",
"unless",
"body",
".",
"is_a?",
"(",
"String",
")",
"make_call",
"(",
"mk_conn",
"(",
"path",
",",
"'Content-Type'",
":",
"ctype",
",",
"'Accept'",
":",
"'application/json'",
")",
",",
":post",
",",
"nil",
",",
"body",
")",
"end"
] | Make a POST call to the Wavefront API and return the result as
a Ruby hash.
@param path [String] path to be appended to the
#net[:api_base] path.
@param body [String,Object] optional body text to post.
Objects will be converted to JSON
@param ctype [String] the content type to use when posting
@return [Hash] API response | [
"Make",
"a",
"POST",
"call",
"to",
"the",
"Wavefront",
"API",
"and",
"return",
"the",
"result",
"as",
"a",
"Ruby",
"hash",
"."
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api_caller.rb#L97-L102 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/core/api_caller.rb | Wavefront.ApiCaller.put | def put(path, body = nil, ctype = 'application/json')
make_call(mk_conn(path, 'Content-Type': ctype,
'Accept': 'application/json'),
:put, nil, body.to_json)
end | ruby | def put(path, body = nil, ctype = 'application/json')
make_call(mk_conn(path, 'Content-Type': ctype,
'Accept': 'application/json'),
:put, nil, body.to_json)
end | [
"def",
"put",
"(",
"path",
",",
"body",
"=",
"nil",
",",
"ctype",
"=",
"'application/json'",
")",
"make_call",
"(",
"mk_conn",
"(",
"path",
",",
"'Content-Type'",
":",
"ctype",
",",
"'Accept'",
":",
"'application/json'",
")",
",",
":put",
",",
"nil",
",",
"body",
".",
"to_json",
")",
"end"
] | Make a PUT call to the Wavefront API and return the result as
a Ruby hash.
@param path [String] path to be appended to the
#net[:api_base] path.
@param body [String] optional body text to post
@param ctype [String] the content type to use when putting
@return [Hash] API response | [
"Make",
"a",
"PUT",
"call",
"to",
"the",
"Wavefront",
"API",
"and",
"return",
"the",
"result",
"as",
"a",
"Ruby",
"hash",
"."
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api_caller.rb#L113-L117 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/core/api_caller.rb | Wavefront.ApiCaller.verbosity | def verbosity(conn, method, *args)
return unless noop || verbose
log format('uri: %s %s', method.upcase, conn.url_prefix)
return unless args.last && !args.last.empty?
log method == :get ? "params: #{args.last}" : "body: #{args.last}"
end | ruby | def verbosity(conn, method, *args)
return unless noop || verbose
log format('uri: %s %s', method.upcase, conn.url_prefix)
return unless args.last && !args.last.empty?
log method == :get ? "params: #{args.last}" : "body: #{args.last}"
end | [
"def",
"verbosity",
"(",
"conn",
",",
"method",
",",
"*",
"args",
")",
"return",
"unless",
"noop",
"||",
"verbose",
"log",
"format",
"(",
"'uri: %s %s'",
",",
"method",
".",
"upcase",
",",
"conn",
".",
"url_prefix",
")",
"return",
"unless",
"args",
".",
"last",
"&&",
"!",
"args",
".",
"last",
".",
"empty?",
"log",
"method",
"==",
":get",
"?",
"\"params: #{args.last}\"",
":",
"\"body: #{args.last}\"",
"end"
] | Try to describe the actual HTTP calls we make. There's a bit
of clumsy guesswork here | [
"Try",
"to",
"describe",
"the",
"actual",
"HTTP",
"calls",
"we",
"make",
".",
"There",
"s",
"a",
"bit",
"of",
"clumsy",
"guesswork",
"here"
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api_caller.rb#L147-L154 | train |
enkessler/cucumber_analytics | lib/cucumber_analytics/outline.rb | CucumberAnalytics.Outline.to_s | def to_s
text = ''
text << tag_output_string + "\n" unless tags.empty?
text << "Scenario Outline:#{name_output_string}"
text << "\n" + description_output_string unless description_text.empty?
text << "\n" unless steps.empty? || description_text.empty?
text << "\n" + steps_output_string unless steps.empty?
text << "\n\n" + examples_output_string unless examples.empty?
text
end | ruby | def to_s
text = ''
text << tag_output_string + "\n" unless tags.empty?
text << "Scenario Outline:#{name_output_string}"
text << "\n" + description_output_string unless description_text.empty?
text << "\n" unless steps.empty? || description_text.empty?
text << "\n" + steps_output_string unless steps.empty?
text << "\n\n" + examples_output_string unless examples.empty?
text
end | [
"def",
"to_s",
"text",
"=",
"''",
"text",
"<<",
"tag_output_string",
"+",
"\"\\n\"",
"unless",
"tags",
".",
"empty?",
"text",
"<<",
"\"Scenario Outline:#{name_output_string}\"",
"text",
"<<",
"\"\\n\"",
"+",
"description_output_string",
"unless",
"description_text",
".",
"empty?",
"text",
"<<",
"\"\\n\"",
"unless",
"steps",
".",
"empty?",
"||",
"description_text",
".",
"empty?",
"text",
"<<",
"\"\\n\"",
"+",
"steps_output_string",
"unless",
"steps",
".",
"empty?",
"text",
"<<",
"\"\\n\\n\"",
"+",
"examples_output_string",
"unless",
"examples",
".",
"empty?",
"text",
"end"
] | Returns a gherkin representation of the outline. | [
"Returns",
"a",
"gherkin",
"representation",
"of",
"the",
"outline",
"."
] | a74642d30b3566fc11fb43c920518fea4587c6bd | https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/outline.rb#L35-L46 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/metric_helper.rb | Wavefront.MetricHelper.dist | def dist(path, interval, value, tags = nil)
key = [path, interval, tags]
@buf[:dists][key] += [value].flatten
end | ruby | def dist(path, interval, value, tags = nil)
key = [path, interval, tags]
@buf[:dists][key] += [value].flatten
end | [
"def",
"dist",
"(",
"path",
",",
"interval",
",",
"value",
",",
"tags",
"=",
"nil",
")",
"key",
"=",
"[",
"path",
",",
"interval",
",",
"tags",
"]",
"@buf",
"[",
":dists",
"]",
"[",
"key",
"]",
"+=",
"[",
"value",
"]",
".",
"flatten",
"end"
] | These distributions are stored in memory, and sent to
Wavefront as native distibutions when the buffer is flushed.
@param path [String] metric path
@param value [Array, Numeric] value(s) to add to distribution
@param interval [Symbol, String] distribution interval, :m,
:h, or :d
@param tags [Hash] point tags | [
"These",
"distributions",
"are",
"stored",
"in",
"memory",
"and",
"sent",
"to",
"Wavefront",
"as",
"native",
"distibutions",
"when",
"the",
"buffer",
"is",
"flushed",
"."
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/metric_helper.rb#L62-L65 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/metric_helper.rb | Wavefront.MetricHelper.flush_gauges | def flush_gauges(gauges)
return if gauges.empty?
to_flush = gauges.dup
@buf[:gauges] = empty_gauges
writer.write(gauges_to_wf(gauges)).tap do |resp|
@buf[:gauges] += to_flush unless resp.ok?
end
end | ruby | def flush_gauges(gauges)
return if gauges.empty?
to_flush = gauges.dup
@buf[:gauges] = empty_gauges
writer.write(gauges_to_wf(gauges)).tap do |resp|
@buf[:gauges] += to_flush unless resp.ok?
end
end | [
"def",
"flush_gauges",
"(",
"gauges",
")",
"return",
"if",
"gauges",
".",
"empty?",
"to_flush",
"=",
"gauges",
".",
"dup",
"@buf",
"[",
":gauges",
"]",
"=",
"empty_gauges",
"writer",
".",
"write",
"(",
"gauges_to_wf",
"(",
"gauges",
")",
")",
".",
"tap",
"do",
"|",
"resp",
"|",
"@buf",
"[",
":gauges",
"]",
"+=",
"to_flush",
"unless",
"resp",
".",
"ok?",
"end",
"end"
] | When we are asked to flush the buffers, duplicate the current
one, hand it off to the writer class, and clear. If writer
tells us there was an error, dump the old buffer into the
the new one for the next flush. | [
"When",
"we",
"are",
"asked",
"to",
"flush",
"the",
"buffers",
"duplicate",
"the",
"current",
"one",
"hand",
"it",
"off",
"to",
"the",
"writer",
"class",
"and",
"clear",
".",
"If",
"writer",
"tells",
"us",
"there",
"was",
"an",
"error",
"dump",
"the",
"old",
"buffer",
"into",
"the",
"the",
"new",
"one",
"for",
"the",
"next",
"flush",
"."
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/metric_helper.rb#L81-L90 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/metric_helper.rb | Wavefront.MetricHelper.replay_counters | def replay_counters(buffer)
buffer.each { |k, v| counter(k[0], v, k[1]) }
end | ruby | def replay_counters(buffer)
buffer.each { |k, v| counter(k[0], v, k[1]) }
end | [
"def",
"replay_counters",
"(",
"buffer",
")",
"buffer",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"counter",
"(",
"k",
"[",
"0",
"]",
",",
"v",
",",
"k",
"[",
"1",
"]",
")",
"}",
"end"
] | Play a failed flush full of counters back into the system | [
"Play",
"a",
"failed",
"flush",
"full",
"of",
"counters",
"back",
"into",
"the",
"system"
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/metric_helper.rb#L116-L118 | train |
wedesoft/malloc | lib/malloc_ext.rb | Hornetseye.Malloc.+ | def +( offset )
if offset > @size
raise "Offset must not be more than #{@size} (but was #{offset})"
end
mark, size = self, @size - offset
retval = orig_plus offset
retval.instance_eval { @mark, @size = mark, size }
retval
end | ruby | def +( offset )
if offset > @size
raise "Offset must not be more than #{@size} (but was #{offset})"
end
mark, size = self, @size - offset
retval = orig_plus offset
retval.instance_eval { @mark, @size = mark, size }
retval
end | [
"def",
"+",
"(",
"offset",
")",
"if",
"offset",
">",
"@size",
"raise",
"\"Offset must not be more than #{@size} (but was #{offset})\"",
"end",
"mark",
",",
"size",
"=",
"self",
",",
"@size",
"-",
"offset",
"retval",
"=",
"orig_plus",
"offset",
"retval",
".",
"instance_eval",
"{",
"@mark",
",",
"@size",
"=",
"mark",
",",
"size",
"}",
"retval",
"end"
] | Operator for doing pointer arithmetic
@example Pointer arithmetic
m = Malloc.new 4
# Malloc(4)
m.write 'abcd'
n = m + 2
# Malloc(2)
n.read 2
# "cd"
@param [Integer] offset Non-negative offset for pointer.
@return [Malloc] A new Malloc object. | [
"Operator",
"for",
"doing",
"pointer",
"arithmetic"
] | 8d2e5f51c277b78b8f116939b4b0be5b6f99328f | https://github.com/wedesoft/malloc/blob/8d2e5f51c277b78b8f116939b4b0be5b6f99328f/lib/malloc_ext.rb#L160-L168 | train |
wedesoft/malloc | lib/malloc_ext.rb | Hornetseye.Malloc.write | def write( data )
if data.is_a? Malloc
if data.size > @size
raise "Must not write more than #{@size} bytes of memory " +
"(illegal attempt to write #{data.size} bytes)"
end
orig_write data, data.size
else
if data.bytesize > @size
raise "Must not write more than #{@size} bytes of memory " +
"(illegal attempt to write #{data.bytesize} bytes)"
end
orig_write data
end
end | ruby | def write( data )
if data.is_a? Malloc
if data.size > @size
raise "Must not write more than #{@size} bytes of memory " +
"(illegal attempt to write #{data.size} bytes)"
end
orig_write data, data.size
else
if data.bytesize > @size
raise "Must not write more than #{@size} bytes of memory " +
"(illegal attempt to write #{data.bytesize} bytes)"
end
orig_write data
end
end | [
"def",
"write",
"(",
"data",
")",
"if",
"data",
".",
"is_a?",
"Malloc",
"if",
"data",
".",
"size",
">",
"@size",
"raise",
"\"Must not write more than #{@size} bytes of memory \"",
"+",
"\"(illegal attempt to write #{data.size} bytes)\"",
"end",
"orig_write",
"data",
",",
"data",
".",
"size",
"else",
"if",
"data",
".",
"bytesize",
">",
"@size",
"raise",
"\"Must not write more than #{@size} bytes of memory \"",
"+",
"\"(illegal attempt to write #{data.bytesize} bytes)\"",
"end",
"orig_write",
"data",
"end",
"end"
] | Write data to memory
@example Reading and writing data
m = Malloc.new 4
# Malloc(4)
m.write 'abcd'
m.read 2
# "ab"
@param [String,Malloc] data A string or malloc object with the data.
@return [String] Returns the parameter +string+.
@see #read | [
"Write",
"data",
"to",
"memory"
] | 8d2e5f51c277b78b8f116939b4b0be5b6f99328f | https://github.com/wedesoft/malloc/blob/8d2e5f51c277b78b8f116939b4b0be5b6f99328f/lib/malloc_ext.rb#L207-L221 | train |
enkessler/cucumber_analytics | lib/cucumber_analytics/example.rb | CucumberAnalytics.Example.to_s | def to_s
text = ''
text << tag_output_string + "\n" unless tags.empty?
text << "Examples:#{name_output_string}"
text << "\n" + description_output_string unless description_text.empty?
text << "\n" unless description_text.empty?
text << "\n" + parameters_output_string
text << "\n" + rows_output_string unless rows.empty?
text
end | ruby | def to_s
text = ''
text << tag_output_string + "\n" unless tags.empty?
text << "Examples:#{name_output_string}"
text << "\n" + description_output_string unless description_text.empty?
text << "\n" unless description_text.empty?
text << "\n" + parameters_output_string
text << "\n" + rows_output_string unless rows.empty?
text
end | [
"def",
"to_s",
"text",
"=",
"''",
"text",
"<<",
"tag_output_string",
"+",
"\"\\n\"",
"unless",
"tags",
".",
"empty?",
"text",
"<<",
"\"Examples:#{name_output_string}\"",
"text",
"<<",
"\"\\n\"",
"+",
"description_output_string",
"unless",
"description_text",
".",
"empty?",
"text",
"<<",
"\"\\n\"",
"unless",
"description_text",
".",
"empty?",
"text",
"<<",
"\"\\n\"",
"+",
"parameters_output_string",
"text",
"<<",
"\"\\n\"",
"+",
"rows_output_string",
"unless",
"rows",
".",
"empty?",
"text",
"end"
] | Returns a gherkin representation of the example. | [
"Returns",
"a",
"gherkin",
"representation",
"of",
"the",
"example",
"."
] | a74642d30b3566fc11fb43c920518fea4587c6bd | https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/example.rb#L83-L94 | train |
snltd/wavefront-sdk | lib/wavefront-sdk/core/api.rb | Wavefront.CoreApi.time_to_ms | def time_to_ms(time)
return false unless time.is_a?(Integer)
return time if time.to_s.size == 13
(time.to_f * 1000).round
end | ruby | def time_to_ms(time)
return false unless time.is_a?(Integer)
return time if time.to_s.size == 13
(time.to_f * 1000).round
end | [
"def",
"time_to_ms",
"(",
"time",
")",
"return",
"false",
"unless",
"time",
".",
"is_a?",
"(",
"Integer",
")",
"return",
"time",
"if",
"time",
".",
"to_s",
".",
"size",
"==",
"13",
"(",
"time",
".",
"to_f",
"*",
"1000",
")",
".",
"round",
"end"
] | Convert an epoch timestamp into epoch milliseconds. If the
timestamp looks like it's already epoch milliseconds, return
it as-is.
@param t [Integer] epoch timestamp
@return [Ingeter] epoch millisecond timestamp | [
"Convert",
"an",
"epoch",
"timestamp",
"into",
"epoch",
"milliseconds",
".",
"If",
"the",
"timestamp",
"looks",
"like",
"it",
"s",
"already",
"epoch",
"milliseconds",
"return",
"it",
"as",
"-",
"is",
"."
] | 93659d2dab64611fd56aee05cf1de1dd732b46f7 | https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api.rb#L75-L79 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/util/permissions/fs-monitor.rb | BoxGrinder.FSMonitor.capture | def capture(*observers, &block)
@lock_a.synchronize do
add_observers(observers)
_capture(&block)
if block_given?
yield
_stop
end
end
end | ruby | def capture(*observers, &block)
@lock_a.synchronize do
add_observers(observers)
_capture(&block)
if block_given?
yield
_stop
end
end
end | [
"def",
"capture",
"(",
"*",
"observers",
",",
"&",
"block",
")",
"@lock_a",
".",
"synchronize",
"do",
"add_observers",
"(",
"observers",
")",
"_capture",
"(",
"&",
"block",
")",
"if",
"block_given?",
"yield",
"_stop",
"end",
"end",
"end"
] | Start capturing paths. Providing a block automatically stops the
capture process upon termination of the scope.
@param Array<#update> Observers to be notified of capture
events. Each observer should expect a hash{} containing a
+:command+, and potentially +:data+.
@yield Block that automatically calls #stop at the end of scope
to cease capture. | [
"Start",
"capturing",
"paths",
".",
"Providing",
"a",
"block",
"automatically",
"stops",
"the",
"capture",
"process",
"upon",
"termination",
"of",
"the",
"scope",
"."
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/util/permissions/fs-monitor.rb#L47-L57 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/util/permissions/fs-monitor.rb | BoxGrinder.FSMonitor.alias_and_capture | def alias_and_capture(klazz, m_sym, flag, &blk)
alias_m_sym = "__alias_#{m_sym}"
klazz.class_eval do
alias_method alias_m_sym, m_sym
define_method(m_sym) do |*args, &blx|
response = send(alias_m_sym, *args, &blx)
blk.call(self, *args) if flag.get_set
response
end
end
end | ruby | def alias_and_capture(klazz, m_sym, flag, &blk)
alias_m_sym = "__alias_#{m_sym}"
klazz.class_eval do
alias_method alias_m_sym, m_sym
define_method(m_sym) do |*args, &blx|
response = send(alias_m_sym, *args, &blx)
blk.call(self, *args) if flag.get_set
response
end
end
end | [
"def",
"alias_and_capture",
"(",
"klazz",
",",
"m_sym",
",",
"flag",
",",
"&",
"blk",
")",
"alias_m_sym",
"=",
"\"__alias_#{m_sym}\"",
"klazz",
".",
"class_eval",
"do",
"alias_method",
"alias_m_sym",
",",
"m_sym",
"define_method",
"(",
"m_sym",
")",
"do",
"|",
"*",
"args",
",",
"&",
"blx",
"|",
"response",
"=",
"send",
"(",
"alias_m_sym",
",",
"*",
"args",
",",
"&",
"blx",
")",
"blk",
".",
"call",
"(",
"self",
",",
"*",
"args",
")",
"if",
"flag",
".",
"get_set",
"response",
"end",
"end",
"end"
] | Cracks open the target class, and injects a wrapper to enable
monitoring. By aliasing the original method the wrapper intercepts the
call, which it forwards onto the 'real' method before executing the hook.
The hook's functionality is provided via a &block, which is passed the
caller's +self+ in addition to the wrapped method's parameters.
Locking the +flag+ signals the hook to begin capturing. | [
"Cracks",
"open",
"the",
"target",
"class",
"and",
"injects",
"a",
"wrapper",
"to",
"enable",
"monitoring",
".",
"By",
"aliasing",
"the",
"original",
"method",
"the",
"wrapper",
"intercepts",
"the",
"call",
"which",
"it",
"forwards",
"onto",
"the",
"real",
"method",
"before",
"executing",
"the",
"hook",
"."
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/util/permissions/fs-monitor.rb#L151-L163 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/helpers/linux-helper.rb | BoxGrinder.RPMVersion.newest | def newest(versions)
versions.sort { |x,y| compare(x,y) }.last
end | ruby | def newest(versions)
versions.sort { |x,y| compare(x,y) }.last
end | [
"def",
"newest",
"(",
"versions",
")",
"versions",
".",
"sort",
"{",
"|",
"x",
",",
"y",
"|",
"compare",
"(",
"x",
",",
"y",
")",
"}",
".",
"last",
"end"
] | Returns newest version from the array | [
"Returns",
"newest",
"version",
"from",
"the",
"array"
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/linux-helper.rb#L50-L52 | train |
boxgrinder/boxgrinder-build | lib/boxgrinder-build/helpers/linux-helper.rb | BoxGrinder.LinuxHelper.partition_mount_points | def partition_mount_points(partitions)
partitions.keys.sort do |a, b|
a_count = a.count('/')
b_count = b.count('/')
if a_count > b_count
v = 1
else
if a_count < b_count
v = -1
else
if a.length == b.length
v = a <=> b
else
v = a.length <=> b.length
end
end
end
# This forces having swap partition at the end of the disk
v = 1 if a_count == 0
v = -1 if b_count == 0
v
end
end | ruby | def partition_mount_points(partitions)
partitions.keys.sort do |a, b|
a_count = a.count('/')
b_count = b.count('/')
if a_count > b_count
v = 1
else
if a_count < b_count
v = -1
else
if a.length == b.length
v = a <=> b
else
v = a.length <=> b.length
end
end
end
# This forces having swap partition at the end of the disk
v = 1 if a_count == 0
v = -1 if b_count == 0
v
end
end | [
"def",
"partition_mount_points",
"(",
"partitions",
")",
"partitions",
".",
"keys",
".",
"sort",
"do",
"|",
"a",
",",
"b",
"|",
"a_count",
"=",
"a",
".",
"count",
"(",
"'/'",
")",
"b_count",
"=",
"b",
".",
"count",
"(",
"'/'",
")",
"if",
"a_count",
">",
"b_count",
"v",
"=",
"1",
"else",
"if",
"a_count",
"<",
"b_count",
"v",
"=",
"-",
"1",
"else",
"if",
"a",
".",
"length",
"==",
"b",
".",
"length",
"v",
"=",
"a",
"<=>",
"b",
"else",
"v",
"=",
"a",
".",
"length",
"<=>",
"b",
".",
"length",
"end",
"end",
"end",
"v",
"=",
"1",
"if",
"a_count",
"==",
"0",
"v",
"=",
"-",
"1",
"if",
"b_count",
"==",
"0",
"v",
"end",
"end"
] | Returns valid array of sorted mount points
['/', '/home'] => ['/', '/home']
['swap', '/', '/home'] => ['/', '/home', 'swap']
['swap', '/', '/home', '/boot'] => ['/', '/boot', '/home', 'swap']
['/tmp-eventlog', '/', '/ubrc', '/tmp-config'] => ['/', '/ubrc', '/tmp-config', '/tmp-eventlog'] | [
"Returns",
"valid",
"array",
"of",
"sorted",
"mount",
"points"
] | fa21c27451d23f281b41a3e32339d5d791d5f420 | https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/linux-helper.rb#L67-L92 | train |
ilkka/consular-terminator | lib/consular/terminator.rb | Consular.Terminator.process! | def process!
windows = @termfile[:windows]
default = windows.delete('default')
execute_window(default, :default => true) unless default[:tabs].empty?
windows.each_pair { |_, cont| execute_window(cont) }
end | ruby | def process!
windows = @termfile[:windows]
default = windows.delete('default')
execute_window(default, :default => true) unless default[:tabs].empty?
windows.each_pair { |_, cont| execute_window(cont) }
end | [
"def",
"process!",
"windows",
"=",
"@termfile",
"[",
":windows",
"]",
"default",
"=",
"windows",
".",
"delete",
"(",
"'default'",
")",
"execute_window",
"(",
"default",
",",
":default",
"=>",
"true",
")",
"unless",
"default",
"[",
":tabs",
"]",
".",
"empty?",
"windows",
".",
"each_pair",
"{",
"|",
"_",
",",
"cont",
"|",
"execute_window",
"(",
"cont",
")",
"}",
"end"
] | Method called by runner to execute Termfile.
@api public | [
"Method",
"called",
"by",
"runner",
"to",
"execute",
"Termfile",
"."
] | a7734c7b1f8390ec5a93bc6719d272cd8c1e1a78 | https://github.com/ilkka/consular-terminator/blob/a7734c7b1f8390ec5a93bc6719d272cd8c1e1a78/lib/consular/terminator.rb#L55-L60 | train |
kete/kete_gets_trollied | lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb | HasTrolleyControllerHelpersOverrides.UrlFor.url_for_trolley | def url_for_trolley(options = { })
return url_for_dc_identifier(@purchasable_item) if @purchasable_item && params[:action] == 'create'
user = options.delete(:user)
trolley = options[:trolley] || @trolley || user.trolley
if trolley.blank?
user = @user
else
user = trolley.user
end
options[:user_id] = user.id
options[:controller] = 'trolleys'
options[:action] = 'show'
options[:urlified_name] = Basket.site_basket.urlified_name
url = url_for(options) # .split(".%23%")[0]
end | ruby | def url_for_trolley(options = { })
return url_for_dc_identifier(@purchasable_item) if @purchasable_item && params[:action] == 'create'
user = options.delete(:user)
trolley = options[:trolley] || @trolley || user.trolley
if trolley.blank?
user = @user
else
user = trolley.user
end
options[:user_id] = user.id
options[:controller] = 'trolleys'
options[:action] = 'show'
options[:urlified_name] = Basket.site_basket.urlified_name
url = url_for(options) # .split(".%23%")[0]
end | [
"def",
"url_for_trolley",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"url_for_dc_identifier",
"(",
"@purchasable_item",
")",
"if",
"@purchasable_item",
"&&",
"params",
"[",
":action",
"]",
"==",
"'create'",
"user",
"=",
"options",
".",
"delete",
"(",
":user",
")",
"trolley",
"=",
"options",
"[",
":trolley",
"]",
"||",
"@trolley",
"||",
"user",
".",
"trolley",
"if",
"trolley",
".",
"blank?",
"user",
"=",
"@user",
"else",
"user",
"=",
"trolley",
".",
"user",
"end",
"options",
"[",
":user_id",
"]",
"=",
"user",
".",
"id",
"options",
"[",
":controller",
"]",
"=",
"'trolleys'",
"options",
"[",
":action",
"]",
"=",
"'show'",
"options",
"[",
":urlified_name",
"]",
"=",
"Basket",
".",
"site_basket",
".",
"urlified_name",
"url",
"=",
"url_for",
"(",
"options",
")",
"end"
] | expects user in options or @user or trolley being set
unless @purchasable_item is present
WARNING: in the case of @purchasable_item
this method name breaks the principle of least surprise
maybe alter trollied gem in future to come right | [
"expects",
"user",
"in",
"options",
"or"
] | a00e2170e08fec7cbc68b09da8a00eb5645e0ef4 | https://github.com/kete/kete_gets_trollied/blob/a00e2170e08fec7cbc68b09da8a00eb5645e0ef4/lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb#L14-L32 | train |
kete/kete_gets_trollied | lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb | HasTrolleyControllerHelpersOverrides.UrlFor.url_for_order | def url_for_order(options = { })
trolley = options.delete(:trolley) || @trolley
trolley = @order.trolley if @order
order = options.delete(:order) || @order || trolley.selected_order
options[:id] = order
options[:controller] = 'orders'
options[:action] = 'show'
options[:urlified_name] = Basket.site_basket.urlified_name
url_for options
end | ruby | def url_for_order(options = { })
trolley = options.delete(:trolley) || @trolley
trolley = @order.trolley if @order
order = options.delete(:order) || @order || trolley.selected_order
options[:id] = order
options[:controller] = 'orders'
options[:action] = 'show'
options[:urlified_name] = Basket.site_basket.urlified_name
url_for options
end | [
"def",
"url_for_order",
"(",
"options",
"=",
"{",
"}",
")",
"trolley",
"=",
"options",
".",
"delete",
"(",
":trolley",
")",
"||",
"@trolley",
"trolley",
"=",
"@order",
".",
"trolley",
"if",
"@order",
"order",
"=",
"options",
".",
"delete",
"(",
":order",
")",
"||",
"@order",
"||",
"trolley",
".",
"selected_order",
"options",
"[",
":id",
"]",
"=",
"order",
"options",
"[",
":controller",
"]",
"=",
"'orders'",
"options",
"[",
":action",
"]",
"=",
"'show'",
"options",
"[",
":urlified_name",
"]",
"=",
"Basket",
".",
"site_basket",
".",
"urlified_name",
"url_for",
"options",
"end"
] | expects order
either as instance variables or in options | [
"expects",
"order",
"either",
"as",
"instance",
"variables",
"or",
"in",
"options"
] | a00e2170e08fec7cbc68b09da8a00eb5645e0ef4 | https://github.com/kete/kete_gets_trollied/blob/a00e2170e08fec7cbc68b09da8a00eb5645e0ef4/lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb#L36-L48 | train |
altabyte/ebay_trader | lib/ebay_trader/session_id.rb | EbayTrader.SessionID.sign_in_url | def sign_in_url(ruparams = {})
url = []
url << EbayTrader.configuration.production? ? 'https://signin.ebay.com' : 'https://signin.sandbox.ebay.com'
url << '/ws/eBayISAPI.dll?SignIn'
url << "&runame=#{url_encode ru_name}"
url << "&SessID=#{url_encode id}"
if ruparams && ruparams.is_a?(Hash) && !ruparams.empty?
params = []
ruparams.each_pair { |key, value| params << "#{key}=#{value}" }
url << "&ruparams=#{url_encode(params.join('&'))}"
end
url.join
end | ruby | def sign_in_url(ruparams = {})
url = []
url << EbayTrader.configuration.production? ? 'https://signin.ebay.com' : 'https://signin.sandbox.ebay.com'
url << '/ws/eBayISAPI.dll?SignIn'
url << "&runame=#{url_encode ru_name}"
url << "&SessID=#{url_encode id}"
if ruparams && ruparams.is_a?(Hash) && !ruparams.empty?
params = []
ruparams.each_pair { |key, value| params << "#{key}=#{value}" }
url << "&ruparams=#{url_encode(params.join('&'))}"
end
url.join
end | [
"def",
"sign_in_url",
"(",
"ruparams",
"=",
"{",
"}",
")",
"url",
"=",
"[",
"]",
"url",
"<<",
"EbayTrader",
".",
"configuration",
".",
"production?",
"?",
"'https://signin.ebay.com'",
":",
"'https://signin.sandbox.ebay.com'",
"url",
"<<",
"'/ws/eBayISAPI.dll?SignIn'",
"url",
"<<",
"\"&runame=#{url_encode ru_name}\"",
"url",
"<<",
"\"&SessID=#{url_encode id}\"",
"if",
"ruparams",
"&&",
"ruparams",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"!",
"ruparams",
".",
"empty?",
"params",
"=",
"[",
"]",
"ruparams",
".",
"each_pair",
"{",
"|",
"key",
",",
"value",
"|",
"params",
"<<",
"\"#{key}=#{value}\"",
"}",
"url",
"<<",
"\"&ruparams=#{url_encode(params.join('&'))}\"",
"end",
"url",
".",
"join",
"end"
] | Get the URL through which a user must sign in using this session ID.
@param [Hash] ruparams eBay appends this data to the AcceptURL and RejectURL.
In a typical rails app this might include the user's model primary key.
@return [String] the sign-in URL. | [
"Get",
"the",
"URL",
"through",
"which",
"a",
"user",
"must",
"sign",
"in",
"using",
"this",
"session",
"ID",
"."
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/session_id.rb#L49-L61 | train |
jmesnil/jmx4r | lib/jmx4r.rb | JMX.MBean.method_missing | def method_missing(method, *args, &block) #:nodoc:
method_in_snake_case = method.to_s.snake_case # this way Java/JRuby styles are compatible
if @operations.keys.include?(method_in_snake_case)
op_name, param_types = @operations[method_in_snake_case]
@connection.invoke @object_name,
op_name,
args.to_java(:Object),
param_types.to_java(:String)
else
super
end
end | ruby | def method_missing(method, *args, &block) #:nodoc:
method_in_snake_case = method.to_s.snake_case # this way Java/JRuby styles are compatible
if @operations.keys.include?(method_in_snake_case)
op_name, param_types = @operations[method_in_snake_case]
@connection.invoke @object_name,
op_name,
args.to_java(:Object),
param_types.to_java(:String)
else
super
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"method_in_snake_case",
"=",
"method",
".",
"to_s",
".",
"snake_case",
"if",
"@operations",
".",
"keys",
".",
"include?",
"(",
"method_in_snake_case",
")",
"op_name",
",",
"param_types",
"=",
"@operations",
"[",
"method_in_snake_case",
"]",
"@connection",
".",
"invoke",
"@object_name",
",",
"op_name",
",",
"args",
".",
"to_java",
"(",
":Object",
")",
",",
"param_types",
".",
"to_java",
"(",
":String",
")",
"else",
"super",
"end",
"end"
] | Creates a new MBean.
object_name:: a string corresponding to a valid ObjectName
connection:: a connection to a MBean server. If none is passed,
use the global connection created by
MBean.establish_connection | [
"Creates",
"a",
"new",
"MBean",
"."
] | 8140fe451d3f9c008e9efa1b56e4e1d710187352 | https://github.com/jmesnil/jmx4r/blob/8140fe451d3f9c008e9efa1b56e4e1d710187352/lib/jmx4r.rb#L97-L109 | train |
jdigger/git-process | lib/git-process/github_pull_request.rb | GitHub.PullRequest.create | def create(base, head, title, body)
logger.info { "Creating a pull request asking for '#{head}' to be merged into '#{base}' on #{repo}." }
begin
return sym_hash_JSON(client.create_pull_request(repo, base, head, title, body))
rescue Octokit::UnprocessableEntity => exp
pull = pull_requests.find { |p| p[:head][:ref] == head and p[:base][:ref] == base }
if pull
logger.warn { "Pull request already exists. See #{pull[:html_url]}" }
else
logger.warn { "UnprocessableEntity: #{exp}" }
end
return pull
end
end | ruby | def create(base, head, title, body)
logger.info { "Creating a pull request asking for '#{head}' to be merged into '#{base}' on #{repo}." }
begin
return sym_hash_JSON(client.create_pull_request(repo, base, head, title, body))
rescue Octokit::UnprocessableEntity => exp
pull = pull_requests.find { |p| p[:head][:ref] == head and p[:base][:ref] == base }
if pull
logger.warn { "Pull request already exists. See #{pull[:html_url]}" }
else
logger.warn { "UnprocessableEntity: #{exp}" }
end
return pull
end
end | [
"def",
"create",
"(",
"base",
",",
"head",
",",
"title",
",",
"body",
")",
"logger",
".",
"info",
"{",
"\"Creating a pull request asking for '#{head}' to be merged into '#{base}' on #{repo}.\"",
"}",
"begin",
"return",
"sym_hash_JSON",
"(",
"client",
".",
"create_pull_request",
"(",
"repo",
",",
"base",
",",
"head",
",",
"title",
",",
"body",
")",
")",
"rescue",
"Octokit",
"::",
"UnprocessableEntity",
"=>",
"exp",
"pull",
"=",
"pull_requests",
".",
"find",
"{",
"|",
"p",
"|",
"p",
"[",
":head",
"]",
"[",
":ref",
"]",
"==",
"head",
"and",
"p",
"[",
":base",
"]",
"[",
":ref",
"]",
"==",
"base",
"}",
"if",
"pull",
"logger",
".",
"warn",
"{",
"\"Pull request already exists. See #{pull[:html_url]}\"",
"}",
"else",
"logger",
".",
"warn",
"{",
"\"UnprocessableEntity: #{exp}\"",
"}",
"end",
"return",
"pull",
"end",
"end"
] | Create a pull request
@see https://developer.github.com/v3/pulls/#create-a-pull-request
@param base [String] The branch (or git ref) you want your changes
pulled into. This should be an existing branch on the current
repository. You cannot submit a pull request to one repo that requests
a merge to a base of another repo.
@param head [String] The branch (or git ref) where your changes are implemented.
@param title [String] Title for the pull request
@param body [String] The body for the pull request (optional). Supports GFM.
@return [Hash] The newly created pull request
@example
@client.create_pull_request("master", "feature-branch",
"Pull Request title", "Pull Request body") | [
"Create",
"a",
"pull",
"request"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_pull_request.rb#L62-L75 | train |
brianstorti/vagalume | lib/vagalume/song.rb | Vagalume.Song.remove_title | def remove_title(lyric)
lines = lyric.lines
lines.shift
lines = remove_empty_lines_from_beginning(lines)
lines.join
end | ruby | def remove_title(lyric)
lines = lyric.lines
lines.shift
lines = remove_empty_lines_from_beginning(lines)
lines.join
end | [
"def",
"remove_title",
"(",
"lyric",
")",
"lines",
"=",
"lyric",
".",
"lines",
"lines",
".",
"shift",
"lines",
"=",
"remove_empty_lines_from_beginning",
"(",
"lines",
")",
"lines",
".",
"join",
"end"
] | This is necessary because, for translations, the song title comes with the
lyric text. Also, the format is not always the same, sometimes it's just one line
for the title, sometimes it's the title followed by some empty lines.
Here we remove the first line and any following empty lines, so we have
a consident API. | [
"This",
"is",
"necessary",
"because",
"for",
"translations",
"the",
"song",
"title",
"comes",
"with",
"the",
"lyric",
"text",
".",
"Also",
"the",
"format",
"is",
"not",
"always",
"the",
"same",
"sometimes",
"it",
"s",
"just",
"one",
"line",
"for",
"the",
"title",
"sometimes",
"it",
"s",
"the",
"title",
"followed",
"by",
"some",
"empty",
"lines",
".",
"Here",
"we",
"remove",
"the",
"first",
"line",
"and",
"any",
"following",
"empty",
"lines",
"so",
"we",
"have",
"a",
"consident",
"API",
"."
] | 0001441a65a9fb9393bb8f4e057eaff5d74b29c8 | https://github.com/brianstorti/vagalume/blob/0001441a65a9fb9393bb8f4e057eaff5d74b29c8/lib/vagalume/song.rb#L34-L39 | train |
acesuares/inline_forms | lib/generators/inline_forms_generator.rb | InlineForms.InlineFormsGenerator.set_some_flags | def set_some_flags
@flag_not_accessible_through_html = true
@flag_create_migration = true
@flag_create_model = true
@create_id = true
for attribute in attributes
@flag_not_accessible_through_html = false if attribute.name == '_enabled'
@flag_create_migration = false if attribute.name == '_no_migration'
@flag_create_model = false if attribute.name == '_no_model'
@create_id = false if attribute.name == "_id" && attribute.type == :false
end
@flag_create_controller = @flag_create_model
@flag_create_resource_route = @flag_create_model
end | ruby | def set_some_flags
@flag_not_accessible_through_html = true
@flag_create_migration = true
@flag_create_model = true
@create_id = true
for attribute in attributes
@flag_not_accessible_through_html = false if attribute.name == '_enabled'
@flag_create_migration = false if attribute.name == '_no_migration'
@flag_create_model = false if attribute.name == '_no_model'
@create_id = false if attribute.name == "_id" && attribute.type == :false
end
@flag_create_controller = @flag_create_model
@flag_create_resource_route = @flag_create_model
end | [
"def",
"set_some_flags",
"@flag_not_accessible_through_html",
"=",
"true",
"@flag_create_migration",
"=",
"true",
"@flag_create_model",
"=",
"true",
"@create_id",
"=",
"true",
"for",
"attribute",
"in",
"attributes",
"@flag_not_accessible_through_html",
"=",
"false",
"if",
"attribute",
".",
"name",
"==",
"'_enabled'",
"@flag_create_migration",
"=",
"false",
"if",
"attribute",
".",
"name",
"==",
"'_no_migration'",
"@flag_create_model",
"=",
"false",
"if",
"attribute",
".",
"name",
"==",
"'_no_model'",
"@create_id",
"=",
"false",
"if",
"attribute",
".",
"name",
"==",
"\"_id\"",
"&&",
"attribute",
".",
"type",
"==",
":false",
"end",
"@flag_create_controller",
"=",
"@flag_create_model",
"@flag_create_resource_route",
"=",
"@flag_create_model",
"end"
] | using flags. | [
"using",
"flags",
"."
] | c2fb3c992d7c1e1371f5a20d559855c6bdba21b4 | https://github.com/acesuares/inline_forms/blob/c2fb3c992d7c1e1371f5a20d559855c6bdba21b4/lib/generators/inline_forms_generator.rb#L78-L91 | train |
bitaxis/rack-cas-rails | lib/rack-cas-rails/action_controller_base_additions.rb | RackCASRails.ActionControllerBaseAdditions.login_url | def login_url(service_url=request.url)
url = URI(Rails.application.cas_server_url)
url.path = "/login"
url.query = "service=#{service_url || request.url}"
url.to_s
end | ruby | def login_url(service_url=request.url)
url = URI(Rails.application.cas_server_url)
url.path = "/login"
url.query = "service=#{service_url || request.url}"
url.to_s
end | [
"def",
"login_url",
"(",
"service_url",
"=",
"request",
".",
"url",
")",
"url",
"=",
"URI",
"(",
"Rails",
".",
"application",
".",
"cas_server_url",
")",
"url",
".",
"path",
"=",
"\"/login\"",
"url",
".",
"query",
"=",
"\"service=#{service_url || request.url}\"",
"url",
".",
"to_s",
"end"
] | Renders the CAS login URL with re-direct back to some URL.
@param service_url [String] Optional url to redirect to after authentication.
@return [String] The CAS login URL. | [
"Renders",
"the",
"CAS",
"login",
"URL",
"with",
"re",
"-",
"direct",
"back",
"to",
"some",
"URL",
"."
] | a2ebc5ce2803868235c6a8ec6b1f018d3caac832 | https://github.com/bitaxis/rack-cas-rails/blob/a2ebc5ce2803868235c6a8ec6b1f018d3caac832/lib/rack-cas-rails/action_controller_base_additions.rb#L31-L36 | train |
altabyte/ebay_trader | lib/ebay_trader/sax_handler.rb | EbayTrader.SaxHandler.format_key | def format_key(key)
key = key.to_s
key = key.gsub('PayPal', 'Paypal')
key = key.gsub('eBay', 'Ebay')
key = key.gsub('EBay', 'Ebay')
key.underscore.to_sym
end | ruby | def format_key(key)
key = key.to_s
key = key.gsub('PayPal', 'Paypal')
key = key.gsub('eBay', 'Ebay')
key = key.gsub('EBay', 'Ebay')
key.underscore.to_sym
end | [
"def",
"format_key",
"(",
"key",
")",
"key",
"=",
"key",
".",
"to_s",
"key",
"=",
"key",
".",
"gsub",
"(",
"'PayPal'",
",",
"'Paypal'",
")",
"key",
"=",
"key",
".",
"gsub",
"(",
"'eBay'",
",",
"'Ebay'",
")",
"key",
"=",
"key",
".",
"gsub",
"(",
"'EBay'",
",",
"'Ebay'",
")",
"key",
".",
"underscore",
".",
"to_sym",
"end"
] | Ensure the key is an underscored Symbol.
Examples:
'ApplyBuyerProtection' -> :apply_buyer_protection
'PayPalEmailAddress' -> :paypal_email_address
'SoldOffeBay' -> :sold_off_ebay
@return [Symbol] the reformatted key. | [
"Ensure",
"the",
"key",
"is",
"an",
"underscored",
"Symbol",
"."
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/sax_handler.rb#L145-L151 | train |
jdigger/git-process | lib/git-process/git_lib.rb | GitProc.GitLib.push_to_server | def push_to_server(local_branch, remote_branch, opts = {})
if opts[:local]
logger.debug('Not pushing to the server because the user selected local-only.')
elsif not has_a_remote?
logger.debug('Not pushing to the server because there is no remote.')
elsif local_branch == config.master_branch
logger.warn('Not pushing to the server because the current branch is the mainline branch.')
else
opts[:prepush].call if opts[:prepush]
push(remote.name, local_branch, remote_branch, :force => opts[:force])
opts[:postpush].call if opts[:postpush]
end
end | ruby | def push_to_server(local_branch, remote_branch, opts = {})
if opts[:local]
logger.debug('Not pushing to the server because the user selected local-only.')
elsif not has_a_remote?
logger.debug('Not pushing to the server because there is no remote.')
elsif local_branch == config.master_branch
logger.warn('Not pushing to the server because the current branch is the mainline branch.')
else
opts[:prepush].call if opts[:prepush]
push(remote.name, local_branch, remote_branch, :force => opts[:force])
opts[:postpush].call if opts[:postpush]
end
end | [
"def",
"push_to_server",
"(",
"local_branch",
",",
"remote_branch",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"opts",
"[",
":local",
"]",
"logger",
".",
"debug",
"(",
"'Not pushing to the server because the user selected local-only.'",
")",
"elsif",
"not",
"has_a_remote?",
"logger",
".",
"debug",
"(",
"'Not pushing to the server because there is no remote.'",
")",
"elsif",
"local_branch",
"==",
"config",
".",
"master_branch",
"logger",
".",
"warn",
"(",
"'Not pushing to the server because the current branch is the mainline branch.'",
")",
"else",
"opts",
"[",
":prepush",
"]",
".",
"call",
"if",
"opts",
"[",
":prepush",
"]",
"push",
"(",
"remote",
".",
"name",
",",
"local_branch",
",",
"remote_branch",
",",
":force",
"=>",
"opts",
"[",
":force",
"]",
")",
"opts",
"[",
":postpush",
"]",
".",
"call",
"if",
"opts",
"[",
":postpush",
"]",
"end",
"end"
] | Push the repository to the server.
@param local_branch [String] the name of the local branch to push from
@param remote_branch [String] the name of the remote branch to push to
@option opts [Boolean] :local should this do nothing because it is in local-only mode?
@option opts [Boolean] :force should it force the push even if it can not fast-forward?
@option opts [Proc] :prepush a block to call before doing the push
@option opts [Proc] :postpush a block to call after doing the push
@return [void] | [
"Push",
"the",
"repository",
"to",
"the",
"server",
"."
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L206-L220 | train |
jdigger/git-process | lib/git-process/git_lib.rb | GitProc.GitLib.branch | def branch(branch_name, opts = {})
if branch_name
if opts[:delete]
return delete_branch(branch_name, opts[:force])
elsif opts[:rename]
return rename_branch(branch_name, opts[:rename])
elsif opts[:upstream]
return set_upstream_branch(branch_name, opts[:upstream])
else
base_branch = opts[:base_branch] || 'master'
if opts[:force]
return change_branch(branch_name, base_branch)
else
return create_branch(branch_name, base_branch)
end
end
else
#list_branches(opts)
return list_branches(opts[:all], opts[:remote], opts[:no_color])
end
end | ruby | def branch(branch_name, opts = {})
if branch_name
if opts[:delete]
return delete_branch(branch_name, opts[:force])
elsif opts[:rename]
return rename_branch(branch_name, opts[:rename])
elsif opts[:upstream]
return set_upstream_branch(branch_name, opts[:upstream])
else
base_branch = opts[:base_branch] || 'master'
if opts[:force]
return change_branch(branch_name, base_branch)
else
return create_branch(branch_name, base_branch)
end
end
else
#list_branches(opts)
return list_branches(opts[:all], opts[:remote], opts[:no_color])
end
end | [
"def",
"branch",
"(",
"branch_name",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"branch_name",
"if",
"opts",
"[",
":delete",
"]",
"return",
"delete_branch",
"(",
"branch_name",
",",
"opts",
"[",
":force",
"]",
")",
"elsif",
"opts",
"[",
":rename",
"]",
"return",
"rename_branch",
"(",
"branch_name",
",",
"opts",
"[",
":rename",
"]",
")",
"elsif",
"opts",
"[",
":upstream",
"]",
"return",
"set_upstream_branch",
"(",
"branch_name",
",",
"opts",
"[",
":upstream",
"]",
")",
"else",
"base_branch",
"=",
"opts",
"[",
":base_branch",
"]",
"||",
"'master'",
"if",
"opts",
"[",
":force",
"]",
"return",
"change_branch",
"(",
"branch_name",
",",
"base_branch",
")",
"else",
"return",
"create_branch",
"(",
"branch_name",
",",
"base_branch",
")",
"end",
"end",
"else",
"return",
"list_branches",
"(",
"opts",
"[",
":all",
"]",
",",
"opts",
"[",
":remote",
"]",
",",
"opts",
"[",
":no_color",
"]",
")",
"end",
"end"
] | Does branch manipulation.
@param [String] branch_name the name of the branch
@option opts [Boolean] :delete delete the remote branch
@option opts [Boolean] :force force the update
@option opts [Boolean] :all list all branches, local and remote
@option opts [Boolean] :no_color force not using any ANSI color codes
@option opts [String] :rename the new name for the branch
@option opts [String] :upstream the new branch to track
@option opts [String] :base_branch ('master') the branch to base the new branch off of
@return [String] the output of running the git command | [
"Does",
"branch",
"manipulation",
"."
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L382-L402 | train |
jdigger/git-process | lib/git-process/git_lib.rb | GitProc.GitLib.remove | def remove(files, opts = {})
args = []
args << '-f' if opts[:force]
args << [*files]
command(:rm, args)
end | ruby | def remove(files, opts = {})
args = []
args << '-f' if opts[:force]
args << [*files]
command(:rm, args)
end | [
"def",
"remove",
"(",
"files",
",",
"opts",
"=",
"{",
"}",
")",
"args",
"=",
"[",
"]",
"args",
"<<",
"'-f'",
"if",
"opts",
"[",
":force",
"]",
"args",
"<<",
"[",
"*",
"files",
"]",
"command",
"(",
":rm",
",",
"args",
")",
"end"
] | Remove the files from the Index
@param [Array<String>] files the file names to remove from the Index
@option opts :force if exists and not false, will force the removal of the files
@return [String] the output of the git command | [
"Remove",
"the",
"files",
"from",
"the",
"Index"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L571-L576 | train |
jdigger/git-process | lib/git-process/git_lib.rb | GitProc.GitLib.write_sync_control_file | def write_sync_control_file(branch_name)
latest_sha = rev_parse(branch_name)
filename = sync_control_filename(branch_name)
logger.debug { "Writing sync control file, #{filename}, with #{latest_sha}" }
File.open(filename, 'w') { |f| f.puts latest_sha }
end | ruby | def write_sync_control_file(branch_name)
latest_sha = rev_parse(branch_name)
filename = sync_control_filename(branch_name)
logger.debug { "Writing sync control file, #{filename}, with #{latest_sha}" }
File.open(filename, 'w') { |f| f.puts latest_sha }
end | [
"def",
"write_sync_control_file",
"(",
"branch_name",
")",
"latest_sha",
"=",
"rev_parse",
"(",
"branch_name",
")",
"filename",
"=",
"sync_control_filename",
"(",
"branch_name",
")",
"logger",
".",
"debug",
"{",
"\"Writing sync control file, #{filename}, with #{latest_sha}\"",
"}",
"File",
".",
"open",
"(",
"filename",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"puts",
"latest_sha",
"}",
"end"
] | Writes the current SHA-1 for the tip of the branch to the "sync control file"
@return [void]
@see GitLib#read_sync_control_file | [
"Writes",
"the",
"current",
"SHA",
"-",
"1",
"for",
"the",
"tip",
"of",
"the",
"branch",
"to",
"the",
"sync",
"control",
"file"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L670-L675 | train |
jdigger/git-process | lib/git-process/git_lib.rb | GitProc.GitLib.delete_sync_control_file! | def delete_sync_control_file!(branch_name)
filename = sync_control_filename(branch_name)
logger.debug { "Deleting sync control file, #{filename}" }
# on some systems, especially Windows, the file may be locked. wait for it to unlock
counter = 10
while counter > 0
begin
File.delete(filename)
counter = 0
rescue
counter = counter - 1
sleep(0.25)
end
end
end | ruby | def delete_sync_control_file!(branch_name)
filename = sync_control_filename(branch_name)
logger.debug { "Deleting sync control file, #{filename}" }
# on some systems, especially Windows, the file may be locked. wait for it to unlock
counter = 10
while counter > 0
begin
File.delete(filename)
counter = 0
rescue
counter = counter - 1
sleep(0.25)
end
end
end | [
"def",
"delete_sync_control_file!",
"(",
"branch_name",
")",
"filename",
"=",
"sync_control_filename",
"(",
"branch_name",
")",
"logger",
".",
"debug",
"{",
"\"Deleting sync control file, #{filename}\"",
"}",
"counter",
"=",
"10",
"while",
"counter",
">",
"0",
"begin",
"File",
".",
"delete",
"(",
"filename",
")",
"counter",
"=",
"0",
"rescue",
"counter",
"=",
"counter",
"-",
"1",
"sleep",
"(",
"0.25",
")",
"end",
"end",
"end"
] | Delete the sync control file for the branch
@return [void]
@see GitLib#write_sync_control_file | [
"Delete",
"the",
"sync",
"control",
"file",
"for",
"the",
"branch"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L700-L715 | train |
jdigger/git-process | lib/git-process/git_lib.rb | GitProc.GitLib.create_git_command | def create_git_command(cmd, opts, redirect)
opts = [opts].flatten.map { |s| escape(s) }.join(' ')
return "git #{cmd} #{opts} #{redirect} 2>&1"
end | ruby | def create_git_command(cmd, opts, redirect)
opts = [opts].flatten.map { |s| escape(s) }.join(' ')
return "git #{cmd} #{opts} #{redirect} 2>&1"
end | [
"def",
"create_git_command",
"(",
"cmd",
",",
"opts",
",",
"redirect",
")",
"opts",
"=",
"[",
"opts",
"]",
".",
"flatten",
".",
"map",
"{",
"|",
"s",
"|",
"escape",
"(",
"s",
")",
"}",
".",
"join",
"(",
"' '",
")",
"return",
"\"git #{cmd} #{opts} #{redirect} 2>&1\"",
"end"
] | Create the CLI for the git command
@param [Symbol, String] cmd the command to run (e.g., :commit)
@param [Array<String, Symbol>] opts the arguments to pass to the command
@param [String] redirect ???????
@return [String] the command line to run | [
"Create",
"the",
"CLI",
"for",
"the",
"git",
"command"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L761-L764 | train |
rapid7/metasploit-model | lib/metasploit/model/search/with.rb | Metasploit::Model::Search::With.ClassMethods.search_with | def search_with(operator_class, options={})
merged_operations = options.merge(
:klass => self
)
operator = operator_class.new(merged_operations)
operator.valid!
search_with_operator_by_name[operator.name] = operator
end | ruby | def search_with(operator_class, options={})
merged_operations = options.merge(
:klass => self
)
operator = operator_class.new(merged_operations)
operator.valid!
search_with_operator_by_name[operator.name] = operator
end | [
"def",
"search_with",
"(",
"operator_class",
",",
"options",
"=",
"{",
"}",
")",
"merged_operations",
"=",
"options",
".",
"merge",
"(",
":klass",
"=>",
"self",
")",
"operator",
"=",
"operator_class",
".",
"new",
"(",
"merged_operations",
")",
"operator",
".",
"valid!",
"search_with_operator_by_name",
"[",
"operator",
".",
"name",
"]",
"=",
"operator",
"end"
] | Declares that this class should be search with an instance of the given `operator_class`.
@param operator_class [Class<Metasploit::Model::Search::Operator::Base>] a class to initialize.
@param options [Hash] Options passed to `operator_class.new` along with `{:klass => self}`, so that the
`operator_class` instance knows it was registered as search this class.
@return [Metasploit::Model::Search::Operator::Base]
@raise (see Metasploit::Model::Base#invalid!) | [
"Declares",
"that",
"this",
"class",
"should",
"be",
"search",
"with",
"an",
"instance",
"of",
"the",
"given",
"operator_class",
"."
] | cb6606bf24218798e853ba44470df31a47d9b627 | https://github.com/rapid7/metasploit-model/blob/cb6606bf24218798e853ba44470df31a47d9b627/lib/metasploit/model/search/with.rb#L58-L66 | train |
djellemah/philtre | lib/philtre/place_holder.rb | Philtre.PlaceHolder.to_s_append | def to_s_append( ds, s )
s << '$' << name.to_s
s << ':' << sql_field.to_s if sql_field
s << '/*' << small_source << '*/'
end | ruby | def to_s_append( ds, s )
s << '$' << name.to_s
s << ':' << sql_field.to_s if sql_field
s << '/*' << small_source << '*/'
end | [
"def",
"to_s_append",
"(",
"ds",
",",
"s",
")",
"s",
"<<",
"'$'",
"<<",
"name",
".",
"to_s",
"s",
"<<",
"':'",
"<<",
"sql_field",
".",
"to_s",
"if",
"sql_field",
"s",
"<<",
"'/*'",
"<<",
"small_source",
"<<",
"'*/'",
"end"
] | this is inserted into the generated SQL from a dataset that
contains PlaceHolder instances. | [
"this",
"is",
"inserted",
"into",
"the",
"generated",
"SQL",
"from",
"a",
"dataset",
"that",
"contains",
"PlaceHolder",
"instances",
"."
] | d0407b9eccaee8918a86ea25feabf500a3b2ac1a | https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/place_holder.rb#L19-L23 | train |
djellemah/philtre | lib/philtre/filter.rb | Philtre.Filter.call | def call( dataset )
# mainly for Sequel::Model
dataset = dataset.dataset if dataset.respond_to? :dataset
# clone here so later order! calls don't mess with a Model's default dataset
dataset = expressions.inject(dataset.clone) do |dataset, filter_expr|
dataset.filter( filter_expr )
end
# preserve existing order if we don't have one.
if order_clause.empty?
dataset
else
# There might be multiple orderings in the order_clause
dataset.order *order_clause
end
end | ruby | def call( dataset )
# mainly for Sequel::Model
dataset = dataset.dataset if dataset.respond_to? :dataset
# clone here so later order! calls don't mess with a Model's default dataset
dataset = expressions.inject(dataset.clone) do |dataset, filter_expr|
dataset.filter( filter_expr )
end
# preserve existing order if we don't have one.
if order_clause.empty?
dataset
else
# There might be multiple orderings in the order_clause
dataset.order *order_clause
end
end | [
"def",
"call",
"(",
"dataset",
")",
"dataset",
"=",
"dataset",
".",
"dataset",
"if",
"dataset",
".",
"respond_to?",
":dataset",
"dataset",
"=",
"expressions",
".",
"inject",
"(",
"dataset",
".",
"clone",
")",
"do",
"|",
"dataset",
",",
"filter_expr",
"|",
"dataset",
".",
"filter",
"(",
"filter_expr",
")",
"end",
"if",
"order_clause",
".",
"empty?",
"dataset",
"else",
"dataset",
".",
"order",
"*",
"order_clause",
"end",
"end"
] | return a modified dataset containing all the predicates | [
"return",
"a",
"modified",
"dataset",
"containing",
"all",
"the",
"predicates"
] | d0407b9eccaee8918a86ea25feabf500a3b2ac1a | https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L51-L67 | train |
djellemah/philtre | lib/philtre/filter.rb | Philtre.Filter.valued_parameters | def valued_parameters
@valued_parameters ||= filter_parameters.select do |key,value|
# :order is special, it must always be excluded
key.to_sym != :order && valued_parameter?(key,value)
end
end | ruby | def valued_parameters
@valued_parameters ||= filter_parameters.select do |key,value|
# :order is special, it must always be excluded
key.to_sym != :order && valued_parameter?(key,value)
end
end | [
"def",
"valued_parameters",
"@valued_parameters",
"||=",
"filter_parameters",
".",
"select",
"do",
"|",
"key",
",",
"value",
"|",
"key",
".",
"to_sym",
"!=",
":order",
"&&",
"valued_parameter?",
"(",
"key",
",",
"value",
")",
"end",
"end"
] | Values in the parameter list which are not blank, and not
an ordering. That is, parameters which will be used to generate
the filter expression. | [
"Values",
"in",
"the",
"parameter",
"list",
"which",
"are",
"not",
"blank",
"and",
"not",
"an",
"ordering",
".",
"That",
"is",
"parameters",
"which",
"will",
"be",
"used",
"to",
"generate",
"the",
"filter",
"expression",
"."
] | d0407b9eccaee8918a86ea25feabf500a3b2ac1a | https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L83-L88 | train |
djellemah/philtre | lib/philtre/filter.rb | Philtre.Filter.to_h | def to_h(all=false)
filter_parameters.select{|k,v| all || !v.blank?}
end | ruby | def to_h(all=false)
filter_parameters.select{|k,v| all || !v.blank?}
end | [
"def",
"to_h",
"(",
"all",
"=",
"false",
")",
"filter_parameters",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"all",
"||",
"!",
"v",
".",
"blank?",
"}",
"end"
] | for use in forms | [
"for",
"use",
"in",
"forms"
] | d0407b9eccaee8918a86ea25feabf500a3b2ac1a | https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L165-L167 | train |
djellemah/philtre | lib/philtre/filter.rb | Philtre.Filter.expr_hash | def expr_hash
vary = valued_parameters.map do |key, value|
[ key, to_expr(key, value) ]
end
Hash[ vary ]
end | ruby | def expr_hash
vary = valued_parameters.map do |key, value|
[ key, to_expr(key, value) ]
end
Hash[ vary ]
end | [
"def",
"expr_hash",
"vary",
"=",
"valued_parameters",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"[",
"key",
",",
"to_expr",
"(",
"key",
",",
"value",
")",
"]",
"end",
"Hash",
"[",
"vary",
"]",
"end"
] | hash of keys to expressions, but only where
there are values. | [
"hash",
"of",
"keys",
"to",
"expressions",
"but",
"only",
"where",
"there",
"are",
"values",
"."
] | d0407b9eccaee8918a86ea25feabf500a3b2ac1a | https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L224-L230 | train |
distil/jserializer | lib/jserializer/base.rb | Jserializer.Base.serializable_hash | def serializable_hash
return serializable_collection if collection?
self.class._attributes.each_with_object({}) do |(name, option), hash|
if _include_from_options?(name) && public_send(option[:include_method])
hash[option[:key] || name] = _set_value(name, option)
end
end
end | ruby | def serializable_hash
return serializable_collection if collection?
self.class._attributes.each_with_object({}) do |(name, option), hash|
if _include_from_options?(name) && public_send(option[:include_method])
hash[option[:key] || name] = _set_value(name, option)
end
end
end | [
"def",
"serializable_hash",
"return",
"serializable_collection",
"if",
"collection?",
"self",
".",
"class",
".",
"_attributes",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"name",
",",
"option",
")",
",",
"hash",
"|",
"if",
"_include_from_options?",
"(",
"name",
")",
"&&",
"public_send",
"(",
"option",
"[",
":include_method",
"]",
")",
"hash",
"[",
"option",
"[",
":key",
"]",
"||",
"name",
"]",
"=",
"_set_value",
"(",
"name",
",",
"option",
")",
"end",
"end",
"end"
] | Returns a hash representation without the root | [
"Returns",
"a",
"hash",
"representation",
"without",
"the",
"root"
] | 7125abb379d7d2b7b7001ecefc8378202542d46c | https://github.com/distil/jserializer/blob/7125abb379d7d2b7b7001ecefc8378202542d46c/lib/jserializer/base.rb#L120-L127 | train |
jdigger/git-process | lib/git-process/git_branch.rb | GitProc.GitBranch.delete! | def delete!(force = false)
if local?
@lib.branch(@name, :force => force, :delete => true)
else
@lib.push(Process.server_name, nil, nil, :delete => @name)
end
end | ruby | def delete!(force = false)
if local?
@lib.branch(@name, :force => force, :delete => true)
else
@lib.push(Process.server_name, nil, nil, :delete => @name)
end
end | [
"def",
"delete!",
"(",
"force",
"=",
"false",
")",
"if",
"local?",
"@lib",
".",
"branch",
"(",
"@name",
",",
":force",
"=>",
"force",
",",
":delete",
"=>",
"true",
")",
"else",
"@lib",
".",
"push",
"(",
"Process",
".",
"server_name",
",",
"nil",
",",
"nil",
",",
":delete",
"=>",
"@name",
")",
"end",
"end"
] | Delete this branch
@param [Boolean] force should this force removal even if the branch has not been fully merged?
@return [String] the output of running the git command | [
"Delete",
"this",
"branch"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_branch.rb#L114-L120 | train |
rapid7/metasploit-model | lib/metasploit/model/search.rb | Metasploit::Model::Search.ClassMethods.search_operator_by_name | def search_operator_by_name
unless instance_variable_defined? :@search_operator_by_name
@search_operator_by_name = {}
search_with_operator_by_name.each_value do |operator|
@search_operator_by_name[operator.name] = operator
end
search_association_operators.each do |operator|
@search_operator_by_name[operator.name] = operator
end
end
@search_operator_by_name
end | ruby | def search_operator_by_name
unless instance_variable_defined? :@search_operator_by_name
@search_operator_by_name = {}
search_with_operator_by_name.each_value do |operator|
@search_operator_by_name[operator.name] = operator
end
search_association_operators.each do |operator|
@search_operator_by_name[operator.name] = operator
end
end
@search_operator_by_name
end | [
"def",
"search_operator_by_name",
"unless",
"instance_variable_defined?",
":@search_operator_by_name",
"@search_operator_by_name",
"=",
"{",
"}",
"search_with_operator_by_name",
".",
"each_value",
"do",
"|",
"operator",
"|",
"@search_operator_by_name",
"[",
"operator",
".",
"name",
"]",
"=",
"operator",
"end",
"search_association_operators",
".",
"each",
"do",
"|",
"operator",
"|",
"@search_operator_by_name",
"[",
"operator",
".",
"name",
"]",
"=",
"operator",
"end",
"end",
"@search_operator_by_name",
"end"
] | Collects all search attributes from search associations and all attributes from this class to show the valid
search operators to search.
@return [Hash{Symbol => Metasploit::Model::Search::Operator}] Maps
{Metasploit::Model::Search::Operator::Base#name} to {Metasploit::Model::Search::Operator::Base#name}. | [
"Collects",
"all",
"search",
"attributes",
"from",
"search",
"associations",
"and",
"all",
"attributes",
"from",
"this",
"class",
"to",
"show",
"the",
"valid",
"search",
"operators",
"to",
"search",
"."
] | cb6606bf24218798e853ba44470df31a47d9b627 | https://github.com/rapid7/metasploit-model/blob/cb6606bf24218798e853ba44470df31a47d9b627/lib/metasploit/model/search.rb#L87-L101 | train |
altabyte/ebay_trader | lib/ebay_trader/xml_builder.rb | EbayTrader.XMLBuilder.root | def root(name, *args, &block)
set_context(&block)
node(name, args, &block)
end | ruby | def root(name, *args, &block)
set_context(&block)
node(name, args, &block)
end | [
"def",
"root",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"set_context",
"(",
"&",
"block",
")",
"node",
"(",
"name",
",",
"args",
",",
"&",
"block",
")",
"end"
] | Begin creating an XML string by specifying the root node.
This also sets the context scope, allowing methods and variables
outside the block to be accessed.
@param [String] name the name of the root node element.
@param [Array] args the data for this element.
@param [Block] block an optional block of sub-elements to be nested
within the root node. | [
"Begin",
"creating",
"an",
"XML",
"string",
"by",
"specifying",
"the",
"root",
"node",
".",
"This",
"also",
"sets",
"the",
"context",
"scope",
"allowing",
"methods",
"and",
"variables",
"outside",
"the",
"block",
"to",
"be",
"accessed",
"."
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L36-L39 | train |
altabyte/ebay_trader | lib/ebay_trader/xml_builder.rb | EbayTrader.XMLBuilder.node | def node(name, args, &block)
content = get_node_content(args)
options = format_node_attributes(get_node_attributes(args))
@_segments ||= []
@_segments << "#{indent_new_line}<#{name}#{options}>#{content}"
if block_given?
@depth += 1
instance_eval(&block)
@depth -= 1
@_segments << indent_new_line
end
@_segments << "</#{name}>"
@xml = @_segments.join('').strip
end | ruby | def node(name, args, &block)
content = get_node_content(args)
options = format_node_attributes(get_node_attributes(args))
@_segments ||= []
@_segments << "#{indent_new_line}<#{name}#{options}>#{content}"
if block_given?
@depth += 1
instance_eval(&block)
@depth -= 1
@_segments << indent_new_line
end
@_segments << "</#{name}>"
@xml = @_segments.join('').strip
end | [
"def",
"node",
"(",
"name",
",",
"args",
",",
"&",
"block",
")",
"content",
"=",
"get_node_content",
"(",
"args",
")",
"options",
"=",
"format_node_attributes",
"(",
"get_node_attributes",
"(",
"args",
")",
")",
"@_segments",
"||=",
"[",
"]",
"@_segments",
"<<",
"\"#{indent_new_line}<#{name}#{options}>#{content}\"",
"if",
"block_given?",
"@depth",
"+=",
"1",
"instance_eval",
"(",
"&",
"block",
")",
"@depth",
"-=",
"1",
"@_segments",
"<<",
"indent_new_line",
"end",
"@_segments",
"<<",
"\"</#{name}>\"",
"@xml",
"=",
"@_segments",
".",
"join",
"(",
"''",
")",
".",
"strip",
"end"
] | Create an XML node
@param [String|Symbol] name the name of the XML element (ul, li, strong, etc...)
@param [Array] args Can contain a String of text or a Hash of attributes
@param [Block] block An optional block which will further nest XML | [
"Create",
"an",
"XML",
"node"
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L54-L68 | train |
altabyte/ebay_trader | lib/ebay_trader/xml_builder.rb | EbayTrader.XMLBuilder.get_node_content | def get_node_content(args)
return nil if block_given?
content = nil
args.each do |arg|
case arg
when Hash
next
when Time
# eBay official TimeStamp format YYYY-MM-DDTHH:MM:SS.SSSZ
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
when DateTime
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
break
else
content = arg.to_s
break
end
end
content
end | ruby | def get_node_content(args)
return nil if block_given?
content = nil
args.each do |arg|
case arg
when Hash
next
when Time
# eBay official TimeStamp format YYYY-MM-DDTHH:MM:SS.SSSZ
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
when DateTime
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
break
else
content = arg.to_s
break
end
end
content
end | [
"def",
"get_node_content",
"(",
"args",
")",
"return",
"nil",
"if",
"block_given?",
"content",
"=",
"nil",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"case",
"arg",
"when",
"Hash",
"next",
"when",
"Time",
"content",
"=",
"arg",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S.%Z'",
")",
"when",
"DateTime",
"content",
"=",
"arg",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S.%Z'",
")",
"break",
"else",
"content",
"=",
"arg",
".",
"to_s",
"break",
"end",
"end",
"content",
"end"
] | Return the node content as a String, unless a block is given.
@return [String] the node data. | [
"Return",
"the",
"node",
"content",
"as",
"a",
"String",
"unless",
"a",
"block",
"is",
"given",
"."
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L81-L100 | train |
altabyte/ebay_trader | lib/ebay_trader/xml_builder.rb | EbayTrader.XMLBuilder.format_node_attributes | def format_node_attributes(options)
options.collect { |key, value|
value = value.to_s.gsub('"', '\"')
" #{key}=\"#{value}\""
}.join('')
end | ruby | def format_node_attributes(options)
options.collect { |key, value|
value = value.to_s.gsub('"', '\"')
" #{key}=\"#{value}\""
}.join('')
end | [
"def",
"format_node_attributes",
"(",
"options",
")",
"options",
".",
"collect",
"{",
"|",
"key",
",",
"value",
"|",
"value",
"=",
"value",
".",
"to_s",
".",
"gsub",
"(",
"'\"'",
",",
"'\\\"'",
")",
"\" #{key}=\\\"#{value}\\\"\"",
"}",
".",
"join",
"(",
"''",
")",
"end"
] | Convert the given Hash of options into a string of XML element attributes. | [
"Convert",
"the",
"given",
"Hash",
"of",
"options",
"into",
"a",
"string",
"of",
"XML",
"element",
"attributes",
"."
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L104-L109 | train |
artursbraucs/mailigen | lib/mailigen/api.rb | Mailigen.Api.call | def call method, params = {}
url = "#{api_url}&method=#{method}"
params = {apikey: self.api_key}.merge params
resp = post_api(url, params)
begin
return JSON.parse(resp)
rescue
return resp.tr('"','')
end
end | ruby | def call method, params = {}
url = "#{api_url}&method=#{method}"
params = {apikey: self.api_key}.merge params
resp = post_api(url, params)
begin
return JSON.parse(resp)
rescue
return resp.tr('"','')
end
end | [
"def",
"call",
"method",
",",
"params",
"=",
"{",
"}",
"url",
"=",
"\"#{api_url}&method=#{method}\"",
"params",
"=",
"{",
"apikey",
":",
"self",
".",
"api_key",
"}",
".",
"merge",
"params",
"resp",
"=",
"post_api",
"(",
"url",
",",
"params",
")",
"begin",
"return",
"JSON",
".",
"parse",
"(",
"resp",
")",
"rescue",
"return",
"resp",
".",
"tr",
"(",
"'\"'",
",",
"''",
")",
"end",
"end"
] | Initialize API wrapper.
@param api_key - from mailigen.com . Required.
@param secure - use SSL. By default FALSE
Call Mailigen api method (Documented in http://dev.mailigen.com/display/AD/Mailigen+API )
@param method - method name
@param params - params if required for API
@return
JSON, String data if all goes well.
Exception if somethnigs goes wrong. | [
"Initialize",
"API",
"wrapper",
"."
] | fb87e72242cfabc2bc4aad0844993d71ed2ff53d | https://github.com/artursbraucs/mailigen/blob/fb87e72242cfabc2bc4aad0844993d71ed2ff53d/lib/mailigen/api.rb#L32-L43 | train |
artursbraucs/mailigen | lib/mailigen/api.rb | Mailigen.Api.post_api | def post_api url, params
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = self.secure
form_params = params.to_query
res = http.post(uri.request_uri, form_params)
res.body
end | ruby | def post_api url, params
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = self.secure
form_params = params.to_query
res = http.post(uri.request_uri, form_params)
res.body
end | [
"def",
"post_api",
"url",
",",
"params",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"self",
".",
"secure",
"form_params",
"=",
"params",
".",
"to_query",
"res",
"=",
"http",
".",
"post",
"(",
"uri",
".",
"request_uri",
",",
"form_params",
")",
"res",
".",
"body",
"end"
] | All api calls throught POST method.
@param url - url to post
@param params - params in hash
@return
response body | [
"All",
"api",
"calls",
"throught",
"POST",
"method",
"."
] | fb87e72242cfabc2bc4aad0844993d71ed2ff53d | https://github.com/artursbraucs/mailigen/blob/fb87e72242cfabc2bc4aad0844993d71ed2ff53d/lib/mailigen/api.rb#L62-L69 | train |
toptierlabs/api_explorer | app/controllers/api_explorer/api_controller.rb | ApiExplorer.ApiController.read_file | def read_file
json_string = ''
if ApiExplorer::use_file
json_path = ApiExplorer::json_path
json_string = File.read(json_path)
else
json_string = ApiExplorer::json_string
end
@methods = JSON.parse(json_string)["methods"]
end | ruby | def read_file
json_string = ''
if ApiExplorer::use_file
json_path = ApiExplorer::json_path
json_string = File.read(json_path)
else
json_string = ApiExplorer::json_string
end
@methods = JSON.parse(json_string)["methods"]
end | [
"def",
"read_file",
"json_string",
"=",
"''",
"if",
"ApiExplorer",
"::",
"use_file",
"json_path",
"=",
"ApiExplorer",
"::",
"json_path",
"json_string",
"=",
"File",
".",
"read",
"(",
"json_path",
")",
"else",
"json_string",
"=",
"ApiExplorer",
"::",
"json_string",
"end",
"@methods",
"=",
"JSON",
".",
"parse",
"(",
"json_string",
")",
"[",
"\"methods\"",
"]",
"end"
] | Read file with methods | [
"Read",
"file",
"with",
"methods"
] | 14b9ad9c687b8c85f178ac7b60887ebe070f182f | https://github.com/toptierlabs/api_explorer/blob/14b9ad9c687b8c85f178ac7b60887ebe070f182f/app/controllers/api_explorer/api_controller.rb#L138-L148 | train |
haberbyte/phoney | lib/phoney/formatter.rb | Phoney.Formatter.format | def format(input, pattern, options={})
fill = options[:fill]
intl_prefix = options[:intl_prefix]||''
trunk_prefix = options[:trunk_prefix]||''
slots = pattern.count(PLACEHOLDER_CHAR)
# Return original input if it is too long
return input if (fill.nil? && input.length > slots)
# Pad and clone the string if necessary.
source = (fill.nil? || fill.empty?) ? input : input.ljust(slots, fill)
result = ''
slot = 0
has_open = had_c = had_n = false
pattern.split('').each_with_index do |chr, index|
case chr
when 'c'
had_c = true
result << intl_prefix
when 'n'
had_n = true
result << trunk_prefix
when '#'
if slot < source.length
result << source[slot]
slot += 1
else
result << ' ' if has_open
end
when '('
if slot < source.length
has_open = true
result << chr
end
when ')'
if (slot < source.length || has_open)
has_open = false
result << chr
end
else
# Don't show space after n if no trunk prefix or after c if no intl prefix
next if (chr == ' ' && pattern[index-1] == 'n' && trunk_prefix.empty?)
next if (chr == ' ' && pattern[index-1] == 'c' && intl_prefix.empty?)
result << chr if (slot < source.length)
end
end
# Not all format strings have a 'c' or 'n' in them.
# If we have an international prefix or a trunk prefix but the format string
# doesn't explictly say where to put it then simply add it to the beginning.
result.prepend trunk_prefix if (!had_n && !trunk_prefix.empty?)
result.prepend "#{intl_prefix} " if (!had_c && !intl_prefix.empty?)
result.strip
end | ruby | def format(input, pattern, options={})
fill = options[:fill]
intl_prefix = options[:intl_prefix]||''
trunk_prefix = options[:trunk_prefix]||''
slots = pattern.count(PLACEHOLDER_CHAR)
# Return original input if it is too long
return input if (fill.nil? && input.length > slots)
# Pad and clone the string if necessary.
source = (fill.nil? || fill.empty?) ? input : input.ljust(slots, fill)
result = ''
slot = 0
has_open = had_c = had_n = false
pattern.split('').each_with_index do |chr, index|
case chr
when 'c'
had_c = true
result << intl_prefix
when 'n'
had_n = true
result << trunk_prefix
when '#'
if slot < source.length
result << source[slot]
slot += 1
else
result << ' ' if has_open
end
when '('
if slot < source.length
has_open = true
result << chr
end
when ')'
if (slot < source.length || has_open)
has_open = false
result << chr
end
else
# Don't show space after n if no trunk prefix or after c if no intl prefix
next if (chr == ' ' && pattern[index-1] == 'n' && trunk_prefix.empty?)
next if (chr == ' ' && pattern[index-1] == 'c' && intl_prefix.empty?)
result << chr if (slot < source.length)
end
end
# Not all format strings have a 'c' or 'n' in them.
# If we have an international prefix or a trunk prefix but the format string
# doesn't explictly say where to put it then simply add it to the beginning.
result.prepend trunk_prefix if (!had_n && !trunk_prefix.empty?)
result.prepend "#{intl_prefix} " if (!had_c && !intl_prefix.empty?)
result.strip
end | [
"def",
"format",
"(",
"input",
",",
"pattern",
",",
"options",
"=",
"{",
"}",
")",
"fill",
"=",
"options",
"[",
":fill",
"]",
"intl_prefix",
"=",
"options",
"[",
":intl_prefix",
"]",
"||",
"''",
"trunk_prefix",
"=",
"options",
"[",
":trunk_prefix",
"]",
"||",
"''",
"slots",
"=",
"pattern",
".",
"count",
"(",
"PLACEHOLDER_CHAR",
")",
"return",
"input",
"if",
"(",
"fill",
".",
"nil?",
"&&",
"input",
".",
"length",
">",
"slots",
")",
"source",
"=",
"(",
"fill",
".",
"nil?",
"||",
"fill",
".",
"empty?",
")",
"?",
"input",
":",
"input",
".",
"ljust",
"(",
"slots",
",",
"fill",
")",
"result",
"=",
"''",
"slot",
"=",
"0",
"has_open",
"=",
"had_c",
"=",
"had_n",
"=",
"false",
"pattern",
".",
"split",
"(",
"''",
")",
".",
"each_with_index",
"do",
"|",
"chr",
",",
"index",
"|",
"case",
"chr",
"when",
"'c'",
"had_c",
"=",
"true",
"result",
"<<",
"intl_prefix",
"when",
"'n'",
"had_n",
"=",
"true",
"result",
"<<",
"trunk_prefix",
"when",
"'#'",
"if",
"slot",
"<",
"source",
".",
"length",
"result",
"<<",
"source",
"[",
"slot",
"]",
"slot",
"+=",
"1",
"else",
"result",
"<<",
"' '",
"if",
"has_open",
"end",
"when",
"'('",
"if",
"slot",
"<",
"source",
".",
"length",
"has_open",
"=",
"true",
"result",
"<<",
"chr",
"end",
"when",
"')'",
"if",
"(",
"slot",
"<",
"source",
".",
"length",
"||",
"has_open",
")",
"has_open",
"=",
"false",
"result",
"<<",
"chr",
"end",
"else",
"next",
"if",
"(",
"chr",
"==",
"' '",
"&&",
"pattern",
"[",
"index",
"-",
"1",
"]",
"==",
"'n'",
"&&",
"trunk_prefix",
".",
"empty?",
")",
"next",
"if",
"(",
"chr",
"==",
"' '",
"&&",
"pattern",
"[",
"index",
"-",
"1",
"]",
"==",
"'c'",
"&&",
"intl_prefix",
".",
"empty?",
")",
"result",
"<<",
"chr",
"if",
"(",
"slot",
"<",
"source",
".",
"length",
")",
"end",
"end",
"result",
".",
"prepend",
"trunk_prefix",
"if",
"(",
"!",
"had_n",
"&&",
"!",
"trunk_prefix",
".",
"empty?",
")",
"result",
".",
"prepend",
"\"#{intl_prefix} \"",
"if",
"(",
"!",
"had_c",
"&&",
"!",
"intl_prefix",
".",
"empty?",
")",
"result",
".",
"strip",
"end"
] | Returns the string formatted according to a pattern.
Examples:
format('123456789', 'XXX-XX-XXXX')
=> "123-45-6789"
format('12345', 'XXX-XX-XXXX')
=> "123-45"
Parameters:
string -- The string to be formatted.
pattern -- The format string, see above examples.
fill -- A string for padding. If the empty string, then the pattern is
filled as much as possible, and the rest of the pattern is
truncated. If nil, and the string is too long for the pattern,
the string is returned unchanged. Otherwise, the string is
padded to fill the pattern, which is not truncated. | [
"Returns",
"the",
"string",
"formatted",
"according",
"to",
"a",
"pattern",
"."
] | b50708d483dd7c19ff42c0a1c542def9feecb90f | https://github.com/haberbyte/phoney/blob/b50708d483dd7c19ff42c0a1c542def9feecb90f/lib/phoney/formatter.rb#L19-L76 | train |
jdigger/git-process | lib/git-process/github_configuration.rb | GitHubService.Configuration.configure_octokit | def configure_octokit(opts = {})
base_url = opts[:base_url] || base_github_api_url_for_remote
Octokit.configure do |c|
c.api_endpoint = api_endpoint(base_url)
c.web_endpoint = web_endpoint(base_url)
end
if logger.level < ::GitProc::GitLogger::INFO
Octokit.middleware = Faraday::RackBuilder.new do |builder|
builder.response :logger, logger
builder.use Octokit::Response::RaiseError
builder.adapter Faraday.default_adapter
end
end
end | ruby | def configure_octokit(opts = {})
base_url = opts[:base_url] || base_github_api_url_for_remote
Octokit.configure do |c|
c.api_endpoint = api_endpoint(base_url)
c.web_endpoint = web_endpoint(base_url)
end
if logger.level < ::GitProc::GitLogger::INFO
Octokit.middleware = Faraday::RackBuilder.new do |builder|
builder.response :logger, logger
builder.use Octokit::Response::RaiseError
builder.adapter Faraday.default_adapter
end
end
end | [
"def",
"configure_octokit",
"(",
"opts",
"=",
"{",
"}",
")",
"base_url",
"=",
"opts",
"[",
":base_url",
"]",
"||",
"base_github_api_url_for_remote",
"Octokit",
".",
"configure",
"do",
"|",
"c",
"|",
"c",
".",
"api_endpoint",
"=",
"api_endpoint",
"(",
"base_url",
")",
"c",
".",
"web_endpoint",
"=",
"web_endpoint",
"(",
"base_url",
")",
"end",
"if",
"logger",
".",
"level",
"<",
"::",
"GitProc",
"::",
"GitLogger",
"::",
"INFO",
"Octokit",
".",
"middleware",
"=",
"Faraday",
"::",
"RackBuilder",
".",
"new",
"do",
"|",
"builder",
"|",
"builder",
".",
"response",
":logger",
",",
"logger",
"builder",
".",
"use",
"Octokit",
"::",
"Response",
"::",
"RaiseError",
"builder",
".",
"adapter",
"Faraday",
".",
"default_adapter",
"end",
"end",
"end"
] | Configures Octokit to use the appropriate URLs for GitHub server.
@option opts [String] :base_url The base URL to use for the GitHub server; defaults to {#base_github_api_url_for_remote}
@return [void]
@todo remove opts and pass in base_url directly | [
"Configures",
"Octokit",
"to",
"use",
"the",
"appropriate",
"URLs",
"for",
"GitHub",
"server",
"."
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_configuration.rb#L100-L113 | train |
jdigger/git-process | lib/git-process/github_configuration.rb | GitHubService.Configuration.create_pw_client | def create_pw_client(opts = {})
usr = opts[:user] || user()
pw = opts[:password] || password()
remote = opts[:remote_name] || self.remote_name
logger.info("Authorizing #{usr} to work with #{remote}.")
configure_octokit(opts)
Octokit::Client.new(:login => usr, :password => pw)
end | ruby | def create_pw_client(opts = {})
usr = opts[:user] || user()
pw = opts[:password] || password()
remote = opts[:remote_name] || self.remote_name
logger.info("Authorizing #{usr} to work with #{remote}.")
configure_octokit(opts)
Octokit::Client.new(:login => usr, :password => pw)
end | [
"def",
"create_pw_client",
"(",
"opts",
"=",
"{",
"}",
")",
"usr",
"=",
"opts",
"[",
":user",
"]",
"||",
"user",
"(",
")",
"pw",
"=",
"opts",
"[",
":password",
"]",
"||",
"password",
"(",
")",
"remote",
"=",
"opts",
"[",
":remote_name",
"]",
"||",
"self",
".",
"remote_name",
"logger",
".",
"info",
"(",
"\"Authorizing #{usr} to work with #{remote}.\"",
")",
"configure_octokit",
"(",
"opts",
")",
"Octokit",
"::",
"Client",
".",
"new",
"(",
":login",
"=>",
"usr",
",",
":password",
"=>",
"pw",
")",
"end"
] | Create a GitHub client using username and password specifically.
Meant to be used to get an OAuth token for "regular" client calls.
@param [Hash] opts the options to create a message with
@option opts [String] :base_url The base URL to use for the GitHub server
@option opts [String] :remote_name (#remote_name) The "remote" name to use (e.g., 'origin')
@option opts [String] :user the username to authenticate with
@option opts [String] :password (#password) the password to authenticate with
@return [Octokit::Client] the Octokit client for communicating with GitHub | [
"Create",
"a",
"GitHub",
"client",
"using",
"username",
"and",
"password",
"specifically",
".",
"Meant",
"to",
"be",
"used",
"to",
"get",
"an",
"OAuth",
"token",
"for",
"regular",
"client",
"calls",
"."
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_configuration.rb#L208-L218 | train |
jdigger/git-process | lib/git-process/github_configuration.rb | GitHubService.Configuration.unprocessable_authorization | def unprocessable_authorization(exp)
errors = exp.errors
if not (errors.nil? or errors.empty?)
error_hash = errors[0]
if error_hash[:resource] == 'OauthAccess'
# error_hash[:code]
return ask_about_resetting_authorization
else
raise exp
end
else
raise exp
end
end | ruby | def unprocessable_authorization(exp)
errors = exp.errors
if not (errors.nil? or errors.empty?)
error_hash = errors[0]
if error_hash[:resource] == 'OauthAccess'
# error_hash[:code]
return ask_about_resetting_authorization
else
raise exp
end
else
raise exp
end
end | [
"def",
"unprocessable_authorization",
"(",
"exp",
")",
"errors",
"=",
"exp",
".",
"errors",
"if",
"not",
"(",
"errors",
".",
"nil?",
"or",
"errors",
".",
"empty?",
")",
"error_hash",
"=",
"errors",
"[",
"0",
"]",
"if",
"error_hash",
"[",
":resource",
"]",
"==",
"'OauthAccess'",
"return",
"ask_about_resetting_authorization",
"else",
"raise",
"exp",
"end",
"else",
"raise",
"exp",
"end",
"end"
] | Tries to more gracefully handle the token already existing. See
@return [String] the OAuth token
@raise [TokenAlreadyExists] the token already exists
@raise [Octokit::UnprocessableEntity] there was another problem | [
"Tries",
"to",
"more",
"gracefully",
"handle",
"the",
"token",
"already",
"existing",
".",
"See"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_configuration.rb#L379-L392 | train |
rapid7/metasploit-model | lib/metasploit/model/association.rb | Metasploit::Model::Association.ClassMethods.association | def association(name, options={})
association = Metasploit::Model::Association::Reflection.new(
:model => self,
:name => name.to_sym,
:class_name => options[:class_name]
)
association.valid!
association_by_name[association.name] = association
end | ruby | def association(name, options={})
association = Metasploit::Model::Association::Reflection.new(
:model => self,
:name => name.to_sym,
:class_name => options[:class_name]
)
association.valid!
association_by_name[association.name] = association
end | [
"def",
"association",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"association",
"=",
"Metasploit",
"::",
"Model",
"::",
"Association",
"::",
"Reflection",
".",
"new",
"(",
":model",
"=>",
"self",
",",
":name",
"=>",
"name",
".",
"to_sym",
",",
":class_name",
"=>",
"options",
"[",
":class_name",
"]",
")",
"association",
".",
"valid!",
"association_by_name",
"[",
"association",
".",
"name",
"]",
"=",
"association",
"end"
] | Registers an association.
@param name [to_sym] Name of the association
@param options [Hash{Symbol => String}]
@option options [String] :class_name Name of association's class.
@return [Metasploit::Model::Association::Reflection] the reflection of the registered association.
@raise [Metasploit::Model::Invalid] if name is blank.
@raise [Metasploit::Model::Invalid] if :class_name is blank. | [
"Registers",
"an",
"association",
"."
] | cb6606bf24218798e853ba44470df31a47d9b627 | https://github.com/rapid7/metasploit-model/blob/cb6606bf24218798e853ba44470df31a47d9b627/lib/metasploit/model/association.rb#L22-L31 | train |
thinkclay/Rails-Annex-Gem | lib/annex/view_helpers.rb | Annex.ViewHelpers.annex_block | def annex_block(identifier, opts = {})
opts[:route] ||= current_route
case Annex::config[:adapter]
when :activerecord
doc = Annex::Block.where(route: "#{opts[:route]}_#{identifier}").first_or_create
content = doc.content
when :mongoid
doc = Annex::Block.where(route: opts[:route]).first_or_create
content = doc.content.try(:[], identifier.to_s)
end
render partial: 'annex/block', locals: { content: content || opts[:default], identifier: identifier, opts: opts }
end | ruby | def annex_block(identifier, opts = {})
opts[:route] ||= current_route
case Annex::config[:adapter]
when :activerecord
doc = Annex::Block.where(route: "#{opts[:route]}_#{identifier}").first_or_create
content = doc.content
when :mongoid
doc = Annex::Block.where(route: opts[:route]).first_or_create
content = doc.content.try(:[], identifier.to_s)
end
render partial: 'annex/block', locals: { content: content || opts[:default], identifier: identifier, opts: opts }
end | [
"def",
"annex_block",
"(",
"identifier",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
":route",
"]",
"||=",
"current_route",
"case",
"Annex",
"::",
"config",
"[",
":adapter",
"]",
"when",
":activerecord",
"doc",
"=",
"Annex",
"::",
"Block",
".",
"where",
"(",
"route",
":",
"\"#{opts[:route]}_#{identifier}\"",
")",
".",
"first_or_create",
"content",
"=",
"doc",
".",
"content",
"when",
":mongoid",
"doc",
"=",
"Annex",
"::",
"Block",
".",
"where",
"(",
"route",
":",
"opts",
"[",
":route",
"]",
")",
".",
"first_or_create",
"content",
"=",
"doc",
".",
"content",
".",
"try",
"(",
":[]",
",",
"identifier",
".",
"to_s",
")",
"end",
"render",
"partial",
":",
"'annex/block'",
",",
"locals",
":",
"{",
"content",
":",
"content",
"||",
"opts",
"[",
":default",
"]",
",",
"identifier",
":",
"identifier",
",",
"opts",
":",
"opts",
"}",
"end"
] | annex_block is a universal helper to render content from
the database and display it on the page | [
"annex_block",
"is",
"a",
"universal",
"helper",
"to",
"render",
"content",
"from",
"the",
"database",
"and",
"display",
"it",
"on",
"the",
"page"
] | aff8c0a3025910d906ea46331053d3b5117a03c9 | https://github.com/thinkclay/Rails-Annex-Gem/blob/aff8c0a3025910d906ea46331053d3b5117a03c9/lib/annex/view_helpers.rb#L10-L26 | train |
jdigger/git-process | lib/git-process/git_remote.rb | GitProc.GitRemote.repo_name | def repo_name
unless @repo_name
url = config["remote.#{name}.url"]
raise GitProcessError.new("There is no #{name} url set up.") if url.nil? or url.empty?
uri = Addressable::URI.parse(url)
@repo_name = uri.path.sub(/\.git/, '').sub(/^\//, '')
end
@repo_name
end | ruby | def repo_name
unless @repo_name
url = config["remote.#{name}.url"]
raise GitProcessError.new("There is no #{name} url set up.") if url.nil? or url.empty?
uri = Addressable::URI.parse(url)
@repo_name = uri.path.sub(/\.git/, '').sub(/^\//, '')
end
@repo_name
end | [
"def",
"repo_name",
"unless",
"@repo_name",
"url",
"=",
"config",
"[",
"\"remote.#{name}.url\"",
"]",
"raise",
"GitProcessError",
".",
"new",
"(",
"\"There is no #{name} url set up.\"",
")",
"if",
"url",
".",
"nil?",
"or",
"url",
".",
"empty?",
"uri",
"=",
"Addressable",
"::",
"URI",
".",
"parse",
"(",
"url",
")",
"@repo_name",
"=",
"uri",
".",
"path",
".",
"sub",
"(",
"/",
"\\.",
"/",
",",
"''",
")",
".",
"sub",
"(",
"/",
"\\/",
"/",
",",
"''",
")",
"end",
"@repo_name",
"end"
] | The name of the repository
@example
repo_name #=> "jdigger/git-process"
@return [String] the name of the repository | [
"The",
"name",
"of",
"the",
"repository"
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_remote.rb#L84-L92 | train |
jdigger/git-process | lib/git-process/git_remote.rb | GitProc.GitRemote.remote_name | def remote_name
unless @remote_name
@remote_name = config['gitProcess.remoteName']
if @remote_name.nil? or @remote_name.empty?
remotes = self.remote_names
if remotes.empty?
@remote_name = nil
else
@remote_name = remotes[0]
raise "remote name is not a String: #{@remote_name.inspect}" unless @remote_name.is_a? String
end
end
logger.debug { "Using remote name of '#{@remote_name}'" }
end
@remote_name
end | ruby | def remote_name
unless @remote_name
@remote_name = config['gitProcess.remoteName']
if @remote_name.nil? or @remote_name.empty?
remotes = self.remote_names
if remotes.empty?
@remote_name = nil
else
@remote_name = remotes[0]
raise "remote name is not a String: #{@remote_name.inspect}" unless @remote_name.is_a? String
end
end
logger.debug { "Using remote name of '#{@remote_name}'" }
end
@remote_name
end | [
"def",
"remote_name",
"unless",
"@remote_name",
"@remote_name",
"=",
"config",
"[",
"'gitProcess.remoteName'",
"]",
"if",
"@remote_name",
".",
"nil?",
"or",
"@remote_name",
".",
"empty?",
"remotes",
"=",
"self",
".",
"remote_names",
"if",
"remotes",
".",
"empty?",
"@remote_name",
"=",
"nil",
"else",
"@remote_name",
"=",
"remotes",
"[",
"0",
"]",
"raise",
"\"remote name is not a String: #{@remote_name.inspect}\"",
"unless",
"@remote_name",
".",
"is_a?",
"String",
"end",
"end",
"logger",
".",
"debug",
"{",
"\"Using remote name of '#{@remote_name}'\"",
"}",
"end",
"@remote_name",
"end"
] | Returns the "remote name" to use. By convention the most common name is "origin".
If the Git configuration "gitProcess.remoteName" is set, that will always be used. Otherwise this
simple returns the first name it finds in the list of remotes.
@return [String, nil] the remote name, or nil if there are none defined | [
"Returns",
"the",
"remote",
"name",
"to",
"use",
".",
"By",
"convention",
"the",
"most",
"common",
"name",
"is",
"origin",
"."
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_remote.rb#L102-L117 | train |
jdigger/git-process | lib/git-process/git_remote.rb | GitProc.GitRemote.expanded_url | def expanded_url(server_name = 'origin', raw_url = nil, opts = {})
if raw_url.nil?
raise ArgumentError.new('Need server_name') unless server_name
conf_key = "remote.#{server_name}.url"
url = config[conf_key]
raise GitHubService::NoRemoteRepository.new("There is no value set for '#{conf_key}'") if url.nil? or url.empty?
else
raise GitHubService::NoRemoteRepository.new("There is no value set for '#{raw_url}'") if raw_url.nil? or raw_url.empty?
url = raw_url
end
if /^\S+@/ =~ url
url.sub(/^(\S+@\S+?):(.*)$/, "ssh://\\1/\\2")
else
uri = URI.parse(url)
host = uri.host
scheme = uri.scheme
raise URI::InvalidURIError.new("Need a scheme in URI: '#{url}'") unless scheme
if scheme == 'file'
url
elsif host.nil?
# assume that the 'scheme' is the named configuration in ~/.ssh/config
rv = GitRemote.hostname_and_user_from_ssh_config(scheme, opts[:ssh_config_file] ||= "#{ENV['HOME']}/.ssh/config")
raise GitHubService::NoRemoteRepository.new("Could not determine a host from #{url}") if rv.nil?
host = rv[0]
user = rv[1]
url.sub(/^\S+:(\S+)$/, "ssh://#{user}@#{host}/\\1")
else
url
end
end
end | ruby | def expanded_url(server_name = 'origin', raw_url = nil, opts = {})
if raw_url.nil?
raise ArgumentError.new('Need server_name') unless server_name
conf_key = "remote.#{server_name}.url"
url = config[conf_key]
raise GitHubService::NoRemoteRepository.new("There is no value set for '#{conf_key}'") if url.nil? or url.empty?
else
raise GitHubService::NoRemoteRepository.new("There is no value set for '#{raw_url}'") if raw_url.nil? or raw_url.empty?
url = raw_url
end
if /^\S+@/ =~ url
url.sub(/^(\S+@\S+?):(.*)$/, "ssh://\\1/\\2")
else
uri = URI.parse(url)
host = uri.host
scheme = uri.scheme
raise URI::InvalidURIError.new("Need a scheme in URI: '#{url}'") unless scheme
if scheme == 'file'
url
elsif host.nil?
# assume that the 'scheme' is the named configuration in ~/.ssh/config
rv = GitRemote.hostname_and_user_from_ssh_config(scheme, opts[:ssh_config_file] ||= "#{ENV['HOME']}/.ssh/config")
raise GitHubService::NoRemoteRepository.new("Could not determine a host from #{url}") if rv.nil?
host = rv[0]
user = rv[1]
url.sub(/^\S+:(\S+)$/, "ssh://#{user}@#{host}/\\1")
else
url
end
end
end | [
"def",
"expanded_url",
"(",
"server_name",
"=",
"'origin'",
",",
"raw_url",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"if",
"raw_url",
".",
"nil?",
"raise",
"ArgumentError",
".",
"new",
"(",
"'Need server_name'",
")",
"unless",
"server_name",
"conf_key",
"=",
"\"remote.#{server_name}.url\"",
"url",
"=",
"config",
"[",
"conf_key",
"]",
"raise",
"GitHubService",
"::",
"NoRemoteRepository",
".",
"new",
"(",
"\"There is no value set for '#{conf_key}'\"",
")",
"if",
"url",
".",
"nil?",
"or",
"url",
".",
"empty?",
"else",
"raise",
"GitHubService",
"::",
"NoRemoteRepository",
".",
"new",
"(",
"\"There is no value set for '#{raw_url}'\"",
")",
"if",
"raw_url",
".",
"nil?",
"or",
"raw_url",
".",
"empty?",
"url",
"=",
"raw_url",
"end",
"if",
"/",
"\\S",
"/",
"=~",
"url",
"url",
".",
"sub",
"(",
"/",
"\\S",
"\\S",
"/",
",",
"\"ssh://\\\\1/\\\\2\"",
")",
"else",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"host",
"=",
"uri",
".",
"host",
"scheme",
"=",
"uri",
".",
"scheme",
"raise",
"URI",
"::",
"InvalidURIError",
".",
"new",
"(",
"\"Need a scheme in URI: '#{url}'\"",
")",
"unless",
"scheme",
"if",
"scheme",
"==",
"'file'",
"url",
"elsif",
"host",
".",
"nil?",
"rv",
"=",
"GitRemote",
".",
"hostname_and_user_from_ssh_config",
"(",
"scheme",
",",
"opts",
"[",
":ssh_config_file",
"]",
"||=",
"\"#{ENV['HOME']}/.ssh/config\"",
")",
"raise",
"GitHubService",
"::",
"NoRemoteRepository",
".",
"new",
"(",
"\"Could not determine a host from #{url}\"",
")",
"if",
"rv",
".",
"nil?",
"host",
"=",
"rv",
"[",
"0",
"]",
"user",
"=",
"rv",
"[",
"1",
"]",
"url",
".",
"sub",
"(",
"/",
"\\S",
"\\S",
"/",
",",
"\"ssh://#{user}@#{host}/\\\\1\"",
")",
"else",
"url",
"end",
"end",
"end"
] | Expands the git configuration server name to a url.
Takes into account further expanding an SSH uri that uses SSH aliasing in .ssh/config
@param [String] server_name the git configuration server name; defaults to 'origin'
@option opts [String] :ssh_config_file the SSH config file to use; defaults to ~/.ssh/config
@return the fully expanded URL; never nil
@raise [GitHubService::NoRemoteRepository] there is not a URL set for the server name
@raise [URI::InvalidURIError] the retrieved URL does not have a schema
@raise [GitHubService::NoRemoteRepository] if could not figure out a host for the retrieved URL
@raise [::ArgumentError] if a server name is not provided
@todo use the netrc gem | [
"Expands",
"the",
"git",
"configuration",
"server",
"name",
"to",
"a",
"url",
"."
] | 5853aa94258e724ce0dbc2f1e7407775e1630964 | https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_remote.rb#L166-L203 | train |
altabyte/ebay_trader | lib/ebay_trader/request.rb | EbayTrader.Request.to_s | def to_s(indent = xml_tab_width)
xml = ''
if defined? Ox
ox_doc = Ox.parse(xml_response)
xml = Ox.dump(ox_doc, indent: indent)
else
rexml_doc = REXML::Document.new(xml_response)
rexml_doc.write(xml, indent)
end
xml
end | ruby | def to_s(indent = xml_tab_width)
xml = ''
if defined? Ox
ox_doc = Ox.parse(xml_response)
xml = Ox.dump(ox_doc, indent: indent)
else
rexml_doc = REXML::Document.new(xml_response)
rexml_doc.write(xml, indent)
end
xml
end | [
"def",
"to_s",
"(",
"indent",
"=",
"xml_tab_width",
")",
"xml",
"=",
"''",
"if",
"defined?",
"Ox",
"ox_doc",
"=",
"Ox",
".",
"parse",
"(",
"xml_response",
")",
"xml",
"=",
"Ox",
".",
"dump",
"(",
"ox_doc",
",",
"indent",
":",
"indent",
")",
"else",
"rexml_doc",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"xml_response",
")",
"rexml_doc",
".",
"write",
"(",
"xml",
",",
"indent",
")",
"end",
"xml",
"end"
] | Get a String representation of the response XML with indentation.
@return [String] the response XML. | [
"Get",
"a",
"String",
"representation",
"of",
"the",
"response",
"XML",
"with",
"indentation",
"."
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/request.rb#L239-L249 | train |
altabyte/ebay_trader | lib/ebay_trader/request.rb | EbayTrader.Request.submit | def submit
raise EbayTraderError, 'Cannot post an eBay API request before application keys have been set' unless EbayTrader.configuration.has_keys_set?
uri = EbayTrader.configuration.uri
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = http_timeout
if uri.port == 443
# http://www.rubyinside.com/nethttp-cheat-sheet-2940.html
http.use_ssl = true
verify = EbayTrader.configuration.ssl_verify
if verify
if verify.is_a?(String)
pem = File.read(verify)
http.cert = OpenSSL::X509::Certificate.new(pem)
http.key = OpenSSL::PKey::RSA.new(pem)
end
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
end
post = Net::HTTP::Post.new(uri.path, headers)
post.body = xml_request
begin
response = http.start { |http| http.request(post) }
rescue OpenSSL::SSL::SSLError => e
# SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
raise EbayTraderError, e
rescue Net::ReadTimeout
raise EbayTraderTimeoutError, "Failed to complete #{call_name} in #{http_timeout} seconds"
rescue Exception => e
raise EbayTraderError, e
ensure
EbayTrader.configuration.counter_callback.call if EbayTrader.configuration.has_counter?
end
@http_response_code = response.code.to_i.freeze
# If the call was successful it should have a response code starting with '2'
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
raise EbayTraderError, "HTTP Response Code: #{http_response_code}" unless http_response_code.between?(200, 299)
if response['Content-Encoding'] == 'gzip'
@xml_response = ActiveSupport::Gzip.decompress(response.body)
else
@xml_response = response.body
end
end | ruby | def submit
raise EbayTraderError, 'Cannot post an eBay API request before application keys have been set' unless EbayTrader.configuration.has_keys_set?
uri = EbayTrader.configuration.uri
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = http_timeout
if uri.port == 443
# http://www.rubyinside.com/nethttp-cheat-sheet-2940.html
http.use_ssl = true
verify = EbayTrader.configuration.ssl_verify
if verify
if verify.is_a?(String)
pem = File.read(verify)
http.cert = OpenSSL::X509::Certificate.new(pem)
http.key = OpenSSL::PKey::RSA.new(pem)
end
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
end
post = Net::HTTP::Post.new(uri.path, headers)
post.body = xml_request
begin
response = http.start { |http| http.request(post) }
rescue OpenSSL::SSL::SSLError => e
# SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
raise EbayTraderError, e
rescue Net::ReadTimeout
raise EbayTraderTimeoutError, "Failed to complete #{call_name} in #{http_timeout} seconds"
rescue Exception => e
raise EbayTraderError, e
ensure
EbayTrader.configuration.counter_callback.call if EbayTrader.configuration.has_counter?
end
@http_response_code = response.code.to_i.freeze
# If the call was successful it should have a response code starting with '2'
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
raise EbayTraderError, "HTTP Response Code: #{http_response_code}" unless http_response_code.between?(200, 299)
if response['Content-Encoding'] == 'gzip'
@xml_response = ActiveSupport::Gzip.decompress(response.body)
else
@xml_response = response.body
end
end | [
"def",
"submit",
"raise",
"EbayTraderError",
",",
"'Cannot post an eBay API request before application keys have been set'",
"unless",
"EbayTrader",
".",
"configuration",
".",
"has_keys_set?",
"uri",
"=",
"EbayTrader",
".",
"configuration",
".",
"uri",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"read_timeout",
"=",
"http_timeout",
"if",
"uri",
".",
"port",
"==",
"443",
"http",
".",
"use_ssl",
"=",
"true",
"verify",
"=",
"EbayTrader",
".",
"configuration",
".",
"ssl_verify",
"if",
"verify",
"if",
"verify",
".",
"is_a?",
"(",
"String",
")",
"pem",
"=",
"File",
".",
"read",
"(",
"verify",
")",
"http",
".",
"cert",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
".",
"new",
"(",
"pem",
")",
"http",
".",
"key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"pem",
")",
"end",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
"else",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"end",
"end",
"post",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"headers",
")",
"post",
".",
"body",
"=",
"xml_request",
"begin",
"response",
"=",
"http",
".",
"start",
"{",
"|",
"http",
"|",
"http",
".",
"request",
"(",
"post",
")",
"}",
"rescue",
"OpenSSL",
"::",
"SSL",
"::",
"SSLError",
"=>",
"e",
"raise",
"EbayTraderError",
",",
"e",
"rescue",
"Net",
"::",
"ReadTimeout",
"raise",
"EbayTraderTimeoutError",
",",
"\"Failed to complete #{call_name} in #{http_timeout} seconds\"",
"rescue",
"Exception",
"=>",
"e",
"raise",
"EbayTraderError",
",",
"e",
"ensure",
"EbayTrader",
".",
"configuration",
".",
"counter_callback",
".",
"call",
"if",
"EbayTrader",
".",
"configuration",
".",
"has_counter?",
"end",
"@http_response_code",
"=",
"response",
".",
"code",
".",
"to_i",
".",
"freeze",
"raise",
"EbayTraderError",
",",
"\"HTTP Response Code: #{http_response_code}\"",
"unless",
"http_response_code",
".",
"between?",
"(",
"200",
",",
"299",
")",
"if",
"response",
"[",
"'Content-Encoding'",
"]",
"==",
"'gzip'",
"@xml_response",
"=",
"ActiveSupport",
"::",
"Gzip",
".",
"decompress",
"(",
"response",
".",
"body",
")",
"else",
"@xml_response",
"=",
"response",
".",
"body",
"end",
"end"
] | Post the xml_request to eBay and record the xml_response. | [
"Post",
"the",
"xml_request",
"to",
"eBay",
"and",
"record",
"the",
"xml_response",
"."
] | 4442b683ea27f02fa0ef73f3f6357396fbe29b56 | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/request.rb#L262-L314 | train |
mileszim/webpurify-gem | lib/web_purify/methods/blacklist.rb | WebPurify.Blacklist.add_to_blacklist | def add_to_blacklist(word, deep_search=0)
params = {
:method => WebPurify::Constants.methods[:add_to_blacklist],
:word => word,
:ds => deep_search
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
return parsed[:success]=='1'
end | ruby | def add_to_blacklist(word, deep_search=0)
params = {
:method => WebPurify::Constants.methods[:add_to_blacklist],
:word => word,
:ds => deep_search
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
return parsed[:success]=='1'
end | [
"def",
"add_to_blacklist",
"(",
"word",
",",
"deep_search",
"=",
"0",
")",
"params",
"=",
"{",
":method",
"=>",
"WebPurify",
"::",
"Constants",
".",
"methods",
"[",
":add_to_blacklist",
"]",
",",
":word",
"=>",
"word",
",",
":ds",
"=>",
"deep_search",
"}",
"parsed",
"=",
"WebPurify",
"::",
"Request",
".",
"query",
"(",
"text_request_base",
",",
"@query_base",
",",
"params",
")",
"return",
"parsed",
"[",
":success",
"]",
"==",
"'1'",
"end"
] | Add a word to the blacklist
@param word [String] The word to add to the blacklist
@param deep_search [Integer] 1 if deep search on word, otherwise 0 for not (default 0)
@return [Boolean] True if successful, false if not | [
"Add",
"a",
"word",
"to",
"the",
"blacklist"
] | d594a0b483f1fe86ec711e37fd9187302f246faa | https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/blacklist.rb#L13-L21 | train |
mileszim/webpurify-gem | lib/web_purify/methods/blacklist.rb | WebPurify.Blacklist.remove_from_blacklist | def remove_from_blacklist(word)
params = {
:method => WebPurify::Constants.methods[:remove_from_blacklist],
:word => word
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
return parsed[:success]=='1'
end | ruby | def remove_from_blacklist(word)
params = {
:method => WebPurify::Constants.methods[:remove_from_blacklist],
:word => word
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
return parsed[:success]=='1'
end | [
"def",
"remove_from_blacklist",
"(",
"word",
")",
"params",
"=",
"{",
":method",
"=>",
"WebPurify",
"::",
"Constants",
".",
"methods",
"[",
":remove_from_blacklist",
"]",
",",
":word",
"=>",
"word",
"}",
"parsed",
"=",
"WebPurify",
"::",
"Request",
".",
"query",
"(",
"text_request_base",
",",
"@query_base",
",",
"params",
")",
"return",
"parsed",
"[",
":success",
"]",
"==",
"'1'",
"end"
] | Remove a word from the blacklist
@param word [String] The word to remove from the blacklist
@return [Boolean] True if successful, false if not | [
"Remove",
"a",
"word",
"from",
"the",
"blacklist"
] | d594a0b483f1fe86ec711e37fd9187302f246faa | https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/blacklist.rb#L28-L35 | train |
mileszim/webpurify-gem | lib/web_purify/methods/blacklist.rb | WebPurify.Blacklist.get_blacklist | def get_blacklist
params = {
:method => WebPurify::Constants.methods[:get_blacklist]
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
if parsed[:word]
return [] << parsed[:word]
else
return []
end
end | ruby | def get_blacklist
params = {
:method => WebPurify::Constants.methods[:get_blacklist]
}
parsed = WebPurify::Request.query(text_request_base, @query_base, params)
if parsed[:word]
return [] << parsed[:word]
else
return []
end
end | [
"def",
"get_blacklist",
"params",
"=",
"{",
":method",
"=>",
"WebPurify",
"::",
"Constants",
".",
"methods",
"[",
":get_blacklist",
"]",
"}",
"parsed",
"=",
"WebPurify",
"::",
"Request",
".",
"query",
"(",
"text_request_base",
",",
"@query_base",
",",
"params",
")",
"if",
"parsed",
"[",
":word",
"]",
"return",
"[",
"]",
"<<",
"parsed",
"[",
":word",
"]",
"else",
"return",
"[",
"]",
"end",
"end"
] | Get the blacklist
@return [Array] An array of words in the blacklist | [
"Get",
"the",
"blacklist"
] | d594a0b483f1fe86ec711e37fd9187302f246faa | https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/blacklist.rb#L41-L51 | train |
stereocat/expectacle | lib/expectacle/thrower_base_io.rb | Expectacle.ThrowerBase.write_and_logging | def write_and_logging(message, command, secret = false)
logging_message = secret ? message : message + command
@logger.info logging_message
if @writer.closed?
@logger.error "Try to write #{command}, but writer closed"
@commands.clear
else
@writer.puts command
end
end | ruby | def write_and_logging(message, command, secret = false)
logging_message = secret ? message : message + command
@logger.info logging_message
if @writer.closed?
@logger.error "Try to write #{command}, but writer closed"
@commands.clear
else
@writer.puts command
end
end | [
"def",
"write_and_logging",
"(",
"message",
",",
"command",
",",
"secret",
"=",
"false",
")",
"logging_message",
"=",
"secret",
"?",
"message",
":",
"message",
"+",
"command",
"@logger",
".",
"info",
"logging_message",
"if",
"@writer",
".",
"closed?",
"@logger",
".",
"error",
"\"Try to write #{command}, but writer closed\"",
"@commands",
".",
"clear",
"else",
"@writer",
".",
"puts",
"command",
"end",
"end"
] | Send string to process and logging the string
@param message [String] Message to logging
@param command [String] Command to send
@param secret [Boolearn] Choise to logging command | [
"Send",
"string",
"to",
"process",
"and",
"logging",
"the",
"string"
] | a67faca42ba5f90068c69047bb6cf01c2bca1b74 | https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_io.rb#L19-L28 | train |
stereocat/expectacle | lib/expectacle/thrower_base_io.rb | Expectacle.ThrowerBase.default_io_logger | def default_io_logger(logger_io, progname)
logger = Logger.new(logger_io)
logger.progname = progname
logger.datetime_format = '%Y-%m-%d %H:%M:%D %Z'
logger
end | ruby | def default_io_logger(logger_io, progname)
logger = Logger.new(logger_io)
logger.progname = progname
logger.datetime_format = '%Y-%m-%d %H:%M:%D %Z'
logger
end | [
"def",
"default_io_logger",
"(",
"logger_io",
",",
"progname",
")",
"logger",
"=",
"Logger",
".",
"new",
"(",
"logger_io",
")",
"logger",
".",
"progname",
"=",
"progname",
"logger",
".",
"datetime_format",
"=",
"'%Y-%m-%d %H:%M:%D %Z'",
"logger",
"end"
] | Setup default IO logger
@return [Logger] logger | [
"Setup",
"default",
"IO",
"logger"
] | a67faca42ba5f90068c69047bb6cf01c2bca1b74 | https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_io.rb#L32-L37 | train |
stereocat/expectacle | lib/expectacle/thrower_base_io.rb | Expectacle.ThrowerBase.load_yaml_file | def load_yaml_file(file_type, file_name)
YAML.load_file file_name
rescue StandardError => error
@logger.error "Cannot load #{file_type}: #{file_name}"
raise error
end | ruby | def load_yaml_file(file_type, file_name)
YAML.load_file file_name
rescue StandardError => error
@logger.error "Cannot load #{file_type}: #{file_name}"
raise error
end | [
"def",
"load_yaml_file",
"(",
"file_type",
",",
"file_name",
")",
"YAML",
".",
"load_file",
"file_name",
"rescue",
"StandardError",
"=>",
"error",
"@logger",
".",
"error",
"\"Cannot load #{file_type}: #{file_name}\"",
"raise",
"error",
"end"
] | YAML file loader
@param file_type [String] File description
@param file_name [String] File name to load
@raise [Error] File load error | [
"YAML",
"file",
"loader"
] | a67faca42ba5f90068c69047bb6cf01c2bca1b74 | https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_io.rb#L58-L63 | train |
keithrbennett/trick_bag | lib/trick_bag/validations/object_validations.rb | TrickBag.Validations.nil_instance_vars | def nil_instance_vars(object, vars)
vars = Array(vars)
vars.select { |var| object.instance_variable_get(var).nil? }
end | ruby | def nil_instance_vars(object, vars)
vars = Array(vars)
vars.select { |var| object.instance_variable_get(var).nil? }
end | [
"def",
"nil_instance_vars",
"(",
"object",
",",
"vars",
")",
"vars",
"=",
"Array",
"(",
"vars",
")",
"vars",
".",
"select",
"{",
"|",
"var",
"|",
"object",
".",
"instance_variable_get",
"(",
"var",
")",
".",
"nil?",
"}",
"end"
] | Returns an array containing each symbol in vars for which the
corresponding instance variable in the specified object is nil. | [
"Returns",
"an",
"array",
"containing",
"each",
"symbol",
"in",
"vars",
"for",
"which",
"the",
"corresponding",
"instance",
"variable",
"in",
"the",
"specified",
"object",
"is",
"nil",
"."
] | a3886a45f32588aba751d13aeba42ae680bcd203 | https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/validations/object_validations.rb#L11-L14 | train |
keithrbennett/trick_bag | lib/trick_bag/validations/object_validations.rb | TrickBag.Validations.raise_on_nil_instance_vars | def raise_on_nil_instance_vars(object, vars)
nil_vars = nil_instance_vars(object, vars)
unless nil_vars.empty?
raise ObjectValidationError.new("The following instance variables were nil: #{nil_vars.join(', ')}.")
end
end | ruby | def raise_on_nil_instance_vars(object, vars)
nil_vars = nil_instance_vars(object, vars)
unless nil_vars.empty?
raise ObjectValidationError.new("The following instance variables were nil: #{nil_vars.join(', ')}.")
end
end | [
"def",
"raise_on_nil_instance_vars",
"(",
"object",
",",
"vars",
")",
"nil_vars",
"=",
"nil_instance_vars",
"(",
"object",
",",
"vars",
")",
"unless",
"nil_vars",
".",
"empty?",
"raise",
"ObjectValidationError",
".",
"new",
"(",
"\"The following instance variables were nil: #{nil_vars.join(', ')}.\"",
")",
"end",
"end"
] | For each symbol in vars, checks to see that the corresponding instance
variable in the specified object is not nil.
If any are nil, raises an error listing the nils. | [
"For",
"each",
"symbol",
"in",
"vars",
"checks",
"to",
"see",
"that",
"the",
"corresponding",
"instance",
"variable",
"in",
"the",
"specified",
"object",
"is",
"not",
"nil",
".",
"If",
"any",
"are",
"nil",
"raises",
"an",
"error",
"listing",
"the",
"nils",
"."
] | a3886a45f32588aba751d13aeba42ae680bcd203 | https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/validations/object_validations.rb#L19-L24 | train |
solutious/rudy | lib/rudy/cli/base.rb | Rudy::CLI.CommandBase.print_header | def print_header
# Send The Huxtables the global values again because they could be
# updated after initialization but before the command was executed
Rudy::Huxtable.update_global @global
li Rudy::CLI.generate_header(@@global, @@config) if @@global.print_header
unless @@global.quiet
if @@global.environment == "prod"
msg = "YOU ARE PLAYING WITH PRODUCTION"
li Rudy::Utils.banner(msg, :normal), $/
end
end
end | ruby | def print_header
# Send The Huxtables the global values again because they could be
# updated after initialization but before the command was executed
Rudy::Huxtable.update_global @global
li Rudy::CLI.generate_header(@@global, @@config) if @@global.print_header
unless @@global.quiet
if @@global.environment == "prod"
msg = "YOU ARE PLAYING WITH PRODUCTION"
li Rudy::Utils.banner(msg, :normal), $/
end
end
end | [
"def",
"print_header",
"Rudy",
"::",
"Huxtable",
".",
"update_global",
"@global",
"li",
"Rudy",
"::",
"CLI",
".",
"generate_header",
"(",
"@@global",
",",
"@@config",
")",
"if",
"@@global",
".",
"print_header",
"unless",
"@@global",
".",
"quiet",
"if",
"@@global",
".",
"environment",
"==",
"\"prod\"",
"msg",
"=",
"\"YOU ARE PLAYING WITH PRODUCTION\"",
"li",
"Rudy",
"::",
"Utils",
".",
"banner",
"(",
"msg",
",",
":normal",
")",
",",
"$/",
"end",
"end",
"end"
] | Print a default header to the screen for every command. | [
"Print",
"a",
"default",
"header",
"to",
"the",
"screen",
"for",
"every",
"command",
"."
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/cli/base.rb#L83-L97 | train |
solutious/rudy | lib/rudy/utils.rb | Rudy.Utils.bell | def bell(chimes=1, logger=nil)
chimes ||= 0
return unless logger
chimed = chimes.to_i
logger.print "\a"*chimes if chimes > 0 && logger
true # be like Rudy.bug()
end | ruby | def bell(chimes=1, logger=nil)
chimes ||= 0
return unless logger
chimed = chimes.to_i
logger.print "\a"*chimes if chimes > 0 && logger
true # be like Rudy.bug()
end | [
"def",
"bell",
"(",
"chimes",
"=",
"1",
",",
"logger",
"=",
"nil",
")",
"chimes",
"||=",
"0",
"return",
"unless",
"logger",
"chimed",
"=",
"chimes",
".",
"to_i",
"logger",
".",
"print",
"\"\\a\"",
"*",
"chimes",
"if",
"chimes",
">",
"0",
"&&",
"logger",
"true",
"end"
] | Make a terminal bell chime | [
"Make",
"a",
"terminal",
"bell",
"chime"
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L98-L104 | train |
solutious/rudy | lib/rudy/utils.rb | Rudy.Utils.bug | def bug(bugid, logger=STDERR)
logger.puts "You have found a bug! If you want, you can email".color(:red)
logger.puts '[email protected]'.color(:red).bright << " about it. It's bug ##{bugid}.".color(:red)
logger.puts "Continuing...".color(:red)
true # so we can string it together like: bug('1') && next if ...
end | ruby | def bug(bugid, logger=STDERR)
logger.puts "You have found a bug! If you want, you can email".color(:red)
logger.puts '[email protected]'.color(:red).bright << " about it. It's bug ##{bugid}.".color(:red)
logger.puts "Continuing...".color(:red)
true # so we can string it together like: bug('1') && next if ...
end | [
"def",
"bug",
"(",
"bugid",
",",
"logger",
"=",
"STDERR",
")",
"logger",
".",
"puts",
"\"You have found a bug! If you want, you can email\"",
".",
"color",
"(",
":red",
")",
"logger",
".",
"puts",
"'[email protected]'",
".",
"color",
"(",
":red",
")",
".",
"bright",
"<<",
"\" about it. It's bug ##{bugid}.\"",
".",
"color",
"(",
":red",
")",
"logger",
".",
"puts",
"\"Continuing...\"",
".",
"color",
"(",
":red",
")",
"true",
"end"
] | Have you seen that episode of The Cosby Show where Dizzy Gillespie... ah nevermind. | [
"Have",
"you",
"seen",
"that",
"episode",
"of",
"The",
"Cosby",
"Show",
"where",
"Dizzy",
"Gillespie",
"...",
"ah",
"nevermind",
"."
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L107-L112 | train |
solutious/rudy | lib/rudy/utils.rb | Rudy.Utils.known_type? | def known_type?(key)
return false unless key
key &&= key.to_s.to_sym
Rudy::ID_MAP.has_key?(key)
end | ruby | def known_type?(key)
return false unless key
key &&= key.to_s.to_sym
Rudy::ID_MAP.has_key?(key)
end | [
"def",
"known_type?",
"(",
"key",
")",
"return",
"false",
"unless",
"key",
"key",
"&&=",
"key",
".",
"to_s",
".",
"to_sym",
"Rudy",
"::",
"ID_MAP",
".",
"has_key?",
"(",
"key",
")",
"end"
] | Is the given +key+ a known type of object? | [
"Is",
"the",
"given",
"+",
"key",
"+",
"a",
"known",
"type",
"of",
"object?"
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L133-L137 | train |
solutious/rudy | lib/rudy/utils.rb | Rudy.Utils.identifier | def identifier(key)
key &&= key.to_sym
return unless Rudy::ID_MAP.has_key?(key)
Rudy::ID_MAP[key]
end | ruby | def identifier(key)
key &&= key.to_sym
return unless Rudy::ID_MAP.has_key?(key)
Rudy::ID_MAP[key]
end | [
"def",
"identifier",
"(",
"key",
")",
"key",
"&&=",
"key",
".",
"to_sym",
"return",
"unless",
"Rudy",
"::",
"ID_MAP",
".",
"has_key?",
"(",
"key",
")",
"Rudy",
"::",
"ID_MAP",
"[",
"key",
"]",
"end"
] | Returns the string identifier associated to this +key+ | [
"Returns",
"the",
"string",
"identifier",
"associated",
"to",
"this",
"+",
"key",
"+"
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L140-L144 | train |
solutious/rudy | lib/rudy/utils.rb | Rudy.Utils.capture | def capture(stream)
#raise "We can only capture STDOUT or STDERR" unless stream == :stdout || stream == :stderr
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").read
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end | ruby | def capture(stream)
#raise "We can only capture STDOUT or STDERR" unless stream == :stdout || stream == :stderr
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").read
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end | [
"def",
"capture",
"(",
"stream",
")",
"begin",
"stream",
"=",
"stream",
".",
"to_s",
"eval",
"\"$#{stream} = StringIO.new\"",
"yield",
"result",
"=",
"eval",
"(",
"\"$#{stream}\"",
")",
".",
"read",
"ensure",
"eval",
"(",
"\"$#{stream} = #{stream.upcase}\"",
")",
"end",
"result",
"end"
] | Capture STDOUT or STDERR to prevent it from being printed.
capture(:stdout) do
...
end | [
"Capture",
"STDOUT",
"or",
"STDERR",
"to",
"prevent",
"it",
"from",
"being",
"printed",
"."
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L236-L248 | train |
solutious/rudy | lib/rudy/utils.rb | Rudy.Utils.write_to_file | def write_to_file(filename, content, mode, chmod=600)
mode = (mode == :append) ? 'a' : 'w'
f = File.open(filename,mode)
f.puts content
f.close
return unless Rudy.sysinfo.os == :unix
raise "Provided chmod is not a Fixnum (#{chmod})" unless chmod.is_a?(Fixnum)
File.chmod(chmod, filename)
end | ruby | def write_to_file(filename, content, mode, chmod=600)
mode = (mode == :append) ? 'a' : 'w'
f = File.open(filename,mode)
f.puts content
f.close
return unless Rudy.sysinfo.os == :unix
raise "Provided chmod is not a Fixnum (#{chmod})" unless chmod.is_a?(Fixnum)
File.chmod(chmod, filename)
end | [
"def",
"write_to_file",
"(",
"filename",
",",
"content",
",",
"mode",
",",
"chmod",
"=",
"600",
")",
"mode",
"=",
"(",
"mode",
"==",
":append",
")",
"?",
"'a'",
":",
"'w'",
"f",
"=",
"File",
".",
"open",
"(",
"filename",
",",
"mode",
")",
"f",
".",
"puts",
"content",
"f",
".",
"close",
"return",
"unless",
"Rudy",
".",
"sysinfo",
".",
"os",
"==",
":unix",
"raise",
"\"Provided chmod is not a Fixnum (#{chmod})\"",
"unless",
"chmod",
".",
"is_a?",
"(",
"Fixnum",
")",
"File",
".",
"chmod",
"(",
"chmod",
",",
"filename",
")",
"end"
] | A basic file writer | [
"A",
"basic",
"file",
"writer"
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L251-L259 | train |
solutious/rudy | lib/rudy/metadata.rb | Rudy.Metadata.refresh! | def refresh!
raise UnknownObject, self.name unless self.exists?
h = Rudy::Metadata.get self.name
return false if h.nil? || h.empty?
obj = self.from_hash(h)
obj.postprocess
obj
end | ruby | def refresh!
raise UnknownObject, self.name unless self.exists?
h = Rudy::Metadata.get self.name
return false if h.nil? || h.empty?
obj = self.from_hash(h)
obj.postprocess
obj
end | [
"def",
"refresh!",
"raise",
"UnknownObject",
",",
"self",
".",
"name",
"unless",
"self",
".",
"exists?",
"h",
"=",
"Rudy",
"::",
"Metadata",
".",
"get",
"self",
".",
"name",
"return",
"false",
"if",
"h",
".",
"nil?",
"||",
"h",
".",
"empty?",
"obj",
"=",
"self",
".",
"from_hash",
"(",
"h",
")",
"obj",
".",
"postprocess",
"obj",
"end"
] | Refresh the metadata object from SimpleDB. If the record doesn't
exist it will raise an UnknownObject error | [
"Refresh",
"the",
"metadata",
"object",
"from",
"SimpleDB",
".",
"If",
"the",
"record",
"doesn",
"t",
"exist",
"it",
"will",
"raise",
"an",
"UnknownObject",
"error"
] | 52627b6228a29243b22ffeb188546f33aec95343 | https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/metadata.rb#L220-L227 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.