repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
mikamai/akamai_api | lib/akamai_api/ccu/purge_status/request.rb | AkamaiApi::CCU::PurgeStatus.Request.execute | def execute purge_id_or_progress_uri
purge_id_or_progress_uri = normalize_progress_uri purge_id_or_progress_uri
response = self.class.get purge_id_or_progress_uri, basic_auth: AkamaiApi.auth
parse_response response
end | ruby | def execute purge_id_or_progress_uri
purge_id_or_progress_uri = normalize_progress_uri purge_id_or_progress_uri
response = self.class.get purge_id_or_progress_uri, basic_auth: AkamaiApi.auth
parse_response response
end | [
"def",
"execute",
"purge_id_or_progress_uri",
"purge_id_or_progress_uri",
"=",
"normalize_progress_uri",
"purge_id_or_progress_uri",
"response",
"=",
"self",
".",
"class",
".",
"get",
"purge_id_or_progress_uri",
",",
"basic_auth",
":",
"AkamaiApi",
".",
"auth",
"parse_response",
"response",
"end"
] | Checks the status of the requested associated with the given argument
@return [Response] an object detailing the response
@raise [AkamaiApi::CCU::PurgeStatus::NotFound] when the request cannot be found
@raise [AkamaiApi::CCU::Error] when there is an error in the request
@raise [AkamaiApi::Unauthorized] when login credentials are invalid | [
"Checks",
"the",
"status",
"of",
"the",
"requested",
"associated",
"with",
"the",
"given",
"argument"
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu/purge_status/request.rb#L37-L41 | train |
mikamai/akamai_api | lib/akamai_api/eccu/find_request.rb | AkamaiApi::ECCU.FindRequest.execute | def execute retrieve_content = false
with_soap_error_handling do
response = client_call :get_info, message: request_body(retrieve_content).to_s
FindResponse.new response[:eccu_info]
end
end | ruby | def execute retrieve_content = false
with_soap_error_handling do
response = client_call :get_info, message: request_body(retrieve_content).to_s
FindResponse.new response[:eccu_info]
end
end | [
"def",
"execute",
"retrieve_content",
"=",
"false",
"with_soap_error_handling",
"do",
"response",
"=",
"client_call",
":get_info",
",",
"message",
":",
"request_body",
"(",
"retrieve_content",
")",
".",
"to_s",
"FindResponse",
".",
"new",
"response",
"[",
":eccu_info",
"]",
"end",
"end"
] | Returns the details of an ECCU request
@param [true,false] retrieve_content set to true if you want to retrieve request content too
@return [FindResponse] | [
"Returns",
"the",
"details",
"of",
"an",
"ECCU",
"request"
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_request.rb#L28-L33 | train |
mikamai/akamai_api | lib/akamai_api/ccu/purge/request.rb | AkamaiApi::CCU::Purge.Request.execute | def execute *items
akamai = Akamai::Edgegrid::HTTP.new(address=baseuri.host, port=baseuri.port)
akamai.setup_edgegrid(creds)
http = Net::HTTP.new(address=baseuri.host, port=baseuri.port)
http.use_ssl = true
items = Array.wrap(items.first) if items.length == 1
req = Net::HTTP::Post.new(resource, initheader = @@headers).tap do |pq|
if for_ccu_v2?
pq.body = request_body items
else
pq.body = {"objects" => items}.to_json
end
end
timestamp = Akamai::Edgegrid::HTTP.eg_timestamp()
nonce = Akamai::Edgegrid::HTTP.new_nonce()
req['Authorization'] = akamai.make_auth_header(req, timestamp, nonce)
parse_response http.request(req)
end | ruby | def execute *items
akamai = Akamai::Edgegrid::HTTP.new(address=baseuri.host, port=baseuri.port)
akamai.setup_edgegrid(creds)
http = Net::HTTP.new(address=baseuri.host, port=baseuri.port)
http.use_ssl = true
items = Array.wrap(items.first) if items.length == 1
req = Net::HTTP::Post.new(resource, initheader = @@headers).tap do |pq|
if for_ccu_v2?
pq.body = request_body items
else
pq.body = {"objects" => items}.to_json
end
end
timestamp = Akamai::Edgegrid::HTTP.eg_timestamp()
nonce = Akamai::Edgegrid::HTTP.new_nonce()
req['Authorization'] = akamai.make_auth_header(req, timestamp, nonce)
parse_response http.request(req)
end | [
"def",
"execute",
"*",
"items",
"akamai",
"=",
"Akamai",
"::",
"Edgegrid",
"::",
"HTTP",
".",
"new",
"(",
"address",
"=",
"baseuri",
".",
"host",
",",
"port",
"=",
"baseuri",
".",
"port",
")",
"akamai",
".",
"setup_edgegrid",
"(",
"creds",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"address",
"=",
"baseuri",
".",
"host",
",",
"port",
"=",
"baseuri",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"true",
"items",
"=",
"Array",
".",
"wrap",
"(",
"items",
".",
"first",
")",
"if",
"items",
".",
"length",
"==",
"1",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"resource",
",",
"initheader",
"=",
"@@headers",
")",
".",
"tap",
"do",
"|",
"pq",
"|",
"if",
"for_ccu_v2?",
"pq",
".",
"body",
"=",
"request_body",
"items",
"else",
"pq",
".",
"body",
"=",
"{",
"\"objects\"",
"=>",
"items",
"}",
".",
"to_json",
"end",
"end",
"timestamp",
"=",
"Akamai",
"::",
"Edgegrid",
"::",
"HTTP",
".",
"eg_timestamp",
"(",
")",
"nonce",
"=",
"Akamai",
"::",
"Edgegrid",
"::",
"HTTP",
".",
"new_nonce",
"(",
")",
"req",
"[",
"'Authorization'",
"]",
"=",
"akamai",
".",
"make_auth_header",
"(",
"req",
",",
"timestamp",
",",
"nonce",
")",
"parse_response",
"http",
".",
"request",
"(",
"req",
")",
"end"
] | Clean the requested resources.
@param [Array<String>] items One or more resources to clean
@return [Response] an object representing the received response
@raise [AkamaiApi::CCU::Error] when there is an error in the request
@raise [AkamaiApi::Unauthorized] when login credentials are invalid
@example Clean a single resource
request.execute 'http://foo.bar/t.txt'
@example Clean multiple resources
request.execute '12345', '12346' | [
"Clean",
"the",
"requested",
"resources",
"."
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu/purge/request.rb#L74-L94 | train |
mikamai/akamai_api | lib/akamai_api/ccu/purge/request.rb | AkamaiApi::CCU::Purge.Request.request_body | def request_body items
{ type: type, action: action, domain: domain, objects: items }.to_json
end | ruby | def request_body items
{ type: type, action: action, domain: domain, objects: items }.to_json
end | [
"def",
"request_body",
"items",
"{",
"type",
":",
"type",
",",
"action",
":",
"action",
",",
"domain",
":",
"domain",
",",
"objects",
":",
"items",
"}",
".",
"to_json",
"end"
] | Request body to send to the API.
@param [Array<String>] items resources to clean
@return [String] request body in JSON format | [
"Request",
"body",
"to",
"send",
"to",
"the",
"API",
"."
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu/purge/request.rb#L99-L101 | train |
mikamai/akamai_api | lib/akamai_api/ccu.rb | AkamaiApi.CCU.purge | def purge action, type, items, opts = {}
request = Purge::Request.new action, type, domain: opts[:domain]
request.execute items
end | ruby | def purge action, type, items, opts = {}
request = Purge::Request.new action, type, domain: opts[:domain]
request.execute items
end | [
"def",
"purge",
"action",
",",
"type",
",",
"items",
",",
"opts",
"=",
"{",
"}",
"request",
"=",
"Purge",
"::",
"Request",
".",
"new",
"action",
",",
"type",
",",
"domain",
":",
"opts",
"[",
":domain",
"]",
"request",
".",
"execute",
"items",
"end"
] | Purges one or more resources
@param [String,Symbol] action type of clean action. Allowed values are:
- :invalidate
- :remove
Check {AkamaiApi::CCU::Purge::Request#action} for more details
@param [String,Symbol] type type of resource to clean. Allowed values are:
- :cpcode
- :arl
Check {AkamaiApi::CCU::Purge::Request#type} for more details
@param [String, Array] items resource(s) to clean
@param [Hash] opts additional options
@option opts [String] :domain domain type where to act. Allowed values are:
- :production
- :staging
Check {AkamaiApi::CCU::Purge::Request#domain} for more details
@return [AkamaiApi::CCU::Purge::Response] an object representing the received response
@raise [AkamaiApi::CCU::Error] when there is an error in the request
@raise [AkamaiApi::Unauthorized] when login credentials are invalid | [
"Purges",
"one",
"or",
"more",
"resources"
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/ccu.rb#L129-L132 | train |
waiting-for-dev/string-direction | lib/string-direction/strategies/dominant_strategy.rb | StringDirection.DominantStrategy.run | def run(string)
string = string.to_s
ltr_count = chars_count(string, ltr_regex)
rtl_count = chars_count(string, rtl_regex)
diff = ltr_count - rtl_count
return ltr if diff > 0
return rtl if diff < 0
nil
end | ruby | def run(string)
string = string.to_s
ltr_count = chars_count(string, ltr_regex)
rtl_count = chars_count(string, rtl_regex)
diff = ltr_count - rtl_count
return ltr if diff > 0
return rtl if diff < 0
nil
end | [
"def",
"run",
"(",
"string",
")",
"string",
"=",
"string",
".",
"to_s",
"ltr_count",
"=",
"chars_count",
"(",
"string",
",",
"ltr_regex",
")",
"rtl_count",
"=",
"chars_count",
"(",
"string",
",",
"rtl_regex",
")",
"diff",
"=",
"ltr_count",
"-",
"rtl_count",
"return",
"ltr",
"if",
"diff",
">",
"0",
"return",
"rtl",
"if",
"diff",
"<",
"0",
"nil",
"end"
] | Get the number of ltr and rtl characters in the supplied string and infer
direction from the most common type. For this strategy the direction can
be ltr or rtl, but never bidi. In case of draw it returns nil.
params [String] The string to inspect
@return [String, nil] | [
"Get",
"the",
"number",
"of",
"ltr",
"and",
"rtl",
"characters",
"in",
"the",
"supplied",
"string",
"and",
"infer",
"direction",
"from",
"the",
"most",
"common",
"type",
".",
"For",
"this",
"strategy",
"the",
"direction",
"can",
"be",
"ltr",
"or",
"rtl",
"but",
"never",
"bidi",
".",
"In",
"case",
"of",
"draw",
"it",
"returns",
"nil",
"."
] | c976ffe0ba91161d14d6e2d069f6febad5b32d34 | https://github.com/waiting-for-dev/string-direction/blob/c976ffe0ba91161d14d6e2d069f6febad5b32d34/lib/string-direction/strategies/dominant_strategy.rb#L10-L18 | train |
mikamai/akamai_api | lib/akamai_api/eccu/find_response.rb | AkamaiApi::ECCU.FindResponse.file | def file
content64 = get_if_handleable(raw[:contents])
{
:content => content64 ? Base64.decode64(content64) : nil,
:size => raw[:file_size].to_i,
:name => get_if_handleable(raw[:filename]),
:md5 => get_if_handleable(raw[:md5_digest])
}.reject { |k, v| v.nil? }
end | ruby | def file
content64 = get_if_handleable(raw[:contents])
{
:content => content64 ? Base64.decode64(content64) : nil,
:size => raw[:file_size].to_i,
:name => get_if_handleable(raw[:filename]),
:md5 => get_if_handleable(raw[:md5_digest])
}.reject { |k, v| v.nil? }
end | [
"def",
"file",
"content64",
"=",
"get_if_handleable",
"(",
"raw",
"[",
":contents",
"]",
")",
"{",
":content",
"=>",
"content64",
"?",
"Base64",
".",
"decode64",
"(",
"content64",
")",
":",
"nil",
",",
":size",
"=>",
"raw",
"[",
":file_size",
"]",
".",
"to_i",
",",
":name",
"=>",
"get_if_handleable",
"(",
"raw",
"[",
":filename",
"]",
")",
",",
":md5",
"=>",
"get_if_handleable",
"(",
"raw",
"[",
":md5_digest",
"]",
")",
"}",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"end"
] | Uploaded file details
@return [Hash] file details
- :content [String] file content
- :size [Fixnum] file size
- :name [String] file name
- :md5 [String] MD5 digest of the file content | [
"Uploaded",
"file",
"details"
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_response.rb#L63-L71 | train |
mikamai/akamai_api | lib/akamai_api/eccu/find_response.rb | AkamaiApi::ECCU.FindResponse.property | def property
{
:name => get_if_handleable(raw[:property_name]),
:exact_match => (raw[:property_name_exact_match] == true),
:type => get_if_handleable(raw[:property_type])
}.reject { |k, v| v.nil? }
end | ruby | def property
{
:name => get_if_handleable(raw[:property_name]),
:exact_match => (raw[:property_name_exact_match] == true),
:type => get_if_handleable(raw[:property_type])
}.reject { |k, v| v.nil? }
end | [
"def",
"property",
"{",
":name",
"=>",
"get_if_handleable",
"(",
"raw",
"[",
":property_name",
"]",
")",
",",
":exact_match",
"=>",
"(",
"raw",
"[",
":property_name_exact_match",
"]",
"==",
"true",
")",
",",
":type",
"=>",
"get_if_handleable",
"(",
"raw",
"[",
":property_type",
"]",
")",
"}",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"end"
] | Digital property details
@return [Hash] property details
- :name [String]
- :exact_match [true,false]
- :type [String] | [
"Digital",
"property",
"details"
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_response.rb#L93-L99 | train |
mikamai/akamai_api | lib/akamai_api/eccu/find_response.rb | AkamaiApi::ECCU.FindResponse.get_if_handleable | def get_if_handleable value
case value
when String then value
when DateTime then value.to_time.utc.xmlschema(3)
else nil
end
end | ruby | def get_if_handleable value
case value
when String then value
when DateTime then value.to_time.utc.xmlschema(3)
else nil
end
end | [
"def",
"get_if_handleable",
"value",
"case",
"value",
"when",
"String",
"then",
"value",
"when",
"DateTime",
"then",
"value",
".",
"to_time",
".",
"utc",
".",
"xmlschema",
"(",
"3",
")",
"else",
"nil",
"end",
"end"
] | This method is used because, for nil values, savon will respond with an hash containing all other attributes.
If we check that the expected type is matched, we can
prevent to retrieve wrong values | [
"This",
"method",
"is",
"used",
"because",
"for",
"nil",
"values",
"savon",
"will",
"respond",
"with",
"an",
"hash",
"containing",
"all",
"other",
"attributes",
".",
"If",
"we",
"check",
"that",
"the",
"expected",
"type",
"is",
"matched",
"we",
"can",
"prevent",
"to",
"retrieve",
"wrong",
"values"
] | a6bc1369e118bb298c71019c9788e5c9bd1753c8 | https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/find_response.rb#L106-L112 | train |
waiting-for-dev/string-direction | lib/string-direction/strategies/marks_strategy.rb | StringDirection.MarksStrategy.run | def run(string)
string = string.to_s
if ltr_mark?(string) && rtl_mark?(string)
bidi
elsif ltr_mark?(string)
ltr
elsif rtl_mark?(string)
rtl
end
end | ruby | def run(string)
string = string.to_s
if ltr_mark?(string) && rtl_mark?(string)
bidi
elsif ltr_mark?(string)
ltr
elsif rtl_mark?(string)
rtl
end
end | [
"def",
"run",
"(",
"string",
")",
"string",
"=",
"string",
".",
"to_s",
"if",
"ltr_mark?",
"(",
"string",
")",
"&&",
"rtl_mark?",
"(",
"string",
")",
"bidi",
"elsif",
"ltr_mark?",
"(",
"string",
")",
"ltr",
"elsif",
"rtl_mark?",
"(",
"string",
")",
"rtl",
"end",
"end"
] | Look for the presence of unicode marks in given string and infers from them its direction
params [String] The string to inspect
@return [String, nil] | [
"Look",
"for",
"the",
"presence",
"of",
"unicode",
"marks",
"in",
"given",
"string",
"and",
"infers",
"from",
"them",
"its",
"direction"
] | c976ffe0ba91161d14d6e2d069f6febad5b32d34 | https://github.com/waiting-for-dev/string-direction/blob/c976ffe0ba91161d14d6e2d069f6febad5b32d34/lib/string-direction/strategies/marks_strategy.rb#L14-L23 | train |
ahnick/ahocorasick | lib/ahocorasick.rb | AhoC.Trie.add | def add pattern
node = @root
# If this is a string process each character
if String(pattern) == pattern
pattern.each_char do |char|
if node.goto(char) == nil
node = node.add(char)
else
node = node.goto(char)
end
end
else # Otherwise, pattern should support "each" method.
for item in pattern
if node.goto(item) == nil
node = node.add(item)
else
node = node.goto(item)
end
end
end
if block_given?
node.output = yield pattern
else
node.output = [pattern]
end
end | ruby | def add pattern
node = @root
# If this is a string process each character
if String(pattern) == pattern
pattern.each_char do |char|
if node.goto(char) == nil
node = node.add(char)
else
node = node.goto(char)
end
end
else # Otherwise, pattern should support "each" method.
for item in pattern
if node.goto(item) == nil
node = node.add(item)
else
node = node.goto(item)
end
end
end
if block_given?
node.output = yield pattern
else
node.output = [pattern]
end
end | [
"def",
"add",
"pattern",
"node",
"=",
"@root",
"if",
"String",
"(",
"pattern",
")",
"==",
"pattern",
"pattern",
".",
"each_char",
"do",
"|",
"char",
"|",
"if",
"node",
".",
"goto",
"(",
"char",
")",
"==",
"nil",
"node",
"=",
"node",
".",
"add",
"(",
"char",
")",
"else",
"node",
"=",
"node",
".",
"goto",
"(",
"char",
")",
"end",
"end",
"else",
"for",
"item",
"in",
"pattern",
"if",
"node",
".",
"goto",
"(",
"item",
")",
"==",
"nil",
"node",
"=",
"node",
".",
"add",
"(",
"item",
")",
"else",
"node",
"=",
"node",
".",
"goto",
"(",
"item",
")",
"end",
"end",
"end",
"if",
"block_given?",
"node",
".",
"output",
"=",
"yield",
"pattern",
"else",
"node",
".",
"output",
"=",
"[",
"pattern",
"]",
"end",
"end"
] | Creates an empty AhoC Trie with only a root node
Accepts an optional argument (either :DFA or :NFA)
indicating the type of automaton to build. If no
argument is passed an NFA will be built.
Add a pattern to the Trie.
Accepts an optional block that can be used
to modify the node output. | [
"Creates",
"an",
"empty",
"AhoC",
"Trie",
"with",
"only",
"a",
"root",
"node"
] | bf5f66ab5823aba83fbedb3460d642292bc85a5f | https://github.com/ahnick/ahocorasick/blob/bf5f66ab5823aba83fbedb3460d642292bc85a5f/lib/ahocorasick.rb#L71-L98 | train |
GoodMeasuresLLC/draper-cancancan | lib/draper/cancancan.rb | Draper.CanCanCan.can? | def can?(action, subject, *extra_args)
while subject.is_a?(Draper::Decorator)
subject = subject.model
end
super(action, subject, *extra_args)
end | ruby | def can?(action, subject, *extra_args)
while subject.is_a?(Draper::Decorator)
subject = subject.model
end
super(action, subject, *extra_args)
end | [
"def",
"can?",
"(",
"action",
",",
"subject",
",",
"*",
"extra_args",
")",
"while",
"subject",
".",
"is_a?",
"(",
"Draper",
"::",
"Decorator",
")",
"subject",
"=",
"subject",
".",
"model",
"end",
"super",
"(",
"action",
",",
"subject",
",",
"*",
"extra_args",
")",
"end"
] | actually don't need any code in my gem's namespace .. | [
"actually",
"don",
"t",
"need",
"any",
"code",
"in",
"my",
"gem",
"s",
"namespace",
".."
] | 0042efe4028d053e9db2a36c9fbf08f7d7935844 | https://github.com/GoodMeasuresLLC/draper-cancancan/blob/0042efe4028d053e9db2a36c9fbf08f7d7935844/lib/draper/cancancan.rb#L6-L12 | train |
jarib/celerity | lib/celerity/element.rb | Celerity.Element.method_missing | def method_missing(meth, *args, &blk)
assert_exists
meth = selector_to_attribute(meth)
if self.class::ATTRIBUTES.include?(meth) || (self.class == Element && @object.hasAttribute(meth.to_s))
return @object.getAttribute(meth.to_s)
end
Log.warn "Element\#method_missing calling super with #{meth.inspect}"
super
end | ruby | def method_missing(meth, *args, &blk)
assert_exists
meth = selector_to_attribute(meth)
if self.class::ATTRIBUTES.include?(meth) || (self.class == Element && @object.hasAttribute(meth.to_s))
return @object.getAttribute(meth.to_s)
end
Log.warn "Element\#method_missing calling super with #{meth.inspect}"
super
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"blk",
")",
"assert_exists",
"meth",
"=",
"selector_to_attribute",
"(",
"meth",
")",
"if",
"self",
".",
"class",
"::",
"ATTRIBUTES",
".",
"include?",
"(",
"meth",
")",
"||",
"(",
"self",
".",
"class",
"==",
"Element",
"&&",
"@object",
".",
"hasAttribute",
"(",
"meth",
".",
"to_s",
")",
")",
"return",
"@object",
".",
"getAttribute",
"(",
"meth",
".",
"to_s",
")",
"end",
"Log",
".",
"warn",
"\"Element\\#method_missing calling super with #{meth.inspect}\"",
"super",
"end"
] | Dynamically get element attributes.
@see ATTRIBUTES constant for a list of valid methods for a given element.
@return [String] The resulting attribute.
@raise [NoMethodError] if the element doesn't support this attribute. | [
"Dynamically",
"get",
"element",
"attributes",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/element.rb#L267-L277 | train |
tario/imageruby | lib/imageruby/bitmap/rbbitmap.rb | ImageRuby.RubyBitmapModl.get_pixel | def get_pixel(x,y)
index = (y*@width + x)
pointindex = index*3
Color.from_rgba(
@array[pointindex+2].ord,
@array[pointindex+1].ord,
@array[pointindex].ord,
@alpha ? @alpha[index].ord : 255
)
end | ruby | def get_pixel(x,y)
index = (y*@width + x)
pointindex = index*3
Color.from_rgba(
@array[pointindex+2].ord,
@array[pointindex+1].ord,
@array[pointindex].ord,
@alpha ? @alpha[index].ord : 255
)
end | [
"def",
"get_pixel",
"(",
"x",
",",
"y",
")",
"index",
"=",
"(",
"y",
"*",
"@width",
"+",
"x",
")",
"pointindex",
"=",
"index",
"*",
"3",
"Color",
".",
"from_rgba",
"(",
"@array",
"[",
"pointindex",
"+",
"2",
"]",
".",
"ord",
",",
"@array",
"[",
"pointindex",
"+",
"1",
"]",
".",
"ord",
",",
"@array",
"[",
"pointindex",
"]",
".",
"ord",
",",
"@alpha",
"?",
"@alpha",
"[",
"index",
"]",
".",
"ord",
":",
"255",
")",
"end"
] | return a Color object of a given x and y coord | [
"return",
"a",
"Color",
"object",
"of",
"a",
"given",
"x",
"and",
"y",
"coord"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/bitmap/rbbitmap.rb#L40-L50 | train |
tario/imageruby | lib/imageruby/bitmap/rbbitmap.rb | ImageRuby.RubyBitmapModl.set_pixel | def set_pixel(x,y,color)
index = (y*@width + x)
pointindex = index*3
@array[pointindex+2] = color.r.chr
@array[pointindex+1] = color.g.chr
@array[pointindex] = color.b.chr
if color.a != 255 then
@alpha = 255.chr*(@height * @width) unless @alpha
@alpha[index] = color.a.chr
end
self
end | ruby | def set_pixel(x,y,color)
index = (y*@width + x)
pointindex = index*3
@array[pointindex+2] = color.r.chr
@array[pointindex+1] = color.g.chr
@array[pointindex] = color.b.chr
if color.a != 255 then
@alpha = 255.chr*(@height * @width) unless @alpha
@alpha[index] = color.a.chr
end
self
end | [
"def",
"set_pixel",
"(",
"x",
",",
"y",
",",
"color",
")",
"index",
"=",
"(",
"y",
"*",
"@width",
"+",
"x",
")",
"pointindex",
"=",
"index",
"*",
"3",
"@array",
"[",
"pointindex",
"+",
"2",
"]",
"=",
"color",
".",
"r",
".",
"chr",
"@array",
"[",
"pointindex",
"+",
"1",
"]",
"=",
"color",
".",
"g",
".",
"chr",
"@array",
"[",
"pointindex",
"]",
"=",
"color",
".",
"b",
".",
"chr",
"if",
"color",
".",
"a",
"!=",
"255",
"then",
"@alpha",
"=",
"255",
".",
"chr",
"*",
"(",
"@height",
"*",
"@width",
")",
"unless",
"@alpha",
"@alpha",
"[",
"index",
"]",
"=",
"color",
".",
"a",
".",
"chr",
"end",
"self",
"end"
] | Creates a duplicate of the image
set a color value for a image | [
"Creates",
"a",
"duplicate",
"of",
"the",
"image",
"set",
"a",
"color",
"value",
"for",
"a",
"image"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/bitmap/rbbitmap.rb#L65-L79 | train |
famished-tiger/Rley | lib/rley/parse_tree_visitor.rb | Rley.ParseTreeVisitor.traverse_subnodes | def traverse_subnodes(aParentNode)
subnodes = aParentNode.subnodes
broadcast(:before_subnodes, aParentNode, subnodes)
# Let's proceed with the visit of subnodes
subnodes.each { |a_node| a_node.accept(self) }
broadcast(:after_subnodes, aParentNode, subnodes)
end | ruby | def traverse_subnodes(aParentNode)
subnodes = aParentNode.subnodes
broadcast(:before_subnodes, aParentNode, subnodes)
# Let's proceed with the visit of subnodes
subnodes.each { |a_node| a_node.accept(self) }
broadcast(:after_subnodes, aParentNode, subnodes)
end | [
"def",
"traverse_subnodes",
"(",
"aParentNode",
")",
"subnodes",
"=",
"aParentNode",
".",
"subnodes",
"broadcast",
"(",
":before_subnodes",
",",
"aParentNode",
",",
"subnodes",
")",
"subnodes",
".",
"each",
"{",
"|",
"a_node",
"|",
"a_node",
".",
"accept",
"(",
"self",
")",
"}",
"broadcast",
"(",
":after_subnodes",
",",
"aParentNode",
",",
"subnodes",
")",
"end"
] | Visit event. The visitor is about to visit the subnodes of a non
terminal node.
@param aParentNode [NonTeminalNode] the (non-terminal) parent node. | [
"Visit",
"event",
".",
"The",
"visitor",
"is",
"about",
"to",
"visit",
"the",
"subnodes",
"of",
"a",
"non",
"terminal",
"node",
"."
] | 307a8ed6a328182c3cb83a0c3ed04c04b7135a13 | https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/parse_tree_visitor.rb#L87-L95 | train |
famished-tiger/Rley | lib/rley/parse_tree_visitor.rb | Rley.ParseTreeVisitor.broadcast | def broadcast(msg, *args)
subscribers.each do |subscr|
next unless subscr.respond_to?(msg) || subscr.respond_to?(:accept_all)
subscr.send(msg, *args)
end
end | ruby | def broadcast(msg, *args)
subscribers.each do |subscr|
next unless subscr.respond_to?(msg) || subscr.respond_to?(:accept_all)
subscr.send(msg, *args)
end
end | [
"def",
"broadcast",
"(",
"msg",
",",
"*",
"args",
")",
"subscribers",
".",
"each",
"do",
"|",
"subscr",
"|",
"next",
"unless",
"subscr",
".",
"respond_to?",
"(",
"msg",
")",
"||",
"subscr",
".",
"respond_to?",
"(",
":accept_all",
")",
"subscr",
".",
"send",
"(",
"msg",
",",
"*",
"args",
")",
"end",
"end"
] | Send a notification to all subscribers.
@param msg [Symbol] event to notify
@param args [Array] arguments of the notification. | [
"Send",
"a",
"notification",
"to",
"all",
"subscribers",
"."
] | 307a8ed6a328182c3cb83a0c3ed04c04b7135a13 | https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/parse_tree_visitor.rb#L100-L106 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.goto | def goto(uri, headers = nil)
uri = "http://#{uri}" unless uri =~ %r{://}
request = HtmlUnit::WebRequest.new(::Java::JavaNet::URL.new(uri))
request.setAdditionalHeaders(headers) if headers
request.setCharset(@charset)
rescue_status_code_exception do
self.page = @webclient.getPage(request)
end
url()
end | ruby | def goto(uri, headers = nil)
uri = "http://#{uri}" unless uri =~ %r{://}
request = HtmlUnit::WebRequest.new(::Java::JavaNet::URL.new(uri))
request.setAdditionalHeaders(headers) if headers
request.setCharset(@charset)
rescue_status_code_exception do
self.page = @webclient.getPage(request)
end
url()
end | [
"def",
"goto",
"(",
"uri",
",",
"headers",
"=",
"nil",
")",
"uri",
"=",
"\"http://#{uri}\"",
"unless",
"uri",
"=~",
"%r{",
"}",
"request",
"=",
"HtmlUnit",
"::",
"WebRequest",
".",
"new",
"(",
"::",
"Java",
"::",
"JavaNet",
"::",
"URL",
".",
"new",
"(",
"uri",
")",
")",
"request",
".",
"setAdditionalHeaders",
"(",
"headers",
")",
"if",
"headers",
"request",
".",
"setCharset",
"(",
"@charset",
")",
"rescue_status_code_exception",
"do",
"self",
".",
"page",
"=",
"@webclient",
".",
"getPage",
"(",
"request",
")",
"end",
"url",
"(",
")",
"end"
] | Goto the given URL
@param [String] uri The url.
@param [Hash] (optional) a Hash of HTTP headers to use for the request.
@return [String] The url. | [
"Goto",
"the",
"given",
"URL"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L96-L109 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.send_keys | def send_keys(keys)
keys = keys.gsub(/\s*/, '').scan(/((?:\{[A-Z]+?\})|.)/u).flatten
keys.each do |key|
element = @page.getFocusedElement
case key
when "{TAB}"
@page.tabToNextElement
when /\w/
element.type(key)
else
raise NotImplementedError
end
end
end | ruby | def send_keys(keys)
keys = keys.gsub(/\s*/, '').scan(/((?:\{[A-Z]+?\})|.)/u).flatten
keys.each do |key|
element = @page.getFocusedElement
case key
when "{TAB}"
@page.tabToNextElement
when /\w/
element.type(key)
else
raise NotImplementedError
end
end
end | [
"def",
"send_keys",
"(",
"keys",
")",
"keys",
"=",
"keys",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
".",
"scan",
"(",
"/",
"\\{",
"\\}",
"/u",
")",
".",
"flatten",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"element",
"=",
"@page",
".",
"getFocusedElement",
"case",
"key",
"when",
"\"{TAB}\"",
"@page",
".",
"tabToNextElement",
"when",
"/",
"\\w",
"/",
"element",
".",
"type",
"(",
"key",
")",
"else",
"raise",
"NotImplementedError",
"end",
"end",
"end"
] | experimental - should be removed? | [
"experimental",
"-",
"should",
"be",
"removed?"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L400-L413 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.resynchronized | def resynchronized(&block)
old_controller = @webclient.ajaxController
@webclient.setAjaxController(::HtmlUnit::NicelyResynchronizingAjaxController.new)
yield self
@webclient.setAjaxController(old_controller)
end | ruby | def resynchronized(&block)
old_controller = @webclient.ajaxController
@webclient.setAjaxController(::HtmlUnit::NicelyResynchronizingAjaxController.new)
yield self
@webclient.setAjaxController(old_controller)
end | [
"def",
"resynchronized",
"(",
"&",
"block",
")",
"old_controller",
"=",
"@webclient",
".",
"ajaxController",
"@webclient",
".",
"setAjaxController",
"(",
"::",
"HtmlUnit",
"::",
"NicelyResynchronizingAjaxController",
".",
"new",
")",
"yield",
"self",
"@webclient",
".",
"setAjaxController",
"(",
"old_controller",
")",
"end"
] | Allows you to temporarily switch to HtmlUnit's NicelyResynchronizingAjaxController
to resynchronize ajax calls.
@browser.resynchronized do |b|
b.link(:id, 'trigger_ajax_call').click
end
@yieldparam [Celerity::Browser] browser The current browser object.
@see Celerity::Browser#new for how to configure the browser to always use this. | [
"Allows",
"you",
"to",
"temporarily",
"switch",
"to",
"HtmlUnit",
"s",
"NicelyResynchronizingAjaxController",
"to",
"resynchronize",
"ajax",
"calls",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L469-L474 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.confirm | def confirm(bool, &block)
blk = lambda { bool }
listener.add_listener(:confirm, &blk)
yield
listener.remove_listener(:confirm, blk)
end | ruby | def confirm(bool, &block)
blk = lambda { bool }
listener.add_listener(:confirm, &blk)
yield
listener.remove_listener(:confirm, blk)
end | [
"def",
"confirm",
"(",
"bool",
",",
"&",
"block",
")",
"blk",
"=",
"lambda",
"{",
"bool",
"}",
"listener",
".",
"add_listener",
"(",
":confirm",
",",
"&",
"blk",
")",
"yield",
"listener",
".",
"remove_listener",
"(",
":confirm",
",",
"blk",
")",
"end"
] | Specify a boolean value to click either 'OK' or 'Cancel' in any confirm
dialogs that might show up during the duration of the given block.
(Celerity only)
@param [Boolean] bool true to click 'OK', false to click 'cancel'
@param [Proc] block A block that will trigger the confirm() call(s). | [
"Specify",
"a",
"boolean",
"value",
"to",
"click",
"either",
"OK",
"or",
"Cancel",
"in",
"any",
"confirm",
"dialogs",
"that",
"might",
"show",
"up",
"during",
"the",
"duration",
"of",
"the",
"given",
"block",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L562-L568 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.add_checker | def add_checker(checker = nil, &block)
if block_given?
@error_checkers << block
elsif Proc === checker
@error_checkers << checker
else
raise ArgumentError, "argument must be a Proc or block"
end
end | ruby | def add_checker(checker = nil, &block)
if block_given?
@error_checkers << block
elsif Proc === checker
@error_checkers << checker
else
raise ArgumentError, "argument must be a Proc or block"
end
end | [
"def",
"add_checker",
"(",
"checker",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"block_given?",
"@error_checkers",
"<<",
"block",
"elsif",
"Proc",
"===",
"checker",
"@error_checkers",
"<<",
"checker",
"else",
"raise",
"ArgumentError",
",",
"\"argument must be a Proc or block\"",
"end",
"end"
] | Add a 'checker' proc that will be run on every page load
@param [Proc] checker The proc to be run (can also be given as a block)
@yieldparam [Celerity::Browser] browser The current browser object.
@raise [ArgumentError] if no Proc or block was given. | [
"Add",
"a",
"checker",
"proc",
"that",
"will",
"be",
"run",
"on",
"every",
"page",
"load"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L578-L586 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.page= | def page=(value)
return if @page == value
@page = value
if @page.respond_to?("getDocumentElement")
@object = @page.getDocumentElement || @object
elsif @page.is_a? HtmlUnit::UnexpectedPage
raise UnexpectedPageException, @page.getWebResponse.getContentType
end
render unless @viewer == DefaultViewer
run_error_checks
value
end | ruby | def page=(value)
return if @page == value
@page = value
if @page.respond_to?("getDocumentElement")
@object = @page.getDocumentElement || @object
elsif @page.is_a? HtmlUnit::UnexpectedPage
raise UnexpectedPageException, @page.getWebResponse.getContentType
end
render unless @viewer == DefaultViewer
run_error_checks
value
end | [
"def",
"page",
"=",
"(",
"value",
")",
"return",
"if",
"@page",
"==",
"value",
"@page",
"=",
"value",
"if",
"@page",
".",
"respond_to?",
"(",
"\"getDocumentElement\"",
")",
"@object",
"=",
"@page",
".",
"getDocumentElement",
"||",
"@object",
"elsif",
"@page",
".",
"is_a?",
"HtmlUnit",
"::",
"UnexpectedPage",
"raise",
"UnexpectedPageException",
",",
"@page",
".",
"getWebResponse",
".",
"getContentType",
"end",
"render",
"unless",
"@viewer",
"==",
"DefaultViewer",
"run_error_checks",
"value",
"end"
] | Sets the current page object for the browser
@param [HtmlUnit::HtmlPage] value The page to set.
@api private | [
"Sets",
"the",
"current",
"page",
"object",
"for",
"the",
"browser"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L746-L760 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.enable_event_listener | def enable_event_listener
@event_listener ||= lambda do |event|
self.page = @page ? @page.getEnclosingWindow.getEnclosedPage : event.getNewPage
end
listener.add_listener(:web_window_event, &@event_listener)
end | ruby | def enable_event_listener
@event_listener ||= lambda do |event|
self.page = @page ? @page.getEnclosingWindow.getEnclosedPage : event.getNewPage
end
listener.add_listener(:web_window_event, &@event_listener)
end | [
"def",
"enable_event_listener",
"@event_listener",
"||=",
"lambda",
"do",
"|",
"event",
"|",
"self",
".",
"page",
"=",
"@page",
"?",
"@page",
".",
"getEnclosingWindow",
".",
"getEnclosedPage",
":",
"event",
".",
"getNewPage",
"end",
"listener",
".",
"add_listener",
"(",
":web_window_event",
",",
"&",
"@event_listener",
")",
"end"
] | Enable Celerity's internal WebWindowEventListener
@api private | [
"Enable",
"Celerity",
"s",
"internal",
"WebWindowEventListener"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L787-L793 | train |
jarib/celerity | lib/celerity/browser.rb | Celerity.Browser.render | def render
@viewer.render_html(self.send(@render_type), url)
rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE
@viewer = DefaultViewer
end | ruby | def render
@viewer.render_html(self.send(@render_type), url)
rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE
@viewer = DefaultViewer
end | [
"def",
"render",
"@viewer",
".",
"render_html",
"(",
"self",
".",
"send",
"(",
"@render_type",
")",
",",
"url",
")",
"rescue",
"Errno",
"::",
"ECONNREFUSED",
",",
"Errno",
"::",
"ECONNRESET",
",",
"Errno",
"::",
"EPIPE",
"@viewer",
"=",
"DefaultViewer",
"end"
] | Render the current page on the connected viewer.
@api private | [
"Render",
"the",
"current",
"page",
"on",
"the",
"connected",
"viewer",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/browser.rb#L913-L917 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.[] | def [] (x,y)
if x.instance_of? Fixnum and y.instance_of? Fixnum
get_pixel(fixx(x),fixy(y))
else
x = (fixx(x)..fixx(x)) if x.instance_of? Fixnum
y = (fixy(y)..fixy(y)) if y.instance_of? Fixnum
if x.instance_of? Range
x = (fixx(x.first)..fixx(x.last))
end
if y.instance_of? Range
y = (fixy(y.first)..fixy(y.last))
end
newimg = Image.new(x.last + 1 - x.first, y.last + 1 - y.first)
width = x.count
(0..y.count).each do |y_|
destpointer = y_*width*3
origpointer = ((y.first + y_)*self.width + x.first)*3
newimg.pixel_data[destpointer..destpointer+width*3] =
self.pixel_data[origpointer..origpointer+width*3]
end
newimg
end
end | ruby | def [] (x,y)
if x.instance_of? Fixnum and y.instance_of? Fixnum
get_pixel(fixx(x),fixy(y))
else
x = (fixx(x)..fixx(x)) if x.instance_of? Fixnum
y = (fixy(y)..fixy(y)) if y.instance_of? Fixnum
if x.instance_of? Range
x = (fixx(x.first)..fixx(x.last))
end
if y.instance_of? Range
y = (fixy(y.first)..fixy(y.last))
end
newimg = Image.new(x.last + 1 - x.first, y.last + 1 - y.first)
width = x.count
(0..y.count).each do |y_|
destpointer = y_*width*3
origpointer = ((y.first + y_)*self.width + x.first)*3
newimg.pixel_data[destpointer..destpointer+width*3] =
self.pixel_data[origpointer..origpointer+width*3]
end
newimg
end
end | [
"def",
"[]",
"(",
"x",
",",
"y",
")",
"if",
"x",
".",
"instance_of?",
"Fixnum",
"and",
"y",
".",
"instance_of?",
"Fixnum",
"get_pixel",
"(",
"fixx",
"(",
"x",
")",
",",
"fixy",
"(",
"y",
")",
")",
"else",
"x",
"=",
"(",
"fixx",
"(",
"x",
")",
"..",
"fixx",
"(",
"x",
")",
")",
"if",
"x",
".",
"instance_of?",
"Fixnum",
"y",
"=",
"(",
"fixy",
"(",
"y",
")",
"..",
"fixy",
"(",
"y",
")",
")",
"if",
"y",
".",
"instance_of?",
"Fixnum",
"if",
"x",
".",
"instance_of?",
"Range",
"x",
"=",
"(",
"fixx",
"(",
"x",
".",
"first",
")",
"..",
"fixx",
"(",
"x",
".",
"last",
")",
")",
"end",
"if",
"y",
".",
"instance_of?",
"Range",
"y",
"=",
"(",
"fixy",
"(",
"y",
".",
"first",
")",
"..",
"fixy",
"(",
"y",
".",
"last",
")",
")",
"end",
"newimg",
"=",
"Image",
".",
"new",
"(",
"x",
".",
"last",
"+",
"1",
"-",
"x",
".",
"first",
",",
"y",
".",
"last",
"+",
"1",
"-",
"y",
".",
"first",
")",
"width",
"=",
"x",
".",
"count",
"(",
"0",
"..",
"y",
".",
"count",
")",
".",
"each",
"do",
"|",
"y_",
"|",
"destpointer",
"=",
"y_",
"*",
"width",
"*",
"3",
"origpointer",
"=",
"(",
"(",
"y",
".",
"first",
"+",
"y_",
")",
"*",
"self",
".",
"width",
"+",
"x",
".",
"first",
")",
"*",
"3",
"newimg",
".",
"pixel_data",
"[",
"destpointer",
"..",
"destpointer",
"+",
"width",
"*",
"3",
"]",
"=",
"self",
".",
"pixel_data",
"[",
"origpointer",
"..",
"origpointer",
"+",
"width",
"*",
"3",
"]",
"end",
"newimg",
"end",
"end"
] | Returs the color of a pixel locate in the given x and y coordinates
or a rectangle section of the image if a range is specified
Example
image[0,0] # return a Color object representing the color of the pixel at 0,0
image[0..20,10..30] # return a image object with the cropped rectagle with x between 0 and 20 and y between 10 and 30
image[0..20,20] # return a image object cropped rectagle with x between 0 and 20 and y equals 15 | [
"Returs",
"the",
"color",
"of",
"a",
"pixel",
"locate",
"in",
"the",
"given",
"x",
"and",
"y",
"coordinates",
"or",
"a",
"rectangle",
"section",
"of",
"the",
"image",
"if",
"a",
"range",
"is",
"specified"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L55-L84 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.[]= | def []= (x,y,obj)
if x.instance_of? Fixnum and y.instance_of? Fixnum
set_pixel(x,y,obj)
else
x = (x..x) if x.instance_of? Fixnum
y = (y..y) if y.instance_of? Fixnum
width = x.count
(0..y.count-1).each do |y_|
origpointer = y_*obj.width*3
destpointer = ((y.first + y_)*self.width + x.first)*3
self.pixel_data[destpointer..destpointer+obj.width*3-1] =
obj.pixel_data[origpointer..origpointer+obj.width*3-1]
end
end
end | ruby | def []= (x,y,obj)
if x.instance_of? Fixnum and y.instance_of? Fixnum
set_pixel(x,y,obj)
else
x = (x..x) if x.instance_of? Fixnum
y = (y..y) if y.instance_of? Fixnum
width = x.count
(0..y.count-1).each do |y_|
origpointer = y_*obj.width*3
destpointer = ((y.first + y_)*self.width + x.first)*3
self.pixel_data[destpointer..destpointer+obj.width*3-1] =
obj.pixel_data[origpointer..origpointer+obj.width*3-1]
end
end
end | [
"def",
"[]=",
"(",
"x",
",",
"y",
",",
"obj",
")",
"if",
"x",
".",
"instance_of?",
"Fixnum",
"and",
"y",
".",
"instance_of?",
"Fixnum",
"set_pixel",
"(",
"x",
",",
"y",
",",
"obj",
")",
"else",
"x",
"=",
"(",
"x",
"..",
"x",
")",
"if",
"x",
".",
"instance_of?",
"Fixnum",
"y",
"=",
"(",
"y",
"..",
"y",
")",
"if",
"y",
".",
"instance_of?",
"Fixnum",
"width",
"=",
"x",
".",
"count",
"(",
"0",
"..",
"y",
".",
"count",
"-",
"1",
")",
".",
"each",
"do",
"|",
"y_",
"|",
"origpointer",
"=",
"y_",
"*",
"obj",
".",
"width",
"*",
"3",
"destpointer",
"=",
"(",
"(",
"y",
".",
"first",
"+",
"y_",
")",
"*",
"self",
".",
"width",
"+",
"x",
".",
"first",
")",
"*",
"3",
"self",
".",
"pixel_data",
"[",
"destpointer",
"..",
"destpointer",
"+",
"obj",
".",
"width",
"*",
"3",
"-",
"1",
"]",
"=",
"obj",
".",
"pixel_data",
"[",
"origpointer",
"..",
"origpointer",
"+",
"obj",
".",
"width",
"*",
"3",
"-",
"1",
"]",
"end",
"end",
"end"
] | Set the color of a pixel locate in the given x and y coordinates
or replace a rectangle section of the image with other image of equal dimensions
if a range is specified
Example
image[0,0] = Color.red # set the color of pixel at 0,0 to Color.red
image[0..20,10..30] = other_image # replace the rectagle with x between 0 and 20 and y between 10 and 30 with other_image | [
"Set",
"the",
"color",
"of",
"a",
"pixel",
"locate",
"in",
"the",
"given",
"x",
"and",
"y",
"coordinates",
"or",
"replace",
"a",
"rectangle",
"section",
"of",
"the",
"image",
"with",
"other",
"image",
"of",
"equal",
"dimensions",
"if",
"a",
"range",
"is",
"specified"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L95-L112 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.each_pixel | def each_pixel
(0..@width-1).each do |x|
(0..@height-1).each do |y|
yield(x,y,get_pixel(x,y))
end
end
end | ruby | def each_pixel
(0..@width-1).each do |x|
(0..@height-1).each do |y|
yield(x,y,get_pixel(x,y))
end
end
end | [
"def",
"each_pixel",
"(",
"0",
"..",
"@width",
"-",
"1",
")",
".",
"each",
"do",
"|",
"x",
"|",
"(",
"0",
"..",
"@height",
"-",
"1",
")",
".",
"each",
"do",
"|",
"y",
"|",
"yield",
"(",
"x",
",",
"y",
",",
"get_pixel",
"(",
"x",
",",
"y",
")",
")",
"end",
"end",
"end"
] | Walks each pixel on the image, block is mandantory to call this function and return
as yield block calls x,y and pixel color for each pixel of the image
This function does not allow to modify any color information of the image (use map_pixel for that)
Examples:
image.each_pixel do |x,y,color|
print "pixel at (#{x},#{y}): #{color.inspect}\n"
end | [
"Walks",
"each",
"pixel",
"on",
"the",
"image",
"block",
"is",
"mandantory",
"to",
"call",
"this",
"function",
"and",
"return",
"as",
"yield",
"block",
"calls",
"x",
"y",
"and",
"pixel",
"color",
"for",
"each",
"pixel",
"of",
"the",
"image"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L198-L204 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.map_pixel | def map_pixel
Image.new(@width, @height) do |x,y|
yield(x,y,get_pixel(x,y))
end
end | ruby | def map_pixel
Image.new(@width, @height) do |x,y|
yield(x,y,get_pixel(x,y))
end
end | [
"def",
"map_pixel",
"Image",
".",
"new",
"(",
"@width",
",",
"@height",
")",
"do",
"|",
"x",
",",
"y",
"|",
"yield",
"(",
"x",
",",
"y",
",",
"get_pixel",
"(",
"x",
",",
"y",
")",
")",
"end",
"end"
] | Creates a new image of same dimensions in which each pixel is replaced with the value returned
by the block passed as parameter, the block receives the coordinates and color of each pixel
Example
image_without_red = image.map_pixel{|x,y,color| color.r = 0; color } # remove color channel of all pixels | [
"Creates",
"a",
"new",
"image",
"of",
"same",
"dimensions",
"in",
"which",
"each",
"pixel",
"is",
"replaced",
"with",
"the",
"value",
"returned",
"by",
"the",
"block",
"passed",
"as",
"parameter",
"the",
"block",
"receives",
"the",
"coordinates",
"and",
"color",
"of",
"each",
"pixel"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L212-L216 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.map_pixel! | def map_pixel!
each_pixel do |x,y,color|
set_pixel(x,y, yield(x,y,get_pixel(x,y)))
end
self
end | ruby | def map_pixel!
each_pixel do |x,y,color|
set_pixel(x,y, yield(x,y,get_pixel(x,y)))
end
self
end | [
"def",
"map_pixel!",
"each_pixel",
"do",
"|",
"x",
",",
"y",
",",
"color",
"|",
"set_pixel",
"(",
"x",
",",
"y",
",",
"yield",
"(",
"x",
",",
"y",
",",
"get_pixel",
"(",
"x",
",",
"y",
")",
")",
")",
"end",
"self",
"end"
] | Replace each pixel of the image with the value returned
by the block passed as parameter, the block receives the coordinates and color of each pixel
Example
image.map_pixel!{|x,y,color| color.r = 0; color } # remove color channel of all pixels | [
"Replace",
"each",
"pixel",
"of",
"the",
"image",
"with",
"the",
"value",
"returned",
"by",
"the",
"block",
"passed",
"as",
"parameter",
"the",
"block",
"receives",
"the",
"coordinates",
"and",
"color",
"of",
"each",
"pixel"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L224-L230 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.color_replace | def color_replace(color1, color2)
newimage = self.dup
newimage.color_replace!(color1,color2)
newimage
end | ruby | def color_replace(color1, color2)
newimage = self.dup
newimage.color_replace!(color1,color2)
newimage
end | [
"def",
"color_replace",
"(",
"color1",
",",
"color2",
")",
"newimage",
"=",
"self",
".",
"dup",
"newimage",
".",
"color_replace!",
"(",
"color1",
",",
"color2",
")",
"newimage",
"end"
] | Duplicate the image and then call color_replace! method with the given parameters | [
"Duplicate",
"the",
"image",
"and",
"then",
"call",
"color_replace!",
"method",
"with",
"the",
"given",
"parameters"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L233-L238 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.color_replace! | def color_replace!( color1, color2)
strcolor1 = color1.to_s
strcolor2 = color2.to_s
a = color2.a.chr
(0..width*height).each do |i|
if pixel_data[i*3..i*3+2] == strcolor1 then
pixel_data[i*3..i*3+2] = strcolor2
alpha_data[i] = a
end
end
end | ruby | def color_replace!( color1, color2)
strcolor1 = color1.to_s
strcolor2 = color2.to_s
a = color2.a.chr
(0..width*height).each do |i|
if pixel_data[i*3..i*3+2] == strcolor1 then
pixel_data[i*3..i*3+2] = strcolor2
alpha_data[i] = a
end
end
end | [
"def",
"color_replace!",
"(",
"color1",
",",
"color2",
")",
"strcolor1",
"=",
"color1",
".",
"to_s",
"strcolor2",
"=",
"color2",
".",
"to_s",
"a",
"=",
"color2",
".",
"a",
".",
"chr",
"(",
"0",
"..",
"width",
"*",
"height",
")",
".",
"each",
"do",
"|",
"i",
"|",
"if",
"pixel_data",
"[",
"i",
"*",
"3",
"..",
"i",
"*",
"3",
"+",
"2",
"]",
"==",
"strcolor1",
"then",
"pixel_data",
"[",
"i",
"*",
"3",
"..",
"i",
"*",
"3",
"+",
"2",
"]",
"=",
"strcolor2",
"alpha_data",
"[",
"i",
"]",
"=",
"a",
"end",
"end",
"end"
] | Replace the color given in the first argument by the color given in the second with alpha values
Examples
image.color_replace!(Color.red, Color.black) # replace red with black
image.color_replace!(Color.black, Color.coerce([0,0,0,128]) ) # replace black with %50 transparent black | [
"Replace",
"the",
"color",
"given",
"in",
"the",
"first",
"argument",
"by",
"the",
"color",
"given",
"in",
"the",
"second",
"with",
"alpha",
"values"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L246-L258 | train |
tario/imageruby | lib/imageruby/pureruby.rb | ImageRuby.PureRubyImageMethods.mask | def mask(color1 = nil)
color1 = color1 || Color.from_rgb(255,255,255)
color2 = color1.dup
color2.a = 0
color_replace(color1,color2)
end | ruby | def mask(color1 = nil)
color1 = color1 || Color.from_rgb(255,255,255)
color2 = color1.dup
color2.a = 0
color_replace(color1,color2)
end | [
"def",
"mask",
"(",
"color1",
"=",
"nil",
")",
"color1",
"=",
"color1",
"||",
"Color",
".",
"from_rgb",
"(",
"255",
",",
"255",
",",
"255",
")",
"color2",
"=",
"color1",
".",
"dup",
"color2",
".",
"a",
"=",
"0",
"color_replace",
"(",
"color1",
",",
"color2",
")",
"end"
] | Replace a color with %100 transparency, useful for mask drawing
Example
masked = other_image.mask(Color.black)
image.draw(0,0,masked) # draw the image without the black pixels | [
"Replace",
"a",
"color",
"with",
"%100",
"transparency",
"useful",
"for",
"mask",
"drawing"
] | ba38c3e4a5c8c068566501f0e73357fd219535e4 | https://github.com/tario/imageruby/blob/ba38c3e4a5c8c068566501f0e73357fd219535e4/lib/imageruby/pureruby.rb#L266-L272 | train |
postmodern/tdiff | lib/tdiff/unordered.rb | TDiff.Unordered.tdiff_unordered | def tdiff_unordered(tree,&block)
return enum_for(:tdiff_unordered,tree) unless block
# check if the nodes differ
unless tdiff_equal(tree)
yield '-', self
yield '+', tree
return self
end
yield ' ', self
tdiff_recursive_unordered(tree,&block)
return self
end | ruby | def tdiff_unordered(tree,&block)
return enum_for(:tdiff_unordered,tree) unless block
# check if the nodes differ
unless tdiff_equal(tree)
yield '-', self
yield '+', tree
return self
end
yield ' ', self
tdiff_recursive_unordered(tree,&block)
return self
end | [
"def",
"tdiff_unordered",
"(",
"tree",
",",
"&",
"block",
")",
"return",
"enum_for",
"(",
":tdiff_unordered",
",",
"tree",
")",
"unless",
"block",
"unless",
"tdiff_equal",
"(",
"tree",
")",
"yield",
"'-'",
",",
"self",
"yield",
"'+'",
",",
"tree",
"return",
"self",
"end",
"yield",
"' '",
",",
"self",
"tdiff_recursive_unordered",
"(",
"tree",
",",
"&",
"block",
")",
"return",
"self",
"end"
] | Finds the differences between `self` and another tree, not respecting
the order of the nodes.
@param [#tdiff_each_child] tree
The other tree.
@yield [change, node]
The given block will be passed the added or removed nodes.
@yieldparam [' ', '+', '-'] change
The state-change of the node.
@yieldparam [Object] node
A node from one of the two trees.
@return [Enumerator]
If no block is given, an Enumerator object will be returned.
@since 0.2.0 | [
"Finds",
"the",
"differences",
"between",
"self",
"and",
"another",
"tree",
"not",
"respecting",
"the",
"order",
"of",
"the",
"nodes",
"."
] | 238f13540529f492726a5d152a833475c1a42f32 | https://github.com/postmodern/tdiff/blob/238f13540529f492726a5d152a833475c1a42f32/lib/tdiff/unordered.rb#L37-L51 | train |
postmodern/tdiff | lib/tdiff/unordered.rb | TDiff.Unordered.tdiff_recursive_unordered | def tdiff_recursive_unordered(tree,&block)
x = enum_for(:tdiff_each_child,self)
y = enum_for(:tdiff_each_child,tree)
unchanged = {}
changes = []
x.each_with_index do |xi,i|
y.each_with_index do |yj,j|
if (!unchanged.has_value?(yj) && xi.tdiff_equal(yj))
unchanged[xi] = yj
changes << [i, ' ', xi]
break
end
end
unless unchanged.has_key?(xi)
changes << [i, '-', xi]
end
end
y.each_with_index do |yj,j|
unless unchanged.has_value?(yj)
changes << [j, '+', yj]
end
end
# order the changes by index to match the behavior of `tdiff`
changes.sort_by { |change| change[0] }.each do |index,change,node|
yield change, node
end
# explicitly release the changes variable
changes = nil
# recurse down the unchanged nodes
unchanged.each do |xi,yj|
xi.tdiff_recursive_unordered(yj,&block)
end
unchanged = nil
end | ruby | def tdiff_recursive_unordered(tree,&block)
x = enum_for(:tdiff_each_child,self)
y = enum_for(:tdiff_each_child,tree)
unchanged = {}
changes = []
x.each_with_index do |xi,i|
y.each_with_index do |yj,j|
if (!unchanged.has_value?(yj) && xi.tdiff_equal(yj))
unchanged[xi] = yj
changes << [i, ' ', xi]
break
end
end
unless unchanged.has_key?(xi)
changes << [i, '-', xi]
end
end
y.each_with_index do |yj,j|
unless unchanged.has_value?(yj)
changes << [j, '+', yj]
end
end
# order the changes by index to match the behavior of `tdiff`
changes.sort_by { |change| change[0] }.each do |index,change,node|
yield change, node
end
# explicitly release the changes variable
changes = nil
# recurse down the unchanged nodes
unchanged.each do |xi,yj|
xi.tdiff_recursive_unordered(yj,&block)
end
unchanged = nil
end | [
"def",
"tdiff_recursive_unordered",
"(",
"tree",
",",
"&",
"block",
")",
"x",
"=",
"enum_for",
"(",
":tdiff_each_child",
",",
"self",
")",
"y",
"=",
"enum_for",
"(",
":tdiff_each_child",
",",
"tree",
")",
"unchanged",
"=",
"{",
"}",
"changes",
"=",
"[",
"]",
"x",
".",
"each_with_index",
"do",
"|",
"xi",
",",
"i",
"|",
"y",
".",
"each_with_index",
"do",
"|",
"yj",
",",
"j",
"|",
"if",
"(",
"!",
"unchanged",
".",
"has_value?",
"(",
"yj",
")",
"&&",
"xi",
".",
"tdiff_equal",
"(",
"yj",
")",
")",
"unchanged",
"[",
"xi",
"]",
"=",
"yj",
"changes",
"<<",
"[",
"i",
",",
"' '",
",",
"xi",
"]",
"break",
"end",
"end",
"unless",
"unchanged",
".",
"has_key?",
"(",
"xi",
")",
"changes",
"<<",
"[",
"i",
",",
"'-'",
",",
"xi",
"]",
"end",
"end",
"y",
".",
"each_with_index",
"do",
"|",
"yj",
",",
"j",
"|",
"unless",
"unchanged",
".",
"has_value?",
"(",
"yj",
")",
"changes",
"<<",
"[",
"j",
",",
"'+'",
",",
"yj",
"]",
"end",
"end",
"changes",
".",
"sort_by",
"{",
"|",
"change",
"|",
"change",
"[",
"0",
"]",
"}",
".",
"each",
"do",
"|",
"index",
",",
"change",
",",
"node",
"|",
"yield",
"change",
",",
"node",
"end",
"changes",
"=",
"nil",
"unchanged",
".",
"each",
"do",
"|",
"xi",
",",
"yj",
"|",
"xi",
".",
"tdiff_recursive_unordered",
"(",
"yj",
",",
"&",
"block",
")",
"end",
"unchanged",
"=",
"nil",
"end"
] | Recursively compares the differences between the children nodes,
without respecting the order of the nodes.
@param [#tdiff_each_child] tree
The other tree.
@yield [change, node]
The given block will be passed the added or removed nodes.
@yieldparam [' ', '+', '-'] change
The state-change of the node.
@yieldparam [Object] node
A node from one of the two trees.
@since 0.3.2 | [
"Recursively",
"compares",
"the",
"differences",
"between",
"the",
"children",
"nodes",
"without",
"respecting",
"the",
"order",
"of",
"the",
"nodes",
"."
] | 238f13540529f492726a5d152a833475c1a42f32 | https://github.com/postmodern/tdiff/blob/238f13540529f492726a5d152a833475c1a42f32/lib/tdiff/unordered.rb#L73-L114 | train |
DimoMohit/onedrive | lib/one_drive.rb | OneDrive.V1.get_drive | def get_drive drive_id
url = base_api_url + "/drives/#{drive_id}"
@drives = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | ruby | def get_drive drive_id
url = base_api_url + "/drives/#{drive_id}"
@drives = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | [
"def",
"get_drive",
"drive_id",
"url",
"=",
"base_api_url",
"+",
"\"/drives/#{drive_id}\"",
"@drives",
"=",
"JSON",
".",
"parse",
"(",
"HTTParty",
".",
"get",
"(",
"url",
",",
"headers",
":",
"set_headers",
")",
".",
"body",
")",
"end"
] | Get a drive by ID | [
"Get",
"a",
"drive",
"by",
"ID"
] | e61b5caa8be5be4038d59846e3b6aab606b12a7c | https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L44-L47 | train |
DimoMohit/onedrive | lib/one_drive.rb | OneDrive.V1.get_users_drive | def get_users_drive id_or_user_principal_name
url = base_api_url + "/users/#{id_or_user_principal_name}/drive"
@drives = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | ruby | def get_users_drive id_or_user_principal_name
url = base_api_url + "/users/#{id_or_user_principal_name}/drive"
@drives = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | [
"def",
"get_users_drive",
"id_or_user_principal_name",
"url",
"=",
"base_api_url",
"+",
"\"/users/#{id_or_user_principal_name}/drive\"",
"@drives",
"=",
"JSON",
".",
"parse",
"(",
"HTTParty",
".",
"get",
"(",
"url",
",",
"headers",
":",
"set_headers",
")",
".",
"body",
")",
"end"
] | Get a user's OneDrive | [
"Get",
"a",
"user",
"s",
"OneDrive"
] | e61b5caa8be5be4038d59846e3b6aab606b12a7c | https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L49-L52 | train |
DimoMohit/onedrive | lib/one_drive.rb | OneDrive.V1.get_my_drive | def get_my_drive
url = base_api_url + "/me/drive"
@my_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | ruby | def get_my_drive
url = base_api_url + "/me/drive"
@my_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | [
"def",
"get_my_drive",
"url",
"=",
"base_api_url",
"+",
"\"/me/drive\"",
"@my_drive",
"=",
"JSON",
".",
"parse",
"(",
"HTTParty",
".",
"get",
"(",
"url",
",",
"headers",
":",
"set_headers",
")",
".",
"body",
")",
"end"
] | Get a current user's OneDrive | [
"Get",
"a",
"current",
"user",
"s",
"OneDrive"
] | e61b5caa8be5be4038d59846e3b6aab606b12a7c | https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L54-L57 | train |
DimoMohit/onedrive | lib/one_drive.rb | OneDrive.V1.get_library_for_site | def get_library_for_site site_id
url = base_api_url + "/sites/#{site_id}/drive"
@drives = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | ruby | def get_library_for_site site_id
url = base_api_url + "/sites/#{site_id}/drive"
@drives = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | [
"def",
"get_library_for_site",
"site_id",
"url",
"=",
"base_api_url",
"+",
"\"/sites/#{site_id}/drive\"",
"@drives",
"=",
"JSON",
".",
"parse",
"(",
"HTTParty",
".",
"get",
"(",
"url",
",",
"headers",
":",
"set_headers",
")",
".",
"body",
")",
"end"
] | Get the document library for a site | [
"Get",
"the",
"document",
"library",
"for",
"a",
"site"
] | e61b5caa8be5be4038d59846e3b6aab606b12a7c | https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L59-L62 | train |
DimoMohit/onedrive | lib/one_drive.rb | OneDrive.V1.get_special_folder_by_name | def get_special_folder_by_name name
url = base_api_url + "/me/drive/special/#{name}"
@special_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | ruby | def get_special_folder_by_name name
url = base_api_url + "/me/drive/special/#{name}"
@special_drive = JSON.parse(HTTParty.get(url,headers: set_headers).body)
end | [
"def",
"get_special_folder_by_name",
"name",
"url",
"=",
"base_api_url",
"+",
"\"/me/drive/special/#{name}\"",
"@special_drive",
"=",
"JSON",
".",
"parse",
"(",
"HTTParty",
".",
"get",
"(",
"url",
",",
"headers",
":",
"set_headers",
")",
".",
"body",
")",
"end"
] | Get a special folder by name | [
"Get",
"a",
"special",
"folder",
"by",
"name"
] | e61b5caa8be5be4038d59846e3b6aab606b12a7c | https://github.com/DimoMohit/onedrive/blob/e61b5caa8be5be4038d59846e3b6aab606b12a7c/lib/one_drive.rb#L64-L67 | train |
jarib/celerity | lib/celerity/elements/table_row.rb | Celerity.TableRow.child_cell | def child_cell(index)
assert_exists
if (index - Celerity.index_offset) >= @cells.length
raise UnknownCellException, "Unable to locate a cell at index #{index}"
end
TableCell.new(self, :object, @cells[index - Celerity.index_offset])
end | ruby | def child_cell(index)
assert_exists
if (index - Celerity.index_offset) >= @cells.length
raise UnknownCellException, "Unable to locate a cell at index #{index}"
end
TableCell.new(self, :object, @cells[index - Celerity.index_offset])
end | [
"def",
"child_cell",
"(",
"index",
")",
"assert_exists",
"if",
"(",
"index",
"-",
"Celerity",
".",
"index_offset",
")",
">=",
"@cells",
".",
"length",
"raise",
"UnknownCellException",
",",
"\"Unable to locate a cell at index #{index}\"",
"end",
"TableCell",
".",
"new",
"(",
"self",
",",
":object",
",",
"@cells",
"[",
"index",
"-",
"Celerity",
".",
"index_offset",
"]",
")",
"end"
] | Get the child cell at the given index | [
"Get",
"the",
"child",
"cell",
"at",
"the",
"given",
"index"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/table_row.rb#L33-L41 | train |
jarib/celerity | lib/celerity/elements/table.rb | Celerity.Table.to_a | def to_a
assert_exists
# @object.getRows.map do |table_row|
# table_row.getCells.map { |td| td.asText.strip }
# end
rows.map do |table_row|
table_row.map { |td| td.text }
end
end | ruby | def to_a
assert_exists
# @object.getRows.map do |table_row|
# table_row.getCells.map { |td| td.asText.strip }
# end
rows.map do |table_row|
table_row.map { |td| td.text }
end
end | [
"def",
"to_a",
"assert_exists",
"rows",
".",
"map",
"do",
"|",
"table_row",
"|",
"table_row",
".",
"map",
"{",
"|",
"td",
"|",
"td",
".",
"text",
"}",
"end",
"end"
] | Returns the text of each cell in the the table as a two-dimensional array.
@return [Array<Array<String>>] | [
"Returns",
"the",
"text",
"of",
"each",
"cell",
"in",
"the",
"the",
"table",
"as",
"a",
"two",
"-",
"dimensional",
"array",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/table.rb#L135-L143 | train |
sj26/skinny | lib/skinny.rb | Skinny.Websocket.start! | def start!
# Steal any remaining data from rack.input
@buffer = @env[Thin::Request::RACK_INPUT].read + @buffer
# Remove references to Thin connection objects, freeing memory
@env.delete Thin::Request::RACK_INPUT
@env.delete Thin::Request::ASYNC_CALLBACK
@env.delete Thin::Request::ASYNC_CLOSE
# Figure out which version we're using
@version = @env['HTTP_SEC_WEBSOCKET_VERSION']
@version ||= "hixie-76" if @env.has_key?('HTTP_SEC_WEBSOCKET_KEY1') and @env.has_key?('HTTP_SEC_WEBSOCKET_KEY2')
@version ||= "hixie-75"
# Pull out the details we care about
@origin ||= @env['HTTP_SEC_WEBSOCKET_ORIGIN'] || @env['HTTP_ORIGIN']
@location ||= "ws#{secure? ? 's' : ''}://#{@env['HTTP_HOST']}#{@env['REQUEST_PATH']}"
@protocol ||= @env['HTTP_SEC_WEBSOCKET_PROTOCOL'] || @env['HTTP_WEBSOCKET_PROTOCOL']
EM.next_tick { callback :on_start, self rescue error! "Error in start callback" }
# Queue up the actual handshake
EM.next_tick method :handshake!
@state = :started
# Return self so we can be used as a response
self
rescue
error! "Error starting connection"
end | ruby | def start!
# Steal any remaining data from rack.input
@buffer = @env[Thin::Request::RACK_INPUT].read + @buffer
# Remove references to Thin connection objects, freeing memory
@env.delete Thin::Request::RACK_INPUT
@env.delete Thin::Request::ASYNC_CALLBACK
@env.delete Thin::Request::ASYNC_CLOSE
# Figure out which version we're using
@version = @env['HTTP_SEC_WEBSOCKET_VERSION']
@version ||= "hixie-76" if @env.has_key?('HTTP_SEC_WEBSOCKET_KEY1') and @env.has_key?('HTTP_SEC_WEBSOCKET_KEY2')
@version ||= "hixie-75"
# Pull out the details we care about
@origin ||= @env['HTTP_SEC_WEBSOCKET_ORIGIN'] || @env['HTTP_ORIGIN']
@location ||= "ws#{secure? ? 's' : ''}://#{@env['HTTP_HOST']}#{@env['REQUEST_PATH']}"
@protocol ||= @env['HTTP_SEC_WEBSOCKET_PROTOCOL'] || @env['HTTP_WEBSOCKET_PROTOCOL']
EM.next_tick { callback :on_start, self rescue error! "Error in start callback" }
# Queue up the actual handshake
EM.next_tick method :handshake!
@state = :started
# Return self so we can be used as a response
self
rescue
error! "Error starting connection"
end | [
"def",
"start!",
"@buffer",
"=",
"@env",
"[",
"Thin",
"::",
"Request",
"::",
"RACK_INPUT",
"]",
".",
"read",
"+",
"@buffer",
"@env",
".",
"delete",
"Thin",
"::",
"Request",
"::",
"RACK_INPUT",
"@env",
".",
"delete",
"Thin",
"::",
"Request",
"::",
"ASYNC_CALLBACK",
"@env",
".",
"delete",
"Thin",
"::",
"Request",
"::",
"ASYNC_CLOSE",
"@version",
"=",
"@env",
"[",
"'HTTP_SEC_WEBSOCKET_VERSION'",
"]",
"@version",
"||=",
"\"hixie-76\"",
"if",
"@env",
".",
"has_key?",
"(",
"'HTTP_SEC_WEBSOCKET_KEY1'",
")",
"and",
"@env",
".",
"has_key?",
"(",
"'HTTP_SEC_WEBSOCKET_KEY2'",
")",
"@version",
"||=",
"\"hixie-75\"",
"@origin",
"||=",
"@env",
"[",
"'HTTP_SEC_WEBSOCKET_ORIGIN'",
"]",
"||",
"@env",
"[",
"'HTTP_ORIGIN'",
"]",
"@location",
"||=",
"\"ws#{secure? ? 's' : ''}://#{@env['HTTP_HOST']}#{@env['REQUEST_PATH']}\"",
"@protocol",
"||=",
"@env",
"[",
"'HTTP_SEC_WEBSOCKET_PROTOCOL'",
"]",
"||",
"@env",
"[",
"'HTTP_WEBSOCKET_PROTOCOL'",
"]",
"EM",
".",
"next_tick",
"{",
"callback",
":on_start",
",",
"self",
"rescue",
"error!",
"\"Error in start callback\"",
"}",
"EM",
".",
"next_tick",
"method",
":handshake!",
"@state",
"=",
":started",
"self",
"rescue",
"error!",
"\"Error starting connection\"",
"end"
] | Start the websocket connection | [
"Start",
"the",
"websocket",
"connection"
] | 5b3e222376dd18f6432825a8b05dc691f1f5d5f5 | https://github.com/sj26/skinny/blob/5b3e222376dd18f6432825a8b05dc691f1f5d5f5/lib/skinny.rb#L102-L132 | train |
sj26/skinny | lib/skinny.rb | Skinny.Websocket.send_frame | def send_frame opcode, payload="", masked=false
payload = payload.dup.force_encoding("ASCII-8BIT") if payload.respond_to? :force_encoding
payload_length = payload.bytesize
# We don't support continuations (yet), so always send fin
fin_byte = 0x80
send_data [fin_byte | opcode].pack("C")
# We shouldn't be sending mask, we're a server only
masked_byte = masked ? 0x80 : 0x00
if payload_length <= 125
send_data [masked_byte | payload_length].pack("C")
elsif payload_length < 2 ** 16
send_data [masked_byte | 126].pack("C")
send_data [payload_length].pack("n")
else
send_data [masked_byte | 127].pack("C")
send_data [payload_length / (2 ** 32), payload_length % (2 ** 32)].pack("NN")
end
if payload_length
if masked
mask_key = Array.new(4) { rand(256) }.pack("C*")
send_data mask_key
payload = mask payload, mask_key
end
send_data payload
end
end | ruby | def send_frame opcode, payload="", masked=false
payload = payload.dup.force_encoding("ASCII-8BIT") if payload.respond_to? :force_encoding
payload_length = payload.bytesize
# We don't support continuations (yet), so always send fin
fin_byte = 0x80
send_data [fin_byte | opcode].pack("C")
# We shouldn't be sending mask, we're a server only
masked_byte = masked ? 0x80 : 0x00
if payload_length <= 125
send_data [masked_byte | payload_length].pack("C")
elsif payload_length < 2 ** 16
send_data [masked_byte | 126].pack("C")
send_data [payload_length].pack("n")
else
send_data [masked_byte | 127].pack("C")
send_data [payload_length / (2 ** 32), payload_length % (2 ** 32)].pack("NN")
end
if payload_length
if masked
mask_key = Array.new(4) { rand(256) }.pack("C*")
send_data mask_key
payload = mask payload, mask_key
end
send_data payload
end
end | [
"def",
"send_frame",
"opcode",
",",
"payload",
"=",
"\"\"",
",",
"masked",
"=",
"false",
"payload",
"=",
"payload",
".",
"dup",
".",
"force_encoding",
"(",
"\"ASCII-8BIT\"",
")",
"if",
"payload",
".",
"respond_to?",
":force_encoding",
"payload_length",
"=",
"payload",
".",
"bytesize",
"fin_byte",
"=",
"0x80",
"send_data",
"[",
"fin_byte",
"|",
"opcode",
"]",
".",
"pack",
"(",
"\"C\"",
")",
"masked_byte",
"=",
"masked",
"?",
"0x80",
":",
"0x00",
"if",
"payload_length",
"<=",
"125",
"send_data",
"[",
"masked_byte",
"|",
"payload_length",
"]",
".",
"pack",
"(",
"\"C\"",
")",
"elsif",
"payload_length",
"<",
"2",
"**",
"16",
"send_data",
"[",
"masked_byte",
"|",
"126",
"]",
".",
"pack",
"(",
"\"C\"",
")",
"send_data",
"[",
"payload_length",
"]",
".",
"pack",
"(",
"\"n\"",
")",
"else",
"send_data",
"[",
"masked_byte",
"|",
"127",
"]",
".",
"pack",
"(",
"\"C\"",
")",
"send_data",
"[",
"payload_length",
"/",
"(",
"2",
"**",
"32",
")",
",",
"payload_length",
"%",
"(",
"2",
"**",
"32",
")",
"]",
".",
"pack",
"(",
"\"NN\"",
")",
"end",
"if",
"payload_length",
"if",
"masked",
"mask_key",
"=",
"Array",
".",
"new",
"(",
"4",
")",
"{",
"rand",
"(",
"256",
")",
"}",
".",
"pack",
"(",
"\"C*\"",
")",
"send_data",
"mask_key",
"payload",
"=",
"mask",
"payload",
",",
"mask_key",
"end",
"send_data",
"payload",
"end",
"end"
] | This is for post-hixie-76 versions only | [
"This",
"is",
"for",
"post",
"-",
"hixie",
"-",
"76",
"versions",
"only"
] | 5b3e222376dd18f6432825a8b05dc691f1f5d5f5 | https://github.com/sj26/skinny/blob/5b3e222376dd18f6432825a8b05dc691f1f5d5f5/lib/skinny.rb#L341-L373 | train |
sj26/skinny | lib/skinny.rb | Skinny.Websocket.finish! | def finish!
if hixie_75? or hixie_76?
send_data "\xff\x00"
else
send_frame OPCODE_CLOSE
end
EM.next_tick { callback(:on_finish, self) rescue error! "Error in finish callback" }
EM.next_tick { close_connection_after_writing }
@state = :finished
rescue
error! "Error finishing WebSocket connection"
end | ruby | def finish!
if hixie_75? or hixie_76?
send_data "\xff\x00"
else
send_frame OPCODE_CLOSE
end
EM.next_tick { callback(:on_finish, self) rescue error! "Error in finish callback" }
EM.next_tick { close_connection_after_writing }
@state = :finished
rescue
error! "Error finishing WebSocket connection"
end | [
"def",
"finish!",
"if",
"hixie_75?",
"or",
"hixie_76?",
"send_data",
"\"\\xff\\x00\"",
"else",
"send_frame",
"OPCODE_CLOSE",
"end",
"EM",
".",
"next_tick",
"{",
"callback",
"(",
":on_finish",
",",
"self",
")",
"rescue",
"error!",
"\"Error in finish callback\"",
"}",
"EM",
".",
"next_tick",
"{",
"close_connection_after_writing",
"}",
"@state",
"=",
":finished",
"rescue",
"error!",
"\"Error finishing WebSocket connection\"",
"end"
] | Finish the connection read for closing | [
"Finish",
"the",
"connection",
"read",
"for",
"closing"
] | 5b3e222376dd18f6432825a8b05dc691f1f5d5f5 | https://github.com/sj26/skinny/blob/5b3e222376dd18f6432825a8b05dc691f1f5d5f5/lib/skinny.rb#L384-L397 | train |
jarib/celerity | lib/celerity/xpath_support.rb | Celerity.XpathSupport.elements_by_xpath | def elements_by_xpath(xpath)
assert_exists
objects = @page.getByXPath(xpath)
# should use an ElementCollection here?
objects.map { |o| element_from_dom_node(o) }
end | ruby | def elements_by_xpath(xpath)
assert_exists
objects = @page.getByXPath(xpath)
# should use an ElementCollection here?
objects.map { |o| element_from_dom_node(o) }
end | [
"def",
"elements_by_xpath",
"(",
"xpath",
")",
"assert_exists",
"objects",
"=",
"@page",
".",
"getByXPath",
"(",
"xpath",
")",
"objects",
".",
"map",
"{",
"|",
"o",
"|",
"element_from_dom_node",
"(",
"o",
")",
"}",
"end"
] | Get all the elements matching the given XPath.
@param [String] xpath
@return [Array<Celerity::Element>] array of elements | [
"Get",
"all",
"the",
"elements",
"matching",
"the",
"given",
"XPath",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/xpath_support.rb#L29-L34 | train |
jarib/celerity | lib/celerity/xpath_support.rb | Celerity.XpathSupport.element_from_dom_node | def element_from_dom_node(obj, identifier_string = nil)
element_class = Util.htmlunit2celerity(obj.class) || Element
element = element_class.new(self, :object, obj)
element.identifier_string = identifier_string
element.extend(ClickableElement) unless element.is_a?(ClickableElement)
element
end | ruby | def element_from_dom_node(obj, identifier_string = nil)
element_class = Util.htmlunit2celerity(obj.class) || Element
element = element_class.new(self, :object, obj)
element.identifier_string = identifier_string
element.extend(ClickableElement) unless element.is_a?(ClickableElement)
element
end | [
"def",
"element_from_dom_node",
"(",
"obj",
",",
"identifier_string",
"=",
"nil",
")",
"element_class",
"=",
"Util",
".",
"htmlunit2celerity",
"(",
"obj",
".",
"class",
")",
"||",
"Element",
"element",
"=",
"element_class",
".",
"new",
"(",
"self",
",",
":object",
",",
"obj",
")",
"element",
".",
"identifier_string",
"=",
"identifier_string",
"element",
".",
"extend",
"(",
"ClickableElement",
")",
"unless",
"element",
".",
"is_a?",
"(",
"ClickableElement",
")",
"element",
"end"
] | Convert the given HtmlUnit DomNode to a Celerity object | [
"Convert",
"the",
"given",
"HtmlUnit",
"DomNode",
"to",
"a",
"Celerity",
"object"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/xpath_support.rb#L40-L48 | train |
jarib/celerity | lib/celerity/elements/text_field.rb | Celerity.TextField.contains_text | def contains_text(expected_text)
assert_exists
case expected_text
when Regexp
value() =~ expected_text
when String
value().index(expected_text)
else
raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}"
end
end | ruby | def contains_text(expected_text)
assert_exists
case expected_text
when Regexp
value() =~ expected_text
when String
value().index(expected_text)
else
raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}"
end
end | [
"def",
"contains_text",
"(",
"expected_text",
")",
"assert_exists",
"case",
"expected_text",
"when",
"Regexp",
"value",
"(",
")",
"=~",
"expected_text",
"when",
"String",
"value",
"(",
")",
".",
"index",
"(",
"expected_text",
")",
"else",
"raise",
"TypeError",
",",
"\"expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}\"",
"end",
"end"
] | Check if the given text fields contains the given String or Regexp. | [
"Check",
"if",
"the",
"given",
"text",
"fields",
"contains",
"the",
"given",
"String",
"or",
"Regexp",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/text_field.rb#L107-L118 | train |
rdunlop/codeclimate_circle_ci_coverage | lib/codeclimate_circle_ci_coverage/patch_simplecov.rb | SimpleCov.ArrayMergeHelper.merge_resultset | def merge_resultset(array)
new_array = dup
array.each_with_index do |element, i|
pair = [element, new_array[i]]
new_array[i] = if pair.any?(&:nil?) && pair.map(&:to_i).all?(&:zero?)
nil
else
element.to_i + new_array[i].to_i
end
end
new_array
end | ruby | def merge_resultset(array)
new_array = dup
array.each_with_index do |element, i|
pair = [element, new_array[i]]
new_array[i] = if pair.any?(&:nil?) && pair.map(&:to_i).all?(&:zero?)
nil
else
element.to_i + new_array[i].to_i
end
end
new_array
end | [
"def",
"merge_resultset",
"(",
"array",
")",
"new_array",
"=",
"dup",
"array",
".",
"each_with_index",
"do",
"|",
"element",
",",
"i",
"|",
"pair",
"=",
"[",
"element",
",",
"new_array",
"[",
"i",
"]",
"]",
"new_array",
"[",
"i",
"]",
"=",
"if",
"pair",
".",
"any?",
"(",
"&",
":nil?",
")",
"&&",
"pair",
".",
"map",
"(",
"&",
":to_i",
")",
".",
"all?",
"(",
"&",
":zero?",
")",
"nil",
"else",
"element",
".",
"to_i",
"+",
"new_array",
"[",
"i",
"]",
".",
"to_i",
"end",
"end",
"new_array",
"end"
] | Merges an array of coverage results with self | [
"Merges",
"an",
"array",
"of",
"coverage",
"results",
"with",
"self"
] | f881fcae0a0b8809c0fac59c39c375e06dd95e04 | https://github.com/rdunlop/codeclimate_circle_ci_coverage/blob/f881fcae0a0b8809c0fac59c39c375e06dd95e04/lib/codeclimate_circle_ci_coverage/patch_simplecov.rb#L10-L21 | train |
jarib/celerity | lib/celerity/elements/image.rb | Celerity.Image.file_created_date | def file_created_date
assert_exists
web_response = @object.getWebResponse(true)
Time.parse(web_response.getResponseHeaderValue("Last-Modified").to_s)
end | ruby | def file_created_date
assert_exists
web_response = @object.getWebResponse(true)
Time.parse(web_response.getResponseHeaderValue("Last-Modified").to_s)
end | [
"def",
"file_created_date",
"assert_exists",
"web_response",
"=",
"@object",
".",
"getWebResponse",
"(",
"true",
")",
"Time",
".",
"parse",
"(",
"web_response",
".",
"getResponseHeaderValue",
"(",
"\"Last-Modified\"",
")",
".",
"to_s",
")",
"end"
] | returns the file created date of the image | [
"returns",
"the",
"file",
"created",
"date",
"of",
"the",
"image"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/image.rb#L28-L32 | train |
jarib/celerity | lib/celerity/elements/image.rb | Celerity.Image.save | def save(filename)
assert_exists
image_reader = @object.getImageReader
file = java.io.File.new(filename)
buffered_image = image_reader.read(0);
javax.imageio.ImageIO.write(buffered_image, image_reader.getFormatName(), file);
end | ruby | def save(filename)
assert_exists
image_reader = @object.getImageReader
file = java.io.File.new(filename)
buffered_image = image_reader.read(0);
javax.imageio.ImageIO.write(buffered_image, image_reader.getFormatName(), file);
end | [
"def",
"save",
"(",
"filename",
")",
"assert_exists",
"image_reader",
"=",
"@object",
".",
"getImageReader",
"file",
"=",
"java",
".",
"io",
".",
"File",
".",
"new",
"(",
"filename",
")",
"buffered_image",
"=",
"image_reader",
".",
"read",
"(",
"0",
")",
";",
"javax",
".",
"imageio",
".",
"ImageIO",
".",
"write",
"(",
"buffered_image",
",",
"image_reader",
".",
"getFormatName",
"(",
")",
",",
"file",
")",
";",
"end"
] | Saves the image to the given file | [
"Saves",
"the",
"image",
"to",
"the",
"given",
"file"
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/image.rb#L80-L86 | train |
jarib/celerity | lib/celerity/util.rb | Celerity.Util.matches? | def matches?(string, what)
Regexp === what ? string.strip =~ what : string == what.to_s
end | ruby | def matches?(string, what)
Regexp === what ? string.strip =~ what : string == what.to_s
end | [
"def",
"matches?",
"(",
"string",
",",
"what",
")",
"Regexp",
"===",
"what",
"?",
"string",
".",
"strip",
"=~",
"what",
":",
"string",
"==",
"what",
".",
"to_s",
"end"
] | Used internally.
@param [String] string The string to match against.
@param [Regexp, String, #to_s] what The match we're looking for.
@return [Fixnum, true, false, nil]
@api private | [
"Used",
"internally",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/util.rb#L124-L126 | train |
jarib/celerity | lib/celerity/listener.rb | Celerity.Listener.add_listener | def add_listener(type, &block)
case type
when :status
@webclient.setStatusHandler(self)
when :alert
@webclient.setAlertHandler(self)
when :attachment
@webclient.setAttachmentHandler(self)
when :web_window_event
@webclient.addWebWindowListener(self)
when :html_parser
@webclient.setHTMLParserListener(self)
when :incorrectness
@webclient.setIncorrectnessListener(self)
when :confirm
@webclient.setConfirmHandler(self)
when :prompt
@webclient.setPromptHandler(self)
else
raise ArgumentError, "unknown listener type #{type.inspect}"
end
@procs[type] << block
end | ruby | def add_listener(type, &block)
case type
when :status
@webclient.setStatusHandler(self)
when :alert
@webclient.setAlertHandler(self)
when :attachment
@webclient.setAttachmentHandler(self)
when :web_window_event
@webclient.addWebWindowListener(self)
when :html_parser
@webclient.setHTMLParserListener(self)
when :incorrectness
@webclient.setIncorrectnessListener(self)
when :confirm
@webclient.setConfirmHandler(self)
when :prompt
@webclient.setPromptHandler(self)
else
raise ArgumentError, "unknown listener type #{type.inspect}"
end
@procs[type] << block
end | [
"def",
"add_listener",
"(",
"type",
",",
"&",
"block",
")",
"case",
"type",
"when",
":status",
"@webclient",
".",
"setStatusHandler",
"(",
"self",
")",
"when",
":alert",
"@webclient",
".",
"setAlertHandler",
"(",
"self",
")",
"when",
":attachment",
"@webclient",
".",
"setAttachmentHandler",
"(",
"self",
")",
"when",
":web_window_event",
"@webclient",
".",
"addWebWindowListener",
"(",
"self",
")",
"when",
":html_parser",
"@webclient",
".",
"setHTMLParserListener",
"(",
"self",
")",
"when",
":incorrectness",
"@webclient",
".",
"setIncorrectnessListener",
"(",
"self",
")",
"when",
":confirm",
"@webclient",
".",
"setConfirmHandler",
"(",
"self",
")",
"when",
":prompt",
"@webclient",
".",
"setPromptHandler",
"(",
"self",
")",
"else",
"raise",
"ArgumentError",
",",
"\"unknown listener type #{type.inspect}\"",
"end",
"@procs",
"[",
"type",
"]",
"<<",
"block",
"end"
] | Add a listener block for one of the available types.
@see Celerity::Browser#add_listener | [
"Add",
"a",
"listener",
"block",
"for",
"one",
"of",
"the",
"available",
"types",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/listener.rb#L27-L50 | train |
famished-tiger/Rley | lib/rley/parse_forest_visitor.rb | Rley.ParseForestVisitor.traverse_children | def traverse_children(aParentNode)
children = aParentNode.children
broadcast(:before_subnodes, aParentNode, children)
# Let's proceed with the visit of children
children.each_with_index do |a_node, i|
edge_sign = aParentNode.signatures[i]
if a_node.kind_of?(SPPF::CompositeNode)
push_node(a_node, edge_sign)
access_paths = node_accesses[a_node]
last_path = legs.last[-1]
path_reused = access_paths.include?(last_path)
unless path_reused
node_accesses[a_node].push(last_path)
a_node.accept(self)
end
pop_node
else
a_node.accept(self)
end
end
broadcast(:after_subnodes, aParentNode, children)
end | ruby | def traverse_children(aParentNode)
children = aParentNode.children
broadcast(:before_subnodes, aParentNode, children)
# Let's proceed with the visit of children
children.each_with_index do |a_node, i|
edge_sign = aParentNode.signatures[i]
if a_node.kind_of?(SPPF::CompositeNode)
push_node(a_node, edge_sign)
access_paths = node_accesses[a_node]
last_path = legs.last[-1]
path_reused = access_paths.include?(last_path)
unless path_reused
node_accesses[a_node].push(last_path)
a_node.accept(self)
end
pop_node
else
a_node.accept(self)
end
end
broadcast(:after_subnodes, aParentNode, children)
end | [
"def",
"traverse_children",
"(",
"aParentNode",
")",
"children",
"=",
"aParentNode",
".",
"children",
"broadcast",
"(",
":before_subnodes",
",",
"aParentNode",
",",
"children",
")",
"children",
".",
"each_with_index",
"do",
"|",
"a_node",
",",
"i",
"|",
"edge_sign",
"=",
"aParentNode",
".",
"signatures",
"[",
"i",
"]",
"if",
"a_node",
".",
"kind_of?",
"(",
"SPPF",
"::",
"CompositeNode",
")",
"push_node",
"(",
"a_node",
",",
"edge_sign",
")",
"access_paths",
"=",
"node_accesses",
"[",
"a_node",
"]",
"last_path",
"=",
"legs",
".",
"last",
"[",
"-",
"1",
"]",
"path_reused",
"=",
"access_paths",
".",
"include?",
"(",
"last_path",
")",
"unless",
"path_reused",
"node_accesses",
"[",
"a_node",
"]",
".",
"push",
"(",
"last_path",
")",
"a_node",
".",
"accept",
"(",
"self",
")",
"end",
"pop_node",
"else",
"a_node",
".",
"accept",
"(",
"self",
")",
"end",
"end",
"broadcast",
"(",
":after_subnodes",
",",
"aParentNode",
",",
"children",
")",
"end"
] | Visit event. The visitor is about to visit the children of a non
terminal node.
@param aParentNode [NonTeminalNode] the (non-terminal) parent node. | [
"Visit",
"event",
".",
"The",
"visitor",
"is",
"about",
"to",
"visit",
"the",
"children",
"of",
"a",
"non",
"terminal",
"node",
"."
] | 307a8ed6a328182c3cb83a0c3ed04c04b7135a13 | https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/parse_forest_visitor.rb#L139-L162 | train |
jarib/celerity | lib/celerity/element_collection.rb | Celerity.ElementCollection.[] | def [](n)
if @elements && @elements[n - Celerity.index_offset]
element_class.new(@container, :object, @elements[n - Celerity.index_offset])
else
iterator_object(n - Celerity.index_offset)
end
end | ruby | def [](n)
if @elements && @elements[n - Celerity.index_offset]
element_class.new(@container, :object, @elements[n - Celerity.index_offset])
else
iterator_object(n - Celerity.index_offset)
end
end | [
"def",
"[]",
"(",
"n",
")",
"if",
"@elements",
"&&",
"@elements",
"[",
"n",
"-",
"Celerity",
".",
"index_offset",
"]",
"element_class",
".",
"new",
"(",
"@container",
",",
":object",
",",
"@elements",
"[",
"n",
"-",
"Celerity",
".",
"index_offset",
"]",
")",
"else",
"iterator_object",
"(",
"n",
"-",
"Celerity",
".",
"index_offset",
")",
"end",
"end"
] | Get the element at the given index.
By default, this is 1-indexed to keep compatibility with Watir.
Also note that because of Watir's lazy loading, this will return an Element
instance even if the index is out of bounds.
@param [Fixnum] n Index of wanted element, 1-indexed unless Celerity.index_offset is changed.
@return [Celerity::Element] Returns a subclass of Celerity::Element | [
"Get",
"the",
"element",
"at",
"the",
"given",
"index",
".",
"By",
"default",
"this",
"is",
"1",
"-",
"indexed",
"to",
"keep",
"compatibility",
"with",
"Watir",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/element_collection.rb#L68-L74 | train |
jarib/celerity | lib/celerity/elements/select_list.rb | Celerity.SelectList.selected? | def selected?(value)
assert_exists
raise UnknownObjectException, "unknown option with value #{value.inspect} for select_list #{@conditions.inspect}" unless include?(value)
[email protected] { |e| matches_option?(e, value) && e.isSelected }
end | ruby | def selected?(value)
assert_exists
raise UnknownObjectException, "unknown option with value #{value.inspect} for select_list #{@conditions.inspect}" unless include?(value)
[email protected] { |e| matches_option?(e, value) && e.isSelected }
end | [
"def",
"selected?",
"(",
"value",
")",
"assert_exists",
"raise",
"UnknownObjectException",
",",
"\"unknown option with value #{value.inspect} for select_list #{@conditions.inspect}\"",
"unless",
"include?",
"(",
"value",
")",
"!",
"!",
"@object",
".",
"getOptions",
".",
"find",
"{",
"|",
"e",
"|",
"matches_option?",
"(",
"e",
",",
"value",
")",
"&&",
"e",
".",
"isSelected",
"}",
"end"
] | Returns true if any of the selected options match the given value.
@param [String, Regexp] value A value.
@raise [Celerity::Exception::UnknownObjectException] if the value does not exist.
@return [true, false] | [
"Returns",
"true",
"if",
"any",
"of",
"the",
"selected",
"options",
"match",
"the",
"given",
"value",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/elements/select_list.rb#L99-L103 | train |
jarib/celerity | lib/celerity/container.rb | Celerity.Container.contains_text | def contains_text(expected_text)
assert_exists
return nil unless respond_to? :text
case expected_text
when Regexp
text() =~ expected_text
when String
text().index(expected_text)
else
raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}"
end
end | ruby | def contains_text(expected_text)
assert_exists
return nil unless respond_to? :text
case expected_text
when Regexp
text() =~ expected_text
when String
text().index(expected_text)
else
raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}"
end
end | [
"def",
"contains_text",
"(",
"expected_text",
")",
"assert_exists",
"return",
"nil",
"unless",
"respond_to?",
":text",
"case",
"expected_text",
"when",
"Regexp",
"text",
"(",
")",
"=~",
"expected_text",
"when",
"String",
"text",
"(",
")",
".",
"index",
"(",
"expected_text",
")",
"else",
"raise",
"TypeError",
",",
"\"expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}\"",
"end",
"end"
] | Check if the element contains the given text.
@param [String, Regexp] expected_text The text to look for.
@return [Fixnum, nil] The index of the matched text, or nil if it doesn't match. | [
"Check",
"if",
"the",
"element",
"contains",
"the",
"given",
"text",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/container.rb#L45-L57 | train |
famished-tiger/Rley | lib/rley/engine.rb | Rley.Engine.parse | def parse(aTokenizer)
tokens = []
aTokenizer.each do |a_token|
next unless a_token
term_name = a_token.terminal
term_symb = grammar.name2symbol[term_name]
a_token.instance_variable_set(:@terminal, term_symb)
tokens << a_token
end
parser = build_parser(grammar)
parser.gf_graph.diagnose if configuration.diagnose
result = parser.parse(tokens)
result.tidy_up!
return result
end | ruby | def parse(aTokenizer)
tokens = []
aTokenizer.each do |a_token|
next unless a_token
term_name = a_token.terminal
term_symb = grammar.name2symbol[term_name]
a_token.instance_variable_set(:@terminal, term_symb)
tokens << a_token
end
parser = build_parser(grammar)
parser.gf_graph.diagnose if configuration.diagnose
result = parser.parse(tokens)
result.tidy_up!
return result
end | [
"def",
"parse",
"(",
"aTokenizer",
")",
"tokens",
"=",
"[",
"]",
"aTokenizer",
".",
"each",
"do",
"|",
"a_token",
"|",
"next",
"unless",
"a_token",
"term_name",
"=",
"a_token",
".",
"terminal",
"term_symb",
"=",
"grammar",
".",
"name2symbol",
"[",
"term_name",
"]",
"a_token",
".",
"instance_variable_set",
"(",
":@terminal",
",",
"term_symb",
")",
"tokens",
"<<",
"a_token",
"end",
"parser",
"=",
"build_parser",
"(",
"grammar",
")",
"parser",
".",
"gf_graph",
".",
"diagnose",
"if",
"configuration",
".",
"diagnose",
"result",
"=",
"parser",
".",
"parse",
"(",
"tokens",
")",
"result",
".",
"tidy_up!",
"return",
"result",
"end"
] | Parse the sequence of tokens produced by the given tokenizer object.
@param aTokenizer [#each]
@return [Parser::GFGParsing] | [
"Parse",
"the",
"sequence",
"of",
"tokens",
"produced",
"by",
"the",
"given",
"tokenizer",
"object",
"."
] | 307a8ed6a328182c3cb83a0c3ed04c04b7135a13 | https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/engine.rb#L78-L94 | train |
famished-tiger/Rley | lib/rley/engine.rb | Rley.Engine.to_ptree | def to_ptree(aRawParse)
factory = ParseRep::ParseTreeFactory.new(aRawParse)
if configuration.repr_builder == :default
result = factory.create(nil)
else
result = factory.create(configuration.repr_builder)
end
return result
end | ruby | def to_ptree(aRawParse)
factory = ParseRep::ParseTreeFactory.new(aRawParse)
if configuration.repr_builder == :default
result = factory.create(nil)
else
result = factory.create(configuration.repr_builder)
end
return result
end | [
"def",
"to_ptree",
"(",
"aRawParse",
")",
"factory",
"=",
"ParseRep",
"::",
"ParseTreeFactory",
".",
"new",
"(",
"aRawParse",
")",
"if",
"configuration",
".",
"repr_builder",
"==",
":default",
"result",
"=",
"factory",
".",
"create",
"(",
"nil",
")",
"else",
"result",
"=",
"factory",
".",
"create",
"(",
"configuration",
".",
"repr_builder",
")",
"end",
"return",
"result",
"end"
] | Convert raw parse result into a parse tree representation
@param aRawParse [Parser::GFGParsing]
@return [Rley::PTree::ParseTree] | [
"Convert",
"raw",
"parse",
"result",
"into",
"a",
"parse",
"tree",
"representation"
] | 307a8ed6a328182c3cb83a0c3ed04c04b7135a13 | https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/engine.rb#L114-L123 | train |
famished-tiger/Rley | lib/rley/engine.rb | Rley.Engine.to_pforest | def to_pforest(aRawParse)
factory = ParseRep::ParseForestFactory.new(aRawParse)
if configuration.repr_builder == :default
result = factory.create(nil)
else
result = factory.create(configuration.repr_builder)
end
return result
end | ruby | def to_pforest(aRawParse)
factory = ParseRep::ParseForestFactory.new(aRawParse)
if configuration.repr_builder == :default
result = factory.create(nil)
else
result = factory.create(configuration.repr_builder)
end
return result
end | [
"def",
"to_pforest",
"(",
"aRawParse",
")",
"factory",
"=",
"ParseRep",
"::",
"ParseForestFactory",
".",
"new",
"(",
"aRawParse",
")",
"if",
"configuration",
".",
"repr_builder",
"==",
":default",
"result",
"=",
"factory",
".",
"create",
"(",
"nil",
")",
"else",
"result",
"=",
"factory",
".",
"create",
"(",
"configuration",
".",
"repr_builder",
")",
"end",
"return",
"result",
"end"
] | Convert raw parse result into a parse forest representation
@param aRawParse [Parser::GFGParsing]
@return [Rley::SPPF::ParseForest] | [
"Convert",
"raw",
"parse",
"result",
"into",
"a",
"parse",
"forest",
"representation"
] | 307a8ed6a328182c3cb83a0c3ed04c04b7135a13 | https://github.com/famished-tiger/Rley/blob/307a8ed6a328182c3cb83a0c3ed04c04b7135a13/lib/rley/engine.rb#L128-L137 | train |
jarib/celerity | lib/celerity/element_locator.rb | Celerity.ElementLocator.with_nullpointer_retry | def with_nullpointer_retry(max_retries = 3)
tries = 0
yield
rescue java.lang.NullPointerException => e
raise e if tries >= max_retries
tries += 1
warn "warning: celerity caught #{e} - retry ##{tries}"
retry
end | ruby | def with_nullpointer_retry(max_retries = 3)
tries = 0
yield
rescue java.lang.NullPointerException => e
raise e if tries >= max_retries
tries += 1
warn "warning: celerity caught #{e} - retry ##{tries}"
retry
end | [
"def",
"with_nullpointer_retry",
"(",
"max_retries",
"=",
"3",
")",
"tries",
"=",
"0",
"yield",
"rescue",
"java",
".",
"lang",
".",
"NullPointerException",
"=>",
"e",
"raise",
"e",
"if",
"tries",
">=",
"max_retries",
"tries",
"+=",
"1",
"warn",
"\"warning: celerity caught #{e} - retry ##{tries}\"",
"retry",
"end"
] | HtmlUnit throws NPEs sometimes when we're locating elements
Retry seems to work fine. | [
"HtmlUnit",
"throws",
"NPEs",
"sometimes",
"when",
"we",
"re",
"locating",
"elements",
"Retry",
"seems",
"to",
"work",
"fine",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/element_locator.rb#L152-L161 | train |
jarib/celerity | lib/celerity/clickable_element.rb | Celerity.ClickableElement.click_and_attach | def click_and_attach
assert_exists_and_enabled
browser = Browser.new(@browser.options.dup)
browser.webclient.set_cookie_manager(
@browser.webclient.get_cookie_manager
) # hirobumi: we do want cookies as well.
@browser.disable_event_listener do
rescue_status_code_exception { browser.page = @object.click }
end
browser
end | ruby | def click_and_attach
assert_exists_and_enabled
browser = Browser.new(@browser.options.dup)
browser.webclient.set_cookie_manager(
@browser.webclient.get_cookie_manager
) # hirobumi: we do want cookies as well.
@browser.disable_event_listener do
rescue_status_code_exception { browser.page = @object.click }
end
browser
end | [
"def",
"click_and_attach",
"assert_exists_and_enabled",
"browser",
"=",
"Browser",
".",
"new",
"(",
"@browser",
".",
"options",
".",
"dup",
")",
"browser",
".",
"webclient",
".",
"set_cookie_manager",
"(",
"@browser",
".",
"webclient",
".",
"get_cookie_manager",
")",
"@browser",
".",
"disable_event_listener",
"do",
"rescue_status_code_exception",
"{",
"browser",
".",
"page",
"=",
"@object",
".",
"click",
"}",
"end",
"browser",
"end"
] | Click the element and return a new Browser instance with the resulting page.
This is useful for elements that trigger popups when clicked.
@return [Celerity::Browser] | [
"Click",
"the",
"element",
"and",
"return",
"a",
"new",
"Browser",
"instance",
"with",
"the",
"resulting",
"page",
".",
"This",
"is",
"useful",
"for",
"elements",
"that",
"trigger",
"popups",
"when",
"clicked",
"."
] | 90c6eeb3db868be1d9c0195b53f040b5b53d0e91 | https://github.com/jarib/celerity/blob/90c6eeb3db868be1d9c0195b53f040b5b53d0e91/lib/celerity/clickable_element.rb#L38-L50 | train |
potatosalad/ruby-erlang-terms | lib/erlang/map.rb | Erlang.Map.value? | def value?(value)
value = Erlang.from(value)
each { |k,v| return true if value == v }
return false
end | ruby | def value?(value)
value = Erlang.from(value)
each { |k,v| return true if value == v }
return false
end | [
"def",
"value?",
"(",
"value",
")",
"value",
"=",
"Erlang",
".",
"from",
"(",
"value",
")",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"return",
"true",
"if",
"value",
"==",
"v",
"}",
"return",
"false",
"end"
] | Return `true` if this `Map` has one or more keys which map to the provided value.
@example
Erlang::Map["A" => 1, "B" => 2, "C" => 3].value?(2) # => true
@param value [Object] The value to check for
@return [Boolean] | [
"Return",
"true",
"if",
"this",
"Map",
"has",
"one",
"or",
"more",
"keys",
"which",
"map",
"to",
"the",
"provided",
"value",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/map.rb#L218-L222 | train |
potatosalad/ruby-erlang-terms | lib/erlang/map.rb | Erlang.Map.get | def get(key)
key = Erlang.from(key)
entry = @trie.get(key)
if entry
return entry[1]
elsif @default
return @default.call(key)
end
end | ruby | def get(key)
key = Erlang.from(key)
entry = @trie.get(key)
if entry
return entry[1]
elsif @default
return @default.call(key)
end
end | [
"def",
"get",
"(",
"key",
")",
"key",
"=",
"Erlang",
".",
"from",
"(",
"key",
")",
"entry",
"=",
"@trie",
".",
"get",
"(",
"key",
")",
"if",
"entry",
"return",
"entry",
"[",
"1",
"]",
"elsif",
"@default",
"return",
"@default",
".",
"call",
"(",
"key",
")",
"end",
"end"
] | Retrieve the value corresponding to the provided key object. If not found, and
this `Map` has a default block, the default block is called to provide the
value. Otherwise, return `nil`.
@example
m = Erlang::Map["A" => 1, "B" => 2, "C" => 3]
m["B"] # => 2
m.get("B") # => 2
m.get("Elephant") # => nil
# Erlang Map with a default proc:
m = Erlang::Map.new("A" => 1, "B" => 2, "C" => 3) { |key| key.size }
m.get("B") # => 2
m.get("Elephant") # => 8
@param key [Object] The key to look up
@return [Object] | [
"Retrieve",
"the",
"value",
"corresponding",
"to",
"the",
"provided",
"key",
"object",
".",
"If",
"not",
"found",
"and",
"this",
"Map",
"has",
"a",
"default",
"block",
"the",
"default",
"block",
"is",
"called",
"to",
"provide",
"the",
"value",
".",
"Otherwise",
"return",
"nil",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/map.rb#L242-L250 | train |
potatosalad/ruby-erlang-terms | lib/erlang/map.rb | Erlang.Map.fetch | def fetch(key, default = Undefined)
key = Erlang.from(key)
entry = @trie.get(key)
if entry
return entry[1]
elsif block_given?
return yield(key)
elsif not Undefined.equal?(default)
return Erlang.from(default)
else
raise KeyError, "key not found: #{key.inspect}"
end
end | ruby | def fetch(key, default = Undefined)
key = Erlang.from(key)
entry = @trie.get(key)
if entry
return entry[1]
elsif block_given?
return yield(key)
elsif not Undefined.equal?(default)
return Erlang.from(default)
else
raise KeyError, "key not found: #{key.inspect}"
end
end | [
"def",
"fetch",
"(",
"key",
",",
"default",
"=",
"Undefined",
")",
"key",
"=",
"Erlang",
".",
"from",
"(",
"key",
")",
"entry",
"=",
"@trie",
".",
"get",
"(",
"key",
")",
"if",
"entry",
"return",
"entry",
"[",
"1",
"]",
"elsif",
"block_given?",
"return",
"yield",
"(",
"key",
")",
"elsif",
"not",
"Undefined",
".",
"equal?",
"(",
"default",
")",
"return",
"Erlang",
".",
"from",
"(",
"default",
")",
"else",
"raise",
"KeyError",
",",
"\"key not found: #{key.inspect}\"",
"end",
"end"
] | Retrieve the value corresponding to the given key object, or use the provided
default value or block, or otherwise raise a `KeyError`.
@overload fetch(key)
Retrieve the value corresponding to the given key, or raise a `KeyError`
if it is not found.
@param key [Object] The key to look up
@overload fetch(key) { |key| ... }
Retrieve the value corresponding to the given key, or call the optional
code block (with the missing key) and get its return value.
@yield [key] The key which was not found
@yieldreturn [Object] Object to return since the key was not found
@param key [Object] The key to look up
@overload fetch(key, default)
Retrieve the value corresponding to the given key, or else return
the provided `default` value.
@param key [Object] The key to look up
@param default [Object] Object to return if the key is not found
@example
m = Erlang::Map["A" => 1, "B" => 2, "C" => 3]
m.fetch("B") # => 2
m.fetch("Elephant") # => KeyError: key not found: "Elephant"
# with a default value:
m.fetch("B", 99) # => 2
m.fetch("Elephant", 99) # => 99
# with a block:
m.fetch("B") { |key| key.size } # => 2
m.fetch("Elephant") { |key| key.size } # => 8
@return [Object] | [
"Retrieve",
"the",
"value",
"corresponding",
"to",
"the",
"given",
"key",
"object",
"or",
"use",
"the",
"provided",
"default",
"value",
"or",
"block",
"or",
"otherwise",
"raise",
"a",
"KeyError",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/map.rb#L286-L298 | train |
potatosalad/ruby-erlang-terms | lib/erlang/map.rb | Erlang.Map.slice | def slice(*wanted)
trie = Trie.new(0)
wanted.each { |key|
key = Erlang.from(key)
trie.put!(key, get(key)) if key?(key)
}
return self.class.alloc(trie, @default)
end | ruby | def slice(*wanted)
trie = Trie.new(0)
wanted.each { |key|
key = Erlang.from(key)
trie.put!(key, get(key)) if key?(key)
}
return self.class.alloc(trie, @default)
end | [
"def",
"slice",
"(",
"*",
"wanted",
")",
"trie",
"=",
"Trie",
".",
"new",
"(",
"0",
")",
"wanted",
".",
"each",
"{",
"|",
"key",
"|",
"key",
"=",
"Erlang",
".",
"from",
"(",
"key",
")",
"trie",
".",
"put!",
"(",
"key",
",",
"get",
"(",
"key",
")",
")",
"if",
"key?",
"(",
"key",
")",
"}",
"return",
"self",
".",
"class",
".",
"alloc",
"(",
"trie",
",",
"@default",
")",
"end"
] | Return a new `Map` with only the associations for the `wanted` keys retained.
@example
m = Erlang::Map["A" => 1, "B" => 2, "C" => 3]
m.slice("B", "C") # => Erlang::Map["B" => 2, "C" => 3]
@param wanted [::Enumerable] The keys to retain
@return [Map] | [
"Return",
"a",
"new",
"Map",
"with",
"only",
"the",
"associations",
"for",
"the",
"wanted",
"keys",
"retained",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/map.rb#L621-L628 | train |
bbc/hive-runner | lib/hive/worker.rb | Hive.Worker.poll_queue | def poll_queue
@job = reserve_job
if @job.nil?
@log.info('No job found')
else
@log.info('Job starting')
begin
@current_job_start_time = Time.now
execute_job
rescue => e
@log.info("Error running test: #{e.message}\n : #{e.backtrace.join("\n :")}")
end
cleanup
end
end | ruby | def poll_queue
@job = reserve_job
if @job.nil?
@log.info('No job found')
else
@log.info('Job starting')
begin
@current_job_start_time = Time.now
execute_job
rescue => e
@log.info("Error running test: #{e.message}\n : #{e.backtrace.join("\n :")}")
end
cleanup
end
end | [
"def",
"poll_queue",
"@job",
"=",
"reserve_job",
"if",
"@job",
".",
"nil?",
"@log",
".",
"info",
"(",
"'No job found'",
")",
"else",
"@log",
".",
"info",
"(",
"'Job starting'",
")",
"begin",
"@current_job_start_time",
"=",
"Time",
".",
"now",
"execute_job",
"rescue",
"=>",
"e",
"@log",
".",
"info",
"(",
"\"Error running test: #{e.message}\\n : #{e.backtrace.join(\"\\n :\")}\"",
")",
"end",
"cleanup",
"end",
"end"
] | The main worker process loop
Check the queues for work | [
"The",
"main",
"worker",
"process",
"loop",
"Check",
"the",
"queues",
"for",
"work"
] | 9079f23362e201c342f416b5038d935e83e0de84 | https://github.com/bbc/hive-runner/blob/9079f23362e201c342f416b5038d935e83e0de84/lib/hive/worker.rb#L89-L103 | train |
bbc/hive-runner | lib/hive/worker.rb | Hive.Worker.reserve_job | def reserve_job
@log.info "Trying to reserve job for queues: #{@queues.join(', ')}"
job = job_message_klass.reserve(@queues, reservation_details)
@log.debug "Job: #{job.inspect}"
raise InvalidJobReservationError.new("Invalid Job Reserved") if ! (job.nil? || job.valid?)
job
end | ruby | def reserve_job
@log.info "Trying to reserve job for queues: #{@queues.join(', ')}"
job = job_message_klass.reserve(@queues, reservation_details)
@log.debug "Job: #{job.inspect}"
raise InvalidJobReservationError.new("Invalid Job Reserved") if ! (job.nil? || job.valid?)
job
end | [
"def",
"reserve_job",
"@log",
".",
"info",
"\"Trying to reserve job for queues: #{@queues.join(', ')}\"",
"job",
"=",
"job_message_klass",
".",
"reserve",
"(",
"@queues",
",",
"reservation_details",
")",
"@log",
".",
"debug",
"\"Job: #{job.inspect}\"",
"raise",
"InvalidJobReservationError",
".",
"new",
"(",
"\"Invalid Job Reserved\"",
")",
"if",
"!",
"(",
"job",
".",
"nil?",
"||",
"job",
".",
"valid?",
")",
"job",
"end"
] | Try to find and reserve a job | [
"Try",
"to",
"find",
"and",
"reserve",
"a",
"job"
] | 9079f23362e201c342f416b5038d935e83e0de84 | https://github.com/bbc/hive-runner/blob/9079f23362e201c342f416b5038d935e83e0de84/lib/hive/worker.rb#L106-L112 | train |
bbc/hive-runner | lib/hive/worker.rb | Hive.Worker.diagnostics | def diagnostics
retn = true
protect
retn = @diagnostic_runner.run if !@diagnostic_runner.nil?
unprotect
@log.info('Diagnostics failed') if not retn
status = device_status
status = set_device_status('happy') if status == 'busy'
raise DeviceNotReady.new("Current device status: '#{status}'") if status != 'happy'
retn
end | ruby | def diagnostics
retn = true
protect
retn = @diagnostic_runner.run if !@diagnostic_runner.nil?
unprotect
@log.info('Diagnostics failed') if not retn
status = device_status
status = set_device_status('happy') if status == 'busy'
raise DeviceNotReady.new("Current device status: '#{status}'") if status != 'happy'
retn
end | [
"def",
"diagnostics",
"retn",
"=",
"true",
"protect",
"retn",
"=",
"@diagnostic_runner",
".",
"run",
"if",
"!",
"@diagnostic_runner",
".",
"nil?",
"unprotect",
"@log",
".",
"info",
"(",
"'Diagnostics failed'",
")",
"if",
"not",
"retn",
"status",
"=",
"device_status",
"status",
"=",
"set_device_status",
"(",
"'happy'",
")",
"if",
"status",
"==",
"'busy'",
"raise",
"DeviceNotReady",
".",
"new",
"(",
"\"Current device status: '#{status}'\"",
")",
"if",
"status",
"!=",
"'happy'",
"retn",
"end"
] | Diagnostics function to be extended in child class, as required | [
"Diagnostics",
"function",
"to",
"be",
"extended",
"in",
"child",
"class",
"as",
"required"
] | 9079f23362e201c342f416b5038d935e83e0de84 | https://github.com/bbc/hive-runner/blob/9079f23362e201c342f416b5038d935e83e0de84/lib/hive/worker.rb#L251-L261 | train |
bbc/hive-runner | lib/hive/worker.rb | Hive.Worker.upload_files | def upload_files(job, *paths)
@log.info("Uploading assets")
paths.each do |path|
@log.info("Uploading files from #{path}")
Dir.foreach(path) do |item|
@log.info("File: #{item}")
next if item == '.' or item == '..'
begin
artifact = job.report_artifact("#{path}/#{item}")
@log.info("Artifact uploaded: #{artifact.attributes.to_s}")
rescue => e
@log.error("Error uploading artifact #{item}: #{e.message}")
@log.error(" : #{e.backtrace.join("\n : ")}")
end
end
end
end | ruby | def upload_files(job, *paths)
@log.info("Uploading assets")
paths.each do |path|
@log.info("Uploading files from #{path}")
Dir.foreach(path) do |item|
@log.info("File: #{item}")
next if item == '.' or item == '..'
begin
artifact = job.report_artifact("#{path}/#{item}")
@log.info("Artifact uploaded: #{artifact.attributes.to_s}")
rescue => e
@log.error("Error uploading artifact #{item}: #{e.message}")
@log.error(" : #{e.backtrace.join("\n : ")}")
end
end
end
end | [
"def",
"upload_files",
"(",
"job",
",",
"*",
"paths",
")",
"@log",
".",
"info",
"(",
"\"Uploading assets\"",
")",
"paths",
".",
"each",
"do",
"|",
"path",
"|",
"@log",
".",
"info",
"(",
"\"Uploading files from #{path}\"",
")",
"Dir",
".",
"foreach",
"(",
"path",
")",
"do",
"|",
"item",
"|",
"@log",
".",
"info",
"(",
"\"File: #{item}\"",
")",
"next",
"if",
"item",
"==",
"'.'",
"or",
"item",
"==",
"'..'",
"begin",
"artifact",
"=",
"job",
".",
"report_artifact",
"(",
"\"#{path}/#{item}\"",
")",
"@log",
".",
"info",
"(",
"\"Artifact uploaded: #{artifact.attributes.to_s}\"",
")",
"rescue",
"=>",
"e",
"@log",
".",
"error",
"(",
"\"Error uploading artifact #{item}: #{e.message}\"",
")",
"@log",
".",
"error",
"(",
"\" : #{e.backtrace.join(\"\\n : \")}\"",
")",
"end",
"end",
"end",
"end"
] | Upload any files from the test | [
"Upload",
"any",
"files",
"from",
"the",
"test"
] | 9079f23362e201c342f416b5038d935e83e0de84 | https://github.com/bbc/hive-runner/blob/9079f23362e201c342f416b5038d935e83e0de84/lib/hive/worker.rb#L294-L310 | train |
bbc/hive-runner | lib/hive/worker.rb | Hive.Worker.checkout_code | def checkout_code(repository, checkout_directory, branch)
CodeCache.repo(repository).checkout(:head, checkout_directory, branch) or raise "Unable to checkout repository #{repository}"
end | ruby | def checkout_code(repository, checkout_directory, branch)
CodeCache.repo(repository).checkout(:head, checkout_directory, branch) or raise "Unable to checkout repository #{repository}"
end | [
"def",
"checkout_code",
"(",
"repository",
",",
"checkout_directory",
",",
"branch",
")",
"CodeCache",
".",
"repo",
"(",
"repository",
")",
".",
"checkout",
"(",
":head",
",",
"checkout_directory",
",",
"branch",
")",
"or",
"raise",
"\"Unable to checkout repository #{repository}\"",
"end"
] | Get a checkout of the repository | [
"Get",
"a",
"checkout",
"of",
"the",
"repository"
] | 9079f23362e201c342f416b5038d935e83e0de84 | https://github.com/bbc/hive-runner/blob/9079f23362e201c342f416b5038d935e83e0de84/lib/hive/worker.rb#L402-L404 | train |
acook/remedy | lib/remedy/characters.rb | Remedy.Characters.gremlins | def gremlins
{
space: "\u2420",
tab: "\u21B9",
carriage_return: "\u23CE",
line_feed: "\u240A",
control_c: "\u2404",
control_d: "\u2403",
control_r: "\u2412",
escape: "\u238B",
backspace: "\u2408",
delete: "\u232B",
up: "\u2191",
down: "\u2193",
left: "\u2190",
right: "\u2192"
}
end | ruby | def gremlins
{
space: "\u2420",
tab: "\u21B9",
carriage_return: "\u23CE",
line_feed: "\u240A",
control_c: "\u2404",
control_d: "\u2403",
control_r: "\u2412",
escape: "\u238B",
backspace: "\u2408",
delete: "\u232B",
up: "\u2191",
down: "\u2193",
left: "\u2190",
right: "\u2192"
}
end | [
"def",
"gremlins",
"{",
"space",
":",
"\"\\u2420\"",
",",
"tab",
":",
"\"\\u21B9\"",
",",
"carriage_return",
":",
"\"\\u23CE\"",
",",
"line_feed",
":",
"\"\\u240A\"",
",",
"control_c",
":",
"\"\\u2404\"",
",",
"control_d",
":",
"\"\\u2403\"",
",",
"control_r",
":",
"\"\\u2412\"",
",",
"escape",
":",
"\"\\u238B\"",
",",
"backspace",
":",
"\"\\u2408\"",
",",
"delete",
":",
"\"\\u232B\"",
",",
"up",
":",
"\"\\u2191\"",
",",
"down",
":",
"\"\\u2193\"",
",",
"left",
":",
"\"\\u2190\"",
",",
"right",
":",
"\"\\u2192\"",
"}",
"end"
] | Glyphs and Alternate Names | [
"Glyphs",
"and",
"Alternate",
"Names"
] | 66452b4e0540dc9c95ca596c69998f79e3a54db6 | https://github.com/acook/remedy/blob/66452b4e0540dc9c95ca596c69998f79e3a54db6/lib/remedy/characters.rb#L130-L151 | train |
potatosalad/ruby-erlang-terms | lib/erlang/bitstring.rb | Erlang.Bitstring.bitslice | def bitslice(arg, length = (missing_length = true))
if missing_length
if arg.is_a?(Range)
from, to = arg.begin, arg.end
from += bitsize if from < 0
return nil if from < 0
to += bitsize if to < 0
to += 1 if !arg.exclude_end?
length = to - from
length = 0 if length < 0
length = bitsize - from if (from + length) > bitsize
return nil if length < 0
l8 = length.div(8)
l1 = length % 8
pad = 8 - l1
enum = each_bit
skip = from
enum = enum.drop_while {
if skip > 0
skip -= 1
next true
else
next false
end
}
head = enum.take(length)
if l1 == 0
return Erlang::Binary[[head.join].pack(BIT_PACK)]
else
tail = head[-l1..-1]
head = head[0...-l1]
tail = ([0] * pad).concat(tail)
return Erlang::Bitstring[[[head.join, tail.join].join].pack(BIT_PACK), bits: l1]
end
else
arg += bitsize if arg < 0
return nil if arg < 0
return nil if arg >= bitsize
a8 = arg.div(8)
a1 = arg % 8
byte = @data.getbyte(a8)
return nil if byte.nil?
return (byte >> ((@bits - a1 - 1) & 7)) & 1
end
else
return nil if length < 0
arg += bitsize if arg < 0
return nil if arg < 0
length = bitsize - arg if (arg + length) > bitsize
return nil if length < 0
l8 = length.div(8)
l1 = length % 8
pad = 8 - l1
enum = each_bit
skip = arg
enum = enum.drop_while {
if skip > 0
skip -= 1
next true
else
next false
end
}
head = enum.take(length)
if l1 == 0
return Erlang::Binary[[head.join].pack(BIT_PACK)]
else
tail = head[-l1..-1]
head = head[0...-l1]
tail = ([0] * pad).concat(tail)
return Erlang::Bitstring[[[head.join, tail.join].join].pack(BIT_PACK), bits: l1]
end
end
end | ruby | def bitslice(arg, length = (missing_length = true))
if missing_length
if arg.is_a?(Range)
from, to = arg.begin, arg.end
from += bitsize if from < 0
return nil if from < 0
to += bitsize if to < 0
to += 1 if !arg.exclude_end?
length = to - from
length = 0 if length < 0
length = bitsize - from if (from + length) > bitsize
return nil if length < 0
l8 = length.div(8)
l1 = length % 8
pad = 8 - l1
enum = each_bit
skip = from
enum = enum.drop_while {
if skip > 0
skip -= 1
next true
else
next false
end
}
head = enum.take(length)
if l1 == 0
return Erlang::Binary[[head.join].pack(BIT_PACK)]
else
tail = head[-l1..-1]
head = head[0...-l1]
tail = ([0] * pad).concat(tail)
return Erlang::Bitstring[[[head.join, tail.join].join].pack(BIT_PACK), bits: l1]
end
else
arg += bitsize if arg < 0
return nil if arg < 0
return nil if arg >= bitsize
a8 = arg.div(8)
a1 = arg % 8
byte = @data.getbyte(a8)
return nil if byte.nil?
return (byte >> ((@bits - a1 - 1) & 7)) & 1
end
else
return nil if length < 0
arg += bitsize if arg < 0
return nil if arg < 0
length = bitsize - arg if (arg + length) > bitsize
return nil if length < 0
l8 = length.div(8)
l1 = length % 8
pad = 8 - l1
enum = each_bit
skip = arg
enum = enum.drop_while {
if skip > 0
skip -= 1
next true
else
next false
end
}
head = enum.take(length)
if l1 == 0
return Erlang::Binary[[head.join].pack(BIT_PACK)]
else
tail = head[-l1..-1]
head = head[0...-l1]
tail = ([0] * pad).concat(tail)
return Erlang::Bitstring[[[head.join, tail.join].join].pack(BIT_PACK), bits: l1]
end
end
end | [
"def",
"bitslice",
"(",
"arg",
",",
"length",
"=",
"(",
"missing_length",
"=",
"true",
")",
")",
"if",
"missing_length",
"if",
"arg",
".",
"is_a?",
"(",
"Range",
")",
"from",
",",
"to",
"=",
"arg",
".",
"begin",
",",
"arg",
".",
"end",
"from",
"+=",
"bitsize",
"if",
"from",
"<",
"0",
"return",
"nil",
"if",
"from",
"<",
"0",
"to",
"+=",
"bitsize",
"if",
"to",
"<",
"0",
"to",
"+=",
"1",
"if",
"!",
"arg",
".",
"exclude_end?",
"length",
"=",
"to",
"-",
"from",
"length",
"=",
"0",
"if",
"length",
"<",
"0",
"length",
"=",
"bitsize",
"-",
"from",
"if",
"(",
"from",
"+",
"length",
")",
">",
"bitsize",
"return",
"nil",
"if",
"length",
"<",
"0",
"l8",
"=",
"length",
".",
"div",
"(",
"8",
")",
"l1",
"=",
"length",
"%",
"8",
"pad",
"=",
"8",
"-",
"l1",
"enum",
"=",
"each_bit",
"skip",
"=",
"from",
"enum",
"=",
"enum",
".",
"drop_while",
"{",
"if",
"skip",
">",
"0",
"skip",
"-=",
"1",
"next",
"true",
"else",
"next",
"false",
"end",
"}",
"head",
"=",
"enum",
".",
"take",
"(",
"length",
")",
"if",
"l1",
"==",
"0",
"return",
"Erlang",
"::",
"Binary",
"[",
"[",
"head",
".",
"join",
"]",
".",
"pack",
"(",
"BIT_PACK",
")",
"]",
"else",
"tail",
"=",
"head",
"[",
"-",
"l1",
"..",
"-",
"1",
"]",
"head",
"=",
"head",
"[",
"0",
"...",
"-",
"l1",
"]",
"tail",
"=",
"(",
"[",
"0",
"]",
"*",
"pad",
")",
".",
"concat",
"(",
"tail",
")",
"return",
"Erlang",
"::",
"Bitstring",
"[",
"[",
"[",
"head",
".",
"join",
",",
"tail",
".",
"join",
"]",
".",
"join",
"]",
".",
"pack",
"(",
"BIT_PACK",
")",
",",
"bits",
":",
"l1",
"]",
"end",
"else",
"arg",
"+=",
"bitsize",
"if",
"arg",
"<",
"0",
"return",
"nil",
"if",
"arg",
"<",
"0",
"return",
"nil",
"if",
"arg",
">=",
"bitsize",
"a8",
"=",
"arg",
".",
"div",
"(",
"8",
")",
"a1",
"=",
"arg",
"%",
"8",
"byte",
"=",
"@data",
".",
"getbyte",
"(",
"a8",
")",
"return",
"nil",
"if",
"byte",
".",
"nil?",
"return",
"(",
"byte",
">>",
"(",
"(",
"@bits",
"-",
"a1",
"-",
"1",
")",
"&",
"7",
")",
")",
"&",
"1",
"end",
"else",
"return",
"nil",
"if",
"length",
"<",
"0",
"arg",
"+=",
"bitsize",
"if",
"arg",
"<",
"0",
"return",
"nil",
"if",
"arg",
"<",
"0",
"length",
"=",
"bitsize",
"-",
"arg",
"if",
"(",
"arg",
"+",
"length",
")",
">",
"bitsize",
"return",
"nil",
"if",
"length",
"<",
"0",
"l8",
"=",
"length",
".",
"div",
"(",
"8",
")",
"l1",
"=",
"length",
"%",
"8",
"pad",
"=",
"8",
"-",
"l1",
"enum",
"=",
"each_bit",
"skip",
"=",
"arg",
"enum",
"=",
"enum",
".",
"drop_while",
"{",
"if",
"skip",
">",
"0",
"skip",
"-=",
"1",
"next",
"true",
"else",
"next",
"false",
"end",
"}",
"head",
"=",
"enum",
".",
"take",
"(",
"length",
")",
"if",
"l1",
"==",
"0",
"return",
"Erlang",
"::",
"Binary",
"[",
"[",
"head",
".",
"join",
"]",
".",
"pack",
"(",
"BIT_PACK",
")",
"]",
"else",
"tail",
"=",
"head",
"[",
"-",
"l1",
"..",
"-",
"1",
"]",
"head",
"=",
"head",
"[",
"0",
"...",
"-",
"l1",
"]",
"tail",
"=",
"(",
"[",
"0",
"]",
"*",
"pad",
")",
".",
"concat",
"(",
"tail",
")",
"return",
"Erlang",
"::",
"Bitstring",
"[",
"[",
"[",
"head",
".",
"join",
",",
"tail",
".",
"join",
"]",
".",
"join",
"]",
".",
"pack",
"(",
"BIT_PACK",
")",
",",
"bits",
":",
"l1",
"]",
"end",
"end",
"end"
] | Return specific objects from the `Bitstring`. All overloads return `nil` if
the starting index is out of range.
@overload bitslice(index)
Returns a single bit at the given `index`. If `index` is negative,
count backwards from the end.
@param index [Integer] The index to retrieve. May be negative.
@return [Integer, nil]
@example
b = Erlang::Bitstring[2, bits: 2]
b.bitslice(0) # => 1
b.bitslice(1) # => 0
b.bitslice(-1) # => 0
b.bitslice(2) # => nil
@overload bitslice(index, length)
Return a bitstring starting at `index` and continuing for `length`
bits or until the end of the `Bitstring`, whichever occurs first.
@param start [Integer] The index to start retrieving bits from. May be
negative.
@param length [Integer] The number of bits to retrieve.
@return [Bitstring, Binary]
@example
b = Erlang::Bitstring[1, 117, bits: 7]
b.bitslice(0, 11) # => Erlang::Bitstring[1, 7, bits: 3]
b.bitslice(11, 4) # => Erlang::Bitstring[5, bits: 4]
b.bitslice(16, 1) # => nil
@overload bitslice(index..end)
Return a bitstring starting at `index` and continuing to index
`end` or the end of the `Bitstring`, whichever occurs first.
@param range [Range] The range of bits to retrieve.
@return [Bitstring, Binary]
@example
b = Erlang::Bitstring[1, 117, bits: 7]
b.bitslice(0...11) # => Erlang::Bitstring[1, 7, bits: 3]
b.bitslice(11...15) # => Erlang::Bitstring[5, bits: 4]
b.bitslice(16..-1) # => nil
@see Erlang::Binary#bitslice | [
"Return",
"specific",
"objects",
"from",
"the",
"Bitstring",
".",
"All",
"overloads",
"return",
"nil",
"if",
"the",
"starting",
"index",
"is",
"out",
"of",
"range",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/bitstring.rb#L191-L264 | train |
potatosalad/ruby-erlang-terms | lib/erlang/bitstring.rb | Erlang.Bitstring.each_bit | def each_bit
return enum_for(:each_bit) unless block_given?
index = 0
headbits = (self.bytesize - 1) * 8
skipbits = 8 - @bits
@data.each_byte do |byte|
loop do
break if index == @bitsize
if index >= headbits
bit = (byte >> (7 - ((index + skipbits) & 7))) & 1
else
bit = (byte >> (7 - (index & 7))) & 1
end
yield bit
index += 1
break if (index & 7) == 0
end
end
return self
end | ruby | def each_bit
return enum_for(:each_bit) unless block_given?
index = 0
headbits = (self.bytesize - 1) * 8
skipbits = 8 - @bits
@data.each_byte do |byte|
loop do
break if index == @bitsize
if index >= headbits
bit = (byte >> (7 - ((index + skipbits) & 7))) & 1
else
bit = (byte >> (7 - (index & 7))) & 1
end
yield bit
index += 1
break if (index & 7) == 0
end
end
return self
end | [
"def",
"each_bit",
"return",
"enum_for",
"(",
":each_bit",
")",
"unless",
"block_given?",
"index",
"=",
"0",
"headbits",
"=",
"(",
"self",
".",
"bytesize",
"-",
"1",
")",
"*",
"8",
"skipbits",
"=",
"8",
"-",
"@bits",
"@data",
".",
"each_byte",
"do",
"|",
"byte",
"|",
"loop",
"do",
"break",
"if",
"index",
"==",
"@bitsize",
"if",
"index",
">=",
"headbits",
"bit",
"=",
"(",
"byte",
">>",
"(",
"7",
"-",
"(",
"(",
"index",
"+",
"skipbits",
")",
"&",
"7",
")",
")",
")",
"&",
"1",
"else",
"bit",
"=",
"(",
"byte",
">>",
"(",
"7",
"-",
"(",
"index",
"&",
"7",
")",
")",
")",
"&",
"1",
"end",
"yield",
"bit",
"index",
"+=",
"1",
"break",
"if",
"(",
"index",
"&",
"7",
")",
"==",
"0",
"end",
"end",
"return",
"self",
"end"
] | Call the given block once for each bit in the `Bitstring`, passing each
bit from first to last successively to the block. If no block is given,
returns an `Enumerator`.
@return [self]
@yield [Integer] | [
"Call",
"the",
"given",
"block",
"once",
"for",
"each",
"bit",
"in",
"the",
"Bitstring",
"passing",
"each",
"bit",
"from",
"first",
"to",
"last",
"successively",
"to",
"the",
"block",
".",
"If",
"no",
"block",
"is",
"given",
"returns",
"an",
"Enumerator",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/bitstring.rb#L322-L341 | train |
TylerRick/capybara-chrome_dev_tools | lib/capybara/chrome_dev_tools/driver_extensions.rb | Capybara::ChromeDevTools.DriverExtensions.start_crmux! | def start_crmux!(opts)
self.chrome_debugging_port = find_free_port(Capybara::ChromeDevTools.preferred_port)
self.crmux_listen_port = find_free_port(chrome_debugging_port + 1)
opts[:options].args << "--remote-debugging-port=#{chrome_debugging_port}"
#opts[:options].add_preference 'debuggerAddress', "127.0.0.1:#{crmux_listen_port}"
@debug_crmux = true
command = "npx crmux #{'-d' if @debug_crmux} \
--port=#{chrome_debugging_port} \
--listen=#{crmux_listen_port}"
puts %(command: #{command}) if Capybara::ChromeDevTools.verbose >= 3
if @debug_crmux
spawn_opts = {[:out, :err] => 'log/crmux.log'}
else
spawn_opts = {}
end
@crmux_pid = spawn(command, spawn_opts)
puts %(Started crmux [pid #{@crmux_pid}], listening at http://localhost:#{crmux_listen_port}, connected to localhost:#{chrome_debugging_port})
# You can also get the part later with: page.driver.browser.capabilities["goog:chromeOptions"]["debuggerAddress"]
sleep 0.1
at_exit do
puts "Killing crmux process #{@crmux_pid}..." if Capybara::ChromeDevTools.verbose >= 1
Process.kill 'TERM', @crmux_pid
end
end | ruby | def start_crmux!(opts)
self.chrome_debugging_port = find_free_port(Capybara::ChromeDevTools.preferred_port)
self.crmux_listen_port = find_free_port(chrome_debugging_port + 1)
opts[:options].args << "--remote-debugging-port=#{chrome_debugging_port}"
#opts[:options].add_preference 'debuggerAddress', "127.0.0.1:#{crmux_listen_port}"
@debug_crmux = true
command = "npx crmux #{'-d' if @debug_crmux} \
--port=#{chrome_debugging_port} \
--listen=#{crmux_listen_port}"
puts %(command: #{command}) if Capybara::ChromeDevTools.verbose >= 3
if @debug_crmux
spawn_opts = {[:out, :err] => 'log/crmux.log'}
else
spawn_opts = {}
end
@crmux_pid = spawn(command, spawn_opts)
puts %(Started crmux [pid #{@crmux_pid}], listening at http://localhost:#{crmux_listen_port}, connected to localhost:#{chrome_debugging_port})
# You can also get the part later with: page.driver.browser.capabilities["goog:chromeOptions"]["debuggerAddress"]
sleep 0.1
at_exit do
puts "Killing crmux process #{@crmux_pid}..." if Capybara::ChromeDevTools.verbose >= 1
Process.kill 'TERM', @crmux_pid
end
end | [
"def",
"start_crmux!",
"(",
"opts",
")",
"self",
".",
"chrome_debugging_port",
"=",
"find_free_port",
"(",
"Capybara",
"::",
"ChromeDevTools",
".",
"preferred_port",
")",
"self",
".",
"crmux_listen_port",
"=",
"find_free_port",
"(",
"chrome_debugging_port",
"+",
"1",
")",
"opts",
"[",
":options",
"]",
".",
"args",
"<<",
"\"--remote-debugging-port=#{chrome_debugging_port}\"",
"@debug_crmux",
"=",
"true",
"command",
"=",
"\"npx crmux #{'-d' if @debug_crmux} \\ --port=#{chrome_debugging_port} \\ --listen=#{crmux_listen_port}\"",
"puts",
"%(command: #{command})",
"if",
"Capybara",
"::",
"ChromeDevTools",
".",
"verbose",
">=",
"3",
"if",
"@debug_crmux",
"spawn_opts",
"=",
"{",
"[",
":out",
",",
":err",
"]",
"=>",
"'log/crmux.log'",
"}",
"else",
"spawn_opts",
"=",
"{",
"}",
"end",
"@crmux_pid",
"=",
"spawn",
"(",
"command",
",",
"spawn_opts",
")",
"puts",
"%(Started crmux [pid #{@crmux_pid}], listening at http://localhost:#{crmux_listen_port}, connected to localhost:#{chrome_debugging_port})",
"sleep",
"0.1",
"at_exit",
"do",
"puts",
"\"Killing crmux process #{@crmux_pid}...\"",
"if",
"Capybara",
"::",
"ChromeDevTools",
".",
"verbose",
">=",
"1",
"Process",
".",
"kill",
"'TERM'",
",",
"@crmux_pid",
"end",
"end"
] | Starts crmux and adds debuggerAddress to opts that points to crmux listen address. | [
"Starts",
"crmux",
"and",
"adds",
"debuggerAddress",
"to",
"opts",
"that",
"points",
"to",
"crmux",
"listen",
"address",
"."
] | 805fcc4ac84a125e15577a278de98d5590610f04 | https://github.com/TylerRick/capybara-chrome_dev_tools/blob/805fcc4ac84a125e15577a278de98d5590610f04/lib/capybara/chrome_dev_tools/driver_extensions.rb#L36-L61 | train |
bbc/hive-runner | lib/hive/device.rb | Hive.Device.start | def start
parent_pid = Process.pid
@worker_pid = Process.fork do
object = Object
@worker_class.split('::').each { |sub| object = object.const_get(sub) }
object.new(@options.merge('parent_pid' => parent_pid, 'device_identity' => self.identity, 'port_allocator' => self.port_allocator, 'hive_id' => Hive.hive_mind.device_details['id']))
end
Process.detach @worker_pid
Hive.logger.info("Worker started with pid #{@worker_pid}")
end | ruby | def start
parent_pid = Process.pid
@worker_pid = Process.fork do
object = Object
@worker_class.split('::').each { |sub| object = object.const_get(sub) }
object.new(@options.merge('parent_pid' => parent_pid, 'device_identity' => self.identity, 'port_allocator' => self.port_allocator, 'hive_id' => Hive.hive_mind.device_details['id']))
end
Process.detach @worker_pid
Hive.logger.info("Worker started with pid #{@worker_pid}")
end | [
"def",
"start",
"parent_pid",
"=",
"Process",
".",
"pid",
"@worker_pid",
"=",
"Process",
".",
"fork",
"do",
"object",
"=",
"Object",
"@worker_class",
".",
"split",
"(",
"'::'",
")",
".",
"each",
"{",
"|",
"sub",
"|",
"object",
"=",
"object",
".",
"const_get",
"(",
"sub",
")",
"}",
"object",
".",
"new",
"(",
"@options",
".",
"merge",
"(",
"'parent_pid'",
"=>",
"parent_pid",
",",
"'device_identity'",
"=>",
"self",
".",
"identity",
",",
"'port_allocator'",
"=>",
"self",
".",
"port_allocator",
",",
"'hive_id'",
"=>",
"Hive",
".",
"hive_mind",
".",
"device_details",
"[",
"'id'",
"]",
")",
")",
"end",
"Process",
".",
"detach",
"@worker_pid",
"Hive",
".",
"logger",
".",
"info",
"(",
"\"Worker started with pid #{@worker_pid}\"",
")",
"end"
] | Initialise the device
Start the worker process | [
"Initialise",
"the",
"device",
"Start",
"the",
"worker",
"process"
] | 9079f23362e201c342f416b5038d935e83e0de84 | https://github.com/bbc/hive-runner/blob/9079f23362e201c342f416b5038d935e83e0de84/lib/hive/device.rb#L23-L33 | train |
bbc/hive-runner | lib/hive/device.rb | Hive.Device.stop | def stop
protect_file = File.expand_path("#{@worker_pid}.protect", PIDS_DIRECTORY)
Hive.logger.debug("Checking for protected file: #{protect_file}")
if File.exists? File.expand_path("#{@worker_pid}.protect", PIDS_DIRECTORY)
Hive.logger.debug("PID #{@worker_pid} is protected")
false
else
@stop_count = @stop_count.nil? ? 0 : @stop_count + 1
if self.running?
if @stop_count < 30
Hive.logger.info("Attempting to terminate process #{@worker_pid} [#{@stop_count}]")
Process.kill 'TERM', @worker_pid
else
Hive.logger.info("Killing process #{@worker_pid}")
Process.kill 'KILL', @worker_pid if self.running?
end
end
if self.running?
false
else
@worker_pid = nil
@stop_count = nil
true
end
end
end | ruby | def stop
protect_file = File.expand_path("#{@worker_pid}.protect", PIDS_DIRECTORY)
Hive.logger.debug("Checking for protected file: #{protect_file}")
if File.exists? File.expand_path("#{@worker_pid}.protect", PIDS_DIRECTORY)
Hive.logger.debug("PID #{@worker_pid} is protected")
false
else
@stop_count = @stop_count.nil? ? 0 : @stop_count + 1
if self.running?
if @stop_count < 30
Hive.logger.info("Attempting to terminate process #{@worker_pid} [#{@stop_count}]")
Process.kill 'TERM', @worker_pid
else
Hive.logger.info("Killing process #{@worker_pid}")
Process.kill 'KILL', @worker_pid if self.running?
end
end
if self.running?
false
else
@worker_pid = nil
@stop_count = nil
true
end
end
end | [
"def",
"stop",
"protect_file",
"=",
"File",
".",
"expand_path",
"(",
"\"#{@worker_pid}.protect\"",
",",
"PIDS_DIRECTORY",
")",
"Hive",
".",
"logger",
".",
"debug",
"(",
"\"Checking for protected file: #{protect_file}\"",
")",
"if",
"File",
".",
"exists?",
"File",
".",
"expand_path",
"(",
"\"#{@worker_pid}.protect\"",
",",
"PIDS_DIRECTORY",
")",
"Hive",
".",
"logger",
".",
"debug",
"(",
"\"PID #{@worker_pid} is protected\"",
")",
"false",
"else",
"@stop_count",
"=",
"@stop_count",
".",
"nil?",
"?",
"0",
":",
"@stop_count",
"+",
"1",
"if",
"self",
".",
"running?",
"if",
"@stop_count",
"<",
"30",
"Hive",
".",
"logger",
".",
"info",
"(",
"\"Attempting to terminate process #{@worker_pid} [#{@stop_count}]\"",
")",
"Process",
".",
"kill",
"'TERM'",
",",
"@worker_pid",
"else",
"Hive",
".",
"logger",
".",
"info",
"(",
"\"Killing process #{@worker_pid}\"",
")",
"Process",
".",
"kill",
"'KILL'",
",",
"@worker_pid",
"if",
"self",
".",
"running?",
"end",
"end",
"if",
"self",
".",
"running?",
"false",
"else",
"@worker_pid",
"=",
"nil",
"@stop_count",
"=",
"nil",
"true",
"end",
"end",
"end"
] | Terminate the worker process | [
"Terminate",
"the",
"worker",
"process"
] | 9079f23362e201c342f416b5038d935e83e0de84 | https://github.com/bbc/hive-runner/blob/9079f23362e201c342f416b5038d935e83e0de84/lib/hive/device.rb#L36-L63 | train |
powerpak/tqdm-ruby | lib/tqdm/printer.rb | Tqdm.Printer.padded_line | def padded_line(iteration, elapsed_time)
meter_line = line(iteration, elapsed_time)
pad_size = [@last_printed_length - meter_line.size, 0].max
@last_printed_length = meter_line.size
meter_line + ' ' * pad_size
end | ruby | def padded_line(iteration, elapsed_time)
meter_line = line(iteration, elapsed_time)
pad_size = [@last_printed_length - meter_line.size, 0].max
@last_printed_length = meter_line.size
meter_line + ' ' * pad_size
end | [
"def",
"padded_line",
"(",
"iteration",
",",
"elapsed_time",
")",
"meter_line",
"=",
"line",
"(",
"iteration",
",",
"elapsed_time",
")",
"pad_size",
"=",
"[",
"@last_printed_length",
"-",
"meter_line",
".",
"size",
",",
"0",
"]",
".",
"max",
"@last_printed_length",
"=",
"meter_line",
".",
"size",
"meter_line",
"+",
"' '",
"*",
"pad_size",
"end"
] | Initialize a new Printer.
@param options [Hash] the options for the instantiating Tqdm::Decorator
@see Tqdm::Decorator#initialize
Pads a status line so that it is long enough to overwrite the previously written line
@param iteration [Integer] number of iterations, out of the total, that are completed
@param elapsed_time [Float] number of seconds passed since start
@return [String] the padded line | [
"Initialize",
"a",
"new",
"Printer",
"."
] | e67b364267e3d884329044b5cc9e1c4d1fd41637 | https://github.com/powerpak/tqdm-ruby/blob/e67b364267e3d884329044b5cc9e1c4d1fd41637/lib/tqdm/printer.rb#L32-L37 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.put | def put(index, element = yield(get(index)))
raise IndexError, "index #{index} outside of tuple bounds" if index < -@size
element = Erlang.from(element)
index += @size if index < 0
if index > @size
suffix = Array.new(index - @size, nil)
suffix << element
return replace_suffix(@size, suffix)
else
return update_root(index, element)
end
end | ruby | def put(index, element = yield(get(index)))
raise IndexError, "index #{index} outside of tuple bounds" if index < -@size
element = Erlang.from(element)
index += @size if index < 0
if index > @size
suffix = Array.new(index - @size, nil)
suffix << element
return replace_suffix(@size, suffix)
else
return update_root(index, element)
end
end | [
"def",
"put",
"(",
"index",
",",
"element",
"=",
"yield",
"(",
"get",
"(",
"index",
")",
")",
")",
"raise",
"IndexError",
",",
"\"index #{index} outside of tuple bounds\"",
"if",
"index",
"<",
"-",
"@size",
"element",
"=",
"Erlang",
".",
"from",
"(",
"element",
")",
"index",
"+=",
"@size",
"if",
"index",
"<",
"0",
"if",
"index",
">",
"@size",
"suffix",
"=",
"Array",
".",
"new",
"(",
"index",
"-",
"@size",
",",
"nil",
")",
"suffix",
"<<",
"element",
"return",
"replace_suffix",
"(",
"@size",
",",
"suffix",
")",
"else",
"return",
"update_root",
"(",
"index",
",",
"element",
")",
"end",
"end"
] | Return a new `Tuple` with a new value at the given `index`. If `index`
is greater than the length of the tuple, the returned tuple will be
padded with `nil`s to the correct size.
@overload put(index, element)
Return a new `Tuple` with the element at `index` replaced by `element`.
@param element [Object] The object to insert into that position
@example
Erlang::Tuple[1, 2, 3, 4].put(2, 99)
# => Erlang::Tuple[1, 2, 99, 4]
Erlang::Tuple[1, 2, 3, 4].put(-1, 99)
# => Erlang::Tuple[1, 2, 3, 99]
Erlang::Tuple[].put(2, 99)
# => Erlang::Tuple[nil, nil, 99]
@overload put(index)
Return a new `Tuple` with the element at `index` replaced by the return
value of the block.
@yield (existing) Once with the existing value at the given `index`.
@example
Erlang::Tuple[1, 2, 3, 4].put(2) { |v| v * 10 }
# => Erlang::Tuple[1, 2, 30, 4]
@param index [Integer] The index to update. May be negative.
@return [Tuple] | [
"Return",
"a",
"new",
"Tuple",
"with",
"a",
"new",
"value",
"at",
"the",
"given",
"index",
".",
"If",
"index",
"is",
"greater",
"than",
"the",
"length",
"of",
"the",
"tuple",
"the",
"returned",
"tuple",
"will",
"be",
"padded",
"with",
"nil",
"s",
"to",
"the",
"correct",
"size",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L202-L213 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.fetch | def fetch(index, default = (missing_default = true))
if index >= -@size && index < @size
return get(index)
elsif block_given?
return Erlang.from(yield(index))
elsif !missing_default
return Erlang.from(default)
else
raise IndexError, "index #{index} outside of tuple bounds"
end
end | ruby | def fetch(index, default = (missing_default = true))
if index >= -@size && index < @size
return get(index)
elsif block_given?
return Erlang.from(yield(index))
elsif !missing_default
return Erlang.from(default)
else
raise IndexError, "index #{index} outside of tuple bounds"
end
end | [
"def",
"fetch",
"(",
"index",
",",
"default",
"=",
"(",
"missing_default",
"=",
"true",
")",
")",
"if",
"index",
">=",
"-",
"@size",
"&&",
"index",
"<",
"@size",
"return",
"get",
"(",
"index",
")",
"elsif",
"block_given?",
"return",
"Erlang",
".",
"from",
"(",
"yield",
"(",
"index",
")",
")",
"elsif",
"!",
"missing_default",
"return",
"Erlang",
".",
"from",
"(",
"default",
")",
"else",
"raise",
"IndexError",
",",
"\"index #{index} outside of tuple bounds\"",
"end",
"end"
] | Retrieve the value at `index` with optional default.
@overload fetch(index)
Retrieve the value at the given index, or raise an `IndexError` if not
found.
@param index [Integer] The index to look up
@raise [IndexError] if index does not exist
@example
t = Erlang::Tuple["A", "B", "C", "D"]
t.fetch(2) # => "C"
t.fetch(-1) # => "D"
t.fetch(4) # => IndexError: index 4 outside of tuple bounds
@overload fetch(index) { |index| ... }
Retrieve the value at the given index, or return the result of yielding
the block if not found.
@yield Once if the index is not found.
@yieldparam [Integer] index The index which does not exist
@yieldreturn [Object] Default value to return
@param index [Integer] The index to look up
@example
t = Erlang::Tuple["A", "B", "C", "D"]
t.fetch(2) { |i| i * i } # => "C"
t.fetch(4) { |i| i * i } # => 16
@overload fetch(index, default)
Retrieve the value at the given index, or return the provided `default`
value if not found.
@param index [Integer] The index to look up
@param default [Object] Object to return if the key is not found
@example
t = Erlang::Tuple["A", "B", "C", "D"]
t.fetch(2, "Z") # => "C"
t.fetch(4, "Z") # => "Z"
@return [Object] | [
"Retrieve",
"the",
"value",
"at",
"index",
"with",
"optional",
"default",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L298-L308 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.slice | def slice(arg, length = (missing_length = true))
if missing_length
if arg.is_a?(Range)
from, to = arg.begin, arg.end
from += @size if from < 0
to += @size if to < 0
to += 1 if !arg.exclude_end?
length = to - from
length = 0 if length < 0
return subsequence(from, length)
else
return get(arg)
end
else
arg += @size if arg < 0
return subsequence(arg, length)
end
end | ruby | def slice(arg, length = (missing_length = true))
if missing_length
if arg.is_a?(Range)
from, to = arg.begin, arg.end
from += @size if from < 0
to += @size if to < 0
to += 1 if !arg.exclude_end?
length = to - from
length = 0 if length < 0
return subsequence(from, length)
else
return get(arg)
end
else
arg += @size if arg < 0
return subsequence(arg, length)
end
end | [
"def",
"slice",
"(",
"arg",
",",
"length",
"=",
"(",
"missing_length",
"=",
"true",
")",
")",
"if",
"missing_length",
"if",
"arg",
".",
"is_a?",
"(",
"Range",
")",
"from",
",",
"to",
"=",
"arg",
".",
"begin",
",",
"arg",
".",
"end",
"from",
"+=",
"@size",
"if",
"from",
"<",
"0",
"to",
"+=",
"@size",
"if",
"to",
"<",
"0",
"to",
"+=",
"1",
"if",
"!",
"arg",
".",
"exclude_end?",
"length",
"=",
"to",
"-",
"from",
"length",
"=",
"0",
"if",
"length",
"<",
"0",
"return",
"subsequence",
"(",
"from",
",",
"length",
")",
"else",
"return",
"get",
"(",
"arg",
")",
"end",
"else",
"arg",
"+=",
"@size",
"if",
"arg",
"<",
"0",
"return",
"subsequence",
"(",
"arg",
",",
"length",
")",
"end",
"end"
] | Return specific objects from the `Tuple`. All overloads return `nil` if
the starting index is out of range.
@overload tuple.slice(index)
Returns a single object at the given `index`. If `index` is negative,
count backwards from the end.
@param index [Integer] The index to retrieve. May be negative.
@return [Object]
@example
t = Erlang::Tuple["A", "B", "C", "D", "E", "F"]
t[2] # => "C"
t[-1] # => "F"
t[6] # => nil
@overload tuple.slice(index, length)
Return a subtuple starting at `index` and continuing for `length`
elements or until the end of the `Tuple`, whichever occurs first.
@param start [Integer] The index to start retrieving elements from. May be
negative.
@param length [Integer] The number of elements to retrieve.
@return [Tuple]
@example
t = Erlang::Tuple["A", "B", "C", "D", "E", "F"]
t[2, 3] # => Erlang::Tuple["C", "D", "E"]
t[-2, 3] # => Erlang::Tuple["E", "F"]
t[20, 1] # => nil
@overload tuple.slice(index..end)
Return a subtuple starting at `index` and continuing to index
`end` or the end of the `Tuple`, whichever occurs first.
@param range [Range] The range of indices to retrieve.
@return [Tuple]
@example
t = Erlang::Tuple["A", "B", "C", "D", "E", "F"]
t[2..3] # => Erlang::Tuple["C", "D"]
t[-2..100] # => Erlang::Tuple["E", "F"]
t[20..21] # => nil | [
"Return",
"specific",
"objects",
"from",
"the",
"Tuple",
".",
"All",
"overloads",
"return",
"nil",
"if",
"the",
"starting",
"index",
"is",
"out",
"of",
"range",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L350-L367 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.insert | def insert(index, *elements)
raise IndexError if index < -@size
index += @size if index < 0
elements = elements.map { |element| Erlang.from(element) }
if index < @size
suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
suffix.unshift(*elements)
elsif index == @size
suffix = elements
else
suffix = Array.new(index - @size, nil).concat(elements)
index = @size
end
return replace_suffix(index, suffix)
end | ruby | def insert(index, *elements)
raise IndexError if index < -@size
index += @size if index < 0
elements = elements.map { |element| Erlang.from(element) }
if index < @size
suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
suffix.unshift(*elements)
elsif index == @size
suffix = elements
else
suffix = Array.new(index - @size, nil).concat(elements)
index = @size
end
return replace_suffix(index, suffix)
end | [
"def",
"insert",
"(",
"index",
",",
"*",
"elements",
")",
"raise",
"IndexError",
"if",
"index",
"<",
"-",
"@size",
"index",
"+=",
"@size",
"if",
"index",
"<",
"0",
"elements",
"=",
"elements",
".",
"map",
"{",
"|",
"element",
"|",
"Erlang",
".",
"from",
"(",
"element",
")",
"}",
"if",
"index",
"<",
"@size",
"suffix",
"=",
"flatten_suffix",
"(",
"@root",
",",
"@levels",
"*",
"BITS_PER_LEVEL",
",",
"index",
",",
"[",
"]",
")",
"suffix",
".",
"unshift",
"(",
"*",
"elements",
")",
"elsif",
"index",
"==",
"@size",
"suffix",
"=",
"elements",
"else",
"suffix",
"=",
"Array",
".",
"new",
"(",
"index",
"-",
"@size",
",",
"nil",
")",
".",
"concat",
"(",
"elements",
")",
"index",
"=",
"@size",
"end",
"return",
"replace_suffix",
"(",
"index",
",",
"suffix",
")",
"end"
] | Return a new `Tuple` with the given values inserted before the element
at `index`. If `index` is greater than the current length, `nil` values
are added to pad the `Tuple` to the required size.
@example
Erlang::Tuple["A", "B", "C", "D"].insert(2, "X", "Y", "Z")
# => Erlang::Tuple["A", "B", "X", "Y", "Z", "C", "D"]
Erlang::Tuple[].insert(2, "X", "Y", "Z")
# => Erlang::Tuple[nil, nil, "X", "Y", "Z"]
@param index [Integer] The index where the new elements should go
@param elements [Array] The elements to add
@return [Tuple]
@raise [IndexError] if index exceeds negative range. | [
"Return",
"a",
"new",
"Tuple",
"with",
"the",
"given",
"values",
"inserted",
"before",
"the",
"element",
"at",
"index",
".",
"If",
"index",
"is",
"greater",
"than",
"the",
"current",
"length",
"nil",
"values",
"are",
"added",
"to",
"pad",
"the",
"Tuple",
"to",
"the",
"required",
"size",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L384-L401 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.delete_at | def delete_at(index)
return self if index >= @size || index < -@size
index += @size if index < 0
suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
return replace_suffix(index, suffix.tap { |a| a.shift })
end | ruby | def delete_at(index)
return self if index >= @size || index < -@size
index += @size if index < 0
suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
return replace_suffix(index, suffix.tap { |a| a.shift })
end | [
"def",
"delete_at",
"(",
"index",
")",
"return",
"self",
"if",
"index",
">=",
"@size",
"||",
"index",
"<",
"-",
"@size",
"index",
"+=",
"@size",
"if",
"index",
"<",
"0",
"suffix",
"=",
"flatten_suffix",
"(",
"@root",
",",
"@levels",
"*",
"BITS_PER_LEVEL",
",",
"index",
",",
"[",
"]",
")",
"return",
"replace_suffix",
"(",
"index",
",",
"suffix",
".",
"tap",
"{",
"|",
"a",
"|",
"a",
".",
"shift",
"}",
")",
"end"
] | Return a new `Tuple` with the element at `index` removed. If the given `index`
does not exist, return `self`.
@example
Erlang::Tuple["A", "B", "C", "D"].delete_at(2)
# => Erlang::Tuple["A", "B", "D"]
@param index [Integer] The index to remove
@return [Tuple] | [
"Return",
"a",
"new",
"Tuple",
"with",
"the",
"element",
"at",
"index",
"removed",
".",
"If",
"the",
"given",
"index",
"does",
"not",
"exist",
"return",
"self",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L412-L418 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.select | def select
return enum_for(:select) unless block_given?
return reduce(self.class.empty) { |tuple, element| yield(element) ? tuple.add(element) : tuple }
end | ruby | def select
return enum_for(:select) unless block_given?
return reduce(self.class.empty) { |tuple, element| yield(element) ? tuple.add(element) : tuple }
end | [
"def",
"select",
"return",
"enum_for",
"(",
":select",
")",
"unless",
"block_given?",
"return",
"reduce",
"(",
"self",
".",
"class",
".",
"empty",
")",
"{",
"|",
"tuple",
",",
"element",
"|",
"yield",
"(",
"element",
")",
"?",
"tuple",
".",
"add",
"(",
"element",
")",
":",
"tuple",
"}",
"end"
] | Return a new `Tuple` containing all elements for which the given block returns
true.
@example
Erlang::Tuple["Bird", "Cow", "Elephant"].select { |e| e.size >= 4 }
# => Erlang::Tuple["Bird", "Elephant"]
@return [Tuple]
@yield [element] Once for each element. | [
"Return",
"a",
"new",
"Tuple",
"containing",
"all",
"elements",
"for",
"which",
"the",
"given",
"block",
"returns",
"true",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L501-L504 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.shuffle | def shuffle
return self.class.new(((array = to_a).frozen? ? array.shuffle : array.shuffle!).freeze)
end | ruby | def shuffle
return self.class.new(((array = to_a).frozen? ? array.shuffle : array.shuffle!).freeze)
end | [
"def",
"shuffle",
"return",
"self",
".",
"class",
".",
"new",
"(",
"(",
"(",
"array",
"=",
"to_a",
")",
".",
"frozen?",
"?",
"array",
".",
"shuffle",
":",
"array",
".",
"shuffle!",
")",
".",
"freeze",
")",
"end"
] | Return a new `Tuple` with the same elements as this one, but randomly permuted.
@example
Erlang::Tuple[1, 2, 3, 4].shuffle # => Erlang::Tuple[4, 1, 3, 2]
@return [Tuple] | [
"Return",
"a",
"new",
"Tuple",
"with",
"the",
"same",
"elements",
"as",
"this",
"one",
"but",
"randomly",
"permuted",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L556-L558 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.reverse | def reverse
return self.class.new(((array = to_a).frozen? ? array.reverse : array.reverse!).freeze)
end | ruby | def reverse
return self.class.new(((array = to_a).frozen? ? array.reverse : array.reverse!).freeze)
end | [
"def",
"reverse",
"return",
"self",
".",
"class",
".",
"new",
"(",
"(",
"(",
"array",
"=",
"to_a",
")",
".",
"frozen?",
"?",
"array",
".",
"reverse",
":",
"array",
".",
"reverse!",
")",
".",
"freeze",
")",
"end"
] | Return a new `Tuple` with the same elements as this one, but in reverse order.
@example
Erlang::Tuple["A", "B", "C"].reverse # => Erlang::Tuple["C", "B", "A"]
@return [Tuple] | [
"Return",
"a",
"new",
"Tuple",
"with",
"the",
"same",
"elements",
"as",
"this",
"one",
"but",
"in",
"reverse",
"order",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L593-L595 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.rotate | def rotate(count = 1)
return self if (count % @size) == 0
return self.class.new(((array = to_a).frozen? ? array.rotate(count) : array.rotate!(count)).freeze)
end | ruby | def rotate(count = 1)
return self if (count % @size) == 0
return self.class.new(((array = to_a).frozen? ? array.rotate(count) : array.rotate!(count)).freeze)
end | [
"def",
"rotate",
"(",
"count",
"=",
"1",
")",
"return",
"self",
"if",
"(",
"count",
"%",
"@size",
")",
"==",
"0",
"return",
"self",
".",
"class",
".",
"new",
"(",
"(",
"(",
"array",
"=",
"to_a",
")",
".",
"frozen?",
"?",
"array",
".",
"rotate",
"(",
"count",
")",
":",
"array",
".",
"rotate!",
"(",
"count",
")",
")",
".",
"freeze",
")",
"end"
] | Return a new `Tuple` with the same elements, but rotated so that the one at
index `count` is the first element of the new tuple. If `count` is positive,
the elements will be shifted left, and those shifted past the lowest position
will be moved to the end. If `count` is negative, the elements will be shifted
right, and those shifted past the last position will be moved to the beginning.
@example
t = Erlang::Tuple["A", "B", "C", "D", "E", "F"]
t.rotate(2) # => Erlang::Tuple["C", "D", "E", "F", "A", "B"]
t.rotate(-1) # => Erlang::Tuple["F", "A", "B", "C", "D", "E"]
@param count [Integer] The number of positions to shift elements by
@return [Tuple] | [
"Return",
"a",
"new",
"Tuple",
"with",
"the",
"same",
"elements",
"but",
"rotated",
"so",
"that",
"the",
"one",
"at",
"index",
"count",
"is",
"the",
"first",
"element",
"of",
"the",
"new",
"tuple",
".",
"If",
"count",
"is",
"positive",
"the",
"elements",
"will",
"be",
"shifted",
"left",
"and",
"those",
"shifted",
"past",
"the",
"lowest",
"position",
"will",
"be",
"moved",
"to",
"the",
"end",
".",
"If",
"count",
"is",
"negative",
"the",
"elements",
"will",
"be",
"shifted",
"right",
"and",
"those",
"shifted",
"past",
"the",
"last",
"position",
"will",
"be",
"moved",
"to",
"the",
"beginning",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L610-L613 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.sort | def sort(&comparator)
comparator = Erlang.method(:compare) unless block_given?
array = super(&comparator)
return self.class.new(array)
end | ruby | def sort(&comparator)
comparator = Erlang.method(:compare) unless block_given?
array = super(&comparator)
return self.class.new(array)
end | [
"def",
"sort",
"(",
"&",
"comparator",
")",
"comparator",
"=",
"Erlang",
".",
"method",
"(",
":compare",
")",
"unless",
"block_given?",
"array",
"=",
"super",
"(",
"&",
"comparator",
")",
"return",
"self",
".",
"class",
".",
"new",
"(",
"array",
")",
"end"
] | Return a new `Tuple` with the same elements, but sorted.
@overload sort
Compare elements with their natural sort key (`#<=>`).
@example
Erlang::Tuple["Elephant", "Dog", "Lion"].sort
# => Erlang::Tuple["Dog", "Elephant", "Lion"]
@overload sort
Uses the block as a comparator to determine sorted order.
@yield [a, b] Any number of times with different pairs of elements.
@yieldreturn [Integer] Negative if the first element should be sorted
lower, positive if the latter element, or 0 if
equal.
@example
Erlang::Tuple["Elephant", "Dog", "Lion"].sort { |a,b| a.size <=> b.size }
# => Erlang::Tuple["Dog", "Lion", "Elephant"]
@return [Tuple] | [
"Return",
"a",
"new",
"Tuple",
"with",
"the",
"same",
"elements",
"but",
"sorted",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L715-L719 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.drop | def drop(n)
return self if n == 0
return self.class.empty if n >= @size
raise ArgumentError, "attempt to drop negative size" if n < 0
return self.class.new(flatten_suffix(@root, @levels * BITS_PER_LEVEL, n, []))
end | ruby | def drop(n)
return self if n == 0
return self.class.empty if n >= @size
raise ArgumentError, "attempt to drop negative size" if n < 0
return self.class.new(flatten_suffix(@root, @levels * BITS_PER_LEVEL, n, []))
end | [
"def",
"drop",
"(",
"n",
")",
"return",
"self",
"if",
"n",
"==",
"0",
"return",
"self",
".",
"class",
".",
"empty",
"if",
"n",
">=",
"@size",
"raise",
"ArgumentError",
",",
"\"attempt to drop negative size\"",
"if",
"n",
"<",
"0",
"return",
"self",
".",
"class",
".",
"new",
"(",
"flatten_suffix",
"(",
"@root",
",",
"@levels",
"*",
"BITS_PER_LEVEL",
",",
"n",
",",
"[",
"]",
")",
")",
"end"
] | Drop the first `n` elements and return the rest in a new `Tuple`.
@example
Erlang::Tuple["A", "B", "C", "D", "E", "F"].drop(2)
# => Erlang::Tuple["C", "D", "E", "F"]
@param n [Integer] The number of elements to remove
@return [Tuple]
@raise ArgumentError if `n` is negative. | [
"Drop",
"the",
"first",
"n",
"elements",
"and",
"return",
"the",
"rest",
"in",
"a",
"new",
"Tuple",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L749-L754 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.* | def *(times)
return self.class.empty if times == 0
return self if times == 1
result = (to_a * times)
return result.is_a?(Array) ? self.class.new(result) : result
end | ruby | def *(times)
return self.class.empty if times == 0
return self if times == 1
result = (to_a * times)
return result.is_a?(Array) ? self.class.new(result) : result
end | [
"def",
"*",
"(",
"times",
")",
"return",
"self",
".",
"class",
".",
"empty",
"if",
"times",
"==",
"0",
"return",
"self",
"if",
"times",
"==",
"1",
"result",
"=",
"(",
"to_a",
"*",
"times",
")",
"return",
"result",
".",
"is_a?",
"(",
"Array",
")",
"?",
"self",
".",
"class",
".",
"new",
"(",
"result",
")",
":",
"result",
"end"
] | Repetition. Return a new `Tuple` built by concatenating `times` copies
of this one together.
@example
Erlang::Tuple["A", "B"] * 3
# => Erlang::Tuple["A", "B", "A", "B", "A", "B"]
@param times [Integer] The number of times to repeat the elements in this tuple
@return [Tuple] | [
"Repetition",
".",
"Return",
"a",
"new",
"Tuple",
"built",
"by",
"concatenating",
"times",
"copies",
"of",
"this",
"one",
"together",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L806-L811 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.combination | def combination(n)
return enum_for(:combination, n) if not block_given?
return self if n < 0 || @size < n
if n == 0
yield []
elsif n == 1
each { |element| yield [element] }
elsif n == @size
yield self.to_a
else
combos = lambda do |result,index,remaining|
while @size - index > remaining
if remaining == 1
yield result.dup << get(index)
else
combos[result.dup << get(index), index+1, remaining-1]
end
index += 1
end
index.upto(@size-1) { |i| result << get(i) }
yield result
end
combos[[], 0, n]
end
return self
end | ruby | def combination(n)
return enum_for(:combination, n) if not block_given?
return self if n < 0 || @size < n
if n == 0
yield []
elsif n == 1
each { |element| yield [element] }
elsif n == @size
yield self.to_a
else
combos = lambda do |result,index,remaining|
while @size - index > remaining
if remaining == 1
yield result.dup << get(index)
else
combos[result.dup << get(index), index+1, remaining-1]
end
index += 1
end
index.upto(@size-1) { |i| result << get(i) }
yield result
end
combos[[], 0, n]
end
return self
end | [
"def",
"combination",
"(",
"n",
")",
"return",
"enum_for",
"(",
":combination",
",",
"n",
")",
"if",
"not",
"block_given?",
"return",
"self",
"if",
"n",
"<",
"0",
"||",
"@size",
"<",
"n",
"if",
"n",
"==",
"0",
"yield",
"[",
"]",
"elsif",
"n",
"==",
"1",
"each",
"{",
"|",
"element",
"|",
"yield",
"[",
"element",
"]",
"}",
"elsif",
"n",
"==",
"@size",
"yield",
"self",
".",
"to_a",
"else",
"combos",
"=",
"lambda",
"do",
"|",
"result",
",",
"index",
",",
"remaining",
"|",
"while",
"@size",
"-",
"index",
">",
"remaining",
"if",
"remaining",
"==",
"1",
"yield",
"result",
".",
"dup",
"<<",
"get",
"(",
"index",
")",
"else",
"combos",
"[",
"result",
".",
"dup",
"<<",
"get",
"(",
"index",
")",
",",
"index",
"+",
"1",
",",
"remaining",
"-",
"1",
"]",
"end",
"index",
"+=",
"1",
"end",
"index",
".",
"upto",
"(",
"@size",
"-",
"1",
")",
"{",
"|",
"i",
"|",
"result",
"<<",
"get",
"(",
"i",
")",
"}",
"yield",
"result",
"end",
"combos",
"[",
"[",
"]",
",",
"0",
",",
"n",
"]",
"end",
"return",
"self",
"end"
] | When invoked with a block, yields all combinations of length `n` of elements
from the `Tuple`, and then returns `self`. There is no guarantee about
which order the combinations will be yielded.
If no block is given, an `Enumerator` is returned instead.
@example
t = Erlang::Tuple[5, 6, 7, 8]
t.combination(3) { |c| puts "Combination: #{c}" }
Combination: [5, 6, 7]
Combination: [5, 6, 8]
Combination: [5, 7, 8]
Combination: [6, 7, 8]
#=> Erlang::Tuple[5, 6, 7, 8]
@return [self, Enumerator] | [
"When",
"invoked",
"with",
"a",
"block",
"yields",
"all",
"combinations",
"of",
"length",
"n",
"of",
"elements",
"from",
"the",
"Tuple",
"and",
"then",
"returns",
"self",
".",
"There",
"is",
"no",
"guarantee",
"about",
"which",
"order",
"the",
"combinations",
"will",
"be",
"yielded",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L886-L911 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.repeated_combination | def repeated_combination(n)
return enum_for(:repeated_combination, n) if not block_given?
if n < 0
# yield nothing
elsif n == 0
yield []
elsif n == 1
each { |element| yield [element] }
elsif @size == 0
# yield nothing
else
combos = lambda do |result,index,remaining|
while index < @size-1
if remaining == 1
yield result.dup << get(index)
else
combos[result.dup << get(index), index, remaining-1]
end
index += 1
end
element = get(index)
remaining.times { result << element }
yield result
end
combos[[], 0, n]
end
return self
end | ruby | def repeated_combination(n)
return enum_for(:repeated_combination, n) if not block_given?
if n < 0
# yield nothing
elsif n == 0
yield []
elsif n == 1
each { |element| yield [element] }
elsif @size == 0
# yield nothing
else
combos = lambda do |result,index,remaining|
while index < @size-1
if remaining == 1
yield result.dup << get(index)
else
combos[result.dup << get(index), index, remaining-1]
end
index += 1
end
element = get(index)
remaining.times { result << element }
yield result
end
combos[[], 0, n]
end
return self
end | [
"def",
"repeated_combination",
"(",
"n",
")",
"return",
"enum_for",
"(",
":repeated_combination",
",",
"n",
")",
"if",
"not",
"block_given?",
"if",
"n",
"<",
"0",
"elsif",
"n",
"==",
"0",
"yield",
"[",
"]",
"elsif",
"n",
"==",
"1",
"each",
"{",
"|",
"element",
"|",
"yield",
"[",
"element",
"]",
"}",
"elsif",
"@size",
"==",
"0",
"else",
"combos",
"=",
"lambda",
"do",
"|",
"result",
",",
"index",
",",
"remaining",
"|",
"while",
"index",
"<",
"@size",
"-",
"1",
"if",
"remaining",
"==",
"1",
"yield",
"result",
".",
"dup",
"<<",
"get",
"(",
"index",
")",
"else",
"combos",
"[",
"result",
".",
"dup",
"<<",
"get",
"(",
"index",
")",
",",
"index",
",",
"remaining",
"-",
"1",
"]",
"end",
"index",
"+=",
"1",
"end",
"element",
"=",
"get",
"(",
"index",
")",
"remaining",
".",
"times",
"{",
"result",
"<<",
"element",
"}",
"yield",
"result",
"end",
"combos",
"[",
"[",
"]",
",",
"0",
",",
"n",
"]",
"end",
"return",
"self",
"end"
] | When invoked with a block, yields all repeated combinations of length `n` of
tuples from the `Tuple`, and then returns `self`. A "repeated combination" is
one in which any tuple from the `Tuple` can appear consecutively any number of
times.
There is no guarantee about which order the combinations will be yielded in.
If no block is given, an `Enumerator` is returned instead.
@example
t = Erlang::Tuple[5, 6, 7, 8]
t.repeated_combination(2) { |c| puts "Combination: #{c}" }
Combination: [5, 5]
Combination: [5, 6]
Combination: [5, 7]
Combination: [5, 8]
Combination: [6, 6]
Combination: [6, 7]
Combination: [6, 8]
Combination: [7, 7]
Combination: [7, 8]
Combination: [8, 8]
# => Erlang::Tuple[5, 6, 7, 8]
@return [self, Enumerator] | [
"When",
"invoked",
"with",
"a",
"block",
"yields",
"all",
"repeated",
"combinations",
"of",
"length",
"n",
"of",
"tuples",
"from",
"the",
"Tuple",
"and",
"then",
"returns",
"self",
".",
"A",
"repeated",
"combination",
"is",
"one",
"in",
"which",
"any",
"tuple",
"from",
"the",
"Tuple",
"can",
"appear",
"consecutively",
"any",
"number",
"of",
"times",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L939-L966 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.permutation | def permutation(n = @size)
return enum_for(:permutation, n) if not block_given?
if n < 0 || @size < n
# yield nothing
elsif n == 0
yield []
elsif n == 1
each { |element| yield [element] }
else
used, result = [], []
perms = lambda do |index|
0.upto(@size-1) do |i|
if !used[i]
result[index] = get(i)
if index < n-1
used[i] = true
perms[index+1]
used[i] = false
else
yield result.dup
end
end
end
end
perms[0]
end
return self
end | ruby | def permutation(n = @size)
return enum_for(:permutation, n) if not block_given?
if n < 0 || @size < n
# yield nothing
elsif n == 0
yield []
elsif n == 1
each { |element| yield [element] }
else
used, result = [], []
perms = lambda do |index|
0.upto(@size-1) do |i|
if !used[i]
result[index] = get(i)
if index < n-1
used[i] = true
perms[index+1]
used[i] = false
else
yield result.dup
end
end
end
end
perms[0]
end
return self
end | [
"def",
"permutation",
"(",
"n",
"=",
"@size",
")",
"return",
"enum_for",
"(",
":permutation",
",",
"n",
")",
"if",
"not",
"block_given?",
"if",
"n",
"<",
"0",
"||",
"@size",
"<",
"n",
"elsif",
"n",
"==",
"0",
"yield",
"[",
"]",
"elsif",
"n",
"==",
"1",
"each",
"{",
"|",
"element",
"|",
"yield",
"[",
"element",
"]",
"}",
"else",
"used",
",",
"result",
"=",
"[",
"]",
",",
"[",
"]",
"perms",
"=",
"lambda",
"do",
"|",
"index",
"|",
"0",
".",
"upto",
"(",
"@size",
"-",
"1",
")",
"do",
"|",
"i",
"|",
"if",
"!",
"used",
"[",
"i",
"]",
"result",
"[",
"index",
"]",
"=",
"get",
"(",
"i",
")",
"if",
"index",
"<",
"n",
"-",
"1",
"used",
"[",
"i",
"]",
"=",
"true",
"perms",
"[",
"index",
"+",
"1",
"]",
"used",
"[",
"i",
"]",
"=",
"false",
"else",
"yield",
"result",
".",
"dup",
"end",
"end",
"end",
"end",
"perms",
"[",
"0",
"]",
"end",
"return",
"self",
"end"
] | Yields all permutations of length `n` of elements from the `Tuple`, and then
returns `self`. If no length `n` is specified, permutations of all elements
will be yielded.
There is no guarantee about which order the permutations will be yielded in.
If no block is given, an `Enumerator` is returned instead.
@example
t = Erlang::Tuple[5, 6, 7]
t.permutation(2) { |p| puts "Permutation: #{p}" }
Permutation: [5, 6]
Permutation: [5, 7]
Permutation: [6, 5]
Permutation: [6, 7]
Permutation: [7, 5]
Permutation: [7, 6]
# => Erlang::Tuple[5, 6, 7]
@return [self, Enumerator] | [
"Yields",
"all",
"permutations",
"of",
"length",
"n",
"of",
"elements",
"from",
"the",
"Tuple",
"and",
"then",
"returns",
"self",
".",
"If",
"no",
"length",
"n",
"is",
"specified",
"permutations",
"of",
"all",
"elements",
"will",
"be",
"yielded",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L989-L1016 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.product | def product(*tuples)
tuples = tuples.map { |tuple| Erlang.from(tuple) }
# if no tuples passed, return "product" as in result of multiplying all elements
return super if tuples.empty?
tuples.unshift(self)
if tuples.any?(&:empty?)
return block_given? ? self : []
end
counters = Array.new(tuples.size, 0)
bump_counters = lambda do
i = tuples.size-1
counters[i] += 1
while counters[i] == tuples[i].size
counters[i] = 0
i -= 1
return true if i == -1 # we are done
counters[i] += 1
end
false # not done yet
end
build_array = lambda do
array = []
counters.each_with_index { |index,i| array << tuples[i][index] }
array
end
if block_given?
while true
yield build_array[]
return self if bump_counters[]
end
else
result = []
while true
result << build_array[]
return result if bump_counters[]
end
end
end | ruby | def product(*tuples)
tuples = tuples.map { |tuple| Erlang.from(tuple) }
# if no tuples passed, return "product" as in result of multiplying all elements
return super if tuples.empty?
tuples.unshift(self)
if tuples.any?(&:empty?)
return block_given? ? self : []
end
counters = Array.new(tuples.size, 0)
bump_counters = lambda do
i = tuples.size-1
counters[i] += 1
while counters[i] == tuples[i].size
counters[i] = 0
i -= 1
return true if i == -1 # we are done
counters[i] += 1
end
false # not done yet
end
build_array = lambda do
array = []
counters.each_with_index { |index,i| array << tuples[i][index] }
array
end
if block_given?
while true
yield build_array[]
return self if bump_counters[]
end
else
result = []
while true
result << build_array[]
return result if bump_counters[]
end
end
end | [
"def",
"product",
"(",
"*",
"tuples",
")",
"tuples",
"=",
"tuples",
".",
"map",
"{",
"|",
"tuple",
"|",
"Erlang",
".",
"from",
"(",
"tuple",
")",
"}",
"return",
"super",
"if",
"tuples",
".",
"empty?",
"tuples",
".",
"unshift",
"(",
"self",
")",
"if",
"tuples",
".",
"any?",
"(",
"&",
":empty?",
")",
"return",
"block_given?",
"?",
"self",
":",
"[",
"]",
"end",
"counters",
"=",
"Array",
".",
"new",
"(",
"tuples",
".",
"size",
",",
"0",
")",
"bump_counters",
"=",
"lambda",
"do",
"i",
"=",
"tuples",
".",
"size",
"-",
"1",
"counters",
"[",
"i",
"]",
"+=",
"1",
"while",
"counters",
"[",
"i",
"]",
"==",
"tuples",
"[",
"i",
"]",
".",
"size",
"counters",
"[",
"i",
"]",
"=",
"0",
"i",
"-=",
"1",
"return",
"true",
"if",
"i",
"==",
"-",
"1",
"counters",
"[",
"i",
"]",
"+=",
"1",
"end",
"false",
"end",
"build_array",
"=",
"lambda",
"do",
"array",
"=",
"[",
"]",
"counters",
".",
"each_with_index",
"{",
"|",
"index",
",",
"i",
"|",
"array",
"<<",
"tuples",
"[",
"i",
"]",
"[",
"index",
"]",
"}",
"array",
"end",
"if",
"block_given?",
"while",
"true",
"yield",
"build_array",
"[",
"]",
"return",
"self",
"if",
"bump_counters",
"[",
"]",
"end",
"else",
"result",
"=",
"[",
"]",
"while",
"true",
"result",
"<<",
"build_array",
"[",
"]",
"return",
"result",
"if",
"bump_counters",
"[",
"]",
"end",
"end",
"end"
] | Cartesian product or multiplication.
@overload product(*tuples)
Return a `Tuple` of all combinations of elements from this `Tuple` and each
of the given tuples or arrays. The length of the returned `Tuple` is the product
of `self.size` and the size of each argument tuple or array.
@example
t1 = Erlang::Tuple[1, 2, 3]
t2 = Erlang::Tuple["A", "B"]
t1.product(t2)
# => [[1, "A"], [1, "B"], [2, "A"], [2, "B"], [3, "A"], [3, "B"]]
@overload product
Return the result of multiplying all the elements in this `Tuple` together.
@example
Erlang::Tuple[1, 2, 3, 4, 5].product # => 120
@return [Tuple] | [
"Cartesian",
"product",
"or",
"multiplication",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L1087-L1129 | train |
potatosalad/ruby-erlang-terms | lib/erlang/tuple.rb | Erlang.Tuple.rindex | def rindex(obj = (missing_arg = true))
obj = Erlang.from(obj)
i = @size - 1
if missing_arg
if block_given?
reverse_each { |element| return i if yield element; i -= 1 }
return nil
else
return enum_for(:rindex)
end
else
reverse_each { |element| return i if element == obj; i -= 1 }
return nil
end
end | ruby | def rindex(obj = (missing_arg = true))
obj = Erlang.from(obj)
i = @size - 1
if missing_arg
if block_given?
reverse_each { |element| return i if yield element; i -= 1 }
return nil
else
return enum_for(:rindex)
end
else
reverse_each { |element| return i if element == obj; i -= 1 }
return nil
end
end | [
"def",
"rindex",
"(",
"obj",
"=",
"(",
"missing_arg",
"=",
"true",
")",
")",
"obj",
"=",
"Erlang",
".",
"from",
"(",
"obj",
")",
"i",
"=",
"@size",
"-",
"1",
"if",
"missing_arg",
"if",
"block_given?",
"reverse_each",
"{",
"|",
"element",
"|",
"return",
"i",
"if",
"yield",
"element",
";",
"i",
"-=",
"1",
"}",
"return",
"nil",
"else",
"return",
"enum_for",
"(",
":rindex",
")",
"end",
"else",
"reverse_each",
"{",
"|",
"element",
"|",
"return",
"i",
"if",
"element",
"==",
"obj",
";",
"i",
"-=",
"1",
"}",
"return",
"nil",
"end",
"end"
] | Find the index of an element, starting from the end of the tuple.
Returns `nil` if no element is found.
@overload rindex(obj)
Return the index of the last element which is `#==` to `obj`.
@example
t = Erlang::Tuple[7, 8, 9, 7, 8, 9]
t.rindex(8) # => 4
@overload rindex
Return the index of the last element for which the block returns true.
@yield [element] Once for each element, last to first, until the block
returns true.
@example
t = Erlang::Tuple[7, 8, 9, 7, 8, 9]
t.rindex { |e| e.even? } # => 4
@return [Integer] | [
"Find",
"the",
"index",
"of",
"an",
"element",
"starting",
"from",
"the",
"end",
"of",
"the",
"tuple",
".",
"Returns",
"nil",
"if",
"no",
"element",
"is",
"found",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/tuple.rb#L1266-L1280 | train |
potatosalad/ruby-erlang-terms | lib/erlang/enumerable.rb | Erlang.Enumerable.partition | def partition
return enum_for(:partition) if not block_given?
a,b = super
return Erlang::Tuple[self.class.new(a), self.class.new(b)]
end | ruby | def partition
return enum_for(:partition) if not block_given?
a,b = super
return Erlang::Tuple[self.class.new(a), self.class.new(b)]
end | [
"def",
"partition",
"return",
"enum_for",
"(",
":partition",
")",
"if",
"not",
"block_given?",
"a",
",",
"b",
"=",
"super",
"return",
"Erlang",
"::",
"Tuple",
"[",
"self",
".",
"class",
".",
"new",
"(",
"a",
")",
",",
"self",
".",
"class",
".",
"new",
"(",
"b",
")",
"]",
"end"
] | Return 2 collections, the first containing all the elements for which the block
evaluates to true, the second containing the rest. | [
"Return",
"2",
"collections",
"the",
"first",
"containing",
"all",
"the",
"elements",
"for",
"which",
"the",
"block",
"evaluates",
"to",
"true",
"the",
"second",
"containing",
"the",
"rest",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/enumerable.rb#L89-L93 | train |
potatosalad/ruby-erlang-terms | lib/erlang/enumerable.rb | Erlang.Enumerable.inspect | def inspect
result = "#{self.class}["
each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect }
return result << "]"
end | ruby | def inspect
result = "#{self.class}["
each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect }
return result << "]"
end | [
"def",
"inspect",
"result",
"=",
"\"#{self.class}[\"",
"each_with_index",
"{",
"|",
"obj",
",",
"i",
"|",
"result",
"<<",
"', '",
"if",
"i",
">",
"0",
";",
"result",
"<<",
"obj",
".",
"inspect",
"}",
"return",
"result",
"<<",
"\"]\"",
"end"
] | Convert this collection to a programmer-readable `String` representation. | [
"Convert",
"this",
"collection",
"to",
"a",
"programmer",
"-",
"readable",
"String",
"representation",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/enumerable.rb#L131-L135 | train |
potatosalad/ruby-erlang-terms | lib/erlang/list.rb | Erlang.List.each | def each
raise Erlang::ImproperListError if improper?
return to_enum unless block_given?
list = self
until list.empty?
yield(list.head)
list = list.tail
end
return self
end | ruby | def each
raise Erlang::ImproperListError if improper?
return to_enum unless block_given?
list = self
until list.empty?
yield(list.head)
list = list.tail
end
return self
end | [
"def",
"each",
"raise",
"Erlang",
"::",
"ImproperListError",
"if",
"improper?",
"return",
"to_enum",
"unless",
"block_given?",
"list",
"=",
"self",
"until",
"list",
".",
"empty?",
"yield",
"(",
"list",
".",
"head",
")",
"list",
"=",
"list",
".",
"tail",
"end",
"return",
"self",
"end"
] | Call the given block once for each item in the list, passing each
item from first to last successively to the block. If no block is given,
returns an `Enumerator`.
@return [self]
@yield [item] | [
"Call",
"the",
"given",
"block",
"once",
"for",
"each",
"item",
"in",
"the",
"list",
"passing",
"each",
"item",
"from",
"first",
"to",
"last",
"successively",
"to",
"the",
"block",
".",
"If",
"no",
"block",
"is",
"given",
"returns",
"an",
"Enumerator",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L151-L160 | train |
potatosalad/ruby-erlang-terms | lib/erlang/list.rb | Erlang.List.flat_map | def flat_map(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:flat_map) unless block_given?
return self if empty?
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
head_list = Erlang::List.from_enum(yield(list.head))
if head_list.empty?
list = list.tail
elsif list.tail.empty?
tail.instance_variable_set(:@head, head_list.head)
tail.instance_variable_set(:@tail, head_list.tail)
tail.immutable!
list = list.tail
else
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@head, head_list.head)
tail.instance_variable_set(:@tail, head_list.tail + new_node)
tail.immutable!
list = list.tail
tail = new_node
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
if out === tail and not out.tail.kind_of?(Erlang::List)
return out.tail
else
return out
end
end | ruby | def flat_map(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:flat_map) unless block_given?
return self if empty?
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
head_list = Erlang::List.from_enum(yield(list.head))
if head_list.empty?
list = list.tail
elsif list.tail.empty?
tail.instance_variable_set(:@head, head_list.head)
tail.instance_variable_set(:@tail, head_list.tail)
tail.immutable!
list = list.tail
else
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@head, head_list.head)
tail.instance_variable_set(:@tail, head_list.tail + new_node)
tail.immutable!
list = list.tail
tail = new_node
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
if out === tail and not out.tail.kind_of?(Erlang::List)
return out.tail
else
return out
end
end | [
"def",
"flat_map",
"(",
"&",
"block",
")",
"raise",
"Erlang",
"::",
"ImproperListError",
"if",
"improper?",
"return",
"enum_for",
"(",
":flat_map",
")",
"unless",
"block_given?",
"return",
"self",
"if",
"empty?",
"out",
"=",
"tail",
"=",
"Erlang",
"::",
"Cons",
".",
"allocate",
"list",
"=",
"self",
"until",
"list",
".",
"empty?",
"head_list",
"=",
"Erlang",
"::",
"List",
".",
"from_enum",
"(",
"yield",
"(",
"list",
".",
"head",
")",
")",
"if",
"head_list",
".",
"empty?",
"list",
"=",
"list",
".",
"tail",
"elsif",
"list",
".",
"tail",
".",
"empty?",
"tail",
".",
"instance_variable_set",
"(",
":@head",
",",
"head_list",
".",
"head",
")",
"tail",
".",
"instance_variable_set",
"(",
":@tail",
",",
"head_list",
".",
"tail",
")",
"tail",
".",
"immutable!",
"list",
"=",
"list",
".",
"tail",
"else",
"new_node",
"=",
"Erlang",
"::",
"Cons",
".",
"allocate",
"new_node",
".",
"instance_variable_set",
"(",
":@improper",
",",
"false",
")",
"tail",
".",
"instance_variable_set",
"(",
":@head",
",",
"head_list",
".",
"head",
")",
"tail",
".",
"instance_variable_set",
"(",
":@tail",
",",
"head_list",
".",
"tail",
"+",
"new_node",
")",
"tail",
".",
"immutable!",
"list",
"=",
"list",
".",
"tail",
"tail",
"=",
"new_node",
"end",
"end",
"if",
"not",
"tail",
".",
"immutable?",
"tail",
".",
"instance_variable_set",
"(",
":@tail",
",",
"Erlang",
"::",
"Nil",
")",
"tail",
".",
"immutable!",
"end",
"if",
"out",
"===",
"tail",
"and",
"not",
"out",
".",
"tail",
".",
"kind_of?",
"(",
"Erlang",
"::",
"List",
")",
"return",
"out",
".",
"tail",
"else",
"return",
"out",
"end",
"end"
] | Return a `List` which is realized by transforming each item into a `List`,
and flattening the resulting lists.
@example
Erlang::List[1, 2, 3].flat_map { |x| Erlang::List[x, 100] }
# => Erlang::List[1, 100, 2, 100, 3, 100]
@return [List] | [
"Return",
"a",
"List",
"which",
"is",
"realized",
"by",
"transforming",
"each",
"item",
"into",
"a",
"List",
"and",
"flattening",
"the",
"resulting",
"lists",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L203-L237 | train |
potatosalad/ruby-erlang-terms | lib/erlang/list.rb | Erlang.List.select | def select(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:select) unless block_given?
out = tail = Erlang::Cons.allocate
list = self
while !list.empty?
if yield(list.head)
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
list = list.tail
else
list = list.tail
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | ruby | def select(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:select) unless block_given?
out = tail = Erlang::Cons.allocate
list = self
while !list.empty?
if yield(list.head)
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
list = list.tail
else
list = list.tail
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | [
"def",
"select",
"(",
"&",
"block",
")",
"raise",
"Erlang",
"::",
"ImproperListError",
"if",
"improper?",
"return",
"enum_for",
"(",
":select",
")",
"unless",
"block_given?",
"out",
"=",
"tail",
"=",
"Erlang",
"::",
"Cons",
".",
"allocate",
"list",
"=",
"self",
"while",
"!",
"list",
".",
"empty?",
"if",
"yield",
"(",
"list",
".",
"head",
")",
"new_node",
"=",
"Erlang",
"::",
"Cons",
".",
"allocate",
"new_node",
".",
"instance_variable_set",
"(",
":@head",
",",
"list",
".",
"head",
")",
"new_node",
".",
"instance_variable_set",
"(",
":@improper",
",",
"false",
")",
"tail",
".",
"instance_variable_set",
"(",
":@tail",
",",
"new_node",
")",
"tail",
".",
"instance_variable_set",
"(",
":@improper",
",",
"false",
")",
"tail",
".",
"immutable!",
"tail",
"=",
"new_node",
"list",
"=",
"list",
".",
"tail",
"else",
"list",
"=",
"list",
".",
"tail",
"end",
"end",
"if",
"not",
"tail",
".",
"immutable?",
"tail",
".",
"instance_variable_set",
"(",
":@tail",
",",
"Erlang",
"::",
"Nil",
")",
"tail",
".",
"immutable!",
"end",
"return",
"out",
".",
"tail",
"end"
] | Return a `List` which contains all the items for which the given block
returns true.
@example
Erlang::List["Bird", "Cow", "Elephant"].select { |e| e.size >= 4 }
# => Erlang::List["Bird", "Elephant"]
@return [List]
@yield [item] Once for each item. | [
"Return",
"a",
"List",
"which",
"contains",
"all",
"the",
"items",
"for",
"which",
"the",
"given",
"block",
"returns",
"true",
"."
] | a3eaa3d976610466a5f5da177109a1248dac020d | https://github.com/potatosalad/ruby-erlang-terms/blob/a3eaa3d976610466a5f5da177109a1248dac020d/lib/erlang/list.rb#L248-L272 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.