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 |
---|---|---|---|---|---|---|---|---|---|---|---|
airbrake/airbrake-ruby | lib/airbrake-ruby/async_sender.rb | Airbrake.AsyncSender.send | def send(notice, promise)
return will_not_deliver(notice) if @unsent.size >= @unsent.max
@unsent << [notice, promise]
promise
end | ruby | def send(notice, promise)
return will_not_deliver(notice) if @unsent.size >= @unsent.max
@unsent << [notice, promise]
promise
end | [
"def",
"send",
"(",
"notice",
",",
"promise",
")",
"return",
"will_not_deliver",
"(",
"notice",
")",
"if",
"@unsent",
".",
"size",
">=",
"@unsent",
".",
"max",
"@unsent",
"<<",
"[",
"notice",
",",
"promise",
"]",
"promise",
"end"
] | Asynchronously sends a notice to Airbrake.
@param [Airbrake::Notice] notice A notice that was generated by the
library
@return [Airbrake::Promise] | [
"Asynchronously",
"sends",
"a",
"notice",
"to",
"Airbrake",
"."
] | bb560edf03df57b559e1dee1d2e9ec6480a686b8 | https://github.com/airbrake/airbrake-ruby/blob/bb560edf03df57b559e1dee1d2e9ec6480a686b8/lib/airbrake-ruby/async_sender.rb#L38-L43 | train |
airbrake/airbrake-ruby | lib/airbrake-ruby/notice.rb | Airbrake.Notice.[]= | def []=(key, value)
raise_if_ignored
unless WRITABLE_KEYS.include?(key)
raise Airbrake::Error,
":#{key} is not recognized among #{WRITABLE_KEYS}"
end
unless value.respond_to?(:to_hash)
raise Airbrake::Error, "Got #{value.class} value, wanted a Hash"
end
@payload[key] = value.to_hash
end | ruby | def []=(key, value)
raise_if_ignored
unless WRITABLE_KEYS.include?(key)
raise Airbrake::Error,
":#{key} is not recognized among #{WRITABLE_KEYS}"
end
unless value.respond_to?(:to_hash)
raise Airbrake::Error, "Got #{value.class} value, wanted a Hash"
end
@payload[key] = value.to_hash
end | [
"def",
"[]=",
"(",
"key",
",",
"value",
")",
"raise_if_ignored",
"unless",
"WRITABLE_KEYS",
".",
"include?",
"(",
"key",
")",
"raise",
"Airbrake",
"::",
"Error",
",",
"\":#{key} is not recognized among #{WRITABLE_KEYS}\"",
"end",
"unless",
"value",
".",
"respond_to?",
"(",
":to_hash",
")",
"raise",
"Airbrake",
"::",
"Error",
",",
"\"Got #{value.class} value, wanted a Hash\"",
"end",
"@payload",
"[",
"key",
"]",
"=",
"value",
".",
"to_hash",
"end"
] | Writes a value to the payload hash. Restricts unrecognized writes.
@example
notice[:params][:my_param] = 'foobar'
@return [void]
@raise [Airbrake::Error] if the notice is ignored
@raise [Airbrake::Error] if the +key+ is not recognized
@raise [Airbrake::Error] if the root value is not a Hash | [
"Writes",
"a",
"value",
"to",
"the",
"payload",
"hash",
".",
"Restricts",
"unrecognized",
"writes",
"."
] | bb560edf03df57b559e1dee1d2e9ec6480a686b8 | https://github.com/airbrake/airbrake-ruby/blob/bb560edf03df57b559e1dee1d2e9ec6480a686b8/lib/airbrake-ruby/notice.rb#L114-L127 | train |
ashfurrow/danger-ruby-swiftlint | lib/danger_plugin.rb | Danger.DangerSwiftlint.run_swiftlint | def run_swiftlint(files, lint_all_files, options, additional_swiftlint_args)
if lint_all_files
result = swiftlint.lint(options, additional_swiftlint_args)
if result == ''
{}
else
JSON.parse(result).flatten
end
else
files
.map { |file| options.merge(path: file) }
.map { |full_options| swiftlint.lint(full_options, additional_swiftlint_args) }
.reject { |s| s == '' }
.map { |s| JSON.parse(s).flatten }
.flatten
end
end | ruby | def run_swiftlint(files, lint_all_files, options, additional_swiftlint_args)
if lint_all_files
result = swiftlint.lint(options, additional_swiftlint_args)
if result == ''
{}
else
JSON.parse(result).flatten
end
else
files
.map { |file| options.merge(path: file) }
.map { |full_options| swiftlint.lint(full_options, additional_swiftlint_args) }
.reject { |s| s == '' }
.map { |s| JSON.parse(s).flatten }
.flatten
end
end | [
"def",
"run_swiftlint",
"(",
"files",
",",
"lint_all_files",
",",
"options",
",",
"additional_swiftlint_args",
")",
"if",
"lint_all_files",
"result",
"=",
"swiftlint",
".",
"lint",
"(",
"options",
",",
"additional_swiftlint_args",
")",
"if",
"result",
"==",
"''",
"{",
"}",
"else",
"JSON",
".",
"parse",
"(",
"result",
")",
".",
"flatten",
"end",
"else",
"files",
".",
"map",
"{",
"|",
"file",
"|",
"options",
".",
"merge",
"(",
"path",
":",
"file",
")",
"}",
".",
"map",
"{",
"|",
"full_options",
"|",
"swiftlint",
".",
"lint",
"(",
"full_options",
",",
"additional_swiftlint_args",
")",
"}",
".",
"reject",
"{",
"|",
"s",
"|",
"s",
"==",
"''",
"}",
".",
"map",
"{",
"|",
"s",
"|",
"JSON",
".",
"parse",
"(",
"s",
")",
".",
"flatten",
"}",
".",
"flatten",
"end",
"end"
] | Run swiftlint on each file and aggregate collect the issues
@return [Array] swiftlint issues | [
"Run",
"swiftlint",
"on",
"each",
"file",
"and",
"aggregate",
"collect",
"the",
"issues"
] | a6ff2fbf492433c865ffc66feffede1d2d1e2f4d | https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L153-L169 | train |
ashfurrow/danger-ruby-swiftlint | lib/danger_plugin.rb | Danger.DangerSwiftlint.find_swift_files | def find_swift_files(dir_selected, files = nil, excluded_paths = [], included_paths = [])
# Needs to be escaped before comparsion with escaped file paths
dir_selected = Shellwords.escape(dir_selected)
# Assign files to lint
files = if files.nil?
(git.modified_files - git.deleted_files) + git.added_files
else
Dir.glob(files)
end
# Filter files to lint
files.
# Ensure only swift files are selected
select { |file| file.end_with?('.swift') }.
# Make sure we don't fail when paths have spaces
map { |file| Shellwords.escape(File.expand_path(file)) }.
# Remove dups
uniq.
# Ensure only files in the selected directory
select { |file| file.start_with?(dir_selected) }.
# Reject files excluded on configuration
reject { |file| file_exists?(excluded_paths, file) }.
# Accept files included on configuration
select do |file|
next true if included_paths.empty?
file_exists?(included_paths, file)
end
end | ruby | def find_swift_files(dir_selected, files = nil, excluded_paths = [], included_paths = [])
# Needs to be escaped before comparsion with escaped file paths
dir_selected = Shellwords.escape(dir_selected)
# Assign files to lint
files = if files.nil?
(git.modified_files - git.deleted_files) + git.added_files
else
Dir.glob(files)
end
# Filter files to lint
files.
# Ensure only swift files are selected
select { |file| file.end_with?('.swift') }.
# Make sure we don't fail when paths have spaces
map { |file| Shellwords.escape(File.expand_path(file)) }.
# Remove dups
uniq.
# Ensure only files in the selected directory
select { |file| file.start_with?(dir_selected) }.
# Reject files excluded on configuration
reject { |file| file_exists?(excluded_paths, file) }.
# Accept files included on configuration
select do |file|
next true if included_paths.empty?
file_exists?(included_paths, file)
end
end | [
"def",
"find_swift_files",
"(",
"dir_selected",
",",
"files",
"=",
"nil",
",",
"excluded_paths",
"=",
"[",
"]",
",",
"included_paths",
"=",
"[",
"]",
")",
"# Needs to be escaped before comparsion with escaped file paths",
"dir_selected",
"=",
"Shellwords",
".",
"escape",
"(",
"dir_selected",
")",
"# Assign files to lint",
"files",
"=",
"if",
"files",
".",
"nil?",
"(",
"git",
".",
"modified_files",
"-",
"git",
".",
"deleted_files",
")",
"+",
"git",
".",
"added_files",
"else",
"Dir",
".",
"glob",
"(",
"files",
")",
"end",
"# Filter files to lint",
"files",
".",
"# Ensure only swift files are selected",
"select",
"{",
"|",
"file",
"|",
"file",
".",
"end_with?",
"(",
"'.swift'",
")",
"}",
".",
"# Make sure we don't fail when paths have spaces",
"map",
"{",
"|",
"file",
"|",
"Shellwords",
".",
"escape",
"(",
"File",
".",
"expand_path",
"(",
"file",
")",
")",
"}",
".",
"# Remove dups",
"uniq",
".",
"# Ensure only files in the selected directory",
"select",
"{",
"|",
"file",
"|",
"file",
".",
"start_with?",
"(",
"dir_selected",
")",
"}",
".",
"# Reject files excluded on configuration",
"reject",
"{",
"|",
"file",
"|",
"file_exists?",
"(",
"excluded_paths",
",",
"file",
")",
"}",
".",
"# Accept files included on configuration",
"select",
"do",
"|",
"file",
"|",
"next",
"true",
"if",
"included_paths",
".",
"empty?",
"file_exists?",
"(",
"included_paths",
",",
"file",
")",
"end",
"end"
] | Find swift files from the files glob
If files are not provided it will use git modifield and added files
@return [Array] swift files | [
"Find",
"swift",
"files",
"from",
"the",
"files",
"glob",
"If",
"files",
"are",
"not",
"provided",
"it",
"will",
"use",
"git",
"modifield",
"and",
"added",
"files"
] | a6ff2fbf492433c865ffc66feffede1d2d1e2f4d | https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L175-L202 | train |
ashfurrow/danger-ruby-swiftlint | lib/danger_plugin.rb | Danger.DangerSwiftlint.load_config | def load_config(filepath)
return {} if filepath.nil? || !File.exist?(filepath)
config_file = File.open(filepath).read
# Replace environment variables
config_file = parse_environment_variables(config_file)
YAML.safe_load(config_file)
end | ruby | def load_config(filepath)
return {} if filepath.nil? || !File.exist?(filepath)
config_file = File.open(filepath).read
# Replace environment variables
config_file = parse_environment_variables(config_file)
YAML.safe_load(config_file)
end | [
"def",
"load_config",
"(",
"filepath",
")",
"return",
"{",
"}",
"if",
"filepath",
".",
"nil?",
"||",
"!",
"File",
".",
"exist?",
"(",
"filepath",
")",
"config_file",
"=",
"File",
".",
"open",
"(",
"filepath",
")",
".",
"read",
"# Replace environment variables",
"config_file",
"=",
"parse_environment_variables",
"(",
"config_file",
")",
"YAML",
".",
"safe_load",
"(",
"config_file",
")",
"end"
] | Get the configuration file | [
"Get",
"the",
"configuration",
"file"
] | a6ff2fbf492433c865ffc66feffede1d2d1e2f4d | https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L205-L214 | train |
ashfurrow/danger-ruby-swiftlint | lib/danger_plugin.rb | Danger.DangerSwiftlint.parse_environment_variables | def parse_environment_variables(file_contents)
# Matches the file contents for environment variables defined like ${VAR_NAME}.
# Replaces them with the environment variable value if it exists.
file_contents.gsub(/\$\{([^{}]+)\}/) do |env_var|
return env_var if ENV[Regexp.last_match[1]].nil?
ENV[Regexp.last_match[1]]
end
end | ruby | def parse_environment_variables(file_contents)
# Matches the file contents for environment variables defined like ${VAR_NAME}.
# Replaces them with the environment variable value if it exists.
file_contents.gsub(/\$\{([^{}]+)\}/) do |env_var|
return env_var if ENV[Regexp.last_match[1]].nil?
ENV[Regexp.last_match[1]]
end
end | [
"def",
"parse_environment_variables",
"(",
"file_contents",
")",
"# Matches the file contents for environment variables defined like ${VAR_NAME}.",
"# Replaces them with the environment variable value if it exists.",
"file_contents",
".",
"gsub",
"(",
"/",
"\\$",
"\\{",
"\\}",
"/",
")",
"do",
"|",
"env_var",
"|",
"return",
"env_var",
"if",
"ENV",
"[",
"Regexp",
".",
"last_match",
"[",
"1",
"]",
"]",
".",
"nil?",
"ENV",
"[",
"Regexp",
".",
"last_match",
"[",
"1",
"]",
"]",
"end",
"end"
] | Find all requested environment variables in the given string and replace them with the correct values. | [
"Find",
"all",
"requested",
"environment",
"variables",
"in",
"the",
"given",
"string",
"and",
"replace",
"them",
"with",
"the",
"correct",
"values",
"."
] | a6ff2fbf492433c865ffc66feffede1d2d1e2f4d | https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L217-L224 | train |
ashfurrow/danger-ruby-swiftlint | lib/danger_plugin.rb | Danger.DangerSwiftlint.file_exists? | def file_exists?(paths, file)
paths.any? do |path|
Find.find(path)
.map { |path_file| Shellwords.escape(path_file) }
.include?(file)
end
end | ruby | def file_exists?(paths, file)
paths.any? do |path|
Find.find(path)
.map { |path_file| Shellwords.escape(path_file) }
.include?(file)
end
end | [
"def",
"file_exists?",
"(",
"paths",
",",
"file",
")",
"paths",
".",
"any?",
"do",
"|",
"path",
"|",
"Find",
".",
"find",
"(",
"path",
")",
".",
"map",
"{",
"|",
"path_file",
"|",
"Shellwords",
".",
"escape",
"(",
"path_file",
")",
"}",
".",
"include?",
"(",
"file",
")",
"end",
"end"
] | Return whether the file exists within a specified collection of paths
@return [Bool] file exists within specified collection of paths | [
"Return",
"whether",
"the",
"file",
"exists",
"within",
"a",
"specified",
"collection",
"of",
"paths"
] | a6ff2fbf492433c865ffc66feffede1d2d1e2f4d | https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L229-L235 | train |
ashfurrow/danger-ruby-swiftlint | lib/danger_plugin.rb | Danger.DangerSwiftlint.format_paths | def format_paths(paths, filepath)
# Extract included paths
paths
.map { |path| File.join(File.dirname(filepath), path) }
.map { |path| File.expand_path(path) }
.select { |path| File.exist?(path) || Dir.exist?(path) }
end | ruby | def format_paths(paths, filepath)
# Extract included paths
paths
.map { |path| File.join(File.dirname(filepath), path) }
.map { |path| File.expand_path(path) }
.select { |path| File.exist?(path) || Dir.exist?(path) }
end | [
"def",
"format_paths",
"(",
"paths",
",",
"filepath",
")",
"# Extract included paths",
"paths",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"filepath",
")",
",",
"path",
")",
"}",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"expand_path",
"(",
"path",
")",
"}",
".",
"select",
"{",
"|",
"path",
"|",
"File",
".",
"exist?",
"(",
"path",
")",
"||",
"Dir",
".",
"exist?",
"(",
"path",
")",
"}",
"end"
] | Parses the configuration file and return the specified files in path
@return [Array] list of files specified in path | [
"Parses",
"the",
"configuration",
"file",
"and",
"return",
"the",
"specified",
"files",
"in",
"path"
] | a6ff2fbf492433c865ffc66feffede1d2d1e2f4d | https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L240-L246 | train |
ashfurrow/danger-ruby-swiftlint | lib/danger_plugin.rb | Danger.DangerSwiftlint.markdown_issues | def markdown_issues(results, heading)
message = "#### #{heading}\n\n".dup
message << "File | Line | Reason |\n"
message << "| --- | ----- | ----- |\n"
results.each do |r|
filename = r['file'].split('/').last
line = r['line']
reason = r['reason']
rule = r['rule_id']
# Other available properties can be found int SwiftLint/…/JSONReporter.swift
message << "#{filename} | #{line} | #{reason} (#{rule})\n"
end
message
end | ruby | def markdown_issues(results, heading)
message = "#### #{heading}\n\n".dup
message << "File | Line | Reason |\n"
message << "| --- | ----- | ----- |\n"
results.each do |r|
filename = r['file'].split('/').last
line = r['line']
reason = r['reason']
rule = r['rule_id']
# Other available properties can be found int SwiftLint/…/JSONReporter.swift
message << "#{filename} | #{line} | #{reason} (#{rule})\n"
end
message
end | [
"def",
"markdown_issues",
"(",
"results",
",",
"heading",
")",
"message",
"=",
"\"#### #{heading}\\n\\n\"",
".",
"dup",
"message",
"<<",
"\"File | Line | Reason |\\n\"",
"message",
"<<",
"\"| --- | ----- | ----- |\\n\"",
"results",
".",
"each",
"do",
"|",
"r",
"|",
"filename",
"=",
"r",
"[",
"'file'",
"]",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"line",
"=",
"r",
"[",
"'line'",
"]",
"reason",
"=",
"r",
"[",
"'reason'",
"]",
"rule",
"=",
"r",
"[",
"'rule_id'",
"]",
"# Other available properties can be found int SwiftLint/…/JSONReporter.swift",
"message",
"<<",
"\"#{filename} | #{line} | #{reason} (#{rule})\\n\"",
"end",
"message",
"end"
] | Create a markdown table from swiftlint issues
@return [String] | [
"Create",
"a",
"markdown",
"table",
"from",
"swiftlint",
"issues"
] | a6ff2fbf492433c865ffc66feffede1d2d1e2f4d | https://github.com/ashfurrow/danger-ruby-swiftlint/blob/a6ff2fbf492433c865ffc66feffede1d2d1e2f4d/lib/danger_plugin.rb#L251-L267 | train |
pusher/pusher-http-ruby | lib/pusher/webhook.rb | Pusher.WebHook.check_signature | def check_signature(secret)
digest = OpenSSL::Digest::SHA256.new
expected = OpenSSL::HMAC.hexdigest(digest, secret, @body)
if @signature == expected
return true
else
Pusher.logger.warn "Received WebHook with invalid signature: got #{@signature}, expected #{expected}"
return false
end
end | ruby | def check_signature(secret)
digest = OpenSSL::Digest::SHA256.new
expected = OpenSSL::HMAC.hexdigest(digest, secret, @body)
if @signature == expected
return true
else
Pusher.logger.warn "Received WebHook with invalid signature: got #{@signature}, expected #{expected}"
return false
end
end | [
"def",
"check_signature",
"(",
"secret",
")",
"digest",
"=",
"OpenSSL",
"::",
"Digest",
"::",
"SHA256",
".",
"new",
"expected",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"hexdigest",
"(",
"digest",
",",
"secret",
",",
"@body",
")",
"if",
"@signature",
"==",
"expected",
"return",
"true",
"else",
"Pusher",
".",
"logger",
".",
"warn",
"\"Received WebHook with invalid signature: got #{@signature}, expected #{expected}\"",
"return",
"false",
"end",
"end"
] | Checks signature against secret and returns boolean | [
"Checks",
"signature",
"against",
"secret",
"and",
"returns",
"boolean"
] | cd666ca74b39dacfae6ca0235c35fcf80eba1e64 | https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/webhook.rb#L99-L108 | train |
pusher/pusher-http-ruby | lib/pusher/client.rb | Pusher.Client.url= | def url=(url)
uri = URI.parse(url)
@scheme = uri.scheme
@app_id = uri.path.split('/').last
@key = uri.user
@secret = uri.password
@host = uri.host
@port = uri.port
end | ruby | def url=(url)
uri = URI.parse(url)
@scheme = uri.scheme
@app_id = uri.path.split('/').last
@key = uri.user
@secret = uri.password
@host = uri.host
@port = uri.port
end | [
"def",
"url",
"=",
"(",
"url",
")",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"@scheme",
"=",
"uri",
".",
"scheme",
"@app_id",
"=",
"uri",
".",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"@key",
"=",
"uri",
".",
"user",
"@secret",
"=",
"uri",
".",
"password",
"@host",
"=",
"uri",
".",
"host",
"@port",
"=",
"uri",
".",
"port",
"end"
] | Configure Pusher connection by providing a url rather than specifying
scheme, key, secret, and app_id separately.
@example
Pusher.url = http://KEY:[email protected]/apps/APP_ID | [
"Configure",
"Pusher",
"connection",
"by",
"providing",
"a",
"url",
"rather",
"than",
"specifying",
"scheme",
"key",
"secret",
"and",
"app_id",
"separately",
"."
] | cd666ca74b39dacfae6ca0235c35fcf80eba1e64 | https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/client.rb#L92-L100 | train |
pusher/pusher-http-ruby | lib/pusher/client.rb | Pusher.Client.trigger | def trigger(channels, event_name, data, params = {})
post('/events', trigger_params(channels, event_name, data, params))
end | ruby | def trigger(channels, event_name, data, params = {})
post('/events', trigger_params(channels, event_name, data, params))
end | [
"def",
"trigger",
"(",
"channels",
",",
"event_name",
",",
"data",
",",
"params",
"=",
"{",
"}",
")",
"post",
"(",
"'/events'",
",",
"trigger_params",
"(",
"channels",
",",
"event_name",
",",
"data",
",",
"params",
")",
")",
"end"
] | Trigger an event on one or more channels
POST /apps/[app_id]/events
@param channels [String or Array] 1-10 channel names
@param event_name [String]
@param data [Object] Event data to be triggered in javascript.
Objects other than strings will be converted to JSON
@param params [Hash] Additional parameters to send to api, e.g socket_id
@return [Hash] See Pusher API docs
@raise [Pusher::Error] Unsuccessful response - see the error message
@raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error | [
"Trigger",
"an",
"event",
"on",
"one",
"or",
"more",
"channels"
] | cd666ca74b39dacfae6ca0235c35fcf80eba1e64 | https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/client.rb#L287-L289 | train |
pusher/pusher-http-ruby | lib/pusher/channel.rb | Pusher.Channel.trigger | def trigger(event_name, data, socket_id = nil)
trigger!(event_name, data, socket_id)
rescue Pusher::Error => e
Pusher.logger.error("#{e.message} (#{e.class})")
Pusher.logger.debug(e.backtrace.join("\n"))
end | ruby | def trigger(event_name, data, socket_id = nil)
trigger!(event_name, data, socket_id)
rescue Pusher::Error => e
Pusher.logger.error("#{e.message} (#{e.class})")
Pusher.logger.debug(e.backtrace.join("\n"))
end | [
"def",
"trigger",
"(",
"event_name",
",",
"data",
",",
"socket_id",
"=",
"nil",
")",
"trigger!",
"(",
"event_name",
",",
"data",
",",
"socket_id",
")",
"rescue",
"Pusher",
"::",
"Error",
"=>",
"e",
"Pusher",
".",
"logger",
".",
"error",
"(",
"\"#{e.message} (#{e.class})\"",
")",
"Pusher",
".",
"logger",
".",
"debug",
"(",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"end"
] | Trigger event, catching and logging any errors.
[Deprecated] This method will be removed in a future gem version. Please
switch to Pusher.trigger or Pusher::Client#trigger instead
@note CAUTION! No exceptions will be raised on failure
@param (see #trigger!) | [
"Trigger",
"event",
"catching",
"and",
"logging",
"any",
"errors",
"."
] | cd666ca74b39dacfae6ca0235c35fcf80eba1e64 | https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/channel.rb#L80-L85 | train |
pusher/pusher-http-ruby | lib/pusher/channel.rb | Pusher.Channel.authentication_string | def authentication_string(socket_id, custom_string = nil)
validate_socket_id(socket_id)
unless custom_string.nil? || custom_string.kind_of?(String)
raise Error, 'Custom argument must be a string'
end
string_to_sign = [socket_id, name, custom_string].
compact.map(&:to_s).join(':')
Pusher.logger.debug "Signing #{string_to_sign}"
token = @client.authentication_token
digest = OpenSSL::Digest::SHA256.new
signature = OpenSSL::HMAC.hexdigest(digest, token.secret, string_to_sign)
return "#{token.key}:#{signature}"
end | ruby | def authentication_string(socket_id, custom_string = nil)
validate_socket_id(socket_id)
unless custom_string.nil? || custom_string.kind_of?(String)
raise Error, 'Custom argument must be a string'
end
string_to_sign = [socket_id, name, custom_string].
compact.map(&:to_s).join(':')
Pusher.logger.debug "Signing #{string_to_sign}"
token = @client.authentication_token
digest = OpenSSL::Digest::SHA256.new
signature = OpenSSL::HMAC.hexdigest(digest, token.secret, string_to_sign)
return "#{token.key}:#{signature}"
end | [
"def",
"authentication_string",
"(",
"socket_id",
",",
"custom_string",
"=",
"nil",
")",
"validate_socket_id",
"(",
"socket_id",
")",
"unless",
"custom_string",
".",
"nil?",
"||",
"custom_string",
".",
"kind_of?",
"(",
"String",
")",
"raise",
"Error",
",",
"'Custom argument must be a string'",
"end",
"string_to_sign",
"=",
"[",
"socket_id",
",",
"name",
",",
"custom_string",
"]",
".",
"compact",
".",
"map",
"(",
":to_s",
")",
".",
"join",
"(",
"':'",
")",
"Pusher",
".",
"logger",
".",
"debug",
"\"Signing #{string_to_sign}\"",
"token",
"=",
"@client",
".",
"authentication_token",
"digest",
"=",
"OpenSSL",
"::",
"Digest",
"::",
"SHA256",
".",
"new",
"signature",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"hexdigest",
"(",
"digest",
",",
"token",
".",
"secret",
",",
"string_to_sign",
")",
"return",
"\"#{token.key}:#{signature}\"",
"end"
] | Compute authentication string required as part of the authentication
endpoint response. Generally the authenticate method should be used in
preference to this one
@param socket_id [String] Each Pusher socket connection receives a
unique socket_id. This is sent from pusher.js to your server when
channel authentication is required.
@param custom_string [String] Allows signing additional data
@return [String]
@raise [Pusher::Error] if socket_id or custom_string invalid | [
"Compute",
"authentication",
"string",
"required",
"as",
"part",
"of",
"the",
"authentication",
"endpoint",
"response",
".",
"Generally",
"the",
"authenticate",
"method",
"should",
"be",
"used",
"in",
"preference",
"to",
"this",
"one"
] | cd666ca74b39dacfae6ca0235c35fcf80eba1e64 | https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/channel.rb#L128-L143 | train |
codevise/pageflow | lib/pageflow/widget_type.rb | Pageflow.WidgetType.render | def render(template, entry)
template.render(File.join('pageflow', name, 'widget'), entry: entry)
end | ruby | def render(template, entry)
template.render(File.join('pageflow', name, 'widget'), entry: entry)
end | [
"def",
"render",
"(",
"template",
",",
"entry",
")",
"template",
".",
"render",
"(",
"File",
".",
"join",
"(",
"'pageflow'",
",",
"name",
",",
"'widget'",
")",
",",
"entry",
":",
"entry",
")",
"end"
] | Override to return html as string. | [
"Override",
"to",
"return",
"html",
"as",
"string",
"."
] | 08a812373823581f44aa59a95b83f0deb55f4ed9 | https://github.com/codevise/pageflow/blob/08a812373823581f44aa59a95b83f0deb55f4ed9/lib/pageflow/widget_type.rb#L43-L45 | train |
codevise/pageflow | app/models/pageflow/account_role_query.rb | Pageflow.AccountRoleQuery.has_at_least_role? | def has_at_least_role?(role)
@user
.memberships
.where(role: Roles.at_least(role))
.where('(entity_id = :account_id AND '\
"entity_type = 'Pageflow::Account')",
account_id: @account.id)
.any?
end | ruby | def has_at_least_role?(role)
@user
.memberships
.where(role: Roles.at_least(role))
.where('(entity_id = :account_id AND '\
"entity_type = 'Pageflow::Account')",
account_id: @account.id)
.any?
end | [
"def",
"has_at_least_role?",
"(",
"role",
")",
"@user",
".",
"memberships",
".",
"where",
"(",
"role",
":",
"Roles",
".",
"at_least",
"(",
"role",
")",
")",
".",
"where",
"(",
"'(entity_id = :account_id AND '",
"\"entity_type = 'Pageflow::Account')\"",
",",
"account_id",
":",
"@account",
".",
"id",
")",
".",
"any?",
"end"
] | Create query that can be used for role comparisons
@param [User] user
Required. Membership user to check.
@param [Pageflow::Account] account
Required. Membership entity to check.
Return true if there is a membership with at least role for
user/account
@param [String] role
Required. Minimum role that we compare against.
@return [Boolean] | [
"Create",
"query",
"that",
"can",
"be",
"used",
"for",
"role",
"comparisons"
] | 08a812373823581f44aa59a95b83f0deb55f4ed9 | https://github.com/codevise/pageflow/blob/08a812373823581f44aa59a95b83f0deb55f4ed9/app/models/pageflow/account_role_query.rb#L58-L66 | train |
codevise/pageflow | lib/pageflow/help_entries.rb | Pageflow.HelpEntries.register | def register(name, options = {})
help_entry = HelpEntry.new(name, options)
@help_entries_by_name[name] = help_entry
collection = find_collection(options[:parent])
collection << help_entry
collection.sort_by! { |help_entry| -help_entry.priority }
end | ruby | def register(name, options = {})
help_entry = HelpEntry.new(name, options)
@help_entries_by_name[name] = help_entry
collection = find_collection(options[:parent])
collection << help_entry
collection.sort_by! { |help_entry| -help_entry.priority }
end | [
"def",
"register",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"help_entry",
"=",
"HelpEntry",
".",
"new",
"(",
"name",
",",
"options",
")",
"@help_entries_by_name",
"[",
"name",
"]",
"=",
"help_entry",
"collection",
"=",
"find_collection",
"(",
"options",
"[",
":parent",
"]",
")",
"collection",
"<<",
"help_entry",
"collection",
".",
"sort_by!",
"{",
"|",
"help_entry",
"|",
"-",
"help_entry",
".",
"priority",
"}",
"end"
] | Add a section to the help dialog displayed in the editor.
Translation keys for the help entry are derived from its name by
appending ".menu_item" and ".text". Text is parsed as markdown.
@param [String] name Translation key prefix
@param [Hash] options
@option options [String] :parent Name of the parent help entry
@option options [Fixnum] :priority (10) Entries with higher
priority come first in the entry list. | [
"Add",
"a",
"section",
"to",
"the",
"help",
"dialog",
"displayed",
"in",
"the",
"editor",
"."
] | 08a812373823581f44aa59a95b83f0deb55f4ed9 | https://github.com/codevise/pageflow/blob/08a812373823581f44aa59a95b83f0deb55f4ed9/lib/pageflow/help_entries.rb#L20-L28 | train |
twitchtv/twirp-ruby | lib/twirp/service.rb | Twirp.Service.call | def call(rack_env)
begin
env = {}
bad_route = route_request(rack_env, env)
return error_response(bad_route, env) if bad_route
@before.each do |hook|
result = hook.call(rack_env, env)
return error_response(result, env) if result.is_a? Twirp::Error
end
output = call_handler(env)
return error_response(output, env) if output.is_a? Twirp::Error
return success_response(output, env)
rescue => e
raise e if self.class.raise_exceptions
begin
@exception_raised.each{|hook| hook.call(e, env) }
rescue => hook_e
e = hook_e
end
twerr = Twirp::Error.internal_with(e)
return error_response(twerr, env)
end
end | ruby | def call(rack_env)
begin
env = {}
bad_route = route_request(rack_env, env)
return error_response(bad_route, env) if bad_route
@before.each do |hook|
result = hook.call(rack_env, env)
return error_response(result, env) if result.is_a? Twirp::Error
end
output = call_handler(env)
return error_response(output, env) if output.is_a? Twirp::Error
return success_response(output, env)
rescue => e
raise e if self.class.raise_exceptions
begin
@exception_raised.each{|hook| hook.call(e, env) }
rescue => hook_e
e = hook_e
end
twerr = Twirp::Error.internal_with(e)
return error_response(twerr, env)
end
end | [
"def",
"call",
"(",
"rack_env",
")",
"begin",
"env",
"=",
"{",
"}",
"bad_route",
"=",
"route_request",
"(",
"rack_env",
",",
"env",
")",
"return",
"error_response",
"(",
"bad_route",
",",
"env",
")",
"if",
"bad_route",
"@before",
".",
"each",
"do",
"|",
"hook",
"|",
"result",
"=",
"hook",
".",
"call",
"(",
"rack_env",
",",
"env",
")",
"return",
"error_response",
"(",
"result",
",",
"env",
")",
"if",
"result",
".",
"is_a?",
"Twirp",
"::",
"Error",
"end",
"output",
"=",
"call_handler",
"(",
"env",
")",
"return",
"error_response",
"(",
"output",
",",
"env",
")",
"if",
"output",
".",
"is_a?",
"Twirp",
"::",
"Error",
"return",
"success_response",
"(",
"output",
",",
"env",
")",
"rescue",
"=>",
"e",
"raise",
"e",
"if",
"self",
".",
"class",
".",
"raise_exceptions",
"begin",
"@exception_raised",
".",
"each",
"{",
"|",
"hook",
"|",
"hook",
".",
"call",
"(",
"e",
",",
"env",
")",
"}",
"rescue",
"=>",
"hook_e",
"e",
"=",
"hook_e",
"end",
"twerr",
"=",
"Twirp",
"::",
"Error",
".",
"internal_with",
"(",
"e",
")",
"return",
"error_response",
"(",
"twerr",
",",
"env",
")",
"end",
"end"
] | Rack app handler. | [
"Rack",
"app",
"handler",
"."
] | 3ec36d2653a14eb8cc73409fb20889e8484db371 | https://github.com/twitchtv/twirp-ruby/blob/3ec36d2653a14eb8cc73409fb20889e8484db371/lib/twirp/service.rb#L61-L87 | train |
twitchtv/twirp-ruby | lib/twirp/service.rb | Twirp.Service.route_request | def route_request(rack_env, env)
rack_request = Rack::Request.new(rack_env)
if rack_request.request_method != "POST"
return bad_route_error("HTTP request method must be POST", rack_request)
end
content_type = rack_request.get_header("CONTENT_TYPE")
if !Encoding.valid_content_type?(content_type)
return bad_route_error("Unexpected Content-Type: #{content_type.inspect}. Content-Type header must be one of #{Encoding.valid_content_types.inspect}", rack_request)
end
env[:content_type] = content_type
path_parts = rack_request.fullpath.split("/")
if path_parts.size < 3 || path_parts[-2] != self.full_name
return bad_route_error("Invalid route. Expected format: POST {BaseURL}/#{self.full_name}/{Method}", rack_request)
end
method_name = path_parts[-1]
base_env = self.class.rpcs[method_name]
if !base_env
return bad_route_error("Invalid rpc method #{method_name.inspect}", rack_request)
end
env.merge!(base_env) # :rpc_method, :input_class, :output_class
input = nil
begin
input = Encoding.decode(rack_request.body.read, env[:input_class], content_type)
rescue => e
error_msg = "Invalid request body for rpc method #{method_name.inspect} with Content-Type=#{content_type}"
if e.is_a?(Google::Protobuf::ParseError)
error_msg += ": #{e.message.strip}"
end
return bad_route_error(error_msg, rack_request)
end
env[:input] = input
env[:http_response_headers] = {}
return
end | ruby | def route_request(rack_env, env)
rack_request = Rack::Request.new(rack_env)
if rack_request.request_method != "POST"
return bad_route_error("HTTP request method must be POST", rack_request)
end
content_type = rack_request.get_header("CONTENT_TYPE")
if !Encoding.valid_content_type?(content_type)
return bad_route_error("Unexpected Content-Type: #{content_type.inspect}. Content-Type header must be one of #{Encoding.valid_content_types.inspect}", rack_request)
end
env[:content_type] = content_type
path_parts = rack_request.fullpath.split("/")
if path_parts.size < 3 || path_parts[-2] != self.full_name
return bad_route_error("Invalid route. Expected format: POST {BaseURL}/#{self.full_name}/{Method}", rack_request)
end
method_name = path_parts[-1]
base_env = self.class.rpcs[method_name]
if !base_env
return bad_route_error("Invalid rpc method #{method_name.inspect}", rack_request)
end
env.merge!(base_env) # :rpc_method, :input_class, :output_class
input = nil
begin
input = Encoding.decode(rack_request.body.read, env[:input_class], content_type)
rescue => e
error_msg = "Invalid request body for rpc method #{method_name.inspect} with Content-Type=#{content_type}"
if e.is_a?(Google::Protobuf::ParseError)
error_msg += ": #{e.message.strip}"
end
return bad_route_error(error_msg, rack_request)
end
env[:input] = input
env[:http_response_headers] = {}
return
end | [
"def",
"route_request",
"(",
"rack_env",
",",
"env",
")",
"rack_request",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"rack_env",
")",
"if",
"rack_request",
".",
"request_method",
"!=",
"\"POST\"",
"return",
"bad_route_error",
"(",
"\"HTTP request method must be POST\"",
",",
"rack_request",
")",
"end",
"content_type",
"=",
"rack_request",
".",
"get_header",
"(",
"\"CONTENT_TYPE\"",
")",
"if",
"!",
"Encoding",
".",
"valid_content_type?",
"(",
"content_type",
")",
"return",
"bad_route_error",
"(",
"\"Unexpected Content-Type: #{content_type.inspect}. Content-Type header must be one of #{Encoding.valid_content_types.inspect}\"",
",",
"rack_request",
")",
"end",
"env",
"[",
":content_type",
"]",
"=",
"content_type",
"path_parts",
"=",
"rack_request",
".",
"fullpath",
".",
"split",
"(",
"\"/\"",
")",
"if",
"path_parts",
".",
"size",
"<",
"3",
"||",
"path_parts",
"[",
"-",
"2",
"]",
"!=",
"self",
".",
"full_name",
"return",
"bad_route_error",
"(",
"\"Invalid route. Expected format: POST {BaseURL}/#{self.full_name}/{Method}\"",
",",
"rack_request",
")",
"end",
"method_name",
"=",
"path_parts",
"[",
"-",
"1",
"]",
"base_env",
"=",
"self",
".",
"class",
".",
"rpcs",
"[",
"method_name",
"]",
"if",
"!",
"base_env",
"return",
"bad_route_error",
"(",
"\"Invalid rpc method #{method_name.inspect}\"",
",",
"rack_request",
")",
"end",
"env",
".",
"merge!",
"(",
"base_env",
")",
"# :rpc_method, :input_class, :output_class",
"input",
"=",
"nil",
"begin",
"input",
"=",
"Encoding",
".",
"decode",
"(",
"rack_request",
".",
"body",
".",
"read",
",",
"env",
"[",
":input_class",
"]",
",",
"content_type",
")",
"rescue",
"=>",
"e",
"error_msg",
"=",
"\"Invalid request body for rpc method #{method_name.inspect} with Content-Type=#{content_type}\"",
"if",
"e",
".",
"is_a?",
"(",
"Google",
"::",
"Protobuf",
"::",
"ParseError",
")",
"error_msg",
"+=",
"\": #{e.message.strip}\"",
"end",
"return",
"bad_route_error",
"(",
"error_msg",
",",
"rack_request",
")",
"end",
"env",
"[",
":input",
"]",
"=",
"input",
"env",
"[",
":http_response_headers",
"]",
"=",
"{",
"}",
"return",
"end"
] | Parse request and fill env with rpc data.
Returns a bad_route error if something went wrong. | [
"Parse",
"request",
"and",
"fill",
"env",
"with",
"rpc",
"data",
".",
"Returns",
"a",
"bad_route",
"error",
"if",
"something",
"went",
"wrong",
"."
] | 3ec36d2653a14eb8cc73409fb20889e8484db371 | https://github.com/twitchtv/twirp-ruby/blob/3ec36d2653a14eb8cc73409fb20889e8484db371/lib/twirp/service.rb#L111-L150 | train |
twitchtv/twirp-ruby | lib/twirp/service_dsl.rb | Twirp.ServiceDSL.rpc | def rpc(rpc_method, input_class, output_class, opts)
raise ArgumentError.new("rpc_method can not be empty") if rpc_method.to_s.empty?
raise ArgumentError.new("input_class must be a Protobuf Message class") unless input_class.is_a?(Class)
raise ArgumentError.new("output_class must be a Protobuf Message class") unless output_class.is_a?(Class)
raise ArgumentError.new("opts[:ruby_method] is mandatory") unless opts && opts[:ruby_method]
rpcdef = {
rpc_method: rpc_method.to_sym, # as defined in the Proto file.
input_class: input_class, # google/protobuf Message class to serialize the input (proto request).
output_class: output_class, # google/protobuf Message class to serialize the output (proto response).
ruby_method: opts[:ruby_method].to_sym, # method on the handler or client to handle this rpc requests.
}
@rpcs ||= {}
@rpcs[rpc_method.to_s] = rpcdef
rpc_define_method(rpcdef) if respond_to? :rpc_define_method # hook for the client to implement the methods on the class
end | ruby | def rpc(rpc_method, input_class, output_class, opts)
raise ArgumentError.new("rpc_method can not be empty") if rpc_method.to_s.empty?
raise ArgumentError.new("input_class must be a Protobuf Message class") unless input_class.is_a?(Class)
raise ArgumentError.new("output_class must be a Protobuf Message class") unless output_class.is_a?(Class)
raise ArgumentError.new("opts[:ruby_method] is mandatory") unless opts && opts[:ruby_method]
rpcdef = {
rpc_method: rpc_method.to_sym, # as defined in the Proto file.
input_class: input_class, # google/protobuf Message class to serialize the input (proto request).
output_class: output_class, # google/protobuf Message class to serialize the output (proto response).
ruby_method: opts[:ruby_method].to_sym, # method on the handler or client to handle this rpc requests.
}
@rpcs ||= {}
@rpcs[rpc_method.to_s] = rpcdef
rpc_define_method(rpcdef) if respond_to? :rpc_define_method # hook for the client to implement the methods on the class
end | [
"def",
"rpc",
"(",
"rpc_method",
",",
"input_class",
",",
"output_class",
",",
"opts",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"rpc_method can not be empty\"",
")",
"if",
"rpc_method",
".",
"to_s",
".",
"empty?",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"input_class must be a Protobuf Message class\"",
")",
"unless",
"input_class",
".",
"is_a?",
"(",
"Class",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"output_class must be a Protobuf Message class\"",
")",
"unless",
"output_class",
".",
"is_a?",
"(",
"Class",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"opts[:ruby_method] is mandatory\"",
")",
"unless",
"opts",
"&&",
"opts",
"[",
":ruby_method",
"]",
"rpcdef",
"=",
"{",
"rpc_method",
":",
"rpc_method",
".",
"to_sym",
",",
"# as defined in the Proto file.",
"input_class",
":",
"input_class",
",",
"# google/protobuf Message class to serialize the input (proto request).",
"output_class",
":",
"output_class",
",",
"# google/protobuf Message class to serialize the output (proto response).",
"ruby_method",
":",
"opts",
"[",
":ruby_method",
"]",
".",
"to_sym",
",",
"# method on the handler or client to handle this rpc requests.",
"}",
"@rpcs",
"||=",
"{",
"}",
"@rpcs",
"[",
"rpc_method",
".",
"to_s",
"]",
"=",
"rpcdef",
"rpc_define_method",
"(",
"rpcdef",
")",
"if",
"respond_to?",
":rpc_define_method",
"# hook for the client to implement the methods on the class",
"end"
] | Configure service rpc methods. | [
"Configure",
"service",
"rpc",
"methods",
"."
] | 3ec36d2653a14eb8cc73409fb20889e8484db371 | https://github.com/twitchtv/twirp-ruby/blob/3ec36d2653a14eb8cc73409fb20889e8484db371/lib/twirp/service_dsl.rb#L29-L46 | train |
copiousfreetime/launchy | lib/launchy/descendant_tracker.rb | Launchy.DescendantTracker.find_child | def find_child( method, *args )
children.find do |child|
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
child.send( method, *args )
end
end | ruby | def find_child( method, *args )
children.find do |child|
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
child.send( method, *args )
end
end | [
"def",
"find_child",
"(",
"method",
",",
"*",
"args",
")",
"children",
".",
"find",
"do",
"|",
"child",
"|",
"Launchy",
".",
"log",
"\"Checking if class #{child} is the one for #{method}(#{args.join(', ')})}\"",
"child",
".",
"send",
"(",
"method",
",",
"args",
")",
"end",
"end"
] | Find one of the child classes by calling the given method
and passing all the rest of the parameters to that method in
each child | [
"Find",
"one",
"of",
"the",
"child",
"classes",
"by",
"calling",
"the",
"given",
"method",
"and",
"passing",
"all",
"the",
"rest",
"of",
"the",
"parameters",
"to",
"that",
"method",
"in",
"each",
"child"
] | 7983dbfb48229e909eb3c228c3c205715cab2365 | https://github.com/copiousfreetime/launchy/blob/7983dbfb48229e909eb3c228c3c205715cab2365/lib/launchy/descendant_tracker.rb#L42-L47 | train |
TwP/logging | lib/rspec/logging_helper.rb | RSpec.LoggingHelper.capture_log_messages | def capture_log_messages( opts = {} )
from = opts.fetch(:from, 'root')
to = opts.fetch(:to, '__rspec__')
exclusive = opts.fetch(:exclusive, true)
appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to)
logger = Logging::Logger[from]
if exclusive
logger.appenders = appender
else
logger.add_appenders(appender)
end
before(:all) do
@log_output = Logging::Appenders[to]
end
before(:each) do
@log_output.reset
end
end | ruby | def capture_log_messages( opts = {} )
from = opts.fetch(:from, 'root')
to = opts.fetch(:to, '__rspec__')
exclusive = opts.fetch(:exclusive, true)
appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to)
logger = Logging::Logger[from]
if exclusive
logger.appenders = appender
else
logger.add_appenders(appender)
end
before(:all) do
@log_output = Logging::Appenders[to]
end
before(:each) do
@log_output.reset
end
end | [
"def",
"capture_log_messages",
"(",
"opts",
"=",
"{",
"}",
")",
"from",
"=",
"opts",
".",
"fetch",
"(",
":from",
",",
"'root'",
")",
"to",
"=",
"opts",
".",
"fetch",
"(",
":to",
",",
"'__rspec__'",
")",
"exclusive",
"=",
"opts",
".",
"fetch",
"(",
":exclusive",
",",
"true",
")",
"appender",
"=",
"Logging",
"::",
"Appenders",
"[",
"to",
"]",
"||",
"Logging",
"::",
"Appenders",
"::",
"StringIo",
".",
"new",
"(",
"to",
")",
"logger",
"=",
"Logging",
"::",
"Logger",
"[",
"from",
"]",
"if",
"exclusive",
"logger",
".",
"appenders",
"=",
"appender",
"else",
"logger",
".",
"add_appenders",
"(",
"appender",
")",
"end",
"before",
"(",
":all",
")",
"do",
"@log_output",
"=",
"Logging",
"::",
"Appenders",
"[",
"to",
"]",
"end",
"before",
"(",
":each",
")",
"do",
"@log_output",
".",
"reset",
"end",
"end"
] | Capture log messages from the Logging framework and make them
available via a @log_output instance variable. The @log_output
supports a readline method to access the log messages. | [
"Capture",
"log",
"messages",
"from",
"the",
"Logging",
"framework",
"and",
"make",
"them",
"available",
"via",
"a"
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/rspec/logging_helper.rb#L9-L29 | train |
TwP/logging | lib/logging/repository.rb | Logging.Repository.parent_name | def parent_name( key )
return if :root == key
a = key.split PATH_DELIMITER
p = :root
while a.slice!(-1) and !a.empty?
k = a.join PATH_DELIMITER
if @h.has_key? k then p = k; break end
end
p
end | ruby | def parent_name( key )
return if :root == key
a = key.split PATH_DELIMITER
p = :root
while a.slice!(-1) and !a.empty?
k = a.join PATH_DELIMITER
if @h.has_key? k then p = k; break end
end
p
end | [
"def",
"parent_name",
"(",
"key",
")",
"return",
"if",
":root",
"==",
"key",
"a",
"=",
"key",
".",
"split",
"PATH_DELIMITER",
"p",
"=",
":root",
"while",
"a",
".",
"slice!",
"(",
"-",
"1",
")",
"and",
"!",
"a",
".",
"empty?",
"k",
"=",
"a",
".",
"join",
"PATH_DELIMITER",
"if",
"@h",
".",
"has_key?",
"k",
"then",
"p",
"=",
"k",
";",
"break",
"end",
"end",
"p",
"end"
] | Returns the name of the parent for the logger identified by the given
_key_. If the _key_ is for the root logger, then +nil+ is returned. | [
"Returns",
"the",
"name",
"of",
"the",
"parent",
"for",
"the",
"logger",
"identified",
"by",
"the",
"given",
"_key_",
".",
"If",
"the",
"_key_",
"is",
"for",
"the",
"root",
"logger",
"then",
"+",
"nil",
"+",
"is",
"returned",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/repository.rb#L180-L190 | train |
TwP/logging | lib/logging/appenders/rolling_file.rb | Logging::Appenders.RollingFile.build_singleton_methods | def build_singleton_methods
method =
case @age
when 'daily'
-> {
now = Time.now
(now.day != age_fn_mtime.day) || (now - age_fn_mtime) > 86400
}
when 'weekly'
-> { (Time.now - age_fn_mtime) > 604800 }
when 'monthly'
-> {
now = Time.now
(now.month != age_fn_mtime.month) || (now - age_fn_mtime) > 2678400
}
when Integer, String
@age = Integer(@age)
-> { (Time.now - age_fn_mtime) > @age }
else
-> { false }
end
self.define_singleton_method(:sufficiently_aged?, method)
end | ruby | def build_singleton_methods
method =
case @age
when 'daily'
-> {
now = Time.now
(now.day != age_fn_mtime.day) || (now - age_fn_mtime) > 86400
}
when 'weekly'
-> { (Time.now - age_fn_mtime) > 604800 }
when 'monthly'
-> {
now = Time.now
(now.month != age_fn_mtime.month) || (now - age_fn_mtime) > 2678400
}
when Integer, String
@age = Integer(@age)
-> { (Time.now - age_fn_mtime) > @age }
else
-> { false }
end
self.define_singleton_method(:sufficiently_aged?, method)
end | [
"def",
"build_singleton_methods",
"method",
"=",
"case",
"@age",
"when",
"'daily'",
"->",
"{",
"now",
"=",
"Time",
".",
"now",
"(",
"now",
".",
"day",
"!=",
"age_fn_mtime",
".",
"day",
")",
"||",
"(",
"now",
"-",
"age_fn_mtime",
")",
">",
"86400",
"}",
"when",
"'weekly'",
"->",
"{",
"(",
"Time",
".",
"now",
"-",
"age_fn_mtime",
")",
">",
"604800",
"}",
"when",
"'monthly'",
"->",
"{",
"now",
"=",
"Time",
".",
"now",
"(",
"now",
".",
"month",
"!=",
"age_fn_mtime",
".",
"month",
")",
"||",
"(",
"now",
"-",
"age_fn_mtime",
")",
">",
"2678400",
"}",
"when",
"Integer",
",",
"String",
"@age",
"=",
"Integer",
"(",
"@age",
")",
"->",
"{",
"(",
"Time",
".",
"now",
"-",
"age_fn_mtime",
")",
">",
"@age",
"}",
"else",
"->",
"{",
"false",
"}",
"end",
"self",
".",
"define_singleton_method",
"(",
":sufficiently_aged?",
",",
"method",
")",
"end"
] | We use meta-programming here to define the `sufficiently_aged?` method for
the rolling appender. The `sufficiently_aged?` method is responsible for
determining if the current log file is older than the rolling criteria -
daily, weekly, etc.
Returns this rolling file appender instance | [
"We",
"use",
"meta",
"-",
"programming",
"here",
"to",
"define",
"the",
"sufficiently_aged?",
"method",
"for",
"the",
"rolling",
"appender",
".",
"The",
"sufficiently_aged?",
"method",
"is",
"responsible",
"for",
"determining",
"if",
"the",
"current",
"log",
"file",
"is",
"older",
"than",
"the",
"rolling",
"criteria",
"-",
"daily",
"weekly",
"etc",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appenders/rolling_file.rb#L218-L245 | train |
TwP/logging | lib/logging/appenders/buffering.rb | Logging::Appenders.Buffering.auto_flushing= | def auto_flushing=( period )
@auto_flushing =
case period
when true; 1
when false, nil, 0; DEFAULT_BUFFER_SIZE
when Integer; period
when String; Integer(period)
else
raise ArgumentError,
"unrecognized auto_flushing period: #{period.inspect}"
end
if @auto_flushing <= 0
raise ArgumentError,
"auto_flushing period must be greater than zero: #{period.inspect}"
end
@auto_flushing = DEFAULT_BUFFER_SIZE if @flush_period && @auto_flushing <= 1
end | ruby | def auto_flushing=( period )
@auto_flushing =
case period
when true; 1
when false, nil, 0; DEFAULT_BUFFER_SIZE
when Integer; period
when String; Integer(period)
else
raise ArgumentError,
"unrecognized auto_flushing period: #{period.inspect}"
end
if @auto_flushing <= 0
raise ArgumentError,
"auto_flushing period must be greater than zero: #{period.inspect}"
end
@auto_flushing = DEFAULT_BUFFER_SIZE if @flush_period && @auto_flushing <= 1
end | [
"def",
"auto_flushing",
"=",
"(",
"period",
")",
"@auto_flushing",
"=",
"case",
"period",
"when",
"true",
";",
"1",
"when",
"false",
",",
"nil",
",",
"0",
";",
"DEFAULT_BUFFER_SIZE",
"when",
"Integer",
";",
"period",
"when",
"String",
";",
"Integer",
"(",
"period",
")",
"else",
"raise",
"ArgumentError",
",",
"\"unrecognized auto_flushing period: #{period.inspect}\"",
"end",
"if",
"@auto_flushing",
"<=",
"0",
"raise",
"ArgumentError",
",",
"\"auto_flushing period must be greater than zero: #{period.inspect}\"",
"end",
"@auto_flushing",
"=",
"DEFAULT_BUFFER_SIZE",
"if",
"@flush_period",
"&&",
"@auto_flushing",
"<=",
"1",
"end"
] | Configure the auto-flushing threshold. Auto-flushing is used to flush
the contents of the logging buffer to the logging destination
automatically when the buffer reaches a certain threshold.
By default, the auto-flushing will be configured to flush after each
log message.
The allowed settings are as follows:
N : flush after every N messages (N is an integer)
true : flush after each log message
false OR
nil OR
0 : only flush when the buffer is full (500 messages)
If the default buffer size of 500 is too small, then you can manually
configure it to be as large as you want. This will consume more memory.
auto_flushing = 42_000 | [
"Configure",
"the",
"auto",
"-",
"flushing",
"threshold",
".",
"Auto",
"-",
"flushing",
"is",
"used",
"to",
"flush",
"the",
"contents",
"of",
"the",
"logging",
"buffer",
"to",
"the",
"logging",
"destination",
"automatically",
"when",
"the",
"buffer",
"reaches",
"a",
"certain",
"threshold",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appenders/buffering.rb#L160-L178 | train |
TwP/logging | lib/logging/appenders/buffering.rb | Logging::Appenders.Buffering._setup_async_flusher | def _setup_async_flusher
# stop and remove any existing async flusher instance
if @async_flusher
@async_flusher.stop
@async_flusher = nil
Thread.pass
end
# create a new async flusher if we have a valid flush period
if @flush_period || async?
@auto_flushing = DEFAULT_BUFFER_SIZE unless @auto_flushing > 1
@async_flusher = AsyncFlusher.new(self, @flush_period)
@async_flusher.start
Thread.pass
end
nil
end | ruby | def _setup_async_flusher
# stop and remove any existing async flusher instance
if @async_flusher
@async_flusher.stop
@async_flusher = nil
Thread.pass
end
# create a new async flusher if we have a valid flush period
if @flush_period || async?
@auto_flushing = DEFAULT_BUFFER_SIZE unless @auto_flushing > 1
@async_flusher = AsyncFlusher.new(self, @flush_period)
@async_flusher.start
Thread.pass
end
nil
end | [
"def",
"_setup_async_flusher",
"# stop and remove any existing async flusher instance",
"if",
"@async_flusher",
"@async_flusher",
".",
"stop",
"@async_flusher",
"=",
"nil",
"Thread",
".",
"pass",
"end",
"# create a new async flusher if we have a valid flush period",
"if",
"@flush_period",
"||",
"async?",
"@auto_flushing",
"=",
"DEFAULT_BUFFER_SIZE",
"unless",
"@auto_flushing",
">",
"1",
"@async_flusher",
"=",
"AsyncFlusher",
".",
"new",
"(",
"self",
",",
"@flush_period",
")",
"@async_flusher",
".",
"start",
"Thread",
".",
"pass",
"end",
"nil",
"end"
] | Using the flush_period, create a new AsyncFlusher attached to this
appender. If the flush_period is nil, then no action will be taken. If a
AsyncFlusher already exists, it will be stopped and a new one will be
created.
Returns `nil` | [
"Using",
"the",
"flush_period",
"create",
"a",
"new",
"AsyncFlusher",
"attached",
"to",
"this",
"appender",
".",
"If",
"the",
"flush_period",
"is",
"nil",
"then",
"no",
"action",
"will",
"be",
"taken",
".",
"If",
"a",
"AsyncFlusher",
"already",
"exists",
"it",
"will",
"be",
"stopped",
"and",
"a",
"new",
"one",
"will",
"be",
"created",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appenders/buffering.rb#L347-L364 | train |
TwP/logging | lib/logging/color_scheme.rb | Logging.ColorScheme.[]= | def []=( color_tag, constants )
@scheme[to_key(color_tag)] = constants.respond_to?(:map) ?
constants.map { |c| to_constant(c) }.join : to_constant(constants)
end | ruby | def []=( color_tag, constants )
@scheme[to_key(color_tag)] = constants.respond_to?(:map) ?
constants.map { |c| to_constant(c) }.join : to_constant(constants)
end | [
"def",
"[]=",
"(",
"color_tag",
",",
"constants",
")",
"@scheme",
"[",
"to_key",
"(",
"color_tag",
")",
"]",
"=",
"constants",
".",
"respond_to?",
"(",
":map",
")",
"?",
"constants",
".",
"map",
"{",
"|",
"c",
"|",
"to_constant",
"(",
"c",
")",
"}",
".",
"join",
":",
"to_constant",
"(",
"constants",
")",
"end"
] | Allow the scheme to be set like a Hash. | [
"Allow",
"the",
"scheme",
"to",
"be",
"set",
"like",
"a",
"Hash",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/color_scheme.rb#L172-L175 | train |
TwP/logging | lib/logging/color_scheme.rb | Logging.ColorScheme.to_constant | def to_constant( v )
v = v.to_s.upcase
ColorScheme.const_get(v) if (ColorScheme.const_defined?(v, false) rescue ColorScheme.const_defined?(v))
end | ruby | def to_constant( v )
v = v.to_s.upcase
ColorScheme.const_get(v) if (ColorScheme.const_defined?(v, false) rescue ColorScheme.const_defined?(v))
end | [
"def",
"to_constant",
"(",
"v",
")",
"v",
"=",
"v",
".",
"to_s",
".",
"upcase",
"ColorScheme",
".",
"const_get",
"(",
"v",
")",
"if",
"(",
"ColorScheme",
".",
"const_defined?",
"(",
"v",
",",
"false",
")",
"rescue",
"ColorScheme",
".",
"const_defined?",
"(",
"v",
")",
")",
"end"
] | Return a normalized representation of a color setting. | [
"Return",
"a",
"normalized",
"representation",
"of",
"a",
"color",
"setting",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/color_scheme.rb#L206-L209 | train |
TwP/logging | lib/logging/appender.rb | Logging.Appender.encoding= | def encoding=( value )
if value.nil?
@encoding = nil
else
@encoding = Object.const_defined?(:Encoding) ? Encoding.find(value.to_s) : nil
end
end | ruby | def encoding=( value )
if value.nil?
@encoding = nil
else
@encoding = Object.const_defined?(:Encoding) ? Encoding.find(value.to_s) : nil
end
end | [
"def",
"encoding",
"=",
"(",
"value",
")",
"if",
"value",
".",
"nil?",
"@encoding",
"=",
"nil",
"else",
"@encoding",
"=",
"Object",
".",
"const_defined?",
"(",
":Encoding",
")",
"?",
"Encoding",
".",
"find",
"(",
"value",
".",
"to_s",
")",
":",
"nil",
"end",
"end"
] | Set the appender encoding to the given value. The value can either be an
Encoding instance or a String or Symbol referring to a valid encoding.
This method only applies to Ruby 1.9 or later. The encoding will always be
nil for older Rubies.
value - The encoding as a String, Symbol, or Encoding instance.
Raises ArgumentError if the value is not a valid encoding. | [
"Set",
"the",
"appender",
"encoding",
"to",
"the",
"given",
"value",
".",
"The",
"value",
"can",
"either",
"be",
"an",
"Encoding",
"instance",
"or",
"a",
"String",
"or",
"Symbol",
"referring",
"to",
"a",
"valid",
"encoding",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appender.rb#L283-L289 | train |
TwP/logging | lib/logging/appender.rb | Logging.Appender.allow | def allow( event )
return nil if @level > event.level
@filters.each do |filter|
break unless event = filter.allow(event)
end
event
end | ruby | def allow( event )
return nil if @level > event.level
@filters.each do |filter|
break unless event = filter.allow(event)
end
event
end | [
"def",
"allow",
"(",
"event",
")",
"return",
"nil",
"if",
"@level",
">",
"event",
".",
"level",
"@filters",
".",
"each",
"do",
"|",
"filter",
"|",
"break",
"unless",
"event",
"=",
"filter",
".",
"allow",
"(",
"event",
")",
"end",
"event",
"end"
] | Check to see if the event should be processed by the appender. An event will
be rejected if the event level is lower than the configured level for the
appender. Or it will be rejected if one of the filters rejects the event.
event - The LogEvent to check
Returns the event if it is allowed; returns `nil` if it is not allowed. | [
"Check",
"to",
"see",
"if",
"the",
"event",
"should",
"be",
"processed",
"by",
"the",
"appender",
".",
"An",
"event",
"will",
"be",
"rejected",
"if",
"the",
"event",
"level",
"is",
"lower",
"than",
"the",
"configured",
"level",
"for",
"the",
"appender",
".",
"Or",
"it",
"will",
"be",
"rejected",
"if",
"one",
"of",
"the",
"filters",
"rejects",
"the",
"event",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/appender.rb#L298-L304 | train |
TwP/logging | lib/logging/diagnostic_context.rb | Logging.MappedDiagnosticContext.context | def context
c = Thread.current.thread_variable_get(NAME)
if c.nil?
c = if Thread.current.thread_variable_get(STACK_NAME)
flatten(stack)
else
Hash.new
end
Thread.current.thread_variable_set(NAME, c)
end
return c
end | ruby | def context
c = Thread.current.thread_variable_get(NAME)
if c.nil?
c = if Thread.current.thread_variable_get(STACK_NAME)
flatten(stack)
else
Hash.new
end
Thread.current.thread_variable_set(NAME, c)
end
return c
end | [
"def",
"context",
"c",
"=",
"Thread",
".",
"current",
".",
"thread_variable_get",
"(",
"NAME",
")",
"if",
"c",
".",
"nil?",
"c",
"=",
"if",
"Thread",
".",
"current",
".",
"thread_variable_get",
"(",
"STACK_NAME",
")",
"flatten",
"(",
"stack",
")",
"else",
"Hash",
".",
"new",
"end",
"Thread",
".",
"current",
".",
"thread_variable_set",
"(",
"NAME",
",",
"c",
")",
"end",
"return",
"c",
"end"
] | Returns the Hash acting as the storage for this MappedDiagnosticContext.
A new storage Hash is created for each Thread running in the
application. | [
"Returns",
"the",
"Hash",
"acting",
"as",
"the",
"storage",
"for",
"this",
"MappedDiagnosticContext",
".",
"A",
"new",
"storage",
"Hash",
"is",
"created",
"for",
"each",
"Thread",
"running",
"in",
"the",
"application",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L160-L173 | train |
TwP/logging | lib/logging/diagnostic_context.rb | Logging.MappedDiagnosticContext.stack | def stack
s = Thread.current.thread_variable_get(STACK_NAME)
if s.nil?
s = [{}]
Thread.current.thread_variable_set(STACK_NAME, s)
end
return s
end | ruby | def stack
s = Thread.current.thread_variable_get(STACK_NAME)
if s.nil?
s = [{}]
Thread.current.thread_variable_set(STACK_NAME, s)
end
return s
end | [
"def",
"stack",
"s",
"=",
"Thread",
".",
"current",
".",
"thread_variable_get",
"(",
"STACK_NAME",
")",
"if",
"s",
".",
"nil?",
"s",
"=",
"[",
"{",
"}",
"]",
"Thread",
".",
"current",
".",
"thread_variable_set",
"(",
"STACK_NAME",
",",
"s",
")",
"end",
"return",
"s",
"end"
] | Returns the stack of Hash objects that are storing the diagnostic
context information. This stack is guarnteed to always contain at least
one Hash. | [
"Returns",
"the",
"stack",
"of",
"Hash",
"objects",
"that",
"are",
"storing",
"the",
"diagnostic",
"context",
"information",
".",
"This",
"stack",
"is",
"guarnteed",
"to",
"always",
"contain",
"at",
"least",
"one",
"Hash",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L179-L186 | train |
TwP/logging | lib/logging/diagnostic_context.rb | Logging.MappedDiagnosticContext.sanitize | def sanitize( hash, target = {} )
unless hash.is_a?(Hash)
raise ArgumentError, "Expecting a Hash but received a #{hash.class.name}"
end
hash.each { |k,v| target[k.to_s] = v }
return target
end | ruby | def sanitize( hash, target = {} )
unless hash.is_a?(Hash)
raise ArgumentError, "Expecting a Hash but received a #{hash.class.name}"
end
hash.each { |k,v| target[k.to_s] = v }
return target
end | [
"def",
"sanitize",
"(",
"hash",
",",
"target",
"=",
"{",
"}",
")",
"unless",
"hash",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"ArgumentError",
",",
"\"Expecting a Hash but received a #{hash.class.name}\"",
"end",
"hash",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"target",
"[",
"k",
".",
"to_s",
"]",
"=",
"v",
"}",
"return",
"target",
"end"
] | Given a Hash convert all keys into Strings. The values are not altered
in any way. The converted keys and their values are stored in the target
Hash if provided. Otherwise a new Hash is created and returned.
hash - The Hash of values to push onto the context stack.
target - The target Hash to store the key value pairs.
Returns a new Hash with all keys converted to Strings.
Raises an ArgumentError if hash is not a Hash. | [
"Given",
"a",
"Hash",
"convert",
"all",
"keys",
"into",
"Strings",
".",
"The",
"values",
"are",
"not",
"altered",
"in",
"any",
"way",
".",
"The",
"converted",
"keys",
"and",
"their",
"values",
"are",
"stored",
"in",
"the",
"target",
"Hash",
"if",
"provided",
".",
"Otherwise",
"a",
"new",
"Hash",
"is",
"created",
"and",
"returned",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L211-L218 | train |
TwP/logging | lib/logging/diagnostic_context.rb | Logging.NestedDiagnosticContext.context | def context
c = Thread.current.thread_variable_get(NAME)
if c.nil?
c = Array.new
Thread.current.thread_variable_set(NAME, c)
end
return c
end | ruby | def context
c = Thread.current.thread_variable_get(NAME)
if c.nil?
c = Array.new
Thread.current.thread_variable_set(NAME, c)
end
return c
end | [
"def",
"context",
"c",
"=",
"Thread",
".",
"current",
".",
"thread_variable_get",
"(",
"NAME",
")",
"if",
"c",
".",
"nil?",
"c",
"=",
"Array",
".",
"new",
"Thread",
".",
"current",
".",
"thread_variable_set",
"(",
"NAME",
",",
"c",
")",
"end",
"return",
"c",
"end"
] | Returns the Array acting as the storage stack for this
NestedDiagnosticContext. A new storage Array is created for each Thread
running in the application. | [
"Returns",
"the",
"Array",
"acting",
"as",
"the",
"storage",
"stack",
"for",
"this",
"NestedDiagnosticContext",
".",
"A",
"new",
"storage",
"Array",
"is",
"created",
"for",
"each",
"Thread",
"running",
"in",
"the",
"application",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/diagnostic_context.rb#L363-L370 | train |
TwP/logging | lib/logging/layouts/parseable.rb | Logging::Layouts.Parseable.iso8601_format | def iso8601_format( time )
value = apply_utc_offset(time)
str = value.strftime('%Y-%m-%dT%H:%M:%S')
str << ('.%06d' % value.usec)
offset = value.gmt_offset.abs
return str << 'Z' if offset == 0
offset = sprintf('%02d:%02d', offset / 3600, offset % 3600 / 60)
return str << (value.gmt_offset < 0 ? '-' : '+') << offset
end | ruby | def iso8601_format( time )
value = apply_utc_offset(time)
str = value.strftime('%Y-%m-%dT%H:%M:%S')
str << ('.%06d' % value.usec)
offset = value.gmt_offset.abs
return str << 'Z' if offset == 0
offset = sprintf('%02d:%02d', offset / 3600, offset % 3600 / 60)
return str << (value.gmt_offset < 0 ? '-' : '+') << offset
end | [
"def",
"iso8601_format",
"(",
"time",
")",
"value",
"=",
"apply_utc_offset",
"(",
"time",
")",
"str",
"=",
"value",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S'",
")",
"str",
"<<",
"(",
"'.%06d'",
"%",
"value",
".",
"usec",
")",
"offset",
"=",
"value",
".",
"gmt_offset",
".",
"abs",
"return",
"str",
"<<",
"'Z'",
"if",
"offset",
"==",
"0",
"offset",
"=",
"sprintf",
"(",
"'%02d:%02d'",
",",
"offset",
"/",
"3600",
",",
"offset",
"%",
"3600",
"/",
"60",
")",
"return",
"str",
"<<",
"(",
"value",
".",
"gmt_offset",
"<",
"0",
"?",
"'-'",
":",
"'+'",
")",
"<<",
"offset",
"end"
] | Convert the given `time` into an ISO8601 formatted time string. | [
"Convert",
"the",
"given",
"time",
"into",
"an",
"ISO8601",
"formatted",
"time",
"string",
"."
] | aa9a5b840479f4176504e4c53ce29d8d01315ccc | https://github.com/TwP/logging/blob/aa9a5b840479f4176504e4c53ce29d8d01315ccc/lib/logging/layouts/parseable.rb#L283-L294 | train |
cfndsl/cfndsl | lib/cfndsl/jsonable.rb | CfnDsl.JSONable.as_json | def as_json(_options = {})
hash = {}
instance_variables.each do |var|
name = var[1..-1]
if name =~ /^__/
# if a variable starts with double underscore, strip one off
name = name[1..-1]
elsif name =~ /^_/
# Hide variables that start with single underscore
name = nil
end
hash[name] = instance_variable_get(var) if name
end
hash
end | ruby | def as_json(_options = {})
hash = {}
instance_variables.each do |var|
name = var[1..-1]
if name =~ /^__/
# if a variable starts with double underscore, strip one off
name = name[1..-1]
elsif name =~ /^_/
# Hide variables that start with single underscore
name = nil
end
hash[name] = instance_variable_get(var) if name
end
hash
end | [
"def",
"as_json",
"(",
"_options",
"=",
"{",
"}",
")",
"hash",
"=",
"{",
"}",
"instance_variables",
".",
"each",
"do",
"|",
"var",
"|",
"name",
"=",
"var",
"[",
"1",
"..",
"-",
"1",
"]",
"if",
"name",
"=~",
"/",
"/",
"# if a variable starts with double underscore, strip one off",
"name",
"=",
"name",
"[",
"1",
"..",
"-",
"1",
"]",
"elsif",
"name",
"=~",
"/",
"/",
"# Hide variables that start with single underscore",
"name",
"=",
"nil",
"end",
"hash",
"[",
"name",
"]",
"=",
"instance_variable_get",
"(",
"var",
")",
"if",
"name",
"end",
"hash",
"end"
] | Use instance variables to build a json object. Instance
variables that begin with a single underscore are elided.
Instance variables that begin with two underscores have one of
them removed. | [
"Use",
"instance",
"variables",
"to",
"build",
"a",
"json",
"object",
".",
"Instance",
"variables",
"that",
"begin",
"with",
"a",
"single",
"underscore",
"are",
"elided",
".",
"Instance",
"variables",
"that",
"begin",
"with",
"two",
"underscores",
"have",
"one",
"of",
"them",
"removed",
"."
] | 785fb272728e0c44f0ddb10393dd56dd84f018af | https://github.com/cfndsl/cfndsl/blob/785fb272728e0c44f0ddb10393dd56dd84f018af/lib/cfndsl/jsonable.rb#L177-L193 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/broadcasts.rb | OpenTok.Broadcasts.find | def find(broadcast_id)
raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty?
broadcast_json = @client.get_broadcast(broadcast_id.to_s)
Broadcast.new self, broadcast_json
end | ruby | def find(broadcast_id)
raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty?
broadcast_json = @client.get_broadcast(broadcast_id.to_s)
Broadcast.new self, broadcast_json
end | [
"def",
"find",
"(",
"broadcast_id",
")",
"raise",
"ArgumentError",
",",
"\"broadcast_id not provided\"",
"if",
"broadcast_id",
".",
"to_s",
".",
"empty?",
"broadcast_json",
"=",
"@client",
".",
"get_broadcast",
"(",
"broadcast_id",
".",
"to_s",
")",
"Broadcast",
".",
"new",
"self",
",",
"broadcast_json",
"end"
] | Gets a Broadcast object for the given broadcast ID.
@param [String] broadcast_id The broadcast ID.
@return [Broadcast] The broadcast object, which includes properties defining the broadcast.
@raise [OpenTokBroadcastError] No matching broadcast found.
@raise [OpenTokAuthenticationError] Authentication failed.
Invalid API key.
@raise [OpenTokError] OpenTok server error. | [
"Gets",
"a",
"Broadcast",
"object",
"for",
"the",
"given",
"broadcast",
"ID",
"."
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/broadcasts.rb#L75-L79 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/broadcasts.rb | OpenTok.Broadcasts.stop | def stop(broadcast_id)
raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty?
broadcast_json = @client.stop_broadcast(broadcast_id)
Broadcast.new self, broadcast_json
end | ruby | def stop(broadcast_id)
raise ArgumentError, "broadcast_id not provided" if broadcast_id.to_s.empty?
broadcast_json = @client.stop_broadcast(broadcast_id)
Broadcast.new self, broadcast_json
end | [
"def",
"stop",
"(",
"broadcast_id",
")",
"raise",
"ArgumentError",
",",
"\"broadcast_id not provided\"",
"if",
"broadcast_id",
".",
"to_s",
".",
"empty?",
"broadcast_json",
"=",
"@client",
".",
"stop_broadcast",
"(",
"broadcast_id",
")",
"Broadcast",
".",
"new",
"self",
",",
"broadcast_json",
"end"
] | Stops an OpenTok broadcast
Note that broadcasts automatically stop after 120 minute
@param [String] broadcast_id The broadcast ID.
@return [Broadcast] The broadcast object, which includes properties defining the broadcast.
@raise [OpenTokBroadcastError] The broadcast could not be stopped. The request was invalid.
@raise [OpenTokAuthenticationError] Authentication failed.
Invalid API key.
@raise [OpenTokError] OpenTok server error. | [
"Stops",
"an",
"OpenTok",
"broadcast"
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/broadcasts.rb#L94-L98 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/opentok.rb | OpenTok.OpenTok.create_session | def create_session(opts={})
# normalize opts so all keys are symbols and only include valid_opts
valid_opts = [ :media_mode, :location, :archive_mode ]
opts = opts.inject({}) do |m,(k,v)|
if valid_opts.include? k.to_sym
m[k.to_sym] = v
end
m
end
# keep opts around for Session constructor, build REST params
params = opts.clone
# anything other than :relayed sets the REST param to "disabled", in which case we force
# opts to be :routed. if we were more strict we could raise an error when the value isn't
# either :relayed or :routed
if params.delete(:media_mode) == :routed
params["p2p.preference"] = "disabled"
else
params["p2p.preference"] = "enabled"
opts[:media_mode] = :relayed
end
# location is optional, but it has to be an IP address if specified at all
unless params[:location].nil?
raise "location must be an IPv4 address" unless params[:location] =~ Resolv::IPv4::Regex
end
# archive mode is optional, but it has to be one of the valid values if present
unless params[:archive_mode].nil?
raise "archive mode must be either always or manual" unless ARCHIVE_MODES.include? params[:archive_mode].to_sym
end
raise "A session with always archive mode must also have the routed media mode." if (params[:archive_mode] == :always && params[:media_mode] == :relayed)
response = client.create_session(params)
Session.new api_key, api_secret, response['sessions']['Session']['session_id'], opts
end | ruby | def create_session(opts={})
# normalize opts so all keys are symbols and only include valid_opts
valid_opts = [ :media_mode, :location, :archive_mode ]
opts = opts.inject({}) do |m,(k,v)|
if valid_opts.include? k.to_sym
m[k.to_sym] = v
end
m
end
# keep opts around for Session constructor, build REST params
params = opts.clone
# anything other than :relayed sets the REST param to "disabled", in which case we force
# opts to be :routed. if we were more strict we could raise an error when the value isn't
# either :relayed or :routed
if params.delete(:media_mode) == :routed
params["p2p.preference"] = "disabled"
else
params["p2p.preference"] = "enabled"
opts[:media_mode] = :relayed
end
# location is optional, but it has to be an IP address if specified at all
unless params[:location].nil?
raise "location must be an IPv4 address" unless params[:location] =~ Resolv::IPv4::Regex
end
# archive mode is optional, but it has to be one of the valid values if present
unless params[:archive_mode].nil?
raise "archive mode must be either always or manual" unless ARCHIVE_MODES.include? params[:archive_mode].to_sym
end
raise "A session with always archive mode must also have the routed media mode." if (params[:archive_mode] == :always && params[:media_mode] == :relayed)
response = client.create_session(params)
Session.new api_key, api_secret, response['sessions']['Session']['session_id'], opts
end | [
"def",
"create_session",
"(",
"opts",
"=",
"{",
"}",
")",
"# normalize opts so all keys are symbols and only include valid_opts",
"valid_opts",
"=",
"[",
":media_mode",
",",
":location",
",",
":archive_mode",
"]",
"opts",
"=",
"opts",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"m",
",",
"(",
"k",
",",
"v",
")",
"|",
"if",
"valid_opts",
".",
"include?",
"k",
".",
"to_sym",
"m",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"end",
"m",
"end",
"# keep opts around for Session constructor, build REST params",
"params",
"=",
"opts",
".",
"clone",
"# anything other than :relayed sets the REST param to \"disabled\", in which case we force",
"# opts to be :routed. if we were more strict we could raise an error when the value isn't",
"# either :relayed or :routed",
"if",
"params",
".",
"delete",
"(",
":media_mode",
")",
"==",
":routed",
"params",
"[",
"\"p2p.preference\"",
"]",
"=",
"\"disabled\"",
"else",
"params",
"[",
"\"p2p.preference\"",
"]",
"=",
"\"enabled\"",
"opts",
"[",
":media_mode",
"]",
"=",
":relayed",
"end",
"# location is optional, but it has to be an IP address if specified at all",
"unless",
"params",
"[",
":location",
"]",
".",
"nil?",
"raise",
"\"location must be an IPv4 address\"",
"unless",
"params",
"[",
":location",
"]",
"=~",
"Resolv",
"::",
"IPv4",
"::",
"Regex",
"end",
"# archive mode is optional, but it has to be one of the valid values if present",
"unless",
"params",
"[",
":archive_mode",
"]",
".",
"nil?",
"raise",
"\"archive mode must be either always or manual\"",
"unless",
"ARCHIVE_MODES",
".",
"include?",
"params",
"[",
":archive_mode",
"]",
".",
"to_sym",
"end",
"raise",
"\"A session with always archive mode must also have the routed media mode.\"",
"if",
"(",
"params",
"[",
":archive_mode",
"]",
"==",
":always",
"&&",
"params",
"[",
":media_mode",
"]",
"==",
":relayed",
")",
"response",
"=",
"client",
".",
"create_session",
"(",
"params",
")",
"Session",
".",
"new",
"api_key",
",",
"api_secret",
",",
"response",
"[",
"'sessions'",
"]",
"[",
"'Session'",
"]",
"[",
"'session_id'",
"]",
",",
"opts",
"end"
] | Create a new OpenTok object.
@param [String] api_key The OpenTok API key for your
{https://tokbox.com/account OpenTok project}.
@param [String] api_secret Your OpenTok API key.
@option opts [Symbol] :api_url Do not set this parameter. It is for internal use by TokBox.
@option opts [Symbol] :ua_addendum Do not set this parameter. It is for internal use by TokBox.
Creates a new OpenTok session and returns the session ID, which uniquely identifies
the session.
For example, when using the OpenTok JavaScript library, use the session ID when calling the
OT.initSession()</a> method (to initialize an OpenTok session).
OpenTok sessions do not expire. However, authentication tokens do expire (see the
generateToken() method). Also note that sessions cannot explicitly be destroyed.
A session ID string can be up to 255 characters long.
Calling this method results in an OpenTokException in the event of an error.
Check the error message for details.
You can also create a session using the OpenTok REST API (see
http://www.tokbox.com/opentok/api/#session_id_production) or at your
{https://tokbox.com/account OpenTok account page}.
@param [Hash] opts (Optional) This hash defines options for the session.
@option opts [Symbol] :media_mode Determines whether the session will transmit streams the
using OpenTok Media Router (<code>:routed</code>) or not (<code>:relayed</code>).
By default, this property is set to <code>:relayed</code>.
With the <code>media_mode</code> property set to <code>:relayed</code>, the session
will attempt to transmit streams directly between clients. If clients cannot connect due to
firewall restrictions, the session uses the OpenTok TURN server to relay audio-video
streams.
With the <code>media_mode</code> property set to <code>:routed</code>, the session will use
the {https://tokbox.com/opentok/tutorials/create-session/#media-mode OpenTok Media Router}.
The OpenTok Media Router provides the following benefits:
* The OpenTok Media Router can decrease bandwidth usage in multiparty sessions.
(When the <code>media_mode</code> property is set to <code>:relayed</code>,
each client must send a separate audio-video stream to each client subscribing to
it.)
* The OpenTok Media Router can improve the quality of the user experience through
{https://tokbox.com/platform/fallback audio fallback and video recovery}. With
these features, if a client's connectivity degrades to a degree that
it does not support video for a stream it's subscribing to, the video is dropped on
that client (without affecting other clients), and the client receives audio only.
If the client's connectivity improves, the video returns.
* The OpenTok Media Router supports the
{https://tokbox.com/opentok/tutorials/archiving archiving}
feature, which lets you record, save, and retrieve OpenTok sessions.
@option opts [String] :location An IP address that the OpenTok servers will use to
situate the session in its global network. If you do not set a location hint,
the OpenTok servers will be based on the first client connecting to the session.
@option opts [Symbol] :archive_mode Determines whether the session will be archived
automatically (<code>:always</code>) or not (<code>:manual</code>). When using automatic
archiving, the session must use the <code>:routed</code> media mode.
@return [Session] The Session object. The session_id property of the object is the session ID. | [
"Create",
"a",
"new",
"OpenTok",
"object",
"."
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/opentok.rb#L145-L181 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/streams.rb | OpenTok.Streams.all | def all(session_id)
raise ArgumentError, 'session_id not provided' if session_id.to_s.empty?
response_json = @client.info_stream(session_id, '')
StreamList.new response_json
end | ruby | def all(session_id)
raise ArgumentError, 'session_id not provided' if session_id.to_s.empty?
response_json = @client.info_stream(session_id, '')
StreamList.new response_json
end | [
"def",
"all",
"(",
"session_id",
")",
"raise",
"ArgumentError",
",",
"'session_id not provided'",
"if",
"session_id",
".",
"to_s",
".",
"empty?",
"response_json",
"=",
"@client",
".",
"info_stream",
"(",
"session_id",
",",
"''",
")",
"StreamList",
".",
"new",
"response_json",
"end"
] | Use this method to get information on all OpenTok streams in a session.
For example, you can call this method to get information about layout classes used by OpenTok streams.
The layout classes define how the stream is displayed in the layout of a live streaming
broadcast or a composed archive. For more information, see
{https://tokbox.com/developer/guides/broadcast/live-streaming/#assign-layout-classes-to-streams Assigning layout classes to streams in live streaming broadcasts}
and {https://tokbox.com/developer/guides/archiving/layout-control.html Customizing the video layout for composed archives}.
@param [String] session_id The session ID of the OpenTok session.
@return [StreamList] The StreamList of Stream objects.
@raise [ArgumentError] The stream_id or session_id is invalid.
@raise [OpenTokAuthenticationError] You are not authorized to fetch the stream information. Check your authentication credentials.
@raise [OpenTokError] An OpenTok server error. | [
"Use",
"this",
"method",
"to",
"get",
"information",
"on",
"all",
"OpenTok",
"streams",
"in",
"a",
"session",
"."
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/streams.rb#L49-L53 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/archives.rb | OpenTok.Archives.find | def find(archive_id)
raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
archive_json = @client.get_archive(archive_id.to_s)
Archive.new self, archive_json
end | ruby | def find(archive_id)
raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
archive_json = @client.get_archive(archive_id.to_s)
Archive.new self, archive_json
end | [
"def",
"find",
"(",
"archive_id",
")",
"raise",
"ArgumentError",
",",
"\"archive_id not provided\"",
"if",
"archive_id",
".",
"to_s",
".",
"empty?",
"archive_json",
"=",
"@client",
".",
"get_archive",
"(",
"archive_id",
".",
"to_s",
")",
"Archive",
".",
"new",
"self",
",",
"archive_json",
"end"
] | Gets an Archive object for the given archive ID.
@param [String] archive_id The archive ID.
@return [Archive] The Archive object.
@raise [OpenTokArchiveError] The archive could not be retrieved. The archive ID is invalid.
@raise [OpenTokAuthenticationError] Authentication failed while retrieving the archive.
Invalid API key.
@raise [OpenTokArchiveError] The archive could not be retrieved. | [
"Gets",
"an",
"Archive",
"object",
"for",
"the",
"given",
"archive",
"ID",
"."
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L90-L94 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/archives.rb | OpenTok.Archives.all | def all(options = {})
raise ArgumentError, "Limit is invalid" unless options[:count].nil? or (0..1000).include? options[:count]
archive_list_json = @client.list_archives(options[:offset], options[:count], options[:sessionId])
ArchiveList.new self, archive_list_json
end | ruby | def all(options = {})
raise ArgumentError, "Limit is invalid" unless options[:count].nil? or (0..1000).include? options[:count]
archive_list_json = @client.list_archives(options[:offset], options[:count], options[:sessionId])
ArchiveList.new self, archive_list_json
end | [
"def",
"all",
"(",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"Limit is invalid\"",
"unless",
"options",
"[",
":count",
"]",
".",
"nil?",
"or",
"(",
"0",
"..",
"1000",
")",
".",
"include?",
"options",
"[",
":count",
"]",
"archive_list_json",
"=",
"@client",
".",
"list_archives",
"(",
"options",
"[",
":offset",
"]",
",",
"options",
"[",
":count",
"]",
",",
"options",
"[",
":sessionId",
"]",
")",
"ArchiveList",
".",
"new",
"self",
",",
"archive_list_json",
"end"
] | Returns an ArchiveList, which is an array of archives that are completed and in-progress,
for your API key.
@param [Hash] options A hash with keys defining which range of archives to retrieve.
@option options [integer] :offset Optional. The index offset of the first archive. 0 is offset
of the most recently started archive. 1 is the offset of the archive that started prior to
the most recent archive. If you do not specify an offset, 0 is used.
@option options [integer] :count Optional. The number of archives to be returned. The maximum
number of archives returned is 1000.
@option options [String] :session_id Optional. The session ID that archives belong to. This is
useful when listing multiple archives for an {https://tokbox.com/developer/guides/archiving/#automatic-archives automatically archived session}.
@return [ArchiveList] An ArchiveList object, which is an array of Archive objects. | [
"Returns",
"an",
"ArchiveList",
"which",
"is",
"an",
"array",
"of",
"archives",
"that",
"are",
"completed",
"and",
"in",
"-",
"progress",
"for",
"your",
"API",
"key",
"."
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L109-L113 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/archives.rb | OpenTok.Archives.stop_by_id | def stop_by_id(archive_id)
raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
archive_json = @client.stop_archive(archive_id)
Archive.new self, archive_json
end | ruby | def stop_by_id(archive_id)
raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
archive_json = @client.stop_archive(archive_id)
Archive.new self, archive_json
end | [
"def",
"stop_by_id",
"(",
"archive_id",
")",
"raise",
"ArgumentError",
",",
"\"archive_id not provided\"",
"if",
"archive_id",
".",
"to_s",
".",
"empty?",
"archive_json",
"=",
"@client",
".",
"stop_archive",
"(",
"archive_id",
")",
"Archive",
".",
"new",
"self",
",",
"archive_json",
"end"
] | Stops an OpenTok archive that is being recorded.
Archives automatically stop recording after 120 minutes or when all clients have disconnected
from the session being archived.
@param [String] archive_id The archive ID of the archive you want to stop recording.
@return [Archive] The Archive object corresponding to the archive being stopped.
@raise [OpenTokArchiveError] The archive could not be stopped. The request was invalid.
@raise [OpenTokAuthenticationError] Authentication failed while stopping an archive.
@raise [OpenTokArchiveError] The archive could not be stopped. The archive ID does not exist.
@raise [OpenTokArchiveError] The archive could not be stopped. The archive is not currently
recording.
@raise [OpenTokArchiveError] The archive could not be started. | [
"Stops",
"an",
"OpenTok",
"archive",
"that",
"is",
"being",
"recorded",
"."
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L130-L134 | train |
opentok/OpenTok-Ruby-SDK | lib/opentok/archives.rb | OpenTok.Archives.delete_by_id | def delete_by_id(archive_id)
raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
response = @client.delete_archive(archive_id)
(200..300).include? response.code
end | ruby | def delete_by_id(archive_id)
raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
response = @client.delete_archive(archive_id)
(200..300).include? response.code
end | [
"def",
"delete_by_id",
"(",
"archive_id",
")",
"raise",
"ArgumentError",
",",
"\"archive_id not provided\"",
"if",
"archive_id",
".",
"to_s",
".",
"empty?",
"response",
"=",
"@client",
".",
"delete_archive",
"(",
"archive_id",
")",
"(",
"200",
"..",
"300",
")",
".",
"include?",
"response",
".",
"code",
"end"
] | Deletes an OpenTok archive.
You can only delete an archive which has a status of "available", "uploaded", or "deleted".
Deleting an archive removes its record from the list of archives. For an "available" archive,
it also removes the archive file, making it unavailable for download. For a "deleted"
archive, the archive remains deleted.
@param [String] archive_id The archive ID of the archive you want to delete.
@raise [OpenTokAuthenticationError] Authentication failed or an invalid archive ID was given.
@raise [OpenTokArchiveError] The archive could not be deleted. The status must be
'available', 'deleted', or 'uploaded'.
@raise [OpenTokArchiveError] The archive could not be deleted. | [
"Deletes",
"an",
"OpenTok",
"archive",
"."
] | dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd | https://github.com/opentok/OpenTok-Ruby-SDK/blob/dfa22dc77d93e4493f48e4ef4c6ea62e58ea8cfd/lib/opentok/archives.rb#L149-L153 | train |
email-spec/email-spec | lib/email_spec/helpers.rb | EmailSpec.Helpers.find_email | def find_email(address, opts={})
address = convert_address(address)
if opts[:with_subject]
expected_subject = (opts[:with_subject].is_a?(String) ? Regexp.escape(opts[:with_subject]) : opts[:with_subject])
mailbox_for(address).find { |m| m.subject =~ Regexp.new(expected_subject) }
elsif opts[:with_text]
expected_text = (opts[:with_text].is_a?(String) ? Regexp.escape(opts[:with_text]) : opts[:with_text])
mailbox_for(address).find { |m| m.default_part_body =~ Regexp.new(expected_text) }
elsif opts[:from]
mailbox_for(address).find { |m| m.from.include? opts[:from] }
else
mailbox_for(address).first
end
end | ruby | def find_email(address, opts={})
address = convert_address(address)
if opts[:with_subject]
expected_subject = (opts[:with_subject].is_a?(String) ? Regexp.escape(opts[:with_subject]) : opts[:with_subject])
mailbox_for(address).find { |m| m.subject =~ Regexp.new(expected_subject) }
elsif opts[:with_text]
expected_text = (opts[:with_text].is_a?(String) ? Regexp.escape(opts[:with_text]) : opts[:with_text])
mailbox_for(address).find { |m| m.default_part_body =~ Regexp.new(expected_text) }
elsif opts[:from]
mailbox_for(address).find { |m| m.from.include? opts[:from] }
else
mailbox_for(address).first
end
end | [
"def",
"find_email",
"(",
"address",
",",
"opts",
"=",
"{",
"}",
")",
"address",
"=",
"convert_address",
"(",
"address",
")",
"if",
"opts",
"[",
":with_subject",
"]",
"expected_subject",
"=",
"(",
"opts",
"[",
":with_subject",
"]",
".",
"is_a?",
"(",
"String",
")",
"?",
"Regexp",
".",
"escape",
"(",
"opts",
"[",
":with_subject",
"]",
")",
":",
"opts",
"[",
":with_subject",
"]",
")",
"mailbox_for",
"(",
"address",
")",
".",
"find",
"{",
"|",
"m",
"|",
"m",
".",
"subject",
"=~",
"Regexp",
".",
"new",
"(",
"expected_subject",
")",
"}",
"elsif",
"opts",
"[",
":with_text",
"]",
"expected_text",
"=",
"(",
"opts",
"[",
":with_text",
"]",
".",
"is_a?",
"(",
"String",
")",
"?",
"Regexp",
".",
"escape",
"(",
"opts",
"[",
":with_text",
"]",
")",
":",
"opts",
"[",
":with_text",
"]",
")",
"mailbox_for",
"(",
"address",
")",
".",
"find",
"{",
"|",
"m",
"|",
"m",
".",
"default_part_body",
"=~",
"Regexp",
".",
"new",
"(",
"expected_text",
")",
"}",
"elsif",
"opts",
"[",
":from",
"]",
"mailbox_for",
"(",
"address",
")",
".",
"find",
"{",
"|",
"m",
"|",
"m",
".",
"from",
".",
"include?",
"opts",
"[",
":from",
"]",
"}",
"else",
"mailbox_for",
"(",
"address",
")",
".",
"first",
"end",
"end"
] | Should be able to accept String or Regexp options. | [
"Should",
"be",
"able",
"to",
"accept",
"String",
"or",
"Regexp",
"options",
"."
] | 107bd6fc5189bab0b1a82b7a21e80f6a7e1c6596 | https://github.com/email-spec/email-spec/blob/107bd6fc5189bab0b1a82b7a21e80f6a7e1c6596/lib/email_spec/helpers.rb#L72-L85 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_router.js.rb | Ferro.Router.path_to_parts | def path_to_parts(path)
path.
downcase.
split('/').
map { |part| part.empty? ? nil : part.strip }.
compact
end | ruby | def path_to_parts(path)
path.
downcase.
split('/').
map { |part| part.empty? ? nil : part.strip }.
compact
end | [
"def",
"path_to_parts",
"(",
"path",
")",
"path",
".",
"downcase",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"{",
"|",
"part",
"|",
"part",
".",
"empty?",
"?",
"nil",
":",
"part",
".",
"strip",
"}",
".",
"compact",
"end"
] | Internal method to split a path into components | [
"Internal",
"method",
"to",
"split",
"a",
"path",
"into",
"components"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L80-L86 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_router.js.rb | Ferro.Router.navigated | def navigated
url = get_location
@params = []
idx = match(path_to_parts(decode(url.pathname)), decode(url.search))
if idx
@routes[idx][:callback].call(@params)
else
@page404.call(url.pathname)
end
end | ruby | def navigated
url = get_location
@params = []
idx = match(path_to_parts(decode(url.pathname)), decode(url.search))
if idx
@routes[idx][:callback].call(@params)
else
@page404.call(url.pathname)
end
end | [
"def",
"navigated",
"url",
"=",
"get_location",
"@params",
"=",
"[",
"]",
"idx",
"=",
"match",
"(",
"path_to_parts",
"(",
"decode",
"(",
"url",
".",
"pathname",
")",
")",
",",
"decode",
"(",
"url",
".",
"search",
")",
")",
"if",
"idx",
"@routes",
"[",
"idx",
"]",
"[",
":callback",
"]",
".",
"call",
"(",
"@params",
")",
"else",
"@page404",
".",
"call",
"(",
"url",
".",
"pathname",
")",
"end",
"end"
] | Internal method called when the web browser navigates | [
"Internal",
"method",
"called",
"when",
"the",
"web",
"browser",
"navigates"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L96-L107 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_router.js.rb | Ferro.Router.match | def match(path, search)
matches = get_matches(path)
if matches.length > 0
match = matches.sort { |m| m[1] }.first
@params = match[2]
add_search_to_params(search)
match[0]
else
nil
end
end | ruby | def match(path, search)
matches = get_matches(path)
if matches.length > 0
match = matches.sort { |m| m[1] }.first
@params = match[2]
add_search_to_params(search)
match[0]
else
nil
end
end | [
"def",
"match",
"(",
"path",
",",
"search",
")",
"matches",
"=",
"get_matches",
"(",
"path",
")",
"if",
"matches",
".",
"length",
">",
"0",
"match",
"=",
"matches",
".",
"sort",
"{",
"|",
"m",
"|",
"m",
"[",
"1",
"]",
"}",
".",
"first",
"@params",
"=",
"match",
"[",
"2",
"]",
"add_search_to_params",
"(",
"search",
")",
"match",
"[",
"0",
"]",
"else",
"nil",
"end",
"end"
] | Internal method to match a path to the most likely route
@param [String] path Url to match
@param [String] search Url search parameters | [
"Internal",
"method",
"to",
"match",
"a",
"path",
"to",
"the",
"most",
"likely",
"route"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L113-L126 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_router.js.rb | Ferro.Router.get_matches | def get_matches(path)
matches = []
@routes.each_with_index do |route, i|
score, pars = score_route(route[:parts], path)
matches << [i, score, pars] if score > 0
end
matches
end | ruby | def get_matches(path)
matches = []
@routes.each_with_index do |route, i|
score, pars = score_route(route[:parts], path)
matches << [i, score, pars] if score > 0
end
matches
end | [
"def",
"get_matches",
"(",
"path",
")",
"matches",
"=",
"[",
"]",
"@routes",
".",
"each_with_index",
"do",
"|",
"route",
",",
"i",
"|",
"score",
",",
"pars",
"=",
"score_route",
"(",
"route",
"[",
":parts",
"]",
",",
"path",
")",
"matches",
"<<",
"[",
"i",
",",
"score",
",",
"pars",
"]",
"if",
"score",
">",
"0",
"end",
"matches",
"end"
] | Internal method to match a path to possible routes
@param [String] path Url to match | [
"Internal",
"method",
"to",
"match",
"a",
"path",
"to",
"possible",
"routes"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L131-L140 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_router.js.rb | Ferro.Router.score_route | def score_route(parts, path)
score = 0
pars = {}
if parts.length == path.length
parts.each_with_index do |part, i|
if part[0] == ':'
score += 1
pars["#{part[1..-1]}"] = path[i]
elsif part == path[i].downcase
score += 2
end
end
end
return score, pars
end | ruby | def score_route(parts, path)
score = 0
pars = {}
if parts.length == path.length
parts.each_with_index do |part, i|
if part[0] == ':'
score += 1
pars["#{part[1..-1]}"] = path[i]
elsif part == path[i].downcase
score += 2
end
end
end
return score, pars
end | [
"def",
"score_route",
"(",
"parts",
",",
"path",
")",
"score",
"=",
"0",
"pars",
"=",
"{",
"}",
"if",
"parts",
".",
"length",
"==",
"path",
".",
"length",
"parts",
".",
"each_with_index",
"do",
"|",
"part",
",",
"i",
"|",
"if",
"part",
"[",
"0",
"]",
"==",
"':'",
"score",
"+=",
"1",
"pars",
"[",
"\"#{part[1..-1]}\"",
"]",
"=",
"path",
"[",
"i",
"]",
"elsif",
"part",
"==",
"path",
"[",
"i",
"]",
".",
"downcase",
"score",
"+=",
"2",
"end",
"end",
"end",
"return",
"score",
",",
"pars",
"end"
] | Internal method to add a match score
@param [String] parts Parts of a route
@param [String] path Url to match | [
"Internal",
"method",
"to",
"add",
"a",
"match",
"score"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L146-L162 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_router.js.rb | Ferro.Router.add_search_to_params | def add_search_to_params(search)
if !search.empty?
pars = search[1..-1].split('&')
pars.each do |par|
pair = par.split('=')
@params[ pair[0] ] = pair[1] if pair.length == 2
end
end
end | ruby | def add_search_to_params(search)
if !search.empty?
pars = search[1..-1].split('&')
pars.each do |par|
pair = par.split('=')
@params[ pair[0] ] = pair[1] if pair.length == 2
end
end
end | [
"def",
"add_search_to_params",
"(",
"search",
")",
"if",
"!",
"search",
".",
"empty?",
"pars",
"=",
"search",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"split",
"(",
"'&'",
")",
"pars",
".",
"each",
"do",
"|",
"par",
"|",
"pair",
"=",
"par",
".",
"split",
"(",
"'='",
")",
"@params",
"[",
"pair",
"[",
"0",
"]",
"]",
"=",
"pair",
"[",
"1",
"]",
"if",
"pair",
".",
"length",
"==",
"2",
"end",
"end",
"end"
] | Internal method to split search parameters
@param [String] search Url search parameters | [
"Internal",
"method",
"to",
"split",
"search",
"parameters"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_router.js.rb#L167-L176 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_factory.js.rb | Ferro.Factory.dasherize | def dasherize(class_name)
return class_name if class_name !~ /[A-Z:_]/
c = class_name.to_s.gsub('::', '')
(c[0] + c[1..-1].gsub(/[A-Z]/){ |c| "-#{c}" }).
downcase.
gsub('_', '-')
end | ruby | def dasherize(class_name)
return class_name if class_name !~ /[A-Z:_]/
c = class_name.to_s.gsub('::', '')
(c[0] + c[1..-1].gsub(/[A-Z]/){ |c| "-#{c}" }).
downcase.
gsub('_', '-')
end | [
"def",
"dasherize",
"(",
"class_name",
")",
"return",
"class_name",
"if",
"class_name",
"!~",
"/",
"/",
"c",
"=",
"class_name",
".",
"to_s",
".",
"gsub",
"(",
"'::'",
",",
"''",
")",
"(",
"c",
"[",
"0",
"]",
"+",
"c",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"gsub",
"(",
"/",
"/",
")",
"{",
"|",
"c",
"|",
"\"-#{c}\"",
"}",
")",
".",
"downcase",
".",
"gsub",
"(",
"'_'",
",",
"'-'",
")",
"end"
] | Convert a Ruby classname to a dasherized name for use with CSS.
@param [String] class_name The Ruby class name
@return [String] CSS class name | [
"Convert",
"a",
"Ruby",
"classname",
"to",
"a",
"dasherized",
"name",
"for",
"use",
"with",
"CSS",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_factory.js.rb#L75-L82 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_factory.js.rb | Ferro.Factory.composite_state | def composite_state(class_name, state)
if @compositor
list = @compositor.css_classes_for("#{class_name}::#{state}")
return list if !list.empty?
end
[ dasherize(state) ]
end | ruby | def composite_state(class_name, state)
if @compositor
list = @compositor.css_classes_for("#{class_name}::#{state}")
return list if !list.empty?
end
[ dasherize(state) ]
end | [
"def",
"composite_state",
"(",
"class_name",
",",
"state",
")",
"if",
"@compositor",
"list",
"=",
"@compositor",
".",
"css_classes_for",
"(",
"\"#{class_name}::#{state}\"",
")",
"return",
"list",
"if",
"!",
"list",
".",
"empty?",
"end",
"[",
"dasherize",
"(",
"state",
")",
"]",
"end"
] | Convert a state-name to a list of CSS class names.
@param [String] class_name Ruby class name
@param [String] state State name
@return [String] A list of CSS class names | [
"Convert",
"a",
"state",
"-",
"name",
"to",
"a",
"list",
"of",
"CSS",
"class",
"names",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_factory.js.rb#L98-L105 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_factory.js.rb | Ferro.Factory.composite_classes | def composite_classes(target, element, add_superclass)
if @compositor
composite_for(target.class.name, element)
if add_superclass
composite_for(target.class.superclass.name, element)
end
end
end | ruby | def composite_classes(target, element, add_superclass)
if @compositor
composite_for(target.class.name, element)
if add_superclass
composite_for(target.class.superclass.name, element)
end
end
end | [
"def",
"composite_classes",
"(",
"target",
",",
"element",
",",
"add_superclass",
")",
"if",
"@compositor",
"composite_for",
"(",
"target",
".",
"class",
".",
"name",
",",
"element",
")",
"if",
"add_superclass",
"composite_for",
"(",
"target",
".",
"class",
".",
"superclass",
".",
"name",
",",
"element",
")",
"end",
"end",
"end"
] | Internal method
Composite CSS classes from Ruby class name | [
"Internal",
"method",
"Composite",
"CSS",
"classes",
"from",
"Ruby",
"class",
"name"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_factory.js.rb#L109-L117 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_compositor.js.rb | Ferro.Compositor.css_classes_for_map | def css_classes_for_map(classname, mapping)
css = mapping[classname]
css.class == String ? css_classes_for_map(css, mapping) : (css || [])
end | ruby | def css_classes_for_map(classname, mapping)
css = mapping[classname]
css.class == String ? css_classes_for_map(css, mapping) : (css || [])
end | [
"def",
"css_classes_for_map",
"(",
"classname",
",",
"mapping",
")",
"css",
"=",
"mapping",
"[",
"classname",
"]",
"css",
".",
"class",
"==",
"String",
"?",
"css_classes_for_map",
"(",
"css",
",",
"mapping",
")",
":",
"(",
"css",
"||",
"[",
"]",
")",
"end"
] | Internal method to get mapping from selected map. | [
"Internal",
"method",
"to",
"get",
"mapping",
"from",
"selected",
"map",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_compositor.js.rb#L38-L41 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_compositor.js.rb | Ferro.Compositor.switch_theme | def switch_theme(root_element, theme)
old_map = @mapping
new_map = map(theme)
root_element.each_child do |e|
old_classes = css_classes_for_map e.class.name, old_map
new_classes = css_classes_for_map e.class.name, new_map
update_element_css_classes(e, old_classes, new_classes)
old_classes = css_classes_for_map e.class.superclass.name, old_map
new_classes = css_classes_for_map e.class.superclass.name, new_map
update_element_css_classes(e, old_classes, new_classes)
end
@mapping = new_map
end | ruby | def switch_theme(root_element, theme)
old_map = @mapping
new_map = map(theme)
root_element.each_child do |e|
old_classes = css_classes_for_map e.class.name, old_map
new_classes = css_classes_for_map e.class.name, new_map
update_element_css_classes(e, old_classes, new_classes)
old_classes = css_classes_for_map e.class.superclass.name, old_map
new_classes = css_classes_for_map e.class.superclass.name, new_map
update_element_css_classes(e, old_classes, new_classes)
end
@mapping = new_map
end | [
"def",
"switch_theme",
"(",
"root_element",
",",
"theme",
")",
"old_map",
"=",
"@mapping",
"new_map",
"=",
"map",
"(",
"theme",
")",
"root_element",
".",
"each_child",
"do",
"|",
"e",
"|",
"old_classes",
"=",
"css_classes_for_map",
"e",
".",
"class",
".",
"name",
",",
"old_map",
"new_classes",
"=",
"css_classes_for_map",
"e",
".",
"class",
".",
"name",
",",
"new_map",
"update_element_css_classes",
"(",
"e",
",",
"old_classes",
",",
"new_classes",
")",
"old_classes",
"=",
"css_classes_for_map",
"e",
".",
"class",
".",
"superclass",
".",
"name",
",",
"old_map",
"new_classes",
"=",
"css_classes_for_map",
"e",
".",
"class",
".",
"superclass",
".",
"name",
",",
"new_map",
"update_element_css_classes",
"(",
"e",
",",
"old_classes",
",",
"new_classes",
")",
"end",
"@mapping",
"=",
"new_map",
"end"
] | Internal method to switch to a new theme. | [
"Internal",
"method",
"to",
"switch",
"to",
"a",
"new",
"theme",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_compositor.js.rb#L44-L59 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_elementary.js.rb | Ferro.Elementary._stylize | def _stylize
styles = style
if styles.class == Hash
set_attribute(
'style',
styles.map { |k, v| "#{k}:#{v};" }.join
)
end
end | ruby | def _stylize
styles = style
if styles.class == Hash
set_attribute(
'style',
styles.map { |k, v| "#{k}:#{v};" }.join
)
end
end | [
"def",
"_stylize",
"styles",
"=",
"style",
"if",
"styles",
".",
"class",
"==",
"Hash",
"set_attribute",
"(",
"'style'",
",",
"styles",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}:#{v};\"",
"}",
".",
"join",
")",
"end",
"end"
] | Internal method. | [
"Internal",
"method",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_elementary.js.rb#L52-L61 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_elementary.js.rb | Ferro.Elementary.add_child | def add_child(name, element_class, options = {})
sym = symbolize(name)
raise "Child '#{sym}' already defined" if @children.has_key?(sym)
raise "Illegal name (#{sym})" if RESERVED_NAMES.include?(sym)
@children[sym] = element_class.new(self, sym, options)
end | ruby | def add_child(name, element_class, options = {})
sym = symbolize(name)
raise "Child '#{sym}' already defined" if @children.has_key?(sym)
raise "Illegal name (#{sym})" if RESERVED_NAMES.include?(sym)
@children[sym] = element_class.new(self, sym, options)
end | [
"def",
"add_child",
"(",
"name",
",",
"element_class",
",",
"options",
"=",
"{",
"}",
")",
"sym",
"=",
"symbolize",
"(",
"name",
")",
"raise",
"\"Child '#{sym}' already defined\"",
"if",
"@children",
".",
"has_key?",
"(",
"sym",
")",
"raise",
"\"Illegal name (#{sym})\"",
"if",
"RESERVED_NAMES",
".",
"include?",
"(",
"sym",
")",
"@children",
"[",
"sym",
"]",
"=",
"element_class",
".",
"new",
"(",
"self",
",",
"sym",
",",
"options",
")",
"end"
] | Add a child element.
@param [String] name A unique name for the element that is not
in RESERVED_NAMES
@param [String] element_class Ruby class name for the new element
@param [Hash] options Options to pass to the element. Any option key
that is not recognized is set as an attribute on the DOM element.
Recognized keys are:
prepend Prepend the new element before this DOM element
content Add the value of content as a textnode to the DOM element | [
"Add",
"a",
"child",
"element",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_elementary.js.rb#L76-L81 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_elementary.js.rb | Ferro.Elementary.each_child | def each_child(&block)
if block_given?
block.call self
@children.each do |_, child|
child.each_child(&block)
end
end
end | ruby | def each_child(&block)
if block_given?
block.call self
@children.each do |_, child|
child.each_child(&block)
end
end
end | [
"def",
"each_child",
"(",
"&",
"block",
")",
"if",
"block_given?",
"block",
".",
"call",
"self",
"@children",
".",
"each",
"do",
"|",
"_",
",",
"child",
"|",
"child",
".",
"each_child",
"(",
"block",
")",
"end",
"end",
"end"
] | Recursively iterate all child elements
param [Block] block A block to execute for every child element
and the element itself | [
"Recursively",
"iterate",
"all",
"child",
"elements"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_elementary.js.rb#L104-L112 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_i18n.js.rb | Ferro.I18n._replace_options | def _replace_options(string, options)
# Unescape the string so we can use the returned string
# to set an elements inner html.
s = string.gsub('<', '<').gsub('>', '>')
if options
# But escape option values to prevent code injection
s.gsub(/%\{(\w+)\}/) do |m|
key = ($1 || m.tr("%{}", ""))
if options.key?(key)
options[key].to_s.gsub('<', '<').gsub('>', '>')
else
key
end
end
else
s
end
end | ruby | def _replace_options(string, options)
# Unescape the string so we can use the returned string
# to set an elements inner html.
s = string.gsub('<', '<').gsub('>', '>')
if options
# But escape option values to prevent code injection
s.gsub(/%\{(\w+)\}/) do |m|
key = ($1 || m.tr("%{}", ""))
if options.key?(key)
options[key].to_s.gsub('<', '<').gsub('>', '>')
else
key
end
end
else
s
end
end | [
"def",
"_replace_options",
"(",
"string",
",",
"options",
")",
"# Unescape the string so we can use the returned string",
"# to set an elements inner html.",
"s",
"=",
"string",
".",
"gsub",
"(",
"'<'",
",",
"'<'",
")",
".",
"gsub",
"(",
"'>'",
",",
"'>'",
")",
"if",
"options",
"# But escape option values to prevent code injection",
"s",
".",
"gsub",
"(",
"/",
"\\{",
"\\w",
"\\}",
"/",
")",
"do",
"|",
"m",
"|",
"key",
"=",
"(",
"$1",
"||",
"m",
".",
"tr",
"(",
"\"%{}\"",
",",
"\"\"",
")",
")",
"if",
"options",
".",
"key?",
"(",
"key",
")",
"options",
"[",
"key",
"]",
".",
"to_s",
".",
"gsub",
"(",
"'<'",
",",
"'<'",
")",
".",
"gsub",
"(",
"'>'",
",",
"'>'",
")",
"else",
"key",
"end",
"end",
"else",
"s",
"end",
"end"
] | Internal method to substitute placeholders with a value. | [
"Internal",
"method",
"to",
"substitute",
"placeholders",
"with",
"a",
"value",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_i18n.js.rb#L116-L135 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_base_element.js.rb | Ferro.BaseElement.option_replace | def option_replace(key, default = nil)
value = @options[key] || default
@options.delete(key) if @options.has_key?(key)
value
end | ruby | def option_replace(key, default = nil)
value = @options[key] || default
@options.delete(key) if @options.has_key?(key)
value
end | [
"def",
"option_replace",
"(",
"key",
",",
"default",
"=",
"nil",
")",
"value",
"=",
"@options",
"[",
"key",
"]",
"||",
"default",
"@options",
".",
"delete",
"(",
"key",
")",
"if",
"@options",
".",
"has_key?",
"(",
"key",
")",
"value",
"end"
] | Delete a key from the elements options hash. Will be renamed
to option_delete.
@param [key] key Key of the option hash to be removed
@param [value] default Optional value to use if option value is nil
@return [value] Return the current option value or value of
default parameter | [
"Delete",
"a",
"key",
"from",
"the",
"elements",
"options",
"hash",
".",
"Will",
"be",
"renamed",
"to",
"option_delete",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_base_element.js.rb#L62-L66 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_base_element.js.rb | Ferro.BaseElement.update_state | def update_state(state, active)
if !active.nil?
@states.each do |s, v|
v[1] = active if s == state
classify_state v
end
end
end | ruby | def update_state(state, active)
if !active.nil?
@states.each do |s, v|
v[1] = active if s == state
classify_state v
end
end
end | [
"def",
"update_state",
"(",
"state",
",",
"active",
")",
"if",
"!",
"active",
".",
"nil?",
"@states",
".",
"each",
"do",
"|",
"s",
",",
"v",
"|",
"v",
"[",
"1",
"]",
"=",
"active",
"if",
"s",
"==",
"state",
"classify_state",
"v",
"end",
"end",
"end"
] | Update the value of the state.
@param [String] state The state name
@param [Boolean] active The new value of the state. Pass
true to enable and set the CSS class
false to disable and remove the CSS class
nil to skip altering state and the CSS class | [
"Update",
"the",
"value",
"of",
"the",
"state",
"."
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_base_element.js.rb#L104-L111 | train |
easydatawarehousing/opal-ferro | opal/opal-ferro/ferro_base_element.js.rb | Ferro.BaseElement.toggle_state | def toggle_state(state)
@states.select { |s, _| s == state }.each do |s, v|
v[1] = !v[1]
classify_state v
end
end | ruby | def toggle_state(state)
@states.select { |s, _| s == state }.each do |s, v|
v[1] = !v[1]
classify_state v
end
end | [
"def",
"toggle_state",
"(",
"state",
")",
"@states",
".",
"select",
"{",
"|",
"s",
",",
"_",
"|",
"s",
"==",
"state",
"}",
".",
"each",
"do",
"|",
"s",
",",
"v",
"|",
"v",
"[",
"1",
"]",
"=",
"!",
"v",
"[",
"1",
"]",
"classify_state",
"v",
"end",
"end"
] | Toggle the boolean value of the state
@param [String] state The state name | [
"Toggle",
"the",
"boolean",
"value",
"of",
"the",
"state"
] | 0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7 | https://github.com/easydatawarehousing/opal-ferro/blob/0cc0c19a956cbc2d9ce99c1539cb774a02cb9ca7/opal/opal-ferro/ferro_base_element.js.rb#L116-L121 | train |
mailman/mailman | lib/mailman/router.rb | Mailman.Router.route | def route(message)
@params.clear
@message = message
result = nil
if @bounce_block and message.respond_to?(:bounced?) and message.bounced?
return instance_exec(&@bounce_block)
end
routes.each do |route|
break if result = route.match!(message)
end
if result
@params.merge!(result[:params])
if !result[:klass].nil?
if result[:klass].is_a?(Class) # no instance method specified
result[:klass].new.send(:receive, @message, @params)
elsif result[:klass].kind_of?(String) # instance method specified
klass, method = result[:klass].split('#')
klass.camelize.constantize.new.send(method.to_sym, @message, @params)
end
elsif result[:block].arity > 0
instance_exec(*result[:args], &result[:block])
else
instance_exec(&result[:block])
end
elsif @default_block
instance_exec(&@default_block)
end
end | ruby | def route(message)
@params.clear
@message = message
result = nil
if @bounce_block and message.respond_to?(:bounced?) and message.bounced?
return instance_exec(&@bounce_block)
end
routes.each do |route|
break if result = route.match!(message)
end
if result
@params.merge!(result[:params])
if !result[:klass].nil?
if result[:klass].is_a?(Class) # no instance method specified
result[:klass].new.send(:receive, @message, @params)
elsif result[:klass].kind_of?(String) # instance method specified
klass, method = result[:klass].split('#')
klass.camelize.constantize.new.send(method.to_sym, @message, @params)
end
elsif result[:block].arity > 0
instance_exec(*result[:args], &result[:block])
else
instance_exec(&result[:block])
end
elsif @default_block
instance_exec(&@default_block)
end
end | [
"def",
"route",
"(",
"message",
")",
"@params",
".",
"clear",
"@message",
"=",
"message",
"result",
"=",
"nil",
"if",
"@bounce_block",
"and",
"message",
".",
"respond_to?",
"(",
":bounced?",
")",
"and",
"message",
".",
"bounced?",
"return",
"instance_exec",
"(",
"@bounce_block",
")",
"end",
"routes",
".",
"each",
"do",
"|",
"route",
"|",
"break",
"if",
"result",
"=",
"route",
".",
"match!",
"(",
"message",
")",
"end",
"if",
"result",
"@params",
".",
"merge!",
"(",
"result",
"[",
":params",
"]",
")",
"if",
"!",
"result",
"[",
":klass",
"]",
".",
"nil?",
"if",
"result",
"[",
":klass",
"]",
".",
"is_a?",
"(",
"Class",
")",
"# no instance method specified",
"result",
"[",
":klass",
"]",
".",
"new",
".",
"send",
"(",
":receive",
",",
"@message",
",",
"@params",
")",
"elsif",
"result",
"[",
":klass",
"]",
".",
"kind_of?",
"(",
"String",
")",
"# instance method specified",
"klass",
",",
"method",
"=",
"result",
"[",
":klass",
"]",
".",
"split",
"(",
"'#'",
")",
"klass",
".",
"camelize",
".",
"constantize",
".",
"new",
".",
"send",
"(",
"method",
".",
"to_sym",
",",
"@message",
",",
"@params",
")",
"end",
"elsif",
"result",
"[",
":block",
"]",
".",
"arity",
">",
"0",
"instance_exec",
"(",
"result",
"[",
":args",
"]",
",",
"result",
"[",
":block",
"]",
")",
"else",
"instance_exec",
"(",
"result",
"[",
":block",
"]",
")",
"end",
"elsif",
"@default_block",
"instance_exec",
"(",
"@default_block",
")",
"end",
"end"
] | Route a message. If the route block accepts arguments, it passes any
captured params. Named params are available from the +params+ helper. The
message is available from the +message+ helper.
@param [Mail::Message] the message to route. | [
"Route",
"a",
"message",
".",
"If",
"the",
"route",
"block",
"accepts",
"arguments",
"it",
"passes",
"any",
"captured",
"params",
".",
"Named",
"params",
"are",
"available",
"from",
"the",
"+",
"params",
"+",
"helper",
".",
"The",
"message",
"is",
"available",
"from",
"the",
"+",
"message",
"+",
"helper",
"."
] | b955154c5d73b85cdc76687222288b1cf5a2ea91 | https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/router.rb#L38-L68 | train |
mailman/mailman | lib/mailman/route.rb | Mailman.Route.match! | def match!(message)
params = {}
args = []
@conditions.each do |condition|
if result = condition.match(message)
params.merge!(result[0])
args += result[1]
else
return nil
end
end
{ :block => @block, :klass => @klass, :params => params, :args => args }
end | ruby | def match!(message)
params = {}
args = []
@conditions.each do |condition|
if result = condition.match(message)
params.merge!(result[0])
args += result[1]
else
return nil
end
end
{ :block => @block, :klass => @klass, :params => params, :args => args }
end | [
"def",
"match!",
"(",
"message",
")",
"params",
"=",
"{",
"}",
"args",
"=",
"[",
"]",
"@conditions",
".",
"each",
"do",
"|",
"condition",
"|",
"if",
"result",
"=",
"condition",
".",
"match",
"(",
"message",
")",
"params",
".",
"merge!",
"(",
"result",
"[",
"0",
"]",
")",
"args",
"+=",
"result",
"[",
"1",
"]",
"else",
"return",
"nil",
"end",
"end",
"{",
":block",
"=>",
"@block",
",",
":klass",
"=>",
"@klass",
",",
":params",
"=>",
"params",
",",
":args",
"=>",
"args",
"}",
"end"
] | Checks whether a message matches the route.
@param [Mail::Message] message the message to match against
@return [Hash] the +:block+ and +:klass+ associated with the route, the
+:params+ hash, and the block +:args+ array. | [
"Checks",
"whether",
"a",
"message",
"matches",
"the",
"route",
"."
] | b955154c5d73b85cdc76687222288b1cf5a2ea91 | https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/route.rb#L25-L37 | train |
mailman/mailman | lib/mailman/application.rb | Mailman.Application.run | def run
Mailman.logger.info "Mailman v#{Mailman::VERSION} started"
if config.rails_root
rails_env = File.join(config.rails_root, 'config', 'environment.rb')
if File.exist?(rails_env) && !(defined?(::Rails) && ::Rails.env)
Mailman.logger.info "Rails root found in #{config.rails_root}, requiring environment..."
require rails_env
end
end
if config.graceful_death
# When user presses CTRL-C, finish processing current message before exiting
Signal.trap("INT") { @polling_interrupt = true }
end
# STDIN
if !IS_WINDOWS && !config.ignore_stdin && $stdin.fcntl(Fcntl::F_GETFL, 0) == 0
Mailman.logger.debug "Processing message from STDIN."
@processor.process($stdin.read)
# IMAP
elsif config.imap
options = {:processor => @processor}.merge(config.imap)
Mailman.logger.info "IMAP receiver enabled (#{options[:username]}@#{options[:server]})."
polling_loop Receiver::IMAP.new(options)
# POP3
elsif config.pop3
options = {:processor => @processor}.merge(config.pop3)
Mailman.logger.info "POP3 receiver enabled (#{options[:username]}@#{options[:server]})."
polling_loop Receiver::POP3.new(options)
# HTTP
elsif config.http
options = {:processor => @processor}.merge(config.http)
Mailman.logger.info "HTTP server started"
Receiver::HTTP.new(options).start_and_block
# Maildir
elsif config.maildir
Mailman.logger.info "Maildir receiver enabled (#{config.maildir})."
Mailman.logger.debug "Processing new message queue..."
@maildir.list(:new).each do |message|
@processor.process_maildir_message(message)
end
if config.watch_maildir
require 'listen'
Mailman.logger.debug "Monitoring the Maildir for new messages..."
base = Pathname.new(@maildir.path)
callback = Proc.new do |modified, added, removed|
added.each do |new_file|
message = Maildir::Message.new(@maildir, Pathname.new(new_file).relative_path_from(base).to_s)
@processor.process_maildir_message(message)
end
end
@listener = Listen::Listener.new(File.join(@maildir.path, 'new'), &callback)
@listener.start
sleep
end
end
end | ruby | def run
Mailman.logger.info "Mailman v#{Mailman::VERSION} started"
if config.rails_root
rails_env = File.join(config.rails_root, 'config', 'environment.rb')
if File.exist?(rails_env) && !(defined?(::Rails) && ::Rails.env)
Mailman.logger.info "Rails root found in #{config.rails_root}, requiring environment..."
require rails_env
end
end
if config.graceful_death
# When user presses CTRL-C, finish processing current message before exiting
Signal.trap("INT") { @polling_interrupt = true }
end
# STDIN
if !IS_WINDOWS && !config.ignore_stdin && $stdin.fcntl(Fcntl::F_GETFL, 0) == 0
Mailman.logger.debug "Processing message from STDIN."
@processor.process($stdin.read)
# IMAP
elsif config.imap
options = {:processor => @processor}.merge(config.imap)
Mailman.logger.info "IMAP receiver enabled (#{options[:username]}@#{options[:server]})."
polling_loop Receiver::IMAP.new(options)
# POP3
elsif config.pop3
options = {:processor => @processor}.merge(config.pop3)
Mailman.logger.info "POP3 receiver enabled (#{options[:username]}@#{options[:server]})."
polling_loop Receiver::POP3.new(options)
# HTTP
elsif config.http
options = {:processor => @processor}.merge(config.http)
Mailman.logger.info "HTTP server started"
Receiver::HTTP.new(options).start_and_block
# Maildir
elsif config.maildir
Mailman.logger.info "Maildir receiver enabled (#{config.maildir})."
Mailman.logger.debug "Processing new message queue..."
@maildir.list(:new).each do |message|
@processor.process_maildir_message(message)
end
if config.watch_maildir
require 'listen'
Mailman.logger.debug "Monitoring the Maildir for new messages..."
base = Pathname.new(@maildir.path)
callback = Proc.new do |modified, added, removed|
added.each do |new_file|
message = Maildir::Message.new(@maildir, Pathname.new(new_file).relative_path_from(base).to_s)
@processor.process_maildir_message(message)
end
end
@listener = Listen::Listener.new(File.join(@maildir.path, 'new'), &callback)
@listener.start
sleep
end
end
end | [
"def",
"run",
"Mailman",
".",
"logger",
".",
"info",
"\"Mailman v#{Mailman::VERSION} started\"",
"if",
"config",
".",
"rails_root",
"rails_env",
"=",
"File",
".",
"join",
"(",
"config",
".",
"rails_root",
",",
"'config'",
",",
"'environment.rb'",
")",
"if",
"File",
".",
"exist?",
"(",
"rails_env",
")",
"&&",
"!",
"(",
"defined?",
"(",
"::",
"Rails",
")",
"&&",
"::",
"Rails",
".",
"env",
")",
"Mailman",
".",
"logger",
".",
"info",
"\"Rails root found in #{config.rails_root}, requiring environment...\"",
"require",
"rails_env",
"end",
"end",
"if",
"config",
".",
"graceful_death",
"# When user presses CTRL-C, finish processing current message before exiting",
"Signal",
".",
"trap",
"(",
"\"INT\"",
")",
"{",
"@polling_interrupt",
"=",
"true",
"}",
"end",
"# STDIN",
"if",
"!",
"IS_WINDOWS",
"&&",
"!",
"config",
".",
"ignore_stdin",
"&&",
"$stdin",
".",
"fcntl",
"(",
"Fcntl",
"::",
"F_GETFL",
",",
"0",
")",
"==",
"0",
"Mailman",
".",
"logger",
".",
"debug",
"\"Processing message from STDIN.\"",
"@processor",
".",
"process",
"(",
"$stdin",
".",
"read",
")",
"# IMAP",
"elsif",
"config",
".",
"imap",
"options",
"=",
"{",
":processor",
"=>",
"@processor",
"}",
".",
"merge",
"(",
"config",
".",
"imap",
")",
"Mailman",
".",
"logger",
".",
"info",
"\"IMAP receiver enabled (#{options[:username]}@#{options[:server]}).\"",
"polling_loop",
"Receiver",
"::",
"IMAP",
".",
"new",
"(",
"options",
")",
"# POP3",
"elsif",
"config",
".",
"pop3",
"options",
"=",
"{",
":processor",
"=>",
"@processor",
"}",
".",
"merge",
"(",
"config",
".",
"pop3",
")",
"Mailman",
".",
"logger",
".",
"info",
"\"POP3 receiver enabled (#{options[:username]}@#{options[:server]}).\"",
"polling_loop",
"Receiver",
"::",
"POP3",
".",
"new",
"(",
"options",
")",
"# HTTP",
"elsif",
"config",
".",
"http",
"options",
"=",
"{",
":processor",
"=>",
"@processor",
"}",
".",
"merge",
"(",
"config",
".",
"http",
")",
"Mailman",
".",
"logger",
".",
"info",
"\"HTTP server started\"",
"Receiver",
"::",
"HTTP",
".",
"new",
"(",
"options",
")",
".",
"start_and_block",
"# Maildir",
"elsif",
"config",
".",
"maildir",
"Mailman",
".",
"logger",
".",
"info",
"\"Maildir receiver enabled (#{config.maildir}).\"",
"Mailman",
".",
"logger",
".",
"debug",
"\"Processing new message queue...\"",
"@maildir",
".",
"list",
"(",
":new",
")",
".",
"each",
"do",
"|",
"message",
"|",
"@processor",
".",
"process_maildir_message",
"(",
"message",
")",
"end",
"if",
"config",
".",
"watch_maildir",
"require",
"'listen'",
"Mailman",
".",
"logger",
".",
"debug",
"\"Monitoring the Maildir for new messages...\"",
"base",
"=",
"Pathname",
".",
"new",
"(",
"@maildir",
".",
"path",
")",
"callback",
"=",
"Proc",
".",
"new",
"do",
"|",
"modified",
",",
"added",
",",
"removed",
"|",
"added",
".",
"each",
"do",
"|",
"new_file",
"|",
"message",
"=",
"Maildir",
"::",
"Message",
".",
"new",
"(",
"@maildir",
",",
"Pathname",
".",
"new",
"(",
"new_file",
")",
".",
"relative_path_from",
"(",
"base",
")",
".",
"to_s",
")",
"@processor",
".",
"process_maildir_message",
"(",
"message",
")",
"end",
"end",
"@listener",
"=",
"Listen",
"::",
"Listener",
".",
"new",
"(",
"File",
".",
"join",
"(",
"@maildir",
".",
"path",
",",
"'new'",
")",
",",
"callback",
")",
"@listener",
".",
"start",
"sleep",
"end",
"end",
"end"
] | Runs the application. | [
"Runs",
"the",
"application",
"."
] | b955154c5d73b85cdc76687222288b1cf5a2ea91 | https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/application.rb#L56-L122 | train |
mailman/mailman | lib/mailman/application.rb | Mailman.Application.polling_loop | def polling_loop(connection)
if polling?
polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds."
else
polling_msg = "Polling disabled. Checking for messages once."
end
Mailman.logger.info(polling_msg)
tries ||= 5
loop do
begin
connection.connect
connection.get_messages
rescue SystemCallError, EOFError => e
Mailman.logger.error e.message
unless (tries -= 1).zero?
Mailman.logger.error "Retrying..."
begin
connection.disconnect
rescue # don't crash in the crash handler
end
retry
end
ensure
connection.started? && connection.disconnect
end
break unless polling?
sleep config.poll_interval
end
end | ruby | def polling_loop(connection)
if polling?
polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds."
else
polling_msg = "Polling disabled. Checking for messages once."
end
Mailman.logger.info(polling_msg)
tries ||= 5
loop do
begin
connection.connect
connection.get_messages
rescue SystemCallError, EOFError => e
Mailman.logger.error e.message
unless (tries -= 1).zero?
Mailman.logger.error "Retrying..."
begin
connection.disconnect
rescue # don't crash in the crash handler
end
retry
end
ensure
connection.started? && connection.disconnect
end
break unless polling?
sleep config.poll_interval
end
end | [
"def",
"polling_loop",
"(",
"connection",
")",
"if",
"polling?",
"polling_msg",
"=",
"\"Polling enabled. Checking every #{config.poll_interval} seconds.\"",
"else",
"polling_msg",
"=",
"\"Polling disabled. Checking for messages once.\"",
"end",
"Mailman",
".",
"logger",
".",
"info",
"(",
"polling_msg",
")",
"tries",
"||=",
"5",
"loop",
"do",
"begin",
"connection",
".",
"connect",
"connection",
".",
"get_messages",
"rescue",
"SystemCallError",
",",
"EOFError",
"=>",
"e",
"Mailman",
".",
"logger",
".",
"error",
"e",
".",
"message",
"unless",
"(",
"tries",
"-=",
"1",
")",
".",
"zero?",
"Mailman",
".",
"logger",
".",
"error",
"\"Retrying...\"",
"begin",
"connection",
".",
"disconnect",
"rescue",
"# don't crash in the crash handler",
"end",
"retry",
"end",
"ensure",
"connection",
".",
"started?",
"&&",
"connection",
".",
"disconnect",
"end",
"break",
"unless",
"polling?",
"sleep",
"config",
".",
"poll_interval",
"end",
"end"
] | Run the polling loop for the email inbox connection | [
"Run",
"the",
"polling",
"loop",
"for",
"the",
"email",
"inbox",
"connection"
] | b955154c5d73b85cdc76687222288b1cf5a2ea91 | https://github.com/mailman/mailman/blob/b955154c5d73b85cdc76687222288b1cf5a2ea91/lib/mailman/application.rb#L134-L164 | train |
airbnb/hypernova-ruby | lib/hypernova/controller_helpers.rb | Hypernova.ControllerHelpers.hypernova_batch_render | def hypernova_batch_render(job)
if @hypernova_batch.nil?
raise NilBatchError.new('called hypernova_batch_render without calling '\
'hypernova_batch_before. Check your around_filter for :hypernova_render_support')
end
batch_token = @hypernova_batch.render(job)
template_safe_token = Hypernova.render_token(batch_token)
@hypernova_batch_mapping[template_safe_token] = batch_token
template_safe_token
end | ruby | def hypernova_batch_render(job)
if @hypernova_batch.nil?
raise NilBatchError.new('called hypernova_batch_render without calling '\
'hypernova_batch_before. Check your around_filter for :hypernova_render_support')
end
batch_token = @hypernova_batch.render(job)
template_safe_token = Hypernova.render_token(batch_token)
@hypernova_batch_mapping[template_safe_token] = batch_token
template_safe_token
end | [
"def",
"hypernova_batch_render",
"(",
"job",
")",
"if",
"@hypernova_batch",
".",
"nil?",
"raise",
"NilBatchError",
".",
"new",
"(",
"'called hypernova_batch_render without calling '",
"'hypernova_batch_before. Check your around_filter for :hypernova_render_support'",
")",
"end",
"batch_token",
"=",
"@hypernova_batch",
".",
"render",
"(",
"job",
")",
"template_safe_token",
"=",
"Hypernova",
".",
"render_token",
"(",
"batch_token",
")",
"@hypernova_batch_mapping",
"[",
"template_safe_token",
"]",
"=",
"batch_token",
"template_safe_token",
"end"
] | enqueue a render into the current request's hypernova batch | [
"enqueue",
"a",
"render",
"into",
"the",
"current",
"request",
"s",
"hypernova",
"batch"
] | ce2497003566bf2837a30ee6bffac700538ffbdc | https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/controller_helpers.rb#L22-L31 | train |
airbnb/hypernova-ruby | lib/hypernova/controller_helpers.rb | Hypernova.ControllerHelpers.render_react_component | def render_react_component(component, data = {})
begin
new_data = get_view_data(component, data)
rescue StandardError => e
on_error(e)
new_data = data
end
job = {
:data => new_data,
:name => component,
}
hypernova_batch_render(job)
end | ruby | def render_react_component(component, data = {})
begin
new_data = get_view_data(component, data)
rescue StandardError => e
on_error(e)
new_data = data
end
job = {
:data => new_data,
:name => component,
}
hypernova_batch_render(job)
end | [
"def",
"render_react_component",
"(",
"component",
",",
"data",
"=",
"{",
"}",
")",
"begin",
"new_data",
"=",
"get_view_data",
"(",
"component",
",",
"data",
")",
"rescue",
"StandardError",
"=>",
"e",
"on_error",
"(",
"e",
")",
"new_data",
"=",
"data",
"end",
"job",
"=",
"{",
":data",
"=>",
"new_data",
",",
":name",
"=>",
"component",
",",
"}",
"hypernova_batch_render",
"(",
"job",
")",
"end"
] | shortcut method to render a react component
@param [String] name the hypernova bundle name, like 'packages/p3/foo.bundle.js' (for now)
@param [Hash] props the props to be passed to the component
:^)k|8 <-- this is a chill peep riding a skateboard | [
"shortcut",
"method",
"to",
"render",
"a",
"react",
"component"
] | ce2497003566bf2837a30ee6bffac700538ffbdc | https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/controller_helpers.rb#L38-L51 | train |
airbnb/hypernova-ruby | lib/hypernova/controller_helpers.rb | Hypernova.ControllerHelpers.hypernova_batch_after | def hypernova_batch_after
if @hypernova_batch.nil?
raise NilBatchError.new('called hypernova_batch_after without calling '\
'hypernova_batch_before. Check your around_filter for :hypernova_render_support')
end
return if @hypernova_batch.empty?
jobs = @hypernova_batch.jobs
hash = jobs.each_with_object({}) do |job, h|
h[job[:name]] = job
end
hash = prepare_request(hash, hash)
if send_request?(hash)
begin
will_send_request(hash)
result = @hypernova_batch.submit!
on_success(result, hash)
rescue StandardError => e
on_error(e, nil, hash)
result = @hypernova_batch.submit_fallback!
end
else
result = @hypernova_batch.submit_fallback!
end
new_body = Hypernova.replace_tokens_with_result(
response.body,
@hypernova_batch_mapping,
result
)
response.body = new_body
end | ruby | def hypernova_batch_after
if @hypernova_batch.nil?
raise NilBatchError.new('called hypernova_batch_after without calling '\
'hypernova_batch_before. Check your around_filter for :hypernova_render_support')
end
return if @hypernova_batch.empty?
jobs = @hypernova_batch.jobs
hash = jobs.each_with_object({}) do |job, h|
h[job[:name]] = job
end
hash = prepare_request(hash, hash)
if send_request?(hash)
begin
will_send_request(hash)
result = @hypernova_batch.submit!
on_success(result, hash)
rescue StandardError => e
on_error(e, nil, hash)
result = @hypernova_batch.submit_fallback!
end
else
result = @hypernova_batch.submit_fallback!
end
new_body = Hypernova.replace_tokens_with_result(
response.body,
@hypernova_batch_mapping,
result
)
response.body = new_body
end | [
"def",
"hypernova_batch_after",
"if",
"@hypernova_batch",
".",
"nil?",
"raise",
"NilBatchError",
".",
"new",
"(",
"'called hypernova_batch_after without calling '",
"'hypernova_batch_before. Check your around_filter for :hypernova_render_support'",
")",
"end",
"return",
"if",
"@hypernova_batch",
".",
"empty?",
"jobs",
"=",
"@hypernova_batch",
".",
"jobs",
"hash",
"=",
"jobs",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"job",
",",
"h",
"|",
"h",
"[",
"job",
"[",
":name",
"]",
"]",
"=",
"job",
"end",
"hash",
"=",
"prepare_request",
"(",
"hash",
",",
"hash",
")",
"if",
"send_request?",
"(",
"hash",
")",
"begin",
"will_send_request",
"(",
"hash",
")",
"result",
"=",
"@hypernova_batch",
".",
"submit!",
"on_success",
"(",
"result",
",",
"hash",
")",
"rescue",
"StandardError",
"=>",
"e",
"on_error",
"(",
"e",
",",
"nil",
",",
"hash",
")",
"result",
"=",
"@hypernova_batch",
".",
"submit_fallback!",
"end",
"else",
"result",
"=",
"@hypernova_batch",
".",
"submit_fallback!",
"end",
"new_body",
"=",
"Hypernova",
".",
"replace_tokens_with_result",
"(",
"response",
".",
"body",
",",
"@hypernova_batch_mapping",
",",
"result",
")",
"response",
".",
"body",
"=",
"new_body",
"end"
] | Modifies response.body to have all batched hypernova render results | [
"Modifies",
"response",
".",
"body",
"to",
"have",
"all",
"batched",
"hypernova",
"render",
"results"
] | ce2497003566bf2837a30ee6bffac700538ffbdc | https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/controller_helpers.rb#L73-L104 | train |
airbnb/hypernova-ruby | lib/hypernova/batch.rb | Hypernova.Batch.jobs_hash | def jobs_hash
hash = {}
jobs.each_with_index { |job, idx| hash[idx.to_s] = job }
hash
end | ruby | def jobs_hash
hash = {}
jobs.each_with_index { |job, idx| hash[idx.to_s] = job }
hash
end | [
"def",
"jobs_hash",
"hash",
"=",
"{",
"}",
"jobs",
".",
"each_with_index",
"{",
"|",
"job",
",",
"idx",
"|",
"hash",
"[",
"idx",
".",
"to_s",
"]",
"=",
"job",
"}",
"hash",
"end"
] | creates a hash with each index mapped to the value at that index | [
"creates",
"a",
"hash",
"with",
"each",
"index",
"mapped",
"to",
"the",
"value",
"at",
"that",
"index"
] | ce2497003566bf2837a30ee6bffac700538ffbdc | https://github.com/airbnb/hypernova-ruby/blob/ce2497003566bf2837a30ee6bffac700538ffbdc/lib/hypernova/batch.rb#L43-L47 | train |
rspec/rspec-its | lib/rspec/its.rb | RSpec.Its.its | def its(attribute, *options, &block)
its_caller = caller.select {|file_line| file_line !~ %r(/lib/rspec/its) }
describe(attribute.to_s, :caller => its_caller) do
let(:__its_subject) do
if Array === attribute
if Hash === subject
attribute.inject(subject) {|inner, attr| inner[attr] }
else
subject[*attribute]
end
else
attribute_chain = attribute.to_s.split('.')
attribute_chain.inject(subject) do |inner_subject, attr|
inner_subject.send(attr)
end
end
end
def is_expected
expect(__its_subject)
end
alias_method :are_expected, :is_expected
def will(matcher=nil, message=nil)
unless matcher.supports_block_expectations?
raise ArgumentError, "`will` only supports block expectations"
end
expect { __its_subject }.to matcher, message
end
def will_not(matcher=nil, message=nil)
unless matcher.supports_block_expectations?
raise ArgumentError, "`will_not` only supports block expectations"
end
expect { __its_subject }.to_not matcher, message
end
def should(matcher=nil, message=nil)
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
def should_not(matcher=nil, message=nil)
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
options << {} unless options.last.kind_of?(Hash)
options.last.merge!(:caller => its_caller)
example(nil, *options, &block)
end
end | ruby | def its(attribute, *options, &block)
its_caller = caller.select {|file_line| file_line !~ %r(/lib/rspec/its) }
describe(attribute.to_s, :caller => its_caller) do
let(:__its_subject) do
if Array === attribute
if Hash === subject
attribute.inject(subject) {|inner, attr| inner[attr] }
else
subject[*attribute]
end
else
attribute_chain = attribute.to_s.split('.')
attribute_chain.inject(subject) do |inner_subject, attr|
inner_subject.send(attr)
end
end
end
def is_expected
expect(__its_subject)
end
alias_method :are_expected, :is_expected
def will(matcher=nil, message=nil)
unless matcher.supports_block_expectations?
raise ArgumentError, "`will` only supports block expectations"
end
expect { __its_subject }.to matcher, message
end
def will_not(matcher=nil, message=nil)
unless matcher.supports_block_expectations?
raise ArgumentError, "`will_not` only supports block expectations"
end
expect { __its_subject }.to_not matcher, message
end
def should(matcher=nil, message=nil)
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
def should_not(matcher=nil, message=nil)
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
options << {} unless options.last.kind_of?(Hash)
options.last.merge!(:caller => its_caller)
example(nil, *options, &block)
end
end | [
"def",
"its",
"(",
"attribute",
",",
"*",
"options",
",",
"&",
"block",
")",
"its_caller",
"=",
"caller",
".",
"select",
"{",
"|",
"file_line",
"|",
"file_line",
"!~",
"%r(",
")",
"}",
"describe",
"(",
"attribute",
".",
"to_s",
",",
":caller",
"=>",
"its_caller",
")",
"do",
"let",
"(",
":__its_subject",
")",
"do",
"if",
"Array",
"===",
"attribute",
"if",
"Hash",
"===",
"subject",
"attribute",
".",
"inject",
"(",
"subject",
")",
"{",
"|",
"inner",
",",
"attr",
"|",
"inner",
"[",
"attr",
"]",
"}",
"else",
"subject",
"[",
"attribute",
"]",
"end",
"else",
"attribute_chain",
"=",
"attribute",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
"attribute_chain",
".",
"inject",
"(",
"subject",
")",
"do",
"|",
"inner_subject",
",",
"attr",
"|",
"inner_subject",
".",
"send",
"(",
"attr",
")",
"end",
"end",
"end",
"def",
"is_expected",
"expect",
"(",
"__its_subject",
")",
"end",
"alias_method",
":are_expected",
",",
":is_expected",
"def",
"will",
"(",
"matcher",
"=",
"nil",
",",
"message",
"=",
"nil",
")",
"unless",
"matcher",
".",
"supports_block_expectations?",
"raise",
"ArgumentError",
",",
"\"`will` only supports block expectations\"",
"end",
"expect",
"{",
"__its_subject",
"}",
".",
"to",
"matcher",
",",
"message",
"end",
"def",
"will_not",
"(",
"matcher",
"=",
"nil",
",",
"message",
"=",
"nil",
")",
"unless",
"matcher",
".",
"supports_block_expectations?",
"raise",
"ArgumentError",
",",
"\"`will_not` only supports block expectations\"",
"end",
"expect",
"{",
"__its_subject",
"}",
".",
"to_not",
"matcher",
",",
"message",
"end",
"def",
"should",
"(",
"matcher",
"=",
"nil",
",",
"message",
"=",
"nil",
")",
"RSpec",
"::",
"Expectations",
"::",
"PositiveExpectationHandler",
".",
"handle_matcher",
"(",
"__its_subject",
",",
"matcher",
",",
"message",
")",
"end",
"def",
"should_not",
"(",
"matcher",
"=",
"nil",
",",
"message",
"=",
"nil",
")",
"RSpec",
"::",
"Expectations",
"::",
"NegativeExpectationHandler",
".",
"handle_matcher",
"(",
"__its_subject",
",",
"matcher",
",",
"message",
")",
"end",
"options",
"<<",
"{",
"}",
"unless",
"options",
".",
"last",
".",
"kind_of?",
"(",
"Hash",
")",
"options",
".",
"last",
".",
"merge!",
"(",
":caller",
"=>",
"its_caller",
")",
"example",
"(",
"nil",
",",
"options",
",",
"block",
")",
"end",
"end"
] | Creates a nested example group named by the submitted `attribute`,
and then generates an example using the submitted block.
@example
# This ...
describe Array do
its(:size) { should eq(0) }
end
# ... generates the same runtime structure as this:
describe Array do
describe "size" do
it "should eq(0)" do
subject.size.should eq(0)
end
end
end
The attribute can be a `Symbol` or a `String`. Given a `String`
with dots, the result is as though you concatenated that `String`
onto the subject in an expression.
@example
describe Person do
subject do
Person.new.tap do |person|
person.phone_numbers << "555-1212"
end
end
its("phone_numbers.first") { should eq("555-1212") }
end
When the subject is a `Hash`, you can refer to the Hash keys by
specifying a `Symbol` or `String` in an array.
@example
describe "a configuration Hash" do
subject do
{ :max_users => 3,
'admin' => :all_permissions.
'john_doe' => {:permissions => [:read, :write]}}
end
its([:max_users]) { should eq(3) }
its(['admin']) { should eq(:all_permissions) }
its(['john_doe', :permissions]) { should eq([:read, :write]) }
# You can still access its regular methods this way:
its(:keys) { should include(:max_users) }
its(:count) { should eq(2) }
end
With an implicit subject, `is_expected` can be used as an alternative
to `should` (e.g. for one-liner use). An `are_expected` alias is also
supplied.
@example
describe Array do
its(:size) { is_expected.to eq(0) }
end
With an implicit subject, `will` can be used as an alternative
to `expect { subject.attribute }.to matcher` (e.g. for one-liner use).
@example
describe Array do
its(:foo) { will raise_error(NoMethodError) }
end
With an implicit subject, `will_not` can be used as an alternative
to `expect { subject.attribute }.to_not matcher` (e.g. for one-liner use).
@example
describe Array do
its(:size) { will_not raise_error }
end
You can pass more than one argument on the `its` block to add
some metadata to the generated example
@example
# This ...
describe Array do
its(:size, :focus) { should eq(0) }
end
# ... generates the same runtime structure as this:
describe Array do
describe "size" do
it "should eq(0)", :focus do
subject.size.should eq(0)
end
end
end
Note that this method does not modify `subject` in any way, so if you
refer to `subject` in `let` or `before` blocks, you're still
referring to the outer subject.
@example
describe Person do
subject { Person.new }
before { subject.age = 25 }
its(:age) { should eq(25) }
end | [
"Creates",
"a",
"nested",
"example",
"group",
"named",
"by",
"the",
"submitted",
"attribute",
"and",
"then",
"generates",
"an",
"example",
"using",
"the",
"submitted",
"block",
"."
] | f80aa97fe87b4da9f991b8556d41905e27a4ffbb | https://github.com/rspec/rspec-its/blob/f80aa97fe87b4da9f991b8556d41905e27a4ffbb/lib/rspec/its.rb#L121-L172 | train |
soffes/hue | lib/hue/light.rb | Hue.Light.refresh | def refresh
json = JSON(Net::HTTP.get(URI.parse(base_url)))
unpack(json)
end | ruby | def refresh
json = JSON(Net::HTTP.get(URI.parse(base_url)))
unpack(json)
end | [
"def",
"refresh",
"json",
"=",
"JSON",
"(",
"Net",
"::",
"HTTP",
".",
"get",
"(",
"URI",
".",
"parse",
"(",
"base_url",
")",
")",
")",
"unpack",
"(",
"json",
")",
"end"
] | Refresh the state of the lamp | [
"Refresh",
"the",
"state",
"of",
"the",
"lamp"
] | 2e9db44148d7d964e586af9268ac4dc1efb379d6 | https://github.com/soffes/hue/blob/2e9db44148d7d964e586af9268ac4dc1efb379d6/lib/hue/light.rb#L138-L141 | train |
Netflix/spectator-rb | lib/spectator/timer.rb | Spectator.Timer.record | def record(nanos)
return if nanos < 0
@count.add_and_get(1)
@total_time.add_and_get(nanos)
@total_sq.add_and_get(nanos * nanos)
@max.max(nanos)
end | ruby | def record(nanos)
return if nanos < 0
@count.add_and_get(1)
@total_time.add_and_get(nanos)
@total_sq.add_and_get(nanos * nanos)
@max.max(nanos)
end | [
"def",
"record",
"(",
"nanos",
")",
"return",
"if",
"nanos",
"<",
"0",
"@count",
".",
"add_and_get",
"(",
"1",
")",
"@total_time",
".",
"add_and_get",
"(",
"nanos",
")",
"@total_sq",
".",
"add_and_get",
"(",
"nanos",
"*",
"nanos",
")",
"@max",
".",
"max",
"(",
"nanos",
")",
"end"
] | Update the statistics kept by this timer. If the amount of nanoseconds
passed is negative, the value will be ignored. | [
"Update",
"the",
"statistics",
"kept",
"by",
"this",
"timer",
".",
"If",
"the",
"amount",
"of",
"nanoseconds",
"passed",
"is",
"negative",
"the",
"value",
"will",
"be",
"ignored",
"."
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/timer.rb#L22-L28 | train |
Netflix/spectator-rb | lib/spectator/meter_id.rb | Spectator.MeterId.with_tag | def with_tag(key, value)
new_tags = @tags.dup
new_tags[key] = value
MeterId.new(@name, new_tags)
end | ruby | def with_tag(key, value)
new_tags = @tags.dup
new_tags[key] = value
MeterId.new(@name, new_tags)
end | [
"def",
"with_tag",
"(",
"key",
",",
"value",
")",
"new_tags",
"=",
"@tags",
".",
"dup",
"new_tags",
"[",
"key",
"]",
"=",
"value",
"MeterId",
".",
"new",
"(",
"@name",
",",
"new_tags",
")",
"end"
] | Create a new MeterId with a given key and value | [
"Create",
"a",
"new",
"MeterId",
"with",
"a",
"given",
"key",
"and",
"value"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/meter_id.rb#L15-L19 | train |
Netflix/spectator-rb | lib/spectator/meter_id.rb | Spectator.MeterId.key | def key
if @key.nil?
hash_key = @name.to_s
@key = hash_key
keys = @tags.keys
keys.sort
keys.each do |k|
v = tags[k]
hash_key += "|#{k}|#{v}"
end
@key = hash_key
end
@key
end | ruby | def key
if @key.nil?
hash_key = @name.to_s
@key = hash_key
keys = @tags.keys
keys.sort
keys.each do |k|
v = tags[k]
hash_key += "|#{k}|#{v}"
end
@key = hash_key
end
@key
end | [
"def",
"key",
"if",
"@key",
".",
"nil?",
"hash_key",
"=",
"@name",
".",
"to_s",
"@key",
"=",
"hash_key",
"keys",
"=",
"@tags",
".",
"keys",
"keys",
".",
"sort",
"keys",
".",
"each",
"do",
"|",
"k",
"|",
"v",
"=",
"tags",
"[",
"k",
"]",
"hash_key",
"+=",
"\"|#{k}|#{v}\"",
"end",
"@key",
"=",
"hash_key",
"end",
"@key",
"end"
] | lazyily compute a key to be used in hashes for efficiency | [
"lazyily",
"compute",
"a",
"key",
"to",
"be",
"used",
"in",
"hashes",
"for",
"efficiency"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/meter_id.rb#L27-L40 | train |
Netflix/spectator-rb | lib/spectator/distribution_summary.rb | Spectator.DistributionSummary.record | def record(amount)
return if amount < 0
@count.add_and_get(1)
@total_amount.add_and_get(amount)
@total_sq.add_and_get(amount * amount)
@max.max(amount)
end | ruby | def record(amount)
return if amount < 0
@count.add_and_get(1)
@total_amount.add_and_get(amount)
@total_sq.add_and_get(amount * amount)
@max.max(amount)
end | [
"def",
"record",
"(",
"amount",
")",
"return",
"if",
"amount",
"<",
"0",
"@count",
".",
"add_and_get",
"(",
"1",
")",
"@total_amount",
".",
"add_and_get",
"(",
"amount",
")",
"@total_sq",
".",
"add_and_get",
"(",
"amount",
"*",
"amount",
")",
"@max",
".",
"max",
"(",
"amount",
")",
"end"
] | Initialize a new DistributionSummary instance with a given id
Update the statistics kept by the summary with the specified amount. | [
"Initialize",
"a",
"new",
"DistributionSummary",
"instance",
"with",
"a",
"given",
"id",
"Update",
"the",
"statistics",
"kept",
"by",
"the",
"summary",
"with",
"the",
"specified",
"amount",
"."
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/distribution_summary.rb#L21-L27 | train |
Netflix/spectator-rb | lib/spectator/distribution_summary.rb | Spectator.DistributionSummary.measure | def measure
cnt = Measure.new(@id.with_stat('count'), @count.get_and_set(0))
tot = Measure.new(@id.with_stat('totalAmount'),
@total_amount.get_and_set(0))
tot_sq = Measure.new(@id.with_stat('totalOfSquares'),
@total_sq.get_and_set(0))
mx = Measure.new(@id.with_stat('max'), @max.get_and_set(Float::NAN))
[cnt, tot, tot_sq, mx]
end | ruby | def measure
cnt = Measure.new(@id.with_stat('count'), @count.get_and_set(0))
tot = Measure.new(@id.with_stat('totalAmount'),
@total_amount.get_and_set(0))
tot_sq = Measure.new(@id.with_stat('totalOfSquares'),
@total_sq.get_and_set(0))
mx = Measure.new(@id.with_stat('max'), @max.get_and_set(Float::NAN))
[cnt, tot, tot_sq, mx]
end | [
"def",
"measure",
"cnt",
"=",
"Measure",
".",
"new",
"(",
"@id",
".",
"with_stat",
"(",
"'count'",
")",
",",
"@count",
".",
"get_and_set",
"(",
"0",
")",
")",
"tot",
"=",
"Measure",
".",
"new",
"(",
"@id",
".",
"with_stat",
"(",
"'totalAmount'",
")",
",",
"@total_amount",
".",
"get_and_set",
"(",
"0",
")",
")",
"tot_sq",
"=",
"Measure",
".",
"new",
"(",
"@id",
".",
"with_stat",
"(",
"'totalOfSquares'",
")",
",",
"@total_sq",
".",
"get_and_set",
"(",
"0",
")",
")",
"mx",
"=",
"Measure",
".",
"new",
"(",
"@id",
".",
"with_stat",
"(",
"'max'",
")",
",",
"@max",
".",
"get_and_set",
"(",
"Float",
"::",
"NAN",
")",
")",
"[",
"cnt",
",",
"tot",
",",
"tot_sq",
",",
"mx",
"]",
"end"
] | Get a list of measurements, and reset the stats
The stats returned are the current count, the total amount,
the sum of the square of the amounts recorded, and the max value | [
"Get",
"a",
"list",
"of",
"measurements",
"and",
"reset",
"the",
"stats",
"The",
"stats",
"returned",
"are",
"the",
"current",
"count",
"the",
"total",
"amount",
"the",
"sum",
"of",
"the",
"square",
"of",
"the",
"amounts",
"recorded",
"and",
"the",
"max",
"value"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/distribution_summary.rb#L42-L51 | train |
Netflix/spectator-rb | lib/spectator/http.rb | Spectator.Http.post_json | def post_json(endpoint, payload)
s = payload.to_json
uri = URI(endpoint)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
req.body = s
begin
res = http.request(req)
rescue StandardError => e
Spectator.logger.info("Cause #{e.cause} - msg=#{e.message}")
return 400
end
res.value
end | ruby | def post_json(endpoint, payload)
s = payload.to_json
uri = URI(endpoint)
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
req.body = s
begin
res = http.request(req)
rescue StandardError => e
Spectator.logger.info("Cause #{e.cause} - msg=#{e.message}")
return 400
end
res.value
end | [
"def",
"post_json",
"(",
"endpoint",
",",
"payload",
")",
"s",
"=",
"payload",
".",
"to_json",
"uri",
"=",
"URI",
"(",
"endpoint",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
",",
"'Content-Type'",
"=>",
"'application/json'",
")",
"req",
".",
"body",
"=",
"s",
"begin",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"rescue",
"StandardError",
"=>",
"e",
"Spectator",
".",
"logger",
".",
"info",
"(",
"\"Cause #{e.cause} - msg=#{e.message}\"",
")",
"return",
"400",
"end",
"res",
".",
"value",
"end"
] | Create a new instance using the given registry
to record stats for the requests performed
Send a JSON payload to a given endpoing | [
"Create",
"a",
"new",
"instance",
"using",
"the",
"given",
"registry",
"to",
"record",
"stats",
"for",
"the",
"requests",
"performed",
"Send",
"a",
"JSON",
"payload",
"to",
"a",
"given",
"endpoing"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/http.rb#L14-L28 | train |
Netflix/spectator-rb | lib/spectator/registry.rb | Spectator.Publisher.stop | def stop
unless @started
Spectator.logger.info('Attemping to stop Spectator ' \
'without a previous call to start')
return
end
@should_stop = true
Spectator.logger.info('Stopping spectator')
@publish_thread.kill if @publish_thread
@started = false
Spectator.logger.info('Sending last batch of metrics before exiting')
send_metrics_now
end | ruby | def stop
unless @started
Spectator.logger.info('Attemping to stop Spectator ' \
'without a previous call to start')
return
end
@should_stop = true
Spectator.logger.info('Stopping spectator')
@publish_thread.kill if @publish_thread
@started = false
Spectator.logger.info('Sending last batch of metrics before exiting')
send_metrics_now
end | [
"def",
"stop",
"unless",
"@started",
"Spectator",
".",
"logger",
".",
"info",
"(",
"'Attemping to stop Spectator '",
"'without a previous call to start'",
")",
"return",
"end",
"@should_stop",
"=",
"true",
"Spectator",
".",
"logger",
".",
"info",
"(",
"'Stopping spectator'",
")",
"@publish_thread",
".",
"kill",
"if",
"@publish_thread",
"@started",
"=",
"false",
"Spectator",
".",
"logger",
".",
"info",
"(",
"'Sending last batch of metrics before exiting'",
")",
"send_metrics_now",
"end"
] | Stop publishing measurements | [
"Stop",
"publishing",
"measurements"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L157-L171 | train |
Netflix/spectator-rb | lib/spectator/registry.rb | Spectator.Publisher.op_for_measurement | def op_for_measurement(measure)
stat = measure.id.tags.fetch(:statistic, :unknown)
OPS.fetch(stat, UNKNOWN_OP)
end | ruby | def op_for_measurement(measure)
stat = measure.id.tags.fetch(:statistic, :unknown)
OPS.fetch(stat, UNKNOWN_OP)
end | [
"def",
"op_for_measurement",
"(",
"measure",
")",
"stat",
"=",
"measure",
".",
"id",
".",
"tags",
".",
"fetch",
"(",
":statistic",
",",
":unknown",
")",
"OPS",
".",
"fetch",
"(",
"stat",
",",
"UNKNOWN_OP",
")",
"end"
] | Get the operation to be used for the given Measure
Gauges are aggregated using MAX_OP, counters with ADD_OP | [
"Get",
"the",
"operation",
"to",
"be",
"used",
"for",
"the",
"given",
"Measure",
"Gauges",
"are",
"aggregated",
"using",
"MAX_OP",
"counters",
"with",
"ADD_OP"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L187-L190 | train |
Netflix/spectator-rb | lib/spectator/registry.rb | Spectator.Publisher.should_send | def should_send(measure)
op = op_for_measurement(measure)
return measure.value > 0 if op == ADD_OP
return !measure.value.nan? if op == MAX_OP
false
end | ruby | def should_send(measure)
op = op_for_measurement(measure)
return measure.value > 0 if op == ADD_OP
return !measure.value.nan? if op == MAX_OP
false
end | [
"def",
"should_send",
"(",
"measure",
")",
"op",
"=",
"op_for_measurement",
"(",
"measure",
")",
"return",
"measure",
".",
"value",
">",
"0",
"if",
"op",
"==",
"ADD_OP",
"return",
"!",
"measure",
".",
"value",
".",
"nan?",
"if",
"op",
"==",
"MAX_OP",
"false",
"end"
] | Gauges are sent if they have a value
Counters if they have a number of increments greater than 0 | [
"Gauges",
"are",
"sent",
"if",
"they",
"have",
"a",
"value",
"Counters",
"if",
"they",
"have",
"a",
"number",
"of",
"increments",
"greater",
"than",
"0"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L194-L200 | train |
Netflix/spectator-rb | lib/spectator/registry.rb | Spectator.Publisher.build_string_table | def build_string_table(measurements)
common_tags = @registry.common_tags
table = {}
common_tags.each do |k, v|
table[k] = 0
table[v] = 0
end
table[:name] = 0
measurements.each do |m|
table[m.id.name] = 0
m.id.tags.each do |k, v|
table[k] = 0
table[v] = 0
end
end
keys = table.keys.sort
keys.each_with_index do |str, index|
table[str] = index
end
table
end | ruby | def build_string_table(measurements)
common_tags = @registry.common_tags
table = {}
common_tags.each do |k, v|
table[k] = 0
table[v] = 0
end
table[:name] = 0
measurements.each do |m|
table[m.id.name] = 0
m.id.tags.each do |k, v|
table[k] = 0
table[v] = 0
end
end
keys = table.keys.sort
keys.each_with_index do |str, index|
table[str] = index
end
table
end | [
"def",
"build_string_table",
"(",
"measurements",
")",
"common_tags",
"=",
"@registry",
".",
"common_tags",
"table",
"=",
"{",
"}",
"common_tags",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"table",
"[",
"k",
"]",
"=",
"0",
"table",
"[",
"v",
"]",
"=",
"0",
"end",
"table",
"[",
":name",
"]",
"=",
"0",
"measurements",
".",
"each",
"do",
"|",
"m",
"|",
"table",
"[",
"m",
".",
"id",
".",
"name",
"]",
"=",
"0",
"m",
".",
"id",
".",
"tags",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"table",
"[",
"k",
"]",
"=",
"0",
"table",
"[",
"v",
"]",
"=",
"0",
"end",
"end",
"keys",
"=",
"table",
".",
"keys",
".",
"sort",
"keys",
".",
"each_with_index",
"do",
"|",
"str",
",",
"index",
"|",
"table",
"[",
"str",
"]",
"=",
"index",
"end",
"table",
"end"
] | Build a string table from the list of measurements
Unique words are identified, and assigned a number starting from 0 based
on their lexicographical order | [
"Build",
"a",
"string",
"table",
"from",
"the",
"list",
"of",
"measurements",
"Unique",
"words",
"are",
"identified",
"and",
"assigned",
"a",
"number",
"starting",
"from",
"0",
"based",
"on",
"their",
"lexicographical",
"order"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L205-L225 | train |
Netflix/spectator-rb | lib/spectator/registry.rb | Spectator.Publisher.payload_for_measurements | def payload_for_measurements(measurements)
table = build_string_table(measurements)
payload = []
payload.push(table.length)
strings = table.keys.sort
payload.concat(strings)
measurements.each { |m| append_measurement(payload, table, m) }
payload
end | ruby | def payload_for_measurements(measurements)
table = build_string_table(measurements)
payload = []
payload.push(table.length)
strings = table.keys.sort
payload.concat(strings)
measurements.each { |m| append_measurement(payload, table, m) }
payload
end | [
"def",
"payload_for_measurements",
"(",
"measurements",
")",
"table",
"=",
"build_string_table",
"(",
"measurements",
")",
"payload",
"=",
"[",
"]",
"payload",
".",
"push",
"(",
"table",
".",
"length",
")",
"strings",
"=",
"table",
".",
"keys",
".",
"sort",
"payload",
".",
"concat",
"(",
"strings",
")",
"measurements",
".",
"each",
"{",
"|",
"m",
"|",
"append_measurement",
"(",
"payload",
",",
"table",
",",
"m",
")",
"}",
"payload",
"end"
] | Generate a payload from the list of measurements
The payload is an array, with the number of elements in the string table
The string table, and measurements | [
"Generate",
"a",
"payload",
"from",
"the",
"list",
"of",
"measurements",
"The",
"payload",
"is",
"an",
"array",
"with",
"the",
"number",
"of",
"elements",
"in",
"the",
"string",
"table",
"The",
"string",
"table",
"and",
"measurements"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L256-L264 | train |
Netflix/spectator-rb | lib/spectator/registry.rb | Spectator.Publisher.send_metrics_now | def send_metrics_now
ms = registry_measurements
if ms.empty?
Spectator.logger.debug 'No measurements to send'
else
uri = @registry.config[:uri]
ms.each_slice(@registry.batch_size) do |batch|
payload = payload_for_measurements(batch)
Spectator.logger.info "Sending #{batch.length} measurements to #{uri}"
@http.post_json(uri, payload)
end
end
end | ruby | def send_metrics_now
ms = registry_measurements
if ms.empty?
Spectator.logger.debug 'No measurements to send'
else
uri = @registry.config[:uri]
ms.each_slice(@registry.batch_size) do |batch|
payload = payload_for_measurements(batch)
Spectator.logger.info "Sending #{batch.length} measurements to #{uri}"
@http.post_json(uri, payload)
end
end
end | [
"def",
"send_metrics_now",
"ms",
"=",
"registry_measurements",
"if",
"ms",
".",
"empty?",
"Spectator",
".",
"logger",
".",
"debug",
"'No measurements to send'",
"else",
"uri",
"=",
"@registry",
".",
"config",
"[",
":uri",
"]",
"ms",
".",
"each_slice",
"(",
"@registry",
".",
"batch_size",
")",
"do",
"|",
"batch",
"|",
"payload",
"=",
"payload_for_measurements",
"(",
"batch",
")",
"Spectator",
".",
"logger",
".",
"info",
"\"Sending #{batch.length} measurements to #{uri}\"",
"@http",
".",
"post_json",
"(",
"uri",
",",
"payload",
")",
"end",
"end",
"end"
] | Send the current measurements to our aggregator service | [
"Send",
"the",
"current",
"measurements",
"to",
"our",
"aggregator",
"service"
] | 0022320f729ea716ca0d12123caf07668e137e0f | https://github.com/Netflix/spectator-rb/blob/0022320f729ea716ca0d12123caf07668e137e0f/lib/spectator/registry.rb#L272-L285 | train |
troessner/transitions | lib/transitions/event.rb | Transitions.Event.timestamp= | def timestamp=(values)
values.each do |value|
case value
when String, Symbol, TrueClass
@timestamps << value
else
fail ArgumentError, 'timestamp must be either: true, a String or a Symbol'
end
end
end | ruby | def timestamp=(values)
values.each do |value|
case value
when String, Symbol, TrueClass
@timestamps << value
else
fail ArgumentError, 'timestamp must be either: true, a String or a Symbol'
end
end
end | [
"def",
"timestamp",
"=",
"(",
"values",
")",
"values",
".",
"each",
"do",
"|",
"value",
"|",
"case",
"value",
"when",
"String",
",",
"Symbol",
",",
"TrueClass",
"@timestamps",
"<<",
"value",
"else",
"fail",
"ArgumentError",
",",
"'timestamp must be either: true, a String or a Symbol'",
"end",
"end",
"end"
] | Set the timestamp attribute.
@raise [ArgumentError] timestamp should be either a String, Symbol or true | [
"Set",
"the",
"timestamp",
"attribute",
"."
] | c31ea6247bf65920fa4a489940ea17d985d2c9df | https://github.com/troessner/transitions/blob/c31ea6247bf65920fa4a489940ea17d985d2c9df/lib/transitions/event.rb#L90-L99 | train |
troessner/transitions | lib/transitions/event.rb | Transitions.Event.timestamp_attribute_name | def timestamp_attribute_name(obj, next_state, user_timestamp)
user_timestamp == true ? default_timestamp_name(obj, next_state) : user_timestamp
end | ruby | def timestamp_attribute_name(obj, next_state, user_timestamp)
user_timestamp == true ? default_timestamp_name(obj, next_state) : user_timestamp
end | [
"def",
"timestamp_attribute_name",
"(",
"obj",
",",
"next_state",
",",
"user_timestamp",
")",
"user_timestamp",
"==",
"true",
"?",
"default_timestamp_name",
"(",
"obj",
",",
"next_state",
")",
":",
"user_timestamp",
"end"
] | Returns the name of the timestamp attribute for this event
If the timestamp was simply true it returns the default_timestamp_name
otherwise, returns the user-specified timestamp name | [
"Returns",
"the",
"name",
"of",
"the",
"timestamp",
"attribute",
"for",
"this",
"event",
"If",
"the",
"timestamp",
"was",
"simply",
"true",
"it",
"returns",
"the",
"default_timestamp_name",
"otherwise",
"returns",
"the",
"user",
"-",
"specified",
"timestamp",
"name"
] | c31ea6247bf65920fa4a489940ea17d985d2c9df | https://github.com/troessner/transitions/blob/c31ea6247bf65920fa4a489940ea17d985d2c9df/lib/transitions/event.rb#L106-L108 | train |
glebm/rails_email_preview | app/controllers/rails_email_preview/emails_controller.rb | RailsEmailPreview.EmailsController.show | def show
prevent_browser_caching
cms_edit_links!
with_email_locale do
if @preview.respond_to?(:preview_mail)
@mail, body = mail_and_body
@mail_body_html = render_to_string(inline: body, layout: 'rails_email_preview/email')
else
raise ArgumentError.new("#{@preview} is not a preview class, does not respond_to?(:preview_mail)")
end
end
end | ruby | def show
prevent_browser_caching
cms_edit_links!
with_email_locale do
if @preview.respond_to?(:preview_mail)
@mail, body = mail_and_body
@mail_body_html = render_to_string(inline: body, layout: 'rails_email_preview/email')
else
raise ArgumentError.new("#{@preview} is not a preview class, does not respond_to?(:preview_mail)")
end
end
end | [
"def",
"show",
"prevent_browser_caching",
"cms_edit_links!",
"with_email_locale",
"do",
"if",
"@preview",
".",
"respond_to?",
"(",
":preview_mail",
")",
"@mail",
",",
"body",
"=",
"mail_and_body",
"@mail_body_html",
"=",
"render_to_string",
"(",
"inline",
":",
"body",
",",
"layout",
":",
"'rails_email_preview/email'",
")",
"else",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{@preview} is not a preview class, does not respond_to?(:preview_mail)\"",
")",
"end",
"end",
"end"
] | Preview an email | [
"Preview",
"an",
"email"
] | 723c126fbbbc4d19f75a9e457817e31d7954ea76 | https://github.com/glebm/rails_email_preview/blob/723c126fbbbc4d19f75a9e457817e31d7954ea76/app/controllers/rails_email_preview/emails_controller.rb#L17-L28 | train |
glebm/rails_email_preview | app/controllers/rails_email_preview/emails_controller.rb | RailsEmailPreview.EmailsController.show_headers | def show_headers
mail = with_email_locale { mail_and_body.first }
render partial: 'rails_email_preview/emails/headers', locals: {mail: mail}
end | ruby | def show_headers
mail = with_email_locale { mail_and_body.first }
render partial: 'rails_email_preview/emails/headers', locals: {mail: mail}
end | [
"def",
"show_headers",
"mail",
"=",
"with_email_locale",
"{",
"mail_and_body",
".",
"first",
"}",
"render",
"partial",
":",
"'rails_email_preview/emails/headers'",
",",
"locals",
":",
"{",
"mail",
":",
"mail",
"}",
"end"
] | Render headers partial. Used by the CMS integration to refetch headers after editing. | [
"Render",
"headers",
"partial",
".",
"Used",
"by",
"the",
"CMS",
"integration",
"to",
"refetch",
"headers",
"after",
"editing",
"."
] | 723c126fbbbc4d19f75a9e457817e31d7954ea76 | https://github.com/glebm/rails_email_preview/blob/723c126fbbbc4d19f75a9e457817e31d7954ea76/app/controllers/rails_email_preview/emails_controller.rb#L59-L62 | train |
glebm/rails_email_preview | app/controllers/rails_email_preview/emails_controller.rb | RailsEmailPreview.EmailsController.show_body | def show_body
prevent_browser_caching
cms_edit_links!
with_email_locale do
_, body = mail_and_body
render inline: body, layout: 'rails_email_preview/email'
end
end | ruby | def show_body
prevent_browser_caching
cms_edit_links!
with_email_locale do
_, body = mail_and_body
render inline: body, layout: 'rails_email_preview/email'
end
end | [
"def",
"show_body",
"prevent_browser_caching",
"cms_edit_links!",
"with_email_locale",
"do",
"_",
",",
"body",
"=",
"mail_and_body",
"render",
"inline",
":",
"body",
",",
"layout",
":",
"'rails_email_preview/email'",
"end",
"end"
] | Render email body iframe HTML. Used by the CMS integration to provide a link back to Show from Edit. | [
"Render",
"email",
"body",
"iframe",
"HTML",
".",
"Used",
"by",
"the",
"CMS",
"integration",
"to",
"provide",
"a",
"link",
"back",
"to",
"Show",
"from",
"Edit",
"."
] | 723c126fbbbc4d19f75a9e457817e31d7954ea76 | https://github.com/glebm/rails_email_preview/blob/723c126fbbbc4d19f75a9e457817e31d7954ea76/app/controllers/rails_email_preview/emails_controller.rb#L65-L72 | train |
ricardochimal/taps | lib/taps/utils.rb | Taps.Utils.incorrect_blobs | def incorrect_blobs(db, table)
return [] if (db.url =~ /mysql:\/\//).nil?
columns = []
db.schema(table).each do |data|
column, cdata = data
columns << column if cdata[:db_type] =~ /text/
end
columns
end | ruby | def incorrect_blobs(db, table)
return [] if (db.url =~ /mysql:\/\//).nil?
columns = []
db.schema(table).each do |data|
column, cdata = data
columns << column if cdata[:db_type] =~ /text/
end
columns
end | [
"def",
"incorrect_blobs",
"(",
"db",
",",
"table",
")",
"return",
"[",
"]",
"if",
"(",
"db",
".",
"url",
"=~",
"/",
"\\/",
"\\/",
"/",
")",
".",
"nil?",
"columns",
"=",
"[",
"]",
"db",
".",
"schema",
"(",
"table",
")",
".",
"each",
"do",
"|",
"data",
"|",
"column",
",",
"cdata",
"=",
"data",
"columns",
"<<",
"column",
"if",
"cdata",
"[",
":db_type",
"]",
"=~",
"/",
"/",
"end",
"columns",
"end"
] | mysql text and blobs fields are handled the same way internally
this is not true for other databases so we must check if the field is
actually text and manually convert it back to a string | [
"mysql",
"text",
"and",
"blobs",
"fields",
"are",
"handled",
"the",
"same",
"way",
"internally",
"this",
"is",
"not",
"true",
"for",
"other",
"databases",
"so",
"we",
"must",
"check",
"if",
"the",
"field",
"is",
"actually",
"text",
"and",
"manually",
"convert",
"it",
"back",
"to",
"a",
"string"
] | 93bd2723df7fc14bc7aa9567f4c070c19145e956 | https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/utils.rb#L78-L87 | train |
ricardochimal/taps | lib/taps/utils.rb | Taps.Utils.server_error_handling | def server_error_handling(&blk)
begin
blk.call
rescue Sequel::DatabaseError => e
if e.message =~ /duplicate key value/i
raise Taps::DuplicatePrimaryKeyError, e.message
else
raise
end
end
end | ruby | def server_error_handling(&blk)
begin
blk.call
rescue Sequel::DatabaseError => e
if e.message =~ /duplicate key value/i
raise Taps::DuplicatePrimaryKeyError, e.message
else
raise
end
end
end | [
"def",
"server_error_handling",
"(",
"&",
"blk",
")",
"begin",
"blk",
".",
"call",
"rescue",
"Sequel",
"::",
"DatabaseError",
"=>",
"e",
"if",
"e",
".",
"message",
"=~",
"/",
"/i",
"raise",
"Taps",
"::",
"DuplicatePrimaryKeyError",
",",
"e",
".",
"message",
"else",
"raise",
"end",
"end",
"end"
] | try to detect server side errors to
give the client a more useful error message | [
"try",
"to",
"detect",
"server",
"side",
"errors",
"to",
"give",
"the",
"client",
"a",
"more",
"useful",
"error",
"message"
] | 93bd2723df7fc14bc7aa9567f4c070c19145e956 | https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/utils.rb#L159-L169 | train |
ricardochimal/taps | lib/taps/data_stream.rb | Taps.DataStream.fetch_rows | def fetch_rows
state[:chunksize] = fetch_chunksize
ds = table.order(*order_by).limit(state[:chunksize], state[:offset])
log.debug "DataStream#fetch_rows SQL -> #{ds.sql}"
rows = Taps::Utils.format_data(ds.all,
:string_columns => string_columns,
:schema => db.schema(table_name),
:table => table_name
)
update_chunksize_stats
rows
end | ruby | def fetch_rows
state[:chunksize] = fetch_chunksize
ds = table.order(*order_by).limit(state[:chunksize], state[:offset])
log.debug "DataStream#fetch_rows SQL -> #{ds.sql}"
rows = Taps::Utils.format_data(ds.all,
:string_columns => string_columns,
:schema => db.schema(table_name),
:table => table_name
)
update_chunksize_stats
rows
end | [
"def",
"fetch_rows",
"state",
"[",
":chunksize",
"]",
"=",
"fetch_chunksize",
"ds",
"=",
"table",
".",
"order",
"(",
"order_by",
")",
".",
"limit",
"(",
"state",
"[",
":chunksize",
"]",
",",
"state",
"[",
":offset",
"]",
")",
"log",
".",
"debug",
"\"DataStream#fetch_rows SQL -> #{ds.sql}\"",
"rows",
"=",
"Taps",
"::",
"Utils",
".",
"format_data",
"(",
"ds",
".",
"all",
",",
":string_columns",
"=>",
"string_columns",
",",
":schema",
"=>",
"db",
".",
"schema",
"(",
"table_name",
")",
",",
":table",
"=>",
"table_name",
")",
"update_chunksize_stats",
"rows",
"end"
] | keep a record of the average chunksize within the first few hundred thousand records, after chunksize
goes below 100 or maybe if offset is > 1000 | [
"keep",
"a",
"record",
"of",
"the",
"average",
"chunksize",
"within",
"the",
"first",
"few",
"hundred",
"thousand",
"records",
"after",
"chunksize",
"goes",
"below",
"100",
"or",
"maybe",
"if",
"offset",
"is",
">",
"1000"
] | 93bd2723df7fc14bc7aa9567f4c070c19145e956 | https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/data_stream.rb#L76-L87 | train |
ricardochimal/taps | lib/taps/data_stream.rb | Taps.DataStream.fetch_remote_in_server | def fetch_remote_in_server(params)
json = self.class.parse_json(params[:json])
encoded_data = params[:encoded_data]
rows = parse_encoded_data(encoded_data, json[:checksum])
@complete = rows == { }
unless @complete
import_rows(rows)
rows[:data].size
else
0
end
end | ruby | def fetch_remote_in_server(params)
json = self.class.parse_json(params[:json])
encoded_data = params[:encoded_data]
rows = parse_encoded_data(encoded_data, json[:checksum])
@complete = rows == { }
unless @complete
import_rows(rows)
rows[:data].size
else
0
end
end | [
"def",
"fetch_remote_in_server",
"(",
"params",
")",
"json",
"=",
"self",
".",
"class",
".",
"parse_json",
"(",
"params",
"[",
":json",
"]",
")",
"encoded_data",
"=",
"params",
"[",
":encoded_data",
"]",
"rows",
"=",
"parse_encoded_data",
"(",
"encoded_data",
",",
"json",
"[",
":checksum",
"]",
")",
"@complete",
"=",
"rows",
"==",
"{",
"}",
"unless",
"@complete",
"import_rows",
"(",
"rows",
")",
"rows",
"[",
":data",
"]",
".",
"size",
"else",
"0",
"end",
"end"
] | this one is used inside the server process | [
"this",
"one",
"is",
"used",
"inside",
"the",
"server",
"process"
] | 93bd2723df7fc14bc7aa9567f4c070c19145e956 | https://github.com/ricardochimal/taps/blob/93bd2723df7fc14bc7aa9567f4c070c19145e956/lib/taps/data_stream.rb#L150-L163 | train |
cinchrb/cinch | lib/cinch/handler.rb | Cinch.Handler.stop | def stop
@bot.loggers.debug "[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads..."
@thread_group.list.each do |thread|
Thread.new do
@bot.loggers.debug "[Ending thread] Waiting 10 seconds for #{thread} to finish..."
thread.join(10)
@bot.loggers.debug "[Killing thread] Killing #{thread}"
thread.kill
end
end
end | ruby | def stop
@bot.loggers.debug "[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads..."
@thread_group.list.each do |thread|
Thread.new do
@bot.loggers.debug "[Ending thread] Waiting 10 seconds for #{thread} to finish..."
thread.join(10)
@bot.loggers.debug "[Killing thread] Killing #{thread}"
thread.kill
end
end
end | [
"def",
"stop",
"@bot",
".",
"loggers",
".",
"debug",
"\"[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads...\"",
"@thread_group",
".",
"list",
".",
"each",
"do",
"|",
"thread",
"|",
"Thread",
".",
"new",
"do",
"@bot",
".",
"loggers",
".",
"debug",
"\"[Ending thread] Waiting 10 seconds for #{thread} to finish...\"",
"thread",
".",
"join",
"(",
"10",
")",
"@bot",
".",
"loggers",
".",
"debug",
"\"[Killing thread] Killing #{thread}\"",
"thread",
".",
"kill",
"end",
"end",
"end"
] | Stops execution of the handler. This means stopping and killing
all associated threads.
@return [void] | [
"Stops",
"execution",
"of",
"the",
"handler",
".",
"This",
"means",
"stopping",
"and",
"killing",
"all",
"associated",
"threads",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/handler.rb#L71-L81 | train |
cinchrb/cinch | lib/cinch/handler.rb | Cinch.Handler.call | def call(message, captures, arguments)
bargs = captures + arguments
thread = Thread.new {
@bot.loggers.debug "[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total."
begin
if @execute_in_callback
@bot.callback.instance_exec(message, *@args, *bargs, &@block)
else
@block.call(message, *@args, *bargs)
end
rescue => e
@bot.loggers.exception(e)
ensure
@bot.loggers.debug "[Thread done] For #{self}: #{Thread.current} -- #{@thread_group.list.size - 1} remaining."
end
}
@thread_group.add(thread)
thread
end | ruby | def call(message, captures, arguments)
bargs = captures + arguments
thread = Thread.new {
@bot.loggers.debug "[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total."
begin
if @execute_in_callback
@bot.callback.instance_exec(message, *@args, *bargs, &@block)
else
@block.call(message, *@args, *bargs)
end
rescue => e
@bot.loggers.exception(e)
ensure
@bot.loggers.debug "[Thread done] For #{self}: #{Thread.current} -- #{@thread_group.list.size - 1} remaining."
end
}
@thread_group.add(thread)
thread
end | [
"def",
"call",
"(",
"message",
",",
"captures",
",",
"arguments",
")",
"bargs",
"=",
"captures",
"+",
"arguments",
"thread",
"=",
"Thread",
".",
"new",
"{",
"@bot",
".",
"loggers",
".",
"debug",
"\"[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total.\"",
"begin",
"if",
"@execute_in_callback",
"@bot",
".",
"callback",
".",
"instance_exec",
"(",
"message",
",",
"@args",
",",
"bargs",
",",
"@block",
")",
"else",
"@block",
".",
"call",
"(",
"message",
",",
"@args",
",",
"bargs",
")",
"end",
"rescue",
"=>",
"e",
"@bot",
".",
"loggers",
".",
"exception",
"(",
"e",
")",
"ensure",
"@bot",
".",
"loggers",
".",
"debug",
"\"[Thread done] For #{self}: #{Thread.current} -- #{@thread_group.list.size - 1} remaining.\"",
"end",
"}",
"@thread_group",
".",
"add",
"(",
"thread",
")",
"thread",
"end"
] | Executes the handler.
@param [Message] message Message that caused the invocation
@param [Array] captures Capture groups of the pattern that are
being passed as arguments
@return [Thread] | [
"Executes",
"the",
"handler",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/handler.rb#L89-L110 | train |
cinchrb/cinch | lib/cinch/syncable.rb | Cinch.Syncable.wait_until_synced | def wait_until_synced(attr)
attr = attr.to_sym
waited = 0
while true
return if attribute_synced?(attr)
waited += 1
if waited % 100 == 0
bot.loggers.warn "A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting" % [attr, self.inspect, waited / 10]
bot.loggers.warn caller.map {|s| " #{s}"}
if waited / 10 >= 30
bot.loggers.warn " Giving up..."
raise Exceptions::SyncedAttributeNotAvailable, "'%s' for %s" % [attr, self.inspect]
end
end
sleep 0.1
end
end | ruby | def wait_until_synced(attr)
attr = attr.to_sym
waited = 0
while true
return if attribute_synced?(attr)
waited += 1
if waited % 100 == 0
bot.loggers.warn "A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting" % [attr, self.inspect, waited / 10]
bot.loggers.warn caller.map {|s| " #{s}"}
if waited / 10 >= 30
bot.loggers.warn " Giving up..."
raise Exceptions::SyncedAttributeNotAvailable, "'%s' for %s" % [attr, self.inspect]
end
end
sleep 0.1
end
end | [
"def",
"wait_until_synced",
"(",
"attr",
")",
"attr",
"=",
"attr",
".",
"to_sym",
"waited",
"=",
"0",
"while",
"true",
"return",
"if",
"attribute_synced?",
"(",
"attr",
")",
"waited",
"+=",
"1",
"if",
"waited",
"%",
"100",
"==",
"0",
"bot",
".",
"loggers",
".",
"warn",
"\"A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting\"",
"%",
"[",
"attr",
",",
"self",
".",
"inspect",
",",
"waited",
"/",
"10",
"]",
"bot",
".",
"loggers",
".",
"warn",
"caller",
".",
"map",
"{",
"|",
"s",
"|",
"\" #{s}\"",
"}",
"if",
"waited",
"/",
"10",
">=",
"30",
"bot",
".",
"loggers",
".",
"warn",
"\" Giving up...\"",
"raise",
"Exceptions",
"::",
"SyncedAttributeNotAvailable",
",",
"\"'%s' for %s\"",
"%",
"[",
"attr",
",",
"self",
".",
"inspect",
"]",
"end",
"end",
"sleep",
"0.1",
"end",
"end"
] | Blocks until the object is synced.
@return [void]
@api private | [
"Blocks",
"until",
"the",
"object",
"is",
"synced",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/syncable.rb#L8-L26 | train |
cinchrb/cinch | lib/cinch/configuration.rb | Cinch.Configuration.load | def load(new_config, from_default = false)
if from_default
@table = self.class.default_config
end
new_config.each do |option, value|
if value.is_a?(Hash)
if self[option].is_a?(Configuration)
self[option].load(value)
else
# recursive merging is handled by subclasses like
# Configuration::Plugins
self[option] = value
end
else
self[option] = value
end
end
end | ruby | def load(new_config, from_default = false)
if from_default
@table = self.class.default_config
end
new_config.each do |option, value|
if value.is_a?(Hash)
if self[option].is_a?(Configuration)
self[option].load(value)
else
# recursive merging is handled by subclasses like
# Configuration::Plugins
self[option] = value
end
else
self[option] = value
end
end
end | [
"def",
"load",
"(",
"new_config",
",",
"from_default",
"=",
"false",
")",
"if",
"from_default",
"@table",
"=",
"self",
".",
"class",
".",
"default_config",
"end",
"new_config",
".",
"each",
"do",
"|",
"option",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"if",
"self",
"[",
"option",
"]",
".",
"is_a?",
"(",
"Configuration",
")",
"self",
"[",
"option",
"]",
".",
"load",
"(",
"value",
")",
"else",
"# recursive merging is handled by subclasses like",
"# Configuration::Plugins",
"self",
"[",
"option",
"]",
"=",
"value",
"end",
"else",
"self",
"[",
"option",
"]",
"=",
"value",
"end",
"end",
"end"
] | Loads a configuration from a hash by merging the hash with
either the current configuration or the default configuration.
@param [Hash] new_config The configuration to load
@param [Boolean] from_default If true, the configuration won't
be merged with the currently set up configuration (by prior
calls to {#load} or {Bot#configure}) but with the default
configuration.
@return [void] | [
"Loads",
"a",
"configuration",
"from",
"a",
"hash",
"by",
"merging",
"the",
"hash",
"with",
"either",
"the",
"current",
"configuration",
"or",
"the",
"default",
"configuration",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/configuration.rb#L44-L62 | train |
cinchrb/cinch | lib/cinch/user_list.rb | Cinch.UserList.find | def find(nick)
if nick == @bot.nick
return @bot
end
downcased_nick = nick.irc_downcase(@bot.irc.isupport["CASEMAPPING"])
@mutex.synchronize do
return @cache[downcased_nick]
end
end | ruby | def find(nick)
if nick == @bot.nick
return @bot
end
downcased_nick = nick.irc_downcase(@bot.irc.isupport["CASEMAPPING"])
@mutex.synchronize do
return @cache[downcased_nick]
end
end | [
"def",
"find",
"(",
"nick",
")",
"if",
"nick",
"==",
"@bot",
".",
"nick",
"return",
"@bot",
"end",
"downcased_nick",
"=",
"nick",
".",
"irc_downcase",
"(",
"@bot",
".",
"irc",
".",
"isupport",
"[",
"\"CASEMAPPING\"",
"]",
")",
"@mutex",
".",
"synchronize",
"do",
"return",
"@cache",
"[",
"downcased_nick",
"]",
"end",
"end"
] | Finds a user.
@param [String] nick nick of a user
@return [User, nil] | [
"Finds",
"a",
"user",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user_list.rb#L61-L70 | train |
cinchrb/cinch | lib/cinch/user.rb | Cinch.User.refresh | def refresh
return if @in_whois
@data.keys.each do |attr|
unsync attr
end
@in_whois = true
if @bot.irc.network.whois_only_one_argument?
@bot.irc.send "WHOIS #@name"
else
@bot.irc.send "WHOIS #@name #@name"
end
end | ruby | def refresh
return if @in_whois
@data.keys.each do |attr|
unsync attr
end
@in_whois = true
if @bot.irc.network.whois_only_one_argument?
@bot.irc.send "WHOIS #@name"
else
@bot.irc.send "WHOIS #@name #@name"
end
end | [
"def",
"refresh",
"return",
"if",
"@in_whois",
"@data",
".",
"keys",
".",
"each",
"do",
"|",
"attr",
"|",
"unsync",
"attr",
"end",
"@in_whois",
"=",
"true",
"if",
"@bot",
".",
"irc",
".",
"network",
".",
"whois_only_one_argument?",
"@bot",
".",
"irc",
".",
"send",
"\"WHOIS #@name\"",
"else",
"@bot",
".",
"irc",
".",
"send",
"\"WHOIS #@name #@name\"",
"end",
"end"
] | Queries the IRC server for information on the user. This will
set the User's state to not synced. After all information are
received, the object will be set back to synced.
@return [void]
@note The alias `whois` is deprecated and will be removed in a
future version. | [
"Queries",
"the",
"IRC",
"server",
"for",
"information",
"on",
"the",
"user",
".",
"This",
"will",
"set",
"the",
"User",
"s",
"state",
"to",
"not",
"synced",
".",
"After",
"all",
"information",
"are",
"received",
"the",
"object",
"will",
"be",
"set",
"back",
"to",
"synced",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L249-L261 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.