id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
8,600
jD91mZM2/synacrb
lib/synacrb.rb
Synacrb.Session.verify_callback
def verify_callback(_, cert) pem = cert.current_cert.public_key.to_pem sha256 = OpenSSL::Digest::SHA256.new hash = sha256.digest(pem).unpack("H*") hash[0].casecmp(@hash).zero? end
ruby
def verify_callback(_, cert) pem = cert.current_cert.public_key.to_pem sha256 = OpenSSL::Digest::SHA256.new hash = sha256.digest(pem).unpack("H*") hash[0].casecmp(@hash).zero? end
[ "def", "verify_callback", "(", "_", ",", "cert", ")", "pem", "=", "cert", ".", "current_cert", ".", "public_key", ".", "to_pem", "sha256", "=", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "new", "hash", "=", "sha256", ".", "digest", "(", "pem", ")", ".", "unpack", "(", "\"H*\"", ")", "hash", "[", "0", "]", ".", "casecmp", "(", "@hash", ")", ".", "zero?", "end" ]
Connect to the server OpenSSL verify callback used by initialize when optional callback argument isn't set.
[ "Connect", "to", "the", "server", "OpenSSL", "verify", "callback", "used", "by", "initialize", "when", "optional", "callback", "argument", "isn", "t", "set", "." ]
c272c8a598f5d41f9185a5b5335213de91c944ab
https://github.com/jD91mZM2/synacrb/blob/c272c8a598f5d41f9185a5b5335213de91c944ab/lib/synacrb.rb#L39-L45
8,601
jD91mZM2/synacrb
lib/synacrb.rb
Synacrb.Session.login_with_token
def login_with_token(bot, name, token) send Common::Login.new(bot, name, nil, token) end
ruby
def login_with_token(bot, name, token) send Common::Login.new(bot, name, nil, token) end
[ "def", "login_with_token", "(", "bot", ",", "name", ",", "token", ")", "send", "Common", "::", "Login", ".", "new", "(", "bot", ",", "name", ",", "nil", ",", "token", ")", "end" ]
Sends the login packet with specific token. Read the result with `read`.
[ "Sends", "the", "login", "packet", "with", "specific", "token", ".", "Read", "the", "result", "with", "read", "." ]
c272c8a598f5d41f9185a5b5335213de91c944ab
https://github.com/jD91mZM2/synacrb/blob/c272c8a598f5d41f9185a5b5335213de91c944ab/lib/synacrb.rb#L61-L63
8,602
jD91mZM2/synacrb
lib/synacrb.rb
Synacrb.Session.send
def send(packet) id = Common.packet_to_id(packet) data = [id, [packet.to_a]].to_msgpack @stream.write Common.encode_u16(data.length) @stream.write data end
ruby
def send(packet) id = Common.packet_to_id(packet) data = [id, [packet.to_a]].to_msgpack @stream.write Common.encode_u16(data.length) @stream.write data end
[ "def", "send", "(", "packet", ")", "id", "=", "Common", ".", "packet_to_id", "(", "packet", ")", "data", "=", "[", "id", ",", "[", "packet", ".", "to_a", "]", "]", ".", "to_msgpack", "@stream", ".", "write", "Common", ".", "encode_u16", "(", "data", ".", "length", ")", "@stream", ".", "write", "data", "end" ]
Transmit a packet over the connection
[ "Transmit", "a", "packet", "over", "the", "connection" ]
c272c8a598f5d41f9185a5b5335213de91c944ab
https://github.com/jD91mZM2/synacrb/blob/c272c8a598f5d41f9185a5b5335213de91c944ab/lib/synacrb.rb#L66-L72
8,603
jD91mZM2/synacrb
lib/synacrb.rb
Synacrb.Session.read
def read() size_a = @stream.read 2 size = Common.decode_u16(size_a) data = @stream.read size data = MessagePack.unpack data class_ = Common.packet_from_id data[0] class_.new *data[1][0] end
ruby
def read() size_a = @stream.read 2 size = Common.decode_u16(size_a) data = @stream.read size data = MessagePack.unpack data class_ = Common.packet_from_id data[0] class_.new *data[1][0] end
[ "def", "read", "(", ")", "size_a", "=", "@stream", ".", "read", "2", "size", "=", "Common", ".", "decode_u16", "(", "size_a", ")", "data", "=", "@stream", ".", "read", "size", "data", "=", "MessagePack", ".", "unpack", "data", "class_", "=", "Common", ".", "packet_from_id", "data", "[", "0", "]", "class_", ".", "new", "data", "[", "1", "]", "[", "0", "]", "end" ]
Read a packet from the connection
[ "Read", "a", "packet", "from", "the", "connection" ]
c272c8a598f5d41f9185a5b5335213de91c944ab
https://github.com/jD91mZM2/synacrb/blob/c272c8a598f5d41f9185a5b5335213de91c944ab/lib/synacrb.rb#L75-L83
8,604
brunofrank/trustvox
lib/trustvox/store.rb
Trustvox.Store.create
def create(store_data) auth_by_platform_token! response = self.class.post('/stores', { body: store_data.to_json }) data = JSON.parse(response.body) rescue nil { status: response.code, data: data, } end
ruby
def create(store_data) auth_by_platform_token! response = self.class.post('/stores', { body: store_data.to_json }) data = JSON.parse(response.body) rescue nil { status: response.code, data: data, } end
[ "def", "create", "(", "store_data", ")", "auth_by_platform_token!", "response", "=", "self", ".", "class", ".", "post", "(", "'/stores'", ",", "{", "body", ":", "store_data", ".", "to_json", "}", ")", "data", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "rescue", "nil", "{", "status", ":", "response", ".", "code", ",", "data", ":", "data", ",", "}", "end" ]
Call create store api @param store_data
[ "Call", "create", "store", "api" ]
1ceb4cfe0bf7c6fa51b951a02810f4e973d8ec23
https://github.com/brunofrank/trustvox/blob/1ceb4cfe0bf7c6fa51b951a02810f4e973d8ec23/lib/trustvox/store.rb#L7-L16
8,605
brunofrank/trustvox
lib/trustvox/store.rb
Trustvox.Store.push_order
def push_order(order_data) body = Utils.build_push_order_data(order_data) auth_by_store_token! response = self.class.post("/stores/#{Config.store_id}/orders", { body: body.to_json }) data = JSON.parse(response.body) rescue nil { status: response.code, data: data } end
ruby
def push_order(order_data) body = Utils.build_push_order_data(order_data) auth_by_store_token! response = self.class.post("/stores/#{Config.store_id}/orders", { body: body.to_json }) data = JSON.parse(response.body) rescue nil { status: response.code, data: data } end
[ "def", "push_order", "(", "order_data", ")", "body", "=", "Utils", ".", "build_push_order_data", "(", "order_data", ")", "auth_by_store_token!", "response", "=", "self", ".", "class", ".", "post", "(", "\"/stores/#{Config.store_id}/orders\"", ",", "{", "body", ":", "body", ".", "to_json", "}", ")", "data", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "rescue", "nil", "{", "status", ":", "response", ".", "code", ",", "data", ":", "data", "}", "end" ]
Call order api @param order_data
[ "Call", "order", "api" ]
1ceb4cfe0bf7c6fa51b951a02810f4e973d8ec23
https://github.com/brunofrank/trustvox/blob/1ceb4cfe0bf7c6fa51b951a02810f4e973d8ec23/lib/trustvox/store.rb#L20-L27
8,606
brunofrank/trustvox
lib/trustvox/store.rb
Trustvox.Store.load_store
def load_store(url) auth_by_platform_token! response = self.class.get("/stores", { query: { url: url} }) data = JSON.parse(response.body) rescue nil { status: response.code, data: data, } end
ruby
def load_store(url) auth_by_platform_token! response = self.class.get("/stores", { query: { url: url} }) data = JSON.parse(response.body) rescue nil { status: response.code, data: data, } end
[ "def", "load_store", "(", "url", ")", "auth_by_platform_token!", "response", "=", "self", ".", "class", ".", "get", "(", "\"/stores\"", ",", "{", "query", ":", "{", "url", ":", "url", "}", "}", ")", "data", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "rescue", "nil", "{", "status", ":", "response", ".", "code", ",", "data", ":", "data", ",", "}", "end" ]
Call store lookup api @param url
[ "Call", "store", "lookup", "api" ]
1ceb4cfe0bf7c6fa51b951a02810f4e973d8ec23
https://github.com/brunofrank/trustvox/blob/1ceb4cfe0bf7c6fa51b951a02810f4e973d8ec23/lib/trustvox/store.rb#L31-L40
8,607
irvingwashington/gem_footprint_analyzer
lib/gem_footprint_analyzer/average_runner.rb
GemFootprintAnalyzer.AverageRunner.calculate_averages
def calculate_averages(results) Array.new(results.first.size) do |require_number| samples = results.map { |r| r[require_number] } first_sample = samples.first average = initialize_average_with_copied_fields(first_sample) AVERAGED_FIELDS.map do |field| next unless first_sample.key?(field) average[field] = calculate_average(samples.map { |s| s[field] }) end average end end
ruby
def calculate_averages(results) Array.new(results.first.size) do |require_number| samples = results.map { |r| r[require_number] } first_sample = samples.first average = initialize_average_with_copied_fields(first_sample) AVERAGED_FIELDS.map do |field| next unless first_sample.key?(field) average[field] = calculate_average(samples.map { |s| s[field] }) end average end end
[ "def", "calculate_averages", "(", "results", ")", "Array", ".", "new", "(", "results", ".", "first", ".", "size", ")", "do", "|", "require_number", "|", "samples", "=", "results", ".", "map", "{", "|", "r", "|", "r", "[", "require_number", "]", "}", "first_sample", "=", "samples", ".", "first", "average", "=", "initialize_average_with_copied_fields", "(", "first_sample", ")", "AVERAGED_FIELDS", ".", "map", "do", "|", "field", "|", "next", "unless", "first_sample", ".", "key?", "(", "field", ")", "average", "[", "field", "]", "=", "calculate_average", "(", "samples", ".", "map", "{", "|", "s", "|", "s", "[", "field", "]", "}", ")", "end", "average", "end", "end" ]
Take corresponding results array values and compare them
[ "Take", "corresponding", "results", "array", "values", "and", "compare", "them" ]
19a8892f6baaeb16b1b166144c4f73852396220c
https://github.com/irvingwashington/gem_footprint_analyzer/blob/19a8892f6baaeb16b1b166144c4f73852396220c/lib/gem_footprint_analyzer/average_runner.rb#L30-L43
8,608
michaeledgar/amp-front
lib/amp-front/third_party/maruku/helpers.rb
MaRuKu.Helpers.md_el
def md_el(node_type, children=[], meta={}, al=nil) if (e=children.first).kind_of?(MDElement) and e.node_type == :ial then if al al += e.ial else al = e.ial end children.shift end e = MDElement.new(node_type, children, meta, al) e.doc = @doc return e end
ruby
def md_el(node_type, children=[], meta={}, al=nil) if (e=children.first).kind_of?(MDElement) and e.node_type == :ial then if al al += e.ial else al = e.ial end children.shift end e = MDElement.new(node_type, children, meta, al) e.doc = @doc return e end
[ "def", "md_el", "(", "node_type", ",", "children", "=", "[", "]", ",", "meta", "=", "{", "}", ",", "al", "=", "nil", ")", "if", "(", "e", "=", "children", ".", "first", ")", ".", "kind_of?", "(", "MDElement", ")", "and", "e", ".", "node_type", "==", ":ial", "then", "if", "al", "al", "+=", "e", ".", "ial", "else", "al", "=", "e", ".", "ial", "end", "children", ".", "shift", "end", "e", "=", "MDElement", ".", "new", "(", "node_type", ",", "children", ",", "meta", ",", "al", ")", "e", ".", "doc", "=", "@doc", "return", "e", "end" ]
if the first is a md_ial, it is used as such
[ "if", "the", "first", "is", "a", "md_ial", "it", "is", "used", "as", "such" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/helpers.rb#L34-L47
8,609
hackberry-gh/actn-db
lib/actn/paths.rb
Actn.Paths.find_root_with_flag
def find_root_with_flag(flag, default=nil) root_path = self.called_from[0] while root_path && ::File.directory?(root_path) && !::File.exist?("#{root_path}/#{flag}") parent = ::File.dirname(root_path) root_path = parent != root_path && parent end root = ::File.exist?("#{root_path}/#{flag}") ? root_path : default raise "Could not find root path for #{self}" unless root RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? Pathname.new(root).expand_path : Pathname.new(root).realpath end
ruby
def find_root_with_flag(flag, default=nil) root_path = self.called_from[0] while root_path && ::File.directory?(root_path) && !::File.exist?("#{root_path}/#{flag}") parent = ::File.dirname(root_path) root_path = parent != root_path && parent end root = ::File.exist?("#{root_path}/#{flag}") ? root_path : default raise "Could not find root path for #{self}" unless root RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? Pathname.new(root).expand_path : Pathname.new(root).realpath end
[ "def", "find_root_with_flag", "(", "flag", ",", "default", "=", "nil", ")", "root_path", "=", "self", ".", "called_from", "[", "0", "]", "while", "root_path", "&&", "::", "File", ".", "directory?", "(", "root_path", ")", "&&", "!", "::", "File", ".", "exist?", "(", "\"#{root_path}/#{flag}\"", ")", "parent", "=", "::", "File", ".", "dirname", "(", "root_path", ")", "root_path", "=", "parent", "!=", "root_path", "&&", "parent", "end", "root", "=", "::", "File", ".", "exist?", "(", "\"#{root_path}/#{flag}\"", ")", "?", "root_path", ":", "default", "raise", "\"Could not find root path for #{self}\"", "unless", "root", "RbConfig", "::", "CONFIG", "[", "'host_os'", "]", "=~", "/", "/", "?", "Pathname", ".", "new", "(", "root", ")", ".", "expand_path", ":", "Pathname", ".", "new", "(", "root", ")", ".", "realpath", "end" ]
i steal this from rails
[ "i", "steal", "this", "from", "rails" ]
53b41773147507d5a7393f6a0b2b056f1e57f6ee
https://github.com/hackberry-gh/actn-db/blob/53b41773147507d5a7393f6a0b2b056f1e57f6ee/lib/actn/paths.rb#L21-L34
8,610
addagger/gaigo
lib/gaigo/helpers/form_helper_v3.rb
Gaigo.FormHelper.ilabel
def ilabel(object_name, method, content_or_options = nil, options = nil, &block) options ||= {} content_is_options = content_or_options.is_a?(Hash) if content_is_options || block_given? options.merge!(content_or_options) if content_is_options text = nil else text = content_or_options end ActionView::Helpers::InstanceTag.new(object_name, method, self, options.delete(:object)).to_ilabel_tag(text, options, &block) end
ruby
def ilabel(object_name, method, content_or_options = nil, options = nil, &block) options ||= {} content_is_options = content_or_options.is_a?(Hash) if content_is_options || block_given? options.merge!(content_or_options) if content_is_options text = nil else text = content_or_options end ActionView::Helpers::InstanceTag.new(object_name, method, self, options.delete(:object)).to_ilabel_tag(text, options, &block) end
[ "def", "ilabel", "(", "object_name", ",", "method", ",", "content_or_options", "=", "nil", ",", "options", "=", "nil", ",", "&", "block", ")", "options", "||=", "{", "}", "content_is_options", "=", "content_or_options", ".", "is_a?", "(", "Hash", ")", "if", "content_is_options", "||", "block_given?", "options", ".", "merge!", "(", "content_or_options", ")", "if", "content_is_options", "text", "=", "nil", "else", "text", "=", "content_or_options", "end", "ActionView", "::", "Helpers", "::", "InstanceTag", ".", "new", "(", "object_name", ",", "method", ",", "self", ",", "options", ".", "delete", "(", ":object", ")", ")", ".", "to_ilabel_tag", "(", "text", ",", "options", ",", "block", ")", "end" ]
module_eval <<-EOV
[ "module_eval", "<<", "-", "EOV" ]
b4dcc77052e859256defdca22d6bbbdfb07480c8
https://github.com/addagger/gaigo/blob/b4dcc77052e859256defdca22d6bbbdfb07480c8/lib/gaigo/helpers/form_helper_v3.rb#L8-L20
8,611
jD91mZM2/synacrb
lib/synacrb/state.rb
Synacrb.State.get_private_channel
def get_private_channel(user) @users.keys .map { |channel| @channels[channel] } .compact .find { |channel| channel.private } # the server doesn't send PMs you don't have access to end
ruby
def get_private_channel(user) @users.keys .map { |channel| @channels[channel] } .compact .find { |channel| channel.private } # the server doesn't send PMs you don't have access to end
[ "def", "get_private_channel", "(", "user", ")", "@users", ".", "keys", ".", "map", "{", "|", "channel", "|", "@channels", "[", "channel", "]", "}", ".", "compact", ".", "find", "{", "|", "channel", "|", "channel", ".", "private", "}", "# the server doesn't send PMs you don't have access to", "end" ]
Search for a private channel with user
[ "Search", "for", "a", "private", "channel", "with", "user" ]
c272c8a598f5d41f9185a5b5335213de91c944ab
https://github.com/jD91mZM2/synacrb/blob/c272c8a598f5d41f9185a5b5335213de91c944ab/lib/synacrb/state.rb#L33-L39
8,612
jD91mZM2/synacrb
lib/synacrb/state.rb
Synacrb.State.get_recipient_unchecked
def get_recipient_unchecked(channel_id) @users.values .find { |user| user.modes.keys .any { |channel| channel == channel_id }} end
ruby
def get_recipient_unchecked(channel_id) @users.values .find { |user| user.modes.keys .any { |channel| channel == channel_id }} end
[ "def", "get_recipient_unchecked", "(", "channel_id", ")", "@users", ".", "values", ".", "find", "{", "|", "user", "|", "user", ".", "modes", ".", "keys", ".", "any", "{", "|", "channel", "|", "channel", "==", "channel_id", "}", "}", "end" ]
Search for the recipient in a private channel. If the channel isn't private, it returns the first user it can find that has a special mode in that channel. So you should probably make sure it's private first.
[ "Search", "for", "the", "recipient", "in", "a", "private", "channel", ".", "If", "the", "channel", "isn", "t", "private", "it", "returns", "the", "first", "user", "it", "can", "find", "that", "has", "a", "special", "mode", "in", "that", "channel", ".", "So", "you", "should", "probably", "make", "sure", "it", "s", "private", "first", "." ]
c272c8a598f5d41f9185a5b5335213de91c944ab
https://github.com/jD91mZM2/synacrb/blob/c272c8a598f5d41f9185a5b5335213de91c944ab/lib/synacrb/state.rb#L53-L57
8,613
payout/rester
lib/rester/client.rb
Rester.Client._init_requester
def _init_requester if circuit_breaker_enabled? @_requester = Utils::CircuitBreaker.new( threshold: error_threshold, retry_period: retry_period ) { |*args| _request(*args) } @_requester.on_open do logger.error("circuit opened for #{name}") end @_requester.on_close do logger.info("circuit closed for #{name}") end else @_requester = proc { |*args| _request(*args) } end end
ruby
def _init_requester if circuit_breaker_enabled? @_requester = Utils::CircuitBreaker.new( threshold: error_threshold, retry_period: retry_period ) { |*args| _request(*args) } @_requester.on_open do logger.error("circuit opened for #{name}") end @_requester.on_close do logger.info("circuit closed for #{name}") end else @_requester = proc { |*args| _request(*args) } end end
[ "def", "_init_requester", "if", "circuit_breaker_enabled?", "@_requester", "=", "Utils", "::", "CircuitBreaker", ".", "new", "(", "threshold", ":", "error_threshold", ",", "retry_period", ":", "retry_period", ")", "{", "|", "*", "args", "|", "_request", "(", "args", ")", "}", "@_requester", ".", "on_open", "do", "logger", ".", "error", "(", "\"circuit opened for #{name}\"", ")", "end", "@_requester", ".", "on_close", "do", "logger", ".", "info", "(", "\"circuit closed for #{name}\"", ")", "end", "else", "@_requester", "=", "proc", "{", "|", "*", "args", "|", "_request", "(", "args", ")", "}", "end", "end" ]
Sets up the circuit breaker for making requests to the service. Any exception raised by the `_request` method will count as a failure for the circuit breaker. Once the threshold for errors has been reached, the circuit opens and all subsequent requests will raise a CircuitOpenError. When the circuit is opened or closed, a message is sent to the logger for the client.
[ "Sets", "up", "the", "circuit", "breaker", "for", "making", "requests", "to", "the", "service", "." ]
404a45fa17e7f92e167a08c0bd90382dafd43cc5
https://github.com/payout/rester/blob/404a45fa17e7f92e167a08c0bd90382dafd43cc5/lib/rester/client.rb#L105-L121
8,614
payout/rester
lib/rester/client.rb
Rester.Client._request
def _request(verb, path, params) Rester.wrap_request do Rester.request_info[:producer_name] = name Rester.request_info[:path] = path Rester.request_info[:verb] = verb logger.info('sending request') _set_default_headers start_time = Time.now.to_f begin response = adapter.request(verb, path, params) _process_response(start_time, verb, path, *response) rescue Errors::TimeoutError logger.error('timed out') raise end end end
ruby
def _request(verb, path, params) Rester.wrap_request do Rester.request_info[:producer_name] = name Rester.request_info[:path] = path Rester.request_info[:verb] = verb logger.info('sending request') _set_default_headers start_time = Time.now.to_f begin response = adapter.request(verb, path, params) _process_response(start_time, verb, path, *response) rescue Errors::TimeoutError logger.error('timed out') raise end end end
[ "def", "_request", "(", "verb", ",", "path", ",", "params", ")", "Rester", ".", "wrap_request", "do", "Rester", ".", "request_info", "[", ":producer_name", "]", "=", "name", "Rester", ".", "request_info", "[", ":path", "]", "=", "path", "Rester", ".", "request_info", "[", ":verb", "]", "=", "verb", "logger", ".", "info", "(", "'sending request'", ")", "_set_default_headers", "start_time", "=", "Time", ".", "now", ".", "to_f", "begin", "response", "=", "adapter", ".", "request", "(", "verb", ",", "path", ",", "params", ")", "_process_response", "(", "start_time", ",", "verb", ",", "path", ",", "response", ")", "rescue", "Errors", "::", "TimeoutError", "logger", ".", "error", "(", "'timed out'", ")", "raise", "end", "end", "end" ]
Add a correlation ID to the header and send the request to the adapter
[ "Add", "a", "correlation", "ID", "to", "the", "header", "and", "send", "the", "request", "to", "the", "adapter" ]
404a45fa17e7f92e167a08c0bd90382dafd43cc5
https://github.com/payout/rester/blob/404a45fa17e7f92e167a08c0bd90382dafd43cc5/lib/rester/client.rb#L125-L143
8,615
valeriomazzeo/danger-junit_results
lib/junit_results/plugin.rb
Danger.DangerJunitResults.parse
def parse(file_path) require 'nokogiri' @doc = Nokogiri::XML(File.open(file_path)) @total_count = @doc.xpath('//testsuite').map { |x| x.attr('tests').to_i }.inject(0){ |sum, x| sum + x } @skipped_count = @doc.xpath('//testsuite').map { |x| x.attr('skipped').to_i }.inject(0){ |sum, x| sum + x } @executed_count = @total_count - @skipped_count @failed_count = @doc.xpath('//testsuite').map { |x| x.attr('failures').to_i }.inject(0){ |sum, x| sum + x } @failures = @doc.xpath('//failure') return @failed_count <= 0 end
ruby
def parse(file_path) require 'nokogiri' @doc = Nokogiri::XML(File.open(file_path)) @total_count = @doc.xpath('//testsuite').map { |x| x.attr('tests').to_i }.inject(0){ |sum, x| sum + x } @skipped_count = @doc.xpath('//testsuite').map { |x| x.attr('skipped').to_i }.inject(0){ |sum, x| sum + x } @executed_count = @total_count - @skipped_count @failed_count = @doc.xpath('//testsuite').map { |x| x.attr('failures').to_i }.inject(0){ |sum, x| sum + x } @failures = @doc.xpath('//failure') return @failed_count <= 0 end
[ "def", "parse", "(", "file_path", ")", "require", "'nokogiri'", "@doc", "=", "Nokogiri", "::", "XML", "(", "File", ".", "open", "(", "file_path", ")", ")", "@total_count", "=", "@doc", ".", "xpath", "(", "'//testsuite'", ")", ".", "map", "{", "|", "x", "|", "x", ".", "attr", "(", "'tests'", ")", ".", "to_i", "}", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "x", "|", "sum", "+", "x", "}", "@skipped_count", "=", "@doc", ".", "xpath", "(", "'//testsuite'", ")", ".", "map", "{", "|", "x", "|", "x", ".", "attr", "(", "'skipped'", ")", ".", "to_i", "}", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "x", "|", "sum", "+", "x", "}", "@executed_count", "=", "@total_count", "-", "@skipped_count", "@failed_count", "=", "@doc", ".", "xpath", "(", "'//testsuite'", ")", ".", "map", "{", "|", "x", "|", "x", ".", "attr", "(", "'failures'", ")", ".", "to_i", "}", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "x", "|", "sum", "+", "x", "}", "@failures", "=", "@doc", ".", "xpath", "(", "'//failure'", ")", "return", "@failed_count", "<=", "0", "end" ]
Parses tests. @return [success]
[ "Parses", "tests", "." ]
6247fee99a3162e5a80002cd360ee47008ad6be3
https://github.com/valeriomazzeo/danger-junit_results/blob/6247fee99a3162e5a80002cd360ee47008ad6be3/lib/junit_results/plugin.rb#L50-L63
8,616
casst01/easy-exist
lib/easy-exist/db.rb
EasyExist.DB.put
def put(document_uri, document) validate_uri(document_uri) res = put_document(document_uri, document, "application/xml") res.success? ? res : handle_error(res) end
ruby
def put(document_uri, document) validate_uri(document_uri) res = put_document(document_uri, document, "application/xml") res.success? ? res : handle_error(res) end
[ "def", "put", "(", "document_uri", ",", "document", ")", "validate_uri", "(", "document_uri", ")", "res", "=", "put_document", "(", "document_uri", ",", "document", ",", "\"application/xml\"", ")", "res", ".", "success?", "?", "res", ":", "handle_error", "(", "res", ")", "end" ]
Puts the given document content at the specified URI @param document_uri [String] the URI at wich to store the document. relative to the collection specified on initialization otherwise '/db'. @return [HTTParty::Response] the response object
[ "Puts", "the", "given", "document", "content", "at", "the", "specified", "URI" ]
5f01d426456f88485783b6148274201908c5e2b7
https://github.com/casst01/easy-exist/blob/5f01d426456f88485783b6148274201908c5e2b7/lib/easy-exist/db.rb#L38-L42
8,617
casst01/easy-exist
lib/easy-exist/db.rb
EasyExist.DB.delete
def delete(document_uri) validate_uri(document_uri) res = HTTParty.delete(document_uri, @default_opts) res.success? ? res : handle_error(res) end
ruby
def delete(document_uri) validate_uri(document_uri) res = HTTParty.delete(document_uri, @default_opts) res.success? ? res : handle_error(res) end
[ "def", "delete", "(", "document_uri", ")", "validate_uri", "(", "document_uri", ")", "res", "=", "HTTParty", ".", "delete", "(", "document_uri", ",", "@default_opts", ")", "res", ".", "success?", "?", "res", ":", "handle_error", "(", "res", ")", "end" ]
Deletes the document at the specified URI from the store @param document_uri [String] the URI of the document to delete. relative to the collection specified on initialization otherwise '/db'. @return [HTTParty::Response] the response object
[ "Deletes", "the", "document", "at", "the", "specified", "URI", "from", "the", "store" ]
5f01d426456f88485783b6148274201908c5e2b7
https://github.com/casst01/easy-exist/blob/5f01d426456f88485783b6148274201908c5e2b7/lib/easy-exist/db.rb#L49-L53
8,618
casst01/easy-exist
lib/easy-exist/db.rb
EasyExist.DB.query
def query(query, opts = {}) body = EasyExist::QueryRequest.new(query, opts).body res = HTTParty.post("", @default_opts.merge({ body: body, headers: { 'Content-Type' => 'application/xml', 'Content-Length' => body.length.to_s } })) res.success? ? res.body : handle_error(res) end
ruby
def query(query, opts = {}) body = EasyExist::QueryRequest.new(query, opts).body res = HTTParty.post("", @default_opts.merge({ body: body, headers: { 'Content-Type' => 'application/xml', 'Content-Length' => body.length.to_s } })) res.success? ? res.body : handle_error(res) end
[ "def", "query", "(", "query", ",", "opts", "=", "{", "}", ")", "body", "=", "EasyExist", "::", "QueryRequest", ".", "new", "(", "query", ",", "opts", ")", ".", "body", "res", "=", "HTTParty", ".", "post", "(", "\"\"", ",", "@default_opts", ".", "merge", "(", "{", "body", ":", "body", ",", "headers", ":", "{", "'Content-Type'", "=>", "'application/xml'", ",", "'Content-Length'", "=>", "body", ".", "length", ".", "to_s", "}", "}", ")", ")", "res", ".", "success?", "?", "res", ".", "body", ":", "handle_error", "(", "res", ")", "end" ]
Runs the given XQuery against the store and returns the results @param query [String] XQuery to run against the store @param opts [Hash] options for the query request. @option opts :start [Integer] Index of first item to be returned. @option opts :max [Integer] The maximum number of items to be returned. @return [String] the query results
[ "Runs", "the", "given", "XQuery", "against", "the", "store", "and", "returns", "the", "results" ]
5f01d426456f88485783b6148274201908c5e2b7
https://github.com/casst01/easy-exist/blob/5f01d426456f88485783b6148274201908c5e2b7/lib/easy-exist/db.rb#L72-L79
8,619
casst01/easy-exist
lib/easy-exist/db.rb
EasyExist.DB.store_query
def store_query(query_uri, query) validate_uri(query_uri) res = put_document(query_uri, query, "application/xquery") res.success? ? res : handle_error(res) end
ruby
def store_query(query_uri, query) validate_uri(query_uri) res = put_document(query_uri, query, "application/xquery") res.success? ? res : handle_error(res) end
[ "def", "store_query", "(", "query_uri", ",", "query", ")", "validate_uri", "(", "query_uri", ")", "res", "=", "put_document", "(", "query_uri", ",", "query", ",", "\"application/xquery\"", ")", "res", ".", "success?", "?", "res", ":", "handle_error", "(", "res", ")", "end" ]
Stores the given query at the specified URI @param query_uri [String] the URI of the query to run @param query [String] the query body @return [HTTParty::Response] the response object
[ "Stores", "the", "given", "query", "at", "the", "specified", "URI" ]
5f01d426456f88485783b6148274201908c5e2b7
https://github.com/casst01/easy-exist/blob/5f01d426456f88485783b6148274201908c5e2b7/lib/easy-exist/db.rb#L86-L90
8,620
casst01/easy-exist
lib/easy-exist/db.rb
EasyExist.DB.put_document
def put_document(uri, document, content_type) HTTParty.put(uri, @default_opts.merge({ body: document, headers: { "Content-Type" => content_type}, })) end
ruby
def put_document(uri, document, content_type) HTTParty.put(uri, @default_opts.merge({ body: document, headers: { "Content-Type" => content_type}, })) end
[ "def", "put_document", "(", "uri", ",", "document", ",", "content_type", ")", "HTTParty", ".", "put", "(", "uri", ",", "@default_opts", ".", "merge", "(", "{", "body", ":", "document", ",", "headers", ":", "{", "\"Content-Type\"", "=>", "content_type", "}", ",", "}", ")", ")", "end" ]
Stores a document at the specified URI and with the specified content type @param uri [String] the URI under which to store the document @param document [String] the document body @param content_type [String] the MIME Type of the document @return [HTTParty::Response] the response object
[ "Stores", "a", "document", "at", "the", "specified", "URI", "and", "with", "the", "specified", "content", "type" ]
5f01d426456f88485783b6148274201908c5e2b7
https://github.com/casst01/easy-exist/blob/5f01d426456f88485783b6148274201908c5e2b7/lib/easy-exist/db.rb#L131-L136
8,621
scotdalton/institutions
lib/institutions/institution/core.rb
Institutions.Core.set_required_attributes
def set_required_attributes(code, name) missing_arguments = [] missing_arguments << :code if code.nil? missing_arguments << :name if name.nil? raise ArgumentError.new("Cannot create the Institution based on the given arguments (:code => #{code.inspect}, :name => #{name.inspect}).\n"+ "The following arguments cannot be nil: #{missing_arguments.inspect}") unless missing_arguments.empty? # Set the instance variables @code, @name = code.to_sym, name end
ruby
def set_required_attributes(code, name) missing_arguments = [] missing_arguments << :code if code.nil? missing_arguments << :name if name.nil? raise ArgumentError.new("Cannot create the Institution based on the given arguments (:code => #{code.inspect}, :name => #{name.inspect}).\n"+ "The following arguments cannot be nil: #{missing_arguments.inspect}") unless missing_arguments.empty? # Set the instance variables @code, @name = code.to_sym, name end
[ "def", "set_required_attributes", "(", "code", ",", "name", ")", "missing_arguments", "=", "[", "]", "missing_arguments", "<<", ":code", "if", "code", ".", "nil?", "missing_arguments", "<<", ":name", "if", "name", ".", "nil?", "raise", "ArgumentError", ".", "new", "(", "\"Cannot create the Institution based on the given arguments (:code => #{code.inspect}, :name => #{name.inspect}).\\n\"", "+", "\"The following arguments cannot be nil: #{missing_arguments.inspect}\"", ")", "unless", "missing_arguments", ".", "empty?", "# Set the instance variables", "@code", ",", "@name", "=", "code", ".", "to_sym", ",", "name", "end" ]
Creates a new Institution object from the given code, name and hash. The optional +hash+, if given, will generate additional attributes and values. For example: require 'institutions' hash = { "attribute1" => "My first attribute.", :array_attribute => [1, 2] } institution = Institutions::Institution.new("my_inst", "My Institution", hash) p institution # -> <Institutions::Institution @code=:my_inst @name="My Institution" @attribute1=My first attribute." @array_attribute=[1, 2] @default=false> Sets the required attributes. Raises an ArgumentError specifying the missing arguments if they are nil.
[ "Creates", "a", "new", "Institution", "object", "from", "the", "given", "code", "name", "and", "hash", "." ]
e979f42d54abca3cc629b70eb3dd82aa84f19982
https://github.com/scotdalton/institutions/blob/e979f42d54abca3cc629b70eb3dd82aa84f19982/lib/institutions/institution/core.rb#L41-L49
8,622
bleonard/daily
app/formatters/json_formatter.rb
Ruport.Formatter::JSON.build_table_body
def build_table_body data.each_with_index do |row, i| output << ",\n" if i > 0 build_row(row) end output << "\n" end
ruby
def build_table_body data.each_with_index do |row, i| output << ",\n" if i > 0 build_row(row) end output << "\n" end
[ "def", "build_table_body", "data", ".", "each_with_index", "do", "|", "row", ",", "i", "|", "output", "<<", "\",\\n\"", "if", "i", ">", "0", "build_row", "(", "row", ")", "end", "output", "<<", "\"\\n\"", "end" ]
Uses the Row controller to build up the table body.
[ "Uses", "the", "Row", "controller", "to", "build", "up", "the", "table", "body", "." ]
0de33921da7ae678f09e782017eee33df69771e7
https://github.com/bleonard/daily/blob/0de33921da7ae678f09e782017eee33df69771e7/app/formatters/json_formatter.rb#L21-L27
8,623
bleonard/daily
app/formatters/json_formatter.rb
Ruport.Formatter::JSON.build_row
def build_row(data = self.data) values = data.to_a keys = self.data.column_names.to_a hash = {} values.each_with_index do |val, i| key = (keys[i] || i).to_s hash[key] = val end line = hash.to_json.to_s output << " #{line}" end
ruby
def build_row(data = self.data) values = data.to_a keys = self.data.column_names.to_a hash = {} values.each_with_index do |val, i| key = (keys[i] || i).to_s hash[key] = val end line = hash.to_json.to_s output << " #{line}" end
[ "def", "build_row", "(", "data", "=", "self", ".", "data", ")", "values", "=", "data", ".", "to_a", "keys", "=", "self", ".", "data", ".", "column_names", ".", "to_a", "hash", "=", "{", "}", "values", ".", "each_with_index", "do", "|", "val", ",", "i", "|", "key", "=", "(", "keys", "[", "i", "]", "||", "i", ")", ".", "to_s", "hash", "[", "key", "]", "=", "val", "end", "line", "=", "hash", ".", "to_json", ".", "to_s", "output", "<<", "\" #{line}\"", "end" ]
Renders individual rows for the table.
[ "Renders", "individual", "rows", "for", "the", "table", "." ]
0de33921da7ae678f09e782017eee33df69771e7
https://github.com/bleonard/daily/blob/0de33921da7ae678f09e782017eee33df69771e7/app/formatters/json_formatter.rb#L36-L46
8,624
bleonard/daily
app/formatters/json_formatter.rb
Ruport.Formatter::JSON.build_grouping_body
def build_grouping_body arr = [] data.each do |_,group| arr << render_group(group, options) end output << arr.join(",\n") end
ruby
def build_grouping_body arr = [] data.each do |_,group| arr << render_group(group, options) end output << arr.join(",\n") end
[ "def", "build_grouping_body", "arr", "=", "[", "]", "data", ".", "each", "do", "|", "_", ",", "group", "|", "arr", "<<", "render_group", "(", "group", ",", "options", ")", "end", "output", "<<", "arr", ".", "join", "(", "\",\\n\"", ")", "end" ]
Generates the body for a grouping. Iterates through the groups and renders them using the group controller.
[ "Generates", "the", "body", "for", "a", "grouping", ".", "Iterates", "through", "the", "groups", "and", "renders", "them", "using", "the", "group", "controller", "." ]
0de33921da7ae678f09e782017eee33df69771e7
https://github.com/bleonard/daily/blob/0de33921da7ae678f09e782017eee33df69771e7/app/formatters/json_formatter.rb#L64-L70
8,625
checkdin/checkdin-ruby
lib/checkdin/users.rb
Checkdin.Users.users
def users(options={}) response = connection.get do |req| req.url "users", options end return_error_or_body(response) end
ruby
def users(options={}) response = connection.get do |req| req.url "users", options end return_error_or_body(response) end
[ "def", "users", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of all users for the authenticating client. @param [Hash] options @option options Integer :limit - The maximum number of records to return.
[ "Get", "a", "list", "of", "all", "users", "for", "the", "authenticating", "client", "." ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/users.rb#L18-L23
8,626
checkdin/checkdin-ruby
lib/checkdin/users.rb
Checkdin.Users.create_user
def create_user(options={}) response = connection.post do |req| req.url "users", options end return_error_or_body(response) end
ruby
def create_user(options={}) response = connection.post do |req| req.url "users", options end return_error_or_body(response) end
[ "def", "create_user", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"users\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Create a user in the checkd.in system tied to the authenticating client. @param [Hash] options @option options String :identifier - REQUIRED, The authenticating client's internal identifier for this user. @option options String :email - REQUIRED, A valid email for the user @option options String :referral_token - OPTIONAL, the referral token of the user that referred the user being created. @option options String :first_name - OPTIONAL @option options String :last_name - OPTIONAL @option options String :gender - OPTIONAL, format of male or female @option options String :birth_date - OPTIONAL, YYYY-MM-DD format @option options String :username - OPTIONAL @option options String :mobile_number - OPTIONAL, XXXYYYZZZZ format @option options String :postal_code_text - OPTIONAL, XXXXX format @option options String :classification - OPTIONAL, the internal group or classification a user belongs to @option options Boolean :delivery_email - OPTIONAL, whether a user should receive email notifications @option options Boolean :delivery_sms - OPTIONAL, whether a user should receive sms notifications @option options Integer :campaign_id - OPTIONAL, automatically join a user to this campaign, rewarding existing known actions
[ "Create", "a", "user", "in", "the", "checkd", ".", "in", "system", "tied", "to", "the", "authenticating", "client", "." ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/users.rb#L52-L57
8,627
checkdin/checkdin-ruby
lib/checkdin/users.rb
Checkdin.Users.create_user_authentication
def create_user_authentication(id, options={}) response = connection.post do |req| req.url "users/#{id}/authentications", options end return_error_or_body(response) end
ruby
def create_user_authentication(id, options={}) response = connection.post do |req| req.url "users/#{id}/authentications", options end return_error_or_body(response) end
[ "def", "create_user_authentication", "(", "id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"users/#{id}/authentications\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Create an authentication for a user param [Integer] id The ID of the user @param [Hash] options @option options String :provider - The name of the provider for the authentication (twitter, facebook, foursquare, linkedin, instagram) @option options String :uid - The user's id for the provider (on the provider's service, not your internal identifier) @option options String :oauth_token - The user's oauth token or access token that can be used to retrieve data on their behalf on the service. @option options String :oauth_token_secret - The user's oauth token secret or access token secret that is used in combination with the oauth token (required for twitter) @option options String :nickname - The user's nickname on the provider's service.
[ "Create", "an", "authentication", "for", "a", "user" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/users.rb#L88-L93
8,628
checkdin/checkdin-ruby
lib/checkdin/users.rb
Checkdin.Users.blacklisted
def blacklisted(options={}) response = connection.get do |req| req.url "users/blacklisted", options end return_error_or_body(response) end
ruby
def blacklisted(options={}) response = connection.get do |req| req.url "users/blacklisted", options end return_error_or_body(response) end
[ "def", "blacklisted", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/blacklisted\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of all blacklisted users for the authenticating client. @param [Hash] options @option options Integer :limit - The maximum number of records to return.
[ "Get", "a", "list", "of", "all", "blacklisted", "users", "for", "the", "authenticating", "client", "." ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/users.rb#L100-L105
8,629
checkdin/checkdin-ruby
lib/checkdin/users.rb
Checkdin.Users.view_user_full_description
def view_user_full_description(id) response = connection.get do |req| req.url "users/#{id}/full" end return_error_or_body(response) end
ruby
def view_user_full_description(id) response = connection.get do |req| req.url "users/#{id}/full" end return_error_or_body(response) end
[ "def", "view_user_full_description", "(", "id", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/#{id}/full\"", "end", "return_error_or_body", "(", "response", ")", "end" ]
View a full user's description param [Integer] id The ID of the user
[ "View", "a", "full", "user", "s", "description" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/users.rb#L142-L147
8,630
mezis/dragonfly-activerecord
lib/dragonfly-activerecord/store.rb
Dragonfly::ActiveRecord.Store.write
def write(temp_object, opts={}) temp_object.file do |fd| File.new.tap do |file| file.metadata = temp_object.meta file.data = fd file.save! return file.id.to_s end end end
ruby
def write(temp_object, opts={}) temp_object.file do |fd| File.new.tap do |file| file.metadata = temp_object.meta file.data = fd file.save! return file.id.to_s end end end
[ "def", "write", "(", "temp_object", ",", "opts", "=", "{", "}", ")", "temp_object", ".", "file", "do", "|", "fd", "|", "File", ".", "new", ".", "tap", "do", "|", "file", "|", "file", ".", "metadata", "=", "temp_object", ".", "meta", "file", ".", "data", "=", "fd", "file", ".", "save!", "return", "file", ".", "id", ".", "to_s", "end", "end", "end" ]
+temp_object+ should respond to +data+ and +meta+
[ "+", "temp_object", "+", "should", "respond", "to", "+", "data", "+", "and", "+", "meta", "+" ]
b14735fdded33c8ca41364407f546661df446e5d
https://github.com/mezis/dragonfly-activerecord/blob/b14735fdded33c8ca41364407f546661df446e5d/lib/dragonfly-activerecord/store.rb#L9-L18
8,631
ryanuber/ruby-aptly
lib/aptly/mirror.rb
Aptly.Mirror.update
def update kwargs={} ignore_cksum = kwargs.arg :ignore_cksum, false ignore_sigs = kwargs.arg :ignore_sigs, false cmd = 'aptly mirror update' cmd += ' -ignore-checksums' if ignore_cksum cmd += ' -ignore-signatures' if ignore_sigs cmd += " #{@name.quote}" Aptly::runcmd cmd end
ruby
def update kwargs={} ignore_cksum = kwargs.arg :ignore_cksum, false ignore_sigs = kwargs.arg :ignore_sigs, false cmd = 'aptly mirror update' cmd += ' -ignore-checksums' if ignore_cksum cmd += ' -ignore-signatures' if ignore_sigs cmd += " #{@name.quote}" Aptly::runcmd cmd end
[ "def", "update", "kwargs", "=", "{", "}", "ignore_cksum", "=", "kwargs", ".", "arg", ":ignore_cksum", ",", "false", "ignore_sigs", "=", "kwargs", ".", "arg", ":ignore_sigs", ",", "false", "cmd", "=", "'aptly mirror update'", "cmd", "+=", "' -ignore-checksums'", "if", "ignore_cksum", "cmd", "+=", "' -ignore-signatures'", "if", "ignore_sigs", "cmd", "+=", "\" #{@name.quote}\"", "Aptly", "::", "runcmd", "cmd", "end" ]
Updates a repository, syncing in all packages which have not already been downloaded and caches them locally. == Parameters: ignore_cksum:: Ignore checksum mismatches ignore_sigs:: Ignore author signature mismatches
[ "Updates", "a", "repository", "syncing", "in", "all", "packages", "which", "have", "not", "already", "been", "downloaded", "and", "caches", "them", "locally", "." ]
9581c38da30119d6a61b7ddac6334ab17fc67164
https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/mirror.rb#L138-L148
8,632
tomdionysus/stringtree-ruby
lib/stringtree/tree.rb
StringTree.Tree.delete
def delete(key) node = find_node(key) return false if node.nil? node.value = nil node.prune true end
ruby
def delete(key) node = find_node(key) return false if node.nil? node.value = nil node.prune true end
[ "def", "delete", "(", "key", ")", "node", "=", "find_node", "(", "key", ")", "return", "false", "if", "node", ".", "nil?", "node", ".", "value", "=", "nil", "node", ".", "prune", "true", "end" ]
Delete a key
[ "Delete", "a", "key" ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/tree.rb#L41-L47
8,633
tomdionysus/stringtree-ruby
lib/stringtree/tree.rb
StringTree.Tree.match_count
def match_count(data, list = {}) return nil if @root == nil i=0 while (i<data.length) node = @root.find_forward(data, i, data.length-i) if (node!=nil && node.value!=nil) if (!list.has_key?(node)) list[node] = 1 else list[node] += 1 end i += node.length else i += 1 end end list end
ruby
def match_count(data, list = {}) return nil if @root == nil i=0 while (i<data.length) node = @root.find_forward(data, i, data.length-i) if (node!=nil && node.value!=nil) if (!list.has_key?(node)) list[node] = 1 else list[node] += 1 end i += node.length else i += 1 end end list end
[ "def", "match_count", "(", "data", ",", "list", "=", "{", "}", ")", "return", "nil", "if", "@root", "==", "nil", "i", "=", "0", "while", "(", "i", "<", "data", ".", "length", ")", "node", "=", "@root", ".", "find_forward", "(", "data", ",", "i", ",", "data", ".", "length", "-", "i", ")", "if", "(", "node!", "=", "nil", "&&", "node", ".", "value!", "=", "nil", ")", "if", "(", "!", "list", ".", "has_key?", "(", "node", ")", ")", "list", "[", "node", "]", "=", "1", "else", "list", "[", "node", "]", "+=", "1", "end", "i", "+=", "node", ".", "length", "else", "i", "+=", "1", "end", "end", "list", "end" ]
Return a Hash of terminating nodes to Integer counts for a given String data, i.e. Find the count of instances of each String in the tree in the given data.
[ "Return", "a", "Hash", "of", "terminating", "nodes", "to", "Integer", "counts", "for", "a", "given", "String", "data", "i", ".", "e", ".", "Find", "the", "count", "of", "instances", "of", "each", "String", "in", "the", "tree", "in", "the", "given", "data", "." ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/tree.rb#L86-L103
8,634
tomdionysus/stringtree-ruby
lib/stringtree/tree.rb
StringTree.Tree.find_node
def find_node(key) return nil if @root == nil node = @root.find_vertical(key) (node.nil? || node.value.nil? ? nil : node) end
ruby
def find_node(key) return nil if @root == nil node = @root.find_vertical(key) (node.nil? || node.value.nil? ? nil : node) end
[ "def", "find_node", "(", "key", ")", "return", "nil", "if", "@root", "==", "nil", "node", "=", "@root", ".", "find_vertical", "(", "key", ")", "(", "node", ".", "nil?", "||", "node", ".", "value", ".", "nil?", "?", "nil", ":", "node", ")", "end" ]
Find a node by its key
[ "Find", "a", "node", "by", "its", "key" ]
b5cf8a327e80855bf4b2bd6fe71950e0cbdff215
https://github.com/tomdionysus/stringtree-ruby/blob/b5cf8a327e80855bf4b2bd6fe71950e0cbdff215/lib/stringtree/tree.rb#L108-L112
8,635
caruby/core
lib/caruby/migration/migrator.rb
CaRuby.Migrator.migrate_to_database
def migrate_to_database(&block) # migrate with save tm = Jinx::Stopwatch.measure { execute_save(&block) }.elapsed logger.debug { format_migration_time_log_message(tm) } end
ruby
def migrate_to_database(&block) # migrate with save tm = Jinx::Stopwatch.measure { execute_save(&block) }.elapsed logger.debug { format_migration_time_log_message(tm) } end
[ "def", "migrate_to_database", "(", "&", "block", ")", "# migrate with save", "tm", "=", "Jinx", "::", "Stopwatch", ".", "measure", "{", "execute_save", "(", "block", ")", "}", ".", "elapsed", "logger", ".", "debug", "{", "format_migration_time_log_message", "(", "tm", ")", "}", "end" ]
Creates a new Migrator with the given options. The migration configuration must provide sufficient information to build a well-formed migration target object. For example, if the target object is a new +CaTissue::SpecimenCollectionGroup+, then the migrator must build that SCG's required +CollectionProtocolRegistration+. The CPR in turn must either exist in the database or the migrator must build the required CPR +participant+ and +collection_protocol+. @option (see Jinx::Migrator#initialize) @option opts [Database] :database the target application database @see #migrate_to_database Imports this migrator's file into the database with the given connect options. This method creates or updates the domain objects mapped from the migration source. If a block is given to this method, then the block is called on each migrated target object. The target object is saved in the database. Every referenced migrated object is created, if necessary. Finally, a migration target owner object is created, if necessary. For example, suppose a migration configuration specifies the following: * the target is a +CaTissue::SpecimenCollectionGroup+ * the field mapping specifies a +Participant+ MRN, * the defaults specify a +CollectionProtocol+ title and a +Site+ name The migrator attempts to fetch the protocol and site from the database. If they do not exist, then they are created. In order to create the protocol and site, the migration configuration must specify sufficient information to validate the objects before creation, as described in {#initialize}. Finally, the SCG +CollectionProtocolRegistration+ owner is created. This CPR references the migration protocol and site. If the +:create+ option is set, then an input record for a target object which already exists in the database is noted in a debug log message and ignored rather than updated. @yield [target, row] operates on the migration target @yieldparam [Resource] target the migrated target domain object @yieldparam [{Symbol => Object}] row the migration source record
[ "Creates", "a", "new", "Migrator", "with", "the", "given", "options", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/migration/migrator.rb#L47-L51
8,636
skift/estore_conventions
lib/estore_conventions/archived_attributes.rb
EstoreConventions.ArchivedAttributes.archive_attributes_utc
def archive_attributes_utc(attribute,start_time = DEFAULT_DAYS_START.ago, end_time = DEFAULT_DAYS_END.ago) archived_attribute_base(attribute, start_time, end_time) do |hsh, obj| hsh[obj.send(archived_time_attribute).to_i] = obj.send(attribute) hsh end end
ruby
def archive_attributes_utc(attribute,start_time = DEFAULT_DAYS_START.ago, end_time = DEFAULT_DAYS_END.ago) archived_attribute_base(attribute, start_time, end_time) do |hsh, obj| hsh[obj.send(archived_time_attribute).to_i] = obj.send(attribute) hsh end end
[ "def", "archive_attributes_utc", "(", "attribute", ",", "start_time", "=", "DEFAULT_DAYS_START", ".", "ago", ",", "end_time", "=", "DEFAULT_DAYS_END", ".", "ago", ")", "archived_attribute_base", "(", "attribute", ",", "start_time", ",", "end_time", ")", "do", "|", "hsh", ",", "obj", "|", "hsh", "[", "obj", ".", "send", "(", "archived_time_attribute", ")", ".", "to_i", "]", "=", "obj", ".", "send", "(", "attribute", ")", "hsh", "end", "end" ]
temp method, for prototyping
[ "temp", "method", "for", "prototyping" ]
b9f1dfa45d476ecbadaa0a50729aeef064961183
https://github.com/skift/estore_conventions/blob/b9f1dfa45d476ecbadaa0a50729aeef064961183/lib/estore_conventions/archived_attributes.rb#L101-L107
8,637
skift/estore_conventions
lib/estore_conventions/archived_attributes.rb
EstoreConventions.ArchivedAttributes.archive_attributes_by_time
def archive_attributes_by_time(attribute,start_time = DEFAULT_DAYS_START.ago, end_time = DEFAULT_DAYS_END.ago) archived_attribute_base(attribute, start_time, end_time) do |hsh, obj| hsh[obj.send(archived_time_attribute)] = obj.send(attribute) hsh end end
ruby
def archive_attributes_by_time(attribute,start_time = DEFAULT_DAYS_START.ago, end_time = DEFAULT_DAYS_END.ago) archived_attribute_base(attribute, start_time, end_time) do |hsh, obj| hsh[obj.send(archived_time_attribute)] = obj.send(attribute) hsh end end
[ "def", "archive_attributes_by_time", "(", "attribute", ",", "start_time", "=", "DEFAULT_DAYS_START", ".", "ago", ",", "end_time", "=", "DEFAULT_DAYS_END", ".", "ago", ")", "archived_attribute_base", "(", "attribute", ",", "start_time", ",", "end_time", ")", "do", "|", "hsh", ",", "obj", "|", "hsh", "[", "obj", ".", "send", "(", "archived_time_attribute", ")", "]", "=", "obj", ".", "send", "(", "attribute", ")", "hsh", "end", "end" ]
temp method, for prototyping save as above, except the keys are Time objects
[ "temp", "method", "for", "prototyping", "save", "as", "above", "except", "the", "keys", "are", "Time", "objects" ]
b9f1dfa45d476ecbadaa0a50729aeef064961183
https://github.com/skift/estore_conventions/blob/b9f1dfa45d476ecbadaa0a50729aeef064961183/lib/estore_conventions/archived_attributes.rb#L111-L117
8,638
nicholas-johnson/content_driven
lib/content_driven/page.rb
ContentDriven.Page.add_child
def add_child key, page = nil if key.is_a? Page page, key = key, (self.keys.length + 1).to_sym end page.parent = self page.url = key self[key] = page end
ruby
def add_child key, page = nil if key.is_a? Page page, key = key, (self.keys.length + 1).to_sym end page.parent = self page.url = key self[key] = page end
[ "def", "add_child", "key", ",", "page", "=", "nil", "if", "key", ".", "is_a?", "Page", "page", ",", "key", "=", "key", ",", "(", "self", ".", "keys", ".", "length", "+", "1", ")", ".", "to_sym", "end", "page", ".", "parent", "=", "self", "page", ".", "url", "=", "key", "self", "[", "key", "]", "=", "page", "end" ]
Add a child page. You will seldom need to call this directly. Instead use add_blog or add_article
[ "Add", "a", "child", "page", ".", "You", "will", "seldom", "need", "to", "call", "this", "directly", ".", "Instead", "use", "add_blog", "or", "add_article" ]
ac362677810e45d95ce21975fed841d3d65f11d7
https://github.com/nicholas-johnson/content_driven/blob/ac362677810e45d95ce21975fed841d3d65f11d7/lib/content_driven/page.rb#L33-L40
8,639
pwnall/authpwn_rails
app/models/credentials/password.rb
Credentials.Password.check_password
def check_password(password) return false unless key key == self.class.hash_password(password, key.split('|', 2).first) end
ruby
def check_password(password) return false unless key key == self.class.hash_password(password, key.split('|', 2).first) end
[ "def", "check_password", "(", "password", ")", "return", "false", "unless", "key", "key", "==", "self", ".", "class", ".", "hash_password", "(", "password", ",", "key", ".", "split", "(", "'|'", ",", "2", ")", ".", "first", ")", "end" ]
Compares a plain-text password against the password hash in this credential. Returns +true+ for a match, +false+ otherwise.
[ "Compares", "a", "plain", "-", "text", "password", "against", "the", "password", "hash", "in", "this", "credential", "." ]
de3bd612a00025e8dc8296a73abe3acba948db17
https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/app/models/credentials/password.rb#L37-L40
8,640
pwnall/authpwn_rails
app/models/credentials/password.rb
Credentials.Password.password=
def password=(new_password) @password = new_password salt = self.class.random_salt self.key = new_password && self.class.hash_password(new_password, salt) end
ruby
def password=(new_password) @password = new_password salt = self.class.random_salt self.key = new_password && self.class.hash_password(new_password, salt) end
[ "def", "password", "=", "(", "new_password", ")", "@password", "=", "new_password", "salt", "=", "self", ".", "class", ".", "random_salt", "self", ".", "key", "=", "new_password", "&&", "self", ".", "class", ".", "hash_password", "(", "new_password", ",", "salt", ")", "end" ]
Password virtual attribute.
[ "Password", "virtual", "attribute", "." ]
de3bd612a00025e8dc8296a73abe3acba948db17
https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/app/models/credentials/password.rb#L53-L57
8,641
technicalpickles/has_markup
shoulda_macros/has_markup.rb
HasMarkup.Shoulda.should_have_markup
def should_have_markup(column, options = {}) options = HasMarkup::default_has_markup_options.merge(options) should_have_instance_methods "#{column}_html" should_require_markup column if options[:required] should_cache_markup column if options[:cache_html] end
ruby
def should_have_markup(column, options = {}) options = HasMarkup::default_has_markup_options.merge(options) should_have_instance_methods "#{column}_html" should_require_markup column if options[:required] should_cache_markup column if options[:cache_html] end
[ "def", "should_have_markup", "(", "column", ",", "options", "=", "{", "}", ")", "options", "=", "HasMarkup", "::", "default_has_markup_options", ".", "merge", "(", "options", ")", "should_have_instance_methods", "\"#{column}_html\"", "should_require_markup", "column", "if", "options", "[", ":required", "]", "should_cache_markup", "column", "if", "options", "[", ":cache_html", "]", "end" ]
Ensure that the model has markup. Accepts all the same options that has_markup does. should_have_markup :content
[ "Ensure", "that", "the", "model", "has", "markup", ".", "Accepts", "all", "the", "same", "options", "that", "has_markup", "does", "." ]
d02df9da091e37b5198d41fb4e6cbd7d103fe32c
https://github.com/technicalpickles/has_markup/blob/d02df9da091e37b5198d41fb4e6cbd7d103fe32c/shoulda_macros/has_markup.rb#L23-L30
8,642
jimcar/orchestrate-api
lib/orchestrate/client.rb
Orchestrate.Client.send_request
def send_request(method, args) request = API::Request.new(method, build_url(method, args), config.api_key) do |r| r.data = args[:json] if args[:json] r.ref = args[:ref] if args[:ref] end request.perform end
ruby
def send_request(method, args) request = API::Request.new(method, build_url(method, args), config.api_key) do |r| r.data = args[:json] if args[:json] r.ref = args[:ref] if args[:ref] end request.perform end
[ "def", "send_request", "(", "method", ",", "args", ")", "request", "=", "API", "::", "Request", ".", "new", "(", "method", ",", "build_url", "(", "method", ",", "args", ")", ",", "config", ".", "api_key", ")", "do", "|", "r", "|", "r", ".", "data", "=", "args", "[", ":json", "]", "if", "args", "[", ":json", "]", "r", ".", "ref", "=", "args", "[", ":ref", "]", "if", "args", "[", ":ref", "]", "end", "request", ".", "perform", "end" ]
Initialize and return a new Client instance. Optionally, configure options for the instance by passing a Configuration object. If no custom configuration is provided, the configuration options from Orchestrate.config will be used. Creates the Request object and sends it via the perform method, which generates and returns the Response object.
[ "Initialize", "and", "return", "a", "new", "Client", "instance", ".", "Optionally", "configure", "options", "for", "the", "instance", "by", "passing", "a", "Configuration", "object", ".", "If", "no", "custom", "configuration", "is", "provided", "the", "configuration", "options", "from", "Orchestrate", ".", "config", "will", "be", "used", "." ]
8931c41d69b9e32096db7615d0b252b971a5857d
https://github.com/jimcar/orchestrate-api/blob/8931c41d69b9e32096db7615d0b252b971a5857d/lib/orchestrate/client.rb#L46-L52
8,643
jimcar/orchestrate-api
lib/orchestrate/client.rb
Orchestrate.Client.build_url
def build_url(method, args) API::URL.new(method, config.base_url, args).path end
ruby
def build_url(method, args) API::URL.new(method, config.base_url, args).path end
[ "def", "build_url", "(", "method", ",", "args", ")", "API", "::", "URL", ".", "new", "(", "method", ",", "config", ".", "base_url", ",", "args", ")", ".", "path", "end" ]
Builds the URL for each HTTP request to the orchestrate.io api.
[ "Builds", "the", "URL", "for", "each", "HTTP", "request", "to", "the", "orchestrate", ".", "io", "api", "." ]
8931c41d69b9e32096db7615d0b252b971a5857d
https://github.com/jimcar/orchestrate-api/blob/8931c41d69b9e32096db7615d0b252b971a5857d/lib/orchestrate/client.rb#L61-L63
8,644
jamiely/simulator
lib/simulator/variable_context.rb
Simulator.VariableContext.add_variables
def add_variables(*vars) # create bound variables for each variable bound_vars = vars.collect do |v| BoundVariable.new v, self end # add all the bound variables to the variables hash keys = vars.collect(&:name) append_hash = Hash[ keys.zip(bound_vars) ] @variables_hash.merge!(append_hash) do |key, oldval, newval| oldval # the first bound variable end end
ruby
def add_variables(*vars) # create bound variables for each variable bound_vars = vars.collect do |v| BoundVariable.new v, self end # add all the bound variables to the variables hash keys = vars.collect(&:name) append_hash = Hash[ keys.zip(bound_vars) ] @variables_hash.merge!(append_hash) do |key, oldval, newval| oldval # the first bound variable end end
[ "def", "add_variables", "(", "*", "vars", ")", "# create bound variables for each variable", "bound_vars", "=", "vars", ".", "collect", "do", "|", "v", "|", "BoundVariable", ".", "new", "v", ",", "self", "end", "# add all the bound variables to the variables hash", "keys", "=", "vars", ".", "collect", "(", ":name", ")", "append_hash", "=", "Hash", "[", "keys", ".", "zip", "(", "bound_vars", ")", "]", "@variables_hash", ".", "merge!", "(", "append_hash", ")", "do", "|", "key", ",", "oldval", ",", "newval", "|", "oldval", "# the first bound variable", "end", "end" ]
add variables. doesn't check for uniqueness, does not overwrite existing
[ "add", "variables", ".", "doesn", "t", "check", "for", "uniqueness", "does", "not", "overwrite", "existing" ]
21395b72241d8f3ca93f90eecb5e1ad2870e9f69
https://github.com/jamiely/simulator/blob/21395b72241d8f3ca93f90eecb5e1ad2870e9f69/lib/simulator/variable_context.rb#L16-L28
8,645
jamiely/simulator
lib/simulator/variable_context.rb
Simulator.VariableContext.set
def set(var_hash) var_hash.each do |variable_name, value| throw :MissingVariable unless @variables_hash.has_key? variable_name bv = @variables_hash[variable_name] bv.value = value end end
ruby
def set(var_hash) var_hash.each do |variable_name, value| throw :MissingVariable unless @variables_hash.has_key? variable_name bv = @variables_hash[variable_name] bv.value = value end end
[ "def", "set", "(", "var_hash", ")", "var_hash", ".", "each", "do", "|", "variable_name", ",", "value", "|", "throw", ":MissingVariable", "unless", "@variables_hash", ".", "has_key?", "variable_name", "bv", "=", "@variables_hash", "[", "variable_name", "]", "bv", ".", "value", "=", "value", "end", "end" ]
Use to set the value for a variety of variables
[ "Use", "to", "set", "the", "value", "for", "a", "variety", "of", "variables" ]
21395b72241d8f3ca93f90eecb5e1ad2870e9f69
https://github.com/jamiely/simulator/blob/21395b72241d8f3ca93f90eecb5e1ad2870e9f69/lib/simulator/variable_context.rb#L31-L38
8,646
akwiatkowski/simple_metar_parser
lib/simple_metar_parser/metar/metar_specials.rb
SimpleMetarParser.MetarSpecials.calculate_rain_and_snow
def calculate_rain_and_snow @snow_metar = 0 @rain_metar = 0 self.specials.each do |s| new_rain = 0 new_snow = 0 coefficient = 1 case s[:precipitation] when 'drizzle' then new_rain = 5 when 'rain' then new_rain = 10 when 'snow' then new_snow = 10 when 'snow grains' then new_snow = 5 when 'ice crystals' then new_snow = 1 new_rain = 1 when 'ice pellets' then new_snow = 2 new_rain = 2 when 'hail' then new_snow = 3 new_rain = 3 when 'small hail/snow pellets' then new_snow = 1 new_rain = 1 end case s[:intensity] when 'in the vicinity' then coefficient = 1.5 when 'heavy' then coefficient = 3 when 'light' then coefficient = 0.5 when 'moderate' then coefficient = 1 end snow = new_snow * coefficient rain = new_rain * coefficient if @snow_metar < snow @snow_metar = snow end if @rain_metar < rain @rain_metar = rain end end # http://www.ofcm.gov/fmh-1/pdf/H-CH8.pdf page 3 # 10 units means more than 0.3 (I assume 0.5) inch per hour, so: # 10 units => 0.5 * 25.4mm real_world_coefficient = 0.5 * 25.4 / 10.0 @snow_metar *= real_world_coefficient @rain_metar *= real_world_coefficient end
ruby
def calculate_rain_and_snow @snow_metar = 0 @rain_metar = 0 self.specials.each do |s| new_rain = 0 new_snow = 0 coefficient = 1 case s[:precipitation] when 'drizzle' then new_rain = 5 when 'rain' then new_rain = 10 when 'snow' then new_snow = 10 when 'snow grains' then new_snow = 5 when 'ice crystals' then new_snow = 1 new_rain = 1 when 'ice pellets' then new_snow = 2 new_rain = 2 when 'hail' then new_snow = 3 new_rain = 3 when 'small hail/snow pellets' then new_snow = 1 new_rain = 1 end case s[:intensity] when 'in the vicinity' then coefficient = 1.5 when 'heavy' then coefficient = 3 when 'light' then coefficient = 0.5 when 'moderate' then coefficient = 1 end snow = new_snow * coefficient rain = new_rain * coefficient if @snow_metar < snow @snow_metar = snow end if @rain_metar < rain @rain_metar = rain end end # http://www.ofcm.gov/fmh-1/pdf/H-CH8.pdf page 3 # 10 units means more than 0.3 (I assume 0.5) inch per hour, so: # 10 units => 0.5 * 25.4mm real_world_coefficient = 0.5 * 25.4 / 10.0 @snow_metar *= real_world_coefficient @rain_metar *= real_world_coefficient end
[ "def", "calculate_rain_and_snow", "@snow_metar", "=", "0", "@rain_metar", "=", "0", "self", ".", "specials", ".", "each", "do", "|", "s", "|", "new_rain", "=", "0", "new_snow", "=", "0", "coefficient", "=", "1", "case", "s", "[", ":precipitation", "]", "when", "'drizzle'", "then", "new_rain", "=", "5", "when", "'rain'", "then", "new_rain", "=", "10", "when", "'snow'", "then", "new_snow", "=", "10", "when", "'snow grains'", "then", "new_snow", "=", "5", "when", "'ice crystals'", "then", "new_snow", "=", "1", "new_rain", "=", "1", "when", "'ice pellets'", "then", "new_snow", "=", "2", "new_rain", "=", "2", "when", "'hail'", "then", "new_snow", "=", "3", "new_rain", "=", "3", "when", "'small hail/snow pellets'", "then", "new_snow", "=", "1", "new_rain", "=", "1", "end", "case", "s", "[", ":intensity", "]", "when", "'in the vicinity'", "then", "coefficient", "=", "1.5", "when", "'heavy'", "then", "coefficient", "=", "3", "when", "'light'", "then", "coefficient", "=", "0.5", "when", "'moderate'", "then", "coefficient", "=", "1", "end", "snow", "=", "new_snow", "*", "coefficient", "rain", "=", "new_rain", "*", "coefficient", "if", "@snow_metar", "<", "snow", "@snow_metar", "=", "snow", "end", "if", "@rain_metar", "<", "rain", "@rain_metar", "=", "rain", "end", "end", "# http://www.ofcm.gov/fmh-1/pdf/H-CH8.pdf page 3", "# 10 units means more than 0.3 (I assume 0.5) inch per hour, so:", "# 10 units => 0.5 * 25.4mm", "real_world_coefficient", "=", "0.5", "*", "25.4", "/", "10.0", "@snow_metar", "*=", "real_world_coefficient", "@rain_metar", "*=", "real_world_coefficient", "end" ]
Calculate precipitation in self defined units and aproximated real world units
[ "Calculate", "precipitation", "in", "self", "defined", "units", "and", "aproximated", "real", "world", "units" ]
ff8ea6162c7be6137c8e56b768784e58d7c8ad01
https://github.com/akwiatkowski/simple_metar_parser/blob/ff8ea6162c7be6137c8e56b768784e58d7c8ad01/lib/simple_metar_parser/metar/metar_specials.rb#L139-L207
8,647
christoph-buente/retentiongrid
lib/retentiongrid/customer.rb
Retentiongrid.Customer.save!
def save! result = Api.post("#{BASE_PATH}/#{customer_id}", body: attributes.to_json) Customer.new(result.parsed_response["rg_customer"]) end
ruby
def save! result = Api.post("#{BASE_PATH}/#{customer_id}", body: attributes.to_json) Customer.new(result.parsed_response["rg_customer"]) end
[ "def", "save!", "result", "=", "Api", ".", "post", "(", "\"#{BASE_PATH}/#{customer_id}\"", ",", "body", ":", "attributes", ".", "to_json", ")", "Customer", ".", "new", "(", "result", ".", "parsed_response", "[", "\"rg_customer\"", "]", ")", "end" ]
Create or update a customer with given id @return [Customer] if successfully created or updated @raise [Httparty::Error] for all sorts of HTTP statuses.
[ "Create", "or", "update", "a", "customer", "with", "given", "id" ]
601d256786dd2e2c42f7374b999cd4e195e0e848
https://github.com/christoph-buente/retentiongrid/blob/601d256786dd2e2c42f7374b999cd4e195e0e848/lib/retentiongrid/customer.rb#L41-L44
8,648
delagoya/mzml
lib/mzml/doc.rb
MzML.Doc.parse_index_list
def parse_index_list self.seek(self.stat.size - 200) # parse the index offset tmp = self.read tmp =~ MzML::RGX::INDEX_OFFSET offset = $1 # if I didn't match anything, compute the index and return unless (offset) return compute_index_list end @index = {} @spectrum_list = [] @chromatogram_list = [] self.seek(offset.to_i) tmp = Nokogiri::XML.parse(self.read).root tmp.css("index").each do |idx| index_type = idx[:name].to_sym @index[index_type] = {} idx.css("offset").each do |o| @index[index_type][o[:idRef]] = o.text().to_i if index_type == :spectrum @spectrum_list << o[:idRef] else @chromatogram_list << o[:idRef] end end end self.rewind return @index end
ruby
def parse_index_list self.seek(self.stat.size - 200) # parse the index offset tmp = self.read tmp =~ MzML::RGX::INDEX_OFFSET offset = $1 # if I didn't match anything, compute the index and return unless (offset) return compute_index_list end @index = {} @spectrum_list = [] @chromatogram_list = [] self.seek(offset.to_i) tmp = Nokogiri::XML.parse(self.read).root tmp.css("index").each do |idx| index_type = idx[:name].to_sym @index[index_type] = {} idx.css("offset").each do |o| @index[index_type][o[:idRef]] = o.text().to_i if index_type == :spectrum @spectrum_list << o[:idRef] else @chromatogram_list << o[:idRef] end end end self.rewind return @index end
[ "def", "parse_index_list", "self", ".", "seek", "(", "self", ".", "stat", ".", "size", "-", "200", ")", "# parse the index offset", "tmp", "=", "self", ".", "read", "tmp", "=~", "MzML", "::", "RGX", "::", "INDEX_OFFSET", "offset", "=", "$1", "# if I didn't match anything, compute the index and return", "unless", "(", "offset", ")", "return", "compute_index_list", "end", "@index", "=", "{", "}", "@spectrum_list", "=", "[", "]", "@chromatogram_list", "=", "[", "]", "self", ".", "seek", "(", "offset", ".", "to_i", ")", "tmp", "=", "Nokogiri", "::", "XML", ".", "parse", "(", "self", ".", "read", ")", ".", "root", "tmp", ".", "css", "(", "\"index\"", ")", ".", "each", "do", "|", "idx", "|", "index_type", "=", "idx", "[", ":name", "]", ".", "to_sym", "@index", "[", "index_type", "]", "=", "{", "}", "idx", ".", "css", "(", "\"offset\"", ")", ".", "each", "do", "|", "o", "|", "@index", "[", "index_type", "]", "[", "o", "[", ":idRef", "]", "]", "=", "o", ".", "text", "(", ")", ".", "to_i", "if", "index_type", "==", ":spectrum", "@spectrum_list", "<<", "o", "[", ":idRef", "]", "else", "@chromatogram_list", "<<", "o", "[", ":idRef", "]", "end", "end", "end", "self", ".", "rewind", "return", "@index", "end" ]
Parses the IndexList
[ "Parses", "the", "IndexList" ]
6375cfe54a32ad3f7ebbeb92f0c25c5e456101de
https://github.com/delagoya/mzml/blob/6375cfe54a32ad3f7ebbeb92f0c25c5e456101de/lib/mzml/doc.rb#L140-L169
8,649
npepinpe/redstruct
lib/redstruct/struct.rb
Redstruct.Struct.expire
def expire(ttl) ttl = (ttl.to_f * 1000).floor return coerce_bool(self.connection.pexpire(@key, ttl)) end
ruby
def expire(ttl) ttl = (ttl.to_f * 1000).floor return coerce_bool(self.connection.pexpire(@key, ttl)) end
[ "def", "expire", "(", "ttl", ")", "ttl", "=", "(", "ttl", ".", "to_f", "*", "1000", ")", ".", "floor", "return", "coerce_bool", "(", "self", ".", "connection", ".", "pexpire", "(", "@key", ",", "ttl", ")", ")", "end" ]
Sets the key to expire after ttl seconds @param [#to_f] ttl the time to live in seconds (where 0.001 = 1ms) @return [Boolean] true if expired, false otherwise
[ "Sets", "the", "key", "to", "expire", "after", "ttl", "seconds" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/struct.rb#L33-L36
8,650
npepinpe/redstruct
lib/redstruct/struct.rb
Redstruct.Struct.expire_at
def expire_at(time) time = (time.to_f * 1000).floor return coerce_bool(self.connection.pexpireat(@key, time)) end
ruby
def expire_at(time) time = (time.to_f * 1000).floor return coerce_bool(self.connection.pexpireat(@key, time)) end
[ "def", "expire_at", "(", "time", ")", "time", "=", "(", "time", ".", "to_f", "*", "1000", ")", ".", "floor", "return", "coerce_bool", "(", "self", ".", "connection", ".", "pexpireat", "(", "@key", ",", "time", ")", ")", "end" ]
Sets the key to expire at the given timestamp. @param [#to_f] time time or unix timestamp at which the key should expire; once converted to float, assumes 1.0 is one second, 0.001 is 1 ms @return [Boolean] true if expired, false otherwise
[ "Sets", "the", "key", "to", "expire", "at", "the", "given", "timestamp", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/struct.rb#L41-L44
8,651
npepinpe/redstruct
lib/redstruct/struct.rb
Redstruct.Struct.restore
def restore(serialized, ttl: 0) ttl = (ttl.to_f * 1000).floor return self.connection.restore(@key, ttl, serialized) end
ruby
def restore(serialized, ttl: 0) ttl = (ttl.to_f * 1000).floor return self.connection.restore(@key, ttl, serialized) end
[ "def", "restore", "(", "serialized", ",", "ttl", ":", "0", ")", "ttl", "=", "(", "ttl", ".", "to_f", "*", "1000", ")", ".", "floor", "return", "self", ".", "connection", ".", "restore", "(", "@key", ",", "ttl", ",", "serialized", ")", "end" ]
Restores the struct to its serialized value as given @param [String] serialized serialized representation of the value @param [#to_f] ttl the time to live (in seconds) for the struct; defaults to 0 (meaning no expiry) @raise [Redis::CommandError] raised if the serialized value is incompatible or the key already exists @return [Boolean] true if restored, false otherwise
[ "Restores", "the", "struct", "to", "its", "serialized", "value", "as", "given" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/struct.rb#L82-L85
8,652
colbell/bitsa
lib/bitsa/cli.rb
Bitsa.CLI.parse
def parse(args) @global_opts = create_global_args(args) @cmd = args.shift || '' @search_data = '' if cmd == 'search' @search_data << args.shift unless args.empty? elsif !CLI::SUB_COMMANDS.include?(cmd) Trollop.die "unknown subcommand '#{cmd}'" end end
ruby
def parse(args) @global_opts = create_global_args(args) @cmd = args.shift || '' @search_data = '' if cmd == 'search' @search_data << args.shift unless args.empty? elsif !CLI::SUB_COMMANDS.include?(cmd) Trollop.die "unknown subcommand '#{cmd}'" end end
[ "def", "parse", "(", "args", ")", "@global_opts", "=", "create_global_args", "(", "args", ")", "@cmd", "=", "args", ".", "shift", "||", "''", "@search_data", "=", "''", "if", "cmd", "==", "'search'", "@search_data", "<<", "args", ".", "shift", "unless", "args", ".", "empty?", "elsif", "!", "CLI", "::", "SUB_COMMANDS", ".", "include?", "(", "cmd", ")", "Trollop", ".", "die", "\"unknown subcommand '#{cmd}'\"", "end", "end" ]
Parse arguments and setup attributes. It also handles showing the Help and Version information. @example parse command line arguments cli = Bitsa::CLI.new cli.parse(ARGV) cli.cmd # => # => "reload" @param args [String[]] Cmd line arguments. @return [nil] @raise [TrollopException] If invalid data is passed
[ "Parse", "arguments", "and", "setup", "attributes", "." ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/cli.rb#L79-L90
8,653
thriventures/storage_room_gem
lib/storage_room/models/collection.rb
StorageRoom.Collection.field
def field(identifier) ensure_loaded do fields.each do |f| return f if f.identifier == identifier end end nil end
ruby
def field(identifier) ensure_loaded do fields.each do |f| return f if f.identifier == identifier end end nil end
[ "def", "field", "(", "identifier", ")", "ensure_loaded", "do", "fields", ".", "each", "do", "|", "f", "|", "return", "f", "if", "f", ".", "identifier", "==", "identifier", "end", "end", "nil", "end" ]
The field with a specific identifier
[ "The", "field", "with", "a", "specific", "identifier" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/models/collection.rb#L51-L59
8,654
thriventures/storage_room_gem
lib/storage_room/models/collection.rb
StorageRoom.Collection.load_associated_collections
def load_associated_collections array = association_fields if array.map{|f| f.collection_loaded?}.include?(false) StorageRoom.log("Fetching associated collections for '#{name}'") array.each{|f| f.collection} end end
ruby
def load_associated_collections array = association_fields if array.map{|f| f.collection_loaded?}.include?(false) StorageRoom.log("Fetching associated collections for '#{name}'") array.each{|f| f.collection} end end
[ "def", "load_associated_collections", "array", "=", "association_fields", "if", "array", ".", "map", "{", "|", "f", "|", "f", ".", "collection_loaded?", "}", ".", "include?", "(", "false", ")", "StorageRoom", ".", "log", "(", "\"Fetching associated collections for '#{name}'\"", ")", "array", ".", "each", "{", "|", "f", "|", "f", ".", "collection", "}", "end", "end" ]
Load all Collections that are related to the current one through AssociationFields
[ "Load", "all", "Collections", "that", "are", "related", "to", "the", "current", "one", "through", "AssociationFields" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/models/collection.rb#L67-L74
8,655
astjohn/cornerstone
app/models/cornerstone/discussion.rb
Cornerstone.Discussion.created_by?
def created_by?(check_user) return false unless check_user.present? return true if check_user.cornerstone_admin? self.user && self.user == check_user end
ruby
def created_by?(check_user) return false unless check_user.present? return true if check_user.cornerstone_admin? self.user && self.user == check_user end
[ "def", "created_by?", "(", "check_user", ")", "return", "false", "unless", "check_user", ".", "present?", "return", "true", "if", "check_user", ".", "cornerstone_admin?", "self", ".", "user", "&&", "self", ".", "user", "==", "check_user", "end" ]
returns true if it was created by given user or if given user is an admin
[ "returns", "true", "if", "it", "was", "created", "by", "given", "user", "or", "if", "given", "user", "is", "an", "admin" ]
d7af7c06288477c961f3e328b8640df4be337301
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/discussion.rb#L49-L53
8,656
astjohn/cornerstone
app/models/cornerstone/discussion.rb
Cornerstone.Discussion.participants
def participants(exclude_email=nil) ps = [] self.posts.each do |p| if p.author_name && p.author_email ps << [p.author_name, p.author_email] end end ps.delete_if{|p| p[1] == exclude_email}.uniq end
ruby
def participants(exclude_email=nil) ps = [] self.posts.each do |p| if p.author_name && p.author_email ps << [p.author_name, p.author_email] end end ps.delete_if{|p| p[1] == exclude_email}.uniq end
[ "def", "participants", "(", "exclude_email", "=", "nil", ")", "ps", "=", "[", "]", "self", ".", "posts", ".", "each", "do", "|", "p", "|", "if", "p", ".", "author_name", "&&", "p", ".", "author_email", "ps", "<<", "[", "p", ".", "author_name", ",", "p", ".", "author_email", "]", "end", "end", "ps", ".", "delete_if", "{", "|", "p", "|", "p", "[", "1", "]", "==", "exclude_email", "}", ".", "uniq", "end" ]
returns an array of participants for the discussion
[ "returns", "an", "array", "of", "participants", "for", "the", "discussion" ]
d7af7c06288477c961f3e328b8640df4be337301
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/discussion.rb#L56-L64
8,657
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation/calculations.rb
ActiveRecord.Calculations.count
def count(column_name = nil, options = {}) column_name, options = nil, column_name if column_name.is_a?(Hash) calculate(:count, column_name, options) end
ruby
def count(column_name = nil, options = {}) column_name, options = nil, column_name if column_name.is_a?(Hash) calculate(:count, column_name, options) end
[ "def", "count", "(", "column_name", "=", "nil", ",", "options", "=", "{", "}", ")", "column_name", ",", "options", "=", "nil", ",", "column_name", "if", "column_name", ".", "is_a?", "(", "Hash", ")", "calculate", "(", ":count", ",", "column_name", ",", "options", ")", "end" ]
Count operates using three different approaches. * Count all: By not passing any parameters to count, it will return a count of all the rows for the model. * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present. * Count using options will find the row count matched by the options used. The third approach, count using options, accepts an option hash as the only parameter. The options are: * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base. * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s). If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns. Pass <tt>:readonly => false</tt> to override. * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting. See eager loading under Associations. * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not include the joined columns. * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ... * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name of a database view). Examples for counting all: Person.count # returns the total count of all people Examples for counting by column: Person.count(:age) # returns the total count of all people whose age is present in database Examples for count with options: Person.count(:conditions => "age > 26") # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN. Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # finds the number of rows matching the conditions and joins. Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") Person.count('id', :conditions => "age > 26") # Performs a COUNT(id) Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*') Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
[ "Count", "operates", "using", "three", "different", "approaches", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation/calculations.rb#L56-L59
8,658
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation/calculations.rb
ActiveRecord.Calculations.sum
def sum(*args) if block_given? self.to_a.sum(*args) {|*block_args| yield(*block_args)} else calculate(:sum, *args) end end
ruby
def sum(*args) if block_given? self.to_a.sum(*args) {|*block_args| yield(*block_args)} else calculate(:sum, *args) end end
[ "def", "sum", "(", "*", "args", ")", "if", "block_given?", "self", ".", "to_a", ".", "sum", "(", "args", ")", "{", "|", "*", "block_args", "|", "yield", "(", "block_args", ")", "}", "else", "calculate", "(", ":sum", ",", "args", ")", "end", "end" ]
Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there's no row. See +calculate+ for examples with options. Person.sum('age') # => 4562
[ "Calculates", "the", "sum", "of", "values", "on", "a", "given", "column", ".", "The", "value", "is", "returned", "with", "the", "same", "data", "type", "of", "the", "column", "0", "if", "there", "s", "no", "row", ".", "See", "+", "calculate", "+", "for", "examples", "with", "options", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation/calculations.rb#L92-L98
8,659
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation/query_methods.rb
ActiveRecord.QueryMethods.reorder
def reorder(*args) return self if args.blank? relation = clone relation.reordering_value = true relation.order_values = args.flatten relation end
ruby
def reorder(*args) return self if args.blank? relation = clone relation.reordering_value = true relation.order_values = args.flatten relation end
[ "def", "reorder", "(", "*", "args", ")", "return", "self", "if", "args", ".", "blank?", "relation", "=", "clone", "relation", ".", "reordering_value", "=", "true", "relation", ".", "order_values", "=", "args", ".", "flatten", "relation", "end" ]
Replaces any existing order defined on the relation with the specified order. User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC' Subsequent calls to order on the same relation will be appended. For example: User.order('email DESC').reorder('id ASC').order('name ASC') generates a query with 'ORDER BY id ASC, name ASC'.
[ "Replaces", "any", "existing", "order", "defined", "on", "the", "relation", "with", "the", "specified", "order", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation/query_methods.rb#L106-L113
8,660
dnd/permit
lib/permit/permit_rule.rb
Permit.PermitRule.matches?
def matches?(person, context_binding) matched = if BUILTIN_ROLES.include? @roles[0] has_builtin_authorization? person, context_binding else has_named_authorizations? person, context_binding end passed_conditionals = matched ? passes_conditionals?(person, context_binding) : false passed = matched && passed_conditionals return passed end
ruby
def matches?(person, context_binding) matched = if BUILTIN_ROLES.include? @roles[0] has_builtin_authorization? person, context_binding else has_named_authorizations? person, context_binding end passed_conditionals = matched ? passes_conditionals?(person, context_binding) : false passed = matched && passed_conditionals return passed end
[ "def", "matches?", "(", "person", ",", "context_binding", ")", "matched", "=", "if", "BUILTIN_ROLES", ".", "include?", "@roles", "[", "0", "]", "has_builtin_authorization?", "person", ",", "context_binding", "else", "has_named_authorizations?", "person", ",", "context_binding", "end", "passed_conditionals", "=", "matched", "?", "passes_conditionals?", "(", "person", ",", "context_binding", ")", ":", "false", "passed", "=", "matched", "&&", "passed_conditionals", "return", "passed", "end" ]
Creates a new PermitRule. +:if+ and +:unless+ conditions may be evaluated for static, dynamic, and named authorizations. They are evaluated after the other rule checks are applied, and only if the rule still matches. The conditionals may make a matching rule not match, but will not make an unmatched rule match. If both +:if+ and +:unless+ are given the +:if+ condition is run first, and if the rule still matches the +:unless+ will be run. @param [:person, :guest, :everyone, Symbol, <Symbol>] roles the role(s) to test against. - :person - +current_person.guest? == false+ This person should be authenticated. This indicates a dynamic authorization. - :guest - +current_person.guest? == true+ This is a person that is not authenticated. This is a static authorization. - :everyone - Any user of the system. This is a static authorization. - Symbol/<Symbol> - This is the key or keys of any of the role(s) to match against in the database. This indicates a named authorization. @param [Hash] options the options to use to configure the authorization. @option options [Symbol] :who Indicates that a method should be checked on the target object to authorize. Checks a variety of possibilities, taking the first variation that the target responds to. When the symbol is prefixed with 'is_' then multiple methods will be tried passing the person in. The methods tried for +:is_owner+ would be +is_owner()+, +is_owner?()+, +owner()+, +owner+, +owners.exist?()+. If this option is given +:of+/+:on+ must also be given. @option options [Symbol] :that alias for +:who+ @option options [Symbol, nil, :any, <Symbol, nil>] :of The name of the instance variable(s) to use as the target resource(s). In a dynamic authorization this is the object that will be tested using the value of +:who+/+:that+. In a named authorization this is the resource the person must be authorized on for one or more of the roles. +:any+ may be given to indicate a match if the person has one of the roles for any resource. If not given, or set to +nil+, then the match will apply to a person that has a matching role authorization for a nil resource. @option options [Symbol, nil, :any, <Symbol, nil>] :on alias for +:of+ @option options [Symbol, String, Proc] :if code to evaluate at the end of the match if it is still valid. If it returns false, the rule will not match. If a proc if given, it will be passed the current subject and binding. A method will be called without any arguments. @option options [Symbol, String, Proc] :unless code to evaluate at the end of the match if it is still valid. If it returns true, the rule will not match. If a proc if given, it will be passed the current subject and binding. A method will be called without any arguments. @raise [PermitConfigurationError] if the rule options are invalid. Determine if the passed in person matches this rule. @param [permit_person] person the person to evaluate for authorization @param [Binding] context_binding the binding to use to locate the resource and/or evaluate the if/unless conditions. @return [Boolean] true if the person matches the rule, otherwise false. @raise [PermitEvaluationError] if there is a problem evaluating the rule.
[ "Creates", "a", "new", "PermitRule", "." ]
4bf41d5cc1fe1cbd100405bda773921e605f7a7a
https://github.com/dnd/permit/blob/4bf41d5cc1fe1cbd100405bda773921e605f7a7a/lib/permit/permit_rule.rb#L83-L93
8,661
jbe/lazy_load
lib/lazy_load.rb
LazyLoad.Mixin.best
def best(*names) names.map do |name| @groups[name] || name end.flatten.each do |name| begin return const_get(name) rescue NameError, LoadError; end end const_get(names.first) end
ruby
def best(*names) names.map do |name| @groups[name] || name end.flatten.each do |name| begin return const_get(name) rescue NameError, LoadError; end end const_get(names.first) end
[ "def", "best", "(", "*", "names", ")", "names", ".", "map", "do", "|", "name", "|", "@groups", "[", "name", "]", "||", "name", "end", ".", "flatten", ".", "each", "do", "|", "name", "|", "begin", "return", "const_get", "(", "name", ")", "rescue", "NameError", ",", "LoadError", ";", "end", "end", "const_get", "(", "names", ".", "first", ")", "end" ]
Return the first available dependency from the list of constant names.
[ "Return", "the", "first", "available", "dependency", "from", "the", "list", "of", "constant", "names", "." ]
41e5e8a08b130c1ba6f032c4d50e317e0140d1f2
https://github.com/jbe/lazy_load/blob/41e5e8a08b130c1ba6f032c4d50e317e0140d1f2/lib/lazy_load.rb#L63-L72
8,662
jonahoffline/link_shrink
lib/link_shrink/cli.rb
LinkShrink.CLI.set_options
def set_options(opts) opts.version, opts.banner = options.version, options.banner opts.set_program_name 'LinkShrink' options.api.map do |k, v| arg = k.to_s.downcase opts.on_head("-#{arg[0]}", "--#{arg}", argument_text_for(k)) do options.api[k] = true end end opts.on_tail('-v', '--version', 'display the version of LinkShrink and exit') do puts opts.ver exit end opts.on_tail('-h', '--help', 'print this help') do puts opts.help exit end end
ruby
def set_options(opts) opts.version, opts.banner = options.version, options.banner opts.set_program_name 'LinkShrink' options.api.map do |k, v| arg = k.to_s.downcase opts.on_head("-#{arg[0]}", "--#{arg}", argument_text_for(k)) do options.api[k] = true end end opts.on_tail('-v', '--version', 'display the version of LinkShrink and exit') do puts opts.ver exit end opts.on_tail('-h', '--help', 'print this help') do puts opts.help exit end end
[ "def", "set_options", "(", "opts", ")", "opts", ".", "version", ",", "opts", ".", "banner", "=", "options", ".", "version", ",", "options", ".", "banner", "opts", ".", "set_program_name", "'LinkShrink'", "options", ".", "api", ".", "map", "do", "|", "k", ",", "v", "|", "arg", "=", "k", ".", "to_s", ".", "downcase", "opts", ".", "on_head", "(", "\"-#{arg[0]}\"", ",", "\"--#{arg}\"", ",", "argument_text_for", "(", "k", ")", ")", "do", "options", ".", "api", "[", "k", "]", "=", "true", "end", "end", "opts", ".", "on_tail", "(", "'-v'", ",", "'--version'", ",", "'display the version of LinkShrink and exit'", ")", "do", "puts", "opts", ".", "ver", "exit", "end", "opts", ".", "on_tail", "(", "'-h'", ",", "'--help'", ",", "'print this help'", ")", "do", "puts", "opts", ".", "help", "exit", "end", "end" ]
Configures the arguments for the command @param opts [OptionParser]
[ "Configures", "the", "arguments", "for", "the", "command" ]
8ed842b4f004265e4e91693df72a4d8c49de3ea8
https://github.com/jonahoffline/link_shrink/blob/8ed842b4f004265e4e91693df72a4d8c49de3ea8/lib/link_shrink/cli.rb#L43-L65
8,663
jonahoffline/link_shrink
lib/link_shrink/cli.rb
LinkShrink.CLI.parse
def parse opts = OptionParser.new(&method(:set_options)) opts.parse!(@args) return process_url if url_present? opts.help end
ruby
def parse opts = OptionParser.new(&method(:set_options)) opts.parse!(@args) return process_url if url_present? opts.help end
[ "def", "parse", "opts", "=", "OptionParser", ".", "new", "(", "method", "(", ":set_options", ")", ")", "opts", ".", "parse!", "(", "@args", ")", "return", "process_url", "if", "url_present?", "opts", ".", "help", "end" ]
Parses the command-line arguments and runs the executable @return [String] The short url or argument passed
[ "Parses", "the", "command", "-", "line", "arguments", "and", "runs", "the", "executable" ]
8ed842b4f004265e4e91693df72a4d8c49de3ea8
https://github.com/jonahoffline/link_shrink/blob/8ed842b4f004265e4e91693df72a4d8c49de3ea8/lib/link_shrink/cli.rb#L73-L78
8,664
zpatten/ztk
lib/ztk/base.rb
ZTK.Base.log_and_raise
def log_and_raise(exception, message, shift=2) Base.log_and_raise(config.ui.logger, exception, message, shift) end
ruby
def log_and_raise(exception, message, shift=2) Base.log_and_raise(config.ui.logger, exception, message, shift) end
[ "def", "log_and_raise", "(", "exception", ",", "message", ",", "shift", "=", "2", ")", "Base", ".", "log_and_raise", "(", "config", ".", "ui", ".", "logger", ",", "exception", ",", "message", ",", "shift", ")", "end" ]
Logs an exception and then raises it. @see Base.log_and_raise @param [Exception] exception The exception class to raise. @param [String] message The message to display with the exception. @param [Integer] shift (2) How many places to shift the caller stack in the log statement.
[ "Logs", "an", "exception", "and", "then", "raises", "it", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/base.rb#L103-L105
8,665
zpatten/ztk
lib/ztk/base.rb
ZTK.Base.direct_log
def direct_log(log_level, &blocK) @config.ui.logger.nil? and raise BaseError, "You must supply a logger for direct logging support!" if !block_given? log_and_raise(BaseError, "You must supply a block to the log method!") elsif (@config.ui.logger.level <= ::Logger.const_get(log_level.to_s.upcase)) @config.ui.logger << ZTK::ANSI.uncolor(yield) end end
ruby
def direct_log(log_level, &blocK) @config.ui.logger.nil? and raise BaseError, "You must supply a logger for direct logging support!" if !block_given? log_and_raise(BaseError, "You must supply a block to the log method!") elsif (@config.ui.logger.level <= ::Logger.const_get(log_level.to_s.upcase)) @config.ui.logger << ZTK::ANSI.uncolor(yield) end end
[ "def", "direct_log", "(", "log_level", ",", "&", "blocK", ")", "@config", ".", "ui", ".", "logger", ".", "nil?", "and", "raise", "BaseError", ",", "\"You must supply a logger for direct logging support!\"", "if", "!", "block_given?", "log_and_raise", "(", "BaseError", ",", "\"You must supply a block to the log method!\"", ")", "elsif", "(", "@config", ".", "ui", ".", "logger", ".", "level", "<=", "::", "Logger", ".", "const_get", "(", "log_level", ".", "to_s", ".", "upcase", ")", ")", "@config", ".", "ui", ".", "logger", "<<", "ZTK", "::", "ANSI", ".", "uncolor", "(", "yield", ")", "end", "end" ]
Direct logging method. This method provides direct writing of data to the current log device. This is mainly used for pushing STDOUT and STDERR into the log file in ZTK::SSH and ZTK::Command, but could easily be used by other classes. The value returned in the block is passed down to the logger specified in the classes configuration. @param [Symbol] log_level This should be any one of [:debug, :info, :warn, :error, :fatal]. @yield No value is passed to the block. @yieldreturn [String] The message to log.
[ "Direct", "logging", "method", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/base.rb#L119-L127
8,666
colbell/bitsa
lib/bitsa/settings.rb
Bitsa.Settings.load_config_file_settings
def load_config_file_settings(config_file_hash) @login = config_file_hash.data[:login] @password = config_file_hash.data[:password] @cache_file_path = config_file_hash.data[:cache_file_path] @auto_check = config_file_hash.data[:auto_check] end
ruby
def load_config_file_settings(config_file_hash) @login = config_file_hash.data[:login] @password = config_file_hash.data[:password] @cache_file_path = config_file_hash.data[:cache_file_path] @auto_check = config_file_hash.data[:auto_check] end
[ "def", "load_config_file_settings", "(", "config_file_hash", ")", "@login", "=", "config_file_hash", ".", "data", "[", ":login", "]", "@password", "=", "config_file_hash", ".", "data", "[", ":password", "]", "@cache_file_path", "=", "config_file_hash", ".", "data", "[", ":cache_file_path", "]", "@auto_check", "=", "config_file_hash", ".", "data", "[", ":auto_check", "]", "end" ]
Load settings from the configuration file hash. @param [Hash] config_file_hash <tt>Hash</tt> of settings loaded from configuration file.
[ "Load", "settings", "from", "the", "configuration", "file", "hash", "." ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/settings.rb#L81-L86
8,667
colbell/bitsa
lib/bitsa/settings.rb
Bitsa.Settings.load_cmd_line_settings
def load_cmd_line_settings(options) @login = options[:login] if options[:login] @password = options[:password] if options[:password] @cache_file_path = options[:cache_file_path] if options[:cache_file_path] @auto_check = options[:auto_check] if options[:auto_check] end
ruby
def load_cmd_line_settings(options) @login = options[:login] if options[:login] @password = options[:password] if options[:password] @cache_file_path = options[:cache_file_path] if options[:cache_file_path] @auto_check = options[:auto_check] if options[:auto_check] end
[ "def", "load_cmd_line_settings", "(", "options", ")", "@login", "=", "options", "[", ":login", "]", "if", "options", "[", ":login", "]", "@password", "=", "options", "[", ":password", "]", "if", "options", "[", ":password", "]", "@cache_file_path", "=", "options", "[", ":cache_file_path", "]", "if", "options", "[", ":cache_file_path", "]", "@auto_check", "=", "options", "[", ":auto_check", "]", "if", "options", "[", ":auto_check", "]", "end" ]
Load settings from the command line hash. Load a setting only if it was passed. @param [Hash] options <tt>Hash</tt> of settings passed on command line.
[ "Load", "settings", "from", "the", "command", "line", "hash", ".", "Load", "a", "setting", "only", "if", "it", "was", "passed", "." ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/settings.rb#L92-L97
8,668
matharvard/tastes_bitter
app/controllers/tastes_bitter/javascript_errors_controller.rb
TastesBitter.JavascriptErrorsController.create
def create browser = Browser.new(ua: params["user_agent"]) error_info = { message: params["message"], file_or_page: params["file_or_page"], line_number: params["line_number"], column_number: params["column_number"], user_agent: params["user_agent"], current_page: params["current_page"], platform: browser.platform.to_s.humanize, browser_name: browser.name, browser_version: browser.full_version, user_ip: request.remote_ip, referrer: request.env["HTTP_REFERER"], stack_trace: params["stack_trace"] } ::TastesBitter::JavascriptErrorsMailer.javascript_error(error_info).deliver_later respond_to do |format| format.js { render nothing: true, status: :ok } end end
ruby
def create browser = Browser.new(ua: params["user_agent"]) error_info = { message: params["message"], file_or_page: params["file_or_page"], line_number: params["line_number"], column_number: params["column_number"], user_agent: params["user_agent"], current_page: params["current_page"], platform: browser.platform.to_s.humanize, browser_name: browser.name, browser_version: browser.full_version, user_ip: request.remote_ip, referrer: request.env["HTTP_REFERER"], stack_trace: params["stack_trace"] } ::TastesBitter::JavascriptErrorsMailer.javascript_error(error_info).deliver_later respond_to do |format| format.js { render nothing: true, status: :ok } end end
[ "def", "create", "browser", "=", "Browser", ".", "new", "(", "ua", ":", "params", "[", "\"user_agent\"", "]", ")", "error_info", "=", "{", "message", ":", "params", "[", "\"message\"", "]", ",", "file_or_page", ":", "params", "[", "\"file_or_page\"", "]", ",", "line_number", ":", "params", "[", "\"line_number\"", "]", ",", "column_number", ":", "params", "[", "\"column_number\"", "]", ",", "user_agent", ":", "params", "[", "\"user_agent\"", "]", ",", "current_page", ":", "params", "[", "\"current_page\"", "]", ",", "platform", ":", "browser", ".", "platform", ".", "to_s", ".", "humanize", ",", "browser_name", ":", "browser", ".", "name", ",", "browser_version", ":", "browser", ".", "full_version", ",", "user_ip", ":", "request", ".", "remote_ip", ",", "referrer", ":", "request", ".", "env", "[", "\"HTTP_REFERER\"", "]", ",", "stack_trace", ":", "params", "[", "\"stack_trace\"", "]", "}", "::", "TastesBitter", "::", "JavascriptErrorsMailer", ".", "javascript_error", "(", "error_info", ")", ".", "deliver_later", "respond_to", "do", "|", "format", "|", "format", ".", "js", "{", "render", "nothing", ":", "true", ",", "status", ":", ":ok", "}", "end", "end" ]
Responsible for handling errors sent from the browser, parsing the data, and sending the email with the information about the error.
[ "Responsible", "for", "handling", "errors", "sent", "from", "the", "browser", "parsing", "the", "data", "and", "sending", "the", "email", "with", "the", "information", "about", "the", "error", "." ]
20e50883dbe4d99282bbd831d7090d0cf56a0665
https://github.com/matharvard/tastes_bitter/blob/20e50883dbe4d99282bbd831d7090d0cf56a0665/app/controllers/tastes_bitter/javascript_errors_controller.rb#L10-L33
8,669
26fe/sem4r
lib/sem4r/report_definition/report_definition_account_extension.rb
Sem4r.ReportDefinitionAccountExtension.report_fields
def report_fields(report_type) soap_message = service.report_definition.report_fields(credentials, report_type) add_counters(soap_message.counters) els = soap_message.response.xpath("//getReportFieldsResponse/rval") els.map do |el| ReportField.from_element(el) end end
ruby
def report_fields(report_type) soap_message = service.report_definition.report_fields(credentials, report_type) add_counters(soap_message.counters) els = soap_message.response.xpath("//getReportFieldsResponse/rval") els.map do |el| ReportField.from_element(el) end end
[ "def", "report_fields", "(", "report_type", ")", "soap_message", "=", "service", ".", "report_definition", ".", "report_fields", "(", "credentials", ",", "report_type", ")", "add_counters", "(", "soap_message", ".", "counters", ")", "els", "=", "soap_message", ".", "response", ".", "xpath", "(", "\"//getReportFieldsResponse/rval\"", ")", "els", ".", "map", "do", "|", "el", "|", "ReportField", ".", "from_element", "(", "el", ")", "end", "end" ]
Query the list of field for a report type @param [ReportDefinition::ReportTypes] a value of
[ "Query", "the", "list", "of", "field", "for", "a", "report", "type" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/report_definition/report_definition_account_extension.rb#L33-L40
8,670
26fe/sem4r
lib/sem4r/report_definition/report_definition_account_extension.rb
Sem4r.ReportDefinitionAccountExtension.report_definition_delete
def report_definition_delete(repdef_or_id) if repdef_or_id.class == ReportDefinition report_definition = repdef_or_id else report_definition = ReportDefinition.new(self) report_definition.instance_eval { @id = repdef_or_id } end op = ReportDefinitionOperation.remove(report_definition) soap_message = service.report_definition.mutate(credentials, op.to_xml) add_counters(soap_message.counters) unless @report_definitions @report_definition.delete_if { |repdef| repdef == report_definition.id } end report_definition.instance_eval { @id = -1 } # repdef status invalid/deleted self end
ruby
def report_definition_delete(repdef_or_id) if repdef_or_id.class == ReportDefinition report_definition = repdef_or_id else report_definition = ReportDefinition.new(self) report_definition.instance_eval { @id = repdef_or_id } end op = ReportDefinitionOperation.remove(report_definition) soap_message = service.report_definition.mutate(credentials, op.to_xml) add_counters(soap_message.counters) unless @report_definitions @report_definition.delete_if { |repdef| repdef == report_definition.id } end report_definition.instance_eval { @id = -1 } # repdef status invalid/deleted self end
[ "def", "report_definition_delete", "(", "repdef_or_id", ")", "if", "repdef_or_id", ".", "class", "==", "ReportDefinition", "report_definition", "=", "repdef_or_id", "else", "report_definition", "=", "ReportDefinition", ".", "new", "(", "self", ")", "report_definition", ".", "instance_eval", "{", "@id", "=", "repdef_or_id", "}", "end", "op", "=", "ReportDefinitionOperation", ".", "remove", "(", "report_definition", ")", "soap_message", "=", "service", ".", "report_definition", ".", "mutate", "(", "credentials", ",", "op", ".", "to_xml", ")", "add_counters", "(", "soap_message", ".", "counters", ")", "unless", "@report_definitions", "@report_definition", ".", "delete_if", "{", "|", "repdef", "|", "repdef", "==", "report_definition", ".", "id", "}", "end", "report_definition", ".", "instance_eval", "{", "@id", "=", "-", "1", "}", "# repdef status invalid/deleted", "self", "end" ]
Delete a report definition @param[ReportDefinition, Number]
[ "Delete", "a", "report", "definition" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/report_definition/report_definition_account_extension.rb#L47-L64
8,671
26fe/sem4r
lib/sem4r/report_definition/report_definition_account_extension.rb
Sem4r.ReportDefinitionAccountExtension.p_report_definitions
def p_report_definitions(refresh = false) report_definitions(refresh).each do |report_definition| puts report_definition.to_s end self end
ruby
def p_report_definitions(refresh = false) report_definitions(refresh).each do |report_definition| puts report_definition.to_s end self end
[ "def", "p_report_definitions", "(", "refresh", "=", "false", ")", "report_definitions", "(", "refresh", ")", ".", "each", "do", "|", "report_definition", "|", "puts", "report_definition", ".", "to_s", "end", "self", "end" ]
Prints on stdout the list of report definition contained into account @param [bool] true if the list must be refreshed @return self
[ "Prints", "on", "stdout", "the", "list", "of", "report", "definition", "contained", "into", "account" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/report_definition/report_definition_account_extension.rb#L95-L100
8,672
rgeyer/rs_user_policy
lib/rs_user_policy/user_collection.rb
RsUserPolicy.UserCollection.add_users
def add_users(users) users.each do |user| unless @users_by_href.has_key?(user.href) @users_by_href[user.href] = RsUserPolicy::User.new(user) end end end
ruby
def add_users(users) users.each do |user| unless @users_by_href.has_key?(user.href) @users_by_href[user.href] = RsUserPolicy::User.new(user) end end end
[ "def", "add_users", "(", "users", ")", "users", ".", "each", "do", "|", "user", "|", "unless", "@users_by_href", ".", "has_key?", "(", "user", ".", "href", ")", "@users_by_href", "[", "user", ".", "href", "]", "=", "RsUserPolicy", "::", "User", ".", "new", "(", "user", ")", "end", "end", "end" ]
Adds users to this collection only if the collection does not already include the specified users. The users RightScale API href is used as the unique identifier for deduplication @param [Array<RightApi::ResourceDetail>] users An array of RightAPI::ResourceDetail for the resource type "user"
[ "Adds", "users", "to", "this", "collection", "only", "if", "the", "collection", "does", "not", "already", "include", "the", "specified", "users", ".", "The", "users", "RightScale", "API", "href", "is", "used", "as", "the", "unique", "identifier", "for", "deduplication" ]
bae3355f1471cc7d28de7992c5d5f4ac39fff68b
https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/user_collection.rb#L41-L47
8,673
colstrom/ezmq
lib/ezmq/subscribe.rb
EZMQ.Subscriber.receive
def receive(**options) message = '' @socket.recv_string message message = message.match(/^(?<topic>[^\ ]*)\ (?<body>.*)/m) decoded = (options[:decode] || @decode).call message['body'] if block_given? yield decoded, message['topic'] else [decoded, message['topic']] end end
ruby
def receive(**options) message = '' @socket.recv_string message message = message.match(/^(?<topic>[^\ ]*)\ (?<body>.*)/m) decoded = (options[:decode] || @decode).call message['body'] if block_given? yield decoded, message['topic'] else [decoded, message['topic']] end end
[ "def", "receive", "(", "**", "options", ")", "message", "=", "''", "@socket", ".", "recv_string", "message", "message", "=", "message", ".", "match", "(", "/", "\\ ", "\\ ", "/m", ")", "decoded", "=", "(", "options", "[", ":decode", "]", "||", "@decode", ")", ".", "call", "message", "[", "'body'", "]", "if", "block_given?", "yield", "decoded", ",", "message", "[", "'topic'", "]", "else", "[", "decoded", ",", "message", "[", "'topic'", "]", "]", "end", "end" ]
Creates a new Subscriber socket. @note The default behaviour is to output and messages received to STDOUT. @param [:bind, :connect] mode (:connect) a mode for the socket. @param [Hash] options optional parameters. @option options [String] topic a topic to subscribe to. @see EZMQ::Socket EZMQ::Socket for optional parameters. @return [Publisher] a new instance of Publisher. Receive a message from the socket. @note This method blocks until a message arrives. @param [Hash] options optional parameters. @option options [lambda] decode how to decode the message. @yield [message, topic] passes the message body and topic to the block. @yieldparam [Object] message the message received (decoded). @yieldparam [String] topic the topic of the message. @return [Object] the message received (decoded).
[ "Creates", "a", "new", "Subscriber", "socket", "." ]
cd7f9f256d6c3f7a844871a3a77a89d7122d5836
https://github.com/colstrom/ezmq/blob/cd7f9f256d6c3f7a844871a3a77a89d7122d5836/lib/ezmq/subscribe.rb#L36-L48
8,674
bilus/kawaii
lib/kawaii/render_methods.rb
Kawaii.RenderMethods.render
def render(tmpl) t = Tilt.new(File.join('views', tmpl)) # @todo Caching! t.render(self) end
ruby
def render(tmpl) t = Tilt.new(File.join('views', tmpl)) # @todo Caching! t.render(self) end
[ "def", "render", "(", "tmpl", ")", "t", "=", "Tilt", ".", "new", "(", "File", ".", "join", "(", "'views'", ",", "tmpl", ")", ")", "# @todo Caching!", "t", ".", "render", "(", "self", ")", "end" ]
Renders a template. @param tmpl [String] file name or path to template, relative to /views in project dir @example Rendering html erb file render('index.html.erb') @todo Layouts.
[ "Renders", "a", "template", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/render_methods.rb#L10-L13
8,675
sonots/growthforecast-client
lib/growthforecast/client.rb
GrowthForecast.Client.get_json
def get_json(path) @request_uri = "#{@base_uri}#{path}" req = get_request(path) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
ruby
def get_json(path) @request_uri = "#{@base_uri}#{path}" req = get_request(path) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
[ "def", "get_json", "(", "path", ")", "@request_uri", "=", "\"#{@base_uri}#{path}\"", "req", "=", "get_request", "(", "path", ")", "@res", "=", "http_connection", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "handle_error", "(", "@res", ",", "@request_uri", ")", "JSON", ".", "parse", "(", "@res", ".", "body", ")", "end" ]
GET the JSON API @param [String] path @return [Hash] response body
[ "GET", "the", "JSON", "API" ]
6e0c463fe47627a96bded7e628f9456da4aa69ee
https://github.com/sonots/growthforecast-client/blob/6e0c463fe47627a96bded7e628f9456da4aa69ee/lib/growthforecast/client.rb#L84-L90
8,676
sonots/growthforecast-client
lib/growthforecast/client.rb
GrowthForecast.Client.post_json
def post_json(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = JSON.generate(data) extheader = { 'Content-Type' => 'application/json' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
ruby
def post_json(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = JSON.generate(data) extheader = { 'Content-Type' => 'application/json' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
[ "def", "post_json", "(", "path", ",", "data", "=", "{", "}", ")", "@request_uri", "=", "\"#{@base_uri}#{path}\"", "body", "=", "JSON", ".", "generate", "(", "data", ")", "extheader", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "req", "=", "post_request", "(", "path", ",", "body", ",", "extheader", ")", "@res", "=", "http_connection", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "handle_error", "(", "@res", ",", "@request_uri", ")", "JSON", ".", "parse", "(", "@res", ".", "body", ")", "end" ]
POST the JSON API @param [String] path @param [Hash] data @return [Hash] response body
[ "POST", "the", "JSON", "API" ]
6e0c463fe47627a96bded7e628f9456da4aa69ee
https://github.com/sonots/growthforecast-client/blob/6e0c463fe47627a96bded7e628f9456da4aa69ee/lib/growthforecast/client.rb#L96-L104
8,677
sonots/growthforecast-client
lib/growthforecast/client.rb
GrowthForecast.Client.post_query
def post_query(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = URI.encode_www_form(data) extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
ruby
def post_query(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = URI.encode_www_form(data) extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
[ "def", "post_query", "(", "path", ",", "data", "=", "{", "}", ")", "@request_uri", "=", "\"#{@base_uri}#{path}\"", "body", "=", "URI", ".", "encode_www_form", "(", "data", ")", "extheader", "=", "{", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", "}", "req", "=", "post_request", "(", "path", ",", "body", ",", "extheader", ")", "@res", "=", "http_connection", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "handle_error", "(", "@res", ",", "@request_uri", ")", "JSON", ".", "parse", "(", "@res", ".", "body", ")", "end" ]
POST the non-JSON API @param [String] path @param [Hash] data @return [String] response body
[ "POST", "the", "non", "-", "JSON", "API" ]
6e0c463fe47627a96bded7e628f9456da4aa69ee
https://github.com/sonots/growthforecast-client/blob/6e0c463fe47627a96bded7e628f9456da4aa69ee/lib/growthforecast/client.rb#L110-L118
8,678
malev/freeling-client
lib/freeling_client/analyzer.rb
FreelingClient.Analyzer.tokens
def tokens(cmd, text) valide_command!(cmd) Enumerator.new do |yielder| call(cmd, text).each do |freeling_line| yielder << parse_token_line(freeling_line) unless freeling_line.empty? end end end
ruby
def tokens(cmd, text) valide_command!(cmd) Enumerator.new do |yielder| call(cmd, text).each do |freeling_line| yielder << parse_token_line(freeling_line) unless freeling_line.empty? end end end
[ "def", "tokens", "(", "cmd", ",", "text", ")", "valide_command!", "(", "cmd", ")", "Enumerator", ".", "new", "do", "|", "yielder", "|", "call", "(", "cmd", ",", "text", ")", ".", "each", "do", "|", "freeling_line", "|", "yielder", "<<", "parse_token_line", "(", "freeling_line", ")", "unless", "freeling_line", ".", "empty?", "end", "end", "end" ]
Generate tokens for a given text Example: >> analyzer = FreelingClient::Analyzer.new >> analyzer.token(:morfo, "Este texto está en español.") Arguments: cmd: (Symbol) text: (String)
[ "Generate", "tokens", "for", "a", "given", "text" ]
1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c
https://github.com/malev/freeling-client/blob/1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c/lib/freeling_client/analyzer.rb#L29-L36
8,679
Figure53/qlab-ruby
lib/qlab-ruby/machine.rb
QLab.Machine.find_workspace
def find_workspace params={} workspaces.find do |ws| matches = true # match each key to the given workspace params.keys.each do |key| matches = matches && (ws.send(key.to_sym) == params[key]) end matches end end
ruby
def find_workspace params={} workspaces.find do |ws| matches = true # match each key to the given workspace params.keys.each do |key| matches = matches && (ws.send(key.to_sym) == params[key]) end matches end end
[ "def", "find_workspace", "params", "=", "{", "}", "workspaces", ".", "find", "do", "|", "ws", "|", "matches", "=", "true", "# match each key to the given workspace", "params", ".", "keys", ".", "each", "do", "|", "key", "|", "matches", "=", "matches", "&&", "(", "ws", ".", "send", "(", "key", ".", "to_sym", ")", "==", "params", "[", "key", "]", ")", "end", "matches", "end", "end" ]
Find a workspace according to the given params.
[ "Find", "a", "workspace", "according", "to", "the", "given", "params", "." ]
169494940f478b897066db4c15f130769aa43243
https://github.com/Figure53/qlab-ruby/blob/169494940f478b897066db4c15f130769aa43243/lib/qlab-ruby/machine.rb#L47-L58
8,680
yipdw/analysand
lib/analysand/errors.rb
Analysand.Errors.ex
def ex(klass, response) klass.new("Expected response to have code 2xx, got #{response.code} instead").tap do |ex| ex.response = response end end
ruby
def ex(klass, response) klass.new("Expected response to have code 2xx, got #{response.code} instead").tap do |ex| ex.response = response end end
[ "def", "ex", "(", "klass", ",", "response", ")", "klass", ".", "new", "(", "\"Expected response to have code 2xx, got #{response.code} instead\"", ")", ".", "tap", "do", "|", "ex", "|", "ex", ".", "response", "=", "response", "end", "end" ]
Instantiates an exception and fills in a response. klass - the exception class response - the response object that caused the error
[ "Instantiates", "an", "exception", "and", "fills", "in", "a", "response", "." ]
bc62e67031bf7e813e49538669f7434f2efd9ee9
https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/errors.rb#L8-L12
8,681
wapcaplet/kelp
lib/kelp/checkbox.rb
Kelp.Checkbox.checkbox_should_be_checked
def checkbox_should_be_checked(checkbox, scope={}) in_scope(scope) do field_checked = find_field(checkbox)['checked'] if !field_checked raise Kelp::Unexpected, "Expected '#{checkbox}' to be checked, but it is unchecked." end end end
ruby
def checkbox_should_be_checked(checkbox, scope={}) in_scope(scope) do field_checked = find_field(checkbox)['checked'] if !field_checked raise Kelp::Unexpected, "Expected '#{checkbox}' to be checked, but it is unchecked." end end end
[ "def", "checkbox_should_be_checked", "(", "checkbox", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "field_checked", "=", "find_field", "(", "checkbox", ")", "[", "'checked'", "]", "if", "!", "field_checked", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected '#{checkbox}' to be checked, but it is unchecked.\"", "end", "end", "end" ]
Verify that the given checkbox is checked. @param [String] checkbox Capybara locator for the checkbox @param [Hash] scope Scoping keywords as understood by {#in_scope} @raise [Kelp::Unexpected] If the given checkbox is not checked @since 0.1.2
[ "Verify", "that", "the", "given", "checkbox", "is", "checked", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/checkbox.rb#L22-L30
8,682
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.parse_email_headers
def parse_email_headers(s) keys={} match = (s =~ /\A((\w[\w\s\_\-]+: .*\n)+)\s*\n/) if match != 0 keys[:data] = s else keys[:data] = $' headers = $1 headers.split("\n").each do |l| # Fails if there are other ':' characters. # k, v = l.split(':') k, v = l.split(':', 2) k, v = normalize_key_and_value(k, v) k = k.to_sym # puts "K = #{k}, V=#{v}" keys[k] = v end end keys end
ruby
def parse_email_headers(s) keys={} match = (s =~ /\A((\w[\w\s\_\-]+: .*\n)+)\s*\n/) if match != 0 keys[:data] = s else keys[:data] = $' headers = $1 headers.split("\n").each do |l| # Fails if there are other ':' characters. # k, v = l.split(':') k, v = l.split(':', 2) k, v = normalize_key_and_value(k, v) k = k.to_sym # puts "K = #{k}, V=#{v}" keys[k] = v end end keys end
[ "def", "parse_email_headers", "(", "s", ")", "keys", "=", "{", "}", "match", "=", "(", "s", "=~", "/", "\\A", "\\w", "\\w", "\\s", "\\_", "\\-", "\\n", "\\s", "\\n", "/", ")", "if", "match", "!=", "0", "keys", "[", ":data", "]", "=", "s", "else", "keys", "[", ":data", "]", "=", "$'", "headers", "=", "$1", "headers", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "l", "|", "# Fails if there are other ':' characters.", "#\t\t\t\tk, v = l.split(':')", "k", ",", "v", "=", "l", ".", "split", "(", "':'", ",", "2", ")", "k", ",", "v", "=", "normalize_key_and_value", "(", "k", ",", "v", ")", "k", "=", "k", ".", "to_sym", "#\t\t\t\tputs \"K = #{k}, V=#{v}\"", "keys", "[", "k", "]", "=", "v", "end", "end", "keys", "end" ]
This parses email headers. Returns an hash. +hash['data']+ is the message. Keys are downcased, space becomes underscore, converted to symbols. My key: true becomes: {:my_key => true}
[ "This", "parses", "email", "headers", ".", "Returns", "an", "hash", "." ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L47-L66
8,683
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.normalize_key_and_value
def normalize_key_and_value(k,v) v = v ? v.strip : true # no value defaults to true k = k.strip # check synonyms v = true if ['yes','true'].include?(v.to_s.downcase) v = false if ['no','false'].include?(v.to_s.downcase) k = k.downcase.gsub(' ','_') return k, v end
ruby
def normalize_key_and_value(k,v) v = v ? v.strip : true # no value defaults to true k = k.strip # check synonyms v = true if ['yes','true'].include?(v.to_s.downcase) v = false if ['no','false'].include?(v.to_s.downcase) k = k.downcase.gsub(' ','_') return k, v end
[ "def", "normalize_key_and_value", "(", "k", ",", "v", ")", "v", "=", "v", "?", "v", ".", "strip", ":", "true", "# no value defaults to true", "k", "=", "k", ".", "strip", "# check synonyms", "v", "=", "true", "if", "[", "'yes'", ",", "'true'", "]", ".", "include?", "(", "v", ".", "to_s", ".", "downcase", ")", "v", "=", "false", "if", "[", "'no'", ",", "'false'", "]", ".", "include?", "(", "v", ".", "to_s", ".", "downcase", ")", "k", "=", "k", ".", "downcase", ".", "gsub", "(", "' '", ",", "'_'", ")", "return", "k", ",", "v", "end" ]
Keys are downcased, space becomes underscore, converted to symbols.
[ "Keys", "are", "downcased", "space", "becomes", "underscore", "converted", "to", "symbols", "." ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L69-L79
8,684
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.number_of_leading_spaces
def number_of_leading_spaces(s) n=0; i=0; while i < s.size c = s[i,1] if c == ' ' i+=1; n+=1; elsif c == "\t" i+=1; n+=TabSize; else break end end n end
ruby
def number_of_leading_spaces(s) n=0; i=0; while i < s.size c = s[i,1] if c == ' ' i+=1; n+=1; elsif c == "\t" i+=1; n+=TabSize; else break end end n end
[ "def", "number_of_leading_spaces", "(", "s", ")", "n", "=", "0", ";", "i", "=", "0", ";", "while", "i", "<", "s", ".", "size", "c", "=", "s", "[", "i", ",", "1", "]", "if", "c", "==", "' '", "i", "+=", "1", ";", "n", "+=", "1", ";", "elsif", "c", "==", "\"\\t\"", "i", "+=", "1", ";", "n", "+=", "TabSize", ";", "else", "break", "end", "end", "n", "end" ]
Returns the number of leading spaces, considering that a tab counts as `TabSize` spaces.
[ "Returns", "the", "number", "of", "leading", "spaces", "considering", "that", "a", "tab", "counts", "as", "TabSize", "spaces", "." ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L83-L96
8,685
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.spaces_before_first_char
def spaces_before_first_char(s) case s.md_type when :ulist i=0; # skip whitespace if present while s[i,1] =~ /\s/; i+=1 end # skip indicator (+, -, *) i+=1 # skip optional whitespace while s[i,1] =~ /\s/; i+=1 end return i when :olist i=0; # skip whitespace while s[i,1] =~ /\s/; i+=1 end # skip digits while s[i,1] =~ /\d/; i+=1 end # skip dot i+=1 # skip whitespace while s[i,1] =~ /\s/; i+=1 end return i else tell_user "BUG (my bad): '#{s}' is not a list" 0 end end
ruby
def spaces_before_first_char(s) case s.md_type when :ulist i=0; # skip whitespace if present while s[i,1] =~ /\s/; i+=1 end # skip indicator (+, -, *) i+=1 # skip optional whitespace while s[i,1] =~ /\s/; i+=1 end return i when :olist i=0; # skip whitespace while s[i,1] =~ /\s/; i+=1 end # skip digits while s[i,1] =~ /\d/; i+=1 end # skip dot i+=1 # skip whitespace while s[i,1] =~ /\s/; i+=1 end return i else tell_user "BUG (my bad): '#{s}' is not a list" 0 end end
[ "def", "spaces_before_first_char", "(", "s", ")", "case", "s", ".", "md_type", "when", ":ulist", "i", "=", "0", ";", "# skip whitespace if present", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "# skip indicator (+, -, *)", "i", "+=", "1", "# skip optional whitespace", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "return", "i", "when", ":olist", "i", "=", "0", ";", "# skip whitespace", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "# skip digits", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\d", "/", ";", "i", "+=", "1", "end", "# skip dot", "i", "+=", "1", "# skip whitespace", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "return", "i", "else", "tell_user", "\"BUG (my bad): '#{s}' is not a list\"", "0", "end", "end" ]
This returns the position of the first real char in a list item For example: '*Hello' # => 1 '* Hello' # => 2 ' * Hello' # => 3 ' * Hello' # => 5 '1.Hello' # => 2 ' 1. Hello' # => 5
[ "This", "returns", "the", "position", "of", "the", "first", "real", "char", "in", "a", "list", "item" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L108-L134
8,686
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.strip_hashes
def strip_hashes(s) s = s[num_leading_hashes(s), s.size] i = s.size-1 while i > 0 && (s[i,1] =~ /(#|\s)/); i-=1; end s[0, i+1].strip end
ruby
def strip_hashes(s) s = s[num_leading_hashes(s), s.size] i = s.size-1 while i > 0 && (s[i,1] =~ /(#|\s)/); i-=1; end s[0, i+1].strip end
[ "def", "strip_hashes", "(", "s", ")", "s", "=", "s", "[", "num_leading_hashes", "(", "s", ")", ",", "s", ".", "size", "]", "i", "=", "s", ".", "size", "-", "1", "while", "i", ">", "0", "&&", "(", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ")", ";", "i", "-=", "1", ";", "end", "s", "[", "0", ",", "i", "+", "1", "]", ".", "strip", "end" ]
Strips initial and final hashes
[ "Strips", "initial", "and", "final", "hashes" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L144-L149
8,687
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.strip_indent
def strip_indent(s, n) i = 0 while i < s.size && n>0 c = s[i,1] if c == ' ' n-=1; elsif c == "\t" n-=TabSize; else break end i+=1 end s[i, s.size] end
ruby
def strip_indent(s, n) i = 0 while i < s.size && n>0 c = s[i,1] if c == ' ' n-=1; elsif c == "\t" n-=TabSize; else break end i+=1 end s[i, s.size] end
[ "def", "strip_indent", "(", "s", ",", "n", ")", "i", "=", "0", "while", "i", "<", "s", ".", "size", "&&", "n", ">", "0", "c", "=", "s", "[", "i", ",", "1", "]", "if", "c", "==", "' '", "n", "-=", "1", ";", "elsif", "c", "==", "\"\\t\"", "n", "-=", "TabSize", ";", "else", "break", "end", "i", "+=", "1", "end", "s", "[", "i", ",", "s", ".", "size", "]", "end" ]
toglie al massimo n caratteri
[ "toglie", "al", "massimo", "n", "caratteri" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L163-L177
8,688
fotonauts/activr
lib/activr/timeline.rb
Activr.Timeline.dump
def dump(options = { }) options = options.dup limit = options.delete(:nb) || 100 self.find(limit).map{ |tl_entry| tl_entry.humanize(options) } end
ruby
def dump(options = { }) options = options.dup limit = options.delete(:nb) || 100 self.find(limit).map{ |tl_entry| tl_entry.humanize(options) } end
[ "def", "dump", "(", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "limit", "=", "options", ".", "delete", "(", ":nb", ")", "||", "100", "self", ".", "find", "(", "limit", ")", ".", "map", "{", "|", "tl_entry", "|", "tl_entry", ".", "humanize", "(", "options", ")", "}", "end" ]
Dump humanization of last timeline entries @param options [Hash] Options hash @option options (see Activr::Timeline::Entry#humanize) @option options [Integer] :nb Number of timeline entries to dump (default: 100) @return [Array<String>] Array of humanized sentences
[ "Dump", "humanization", "of", "last", "timeline", "entries" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/timeline.rb#L368-L374
8,689
fotonauts/activr
lib/activr/timeline.rb
Activr.Timeline.trim!
def trim! # check if trimming is needed if (self.trim_max_length > 0) && (self.count > self.trim_max_length) last_tle = self.find(1, :skip => self.trim_max_length - 1).first if last_tle self.delete(:before => last_tle.activity.at) end end end
ruby
def trim! # check if trimming is needed if (self.trim_max_length > 0) && (self.count > self.trim_max_length) last_tle = self.find(1, :skip => self.trim_max_length - 1).first if last_tle self.delete(:before => last_tle.activity.at) end end end
[ "def", "trim!", "# check if trimming is needed", "if", "(", "self", ".", "trim_max_length", ">", "0", ")", "&&", "(", "self", ".", "count", ">", "self", ".", "trim_max_length", ")", "last_tle", "=", "self", ".", "find", "(", "1", ",", ":skip", "=>", "self", ".", "trim_max_length", "-", "1", ")", ".", "first", "if", "last_tle", "self", ".", "delete", "(", ":before", "=>", "last_tle", ".", "activity", ".", "at", ")", "end", "end", "end" ]
Remove old timeline entries
[ "Remove", "old", "timeline", "entries" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/timeline.rb#L385-L393
8,690
alphagov/govuk_navigation_helpers
lib/govuk_navigation_helpers/rummager_taxonomy_sidebar_links.rb
GovukNavigationHelpers.RummagerTaxonomySidebarLinks.content_related_to
def content_related_to(taxon, used_related_links) statsd.time(:taxonomy_sidebar_search_time) do begin results = Services.rummager.search( similar_to: @content_item.base_path, start: 0, count: 3, filter_taxons: [taxon.content_id], filter_navigation_document_supertype: 'guidance', reject_link: used_related_links.to_a, fields: %w[title link], )['results'] statsd.increment(:taxonomy_sidebar_searches) results .map { |result| { title: result['title'], link: result['link'], } } .sort_by { |result| result[:title] } rescue StandardError => e GovukNavigationHelpers.configuration.error_handler.notify(e) [] end end end
ruby
def content_related_to(taxon, used_related_links) statsd.time(:taxonomy_sidebar_search_time) do begin results = Services.rummager.search( similar_to: @content_item.base_path, start: 0, count: 3, filter_taxons: [taxon.content_id], filter_navigation_document_supertype: 'guidance', reject_link: used_related_links.to_a, fields: %w[title link], )['results'] statsd.increment(:taxonomy_sidebar_searches) results .map { |result| { title: result['title'], link: result['link'], } } .sort_by { |result| result[:title] } rescue StandardError => e GovukNavigationHelpers.configuration.error_handler.notify(e) [] end end end
[ "def", "content_related_to", "(", "taxon", ",", "used_related_links", ")", "statsd", ".", "time", "(", ":taxonomy_sidebar_search_time", ")", "do", "begin", "results", "=", "Services", ".", "rummager", ".", "search", "(", "similar_to", ":", "@content_item", ".", "base_path", ",", "start", ":", "0", ",", "count", ":", "3", ",", "filter_taxons", ":", "[", "taxon", ".", "content_id", "]", ",", "filter_navigation_document_supertype", ":", "'guidance'", ",", "reject_link", ":", "used_related_links", ".", "to_a", ",", "fields", ":", "%w[", "title", "link", "]", ",", ")", "[", "'results'", "]", "statsd", ".", "increment", "(", ":taxonomy_sidebar_searches", ")", "results", ".", "map", "{", "|", "result", "|", "{", "title", ":", "result", "[", "'title'", "]", ",", "link", ":", "result", "[", "'link'", "]", ",", "}", "}", ".", "sort_by", "{", "|", "result", "|", "result", "[", ":title", "]", "}", "rescue", "StandardError", "=>", "e", "GovukNavigationHelpers", ".", "configuration", ".", "error_handler", ".", "notify", "(", "e", ")", "[", "]", "end", "end", "end" ]
This method will fetch content related to content_item, and tagged to taxon. This is a temporary method that uses search to achieve this. This behaviour is to be moved into  the content store
[ "This", "method", "will", "fetch", "content", "related", "to", "content_item", "and", "tagged", "to", "taxon", ".", "This", "is", "a", "temporary", "method", "that", "uses", "search", "to", "achieve", "this", ".", "This", "behaviour", "is", "to", "be", "moved", "into", "the", "content", "store" ]
5eddcaec5412473fa4e22ef8b8d2cbe406825886
https://github.com/alphagov/govuk_navigation_helpers/blob/5eddcaec5412473fa4e22ef8b8d2cbe406825886/lib/govuk_navigation_helpers/rummager_taxonomy_sidebar_links.rb#L32-L55
8,691
sanichi/icu_tournament
lib/icu_tournament/tournament_sp.rb
ICU.Player.to_sp_text
def to_sp_text(rounds, format) attrs = [num.to_s, name, id.to_s, ('%.1f' % points).sub(/\.0/, '')] (1..rounds).each do |r| result = find_result(r) attrs << (result ? result.to_sp_text : " : ") end format % attrs end
ruby
def to_sp_text(rounds, format) attrs = [num.to_s, name, id.to_s, ('%.1f' % points).sub(/\.0/, '')] (1..rounds).each do |r| result = find_result(r) attrs << (result ? result.to_sp_text : " : ") end format % attrs end
[ "def", "to_sp_text", "(", "rounds", ",", "format", ")", "attrs", "=", "[", "num", ".", "to_s", ",", "name", ",", "id", ".", "to_s", ",", "(", "'%.1f'", "%", "points", ")", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "]", "(", "1", "..", "rounds", ")", ".", "each", "do", "|", "r", "|", "result", "=", "find_result", "(", "r", ")", "attrs", "<<", "(", "result", "?", "result", ".", "to_sp_text", ":", "\" : \"", ")", "end", "format", "%", "attrs", "end" ]
Format a player's record as it would appear in an SP text export file.
[ "Format", "a", "player", "s", "record", "as", "it", "would", "appear", "in", "an", "SP", "text", "export", "file", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament_sp.rb#L333-L340
8,692
sanichi/icu_tournament
lib/icu_tournament/tournament_sp.rb
ICU.Result.to_sp_text
def to_sp_text sp = opponent ? opponent.to_s : '0' sp << ':' if rateable sp << score else sp << case score when 'W' then '+' when 'L' then '-' else '=' end end end
ruby
def to_sp_text sp = opponent ? opponent.to_s : '0' sp << ':' if rateable sp << score else sp << case score when 'W' then '+' when 'L' then '-' else '=' end end end
[ "def", "to_sp_text", "sp", "=", "opponent", "?", "opponent", ".", "to_s", ":", "'0'", "sp", "<<", "':'", "if", "rateable", "sp", "<<", "score", "else", "sp", "<<", "case", "score", "when", "'W'", "then", "'+'", "when", "'L'", "then", "'-'", "else", "'='", "end", "end", "end" ]
Format a player's result as it would appear in an SP text export file.
[ "Format", "a", "player", "s", "result", "as", "it", "would", "appear", "in", "an", "SP", "text", "export", "file", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament_sp.rb#L345-L357
8,693
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.get_baseline_value
def get_baseline_value(baseline_type, obj, ts = Time.now.ceil) unless Octo::Counter.constants.include?baseline_type raise ArgumentError, 'No such baseline defined' end args = { ts: ts, type: Octo::Counter.const_get(baseline_type), uid: obj.unique_id, enterprise_id: obj.enterprise.id } bl = get_cached(args) if bl bl.val else 0.01 end end
ruby
def get_baseline_value(baseline_type, obj, ts = Time.now.ceil) unless Octo::Counter.constants.include?baseline_type raise ArgumentError, 'No such baseline defined' end args = { ts: ts, type: Octo::Counter.const_get(baseline_type), uid: obj.unique_id, enterprise_id: obj.enterprise.id } bl = get_cached(args) if bl bl.val else 0.01 end end
[ "def", "get_baseline_value", "(", "baseline_type", ",", "obj", ",", "ts", "=", "Time", ".", "now", ".", "ceil", ")", "unless", "Octo", "::", "Counter", ".", "constants", ".", "include?", "baseline_type", "raise", "ArgumentError", ",", "'No such baseline defined'", "end", "args", "=", "{", "ts", ":", "ts", ",", "type", ":", "Octo", "::", "Counter", ".", "const_get", "(", "baseline_type", ")", ",", "uid", ":", "obj", ".", "unique_id", ",", "enterprise_id", ":", "obj", ".", "enterprise", ".", "id", "}", "bl", "=", "get_cached", "(", "args", ")", "if", "bl", "bl", ".", "val", "else", "0.01", "end", "end" ]
Finds baseline value of an object @param [Fixnum] baseline_type One of the valid Baseline Types defined @param [Object] obj The object for whom baseline value is to be found @param [Time] ts The timestamp at which baseline is to be found
[ "Finds", "baseline", "value", "of", "an", "object" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L40-L57
8,694
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.aggregate
def aggregate(type, ts) Octo::Enterprise.each do |enterprise| aggregate_baseline enterprise.id, type, ts end end
ruby
def aggregate(type, ts) Octo::Enterprise.each do |enterprise| aggregate_baseline enterprise.id, type, ts end end
[ "def", "aggregate", "(", "type", ",", "ts", ")", "Octo", "::", "Enterprise", ".", "each", "do", "|", "enterprise", "|", "aggregate_baseline", "enterprise", ".", "id", ",", "type", ",", "ts", "end", "end" ]
Does an aggregation of type for a timestamp @param [Fixnum] type The counter type for which aggregation has to be done @param [Time] ts The time at which aggregation should happen
[ "Does", "an", "aggregation", "of", "type", "for", "a", "timestamp" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L63-L67
8,695
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.aggregate_baseline
def aggregate_baseline(enterprise_id, type, ts = Time.now.floor) clazz = @baseline_for.constantize _ts = ts start_calc_time = (_ts.to_datetime - MAX_DURATION.day).to_time last_n_days_interval = start_calc_time.ceil.to(_ts, 24.hour) last_n_days_interval.each do |hist| args = { ts: hist, type: type, enterprise_id: enterprise_id } counters = @baseline_for.constantize.send(:where, args) baseline = baseline_from_counters(counters) store_baseline enterprise_id, type, hist, baseline end end
ruby
def aggregate_baseline(enterprise_id, type, ts = Time.now.floor) clazz = @baseline_for.constantize _ts = ts start_calc_time = (_ts.to_datetime - MAX_DURATION.day).to_time last_n_days_interval = start_calc_time.ceil.to(_ts, 24.hour) last_n_days_interval.each do |hist| args = { ts: hist, type: type, enterprise_id: enterprise_id } counters = @baseline_for.constantize.send(:where, args) baseline = baseline_from_counters(counters) store_baseline enterprise_id, type, hist, baseline end end
[ "def", "aggregate_baseline", "(", "enterprise_id", ",", "type", ",", "ts", "=", "Time", ".", "now", ".", "floor", ")", "clazz", "=", "@baseline_for", ".", "constantize", "_ts", "=", "ts", "start_calc_time", "=", "(", "_ts", ".", "to_datetime", "-", "MAX_DURATION", ".", "day", ")", ".", "to_time", "last_n_days_interval", "=", "start_calc_time", ".", "ceil", ".", "to", "(", "_ts", ",", "24", ".", "hour", ")", "last_n_days_interval", ".", "each", "do", "|", "hist", "|", "args", "=", "{", "ts", ":", "hist", ",", "type", ":", "type", ",", "enterprise_id", ":", "enterprise_id", "}", "counters", "=", "@baseline_for", ".", "constantize", ".", "send", "(", ":where", ",", "args", ")", "baseline", "=", "baseline_from_counters", "(", "counters", ")", "store_baseline", "enterprise_id", ",", "type", ",", "hist", ",", "baseline", "end", "end" ]
Aggregates the baseline for a minute
[ "Aggregates", "the", "baseline", "for", "a", "minute" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L71-L86
8,696
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.store_baseline
def store_baseline(enterprise_id, type, ts, baseline) return if baseline.nil? or baseline.empty? baseline.each do |uid, val| self.new({ enterprise_id: enterprise_id, type: type, ts: ts, uid: uid, val: val }).save! end end
ruby
def store_baseline(enterprise_id, type, ts, baseline) return if baseline.nil? or baseline.empty? baseline.each do |uid, val| self.new({ enterprise_id: enterprise_id, type: type, ts: ts, uid: uid, val: val }).save! end end
[ "def", "store_baseline", "(", "enterprise_id", ",", "type", ",", "ts", ",", "baseline", ")", "return", "if", "baseline", ".", "nil?", "or", "baseline", ".", "empty?", "baseline", ".", "each", "do", "|", "uid", ",", "val", "|", "self", ".", "new", "(", "{", "enterprise_id", ":", "enterprise_id", ",", "type", ":", "type", ",", "ts", ":", "ts", ",", "uid", ":", "uid", ",", "val", ":", "val", "}", ")", ".", "save!", "end", "end" ]
Stores the baseline for an enterprise, and type @param [String] enterprise_id The enterprise ID of enterprise @param [Fixnum] type The Counter type as baseline type @param [Time] ts The time stamp of storage @param [Hash{String => Float}] baseline A hash representing baseline
[ "Stores", "the", "baseline", "for", "an", "enterprise", "and", "type" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L95-L106
8,697
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.baseline_from_counters
def baseline_from_counters(counters) baseline = {} uid_groups = counters.group_by { |x| x.uid } uid_groups.each do |uid, counts| baseline[uid] = score_counts(counts) end baseline end
ruby
def baseline_from_counters(counters) baseline = {} uid_groups = counters.group_by { |x| x.uid } uid_groups.each do |uid, counts| baseline[uid] = score_counts(counts) end baseline end
[ "def", "baseline_from_counters", "(", "counters", ")", "baseline", "=", "{", "}", "uid_groups", "=", "counters", ".", "group_by", "{", "|", "x", "|", "x", ".", "uid", "}", "uid_groups", ".", "each", "do", "|", "uid", ",", "counts", "|", "baseline", "[", "uid", "]", "=", "score_counts", "(", "counts", ")", "end", "baseline", "end" ]
Calculates the baseline from counters
[ "Calculates", "the", "baseline", "from", "counters" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L109-L116
8,698
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.score_counts
def score_counts(counts) if counts.count > 0 _num = counts.map { |x| x.obp } _num.percentile(90) else 0.01 end end
ruby
def score_counts(counts) if counts.count > 0 _num = counts.map { |x| x.obp } _num.percentile(90) else 0.01 end end
[ "def", "score_counts", "(", "counts", ")", "if", "counts", ".", "count", ">", "0", "_num", "=", "counts", ".", "map", "{", "|", "x", "|", "x", ".", "obp", "}", "_num", ".", "percentile", "(", "90", ")", "else", "0.01", "end", "end" ]
Calculates the baseline score from an array of scores @param [Array<Float>] counts The counts array @return [Float] The baseline score for counters
[ "Calculates", "the", "baseline", "score", "from", "an", "array", "of", "scores" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L121-L128
8,699
brainlid/locale_dating
lib/locale_dating.rb
LocaleDating.ClassMethods.locale_dating_naming_checks
def locale_dating_naming_checks(args, options) options.reverse_merge!(:format => :default) options[:ending] ||= "as_#{options[:format]}".to_sym unless options[:format] == :default options[:ending] ||= :as_text # error if multiple args used with :name option raise MethodOverwriteError, "multiple attributes cannot be wrapped with an explicitly named method" if args.length > 1 && options.key?(:name) end
ruby
def locale_dating_naming_checks(args, options) options.reverse_merge!(:format => :default) options[:ending] ||= "as_#{options[:format]}".to_sym unless options[:format] == :default options[:ending] ||= :as_text # error if multiple args used with :name option raise MethodOverwriteError, "multiple attributes cannot be wrapped with an explicitly named method" if args.length > 1 && options.key?(:name) end
[ "def", "locale_dating_naming_checks", "(", "args", ",", "options", ")", "options", ".", "reverse_merge!", "(", ":format", "=>", ":default", ")", "options", "[", ":ending", "]", "||=", "\"as_#{options[:format]}\"", ".", "to_sym", "unless", "options", "[", ":format", "]", "==", ":default", "options", "[", ":ending", "]", "||=", ":as_text", "# error if multiple args used with :name option", "raise", "MethodOverwriteError", ",", "\"multiple attributes cannot be wrapped with an explicitly named method\"", "if", "args", ".", "length", ">", "1", "&&", "options", ".", "key?", "(", ":name", ")", "end" ]
Given the options for a locale_dating call, set the defaults for the naming convention to use.
[ "Given", "the", "options", "for", "a", "locale_dating", "call", "set", "the", "defaults", "for", "the", "naming", "convention", "to", "use", "." ]
696aa73a648d5c0552a437801b07331c6cc005ee
https://github.com/brainlid/locale_dating/blob/696aa73a648d5c0552a437801b07331c6cc005ee/lib/locale_dating.rb#L176-L182