repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
jmdeldin/cross_validation | lib/cross_validation/runner.rb | CrossValidation.Runner.valid? | def valid?
@errors = []
@critical_keys.each do |k|
any_error = public_send(k).nil?
@errors << k if any_error
end
@errors.size == 0
end | ruby | def valid?
@errors = []
@critical_keys.each do |k|
any_error = public_send(k).nil?
@errors << k if any_error
end
@errors.size == 0
end | [
"def",
"valid?",
"@errors",
"=",
"[",
"]",
"@critical_keys",
".",
"each",
"do",
"|",
"k",
"|",
"any_error",
"=",
"public_send",
"(",
"k",
")",
".",
"nil?",
"@errors",
"<<",
"k",
"if",
"any_error",
"end",
"@errors",
".",
"size",
"==",
"0",
"end"
] | Checks if all of the required run parameters are set.
@return [Boolean] | [
"Checks",
"if",
"all",
"of",
"the",
"required",
"run",
"parameters",
"are",
"set",
"."
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/runner.rb#L69-L77 | train |
jmdeldin/cross_validation | lib/cross_validation/runner.rb | CrossValidation.Runner.run | def run
fail_if_invalid
partitions = Partitioner.subset(documents, k)
results = partitions.map.with_index do |part, i|
training_samples = Partitioner.exclude_index(documents, i)
classifier_instance = classifier.call()
train(classifier_instance, training_samples)
# fetch confusion keys
part.each do |x|
prediction = classify(classifier_instance, x)
matrix.store(prediction, fetch_sample_class.call(x))
end
end
matrix
end | ruby | def run
fail_if_invalid
partitions = Partitioner.subset(documents, k)
results = partitions.map.with_index do |part, i|
training_samples = Partitioner.exclude_index(documents, i)
classifier_instance = classifier.call()
train(classifier_instance, training_samples)
# fetch confusion keys
part.each do |x|
prediction = classify(classifier_instance, x)
matrix.store(prediction, fetch_sample_class.call(x))
end
end
matrix
end | [
"def",
"run",
"fail_if_invalid",
"partitions",
"=",
"Partitioner",
".",
"subset",
"(",
"documents",
",",
"k",
")",
"results",
"=",
"partitions",
".",
"map",
".",
"with_index",
"do",
"|",
"part",
",",
"i",
"|",
"training_samples",
"=",
"Partitioner",
".",
"exclude_index",
"(",
"documents",
",",
"i",
")",
"classifier_instance",
"=",
"classifier",
".",
"call",
"(",
")",
"train",
"(",
"classifier_instance",
",",
"training_samples",
")",
"part",
".",
"each",
"do",
"|",
"x",
"|",
"prediction",
"=",
"classify",
"(",
"classifier_instance",
",",
"x",
")",
"matrix",
".",
"store",
"(",
"prediction",
",",
"fetch_sample_class",
".",
"call",
"(",
"x",
")",
")",
"end",
"end",
"matrix",
"end"
] | Performs k-fold cross-validation and returns a confusion matrix.
The algorithm is as follows (Mitchell, 1997, p147):
partitions = partition data into k-equal sized subsets (folds)
for i = 1 -> k:
T = data \ partitions[i]
train(T)
classify(partitions[i])
output confusion matrix
@raise [ArgumentError] if the runner is missing required attributes
@return [ConfusionMatrix] | [
"Performs",
"k",
"-",
"fold",
"cross",
"-",
"validation",
"and",
"returns",
"a",
"confusion",
"matrix",
"."
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/runner.rb#L97-L117 | train |
kkirsche/medium-sdk-ruby | lib/medium/publications.rb | Medium.Publications.create_post | def create_post(publication, opts)
response = @client.post "publications/#{publication['id']}/posts",
build_request_with(opts)
Medium::Client.validate response
end | ruby | def create_post(publication, opts)
response = @client.post "publications/#{publication['id']}/posts",
build_request_with(opts)
Medium::Client.validate response
end | [
"def",
"create_post",
"(",
"publication",
",",
"opts",
")",
"response",
"=",
"@client",
".",
"post",
"\"publications/#{publication['id']}/posts\"",
",",
"build_request_with",
"(",
"opts",
")",
"Medium",
"::",
"Client",
".",
"validate",
"response",
"end"
] | Creates a post in a publication on behalf of the authenticated user.
@param publication [Publication] A publication object.
@param opts [Hash] A hash of options to use when creating a post. The opts
hash requires the keys: `:title`, `:content_format`, and `:content`. The
following keys are optional: `:tags`, `:canonical_url`,
`:publish_status`, and `:license`
@return [Hash] The response is a Post object within a data envelope.
Example response:
```
HTTP/1.1 201 OK
Content-Type: application/json; charset=utf-8
{
"data": {
"id": "e6f36a",
"title": "Liverpool FC",
"authorId": "5303d74c64f66366f00cb9b2a94f3251bf5",
"tags": ["football", "sport", "Liverpool"],
"url": "https://medium.com/@majelbstoat/liverpool-fc-e6f36a",
"canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc",
"publishStatus": "public",
"publishedAt": 1442286338435,
"license": "all-rights-reserved",
"licenseUrl": "https://medium.com/policy/9db0094a1e0f",
"publicationId": "e3ef7f020bd"
}
}
``` | [
"Creates",
"a",
"post",
"in",
"a",
"publication",
"on",
"behalf",
"of",
"the",
"authenticated",
"user",
"."
] | eb3bbab3233737d4a60936c8a3b9dfdaf5e855bb | https://github.com/kkirsche/medium-sdk-ruby/blob/eb3bbab3233737d4a60936c8a3b9dfdaf5e855bb/lib/medium/publications.rb#L64-L68 | train |
damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.sign_in_user | def sign_in_user(username:, password:, client_id:, client_secret:, scope: 'openid')
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form username: username, password: password, scope: scope, grant_type: 'password'
end
end | ruby | def sign_in_user(username:, password:, client_id:, client_secret:, scope: 'openid')
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form username: username, password: password, scope: scope, grant_type: 'password'
end
end | [
"def",
"sign_in_user",
"(",
"username",
":",
",",
"password",
":",
",",
"client_id",
":",
",",
"client_secret",
":",
",",
"scope",
":",
"'openid'",
")",
"client",
"(",
"issuer",
")",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"/oauth2/#{auth_server_id}/v1/token\"",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded'",
"req",
".",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'Basic: '",
"+",
"Base64",
".",
"strict_encode64",
"(",
"\"#{client_id}:#{client_secret}\"",
")",
"req",
".",
"body",
"=",
"URI",
".",
"encode_www_form",
"username",
":",
"username",
",",
"password",
":",
"password",
",",
"scope",
":",
"scope",
",",
"grant_type",
":",
"'password'",
"end",
"end"
] | sign in user to get tokens | [
"sign",
"in",
"user",
"to",
"get",
"tokens"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L27-L34 | train |
damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.sign_in_client | def sign_in_client(client_id:, client_secret:, scope:)
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form scope: scope, grant_type: 'client_credentials'
end
end | ruby | def sign_in_client(client_id:, client_secret:, scope:)
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form scope: scope, grant_type: 'client_credentials'
end
end | [
"def",
"sign_in_client",
"(",
"client_id",
":",
",",
"client_secret",
":",
",",
"scope",
":",
")",
"client",
"(",
"issuer",
")",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"/oauth2/#{auth_server_id}/v1/token\"",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded'",
"req",
".",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'Basic: '",
"+",
"Base64",
".",
"strict_encode64",
"(",
"\"#{client_id}:#{client_secret}\"",
")",
"req",
".",
"body",
"=",
"URI",
".",
"encode_www_form",
"scope",
":",
"scope",
",",
"grant_type",
":",
"'client_credentials'",
"end",
"end"
] | sign in client to get access_token | [
"sign",
"in",
"client",
"to",
"get",
"access_token"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L37-L44 | train |
damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.verify_token | def verify_token(token, issuer:, audience:, client_id:)
header, payload = token.split('.').first(2).map{|encoded| JSON.parse(Base64.decode64(encoded))}
# validate claims
raise InvalidToken.new('Invalid issuer') if payload['iss'] != issuer
raise InvalidToken.new('Invalid audience') if payload['aud'] != audience
raise InvalidToken.new('Invalid client') if !Array(client_id).include?(payload['cid'])
raise InvalidToken.new('Token is expired') if payload['exp'].to_i <= Time.now.to_i
# validate signature
jwk = JSON::JWK.new(get_jwk(header, payload))
JSON::JWT.decode(token, jwk.to_key)
end | ruby | def verify_token(token, issuer:, audience:, client_id:)
header, payload = token.split('.').first(2).map{|encoded| JSON.parse(Base64.decode64(encoded))}
# validate claims
raise InvalidToken.new('Invalid issuer') if payload['iss'] != issuer
raise InvalidToken.new('Invalid audience') if payload['aud'] != audience
raise InvalidToken.new('Invalid client') if !Array(client_id).include?(payload['cid'])
raise InvalidToken.new('Token is expired') if payload['exp'].to_i <= Time.now.to_i
# validate signature
jwk = JSON::JWK.new(get_jwk(header, payload))
JSON::JWT.decode(token, jwk.to_key)
end | [
"def",
"verify_token",
"(",
"token",
",",
"issuer",
":",
",",
"audience",
":",
",",
"client_id",
":",
")",
"header",
",",
"payload",
"=",
"token",
".",
"split",
"(",
"'.'",
")",
".",
"first",
"(",
"2",
")",
".",
"map",
"{",
"|",
"encoded",
"|",
"JSON",
".",
"parse",
"(",
"Base64",
".",
"decode64",
"(",
"encoded",
")",
")",
"}",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Invalid issuer'",
")",
"if",
"payload",
"[",
"'iss'",
"]",
"!=",
"issuer",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Invalid audience'",
")",
"if",
"payload",
"[",
"'aud'",
"]",
"!=",
"audience",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Invalid client'",
")",
"if",
"!",
"Array",
"(",
"client_id",
")",
".",
"include?",
"(",
"payload",
"[",
"'cid'",
"]",
")",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Token is expired'",
")",
"if",
"payload",
"[",
"'exp'",
"]",
".",
"to_i",
"<=",
"Time",
".",
"now",
".",
"to_i",
"jwk",
"=",
"JSON",
"::",
"JWK",
".",
"new",
"(",
"get_jwk",
"(",
"header",
",",
"payload",
")",
")",
"JSON",
"::",
"JWT",
".",
"decode",
"(",
"token",
",",
"jwk",
".",
"to_key",
")",
"end"
] | validate the token | [
"validate",
"the",
"token"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L47-L59 | train |
damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.get_jwk | def get_jwk(header, payload)
kid = header['kid']
# cache hit
return JWKS_CACHE[kid] if JWKS_CACHE[kid]
# fetch jwk
logger.info("[Okta::Jwt] Fetching public key: kid => #{kid} ...") if logger
jwks_response = client(payload['iss']).get do |req|
req.url get_metadata(payload)['jwks_uri']
end
jwk = JSON.parse(jwks_response.body)['keys'].find do |key|
key.dig('kid') == kid
end
# cache and return the key
jwk.tap{JWKS_CACHE[kid] = jwk}
end | ruby | def get_jwk(header, payload)
kid = header['kid']
# cache hit
return JWKS_CACHE[kid] if JWKS_CACHE[kid]
# fetch jwk
logger.info("[Okta::Jwt] Fetching public key: kid => #{kid} ...") if logger
jwks_response = client(payload['iss']).get do |req|
req.url get_metadata(payload)['jwks_uri']
end
jwk = JSON.parse(jwks_response.body)['keys'].find do |key|
key.dig('kid') == kid
end
# cache and return the key
jwk.tap{JWKS_CACHE[kid] = jwk}
end | [
"def",
"get_jwk",
"(",
"header",
",",
"payload",
")",
"kid",
"=",
"header",
"[",
"'kid'",
"]",
"return",
"JWKS_CACHE",
"[",
"kid",
"]",
"if",
"JWKS_CACHE",
"[",
"kid",
"]",
"logger",
".",
"info",
"(",
"\"[Okta::Jwt] Fetching public key: kid => #{kid} ...\"",
")",
"if",
"logger",
"jwks_response",
"=",
"client",
"(",
"payload",
"[",
"'iss'",
"]",
")",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"get_metadata",
"(",
"payload",
")",
"[",
"'jwks_uri'",
"]",
"end",
"jwk",
"=",
"JSON",
".",
"parse",
"(",
"jwks_response",
".",
"body",
")",
"[",
"'keys'",
"]",
".",
"find",
"do",
"|",
"key",
"|",
"key",
".",
"dig",
"(",
"'kid'",
")",
"==",
"kid",
"end",
"jwk",
".",
"tap",
"{",
"JWKS_CACHE",
"[",
"kid",
"]",
"=",
"jwk",
"}",
"end"
] | extract public key from metadata's jwks_uri using kid | [
"extract",
"public",
"key",
"from",
"metadata",
"s",
"jwks_uri",
"using",
"kid"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L62-L79 | train |
jmdeldin/cross_validation | lib/cross_validation/confusion_matrix.rb | CrossValidation.ConfusionMatrix.store | def store(actual, truth)
key = @keys_for.call(truth, actual)
if @values.key?(key)
@values[key] += 1
else
fail IndexError, "#{key} not found in confusion matrix"
end
self
end | ruby | def store(actual, truth)
key = @keys_for.call(truth, actual)
if @values.key?(key)
@values[key] += 1
else
fail IndexError, "#{key} not found in confusion matrix"
end
self
end | [
"def",
"store",
"(",
"actual",
",",
"truth",
")",
"key",
"=",
"@keys_for",
".",
"call",
"(",
"truth",
",",
"actual",
")",
"if",
"@values",
".",
"key?",
"(",
"key",
")",
"@values",
"[",
"key",
"]",
"+=",
"1",
"else",
"fail",
"IndexError",
",",
"\"#{key} not found in confusion matrix\"",
"end",
"self",
"end"
] | Save the result of classification
@param [Object] actual The classified value
@param [Object] truth The known, expected value
@return [self] | [
"Save",
"the",
"result",
"of",
"classification"
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/confusion_matrix.rb#L36-L46 | train |
jmdeldin/cross_validation | lib/cross_validation/confusion_matrix.rb | CrossValidation.ConfusionMatrix.fscore | def fscore(beta)
b2 = Float(beta**2)
((b2 + 1) * precision * recall) / (b2 * precision + recall)
end | ruby | def fscore(beta)
b2 = Float(beta**2)
((b2 + 1) * precision * recall) / (b2 * precision + recall)
end | [
"def",
"fscore",
"(",
"beta",
")",
"b2",
"=",
"Float",
"(",
"beta",
"**",
"2",
")",
"(",
"(",
"b2",
"+",
"1",
")",
"*",
"precision",
"*",
"recall",
")",
"/",
"(",
"b2",
"*",
"precision",
"+",
"recall",
")",
"end"
] | Returns the F-measure of the classifier's precision and recall.
@param [Float] beta Favor precision (<1), recall (>1), or both (1)
@return [Float] | [
"Returns",
"the",
"F",
"-",
"measure",
"of",
"the",
"classifier",
"s",
"precision",
"and",
"recall",
"."
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/confusion_matrix.rb#L73-L76 | train |
tario/evalhook | lib/evalhook.rb | EvalHook.HookHandler.packet | def packet(code)
@global_variable_name = nil
partialruby_packet = partialruby_context.packet(code)
@all_packets ||= []
newpacket = EvalHook::Packet.new(partialruby_packet, @global_variable_name)
@all_packets << newpacket
newpacket
end | ruby | def packet(code)
@global_variable_name = nil
partialruby_packet = partialruby_context.packet(code)
@all_packets ||= []
newpacket = EvalHook::Packet.new(partialruby_packet, @global_variable_name)
@all_packets << newpacket
newpacket
end | [
"def",
"packet",
"(",
"code",
")",
"@global_variable_name",
"=",
"nil",
"partialruby_packet",
"=",
"partialruby_context",
".",
"packet",
"(",
"code",
")",
"@all_packets",
"||=",
"[",
"]",
"newpacket",
"=",
"EvalHook",
"::",
"Packet",
".",
"new",
"(",
"partialruby_packet",
",",
"@global_variable_name",
")",
"@all_packets",
"<<",
"newpacket",
"newpacket",
"end"
] | Creates a packet of preprocessed ruby code to run it later
, useful to execute the same code repeatedly and avoid heavy
preprocessing of ruby code all the times.
See EvalHook::Packet for more information
Example:
hook_handler = HookHandler.new
pack = hook_handler.packet('print "hello world\n"')
10.times do
pack.run
end
pack.dispose | [
"Creates",
"a",
"packet",
"of",
"preprocessed",
"ruby",
"code",
"to",
"run",
"it",
"later",
"useful",
"to",
"execute",
"the",
"same",
"code",
"repeatedly",
"and",
"avoid",
"heavy",
"preprocessing",
"of",
"ruby",
"code",
"all",
"the",
"times",
"."
] | 56645703b4f648ae0ad1c56962bf9f786fe2d74d | https://github.com/tario/evalhook/blob/56645703b4f648ae0ad1c56962bf9f786fe2d74d/lib/evalhook.rb#L284-L292 | train |
chrismoos/fastr | lib/fastr/application.rb | Fastr.Application.boot | def boot
Thread.new do
sleep 1 until EM.reactor_running?
begin
log.info "Loading application..."
app_init
load_settings
Fastr::Plugin.load(self)
load_app_classes
setup_router
setup_watcher
log.info "Application loaded successfully."
@booting = false
plugin_after_boot
rescue Exception => e
log.error "#{e}"
puts e.backtrace
log.fatal "Exiting due to previous errors..."
exit(1)
end
end
end | ruby | def boot
Thread.new do
sleep 1 until EM.reactor_running?
begin
log.info "Loading application..."
app_init
load_settings
Fastr::Plugin.load(self)
load_app_classes
setup_router
setup_watcher
log.info "Application loaded successfully."
@booting = false
plugin_after_boot
rescue Exception => e
log.error "#{e}"
puts e.backtrace
log.fatal "Exiting due to previous errors..."
exit(1)
end
end
end | [
"def",
"boot",
"Thread",
".",
"new",
"do",
"sleep",
"1",
"until",
"EM",
".",
"reactor_running?",
"begin",
"log",
".",
"info",
"\"Loading application...\"",
"app_init",
"load_settings",
"Fastr",
"::",
"Plugin",
".",
"load",
"(",
"self",
")",
"load_app_classes",
"setup_router",
"setup_watcher",
"log",
".",
"info",
"\"Application loaded successfully.\"",
"@booting",
"=",
"false",
"plugin_after_boot",
"rescue",
"Exception",
"=>",
"e",
"log",
".",
"error",
"\"#{e}\"",
"puts",
"e",
".",
"backtrace",
"log",
".",
"fatal",
"\"Exiting due to previous errors...\"",
"exit",
"(",
"1",
")",
"end",
"end",
"end"
] | This is used to initialize the application.
It runs in a thread because startup depends on EventMachine running | [
"This",
"is",
"used",
"to",
"initialize",
"the",
"application",
".",
"It",
"runs",
"in",
"a",
"thread",
"because",
"startup",
"depends",
"on",
"EventMachine",
"running"
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/application.rb#L65-L90 | train |
chrismoos/fastr | lib/fastr/application.rb | Fastr.Application.load_app_classes | def load_app_classes
@@load_paths.each do |name, path|
log.debug "Loading #{name} classes..."
Dir["#{self.app_path}/#{path}"].each do |f|
log.debug "Loading: #{f}"
load(f)
end
end
end | ruby | def load_app_classes
@@load_paths.each do |name, path|
log.debug "Loading #{name} classes..."
Dir["#{self.app_path}/#{path}"].each do |f|
log.debug "Loading: #{f}"
load(f)
end
end
end | [
"def",
"load_app_classes",
"@@load_paths",
".",
"each",
"do",
"|",
"name",
",",
"path",
"|",
"log",
".",
"debug",
"\"Loading #{name} classes...\"",
"Dir",
"[",
"\"#{self.app_path}/#{path}\"",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"log",
".",
"debug",
"\"Loading: #{f}\"",
"load",
"(",
"f",
")",
"end",
"end",
"end"
] | Loads all application classes. Called on startup. | [
"Loads",
"all",
"application",
"classes",
".",
"Called",
"on",
"startup",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/application.rb#L99-L108 | train |
chrismoos/fastr | lib/fastr/application.rb | Fastr.Application.setup_watcher | def setup_watcher
this = self
Handler.send(:define_method, :app) do
this
end
@@load_paths.each do |name, path|
Dir["#{self.app_path}/#{path}"].each do |f|
EM.watch_file(f, Handler)
end
end
end | ruby | def setup_watcher
this = self
Handler.send(:define_method, :app) do
this
end
@@load_paths.each do |name, path|
Dir["#{self.app_path}/#{path}"].each do |f|
EM.watch_file(f, Handler)
end
end
end | [
"def",
"setup_watcher",
"this",
"=",
"self",
"Handler",
".",
"send",
"(",
":define_method",
",",
":app",
")",
"do",
"this",
"end",
"@@load_paths",
".",
"each",
"do",
"|",
"name",
",",
"path",
"|",
"Dir",
"[",
"\"#{self.app_path}/#{path}\"",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"EM",
".",
"watch_file",
"(",
"f",
",",
"Handler",
")",
"end",
"end",
"end"
] | Watch for any file changes in the load paths. | [
"Watch",
"for",
"any",
"file",
"changes",
"in",
"the",
"load",
"paths",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/application.rb#L126-L137 | train |
cldwalker/datomic-client | lib/datomic/client.rb | Datomic.Client.transact | def transact(dbname, data)
data = transmute_data(data)
RestClient.post(db_url(dbname) + "/", {"tx-data" => data},
:Accept => 'application/edn', &HANDLE_RESPONSE)
end | ruby | def transact(dbname, data)
data = transmute_data(data)
RestClient.post(db_url(dbname) + "/", {"tx-data" => data},
:Accept => 'application/edn', &HANDLE_RESPONSE)
end | [
"def",
"transact",
"(",
"dbname",
",",
"data",
")",
"data",
"=",
"transmute_data",
"(",
"data",
")",
"RestClient",
".",
"post",
"(",
"db_url",
"(",
"dbname",
")",
"+",
"\"/\"",
",",
"{",
"\"tx-data\"",
"=>",
"data",
"}",
",",
":Accept",
"=>",
"'application/edn'",
",",
"&",
"HANDLE_RESPONSE",
")",
"end"
] | Data can be a ruby data structure or a string representing clojure data | [
"Data",
"can",
"be",
"a",
"ruby",
"data",
"structure",
"or",
"a",
"string",
"representing",
"clojure",
"data"
] | 49147cc1a7241dfd38c381ff0301e5d83335ed9c | https://github.com/cldwalker/datomic-client/blob/49147cc1a7241dfd38c381ff0301e5d83335ed9c/lib/datomic/client.rb#L30-L34 | train |
cldwalker/datomic-client | lib/datomic/client.rb | Datomic.Client.query | def query(query, args_or_dbname, params = {})
query = transmute_data(query)
args = args_or_dbname.is_a?(String) ? [db_alias(args_or_dbname)] : args_or_dbname
args = transmute_data(args)
get root_url("api/query"), params.merge(:q => query, :args => args)
end | ruby | def query(query, args_or_dbname, params = {})
query = transmute_data(query)
args = args_or_dbname.is_a?(String) ? [db_alias(args_or_dbname)] : args_or_dbname
args = transmute_data(args)
get root_url("api/query"), params.merge(:q => query, :args => args)
end | [
"def",
"query",
"(",
"query",
",",
"args_or_dbname",
",",
"params",
"=",
"{",
"}",
")",
"query",
"=",
"transmute_data",
"(",
"query",
")",
"args",
"=",
"args_or_dbname",
".",
"is_a?",
"(",
"String",
")",
"?",
"[",
"db_alias",
"(",
"args_or_dbname",
")",
"]",
":",
"args_or_dbname",
"args",
"=",
"transmute_data",
"(",
"args",
")",
"get",
"root_url",
"(",
"\"api/query\"",
")",
",",
"params",
".",
"merge",
"(",
":q",
"=>",
"query",
",",
":args",
"=>",
"args",
")",
"end"
] | Query can be a ruby data structure or a string representing clojure data
If the args_or_dbname is a String, it will be converted into one arg
pointing to that database. | [
"Query",
"can",
"be",
"a",
"ruby",
"data",
"structure",
"or",
"a",
"string",
"representing",
"clojure",
"data",
"If",
"the",
"args_or_dbname",
"is",
"a",
"String",
"it",
"will",
"be",
"converted",
"into",
"one",
"arg",
"pointing",
"to",
"that",
"database",
"."
] | 49147cc1a7241dfd38c381ff0301e5d83335ed9c | https://github.com/cldwalker/datomic-client/blob/49147cc1a7241dfd38c381ff0301e5d83335ed9c/lib/datomic/client.rb#L58-L63 | train |
LatoTeam/lato_view | app/helpers/lato_view/application_helper.rb | LatoView.ApplicationHelper.view | def view(*names)
# mantain compatibility with old cells (lato_view 1.0)
if names.length === 1
puts "YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE"
old_cell = "LatoView::CellsV1::#{names.first.capitalize}::Cell".constantize
return old_cell
end
# return correct cell
cell_class = "LatoView::"
names.each do |name|
cell_class = "#{cell_class}#{name.capitalize}::"
end
cell_class = "#{cell_class}Cell".constantize
return cell_class
end | ruby | def view(*names)
# mantain compatibility with old cells (lato_view 1.0)
if names.length === 1
puts "YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE"
old_cell = "LatoView::CellsV1::#{names.first.capitalize}::Cell".constantize
return old_cell
end
# return correct cell
cell_class = "LatoView::"
names.each do |name|
cell_class = "#{cell_class}#{name.capitalize}::"
end
cell_class = "#{cell_class}Cell".constantize
return cell_class
end | [
"def",
"view",
"(",
"*",
"names",
")",
"if",
"names",
".",
"length",
"===",
"1",
"puts",
"\"YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE\"",
"old_cell",
"=",
"\"LatoView::CellsV1::#{names.first.capitalize}::Cell\"",
".",
"constantize",
"return",
"old_cell",
"end",
"cell_class",
"=",
"\"LatoView::\"",
"names",
".",
"each",
"do",
"|",
"name",
"|",
"cell_class",
"=",
"\"#{cell_class}#{name.capitalize}::\"",
"end",
"cell_class",
"=",
"\"#{cell_class}Cell\"",
".",
"constantize",
"return",
"cell_class",
"end"
] | This function render a cell set with params. | [
"This",
"function",
"render",
"a",
"cell",
"set",
"with",
"params",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/app/helpers/lato_view/application_helper.rb#L6-L20 | train |
LatoTeam/lato_view | lib/lato_view/interface/images.rb | LatoView.Interface::Images.view_getSidebarLogo | def view_getSidebarLogo
return VIEW_SIDEBARLOGO if defined? VIEW_SIDEBARLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/sidebar_logo.svg")
return "lato/sidebar_logo.svg"
end
if File.exist?("#{dir}/sidebar_logo.png")
return "lato/sidebar_logo.png"
end
if File.exist?("#{dir}/sidebar_logo.jpg")
return "lato/sidebar_logo.jpg"
end
if File.exist?("#{dir}/sidebar_logo.gif")
return "lato/sidebar_logo.gif"
end
return view_getApplicationLogo
end | ruby | def view_getSidebarLogo
return VIEW_SIDEBARLOGO if defined? VIEW_SIDEBARLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/sidebar_logo.svg")
return "lato/sidebar_logo.svg"
end
if File.exist?("#{dir}/sidebar_logo.png")
return "lato/sidebar_logo.png"
end
if File.exist?("#{dir}/sidebar_logo.jpg")
return "lato/sidebar_logo.jpg"
end
if File.exist?("#{dir}/sidebar_logo.gif")
return "lato/sidebar_logo.gif"
end
return view_getApplicationLogo
end | [
"def",
"view_getSidebarLogo",
"return",
"VIEW_SIDEBARLOGO",
"if",
"defined?",
"VIEW_SIDEBARLOGO",
"dir",
"=",
"\"#{Rails.root}/app/assets/images/lato/\"",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.svg\"",
")",
"return",
"\"lato/sidebar_logo.svg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.png\"",
")",
"return",
"\"lato/sidebar_logo.png\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.jpg\"",
")",
"return",
"\"lato/sidebar_logo.jpg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.gif\"",
")",
"return",
"\"lato/sidebar_logo.gif\"",
"end",
"return",
"view_getApplicationLogo",
"end"
] | This function return the url of sidebar logo. | [
"This",
"function",
"return",
"the",
"url",
"of",
"sidebar",
"logo",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/images.rb#L6-L22 | train |
LatoTeam/lato_view | lib/lato_view/interface/images.rb | LatoView.Interface::Images.view_getLoginLogo | def view_getLoginLogo
return VIEW_LOGINLOGO if defined? VIEW_LOGINLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/login_logo.svg")
return "lato/login_logo.svg"
end
if File.exist?("#{dir}/login_logo.png")
return "lato/login_logo.png"
end
if File.exist?("#{dir}/login_logo.jpg")
return "lato/login_logo.jpg"
end
if File.exist?("#{dir}/login_logo.gif")
return "lato/login_logo.gif"
end
return view_getApplicationLogo
end | ruby | def view_getLoginLogo
return VIEW_LOGINLOGO if defined? VIEW_LOGINLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/login_logo.svg")
return "lato/login_logo.svg"
end
if File.exist?("#{dir}/login_logo.png")
return "lato/login_logo.png"
end
if File.exist?("#{dir}/login_logo.jpg")
return "lato/login_logo.jpg"
end
if File.exist?("#{dir}/login_logo.gif")
return "lato/login_logo.gif"
end
return view_getApplicationLogo
end | [
"def",
"view_getLoginLogo",
"return",
"VIEW_LOGINLOGO",
"if",
"defined?",
"VIEW_LOGINLOGO",
"dir",
"=",
"\"#{Rails.root}/app/assets/images/lato/\"",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.svg\"",
")",
"return",
"\"lato/login_logo.svg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.png\"",
")",
"return",
"\"lato/login_logo.png\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.jpg\"",
")",
"return",
"\"lato/login_logo.jpg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.gif\"",
")",
"return",
"\"lato/login_logo.gif\"",
"end",
"return",
"view_getApplicationLogo",
"end"
] | This function return the url of login logo. | [
"This",
"function",
"return",
"the",
"url",
"of",
"login",
"logo",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/images.rb#L25-L41 | train |
LatoTeam/lato_view | lib/lato_view/interface/images.rb | LatoView.Interface::Images.view_getApplicationLogo | def view_getApplicationLogo
return VIEW_APPLOGO if defined? VIEW_APPLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/logo.svg")
return "lato/logo.svg"
end
if File.exist?("#{dir}/logo.png")
return "lato/logo.png"
end
if File.exist?("#{dir}/logo.jpg")
return "lato/logo.jpg"
end
if File.exist?("#{dir}/logo.gif")
return "lato/logo.gif"
end
return false
end | ruby | def view_getApplicationLogo
return VIEW_APPLOGO if defined? VIEW_APPLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/logo.svg")
return "lato/logo.svg"
end
if File.exist?("#{dir}/logo.png")
return "lato/logo.png"
end
if File.exist?("#{dir}/logo.jpg")
return "lato/logo.jpg"
end
if File.exist?("#{dir}/logo.gif")
return "lato/logo.gif"
end
return false
end | [
"def",
"view_getApplicationLogo",
"return",
"VIEW_APPLOGO",
"if",
"defined?",
"VIEW_APPLOGO",
"dir",
"=",
"\"#{Rails.root}/app/assets/images/lato/\"",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.svg\"",
")",
"return",
"\"lato/logo.svg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.png\"",
")",
"return",
"\"lato/logo.png\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.jpg\"",
")",
"return",
"\"lato/logo.jpg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.gif\"",
")",
"return",
"\"lato/logo.gif\"",
"end",
"return",
"false",
"end"
] | This function return the url of application logo. | [
"This",
"function",
"return",
"the",
"url",
"of",
"application",
"logo",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/images.rb#L44-L60 | train |
chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.dispatch | def dispatch(env)
return [500, {'Content-Type' => 'text/plain'}, ["Server Not Ready"]] if @booting
begin
new_env = plugin_before_dispatch(env)
plugin_after_dispatch(new_env, do_dispatch(new_env))
rescue Exception => e
bt = e.backtrace.join("\n")
[500, {'Content-Type' => 'text/plain'}, ["Exception: #{e}\n\n#{bt}"]]
end
end | ruby | def dispatch(env)
return [500, {'Content-Type' => 'text/plain'}, ["Server Not Ready"]] if @booting
begin
new_env = plugin_before_dispatch(env)
plugin_after_dispatch(new_env, do_dispatch(new_env))
rescue Exception => e
bt = e.backtrace.join("\n")
[500, {'Content-Type' => 'text/plain'}, ["Exception: #{e}\n\n#{bt}"]]
end
end | [
"def",
"dispatch",
"(",
"env",
")",
"return",
"[",
"500",
",",
"{",
"'Content-Type'",
"=>",
"'text/plain'",
"}",
",",
"[",
"\"Server Not Ready\"",
"]",
"]",
"if",
"@booting",
"begin",
"new_env",
"=",
"plugin_before_dispatch",
"(",
"env",
")",
"plugin_after_dispatch",
"(",
"new_env",
",",
"do_dispatch",
"(",
"new_env",
")",
")",
"rescue",
"Exception",
"=>",
"e",
"bt",
"=",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"[",
"500",
",",
"{",
"'Content-Type'",
"=>",
"'text/plain'",
"}",
",",
"[",
"\"Exception: #{e}\\n\\n#{bt}\"",
"]",
"]",
"end",
"end"
] | Convenience wrapper for do_dispatch
This is the heart of the server, called indirectly by a Rack aware server.
@param env [Hash]
@return [Array] | [
"Convenience",
"wrapper",
"for",
"do_dispatch",
"This",
"is",
"the",
"heart",
"of",
"the",
"server",
"called",
"indirectly",
"by",
"a",
"Rack",
"aware",
"server",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L11-L21 | train |
chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.do_dispatch | def do_dispatch(env)
path = env['PATH_INFO']
# Try to serve a public file
ret = dispatch_public(env, path)
return ret if not ret.nil?
log.debug "Checking for routes that match: #{path}"
route = router.match(env)
if route.has_key? :ok
dispatch_controller(route, env)
else
[404, {"Content-Type" => "text/plain"}, ["404 Not Found: #{path}"]]
end
end | ruby | def do_dispatch(env)
path = env['PATH_INFO']
# Try to serve a public file
ret = dispatch_public(env, path)
return ret if not ret.nil?
log.debug "Checking for routes that match: #{path}"
route = router.match(env)
if route.has_key? :ok
dispatch_controller(route, env)
else
[404, {"Content-Type" => "text/plain"}, ["404 Not Found: #{path}"]]
end
end | [
"def",
"do_dispatch",
"(",
"env",
")",
"path",
"=",
"env",
"[",
"'PATH_INFO'",
"]",
"ret",
"=",
"dispatch_public",
"(",
"env",
",",
"path",
")",
"return",
"ret",
"if",
"not",
"ret",
".",
"nil?",
"log",
".",
"debug",
"\"Checking for routes that match: #{path}\"",
"route",
"=",
"router",
".",
"match",
"(",
"env",
")",
"if",
"route",
".",
"has_key?",
":ok",
"dispatch_controller",
"(",
"route",
",",
"env",
")",
"else",
"[",
"404",
",",
"{",
"\"Content-Type\"",
"=>",
"\"text/plain\"",
"}",
",",
"[",
"\"404 Not Found: #{path}\"",
"]",
"]",
"end",
"end"
] | Route, instantiate controller, return response from controller's action. | [
"Route",
"instantiate",
"controller",
"return",
"response",
"from",
"controller",
"s",
"action",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L24-L39 | train |
chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.setup_controller | def setup_controller(controller, env, vars)
controller.env = env
controller.headers = {}
setup_controller_params(controller, env, vars)
controller.cookies = Fastr::HTTP.parse_cookies(env)
controller.app = self
end | ruby | def setup_controller(controller, env, vars)
controller.env = env
controller.headers = {}
setup_controller_params(controller, env, vars)
controller.cookies = Fastr::HTTP.parse_cookies(env)
controller.app = self
end | [
"def",
"setup_controller",
"(",
"controller",
",",
"env",
",",
"vars",
")",
"controller",
".",
"env",
"=",
"env",
"controller",
".",
"headers",
"=",
"{",
"}",
"setup_controller_params",
"(",
"controller",
",",
"env",
",",
"vars",
")",
"controller",
".",
"cookies",
"=",
"Fastr",
"::",
"HTTP",
".",
"parse_cookies",
"(",
"env",
")",
"controller",
".",
"app",
"=",
"self",
"end"
] | Sets up a controller for a request. | [
"Sets",
"up",
"a",
"controller",
"for",
"a",
"request",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L95-L103 | train |
chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.setup_controller_params | def setup_controller_params(controller, env, vars)
if Fastr::HTTP.method?(env, :get)
controller.get_params = Fastr::HTTP.parse_query_string(env['QUERY_STRING'])
controller.params = controller.get_params.merge(vars)
elsif Fastr::HTTP.method?(env, :post)
controller.post_params = {}
controller.post_params = Fastr::HTTP.parse_query_string(env['rack.input'].read) if env['rack.input']
controller.params = controller.post_params.merge(vars)
else
controller.params = vars
end
end | ruby | def setup_controller_params(controller, env, vars)
if Fastr::HTTP.method?(env, :get)
controller.get_params = Fastr::HTTP.parse_query_string(env['QUERY_STRING'])
controller.params = controller.get_params.merge(vars)
elsif Fastr::HTTP.method?(env, :post)
controller.post_params = {}
controller.post_params = Fastr::HTTP.parse_query_string(env['rack.input'].read) if env['rack.input']
controller.params = controller.post_params.merge(vars)
else
controller.params = vars
end
end | [
"def",
"setup_controller_params",
"(",
"controller",
",",
"env",
",",
"vars",
")",
"if",
"Fastr",
"::",
"HTTP",
".",
"method?",
"(",
"env",
",",
":get",
")",
"controller",
".",
"get_params",
"=",
"Fastr",
"::",
"HTTP",
".",
"parse_query_string",
"(",
"env",
"[",
"'QUERY_STRING'",
"]",
")",
"controller",
".",
"params",
"=",
"controller",
".",
"get_params",
".",
"merge",
"(",
"vars",
")",
"elsif",
"Fastr",
"::",
"HTTP",
".",
"method?",
"(",
"env",
",",
":post",
")",
"controller",
".",
"post_params",
"=",
"{",
"}",
"controller",
".",
"post_params",
"=",
"Fastr",
"::",
"HTTP",
".",
"parse_query_string",
"(",
"env",
"[",
"'rack.input'",
"]",
".",
"read",
")",
"if",
"env",
"[",
"'rack.input'",
"]",
"controller",
".",
"params",
"=",
"controller",
".",
"post_params",
".",
"merge",
"(",
"vars",
")",
"else",
"controller",
".",
"params",
"=",
"vars",
"end",
"end"
] | Populate the parameters based on the HTTP method. | [
"Populate",
"the",
"parameters",
"based",
"on",
"the",
"HTTP",
"method",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L106-L117 | train |
chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.plugin_before_dispatch | def plugin_before_dispatch(env)
new_env = env
self.plugins.each do |plugin|
if plugin.respond_to? :before_dispatch
new_env = plugin.send(:before_dispatch, self, env)
end
end
new_env
end | ruby | def plugin_before_dispatch(env)
new_env = env
self.plugins.each do |plugin|
if plugin.respond_to? :before_dispatch
new_env = plugin.send(:before_dispatch, self, env)
end
end
new_env
end | [
"def",
"plugin_before_dispatch",
"(",
"env",
")",
"new_env",
"=",
"env",
"self",
".",
"plugins",
".",
"each",
"do",
"|",
"plugin",
"|",
"if",
"plugin",
".",
"respond_to?",
":before_dispatch",
"new_env",
"=",
"plugin",
".",
"send",
"(",
":before_dispatch",
",",
"self",
",",
"env",
")",
"end",
"end",
"new_env",
"end"
] | Runs before_dispatch in all plugins.
@param env [Hash]
@return [Hash] | [
"Runs",
"before_dispatch",
"in",
"all",
"plugins",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L123-L133 | train |
chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.plugin_after_dispatch | def plugin_after_dispatch(env, response)
new_response = response
self.plugins.each do |plugin|
if plugin.respond_to? :after_dispatch
new_response = plugin.send(:after_dispatch, self, env, response)
end
end
new_response
end | ruby | def plugin_after_dispatch(env, response)
new_response = response
self.plugins.each do |plugin|
if plugin.respond_to? :after_dispatch
new_response = plugin.send(:after_dispatch, self, env, response)
end
end
new_response
end | [
"def",
"plugin_after_dispatch",
"(",
"env",
",",
"response",
")",
"new_response",
"=",
"response",
"self",
".",
"plugins",
".",
"each",
"do",
"|",
"plugin",
"|",
"if",
"plugin",
".",
"respond_to?",
":after_dispatch",
"new_response",
"=",
"plugin",
".",
"send",
"(",
":after_dispatch",
",",
"self",
",",
"env",
",",
"response",
")",
"end",
"end",
"new_response",
"end"
] | Runs after_dispatch in all plugins.
@param env [Hash]
@return [Hash] | [
"Runs",
"after_dispatch",
"in",
"all",
"plugins",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L139-L149 | train |
jonahoffline/filepreviews-ruby | lib/filepreviews/cli.rb | Filepreviews.CLI.options | def options(opts)
opts.version = Filepreviews::VERSION
opts.banner = BANNER
opts.set_program_name 'Filepreviews.io'
opts.on('-k', '--api_key [key]', String,
'use API key from Filepreviews.io') do |api_key|
Filepreviews.api_key = api_key
end
opts.on('-s', '--secret_key [key]', String,
'use Secret key from Filepreviews.io') do |secret_key|
Filepreviews.secret_key = secret_key
end
opts.on('-m', '--metadata', 'load metadata response') do
@metadata = true
end
opts.on_tail('-v', '--version', 'display the version of Filepreviews') do
puts opts.version
exit
end
opts.on_tail('-h', '--help', 'print this help') do
puts opts.help
exit
end
end | ruby | def options(opts)
opts.version = Filepreviews::VERSION
opts.banner = BANNER
opts.set_program_name 'Filepreviews.io'
opts.on('-k', '--api_key [key]', String,
'use API key from Filepreviews.io') do |api_key|
Filepreviews.api_key = api_key
end
opts.on('-s', '--secret_key [key]', String,
'use Secret key from Filepreviews.io') do |secret_key|
Filepreviews.secret_key = secret_key
end
opts.on('-m', '--metadata', 'load metadata response') do
@metadata = true
end
opts.on_tail('-v', '--version', 'display the version of Filepreviews') do
puts opts.version
exit
end
opts.on_tail('-h', '--help', 'print this help') do
puts opts.help
exit
end
end | [
"def",
"options",
"(",
"opts",
")",
"opts",
".",
"version",
"=",
"Filepreviews",
"::",
"VERSION",
"opts",
".",
"banner",
"=",
"BANNER",
"opts",
".",
"set_program_name",
"'Filepreviews.io'",
"opts",
".",
"on",
"(",
"'-k'",
",",
"'--api_key [key]'",
",",
"String",
",",
"'use API key from Filepreviews.io'",
")",
"do",
"|",
"api_key",
"|",
"Filepreviews",
".",
"api_key",
"=",
"api_key",
"end",
"opts",
".",
"on",
"(",
"'-s'",
",",
"'--secret_key [key]'",
",",
"String",
",",
"'use Secret key from Filepreviews.io'",
")",
"do",
"|",
"secret_key",
"|",
"Filepreviews",
".",
"secret_key",
"=",
"secret_key",
"end",
"opts",
".",
"on",
"(",
"'-m'",
",",
"'--metadata'",
",",
"'load metadata response'",
")",
"do",
"@metadata",
"=",
"true",
"end",
"opts",
".",
"on_tail",
"(",
"'-v'",
",",
"'--version'",
",",
"'display the version of Filepreviews'",
")",
"do",
"puts",
"opts",
".",
"version",
"exit",
"end",
"opts",
".",
"on_tail",
"(",
"'-h'",
",",
"'--help'",
",",
"'print this help'",
")",
"do",
"puts",
"opts",
".",
"help",
"exit",
"end",
"end"
] | Passes arguments from ARGV and sets metadata flag
@param args [Array<String>] The command-line arguments
Configures the arguments for the command
@param opts [OptionParser] | [
"Passes",
"arguments",
"from",
"ARGV",
"and",
"sets",
"metadata",
"flag"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/cli.rb#L22-L50 | train |
jonahoffline/filepreviews-ruby | lib/filepreviews/cli.rb | Filepreviews.CLI.parse | def parse
opts = OptionParser.new(&method(:options))
opts.parse!(@args)
return opts.help if @args.last.nil?
file_preview = Filepreviews.generate(@args.last)
@metadata ? file_preview.metadata(js: true) : file_preview
end | ruby | def parse
opts = OptionParser.new(&method(:options))
opts.parse!(@args)
return opts.help if @args.last.nil?
file_preview = Filepreviews.generate(@args.last)
@metadata ? file_preview.metadata(js: true) : file_preview
end | [
"def",
"parse",
"opts",
"=",
"OptionParser",
".",
"new",
"(",
"&",
"method",
"(",
":options",
")",
")",
"opts",
".",
"parse!",
"(",
"@args",
")",
"return",
"opts",
".",
"help",
"if",
"@args",
".",
"last",
".",
"nil?",
"file_preview",
"=",
"Filepreviews",
".",
"generate",
"(",
"@args",
".",
"last",
")",
"@metadata",
"?",
"file_preview",
".",
"metadata",
"(",
"js",
":",
"true",
")",
":",
"file_preview",
"end"
] | Parses options sent from command-line | [
"Parses",
"options",
"sent",
"from",
"command",
"-",
"line"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/cli.rb#L53-L60 | train |
shideneyu/ownlan | lib/ownlan/config.rb | Ownlan.Configuration.source_mac | def source_mac
@source_mac ||= if self.victim_ip
::ServiceObjects::NetworkInformation.self_mac(interface)
else
gateway_ip = ServiceObjects::NetworkInformation.gateway_ip
mac = ::Ownlan::Attack::Base.new(self).ip_to_mac(gateway_ip)
end
end | ruby | def source_mac
@source_mac ||= if self.victim_ip
::ServiceObjects::NetworkInformation.self_mac(interface)
else
gateway_ip = ServiceObjects::NetworkInformation.gateway_ip
mac = ::Ownlan::Attack::Base.new(self).ip_to_mac(gateway_ip)
end
end | [
"def",
"source_mac",
"@source_mac",
"||=",
"if",
"self",
".",
"victim_ip",
"::",
"ServiceObjects",
"::",
"NetworkInformation",
".",
"self_mac",
"(",
"interface",
")",
"else",
"gateway_ip",
"=",
"ServiceObjects",
"::",
"NetworkInformation",
".",
"gateway_ip",
"mac",
"=",
"::",
"Ownlan",
"::",
"Attack",
"::",
"Base",
".",
"new",
"(",
"self",
")",
".",
"ip_to_mac",
"(",
"gateway_ip",
")",
"end",
"end"
] | Create a new instance.
@return [Ownlan::Configuration] | [
"Create",
"a",
"new",
"instance",
"."
] | 2815a8be08e0fdbf18f9e422776d8d354a60a902 | https://github.com/shideneyu/ownlan/blob/2815a8be08e0fdbf18f9e422776d8d354a60a902/lib/ownlan/config.rb#L45-L52 | train |
esumbar/passphrase | lib/passphrase/diceware_random.rb | Passphrase.DicewareRandom.die_rolls | def die_rolls(number_of_words)
# The Diceware method specifies five rolls of the die for each word.
die_rolls_per_word = 5
total_die_rolls = number_of_words * die_rolls_per_word
die_roll_sequence = generate_random_numbers(total_die_rolls, 6, 1)
group_die_rolls(die_roll_sequence, number_of_words, die_rolls_per_word)
end | ruby | def die_rolls(number_of_words)
# The Diceware method specifies five rolls of the die for each word.
die_rolls_per_word = 5
total_die_rolls = number_of_words * die_rolls_per_word
die_roll_sequence = generate_random_numbers(total_die_rolls, 6, 1)
group_die_rolls(die_roll_sequence, number_of_words, die_rolls_per_word)
end | [
"def",
"die_rolls",
"(",
"number_of_words",
")",
"die_rolls_per_word",
"=",
"5",
"total_die_rolls",
"=",
"number_of_words",
"*",
"die_rolls_per_word",
"die_roll_sequence",
"=",
"generate_random_numbers",
"(",
"total_die_rolls",
",",
"6",
",",
"1",
")",
"group_die_rolls",
"(",
"die_roll_sequence",
",",
"number_of_words",
",",
"die_rolls_per_word",
")",
"end"
] | Returns an array of strings where each string comprises five numeric
characters, each one representing one roll of a die. The number of
elements in the array equals the number of words specified for the
passphrase.
@param number_of_words [Integer] the desired number of words in the
passphrase
@return [Array<String>] an array of strings each one of which represents
five rolls of a die | [
"Returns",
"an",
"array",
"of",
"strings",
"where",
"each",
"string",
"comprises",
"five",
"numeric",
"characters",
"each",
"one",
"representing",
"one",
"roll",
"of",
"a",
"die",
".",
"The",
"number",
"of",
"elements",
"in",
"the",
"array",
"equals",
"the",
"number",
"of",
"words",
"specified",
"for",
"the",
"passphrase",
"."
] | 5faaa6dcf71f31bc6acad6f683f581408e0b5c32 | https://github.com/esumbar/passphrase/blob/5faaa6dcf71f31bc6acad6f683f581408e0b5c32/lib/passphrase/diceware_random.rb#L46-L52 | train |
jonahoffline/filepreviews-ruby | lib/filepreviews/utils.rb | Filepreviews.Utils.process_params | def process_params(params)
parameters = { url: CGI.unescape(params.url) }
if params.metadata
parameters[:metadata] = extract_metadata(params.metadata)
end
parameters
end | ruby | def process_params(params)
parameters = { url: CGI.unescape(params.url) }
if params.metadata
parameters[:metadata] = extract_metadata(params.metadata)
end
parameters
end | [
"def",
"process_params",
"(",
"params",
")",
"parameters",
"=",
"{",
"url",
":",
"CGI",
".",
"unescape",
"(",
"params",
".",
"url",
")",
"}",
"if",
"params",
".",
"metadata",
"parameters",
"[",
":metadata",
"]",
"=",
"extract_metadata",
"(",
"params",
".",
"metadata",
")",
"end",
"parameters",
"end"
] | Returns processed options and url as parameters
@param params [Hash<Symbol>] :url and :metadata
@return [Hash<Symbol>] processed parameters for http request | [
"Returns",
"processed",
"options",
"and",
"url",
"as",
"parameters"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/utils.rb#L41-L49 | train |
chrismoos/fastr | lib/fastr/router.rb | Fastr.Router.match | def match(env)
self.routes.each do |info|
# If the route didn't specify method(s) to limit by, then all HTTP methods are valid.
# If the route specified method(s), we check the request's HTTP method and validate
# that it exists in that list.
next unless info[:methods].nil? or info[:methods].include?(env["REQUEST_METHOD"].downcase.to_sym)
match = env['PATH_INFO'].match(info[:regex])
# See if a route matches
if not match.nil?
# Map any parameters in our matched string
vars = {}
info[:vars].each_index do |i|
var = info[:vars][i]
vars[var] = match[i+1]
end
return {:ok => vars.merge!(info[:hash]) }
end
end
{:error => :not_found}
end | ruby | def match(env)
self.routes.each do |info|
# If the route didn't specify method(s) to limit by, then all HTTP methods are valid.
# If the route specified method(s), we check the request's HTTP method and validate
# that it exists in that list.
next unless info[:methods].nil? or info[:methods].include?(env["REQUEST_METHOD"].downcase.to_sym)
match = env['PATH_INFO'].match(info[:regex])
# See if a route matches
if not match.nil?
# Map any parameters in our matched string
vars = {}
info[:vars].each_index do |i|
var = info[:vars][i]
vars[var] = match[i+1]
end
return {:ok => vars.merge!(info[:hash]) }
end
end
{:error => :not_found}
end | [
"def",
"match",
"(",
"env",
")",
"self",
".",
"routes",
".",
"each",
"do",
"|",
"info",
"|",
"next",
"unless",
"info",
"[",
":methods",
"]",
".",
"nil?",
"or",
"info",
"[",
":methods",
"]",
".",
"include?",
"(",
"env",
"[",
"\"REQUEST_METHOD\"",
"]",
".",
"downcase",
".",
"to_sym",
")",
"match",
"=",
"env",
"[",
"'PATH_INFO'",
"]",
".",
"match",
"(",
"info",
"[",
":regex",
"]",
")",
"if",
"not",
"match",
".",
"nil?",
"vars",
"=",
"{",
"}",
"info",
"[",
":vars",
"]",
".",
"each_index",
"do",
"|",
"i",
"|",
"var",
"=",
"info",
"[",
":vars",
"]",
"[",
"i",
"]",
"vars",
"[",
"var",
"]",
"=",
"match",
"[",
"i",
"+",
"1",
"]",
"end",
"return",
"{",
":ok",
"=>",
"vars",
".",
"merge!",
"(",
"info",
"[",
":hash",
"]",
")",
"}",
"end",
"end",
"{",
":error",
"=>",
":not_found",
"}",
"end"
] | Searches the routes for a match given a Rack env.
{#match} looks in the {#routes} to find a match.
This method looks at PATH_INFO in +env+ to get the current request's path.
== Return
No Match:
{:error => :not_found}
Match:
{:ok => {:controller => 'controller', :action => 'action', :var => 'value'}}
@param env [Hash]
@return [Hash] | [
"Searches",
"the",
"routes",
"for",
"a",
"match",
"given",
"a",
"Rack",
"env",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/router.rb#L51-L77 | train |
chrismoos/fastr | lib/fastr/router.rb | Fastr.Router.for | def for(path, *args)
arg = args[0]
log.debug "Adding route, path: #{path}, args: #{args.inspect}"
match = get_regex_for_route(path, arg)
hash = get_to_hash(arg)
route_info = {:regex => match[:regex], :args => arg, :vars => match[:vars], :hash => hash}
# Add the HTTP methods for this route if they exist in options
route_info[:methods] = arg[:methods] if not arg.nil? and arg.has_key? :methods
self.routes.push(route_info)
end | ruby | def for(path, *args)
arg = args[0]
log.debug "Adding route, path: #{path}, args: #{args.inspect}"
match = get_regex_for_route(path, arg)
hash = get_to_hash(arg)
route_info = {:regex => match[:regex], :args => arg, :vars => match[:vars], :hash => hash}
# Add the HTTP methods for this route if they exist in options
route_info[:methods] = arg[:methods] if not arg.nil? and arg.has_key? :methods
self.routes.push(route_info)
end | [
"def",
"for",
"(",
"path",
",",
"*",
"args",
")",
"arg",
"=",
"args",
"[",
"0",
"]",
"log",
".",
"debug",
"\"Adding route, path: #{path}, args: #{args.inspect}\"",
"match",
"=",
"get_regex_for_route",
"(",
"path",
",",
"arg",
")",
"hash",
"=",
"get_to_hash",
"(",
"arg",
")",
"route_info",
"=",
"{",
":regex",
"=>",
"match",
"[",
":regex",
"]",
",",
":args",
"=>",
"arg",
",",
":vars",
"=>",
"match",
"[",
":vars",
"]",
",",
":hash",
"=>",
"hash",
"}",
"route_info",
"[",
":methods",
"]",
"=",
"arg",
"[",
":methods",
"]",
"if",
"not",
"arg",
".",
"nil?",
"and",
"arg",
".",
"has_key?",
":methods",
"self",
".",
"routes",
".",
"push",
"(",
"route_info",
")",
"end"
] | Adds a route for a path and arguments.
@param path [String]
@param args [Array] | [
"Adds",
"a",
"route",
"for",
"a",
"path",
"and",
"arguments",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/router.rb#L92-L104 | train |
delano/uri-redis | lib/uri/redis.rb | URI.Redis.conf | def conf
hsh = {
:host => host,
:port => port,
:db => db
}.merge parse_query(query)
hsh[:password] = password if password
hsh
end | ruby | def conf
hsh = {
:host => host,
:port => port,
:db => db
}.merge parse_query(query)
hsh[:password] = password if password
hsh
end | [
"def",
"conf",
"hsh",
"=",
"{",
":host",
"=>",
"host",
",",
":port",
"=>",
"port",
",",
":db",
"=>",
"db",
"}",
".",
"merge",
"parse_query",
"(",
"query",
")",
"hsh",
"[",
":password",
"]",
"=",
"password",
"if",
"password",
"hsh",
"end"
] | Returns a hash suitable for sending to Redis.new.
The hash is generated from the host, port, db and
password from the URI as well as any query vars.
e.g.
uri = URI.parse "redis://127.0.0.1/6/?timeout=5"
uri.conf
# => {:db=>6, :timeout=>"5", :host=>"127.0.0.1", :port=>6379} | [
"Returns",
"a",
"hash",
"suitable",
"for",
"sending",
"to",
"Redis",
".",
"new",
".",
"The",
"hash",
"is",
"generated",
"from",
"the",
"host",
"port",
"db",
"and",
"password",
"from",
"the",
"URI",
"as",
"well",
"as",
"any",
"query",
"vars",
"."
] | 4264526318117264df09fd6f5a42ee605f1db0fd | https://github.com/delano/uri-redis/blob/4264526318117264df09fd6f5a42ee605f1db0fd/lib/uri/redis.rb#L55-L63 | train |
LatoTeam/lato_view | lib/lato_view/interface/themes.rb | LatoView.Interface::Themes.view_getCurrentTemplateName | def view_getCurrentTemplateName
return VIEW_CURRENTTEMPLATENAME if defined? VIEW_CURRENTTEMPLATENAME
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# verifico esistenza dati
if !config || !config['template']
return false
end
# verifico che il template sia valido
unless VIEW_TEMPLATES.include? config['template']
raise 'Template value is not correct on view.yml config file' and return false
end
# ritorno nome template
return config['template']
else
return false
end
end | ruby | def view_getCurrentTemplateName
return VIEW_CURRENTTEMPLATENAME if defined? VIEW_CURRENTTEMPLATENAME
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# verifico esistenza dati
if !config || !config['template']
return false
end
# verifico che il template sia valido
unless VIEW_TEMPLATES.include? config['template']
raise 'Template value is not correct on view.yml config file' and return false
end
# ritorno nome template
return config['template']
else
return false
end
end | [
"def",
"view_getCurrentTemplateName",
"return",
"VIEW_CURRENTTEMPLATENAME",
"if",
"defined?",
"VIEW_CURRENTTEMPLATENAME",
"directory",
"=",
"core_getCacheDirectory",
"if",
"File",
".",
"exist?",
"\"#{directory}/view.yml\"",
"config",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"\"#{directory}/view.yml\"",
",",
"__FILE__",
")",
")",
")",
"if",
"!",
"config",
"||",
"!",
"config",
"[",
"'template'",
"]",
"return",
"false",
"end",
"unless",
"VIEW_TEMPLATES",
".",
"include?",
"config",
"[",
"'template'",
"]",
"raise",
"'Template value is not correct on view.yml config file'",
"and",
"return",
"false",
"end",
"return",
"config",
"[",
"'template'",
"]",
"else",
"return",
"false",
"end",
"end"
] | This function return the name of the current theme used for the
application. | [
"This",
"function",
"return",
"the",
"name",
"of",
"the",
"current",
"theme",
"used",
"for",
"the",
"application",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/themes.rb#L7-L28 | train |
timrogers/rapgenius | lib/rapgenius/artist.rb | RapGenius.Artist.songs | def songs(options = {page: 1})
songs_url = "/artists/#{@id}/songs/?page=#{options[:page]}"
fetch(songs_url)["response"]["songs"].map do |song|
Song.new(
artist: Artist.new(
name: song["primary_artist"]["name"],
id: song["primary_artist"]["id"],
type: :primary
),
title: song["title"],
id: song["id"]
)
end
end | ruby | def songs(options = {page: 1})
songs_url = "/artists/#{@id}/songs/?page=#{options[:page]}"
fetch(songs_url)["response"]["songs"].map do |song|
Song.new(
artist: Artist.new(
name: song["primary_artist"]["name"],
id: song["primary_artist"]["id"],
type: :primary
),
title: song["title"],
id: song["id"]
)
end
end | [
"def",
"songs",
"(",
"options",
"=",
"{",
"page",
":",
"1",
"}",
")",
"songs_url",
"=",
"\"/artists/#{@id}/songs/?page=#{options[:page]}\"",
"fetch",
"(",
"songs_url",
")",
"[",
"\"response\"",
"]",
"[",
"\"songs\"",
"]",
".",
"map",
"do",
"|",
"song",
"|",
"Song",
".",
"new",
"(",
"artist",
":",
"Artist",
".",
"new",
"(",
"name",
":",
"song",
"[",
"\"primary_artist\"",
"]",
"[",
"\"name\"",
"]",
",",
"id",
":",
"song",
"[",
"\"primary_artist\"",
"]",
"[",
"\"id\"",
"]",
",",
"type",
":",
":primary",
")",
",",
"title",
":",
"song",
"[",
"\"title\"",
"]",
",",
"id",
":",
"song",
"[",
"\"id\"",
"]",
")",
"end",
"end"
] | You seem to be able to load 20 songs at a time for an artist. I haven't
found a way to vary the number you get back from the query, but you can
paginate through in blocks of 20 songs. | [
"You",
"seem",
"to",
"be",
"able",
"to",
"load",
"20",
"songs",
"at",
"a",
"time",
"for",
"an",
"artist",
".",
"I",
"haven",
"t",
"found",
"a",
"way",
"to",
"vary",
"the",
"number",
"you",
"get",
"back",
"from",
"the",
"query",
"but",
"you",
"can",
"paginate",
"through",
"in",
"blocks",
"of",
"20",
"songs",
"."
] | 6c1c9f4e98828ae12ae2deea2570e30b31d1e6b7 | https://github.com/timrogers/rapgenius/blob/6c1c9f4e98828ae12ae2deea2570e30b31d1e6b7/lib/rapgenius/artist.rb#L40-L54 | train |
LatoTeam/lato_view | lib/lato_view/interface/assets.rb | LatoView.Interface::Assets.view_getApplicationsAssetsItems | def view_getApplicationsAssetsItems
return VIEW_APPASSETS if defined? VIEW_APPASSETS
# inizializzo la lista delle voci della navbar
assets = []
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# estraggo i dati dallo yaml
data = getConfigAssets(config)
# aggiungo i dati nella risposta
data.each do |single_asset|
assets.push(single_asset)
end
end
# ritorno il risultato
return assets
end | ruby | def view_getApplicationsAssetsItems
return VIEW_APPASSETS if defined? VIEW_APPASSETS
# inizializzo la lista delle voci della navbar
assets = []
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# estraggo i dati dallo yaml
data = getConfigAssets(config)
# aggiungo i dati nella risposta
data.each do |single_asset|
assets.push(single_asset)
end
end
# ritorno il risultato
return assets
end | [
"def",
"view_getApplicationsAssetsItems",
"return",
"VIEW_APPASSETS",
"if",
"defined?",
"VIEW_APPASSETS",
"assets",
"=",
"[",
"]",
"directory",
"=",
"core_getCacheDirectory",
"if",
"File",
".",
"exist?",
"\"#{directory}/view.yml\"",
"config",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"\"#{directory}/view.yml\"",
",",
"__FILE__",
")",
")",
")",
"data",
"=",
"getConfigAssets",
"(",
"config",
")",
"data",
".",
"each",
"do",
"|",
"single_asset",
"|",
"assets",
".",
"push",
"(",
"single_asset",
")",
"end",
"end",
"return",
"assets",
"end"
] | This function return an array of url of assets from the main application. | [
"This",
"function",
"return",
"an",
"array",
"of",
"url",
"of",
"assets",
"from",
"the",
"main",
"application",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/assets.rb#L51-L70 | train |
jonahoffline/filepreviews-ruby | lib/filepreviews/http.rb | Filepreviews.HTTP.default_connection | def default_connection(url = BASE_URL, debug = false)
Faraday.new(url: url) do |conn|
conn.adapter :typhoeus
conn.headers[:user_agent] = USER_AGENT
conn.headers[:content_type] = 'application/json'
configure_api_auth_header(conn.headers)
configure_logger(conn) if debug
end
end | ruby | def default_connection(url = BASE_URL, debug = false)
Faraday.new(url: url) do |conn|
conn.adapter :typhoeus
conn.headers[:user_agent] = USER_AGENT
conn.headers[:content_type] = 'application/json'
configure_api_auth_header(conn.headers)
configure_logger(conn) if debug
end
end | [
"def",
"default_connection",
"(",
"url",
"=",
"BASE_URL",
",",
"debug",
"=",
"false",
")",
"Faraday",
".",
"new",
"(",
"url",
":",
"url",
")",
"do",
"|",
"conn",
"|",
"conn",
".",
"adapter",
":typhoeus",
"conn",
".",
"headers",
"[",
":user_agent",
"]",
"=",
"USER_AGENT",
"conn",
".",
"headers",
"[",
":content_type",
"]",
"=",
"'application/json'",
"configure_api_auth_header",
"(",
"conn",
".",
"headers",
")",
"configure_logger",
"(",
"conn",
")",
"if",
"debug",
"end",
"end"
] | Returns custom Typhoeus connection configuration
@param url [String] API url to be used as base
@param debug [Boolean] flag to log responses into STDOUT
@return [Typhoeus::Connection] configured http client for requests to API | [
"Returns",
"custom",
"Typhoeus",
"connection",
"configuration"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/http.rb#L22-L30 | train |
jonahoffline/filepreviews-ruby | lib/filepreviews/http.rb | Filepreviews.HTTP.prepare_request | def prepare_request(params)
request = process_params(params)
request.store(:sizes, [extract_size(params.size)]) if params.size
request.store(:format, params.format) if params.format
request.store(:data, params.data) if params.data
request.store(:uploader, params.uploader) if params.uploader
request.store(:pages, params.pages) if params.pages
request
end | ruby | def prepare_request(params)
request = process_params(params)
request.store(:sizes, [extract_size(params.size)]) if params.size
request.store(:format, params.format) if params.format
request.store(:data, params.data) if params.data
request.store(:uploader, params.uploader) if params.uploader
request.store(:pages, params.pages) if params.pages
request
end | [
"def",
"prepare_request",
"(",
"params",
")",
"request",
"=",
"process_params",
"(",
"params",
")",
"request",
".",
"store",
"(",
":sizes",
",",
"[",
"extract_size",
"(",
"params",
".",
"size",
")",
"]",
")",
"if",
"params",
".",
"size",
"request",
".",
"store",
"(",
":format",
",",
"params",
".",
"format",
")",
"if",
"params",
".",
"format",
"request",
".",
"store",
"(",
":data",
",",
"params",
".",
"data",
")",
"if",
"params",
".",
"data",
"request",
".",
"store",
"(",
":uploader",
",",
"params",
".",
"uploader",
")",
"if",
"params",
".",
"uploader",
"request",
".",
"store",
"(",
":pages",
",",
"params",
".",
"pages",
")",
"if",
"params",
".",
"pages",
"request",
"end"
] | Returns processed metadata, and image attributes params
@param params [Hash<Symbol>] metadata and image attributes
@return [Hash<Symbol>] processed parameters | [
"Returns",
"processed",
"metadata",
"and",
"image",
"attributes",
"params"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/http.rb#L63-L71 | train |
jonahoffline/filepreviews-ruby | lib/filepreviews/http.rb | Filepreviews.HTTP.fetch | def fetch(params, endpoint_path = 'previews')
options = prepare_request(params)
response = default_connection(BASE_URL, params.debug)
.post do |req|
req.url("/v2/#{endpoint_path}/")
req.body = JSON.generate(options)
end
parse(response.body)
end | ruby | def fetch(params, endpoint_path = 'previews')
options = prepare_request(params)
response = default_connection(BASE_URL, params.debug)
.post do |req|
req.url("/v2/#{endpoint_path}/")
req.body = JSON.generate(options)
end
parse(response.body)
end | [
"def",
"fetch",
"(",
"params",
",",
"endpoint_path",
"=",
"'previews'",
")",
"options",
"=",
"prepare_request",
"(",
"params",
")",
"response",
"=",
"default_connection",
"(",
"BASE_URL",
",",
"params",
".",
"debug",
")",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"(",
"\"/v2/#{endpoint_path}/\"",
")",
"req",
".",
"body",
"=",
"JSON",
".",
"generate",
"(",
"options",
")",
"end",
"parse",
"(",
"response",
".",
"body",
")",
"end"
] | Returns parsed response from API
@return [Filepreviews::Response] json response as callable methods | [
"Returns",
"parsed",
"response",
"from",
"API"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/http.rb#L75-L84 | train |
lloeki/ruby-skyjam | lib/skyjam/client.rb | SkyJam.Client.loadalltracks | def loadalltracks
uri = URI(@service_url + 'loadalltracks')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('u' => 0, 'xt' => @cookie)
req['Authorization'] = 'GoogleLogin auth=%s' % @auth
res = http.request(req)
unless res.is_a? Net::HTTPSuccess
fail Error, 'loadalltracks failed: #{res.code}'
end
JSON.parse(res.body)
end | ruby | def loadalltracks
uri = URI(@service_url + 'loadalltracks')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('u' => 0, 'xt' => @cookie)
req['Authorization'] = 'GoogleLogin auth=%s' % @auth
res = http.request(req)
unless res.is_a? Net::HTTPSuccess
fail Error, 'loadalltracks failed: #{res.code}'
end
JSON.parse(res.body)
end | [
"def",
"loadalltracks",
"uri",
"=",
"URI",
"(",
"@service_url",
"+",
"'loadalltracks'",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"true",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
")",
"req",
".",
"set_form_data",
"(",
"'u'",
"=>",
"0",
",",
"'xt'",
"=>",
"@cookie",
")",
"req",
"[",
"'Authorization'",
"]",
"=",
"'GoogleLogin auth=%s'",
"%",
"@auth",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"unless",
"res",
".",
"is_a?",
"Net",
"::",
"HTTPSuccess",
"fail",
"Error",
",",
"'loadalltracks failed: #{res.code}'",
"end",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Web Client API | [
"Web",
"Client",
"API"
] | af435d56303b6a0790d299f4aa627d83c650a8b3 | https://github.com/lloeki/ruby-skyjam/blob/af435d56303b6a0790d299f4aa627d83c650a8b3/lib/skyjam/client.rb#L66-L82 | train |
lloeki/ruby-skyjam | lib/skyjam/client.rb | SkyJam.Client.mac_addr | def mac_addr
case RUBY_PLATFORM
when /darwin/
if (m = `ifconfig en0`.match(/ether (\S{17})/))
m[1].upcase
end
when /linux/
devices = Dir['/sys/class/net/*/address'].reject { |a| a =~ %r{/lo/} }
dev = devices.first
File.read(dev).chomp.upcase
end
end | ruby | def mac_addr
case RUBY_PLATFORM
when /darwin/
if (m = `ifconfig en0`.match(/ether (\S{17})/))
m[1].upcase
end
when /linux/
devices = Dir['/sys/class/net/*/address'].reject { |a| a =~ %r{/lo/} }
dev = devices.first
File.read(dev).chomp.upcase
end
end | [
"def",
"mac_addr",
"case",
"RUBY_PLATFORM",
"when",
"/",
"/",
"if",
"(",
"m",
"=",
"`",
"`",
".",
"match",
"(",
"/",
"\\S",
"/",
")",
")",
"m",
"[",
"1",
"]",
".",
"upcase",
"end",
"when",
"/",
"/",
"devices",
"=",
"Dir",
"[",
"'/sys/class/net/*/address'",
"]",
".",
"reject",
"{",
"|",
"a",
"|",
"a",
"=~",
"%r{",
"}",
"}",
"dev",
"=",
"devices",
".",
"first",
"File",
".",
"read",
"(",
"dev",
")",
".",
"chomp",
".",
"upcase",
"end",
"end"
] | MusicManager Uploader identification | [
"MusicManager",
"Uploader",
"identification"
] | af435d56303b6a0790d299f4aa627d83c650a8b3 | https://github.com/lloeki/ruby-skyjam/blob/af435d56303b6a0790d299f4aa627d83c650a8b3/lib/skyjam/client.rb#L163-L174 | train |
lbeder/rediska | lib/rediska/driver.rb | Rediska.Driver.zscan_each | def zscan_each(key, *args, &block)
data_type_check(key, ZSet)
return [] unless data[key]
return to_enum(:zscan_each, key, options) unless block_given?
cursor = 0
loop do
cursor, values = zscan(key, cursor, options)
values.each(&block)
break if cursor == '0'
end
end | ruby | def zscan_each(key, *args, &block)
data_type_check(key, ZSet)
return [] unless data[key]
return to_enum(:zscan_each, key, options) unless block_given?
cursor = 0
loop do
cursor, values = zscan(key, cursor, options)
values.each(&block)
break if cursor == '0'
end
end | [
"def",
"zscan_each",
"(",
"key",
",",
"*",
"args",
",",
"&",
"block",
")",
"data_type_check",
"(",
"key",
",",
"ZSet",
")",
"return",
"[",
"]",
"unless",
"data",
"[",
"key",
"]",
"return",
"to_enum",
"(",
":zscan_each",
",",
"key",
",",
"options",
")",
"unless",
"block_given?",
"cursor",
"=",
"0",
"loop",
"do",
"cursor",
",",
"values",
"=",
"zscan",
"(",
"key",
",",
"cursor",
",",
"options",
")",
"values",
".",
"each",
"(",
"&",
"block",
")",
"break",
"if",
"cursor",
"==",
"'0'",
"end",
"end"
] | Originally from redis-rb | [
"Originally",
"from",
"redis",
"-",
"rb"
] | b02c1558c4aef0f5bbbac06f1216359dafe6d36c | https://github.com/lbeder/rediska/blob/b02c1558c4aef0f5bbbac06f1216359dafe6d36c/lib/rediska/driver.rb#L1128-L1139 | train |
philou/storexplore | lib/storexplore/walker_page.rb | Storexplore.WalkerPage.get_all | def get_all(selector, separator)
elements = @mechanize_page.search(selector)
throw_if_empty(elements, "elements", selector)
(elements.map &:text).join(separator)
end | ruby | def get_all(selector, separator)
elements = @mechanize_page.search(selector)
throw_if_empty(elements, "elements", selector)
(elements.map &:text).join(separator)
end | [
"def",
"get_all",
"(",
"selector",
",",
"separator",
")",
"elements",
"=",
"@mechanize_page",
".",
"search",
"(",
"selector",
")",
"throw_if_empty",
"(",
"elements",
",",
"\"elements\"",
",",
"selector",
")",
"(",
"elements",
".",
"map",
"&",
":text",
")",
".",
"join",
"(",
"separator",
")",
"end"
] | String with the text of all matching elements, separated by separator. | [
"String",
"with",
"the",
"text",
"of",
"all",
"matching",
"elements",
"separated",
"by",
"separator",
"."
] | 475ff912bb79142a0f5f2ac2092f66c605176af5 | https://github.com/philou/storexplore/blob/475ff912bb79142a0f5f2ac2092f66c605176af5/lib/storexplore/walker_page.rb#L58-L63 | train |
hybridgroup/taskmapper | lib/taskmapper/helper.rb | TaskMapper::Provider.Helper.easy_finder | def easy_finder(api, symbol, options, at_index = 0)
if api.is_a? Class
return api if options.length == 0 and symbol == :first
options.insert(at_index, symbol) if options[at_index].is_a?(Hash)
api.find(*options)
else
raise TaskMapper::Exception.new("#{Helper.name}::#{this_method} method must be implemented by the provider")
end
end | ruby | def easy_finder(api, symbol, options, at_index = 0)
if api.is_a? Class
return api if options.length == 0 and symbol == :first
options.insert(at_index, symbol) if options[at_index].is_a?(Hash)
api.find(*options)
else
raise TaskMapper::Exception.new("#{Helper.name}::#{this_method} method must be implemented by the provider")
end
end | [
"def",
"easy_finder",
"(",
"api",
",",
"symbol",
",",
"options",
",",
"at_index",
"=",
"0",
")",
"if",
"api",
".",
"is_a?",
"Class",
"return",
"api",
"if",
"options",
".",
"length",
"==",
"0",
"and",
"symbol",
"==",
":first",
"options",
".",
"insert",
"(",
"at_index",
",",
"symbol",
")",
"if",
"options",
"[",
"at_index",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"api",
".",
"find",
"(",
"*",
"options",
")",
"else",
"raise",
"TaskMapper",
"::",
"Exception",
".",
"new",
"(",
"\"#{Helper.name}::#{this_method} method must be implemented by the provider\"",
")",
"end",
"end"
] | A helper method for easy finding | [
"A",
"helper",
"method",
"for",
"easy",
"finding"
] | 80af7b43d955e7a9f360fec3b4137e2cd1b418d6 | https://github.com/hybridgroup/taskmapper/blob/80af7b43d955e7a9f360fec3b4137e2cd1b418d6/lib/taskmapper/helper.rb#L13-L21 | train |
hybridgroup/taskmapper | lib/taskmapper/helper.rb | TaskMapper::Provider.Helper.search_by_attribute | def search_by_attribute(things, options = {}, limit = 1000)
things.find_all do |thing|
options.inject(true) do |memo, kv|
break unless memo
key, value = kv
begin
memo &= thing.send(key) == value
rescue NoMethodError
memo = false
end
memo
end and (limit -= 1) > 0
end
end | ruby | def search_by_attribute(things, options = {}, limit = 1000)
things.find_all do |thing|
options.inject(true) do |memo, kv|
break unless memo
key, value = kv
begin
memo &= thing.send(key) == value
rescue NoMethodError
memo = false
end
memo
end and (limit -= 1) > 0
end
end | [
"def",
"search_by_attribute",
"(",
"things",
",",
"options",
"=",
"{",
"}",
",",
"limit",
"=",
"1000",
")",
"things",
".",
"find_all",
"do",
"|",
"thing",
"|",
"options",
".",
"inject",
"(",
"true",
")",
"do",
"|",
"memo",
",",
"kv",
"|",
"break",
"unless",
"memo",
"key",
",",
"value",
"=",
"kv",
"begin",
"memo",
"&=",
"thing",
".",
"send",
"(",
"key",
")",
"==",
"value",
"rescue",
"NoMethodError",
"memo",
"=",
"false",
"end",
"memo",
"end",
"and",
"(",
"limit",
"-=",
"1",
")",
">",
"0",
"end",
"end"
] | Goes through all the things and returns results that match the options attributes hash | [
"Goes",
"through",
"all",
"the",
"things",
"and",
"returns",
"results",
"that",
"match",
"the",
"options",
"attributes",
"hash"
] | 80af7b43d955e7a9f360fec3b4137e2cd1b418d6 | https://github.com/hybridgroup/taskmapper/blob/80af7b43d955e7a9f360fec3b4137e2cd1b418d6/lib/taskmapper/helper.rb#L34-L47 | train |
glebpom/daemonizer | lib/daemonizer/stats.rb | Daemonizer::Stats.MemoryStats.determine_private_dirty_rss | def determine_private_dirty_rss(pid)
total = 0
File.read("/proc/#{pid}/smaps").split("\n").each do |line|
line =~ /^(Private)_Dirty: +(\d+)/
if $2
total += $2.to_i
end
end
if total == 0
return nil
else
return total
end
rescue Errno::EACCES, Errno::ENOENT
return nil
end | ruby | def determine_private_dirty_rss(pid)
total = 0
File.read("/proc/#{pid}/smaps").split("\n").each do |line|
line =~ /^(Private)_Dirty: +(\d+)/
if $2
total += $2.to_i
end
end
if total == 0
return nil
else
return total
end
rescue Errno::EACCES, Errno::ENOENT
return nil
end | [
"def",
"determine_private_dirty_rss",
"(",
"pid",
")",
"total",
"=",
"0",
"File",
".",
"read",
"(",
"\"/proc/#{pid}/smaps\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"each",
"do",
"|",
"line",
"|",
"line",
"=~",
"/",
"\\d",
"/",
"if",
"$2",
"total",
"+=",
"$2",
".",
"to_i",
"end",
"end",
"if",
"total",
"==",
"0",
"return",
"nil",
"else",
"return",
"total",
"end",
"rescue",
"Errno",
"::",
"EACCES",
",",
"Errno",
"::",
"ENOENT",
"return",
"nil",
"end"
] | Returns the private dirty RSS for the given process, in KB. | [
"Returns",
"the",
"private",
"dirty",
"RSS",
"for",
"the",
"given",
"process",
"in",
"KB",
"."
] | 18b5ba213fb7dfb03acd25dac6af20860added57 | https://github.com/glebpom/daemonizer/blob/18b5ba213fb7dfb03acd25dac6af20860added57/lib/daemonizer/stats.rb#L255-L270 | train |
bmuller/ankusa | lib/ankusa/classifier.rb | Ankusa.Classifier.train | def train(klass, text)
th = TextHash.new(text)
th.each { |word, count|
@storage.incr_word_count klass, word, count
yield word, count if block_given?
}
@storage.incr_total_word_count klass, th.word_count
doccount = (text.kind_of? Array) ? text.length : 1
@storage.incr_doc_count klass, doccount
@classnames << klass unless @classnames.include? klass
# cache is now dirty of these vars
@doc_count_totals = nil
@vocab_sizes = nil
th
end | ruby | def train(klass, text)
th = TextHash.new(text)
th.each { |word, count|
@storage.incr_word_count klass, word, count
yield word, count if block_given?
}
@storage.incr_total_word_count klass, th.word_count
doccount = (text.kind_of? Array) ? text.length : 1
@storage.incr_doc_count klass, doccount
@classnames << klass unless @classnames.include? klass
# cache is now dirty of these vars
@doc_count_totals = nil
@vocab_sizes = nil
th
end | [
"def",
"train",
"(",
"klass",
",",
"text",
")",
"th",
"=",
"TextHash",
".",
"new",
"(",
"text",
")",
"th",
".",
"each",
"{",
"|",
"word",
",",
"count",
"|",
"@storage",
".",
"incr_word_count",
"klass",
",",
"word",
",",
"count",
"yield",
"word",
",",
"count",
"if",
"block_given?",
"}",
"@storage",
".",
"incr_total_word_count",
"klass",
",",
"th",
".",
"word_count",
"doccount",
"=",
"(",
"text",
".",
"kind_of?",
"Array",
")",
"?",
"text",
".",
"length",
":",
"1",
"@storage",
".",
"incr_doc_count",
"klass",
",",
"doccount",
"@classnames",
"<<",
"klass",
"unless",
"@classnames",
".",
"include?",
"klass",
"@doc_count_totals",
"=",
"nil",
"@vocab_sizes",
"=",
"nil",
"th",
"end"
] | text can be either an array of strings or a string
klass is a symbol | [
"text",
"can",
"be",
"either",
"an",
"array",
"of",
"strings",
"or",
"a",
"string",
"klass",
"is",
"a",
"symbol"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/classifier.rb#L14-L28 | train |
danielb2/trakt | lib/trakt/show.rb | Trakt.Show.unseen | def unseen(title)
all = seasons title
episodes_per_season = {}
episodes_to_remove = []
all.each do |season_info|
season_num = season_info['season']
next if season_num == 0 # dont need to remove specials
episodes = season_info['episodes']
1.upto(episodes) do |episode|
episodes_to_remove << { season: season_num, episode: episode }
end
end
episode_unseen tvdb_id: title, episodes: episodes_to_remove
end | ruby | def unseen(title)
all = seasons title
episodes_per_season = {}
episodes_to_remove = []
all.each do |season_info|
season_num = season_info['season']
next if season_num == 0 # dont need to remove specials
episodes = season_info['episodes']
1.upto(episodes) do |episode|
episodes_to_remove << { season: season_num, episode: episode }
end
end
episode_unseen tvdb_id: title, episodes: episodes_to_remove
end | [
"def",
"unseen",
"(",
"title",
")",
"all",
"=",
"seasons",
"title",
"episodes_per_season",
"=",
"{",
"}",
"episodes_to_remove",
"=",
"[",
"]",
"all",
".",
"each",
"do",
"|",
"season_info",
"|",
"season_num",
"=",
"season_info",
"[",
"'season'",
"]",
"next",
"if",
"season_num",
"==",
"0",
"episodes",
"=",
"season_info",
"[",
"'episodes'",
"]",
"1",
".",
"upto",
"(",
"episodes",
")",
"do",
"|",
"episode",
"|",
"episodes_to_remove",
"<<",
"{",
"season",
":",
"season_num",
",",
"episode",
":",
"episode",
"}",
"end",
"end",
"episode_unseen",
"tvdb_id",
":",
"title",
",",
"episodes",
":",
"episodes_to_remove",
"end"
] | need to use thetvdb id here since the slug can't be used for unseen | [
"need",
"to",
"use",
"thetvdb",
"id",
"here",
"since",
"the",
"slug",
"can",
"t",
"be",
"used",
"for",
"unseen"
] | e49634903626fb9ad6cf14f2f20a232bc7ecf2f4 | https://github.com/danielb2/trakt/blob/e49634903626fb9ad6cf14f2f20a232bc7ecf2f4/lib/trakt/show.rb#L17-L30 | train |
mbleigh/colorist | lib/colorist/color.rb | Colorist.Color.+ | def +(other_color)
other_color = Colorist::Color.from(other_color)
color = self.dup
color.r += other_color.r
color.g += other_color.g
color.b += other_color.b
color
end | ruby | def +(other_color)
other_color = Colorist::Color.from(other_color)
color = self.dup
color.r += other_color.r
color.g += other_color.g
color.b += other_color.b
color
end | [
"def",
"+",
"(",
"other_color",
")",
"other_color",
"=",
"Colorist",
"::",
"Color",
".",
"from",
"(",
"other_color",
")",
"color",
"=",
"self",
".",
"dup",
"color",
".",
"r",
"+=",
"other_color",
".",
"r",
"color",
".",
"g",
"+=",
"other_color",
".",
"g",
"color",
".",
"b",
"+=",
"other_color",
".",
"b",
"color",
"end"
] | Create a duplicate of this color.
Add the individual RGB values of two colors together. You
may also use an equivalent numeric or string color representation.
Examples:
gray = Colorist::Color.new(0x333333)
gray + "#300" # => <Color #663333>
gray + 0x000000 # => <Color #333333>
white = "white".to_color
gray + white # => <Color #ffffff> | [
"Create",
"a",
"duplicate",
"of",
"this",
"color",
".",
"Add",
"the",
"individual",
"RGB",
"values",
"of",
"two",
"colors",
"together",
".",
"You",
"may",
"also",
"use",
"an",
"equivalent",
"numeric",
"or",
"string",
"color",
"representation",
"."
] | c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927 | https://github.com/mbleigh/colorist/blob/c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927/lib/colorist/color.rb#L285-L292 | train |
mbleigh/colorist | lib/colorist/color.rb | Colorist.Color.to_hsv | def to_hsv
red, green, blue = *[r, g, b].collect {|x| x / 255.0}
max = [red, green, blue].max
min = [red, green, blue].min
if min == max
hue = 0
elsif max == red
hue = 60 * ((green - blue) / (max - min))
elsif max == green
hue = 60 * ((blue - red) / (max - min)) + 120
elsif max == blue
hue = 60 * ((red - green) / (max - min)) + 240
end
saturation = (max == 0) ? 0 : (max - min) / max
[hue % 360, saturation, max]
end | ruby | def to_hsv
red, green, blue = *[r, g, b].collect {|x| x / 255.0}
max = [red, green, blue].max
min = [red, green, blue].min
if min == max
hue = 0
elsif max == red
hue = 60 * ((green - blue) / (max - min))
elsif max == green
hue = 60 * ((blue - red) / (max - min)) + 120
elsif max == blue
hue = 60 * ((red - green) / (max - min)) + 240
end
saturation = (max == 0) ? 0 : (max - min) / max
[hue % 360, saturation, max]
end | [
"def",
"to_hsv",
"red",
",",
"green",
",",
"blue",
"=",
"*",
"[",
"r",
",",
"g",
",",
"b",
"]",
".",
"collect",
"{",
"|",
"x",
"|",
"x",
"/",
"255.0",
"}",
"max",
"=",
"[",
"red",
",",
"green",
",",
"blue",
"]",
".",
"max",
"min",
"=",
"[",
"red",
",",
"green",
",",
"blue",
"]",
".",
"min",
"if",
"min",
"==",
"max",
"hue",
"=",
"0",
"elsif",
"max",
"==",
"red",
"hue",
"=",
"60",
"*",
"(",
"(",
"green",
"-",
"blue",
")",
"/",
"(",
"max",
"-",
"min",
")",
")",
"elsif",
"max",
"==",
"green",
"hue",
"=",
"60",
"*",
"(",
"(",
"blue",
"-",
"red",
")",
"/",
"(",
"max",
"-",
"min",
")",
")",
"+",
"120",
"elsif",
"max",
"==",
"blue",
"hue",
"=",
"60",
"*",
"(",
"(",
"red",
"-",
"green",
")",
"/",
"(",
"max",
"-",
"min",
")",
")",
"+",
"240",
"end",
"saturation",
"=",
"(",
"max",
"==",
"0",
")",
"?",
"0",
":",
"(",
"max",
"-",
"min",
")",
"/",
"max",
"[",
"hue",
"%",
"360",
",",
"saturation",
",",
"max",
"]",
"end"
] | Returns an array of the hue, saturation and value of the color.
Hue will range from 0-359, hue and saturation will be between 0 and 1. | [
"Returns",
"an",
"array",
"of",
"the",
"hue",
"saturation",
"and",
"value",
"of",
"the",
"color",
".",
"Hue",
"will",
"range",
"from",
"0",
"-",
"359",
"hue",
"and",
"saturation",
"will",
"be",
"between",
"0",
"and",
"1",
"."
] | c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927 | https://github.com/mbleigh/colorist/blob/c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927/lib/colorist/color.rb#L362-L379 | train |
mbleigh/colorist | lib/colorist/color.rb | Colorist.Color.gradient_to | def gradient_to(color, steps = 10)
color_to = Colorist::Color.from(color)
red = color_to.r - r
green = color_to.g - g
blue = color_to.b - b
result = (1..(steps - 3)).to_a.collect do |step|
percentage = step.to_f / (steps - 1)
Color.from_rgb(r + (red * percentage), g + (green * percentage), b + (blue * percentage))
end
# Add first and last colors to result, avoiding uneccessary calculation and rounding errors
result.unshift(self.dup)
result.push(color.dup)
result
end | ruby | def gradient_to(color, steps = 10)
color_to = Colorist::Color.from(color)
red = color_to.r - r
green = color_to.g - g
blue = color_to.b - b
result = (1..(steps - 3)).to_a.collect do |step|
percentage = step.to_f / (steps - 1)
Color.from_rgb(r + (red * percentage), g + (green * percentage), b + (blue * percentage))
end
# Add first and last colors to result, avoiding uneccessary calculation and rounding errors
result.unshift(self.dup)
result.push(color.dup)
result
end | [
"def",
"gradient_to",
"(",
"color",
",",
"steps",
"=",
"10",
")",
"color_to",
"=",
"Colorist",
"::",
"Color",
".",
"from",
"(",
"color",
")",
"red",
"=",
"color_to",
".",
"r",
"-",
"r",
"green",
"=",
"color_to",
".",
"g",
"-",
"g",
"blue",
"=",
"color_to",
".",
"b",
"-",
"b",
"result",
"=",
"(",
"1",
"..",
"(",
"steps",
"-",
"3",
")",
")",
".",
"to_a",
".",
"collect",
"do",
"|",
"step",
"|",
"percentage",
"=",
"step",
".",
"to_f",
"/",
"(",
"steps",
"-",
"1",
")",
"Color",
".",
"from_rgb",
"(",
"r",
"+",
"(",
"red",
"*",
"percentage",
")",
",",
"g",
"+",
"(",
"green",
"*",
"percentage",
")",
",",
"b",
"+",
"(",
"blue",
"*",
"percentage",
")",
")",
"end",
"result",
".",
"unshift",
"(",
"self",
".",
"dup",
")",
"result",
".",
"push",
"(",
"color",
".",
"dup",
")",
"result",
"end"
] | Uses a naive formula to generate a gradient between this color and the given color.
Returns the array of colors that make the gradient, including this color and the
target color. By default will return 10 colors, but this can be changed by supplying
an optional steps parameter. | [
"Uses",
"a",
"naive",
"formula",
"to",
"generate",
"a",
"gradient",
"between",
"this",
"color",
"and",
"the",
"given",
"color",
".",
"Returns",
"the",
"array",
"of",
"colors",
"that",
"make",
"the",
"gradient",
"including",
"this",
"color",
"and",
"the",
"target",
"color",
".",
"By",
"default",
"will",
"return",
"10",
"colors",
"but",
"this",
"can",
"be",
"changed",
"by",
"supplying",
"an",
"optional",
"steps",
"parameter",
"."
] | c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927 | https://github.com/mbleigh/colorist/blob/c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927/lib/colorist/color.rb#L423-L439 | train |
adamzaninovich/gematria | lib/gematria/table_manager.rb | Gematria.TableManager.add_table | def add_table(name, table)
if table.is_a? Hash
tables[name.to_sym] = table
else
raise TypeError, 'Invalid table format'
end
end | ruby | def add_table(name, table)
if table.is_a? Hash
tables[name.to_sym] = table
else
raise TypeError, 'Invalid table format'
end
end | [
"def",
"add_table",
"(",
"name",
",",
"table",
")",
"if",
"table",
".",
"is_a?",
"Hash",
"tables",
"[",
"name",
".",
"to_sym",
"]",
"=",
"table",
"else",
"raise",
"TypeError",
",",
"'Invalid table format'",
"end",
"end"
] | Adds a table to the table store. A valid table must be a Hash with single character string keys and numerical values.
A table that is not a Hash will raise a TypeError. The table name will be converted to a Symbol.
@example
Gematria::Tables.add_table :mini_english, 'a' => 1, 'b' => 2, 'c' => 3
@raise [TypeError] if table is not a valid Hash
@param name [#to_sym] table name
@param table [Hash{String => Number}] table of characters pointing to corresponding values
@return [void] | [
"Adds",
"a",
"table",
"to",
"the",
"table",
"store",
".",
"A",
"valid",
"table",
"must",
"be",
"a",
"Hash",
"with",
"single",
"character",
"string",
"keys",
"and",
"numerical",
"values",
".",
"A",
"table",
"that",
"is",
"not",
"a",
"Hash",
"will",
"raise",
"a",
"TypeError",
".",
"The",
"table",
"name",
"will",
"be",
"converted",
"to",
"a",
"Symbol",
"."
] | 962d18ee1699939c483dacb1664267b5ed8540e2 | https://github.com/adamzaninovich/gematria/blob/962d18ee1699939c483dacb1664267b5ed8540e2/lib/gematria/table_manager.rb#L38-L44 | train |
astashov/debugger-xml | lib/debugger/commands/frame.rb | Debugger.FrameFunctions.get_pr_arguments_with_xml | def get_pr_arguments_with_xml(mark, *args)
res = get_pr_arguments_without_xml((!!mark).to_s, *args)
res[:file] = File.expand_path(res[:file])
res
end | ruby | def get_pr_arguments_with_xml(mark, *args)
res = get_pr_arguments_without_xml((!!mark).to_s, *args)
res[:file] = File.expand_path(res[:file])
res
end | [
"def",
"get_pr_arguments_with_xml",
"(",
"mark",
",",
"*",
"args",
")",
"res",
"=",
"get_pr_arguments_without_xml",
"(",
"(",
"!",
"!",
"mark",
")",
".",
"to_s",
",",
"*",
"args",
")",
"res",
"[",
":file",
"]",
"=",
"File",
".",
"expand_path",
"(",
"res",
"[",
":file",
"]",
")",
"res",
"end"
] | Mark should be 'true' or 'false', as a String | [
"Mark",
"should",
"be",
"true",
"or",
"false",
"as",
"a",
"String"
] | 522746dc84fdf72cc089571b6884cac792ce0267 | https://github.com/astashov/debugger-xml/blob/522746dc84fdf72cc089571b6884cac792ce0267/lib/debugger/commands/frame.rb#L5-L9 | train |
mattThousand/sad_panda | lib/sad_panda/emotion.rb | SadPanda.Emotion.call | def call
words = stems_for(remove_stopwords_in(@words))
score_words(frequencies_for(words))
scores.key(scores.values.max)
end | ruby | def call
words = stems_for(remove_stopwords_in(@words))
score_words(frequencies_for(words))
scores.key(scores.values.max)
end | [
"def",
"call",
"words",
"=",
"stems_for",
"(",
"remove_stopwords_in",
"(",
"@words",
")",
")",
"score_words",
"(",
"frequencies_for",
"(",
"words",
")",
")",
"scores",
".",
"key",
"(",
"scores",
".",
"values",
".",
"max",
")",
"end"
] | Main method that initiates scoring emotions | [
"Main",
"method",
"that",
"initiates",
"scoring",
"emotions"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L18-L23 | train |
mattThousand/sad_panda | lib/sad_panda/emotion.rb | SadPanda.Emotion.method_missing | def method_missing(emotion)
return scores[emotion] || 0 if scores.keys.include? emotion
raise NoMethodError, "#{emotion} is not defined"
end | ruby | def method_missing(emotion)
return scores[emotion] || 0 if scores.keys.include? emotion
raise NoMethodError, "#{emotion} is not defined"
end | [
"def",
"method_missing",
"(",
"emotion",
")",
"return",
"scores",
"[",
"emotion",
"]",
"||",
"0",
"if",
"scores",
".",
"keys",
".",
"include?",
"emotion",
"raise",
"NoMethodError",
",",
"\"#{emotion} is not defined\"",
"end"
] | MethodMissing to implement metods that
are the names of each emotion that will returen
the score of that specific emotion for the text | [
"MethodMissing",
"to",
"implement",
"metods",
"that",
"are",
"the",
"names",
"of",
"each",
"emotion",
"that",
"will",
"returen",
"the",
"score",
"of",
"that",
"specific",
"emotion",
"for",
"the",
"text"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L28-L32 | train |
mattThousand/sad_panda | lib/sad_panda/emotion.rb | SadPanda.Emotion.ambiguous_score | def ambiguous_score
unq_scores = scores.values.uniq
scores[:ambiguous] = 1 if unq_scores.length == 1 && unq_scores.first.zero?
end | ruby | def ambiguous_score
unq_scores = scores.values.uniq
scores[:ambiguous] = 1 if unq_scores.length == 1 && unq_scores.first.zero?
end | [
"def",
"ambiguous_score",
"unq_scores",
"=",
"scores",
".",
"values",
".",
"uniq",
"scores",
"[",
":ambiguous",
"]",
"=",
"1",
"if",
"unq_scores",
".",
"length",
"==",
"1",
"&&",
"unq_scores",
".",
"first",
".",
"zero?",
"end"
] | Last part of the scoring process
If all scores are empty ambiguous is scored as 1 | [
"Last",
"part",
"of",
"the",
"scoring",
"process",
"If",
"all",
"scores",
"are",
"empty",
"ambiguous",
"is",
"scored",
"as",
"1"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L38-L41 | train |
mattThousand/sad_panda | lib/sad_panda/emotion.rb | SadPanda.Emotion.score_emotions | def score_emotions(emotion, term, frequency)
return unless SadPanda::Bank::EMOTIONS[emotion].include?(term)
scores[emotion] += frequency
end | ruby | def score_emotions(emotion, term, frequency)
return unless SadPanda::Bank::EMOTIONS[emotion].include?(term)
scores[emotion] += frequency
end | [
"def",
"score_emotions",
"(",
"emotion",
",",
"term",
",",
"frequency",
")",
"return",
"unless",
"SadPanda",
"::",
"Bank",
"::",
"EMOTIONS",
"[",
"emotion",
"]",
".",
"include?",
"(",
"term",
")",
"scores",
"[",
"emotion",
"]",
"+=",
"frequency",
"end"
] | Increments the score of an emotion if the word exist
in that emotion bank | [
"Increments",
"the",
"score",
"of",
"an",
"emotion",
"if",
"the",
"word",
"exist",
"in",
"that",
"emotion",
"bank"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L45-L49 | train |
mattThousand/sad_panda | lib/sad_panda/emotion.rb | SadPanda.Emotion.set_emotions | def set_emotions(word, frequency)
SadPanda::Bank::EMOTIONS.keys.each do |emotion|
score_emotions(emotion, word, frequency)
end
end | ruby | def set_emotions(word, frequency)
SadPanda::Bank::EMOTIONS.keys.each do |emotion|
score_emotions(emotion, word, frequency)
end
end | [
"def",
"set_emotions",
"(",
"word",
",",
"frequency",
")",
"SadPanda",
"::",
"Bank",
"::",
"EMOTIONS",
".",
"keys",
".",
"each",
"do",
"|",
"emotion",
"|",
"score_emotions",
"(",
"emotion",
",",
"word",
",",
"frequency",
")",
"end",
"end"
] | Iterates all emotions for word in text | [
"Iterates",
"all",
"emotions",
"for",
"word",
"in",
"text"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L52-L56 | train |
mattThousand/sad_panda | lib/sad_panda/emotion.rb | SadPanda.Emotion.score_words | def score_words(word_frequencies)
word_frequencies.each do |word, frequency|
set_emotions(word, frequency)
end
score_emoticons
ambiguous_score
end | ruby | def score_words(word_frequencies)
word_frequencies.each do |word, frequency|
set_emotions(word, frequency)
end
score_emoticons
ambiguous_score
end | [
"def",
"score_words",
"(",
"word_frequencies",
")",
"word_frequencies",
".",
"each",
"do",
"|",
"word",
",",
"frequency",
"|",
"set_emotions",
"(",
"word",
",",
"frequency",
")",
"end",
"score_emoticons",
"ambiguous_score",
"end"
] | Logic to score all unique words in the text | [
"Logic",
"to",
"score",
"all",
"unique",
"words",
"in",
"the",
"text"
] | 2ccb1496529d5c5a453d3822fa44b746295f3962 | https://github.com/mattThousand/sad_panda/blob/2ccb1496529d5c5a453d3822fa44b746295f3962/lib/sad_panda/emotion.rb#L68-L76 | train |
jpettersson/autoversion | lib/autoversion/dsl.rb | Autoversion.DSL.parse_file | def parse_file path, matcher
File.open(path) do |f|
f.each do |line|
if m = matcher.call(line)
return m
end
end
end
raise "#{path}: found no matching lines."
end | ruby | def parse_file path, matcher
File.open(path) do |f|
f.each do |line|
if m = matcher.call(line)
return m
end
end
end
raise "#{path}: found no matching lines."
end | [
"def",
"parse_file",
"path",
",",
"matcher",
"File",
".",
"open",
"(",
"path",
")",
"do",
"|",
"f",
"|",
"f",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"m",
"=",
"matcher",
".",
"call",
"(",
"line",
")",
"return",
"m",
"end",
"end",
"end",
"raise",
"\"#{path}: found no matching lines.\"",
"end"
] | Parse the specified file with the provided matcher.
The first returned match will be used as the version. | [
"Parse",
"the",
"specified",
"file",
"with",
"the",
"provided",
"matcher",
"."
] | 15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7 | https://github.com/jpettersson/autoversion/blob/15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7/lib/autoversion/dsl.rb#L30-L40 | train |
jpettersson/autoversion | lib/autoversion/dsl.rb | Autoversion.DSL.update_file | def update_file path, matcher, currentVersion, nextVersion
temp_path = "#{path}.autoversion"
begin
File.open(path) do |source|
File.open(temp_path, 'w') do |target|
source.each do |line|
if matcher.call(line)
target.write line.gsub currentVersion.to_s, nextVersion.to_s
else
target.write line
end
end
end
end
File.rename temp_path, path
ensure
File.unlink temp_path if File.file? temp_path
end
end | ruby | def update_file path, matcher, currentVersion, nextVersion
temp_path = "#{path}.autoversion"
begin
File.open(path) do |source|
File.open(temp_path, 'w') do |target|
source.each do |line|
if matcher.call(line)
target.write line.gsub currentVersion.to_s, nextVersion.to_s
else
target.write line
end
end
end
end
File.rename temp_path, path
ensure
File.unlink temp_path if File.file? temp_path
end
end | [
"def",
"update_file",
"path",
",",
"matcher",
",",
"currentVersion",
",",
"nextVersion",
"temp_path",
"=",
"\"#{path}.autoversion\"",
"begin",
"File",
".",
"open",
"(",
"path",
")",
"do",
"|",
"source",
"|",
"File",
".",
"open",
"(",
"temp_path",
",",
"'w'",
")",
"do",
"|",
"target",
"|",
"source",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"matcher",
".",
"call",
"(",
"line",
")",
"target",
".",
"write",
"line",
".",
"gsub",
"currentVersion",
".",
"to_s",
",",
"nextVersion",
".",
"to_s",
"else",
"target",
".",
"write",
"line",
"end",
"end",
"end",
"end",
"File",
".",
"rename",
"temp_path",
",",
"path",
"ensure",
"File",
".",
"unlink",
"temp_path",
"if",
"File",
".",
"file?",
"temp_path",
"end",
"end"
] | Update a file naively matching the specified matcher and replace any
matching lines with the new version. | [
"Update",
"a",
"file",
"naively",
"matching",
"the",
"specified",
"matcher",
"and",
"replace",
"any",
"matching",
"lines",
"with",
"the",
"new",
"version",
"."
] | 15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7 | https://github.com/jpettersson/autoversion/blob/15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7/lib/autoversion/dsl.rb#L44-L64 | train |
jpettersson/autoversion | lib/autoversion/dsl.rb | Autoversion.DSL.update_files | def update_files paths, matcher, currentVersion, nextVersion
paths.each do |path|
update_file path, matcher, currentVersion, nextVersion
end
end | ruby | def update_files paths, matcher, currentVersion, nextVersion
paths.each do |path|
update_file path, matcher, currentVersion, nextVersion
end
end | [
"def",
"update_files",
"paths",
",",
"matcher",
",",
"currentVersion",
",",
"nextVersion",
"paths",
".",
"each",
"do",
"|",
"path",
"|",
"update_file",
"path",
",",
"matcher",
",",
"currentVersion",
",",
"nextVersion",
"end",
"end"
] | Convenience function for update_file to apply to multiple files. | [
"Convenience",
"function",
"for",
"update_file",
"to",
"apply",
"to",
"multiple",
"files",
"."
] | 15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7 | https://github.com/jpettersson/autoversion/blob/15ec1d15aa25fff90cbd4f3c6e9802fc3f31fcd7/lib/autoversion/dsl.rb#L67-L71 | train |
rightscale/right_link | scripts/bundle_runner.rb | RightScale.BundleRunner.echo | def echo(options)
which = options[:id] ? "with ID #{options[:id].inspect}" : "named #{format_script_name(options[:name])}"
scope = options[:scope] == :all ? "'all' servers" : "a 'single' server"
where = options[:tags] ? "on #{scope} with tags #{options[:tags].inspect}" : "locally on this server"
using = ""
if options[:parameters] && !options[:parameters].empty?
using = " using parameters #{options[:parameters].inspect}"
end
if options[:json]
using += !using.empty? && options[:json_file] ? " and " : " using "
using += "options from JSON file #{options[:json_file].inspect}"
end
if options[:thread]
thread = " on thread #{options[:thread]}"
else
thread = ""
end
if options[:policy]
policy = " auditing on policy #{options[:policy]}"
else
policy = ""
end
puts "Requesting to execute the #{type} #{which} #{where}#{using}#{thread}#{policy}"
true
end | ruby | def echo(options)
which = options[:id] ? "with ID #{options[:id].inspect}" : "named #{format_script_name(options[:name])}"
scope = options[:scope] == :all ? "'all' servers" : "a 'single' server"
where = options[:tags] ? "on #{scope} with tags #{options[:tags].inspect}" : "locally on this server"
using = ""
if options[:parameters] && !options[:parameters].empty?
using = " using parameters #{options[:parameters].inspect}"
end
if options[:json]
using += !using.empty? && options[:json_file] ? " and " : " using "
using += "options from JSON file #{options[:json_file].inspect}"
end
if options[:thread]
thread = " on thread #{options[:thread]}"
else
thread = ""
end
if options[:policy]
policy = " auditing on policy #{options[:policy]}"
else
policy = ""
end
puts "Requesting to execute the #{type} #{which} #{where}#{using}#{thread}#{policy}"
true
end | [
"def",
"echo",
"(",
"options",
")",
"which",
"=",
"options",
"[",
":id",
"]",
"?",
"\"with ID #{options[:id].inspect}\"",
":",
"\"named #{format_script_name(options[:name])}\"",
"scope",
"=",
"options",
"[",
":scope",
"]",
"==",
":all",
"?",
"\"'all' servers\"",
":",
"\"a 'single' server\"",
"where",
"=",
"options",
"[",
":tags",
"]",
"?",
"\"on #{scope} with tags #{options[:tags].inspect}\"",
":",
"\"locally on this server\"",
"using",
"=",
"\"\"",
"if",
"options",
"[",
":parameters",
"]",
"&&",
"!",
"options",
"[",
":parameters",
"]",
".",
"empty?",
"using",
"=",
"\" using parameters #{options[:parameters].inspect}\"",
"end",
"if",
"options",
"[",
":json",
"]",
"using",
"+=",
"!",
"using",
".",
"empty?",
"&&",
"options",
"[",
":json_file",
"]",
"?",
"\" and \"",
":",
"\" using \"",
"using",
"+=",
"\"options from JSON file #{options[:json_file].inspect}\"",
"end",
"if",
"options",
"[",
":thread",
"]",
"thread",
"=",
"\" on thread #{options[:thread]}\"",
"else",
"thread",
"=",
"\"\"",
"end",
"if",
"options",
"[",
":policy",
"]",
"policy",
"=",
"\" auditing on policy #{options[:policy]}\"",
"else",
"policy",
"=",
"\"\"",
"end",
"puts",
"\"Requesting to execute the #{type} #{which} #{where}#{using}#{thread}#{policy}\"",
"true",
"end"
] | Echo what is being requested
=== Parameters
options(Hash):: Options specified
=== Return
true:: Always return true | [
"Echo",
"what",
"is",
"being",
"requested"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/bundle_runner.rb#L105-L131 | train |
rightscale/right_link | scripts/bundle_runner.rb | RightScale.BundleRunner.to_forwarder_options | def to_forwarder_options(options)
result = {}
if options[:tags]
result[:tags] = options[:tags]
result[:selector] = options[:scope]
end
if options[:thread]
result[:thread] = options[:thread]
end
if options[:policy]
result[:policy] = options[:policy]
end
if options[:audit_period]
result[:audit_period] = options[:audit_period].to_s
end
result
end | ruby | def to_forwarder_options(options)
result = {}
if options[:tags]
result[:tags] = options[:tags]
result[:selector] = options[:scope]
end
if options[:thread]
result[:thread] = options[:thread]
end
if options[:policy]
result[:policy] = options[:policy]
end
if options[:audit_period]
result[:audit_period] = options[:audit_period].to_s
end
result
end | [
"def",
"to_forwarder_options",
"(",
"options",
")",
"result",
"=",
"{",
"}",
"if",
"options",
"[",
":tags",
"]",
"result",
"[",
":tags",
"]",
"=",
"options",
"[",
":tags",
"]",
"result",
"[",
":selector",
"]",
"=",
"options",
"[",
":scope",
"]",
"end",
"if",
"options",
"[",
":thread",
"]",
"result",
"[",
":thread",
"]",
"=",
"options",
"[",
":thread",
"]",
"end",
"if",
"options",
"[",
":policy",
"]",
"result",
"[",
":policy",
"]",
"=",
"options",
"[",
":policy",
"]",
"end",
"if",
"options",
"[",
":audit_period",
"]",
"result",
"[",
":audit_period",
"]",
"=",
"options",
"[",
":audit_period",
"]",
".",
"to_s",
"end",
"result",
"end"
] | Map arguments options into forwarder actor compatible options
=== Parameters
options(Hash):: Arguments options
=== Return
result(Hash):: Forwarder actor compatible options hash | [
"Map",
"arguments",
"options",
"into",
"forwarder",
"actor",
"compatible",
"options"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/bundle_runner.rb#L210-L227 | train |
xlucas/ruyml | lib/ruyml.rb | Ruyml.Data.render | def render(template, output = nil)
result = ERB.new(File.read(template), 0, '-').result(binding)
if !output.nil?
File.open(output, "w") do |file|
file.write(result)
end
else
puts result
end
end | ruby | def render(template, output = nil)
result = ERB.new(File.read(template), 0, '-').result(binding)
if !output.nil?
File.open(output, "w") do |file|
file.write(result)
end
else
puts result
end
end | [
"def",
"render",
"(",
"template",
",",
"output",
"=",
"nil",
")",
"result",
"=",
"ERB",
".",
"new",
"(",
"File",
".",
"read",
"(",
"template",
")",
",",
"0",
",",
"'-'",
")",
".",
"result",
"(",
"binding",
")",
"if",
"!",
"output",
".",
"nil?",
"File",
".",
"open",
"(",
"output",
",",
"\"w\"",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"result",
")",
"end",
"else",
"puts",
"result",
"end",
"end"
] | Create RUYML data from a YAML hash.
Underlying hashes will be accessed
as instances of this class. Other
types are kept untouched and returned
as is.
Renders RUYML data using the given template.
Rendered data is either written to an optional
output file path or to stdout. | [
"Create",
"RUYML",
"data",
"from",
"a",
"YAML",
"hash",
".",
"Underlying",
"hashes",
"will",
"be",
"accessed",
"as",
"instances",
"of",
"this",
"class",
".",
"Other",
"types",
"are",
"kept",
"untouched",
"and",
"returned",
"as",
"is",
".",
"Renders",
"RUYML",
"data",
"using",
"the",
"given",
"template",
".",
"Rendered",
"data",
"is",
"either",
"written",
"to",
"an",
"optional",
"output",
"file",
"path",
"or",
"to",
"stdout",
"."
] | 1935cdb62531abf4578082ecd02416f2e67ea760 | https://github.com/xlucas/ruyml/blob/1935cdb62531abf4578082ecd02416f2e67ea760/lib/ruyml.rb#L25-L34 | train |
vinibaggio/outpost | lib/outpost/application.rb | Outpost.Application.add_scout | def add_scout(scout_description, &block)
config = ScoutConfig.new
config.instance_eval(&block)
scout_description.each do |scout, description|
@scouts[scout] << {
:description => description,
:config => config
}
end
end | ruby | def add_scout(scout_description, &block)
config = ScoutConfig.new
config.instance_eval(&block)
scout_description.each do |scout, description|
@scouts[scout] << {
:description => description,
:config => config
}
end
end | [
"def",
"add_scout",
"(",
"scout_description",
",",
"&",
"block",
")",
"config",
"=",
"ScoutConfig",
".",
"new",
"config",
".",
"instance_eval",
"(",
"&",
"block",
")",
"scout_description",
".",
"each",
"do",
"|",
"scout",
",",
"description",
"|",
"@scouts",
"[",
"scout",
"]",
"<<",
"{",
":description",
"=>",
"description",
",",
":config",
"=>",
"config",
"}",
"end",
"end"
] | New instance of a Outpost-based class.
@see Application#using | [
"New",
"instance",
"of",
"a",
"Outpost",
"-",
"based",
"class",
"."
] | 9fc19952e742598d367dde3fd143c3eaa594720b | https://github.com/vinibaggio/outpost/blob/9fc19952e742598d367dde3fd143c3eaa594720b/lib/outpost/application.rb#L113-L123 | train |
vinibaggio/outpost | lib/outpost/application.rb | Outpost.Application.notify | def notify
if reports.any?
@notifiers.each do |notifier, options|
# .dup is NOT reliable
options_copy = Marshal.load(Marshal.dump(options))
notifier.new(options_copy).notify(self)
end
end
end | ruby | def notify
if reports.any?
@notifiers.each do |notifier, options|
# .dup is NOT reliable
options_copy = Marshal.load(Marshal.dump(options))
notifier.new(options_copy).notify(self)
end
end
end | [
"def",
"notify",
"if",
"reports",
".",
"any?",
"@notifiers",
".",
"each",
"do",
"|",
"notifier",
",",
"options",
"|",
"options_copy",
"=",
"Marshal",
".",
"load",
"(",
"Marshal",
".",
"dump",
"(",
"options",
")",
")",
"notifier",
".",
"new",
"(",
"options_copy",
")",
".",
"notify",
"(",
"self",
")",
"end",
"end",
"end"
] | Runs all notifications associated with an Outpost-based class. | [
"Runs",
"all",
"notifications",
"associated",
"with",
"an",
"Outpost",
"-",
"based",
"class",
"."
] | 9fc19952e742598d367dde3fd143c3eaa594720b | https://github.com/vinibaggio/outpost/blob/9fc19952e742598d367dde3fd143c3eaa594720b/lib/outpost/application.rb#L145-L153 | train |
rightscale/right_link | lib/instance/audit_proxy.rb | RightScale.AuditProxy.append_output | def append_output(text)
@mutex.synchronize do
@buffer << RightScale::AuditProxy.force_utf8(text)
end
EM.next_tick do
buffer_size = nil
@mutex.synchronize do
buffer_size = @buffer.size
end
if buffer_size > MAX_AUDIT_SIZE
flush_buffer
else
reset_timer
end
end
end | ruby | def append_output(text)
@mutex.synchronize do
@buffer << RightScale::AuditProxy.force_utf8(text)
end
EM.next_tick do
buffer_size = nil
@mutex.synchronize do
buffer_size = @buffer.size
end
if buffer_size > MAX_AUDIT_SIZE
flush_buffer
else
reset_timer
end
end
end | [
"def",
"append_output",
"(",
"text",
")",
"@mutex",
".",
"synchronize",
"do",
"@buffer",
"<<",
"RightScale",
"::",
"AuditProxy",
".",
"force_utf8",
"(",
"text",
")",
"end",
"EM",
".",
"next_tick",
"do",
"buffer_size",
"=",
"nil",
"@mutex",
".",
"synchronize",
"do",
"buffer_size",
"=",
"@buffer",
".",
"size",
"end",
"if",
"buffer_size",
">",
"MAX_AUDIT_SIZE",
"flush_buffer",
"else",
"reset_timer",
"end",
"end",
"end"
] | Append output to current audit section
=== Parameters
text(String):: Output to append to audit entry
=== Return
true:: Always return true
=== Raise
ApplicationError:: If audit id is missing from passed-in options | [
"Append",
"output",
"to",
"current",
"audit",
"section"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_proxy.rb#L146-L163 | train |
rightscale/right_link | lib/instance/audit_proxy.rb | RightScale.AuditProxy.internal_send_audit | def internal_send_audit(options)
RightScale::AuditProxy.force_utf8!(options[:text])
opts = { :audit_id => @audit_id, :category => options[:category], :offset => @size }
opts[:category] ||= EventCategories::CATEGORY_NOTIFICATION
unless EventCategories::CATEGORIES.include?(opts[:category])
Log.warning("Invalid category '#{opts[:category]}' for notification '#{options[:text]}', using generic category instead")
opts[:category] = EventCategories::CATEGORY_NOTIFICATION
end
log_method = options[:kind] == :error ? :error : :info
log_text = AuditFormatter.send(options[:kind], options[:text])[:detail]
log_text.chomp.split("\n").each { |l| Log.__send__(log_method, l) }
begin
audit = AuditFormatter.__send__(options[:kind], options[:text])
@size += audit[:detail].size
request = RetryableRequest.new("/auditor/update_entry", opts.merge(audit), :timeout => AUDIT_DELIVERY_TIMEOUT)
request.callback { |_| } # No result of interest other than know it was successful
request.errback { |message| Log.error("Failed to send update for audit #{@audit_id} (#{message})") }
request.run
rescue Exception => e
Log.error("Failed to send update for audit #{@audit_id}", e, :trace)
end
true
end | ruby | def internal_send_audit(options)
RightScale::AuditProxy.force_utf8!(options[:text])
opts = { :audit_id => @audit_id, :category => options[:category], :offset => @size }
opts[:category] ||= EventCategories::CATEGORY_NOTIFICATION
unless EventCategories::CATEGORIES.include?(opts[:category])
Log.warning("Invalid category '#{opts[:category]}' for notification '#{options[:text]}', using generic category instead")
opts[:category] = EventCategories::CATEGORY_NOTIFICATION
end
log_method = options[:kind] == :error ? :error : :info
log_text = AuditFormatter.send(options[:kind], options[:text])[:detail]
log_text.chomp.split("\n").each { |l| Log.__send__(log_method, l) }
begin
audit = AuditFormatter.__send__(options[:kind], options[:text])
@size += audit[:detail].size
request = RetryableRequest.new("/auditor/update_entry", opts.merge(audit), :timeout => AUDIT_DELIVERY_TIMEOUT)
request.callback { |_| } # No result of interest other than know it was successful
request.errback { |message| Log.error("Failed to send update for audit #{@audit_id} (#{message})") }
request.run
rescue Exception => e
Log.error("Failed to send update for audit #{@audit_id}", e, :trace)
end
true
end | [
"def",
"internal_send_audit",
"(",
"options",
")",
"RightScale",
"::",
"AuditProxy",
".",
"force_utf8!",
"(",
"options",
"[",
":text",
"]",
")",
"opts",
"=",
"{",
":audit_id",
"=>",
"@audit_id",
",",
":category",
"=>",
"options",
"[",
":category",
"]",
",",
":offset",
"=>",
"@size",
"}",
"opts",
"[",
":category",
"]",
"||=",
"EventCategories",
"::",
"CATEGORY_NOTIFICATION",
"unless",
"EventCategories",
"::",
"CATEGORIES",
".",
"include?",
"(",
"opts",
"[",
":category",
"]",
")",
"Log",
".",
"warning",
"(",
"\"Invalid category '#{opts[:category]}' for notification '#{options[:text]}', using generic category instead\"",
")",
"opts",
"[",
":category",
"]",
"=",
"EventCategories",
"::",
"CATEGORY_NOTIFICATION",
"end",
"log_method",
"=",
"options",
"[",
":kind",
"]",
"==",
":error",
"?",
":error",
":",
":info",
"log_text",
"=",
"AuditFormatter",
".",
"send",
"(",
"options",
"[",
":kind",
"]",
",",
"options",
"[",
":text",
"]",
")",
"[",
":detail",
"]",
"log_text",
".",
"chomp",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"each",
"{",
"|",
"l",
"|",
"Log",
".",
"__send__",
"(",
"log_method",
",",
"l",
")",
"}",
"begin",
"audit",
"=",
"AuditFormatter",
".",
"__send__",
"(",
"options",
"[",
":kind",
"]",
",",
"options",
"[",
":text",
"]",
")",
"@size",
"+=",
"audit",
"[",
":detail",
"]",
".",
"size",
"request",
"=",
"RetryableRequest",
".",
"new",
"(",
"\"/auditor/update_entry\"",
",",
"opts",
".",
"merge",
"(",
"audit",
")",
",",
":timeout",
"=>",
"AUDIT_DELIVERY_TIMEOUT",
")",
"request",
".",
"callback",
"{",
"|",
"_",
"|",
"}",
"request",
".",
"errback",
"{",
"|",
"message",
"|",
"Log",
".",
"error",
"(",
"\"Failed to send update for audit #{@audit_id} (#{message})\"",
")",
"}",
"request",
".",
"run",
"rescue",
"Exception",
"=>",
"e",
"Log",
".",
"error",
"(",
"\"Failed to send update for audit #{@audit_id}\"",
",",
"e",
",",
":trace",
")",
"end",
"true",
"end"
] | Actually send audits to core agent and log failures
=== Parameters
options[:kind](Symbol):: One of :status, :new_section, :info, :error, :output
options[:text](String):: Text to be audited
options[:category](String):: Optional, must be one of RightScale::EventCategories::CATEGORIES
=== Return
true:: Always return true | [
"Actually",
"send",
"audits",
"to",
"core",
"agent",
"and",
"log",
"failures"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_proxy.rb#L217-L241 | train |
rightscale/right_link | lib/instance/audit_proxy.rb | RightScale.AuditProxy.flush_buffer | def flush_buffer
# note we must discard cancelled timer or else we never create a new timer and stay cancelled.
if @timer
@timer.cancel
@timer = nil
end
to_send = nil
@mutex.synchronize do
unless @buffer.empty?
to_send = @buffer
@buffer = ''
end
end
if to_send
internal_send_audit(:kind => :output, :text => to_send, :category => EventCategories::NONE)
end
end | ruby | def flush_buffer
# note we must discard cancelled timer or else we never create a new timer and stay cancelled.
if @timer
@timer.cancel
@timer = nil
end
to_send = nil
@mutex.synchronize do
unless @buffer.empty?
to_send = @buffer
@buffer = ''
end
end
if to_send
internal_send_audit(:kind => :output, :text => to_send, :category => EventCategories::NONE)
end
end | [
"def",
"flush_buffer",
"if",
"@timer",
"@timer",
".",
"cancel",
"@timer",
"=",
"nil",
"end",
"to_send",
"=",
"nil",
"@mutex",
".",
"synchronize",
"do",
"unless",
"@buffer",
".",
"empty?",
"to_send",
"=",
"@buffer",
"@buffer",
"=",
"''",
"end",
"end",
"if",
"to_send",
"internal_send_audit",
"(",
":kind",
"=>",
":output",
",",
":text",
"=>",
"to_send",
",",
":category",
"=>",
"EventCategories",
"::",
"NONE",
")",
"end",
"end"
] | Send any buffered output to auditor
=== Return
Always return true | [
"Send",
"any",
"buffered",
"output",
"to",
"auditor"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/audit_proxy.rb#L247-L265 | train |
ahuth/emcee | lib/emcee/document.rb | Emcee.Document.htmlify_except | def htmlify_except(nodes)
nodes.reduce(to_html) do |output, node|
output.gsub(node.to_html, node.to_xhtml)
end
end | ruby | def htmlify_except(nodes)
nodes.reduce(to_html) do |output, node|
output.gsub(node.to_html, node.to_xhtml)
end
end | [
"def",
"htmlify_except",
"(",
"nodes",
")",
"nodes",
".",
"reduce",
"(",
"to_html",
")",
"do",
"|",
"output",
",",
"node",
"|",
"output",
".",
"gsub",
"(",
"node",
".",
"to_html",
",",
"node",
".",
"to_xhtml",
")",
"end",
"end"
] | Generate an html string for the current document, but replace the provided
nodes with their xhtml strings. | [
"Generate",
"an",
"html",
"string",
"for",
"the",
"current",
"document",
"but",
"replace",
"the",
"provided",
"nodes",
"with",
"their",
"xhtml",
"strings",
"."
] | 0c846c037bffe912cb111ebb973e50c98d034995 | https://github.com/ahuth/emcee/blob/0c846c037bffe912cb111ebb973e50c98d034995/lib/emcee/document.rb#L59-L63 | train |
rightscale/right_link | scripts/reenroller.rb | RightScale.Reenroller.run | def run(options)
check_privileges
AgentConfig.root_dir = AgentConfig.right_link_root_dirs
if RightScale::Platform.windows?
cleanup_certificates(options)
# Write state file to indicate to RightScaleService that it should not
# enter the rebooting state (which is the default behavior when the
# RightScaleService starts).
reenroller_state = {:reenroll => true}
File.open(STATE_FILE, "w") { |f| f.write reenroller_state.to_json }
print 'Restarting RightScale service...' if options[:verbose]
res = system('net start RightScale')
puts to_ok(res) if options[:verbose]
else
print 'Stopping RightLink daemon...' if options[:verbose]
pid_file = AgentConfig.pid_file('instance')
pid = pid_file ? pid_file.read_pid[:pid] : nil
system('/opt/rightscale/bin/rchk --stop')
# Wait for agent process to terminate
retries = 0
while process_running?(pid) && retries < 40
sleep(0.5)
retries += 1
print '.' if options[:verbose]
end
puts to_ok(!process_running?(pid)) if options[:verbose]
# Kill it if it's still alive after ~ 20 sec
if process_running?(pid)
print 'Forcing RightLink daemon to exit...' if options[:verbose]
res = Process.kill('KILL', pid) rescue nil
puts to_ok(res) if options[:verbose]
end
cleanup_certificates(options)
# Resume option bypasses cloud state initialization so that we can
# override the user data
puts((options[:resume] ? 'Resuming' : 'Restarting') + ' RightLink daemon...') if options[:verbose]
action = (options[:resume] ? 'resume' : 'start')
res = system("/etc/init.d/rightlink #{action} > /dev/null")
end
true
end | ruby | def run(options)
check_privileges
AgentConfig.root_dir = AgentConfig.right_link_root_dirs
if RightScale::Platform.windows?
cleanup_certificates(options)
# Write state file to indicate to RightScaleService that it should not
# enter the rebooting state (which is the default behavior when the
# RightScaleService starts).
reenroller_state = {:reenroll => true}
File.open(STATE_FILE, "w") { |f| f.write reenroller_state.to_json }
print 'Restarting RightScale service...' if options[:verbose]
res = system('net start RightScale')
puts to_ok(res) if options[:verbose]
else
print 'Stopping RightLink daemon...' if options[:verbose]
pid_file = AgentConfig.pid_file('instance')
pid = pid_file ? pid_file.read_pid[:pid] : nil
system('/opt/rightscale/bin/rchk --stop')
# Wait for agent process to terminate
retries = 0
while process_running?(pid) && retries < 40
sleep(0.5)
retries += 1
print '.' if options[:verbose]
end
puts to_ok(!process_running?(pid)) if options[:verbose]
# Kill it if it's still alive after ~ 20 sec
if process_running?(pid)
print 'Forcing RightLink daemon to exit...' if options[:verbose]
res = Process.kill('KILL', pid) rescue nil
puts to_ok(res) if options[:verbose]
end
cleanup_certificates(options)
# Resume option bypasses cloud state initialization so that we can
# override the user data
puts((options[:resume] ? 'Resuming' : 'Restarting') + ' RightLink daemon...') if options[:verbose]
action = (options[:resume] ? 'resume' : 'start')
res = system("/etc/init.d/rightlink #{action} > /dev/null")
end
true
end | [
"def",
"run",
"(",
"options",
")",
"check_privileges",
"AgentConfig",
".",
"root_dir",
"=",
"AgentConfig",
".",
"right_link_root_dirs",
"if",
"RightScale",
"::",
"Platform",
".",
"windows?",
"cleanup_certificates",
"(",
"options",
")",
"reenroller_state",
"=",
"{",
":reenroll",
"=>",
"true",
"}",
"File",
".",
"open",
"(",
"STATE_FILE",
",",
"\"w\"",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"reenroller_state",
".",
"to_json",
"}",
"print",
"'Restarting RightScale service...'",
"if",
"options",
"[",
":verbose",
"]",
"res",
"=",
"system",
"(",
"'net start RightScale'",
")",
"puts",
"to_ok",
"(",
"res",
")",
"if",
"options",
"[",
":verbose",
"]",
"else",
"print",
"'Stopping RightLink daemon...'",
"if",
"options",
"[",
":verbose",
"]",
"pid_file",
"=",
"AgentConfig",
".",
"pid_file",
"(",
"'instance'",
")",
"pid",
"=",
"pid_file",
"?",
"pid_file",
".",
"read_pid",
"[",
":pid",
"]",
":",
"nil",
"system",
"(",
"'/opt/rightscale/bin/rchk --stop'",
")",
"retries",
"=",
"0",
"while",
"process_running?",
"(",
"pid",
")",
"&&",
"retries",
"<",
"40",
"sleep",
"(",
"0.5",
")",
"retries",
"+=",
"1",
"print",
"'.'",
"if",
"options",
"[",
":verbose",
"]",
"end",
"puts",
"to_ok",
"(",
"!",
"process_running?",
"(",
"pid",
")",
")",
"if",
"options",
"[",
":verbose",
"]",
"if",
"process_running?",
"(",
"pid",
")",
"print",
"'Forcing RightLink daemon to exit...'",
"if",
"options",
"[",
":verbose",
"]",
"res",
"=",
"Process",
".",
"kill",
"(",
"'KILL'",
",",
"pid",
")",
"rescue",
"nil",
"puts",
"to_ok",
"(",
"res",
")",
"if",
"options",
"[",
":verbose",
"]",
"end",
"cleanup_certificates",
"(",
"options",
")",
"puts",
"(",
"(",
"options",
"[",
":resume",
"]",
"?",
"'Resuming'",
":",
"'Restarting'",
")",
"+",
"' RightLink daemon...'",
")",
"if",
"options",
"[",
":verbose",
"]",
"action",
"=",
"(",
"options",
"[",
":resume",
"]",
"?",
"'resume'",
":",
"'start'",
")",
"res",
"=",
"system",
"(",
"\"/etc/init.d/rightlink #{action} > /dev/null\"",
")",
"end",
"true",
"end"
] | Trigger re-enrollment
=== Return
true:: Always return true | [
"Trigger",
"re",
"-",
"enrollment"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/reenroller.rb#L43-L85 | train |
rightscale/right_link | scripts/reenroller.rb | RightScale.Reenroller.process_running? | def process_running?(pid)
return false unless pid
Process.getpgid(pid) != -1
rescue Errno::ESRCH
false
end | ruby | def process_running?(pid)
return false unless pid
Process.getpgid(pid) != -1
rescue Errno::ESRCH
false
end | [
"def",
"process_running?",
"(",
"pid",
")",
"return",
"false",
"unless",
"pid",
"Process",
".",
"getpgid",
"(",
"pid",
")",
"!=",
"-",
"1",
"rescue",
"Errno",
"::",
"ESRCH",
"false",
"end"
] | Checks whether process with given pid is running
=== Parameters
pid(Fixnum):: Process id to be checked
=== Return
true:: If process is running
false:: Otherwise | [
"Checks",
"whether",
"process",
"with",
"given",
"pid",
"is",
"running"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/reenroller.rb#L143-L148 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.start | def start(options)
begin
setup_traps
@state_serializer = Serializer.new(:json)
# Retrieve instance agent configuration options
@agent = AgentConfig.agent_options('instance')
error("No instance agent configured", nil, abort = true) if @agent.empty?
# Apply agent's ping interval if needed and adjust options to make them consistent
@options = options
unless @options[:time_limit]
if @agent[:ping_interval]
@options[:time_limit] = @agent[:ping_interval] * PING_INTERVAL_MULTIPLIER
else
@options[:time_limit] = DEFAULT_TIME_LIMIT
end
end
@options[:retry_interval] = [@options[:retry_interval], @options[:time_limit]].min
@options[:max_attempts] = [@options[:max_attempts], @options[:time_limit] / @options[:retry_interval]].min
@options[:log_path] ||= RightScale::Platform.filesystem.log_dir
# Attach to log used by instance agent
Log.program_name = 'RightLink'
Log.facility = 'user'
Log.log_to_file_only(@agent[:log_to_file_only])
Log.init(@agent[:identity], @options[:log_path], :print => true)
Log.level = :debug if @options[:verbose]
@logging_enabled = true
# Catch any egregious eventmachine failures, especially failure to connect to agent with CommandIO
# Exit even if running as daemon since no longer can trust EM and should get restarted automatically
EM.error_handler do |e|
if e.class == RuntimeError && e.message =~ /no connection/
error("Failed to connect to agent for communication check", nil, abort = false)
@command_io_failures = (@command_io_failures || 0) + 1
reenroll! if @command_io_failures > @options[:max_attempts]
else
error("Internal checker failure", e, abort = true)
end
end
# note that our Windows service monitors rnac and rchk processes
# externally and restarts them if they die, so no need to roll our
# own cross-monitoring on that platform.
use_agent_watcher = !RightScale::Platform.windows?
EM.run do
check
setup_agent_watcher if use_agent_watcher
end
stop_agent_watcher if use_agent_watcher
rescue SystemExit => e
raise e
rescue Exception => e
error("Failed to run", e, abort = true)
end
true
end | ruby | def start(options)
begin
setup_traps
@state_serializer = Serializer.new(:json)
# Retrieve instance agent configuration options
@agent = AgentConfig.agent_options('instance')
error("No instance agent configured", nil, abort = true) if @agent.empty?
# Apply agent's ping interval if needed and adjust options to make them consistent
@options = options
unless @options[:time_limit]
if @agent[:ping_interval]
@options[:time_limit] = @agent[:ping_interval] * PING_INTERVAL_MULTIPLIER
else
@options[:time_limit] = DEFAULT_TIME_LIMIT
end
end
@options[:retry_interval] = [@options[:retry_interval], @options[:time_limit]].min
@options[:max_attempts] = [@options[:max_attempts], @options[:time_limit] / @options[:retry_interval]].min
@options[:log_path] ||= RightScale::Platform.filesystem.log_dir
# Attach to log used by instance agent
Log.program_name = 'RightLink'
Log.facility = 'user'
Log.log_to_file_only(@agent[:log_to_file_only])
Log.init(@agent[:identity], @options[:log_path], :print => true)
Log.level = :debug if @options[:verbose]
@logging_enabled = true
# Catch any egregious eventmachine failures, especially failure to connect to agent with CommandIO
# Exit even if running as daemon since no longer can trust EM and should get restarted automatically
EM.error_handler do |e|
if e.class == RuntimeError && e.message =~ /no connection/
error("Failed to connect to agent for communication check", nil, abort = false)
@command_io_failures = (@command_io_failures || 0) + 1
reenroll! if @command_io_failures > @options[:max_attempts]
else
error("Internal checker failure", e, abort = true)
end
end
# note that our Windows service monitors rnac and rchk processes
# externally and restarts them if they die, so no need to roll our
# own cross-monitoring on that platform.
use_agent_watcher = !RightScale::Platform.windows?
EM.run do
check
setup_agent_watcher if use_agent_watcher
end
stop_agent_watcher if use_agent_watcher
rescue SystemExit => e
raise e
rescue Exception => e
error("Failed to run", e, abort = true)
end
true
end | [
"def",
"start",
"(",
"options",
")",
"begin",
"setup_traps",
"@state_serializer",
"=",
"Serializer",
".",
"new",
"(",
":json",
")",
"@agent",
"=",
"AgentConfig",
".",
"agent_options",
"(",
"'instance'",
")",
"error",
"(",
"\"No instance agent configured\"",
",",
"nil",
",",
"abort",
"=",
"true",
")",
"if",
"@agent",
".",
"empty?",
"@options",
"=",
"options",
"unless",
"@options",
"[",
":time_limit",
"]",
"if",
"@agent",
"[",
":ping_interval",
"]",
"@options",
"[",
":time_limit",
"]",
"=",
"@agent",
"[",
":ping_interval",
"]",
"*",
"PING_INTERVAL_MULTIPLIER",
"else",
"@options",
"[",
":time_limit",
"]",
"=",
"DEFAULT_TIME_LIMIT",
"end",
"end",
"@options",
"[",
":retry_interval",
"]",
"=",
"[",
"@options",
"[",
":retry_interval",
"]",
",",
"@options",
"[",
":time_limit",
"]",
"]",
".",
"min",
"@options",
"[",
":max_attempts",
"]",
"=",
"[",
"@options",
"[",
":max_attempts",
"]",
",",
"@options",
"[",
":time_limit",
"]",
"/",
"@options",
"[",
":retry_interval",
"]",
"]",
".",
"min",
"@options",
"[",
":log_path",
"]",
"||=",
"RightScale",
"::",
"Platform",
".",
"filesystem",
".",
"log_dir",
"Log",
".",
"program_name",
"=",
"'RightLink'",
"Log",
".",
"facility",
"=",
"'user'",
"Log",
".",
"log_to_file_only",
"(",
"@agent",
"[",
":log_to_file_only",
"]",
")",
"Log",
".",
"init",
"(",
"@agent",
"[",
":identity",
"]",
",",
"@options",
"[",
":log_path",
"]",
",",
":print",
"=>",
"true",
")",
"Log",
".",
"level",
"=",
":debug",
"if",
"@options",
"[",
":verbose",
"]",
"@logging_enabled",
"=",
"true",
"EM",
".",
"error_handler",
"do",
"|",
"e",
"|",
"if",
"e",
".",
"class",
"==",
"RuntimeError",
"&&",
"e",
".",
"message",
"=~",
"/",
"/",
"error",
"(",
"\"Failed to connect to agent for communication check\"",
",",
"nil",
",",
"abort",
"=",
"false",
")",
"@command_io_failures",
"=",
"(",
"@command_io_failures",
"||",
"0",
")",
"+",
"1",
"reenroll!",
"if",
"@command_io_failures",
">",
"@options",
"[",
":max_attempts",
"]",
"else",
"error",
"(",
"\"Internal checker failure\"",
",",
"e",
",",
"abort",
"=",
"true",
")",
"end",
"end",
"use_agent_watcher",
"=",
"!",
"RightScale",
"::",
"Platform",
".",
"windows?",
"EM",
".",
"run",
"do",
"check",
"setup_agent_watcher",
"if",
"use_agent_watcher",
"end",
"stop_agent_watcher",
"if",
"use_agent_watcher",
"rescue",
"SystemExit",
"=>",
"e",
"raise",
"e",
"rescue",
"Exception",
"=>",
"e",
"error",
"(",
"\"Failed to run\"",
",",
"e",
",",
"abort",
"=",
"true",
")",
"end",
"true",
"end"
] | Run daemon or run one agent communication check
If running as a daemon, store pid in same location as agent except suffix the
agent identity with '-rchk'.
=== Parameters
options(Hash):: Run options
:time_limit(Integer):: Time limit for last communication and interval for daemon checks,
defaults to PING_INTERVAL_MULTIPLIER times agent's ping interval or to DEFAULT_TIME_LIMIT
:max_attempts(Integer):: Maximum number of communication check attempts,
defaults to DEFAULT_MAX_ATTEMPTS
:retry_interval(Integer):: Number of seconds to wait before retrying communication check,
defaults to DEFAULT_RETRY_INTERVAL, reset to :time_limit if exceeds it
:daemon(Boolean):: Whether to run as a daemon rather than do a one-time communication check
:log_path(String):: Log file directory, defaults to one used by agent
:stop(Boolean):: Whether to stop the currently running daemon and then exit
:ping(Boolean):: Try communicating now regardless of whether have communicated within
the configured time limit, ignored if :daemon true
:verbose(Boolean):: Whether to display debug information
=== Return
true:: Always return true | [
"Run",
"daemon",
"or",
"run",
"one",
"agent",
"communication",
"check",
"If",
"running",
"as",
"a",
"daemon",
"store",
"pid",
"in",
"same",
"location",
"as",
"agent",
"except",
"suffix",
"the",
"agent",
"identity",
"with",
"-",
"rchk",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L164-L222 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.check | def check
begin
checker_identity = "#{@agent[:identity]}-rchk"
pid_file = PidFile.new(checker_identity, @agent[:pid_dir])
if @options[:stop]
# Stop checker
pid_data = pid_file.read_pid
if pid_data[:pid]
info("Stopping checker daemon")
if RightScale::Platform.windows?
begin
send_command({:name => :terminate}, verbose = @options[:verbose], timeout = 30) do |r|
info(r)
terminate
end
rescue Exception => e
error("Failed stopping checker daemon, confirm it is still running", e, abort = true)
end
else
Process.kill('TERM', pid_data[:pid])
terminate
end
else
terminate
end
elsif @options[:daemon]
# Run checker as daemon
pid_file.check rescue error("Cannot start checker daemon because already running", nil, abort = true)
daemonize(checker_identity, @options) unless RightScale::Platform.windows?
pid_file.write
at_exit { pid_file.remove }
listen_port = CommandConstants::BASE_INSTANCE_AGENT_CHECKER_SOCKET_PORT
@command_runner = CommandRunner.start(listen_port, checker_identity, AgentCheckerCommands.get(self))
info("Checker daemon options:")
log_options = @options.inject([]) { |t, (k, v)| t << "- #{k}: #{v}" }
log_options.each { |l| info(l, to_console = false, no_check = true) }
info("Starting checker daemon with #{elapsed(@options[:time_limit])} polling " +
"and #{elapsed(@options[:time_limit])} last communication limit")
iteration = 0
EM.add_periodic_timer(@options[:time_limit]) do
iteration += 1
debug("Checker iteration #{iteration}")
check_communication(0)
end
else
# Perform one check
check_communication(0, @options[:ping])
end
rescue SystemExit => e
raise e
rescue Exception => e
error("Internal checker failure", e, abort = true)
end
true
end | ruby | def check
begin
checker_identity = "#{@agent[:identity]}-rchk"
pid_file = PidFile.new(checker_identity, @agent[:pid_dir])
if @options[:stop]
# Stop checker
pid_data = pid_file.read_pid
if pid_data[:pid]
info("Stopping checker daemon")
if RightScale::Platform.windows?
begin
send_command({:name => :terminate}, verbose = @options[:verbose], timeout = 30) do |r|
info(r)
terminate
end
rescue Exception => e
error("Failed stopping checker daemon, confirm it is still running", e, abort = true)
end
else
Process.kill('TERM', pid_data[:pid])
terminate
end
else
terminate
end
elsif @options[:daemon]
# Run checker as daemon
pid_file.check rescue error("Cannot start checker daemon because already running", nil, abort = true)
daemonize(checker_identity, @options) unless RightScale::Platform.windows?
pid_file.write
at_exit { pid_file.remove }
listen_port = CommandConstants::BASE_INSTANCE_AGENT_CHECKER_SOCKET_PORT
@command_runner = CommandRunner.start(listen_port, checker_identity, AgentCheckerCommands.get(self))
info("Checker daemon options:")
log_options = @options.inject([]) { |t, (k, v)| t << "- #{k}: #{v}" }
log_options.each { |l| info(l, to_console = false, no_check = true) }
info("Starting checker daemon with #{elapsed(@options[:time_limit])} polling " +
"and #{elapsed(@options[:time_limit])} last communication limit")
iteration = 0
EM.add_periodic_timer(@options[:time_limit]) do
iteration += 1
debug("Checker iteration #{iteration}")
check_communication(0)
end
else
# Perform one check
check_communication(0, @options[:ping])
end
rescue SystemExit => e
raise e
rescue Exception => e
error("Internal checker failure", e, abort = true)
end
true
end | [
"def",
"check",
"begin",
"checker_identity",
"=",
"\"#{@agent[:identity]}-rchk\"",
"pid_file",
"=",
"PidFile",
".",
"new",
"(",
"checker_identity",
",",
"@agent",
"[",
":pid_dir",
"]",
")",
"if",
"@options",
"[",
":stop",
"]",
"pid_data",
"=",
"pid_file",
".",
"read_pid",
"if",
"pid_data",
"[",
":pid",
"]",
"info",
"(",
"\"Stopping checker daemon\"",
")",
"if",
"RightScale",
"::",
"Platform",
".",
"windows?",
"begin",
"send_command",
"(",
"{",
":name",
"=>",
":terminate",
"}",
",",
"verbose",
"=",
"@options",
"[",
":verbose",
"]",
",",
"timeout",
"=",
"30",
")",
"do",
"|",
"r",
"|",
"info",
"(",
"r",
")",
"terminate",
"end",
"rescue",
"Exception",
"=>",
"e",
"error",
"(",
"\"Failed stopping checker daemon, confirm it is still running\"",
",",
"e",
",",
"abort",
"=",
"true",
")",
"end",
"else",
"Process",
".",
"kill",
"(",
"'TERM'",
",",
"pid_data",
"[",
":pid",
"]",
")",
"terminate",
"end",
"else",
"terminate",
"end",
"elsif",
"@options",
"[",
":daemon",
"]",
"pid_file",
".",
"check",
"rescue",
"error",
"(",
"\"Cannot start checker daemon because already running\"",
",",
"nil",
",",
"abort",
"=",
"true",
")",
"daemonize",
"(",
"checker_identity",
",",
"@options",
")",
"unless",
"RightScale",
"::",
"Platform",
".",
"windows?",
"pid_file",
".",
"write",
"at_exit",
"{",
"pid_file",
".",
"remove",
"}",
"listen_port",
"=",
"CommandConstants",
"::",
"BASE_INSTANCE_AGENT_CHECKER_SOCKET_PORT",
"@command_runner",
"=",
"CommandRunner",
".",
"start",
"(",
"listen_port",
",",
"checker_identity",
",",
"AgentCheckerCommands",
".",
"get",
"(",
"self",
")",
")",
"info",
"(",
"\"Checker daemon options:\"",
")",
"log_options",
"=",
"@options",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"t",
",",
"(",
"k",
",",
"v",
")",
"|",
"t",
"<<",
"\"- #{k}: #{v}\"",
"}",
"log_options",
".",
"each",
"{",
"|",
"l",
"|",
"info",
"(",
"l",
",",
"to_console",
"=",
"false",
",",
"no_check",
"=",
"true",
")",
"}",
"info",
"(",
"\"Starting checker daemon with #{elapsed(@options[:time_limit])} polling \"",
"+",
"\"and #{elapsed(@options[:time_limit])} last communication limit\"",
")",
"iteration",
"=",
"0",
"EM",
".",
"add_periodic_timer",
"(",
"@options",
"[",
":time_limit",
"]",
")",
"do",
"iteration",
"+=",
"1",
"debug",
"(",
"\"Checker iteration #{iteration}\"",
")",
"check_communication",
"(",
"0",
")",
"end",
"else",
"check_communication",
"(",
"0",
",",
"@options",
"[",
":ping",
"]",
")",
"end",
"rescue",
"SystemExit",
"=>",
"e",
"raise",
"e",
"rescue",
"Exception",
"=>",
"e",
"error",
"(",
"\"Internal checker failure\"",
",",
"e",
",",
"abort",
"=",
"true",
")",
"end",
"true",
"end"
] | Perform required checks
=== Return
true:: Always return true | [
"Perform",
"required",
"checks"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L269-L328 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.check_communication | def check_communication(attempt, must_try = false)
attempt += 1
begin
if !must_try && (time = time_since_last_communication) < @options[:time_limit]
@retry_timer.cancel if @retry_timer
elapsed = elapsed(time)
info("Passed communication check with activity as recently as #{elapsed} ago", to_console = !@options[:daemon])
terminate unless @options[:daemon]
elsif attempt <= @options[:max_attempts]
debug("Trying communication" + (attempt > 1 ? ", attempt #{attempt}" : ""))
try_communicating(attempt)
@retry_timer = EM::Timer.new(@options[:retry_interval]) do
error("Communication attempt #{attempt} timed out after #{elapsed(@options[:retry_interval])}")
@agent = AgentConfig.agent_options('instance') # Reload in case not using right cookie
check_communication(attempt)
end
else
reenroll!
end
rescue SystemExit => e
raise e
rescue Exception => e
abort = !@options[:daemon] && (attempt > @options[:max_attempts])
error("Failed communication check", e, abort)
check_communication(attempt)
end
true
end | ruby | def check_communication(attempt, must_try = false)
attempt += 1
begin
if !must_try && (time = time_since_last_communication) < @options[:time_limit]
@retry_timer.cancel if @retry_timer
elapsed = elapsed(time)
info("Passed communication check with activity as recently as #{elapsed} ago", to_console = !@options[:daemon])
terminate unless @options[:daemon]
elsif attempt <= @options[:max_attempts]
debug("Trying communication" + (attempt > 1 ? ", attempt #{attempt}" : ""))
try_communicating(attempt)
@retry_timer = EM::Timer.new(@options[:retry_interval]) do
error("Communication attempt #{attempt} timed out after #{elapsed(@options[:retry_interval])}")
@agent = AgentConfig.agent_options('instance') # Reload in case not using right cookie
check_communication(attempt)
end
else
reenroll!
end
rescue SystemExit => e
raise e
rescue Exception => e
abort = !@options[:daemon] && (attempt > @options[:max_attempts])
error("Failed communication check", e, abort)
check_communication(attempt)
end
true
end | [
"def",
"check_communication",
"(",
"attempt",
",",
"must_try",
"=",
"false",
")",
"attempt",
"+=",
"1",
"begin",
"if",
"!",
"must_try",
"&&",
"(",
"time",
"=",
"time_since_last_communication",
")",
"<",
"@options",
"[",
":time_limit",
"]",
"@retry_timer",
".",
"cancel",
"if",
"@retry_timer",
"elapsed",
"=",
"elapsed",
"(",
"time",
")",
"info",
"(",
"\"Passed communication check with activity as recently as #{elapsed} ago\"",
",",
"to_console",
"=",
"!",
"@options",
"[",
":daemon",
"]",
")",
"terminate",
"unless",
"@options",
"[",
":daemon",
"]",
"elsif",
"attempt",
"<=",
"@options",
"[",
":max_attempts",
"]",
"debug",
"(",
"\"Trying communication\"",
"+",
"(",
"attempt",
">",
"1",
"?",
"\", attempt #{attempt}\"",
":",
"\"\"",
")",
")",
"try_communicating",
"(",
"attempt",
")",
"@retry_timer",
"=",
"EM",
"::",
"Timer",
".",
"new",
"(",
"@options",
"[",
":retry_interval",
"]",
")",
"do",
"error",
"(",
"\"Communication attempt #{attempt} timed out after #{elapsed(@options[:retry_interval])}\"",
")",
"@agent",
"=",
"AgentConfig",
".",
"agent_options",
"(",
"'instance'",
")",
"check_communication",
"(",
"attempt",
")",
"end",
"else",
"reenroll!",
"end",
"rescue",
"SystemExit",
"=>",
"e",
"raise",
"e",
"rescue",
"Exception",
"=>",
"e",
"abort",
"=",
"!",
"@options",
"[",
":daemon",
"]",
"&&",
"(",
"attempt",
">",
"@options",
"[",
":max_attempts",
"]",
")",
"error",
"(",
"\"Failed communication check\"",
",",
"e",
",",
"abort",
")",
"check_communication",
"(",
"attempt",
")",
"end",
"true",
"end"
] | Check communication, repeatedly if necessary
=== Parameters
attempt(Integer):: Number of attempts thus far
must_try(Boolean):: Try communicating regardless of whether required based on time limit
=== Return
true:: Always return true | [
"Check",
"communication",
"repeatedly",
"if",
"necessary"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L338-L365 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.time_since_last_communication | def time_since_last_communication
state_file = @options[:state_path] || File.join(AgentConfig.agent_state_dir, 'state.js')
state = @state_serializer.load(File.read(state_file)) if File.file?(state_file)
state.nil? ? (@options[:time_limit] + 1) : (Time.now.to_i - state["last_communication"])
end | ruby | def time_since_last_communication
state_file = @options[:state_path] || File.join(AgentConfig.agent_state_dir, 'state.js')
state = @state_serializer.load(File.read(state_file)) if File.file?(state_file)
state.nil? ? (@options[:time_limit] + 1) : (Time.now.to_i - state["last_communication"])
end | [
"def",
"time_since_last_communication",
"state_file",
"=",
"@options",
"[",
":state_path",
"]",
"||",
"File",
".",
"join",
"(",
"AgentConfig",
".",
"agent_state_dir",
",",
"'state.js'",
")",
"state",
"=",
"@state_serializer",
".",
"load",
"(",
"File",
".",
"read",
"(",
"state_file",
")",
")",
"if",
"File",
".",
"file?",
"(",
"state_file",
")",
"state",
".",
"nil?",
"?",
"(",
"@options",
"[",
":time_limit",
"]",
"+",
"1",
")",
":",
"(",
"Time",
".",
"now",
".",
"to_i",
"-",
"state",
"[",
"\"last_communication\"",
"]",
")",
"end"
] | Get elapsed time since last communication
=== Return
(Integer):: Elapsed time | [
"Get",
"elapsed",
"time",
"since",
"last",
"communication"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L371-L375 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.try_communicating | def try_communicating(attempt)
begin
send_command({:name => "check_connectivity"}, @options[:verbose], COMMAND_IO_TIMEOUT) do |r|
@command_io_failures = 0
res = serialize_operation_result(r) rescue nil
if res && res.success?
info("Successful agent communication" + (attempt > 1 ? " on attempt #{attempt}" : ""))
@retry_timer.cancel if @retry_timer
check_communication(attempt)
else
error = (res && result.content) || "<unknown error>"
error("Failed agent communication attempt", error, abort = false)
# Let existing timer control next attempt
end
end
rescue Exception => e
error("Failed to access agent for communication check", e, abort = false)
end
true
end | ruby | def try_communicating(attempt)
begin
send_command({:name => "check_connectivity"}, @options[:verbose], COMMAND_IO_TIMEOUT) do |r|
@command_io_failures = 0
res = serialize_operation_result(r) rescue nil
if res && res.success?
info("Successful agent communication" + (attempt > 1 ? " on attempt #{attempt}" : ""))
@retry_timer.cancel if @retry_timer
check_communication(attempt)
else
error = (res && result.content) || "<unknown error>"
error("Failed agent communication attempt", error, abort = false)
# Let existing timer control next attempt
end
end
rescue Exception => e
error("Failed to access agent for communication check", e, abort = false)
end
true
end | [
"def",
"try_communicating",
"(",
"attempt",
")",
"begin",
"send_command",
"(",
"{",
":name",
"=>",
"\"check_connectivity\"",
"}",
",",
"@options",
"[",
":verbose",
"]",
",",
"COMMAND_IO_TIMEOUT",
")",
"do",
"|",
"r",
"|",
"@command_io_failures",
"=",
"0",
"res",
"=",
"serialize_operation_result",
"(",
"r",
")",
"rescue",
"nil",
"if",
"res",
"&&",
"res",
".",
"success?",
"info",
"(",
"\"Successful agent communication\"",
"+",
"(",
"attempt",
">",
"1",
"?",
"\" on attempt #{attempt}\"",
":",
"\"\"",
")",
")",
"@retry_timer",
".",
"cancel",
"if",
"@retry_timer",
"check_communication",
"(",
"attempt",
")",
"else",
"error",
"=",
"(",
"res",
"&&",
"result",
".",
"content",
")",
"||",
"\"<unknown error>\"",
"error",
"(",
"\"Failed agent communication attempt\"",
",",
"error",
",",
"abort",
"=",
"false",
")",
"end",
"end",
"rescue",
"Exception",
"=>",
"e",
"error",
"(",
"\"Failed to access agent for communication check\"",
",",
"e",
",",
"abort",
"=",
"false",
")",
"end",
"true",
"end"
] | Ask instance agent to try to communicate
=== Parameters
attempt(Integer):: Number of attempts thus far
=== Return
true:: Always return true | [
"Ask",
"instance",
"agent",
"to",
"try",
"to",
"communicate"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L384-L403 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.reenroll! | def reenroll!
unless @reenrolling
@reenrolling = true
begin
info("Triggering re-enroll after unsuccessful communication check", to_console = true)
cmd = "rs_reenroll"
cmd += " -v" if @options[:verbose]
cmd += '&' unless RightScale::Platform.windows?
# Windows relies on the command protocol to terminate properly.
# If rchk terminates itself, then rchk --stop will hang trying
# to connect to this rchk.
terminate unless RightScale::Platform.windows?
system(cmd)
# Wait around until rs_reenroll has a chance to stop the checker
# otherwise we may restart it
sleep(5)
rescue Exception => e
error("Failed re-enroll after unsuccessful communication check", e, abort = true)
end
@reenrolling = false
end
true
end | ruby | def reenroll!
unless @reenrolling
@reenrolling = true
begin
info("Triggering re-enroll after unsuccessful communication check", to_console = true)
cmd = "rs_reenroll"
cmd += " -v" if @options[:verbose]
cmd += '&' unless RightScale::Platform.windows?
# Windows relies on the command protocol to terminate properly.
# If rchk terminates itself, then rchk --stop will hang trying
# to connect to this rchk.
terminate unless RightScale::Platform.windows?
system(cmd)
# Wait around until rs_reenroll has a chance to stop the checker
# otherwise we may restart it
sleep(5)
rescue Exception => e
error("Failed re-enroll after unsuccessful communication check", e, abort = true)
end
@reenrolling = false
end
true
end | [
"def",
"reenroll!",
"unless",
"@reenrolling",
"@reenrolling",
"=",
"true",
"begin",
"info",
"(",
"\"Triggering re-enroll after unsuccessful communication check\"",
",",
"to_console",
"=",
"true",
")",
"cmd",
"=",
"\"rs_reenroll\"",
"cmd",
"+=",
"\" -v\"",
"if",
"@options",
"[",
":verbose",
"]",
"cmd",
"+=",
"'&'",
"unless",
"RightScale",
"::",
"Platform",
".",
"windows?",
"terminate",
"unless",
"RightScale",
"::",
"Platform",
".",
"windows?",
"system",
"(",
"cmd",
")",
"sleep",
"(",
"5",
")",
"rescue",
"Exception",
"=>",
"e",
"error",
"(",
"\"Failed re-enroll after unsuccessful communication check\"",
",",
"e",
",",
"abort",
"=",
"true",
")",
"end",
"@reenrolling",
"=",
"false",
"end",
"true",
"end"
] | Trigger re-enroll
This will normally cause the checker to exit
=== Return
true:: Always return true | [
"Trigger",
"re",
"-",
"enroll",
"This",
"will",
"normally",
"cause",
"the",
"checker",
"to",
"exit"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L410-L432 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.error | def error(description, error = nil, abort = false)
if @logging_enabled
msg = "[check] #{description}"
msg += ", aborting" if abort
msg = Log.format(msg, error, :trace) if error
Log.error(msg)
end
msg = description
msg += ": #{error}" if error
puts "** #{msg}"
if abort
terminate
exit(1)
end
true
end | ruby | def error(description, error = nil, abort = false)
if @logging_enabled
msg = "[check] #{description}"
msg += ", aborting" if abort
msg = Log.format(msg, error, :trace) if error
Log.error(msg)
end
msg = description
msg += ": #{error}" if error
puts "** #{msg}"
if abort
terminate
exit(1)
end
true
end | [
"def",
"error",
"(",
"description",
",",
"error",
"=",
"nil",
",",
"abort",
"=",
"false",
")",
"if",
"@logging_enabled",
"msg",
"=",
"\"[check] #{description}\"",
"msg",
"+=",
"\", aborting\"",
"if",
"abort",
"msg",
"=",
"Log",
".",
"format",
"(",
"msg",
",",
"error",
",",
":trace",
")",
"if",
"error",
"Log",
".",
"error",
"(",
"msg",
")",
"end",
"msg",
"=",
"description",
"msg",
"+=",
"\": #{error}\"",
"if",
"error",
"puts",
"\"** #{msg}\"",
"if",
"abort",
"terminate",
"exit",
"(",
"1",
")",
"end",
"true",
"end"
] | Handle error by logging message and optionally aborting execution
=== Parameters
description(String):: Description of context where error occurred
error(Exception|String):: Exception or error message
abort(Boolean):: Whether to abort execution
=== Return
true:: If do not abort | [
"Handle",
"error",
"by",
"logging",
"message",
"and",
"optionally",
"aborting",
"execution"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L484-L501 | train |
rightscale/right_link | scripts/agent_checker.rb | RightScale.AgentChecker.elapsed | def elapsed(time)
time = time.to_i
if time <= MINUTE
"#{time} sec"
elsif time <= HOUR
minutes = time / MINUTE
seconds = time - (minutes * MINUTE)
"#{minutes} min #{seconds} sec"
elsif time <= DAY
hours = time / HOUR
minutes = (time - (hours * HOUR)) / MINUTE
"#{hours} hr #{minutes} min"
else
days = time / DAY
hours = (time - (days * DAY)) / HOUR
minutes = (time - (days * DAY) - (hours * HOUR)) / MINUTE
"#{days} day#{days == 1 ? '' : 's'} #{hours} hr #{minutes} min"
end
end | ruby | def elapsed(time)
time = time.to_i
if time <= MINUTE
"#{time} sec"
elsif time <= HOUR
minutes = time / MINUTE
seconds = time - (minutes * MINUTE)
"#{minutes} min #{seconds} sec"
elsif time <= DAY
hours = time / HOUR
minutes = (time - (hours * HOUR)) / MINUTE
"#{hours} hr #{minutes} min"
else
days = time / DAY
hours = (time - (days * DAY)) / HOUR
minutes = (time - (days * DAY) - (hours * HOUR)) / MINUTE
"#{days} day#{days == 1 ? '' : 's'} #{hours} hr #{minutes} min"
end
end | [
"def",
"elapsed",
"(",
"time",
")",
"time",
"=",
"time",
".",
"to_i",
"if",
"time",
"<=",
"MINUTE",
"\"#{time} sec\"",
"elsif",
"time",
"<=",
"HOUR",
"minutes",
"=",
"time",
"/",
"MINUTE",
"seconds",
"=",
"time",
"-",
"(",
"minutes",
"*",
"MINUTE",
")",
"\"#{minutes} min #{seconds} sec\"",
"elsif",
"time",
"<=",
"DAY",
"hours",
"=",
"time",
"/",
"HOUR",
"minutes",
"=",
"(",
"time",
"-",
"(",
"hours",
"*",
"HOUR",
")",
")",
"/",
"MINUTE",
"\"#{hours} hr #{minutes} min\"",
"else",
"days",
"=",
"time",
"/",
"DAY",
"hours",
"=",
"(",
"time",
"-",
"(",
"days",
"*",
"DAY",
")",
")",
"/",
"HOUR",
"minutes",
"=",
"(",
"time",
"-",
"(",
"days",
"*",
"DAY",
")",
"-",
"(",
"hours",
"*",
"HOUR",
")",
")",
"/",
"MINUTE",
"\"#{days} day#{days == 1 ? '' : 's'} #{hours} hr #{minutes} min\"",
"end",
"end"
] | Convert elapsed time in seconds to displayable format
=== Parameters
time(Integer|Float):: Elapsed time
=== Return
(String):: Display string | [
"Convert",
"elapsed",
"time",
"in",
"seconds",
"to",
"displayable",
"format"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/scripts/agent_checker.rb#L510-L528 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.run_recipe_command | def run_recipe_command(opts)
payload = opts[:options] || {}
target = {}
target[:tags] = payload.delete(:tags) if payload[:tags]
target[:scope] = payload.delete(:scope) if payload[:scope]
target[:selector] = payload.delete(:selector) if payload[:selector]
if (target[:tags] && !target[:tags].empty?) || target[:scope] || (target[:selector] == :all)
send_push("/instance_scheduler/execute", opts[:conn], payload, target)
else
run_request("/forwarder/schedule_recipe", opts[:conn], payload)
end
end | ruby | def run_recipe_command(opts)
payload = opts[:options] || {}
target = {}
target[:tags] = payload.delete(:tags) if payload[:tags]
target[:scope] = payload.delete(:scope) if payload[:scope]
target[:selector] = payload.delete(:selector) if payload[:selector]
if (target[:tags] && !target[:tags].empty?) || target[:scope] || (target[:selector] == :all)
send_push("/instance_scheduler/execute", opts[:conn], payload, target)
else
run_request("/forwarder/schedule_recipe", opts[:conn], payload)
end
end | [
"def",
"run_recipe_command",
"(",
"opts",
")",
"payload",
"=",
"opts",
"[",
":options",
"]",
"||",
"{",
"}",
"target",
"=",
"{",
"}",
"target",
"[",
":tags",
"]",
"=",
"payload",
".",
"delete",
"(",
":tags",
")",
"if",
"payload",
"[",
":tags",
"]",
"target",
"[",
":scope",
"]",
"=",
"payload",
".",
"delete",
"(",
":scope",
")",
"if",
"payload",
"[",
":scope",
"]",
"target",
"[",
":selector",
"]",
"=",
"payload",
".",
"delete",
"(",
":selector",
")",
"if",
"payload",
"[",
":selector",
"]",
"if",
"(",
"target",
"[",
":tags",
"]",
"&&",
"!",
"target",
"[",
":tags",
"]",
".",
"empty?",
")",
"||",
"target",
"[",
":scope",
"]",
"||",
"(",
"target",
"[",
":selector",
"]",
"==",
":all",
")",
"send_push",
"(",
"\"/instance_scheduler/execute\"",
",",
"opts",
"[",
":conn",
"]",
",",
"payload",
",",
"target",
")",
"else",
"run_request",
"(",
"\"/forwarder/schedule_recipe\"",
",",
"opts",
"[",
":conn",
"]",
",",
"payload",
")",
"end",
"end"
] | Run recipe command implementation
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:options](Hash):: Pass-through options sent to forwarder or instance_scheduler
with a :tags value indicating tag-based routing instead of local execution
=== Return
true:: Always return true | [
"Run",
"recipe",
"command",
"implementation"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L120-L131 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.run_right_script_command | def run_right_script_command(opts)
payload = opts[:options] || {}
target = {}
target[:tags] = payload.delete(:tags) if payload[:tags]
target[:scope] = payload.delete(:scope) if payload[:scope]
target[:selector] = payload.delete(:selector) if payload[:selector]
if (target[:tags] && !target[:tags].empty?) || target[:scope] || (target[:selector] == :all)
send_push("/instance_scheduler/execute", opts[:conn], payload, target)
else
run_request("/forwarder/schedule_right_script", opts[:conn], payload)
end
end | ruby | def run_right_script_command(opts)
payload = opts[:options] || {}
target = {}
target[:tags] = payload.delete(:tags) if payload[:tags]
target[:scope] = payload.delete(:scope) if payload[:scope]
target[:selector] = payload.delete(:selector) if payload[:selector]
if (target[:tags] && !target[:tags].empty?) || target[:scope] || (target[:selector] == :all)
send_push("/instance_scheduler/execute", opts[:conn], payload, target)
else
run_request("/forwarder/schedule_right_script", opts[:conn], payload)
end
end | [
"def",
"run_right_script_command",
"(",
"opts",
")",
"payload",
"=",
"opts",
"[",
":options",
"]",
"||",
"{",
"}",
"target",
"=",
"{",
"}",
"target",
"[",
":tags",
"]",
"=",
"payload",
".",
"delete",
"(",
":tags",
")",
"if",
"payload",
"[",
":tags",
"]",
"target",
"[",
":scope",
"]",
"=",
"payload",
".",
"delete",
"(",
":scope",
")",
"if",
"payload",
"[",
":scope",
"]",
"target",
"[",
":selector",
"]",
"=",
"payload",
".",
"delete",
"(",
":selector",
")",
"if",
"payload",
"[",
":selector",
"]",
"if",
"(",
"target",
"[",
":tags",
"]",
"&&",
"!",
"target",
"[",
":tags",
"]",
".",
"empty?",
")",
"||",
"target",
"[",
":scope",
"]",
"||",
"(",
"target",
"[",
":selector",
"]",
"==",
":all",
")",
"send_push",
"(",
"\"/instance_scheduler/execute\"",
",",
"opts",
"[",
":conn",
"]",
",",
"payload",
",",
"target",
")",
"else",
"run_request",
"(",
"\"/forwarder/schedule_right_script\"",
",",
"opts",
"[",
":conn",
"]",
",",
"payload",
")",
"end",
"end"
] | Run RightScript command implementation
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:options](Hash):: Pass-through options sent to forwarder or instance_scheduler
with a :tags value indicating tag-based routing instead of local execution
=== Return
true:: Always return true | [
"Run",
"RightScript",
"command",
"implementation"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L142-L153 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.send_retryable_request_command | def send_retryable_request_command(opts)
options = opts[:options]
options[:timeout] ||= opts[:timeout]
send_retryable_request(opts[:type], opts[:conn], opts[:payload], options)
end | ruby | def send_retryable_request_command(opts)
options = opts[:options]
options[:timeout] ||= opts[:timeout]
send_retryable_request(opts[:type], opts[:conn], opts[:payload], options)
end | [
"def",
"send_retryable_request_command",
"(",
"opts",
")",
"options",
"=",
"opts",
"[",
":options",
"]",
"options",
"[",
":timeout",
"]",
"||=",
"opts",
"[",
":timeout",
"]",
"send_retryable_request",
"(",
"opts",
"[",
":type",
"]",
",",
"opts",
"[",
":conn",
"]",
",",
"opts",
"[",
":payload",
"]",
",",
"options",
")",
"end"
] | Send a retryable request to a single target with a response expected, retrying multiple times
at the application layer in case failures or errors occur.
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:type](String):: Request type
opts[:payload](String):: Request data, optional
opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout
opts[:options](Hash):: Request options
=== Return
true:: Always return true | [
"Send",
"a",
"retryable",
"request",
"to",
"a",
"single",
"target",
"with",
"a",
"response",
"expected",
"retrying",
"multiple",
"times",
"at",
"the",
"application",
"layer",
"in",
"case",
"failures",
"or",
"errors",
"occur",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L197-L201 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.get_instance_state_agent_command | def get_instance_state_agent_command(opts)
result = RightScale::InstanceState.value
CommandIO.instance.reply(opts[:conn], JSON.dump({ :result => result }) )
rescue Exception => e
CommandIO.instance.reply(opts[:conn], JSON.dump({ :error => e.message }) )
end | ruby | def get_instance_state_agent_command(opts)
result = RightScale::InstanceState.value
CommandIO.instance.reply(opts[:conn], JSON.dump({ :result => result }) )
rescue Exception => e
CommandIO.instance.reply(opts[:conn], JSON.dump({ :error => e.message }) )
end | [
"def",
"get_instance_state_agent_command",
"(",
"opts",
")",
"result",
"=",
"RightScale",
"::",
"InstanceState",
".",
"value",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"JSON",
".",
"dump",
"(",
"{",
":result",
"=>",
"result",
"}",
")",
")",
"rescue",
"Exception",
"=>",
"e",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"JSON",
".",
"dump",
"(",
"{",
":error",
"=>",
"e",
".",
"message",
"}",
")",
")",
"end"
] | Get Instance State value for Agent type
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
=== Return
true:: Always return true | [
"Get",
"Instance",
"State",
"value",
"for",
"Agent",
"type"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L234-L239 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.get_instance_state_run_command | def get_instance_state_run_command(opts)
value = RightScale::InstanceState.value
result = case value
when 'booting'
"booting#{InstanceState.reboot? ? ':reboot' : ''}"
when 'operational', 'stranded'
value
when 'decommissioning', 'decommissioned'
decom_reason = "unknown"
decom_reason = InstanceState.decommission_type if ShutdownRequest::LEVELS.include?(InstanceState.decommission_type)
"shutting-down:#{decom_reason}"
end
CommandIO.instance.reply(opts[:conn], JSON.dump({ :result => result }) )
rescue Exception => e
CommandIO.instance.reply(opts[:conn], JSON.dump({ :error => e.message }) )
end | ruby | def get_instance_state_run_command(opts)
value = RightScale::InstanceState.value
result = case value
when 'booting'
"booting#{InstanceState.reboot? ? ':reboot' : ''}"
when 'operational', 'stranded'
value
when 'decommissioning', 'decommissioned'
decom_reason = "unknown"
decom_reason = InstanceState.decommission_type if ShutdownRequest::LEVELS.include?(InstanceState.decommission_type)
"shutting-down:#{decom_reason}"
end
CommandIO.instance.reply(opts[:conn], JSON.dump({ :result => result }) )
rescue Exception => e
CommandIO.instance.reply(opts[:conn], JSON.dump({ :error => e.message }) )
end | [
"def",
"get_instance_state_run_command",
"(",
"opts",
")",
"value",
"=",
"RightScale",
"::",
"InstanceState",
".",
"value",
"result",
"=",
"case",
"value",
"when",
"'booting'",
"\"booting#{InstanceState.reboot? ? ':reboot' : ''}\"",
"when",
"'operational'",
",",
"'stranded'",
"value",
"when",
"'decommissioning'",
",",
"'decommissioned'",
"decom_reason",
"=",
"\"unknown\"",
"decom_reason",
"=",
"InstanceState",
".",
"decommission_type",
"if",
"ShutdownRequest",
"::",
"LEVELS",
".",
"include?",
"(",
"InstanceState",
".",
"decommission_type",
")",
"\"shutting-down:#{decom_reason}\"",
"end",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"JSON",
".",
"dump",
"(",
"{",
":result",
"=>",
"result",
"}",
")",
")",
"rescue",
"Exception",
"=>",
"e",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"JSON",
".",
"dump",
"(",
"{",
":error",
"=>",
"e",
".",
"message",
"}",
")",
")",
"end"
] | Get Instance State value for Run type
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
=== Return
true:: Always return true | [
"Get",
"Instance",
"State",
"value",
"for",
"Run",
"type"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L248-L263 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.get_tags_command | def get_tags_command(opts)
AgentTagManager.instance.tags(opts) { |tags| CommandIO.instance.reply(opts[:conn], tags) }
end | ruby | def get_tags_command(opts)
AgentTagManager.instance.tags(opts) { |tags| CommandIO.instance.reply(opts[:conn], tags) }
end | [
"def",
"get_tags_command",
"(",
"opts",
")",
"AgentTagManager",
".",
"instance",
".",
"tags",
"(",
"opts",
")",
"{",
"|",
"tags",
"|",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"tags",
")",
"}",
"end"
] | Get tags command
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout
=== Return
true:: Always return true | [
"Get",
"tags",
"command"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L298-L300 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.add_tag_command | def add_tag_command(opts)
AgentTagManager.instance.add_tags(opts[:tag], opts) do |raw_response|
reply = @serializer.dump(raw_response) rescue raw_response
CommandIO.instance.reply(opts[:conn], reply)
end
end | ruby | def add_tag_command(opts)
AgentTagManager.instance.add_tags(opts[:tag], opts) do |raw_response|
reply = @serializer.dump(raw_response) rescue raw_response
CommandIO.instance.reply(opts[:conn], reply)
end
end | [
"def",
"add_tag_command",
"(",
"opts",
")",
"AgentTagManager",
".",
"instance",
".",
"add_tags",
"(",
"opts",
"[",
":tag",
"]",
",",
"opts",
")",
"do",
"|",
"raw_response",
"|",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"raw_response",
")",
"rescue",
"raw_response",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"reply",
")",
"end",
"end"
] | Add given tag
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:tag](String):: Tag to be added
opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout
=== Return
true:: Always return true | [
"Add",
"given",
"tag"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L311-L316 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.remove_tag_command | def remove_tag_command(opts)
AgentTagManager.instance.remove_tags(opts[:tag], opts) do |raw_response|
reply = @serializer.dump(raw_response) rescue raw_response
CommandIO.instance.reply(opts[:conn], reply)
end
end | ruby | def remove_tag_command(opts)
AgentTagManager.instance.remove_tags(opts[:tag], opts) do |raw_response|
reply = @serializer.dump(raw_response) rescue raw_response
CommandIO.instance.reply(opts[:conn], reply)
end
end | [
"def",
"remove_tag_command",
"(",
"opts",
")",
"AgentTagManager",
".",
"instance",
".",
"remove_tags",
"(",
"opts",
"[",
":tag",
"]",
",",
"opts",
")",
"do",
"|",
"raw_response",
"|",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"raw_response",
")",
"rescue",
"raw_response",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"reply",
")",
"end",
"end"
] | Remove given tag
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:tag](String):: Tag to be removed
opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout
=== Return
true:: Always return true | [
"Remove",
"given",
"tag"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L327-L332 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.query_tags_command | def query_tags_command(opts)
AgentTagManager.instance.query_tags_raw(opts[:tags], opts[:hrefs], opts) do |raw_response|
reply = @serializer.dump(raw_response) rescue raw_response
CommandIO.instance.reply(opts[:conn], reply)
end
end | ruby | def query_tags_command(opts)
AgentTagManager.instance.query_tags_raw(opts[:tags], opts[:hrefs], opts) do |raw_response|
reply = @serializer.dump(raw_response) rescue raw_response
CommandIO.instance.reply(opts[:conn], reply)
end
end | [
"def",
"query_tags_command",
"(",
"opts",
")",
"AgentTagManager",
".",
"instance",
".",
"query_tags_raw",
"(",
"opts",
"[",
":tags",
"]",
",",
"opts",
"[",
":hrefs",
"]",
",",
"opts",
")",
"do",
"|",
"raw_response",
"|",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"raw_response",
")",
"rescue",
"raw_response",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"reply",
")",
"end",
"end"
] | Query for instances with given tags
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:tags](String):: Tags to be used in query
opts[:timeout](Integer):: Timeout for retryable request, -1 or nil for no timeout
=== Return
true:: Always return true | [
"Query",
"for",
"instances",
"with",
"given",
"tags"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L343-L348 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.audit_create_entry_command | def audit_create_entry_command(opts)
payload = {
:agent_identity => @agent_identity,
:summary => opts[:summary],
:category => opts[:category] || RightScale::EventCategories::NONE,
:user_email => opts[:user_email],
:detail => opts[:detail]
}
send_push('/auditor/create_entry', opts[:conn], payload)
end | ruby | def audit_create_entry_command(opts)
payload = {
:agent_identity => @agent_identity,
:summary => opts[:summary],
:category => opts[:category] || RightScale::EventCategories::NONE,
:user_email => opts[:user_email],
:detail => opts[:detail]
}
send_push('/auditor/create_entry', opts[:conn], payload)
end | [
"def",
"audit_create_entry_command",
"(",
"opts",
")",
"payload",
"=",
"{",
":agent_identity",
"=>",
"@agent_identity",
",",
":summary",
"=>",
"opts",
"[",
":summary",
"]",
",",
":category",
"=>",
"opts",
"[",
":category",
"]",
"||",
"RightScale",
"::",
"EventCategories",
"::",
"NONE",
",",
":user_email",
"=>",
"opts",
"[",
":user_email",
"]",
",",
":detail",
"=>",
"opts",
"[",
":detail",
"]",
"}",
"send_push",
"(",
"'/auditor/create_entry'",
",",
"opts",
"[",
":conn",
"]",
",",
"payload",
")",
"end"
] | Create an audit entry.
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:summary](String):: Initial audit summary; must be present in order to avoid a blank summary!
opts[:category](String):: One of the categories enumerated by RightScale::EventCategories
opts[:user_email](String):: Optional; email of user who caused the audit event
=== Return
result(RightScale::OperationResult):: result; if successful, payload == an integer audit ID | [
"Create",
"an",
"audit",
"entry",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L360-L370 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.audit_update_status_command | def audit_update_status_command(opts)
AuditCookStub.instance.forward_audit(:update_status, opts[:content], opts[:thread_name], opts[:options])
CommandIO.instance.reply(opts[:conn], 'OK', close_after_writing=false)
end | ruby | def audit_update_status_command(opts)
AuditCookStub.instance.forward_audit(:update_status, opts[:content], opts[:thread_name], opts[:options])
CommandIO.instance.reply(opts[:conn], 'OK', close_after_writing=false)
end | [
"def",
"audit_update_status_command",
"(",
"opts",
")",
"AuditCookStub",
".",
"instance",
".",
"forward_audit",
"(",
":update_status",
",",
"opts",
"[",
":content",
"]",
",",
"opts",
"[",
":thread_name",
"]",
",",
"opts",
"[",
":options",
"]",
")",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"'OK'",
",",
"close_after_writing",
"=",
"false",
")",
"end"
] | Update audit summary
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:title](Hash):: Chef attributes hash
=== Return
true:: Always return true | [
"Update",
"audit",
"summary"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L380-L383 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.set_inputs_patch_command | def set_inputs_patch_command(opts)
payload = {:agent_identity => @agent_identity, :patch => opts[:patch]}
send_push("/updater/update_inputs", opts[:conn], payload)
CommandIO.instance.reply(opts[:conn], 'OK')
end | ruby | def set_inputs_patch_command(opts)
payload = {:agent_identity => @agent_identity, :patch => opts[:patch]}
send_push("/updater/update_inputs", opts[:conn], payload)
CommandIO.instance.reply(opts[:conn], 'OK')
end | [
"def",
"set_inputs_patch_command",
"(",
"opts",
")",
"payload",
"=",
"{",
":agent_identity",
"=>",
"@agent_identity",
",",
":patch",
"=>",
"opts",
"[",
":patch",
"]",
"}",
"send_push",
"(",
"\"/updater/update_inputs\"",
",",
"opts",
"[",
":conn",
"]",
",",
"payload",
")",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"'OK'",
")",
"end"
] | Update inputs patch to be sent back to core after cook process finishes
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:patch](Hash):: Patch to be forwarded to core
=== Return
true:: Always return true | [
"Update",
"inputs",
"patch",
"to",
"be",
"sent",
"back",
"to",
"core",
"after",
"cook",
"process",
"finishes"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L445-L449 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.send_push | def send_push(type, conn, payload = nil, target = nil, options = {})
payload ||= {}
payload[:agent_identity] = @agent_identity
Sender.instance.send_push(type, payload, target, options)
CommandIO.instance.reply(conn, 'OK')
true
end | ruby | def send_push(type, conn, payload = nil, target = nil, options = {})
payload ||= {}
payload[:agent_identity] = @agent_identity
Sender.instance.send_push(type, payload, target, options)
CommandIO.instance.reply(conn, 'OK')
true
end | [
"def",
"send_push",
"(",
"type",
",",
"conn",
",",
"payload",
"=",
"nil",
",",
"target",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"payload",
"||=",
"{",
"}",
"payload",
"[",
":agent_identity",
"]",
"=",
"@agent_identity",
"Sender",
".",
"instance",
".",
"send_push",
"(",
"type",
",",
"payload",
",",
"target",
",",
"options",
")",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"conn",
",",
"'OK'",
")",
"true",
"end"
] | Helper method to send a request to one or more targets with no response expected
See Sender for details | [
"Helper",
"method",
"to",
"send",
"a",
"request",
"to",
"one",
"or",
"more",
"targets",
"with",
"no",
"response",
"expected",
"See",
"Sender",
"for",
"details"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L468-L474 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.send_request | def send_request(type, conn, payload = nil, target = nil, options = {})
payload ||= {}
payload[:agent_identity] = @agent_identity
Sender.instance.send_request(type, payload, target, options) do |r|
reply = @serializer.dump(r) rescue '\"Failed to serialize response\"'
CommandIO.instance.reply(conn, reply)
end
true
end | ruby | def send_request(type, conn, payload = nil, target = nil, options = {})
payload ||= {}
payload[:agent_identity] = @agent_identity
Sender.instance.send_request(type, payload, target, options) do |r|
reply = @serializer.dump(r) rescue '\"Failed to serialize response\"'
CommandIO.instance.reply(conn, reply)
end
true
end | [
"def",
"send_request",
"(",
"type",
",",
"conn",
",",
"payload",
"=",
"nil",
",",
"target",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"payload",
"||=",
"{",
"}",
"payload",
"[",
":agent_identity",
"]",
"=",
"@agent_identity",
"Sender",
".",
"instance",
".",
"send_request",
"(",
"type",
",",
"payload",
",",
"target",
",",
"options",
")",
"do",
"|",
"r",
"|",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"r",
")",
"rescue",
"'\\\"Failed to serialize response\\\"'",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"conn",
",",
"reply",
")",
"end",
"true",
"end"
] | Helper method to send a request to a single target agent with a response expected
The request is retried if the response is not received in a reasonable amount of time
The request is timed out if not received in time, typically configured to 2 minutes
The request is allowed to expire per the agent's configured time-to-live, typically 1 minute
See Sender for details | [
"Helper",
"method",
"to",
"send",
"a",
"request",
"to",
"a",
"single",
"target",
"agent",
"with",
"a",
"response",
"expected",
"The",
"request",
"is",
"retried",
"if",
"the",
"response",
"is",
"not",
"received",
"in",
"a",
"reasonable",
"amount",
"of",
"time",
"The",
"request",
"is",
"timed",
"out",
"if",
"not",
"received",
"in",
"time",
"typically",
"configured",
"to",
"2",
"minutes",
"The",
"request",
"is",
"allowed",
"to",
"expire",
"per",
"the",
"agent",
"s",
"configured",
"time",
"-",
"to",
"-",
"live",
"typically",
"1",
"minute",
"See",
"Sender",
"for",
"details"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L481-L489 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.send_retryable_request | def send_retryable_request(type, conn, payload = nil, opts = {})
req = RetryableRequest.new(type, payload, opts)
callback = Proc.new do |content|
result = OperationResult.success(content)
reply = @serializer.dump(result) rescue '\"Failed to serialize response\"'
CommandIO.instance.reply(conn, reply)
end
errback = Proc.new do |content|
result = OperationResult.error(content)
reply = @serializer.dump(result) rescue '\"Failed to serialize response\"'
CommandIO.instance.reply(conn, reply)
end
req.callback(&callback)
req.errback(&errback)
req.run
end | ruby | def send_retryable_request(type, conn, payload = nil, opts = {})
req = RetryableRequest.new(type, payload, opts)
callback = Proc.new do |content|
result = OperationResult.success(content)
reply = @serializer.dump(result) rescue '\"Failed to serialize response\"'
CommandIO.instance.reply(conn, reply)
end
errback = Proc.new do |content|
result = OperationResult.error(content)
reply = @serializer.dump(result) rescue '\"Failed to serialize response\"'
CommandIO.instance.reply(conn, reply)
end
req.callback(&callback)
req.errback(&errback)
req.run
end | [
"def",
"send_retryable_request",
"(",
"type",
",",
"conn",
",",
"payload",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
")",
"req",
"=",
"RetryableRequest",
".",
"new",
"(",
"type",
",",
"payload",
",",
"opts",
")",
"callback",
"=",
"Proc",
".",
"new",
"do",
"|",
"content",
"|",
"result",
"=",
"OperationResult",
".",
"success",
"(",
"content",
")",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"result",
")",
"rescue",
"'\\\"Failed to serialize response\\\"'",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"conn",
",",
"reply",
")",
"end",
"errback",
"=",
"Proc",
".",
"new",
"do",
"|",
"content",
"|",
"result",
"=",
"OperationResult",
".",
"error",
"(",
"content",
")",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"result",
")",
"rescue",
"'\\\"Failed to serialize response\\\"'",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"conn",
",",
"reply",
")",
"end",
"req",
".",
"callback",
"(",
"&",
"callback",
")",
"req",
".",
"errback",
"(",
"&",
"errback",
")",
"req",
".",
"run",
"end"
] | Helper method to send a retryable request to a single target with a response expected,
retrying at the application layer until the request succeeds or the timeout elapses;
default timeout is 'forever'.
See RetryableRequest for details | [
"Helper",
"method",
"to",
"send",
"a",
"retryable",
"request",
"to",
"a",
"single",
"target",
"with",
"a",
"response",
"expected",
"retrying",
"at",
"the",
"application",
"layer",
"until",
"the",
"request",
"succeeds",
"or",
"the",
"timeout",
"elapses",
";",
"default",
"timeout",
"is",
"forever",
"."
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L496-L514 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.run_request | def run_request(type, conn, payload)
payload ||= {}
payload[:agent_identity] = @agent_identity
Sender.instance.send_request(type, payload) do |r|
r = OperationResult.from_results(r)
if r && r.success? && r.content.is_a?(RightScale::ExecutableBundle)
@scheduler.schedule_bundle(:bundle => r.content)
reply = @serializer.dump(OperationResult.success)
else
reply = @serializer.dump(r) rescue '\"Failed to serialize response\"'
end
CommandIO.instance.reply(conn, reply)
end
true
end | ruby | def run_request(type, conn, payload)
payload ||= {}
payload[:agent_identity] = @agent_identity
Sender.instance.send_request(type, payload) do |r|
r = OperationResult.from_results(r)
if r && r.success? && r.content.is_a?(RightScale::ExecutableBundle)
@scheduler.schedule_bundle(:bundle => r.content)
reply = @serializer.dump(OperationResult.success)
else
reply = @serializer.dump(r) rescue '\"Failed to serialize response\"'
end
CommandIO.instance.reply(conn, reply)
end
true
end | [
"def",
"run_request",
"(",
"type",
",",
"conn",
",",
"payload",
")",
"payload",
"||=",
"{",
"}",
"payload",
"[",
":agent_identity",
"]",
"=",
"@agent_identity",
"Sender",
".",
"instance",
".",
"send_request",
"(",
"type",
",",
"payload",
")",
"do",
"|",
"r",
"|",
"r",
"=",
"OperationResult",
".",
"from_results",
"(",
"r",
")",
"if",
"r",
"&&",
"r",
".",
"success?",
"&&",
"r",
".",
"content",
".",
"is_a?",
"(",
"RightScale",
"::",
"ExecutableBundle",
")",
"@scheduler",
".",
"schedule_bundle",
"(",
":bundle",
"=>",
"r",
".",
"content",
")",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"OperationResult",
".",
"success",
")",
"else",
"reply",
"=",
"@serializer",
".",
"dump",
"(",
"r",
")",
"rescue",
"'\\\"Failed to serialize response\\\"'",
"end",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"conn",
",",
"reply",
")",
"end",
"true",
"end"
] | Send scheduling request for recipe or RightScript
If it returns with a bundle, schedule the bundle for execution
=== Parameters
type(String):: Type of request
conn(EM::Connection):: Connection used to send reply
payload(Hash):: Request parameters
=== Return
true:: Always return true | [
"Send",
"scheduling",
"request",
"for",
"recipe",
"or",
"RightScript",
"If",
"it",
"returns",
"with",
"a",
"bundle",
"schedule",
"the",
"bundle",
"for",
"execution"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L526-L540 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.get_shutdown_request_command | def get_shutdown_request_command(opts)
shutdown_request = ShutdownRequest.instance
CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? })
rescue Exception => e
CommandIO.instance.reply(opts[:conn], { :error => e.message })
end | ruby | def get_shutdown_request_command(opts)
shutdown_request = ShutdownRequest.instance
CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? })
rescue Exception => e
CommandIO.instance.reply(opts[:conn], { :error => e.message })
end | [
"def",
"get_shutdown_request_command",
"(",
"opts",
")",
"shutdown_request",
"=",
"ShutdownRequest",
".",
"instance",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"{",
":level",
"=>",
"shutdown_request",
".",
"level",
",",
":immediately",
"=>",
"shutdown_request",
".",
"immediately?",
"}",
")",
"rescue",
"Exception",
"=>",
"e",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"{",
":error",
"=>",
"e",
".",
"message",
"}",
")",
"end"
] | Get shutdown request command
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
=== Return
true:: Always return true | [
"Get",
"shutdown",
"request",
"command"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L561-L566 | train |
rightscale/right_link | lib/instance/instance_commands.rb | RightScale.InstanceCommands.set_shutdown_request_command | def set_shutdown_request_command(opts)
shutdown_request = ShutdownRequest.submit(opts)
CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? })
rescue Exception => e
CommandIO.instance.reply(opts[:conn], { :error => e.message })
end | ruby | def set_shutdown_request_command(opts)
shutdown_request = ShutdownRequest.submit(opts)
CommandIO.instance.reply(opts[:conn], { :level => shutdown_request.level, :immediately => shutdown_request.immediately? })
rescue Exception => e
CommandIO.instance.reply(opts[:conn], { :error => e.message })
end | [
"def",
"set_shutdown_request_command",
"(",
"opts",
")",
"shutdown_request",
"=",
"ShutdownRequest",
".",
"submit",
"(",
"opts",
")",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"{",
":level",
"=>",
"shutdown_request",
".",
"level",
",",
":immediately",
"=>",
"shutdown_request",
".",
"immediately?",
"}",
")",
"rescue",
"Exception",
"=>",
"e",
"CommandIO",
".",
"instance",
".",
"reply",
"(",
"opts",
"[",
":conn",
"]",
",",
"{",
":error",
"=>",
"e",
".",
"message",
"}",
")",
"end"
] | Set reboot timeout command
=== Parameters
opts[:conn](EM::Connection):: Connection used to send reply
opts[:level](String):: shutdown request level
opts[:immediately](Boolean):: shutdown immediacy or nil
=== Return
true:: Always return true | [
"Set",
"reboot",
"timeout",
"command"
] | b33a209c20a8a0942dd9f1fe49a08030d4ca209f | https://github.com/rightscale/right_link/blob/b33a209c20a8a0942dd9f1fe49a08030d4ca209f/lib/instance/instance_commands.rb#L577-L582 | train |
streamio/streamio-rb | lib/streamio/video.rb | Streamio.Video.add_transcoding | def add_transcoding(parameters)
response = self.class.resource.post("#{id}/transcodings", parameters)
reload
response.code.to_i == 201
end | ruby | def add_transcoding(parameters)
response = self.class.resource.post("#{id}/transcodings", parameters)
reload
response.code.to_i == 201
end | [
"def",
"add_transcoding",
"(",
"parameters",
")",
"response",
"=",
"self",
".",
"class",
".",
"resource",
".",
"post",
"(",
"\"#{id}/transcodings\"",
",",
"parameters",
")",
"reload",
"response",
".",
"code",
".",
"to_i",
"==",
"201",
"end"
] | Adds a transcoding to the video instance and reloads itself to
reflect the changed transcodings array.
@param [Hash] parameters The parameters to pass in when creating the transcoding.
@option parameters [String] :encoding_profile_id Id of the Encoding Profile to be used for the transcoding.
@return [Boolean] Indicating wether the transcoding was successfully created. | [
"Adds",
"a",
"transcoding",
"to",
"the",
"video",
"instance",
"and",
"reloads",
"itself",
"to",
"reflect",
"the",
"changed",
"transcodings",
"array",
"."
] | 7285a065e2301c7f2aafe5fbfad9332680159852 | https://github.com/streamio/streamio-rb/blob/7285a065e2301c7f2aafe5fbfad9332680159852/lib/streamio/video.rb#L16-L20 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.