id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,300 | xinminlabs/synvert-core | lib/synvert/core/rewriter/instance.rb | Synvert::Core.Rewriter::Instance.remove_code_or_whole_line | def remove_code_or_whole_line(source, line)
newline_at_end_of_line = source[-1] == "\n"
source_arr = source.split("\n")
if source_arr[line - 1] && source_arr[line - 1].strip.empty?
source_arr.delete_at(line - 1)
if source_arr[line - 2] && source_arr[line - 2].strip.empty? && source_arr[line - 1] && source_arr[line - 1].strip.empty?
source_arr.delete_at(line - 1)
end
source_arr.join("\n") + (newline_at_end_of_line ? "\n" : '')
else
source
end
end | ruby | def remove_code_or_whole_line(source, line)
newline_at_end_of_line = source[-1] == "\n"
source_arr = source.split("\n")
if source_arr[line - 1] && source_arr[line - 1].strip.empty?
source_arr.delete_at(line - 1)
if source_arr[line - 2] && source_arr[line - 2].strip.empty? && source_arr[line - 1] && source_arr[line - 1].strip.empty?
source_arr.delete_at(line - 1)
end
source_arr.join("\n") + (newline_at_end_of_line ? "\n" : '')
else
source
end
end | [
"def",
"remove_code_or_whole_line",
"(",
"source",
",",
"line",
")",
"newline_at_end_of_line",
"=",
"source",
"[",
"-",
"1",
"]",
"==",
"\"\\n\"",
"source_arr",
"=",
"source",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"source_arr",
"[",
"line",
"-",
"1",
"]",
"&&",
"source_arr",
"[",
"line",
"-",
"1",
"]",
".",
"strip",
".",
"empty?",
"source_arr",
".",
"delete_at",
"(",
"line",
"-",
"1",
")",
"if",
"source_arr",
"[",
"line",
"-",
"2",
"]",
"&&",
"source_arr",
"[",
"line",
"-",
"2",
"]",
".",
"strip",
".",
"empty?",
"&&",
"source_arr",
"[",
"line",
"-",
"1",
"]",
"&&",
"source_arr",
"[",
"line",
"-",
"1",
"]",
".",
"strip",
".",
"empty?",
"source_arr",
".",
"delete_at",
"(",
"line",
"-",
"1",
")",
"end",
"source_arr",
".",
"join",
"(",
"\"\\n\"",
")",
"+",
"(",
"newline_at_end_of_line",
"?",
"\"\\n\"",
":",
"''",
")",
"else",
"source",
"end",
"end"
] | It checks if code is removed and that line is empty.
@param source [String] source code of file
@param line [String] the line number | [
"It",
"checks",
"if",
"code",
"is",
"removed",
"and",
"that",
"line",
"is",
"empty",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/instance.rb#L288-L300 |
4,301 | SmallLars/openssl-ccm | lib/openssl/ccm.rb | OpenSSL.CCM.encrypt | def encrypt(data, nonce, additional_data = '')
valid?(data, nonce, additional_data)
crypt(data, nonce) + mac(data, nonce, additional_data)
end | ruby | def encrypt(data, nonce, additional_data = '')
valid?(data, nonce, additional_data)
crypt(data, nonce) + mac(data, nonce, additional_data)
end | [
"def",
"encrypt",
"(",
"data",
",",
"nonce",
",",
"additional_data",
"=",
"''",
")",
"valid?",
"(",
"data",
",",
"nonce",
",",
"additional_data",
")",
"crypt",
"(",
"data",
",",
"nonce",
")",
"+",
"mac",
"(",
"data",
",",
"nonce",
",",
"additional_data",
")",
"end"
] | Creates a new CCM object.
@param cipher [String] one of the supported algorithms like 'AES'
@param key [String] the key used for encryption and decryption
@param mac_len [Number] the length of the mac.
needs to be in 4, 6, 8, 10, 12, 14, 16
@return [Object] the new CCM object
Encrypts the input data and appends mac for authentication.
If there is additional data, its included into mac calculation.
@param data [String] the data to encrypt
@param nonce [String] the nonce used for encryption
@param additional_data [String] additional data to
authenticate with mac (not part of the output)
@return [String] the encrypted data with appended mac | [
"Creates",
"a",
"new",
"CCM",
"object",
"."
] | 15f258f0db5779a3fb186ab7f957eb8c2bcef13a | https://github.com/SmallLars/openssl-ccm/blob/15f258f0db5779a3fb186ab7f957eb8c2bcef13a/lib/openssl/ccm.rb#L68-L72 |
4,302 | PublicHealthEngland/ndr_support | lib/ndr_support/utf8_encoding/force_binary.rb | UTF8Encoding.ForceBinary.binary_encode_if_any_high_ascii | def binary_encode_if_any_high_ascii(string)
string = ensure_utf8(string)
string.force_encoding('BINARY') if string.bytes.detect { |byte| byte > 127 }
string
end | ruby | def binary_encode_if_any_high_ascii(string)
string = ensure_utf8(string)
string.force_encoding('BINARY') if string.bytes.detect { |byte| byte > 127 }
string
end | [
"def",
"binary_encode_if_any_high_ascii",
"(",
"string",
")",
"string",
"=",
"ensure_utf8",
"(",
"string",
")",
"string",
".",
"force_encoding",
"(",
"'BINARY'",
")",
"if",
"string",
".",
"bytes",
".",
"detect",
"{",
"|",
"byte",
"|",
"byte",
">",
"127",
"}",
"string",
"end"
] | Returns a BINARY-encoded version of `string`, if is cannot be represented as 7bit ASCII. | [
"Returns",
"a",
"BINARY",
"-",
"encoded",
"version",
"of",
"string",
"if",
"is",
"cannot",
"be",
"represented",
"as",
"7bit",
"ASCII",
"."
] | 6daf98ca972e79de1c8457eb720f058b03ead21c | https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/utf8_encoding/force_binary.rb#L28-L32 |
4,303 | PublicHealthEngland/ndr_support | lib/ndr_support/utf8_encoding/force_binary.rb | UTF8Encoding.ForceBinary.binary_encode_any_high_ascii_in_hash | def binary_encode_any_high_ascii_in_hash(hash)
Hash[hash.map { |key, value| [key, binary_encode_any_high_ascii(value)] }]
end | ruby | def binary_encode_any_high_ascii_in_hash(hash)
Hash[hash.map { |key, value| [key, binary_encode_any_high_ascii(value)] }]
end | [
"def",
"binary_encode_any_high_ascii_in_hash",
"(",
"hash",
")",
"Hash",
"[",
"hash",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"[",
"key",
",",
"binary_encode_any_high_ascii",
"(",
"value",
")",
"]",
"}",
"]",
"end"
] | Ensures all values of the given `hash` are BINARY-encoded, if necessary. | [
"Ensures",
"all",
"values",
"of",
"the",
"given",
"hash",
"are",
"BINARY",
"-",
"encoded",
"if",
"necessary",
"."
] | 6daf98ca972e79de1c8457eb720f058b03ead21c | https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/utf8_encoding/force_binary.rb#L35-L37 |
4,304 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.has_key? | def has_key?(key)
if :hash == self.type
self.children.any? { |pair_node| pair_node.key.to_value == key }
else
raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}"
end
end | ruby | def has_key?(key)
if :hash == self.type
self.children.any? { |pair_node| pair_node.key.to_value == key }
else
raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}"
end
end | [
"def",
"has_key?",
"(",
"key",
")",
"if",
":hash",
"==",
"self",
".",
"type",
"self",
".",
"children",
".",
"any?",
"{",
"|",
"pair_node",
"|",
"pair_node",
".",
"key",
".",
"to_value",
"==",
"key",
"}",
"else",
"raise",
"Synvert",
"::",
"Core",
"::",
"MethodNotSupported",
".",
"new",
"\"has_key? is not handled for #{self.debug_info}\"",
"end",
"end"
] | Test if hash node contains specified key.
@param [Object] key value.
@return [Boolean] true if specified key exists.
@raise [Synvert::Core::MethodNotSupported] if calls on other node. | [
"Test",
"if",
"hash",
"node",
"contains",
"specified",
"key",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L186-L192 |
4,305 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.hash_value | def hash_value(key)
if :hash == self.type
value_node = self.children.find { |pair_node| pair_node.key.to_value == key }
value_node ? value_node.value : nil
else
raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}"
end
end | ruby | def hash_value(key)
if :hash == self.type
value_node = self.children.find { |pair_node| pair_node.key.to_value == key }
value_node ? value_node.value : nil
else
raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}"
end
end | [
"def",
"hash_value",
"(",
"key",
")",
"if",
":hash",
"==",
"self",
".",
"type",
"value_node",
"=",
"self",
".",
"children",
".",
"find",
"{",
"|",
"pair_node",
"|",
"pair_node",
".",
"key",
".",
"to_value",
"==",
"key",
"}",
"value_node",
"?",
"value_node",
".",
"value",
":",
"nil",
"else",
"raise",
"Synvert",
"::",
"Core",
"::",
"MethodNotSupported",
".",
"new",
"\"has_key? is not handled for #{self.debug_info}\"",
"end",
"end"
] | Get hash value node according to specified key.
@param [Object] key value.
@return [Parser::AST::Node] value node.
@raise [Synvert::Core::MethodNotSupported] if calls on other node. | [
"Get",
"hash",
"value",
"node",
"according",
"to",
"specified",
"key",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L199-L206 |
4,306 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.to_value | def to_value
case self.type
when :int, :str, :sym
self.children.last
when :true
true
when :false
false
when :array
self.children.map(&:to_value)
when :irange
(self.children.first.to_value..self.children.last.to_value)
when :begin
self.children.first.to_value
else
raise Synvert::Core::MethodNotSupported.new "to_value is not handled for #{self.debug_info}"
end
end | ruby | def to_value
case self.type
when :int, :str, :sym
self.children.last
when :true
true
when :false
false
when :array
self.children.map(&:to_value)
when :irange
(self.children.first.to_value..self.children.last.to_value)
when :begin
self.children.first.to_value
else
raise Synvert::Core::MethodNotSupported.new "to_value is not handled for #{self.debug_info}"
end
end | [
"def",
"to_value",
"case",
"self",
".",
"type",
"when",
":int",
",",
":str",
",",
":sym",
"self",
".",
"children",
".",
"last",
"when",
":true",
"true",
"when",
":false",
"false",
"when",
":array",
"self",
".",
"children",
".",
"map",
"(",
":to_value",
")",
"when",
":irange",
"(",
"self",
".",
"children",
".",
"first",
".",
"to_value",
"..",
"self",
".",
"children",
".",
"last",
".",
"to_value",
")",
"when",
":begin",
"self",
".",
"children",
".",
"first",
".",
"to_value",
"else",
"raise",
"Synvert",
"::",
"Core",
"::",
"MethodNotSupported",
".",
"new",
"\"to_value is not handled for #{self.debug_info}\"",
"end",
"end"
] | Return the exact value.
@return [Object] exact value.
@raise [Synvert::Core::MethodNotSupported] if calls on other node. | [
"Return",
"the",
"exact",
"value",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L260-L277 |
4,307 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.recursive_children | def recursive_children
self.children.each do |child|
if Parser::AST::Node === child
yield child
child.recursive_children { |c| yield c }
end
end
end | ruby | def recursive_children
self.children.each do |child|
if Parser::AST::Node === child
yield child
child.recursive_children { |c| yield c }
end
end
end | [
"def",
"recursive_children",
"self",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"if",
"Parser",
"::",
"AST",
"::",
"Node",
"===",
"child",
"yield",
"child",
"child",
".",
"recursive_children",
"{",
"|",
"c",
"|",
"yield",
"c",
"}",
"end",
"end",
"end"
] | Recursively iterate all child nodes of current node.
@yield [child] Gives a child node.
@yieldparam child [Parser::AST::Node] child node | [
"Recursively",
"iterate",
"all",
"child",
"nodes",
"of",
"current",
"node",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L321-L328 |
4,308 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.match? | def match?(rules)
flat_hash(rules).keys.all? do |multi_keys|
if multi_keys.last == :any
actual_values = actual_value(self, multi_keys[0...-1])
expected = expected_value(rules, multi_keys)
actual_values.any? { |actual| match_value?(actual, expected) }
elsif multi_keys.last == :not
actual = actual_value(self, multi_keys[0...-1])
expected = expected_value(rules, multi_keys)
!match_value?(actual, expected)
else
actual = actual_value(self, multi_keys)
expected = expected_value(rules, multi_keys)
match_value?(actual, expected)
end
end
end | ruby | def match?(rules)
flat_hash(rules).keys.all? do |multi_keys|
if multi_keys.last == :any
actual_values = actual_value(self, multi_keys[0...-1])
expected = expected_value(rules, multi_keys)
actual_values.any? { |actual| match_value?(actual, expected) }
elsif multi_keys.last == :not
actual = actual_value(self, multi_keys[0...-1])
expected = expected_value(rules, multi_keys)
!match_value?(actual, expected)
else
actual = actual_value(self, multi_keys)
expected = expected_value(rules, multi_keys)
match_value?(actual, expected)
end
end
end | [
"def",
"match?",
"(",
"rules",
")",
"flat_hash",
"(",
"rules",
")",
".",
"keys",
".",
"all?",
"do",
"|",
"multi_keys",
"|",
"if",
"multi_keys",
".",
"last",
"==",
":any",
"actual_values",
"=",
"actual_value",
"(",
"self",
",",
"multi_keys",
"[",
"0",
"...",
"-",
"1",
"]",
")",
"expected",
"=",
"expected_value",
"(",
"rules",
",",
"multi_keys",
")",
"actual_values",
".",
"any?",
"{",
"|",
"actual",
"|",
"match_value?",
"(",
"actual",
",",
"expected",
")",
"}",
"elsif",
"multi_keys",
".",
"last",
"==",
":not",
"actual",
"=",
"actual_value",
"(",
"self",
",",
"multi_keys",
"[",
"0",
"...",
"-",
"1",
"]",
")",
"expected",
"=",
"expected_value",
"(",
"rules",
",",
"multi_keys",
")",
"!",
"match_value?",
"(",
"actual",
",",
"expected",
")",
"else",
"actual",
"=",
"actual_value",
"(",
"self",
",",
"multi_keys",
")",
"expected",
"=",
"expected_value",
"(",
"rules",
",",
"multi_keys",
")",
"match_value?",
"(",
"actual",
",",
"expected",
")",
"end",
"end",
"end"
] | Match current node with rules.
@param rules [Hash] rules to match.
@return true if matches. | [
"Match",
"current",
"node",
"with",
"rules",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L334-L350 |
4,309 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.match_value? | def match_value?(actual, expected)
case expected
when Symbol
if Parser::AST::Node === actual
actual.to_source == ":#{expected}"
else
actual.to_sym == expected
end
when String
if Parser::AST::Node === actual
actual.to_source == expected ||
(actual.to_source[0] == ':' && actual.to_source[1..-1] == expected) ||
actual.to_source[1...-1] == expected
else
actual.to_s == expected
end
when Regexp
if Parser::AST::Node === actual
actual.to_source =~ Regexp.new(expected.to_s, Regexp::MULTILINE)
else
actual.to_s =~ Regexp.new(expected.to_s, Regexp::MULTILINE)
end
when Array
return false unless expected.length == actual.length
actual.zip(expected).all? { |a, e| match_value?(a, e) }
when NilClass
actual.nil?
when Numeric
if Parser::AST::Node === actual
actual.children[0] == expected
else
actual == expected
end
when TrueClass
:true == actual.type
when FalseClass
:false == actual.type
when Parser::AST::Node
actual == expected
else
raise Synvert::Core::MethodNotSupported.new "#{expected.class} is not handled for match_value?"
end
end | ruby | def match_value?(actual, expected)
case expected
when Symbol
if Parser::AST::Node === actual
actual.to_source == ":#{expected}"
else
actual.to_sym == expected
end
when String
if Parser::AST::Node === actual
actual.to_source == expected ||
(actual.to_source[0] == ':' && actual.to_source[1..-1] == expected) ||
actual.to_source[1...-1] == expected
else
actual.to_s == expected
end
when Regexp
if Parser::AST::Node === actual
actual.to_source =~ Regexp.new(expected.to_s, Regexp::MULTILINE)
else
actual.to_s =~ Regexp.new(expected.to_s, Regexp::MULTILINE)
end
when Array
return false unless expected.length == actual.length
actual.zip(expected).all? { |a, e| match_value?(a, e) }
when NilClass
actual.nil?
when Numeric
if Parser::AST::Node === actual
actual.children[0] == expected
else
actual == expected
end
when TrueClass
:true == actual.type
when FalseClass
:false == actual.type
when Parser::AST::Node
actual == expected
else
raise Synvert::Core::MethodNotSupported.new "#{expected.class} is not handled for match_value?"
end
end | [
"def",
"match_value?",
"(",
"actual",
",",
"expected",
")",
"case",
"expected",
"when",
"Symbol",
"if",
"Parser",
"::",
"AST",
"::",
"Node",
"===",
"actual",
"actual",
".",
"to_source",
"==",
"\":#{expected}\"",
"else",
"actual",
".",
"to_sym",
"==",
"expected",
"end",
"when",
"String",
"if",
"Parser",
"::",
"AST",
"::",
"Node",
"===",
"actual",
"actual",
".",
"to_source",
"==",
"expected",
"||",
"(",
"actual",
".",
"to_source",
"[",
"0",
"]",
"==",
"':'",
"&&",
"actual",
".",
"to_source",
"[",
"1",
"..",
"-",
"1",
"]",
"==",
"expected",
")",
"||",
"actual",
".",
"to_source",
"[",
"1",
"...",
"-",
"1",
"]",
"==",
"expected",
"else",
"actual",
".",
"to_s",
"==",
"expected",
"end",
"when",
"Regexp",
"if",
"Parser",
"::",
"AST",
"::",
"Node",
"===",
"actual",
"actual",
".",
"to_source",
"=~",
"Regexp",
".",
"new",
"(",
"expected",
".",
"to_s",
",",
"Regexp",
"::",
"MULTILINE",
")",
"else",
"actual",
".",
"to_s",
"=~",
"Regexp",
".",
"new",
"(",
"expected",
".",
"to_s",
",",
"Regexp",
"::",
"MULTILINE",
")",
"end",
"when",
"Array",
"return",
"false",
"unless",
"expected",
".",
"length",
"==",
"actual",
".",
"length",
"actual",
".",
"zip",
"(",
"expected",
")",
".",
"all?",
"{",
"|",
"a",
",",
"e",
"|",
"match_value?",
"(",
"a",
",",
"e",
")",
"}",
"when",
"NilClass",
"actual",
".",
"nil?",
"when",
"Numeric",
"if",
"Parser",
"::",
"AST",
"::",
"Node",
"===",
"actual",
"actual",
".",
"children",
"[",
"0",
"]",
"==",
"expected",
"else",
"actual",
"==",
"expected",
"end",
"when",
"TrueClass",
":true",
"==",
"actual",
".",
"type",
"when",
"FalseClass",
":false",
"==",
"actual",
".",
"type",
"when",
"Parser",
"::",
"AST",
"::",
"Node",
"actual",
"==",
"expected",
"else",
"raise",
"Synvert",
"::",
"Core",
"::",
"MethodNotSupported",
".",
"new",
"\"#{expected.class} is not handled for match_value?\"",
"end",
"end"
] | Compare actual value with expected value.
@param actual [Object] actual value.
@param expected [Object] expected value.
@return [Integer] -1, 0 or 1.
@raise [Synvert::Core::MethodNotSupported] if expected class is not supported. | [
"Compare",
"actual",
"value",
"with",
"expected",
"value",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L404-L446 |
4,310 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.flat_hash | def flat_hash(h, k = [])
new_hash = {}
h.each_pair do |key, val|
if val.is_a?(Hash)
new_hash.merge!(flat_hash(val, k + [key]))
else
new_hash[k + [key]] = val
end
end
new_hash
end | ruby | def flat_hash(h, k = [])
new_hash = {}
h.each_pair do |key, val|
if val.is_a?(Hash)
new_hash.merge!(flat_hash(val, k + [key]))
else
new_hash[k + [key]] = val
end
end
new_hash
end | [
"def",
"flat_hash",
"(",
"h",
",",
"k",
"=",
"[",
"]",
")",
"new_hash",
"=",
"{",
"}",
"h",
".",
"each_pair",
"do",
"|",
"key",
",",
"val",
"|",
"if",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"new_hash",
".",
"merge!",
"(",
"flat_hash",
"(",
"val",
",",
"k",
"+",
"[",
"key",
"]",
")",
")",
"else",
"new_hash",
"[",
"k",
"+",
"[",
"key",
"]",
"]",
"=",
"val",
"end",
"end",
"new_hash",
"end"
] | Convert a hash to flat one.
@example
flat_hash(type: 'block', caller: {type: 'send', receiver: 'RSpec'})
#=> {[:type] => 'block', [:caller, :type] => 'send', [:caller, :receiver] => 'RSpec'}
@param h [Hash] original hash.
@return flatten hash. | [
"Convert",
"a",
"hash",
"to",
"flat",
"one",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L455-L465 |
4,311 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.actual_value | def actual_value(node, multi_keys)
multi_keys.inject(node) { |n, key|
if n
key == :source ? n.send(key) : n.send(key)
end
}
end | ruby | def actual_value(node, multi_keys)
multi_keys.inject(node) { |n, key|
if n
key == :source ? n.send(key) : n.send(key)
end
}
end | [
"def",
"actual_value",
"(",
"node",
",",
"multi_keys",
")",
"multi_keys",
".",
"inject",
"(",
"node",
")",
"{",
"|",
"n",
",",
"key",
"|",
"if",
"n",
"key",
"==",
":source",
"?",
"n",
".",
"send",
"(",
"key",
")",
":",
"n",
".",
"send",
"(",
"key",
")",
"end",
"}",
"end"
] | Get actual value from the node.
@param node [Parser::AST::Node]
@param multi_keys [Array<Symbol>]
@return [Object] actual value. | [
"Get",
"actual",
"value",
"from",
"the",
"node",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L472-L478 |
4,312 | xinminlabs/synvert-core | lib/synvert/core/node_ext.rb | Parser::AST.Node.expected_value | def expected_value(rules, multi_keys)
multi_keys.inject(rules) { |o, key| o[key] }
end | ruby | def expected_value(rules, multi_keys)
multi_keys.inject(rules) { |o, key| o[key] }
end | [
"def",
"expected_value",
"(",
"rules",
",",
"multi_keys",
")",
"multi_keys",
".",
"inject",
"(",
"rules",
")",
"{",
"|",
"o",
",",
"key",
"|",
"o",
"[",
"key",
"]",
"}",
"end"
] | Get expected value from rules.
@param rules [Hash]
@param multi_keys [Array<Symbol>]
@return [Object] expected value. | [
"Get",
"expected",
"value",
"from",
"rules",
"."
] | a490bfd30eaec81002d10f8fb61b49138708e46c | https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L485-L487 |
4,313 | scrapper/perobs | lib/perobs/BigArrayNode.rb | PEROBS.BigArrayNode.set | def set(index, value)
node = self
# Traverse the tree to find the right node to add or replace the value.
while node do
# Once we have reached a leaf node we can insert or replace the value.
if node.is_leaf?
if index >= node.values.size
node.fatal "Set index (#{index}) larger than values array " +
"(#{node.values.size})."
end
node.values[index] = value
return
else
# Descend into the right child node to add the value to.
cidx = node.search_child_index(index)
index -= node.offsets[cidx]
node = node.children[cidx]
end
end
node.fatal "Could not find proper node to set the value while " +
"looking for index #{index}"
end | ruby | def set(index, value)
node = self
# Traverse the tree to find the right node to add or replace the value.
while node do
# Once we have reached a leaf node we can insert or replace the value.
if node.is_leaf?
if index >= node.values.size
node.fatal "Set index (#{index}) larger than values array " +
"(#{node.values.size})."
end
node.values[index] = value
return
else
# Descend into the right child node to add the value to.
cidx = node.search_child_index(index)
index -= node.offsets[cidx]
node = node.children[cidx]
end
end
node.fatal "Could not find proper node to set the value while " +
"looking for index #{index}"
end | [
"def",
"set",
"(",
"index",
",",
"value",
")",
"node",
"=",
"self",
"# Traverse the tree to find the right node to add or replace the value.",
"while",
"node",
"do",
"# Once we have reached a leaf node we can insert or replace the value.",
"if",
"node",
".",
"is_leaf?",
"if",
"index",
">=",
"node",
".",
"values",
".",
"size",
"node",
".",
"fatal",
"\"Set index (#{index}) larger than values array \"",
"+",
"\"(#{node.values.size}).\"",
"end",
"node",
".",
"values",
"[",
"index",
"]",
"=",
"value",
"return",
"else",
"# Descend into the right child node to add the value to.",
"cidx",
"=",
"node",
".",
"search_child_index",
"(",
"index",
")",
"index",
"-=",
"node",
".",
"offsets",
"[",
"cidx",
"]",
"node",
"=",
"node",
".",
"children",
"[",
"cidx",
"]",
"end",
"end",
"node",
".",
"fatal",
"\"Could not find proper node to set the value while \"",
"+",
"\"looking for index #{index}\"",
"end"
] | Set the given value at the given index.
@param index [Integer] Position to insert at
@param value [Integer] value to insert | [
"Set",
"the",
"given",
"value",
"at",
"the",
"given",
"index",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L134-L157 |
4,314 | scrapper/perobs | lib/perobs/BigArrayNode.rb | PEROBS.BigArrayNode.insert | def insert(index, value)
node = self
cidx = nil
# Traverse the tree to find the right node to add or replace the value.
while node do
# All nodes that we find on the way that are full will be split into
# two half-full nodes.
if node.size >= @tree.node_size
# Re-add the index from the last parent node since we will descent
# into one of the split nodes.
index += node.parent.offsets[cidx] if node.parent
node = node.split_node
end
# Once we have reached a leaf node we can insert or replace the value.
if node.is_leaf?
node.values.insert(index, value)
node.parent.adjust_offsets(node, 1) if node.parent
return
else
# Descend into the right child node to add the value to.
cidx = node.search_child_index(index)
if (index -= node.offsets[cidx]) < 0
node.fatal "Index (#{index}) became negative"
end
node = node.children[cidx]
end
end
node.fatal "Could not find proper node to insert the value while " +
"looking for index #{index}"
end | ruby | def insert(index, value)
node = self
cidx = nil
# Traverse the tree to find the right node to add or replace the value.
while node do
# All nodes that we find on the way that are full will be split into
# two half-full nodes.
if node.size >= @tree.node_size
# Re-add the index from the last parent node since we will descent
# into one of the split nodes.
index += node.parent.offsets[cidx] if node.parent
node = node.split_node
end
# Once we have reached a leaf node we can insert or replace the value.
if node.is_leaf?
node.values.insert(index, value)
node.parent.adjust_offsets(node, 1) if node.parent
return
else
# Descend into the right child node to add the value to.
cidx = node.search_child_index(index)
if (index -= node.offsets[cidx]) < 0
node.fatal "Index (#{index}) became negative"
end
node = node.children[cidx]
end
end
node.fatal "Could not find proper node to insert the value while " +
"looking for index #{index}"
end | [
"def",
"insert",
"(",
"index",
",",
"value",
")",
"node",
"=",
"self",
"cidx",
"=",
"nil",
"# Traverse the tree to find the right node to add or replace the value.",
"while",
"node",
"do",
"# All nodes that we find on the way that are full will be split into",
"# two half-full nodes.",
"if",
"node",
".",
"size",
">=",
"@tree",
".",
"node_size",
"# Re-add the index from the last parent node since we will descent",
"# into one of the split nodes.",
"index",
"+=",
"node",
".",
"parent",
".",
"offsets",
"[",
"cidx",
"]",
"if",
"node",
".",
"parent",
"node",
"=",
"node",
".",
"split_node",
"end",
"# Once we have reached a leaf node we can insert or replace the value.",
"if",
"node",
".",
"is_leaf?",
"node",
".",
"values",
".",
"insert",
"(",
"index",
",",
"value",
")",
"node",
".",
"parent",
".",
"adjust_offsets",
"(",
"node",
",",
"1",
")",
"if",
"node",
".",
"parent",
"return",
"else",
"# Descend into the right child node to add the value to.",
"cidx",
"=",
"node",
".",
"search_child_index",
"(",
"index",
")",
"if",
"(",
"index",
"-=",
"node",
".",
"offsets",
"[",
"cidx",
"]",
")",
"<",
"0",
"node",
".",
"fatal",
"\"Index (#{index}) became negative\"",
"end",
"node",
"=",
"node",
".",
"children",
"[",
"cidx",
"]",
"end",
"end",
"node",
".",
"fatal",
"\"Could not find proper node to insert the value while \"",
"+",
"\"looking for index #{index}\"",
"end"
] | Insert the given value at the given index. All following values will be
pushed to a higher index.
@param index [Integer] Position to insert at
@param value [Integer] value to insert | [
"Insert",
"the",
"given",
"value",
"at",
"the",
"given",
"index",
".",
"All",
"following",
"values",
"will",
"be",
"pushed",
"to",
"a",
"higher",
"index",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L163-L195 |
4,315 | scrapper/perobs | lib/perobs/BigArrayNode.rb | PEROBS.BigArrayNode.value_index | def value_index(idx)
node = self
while node.parent
idx += node.parent.offsets[node.index_in_parent_node]
node = node.parent
end
idx
end | ruby | def value_index(idx)
node = self
while node.parent
idx += node.parent.offsets[node.index_in_parent_node]
node = node.parent
end
idx
end | [
"def",
"value_index",
"(",
"idx",
")",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
"idx",
"+=",
"node",
".",
"parent",
".",
"offsets",
"[",
"node",
".",
"index_in_parent_node",
"]",
"node",
"=",
"node",
".",
"parent",
"end",
"idx",
"end"
] | Compute the array index of the value with the given index in the current
node.
@param idx [Integer] Index of the value in the current node
@return [Integer] Array index of the value | [
"Compute",
"the",
"array",
"index",
"of",
"the",
"value",
"with",
"the",
"given",
"index",
"in",
"the",
"current",
"node",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L647-L655 |
4,316 | scrapper/perobs | lib/perobs/BigArrayNode.rb | PEROBS.BigArrayNode.move_first_element_of_successor_to_child | def move_first_element_of_successor_to_child(child_index)
child = @children[child_index]
succ = @children[child_index + 1]
if child.is_leaf?
# Adjust offset for the successor node
@offsets[child_index + 1] += 1
# Move the value
child.values << succ.values.shift
else
# Before:
#
# Root Node +--------------------------------+
# Offsets | 0 7 |
# Children | |
# child v succ v
# Level 1 +---------------++-------------------------------------+
# Offsets | 0 4 || 0 4 6 9 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# After:
#
# Root Node +--------------------------------+
# Offsets | 0 11 |
# Children | |
# child v succ v
# Level 1 +--------------------------++--------------------------+
# Offsets | 0 4 7 || 0 2 5 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# Adjust the offsets of the successor. The 2nd original offset
# determines the delta for the parent node.
succ.offsets.shift
delta = succ.offsets.first
succ.offsets.map! { |o| o -= delta }
# The additional child offset can be taken from the parent node
# reference.
child.offsets << @offsets[child_index + 1]
# The parent node offset of the successor needs to be corrected by the
# delta value.
@offsets[child_index + 1] += delta
# Move the child reference
child.children << succ.children.shift
child.children.last.parent = child
end
end | ruby | def move_first_element_of_successor_to_child(child_index)
child = @children[child_index]
succ = @children[child_index + 1]
if child.is_leaf?
# Adjust offset for the successor node
@offsets[child_index + 1] += 1
# Move the value
child.values << succ.values.shift
else
# Before:
#
# Root Node +--------------------------------+
# Offsets | 0 7 |
# Children | |
# child v succ v
# Level 1 +---------------++-------------------------------------+
# Offsets | 0 4 || 0 4 6 9 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# After:
#
# Root Node +--------------------------------+
# Offsets | 0 11 |
# Children | |
# child v succ v
# Level 1 +--------------------------++--------------------------+
# Offsets | 0 4 7 || 0 2 5 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# Adjust the offsets of the successor. The 2nd original offset
# determines the delta for the parent node.
succ.offsets.shift
delta = succ.offsets.first
succ.offsets.map! { |o| o -= delta }
# The additional child offset can be taken from the parent node
# reference.
child.offsets << @offsets[child_index + 1]
# The parent node offset of the successor needs to be corrected by the
# delta value.
@offsets[child_index + 1] += delta
# Move the child reference
child.children << succ.children.shift
child.children.last.parent = child
end
end | [
"def",
"move_first_element_of_successor_to_child",
"(",
"child_index",
")",
"child",
"=",
"@children",
"[",
"child_index",
"]",
"succ",
"=",
"@children",
"[",
"child_index",
"+",
"1",
"]",
"if",
"child",
".",
"is_leaf?",
"# Adjust offset for the successor node",
"@offsets",
"[",
"child_index",
"+",
"1",
"]",
"+=",
"1",
"# Move the value",
"child",
".",
"values",
"<<",
"succ",
".",
"values",
".",
"shift",
"else",
"# Before:",
"#",
"# Root Node +--------------------------------+",
"# Offsets | 0 7 |",
"# Children | |",
"# child v succ v",
"# Level 1 +---------------++-------------------------------------+",
"# Offsets | 0 4 || 0 4 6 9 |",
"# Children | | | | | |",
"# v v v v v v",
"# Leaves +---------++-------++----------++-------++----------++-------+",
"# Values | A B C D || E F G || H I J K || L M || N O P || Q R |",
"#",
"# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17",
"#",
"# After:",
"#",
"# Root Node +--------------------------------+",
"# Offsets | 0 11 |",
"# Children | |",
"# child v succ v",
"# Level 1 +--------------------------++--------------------------+",
"# Offsets | 0 4 7 || 0 2 5 |",
"# Children | | | | | |",
"# v v v v v v",
"# Leaves +---------++-------++----------++-------++----------++-------+",
"# Values | A B C D || E F G || H I J K || L M || N O P || Q R |",
"#",
"# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17",
"#",
"# Adjust the offsets of the successor. The 2nd original offset",
"# determines the delta for the parent node.",
"succ",
".",
"offsets",
".",
"shift",
"delta",
"=",
"succ",
".",
"offsets",
".",
"first",
"succ",
".",
"offsets",
".",
"map!",
"{",
"|",
"o",
"|",
"o",
"-=",
"delta",
"}",
"# The additional child offset can be taken from the parent node",
"# reference.",
"child",
".",
"offsets",
"<<",
"@offsets",
"[",
"child_index",
"+",
"1",
"]",
"# The parent node offset of the successor needs to be corrected by the",
"# delta value.",
"@offsets",
"[",
"child_index",
"+",
"1",
"]",
"+=",
"delta",
"# Move the child reference",
"child",
".",
"children",
"<<",
"succ",
".",
"children",
".",
"shift",
"child",
".",
"children",
".",
"last",
".",
"parent",
"=",
"child",
"end",
"end"
] | Move first element of successor to end of child node
@param child_index [Integer] index of the child | [
"Move",
"first",
"element",
"of",
"successor",
"to",
"end",
"of",
"child",
"node"
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L824-L879 |
4,317 | scrapper/perobs | lib/perobs/BigArrayNode.rb | PEROBS.BigArrayNode.move_last_element_of_predecessor_to_child | def move_last_element_of_predecessor_to_child(child_index)
pred = @children[child_index - 1]
child = @children[child_index]
if child.is_leaf?
# Adjust offset for the predecessor node
@offsets[child_index] -= 1
# Move the value
child.values.unshift(pred.values.pop)
else
# Before:
#
# Root Node +--------------------------------+
# Offsets | 0 13 |
# Children | |
# pred v child v
# Level 1 +---------------------------------++-------------------+
# Offsets | 0 4 7 11 || 0 3 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# After:
#
# Root Node +--------------------------------+
# Offsets | 0 11 |
# Children | |
# prepd v child v
# Level 1 +--------------------------++--------------------------+
# Offsets | 0 4 7 || 0 2 5 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# Remove the last predecessor offset and update the child offset with
# it
delta = @offsets[child_index] - pred.offsets.last
@offsets[child_index] = pred.offsets.pop
# Adjust all the offsets of the child
child.offsets.map! { |o| o += delta }
# And prepend the 0 offset
child.offsets.unshift(0)
# Move the child reference
child.children.unshift(pred.children.pop)
child.children.first.parent = child
end
end | ruby | def move_last_element_of_predecessor_to_child(child_index)
pred = @children[child_index - 1]
child = @children[child_index]
if child.is_leaf?
# Adjust offset for the predecessor node
@offsets[child_index] -= 1
# Move the value
child.values.unshift(pred.values.pop)
else
# Before:
#
# Root Node +--------------------------------+
# Offsets | 0 13 |
# Children | |
# pred v child v
# Level 1 +---------------------------------++-------------------+
# Offsets | 0 4 7 11 || 0 3 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# After:
#
# Root Node +--------------------------------+
# Offsets | 0 11 |
# Children | |
# prepd v child v
# Level 1 +--------------------------++--------------------------+
# Offsets | 0 4 7 || 0 2 5 |
# Children | | | | | |
# v v v v v v
# Leaves +---------++-------++----------++-------++----------++-------+
# Values | A B C D || E F G || H I J K || L M || N O P || Q R |
#
# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# Remove the last predecessor offset and update the child offset with
# it
delta = @offsets[child_index] - pred.offsets.last
@offsets[child_index] = pred.offsets.pop
# Adjust all the offsets of the child
child.offsets.map! { |o| o += delta }
# And prepend the 0 offset
child.offsets.unshift(0)
# Move the child reference
child.children.unshift(pred.children.pop)
child.children.first.parent = child
end
end | [
"def",
"move_last_element_of_predecessor_to_child",
"(",
"child_index",
")",
"pred",
"=",
"@children",
"[",
"child_index",
"-",
"1",
"]",
"child",
"=",
"@children",
"[",
"child_index",
"]",
"if",
"child",
".",
"is_leaf?",
"# Adjust offset for the predecessor node",
"@offsets",
"[",
"child_index",
"]",
"-=",
"1",
"# Move the value",
"child",
".",
"values",
".",
"unshift",
"(",
"pred",
".",
"values",
".",
"pop",
")",
"else",
"# Before:",
"#",
"# Root Node +--------------------------------+",
"# Offsets | 0 13 |",
"# Children | |",
"# pred v child v",
"# Level 1 +---------------------------------++-------------------+",
"# Offsets | 0 4 7 11 || 0 3 |",
"# Children | | | | | |",
"# v v v v v v",
"# Leaves +---------++-------++----------++-------++----------++-------+",
"# Values | A B C D || E F G || H I J K || L M || N O P || Q R |",
"#",
"# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17",
"#",
"# After:",
"#",
"# Root Node +--------------------------------+",
"# Offsets | 0 11 |",
"# Children | |",
"# prepd v child v",
"# Level 1 +--------------------------++--------------------------+",
"# Offsets | 0 4 7 || 0 2 5 |",
"# Children | | | | | |",
"# v v v v v v",
"# Leaves +---------++-------++----------++-------++----------++-------+",
"# Values | A B C D || E F G || H I J K || L M || N O P || Q R |",
"#",
"# Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17",
"#",
"# Remove the last predecessor offset and update the child offset with",
"# it",
"delta",
"=",
"@offsets",
"[",
"child_index",
"]",
"-",
"pred",
".",
"offsets",
".",
"last",
"@offsets",
"[",
"child_index",
"]",
"=",
"pred",
".",
"offsets",
".",
"pop",
"# Adjust all the offsets of the child",
"child",
".",
"offsets",
".",
"map!",
"{",
"|",
"o",
"|",
"o",
"+=",
"delta",
"}",
"# And prepend the 0 offset",
"child",
".",
"offsets",
".",
"unshift",
"(",
"0",
")",
"# Move the child reference",
"child",
".",
"children",
".",
"unshift",
"(",
"pred",
".",
"children",
".",
"pop",
")",
"child",
".",
"children",
".",
"first",
".",
"parent",
"=",
"child",
"end",
"end"
] | Move last element of predecessor node to child
@param child_index [Integer] index of the child | [
"Move",
"last",
"element",
"of",
"predecessor",
"node",
"to",
"child"
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L883-L935 |
4,318 | scrapper/perobs | lib/perobs/BigHash.rb | PEROBS.BigHash.[]= | def []=(key, value)
hashed_key = hash_key(key)
@store.transaction do
entry = @store.new(Entry, key, value)
if (existing_entry = @btree.get(hashed_key))
# There is already an existing entry for this hashed key.
if existing_entry.is_a?(Collisions)
# Find the right index to insert the new entry. If there is
# already an entry with the same key overwrite that entry.
index_to_insert = 0
overwrite = false
existing_entry.each do |ae|
if ae.key == key
overwrite = true
break
end
index_to_insert += 1
end
self.entry_counter += 1 unless overwrite
existing_entry[index_to_insert] = entry
elsif existing_entry.key == key
# The existing value is for the identical key. We can safely
# overwrite
@btree.insert(hashed_key, entry)
else
# There is a single existing entry, but for a different key. Create
# a new PEROBS::Array and store both entries.
array_entry = @store.new(Collisions)
array_entry << existing_entry
array_entry << entry
@btree.insert(hashed_key, array_entry)
self.entry_counter += 1
end
else
# No existing entry. Insert the new entry.
@btree.insert(hashed_key, entry)
self.entry_counter += 1
end
end
end | ruby | def []=(key, value)
hashed_key = hash_key(key)
@store.transaction do
entry = @store.new(Entry, key, value)
if (existing_entry = @btree.get(hashed_key))
# There is already an existing entry for this hashed key.
if existing_entry.is_a?(Collisions)
# Find the right index to insert the new entry. If there is
# already an entry with the same key overwrite that entry.
index_to_insert = 0
overwrite = false
existing_entry.each do |ae|
if ae.key == key
overwrite = true
break
end
index_to_insert += 1
end
self.entry_counter += 1 unless overwrite
existing_entry[index_to_insert] = entry
elsif existing_entry.key == key
# The existing value is for the identical key. We can safely
# overwrite
@btree.insert(hashed_key, entry)
else
# There is a single existing entry, but for a different key. Create
# a new PEROBS::Array and store both entries.
array_entry = @store.new(Collisions)
array_entry << existing_entry
array_entry << entry
@btree.insert(hashed_key, array_entry)
self.entry_counter += 1
end
else
# No existing entry. Insert the new entry.
@btree.insert(hashed_key, entry)
self.entry_counter += 1
end
end
end | [
"def",
"[]=",
"(",
"key",
",",
"value",
")",
"hashed_key",
"=",
"hash_key",
"(",
"key",
")",
"@store",
".",
"transaction",
"do",
"entry",
"=",
"@store",
".",
"new",
"(",
"Entry",
",",
"key",
",",
"value",
")",
"if",
"(",
"existing_entry",
"=",
"@btree",
".",
"get",
"(",
"hashed_key",
")",
")",
"# There is already an existing entry for this hashed key.",
"if",
"existing_entry",
".",
"is_a?",
"(",
"Collisions",
")",
"# Find the right index to insert the new entry. If there is",
"# already an entry with the same key overwrite that entry.",
"index_to_insert",
"=",
"0",
"overwrite",
"=",
"false",
"existing_entry",
".",
"each",
"do",
"|",
"ae",
"|",
"if",
"ae",
".",
"key",
"==",
"key",
"overwrite",
"=",
"true",
"break",
"end",
"index_to_insert",
"+=",
"1",
"end",
"self",
".",
"entry_counter",
"+=",
"1",
"unless",
"overwrite",
"existing_entry",
"[",
"index_to_insert",
"]",
"=",
"entry",
"elsif",
"existing_entry",
".",
"key",
"==",
"key",
"# The existing value is for the identical key. We can safely",
"# overwrite",
"@btree",
".",
"insert",
"(",
"hashed_key",
",",
"entry",
")",
"else",
"# There is a single existing entry, but for a different key. Create",
"# a new PEROBS::Array and store both entries.",
"array_entry",
"=",
"@store",
".",
"new",
"(",
"Collisions",
")",
"array_entry",
"<<",
"existing_entry",
"array_entry",
"<<",
"entry",
"@btree",
".",
"insert",
"(",
"hashed_key",
",",
"array_entry",
")",
"self",
".",
"entry_counter",
"+=",
"1",
"end",
"else",
"# No existing entry. Insert the new entry.",
"@btree",
".",
"insert",
"(",
"hashed_key",
",",
"entry",
")",
"self",
".",
"entry_counter",
"+=",
"1",
"end",
"end",
"end"
] | Insert a value that is associated with the given key. If a value for
this key already exists, the value will be overwritten with the newly
provided value.
@param key [Integer or String]
@param value [Any PEROBS storable object] | [
"Insert",
"a",
"value",
"that",
"is",
"associated",
"with",
"the",
"given",
"key",
".",
"If",
"a",
"value",
"for",
"this",
"key",
"already",
"exists",
"the",
"value",
"will",
"be",
"overwritten",
"with",
"the",
"newly",
"provided",
"value",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L90-L130 |
4,319 | scrapper/perobs | lib/perobs/BigHash.rb | PEROBS.BigHash.[] | def [](key)
hashed_key = hash_key(key)
unless (entry = @btree.get(hashed_key))
return nil
end
if entry.is_a?(PEROBS::Array)
entry.each do |ae|
return ae.value if ae.key == key
end
else
return entry.value if entry.key == key
end
nil
end | ruby | def [](key)
hashed_key = hash_key(key)
unless (entry = @btree.get(hashed_key))
return nil
end
if entry.is_a?(PEROBS::Array)
entry.each do |ae|
return ae.value if ae.key == key
end
else
return entry.value if entry.key == key
end
nil
end | [
"def",
"[]",
"(",
"key",
")",
"hashed_key",
"=",
"hash_key",
"(",
"key",
")",
"unless",
"(",
"entry",
"=",
"@btree",
".",
"get",
"(",
"hashed_key",
")",
")",
"return",
"nil",
"end",
"if",
"entry",
".",
"is_a?",
"(",
"PEROBS",
"::",
"Array",
")",
"entry",
".",
"each",
"do",
"|",
"ae",
"|",
"return",
"ae",
".",
"value",
"if",
"ae",
".",
"key",
"==",
"key",
"end",
"else",
"return",
"entry",
".",
"value",
"if",
"entry",
".",
"key",
"==",
"key",
"end",
"nil",
"end"
] | Retrieve the value for the given key. If no value for the key is found
nil is returned.
@param key [Integer or String]
@return [Any PEROBS storable object] | [
"Retrieve",
"the",
"value",
"for",
"the",
"given",
"key",
".",
"If",
"no",
"value",
"for",
"the",
"key",
"is",
"found",
"nil",
"is",
"returned",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L136-L151 |
4,320 | scrapper/perobs | lib/perobs/BigHash.rb | PEROBS.BigHash.has_key? | def has_key?(key)
hashed_key = hash_key(key)
unless (entry = @btree.get(hashed_key))
return false
end
if entry.is_a?(PEROBS::Array)
entry.each do |ae|
return true if ae.key == key
end
else
return true if entry.key == key
end
false
end | ruby | def has_key?(key)
hashed_key = hash_key(key)
unless (entry = @btree.get(hashed_key))
return false
end
if entry.is_a?(PEROBS::Array)
entry.each do |ae|
return true if ae.key == key
end
else
return true if entry.key == key
end
false
end | [
"def",
"has_key?",
"(",
"key",
")",
"hashed_key",
"=",
"hash_key",
"(",
"key",
")",
"unless",
"(",
"entry",
"=",
"@btree",
".",
"get",
"(",
"hashed_key",
")",
")",
"return",
"false",
"end",
"if",
"entry",
".",
"is_a?",
"(",
"PEROBS",
"::",
"Array",
")",
"entry",
".",
"each",
"do",
"|",
"ae",
"|",
"return",
"true",
"if",
"ae",
".",
"key",
"==",
"key",
"end",
"else",
"return",
"true",
"if",
"entry",
".",
"key",
"==",
"key",
"end",
"false",
"end"
] | Check if the is a value stored for the given key.
@param key [Integer or String]
@return [TrueClass or FalseClass] | [
"Check",
"if",
"the",
"is",
"a",
"value",
"stored",
"for",
"the",
"given",
"key",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L156-L171 |
4,321 | scrapper/perobs | lib/perobs/BigHash.rb | PEROBS.BigHash.delete | def delete(key)
hashed_key = hash_key(key)
unless (entry = @btree.get(hashed_key))
return nil
end
if entry.is_a?(PEROBS::Array)
entry.each_with_index do |ae, i|
if ae.key == key
self.entry_counter -= 1
return entry.delete_at(i).value
end
end
else
return entry.value if entry.key == key
end
nil
end | ruby | def delete(key)
hashed_key = hash_key(key)
unless (entry = @btree.get(hashed_key))
return nil
end
if entry.is_a?(PEROBS::Array)
entry.each_with_index do |ae, i|
if ae.key == key
self.entry_counter -= 1
return entry.delete_at(i).value
end
end
else
return entry.value if entry.key == key
end
nil
end | [
"def",
"delete",
"(",
"key",
")",
"hashed_key",
"=",
"hash_key",
"(",
"key",
")",
"unless",
"(",
"entry",
"=",
"@btree",
".",
"get",
"(",
"hashed_key",
")",
")",
"return",
"nil",
"end",
"if",
"entry",
".",
"is_a?",
"(",
"PEROBS",
"::",
"Array",
")",
"entry",
".",
"each_with_index",
"do",
"|",
"ae",
",",
"i",
"|",
"if",
"ae",
".",
"key",
"==",
"key",
"self",
".",
"entry_counter",
"-=",
"1",
"return",
"entry",
".",
"delete_at",
"(",
"i",
")",
".",
"value",
"end",
"end",
"else",
"return",
"entry",
".",
"value",
"if",
"entry",
".",
"key",
"==",
"key",
"end",
"nil",
"end"
] | Delete and return the entry for the given key. Return nil if no matching
entry exists.
@param key [Integer or String]
@return [Object] Deleted entry | [
"Delete",
"and",
"return",
"the",
"entry",
"for",
"the",
"given",
"key",
".",
"Return",
"nil",
"if",
"no",
"matching",
"entry",
"exists",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L177-L195 |
4,322 | scrapper/perobs | lib/perobs/BigHash.rb | PEROBS.BigHash.check | def check
return false unless @btree.check
i = 0
each do |k, v|
i += 1
end
unless @entry_counter == i
PEROBS.log.error "BigHash contains #{i} values but entry counter " +
"is #{@entry_counter}"
return false
end
true
end | ruby | def check
return false unless @btree.check
i = 0
each do |k, v|
i += 1
end
unless @entry_counter == i
PEROBS.log.error "BigHash contains #{i} values but entry counter " +
"is #{@entry_counter}"
return false
end
true
end | [
"def",
"check",
"return",
"false",
"unless",
"@btree",
".",
"check",
"i",
"=",
"0",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"i",
"+=",
"1",
"end",
"unless",
"@entry_counter",
"==",
"i",
"PEROBS",
".",
"log",
".",
"error",
"\"BigHash contains #{i} values but entry counter \"",
"+",
"\"is #{@entry_counter}\"",
"return",
"false",
"end",
"true",
"end"
] | Check if the data structure contains any errors.
@return [Boolean] true if no erros were found, false otherwise | [
"Check",
"if",
"the",
"data",
"structure",
"contains",
"any",
"errors",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L236-L251 |
4,323 | regru/reg_api2-ruby | lib/reg_api2/sym_hash.rb | RegApi2.SymHash.method_missing | def method_missing(key, *args, &block)
if key.to_s =~ /\A(.+)=\z/
self[$1] = args.first
return args.first
end
if key.to_s =~ /\A(.+)\?\z/
return !!self[$1]
end
return self[key] if has_key?(key)
nil
end | ruby | def method_missing(key, *args, &block)
if key.to_s =~ /\A(.+)=\z/
self[$1] = args.first
return args.first
end
if key.to_s =~ /\A(.+)\?\z/
return !!self[$1]
end
return self[key] if has_key?(key)
nil
end | [
"def",
"method_missing",
"(",
"key",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"key",
".",
"to_s",
"=~",
"/",
"\\A",
"\\z",
"/",
"self",
"[",
"$1",
"]",
"=",
"args",
".",
"first",
"return",
"args",
".",
"first",
"end",
"if",
"key",
".",
"to_s",
"=~",
"/",
"\\A",
"\\?",
"\\z",
"/",
"return",
"!",
"!",
"self",
"[",
"$1",
"]",
"end",
"return",
"self",
"[",
"key",
"]",
"if",
"has_key?",
"(",
"key",
")",
"nil",
"end"
] | Sets or gets field in the hash. | [
"Sets",
"or",
"gets",
"field",
"in",
"the",
"hash",
"."
] | 82fadffc9da6534761003b8a33edb77ab617df70 | https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/sym_hash.rb#L52-L62 |
4,324 | scrapper/perobs | lib/perobs/SpaceTree.rb | PEROBS.SpaceTree.open | def open
@nodes.open
@cache.clear
node = @nodes.total_entries == 0 ?
SpaceTreeNode::create(self) :
SpaceTreeNode::load(self, @nodes.first_entry)
@root_address = node.node_address
end | ruby | def open
@nodes.open
@cache.clear
node = @nodes.total_entries == 0 ?
SpaceTreeNode::create(self) :
SpaceTreeNode::load(self, @nodes.first_entry)
@root_address = node.node_address
end | [
"def",
"open",
"@nodes",
".",
"open",
"@cache",
".",
"clear",
"node",
"=",
"@nodes",
".",
"total_entries",
"==",
"0",
"?",
"SpaceTreeNode",
"::",
"create",
"(",
"self",
")",
":",
"SpaceTreeNode",
"::",
"load",
"(",
"self",
",",
"@nodes",
".",
"first_entry",
")",
"@root_address",
"=",
"node",
".",
"node_address",
"end"
] | Manage the free spaces tree in the specified directory
@param dir [String] directory path of an existing directory
Open the SpaceTree file. | [
"Manage",
"the",
"free",
"spaces",
"tree",
"in",
"the",
"specified",
"directory"
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L61-L68 |
4,325 | scrapper/perobs | lib/perobs/SpaceTree.rb | PEROBS.SpaceTree.add_space | def add_space(address, size)
if size <= 0
PEROBS.log.fatal "Size (#{size}) must be larger than 0."
end
# The following check is fairly costly and should never trigger unless
# there is a bug in the PEROBS code. Only use this for debugging.
#if has_space?(address, size)
# PEROBS.log.fatal "The space with address #{address} and size " +
# "#{size} can't be added twice."
#end
root.add_space(address, size)
end | ruby | def add_space(address, size)
if size <= 0
PEROBS.log.fatal "Size (#{size}) must be larger than 0."
end
# The following check is fairly costly and should never trigger unless
# there is a bug in the PEROBS code. Only use this for debugging.
#if has_space?(address, size)
# PEROBS.log.fatal "The space with address #{address} and size " +
# "#{size} can't be added twice."
#end
root.add_space(address, size)
end | [
"def",
"add_space",
"(",
"address",
",",
"size",
")",
"if",
"size",
"<=",
"0",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Size (#{size}) must be larger than 0.\"",
"end",
"# The following check is fairly costly and should never trigger unless",
"# there is a bug in the PEROBS code. Only use this for debugging.",
"#if has_space?(address, size)",
"# PEROBS.log.fatal \"The space with address #{address} and size \" +",
"# \"#{size} can't be added twice.\"",
"#end",
"root",
".",
"add_space",
"(",
"address",
",",
"size",
")",
"end"
] | Add a new space with a given address and size.
@param address [Integer] Starting address of the space
@param size [Integer] size of the space in bytes | [
"Add",
"a",
"new",
"space",
"with",
"a",
"given",
"address",
"and",
"size",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L110-L121 |
4,326 | scrapper/perobs | lib/perobs/SpaceTree.rb | PEROBS.SpaceTree.get_space | def get_space(size)
if size <= 0
PEROBS.log.fatal "Size (#{size}) must be larger than 0."
end
if (address_size = root.find_matching_space(size))
# First we try to find an exact match.
return address_size
elsif (address_size = root.find_equal_or_larger_space(size))
return address_size
else
return nil
end
end | ruby | def get_space(size)
if size <= 0
PEROBS.log.fatal "Size (#{size}) must be larger than 0."
end
if (address_size = root.find_matching_space(size))
# First we try to find an exact match.
return address_size
elsif (address_size = root.find_equal_or_larger_space(size))
return address_size
else
return nil
end
end | [
"def",
"get_space",
"(",
"size",
")",
"if",
"size",
"<=",
"0",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Size (#{size}) must be larger than 0.\"",
"end",
"if",
"(",
"address_size",
"=",
"root",
".",
"find_matching_space",
"(",
"size",
")",
")",
"# First we try to find an exact match.",
"return",
"address_size",
"elsif",
"(",
"address_size",
"=",
"root",
".",
"find_equal_or_larger_space",
"(",
"size",
")",
")",
"return",
"address_size",
"else",
"return",
"nil",
"end",
"end"
] | Get a space that has at least the requested size.
@param size [Integer] Required size in bytes
@return [Array] Touple with address and actual size of the space. | [
"Get",
"a",
"space",
"that",
"has",
"at",
"least",
"the",
"requested",
"size",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L126-L139 |
4,327 | scrapper/perobs | lib/perobs/SpaceTree.rb | PEROBS.SpaceTree.each | def each
root.each do |node, mode, stack|
if mode == :on_enter
yield(node.blob_address, node.size)
end
end
end | ruby | def each
root.each do |node, mode, stack|
if mode == :on_enter
yield(node.blob_address, node.size)
end
end
end | [
"def",
"each",
"root",
".",
"each",
"do",
"|",
"node",
",",
"mode",
",",
"stack",
"|",
"if",
"mode",
"==",
":on_enter",
"yield",
"(",
"node",
".",
"blob_address",
",",
"node",
".",
"size",
")",
"end",
"end",
"end"
] | Iterate over all entries and yield address and size. | [
"Iterate",
"over",
"all",
"entries",
"and",
"yield",
"address",
"and",
"size",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L174-L180 |
4,328 | Absolight/epp-client | lib/epp-client/afnic.rb | EPPClient.AFNIC.legalEntityInfos | def legalEntityInfos(leI) #:nodoc:
ret = {}
ret[:legalStatus] = leI.xpath('frnic:legalStatus', EPPClient::SCHEMAS_URL).attr('s').value
unless (r = leI.xpath('frnic:idStatus', EPPClient::SCHEMAS_URL)).empty?
ret[:idStatus] = { :value => r.text }
ret[:idStatus][:when] = r.attr('when').value if r.attr('when')
ret[:idStatus][:source] = r.attr('source').value if r.attr('source')
end
%w(siren VAT trademark DUNS local).each do |val|
unless (r = leI.xpath("frnic:#{val}", EPPClient::SCHEMAS_URL)).empty?
ret[val.to_sym] = r.text
end
end
unless (asso = leI.xpath('frnic:asso', EPPClient::SCHEMAS_URL)).empty?
ret[:asso] = {}
if !(r = asso.xpath('frnic:waldec', EPPClient::SCHEMAS_URL)).empty?
ret[:asso][:waldec] = r.text
else
unless (decl = asso.xpath('frnic:decl', EPPClient::SCHEMAS_URL)).empty?
ret[:asso][:decl] = Date.parse(decl.text)
end
publ = asso.xpath('frnic:publ', EPPClient::SCHEMAS_URL)
ret[:asso][:publ] = {
:date => Date.parse(publ.text),
:page => publ.attr('page').value,
}
if (announce = publ.attr('announce')) && announce.value != '0'
ret[:asso][:publ][:announce] = announce.value
end
end
end
ret
end | ruby | def legalEntityInfos(leI) #:nodoc:
ret = {}
ret[:legalStatus] = leI.xpath('frnic:legalStatus', EPPClient::SCHEMAS_URL).attr('s').value
unless (r = leI.xpath('frnic:idStatus', EPPClient::SCHEMAS_URL)).empty?
ret[:idStatus] = { :value => r.text }
ret[:idStatus][:when] = r.attr('when').value if r.attr('when')
ret[:idStatus][:source] = r.attr('source').value if r.attr('source')
end
%w(siren VAT trademark DUNS local).each do |val|
unless (r = leI.xpath("frnic:#{val}", EPPClient::SCHEMAS_URL)).empty?
ret[val.to_sym] = r.text
end
end
unless (asso = leI.xpath('frnic:asso', EPPClient::SCHEMAS_URL)).empty?
ret[:asso] = {}
if !(r = asso.xpath('frnic:waldec', EPPClient::SCHEMAS_URL)).empty?
ret[:asso][:waldec] = r.text
else
unless (decl = asso.xpath('frnic:decl', EPPClient::SCHEMAS_URL)).empty?
ret[:asso][:decl] = Date.parse(decl.text)
end
publ = asso.xpath('frnic:publ', EPPClient::SCHEMAS_URL)
ret[:asso][:publ] = {
:date => Date.parse(publ.text),
:page => publ.attr('page').value,
}
if (announce = publ.attr('announce')) && announce.value != '0'
ret[:asso][:publ][:announce] = announce.value
end
end
end
ret
end | [
"def",
"legalEntityInfos",
"(",
"leI",
")",
"#:nodoc:",
"ret",
"=",
"{",
"}",
"ret",
"[",
":legalStatus",
"]",
"=",
"leI",
".",
"xpath",
"(",
"'frnic:legalStatus'",
",",
"EPPClient",
"::",
"SCHEMAS_URL",
")",
".",
"attr",
"(",
"'s'",
")",
".",
"value",
"unless",
"(",
"r",
"=",
"leI",
".",
"xpath",
"(",
"'frnic:idStatus'",
",",
"EPPClient",
"::",
"SCHEMAS_URL",
")",
")",
".",
"empty?",
"ret",
"[",
":idStatus",
"]",
"=",
"{",
":value",
"=>",
"r",
".",
"text",
"}",
"ret",
"[",
":idStatus",
"]",
"[",
":when",
"]",
"=",
"r",
".",
"attr",
"(",
"'when'",
")",
".",
"value",
"if",
"r",
".",
"attr",
"(",
"'when'",
")",
"ret",
"[",
":idStatus",
"]",
"[",
":source",
"]",
"=",
"r",
".",
"attr",
"(",
"'source'",
")",
".",
"value",
"if",
"r",
".",
"attr",
"(",
"'source'",
")",
"end",
"%w(",
"siren",
"VAT",
"trademark",
"DUNS",
"local",
")",
".",
"each",
"do",
"|",
"val",
"|",
"unless",
"(",
"r",
"=",
"leI",
".",
"xpath",
"(",
"\"frnic:#{val}\"",
",",
"EPPClient",
"::",
"SCHEMAS_URL",
")",
")",
".",
"empty?",
"ret",
"[",
"val",
".",
"to_sym",
"]",
"=",
"r",
".",
"text",
"end",
"end",
"unless",
"(",
"asso",
"=",
"leI",
".",
"xpath",
"(",
"'frnic:asso'",
",",
"EPPClient",
"::",
"SCHEMAS_URL",
")",
")",
".",
"empty?",
"ret",
"[",
":asso",
"]",
"=",
"{",
"}",
"if",
"!",
"(",
"r",
"=",
"asso",
".",
"xpath",
"(",
"'frnic:waldec'",
",",
"EPPClient",
"::",
"SCHEMAS_URL",
")",
")",
".",
"empty?",
"ret",
"[",
":asso",
"]",
"[",
":waldec",
"]",
"=",
"r",
".",
"text",
"else",
"unless",
"(",
"decl",
"=",
"asso",
".",
"xpath",
"(",
"'frnic:decl'",
",",
"EPPClient",
"::",
"SCHEMAS_URL",
")",
")",
".",
"empty?",
"ret",
"[",
":asso",
"]",
"[",
":decl",
"]",
"=",
"Date",
".",
"parse",
"(",
"decl",
".",
"text",
")",
"end",
"publ",
"=",
"asso",
".",
"xpath",
"(",
"'frnic:publ'",
",",
"EPPClient",
"::",
"SCHEMAS_URL",
")",
"ret",
"[",
":asso",
"]",
"[",
":publ",
"]",
"=",
"{",
":date",
"=>",
"Date",
".",
"parse",
"(",
"publ",
".",
"text",
")",
",",
":page",
"=>",
"publ",
".",
"attr",
"(",
"'page'",
")",
".",
"value",
",",
"}",
"if",
"(",
"announce",
"=",
"publ",
".",
"attr",
"(",
"'announce'",
")",
")",
"&&",
"announce",
".",
"value",
"!=",
"'0'",
"ret",
"[",
":asso",
"]",
"[",
":publ",
"]",
"[",
":announce",
"]",
"=",
"announce",
".",
"value",
"end",
"end",
"end",
"ret",
"end"
] | parse legalEntityInfos content. | [
"parse",
"legalEntityInfos",
"content",
"."
] | c0025daee5e7087f60b654595a8e7d92e966c54e | https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/afnic.rb#L82-L114 |
4,329 | scrapper/perobs | lib/perobs/IDList.rb | PEROBS.IDList.insert | def insert(id)
# Find the index of the page that should hold ID.
index = @page_records.bsearch_index { |pr| pr.max_id >= id }
# Get the corresponding IDListPageRecord object.
page = @page_records[index]
# In case the page is already full we'll have to create a new page.
# There is no guarantee that a split will yield an page with space as we
# split by ID range, not by distributing the values evenly across the
# two pages.
while page.is_full?
new_page = page.split
# Store the newly created page into the page_records list.
@page_records.insert(index + 1, new_page)
if id >= new_page.min_id
# We need to insert the ID into the newly created page. Adjust index
# and page reference accordingly.
index += 1
page = new_page
end
end
# Insert the ID into the page.
page.insert(id)
end | ruby | def insert(id)
# Find the index of the page that should hold ID.
index = @page_records.bsearch_index { |pr| pr.max_id >= id }
# Get the corresponding IDListPageRecord object.
page = @page_records[index]
# In case the page is already full we'll have to create a new page.
# There is no guarantee that a split will yield an page with space as we
# split by ID range, not by distributing the values evenly across the
# two pages.
while page.is_full?
new_page = page.split
# Store the newly created page into the page_records list.
@page_records.insert(index + 1, new_page)
if id >= new_page.min_id
# We need to insert the ID into the newly created page. Adjust index
# and page reference accordingly.
index += 1
page = new_page
end
end
# Insert the ID into the page.
page.insert(id)
end | [
"def",
"insert",
"(",
"id",
")",
"# Find the index of the page that should hold ID.",
"index",
"=",
"@page_records",
".",
"bsearch_index",
"{",
"|",
"pr",
"|",
"pr",
".",
"max_id",
">=",
"id",
"}",
"# Get the corresponding IDListPageRecord object.",
"page",
"=",
"@page_records",
"[",
"index",
"]",
"# In case the page is already full we'll have to create a new page.",
"# There is no guarantee that a split will yield an page with space as we",
"# split by ID range, not by distributing the values evenly across the",
"# two pages.",
"while",
"page",
".",
"is_full?",
"new_page",
"=",
"page",
".",
"split",
"# Store the newly created page into the page_records list.",
"@page_records",
".",
"insert",
"(",
"index",
"+",
"1",
",",
"new_page",
")",
"if",
"id",
">=",
"new_page",
".",
"min_id",
"# We need to insert the ID into the newly created page. Adjust index",
"# and page reference accordingly.",
"index",
"+=",
"1",
"page",
"=",
"new_page",
"end",
"end",
"# Insert the ID into the page.",
"page",
".",
"insert",
"(",
"id",
")",
"end"
] | Create a new IDList object. The data that can't be kept in memory will
be stored in the specified directory under the given name.
@param dir [String] Path of the directory
@param name [String] Name of the file
@param max_in_memory [Integer] Specifies the maximum number of values
that will be kept in memory. If the list is larger, values will
be cached in the specified file.
@param page_size [Integer] The number of values per page. The default
value is 32 which was found the best performing config in tests.
Insert a new value into the list.
@param id [Integer] The value to add | [
"Create",
"a",
"new",
"IDList",
"object",
".",
"The",
"data",
"that",
"can",
"t",
"be",
"kept",
"in",
"memory",
"will",
"be",
"stored",
"in",
"the",
"specified",
"directory",
"under",
"the",
"given",
"name",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDList.rb#L59-L83 |
4,330 | scrapper/perobs | lib/perobs/IDList.rb | PEROBS.IDList.check | def check
last_max = -1
unless (min_id = @page_records.first.min_id) == 0
raise RuntimeError, "min_id of first record (#{min_id}) " +
"must be 0."
end
@page_records.each do |pr|
unless pr.min_id == last_max + 1
raise RuntimeError, "max_id of previous record (#{last_max}) " +
"must be exactly 1 smaller than current record (#{pr.min_id})."
end
last_max = pr.max_id
pr.check
end
unless last_max == 2 ** 64
raise RuntimeError, "max_id of last records " +
"(#{@page_records.last.max_id}) must be #{2 ** 64})."
end
end | ruby | def check
last_max = -1
unless (min_id = @page_records.first.min_id) == 0
raise RuntimeError, "min_id of first record (#{min_id}) " +
"must be 0."
end
@page_records.each do |pr|
unless pr.min_id == last_max + 1
raise RuntimeError, "max_id of previous record (#{last_max}) " +
"must be exactly 1 smaller than current record (#{pr.min_id})."
end
last_max = pr.max_id
pr.check
end
unless last_max == 2 ** 64
raise RuntimeError, "max_id of last records " +
"(#{@page_records.last.max_id}) must be #{2 ** 64})."
end
end | [
"def",
"check",
"last_max",
"=",
"-",
"1",
"unless",
"(",
"min_id",
"=",
"@page_records",
".",
"first",
".",
"min_id",
")",
"==",
"0",
"raise",
"RuntimeError",
",",
"\"min_id of first record (#{min_id}) \"",
"+",
"\"must be 0.\"",
"end",
"@page_records",
".",
"each",
"do",
"|",
"pr",
"|",
"unless",
"pr",
".",
"min_id",
"==",
"last_max",
"+",
"1",
"raise",
"RuntimeError",
",",
"\"max_id of previous record (#{last_max}) \"",
"+",
"\"must be exactly 1 smaller than current record (#{pr.min_id}).\"",
"end",
"last_max",
"=",
"pr",
".",
"max_id",
"pr",
".",
"check",
"end",
"unless",
"last_max",
"==",
"2",
"**",
"64",
"raise",
"RuntimeError",
",",
"\"max_id of last records \"",
"+",
"\"(#{@page_records.last.max_id}) must be #{2 ** 64}).\"",
"end",
"end"
] | Perform some consistency checks on the internal data structures. Raises
a RuntimeError in case a problem is found. | [
"Perform",
"some",
"consistency",
"checks",
"on",
"the",
"internal",
"data",
"structures",
".",
"Raises",
"a",
"RuntimeError",
"in",
"case",
"a",
"problem",
"is",
"found",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDList.rb#L107-L127 |
4,331 | louismrose/lncs | lib/lncs/paper.rb | LNCS.Paper.paths_to_pdfs | def paths_to_pdfs
paths = []
Zip::ZipFile.open(path) do |zipfile|
zipfile.select { |file| zipfile.get_entry(file).file? }.each do |file|
paths << file.name if file.name.end_with? ".pdf"
end
end
paths
end | ruby | def paths_to_pdfs
paths = []
Zip::ZipFile.open(path) do |zipfile|
zipfile.select { |file| zipfile.get_entry(file).file? }.each do |file|
paths << file.name if file.name.end_with? ".pdf"
end
end
paths
end | [
"def",
"paths_to_pdfs",
"paths",
"=",
"[",
"]",
"Zip",
"::",
"ZipFile",
".",
"open",
"(",
"path",
")",
"do",
"|",
"zipfile",
"|",
"zipfile",
".",
"select",
"{",
"|",
"file",
"|",
"zipfile",
".",
"get_entry",
"(",
"file",
")",
".",
"file?",
"}",
".",
"each",
"do",
"|",
"file",
"|",
"paths",
"<<",
"file",
".",
"name",
"if",
"file",
".",
"name",
".",
"end_with?",
"\".pdf\"",
"end",
"end",
"paths",
"end"
] | Locate all PDF files within the ZIP | [
"Locate",
"all",
"PDF",
"files",
"within",
"the",
"ZIP"
] | 88dc0f95c294a9a319407a65c3b9891b54d16e59 | https://github.com/louismrose/lncs/blob/88dc0f95c294a9a319407a65c3b9891b54d16e59/lib/lncs/paper.rb#L104-L114 |
4,332 | jwood/tenacity | lib/tenacity/class_methods.rb | Tenacity.ClassMethods.t_has_one | def t_has_one(name, options={})
extend(Associations::HasOne::ClassMethods)
association = _t_create_association(:t_has_one, name, options)
initialize_has_one_association(association)
define_method(association.name) do |*params|
get_associate(association, params) do
has_one_associate(association)
end
end
define_method("#{association.name}=") do |associate|
set_associate(association, associate) do
set_has_one_associate(association, associate)
end
end
end | ruby | def t_has_one(name, options={})
extend(Associations::HasOne::ClassMethods)
association = _t_create_association(:t_has_one, name, options)
initialize_has_one_association(association)
define_method(association.name) do |*params|
get_associate(association, params) do
has_one_associate(association)
end
end
define_method("#{association.name}=") do |associate|
set_associate(association, associate) do
set_has_one_associate(association, associate)
end
end
end | [
"def",
"t_has_one",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"extend",
"(",
"Associations",
"::",
"HasOne",
"::",
"ClassMethods",
")",
"association",
"=",
"_t_create_association",
"(",
":t_has_one",
",",
"name",
",",
"options",
")",
"initialize_has_one_association",
"(",
"association",
")",
"define_method",
"(",
"association",
".",
"name",
")",
"do",
"|",
"*",
"params",
"|",
"get_associate",
"(",
"association",
",",
"params",
")",
"do",
"has_one_associate",
"(",
"association",
")",
"end",
"end",
"define_method",
"(",
"\"#{association.name}=\"",
")",
"do",
"|",
"associate",
"|",
"set_associate",
"(",
"association",
",",
"associate",
")",
"do",
"set_has_one_associate",
"(",
"association",
",",
"associate",
")",
"end",
"end",
"end"
] | Specifies a one-to-one association with another class. This method should only be used
if the other class contains the foreign key. If the current class contains the foreign key,
then you should use +t_belongs_to+ instead.
The following methods for retrieval and query of a single associated object will be added:
[association(force_reload = false)]
Returns the associated object. +nil+ is returned if none is found.
[association=(associate)]
Assigns the associate object, extracts the primary key, sets it as the foreign key,
and saves the associate object.
(+association+ is replaced with the symbol passed as the first argument, so
<tt>t_has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
=== Example
An Account class declares <tt>t_has_one :beneficiary</tt>, which will add:
* <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first, :conditions => "account_id = #{id}")</tt>)
* <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
=== Supported options
[:class_name]
Specify the class name of the association. Use it only if that name can't be inferred
from the association name. So <tt>t_has_one :manager</tt> will by default be linked to the Manager class, but
if the real class name is Person, you'll have to specify it with this option.
[:foreign_key]
Specify the foreign key used for the association. By default this is guessed to be the name
of this class in lower-case and "_id" suffixed. So a Person class that makes a +t_has_one+ association
will use "person_id" as the default <tt>:foreign_key</tt>.
[:dependent]
If set to <tt>:destroy</tt>, the associated object is deleted when this object is, and all delete
callbacks are called. If set to <tt>:delete</tt>, the associated object is deleted *without*
calling any of its delete callbacks. If set to <tt>:nullify</tt>, the associated object's
foreign key is set to +NULL+.
[:readonly]
If true, the associated object is readonly through the association.
[:autosave]
If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default.
[:as]
Specifies a polymorphic interface (See <tt>t_belongs_to</tt>).
[:disable_foreign_key_constraints]
If true, bypass foreign key constraints, like verifying no other objects are storing the key of the source object
before deleting it. Defaults to false.
Option examples:
t_has_one :credit_card, :dependent => :destroy # destroys the associated credit card
t_has_one :credit_card, :dependent => :nullify # updates the associated records foreign key value to NULL rather than destroying it
t_has_one :project_manager, :class_name => "Person"
t_has_one :project_manager, :foreign_key => "project_id" # within class named SecretProject
t_has_one :boss, :readonly => :true
t_has_one :attachment, :as => :attachable | [
"Specifies",
"a",
"one",
"-",
"to",
"-",
"one",
"association",
"with",
"another",
"class",
".",
"This",
"method",
"should",
"only",
"be",
"used",
"if",
"the",
"other",
"class",
"contains",
"the",
"foreign",
"key",
".",
"If",
"the",
"current",
"class",
"contains",
"the",
"foreign",
"key",
"then",
"you",
"should",
"use",
"+",
"t_belongs_to",
"+",
"instead",
"."
] | 2094c926dd14779f69c70e59fb20fdda3ae819cf | https://github.com/jwood/tenacity/blob/2094c926dd14779f69c70e59fb20fdda3ae819cf/lib/tenacity/class_methods.rb#L198-L214 |
4,333 | jwood/tenacity | lib/tenacity/class_methods.rb | Tenacity.ClassMethods.t_belongs_to | def t_belongs_to(name, options={})
extend(Associations::BelongsTo::ClassMethods)
association = _t_create_association(:t_belongs_to, name, options)
initialize_belongs_to_association(association)
define_method(association.name) do |*params|
get_associate(association, params) do
belongs_to_associate(association)
end
end
define_method("#{association.name}=") do |associate|
set_associate(association, associate) do
set_belongs_to_associate(association, associate)
end
end
end | ruby | def t_belongs_to(name, options={})
extend(Associations::BelongsTo::ClassMethods)
association = _t_create_association(:t_belongs_to, name, options)
initialize_belongs_to_association(association)
define_method(association.name) do |*params|
get_associate(association, params) do
belongs_to_associate(association)
end
end
define_method("#{association.name}=") do |associate|
set_associate(association, associate) do
set_belongs_to_associate(association, associate)
end
end
end | [
"def",
"t_belongs_to",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"extend",
"(",
"Associations",
"::",
"BelongsTo",
"::",
"ClassMethods",
")",
"association",
"=",
"_t_create_association",
"(",
":t_belongs_to",
",",
"name",
",",
"options",
")",
"initialize_belongs_to_association",
"(",
"association",
")",
"define_method",
"(",
"association",
".",
"name",
")",
"do",
"|",
"*",
"params",
"|",
"get_associate",
"(",
"association",
",",
"params",
")",
"do",
"belongs_to_associate",
"(",
"association",
")",
"end",
"end",
"define_method",
"(",
"\"#{association.name}=\"",
")",
"do",
"|",
"associate",
"|",
"set_associate",
"(",
"association",
",",
"associate",
")",
"do",
"set_belongs_to_associate",
"(",
"association",
",",
"associate",
")",
"end",
"end",
"end"
] | Specifies a one-to-one association with another class. This method should only be used
if this class contains the foreign key. If the other class contains the foreign key,
then you should use +t_has_one+ instead.
Methods will be added for retrieval and query for a single associated object, for which
this object holds an id:
[association(force_reload = false)]
Returns the associated object. +nil+ is returned if none is found.
[association=(associate)]
Assigns the associate object, extracts the primary key, and sets it as the foreign key.
(+association+ is replaced with the symbol passed as the first argument, so
<tt>t_belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
=== Example
A Post class declares <tt>t_belongs_to :author</tt>, which will add:
* <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
* <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
=== Supported options
[:class_name]
Specify the class name of the association. Use it only if that name can't be inferred
from the association name. So <tt>t_belongs_to :manager</tt> will by default be linked to the Manager class, but
if the real class name is Person, you'll have to specify it with this option.
[:foreign_key]
Specify the foreign key used for the association. By default this is guessed to be the name
of the association with an "_id" suffix. So a class that defines a <tt>t_belongs_to :person</tt>
association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
<tt>t_belongs_to :favorite_person, :class_name => "Person"</tt> will use a foreign key
of "favorite_person_id".
[:dependent]
If set to <tt>:destroy</tt>, the associated object is deleted when this object is, calling all delete
callbacks. If set to <tt>:delete</tt>, the associated object is deleted *without* calling any of
its delete callbacks. This option should not be specified when <tt>t_belongs_to</tt> is used in
conjuction with a <tt>t_has_many</tt> relationship on another class because of the potential
to leave orphaned records behind.
[:readonly]
If true, the associated object is readonly through the association.
[:autosave]
If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default.
[:polymorphic]
Specify this association is a polymorphic association by passing +true+. (*Note*: IDs for polymorphic associations are always
stored as strings in the database.)
[:disable_foreign_key_constraints]
If true, bypass foreign key constraints, like verifying the target object exists when the relationship is created.
Defaults to false.
Option examples:
t_belongs_to :project_manager, :class_name => "Person"
t_belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id"
t_belongs_to :project, :readonly => true
t_belongs_to :attachable, :polymorphic => true | [
"Specifies",
"a",
"one",
"-",
"to",
"-",
"one",
"association",
"with",
"another",
"class",
".",
"This",
"method",
"should",
"only",
"be",
"used",
"if",
"this",
"class",
"contains",
"the",
"foreign",
"key",
".",
"If",
"the",
"other",
"class",
"contains",
"the",
"foreign",
"key",
"then",
"you",
"should",
"use",
"+",
"t_has_one",
"+",
"instead",
"."
] | 2094c926dd14779f69c70e59fb20fdda3ae819cf | https://github.com/jwood/tenacity/blob/2094c926dd14779f69c70e59fb20fdda3ae819cf/lib/tenacity/class_methods.rb#L271-L287 |
4,334 | jwood/tenacity | lib/tenacity/class_methods.rb | Tenacity.ClassMethods.t_has_many | def t_has_many(name, options={})
extend(Associations::HasMany::ClassMethods)
association = _t_create_association(:t_has_many, name, options)
initialize_has_many_association(association)
define_method(association.name) do |*params|
get_associate(association, params) do
has_many_associates(association)
end
end
define_method("#{association.name}=") do |associates|
_t_mark_dirty if respond_to?(:_t_mark_dirty)
set_associate(association, associates) do
set_has_many_associates(association, associates)
end
end
define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids") do
has_many_associate_ids(association)
end
define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids=") do |associate_ids|
_t_mark_dirty if respond_to?(:_t_mark_dirty)
set_has_many_associate_ids(association, associate_ids)
end
private
define_method(:_t_save_without_callback) do
save_without_callback
end
end | ruby | def t_has_many(name, options={})
extend(Associations::HasMany::ClassMethods)
association = _t_create_association(:t_has_many, name, options)
initialize_has_many_association(association)
define_method(association.name) do |*params|
get_associate(association, params) do
has_many_associates(association)
end
end
define_method("#{association.name}=") do |associates|
_t_mark_dirty if respond_to?(:_t_mark_dirty)
set_associate(association, associates) do
set_has_many_associates(association, associates)
end
end
define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids") do
has_many_associate_ids(association)
end
define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids=") do |associate_ids|
_t_mark_dirty if respond_to?(:_t_mark_dirty)
set_has_many_associate_ids(association, associate_ids)
end
private
define_method(:_t_save_without_callback) do
save_without_callback
end
end | [
"def",
"t_has_many",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"extend",
"(",
"Associations",
"::",
"HasMany",
"::",
"ClassMethods",
")",
"association",
"=",
"_t_create_association",
"(",
":t_has_many",
",",
"name",
",",
"options",
")",
"initialize_has_many_association",
"(",
"association",
")",
"define_method",
"(",
"association",
".",
"name",
")",
"do",
"|",
"*",
"params",
"|",
"get_associate",
"(",
"association",
",",
"params",
")",
"do",
"has_many_associates",
"(",
"association",
")",
"end",
"end",
"define_method",
"(",
"\"#{association.name}=\"",
")",
"do",
"|",
"associates",
"|",
"_t_mark_dirty",
"if",
"respond_to?",
"(",
":_t_mark_dirty",
")",
"set_associate",
"(",
"association",
",",
"associates",
")",
"do",
"set_has_many_associates",
"(",
"association",
",",
"associates",
")",
"end",
"end",
"define_method",
"(",
"\"#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids\"",
")",
"do",
"has_many_associate_ids",
"(",
"association",
")",
"end",
"define_method",
"(",
"\"#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids=\"",
")",
"do",
"|",
"associate_ids",
"|",
"_t_mark_dirty",
"if",
"respond_to?",
"(",
":_t_mark_dirty",
")",
"set_has_many_associate_ids",
"(",
"association",
",",
"associate_ids",
")",
"end",
"private",
"define_method",
"(",
":_t_save_without_callback",
")",
"do",
"save_without_callback",
"end",
"end"
] | Specifies a one-to-many association.
The following methods for retrieval and query of collections of associated objects will be added:
[collection(force_reload = false)]
Returns an array of all the associated objects.
An empty array is returned if none are found.
[collection<<(object, ...)]
Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
[collection.push(object, ...)]
Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
[collection.concat(other_array)]
Adds the objects in the other array to the collection by setting their foreign keys to the collection's primary key.
[collection.delete(object, ...)]
Removes one or more objects from the collection by setting their foreign keys to +NULL+.
Objects will be in addition deleted and callbacks called if they're associated with <tt>:dependent => :destroy</tt>,
and deleted and callbacks skipped if they're associated with <tt>:dependent => :delete_all</tt>.
[collection.destroy_all]
Removes all objects from the collection, and deletes them from their respective
database. If the deleted objects have any delete callbacks defined, they will be called.
[collection.delete_all]
Removes all objects from the collection, and deletes them from their respective
database. No delete callbacks will be called, regardless of whether or not they are defined.
[collection=objects]
Replaces the collections content by setting it to the list of specified objects.
[collection_singular_ids]
Returns an array of the associated objects' ids
[collection_singular_ids=ids]
Replace the collection with the objects identified by the primary keys in +ids+.
[collection.clear]
Removes every object from the collection. This deletes the associated objects and issues callbacks
if they are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the
database without calling any callbacks if <tt>:dependent => :delete_all</tt>, otherwise sets their
foreign keys to +NULL+.
[collection.empty?]
Returns +true+ if there are no associated objects.
[collection.size]
Returns the number of associated objects.
(*Note*: +collection+ is replaced with the symbol passed as the first argument, so
<tt>t_has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
=== Example
Example: A Firm class declares <tt>t_has_many :clients</tt>, which will add:
* <tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions => ["firm_id = ?", id]</tt>)
* <tt>Firm#clients<<</tt>
* <tt>Firm#clients.delete</tt>
* <tt>Firm#clients=</tt>
* <tt>Firm#client_ids</tt>
* <tt>Firm#client_ids=</tt>
* <tt>Firm#clients.clear</tt>
* <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
* <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
=== Supported options
[:class_name]
Specify the class name of the association. Use it only if that name can't be inferred
from the association name. So <tt>t_has_many :products</tt> will by default be linked
to the Product class, but if the real class name is SpecialProduct, you'll have to
specify it with this option.
[:foreign_key]
Specify the foreign key used for the association. By default this is guessed to be the name
of this class in lower-case and "_id" suffixed. So a Person class that makes a +t_has_many+
association will use "person_id" as the default <tt>:foreign_key</tt>.
[:dependent]
If set to <tt>:destroy</tt> all the associated objects are deleted alongside this object
in addition to calling their delete callbacks. If set to <tt>:delete_all</tt> all
associated objects are deleted *without* calling their delete callbacks. If set to
<tt>:nullify</tt> all associated objects' foreign keys are set to +NULL+ *without* calling
their save backs.
[:readonly]
If true, all the associated objects are readonly through the association.
[:limit]
An integer determining the limit on the number of rows that should be returned. Results
are ordered by a string representation of the id.
[:offset]
An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
Results are ordered by a string representation of the id.
[:autosave]
If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default.
[:as]
Specifies a polymorphic interface (See <tt>t_belongs_to</tt>).
[:disable_foreign_key_constraints]
If true, bypass foreign key constraints, like verifying no other objects are storing the key of the source object
before deleting it. Defaults to false.
Option examples:
t_has_many :products, :class_name => "SpecialProduct"
t_has_many :engineers, :foreign_key => "project_id" # within class named SecretProject
t_has_many :tasks, :dependent => :destroy
t_has_many :reports, :readonly => true
t_has_many :tags, :as => :taggable | [
"Specifies",
"a",
"one",
"-",
"to",
"-",
"many",
"association",
"."
] | 2094c926dd14779f69c70e59fb20fdda3ae819cf | https://github.com/jwood/tenacity/blob/2094c926dd14779f69c70e59fb20fdda3ae819cf/lib/tenacity/class_methods.rb#L383-L415 |
4,335 | sagmor/yard-mruby | lib/yard/mruby/code_objects/function_object.rb | YARD::MRuby::CodeObjects.FunctionObject.aliases | def aliases
list = []
return list unless namespace.is_a?(HeaderObject)
namespace.aliases.each do |o, aname|
list << o if aname == name && o.scope == scope
end
list
end | ruby | def aliases
list = []
return list unless namespace.is_a?(HeaderObject)
namespace.aliases.each do |o, aname|
list << o if aname == name && o.scope == scope
end
list
end | [
"def",
"aliases",
"list",
"=",
"[",
"]",
"return",
"list",
"unless",
"namespace",
".",
"is_a?",
"(",
"HeaderObject",
")",
"namespace",
".",
"aliases",
".",
"each",
"do",
"|",
"o",
",",
"aname",
"|",
"list",
"<<",
"o",
"if",
"aname",
"==",
"name",
"&&",
"o",
".",
"scope",
"==",
"scope",
"end",
"list",
"end"
] | Returns all alias names of the object
@return [Array<Symbol>] the alias names | [
"Returns",
"all",
"alias",
"names",
"of",
"the",
"object"
] | c20c2f415d15235fdc96ac177cb008eb3e11358a | https://github.com/sagmor/yard-mruby/blob/c20c2f415d15235fdc96ac177cb008eb3e11358a/lib/yard/mruby/code_objects/function_object.rb#L62-L69 |
4,336 | proglottis/glicko2 | lib/glicko2/rating_period.rb | Glicko2.RatingPeriod.game | def game(game_seeds, ranks)
game_seeds.each_with_index do |iseed, i|
game_seeds.each_with_index do |jseed, j|
next if i == j
@raters[iseed].add(player(jseed).rating, Util.ranks_to_score(ranks[i], ranks[j]))
end
end
end | ruby | def game(game_seeds, ranks)
game_seeds.each_with_index do |iseed, i|
game_seeds.each_with_index do |jseed, j|
next if i == j
@raters[iseed].add(player(jseed).rating, Util.ranks_to_score(ranks[i], ranks[j]))
end
end
end | [
"def",
"game",
"(",
"game_seeds",
",",
"ranks",
")",
"game_seeds",
".",
"each_with_index",
"do",
"|",
"iseed",
",",
"i",
"|",
"game_seeds",
".",
"each_with_index",
"do",
"|",
"jseed",
",",
"j",
"|",
"next",
"if",
"i",
"==",
"j",
"@raters",
"[",
"iseed",
"]",
".",
"add",
"(",
"player",
"(",
"jseed",
")",
".",
"rating",
",",
"Util",
".",
"ranks_to_score",
"(",
"ranks",
"[",
"i",
"]",
",",
"ranks",
"[",
"j",
"]",
")",
")",
"end",
"end",
"end"
] | Register a game with this rating period
@param [Array<#rating,#rating_deviation,#volatility>] game_seeds ratings participating in a game
@param [Array<Integer>] ranks corresponding ranks | [
"Register",
"a",
"game",
"with",
"this",
"rating",
"period"
] | 8ede9a758a1a35b2bc5e6d4706aad856ec8f7812 | https://github.com/proglottis/glicko2/blob/8ede9a758a1a35b2bc5e6d4706aad856ec8f7812/lib/glicko2/rating_period.rb#L35-L42 |
4,337 | holtrop/ruby-gnucash | lib/gnucash/value.rb | Gnucash.Value.+ | def +(other)
if other.is_a?(Value)
lcm_div = @div.lcm(other.div)
Value.new((@val * (lcm_div / @div)) + (other.val * (lcm_div / other.div)), lcm_div)
elsif other.is_a?(Numeric)
to_f + other
else
raise "Unexpected argument"
end
end | ruby | def +(other)
if other.is_a?(Value)
lcm_div = @div.lcm(other.div)
Value.new((@val * (lcm_div / @div)) + (other.val * (lcm_div / other.div)), lcm_div)
elsif other.is_a?(Numeric)
to_f + other
else
raise "Unexpected argument"
end
end | [
"def",
"+",
"(",
"other",
")",
"if",
"other",
".",
"is_a?",
"(",
"Value",
")",
"lcm_div",
"=",
"@div",
".",
"lcm",
"(",
"other",
".",
"div",
")",
"Value",
".",
"new",
"(",
"(",
"@val",
"*",
"(",
"lcm_div",
"/",
"@div",
")",
")",
"+",
"(",
"other",
".",
"val",
"*",
"(",
"lcm_div",
"/",
"other",
".",
"div",
")",
")",
",",
"lcm_div",
")",
"elsif",
"other",
".",
"is_a?",
"(",
"Numeric",
")",
"to_f",
"+",
"other",
"else",
"raise",
"\"Unexpected argument\"",
"end",
"end"
] | Construct a Value object.
@param val [String, Integer]
Either a String in the form "1234/100" or an integer containing the
raw value.
@param div [Integer]
The divisor value to use (when +val+ is given as a Integer).
Add to a Value object.
@param other [Value, Numeric]
@return [Value] Result of addition. | [
"Construct",
"a",
"Value",
"object",
"."
] | a233cc4da0f36b13bc3f7a17264adb82c8a12c6b | https://github.com/holtrop/ruby-gnucash/blob/a233cc4da0f36b13bc3f7a17264adb82c8a12c6b/lib/gnucash/value.rb#L49-L58 |
4,338 | holtrop/ruby-gnucash | lib/gnucash/value.rb | Gnucash.Value.* | def *(other)
if other.is_a?(Value)
other = other.to_f
end
if other.is_a?(Numeric)
to_f * other
else
raise "Unexpected argument (#{other.inspect})"
end
end | ruby | def *(other)
if other.is_a?(Value)
other = other.to_f
end
if other.is_a?(Numeric)
to_f * other
else
raise "Unexpected argument (#{other.inspect})"
end
end | [
"def",
"*",
"(",
"other",
")",
"if",
"other",
".",
"is_a?",
"(",
"Value",
")",
"other",
"=",
"other",
".",
"to_f",
"end",
"if",
"other",
".",
"is_a?",
"(",
"Numeric",
")",
"to_f",
"*",
"other",
"else",
"raise",
"\"Unexpected argument (#{other.inspect})\"",
"end",
"end"
] | Multiply a Value object.
@param other [Numeric, Value] Multiplier.
@return [Numeric] Result of multiplication. | [
"Multiply",
"a",
"Value",
"object",
"."
] | a233cc4da0f36b13bc3f7a17264adb82c8a12c6b | https://github.com/holtrop/ruby-gnucash/blob/a233cc4da0f36b13bc3f7a17264adb82c8a12c6b/lib/gnucash/value.rb#L88-L97 |
4,339 | notonthehighstreet/chicago | lib/chicago/star_schema.rb | Chicago.StarSchema.add | def add(schema_table)
if schema_table.kind_of? Schema::Fact
collection = @facts
elsif schema_table.kind_of? Schema::Dimension
collection = @dimensions
end
add_to_collection collection, schema_table
end | ruby | def add(schema_table)
if schema_table.kind_of? Schema::Fact
collection = @facts
elsif schema_table.kind_of? Schema::Dimension
collection = @dimensions
end
add_to_collection collection, schema_table
end | [
"def",
"add",
"(",
"schema_table",
")",
"if",
"schema_table",
".",
"kind_of?",
"Schema",
"::",
"Fact",
"collection",
"=",
"@facts",
"elsif",
"schema_table",
".",
"kind_of?",
"Schema",
"::",
"Dimension",
"collection",
"=",
"@dimensions",
"end",
"add_to_collection",
"collection",
",",
"schema_table",
"end"
] | Adds a prebuilt schema table to the schema
Schema tables may not be dupliates of already present tables in
the schema.
TODO: figure out how to deal with linked dimensions when adding
facts. | [
"Adds",
"a",
"prebuilt",
"schema",
"table",
"to",
"the",
"schema"
] | 428e94f8089d2f36fdcff2e27ea2af572b816def | https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L62-L70 |
4,340 | notonthehighstreet/chicago | lib/chicago/star_schema.rb | Chicago.StarSchema.define_fact | def define_fact(name, &block)
add Schema::Builders::FactBuilder.new(self).build(name, &block)
end | ruby | def define_fact(name, &block)
add Schema::Builders::FactBuilder.new(self).build(name, &block)
end | [
"def",
"define_fact",
"(",
"name",
",",
"&",
"block",
")",
"add",
"Schema",
"::",
"Builders",
"::",
"FactBuilder",
".",
"new",
"(",
"self",
")",
".",
"build",
"(",
"name",
",",
"block",
")",
"end"
] | Defines a fact table named +name+ in this schema.
@see Chicago::Schema::Builders::FactBuilder
@return [Chicago::Schema::Fact] the defined fact.
@raise Chicago::MissingDefinitionError | [
"Defines",
"a",
"fact",
"table",
"named",
"+",
"name",
"+",
"in",
"this",
"schema",
"."
] | 428e94f8089d2f36fdcff2e27ea2af572b816def | https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L77-L79 |
4,341 | notonthehighstreet/chicago | lib/chicago/star_schema.rb | Chicago.StarSchema.define_dimension | def define_dimension(name, &block)
add Schema::Builders::DimensionBuilder.new(self).build(name, &block)
end | ruby | def define_dimension(name, &block)
add Schema::Builders::DimensionBuilder.new(self).build(name, &block)
end | [
"def",
"define_dimension",
"(",
"name",
",",
"&",
"block",
")",
"add",
"Schema",
"::",
"Builders",
"::",
"DimensionBuilder",
".",
"new",
"(",
"self",
")",
".",
"build",
"(",
"name",
",",
"block",
")",
"end"
] | Defines a dimension table named +name+ in this schema.
For example:
@schema.define_dimension(:date) do
columns do
date :date
year :year
string :month
...
end
natural_key :date
null_record :id => 1, :month => "Unknown Month"
end
@see Chicago::Schema::Builders::DimensionBuilder
@return [Chicago::Schema::Dimension] the defined dimension. | [
"Defines",
"a",
"dimension",
"table",
"named",
"+",
"name",
"+",
"in",
"this",
"schema",
"."
] | 428e94f8089d2f36fdcff2e27ea2af572b816def | https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L99-L101 |
4,342 | notonthehighstreet/chicago | lib/chicago/star_schema.rb | Chicago.StarSchema.define_shrunken_dimension | def define_shrunken_dimension(name, base_name, &block)
add Schema::Builders::ShrunkenDimensionBuilder.new(self, base_name).
build(name, &block)
end | ruby | def define_shrunken_dimension(name, base_name, &block)
add Schema::Builders::ShrunkenDimensionBuilder.new(self, base_name).
build(name, &block)
end | [
"def",
"define_shrunken_dimension",
"(",
"name",
",",
"base_name",
",",
"&",
"block",
")",
"add",
"Schema",
"::",
"Builders",
"::",
"ShrunkenDimensionBuilder",
".",
"new",
"(",
"self",
",",
"base_name",
")",
".",
"build",
"(",
"name",
",",
"block",
")",
"end"
] | Defines a shrunken dimension table named +name+ in this schema.
+base_name+ is the name of the base dimension that the shrunken
dimension is derived from; this base dimention must already be
defined.
@see Chicago::Schema::Builders::ShrunkenDimensionBuilder
@raise [Chicago::MissingDefinitionError] if the base dimension is not defined.
@return [Chicago::Schema::Dimension] the defined dimension. | [
"Defines",
"a",
"shrunken",
"dimension",
"table",
"named",
"+",
"name",
"+",
"in",
"this",
"schema",
"."
] | 428e94f8089d2f36fdcff2e27ea2af572b816def | https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L112-L115 |
4,343 | jeffnyman/tapestry | lib/tapestry/extensions/data_setter.rb | Tapestry.DataSetter.use_data_with | def use_data_with(key, value)
element = send(key.to_s.tr(' ', '_'))
set_and_select(key, element, value)
check_and_uncheck(key, element, value)
end | ruby | def use_data_with(key, value)
element = send(key.to_s.tr(' ', '_'))
set_and_select(key, element, value)
check_and_uncheck(key, element, value)
end | [
"def",
"use_data_with",
"(",
"key",
",",
"value",
")",
"element",
"=",
"send",
"(",
"key",
".",
"to_s",
".",
"tr",
"(",
"' '",
",",
"'_'",
")",
")",
"set_and_select",
"(",
"key",
",",
"element",
",",
"value",
")",
"check_and_uncheck",
"(",
"key",
",",
"element",
",",
"value",
")",
"end"
] | This is the method that is delegated to in order to make sure that
elements are interacted with appropriately. This will in turn delegate
to `set_and_select` and `check_and_uncheck`, which determines what
actions are viable based on the type of element that is being dealt
with. These aspects are what tie this particular implementation to
Watir. | [
"This",
"is",
"the",
"method",
"that",
"is",
"delegated",
"to",
"in",
"order",
"to",
"make",
"sure",
"that",
"elements",
"are",
"interacted",
"with",
"appropriately",
".",
"This",
"will",
"in",
"turn",
"delegate",
"to",
"set_and_select",
"and",
"check_and_uncheck",
"which",
"determines",
"what",
"actions",
"are",
"viable",
"based",
"on",
"the",
"type",
"of",
"element",
"that",
"is",
"being",
"dealt",
"with",
".",
"These",
"aspects",
"are",
"what",
"tie",
"this",
"particular",
"implementation",
"to",
"Watir",
"."
] | da28652dd6de71e415cd2c01afd89f641938a05b | https://github.com/jeffnyman/tapestry/blob/da28652dd6de71e415cd2c01afd89f641938a05b/lib/tapestry/extensions/data_setter.rb#L79-L83 |
4,344 | tagoh/ruby-bugzilla | lib/bugzilla/bugzilla.rb | Bugzilla.Bugzilla.requires_version | def requires_version(cmd, version_)
v = check_version(version_)
raise NoMethodError, sprintf("%s is not supported in Bugzilla %s", cmd, v[1]) unless v[0]
end | ruby | def requires_version(cmd, version_)
v = check_version(version_)
raise NoMethodError, sprintf("%s is not supported in Bugzilla %s", cmd, v[1]) unless v[0]
end | [
"def",
"requires_version",
"(",
"cmd",
",",
"version_",
")",
"v",
"=",
"check_version",
"(",
"version_",
")",
"raise",
"NoMethodError",
",",
"sprintf",
"(",
"\"%s is not supported in Bugzilla %s\"",
",",
"cmd",
",",
"v",
"[",
"1",
"]",
")",
"unless",
"v",
"[",
"0",
"]",
"end"
] | def check_version
=begin rdoc
==== Bugzilla::Bugzilla#requires_version(cmd, version_)
Raise an exception if the Bugzilla doesn't satisfy
the requirement of the _version_.
=end | [
"def",
"check_version",
"=",
"begin",
"rdoc"
] | 5aabec1b045473bcd6e6ac7427b68adb3e3b4886 | https://github.com/tagoh/ruby-bugzilla/blob/5aabec1b045473bcd6e6ac7427b68adb3e3b4886/lib/bugzilla/bugzilla.rb#L65-L68 |
4,345 | scrapper/perobs | lib/perobs/IDListPageFile.rb | PEROBS.IDListPageFile.load | def load(page_idx, record)
# The IDListPageRecord will tell us the actual number of values stored
# in this page.
values = []
unless (entries = record.page_entries) == 0
begin
@f.seek(page_idx * @page_size * 8)
values = @f.read(entries * 8).unpack("Q#{entries}")
rescue IOError => e
PEROBS.log.fatal "Cannot read cache file #{@file_name}: #{e.message}"
end
end
# Create the IDListPage object with the given values.
p = IDListPage.new(self, record, page_idx, values)
@pages.insert(p, false)
p
end | ruby | def load(page_idx, record)
# The IDListPageRecord will tell us the actual number of values stored
# in this page.
values = []
unless (entries = record.page_entries) == 0
begin
@f.seek(page_idx * @page_size * 8)
values = @f.read(entries * 8).unpack("Q#{entries}")
rescue IOError => e
PEROBS.log.fatal "Cannot read cache file #{@file_name}: #{e.message}"
end
end
# Create the IDListPage object with the given values.
p = IDListPage.new(self, record, page_idx, values)
@pages.insert(p, false)
p
end | [
"def",
"load",
"(",
"page_idx",
",",
"record",
")",
"# The IDListPageRecord will tell us the actual number of values stored",
"# in this page.",
"values",
"=",
"[",
"]",
"unless",
"(",
"entries",
"=",
"record",
".",
"page_entries",
")",
"==",
"0",
"begin",
"@f",
".",
"seek",
"(",
"page_idx",
"*",
"@page_size",
"*",
"8",
")",
"values",
"=",
"@f",
".",
"read",
"(",
"entries",
"*",
"8",
")",
".",
"unpack",
"(",
"\"Q#{entries}\"",
")",
"rescue",
"IOError",
"=>",
"e",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Cannot read cache file #{@file_name}: #{e.message}\"",
"end",
"end",
"# Create the IDListPage object with the given values.",
"p",
"=",
"IDListPage",
".",
"new",
"(",
"self",
",",
"record",
",",
"page_idx",
",",
"values",
")",
"@pages",
".",
"insert",
"(",
"p",
",",
"false",
")",
"p",
"end"
] | Create a new IDListPageFile object that uses the given file in the given
directory as cache file.
@param list [IDList] The IDList object that caches pages here
@param dir [String] An existing directory
@param name [String] A file name (without path)
@param max_in_memory [Integer] Maximum number of pages to keep in memory
@param page_size [Integer] The number of values in each page
Load the IDListPage from the cache file.
@param page_idx [Integer] The page index in the page file
@param record [IDListPageRecord] the corresponding IDListPageRecord
@return [IDListPage] The loaded values | [
"Create",
"a",
"new",
"IDListPageFile",
"object",
"that",
"uses",
"the",
"given",
"file",
"in",
"the",
"given",
"directory",
"as",
"cache",
"file",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDListPageFile.rb#L66-L84 |
4,346 | scrapper/perobs | lib/perobs/IDListPageFile.rb | PEROBS.IDListPageFile.new_page | def new_page(record, values = [])
idx = @page_counter
@page_counter += 1
mark_page_as_modified(IDListPage.new(self, record, idx, values))
idx
end | ruby | def new_page(record, values = [])
idx = @page_counter
@page_counter += 1
mark_page_as_modified(IDListPage.new(self, record, idx, values))
idx
end | [
"def",
"new_page",
"(",
"record",
",",
"values",
"=",
"[",
"]",
")",
"idx",
"=",
"@page_counter",
"@page_counter",
"+=",
"1",
"mark_page_as_modified",
"(",
"IDListPage",
".",
"new",
"(",
"self",
",",
"record",
",",
"idx",
",",
"values",
")",
")",
"idx",
"end"
] | Create a new IDListPage and register it.
@param record [IDListPageRecord] The corresponding record.
@param values [Array of Integer] The values stored in the page
@return [IDListPage] | [
"Create",
"a",
"new",
"IDListPage",
"and",
"register",
"it",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDListPageFile.rb#L95-L100 |
4,347 | scrapper/perobs | lib/perobs/IDListPageFile.rb | PEROBS.IDListPageFile.page | def page(record)
p = @pages.get(record.page_idx, record) || load(record.page_idx, record)
unless p.uid == record.page_idx
raise RuntimeError, "Page reference mismatch. Record " +
"#{record.page_idx} points to page #{p.uid}"
end
p
end | ruby | def page(record)
p = @pages.get(record.page_idx, record) || load(record.page_idx, record)
unless p.uid == record.page_idx
raise RuntimeError, "Page reference mismatch. Record " +
"#{record.page_idx} points to page #{p.uid}"
end
p
end | [
"def",
"page",
"(",
"record",
")",
"p",
"=",
"@pages",
".",
"get",
"(",
"record",
".",
"page_idx",
",",
"record",
")",
"||",
"load",
"(",
"record",
".",
"page_idx",
",",
"record",
")",
"unless",
"p",
".",
"uid",
"==",
"record",
".",
"page_idx",
"raise",
"RuntimeError",
",",
"\"Page reference mismatch. Record \"",
"+",
"\"#{record.page_idx} points to page #{p.uid}\"",
"end",
"p",
"end"
] | Return the IDListPage object with the given index.
@param record [IDListPageRecord] the corresponding IDListPageRecord
@return [IDListPage] The page corresponding to the index. | [
"Return",
"the",
"IDListPage",
"object",
"with",
"the",
"given",
"index",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDListPageFile.rb#L105-L113 |
4,348 | scrapper/perobs | lib/perobs/IDListPageFile.rb | PEROBS.IDListPageFile.save_page | def save_page(p)
if p.record.page_entries != p.values.length
raise RuntimeError, "page_entries mismatch for node #{p.uid}"
end
begin
@f.seek(p.uid * @page_size * 8)
@f.write(p.values.pack('Q*'))
rescue IOError => e
PEROBS.log.fatal "Cannot write cache file #{@file_name}: #{e.message}"
end
end | ruby | def save_page(p)
if p.record.page_entries != p.values.length
raise RuntimeError, "page_entries mismatch for node #{p.uid}"
end
begin
@f.seek(p.uid * @page_size * 8)
@f.write(p.values.pack('Q*'))
rescue IOError => e
PEROBS.log.fatal "Cannot write cache file #{@file_name}: #{e.message}"
end
end | [
"def",
"save_page",
"(",
"p",
")",
"if",
"p",
".",
"record",
".",
"page_entries",
"!=",
"p",
".",
"values",
".",
"length",
"raise",
"RuntimeError",
",",
"\"page_entries mismatch for node #{p.uid}\"",
"end",
"begin",
"@f",
".",
"seek",
"(",
"p",
".",
"uid",
"*",
"@page_size",
"*",
"8",
")",
"@f",
".",
"write",
"(",
"p",
".",
"values",
".",
"pack",
"(",
"'Q*'",
")",
")",
"rescue",
"IOError",
"=>",
"e",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Cannot write cache file #{@file_name}: #{e.message}\"",
"end",
"end"
] | Save the given IDListPage into the cache file.
@param p [IDListPage] page to store | [
"Save",
"the",
"given",
"IDListPage",
"into",
"the",
"cache",
"file",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDListPageFile.rb#L144-L154 |
4,349 | THECALLR/sdk-ruby | lib/callr.rb | CALLR.Api.send | def send(method, params = [], id = nil)
check_auth()
json = {
:id => id.nil? || id.is_a?(Integer) == false ? rand(999 - 100) + 100 : id,
:jsonrpc => "2.0",
:method => method,
:params => params.is_a?(Array) ? params : []
}.to_json
uri = URI.parse(API_URL)
http = http_or_http_proxy(uri)
req = Net::HTTP::Post.new(uri.request_uri, @headers)
req.basic_auth(@login, @password)
req.add_field('User-Agent', "sdk=RUBY; sdk-version=#{SDK_VERSION}; lang-version=#{RUBY_VERSION}; platform=#{RUBY_PLATFORM}")
req.add_field('CALLR-Login-As', @login_as) unless @login_as.to_s.empty?
begin
res = http.request(req, json)
if res.code.to_i != 200
raise CallrException.new("HTTP_CODE_ERROR", -1, {:http_code => res.code.to_i, :http_message => res.message})
end
return parse_response(res)
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Errno::ETIMEDOUT, Errno::ECONNREFUSED,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
raise CallrException.new("HTTP_EXCEPTION", -2, {:exception => e})
end
end | ruby | def send(method, params = [], id = nil)
check_auth()
json = {
:id => id.nil? || id.is_a?(Integer) == false ? rand(999 - 100) + 100 : id,
:jsonrpc => "2.0",
:method => method,
:params => params.is_a?(Array) ? params : []
}.to_json
uri = URI.parse(API_URL)
http = http_or_http_proxy(uri)
req = Net::HTTP::Post.new(uri.request_uri, @headers)
req.basic_auth(@login, @password)
req.add_field('User-Agent', "sdk=RUBY; sdk-version=#{SDK_VERSION}; lang-version=#{RUBY_VERSION}; platform=#{RUBY_PLATFORM}")
req.add_field('CALLR-Login-As', @login_as) unless @login_as.to_s.empty?
begin
res = http.request(req, json)
if res.code.to_i != 200
raise CallrException.new("HTTP_CODE_ERROR", -1, {:http_code => res.code.to_i, :http_message => res.message})
end
return parse_response(res)
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Errno::ETIMEDOUT, Errno::ECONNREFUSED,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
raise CallrException.new("HTTP_EXCEPTION", -2, {:exception => e})
end
end | [
"def",
"send",
"(",
"method",
",",
"params",
"=",
"[",
"]",
",",
"id",
"=",
"nil",
")",
"check_auth",
"(",
")",
"json",
"=",
"{",
":id",
"=>",
"id",
".",
"nil?",
"||",
"id",
".",
"is_a?",
"(",
"Integer",
")",
"==",
"false",
"?",
"rand",
"(",
"999",
"-",
"100",
")",
"+",
"100",
":",
"id",
",",
":jsonrpc",
"=>",
"\"2.0\"",
",",
":method",
"=>",
"method",
",",
":params",
"=>",
"params",
".",
"is_a?",
"(",
"Array",
")",
"?",
"params",
":",
"[",
"]",
"}",
".",
"to_json",
"uri",
"=",
"URI",
".",
"parse",
"(",
"API_URL",
")",
"http",
"=",
"http_or_http_proxy",
"(",
"uri",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"request_uri",
",",
"@headers",
")",
"req",
".",
"basic_auth",
"(",
"@login",
",",
"@password",
")",
"req",
".",
"add_field",
"(",
"'User-Agent'",
",",
"\"sdk=RUBY; sdk-version=#{SDK_VERSION}; lang-version=#{RUBY_VERSION}; platform=#{RUBY_PLATFORM}\"",
")",
"req",
".",
"add_field",
"(",
"'CALLR-Login-As'",
",",
"@login_as",
")",
"unless",
"@login_as",
".",
"to_s",
".",
"empty?",
"begin",
"res",
"=",
"http",
".",
"request",
"(",
"req",
",",
"json",
")",
"if",
"res",
".",
"code",
".",
"to_i",
"!=",
"200",
"raise",
"CallrException",
".",
"new",
"(",
"\"HTTP_CODE_ERROR\"",
",",
"-",
"1",
",",
"{",
":http_code",
"=>",
"res",
".",
"code",
".",
"to_i",
",",
":http_message",
"=>",
"res",
".",
"message",
"}",
")",
"end",
"return",
"parse_response",
"(",
"res",
")",
"rescue",
"Timeout",
"::",
"Error",
",",
"Errno",
"::",
"EINVAL",
",",
"Errno",
"::",
"ECONNRESET",
",",
"EOFError",
",",
"Errno",
"::",
"ETIMEDOUT",
",",
"Errno",
"::",
"ECONNREFUSED",
",",
"Net",
"::",
"HTTPBadResponse",
",",
"Net",
"::",
"HTTPHeaderSyntaxError",
",",
"Net",
"::",
"ProtocolError",
"=>",
"e",
"raise",
"CallrException",
".",
"new",
"(",
"\"HTTP_EXCEPTION\"",
",",
"-",
"2",
",",
"{",
":exception",
"=>",
"e",
"}",
")",
"end",
"end"
] | Send a request to CALLR webservice | [
"Send",
"a",
"request",
"to",
"CALLR",
"webservice"
] | e10f5fe527ab378b4b298045b0c49397b8f8df8b | https://github.com/THECALLR/sdk-ruby/blob/e10f5fe527ab378b4b298045b0c49397b8f8df8b/lib/callr.rb#L80-L108 |
4,350 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.write_object | def write_object(id, raw)
if @entries.length > @btreedb.max_blob_size
# The blob has reached the maximum size. Replace the blob with a BTree
# node directory and distribute the blob entires into the sub-blobs of
# the new BTree node.
split_blob
# Insert the passed object into the newly created BTree node.
@btreedb.put_raw_object(raw, id)
else
bytes = raw.bytesize
crc32 = Zlib.crc32(raw, 0)
start_address = reserve_bytes(id, bytes, crc32)
if write_to_blobs_file(raw, start_address) != bytes
PEROBS.log.fatal 'Object length does not match written bytes'
end
write_index
end
end | ruby | def write_object(id, raw)
if @entries.length > @btreedb.max_blob_size
# The blob has reached the maximum size. Replace the blob with a BTree
# node directory and distribute the blob entires into the sub-blobs of
# the new BTree node.
split_blob
# Insert the passed object into the newly created BTree node.
@btreedb.put_raw_object(raw, id)
else
bytes = raw.bytesize
crc32 = Zlib.crc32(raw, 0)
start_address = reserve_bytes(id, bytes, crc32)
if write_to_blobs_file(raw, start_address) != bytes
PEROBS.log.fatal 'Object length does not match written bytes'
end
write_index
end
end | [
"def",
"write_object",
"(",
"id",
",",
"raw",
")",
"if",
"@entries",
".",
"length",
">",
"@btreedb",
".",
"max_blob_size",
"# The blob has reached the maximum size. Replace the blob with a BTree",
"# node directory and distribute the blob entires into the sub-blobs of",
"# the new BTree node.",
"split_blob",
"# Insert the passed object into the newly created BTree node.",
"@btreedb",
".",
"put_raw_object",
"(",
"raw",
",",
"id",
")",
"else",
"bytes",
"=",
"raw",
".",
"bytesize",
"crc32",
"=",
"Zlib",
".",
"crc32",
"(",
"raw",
",",
"0",
")",
"start_address",
"=",
"reserve_bytes",
"(",
"id",
",",
"bytes",
",",
"crc32",
")",
"if",
"write_to_blobs_file",
"(",
"raw",
",",
"start_address",
")",
"!=",
"bytes",
"PEROBS",
".",
"log",
".",
"fatal",
"'Object length does not match written bytes'",
"end",
"write_index",
"end",
"end"
] | Create a new BTreeBlob object.
@param dir [String] Fully qualified directory name
@param btreedb [BTreeDB] Reference to the DB that owns this blob
Write the given bytes with the given ID into the DB.
@param id [Integer] ID
@param raw [String] sequence of bytes | [
"Create",
"a",
"new",
"BTreeBlob",
"object",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L70-L87 |
4,351 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.mark | def mark(id)
found = false
@entries.each do |entry|
if entry[ID] == id
entry[MARKED] = 1
found = true
break
end
end
unless found
PEROBS.log.fatal "Cannot find an entry for ID #{'%016X' % id} " +
"#{id} to mark"
end
write_index
end | ruby | def mark(id)
found = false
@entries.each do |entry|
if entry[ID] == id
entry[MARKED] = 1
found = true
break
end
end
unless found
PEROBS.log.fatal "Cannot find an entry for ID #{'%016X' % id} " +
"#{id} to mark"
end
write_index
end | [
"def",
"mark",
"(",
"id",
")",
"found",
"=",
"false",
"@entries",
".",
"each",
"do",
"|",
"entry",
"|",
"if",
"entry",
"[",
"ID",
"]",
"==",
"id",
"entry",
"[",
"MARKED",
"]",
"=",
"1",
"found",
"=",
"true",
"break",
"end",
"end",
"unless",
"found",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Cannot find an entry for ID #{'%016X' % id} \"",
"+",
"\"#{id} to mark\"",
"end",
"write_index",
"end"
] | Set a mark on the entry with the given ID.
@param id [Integer] ID of the entry | [
"Set",
"a",
"mark",
"on",
"the",
"entry",
"with",
"the",
"given",
"ID",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L113-L129 |
4,352 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.is_marked? | def is_marked?(id, ignore_errors = false)
@entries.each do |entry|
return entry[MARKED] != 0 if entry[ID] == id
end
return false if ignore_errors
PEROBS.log.fatal "Cannot find an entry for ID #{'%016X' % id} to check"
end | ruby | def is_marked?(id, ignore_errors = false)
@entries.each do |entry|
return entry[MARKED] != 0 if entry[ID] == id
end
return false if ignore_errors
PEROBS.log.fatal "Cannot find an entry for ID #{'%016X' % id} to check"
end | [
"def",
"is_marked?",
"(",
"id",
",",
"ignore_errors",
"=",
"false",
")",
"@entries",
".",
"each",
"do",
"|",
"entry",
"|",
"return",
"entry",
"[",
"MARKED",
"]",
"!=",
"0",
"if",
"entry",
"[",
"ID",
"]",
"==",
"id",
"end",
"return",
"false",
"if",
"ignore_errors",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Cannot find an entry for ID #{'%016X' % id} to check\"",
"end"
] | Check if the entry for a given ID is marked.
@param id [Integer] ID of the entry
@param ignore_errors [Boolean] If set to true no errors will be raised
for non-existing objects.
@return [TrueClass or FalseClass] true if marked, false otherwise | [
"Check",
"if",
"the",
"entry",
"for",
"a",
"given",
"ID",
"is",
"marked",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L136-L143 |
4,353 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.delete_unmarked_entries | def delete_unmarked_entries
deleted_ids = []
# First remove the entry from the hash table.
@entries_by_id.delete_if do |id, e|
if e[MARKED] == 0
deleted_ids << id
true
else
false
end
end
# Then delete the entry itself.
@entries.delete_if { |e| e[MARKED] == 0 }
write_index
deleted_ids
end | ruby | def delete_unmarked_entries
deleted_ids = []
# First remove the entry from the hash table.
@entries_by_id.delete_if do |id, e|
if e[MARKED] == 0
deleted_ids << id
true
else
false
end
end
# Then delete the entry itself.
@entries.delete_if { |e| e[MARKED] == 0 }
write_index
deleted_ids
end | [
"def",
"delete_unmarked_entries",
"deleted_ids",
"=",
"[",
"]",
"# First remove the entry from the hash table.",
"@entries_by_id",
".",
"delete_if",
"do",
"|",
"id",
",",
"e",
"|",
"if",
"e",
"[",
"MARKED",
"]",
"==",
"0",
"deleted_ids",
"<<",
"id",
"true",
"else",
"false",
"end",
"end",
"# Then delete the entry itself.",
"@entries",
".",
"delete_if",
"{",
"|",
"e",
"|",
"e",
"[",
"MARKED",
"]",
"==",
"0",
"}",
"write_index",
"deleted_ids",
"end"
] | Remove all entries from the index that have not been marked.
@return [Array] List of deleted object IDs. | [
"Remove",
"all",
"entries",
"from",
"the",
"index",
"that",
"have",
"not",
"been",
"marked",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L147-L163 |
4,354 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.check | def check(repair = false)
# Determine size of the data blobs file.
data_file_size = File.exist?(@blobs_file_name) ?
File.size(@blobs_file_name) : 0
next_start = 0
prev_entry = nil
@entries.each do |entry|
# Entries should never overlap
if prev_entry && next_start > entry[START]
PEROBS.log.fatal
"#{@dir}: Index entries are overlapping\n" +
"ID: #{'%016X' % prev_entry[ID]} " +
"Start: #{prev_entry[START]} " +
"Bytes: #{prev_entry[BYTES]}\n" +
"ID: #{'%016X' % entry[ID]} Start: #{entry[START]} " +
"Bytes: #{entry[BYTES]}"
end
next_start = entry[START] + entry[BYTES]
# Entries must fit within the data file
if next_start > data_file_size
PEROBS.log.fatal
"#{@dir}: Entry for ID #{'%016X' % entry[ID]} " +
"goes beyond 'data' file " +
"size (#{data_file_size})\n" +
"ID: #{'%016X' % entry[ID]} Start: #{entry[START]} " +
"Bytes: #{entry[BYTES]}"
end
prev_entry = entry
end
true
end | ruby | def check(repair = false)
# Determine size of the data blobs file.
data_file_size = File.exist?(@blobs_file_name) ?
File.size(@blobs_file_name) : 0
next_start = 0
prev_entry = nil
@entries.each do |entry|
# Entries should never overlap
if prev_entry && next_start > entry[START]
PEROBS.log.fatal
"#{@dir}: Index entries are overlapping\n" +
"ID: #{'%016X' % prev_entry[ID]} " +
"Start: #{prev_entry[START]} " +
"Bytes: #{prev_entry[BYTES]}\n" +
"ID: #{'%016X' % entry[ID]} Start: #{entry[START]} " +
"Bytes: #{entry[BYTES]}"
end
next_start = entry[START] + entry[BYTES]
# Entries must fit within the data file
if next_start > data_file_size
PEROBS.log.fatal
"#{@dir}: Entry for ID #{'%016X' % entry[ID]} " +
"goes beyond 'data' file " +
"size (#{data_file_size})\n" +
"ID: #{'%016X' % entry[ID]} Start: #{entry[START]} " +
"Bytes: #{entry[BYTES]}"
end
prev_entry = entry
end
true
end | [
"def",
"check",
"(",
"repair",
"=",
"false",
")",
"# Determine size of the data blobs file.",
"data_file_size",
"=",
"File",
".",
"exist?",
"(",
"@blobs_file_name",
")",
"?",
"File",
".",
"size",
"(",
"@blobs_file_name",
")",
":",
"0",
"next_start",
"=",
"0",
"prev_entry",
"=",
"nil",
"@entries",
".",
"each",
"do",
"|",
"entry",
"|",
"# Entries should never overlap",
"if",
"prev_entry",
"&&",
"next_start",
">",
"entry",
"[",
"START",
"]",
"PEROBS",
".",
"log",
".",
"fatal",
"\"#{@dir}: Index entries are overlapping\\n\"",
"+",
"\"ID: #{'%016X' % prev_entry[ID]} \"",
"+",
"\"Start: #{prev_entry[START]} \"",
"+",
"\"Bytes: #{prev_entry[BYTES]}\\n\"",
"+",
"\"ID: #{'%016X' % entry[ID]} Start: #{entry[START]} \"",
"+",
"\"Bytes: #{entry[BYTES]}\"",
"end",
"next_start",
"=",
"entry",
"[",
"START",
"]",
"+",
"entry",
"[",
"BYTES",
"]",
"# Entries must fit within the data file",
"if",
"next_start",
">",
"data_file_size",
"PEROBS",
".",
"log",
".",
"fatal",
"\"#{@dir}: Entry for ID #{'%016X' % entry[ID]} \"",
"+",
"\"goes beyond 'data' file \"",
"+",
"\"size (#{data_file_size})\\n\"",
"+",
"\"ID: #{'%016X' % entry[ID]} Start: #{entry[START]} \"",
"+",
"\"Bytes: #{entry[BYTES]}\"",
"end",
"prev_entry",
"=",
"entry",
"end",
"true",
"end"
] | Run a basic consistency check.
@param repair [TrueClass/FalseClass] Not used right now
@return [TrueClass/FalseClass] Always true right now | [
"Run",
"a",
"basic",
"consistency",
"check",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L168-L202 |
4,355 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.write_to_blobs_file | def write_to_blobs_file(raw, address)
begin
File.write(@blobs_file_name, raw, address)
rescue IOError => e
PEROBS.log.fatal "Cannot write blobs file #{@blobs_file_name}: " +
e.message
end
end | ruby | def write_to_blobs_file(raw, address)
begin
File.write(@blobs_file_name, raw, address)
rescue IOError => e
PEROBS.log.fatal "Cannot write blobs file #{@blobs_file_name}: " +
e.message
end
end | [
"def",
"write_to_blobs_file",
"(",
"raw",
",",
"address",
")",
"begin",
"File",
".",
"write",
"(",
"@blobs_file_name",
",",
"raw",
",",
"address",
")",
"rescue",
"IOError",
"=>",
"e",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Cannot write blobs file #{@blobs_file_name}: \"",
"+",
"e",
".",
"message",
"end",
"end"
] | Write a string of bytes into the file at the given address.
@param raw [String] bytes to write
@param address [Integer] offset in the file
@return [Integer] number of bytes written | [
"Write",
"a",
"string",
"of",
"bytes",
"into",
"the",
"file",
"at",
"the",
"given",
"address",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L210-L217 |
4,356 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.read_from_blobs_file | def read_from_blobs_file(entry)
begin
raw = File.read(@blobs_file_name, entry[BYTES], entry[START])
rescue => e
PEROBS.log.fatal "Cannot read blobs file #{@blobs_file_name}: " +
e.message
end
if Zlib.crc32(raw, 0) != entry[CRC]
PEROBS.log.fatal "BTreeBlob for object #{entry[ID]} has been " +
"corrupted: Checksum mismatch"
end
raw
end | ruby | def read_from_blobs_file(entry)
begin
raw = File.read(@blobs_file_name, entry[BYTES], entry[START])
rescue => e
PEROBS.log.fatal "Cannot read blobs file #{@blobs_file_name}: " +
e.message
end
if Zlib.crc32(raw, 0) != entry[CRC]
PEROBS.log.fatal "BTreeBlob for object #{entry[ID]} has been " +
"corrupted: Checksum mismatch"
end
raw
end | [
"def",
"read_from_blobs_file",
"(",
"entry",
")",
"begin",
"raw",
"=",
"File",
".",
"read",
"(",
"@blobs_file_name",
",",
"entry",
"[",
"BYTES",
"]",
",",
"entry",
"[",
"START",
"]",
")",
"rescue",
"=>",
"e",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Cannot read blobs file #{@blobs_file_name}: \"",
"+",
"e",
".",
"message",
"end",
"if",
"Zlib",
".",
"crc32",
"(",
"raw",
",",
"0",
")",
"!=",
"entry",
"[",
"CRC",
"]",
"PEROBS",
".",
"log",
".",
"fatal",
"\"BTreeBlob for object #{entry[ID]} has been \"",
"+",
"\"corrupted: Checksum mismatch\"",
"end",
"raw",
"end"
] | Read _bytes_ bytes from the file starting at offset _address_.
@param entry [Array] Index entry for the object
@return [String] Raw bytes of the blob. | [
"Read",
"_bytes_",
"bytes",
"from",
"the",
"file",
"starting",
"at",
"offset",
"_address_",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L222-L235 |
4,357 | scrapper/perobs | lib/perobs/BTreeBlob.rb | PEROBS.BTreeBlob.reserve_bytes | def reserve_bytes(id, bytes, crc32)
# index of first blob after the last seen entry
end_of_last_entry = 0
# blob index of best fit segment
best_fit_start = nil
# best fir segment size in bytes
best_fit_bytes = nil
# Index where to insert the new entry. Append by default.
best_fit_index = -1
# If there is already an entry for an object with the _id_, we mark it
# for deletion.
entry_to_delete = nil
@entries.each.with_index do |entry, i|
if entry[ID] == id
# We've found an old entry for this ID. Mark it for deletion.
entry_to_delete = entry
next
end
gap = entry[START] - end_of_last_entry
if gap >= bytes &&
(best_fit_bytes.nil? || gap < best_fit_bytes)
# We've found a segment that fits the requested bytes and fits
# better than any previous find.
best_fit_start = end_of_last_entry
best_fit_bytes = gap
# The old entry gets deleted before the new one gets inserted. We
# need to correct the index appropriately.
best_fit_index = i - (entry_to_delete ? 1 : 0)
end
end_of_last_entry = entry[START] + entry[BYTES]
end
# Delete the old entry if requested.
@entries.delete(entry_to_delete) if entry_to_delete
# Create a new entry and insert it. The order must match the above
# defined constants!
# Object reads can trigger creation of new objects. As the marking
# process triggers reads as well, all newly created objects are always
# marked to prevent them from being collected right after creation.
entry = [ id, bytes, best_fit_start || end_of_last_entry, 1, crc32 ]
@entries.insert(best_fit_index, entry)
@entries_by_id[id] = entry
entry[START]
end | ruby | def reserve_bytes(id, bytes, crc32)
# index of first blob after the last seen entry
end_of_last_entry = 0
# blob index of best fit segment
best_fit_start = nil
# best fir segment size in bytes
best_fit_bytes = nil
# Index where to insert the new entry. Append by default.
best_fit_index = -1
# If there is already an entry for an object with the _id_, we mark it
# for deletion.
entry_to_delete = nil
@entries.each.with_index do |entry, i|
if entry[ID] == id
# We've found an old entry for this ID. Mark it for deletion.
entry_to_delete = entry
next
end
gap = entry[START] - end_of_last_entry
if gap >= bytes &&
(best_fit_bytes.nil? || gap < best_fit_bytes)
# We've found a segment that fits the requested bytes and fits
# better than any previous find.
best_fit_start = end_of_last_entry
best_fit_bytes = gap
# The old entry gets deleted before the new one gets inserted. We
# need to correct the index appropriately.
best_fit_index = i - (entry_to_delete ? 1 : 0)
end
end_of_last_entry = entry[START] + entry[BYTES]
end
# Delete the old entry if requested.
@entries.delete(entry_to_delete) if entry_to_delete
# Create a new entry and insert it. The order must match the above
# defined constants!
# Object reads can trigger creation of new objects. As the marking
# process triggers reads as well, all newly created objects are always
# marked to prevent them from being collected right after creation.
entry = [ id, bytes, best_fit_start || end_of_last_entry, 1, crc32 ]
@entries.insert(best_fit_index, entry)
@entries_by_id[id] = entry
entry[START]
end | [
"def",
"reserve_bytes",
"(",
"id",
",",
"bytes",
",",
"crc32",
")",
"# index of first blob after the last seen entry",
"end_of_last_entry",
"=",
"0",
"# blob index of best fit segment",
"best_fit_start",
"=",
"nil",
"# best fir segment size in bytes",
"best_fit_bytes",
"=",
"nil",
"# Index where to insert the new entry. Append by default.",
"best_fit_index",
"=",
"-",
"1",
"# If there is already an entry for an object with the _id_, we mark it",
"# for deletion.",
"entry_to_delete",
"=",
"nil",
"@entries",
".",
"each",
".",
"with_index",
"do",
"|",
"entry",
",",
"i",
"|",
"if",
"entry",
"[",
"ID",
"]",
"==",
"id",
"# We've found an old entry for this ID. Mark it for deletion.",
"entry_to_delete",
"=",
"entry",
"next",
"end",
"gap",
"=",
"entry",
"[",
"START",
"]",
"-",
"end_of_last_entry",
"if",
"gap",
">=",
"bytes",
"&&",
"(",
"best_fit_bytes",
".",
"nil?",
"||",
"gap",
"<",
"best_fit_bytes",
")",
"# We've found a segment that fits the requested bytes and fits",
"# better than any previous find.",
"best_fit_start",
"=",
"end_of_last_entry",
"best_fit_bytes",
"=",
"gap",
"# The old entry gets deleted before the new one gets inserted. We",
"# need to correct the index appropriately.",
"best_fit_index",
"=",
"i",
"-",
"(",
"entry_to_delete",
"?",
"1",
":",
"0",
")",
"end",
"end_of_last_entry",
"=",
"entry",
"[",
"START",
"]",
"+",
"entry",
"[",
"BYTES",
"]",
"end",
"# Delete the old entry if requested.",
"@entries",
".",
"delete",
"(",
"entry_to_delete",
")",
"if",
"entry_to_delete",
"# Create a new entry and insert it. The order must match the above",
"# defined constants!",
"# Object reads can trigger creation of new objects. As the marking",
"# process triggers reads as well, all newly created objects are always",
"# marked to prevent them from being collected right after creation.",
"entry",
"=",
"[",
"id",
",",
"bytes",
",",
"best_fit_start",
"||",
"end_of_last_entry",
",",
"1",
",",
"crc32",
"]",
"@entries",
".",
"insert",
"(",
"best_fit_index",
",",
"entry",
")",
"@entries_by_id",
"[",
"id",
"]",
"=",
"entry",
"entry",
"[",
"START",
"]",
"end"
] | Reserve the bytes needed for the specified number of bytes with the
given ID.
@param id [Integer] ID of the entry
@param bytes [Integer] number of bytes for this entry
@return [Integer] the start address of the reserved blob | [
"Reserve",
"the",
"bytes",
"needed",
"for",
"the",
"specified",
"number",
"of",
"bytes",
"with",
"the",
"given",
"ID",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTreeBlob.rb#L242-L289 |
4,358 | scrapper/perobs | lib/perobs/PersistentObjectCache.rb | PEROBS.PersistentObjectCache.get | def get(uid, ref = nil)
# First check if it's a modified object.
if (object = @modified_entries[uid])
return object
end
# Then check the unmodified object list.
if (object = @unmodified_entries[uid % @size]) && object.uid == uid
return object
end
# If we don't have it in memory we need to load it.
@klass::load(@collection, uid, ref)
end | ruby | def get(uid, ref = nil)
# First check if it's a modified object.
if (object = @modified_entries[uid])
return object
end
# Then check the unmodified object list.
if (object = @unmodified_entries[uid % @size]) && object.uid == uid
return object
end
# If we don't have it in memory we need to load it.
@klass::load(@collection, uid, ref)
end | [
"def",
"get",
"(",
"uid",
",",
"ref",
"=",
"nil",
")",
"# First check if it's a modified object.",
"if",
"(",
"object",
"=",
"@modified_entries",
"[",
"uid",
"]",
")",
"return",
"object",
"end",
"# Then check the unmodified object list.",
"if",
"(",
"object",
"=",
"@unmodified_entries",
"[",
"uid",
"%",
"@size",
"]",
")",
"&&",
"object",
".",
"uid",
"==",
"uid",
"return",
"object",
"end",
"# If we don't have it in memory we need to load it.",
"@klass",
"::",
"load",
"(",
"@collection",
",",
"uid",
",",
"ref",
")",
"end"
] | Retrieve a object reference from the cache.
@param uid [Integer] uid of the object to retrieve.
@param ref [Object] optional reference to be used by the load method | [
"Retrieve",
"a",
"object",
"reference",
"from",
"the",
"cache",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/PersistentObjectCache.rb#L84-L97 |
4,359 | scrapper/perobs | lib/perobs/PersistentObjectCache.rb | PEROBS.PersistentObjectCache.delete | def delete(uid)
@modified_entries.delete(uid)
index = uid % @size
if (object = @unmodified_entries[index]) && object.uid == uid
@unmodified_entries[index] = nil
end
end | ruby | def delete(uid)
@modified_entries.delete(uid)
index = uid % @size
if (object = @unmodified_entries[index]) && object.uid == uid
@unmodified_entries[index] = nil
end
end | [
"def",
"delete",
"(",
"uid",
")",
"@modified_entries",
".",
"delete",
"(",
"uid",
")",
"index",
"=",
"uid",
"%",
"@size",
"if",
"(",
"object",
"=",
"@unmodified_entries",
"[",
"index",
"]",
")",
"&&",
"object",
".",
"uid",
"==",
"uid",
"@unmodified_entries",
"[",
"index",
"]",
"=",
"nil",
"end",
"end"
] | Remove a object from the cache.
@param uid [Integer] unique ID of object to remove. | [
"Remove",
"a",
"object",
"from",
"the",
"cache",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/PersistentObjectCache.rb#L101-L108 |
4,360 | scrapper/perobs | lib/perobs/PersistentObjectCache.rb | PEROBS.PersistentObjectCache.flush | def flush(now = false)
if now || (@flush_counter -= 1) <= 0
@modified_entries.each do |id, object|
object.save
end
@modified_entries = ::Hash.new
@flush_counter = @flush_delay
end
@flush_times += 1
end | ruby | def flush(now = false)
if now || (@flush_counter -= 1) <= 0
@modified_entries.each do |id, object|
object.save
end
@modified_entries = ::Hash.new
@flush_counter = @flush_delay
end
@flush_times += 1
end | [
"def",
"flush",
"(",
"now",
"=",
"false",
")",
"if",
"now",
"||",
"(",
"@flush_counter",
"-=",
"1",
")",
"<=",
"0",
"@modified_entries",
".",
"each",
"do",
"|",
"id",
",",
"object",
"|",
"object",
".",
"save",
"end",
"@modified_entries",
"=",
"::",
"Hash",
".",
"new",
"@flush_counter",
"=",
"@flush_delay",
"end",
"@flush_times",
"+=",
"1",
"end"
] | Write all excess modified objects into the backing store. If now is true
all modified objects will be written.
@param now [Boolean] | [
"Write",
"all",
"excess",
"modified",
"objects",
"into",
"the",
"backing",
"store",
".",
"If",
"now",
"is",
"true",
"all",
"modified",
"objects",
"will",
"be",
"written",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/PersistentObjectCache.rb#L113-L122 |
4,361 | PublicHealthEngland/ndr_support | lib/ndr_support/utf8_encoding/control_characters.rb | UTF8Encoding.ControlCharacters.escape_control_chars_in_object! | def escape_control_chars_in_object!(object)
case object
when String
escape_control_chars!(object)
when Hash
escape_control_chars_in_hash!(object)
when Array
escape_control_chars_in_array!(object)
else
object
end
end | ruby | def escape_control_chars_in_object!(object)
case object
when String
escape_control_chars!(object)
when Hash
escape_control_chars_in_hash!(object)
when Array
escape_control_chars_in_array!(object)
else
object
end
end | [
"def",
"escape_control_chars_in_object!",
"(",
"object",
")",
"case",
"object",
"when",
"String",
"escape_control_chars!",
"(",
"object",
")",
"when",
"Hash",
"escape_control_chars_in_hash!",
"(",
"object",
")",
"when",
"Array",
"escape_control_chars_in_array!",
"(",
"object",
")",
"else",
"object",
"end",
"end"
] | Recursively escape any control characters in `object`. | [
"Recursively",
"escape",
"any",
"control",
"characters",
"in",
"object",
"."
] | 6daf98ca972e79de1c8457eb720f058b03ead21c | https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/utf8_encoding/control_characters.rb#L11-L22 |
4,362 | PublicHealthEngland/ndr_support | lib/ndr_support/utf8_encoding/control_characters.rb | UTF8Encoding.ControlCharacters.escape_control_chars! | def escape_control_chars!(string)
string.gsub!(CONTROL_CHARACTERS) do |character|
UTF8Encoding::REPLACEMENT_SCHEME[character]
end
string
end | ruby | def escape_control_chars!(string)
string.gsub!(CONTROL_CHARACTERS) do |character|
UTF8Encoding::REPLACEMENT_SCHEME[character]
end
string
end | [
"def",
"escape_control_chars!",
"(",
"string",
")",
"string",
".",
"gsub!",
"(",
"CONTROL_CHARACTERS",
")",
"do",
"|",
"character",
"|",
"UTF8Encoding",
"::",
"REPLACEMENT_SCHEME",
"[",
"character",
"]",
"end",
"string",
"end"
] | Escapes in-place any control characters in `string`, before returning it. | [
"Escapes",
"in",
"-",
"place",
"any",
"control",
"characters",
"in",
"string",
"before",
"returning",
"it",
"."
] | 6daf98ca972e79de1c8457eb720f058b03ead21c | https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/utf8_encoding/control_characters.rb#L30-L35 |
4,363 | ghempton/state_manager | lib/state_manager/state.rb | StateManager.State.find_states | def find_states(path)
state = self
parts = path.split('.')
ret = []
parts.each do |name|
state = state.states[name.to_sym]
ret << state
return unless state
end
ret
end | ruby | def find_states(path)
state = self
parts = path.split('.')
ret = []
parts.each do |name|
state = state.states[name.to_sym]
ret << state
return unless state
end
ret
end | [
"def",
"find_states",
"(",
"path",
")",
"state",
"=",
"self",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"ret",
"=",
"[",
"]",
"parts",
".",
"each",
"do",
"|",
"name",
"|",
"state",
"=",
"state",
".",
"states",
"[",
"name",
".",
"to_sym",
"]",
"ret",
"<<",
"state",
"return",
"unless",
"state",
"end",
"ret",
"end"
] | Find all the states along the path | [
"Find",
"all",
"the",
"states",
"along",
"the",
"path"
] | 0e10fbb3c4b7718aa6602e240f4d8adf9cd72008 | https://github.com/ghempton/state_manager/blob/0e10fbb3c4b7718aa6602e240f4d8adf9cd72008/lib/state_manager/state.rb#L108-L118 |
4,364 | ghempton/state_manager | lib/state_manager/state.rb | StateManager.State.initial_state | def initial_state
if state = self.class.specification.initial_state
find_state(state.to_s)
elsif leaf?
self
else
states.values.first.initial_state
end
end | ruby | def initial_state
if state = self.class.specification.initial_state
find_state(state.to_s)
elsif leaf?
self
else
states.values.first.initial_state
end
end | [
"def",
"initial_state",
"if",
"state",
"=",
"self",
".",
"class",
".",
"specification",
".",
"initial_state",
"find_state",
"(",
"state",
".",
"to_s",
")",
"elsif",
"leaf?",
"self",
"else",
"states",
".",
"values",
".",
"first",
".",
"initial_state",
"end",
"end"
] | If an initial state is not explicitly specified, we choose the first leaf
state | [
"If",
"an",
"initial",
"state",
"is",
"not",
"explicitly",
"specified",
"we",
"choose",
"the",
"first",
"leaf",
"state"
] | 0e10fbb3c4b7718aa6602e240f4d8adf9cd72008 | https://github.com/ghempton/state_manager/blob/0e10fbb3c4b7718aa6602e240f4d8adf9cd72008/lib/state_manager/state.rb#L132-L140 |
4,365 | scrapper/perobs | lib/perobs/BTree.rb | PEROBS.BTree.open | def open(file_must_exist = false)
if @dirty_flag.is_locked?
PEROBS.log.fatal "Index file #{@nodes.file_name} is already " +
"locked"
end
if file_must_exist && [email protected]_exist?
PEROBS.log.fatal "Index file #{@nodes.file_name} does not exist"
end
@node_cache.clear
@nodes.open
if @nodes.total_entries == 0
# We've created a new nodes file
node = BTreeNode::create(self)
else
# We are loading an existing tree.
node = BTreeNode::load_and_link(self, @nodes.first_entry)
@first_leaf = BTreeNode::load_and_link(
self, @nodes.get_custom_data('first_leaf'))
@last_leaf = BTreeNode::load_and_link(
self, @nodes.get_custom_data('last_leaf'))
end
set_root(node)
# Get the total number of entries that are stored in the tree.
@size = @nodes.get_custom_data('btree_size')
end | ruby | def open(file_must_exist = false)
if @dirty_flag.is_locked?
PEROBS.log.fatal "Index file #{@nodes.file_name} is already " +
"locked"
end
if file_must_exist && [email protected]_exist?
PEROBS.log.fatal "Index file #{@nodes.file_name} does not exist"
end
@node_cache.clear
@nodes.open
if @nodes.total_entries == 0
# We've created a new nodes file
node = BTreeNode::create(self)
else
# We are loading an existing tree.
node = BTreeNode::load_and_link(self, @nodes.first_entry)
@first_leaf = BTreeNode::load_and_link(
self, @nodes.get_custom_data('first_leaf'))
@last_leaf = BTreeNode::load_and_link(
self, @nodes.get_custom_data('last_leaf'))
end
set_root(node)
# Get the total number of entries that are stored in the tree.
@size = @nodes.get_custom_data('btree_size')
end | [
"def",
"open",
"(",
"file_must_exist",
"=",
"false",
")",
"if",
"@dirty_flag",
".",
"is_locked?",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Index file #{@nodes.file_name} is already \"",
"+",
"\"locked\"",
"end",
"if",
"file_must_exist",
"&&",
"!",
"@nodes",
".",
"file_exist?",
"PEROBS",
".",
"log",
".",
"fatal",
"\"Index file #{@nodes.file_name} does not exist\"",
"end",
"@node_cache",
".",
"clear",
"@nodes",
".",
"open",
"if",
"@nodes",
".",
"total_entries",
"==",
"0",
"# We've created a new nodes file",
"node",
"=",
"BTreeNode",
"::",
"create",
"(",
"self",
")",
"else",
"# We are loading an existing tree.",
"node",
"=",
"BTreeNode",
"::",
"load_and_link",
"(",
"self",
",",
"@nodes",
".",
"first_entry",
")",
"@first_leaf",
"=",
"BTreeNode",
"::",
"load_and_link",
"(",
"self",
",",
"@nodes",
".",
"get_custom_data",
"(",
"'first_leaf'",
")",
")",
"@last_leaf",
"=",
"BTreeNode",
"::",
"load_and_link",
"(",
"self",
",",
"@nodes",
".",
"get_custom_data",
"(",
"'last_leaf'",
")",
")",
"end",
"set_root",
"(",
"node",
")",
"# Get the total number of entries that are stored in the tree.",
"@size",
"=",
"@nodes",
".",
"get_custom_data",
"(",
"'btree_size'",
")",
"end"
] | Create a new BTree object.
@param dir [String] Directory to store the tree file
@param name [String] Base name of the BTree related files in 'dir'
@param order [Integer] The maximum number of keys per node. This number
must be odd and larger than 2 and smaller than 2**16 - 1.
@param progressmeter [ProgressMeter] reference to a ProgressMeter object
Open the tree file. | [
"Create",
"a",
"new",
"BTree",
"object",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTree.rb#L89-L116 |
4,366 | scrapper/perobs | lib/perobs/BTree.rb | PEROBS.BTree.check | def check(&block)
sync
return false unless @nodes.check
entries = 0
res = true
@progressmeter.start('Checking index structure', @size) do |pm|
res = @root.check do |k, v|
pm.update(entries += 1)
block_given? ? yield(k, v) : true
end
end
unless entries == @size
PEROBS.log.error "The BTree size (#{@size}) and the number of " +
"found entries (#{entries}) don't match"
return false
end
res
end | ruby | def check(&block)
sync
return false unless @nodes.check
entries = 0
res = true
@progressmeter.start('Checking index structure', @size) do |pm|
res = @root.check do |k, v|
pm.update(entries += 1)
block_given? ? yield(k, v) : true
end
end
unless entries == @size
PEROBS.log.error "The BTree size (#{@size}) and the number of " +
"found entries (#{entries}) don't match"
return false
end
res
end | [
"def",
"check",
"(",
"&",
"block",
")",
"sync",
"return",
"false",
"unless",
"@nodes",
".",
"check",
"entries",
"=",
"0",
"res",
"=",
"true",
"@progressmeter",
".",
"start",
"(",
"'Checking index structure'",
",",
"@size",
")",
"do",
"|",
"pm",
"|",
"res",
"=",
"@root",
".",
"check",
"do",
"|",
"k",
",",
"v",
"|",
"pm",
".",
"update",
"(",
"entries",
"+=",
"1",
")",
"block_given?",
"?",
"yield",
"(",
"k",
",",
"v",
")",
":",
"true",
"end",
"end",
"unless",
"entries",
"==",
"@size",
"PEROBS",
".",
"log",
".",
"error",
"\"The BTree size (#{@size}) and the number of \"",
"+",
"\"found entries (#{entries}) don't match\"",
"return",
"false",
"end",
"res",
"end"
] | Check if the tree file contains any errors.
@return [Boolean] true if no erros were found, false otherwise | [
"Check",
"if",
"the",
"tree",
"file",
"contains",
"any",
"errors",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTree.rb#L163-L183 |
4,367 | scrapper/perobs | lib/perobs/BTree.rb | PEROBS.BTree.remove | def remove(key)
@size -= 1 unless (removed_value = @root.remove(key)).nil?
# Check if the root node only contains one child link after the delete
# operation. Then we can delete that node and pull the tree one level
# up. This could happen for a sequence of nodes that all got merged to
# single child nodes.
while [email protected]_leaf && @root.children.size == 1
old_root = @root
set_root(@root.children.first)
@root.parent = nil
delete_node(old_root.node_address)
end
@node_cache.flush
removed_value
end | ruby | def remove(key)
@size -= 1 unless (removed_value = @root.remove(key)).nil?
# Check if the root node only contains one child link after the delete
# operation. Then we can delete that node and pull the tree one level
# up. This could happen for a sequence of nodes that all got merged to
# single child nodes.
while [email protected]_leaf && @root.children.size == 1
old_root = @root
set_root(@root.children.first)
@root.parent = nil
delete_node(old_root.node_address)
end
@node_cache.flush
removed_value
end | [
"def",
"remove",
"(",
"key",
")",
"@size",
"-=",
"1",
"unless",
"(",
"removed_value",
"=",
"@root",
".",
"remove",
"(",
"key",
")",
")",
".",
"nil?",
"# Check if the root node only contains one child link after the delete",
"# operation. Then we can delete that node and pull the tree one level",
"# up. This could happen for a sequence of nodes that all got merged to",
"# single child nodes.",
"while",
"!",
"@root",
".",
"is_leaf",
"&&",
"@root",
".",
"children",
".",
"size",
"==",
"1",
"old_root",
"=",
"@root",
"set_root",
"(",
"@root",
".",
"children",
".",
"first",
")",
"@root",
".",
"parent",
"=",
"nil",
"delete_node",
"(",
"old_root",
".",
"node_address",
")",
"end",
"@node_cache",
".",
"flush",
"removed_value",
"end"
] | Find and remove the value associated with the given key. If no entry was
found, return nil, otherwise the found value. | [
"Find",
"and",
"remove",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
".",
"If",
"no",
"entry",
"was",
"found",
"return",
"nil",
"otherwise",
"the",
"found",
"value",
"."
] | 1c9327656912cf96683849f92d260546af856adf | https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BTree.rb#L225-L241 |
4,368 | proglottis/glicko2 | lib/glicko2/rater.rb | Glicko2.Rater.add | def add(other_rating, score)
g, e = other_rating.gravity_expected_score(rating.mean)
@v_pre += g**2 * e * (1 - e)
@delta_pre += g * (score - e)
end | ruby | def add(other_rating, score)
g, e = other_rating.gravity_expected_score(rating.mean)
@v_pre += g**2 * e * (1 - e)
@delta_pre += g * (score - e)
end | [
"def",
"add",
"(",
"other_rating",
",",
"score",
")",
"g",
",",
"e",
"=",
"other_rating",
".",
"gravity_expected_score",
"(",
"rating",
".",
"mean",
")",
"@v_pre",
"+=",
"g",
"**",
"2",
"*",
"e",
"*",
"(",
"1",
"-",
"e",
")",
"@delta_pre",
"+=",
"g",
"*",
"(",
"score",
"-",
"e",
")",
"end"
] | Add an outcome against the rating | [
"Add",
"an",
"outcome",
"against",
"the",
"rating"
] | 8ede9a758a1a35b2bc5e6d4706aad856ec8f7812 | https://github.com/proglottis/glicko2/blob/8ede9a758a1a35b2bc5e6d4706aad856ec8f7812/lib/glicko2/rater.rb#L13-L17 |
4,369 | proglottis/glicko2 | lib/glicko2/rater.rb | Glicko2.Rater.rate | def rate(tau)
v = @v_pre**-1
delta2 = (@delta_pre * v)**2
sd2 = rating.sd**2
a = Math.log(rating.volatility**2)
if v.finite?
f = lambda do |x|
expX = Math.exp(x)
(expX * (delta2 - sd2 - v - expX)) / (2 * (sd2 + v + expX)**2) - (x - a) / tau**2
end
if delta2 > sd2 + v
b = Math.log(delta2 - sd2 - v)
else
k = 1
k += 1 while f.call(a - k * tau) < 0
b = a - k * tau
end
a = Util.illinois_method(a, b, &f)
end
volatility = Math.exp(a / 2.0)
sd_pre = Math.sqrt(sd2 + volatility**2)
sd = 1 / Math.sqrt(1.0 / sd_pre**2 + 1 / v)
mean = rating.mean + sd**2 * @delta_pre
Rating.new(mean, sd, volatility)
end | ruby | def rate(tau)
v = @v_pre**-1
delta2 = (@delta_pre * v)**2
sd2 = rating.sd**2
a = Math.log(rating.volatility**2)
if v.finite?
f = lambda do |x|
expX = Math.exp(x)
(expX * (delta2 - sd2 - v - expX)) / (2 * (sd2 + v + expX)**2) - (x - a) / tau**2
end
if delta2 > sd2 + v
b = Math.log(delta2 - sd2 - v)
else
k = 1
k += 1 while f.call(a - k * tau) < 0
b = a - k * tau
end
a = Util.illinois_method(a, b, &f)
end
volatility = Math.exp(a / 2.0)
sd_pre = Math.sqrt(sd2 + volatility**2)
sd = 1 / Math.sqrt(1.0 / sd_pre**2 + 1 / v)
mean = rating.mean + sd**2 * @delta_pre
Rating.new(mean, sd, volatility)
end | [
"def",
"rate",
"(",
"tau",
")",
"v",
"=",
"@v_pre",
"**",
"-",
"1",
"delta2",
"=",
"(",
"@delta_pre",
"*",
"v",
")",
"**",
"2",
"sd2",
"=",
"rating",
".",
"sd",
"**",
"2",
"a",
"=",
"Math",
".",
"log",
"(",
"rating",
".",
"volatility",
"**",
"2",
")",
"if",
"v",
".",
"finite?",
"f",
"=",
"lambda",
"do",
"|",
"x",
"|",
"expX",
"=",
"Math",
".",
"exp",
"(",
"x",
")",
"(",
"expX",
"*",
"(",
"delta2",
"-",
"sd2",
"-",
"v",
"-",
"expX",
")",
")",
"/",
"(",
"2",
"*",
"(",
"sd2",
"+",
"v",
"+",
"expX",
")",
"**",
"2",
")",
"-",
"(",
"x",
"-",
"a",
")",
"/",
"tau",
"**",
"2",
"end",
"if",
"delta2",
">",
"sd2",
"+",
"v",
"b",
"=",
"Math",
".",
"log",
"(",
"delta2",
"-",
"sd2",
"-",
"v",
")",
"else",
"k",
"=",
"1",
"k",
"+=",
"1",
"while",
"f",
".",
"call",
"(",
"a",
"-",
"k",
"*",
"tau",
")",
"<",
"0",
"b",
"=",
"a",
"-",
"k",
"*",
"tau",
"end",
"a",
"=",
"Util",
".",
"illinois_method",
"(",
"a",
",",
"b",
",",
"f",
")",
"end",
"volatility",
"=",
"Math",
".",
"exp",
"(",
"a",
"/",
"2.0",
")",
"sd_pre",
"=",
"Math",
".",
"sqrt",
"(",
"sd2",
"+",
"volatility",
"**",
"2",
")",
"sd",
"=",
"1",
"/",
"Math",
".",
"sqrt",
"(",
"1.0",
"/",
"sd_pre",
"**",
"2",
"+",
"1",
"/",
"v",
")",
"mean",
"=",
"rating",
".",
"mean",
"+",
"sd",
"**",
"2",
"*",
"@delta_pre",
"Rating",
".",
"new",
"(",
"mean",
",",
"sd",
",",
"volatility",
")",
"end"
] | Rate calculates Rating as at the start of the following period based on game outcomes | [
"Rate",
"calculates",
"Rating",
"as",
"at",
"the",
"start",
"of",
"the",
"following",
"period",
"based",
"on",
"game",
"outcomes"
] | 8ede9a758a1a35b2bc5e6d4706aad856ec8f7812 | https://github.com/proglottis/glicko2/blob/8ede9a758a1a35b2bc5e6d4706aad856ec8f7812/lib/glicko2/rater.rb#L20-L44 |
4,370 | kristianmandrup/schemaker | lib/schemaker/models.rb | Schemaker.Models.configure | def configure
return quick_join if !join_model
[subject_model, object_model, join_model].compact.each do |model|
model.configure
end
end | ruby | def configure
return quick_join if !join_model
[subject_model, object_model, join_model].compact.each do |model|
model.configure
end
end | [
"def",
"configure",
"return",
"quick_join",
"if",
"!",
"join_model",
"[",
"subject_model",
",",
"object_model",
",",
"join_model",
"]",
".",
"compact",
".",
"each",
"do",
"|",
"model",
"|",
"model",
".",
"configure",
"end",
"end"
] | configure each model in turn | [
"configure",
"each",
"model",
"in",
"turn"
] | 47399410cc6785291c656cec6cc2b9aa47f3652a | https://github.com/kristianmandrup/schemaker/blob/47399410cc6785291c656cec6cc2b9aa47f3652a/lib/schemaker/models.rb#L47-L52 |
4,371 | kristianmandrup/schemaker | lib/schemaker/models.rb | Schemaker.Models.get_class | def get_class type
case type
when Class
type
when BaseModel
type.my_class
when String, Symbol
return get_class send("#{type}_model") if [:subject, :object, :join].include?(type.to_sym)
type.to_s.constantize
else
raise "Can't determine a class from: #{type}"
end
end | ruby | def get_class type
case type
when Class
type
when BaseModel
type.my_class
when String, Symbol
return get_class send("#{type}_model") if [:subject, :object, :join].include?(type.to_sym)
type.to_s.constantize
else
raise "Can't determine a class from: #{type}"
end
end | [
"def",
"get_class",
"type",
"case",
"type",
"when",
"Class",
"type",
"when",
"BaseModel",
"type",
".",
"my_class",
"when",
"String",
",",
"Symbol",
"return",
"get_class",
"send",
"(",
"\"#{type}_model\"",
")",
"if",
"[",
":subject",
",",
":object",
",",
":join",
"]",
".",
"include?",
"(",
"type",
".",
"to_sym",
")",
"type",
".",
"to_s",
".",
"constantize",
"else",
"raise",
"\"Can't determine a class from: #{type}\"",
"end",
"end"
] | retrieves a given Class ie. a type of model
@param [Class, String, Symbol, BaseModel] which class to get
@return [Class] the Class (model) of interest | [
"retrieves",
"a",
"given",
"Class",
"ie",
".",
"a",
"type",
"of",
"model"
] | 47399410cc6785291c656cec6cc2b9aa47f3652a | https://github.com/kristianmandrup/schemaker/blob/47399410cc6785291c656cec6cc2b9aa47f3652a/lib/schemaker/models.rb#L84-L96 |
4,372 | jcmuller/build_status_server | lib/build_status_server/config.rb | BuildStatusServer.Config.load_config_file | def load_config_file(config_file = nil)
curated_file = nil
if config_file
f = File.expand_path(config_file)
if File.exists?(f)
curated_file = f
else
raise "Supplied config file (#{config_file}) doesn't seem to exist"
end
else
locations_to_try.each do |possible_conf_file|
f = File.expand_path(possible_conf_file)
if File.exists?(f)
curated_file = f
break
end
end
if curated_file.nil?
show_config_file_suggestion
return YAML.load(get_example_config)
end
end
YAML.load_file(curated_file).tap do |config|
raise "This is an invalid configuration file!" unless config.class == Hash
end
end | ruby | def load_config_file(config_file = nil)
curated_file = nil
if config_file
f = File.expand_path(config_file)
if File.exists?(f)
curated_file = f
else
raise "Supplied config file (#{config_file}) doesn't seem to exist"
end
else
locations_to_try.each do |possible_conf_file|
f = File.expand_path(possible_conf_file)
if File.exists?(f)
curated_file = f
break
end
end
if curated_file.nil?
show_config_file_suggestion
return YAML.load(get_example_config)
end
end
YAML.load_file(curated_file).tap do |config|
raise "This is an invalid configuration file!" unless config.class == Hash
end
end | [
"def",
"load_config_file",
"(",
"config_file",
"=",
"nil",
")",
"curated_file",
"=",
"nil",
"if",
"config_file",
"f",
"=",
"File",
".",
"expand_path",
"(",
"config_file",
")",
"if",
"File",
".",
"exists?",
"(",
"f",
")",
"curated_file",
"=",
"f",
"else",
"raise",
"\"Supplied config file (#{config_file}) doesn't seem to exist\"",
"end",
"else",
"locations_to_try",
".",
"each",
"do",
"|",
"possible_conf_file",
"|",
"f",
"=",
"File",
".",
"expand_path",
"(",
"possible_conf_file",
")",
"if",
"File",
".",
"exists?",
"(",
"f",
")",
"curated_file",
"=",
"f",
"break",
"end",
"end",
"if",
"curated_file",
".",
"nil?",
"show_config_file_suggestion",
"return",
"YAML",
".",
"load",
"(",
"get_example_config",
")",
"end",
"end",
"YAML",
".",
"load_file",
"(",
"curated_file",
")",
".",
"tap",
"do",
"|",
"config",
"|",
"raise",
"\"This is an invalid configuration file!\"",
"unless",
"config",
".",
"class",
"==",
"Hash",
"end",
"end"
] | This is responsible to return a hash with the contents of a YAML file | [
"This",
"is",
"responsible",
"to",
"return",
"a",
"hash",
"with",
"the",
"contents",
"of",
"a",
"YAML",
"file"
] | 1a8329512ef6ee6dd01e886f5c7b68d0e22523df | https://github.com/jcmuller/build_status_server/blob/1a8329512ef6ee6dd01e886f5c7b68d0e22523df/lib/build_status_server/config.rb#L29-L58 |
4,373 | thelabtech/questionnaire | app/helpers/qe/answer_pages_helper.rb | Qe.AnswerPagesHelper.li_page_active_if | def li_page_active_if(condition, attributes = {}, &block)
if condition
attributes[:class] ||= ''
attributes[:class] += " active"
end
content_tag("li", attributes, &block)
end | ruby | def li_page_active_if(condition, attributes = {}, &block)
if condition
attributes[:class] ||= ''
attributes[:class] += " active"
end
content_tag("li", attributes, &block)
end | [
"def",
"li_page_active_if",
"(",
"condition",
",",
"attributes",
"=",
"{",
"}",
",",
"&",
"block",
")",
"if",
"condition",
"attributes",
"[",
":class",
"]",
"||=",
"''",
"attributes",
"[",
":class",
"]",
"+=",
"\" active\"",
"end",
"content_tag",
"(",
"\"li\"",
",",
"attributes",
",",
"block",
")",
"end"
] | page sidebar navigation | [
"page",
"sidebar",
"navigation"
] | 02eb47cbcda8cca28a5db78e18623d0957aa2c9b | https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/helpers/qe/answer_pages_helper.rb#L7-L13 |
4,374 | sleewoo/minispec | lib/minispec/api/class/after.rb | MiniSpec.ClassAPI.after | def after *matchers, &proc
proc || raise(ArgumentError, 'block is missing')
matchers.flatten!
matchers = [:*] if matchers.empty?
return if after?.find {|x| x[0] == matchers && x[1].source_location == proc.source_location}
after?.push([matchers, proc])
end | ruby | def after *matchers, &proc
proc || raise(ArgumentError, 'block is missing')
matchers.flatten!
matchers = [:*] if matchers.empty?
return if after?.find {|x| x[0] == matchers && x[1].source_location == proc.source_location}
after?.push([matchers, proc])
end | [
"def",
"after",
"*",
"matchers",
",",
"&",
"proc",
"proc",
"||",
"raise",
"(",
"ArgumentError",
",",
"'block is missing'",
")",
"matchers",
".",
"flatten!",
"matchers",
"=",
"[",
":*",
"]",
"if",
"matchers",
".",
"empty?",
"return",
"if",
"after?",
".",
"find",
"{",
"|",
"x",
"|",
"x",
"[",
"0",
"]",
"==",
"matchers",
"&&",
"x",
"[",
"1",
"]",
".",
"source_location",
"==",
"proc",
".",
"source_location",
"}",
"after?",
".",
"push",
"(",
"[",
"matchers",
",",
"proc",
"]",
")",
"end"
] | same as `before` except it will run after matched tests.
@note `after` hooks will run even on failed tests.
however it wont run if some exception arise inside test. | [
"same",
"as",
"before",
"except",
"it",
"will",
"run",
"after",
"matched",
"tests",
"."
] | 6dcdacd041cc031c21f2fe70b6e5b22c6af636c5 | https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/api/class/after.rb#L7-L13 |
4,375 | rossmeissl/bombshell | lib/bombshell/shell.rb | Bombshell.Shell._prompt | def _prompt
if self.class.bombshell_prompt.is_a? String
self.class.bombshell_prompt
elsif self.class.bombshell_prompt.is_a? Proc and self.class.bombshell_prompt.arity == 1
self.class.bombshell_prompt.call self
elsif self.class.bombshell_prompt.is_a? Proc
self.class.bombshell_prompt.call
else
'[Bombshell]'
end
end | ruby | def _prompt
if self.class.bombshell_prompt.is_a? String
self.class.bombshell_prompt
elsif self.class.bombshell_prompt.is_a? Proc and self.class.bombshell_prompt.arity == 1
self.class.bombshell_prompt.call self
elsif self.class.bombshell_prompt.is_a? Proc
self.class.bombshell_prompt.call
else
'[Bombshell]'
end
end | [
"def",
"_prompt",
"if",
"self",
".",
"class",
".",
"bombshell_prompt",
".",
"is_a?",
"String",
"self",
".",
"class",
".",
"bombshell_prompt",
"elsif",
"self",
".",
"class",
".",
"bombshell_prompt",
".",
"is_a?",
"Proc",
"and",
"self",
".",
"class",
".",
"bombshell_prompt",
".",
"arity",
"==",
"1",
"self",
".",
"class",
".",
"bombshell_prompt",
".",
"call",
"self",
"elsif",
"self",
".",
"class",
".",
"bombshell_prompt",
".",
"is_a?",
"Proc",
"self",
".",
"class",
".",
"bombshell_prompt",
".",
"call",
"else",
"'[Bombshell]'",
"end",
"end"
] | Render and return your shell's prompt.
You can define the prompt with <tt>MyShell.prompt_with</tt> and access it without rendering with <tt>MyShell.bombshell_prompt</tt>.
@see ClassMethods#prompt_with
@see ClassMethods#bombshell_prompt
@return String | [
"Render",
"and",
"return",
"your",
"shell",
"s",
"prompt",
"."
] | 542c855eb741095b1e88cc1bbfa1c1bacfcd9ebd | https://github.com/rossmeissl/bombshell/blob/542c855eb741095b1e88cc1bbfa1c1bacfcd9ebd/lib/bombshell/shell.rb#L26-L36 |
4,376 | christianhellsten/guard-bundler-audit | lib/guard/bundler_audit.rb | Guard.BundlerAudit.audit | def audit
res = ::Bundler::Audit::Scanner.new.scan.to_a.map do |vuln|
case vuln
when ::Bundler::Audit::Scanner::InsecureSource
insecure_source_message vuln
when ::Bundler::Audit::Scanner::UnpatchedGem
insecure_gem_message vuln
else
insecure_message vuln
end
end
if res.any?
message = "Vulnerabilities found:\n" + res.join("\n")
color = :red
notify message
else
message = "No vulnerabilities found."
color = :green
end
UI.info(UI.send(:color, message, color))
end | ruby | def audit
res = ::Bundler::Audit::Scanner.new.scan.to_a.map do |vuln|
case vuln
when ::Bundler::Audit::Scanner::InsecureSource
insecure_source_message vuln
when ::Bundler::Audit::Scanner::UnpatchedGem
insecure_gem_message vuln
else
insecure_message vuln
end
end
if res.any?
message = "Vulnerabilities found:\n" + res.join("\n")
color = :red
notify message
else
message = "No vulnerabilities found."
color = :green
end
UI.info(UI.send(:color, message, color))
end | [
"def",
"audit",
"res",
"=",
"::",
"Bundler",
"::",
"Audit",
"::",
"Scanner",
".",
"new",
".",
"scan",
".",
"to_a",
".",
"map",
"do",
"|",
"vuln",
"|",
"case",
"vuln",
"when",
"::",
"Bundler",
"::",
"Audit",
"::",
"Scanner",
"::",
"InsecureSource",
"insecure_source_message",
"vuln",
"when",
"::",
"Bundler",
"::",
"Audit",
"::",
"Scanner",
"::",
"UnpatchedGem",
"insecure_gem_message",
"vuln",
"else",
"insecure_message",
"vuln",
"end",
"end",
"if",
"res",
".",
"any?",
"message",
"=",
"\"Vulnerabilities found:\\n\"",
"+",
"res",
".",
"join",
"(",
"\"\\n\"",
")",
"color",
"=",
":red",
"notify",
"message",
"else",
"message",
"=",
"\"No vulnerabilities found.\"",
"color",
"=",
":green",
"end",
"UI",
".",
"info",
"(",
"UI",
".",
"send",
"(",
":color",
",",
"message",
",",
"color",
")",
")",
"end"
] | Scans for vulnerabilities and reports them. | [
"Scans",
"for",
"vulnerabilities",
"and",
"reports",
"them",
"."
] | 0b9d51c8a3bdd08c8eb1406ef171da97633d4c72 | https://github.com/christianhellsten/guard-bundler-audit/blob/0b9d51c8a3bdd08c8eb1406ef171da97633d4c72/lib/guard/bundler_audit.rb#L35-L55 |
4,377 | zerowidth/camper_van | lib/camper_van/ircd.rb | CamperVan.IRCD.receive_line | def receive_line(line)
if @active
cmd = parse(line)
handle cmd
end
rescue HandlerMissing
logger.info "ignoring irc command #{cmd.inspect}: no handler"
end | ruby | def receive_line(line)
if @active
cmd = parse(line)
handle cmd
end
rescue HandlerMissing
logger.info "ignoring irc command #{cmd.inspect}: no handler"
end | [
"def",
"receive_line",
"(",
"line",
")",
"if",
"@active",
"cmd",
"=",
"parse",
"(",
"line",
")",
"handle",
"cmd",
"end",
"rescue",
"HandlerMissing",
"logger",
".",
"info",
"\"ignoring irc command #{cmd.inspect}: no handler\"",
"end"
] | Handler for when a client sends an IRC command | [
"Handler",
"for",
"when",
"a",
"client",
"sends",
"an",
"IRC",
"command"
] | 984351a3b472e936a451f1d1cd987ca27d981d23 | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/ircd.rb#L74-L81 |
4,378 | zerowidth/camper_van | lib/camper_van/ircd.rb | CamperVan.IRCD.check_campfire_authentication | def check_campfire_authentication(&callback)
# invalid user only returns a nil result!
campfire.user("me") do |user|
if user.name
yield
else
command_reply :notice, "AUTH", "could not connect to campfire: invalid API key"
shutdown
end
end
rescue Firering::Connection::HTTPError => e
command_reply :notice, "AUTH", "could not connect to campfire: #{e.message}"
shutdown
end | ruby | def check_campfire_authentication(&callback)
# invalid user only returns a nil result!
campfire.user("me") do |user|
if user.name
yield
else
command_reply :notice, "AUTH", "could not connect to campfire: invalid API key"
shutdown
end
end
rescue Firering::Connection::HTTPError => e
command_reply :notice, "AUTH", "could not connect to campfire: #{e.message}"
shutdown
end | [
"def",
"check_campfire_authentication",
"(",
"&",
"callback",
")",
"# invalid user only returns a nil result!",
"campfire",
".",
"user",
"(",
"\"me\"",
")",
"do",
"|",
"user",
"|",
"if",
"user",
".",
"name",
"yield",
"else",
"command_reply",
":notice",
",",
"\"AUTH\"",
",",
"\"could not connect to campfire: invalid API key\"",
"shutdown",
"end",
"end",
"rescue",
"Firering",
"::",
"Connection",
"::",
"HTTPError",
"=>",
"e",
"command_reply",
":notice",
",",
"\"AUTH\"",
",",
"\"could not connect to campfire: #{e.message}\"",
"shutdown",
"end"
] | Checks that the campfire authentication is successful.
callback - a block to call if successful.
Yields to the callback on success (async)
If it fails, it replies with an error to the client and
disconnects. | [
"Checks",
"that",
"the",
"campfire",
"authentication",
"is",
"successful",
"."
] | 984351a3b472e936a451f1d1cd987ca27d981d23 | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/ircd.rb#L308-L321 |
4,379 | zerowidth/camper_van | lib/camper_van/ircd.rb | CamperVan.IRCD.check_nick_matches_authenticated_user | def check_nick_matches_authenticated_user
campfire.user("me") do |user|
name = irc_name user.name
if name != nick
user_reply :nick, name
@nick = name
end
end
end | ruby | def check_nick_matches_authenticated_user
campfire.user("me") do |user|
name = irc_name user.name
if name != nick
user_reply :nick, name
@nick = name
end
end
end | [
"def",
"check_nick_matches_authenticated_user",
"campfire",
".",
"user",
"(",
"\"me\"",
")",
"do",
"|",
"user",
"|",
"name",
"=",
"irc_name",
"user",
".",
"name",
"if",
"name",
"!=",
"nick",
"user_reply",
":nick",
",",
"name",
"@nick",
"=",
"name",
"end",
"end",
"end"
] | Check to see that the nick as provided during the registration
process matches the authenticated campfire user. If the nicks don't
match, send a nick change to the connected client. | [
"Check",
"to",
"see",
"that",
"the",
"nick",
"as",
"provided",
"during",
"the",
"registration",
"process",
"matches",
"the",
"authenticated",
"campfire",
"user",
".",
"If",
"the",
"nicks",
"don",
"t",
"match",
"send",
"a",
"nick",
"change",
"to",
"the",
"connected",
"client",
"."
] | 984351a3b472e936a451f1d1cd987ca27d981d23 | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/ircd.rb#L326-L334 |
4,380 | godfat/rest-more | lib/rest-core/util/rails_util_util.rb | RestCore::RailsUtilUtil.InstanceMethod.rc_setup | def rc_setup client, options={}
rc_options_ctl(client).merge!(
rc_options_extract(client.members, options, :reject))
rc_options_new(client).merge!(
rc_options_extract(client.members, options, :select))
end | ruby | def rc_setup client, options={}
rc_options_ctl(client).merge!(
rc_options_extract(client.members, options, :reject))
rc_options_new(client).merge!(
rc_options_extract(client.members, options, :select))
end | [
"def",
"rc_setup",
"client",
",",
"options",
"=",
"{",
"}",
"rc_options_ctl",
"(",
"client",
")",
".",
"merge!",
"(",
"rc_options_extract",
"(",
"client",
".",
"members",
",",
"options",
",",
":reject",
")",
")",
"rc_options_new",
"(",
"client",
")",
".",
"merge!",
"(",
"rc_options_extract",
"(",
"client",
".",
"members",
",",
"options",
",",
":select",
")",
")",
"end"
] | to mark below private in controllers | [
"to",
"mark",
"below",
"private",
"in",
"controllers"
] | 7a5faa6a5d3ec3bb2c5ccb447f78e2df0fa727c5 | https://github.com/godfat/rest-more/blob/7a5faa6a5d3ec3bb2c5ccb447f78e2df0fa727c5/lib/rest-core/util/rails_util_util.rb#L24-L30 |
4,381 | flergl/java-properties-for-ruby | lib/java_properties.rb | JavaProperties.Properties.to_s | def to_s
string = ""
# Sort to make testing easier -> output will consistent
@props.sort_by do |key,val|
key.to_s
end.each do |key,val|
string << Encoding.encode(key.to_s) << "=" << Encoding.encode(val) << "\n"
end
string
end | ruby | def to_s
string = ""
# Sort to make testing easier -> output will consistent
@props.sort_by do |key,val|
key.to_s
end.each do |key,val|
string << Encoding.encode(key.to_s) << "=" << Encoding.encode(val) << "\n"
end
string
end | [
"def",
"to_s",
"string",
"=",
"\"\"",
"# Sort to make testing easier -> output will consistent",
"@props",
".",
"sort_by",
"do",
"|",
"key",
",",
"val",
"|",
"key",
".",
"to_s",
"end",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"string",
"<<",
"Encoding",
".",
"encode",
"(",
"key",
".",
"to_s",
")",
"<<",
"\"=\"",
"<<",
"Encoding",
".",
"encode",
"(",
"val",
")",
"<<",
"\"\\n\"",
"end",
"string",
"end"
] | Converts the properties contained in this object into a
string that can be saved directly as a Java properties
file. | [
"Converts",
"the",
"properties",
"contained",
"in",
"this",
"object",
"into",
"a",
"string",
"that",
"can",
"be",
"saved",
"directly",
"as",
"a",
"Java",
"properties",
"file",
"."
] | 2d25162ffd720d4f7c2602a0536924bda800b698 | https://github.com/flergl/java-properties-for-ruby/blob/2d25162ffd720d4f7c2602a0536924bda800b698/lib/java_properties.rb#L87-L96 |
4,382 | thelabtech/questionnaire | app/presenters/qe/answer_pages_presenter.rb | Qe.AnswerPagesPresenter.page_list | def page_list(answer_sheets, a = nil, custom_pages = nil)
page_list = []
answer_sheets.each do |answer_sheet|
pages.each do |page|
page_list << new_page_link(answer_sheet, page, a)
end
end
page_list = page_list + custom_pages unless custom_pages.nil?
page_list
end | ruby | def page_list(answer_sheets, a = nil, custom_pages = nil)
page_list = []
answer_sheets.each do |answer_sheet|
pages.each do |page|
page_list << new_page_link(answer_sheet, page, a)
end
end
page_list = page_list + custom_pages unless custom_pages.nil?
page_list
end | [
"def",
"page_list",
"(",
"answer_sheets",
",",
"a",
"=",
"nil",
",",
"custom_pages",
"=",
"nil",
")",
"page_list",
"=",
"[",
"]",
"answer_sheets",
".",
"each",
"do",
"|",
"answer_sheet",
"|",
"pages",
".",
"each",
"do",
"|",
"page",
"|",
"page_list",
"<<",
"new_page_link",
"(",
"answer_sheet",
",",
"page",
",",
"a",
")",
"end",
"end",
"page_list",
"=",
"page_list",
"+",
"custom_pages",
"unless",
"custom_pages",
".",
"nil?",
"page_list",
"end"
] | for pages_list sidebar | [
"for",
"pages_list",
"sidebar"
] | 02eb47cbcda8cca28a5db78e18623d0957aa2c9b | https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/presenters/qe/answer_pages_presenter.rb#L88-L97 |
4,383 | gregbell/inherited_views | lib/inherited_views/helpers.rb | InheritedViews.Helpers.render_partial_or_default | def render_partial_or_default(name, options = {})
render options.merge(:partial => name)
rescue ActionView::MissingTemplate
render options.merge(:partial => "#{controller.class.default_views}/#{name}")
end | ruby | def render_partial_or_default(name, options = {})
render options.merge(:partial => name)
rescue ActionView::MissingTemplate
render options.merge(:partial => "#{controller.class.default_views}/#{name}")
end | [
"def",
"render_partial_or_default",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"render",
"options",
".",
"merge",
"(",
":partial",
"=>",
"name",
")",
"rescue",
"ActionView",
"::",
"MissingTemplate",
"render",
"options",
".",
"merge",
"(",
":partial",
"=>",
"\"#{controller.class.default_views}/#{name}\"",
")",
"end"
] | Tries to render the partial, if it doesn't exist, we will
try to find the partial in the default views folder for this
controller.
Example:
in app/views/users/index.html.erb
<%= render_partial_or_default 'item', :collection => @items %>
First it will try to reder 'app/views/users/_item.html.erb'. If
this file doesn't exist, it will lookup _item.html.erb in the
default views folder. | [
"Tries",
"to",
"render",
"the",
"partial",
"if",
"it",
"doesn",
"t",
"exist",
"we",
"will",
"try",
"to",
"find",
"the",
"partial",
"in",
"the",
"default",
"views",
"folder",
"for",
"this",
"controller",
"."
] | 0905018bdf6fc07923792d66390e545888bf7cb8 | https://github.com/gregbell/inherited_views/blob/0905018bdf6fc07923792d66390e545888bf7cb8/lib/inherited_views/helpers.rb#L17-L21 |
4,384 | ewannema/mm_json_client | lib/mm_json_client/client.rb | MmJsonClient.Client.client_objects_to_h | def client_objects_to_h(value)
case value.class.to_s
when /^MmJsonClient/
client_objects_to_h(value.to_h)
when 'Hash'
Hash[value.map { |k, v| [k, client_objects_to_h(v)] }]
when 'Array'
value.map { |v| client_objects_to_h(v) }
else
value
end
end | ruby | def client_objects_to_h(value)
case value.class.to_s
when /^MmJsonClient/
client_objects_to_h(value.to_h)
when 'Hash'
Hash[value.map { |k, v| [k, client_objects_to_h(v)] }]
when 'Array'
value.map { |v| client_objects_to_h(v) }
else
value
end
end | [
"def",
"client_objects_to_h",
"(",
"value",
")",
"case",
"value",
".",
"class",
".",
"to_s",
"when",
"/",
"/",
"client_objects_to_h",
"(",
"value",
".",
"to_h",
")",
"when",
"'Hash'",
"Hash",
"[",
"value",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
",",
"client_objects_to_h",
"(",
"v",
")",
"]",
"}",
"]",
"when",
"'Array'",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"client_objects_to_h",
"(",
"v",
")",
"}",
"else",
"value",
"end",
"end"
] | Recusively converts found MmJsonClient objects to hashes. | [
"Recusively",
"converts",
"found",
"MmJsonClient",
"objects",
"to",
"hashes",
"."
] | b6768b5ab52b097c2d6a7fb8000057f9537fef1c | https://github.com/ewannema/mm_json_client/blob/b6768b5ab52b097c2d6a7fb8000057f9537fef1c/lib/mm_json_client/client.rb#L50-L61 |
4,385 | cucumber-ltd/relish-gem | lib/relish/options_file.rb | Relish.OptionsFile.store | def store(options)
@options = self.options.merge(options)
FileUtils.touch(@path)
File.open(@path, 'w') do |file|
YAML.dump(@options, file)
end
end | ruby | def store(options)
@options = self.options.merge(options)
FileUtils.touch(@path)
File.open(@path, 'w') do |file|
YAML.dump(@options, file)
end
end | [
"def",
"store",
"(",
"options",
")",
"@options",
"=",
"self",
".",
"options",
".",
"merge",
"(",
"options",
")",
"FileUtils",
".",
"touch",
"(",
"@path",
")",
"File",
".",
"open",
"(",
"@path",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"YAML",
".",
"dump",
"(",
"@options",
",",
"file",
")",
"end",
"end"
] | Store the given options into the file. Existing options with the same keys
will be overwritten. | [
"Store",
"the",
"given",
"options",
"into",
"the",
"file",
".",
"Existing",
"options",
"with",
"the",
"same",
"keys",
"will",
"be",
"overwritten",
"."
] | 3809c3e10aaefb84fedbcaa60e61cfc840b892a1 | https://github.com/cucumber-ltd/relish-gem/blob/3809c3e10aaefb84fedbcaa60e61cfc840b892a1/lib/relish/options_file.rb#L15-L21 |
4,386 | johnl/web-page-parser | lib/web-page-parser/parsers/new_york_times_page_parser.rb | WebPageParser.NewYorkTimesPageParserV1.retrieve_page | def retrieve_page
return nil unless url
spurl = url
spurl << (spurl.include?("?") ? "&" : "?")
spurl << "pagewanted=all"
p = super(spurl)
# If it fails, reset the session and try one more time
unless retreive_successful?(p)
self.class.retrieve_session ||= WebPageParser::HTTP::Session.new
p = super(spurl)
end
if retreive_successful?(p)
p
else
raise RetrieveError, "Blocked by NYT paywall"
end
end | ruby | def retrieve_page
return nil unless url
spurl = url
spurl << (spurl.include?("?") ? "&" : "?")
spurl << "pagewanted=all"
p = super(spurl)
# If it fails, reset the session and try one more time
unless retreive_successful?(p)
self.class.retrieve_session ||= WebPageParser::HTTP::Session.new
p = super(spurl)
end
if retreive_successful?(p)
p
else
raise RetrieveError, "Blocked by NYT paywall"
end
end | [
"def",
"retrieve_page",
"return",
"nil",
"unless",
"url",
"spurl",
"=",
"url",
"spurl",
"<<",
"(",
"spurl",
".",
"include?",
"(",
"\"?\"",
")",
"?",
"\"&\"",
":",
"\"?\"",
")",
"spurl",
"<<",
"\"pagewanted=all\"",
"p",
"=",
"super",
"(",
"spurl",
")",
"# If it fails, reset the session and try one more time",
"unless",
"retreive_successful?",
"(",
"p",
")",
"self",
".",
"class",
".",
"retrieve_session",
"||=",
"WebPageParser",
"::",
"HTTP",
"::",
"Session",
".",
"new",
"p",
"=",
"super",
"(",
"spurl",
")",
"end",
"if",
"retreive_successful?",
"(",
"p",
")",
"p",
"else",
"raise",
"RetrieveError",
",",
"\"Blocked by NYT paywall\"",
"end",
"end"
] | We want to modify the url to request multi-page articles all in one request | [
"We",
"want",
"to",
"modify",
"the",
"url",
"to",
"request",
"multi",
"-",
"page",
"articles",
"all",
"in",
"one",
"request"
] | 105cbe6fda569c6c6667ed655ea6c6771c1d9037 | https://github.com/johnl/web-page-parser/blob/105cbe6fda569c6c6667ed655ea6c6771c1d9037/lib/web-page-parser/parsers/new_york_times_page_parser.rb#L25-L41 |
4,387 | julik/tickly | lib/tickly/parser.rb | Tickly.Parser.wrap_io_or_string | def wrap_io_or_string(io_or_str)
return io_or_str if io_or_str.respond_to?(:read_one_char) # Bychar or R
return R.new(io_or_str) if io_or_str.respond_to?(:read)
R.new(StringIO.new(io_or_str))
end | ruby | def wrap_io_or_string(io_or_str)
return io_or_str if io_or_str.respond_to?(:read_one_char) # Bychar or R
return R.new(io_or_str) if io_or_str.respond_to?(:read)
R.new(StringIO.new(io_or_str))
end | [
"def",
"wrap_io_or_string",
"(",
"io_or_str",
")",
"return",
"io_or_str",
"if",
"io_or_str",
".",
"respond_to?",
"(",
":read_one_char",
")",
"# Bychar or R",
"return",
"R",
".",
"new",
"(",
"io_or_str",
")",
"if",
"io_or_str",
".",
"respond_to?",
"(",
":read",
")",
"R",
".",
"new",
"(",
"StringIO",
".",
"new",
"(",
"io_or_str",
")",
")",
"end"
] | Returns the given String or IO object wrapped in an object that has
one method, read_one_char - that gets used by all the subsequent
parsing steps | [
"Returns",
"the",
"given",
"String",
"or",
"IO",
"object",
"wrapped",
"in",
"an",
"object",
"that",
"has",
"one",
"method",
"read_one_char",
"-",
"that",
"gets",
"used",
"by",
"all",
"the",
"subsequent",
"parsing",
"steps"
] | 0b52d2bc46cd8fd63ba93e0884ae31a24598df9a | https://github.com/julik/tickly/blob/0b52d2bc46cd8fd63ba93e0884ae31a24598df9a/lib/tickly/parser.rb#L19-L23 |
4,388 | julik/tickly | lib/tickly/parser.rb | Tickly.Parser.wrap_up | def wrap_up(expressions, stack, buf, stack_depth, multiple_expressions)
stack << buf if (buf.length > 0)
return stack unless multiple_expressions
expressions << stack if stack.any?
# Make sure that all of the expresisons get collapsed
expressions = expressions.map do | e |
compact_subexpr(e, stack_depth + 1)
end
return expressions
end | ruby | def wrap_up(expressions, stack, buf, stack_depth, multiple_expressions)
stack << buf if (buf.length > 0)
return stack unless multiple_expressions
expressions << stack if stack.any?
# Make sure that all of the expresisons get collapsed
expressions = expressions.map do | e |
compact_subexpr(e, stack_depth + 1)
end
return expressions
end | [
"def",
"wrap_up",
"(",
"expressions",
",",
"stack",
",",
"buf",
",",
"stack_depth",
",",
"multiple_expressions",
")",
"stack",
"<<",
"buf",
"if",
"(",
"buf",
".",
"length",
">",
"0",
")",
"return",
"stack",
"unless",
"multiple_expressions",
"expressions",
"<<",
"stack",
"if",
"stack",
".",
"any?",
"# Make sure that all of the expresisons get collapsed",
"expressions",
"=",
"expressions",
".",
"map",
"do",
"|",
"e",
"|",
"compact_subexpr",
"(",
"e",
",",
"stack_depth",
"+",
"1",
")",
"end",
"return",
"expressions",
"end"
] | Package the expressions, stack and buffer.
We use a special flag to tell us whether we need multuple expressions.
If we do, the expressions will be returned. If not, just the stack.
Also, anything that remains on the stack will be put on the expressions
list if multiple_expressions is true. | [
"Package",
"the",
"expressions",
"stack",
"and",
"buffer",
".",
"We",
"use",
"a",
"special",
"flag",
"to",
"tell",
"us",
"whether",
"we",
"need",
"multuple",
"expressions",
".",
"If",
"we",
"do",
"the",
"expressions",
"will",
"be",
"returned",
".",
"If",
"not",
"just",
"the",
"stack",
".",
"Also",
"anything",
"that",
"remains",
"on",
"the",
"stack",
"will",
"be",
"put",
"on",
"the",
"expressions",
"list",
"if",
"multiple_expressions",
"is",
"true",
"."
] | 0b52d2bc46cd8fd63ba93e0884ae31a24598df9a | https://github.com/julik/tickly/blob/0b52d2bc46cd8fd63ba93e0884ae31a24598df9a/lib/tickly/parser.rb#L64-L76 |
4,389 | julik/tickly | lib/tickly/parser.rb | Tickly.Parser.consume_remaining_buffer | def consume_remaining_buffer(stack, buf)
return if buf.length == 0
stack << buf.dup
buf.replace('')
end | ruby | def consume_remaining_buffer(stack, buf)
return if buf.length == 0
stack << buf.dup
buf.replace('')
end | [
"def",
"consume_remaining_buffer",
"(",
"stack",
",",
"buf",
")",
"return",
"if",
"buf",
".",
"length",
"==",
"0",
"stack",
"<<",
"buf",
".",
"dup",
"buf",
".",
"replace",
"(",
"''",
")",
"end"
] | If the passed buf contains any bytes, put them on the stack and
empty the buffer | [
"If",
"the",
"passed",
"buf",
"contains",
"any",
"bytes",
"put",
"them",
"on",
"the",
"stack",
"and",
"empty",
"the",
"buffer"
] | 0b52d2bc46cd8fd63ba93e0884ae31a24598df9a | https://github.com/julik/tickly/blob/0b52d2bc46cd8fd63ba93e0884ae31a24598df9a/lib/tickly/parser.rb#L80-L84 |
4,390 | julik/tickly | lib/tickly/parser.rb | Tickly.Parser.parse_expr | def parse_expr(io, stop_char = nil, stack_depth = 0, multiple_expressions = false)
# A standard stack is an expression that does not evaluate to a string
expressions = []
stack = []
buf = ''
loop do
char = io.read_one_char
# Ignore carriage returns
next if char == "\r"
if stop_char && char.nil?
raise Error, "IO ran out when parsing a subexpression (expected to end on #{stop_char.inspect})"
elsif char == stop_char # Bail out of a subexpr or bail out on nil
# TODO: default stop_char is nil, and this is also what gets returned from a depleted
# IO on IO#read(). We should do that in Bychar.
# Handle any remaining subexpressions
return wrap_up(expressions, stack, buf, stack_depth, multiple_expressions)
elsif char == " " || char == "\n" # Space
if buf.length > 0
stack << buf
buf = ''
end
if TERMINATORS.include?(char) && stack.any? # Introduce a stack separator! This is a new line
# First get rid of the remaining buffer data
consume_remaining_buffer(stack, buf)
# Since we now finished an expression and it is on the stack,
# we can run this expression through the filter
filtered_expr = compact_subexpr(stack, stack_depth + 1)
# Only preserve the parsed expression if it's not nil
expressions << filtered_expr unless filtered_expr.nil?
# Reset the stack for the next expression
stack = []
# Note that we will return multiple expressions instead of one
multiple_expressions = true
end
elsif char == '[' # Opens a new string expression
consume_remaining_buffer(stack, buf)
stack << [:b] + parse_expr(io, ']', stack_depth + 1)
elsif char == '{' # Opens a new literal expression
consume_remaining_buffer(stack, buf)
stack << [:c] + parse_expr(io, '}', stack_depth + 1)
elsif QUOTES.include?(char) # String
consume_remaining_buffer(stack, buf)
stack << parse_str(io, char)
else
buf << char
end
end
raise Error, "Should never happen"
end | ruby | def parse_expr(io, stop_char = nil, stack_depth = 0, multiple_expressions = false)
# A standard stack is an expression that does not evaluate to a string
expressions = []
stack = []
buf = ''
loop do
char = io.read_one_char
# Ignore carriage returns
next if char == "\r"
if stop_char && char.nil?
raise Error, "IO ran out when parsing a subexpression (expected to end on #{stop_char.inspect})"
elsif char == stop_char # Bail out of a subexpr or bail out on nil
# TODO: default stop_char is nil, and this is also what gets returned from a depleted
# IO on IO#read(). We should do that in Bychar.
# Handle any remaining subexpressions
return wrap_up(expressions, stack, buf, stack_depth, multiple_expressions)
elsif char == " " || char == "\n" # Space
if buf.length > 0
stack << buf
buf = ''
end
if TERMINATORS.include?(char) && stack.any? # Introduce a stack separator! This is a new line
# First get rid of the remaining buffer data
consume_remaining_buffer(stack, buf)
# Since we now finished an expression and it is on the stack,
# we can run this expression through the filter
filtered_expr = compact_subexpr(stack, stack_depth + 1)
# Only preserve the parsed expression if it's not nil
expressions << filtered_expr unless filtered_expr.nil?
# Reset the stack for the next expression
stack = []
# Note that we will return multiple expressions instead of one
multiple_expressions = true
end
elsif char == '[' # Opens a new string expression
consume_remaining_buffer(stack, buf)
stack << [:b] + parse_expr(io, ']', stack_depth + 1)
elsif char == '{' # Opens a new literal expression
consume_remaining_buffer(stack, buf)
stack << [:c] + parse_expr(io, '}', stack_depth + 1)
elsif QUOTES.include?(char) # String
consume_remaining_buffer(stack, buf)
stack << parse_str(io, char)
else
buf << char
end
end
raise Error, "Should never happen"
end | [
"def",
"parse_expr",
"(",
"io",
",",
"stop_char",
"=",
"nil",
",",
"stack_depth",
"=",
"0",
",",
"multiple_expressions",
"=",
"false",
")",
"# A standard stack is an expression that does not evaluate to a string",
"expressions",
"=",
"[",
"]",
"stack",
"=",
"[",
"]",
"buf",
"=",
"''",
"loop",
"do",
"char",
"=",
"io",
".",
"read_one_char",
"# Ignore carriage returns",
"next",
"if",
"char",
"==",
"\"\\r\"",
"if",
"stop_char",
"&&",
"char",
".",
"nil?",
"raise",
"Error",
",",
"\"IO ran out when parsing a subexpression (expected to end on #{stop_char.inspect})\"",
"elsif",
"char",
"==",
"stop_char",
"# Bail out of a subexpr or bail out on nil",
"# TODO: default stop_char is nil, and this is also what gets returned from a depleted",
"# IO on IO#read(). We should do that in Bychar.",
"# Handle any remaining subexpressions",
"return",
"wrap_up",
"(",
"expressions",
",",
"stack",
",",
"buf",
",",
"stack_depth",
",",
"multiple_expressions",
")",
"elsif",
"char",
"==",
"\" \"",
"||",
"char",
"==",
"\"\\n\"",
"# Space",
"if",
"buf",
".",
"length",
">",
"0",
"stack",
"<<",
"buf",
"buf",
"=",
"''",
"end",
"if",
"TERMINATORS",
".",
"include?",
"(",
"char",
")",
"&&",
"stack",
".",
"any?",
"# Introduce a stack separator! This is a new line",
"# First get rid of the remaining buffer data",
"consume_remaining_buffer",
"(",
"stack",
",",
"buf",
")",
"# Since we now finished an expression and it is on the stack,",
"# we can run this expression through the filter",
"filtered_expr",
"=",
"compact_subexpr",
"(",
"stack",
",",
"stack_depth",
"+",
"1",
")",
"# Only preserve the parsed expression if it's not nil",
"expressions",
"<<",
"filtered_expr",
"unless",
"filtered_expr",
".",
"nil?",
"# Reset the stack for the next expression",
"stack",
"=",
"[",
"]",
"# Note that we will return multiple expressions instead of one",
"multiple_expressions",
"=",
"true",
"end",
"elsif",
"char",
"==",
"'['",
"# Opens a new string expression",
"consume_remaining_buffer",
"(",
"stack",
",",
"buf",
")",
"stack",
"<<",
"[",
":b",
"]",
"+",
"parse_expr",
"(",
"io",
",",
"']'",
",",
"stack_depth",
"+",
"1",
")",
"elsif",
"char",
"==",
"'{'",
"# Opens a new literal expression ",
"consume_remaining_buffer",
"(",
"stack",
",",
"buf",
")",
"stack",
"<<",
"[",
":c",
"]",
"+",
"parse_expr",
"(",
"io",
",",
"'}'",
",",
"stack_depth",
"+",
"1",
")",
"elsif",
"QUOTES",
".",
"include?",
"(",
"char",
")",
"# String",
"consume_remaining_buffer",
"(",
"stack",
",",
"buf",
")",
"stack",
"<<",
"parse_str",
"(",
"io",
",",
"char",
")",
"else",
"buf",
"<<",
"char",
"end",
"end",
"raise",
"Error",
",",
"\"Should never happen\"",
"end"
] | Parse from a passed IO object either until an unescaped stop_char is reached
or until the IO is exhausted. The last argument is the class used to
compose the subexpression being parsed. The subparser is reentrant and not
destructive for the object containing it. | [
"Parse",
"from",
"a",
"passed",
"IO",
"object",
"either",
"until",
"an",
"unescaped",
"stop_char",
"is",
"reached",
"or",
"until",
"the",
"IO",
"is",
"exhausted",
".",
"The",
"last",
"argument",
"is",
"the",
"class",
"used",
"to",
"compose",
"the",
"subexpression",
"being",
"parsed",
".",
"The",
"subparser",
"is",
"reentrant",
"and",
"not",
"destructive",
"for",
"the",
"object",
"containing",
"it",
"."
] | 0b52d2bc46cd8fd63ba93e0884ae31a24598df9a | https://github.com/julik/tickly/blob/0b52d2bc46cd8fd63ba93e0884ae31a24598df9a/lib/tickly/parser.rb#L90-L147 |
4,391 | julik/tickly | lib/tickly/parser.rb | Tickly.Parser.parse_str | def parse_str(io, stop_quote)
buf = ''
loop do
c = io.read_one_char
if c.nil?
raise Error, "The IO ran out before the end of a literal string"
elsif buf.length > 0 && buf[-1..-1] == ESC # If this char was escaped
# Trim the escape character at the end of the buffer
buf = buf[0..-2]
buf << c
elsif c == stop_quote
return buf
else
buf << c
end
end
end | ruby | def parse_str(io, stop_quote)
buf = ''
loop do
c = io.read_one_char
if c.nil?
raise Error, "The IO ran out before the end of a literal string"
elsif buf.length > 0 && buf[-1..-1] == ESC # If this char was escaped
# Trim the escape character at the end of the buffer
buf = buf[0..-2]
buf << c
elsif c == stop_quote
return buf
else
buf << c
end
end
end | [
"def",
"parse_str",
"(",
"io",
",",
"stop_quote",
")",
"buf",
"=",
"''",
"loop",
"do",
"c",
"=",
"io",
".",
"read_one_char",
"if",
"c",
".",
"nil?",
"raise",
"Error",
",",
"\"The IO ran out before the end of a literal string\"",
"elsif",
"buf",
".",
"length",
">",
"0",
"&&",
"buf",
"[",
"-",
"1",
"..",
"-",
"1",
"]",
"==",
"ESC",
"# If this char was escaped",
"# Trim the escape character at the end of the buffer",
"buf",
"=",
"buf",
"[",
"0",
"..",
"-",
"2",
"]",
"buf",
"<<",
"c",
"elsif",
"c",
"==",
"stop_quote",
"return",
"buf",
"else",
"buf",
"<<",
"c",
"end",
"end",
"end"
] | Parse a string literal, in single or double quotes. | [
"Parse",
"a",
"string",
"literal",
"in",
"single",
"or",
"double",
"quotes",
"."
] | 0b52d2bc46cd8fd63ba93e0884ae31a24598df9a | https://github.com/julik/tickly/blob/0b52d2bc46cd8fd63ba93e0884ae31a24598df9a/lib/tickly/parser.rb#L150-L166 |
4,392 | Sage/class_kit | lib/class_kit/attribute_helper.rb | ClassKit.AttributeHelper.get_attributes | def get_attributes(klass)
return @attribute_store[klass] if @attribute_store.key?(klass)
attributes = []
klass.ancestors.map do |k|
hash = k.instance_variable_get(:@class_kit_attributes)
if hash != nil
hash.values.each do |a|
attributes.push(a)
end
end
end
attributes.compact!
@attribute_store[klass] = attributes
attributes
end | ruby | def get_attributes(klass)
return @attribute_store[klass] if @attribute_store.key?(klass)
attributes = []
klass.ancestors.map do |k|
hash = k.instance_variable_get(:@class_kit_attributes)
if hash != nil
hash.values.each do |a|
attributes.push(a)
end
end
end
attributes.compact!
@attribute_store[klass] = attributes
attributes
end | [
"def",
"get_attributes",
"(",
"klass",
")",
"return",
"@attribute_store",
"[",
"klass",
"]",
"if",
"@attribute_store",
".",
"key?",
"(",
"klass",
")",
"attributes",
"=",
"[",
"]",
"klass",
".",
"ancestors",
".",
"map",
"do",
"|",
"k",
"|",
"hash",
"=",
"k",
".",
"instance_variable_get",
"(",
":@class_kit_attributes",
")",
"if",
"hash",
"!=",
"nil",
"hash",
".",
"values",
".",
"each",
"do",
"|",
"a",
"|",
"attributes",
".",
"push",
"(",
"a",
")",
"end",
"end",
"end",
"attributes",
".",
"compact!",
"@attribute_store",
"[",
"klass",
"]",
"=",
"attributes",
"attributes",
"end"
] | Get attributes for a given class
@param klass [ClassKit] a class that has been extended with ClassKit
@return [Hash] | [
"Get",
"attributes",
"for",
"a",
"given",
"class"
] | addbb656e728adc353ee6eb6b1f9fd131effc8d1 | https://github.com/Sage/class_kit/blob/addbb656e728adc353ee6eb6b1f9fd131effc8d1/lib/class_kit/attribute_helper.rb#L17-L33 |
4,393 | Sage/class_kit | lib/class_kit/attribute_helper.rb | ClassKit.AttributeHelper.get_attribute | def get_attribute(klass:, name:)
get_attributes(klass).detect { |a| a[:name] == name } ||
raise(ClassKit::Exceptions::AttributeNotFoundError, "Attribute: #{name}, could not be found.")
end | ruby | def get_attribute(klass:, name:)
get_attributes(klass).detect { |a| a[:name] == name } ||
raise(ClassKit::Exceptions::AttributeNotFoundError, "Attribute: #{name}, could not be found.")
end | [
"def",
"get_attribute",
"(",
"klass",
":",
",",
"name",
":",
")",
"get_attributes",
"(",
"klass",
")",
".",
"detect",
"{",
"|",
"a",
"|",
"a",
"[",
":name",
"]",
"==",
"name",
"}",
"||",
"raise",
"(",
"ClassKit",
"::",
"Exceptions",
"::",
"AttributeNotFoundError",
",",
"\"Attribute: #{name}, could not be found.\"",
")",
"end"
] | Get attribute for a given class and name
@param klass [ClassKit] a class that has been extended with ClassKit
@param name [Symbol] an attribute name
@raise [ClassKit::Exceptions::AttributeNotFoundError] if the given attribute could not be found
@return [Hash] that describes the attribute | [
"Get",
"attribute",
"for",
"a",
"given",
"class",
"and",
"name"
] | addbb656e728adc353ee6eb6b1f9fd131effc8d1 | https://github.com/Sage/class_kit/blob/addbb656e728adc353ee6eb6b1f9fd131effc8d1/lib/class_kit/attribute_helper.rb#L43-L46 |
4,394 | cfanbase/cfan122 | lib/cfan122.rb | Cfan122.Reloader.cleanup | def cleanup(parent = Object, current = @top)
return unless all_project_objects_lookup[current]
current.constants.each {|const| cleanup current, current.const_get(const)}
parent.send(:remove_const, current.to_s.split('::').last.to_sym)
end | ruby | def cleanup(parent = Object, current = @top)
return unless all_project_objects_lookup[current]
current.constants.each {|const| cleanup current, current.const_get(const)}
parent.send(:remove_const, current.to_s.split('::').last.to_sym)
end | [
"def",
"cleanup",
"(",
"parent",
"=",
"Object",
",",
"current",
"=",
"@top",
")",
"return",
"unless",
"all_project_objects_lookup",
"[",
"current",
"]",
"current",
".",
"constants",
".",
"each",
"{",
"|",
"const",
"|",
"cleanup",
"current",
",",
"current",
".",
"const_get",
"(",
"const",
")",
"}",
"parent",
".",
"send",
"(",
":remove_const",
",",
"current",
".",
"to_s",
".",
"split",
"(",
"'::'",
")",
".",
"last",
".",
"to_sym",
")",
"end"
] | Recursively removes all constant entries of modules and classes under
the MyGemName namespace | [
"Recursively",
"removes",
"all",
"constant",
"entries",
"of",
"modules",
"and",
"classes",
"under",
"the",
"MyGemName",
"namespace"
] | ea0842d58cf36ffd1d555b26ed24db6a3e68ab26 | https://github.com/cfanbase/cfan122/blob/ea0842d58cf36ffd1d555b26ed24db6a3e68ab26/lib/cfan122.rb#L74-L78 |
4,395 | Sage/class_kit | lib/class_kit/helper.rb | ClassKit.Helper.to_hash | def to_hash(object, use_alias = false)
return object.map { |i| to_hash(i, use_alias) } if object.is_a?(Array)
validate_class_kit(object.class)
hash = {}
attributes = @attribute_helper.get_attributes(object.class)
attributes.each do |attribute|
key = use_alias ? (attribute[:alias] || attribute[:name]) : attribute[:name]
type = attribute[:type]
value = object.public_send(attribute[:name])
if value != nil
hash[key] = if is_class_kit?(type)
to_hash(value, use_alias)
elsif type == Array
value.map do |i|
if is_class_kit?(i.class)
to_hash(i, use_alias)
else
i
end
end
else
value
end
end
end
@hash_helper.indifferent!(hash)
hash
end | ruby | def to_hash(object, use_alias = false)
return object.map { |i| to_hash(i, use_alias) } if object.is_a?(Array)
validate_class_kit(object.class)
hash = {}
attributes = @attribute_helper.get_attributes(object.class)
attributes.each do |attribute|
key = use_alias ? (attribute[:alias] || attribute[:name]) : attribute[:name]
type = attribute[:type]
value = object.public_send(attribute[:name])
if value != nil
hash[key] = if is_class_kit?(type)
to_hash(value, use_alias)
elsif type == Array
value.map do |i|
if is_class_kit?(i.class)
to_hash(i, use_alias)
else
i
end
end
else
value
end
end
end
@hash_helper.indifferent!(hash)
hash
end | [
"def",
"to_hash",
"(",
"object",
",",
"use_alias",
"=",
"false",
")",
"return",
"object",
".",
"map",
"{",
"|",
"i",
"|",
"to_hash",
"(",
"i",
",",
"use_alias",
")",
"}",
"if",
"object",
".",
"is_a?",
"(",
"Array",
")",
"validate_class_kit",
"(",
"object",
".",
"class",
")",
"hash",
"=",
"{",
"}",
"attributes",
"=",
"@attribute_helper",
".",
"get_attributes",
"(",
"object",
".",
"class",
")",
"attributes",
".",
"each",
"do",
"|",
"attribute",
"|",
"key",
"=",
"use_alias",
"?",
"(",
"attribute",
"[",
":alias",
"]",
"||",
"attribute",
"[",
":name",
"]",
")",
":",
"attribute",
"[",
":name",
"]",
"type",
"=",
"attribute",
"[",
":type",
"]",
"value",
"=",
"object",
".",
"public_send",
"(",
"attribute",
"[",
":name",
"]",
")",
"if",
"value",
"!=",
"nil",
"hash",
"[",
"key",
"]",
"=",
"if",
"is_class_kit?",
"(",
"type",
")",
"to_hash",
"(",
"value",
",",
"use_alias",
")",
"elsif",
"type",
"==",
"Array",
"value",
".",
"map",
"do",
"|",
"i",
"|",
"if",
"is_class_kit?",
"(",
"i",
".",
"class",
")",
"to_hash",
"(",
"i",
",",
"use_alias",
")",
"else",
"i",
"end",
"end",
"else",
"value",
"end",
"end",
"end",
"@hash_helper",
".",
"indifferent!",
"(",
"hash",
")",
"hash",
"end"
] | This method is called to convert a ClassKit object into a Hash. | [
"This",
"method",
"is",
"called",
"to",
"convert",
"a",
"ClassKit",
"object",
"into",
"a",
"Hash",
"."
] | addbb656e728adc353ee6eb6b1f9fd131effc8d1 | https://github.com/Sage/class_kit/blob/addbb656e728adc353ee6eb6b1f9fd131effc8d1/lib/class_kit/helper.rb#L20-L50 |
4,396 | Sage/class_kit | lib/class_kit/helper.rb | ClassKit.Helper.to_json | def to_json(object, use_alias = false)
hash = to_hash(object, use_alias)
JSON.dump(hash)
end | ruby | def to_json(object, use_alias = false)
hash = to_hash(object, use_alias)
JSON.dump(hash)
end | [
"def",
"to_json",
"(",
"object",
",",
"use_alias",
"=",
"false",
")",
"hash",
"=",
"to_hash",
"(",
"object",
",",
"use_alias",
")",
"JSON",
".",
"dump",
"(",
"hash",
")",
"end"
] | This method is called to convert a ClassKit object into JSON. | [
"This",
"method",
"is",
"called",
"to",
"convert",
"a",
"ClassKit",
"object",
"into",
"JSON",
"."
] | addbb656e728adc353ee6eb6b1f9fd131effc8d1 | https://github.com/Sage/class_kit/blob/addbb656e728adc353ee6eb6b1f9fd131effc8d1/lib/class_kit/helper.rb#L93-L96 |
4,397 | Sage/class_kit | lib/class_kit/helper.rb | ClassKit.Helper.from_json | def from_json(json:, klass:, use_alias: false)
hash = JSON.load(json)
from_hash(hash: hash, klass: klass, use_alias: use_alias)
end | ruby | def from_json(json:, klass:, use_alias: false)
hash = JSON.load(json)
from_hash(hash: hash, klass: klass, use_alias: use_alias)
end | [
"def",
"from_json",
"(",
"json",
":",
",",
"klass",
":",
",",
"use_alias",
":",
"false",
")",
"hash",
"=",
"JSON",
".",
"load",
"(",
"json",
")",
"from_hash",
"(",
"hash",
":",
"hash",
",",
"klass",
":",
"klass",
",",
"use_alias",
":",
"use_alias",
")",
"end"
] | This method is called to convert JSON into a ClassKit object. | [
"This",
"method",
"is",
"called",
"to",
"convert",
"JSON",
"into",
"a",
"ClassKit",
"object",
"."
] | addbb656e728adc353ee6eb6b1f9fd131effc8d1 | https://github.com/Sage/class_kit/blob/addbb656e728adc353ee6eb6b1f9fd131effc8d1/lib/class_kit/helper.rb#L99-L102 |
4,398 | calonso/rails_friendly_urls | lib/rails_friendly_urls/friendly_url.rb | RailsFriendlyUrls.FriendlyUrl.set_destination_data! | def set_destination_data!
route_info = Rails.application.routes.recognize_path self.path
self.controller = route_info[:controller]
self.action = route_info[:action]
self.defaults = route_info.reject { |k, v| [:controller, :action].include? k }
end | ruby | def set_destination_data!
route_info = Rails.application.routes.recognize_path self.path
self.controller = route_info[:controller]
self.action = route_info[:action]
self.defaults = route_info.reject { |k, v| [:controller, :action].include? k }
end | [
"def",
"set_destination_data!",
"route_info",
"=",
"Rails",
".",
"application",
".",
"routes",
".",
"recognize_path",
"self",
".",
"path",
"self",
".",
"controller",
"=",
"route_info",
"[",
":controller",
"]",
"self",
".",
"action",
"=",
"route_info",
"[",
":action",
"]",
"self",
".",
"defaults",
"=",
"route_info",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"[",
":controller",
",",
":action",
"]",
".",
"include?",
"k",
"}",
"end"
] | This method tries to identify the route contained at self.path to extract
the destination's controller, action and other arguments and save them
into the corresponding controller, action and defaults fields of the
including objects. | [
"This",
"method",
"tries",
"to",
"identify",
"the",
"route",
"contained",
"at",
"self",
".",
"path",
"to",
"extract",
"the",
"destination",
"s",
"controller",
"action",
"and",
"other",
"arguments",
"and",
"save",
"them",
"into",
"the",
"corresponding",
"controller",
"action",
"and",
"defaults",
"fields",
"of",
"the",
"including",
"objects",
"."
] | 356fc101f106bda1ce890ae8f5ffc7cc44a56ec2 | https://github.com/calonso/rails_friendly_urls/blob/356fc101f106bda1ce890ae8f5ffc7cc44a56ec2/lib/rails_friendly_urls/friendly_url.rb#L14-L19 |
4,399 | Telestream/telestream-cloud-ruby-sdk | tts/lib/telestream_cloud_tts/api/tts_api.rb | TelestreamCloud::Tts.TtsApi.corpora | def corpora(project_id, opts = {})
data, _status_code, _headers = corpora_with_http_info(project_id, opts)
return data
end | ruby | def corpora(project_id, opts = {})
data, _status_code, _headers = corpora_with_http_info(project_id, opts)
return data
end | [
"def",
"corpora",
"(",
"project_id",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"corpora_with_http_info",
"(",
"project_id",
",",
"opts",
")",
"return",
"data",
"end"
] | Returns a collection of Corpora
Returns a collection of Corpora
@param project_id ID of the Project
@param [Hash] opts the optional parameters
@return [CorporaCollection] | [
"Returns",
"a",
"collection",
"of",
"Corpora",
"Returns",
"a",
"collection",
"of",
"Corpora"
] | c232427aa3e84688ba41ec28e5bef1cc72832bf4 | https://github.com/Telestream/telestream-cloud-ruby-sdk/blob/c232427aa3e84688ba41ec28e5bef1cc72832bf4/tts/lib/telestream_cloud_tts/api/tts_api.rb#L28-L31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.