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 |
---|---|---|---|---|---|---|---|---|---|---|---|
chrislee35/dnsbl-client | lib/dnsbl/client.rb | DNSBL.Client.lookup | def lookup(item)
# if item is an array, use it, otherwise make it one
items = item
if item.is_a? String
items = [item]
end
# place the results in the results array
results = []
# for each ip or hostname
items.each do |item|
# sent is used to determine when we have all the answers
sent = 0
# record the start time
@starttime = Time.now.to_f
# determine the type of query
itemtype = (item =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) ? 'ip' : 'domain'
# for each dnsbl that supports our type, create the DNS query packet and send it
# rotate across our configured name servers and increment sent
@dnsbls.each do |name,config|
next if config['disabled']
next unless config['type'] == itemtype
begin
msg = _encode_query(item,itemtype,config['domain'],config['apikey'])
@sockets[@socket_index].send(msg,0)
@socket_index += 1
@socket_index %= @sockets.length
sent += 1
rescue Exception => e
puts e
puts e.backtrace.join("\n")
end
end
# while we still expect answers
while sent > 0
# wait on the socket for maximally 1.5 seconds
r,_,_ = IO.select(@sockets,nil,nil,1.5)
# if we time out, break out of the loop
break unless r
# for each reply, decode it and receive results, decrement the pending answers
r.each do |s|
begin
response = _decode_response(s.recv(4096))
results += response
rescue Exception => e
puts e
puts e.backtrace.join("\n")
end
sent -= 1
end
end
end
results
end | ruby | def lookup(item)
# if item is an array, use it, otherwise make it one
items = item
if item.is_a? String
items = [item]
end
# place the results in the results array
results = []
# for each ip or hostname
items.each do |item|
# sent is used to determine when we have all the answers
sent = 0
# record the start time
@starttime = Time.now.to_f
# determine the type of query
itemtype = (item =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) ? 'ip' : 'domain'
# for each dnsbl that supports our type, create the DNS query packet and send it
# rotate across our configured name servers and increment sent
@dnsbls.each do |name,config|
next if config['disabled']
next unless config['type'] == itemtype
begin
msg = _encode_query(item,itemtype,config['domain'],config['apikey'])
@sockets[@socket_index].send(msg,0)
@socket_index += 1
@socket_index %= @sockets.length
sent += 1
rescue Exception => e
puts e
puts e.backtrace.join("\n")
end
end
# while we still expect answers
while sent > 0
# wait on the socket for maximally 1.5 seconds
r,_,_ = IO.select(@sockets,nil,nil,1.5)
# if we time out, break out of the loop
break unless r
# for each reply, decode it and receive results, decrement the pending answers
r.each do |s|
begin
response = _decode_response(s.recv(4096))
results += response
rescue Exception => e
puts e
puts e.backtrace.join("\n")
end
sent -= 1
end
end
end
results
end | [
"def",
"lookup",
"(",
"item",
")",
"# if item is an array, use it, otherwise make it one",
"items",
"=",
"item",
"if",
"item",
".",
"is_a?",
"String",
"items",
"=",
"[",
"item",
"]",
"end",
"# place the results in the results array",
"results",
"=",
"[",
"]",
"# for each ip or hostname",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"# sent is used to determine when we have all the answers",
"sent",
"=",
"0",
"# record the start time",
"@starttime",
"=",
"Time",
".",
"now",
".",
"to_f",
"# determine the type of query",
"itemtype",
"=",
"(",
"item",
"=~",
"/",
"\\d",
"\\.",
"\\d",
"\\.",
"\\d",
"\\.",
"\\d",
"/",
")",
"?",
"'ip'",
":",
"'domain'",
"# for each dnsbl that supports our type, create the DNS query packet and send it",
"# rotate across our configured name servers and increment sent",
"@dnsbls",
".",
"each",
"do",
"|",
"name",
",",
"config",
"|",
"next",
"if",
"config",
"[",
"'disabled'",
"]",
"next",
"unless",
"config",
"[",
"'type'",
"]",
"==",
"itemtype",
"begin",
"msg",
"=",
"_encode_query",
"(",
"item",
",",
"itemtype",
",",
"config",
"[",
"'domain'",
"]",
",",
"config",
"[",
"'apikey'",
"]",
")",
"@sockets",
"[",
"@socket_index",
"]",
".",
"send",
"(",
"msg",
",",
"0",
")",
"@socket_index",
"+=",
"1",
"@socket_index",
"%=",
"@sockets",
".",
"length",
"sent",
"+=",
"1",
"rescue",
"Exception",
"=>",
"e",
"puts",
"e",
"puts",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"end",
"# while we still expect answers",
"while",
"sent",
">",
"0",
"# wait on the socket for maximally 1.5 seconds",
"r",
",",
"_",
",",
"_",
"=",
"IO",
".",
"select",
"(",
"@sockets",
",",
"nil",
",",
"nil",
",",
"1.5",
")",
"# if we time out, break out of the loop",
"break",
"unless",
"r",
"# for each reply, decode it and receive results, decrement the pending answers",
"r",
".",
"each",
"do",
"|",
"s",
"|",
"begin",
"response",
"=",
"_decode_response",
"(",
"s",
".",
"recv",
"(",
"4096",
")",
")",
"results",
"+=",
"response",
"rescue",
"Exception",
"=>",
"e",
"puts",
"e",
"puts",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"sent",
"-=",
"1",
"end",
"end",
"end",
"results",
"end"
] | lookup performs the sending of DNS queries for the given items
returns an array of DNSBLResult | [
"lookup",
"performs",
"the",
"sending",
"of",
"DNS",
"queries",
"for",
"the",
"given",
"items",
"returns",
"an",
"array",
"of",
"DNSBLResult"
] | d88bb5eae3dfd03c418f67ae5767234a862a92b8 | https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L129-L181 | train |
chrislee35/dnsbl-client | lib/dnsbl/client.rb | DNSBL.Client._decode_response | def _decode_response(buf)
reply = Resolv::DNS::Message.decode(buf)
results = []
reply.each_answer do |name,ttl,data|
if name.to_s =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/
ip = [$4,$3,$2,$1].join(".")
domain = $5
@dnsbls.each do |dnsblname, config|
next unless data.is_a? Resolv::DNS::Resource::IN::A
if domain == config['domain']
meaning = config[data.address.to_s] || data.address.to_s
results << DNSBLResult.new(dnsblname, ip, name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime)
break
end
end
else
@dnsbls.each do |dnsblname, config|
if name.to_s.end_with?(config['domain'])
meaning = nil
if config['decoder']
meaning = self.send(("__"+config['decoder']).to_sym, data.address.to_s)
elsif config[data.address.to_s]
meaning = config[data.address.to_s]
else
meaning = data.address.to_s
end
results << DNSBLResult.new(dnsblname, name.to_s.gsub("."+config['domain'],''), name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime)
break
end
end
end
end
results
end | ruby | def _decode_response(buf)
reply = Resolv::DNS::Message.decode(buf)
results = []
reply.each_answer do |name,ttl,data|
if name.to_s =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/
ip = [$4,$3,$2,$1].join(".")
domain = $5
@dnsbls.each do |dnsblname, config|
next unless data.is_a? Resolv::DNS::Resource::IN::A
if domain == config['domain']
meaning = config[data.address.to_s] || data.address.to_s
results << DNSBLResult.new(dnsblname, ip, name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime)
break
end
end
else
@dnsbls.each do |dnsblname, config|
if name.to_s.end_with?(config['domain'])
meaning = nil
if config['decoder']
meaning = self.send(("__"+config['decoder']).to_sym, data.address.to_s)
elsif config[data.address.to_s]
meaning = config[data.address.to_s]
else
meaning = data.address.to_s
end
results << DNSBLResult.new(dnsblname, name.to_s.gsub("."+config['domain'],''), name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime)
break
end
end
end
end
results
end | [
"def",
"_decode_response",
"(",
"buf",
")",
"reply",
"=",
"Resolv",
"::",
"DNS",
"::",
"Message",
".",
"decode",
"(",
"buf",
")",
"results",
"=",
"[",
"]",
"reply",
".",
"each_answer",
"do",
"|",
"name",
",",
"ttl",
",",
"data",
"|",
"if",
"name",
".",
"to_s",
"=~",
"/",
"\\d",
"\\.",
"\\d",
"\\.",
"\\d",
"\\.",
"\\d",
"\\.",
"/",
"ip",
"=",
"[",
"$4",
",",
"$3",
",",
"$2",
",",
"$1",
"]",
".",
"join",
"(",
"\".\"",
")",
"domain",
"=",
"$5",
"@dnsbls",
".",
"each",
"do",
"|",
"dnsblname",
",",
"config",
"|",
"next",
"unless",
"data",
".",
"is_a?",
"Resolv",
"::",
"DNS",
"::",
"Resource",
"::",
"IN",
"::",
"A",
"if",
"domain",
"==",
"config",
"[",
"'domain'",
"]",
"meaning",
"=",
"config",
"[",
"data",
".",
"address",
".",
"to_s",
"]",
"||",
"data",
".",
"address",
".",
"to_s",
"results",
"<<",
"DNSBLResult",
".",
"new",
"(",
"dnsblname",
",",
"ip",
",",
"name",
".",
"to_s",
",",
"data",
".",
"address",
".",
"to_s",
",",
"meaning",
",",
"Time",
".",
"now",
".",
"to_f",
"-",
"@starttime",
")",
"break",
"end",
"end",
"else",
"@dnsbls",
".",
"each",
"do",
"|",
"dnsblname",
",",
"config",
"|",
"if",
"name",
".",
"to_s",
".",
"end_with?",
"(",
"config",
"[",
"'domain'",
"]",
")",
"meaning",
"=",
"nil",
"if",
"config",
"[",
"'decoder'",
"]",
"meaning",
"=",
"self",
".",
"send",
"(",
"(",
"\"__\"",
"+",
"config",
"[",
"'decoder'",
"]",
")",
".",
"to_sym",
",",
"data",
".",
"address",
".",
"to_s",
")",
"elsif",
"config",
"[",
"data",
".",
"address",
".",
"to_s",
"]",
"meaning",
"=",
"config",
"[",
"data",
".",
"address",
".",
"to_s",
"]",
"else",
"meaning",
"=",
"data",
".",
"address",
".",
"to_s",
"end",
"results",
"<<",
"DNSBLResult",
".",
"new",
"(",
"dnsblname",
",",
"name",
".",
"to_s",
".",
"gsub",
"(",
"\".\"",
"+",
"config",
"[",
"'domain'",
"]",
",",
"''",
")",
",",
"name",
".",
"to_s",
",",
"data",
".",
"address",
".",
"to_s",
",",
"meaning",
",",
"Time",
".",
"now",
".",
"to_f",
"-",
"@starttime",
")",
"break",
"end",
"end",
"end",
"end",
"results",
"end"
] | takes a DNS response and converts it into a DNSBLResult | [
"takes",
"a",
"DNS",
"response",
"and",
"converts",
"it",
"into",
"a",
"DNSBLResult"
] | d88bb5eae3dfd03c418f67ae5767234a862a92b8 | https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L186-L219 | train |
chrislee35/dnsbl-client | lib/dnsbl/client.rb | DNSBL.Client.__phpot_decoder | def __phpot_decoder(ip)
octets = ip.split(/\./)
if octets.length != 4 or octets[0] != "127"
return "invalid response"
elsif octets[3] == "0"
search_engines = ["undocumented", "AltaVista", "Ask", "Baidu", "Excite", "Google", "Looksmart", "Lycos", "MSN", "Yahoo", "Cuil", "InfoSeek", "Miscellaneous"]
sindex = octets[2].to_i
if sindex >= search_engines.length
return "type=search engine,engine=unknown"
else
return "type=search engine,engine=#{search_engines[sindex]}"
end
else
days, threatscore, flags = octets[1,3]
flags = flags.to_i
types = []
if (flags & 0x1) == 0x1
types << "suspicious"
end
if (flags & 0x2) == 0x2
types << "harvester"
end
if (flags & 0x4) == 0x4
types << "comment spammer"
end
if (flags & 0xf8) > 0
types << "reserved"
end
type = types.join(",")
return "days=#{days},score=#{threatscore},type=#{type}"
end
end | ruby | def __phpot_decoder(ip)
octets = ip.split(/\./)
if octets.length != 4 or octets[0] != "127"
return "invalid response"
elsif octets[3] == "0"
search_engines = ["undocumented", "AltaVista", "Ask", "Baidu", "Excite", "Google", "Looksmart", "Lycos", "MSN", "Yahoo", "Cuil", "InfoSeek", "Miscellaneous"]
sindex = octets[2].to_i
if sindex >= search_engines.length
return "type=search engine,engine=unknown"
else
return "type=search engine,engine=#{search_engines[sindex]}"
end
else
days, threatscore, flags = octets[1,3]
flags = flags.to_i
types = []
if (flags & 0x1) == 0x1
types << "suspicious"
end
if (flags & 0x2) == 0x2
types << "harvester"
end
if (flags & 0x4) == 0x4
types << "comment spammer"
end
if (flags & 0xf8) > 0
types << "reserved"
end
type = types.join(",")
return "days=#{days},score=#{threatscore},type=#{type}"
end
end | [
"def",
"__phpot_decoder",
"(",
"ip",
")",
"octets",
"=",
"ip",
".",
"split",
"(",
"/",
"\\.",
"/",
")",
"if",
"octets",
".",
"length",
"!=",
"4",
"or",
"octets",
"[",
"0",
"]",
"!=",
"\"127\"",
"return",
"\"invalid response\"",
"elsif",
"octets",
"[",
"3",
"]",
"==",
"\"0\"",
"search_engines",
"=",
"[",
"\"undocumented\"",
",",
"\"AltaVista\"",
",",
"\"Ask\"",
",",
"\"Baidu\"",
",",
"\"Excite\"",
",",
"\"Google\"",
",",
"\"Looksmart\"",
",",
"\"Lycos\"",
",",
"\"MSN\"",
",",
"\"Yahoo\"",
",",
"\"Cuil\"",
",",
"\"InfoSeek\"",
",",
"\"Miscellaneous\"",
"]",
"sindex",
"=",
"octets",
"[",
"2",
"]",
".",
"to_i",
"if",
"sindex",
">=",
"search_engines",
".",
"length",
"return",
"\"type=search engine,engine=unknown\"",
"else",
"return",
"\"type=search engine,engine=#{search_engines[sindex]}\"",
"end",
"else",
"days",
",",
"threatscore",
",",
"flags",
"=",
"octets",
"[",
"1",
",",
"3",
"]",
"flags",
"=",
"flags",
".",
"to_i",
"types",
"=",
"[",
"]",
"if",
"(",
"flags",
"&",
"0x1",
")",
"==",
"0x1",
"types",
"<<",
"\"suspicious\"",
"end",
"if",
"(",
"flags",
"&",
"0x2",
")",
"==",
"0x2",
"types",
"<<",
"\"harvester\"",
"end",
"if",
"(",
"flags",
"&",
"0x4",
")",
"==",
"0x4",
"types",
"<<",
"\"comment spammer\"",
"end",
"if",
"(",
"flags",
"&",
"0xf8",
")",
">",
"0",
"types",
"<<",
"\"reserved\"",
"end",
"type",
"=",
"types",
".",
"join",
"(",
"\",\"",
")",
"return",
"\"days=#{days},score=#{threatscore},type=#{type}\"",
"end",
"end"
] | decodes the response from Project Honey Pot's service | [
"decodes",
"the",
"response",
"from",
"Project",
"Honey",
"Pot",
"s",
"service"
] | d88bb5eae3dfd03c418f67ae5767234a862a92b8 | https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L222-L253 | train |
jgoizueta/flt | lib/flt/support/flag_values.rb | Flt.Support.FlagValues | def FlagValues(*params)
if params.size==1 && params.first.kind_of?(FlagValues)
params.first
else
FlagValues.new(*params)
end
end | ruby | def FlagValues(*params)
if params.size==1 && params.first.kind_of?(FlagValues)
params.first
else
FlagValues.new(*params)
end
end | [
"def",
"FlagValues",
"(",
"*",
"params",
")",
"if",
"params",
".",
"size",
"==",
"1",
"&&",
"params",
".",
"first",
".",
"kind_of?",
"(",
"FlagValues",
")",
"params",
".",
"first",
"else",
"FlagValues",
".",
"new",
"(",
"params",
")",
"end",
"end"
] | Constructor for FlagValues | [
"Constructor",
"for",
"FlagValues"
] | 068869cfb81fe339658348490f4ea1294facfffa | https://github.com/jgoizueta/flt/blob/068869cfb81fe339658348490f4ea1294facfffa/lib/flt/support/flag_values.rb#L322-L328 | train |
jgoizueta/flt | lib/flt/support/flag_values.rb | Flt.Support.Flags | def Flags(*params)
if params.size==1 && params.first.kind_of?(Flags)
params.first
else
Flags.new(*params)
end
end | ruby | def Flags(*params)
if params.size==1 && params.first.kind_of?(Flags)
params.first
else
Flags.new(*params)
end
end | [
"def",
"Flags",
"(",
"*",
"params",
")",
"if",
"params",
".",
"size",
"==",
"1",
"&&",
"params",
".",
"first",
".",
"kind_of?",
"(",
"Flags",
")",
"params",
".",
"first",
"else",
"Flags",
".",
"new",
"(",
"params",
")",
"end",
"end"
] | Constructor for Flags | [
"Constructor",
"for",
"Flags"
] | 068869cfb81fe339658348490f4ea1294facfffa | https://github.com/jgoizueta/flt/blob/068869cfb81fe339658348490f4ea1294facfffa/lib/flt/support/flag_values.rb#L331-L337 | train |
jgoizueta/flt | lib/flt/tolerance.rb | Flt.Tolerance.integer | def integer(x)
# return integer?(x) ? x.round : nil
r = x.round
((x-r).abs <= relative_to(x)) ? r : nil
end | ruby | def integer(x)
# return integer?(x) ? x.round : nil
r = x.round
((x-r).abs <= relative_to(x)) ? r : nil
end | [
"def",
"integer",
"(",
"x",
")",
"# return integer?(x) ? x.round : nil",
"r",
"=",
"x",
".",
"round",
"(",
"(",
"x",
"-",
"r",
")",
".",
"abs",
"<=",
"relative_to",
"(",
"x",
")",
")",
"?",
"r",
":",
"nil",
"end"
] | If the argument is close to an integer it rounds it | [
"If",
"the",
"argument",
"is",
"close",
"to",
"an",
"integer",
"it",
"rounds",
"it"
] | 068869cfb81fe339658348490f4ea1294facfffa | https://github.com/jgoizueta/flt/blob/068869cfb81fe339658348490f4ea1294facfffa/lib/flt/tolerance.rb#L135-L139 | train |
muffinista/gopher2000 | lib/gopher2000/dsl.rb | Gopher.DSL.mount | def mount(path, opts = {})
route, folder = path.first
#
# if path has more than the one option (:route => :folder),
# then incorporate the rest of the hash into our opts
#
if path.size > 1
other_opts = path.dup
other_opts.delete(route)
opts = opts.merge(other_opts)
end
application.mount(route, opts.merge({:path => folder}))
end | ruby | def mount(path, opts = {})
route, folder = path.first
#
# if path has more than the one option (:route => :folder),
# then incorporate the rest of the hash into our opts
#
if path.size > 1
other_opts = path.dup
other_opts.delete(route)
opts = opts.merge(other_opts)
end
application.mount(route, opts.merge({:path => folder}))
end | [
"def",
"mount",
"(",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"route",
",",
"folder",
"=",
"path",
".",
"first",
"#",
"# if path has more than the one option (:route => :folder),",
"# then incorporate the rest of the hash into our opts",
"#",
"if",
"path",
".",
"size",
">",
"1",
"other_opts",
"=",
"path",
".",
"dup",
"other_opts",
".",
"delete",
"(",
"route",
")",
"opts",
"=",
"opts",
".",
"merge",
"(",
"other_opts",
")",
"end",
"application",
".",
"mount",
"(",
"route",
",",
"opts",
".",
"merge",
"(",
"{",
":path",
"=>",
"folder",
"}",
")",
")",
"end"
] | mount a folder for browsing | [
"mount",
"a",
"folder",
"for",
"browsing"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/dsl.rb#L43-L57 | train |
muffinista/gopher2000 | lib/gopher2000/response.rb | Gopher.Response.size | def size
case self.body
when String then self.body.length
when StringIO then self.body.length
when File then self.body.size
else 0
end
end | ruby | def size
case self.body
when String then self.body.length
when StringIO then self.body.length
when File then self.body.size
else 0
end
end | [
"def",
"size",
"case",
"self",
".",
"body",
"when",
"String",
"then",
"self",
".",
"body",
".",
"length",
"when",
"StringIO",
"then",
"self",
".",
"body",
".",
"length",
"when",
"File",
"then",
"self",
".",
"body",
".",
"size",
"else",
"0",
"end",
"end"
] | get the size, in bytes, of the response. used for logging
@return [Integer] size | [
"get",
"the",
"size",
"in",
"bytes",
"of",
"the",
"response",
".",
"used",
"for",
"logging"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/response.rb#L16-L23 | train |
muffinista/gopher2000 | lib/gopher2000/server.rb | Gopher.Server.run! | def run!
EventMachine::run do
Signal.trap("INT") {
puts "It's a trap!"
EventMachine.stop
}
Signal.trap("TERM") {
puts "It's a trap!"
EventMachine.stop
}
EventMachine.kqueue = true if EventMachine.kqueue?
EventMachine.epoll = true if EventMachine.epoll?
STDERR.puts "start server at #{host} #{port}"
if @app.non_blocking?
STDERR.puts "Not blocking on requests"
end
EventMachine::start_server(host, port, Gopher::Dispatcher) do |conn|
#
# check if we should reload any scripts before moving along
#
@app.reload_stale
#
# roughly matching sinatra's style of duping the app to respond
# to requests, @see http://www.sinatrarb.com/intro#Request/Instance%20Scope
#
# this essentially means we have 'one instance per request'
#
conn.app = @app.dup
end
end
end | ruby | def run!
EventMachine::run do
Signal.trap("INT") {
puts "It's a trap!"
EventMachine.stop
}
Signal.trap("TERM") {
puts "It's a trap!"
EventMachine.stop
}
EventMachine.kqueue = true if EventMachine.kqueue?
EventMachine.epoll = true if EventMachine.epoll?
STDERR.puts "start server at #{host} #{port}"
if @app.non_blocking?
STDERR.puts "Not blocking on requests"
end
EventMachine::start_server(host, port, Gopher::Dispatcher) do |conn|
#
# check if we should reload any scripts before moving along
#
@app.reload_stale
#
# roughly matching sinatra's style of duping the app to respond
# to requests, @see http://www.sinatrarb.com/intro#Request/Instance%20Scope
#
# this essentially means we have 'one instance per request'
#
conn.app = @app.dup
end
end
end | [
"def",
"run!",
"EventMachine",
"::",
"run",
"do",
"Signal",
".",
"trap",
"(",
"\"INT\"",
")",
"{",
"puts",
"\"It's a trap!\"",
"EventMachine",
".",
"stop",
"}",
"Signal",
".",
"trap",
"(",
"\"TERM\"",
")",
"{",
"puts",
"\"It's a trap!\"",
"EventMachine",
".",
"stop",
"}",
"EventMachine",
".",
"kqueue",
"=",
"true",
"if",
"EventMachine",
".",
"kqueue?",
"EventMachine",
".",
"epoll",
"=",
"true",
"if",
"EventMachine",
".",
"epoll?",
"STDERR",
".",
"puts",
"\"start server at #{host} #{port}\"",
"if",
"@app",
".",
"non_blocking?",
"STDERR",
".",
"puts",
"\"Not blocking on requests\"",
"end",
"EventMachine",
"::",
"start_server",
"(",
"host",
",",
"port",
",",
"Gopher",
"::",
"Dispatcher",
")",
"do",
"|",
"conn",
"|",
"#",
"# check if we should reload any scripts before moving along",
"#",
"@app",
".",
"reload_stale",
"#",
"# roughly matching sinatra's style of duping the app to respond",
"# to requests, @see http://www.sinatrarb.com/intro#Request/Instance%20Scope",
"#",
"# this essentially means we have 'one instance per request'",
"#",
"conn",
".",
"app",
"=",
"@app",
".",
"dup",
"end",
"end",
"end"
] | main app loop. called via at_exit block defined in DSL | [
"main",
"app",
"loop",
".",
"called",
"via",
"at_exit",
"block",
"defined",
"in",
"DSL"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/server.rb#L34-L70 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.should_reload? | def should_reload?
! last_reload.nil? && self.scripts.any? do |f|
File.mtime(f) > last_reload
end
end | ruby | def should_reload?
! last_reload.nil? && self.scripts.any? do |f|
File.mtime(f) > last_reload
end
end | [
"def",
"should_reload?",
"!",
"last_reload",
".",
"nil?",
"&&",
"self",
".",
"scripts",
".",
"any?",
"do",
"|",
"f",
"|",
"File",
".",
"mtime",
"(",
"f",
")",
">",
"last_reload",
"end",
"end"
] | check if our script has been updated since the last reload | [
"check",
"if",
"our",
"script",
"has",
"been",
"updated",
"since",
"the",
"last",
"reload"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L68-L72 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.reload_stale | def reload_stale
reload_check = should_reload?
self.last_reload = Time.now
return if ! reload_check
reset!
self.scripts.each do |f|
debug_log "reload #{f}"
load f
end
end | ruby | def reload_stale
reload_check = should_reload?
self.last_reload = Time.now
return if ! reload_check
reset!
self.scripts.each do |f|
debug_log "reload #{f}"
load f
end
end | [
"def",
"reload_stale",
"reload_check",
"=",
"should_reload?",
"self",
".",
"last_reload",
"=",
"Time",
".",
"now",
"return",
"if",
"!",
"reload_check",
"reset!",
"self",
".",
"scripts",
".",
"each",
"do",
"|",
"f",
"|",
"debug_log",
"\"reload #{f}\"",
"load",
"f",
"end",
"end"
] | reload scripts if needed | [
"reload",
"scripts",
"if",
"needed"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L77-L88 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.mount | def mount(path, opts = {}, klass = Gopher::Handlers::DirectoryHandler)
debug_log "MOUNT #{path} #{opts.inspect}"
opts[:mount_point] = path
handler = klass.new(opts)
handler.application = self
#
# add a route for the mounted class
#
route(globify(path)) do
# when we call, pass the params and request object for this
# particular request
handler.call(params, request)
end
end | ruby | def mount(path, opts = {}, klass = Gopher::Handlers::DirectoryHandler)
debug_log "MOUNT #{path} #{opts.inspect}"
opts[:mount_point] = path
handler = klass.new(opts)
handler.application = self
#
# add a route for the mounted class
#
route(globify(path)) do
# when we call, pass the params and request object for this
# particular request
handler.call(params, request)
end
end | [
"def",
"mount",
"(",
"path",
",",
"opts",
"=",
"{",
"}",
",",
"klass",
"=",
"Gopher",
"::",
"Handlers",
"::",
"DirectoryHandler",
")",
"debug_log",
"\"MOUNT #{path} #{opts.inspect}\"",
"opts",
"[",
":mount_point",
"]",
"=",
"path",
"handler",
"=",
"klass",
".",
"new",
"(",
"opts",
")",
"handler",
".",
"application",
"=",
"self",
"#",
"# add a route for the mounted class",
"#",
"route",
"(",
"globify",
"(",
"path",
")",
")",
"do",
"# when we call, pass the params and request object for this",
"# particular request",
"handler",
".",
"call",
"(",
"params",
",",
"request",
")",
"end",
"end"
] | mount a directory for browsing via gopher
@param [Hash] path A hash specifying the path your route will answer to, and the filesystem path to use '/route' => '/home/path/etc'
@param [Hash] opts a hash of options for the mount. Primarily this is a filter, which will restrict the list files outputted. example: :filter => '*.jpg'
@param [Class] klass The class that should be used to handle this mount. You could write and use a custom handler if desired
@example mount the directory '/home/user/foo' at the gopher path '/files', and only show JPG files:
mount '/files' => '/home/user/foo', :filter => '*.jpg' | [
"mount",
"a",
"directory",
"for",
"browsing",
"via",
"gopher"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L101-L116 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.lookup | def lookup(selector)
unless routes.nil?
routes.each do |pattern, keys, block|
if match = pattern.match(selector)
match = match.to_a
url = match.shift
params = to_params_hash(keys, match)
#
# @todo think about this
#
@params = params
return params, block
end
end
end
unless @default_route.nil?
return {}, @default_route
end
raise Gopher::NotFoundError
end | ruby | def lookup(selector)
unless routes.nil?
routes.each do |pattern, keys, block|
if match = pattern.match(selector)
match = match.to_a
url = match.shift
params = to_params_hash(keys, match)
#
# @todo think about this
#
@params = params
return params, block
end
end
end
unless @default_route.nil?
return {}, @default_route
end
raise Gopher::NotFoundError
end | [
"def",
"lookup",
"(",
"selector",
")",
"unless",
"routes",
".",
"nil?",
"routes",
".",
"each",
"do",
"|",
"pattern",
",",
"keys",
",",
"block",
"|",
"if",
"match",
"=",
"pattern",
".",
"match",
"(",
"selector",
")",
"match",
"=",
"match",
".",
"to_a",
"url",
"=",
"match",
".",
"shift",
"params",
"=",
"to_params_hash",
"(",
"keys",
",",
"match",
")",
"#",
"# @todo think about this",
"#",
"@params",
"=",
"params",
"return",
"params",
",",
"block",
"end",
"end",
"end",
"unless",
"@default_route",
".",
"nil?",
"return",
"{",
"}",
",",
"@default_route",
"end",
"raise",
"Gopher",
"::",
"NotFoundError",
"end"
] | lookup an incoming path
@param [String] selector the selector path of the incoming request | [
"lookup",
"an",
"incoming",
"path"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L163-L188 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.dispatch | def dispatch(req)
debug_log(req)
response = Response.new
@request = req
if ! @request.valid?
response.body = handle_invalid_request
response.code = :error
else
begin
debug_log("do lookup for #{@request.selector}")
@params, block = lookup(@request.selector)
#
# call the block that handles this lookup
#
response.body = block.bind(self).call
response.code = :success
rescue Gopher::NotFoundError => e
debug_log("#{@request.selector} -- not found")
response.body = handle_not_found
response.code = :missing
rescue Exception => e
debug_log("#{@request.selector} -- error")
debug_log(e.inspect)
debug_log(e.backtrace)
response.body = handle_error(e)
response.code = :error
end
end
access_log(req, response)
response
end | ruby | def dispatch(req)
debug_log(req)
response = Response.new
@request = req
if ! @request.valid?
response.body = handle_invalid_request
response.code = :error
else
begin
debug_log("do lookup for #{@request.selector}")
@params, block = lookup(@request.selector)
#
# call the block that handles this lookup
#
response.body = block.bind(self).call
response.code = :success
rescue Gopher::NotFoundError => e
debug_log("#{@request.selector} -- not found")
response.body = handle_not_found
response.code = :missing
rescue Exception => e
debug_log("#{@request.selector} -- error")
debug_log(e.inspect)
debug_log(e.backtrace)
response.body = handle_error(e)
response.code = :error
end
end
access_log(req, response)
response
end | [
"def",
"dispatch",
"(",
"req",
")",
"debug_log",
"(",
"req",
")",
"response",
"=",
"Response",
".",
"new",
"@request",
"=",
"req",
"if",
"!",
"@request",
".",
"valid?",
"response",
".",
"body",
"=",
"handle_invalid_request",
"response",
".",
"code",
"=",
":error",
"else",
"begin",
"debug_log",
"(",
"\"do lookup for #{@request.selector}\"",
")",
"@params",
",",
"block",
"=",
"lookup",
"(",
"@request",
".",
"selector",
")",
"#",
"# call the block that handles this lookup",
"#",
"response",
".",
"body",
"=",
"block",
".",
"bind",
"(",
"self",
")",
".",
"call",
"response",
".",
"code",
"=",
":success",
"rescue",
"Gopher",
"::",
"NotFoundError",
"=>",
"e",
"debug_log",
"(",
"\"#{@request.selector} -- not found\"",
")",
"response",
".",
"body",
"=",
"handle_not_found",
"response",
".",
"code",
"=",
":missing",
"rescue",
"Exception",
"=>",
"e",
"debug_log",
"(",
"\"#{@request.selector} -- error\"",
")",
"debug_log",
"(",
"e",
".",
"inspect",
")",
"debug_log",
"(",
"e",
".",
"backtrace",
")",
"response",
".",
"body",
"=",
"handle_error",
"(",
"e",
")",
"response",
".",
"code",
"=",
":error",
"end",
"end",
"access_log",
"(",
"req",
",",
"response",
")",
"response",
"end"
] | find and run the first route which matches the incoming request
@param [Request] req Gopher::Request object | [
"find",
"and",
"run",
"the",
"first",
"route",
"which",
"matches",
"the",
"incoming",
"request"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L195-L230 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.find_template | def find_template(t)
x = menus[t]
if x
return x, Gopher::Rendering::Menu
end
x = text_templates[t]
if x
return x, Gopher::Rendering::Text
end
end | ruby | def find_template(t)
x = menus[t]
if x
return x, Gopher::Rendering::Menu
end
x = text_templates[t]
if x
return x, Gopher::Rendering::Text
end
end | [
"def",
"find_template",
"(",
"t",
")",
"x",
"=",
"menus",
"[",
"t",
"]",
"if",
"x",
"return",
"x",
",",
"Gopher",
"::",
"Rendering",
"::",
"Menu",
"end",
"x",
"=",
"text_templates",
"[",
"t",
"]",
"if",
"x",
"return",
"x",
",",
"Gopher",
"::",
"Rendering",
"::",
"Text",
"end",
"end"
] | find a template
@param [String/Symbol] t name of the template
@return template block and the class context it should use | [
"find",
"a",
"template"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L301-L310 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.render | def render(template, *arguments)
#
# find the right renderer we need
#
block, handler = find_template(template)
raise TemplateNotFound if block.nil?
ctx = handler.new(self)
ctx.params = @params
ctx.request = @request
ctx.instance_exec(*arguments, &block)
end | ruby | def render(template, *arguments)
#
# find the right renderer we need
#
block, handler = find_template(template)
raise TemplateNotFound if block.nil?
ctx = handler.new(self)
ctx.params = @params
ctx.request = @request
ctx.instance_exec(*arguments, &block)
end | [
"def",
"render",
"(",
"template",
",",
"*",
"arguments",
")",
"#",
"# find the right renderer we need",
"#",
"block",
",",
"handler",
"=",
"find_template",
"(",
"template",
")",
"raise",
"TemplateNotFound",
"if",
"block",
".",
"nil?",
"ctx",
"=",
"handler",
".",
"new",
"(",
"self",
")",
"ctx",
".",
"params",
"=",
"@params",
"ctx",
".",
"request",
"=",
"@request",
"ctx",
".",
"instance_exec",
"(",
"arguments",
",",
"block",
")",
"end"
] | Find the desired template and call it within the proper context
@param [String/Symbol] template name of the template to render
@param [Array] arguments optional arguments to be passed to template
@return result of rendering | [
"Find",
"the",
"desired",
"template",
"and",
"call",
"it",
"within",
"the",
"proper",
"context"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L318-L331 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.compile! | def compile!(path, &block)
method_name = path
route_method = Application.generate_method(method_name, &block)
pattern, keys = compile path
[ pattern, keys, route_method ]
end | ruby | def compile!(path, &block)
method_name = path
route_method = Application.generate_method(method_name, &block)
pattern, keys = compile path
[ pattern, keys, route_method ]
end | [
"def",
"compile!",
"(",
"path",
",",
"&",
"block",
")",
"method_name",
"=",
"path",
"route_method",
"=",
"Application",
".",
"generate_method",
"(",
"method_name",
",",
"block",
")",
"pattern",
",",
"keys",
"=",
"compile",
"path",
"[",
"pattern",
",",
"keys",
",",
"route_method",
"]",
"end"
] | compile a route | [
"compile",
"a",
"route"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L402-L408 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.init_access_log | def init_access_log
return if access_log_dest.nil?
log = ::Logging.logger['access_log']
pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN)
log.add_appenders(
::Logging.appenders.rolling_file(access_log_dest,
:level => :debug,
:age => 'daily',
:layout => pattern)
)
log
end | ruby | def init_access_log
return if access_log_dest.nil?
log = ::Logging.logger['access_log']
pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN)
log.add_appenders(
::Logging.appenders.rolling_file(access_log_dest,
:level => :debug,
:age => 'daily',
:layout => pattern)
)
log
end | [
"def",
"init_access_log",
"return",
"if",
"access_log_dest",
".",
"nil?",
"log",
"=",
"::",
"Logging",
".",
"logger",
"[",
"'access_log'",
"]",
"pattern",
"=",
"::",
"Logging",
".",
"layouts",
".",
"pattern",
"(",
":pattern",
"=>",
"ACCESS_LOG_PATTERN",
")",
"log",
".",
"add_appenders",
"(",
"::",
"Logging",
".",
"appenders",
".",
"rolling_file",
"(",
"access_log_dest",
",",
":level",
"=>",
":debug",
",",
":age",
"=>",
"'daily'",
",",
":layout",
"=>",
"pattern",
")",
")",
"log",
"end"
] | initialize a Logger for tracking hits to the server | [
"initialize",
"a",
"Logger",
"for",
"tracking",
"hits",
"to",
"the",
"server"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L514-L528 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.access_log | def access_log(request, response)
return if access_log_dest.nil?
@@access_logger ||= init_access_log
code = response.respond_to?(:code) ? response.code.to_s : "success"
size = response.respond_to?(:size) ? response.size : response.length
output = [request.ip_address, request.selector, request.input, code.to_s, size].join("\t")
@@access_logger.debug output
end | ruby | def access_log(request, response)
return if access_log_dest.nil?
@@access_logger ||= init_access_log
code = response.respond_to?(:code) ? response.code.to_s : "success"
size = response.respond_to?(:size) ? response.size : response.length
output = [request.ip_address, request.selector, request.input, code.to_s, size].join("\t")
@@access_logger.debug output
end | [
"def",
"access_log",
"(",
"request",
",",
"response",
")",
"return",
"if",
"access_log_dest",
".",
"nil?",
"@@access_logger",
"||=",
"init_access_log",
"code",
"=",
"response",
".",
"respond_to?",
"(",
":code",
")",
"?",
"response",
".",
"code",
".",
"to_s",
":",
"\"success\"",
"size",
"=",
"response",
".",
"respond_to?",
"(",
":size",
")",
"?",
"response",
".",
"size",
":",
"response",
".",
"length",
"output",
"=",
"[",
"request",
".",
"ip_address",
",",
"request",
".",
"selector",
",",
"request",
".",
"input",
",",
"code",
".",
"to_s",
",",
"size",
"]",
".",
"join",
"(",
"\"\\t\"",
")",
"@@access_logger",
".",
"debug",
"output",
"end"
] | write out an entry to our access log | [
"write",
"out",
"an",
"entry",
"to",
"our",
"access",
"log"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L533-L542 | train |
muffinista/gopher2000 | lib/gopher2000/base.rb | Gopher.Application.to_params_hash | def to_params_hash(keys,values)
hash = {}
keys.size.times { |i| hash[ keys[i].to_sym ] = values[i] }
hash
end | ruby | def to_params_hash(keys,values)
hash = {}
keys.size.times { |i| hash[ keys[i].to_sym ] = values[i] }
hash
end | [
"def",
"to_params_hash",
"(",
"keys",
",",
"values",
")",
"hash",
"=",
"{",
"}",
"keys",
".",
"size",
".",
"times",
"{",
"|",
"i",
"|",
"hash",
"[",
"keys",
"[",
"i",
"]",
".",
"to_sym",
"]",
"=",
"values",
"[",
"i",
"]",
"}",
"hash",
"end"
] | zip up two arrays of keys and values from an incoming request | [
"zip",
"up",
"two",
"arrays",
"of",
"keys",
"and",
"values",
"from",
"an",
"incoming",
"request"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L548-L552 | train |
muffinista/gopher2000 | lib/gopher2000/dispatcher.rb | Gopher.Dispatcher.call! | def call!(request)
operation = proc {
app.dispatch(request)
}
callback = proc {|result|
send_response result
close_connection_after_writing
}
#
# if we don't want to block on slow calls, use EM#defer
# @see http://eventmachine.rubyforge.org/EventMachine.html#M000486
#
if app.non_blocking?
EventMachine.defer( operation, callback )
else
callback.call(operation.call)
end
end | ruby | def call!(request)
operation = proc {
app.dispatch(request)
}
callback = proc {|result|
send_response result
close_connection_after_writing
}
#
# if we don't want to block on slow calls, use EM#defer
# @see http://eventmachine.rubyforge.org/EventMachine.html#M000486
#
if app.non_blocking?
EventMachine.defer( operation, callback )
else
callback.call(operation.call)
end
end | [
"def",
"call!",
"(",
"request",
")",
"operation",
"=",
"proc",
"{",
"app",
".",
"dispatch",
"(",
"request",
")",
"}",
"callback",
"=",
"proc",
"{",
"|",
"result",
"|",
"send_response",
"result",
"close_connection_after_writing",
"}",
"#",
"# if we don't want to block on slow calls, use EM#defer",
"# @see http://eventmachine.rubyforge.org/EventMachine.html#M000486",
"#",
"if",
"app",
".",
"non_blocking?",
"EventMachine",
".",
"defer",
"(",
"operation",
",",
"callback",
")",
"else",
"callback",
".",
"call",
"(",
"operation",
".",
"call",
")",
"end",
"end"
] | generate a request object from an incoming selector, and dispatch it to the app
@param [Request] request Request object to handle
@return Response object | [
"generate",
"a",
"request",
"object",
"from",
"an",
"incoming",
"selector",
"and",
"dispatch",
"it",
"to",
"the",
"app"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/dispatcher.rb#L46-L64 | train |
muffinista/gopher2000 | lib/gopher2000/dispatcher.rb | Gopher.Dispatcher.send_response | def send_response(response)
case response
when Gopher::Response then send_response(response.body)
when String then send_data(response + end_of_transmission)
when StringIO then send_data(response.read + end_of_transmission)
when File
while chunk = response.read(8192) do
send_data(chunk)
end
response.close
end
end | ruby | def send_response(response)
case response
when Gopher::Response then send_response(response.body)
when String then send_data(response + end_of_transmission)
when StringIO then send_data(response.read + end_of_transmission)
when File
while chunk = response.read(8192) do
send_data(chunk)
end
response.close
end
end | [
"def",
"send_response",
"(",
"response",
")",
"case",
"response",
"when",
"Gopher",
"::",
"Response",
"then",
"send_response",
"(",
"response",
".",
"body",
")",
"when",
"String",
"then",
"send_data",
"(",
"response",
"+",
"end_of_transmission",
")",
"when",
"StringIO",
"then",
"send_data",
"(",
"response",
".",
"read",
"+",
"end_of_transmission",
")",
"when",
"File",
"while",
"chunk",
"=",
"response",
".",
"read",
"(",
"8192",
")",
"do",
"send_data",
"(",
"chunk",
")",
"end",
"response",
".",
"close",
"end",
"end"
] | send the response back to the client
@param [Response] response object | [
"send",
"the",
"response",
"back",
"to",
"the",
"client"
] | 0b5333c368b307772a41b4bc77b208d5c3f9196b | https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/dispatcher.rb#L70-L81 | train |
appsignal/appsignal-ruby | lib/appsignal/auth_check.rb | Appsignal.AuthCheck.perform_with_result | def perform_with_result
status = perform
result =
case status
when "200"
"AppSignal has confirmed authorization!"
when "401"
"API key not valid with AppSignal..."
else
"Could not confirm authorization: " \
"#{status.nil? ? "nil" : status}"
end
[status, result]
rescue => e
result = "Something went wrong while trying to "\
"authenticate with AppSignal: #{e}"
[nil, result]
end | ruby | def perform_with_result
status = perform
result =
case status
when "200"
"AppSignal has confirmed authorization!"
when "401"
"API key not valid with AppSignal..."
else
"Could not confirm authorization: " \
"#{status.nil? ? "nil" : status}"
end
[status, result]
rescue => e
result = "Something went wrong while trying to "\
"authenticate with AppSignal: #{e}"
[nil, result]
end | [
"def",
"perform_with_result",
"status",
"=",
"perform",
"result",
"=",
"case",
"status",
"when",
"\"200\"",
"\"AppSignal has confirmed authorization!\"",
"when",
"\"401\"",
"\"API key not valid with AppSignal...\"",
"else",
"\"Could not confirm authorization: \"",
"\"#{status.nil? ? \"nil\" : status}\"",
"end",
"[",
"status",
",",
"result",
"]",
"rescue",
"=>",
"e",
"result",
"=",
"\"Something went wrong while trying to \"",
"\"authenticate with AppSignal: #{e}\"",
"[",
"nil",
",",
"result",
"]",
"end"
] | Perform push api validation request and return a descriptive response
tuple.
@return [Array<String/nil, String>] response tuple.
- First value is the response status code.
- Second value is a description of the response and the exception error
message if an exception occured. | [
"Perform",
"push",
"api",
"validation",
"request",
"and",
"return",
"a",
"descriptive",
"response",
"tuple",
"."
] | 23a07f6f01857a967921adb83deb98b07d160629 | https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/auth_check.rb#L48-L65 | train |
appsignal/appsignal-ruby | lib/appsignal/config.rb | Appsignal.Config.maintain_backwards_compatibility | def maintain_backwards_compatibility(configuration)
configuration.tap do |config|
DEPRECATED_CONFIG_KEY_MAPPING.each do |old_key, new_key|
old_config_value = config.delete(old_key)
next unless old_config_value
deprecation_message \
"Old configuration key found. Please update the "\
"'#{old_key}' to '#{new_key}'.",
logger
next if config[new_key] # Skip if new key is already in use
config[new_key] = old_config_value
end
if config.include?(:working_dir_path)
deprecation_message \
"'working_dir_path' is deprecated, please use " \
"'working_directory_path' instead and specify the " \
"full path to the working directory",
logger
end
end
end | ruby | def maintain_backwards_compatibility(configuration)
configuration.tap do |config|
DEPRECATED_CONFIG_KEY_MAPPING.each do |old_key, new_key|
old_config_value = config.delete(old_key)
next unless old_config_value
deprecation_message \
"Old configuration key found. Please update the "\
"'#{old_key}' to '#{new_key}'.",
logger
next if config[new_key] # Skip if new key is already in use
config[new_key] = old_config_value
end
if config.include?(:working_dir_path)
deprecation_message \
"'working_dir_path' is deprecated, please use " \
"'working_directory_path' instead and specify the " \
"full path to the working directory",
logger
end
end
end | [
"def",
"maintain_backwards_compatibility",
"(",
"configuration",
")",
"configuration",
".",
"tap",
"do",
"|",
"config",
"|",
"DEPRECATED_CONFIG_KEY_MAPPING",
".",
"each",
"do",
"|",
"old_key",
",",
"new_key",
"|",
"old_config_value",
"=",
"config",
".",
"delete",
"(",
"old_key",
")",
"next",
"unless",
"old_config_value",
"deprecation_message",
"\"Old configuration key found. Please update the \"",
"\"'#{old_key}' to '#{new_key}'.\"",
",",
"logger",
"next",
"if",
"config",
"[",
"new_key",
"]",
"# Skip if new key is already in use",
"config",
"[",
"new_key",
"]",
"=",
"old_config_value",
"end",
"if",
"config",
".",
"include?",
"(",
":working_dir_path",
")",
"deprecation_message",
"\"'working_dir_path' is deprecated, please use \"",
"\"'working_directory_path' instead and specify the \"",
"\"full path to the working directory\"",
",",
"logger",
"end",
"end",
"end"
] | Maintain backwards compatibility with config files generated by earlier
versions of the gem
Used by {#load_from_disk}. No compatibility for env variables or initial config currently. | [
"Maintain",
"backwards",
"compatibility",
"with",
"config",
"files",
"generated",
"by",
"earlier",
"versions",
"of",
"the",
"gem"
] | 23a07f6f01857a967921adb83deb98b07d160629 | https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/config.rb#L283-L305 | train |
appsignal/appsignal-ruby | lib/appsignal/transaction.rb | Appsignal.Transaction.background_queue_start | def background_queue_start
env = environment
return unless env
queue_start = env[:queue_start]
return unless queue_start
(queue_start.to_f * 1000.0).to_i
end | ruby | def background_queue_start
env = environment
return unless env
queue_start = env[:queue_start]
return unless queue_start
(queue_start.to_f * 1000.0).to_i
end | [
"def",
"background_queue_start",
"env",
"=",
"environment",
"return",
"unless",
"env",
"queue_start",
"=",
"env",
"[",
":queue_start",
"]",
"return",
"unless",
"queue_start",
"(",
"queue_start",
".",
"to_f",
"*",
"1000.0",
")",
".",
"to_i",
"end"
] | Returns calculated background queue start time in milliseconds, based on
environment values.
@return [nil] if no {#environment} is present.
@return [nil] if there is no `:queue_start` in the {#environment}.
@return [Integer] | [
"Returns",
"calculated",
"background",
"queue",
"start",
"time",
"in",
"milliseconds",
"based",
"on",
"environment",
"values",
"."
] | 23a07f6f01857a967921adb83deb98b07d160629 | https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/transaction.rb#L340-L347 | train |
appsignal/appsignal-ruby | lib/appsignal/transaction.rb | Appsignal.Transaction.http_queue_start | def http_queue_start
env = environment
return unless env
env_var = env["HTTP_X_QUEUE_START".freeze] || env["HTTP_X_REQUEST_START".freeze]
return unless env_var
cleaned_value = env_var.tr("^0-9".freeze, "".freeze)
return if cleaned_value.empty?
value = cleaned_value.to_i
if value > 4_102_441_200_000
# Value is in microseconds. Transform to milliseconds.
value / 1_000
elsif value < 946_681_200_000
# Value is too low to be plausible
nil
else
# Value is in milliseconds
value
end
end | ruby | def http_queue_start
env = environment
return unless env
env_var = env["HTTP_X_QUEUE_START".freeze] || env["HTTP_X_REQUEST_START".freeze]
return unless env_var
cleaned_value = env_var.tr("^0-9".freeze, "".freeze)
return if cleaned_value.empty?
value = cleaned_value.to_i
if value > 4_102_441_200_000
# Value is in microseconds. Transform to milliseconds.
value / 1_000
elsif value < 946_681_200_000
# Value is too low to be plausible
nil
else
# Value is in milliseconds
value
end
end | [
"def",
"http_queue_start",
"env",
"=",
"environment",
"return",
"unless",
"env",
"env_var",
"=",
"env",
"[",
"\"HTTP_X_QUEUE_START\"",
".",
"freeze",
"]",
"||",
"env",
"[",
"\"HTTP_X_REQUEST_START\"",
".",
"freeze",
"]",
"return",
"unless",
"env_var",
"cleaned_value",
"=",
"env_var",
".",
"tr",
"(",
"\"^0-9\"",
".",
"freeze",
",",
"\"\"",
".",
"freeze",
")",
"return",
"if",
"cleaned_value",
".",
"empty?",
"value",
"=",
"cleaned_value",
".",
"to_i",
"if",
"value",
">",
"4_102_441_200_000",
"# Value is in microseconds. Transform to milliseconds.",
"value",
"/",
"1_000",
"elsif",
"value",
"<",
"946_681_200_000",
"# Value is too low to be plausible",
"nil",
"else",
"# Value is in milliseconds",
"value",
"end",
"end"
] | Returns HTTP queue start time in milliseconds.
@return [nil] if no queue start time is found.
@return [nil] if begin time is too low to be plausible.
@return [Integer] queue start in milliseconds. | [
"Returns",
"HTTP",
"queue",
"start",
"time",
"in",
"milliseconds",
"."
] | 23a07f6f01857a967921adb83deb98b07d160629 | https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/transaction.rb#L354-L373 | train |
appsignal/appsignal-ruby | lib/appsignal/transaction.rb | Appsignal.Transaction.sanitized_environment | def sanitized_environment
env = environment
return if env.empty?
{}.tap do |out|
Appsignal.config[:request_headers].each do |key|
out[key] = env[key] if env[key]
end
end
end | ruby | def sanitized_environment
env = environment
return if env.empty?
{}.tap do |out|
Appsignal.config[:request_headers].each do |key|
out[key] = env[key] if env[key]
end
end
end | [
"def",
"sanitized_environment",
"env",
"=",
"environment",
"return",
"if",
"env",
".",
"empty?",
"{",
"}",
".",
"tap",
"do",
"|",
"out",
"|",
"Appsignal",
".",
"config",
"[",
":request_headers",
"]",
".",
"each",
"do",
"|",
"key",
"|",
"out",
"[",
"key",
"]",
"=",
"env",
"[",
"key",
"]",
"if",
"env",
"[",
"key",
"]",
"end",
"end",
"end"
] | Returns sanitized environment for a transaction.
The environment of a transaction can contain a lot of information, not
all of it useful for debugging.
@return [nil] if no environment is present.
@return [Hash<String, Object>] | [
"Returns",
"sanitized",
"environment",
"for",
"a",
"transaction",
"."
] | 23a07f6f01857a967921adb83deb98b07d160629 | https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/transaction.rb#L401-L410 | train |
appsignal/appsignal-ruby | lib/appsignal/transaction.rb | Appsignal.Transaction.sanitized_session_data | def sanitized_session_data
return if Appsignal.config[:skip_session_data] ||
!request.respond_to?(:session)
session = request.session
return unless session
Appsignal::Utils::HashSanitizer.sanitize(
session.to_hash, Appsignal.config[:filter_session_data]
)
end | ruby | def sanitized_session_data
return if Appsignal.config[:skip_session_data] ||
!request.respond_to?(:session)
session = request.session
return unless session
Appsignal::Utils::HashSanitizer.sanitize(
session.to_hash, Appsignal.config[:filter_session_data]
)
end | [
"def",
"sanitized_session_data",
"return",
"if",
"Appsignal",
".",
"config",
"[",
":skip_session_data",
"]",
"||",
"!",
"request",
".",
"respond_to?",
"(",
":session",
")",
"session",
"=",
"request",
".",
"session",
"return",
"unless",
"session",
"Appsignal",
"::",
"Utils",
"::",
"HashSanitizer",
".",
"sanitize",
"(",
"session",
".",
"to_hash",
",",
"Appsignal",
".",
"config",
"[",
":filter_session_data",
"]",
")",
"end"
] | Returns sanitized session data.
The session data is sanitized by the {Appsignal::Utils::HashSanitizer}.
@return [nil] if `:skip_session_data` config is set to `true`.
@return [nil] if the {#request} object doesn't respond to `#session`.
@return [nil] if the {#request} session data is `nil`.
@return [Hash<String, Object>] | [
"Returns",
"sanitized",
"session",
"data",
"."
] | 23a07f6f01857a967921adb83deb98b07d160629 | https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/transaction.rb#L420-L429 | train |
d0z0/redis_analytics | lib/redis_analytics/visit.rb | RedisAnalytics.Visit.for_each_time_range | def for_each_time_range(t)
RedisAnalytics.redis_key_timestamps.map{|x, y| t.strftime(x)}.each do |ts|
yield(ts)
end
end | ruby | def for_each_time_range(t)
RedisAnalytics.redis_key_timestamps.map{|x, y| t.strftime(x)}.each do |ts|
yield(ts)
end
end | [
"def",
"for_each_time_range",
"(",
"t",
")",
"RedisAnalytics",
".",
"redis_key_timestamps",
".",
"map",
"{",
"|",
"x",
",",
"y",
"|",
"t",
".",
"strftime",
"(",
"x",
")",
"}",
".",
"each",
"do",
"|",
"ts",
"|",
"yield",
"(",
"ts",
")",
"end",
"end"
] | This class represents one unique visit
User may have never visited the site
User may have visited before but his visit is expired
Everything counted here is unique for a visit
helpers | [
"This",
"class",
"represents",
"one",
"unique",
"visit",
"User",
"may",
"have",
"never",
"visited",
"the",
"site",
"User",
"may",
"have",
"visited",
"before",
"but",
"his",
"visit",
"is",
"expired",
"Everything",
"counted",
"here",
"is",
"unique",
"for",
"a",
"visit",
"helpers"
] | f29c9db9b7425f0ee80bdd8cf572295e79d3d2bd | https://github.com/d0z0/redis_analytics/blob/f29c9db9b7425f0ee80bdd8cf572295e79d3d2bd/lib/redis_analytics/visit.rb#L11-L15 | train |
d0z0/redis_analytics | lib/redis_analytics/visit.rb | RedisAnalytics.Visit.record | def record
if @current_visit_seq
track("visit_time", @t.to_i - @last_visit_end_time.to_i)
else
@current_visit_seq ||= counter("visits")
track("visits", 1) # track core 'visit' metric
if @first_visit_seq
track("repeat_visits", 1)
else
@first_visit_seq ||= counter("unique_visits")
track("first_visits", 1)
track("unique_visits", 1)
end
exec_custom_methods('visit') # custom methods that are measured on a per-visit basis
end
exec_custom_methods('hit') # custom methods that are measured on a per-page-view (per-hit) basis
track("page_views", 1) # track core 'page_view' metric
track("second_page_views", 1) if @page_view_seq_no.to_i == 1 # @last_visit_start_time and (@last_visit_start_time.to_i == @last_visit_end_time.to_i)
@rack_response
end | ruby | def record
if @current_visit_seq
track("visit_time", @t.to_i - @last_visit_end_time.to_i)
else
@current_visit_seq ||= counter("visits")
track("visits", 1) # track core 'visit' metric
if @first_visit_seq
track("repeat_visits", 1)
else
@first_visit_seq ||= counter("unique_visits")
track("first_visits", 1)
track("unique_visits", 1)
end
exec_custom_methods('visit') # custom methods that are measured on a per-visit basis
end
exec_custom_methods('hit') # custom methods that are measured on a per-page-view (per-hit) basis
track("page_views", 1) # track core 'page_view' metric
track("second_page_views", 1) if @page_view_seq_no.to_i == 1 # @last_visit_start_time and (@last_visit_start_time.to_i == @last_visit_end_time.to_i)
@rack_response
end | [
"def",
"record",
"if",
"@current_visit_seq",
"track",
"(",
"\"visit_time\"",
",",
"@t",
".",
"to_i",
"-",
"@last_visit_end_time",
".",
"to_i",
")",
"else",
"@current_visit_seq",
"||=",
"counter",
"(",
"\"visits\"",
")",
"track",
"(",
"\"visits\"",
",",
"1",
")",
"# track core 'visit' metric",
"if",
"@first_visit_seq",
"track",
"(",
"\"repeat_visits\"",
",",
"1",
")",
"else",
"@first_visit_seq",
"||=",
"counter",
"(",
"\"unique_visits\"",
")",
"track",
"(",
"\"first_visits\"",
",",
"1",
")",
"track",
"(",
"\"unique_visits\"",
",",
"1",
")",
"end",
"exec_custom_methods",
"(",
"'visit'",
")",
"# custom methods that are measured on a per-visit basis",
"end",
"exec_custom_methods",
"(",
"'hit'",
")",
"# custom methods that are measured on a per-page-view (per-hit) basis",
"track",
"(",
"\"page_views\"",
",",
"1",
")",
"# track core 'page_view' metric",
"track",
"(",
"\"second_page_views\"",
",",
"1",
")",
"if",
"@page_view_seq_no",
".",
"to_i",
"==",
"1",
"# @last_visit_start_time and (@last_visit_start_time.to_i == @last_visit_end_time.to_i)",
"@rack_response",
"end"
] | method used in analytics.rb to initialize visit
called from analytics.rb | [
"method",
"used",
"in",
"analytics",
".",
"rb",
"to",
"initialize",
"visit",
"called",
"from",
"analytics",
".",
"rb"
] | f29c9db9b7425f0ee80bdd8cf572295e79d3d2bd | https://github.com/d0z0/redis_analytics/blob/f29c9db9b7425f0ee80bdd8cf572295e79d3d2bd/lib/redis_analytics/visit.rb#L45-L64 | train |
7even/vkontakte_api | lib/vkontakte_api/configuration.rb | VkontakteApi.Configuration.reset | def reset
@adapter = DEFAULT_ADAPTER
@http_verb = DEFAULT_HTTP_VERB
@faraday_options = {}
@max_retries = DEFAULT_MAX_RETRIES
@logger = ::Logger.new(STDOUT)
@log_requests = DEFAULT_LOGGER_OPTIONS[:requests]
@log_errors = DEFAULT_LOGGER_OPTIONS[:errors]
@log_responses = DEFAULT_LOGGER_OPTIONS[:responses]
@api_version = nil
end | ruby | def reset
@adapter = DEFAULT_ADAPTER
@http_verb = DEFAULT_HTTP_VERB
@faraday_options = {}
@max_retries = DEFAULT_MAX_RETRIES
@logger = ::Logger.new(STDOUT)
@log_requests = DEFAULT_LOGGER_OPTIONS[:requests]
@log_errors = DEFAULT_LOGGER_OPTIONS[:errors]
@log_responses = DEFAULT_LOGGER_OPTIONS[:responses]
@api_version = nil
end | [
"def",
"reset",
"@adapter",
"=",
"DEFAULT_ADAPTER",
"@http_verb",
"=",
"DEFAULT_HTTP_VERB",
"@faraday_options",
"=",
"{",
"}",
"@max_retries",
"=",
"DEFAULT_MAX_RETRIES",
"@logger",
"=",
"::",
"Logger",
".",
"new",
"(",
"STDOUT",
")",
"@log_requests",
"=",
"DEFAULT_LOGGER_OPTIONS",
"[",
":requests",
"]",
"@log_errors",
"=",
"DEFAULT_LOGGER_OPTIONS",
"[",
":errors",
"]",
"@log_responses",
"=",
"DEFAULT_LOGGER_OPTIONS",
"[",
":responses",
"]",
"@api_version",
"=",
"nil",
"end"
] | Reset all configuration options to defaults. | [
"Reset",
"all",
"configuration",
"options",
"to",
"defaults",
"."
] | daa4a9126d816926d31421bdcfd31538ac25d83b | https://github.com/7even/vkontakte_api/blob/daa4a9126d816926d31421bdcfd31538ac25d83b/lib/vkontakte_api/configuration.rb#L58-L68 | train |
7even/vkontakte_api | lib/vkontakte_api/method.rb | VkontakteApi.Method.call | def call(args = {}, &block)
response = API.call(full_name, args, token)
Result.process(response, type, block)
end | ruby | def call(args = {}, &block)
response = API.call(full_name, args, token)
Result.process(response, type, block)
end | [
"def",
"call",
"(",
"args",
"=",
"{",
"}",
",",
"&",
"block",
")",
"response",
"=",
"API",
".",
"call",
"(",
"full_name",
",",
"args",
",",
"token",
")",
"Result",
".",
"process",
"(",
"response",
",",
"type",
",",
"block",
")",
"end"
] | Calling the API method.
It delegates the network request to `API.call` and result processing to `Result.process`.
@param [Hash] args Arguments for the API method. | [
"Calling",
"the",
"API",
"method",
".",
"It",
"delegates",
"the",
"network",
"request",
"to",
"API",
".",
"call",
"and",
"result",
"processing",
"to",
"Result",
".",
"process",
"."
] | daa4a9126d816926d31421bdcfd31538ac25d83b | https://github.com/7even/vkontakte_api/blob/daa4a9126d816926d31421bdcfd31538ac25d83b/lib/vkontakte_api/method.rb#L12-L15 | train |
7even/vkontakte_api | lib/vkontakte_api/authorization.rb | VkontakteApi.Authorization.authorization_url | def authorization_url(options = {})
type = options.delete(:type) || :site
# redirect_uri passed in options overrides the global setting
options[:redirect_uri] ||= VkontakteApi.redirect_uri
options[:scope] = VkontakteApi::Utils.flatten_argument(options[:scope]) if options[:scope]
case type
when :site
client.auth_code.authorize_url(options)
when :client
client.implicit.authorize_url(options)
else
raise ArgumentError, "Unknown authorization type #{type.inspect}"
end
end | ruby | def authorization_url(options = {})
type = options.delete(:type) || :site
# redirect_uri passed in options overrides the global setting
options[:redirect_uri] ||= VkontakteApi.redirect_uri
options[:scope] = VkontakteApi::Utils.flatten_argument(options[:scope]) if options[:scope]
case type
when :site
client.auth_code.authorize_url(options)
when :client
client.implicit.authorize_url(options)
else
raise ArgumentError, "Unknown authorization type #{type.inspect}"
end
end | [
"def",
"authorization_url",
"(",
"options",
"=",
"{",
"}",
")",
"type",
"=",
"options",
".",
"delete",
"(",
":type",
")",
"||",
":site",
"# redirect_uri passed in options overrides the global setting",
"options",
"[",
":redirect_uri",
"]",
"||=",
"VkontakteApi",
".",
"redirect_uri",
"options",
"[",
":scope",
"]",
"=",
"VkontakteApi",
"::",
"Utils",
".",
"flatten_argument",
"(",
"options",
"[",
":scope",
"]",
")",
"if",
"options",
"[",
":scope",
"]",
"case",
"type",
"when",
":site",
"client",
".",
"auth_code",
".",
"authorize_url",
"(",
"options",
")",
"when",
":client",
"client",
".",
"implicit",
".",
"authorize_url",
"(",
"options",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Unknown authorization type #{type.inspect}\"",
"end",
"end"
] | URL for redirecting the user to VK where he gives the application all the requested access rights.
@option options [Symbol] :type The type of authorization being used (`:site` and `:client` supported).
@option options [String] :redirect_uri URL for redirecting the user back to the application (overrides the global configuration value).
@option options [Array] :scope An array of requested access rights (each represented by a symbol or a string).
@raise [ArgumentError] raises after receiving an unknown authorization type.
@return [String] URL to redirect the user to. | [
"URL",
"for",
"redirecting",
"the",
"user",
"to",
"VK",
"where",
"he",
"gives",
"the",
"application",
"all",
"the",
"requested",
"access",
"rights",
"."
] | daa4a9126d816926d31421bdcfd31538ac25d83b | https://github.com/7even/vkontakte_api/blob/daa4a9126d816926d31421bdcfd31538ac25d83b/lib/vkontakte_api/authorization.rb#L24-L38 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.add_series | def add_series(params)
# Check that the required input has been specified.
unless params.has_key?(:values)
raise "Must specify ':values' in add_series"
end
if @requires_category != 0 && !params.has_key?(:categories)
raise "Must specify ':categories' in add_series for this chart type"
end
@series << Series.new(self, params)
# Set the secondary axis properties.
x2_axis = params[:x2_axis]
y2_axis = params[:y2_axis]
# Store secondary status for combined charts.
if ptrue?(x2_axis) || ptrue?(y2_axis)
@is_secondary = true
end
# Set the gap and overlap for Bar/Column charts.
if params[:gap]
if ptrue?(y2_axis)
@series_gap_2 = params[:gap]
else
@series_gap_1 = params[:gap]
end
end
# Set the overlap for Bar/Column charts.
if params[:overlap]
if ptrue?(y2_axis)
@series_overlap_2 = params[:overlap]
else
@series_overlap_1 = params[:overlap]
end
end
end | ruby | def add_series(params)
# Check that the required input has been specified.
unless params.has_key?(:values)
raise "Must specify ':values' in add_series"
end
if @requires_category != 0 && !params.has_key?(:categories)
raise "Must specify ':categories' in add_series for this chart type"
end
@series << Series.new(self, params)
# Set the secondary axis properties.
x2_axis = params[:x2_axis]
y2_axis = params[:y2_axis]
# Store secondary status for combined charts.
if ptrue?(x2_axis) || ptrue?(y2_axis)
@is_secondary = true
end
# Set the gap and overlap for Bar/Column charts.
if params[:gap]
if ptrue?(y2_axis)
@series_gap_2 = params[:gap]
else
@series_gap_1 = params[:gap]
end
end
# Set the overlap for Bar/Column charts.
if params[:overlap]
if ptrue?(y2_axis)
@series_overlap_2 = params[:overlap]
else
@series_overlap_1 = params[:overlap]
end
end
end | [
"def",
"add_series",
"(",
"params",
")",
"# Check that the required input has been specified.",
"unless",
"params",
".",
"has_key?",
"(",
":values",
")",
"raise",
"\"Must specify ':values' in add_series\"",
"end",
"if",
"@requires_category",
"!=",
"0",
"&&",
"!",
"params",
".",
"has_key?",
"(",
":categories",
")",
"raise",
"\"Must specify ':categories' in add_series for this chart type\"",
"end",
"@series",
"<<",
"Series",
".",
"new",
"(",
"self",
",",
"params",
")",
"# Set the secondary axis properties.",
"x2_axis",
"=",
"params",
"[",
":x2_axis",
"]",
"y2_axis",
"=",
"params",
"[",
":y2_axis",
"]",
"# Store secondary status for combined charts.",
"if",
"ptrue?",
"(",
"x2_axis",
")",
"||",
"ptrue?",
"(",
"y2_axis",
")",
"@is_secondary",
"=",
"true",
"end",
"# Set the gap and overlap for Bar/Column charts.",
"if",
"params",
"[",
":gap",
"]",
"if",
"ptrue?",
"(",
"y2_axis",
")",
"@series_gap_2",
"=",
"params",
"[",
":gap",
"]",
"else",
"@series_gap_1",
"=",
"params",
"[",
":gap",
"]",
"end",
"end",
"# Set the overlap for Bar/Column charts.",
"if",
"params",
"[",
":overlap",
"]",
"if",
"ptrue?",
"(",
"y2_axis",
")",
"@series_overlap_2",
"=",
"params",
"[",
":overlap",
"]",
"else",
"@series_overlap_1",
"=",
"params",
"[",
":overlap",
"]",
"end",
"end",
"end"
] | Add a series and it's properties to a chart. | [
"Add",
"a",
"series",
"and",
"it",
"s",
"properties",
"to",
"a",
"chart",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L247-L285 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.set_size | def set_size(params = {})
@width = params[:width] if params[:width]
@height = params[:height] if params[:height]
@x_scale = params[:x_scale] if params[:x_scale]
@y_scale = params[:y_scale] if params[:y_scale]
@x_offset = params[:x_offset] if params[:x_offset]
@y_offset = params[:y_offset] if params[:y_offset]
end | ruby | def set_size(params = {})
@width = params[:width] if params[:width]
@height = params[:height] if params[:height]
@x_scale = params[:x_scale] if params[:x_scale]
@y_scale = params[:y_scale] if params[:y_scale]
@x_offset = params[:x_offset] if params[:x_offset]
@y_offset = params[:y_offset] if params[:y_offset]
end | [
"def",
"set_size",
"(",
"params",
"=",
"{",
"}",
")",
"@width",
"=",
"params",
"[",
":width",
"]",
"if",
"params",
"[",
":width",
"]",
"@height",
"=",
"params",
"[",
":height",
"]",
"if",
"params",
"[",
":height",
"]",
"@x_scale",
"=",
"params",
"[",
":x_scale",
"]",
"if",
"params",
"[",
":x_scale",
"]",
"@y_scale",
"=",
"params",
"[",
":y_scale",
"]",
"if",
"params",
"[",
":y_scale",
"]",
"@x_offset",
"=",
"params",
"[",
":x_offset",
"]",
"if",
"params",
"[",
":x_offset",
"]",
"@y_offset",
"=",
"params",
"[",
":y_offset",
"]",
"if",
"params",
"[",
":y_offset",
"]",
"end"
] | Set dimensions for scale for the chart. | [
"Set",
"dimensions",
"for",
"scale",
"for",
"the",
"chart",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L392-L399 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.set_up_down_bars | def set_up_down_bars(params = {})
# Map border to line.
[:up, :down].each do |up_down|
if params[up_down]
params[up_down][:line] = params[up_down][:border] if params[up_down][:border]
else
params[up_down] = {}
end
end
# Set the up and down bar properties.
@up_down_bars = {
:_up => Chartline.new(params[:up]),
:_down => Chartline.new(params[:down])
}
end | ruby | def set_up_down_bars(params = {})
# Map border to line.
[:up, :down].each do |up_down|
if params[up_down]
params[up_down][:line] = params[up_down][:border] if params[up_down][:border]
else
params[up_down] = {}
end
end
# Set the up and down bar properties.
@up_down_bars = {
:_up => Chartline.new(params[:up]),
:_down => Chartline.new(params[:down])
}
end | [
"def",
"set_up_down_bars",
"(",
"params",
"=",
"{",
"}",
")",
"# Map border to line.",
"[",
":up",
",",
":down",
"]",
".",
"each",
"do",
"|",
"up_down",
"|",
"if",
"params",
"[",
"up_down",
"]",
"params",
"[",
"up_down",
"]",
"[",
":line",
"]",
"=",
"params",
"[",
"up_down",
"]",
"[",
":border",
"]",
"if",
"params",
"[",
"up_down",
"]",
"[",
":border",
"]",
"else",
"params",
"[",
"up_down",
"]",
"=",
"{",
"}",
"end",
"end",
"# Set the up and down bar properties.",
"@up_down_bars",
"=",
"{",
":_up",
"=>",
"Chartline",
".",
"new",
"(",
"params",
"[",
":up",
"]",
")",
",",
":_down",
"=>",
"Chartline",
".",
"new",
"(",
"params",
"[",
":down",
"]",
")",
"}",
"end"
] | Set properties for the chart up-down bars. | [
"Set",
"properties",
"for",
"the",
"chart",
"up",
"-",
"down",
"bars",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L415-L430 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.convert_font_args | def convert_font_args(params)
return unless params
font = params_to_font(params)
# Convert font size units.
font[:_size] *= 100 if font[:_size] && font[:_size] != 0
# Convert rotation into 60,000ths of a degree.
if ptrue?(font[:_rotation])
font[:_rotation] = 60_000 * font[:_rotation].to_i
end
font
end | ruby | def convert_font_args(params)
return unless params
font = params_to_font(params)
# Convert font size units.
font[:_size] *= 100 if font[:_size] && font[:_size] != 0
# Convert rotation into 60,000ths of a degree.
if ptrue?(font[:_rotation])
font[:_rotation] = 60_000 * font[:_rotation].to_i
end
font
end | [
"def",
"convert_font_args",
"(",
"params",
")",
"return",
"unless",
"params",
"font",
"=",
"params_to_font",
"(",
"params",
")",
"# Convert font size units.",
"font",
"[",
":_size",
"]",
"*=",
"100",
"if",
"font",
"[",
":_size",
"]",
"&&",
"font",
"[",
":_size",
"]",
"!=",
"0",
"# Convert rotation into 60,000ths of a degree.",
"if",
"ptrue?",
"(",
"font",
"[",
":_rotation",
"]",
")",
"font",
"[",
":_rotation",
"]",
"=",
"60_000",
"*",
"font",
"[",
":_rotation",
"]",
".",
"to_i",
"end",
"font",
"end"
] | Convert user defined font values into private hash values. | [
"Convert",
"user",
"defined",
"font",
"values",
"into",
"private",
"hash",
"values",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L513-L526 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.process_names | def process_names(name = nil, name_formula = nil) # :nodoc:
# Name looks like a formula, use it to set name_formula.
if name.respond_to?(:to_ary)
cell = xl_rowcol_to_cell(name[1], name[2], 1, 1)
name_formula = "#{quote_sheetname(name[0])}!#{cell}"
name = ''
elsif
name && name =~ /^=[^!]+!\$/
name_formula = name
name = ''
end
[name, name_formula]
end | ruby | def process_names(name = nil, name_formula = nil) # :nodoc:
# Name looks like a formula, use it to set name_formula.
if name.respond_to?(:to_ary)
cell = xl_rowcol_to_cell(name[1], name[2], 1, 1)
name_formula = "#{quote_sheetname(name[0])}!#{cell}"
name = ''
elsif
name && name =~ /^=[^!]+!\$/
name_formula = name
name = ''
end
[name, name_formula]
end | [
"def",
"process_names",
"(",
"name",
"=",
"nil",
",",
"name_formula",
"=",
"nil",
")",
"# :nodoc:",
"# Name looks like a formula, use it to set name_formula.",
"if",
"name",
".",
"respond_to?",
"(",
":to_ary",
")",
"cell",
"=",
"xl_rowcol_to_cell",
"(",
"name",
"[",
"1",
"]",
",",
"name",
"[",
"2",
"]",
",",
"1",
",",
"1",
")",
"name_formula",
"=",
"\"#{quote_sheetname(name[0])}!#{cell}\"",
"name",
"=",
"''",
"elsif",
"name",
"&&",
"name",
"=~",
"/",
"\\$",
"/",
"name_formula",
"=",
"name",
"name",
"=",
"''",
"end",
"[",
"name",
",",
"name_formula",
"]",
"end"
] | Switch name and name_formula parameters if required. | [
"Switch",
"name",
"and",
"name_formula",
"parameters",
"if",
"required",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L546-L559 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.get_data_type | def get_data_type(data) # :nodoc:
# Check for no data in the series.
return 'none' unless data
return 'none' if data.empty?
return 'multi_str' if data.first.kind_of?(Array)
# If the token isn't a number assume it is a string.
data.each do |token|
next unless token
return 'str' unless token.kind_of?(Numeric)
end
# The series data was all numeric.
'num'
end | ruby | def get_data_type(data) # :nodoc:
# Check for no data in the series.
return 'none' unless data
return 'none' if data.empty?
return 'multi_str' if data.first.kind_of?(Array)
# If the token isn't a number assume it is a string.
data.each do |token|
next unless token
return 'str' unless token.kind_of?(Numeric)
end
# The series data was all numeric.
'num'
end | [
"def",
"get_data_type",
"(",
"data",
")",
"# :nodoc:",
"# Check for no data in the series.",
"return",
"'none'",
"unless",
"data",
"return",
"'none'",
"if",
"data",
".",
"empty?",
"return",
"'multi_str'",
"if",
"data",
".",
"first",
".",
"kind_of?",
"(",
"Array",
")",
"# If the token isn't a number assume it is a string.",
"data",
".",
"each",
"do",
"|",
"token",
"|",
"next",
"unless",
"token",
"return",
"'str'",
"unless",
"token",
".",
"kind_of?",
"(",
"Numeric",
")",
"end",
"# The series data was all numeric.",
"'num'",
"end"
] | Find the overall type of the data associated with a series.
TODO. Need to handle date type. | [
"Find",
"the",
"overall",
"type",
"of",
"the",
"data",
"associated",
"with",
"a",
"series",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L649-L663 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.color | def color(color_code) # :nodoc:
if color_code and color_code =~ /^#[0-9a-fA-F]{6}$/
# Convert a HTML style #RRGGBB color.
color_code.sub(/^#/, '').upcase
else
index = Format.color(color_code)
raise "Unknown color '#{color_code}' used in chart formatting." unless index
palette_color(index)
end
end | ruby | def color(color_code) # :nodoc:
if color_code and color_code =~ /^#[0-9a-fA-F]{6}$/
# Convert a HTML style #RRGGBB color.
color_code.sub(/^#/, '').upcase
else
index = Format.color(color_code)
raise "Unknown color '#{color_code}' used in chart formatting." unless index
palette_color(index)
end
end | [
"def",
"color",
"(",
"color_code",
")",
"# :nodoc:",
"if",
"color_code",
"and",
"color_code",
"=~",
"/",
"/",
"# Convert a HTML style #RRGGBB color.",
"color_code",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
".",
"upcase",
"else",
"index",
"=",
"Format",
".",
"color",
"(",
"color_code",
")",
"raise",
"\"Unknown color '#{color_code}' used in chart formatting.\"",
"unless",
"index",
"palette_color",
"(",
"index",
")",
"end",
"end"
] | Convert the user specified colour index or string to a rgb colour. | [
"Convert",
"the",
"user",
"specified",
"colour",
"index",
"or",
"string",
"to",
"a",
"rgb",
"colour",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L668-L677 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.get_font_style_attributes | def get_font_style_attributes(font)
return [] unless font
attributes = []
attributes << ['sz', font[:_size]] if ptrue?(font[:_size])
attributes << ['b', font[:_bold]] if font[:_bold]
attributes << ['i', font[:_italic]] if font[:_italic]
attributes << ['u', 'sng'] if font[:_underline]
# Turn off baseline when testing fonts that don't have it.
if font[:_baseline] != -1
attributes << ['baseline', font[:_baseline]]
end
attributes
end | ruby | def get_font_style_attributes(font)
return [] unless font
attributes = []
attributes << ['sz', font[:_size]] if ptrue?(font[:_size])
attributes << ['b', font[:_bold]] if font[:_bold]
attributes << ['i', font[:_italic]] if font[:_italic]
attributes << ['u', 'sng'] if font[:_underline]
# Turn off baseline when testing fonts that don't have it.
if font[:_baseline] != -1
attributes << ['baseline', font[:_baseline]]
end
attributes
end | [
"def",
"get_font_style_attributes",
"(",
"font",
")",
"return",
"[",
"]",
"unless",
"font",
"attributes",
"=",
"[",
"]",
"attributes",
"<<",
"[",
"'sz'",
",",
"font",
"[",
":_size",
"]",
"]",
"if",
"ptrue?",
"(",
"font",
"[",
":_size",
"]",
")",
"attributes",
"<<",
"[",
"'b'",
",",
"font",
"[",
":_bold",
"]",
"]",
"if",
"font",
"[",
":_bold",
"]",
"attributes",
"<<",
"[",
"'i'",
",",
"font",
"[",
":_italic",
"]",
"]",
"if",
"font",
"[",
":_italic",
"]",
"attributes",
"<<",
"[",
"'u'",
",",
"'sng'",
"]",
"if",
"font",
"[",
":_underline",
"]",
"# Turn off baseline when testing fonts that don't have it.",
"if",
"font",
"[",
":_baseline",
"]",
"!=",
"-",
"1",
"attributes",
"<<",
"[",
"'baseline'",
",",
"font",
"[",
":_baseline",
"]",
"]",
"end",
"attributes",
"end"
] | Get the font style attributes from a font hash. | [
"Get",
"the",
"font",
"style",
"attributes",
"from",
"a",
"font",
"hash",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L719-L733 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.get_font_latin_attributes | def get_font_latin_attributes(font)
return [] unless font
attributes = []
attributes << ['typeface', font[:_name]] if ptrue?(font[:_name])
attributes << ['pitchFamily', font[:_pitch_family]] if font[:_pitch_family]
attributes << ['charset', font[:_charset]] if font[:_charset]
attributes
end | ruby | def get_font_latin_attributes(font)
return [] unless font
attributes = []
attributes << ['typeface', font[:_name]] if ptrue?(font[:_name])
attributes << ['pitchFamily', font[:_pitch_family]] if font[:_pitch_family]
attributes << ['charset', font[:_charset]] if font[:_charset]
attributes
end | [
"def",
"get_font_latin_attributes",
"(",
"font",
")",
"return",
"[",
"]",
"unless",
"font",
"attributes",
"=",
"[",
"]",
"attributes",
"<<",
"[",
"'typeface'",
",",
"font",
"[",
":_name",
"]",
"]",
"if",
"ptrue?",
"(",
"font",
"[",
":_name",
"]",
")",
"attributes",
"<<",
"[",
"'pitchFamily'",
",",
"font",
"[",
":_pitch_family",
"]",
"]",
"if",
"font",
"[",
":_pitch_family",
"]",
"attributes",
"<<",
"[",
"'charset'",
",",
"font",
"[",
":_charset",
"]",
"]",
"if",
"font",
"[",
":_charset",
"]",
"attributes",
"end"
] | Get the font latin attributes from a font hash. | [
"Get",
"the",
"font",
"latin",
"attributes",
"from",
"a",
"font",
"hash",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L738-L747 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.write_series_name | def write_series_name(series) # :nodoc:
if series.name_formula
write_tx_formula(series.name_formula, series.name_id)
elsif series.name
write_tx_value(series.name)
end
end | ruby | def write_series_name(series) # :nodoc:
if series.name_formula
write_tx_formula(series.name_formula, series.name_id)
elsif series.name
write_tx_value(series.name)
end
end | [
"def",
"write_series_name",
"(",
"series",
")",
"# :nodoc:",
"if",
"series",
".",
"name_formula",
"write_tx_formula",
"(",
"series",
".",
"name_formula",
",",
"series",
".",
"name_id",
")",
"elsif",
"series",
".",
"name",
"write_tx_value",
"(",
"series",
".",
"name",
")",
"end",
"end"
] | Write the series name. | [
"Write",
"the",
"series",
"name",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L1074-L1080 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.write_axis_font | def write_axis_font(font) # :nodoc:
return unless font
@writer.tag_elements('c:txPr') do
write_a_body_pr(font[:_rotation])
write_a_lst_style
@writer.tag_elements('a:p') do
write_a_p_pr_rich(font)
write_a_end_para_rpr
end
end
end | ruby | def write_axis_font(font) # :nodoc:
return unless font
@writer.tag_elements('c:txPr') do
write_a_body_pr(font[:_rotation])
write_a_lst_style
@writer.tag_elements('a:p') do
write_a_p_pr_rich(font)
write_a_end_para_rpr
end
end
end | [
"def",
"write_axis_font",
"(",
"font",
")",
"# :nodoc:",
"return",
"unless",
"font",
"@writer",
".",
"tag_elements",
"(",
"'c:txPr'",
")",
"do",
"write_a_body_pr",
"(",
"font",
"[",
":_rotation",
"]",
")",
"write_a_lst_style",
"@writer",
".",
"tag_elements",
"(",
"'a:p'",
")",
"do",
"write_a_p_pr_rich",
"(",
"font",
")",
"write_a_end_para_rpr",
"end",
"end",
"end"
] | Write the axis font elements. | [
"Write",
"the",
"axis",
"font",
"elements",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L2504-L2515 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.write_error_bars | def write_error_bars(error_bars)
return unless ptrue?(error_bars)
if error_bars[:_x_error_bars]
write_err_bars('x', error_bars[:_x_error_bars])
end
if error_bars[:_y_error_bars]
write_err_bars('y', error_bars[:_y_error_bars])
end
end | ruby | def write_error_bars(error_bars)
return unless ptrue?(error_bars)
if error_bars[:_x_error_bars]
write_err_bars('x', error_bars[:_x_error_bars])
end
if error_bars[:_y_error_bars]
write_err_bars('y', error_bars[:_y_error_bars])
end
end | [
"def",
"write_error_bars",
"(",
"error_bars",
")",
"return",
"unless",
"ptrue?",
"(",
"error_bars",
")",
"if",
"error_bars",
"[",
":_x_error_bars",
"]",
"write_err_bars",
"(",
"'x'",
",",
"error_bars",
"[",
":_x_error_bars",
"]",
")",
"end",
"if",
"error_bars",
"[",
":_y_error_bars",
"]",
"write_err_bars",
"(",
"'y'",
",",
"error_bars",
"[",
":_y_error_bars",
"]",
")",
"end",
"end"
] | Write the X and Y error bars. | [
"Write",
"the",
"X",
"and",
"Y",
"error",
"bars",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L2534-L2543 | train |
cxn03651/write_xlsx | lib/write_xlsx/chart.rb | Writexlsx.Chart.write_custom_error | def write_custom_error(error_bars)
if ptrue?(error_bars.plus_values)
write_custom_error_base('c:plus', error_bars.plus_values, error_bars.plus_data)
write_custom_error_base('c:minus', error_bars.minus_values, error_bars.minus_data)
end
end | ruby | def write_custom_error(error_bars)
if ptrue?(error_bars.plus_values)
write_custom_error_base('c:plus', error_bars.plus_values, error_bars.plus_data)
write_custom_error_base('c:minus', error_bars.minus_values, error_bars.minus_data)
end
end | [
"def",
"write_custom_error",
"(",
"error_bars",
")",
"if",
"ptrue?",
"(",
"error_bars",
".",
"plus_values",
")",
"write_custom_error_base",
"(",
"'c:plus'",
",",
"error_bars",
".",
"plus_values",
",",
"error_bars",
".",
"plus_data",
")",
"write_custom_error_base",
"(",
"'c:minus'",
",",
"error_bars",
".",
"minus_values",
",",
"error_bars",
".",
"minus_data",
")",
"end",
"end"
] | Write the custom error bars type. | [
"Write",
"the",
"custom",
"error",
"bars",
"type",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/chart.rb#L2620-L2625 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.protect | def protect(password = nil, options = {})
check_parameter(options, protect_default_settings.keys, 'protect')
@protect = protect_default_settings.merge(options)
# Set the password after the user defined values.
@protect[:password] =
sprintf("%X", encode_password(password)) if password && password != ''
end | ruby | def protect(password = nil, options = {})
check_parameter(options, protect_default_settings.keys, 'protect')
@protect = protect_default_settings.merge(options)
# Set the password after the user defined values.
@protect[:password] =
sprintf("%X", encode_password(password)) if password && password != ''
end | [
"def",
"protect",
"(",
"password",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"check_parameter",
"(",
"options",
",",
"protect_default_settings",
".",
"keys",
",",
"'protect'",
")",
"@protect",
"=",
"protect_default_settings",
".",
"merge",
"(",
"options",
")",
"# Set the password after the user defined values.",
"@protect",
"[",
":password",
"]",
"=",
"sprintf",
"(",
"\"%X\"",
",",
"encode_password",
"(",
"password",
")",
")",
"if",
"password",
"&&",
"password",
"!=",
"''",
"end"
] | Set the worksheet protection flags to prevent modification of worksheet
objects.
The protect() method is used to protect a worksheet from modification:
worksheet.protect
The protect() method also has the effect of enabling a cell's locked
and hidden properties if they have been set. A locked cell cannot be
edited and this property is on by default for all cells. A hidden
cell will display the results of a formula but not the formula itself.
See the protection.rb program in the examples directory of the distro
for an illustrative example and the +set_locked+ and +set_hidden+ format
methods in "CELL FORMATTING", see Format.
You can optionally add a password to the worksheet protection:
worksheet.protect('drowssap')
Passing the empty string '' is the same as turning on protection
without a password.
Note, the worksheet level password in Excel provides very weak
protection. It does not encrypt your data and is very easy to
deactivate. Full workbook encryption is not supported by WriteXLSX
since it requires a completely different file format and would take
several man months to implement.
You can specify which worksheet elements that you which to protect
by passing a hash with any or all of the following keys:
# Default shown.
options = {
:objects => false,
:scenarios => false,
:format_cells => false,
:format_columns => false,
:format_rows => false,
:insert_columns => false,
:insert_rows => false,
:insert_hyperlinks => false,
:delete_columns => false,
:delete_rows => false,
:select_locked_cells => true,
:sort => false,
:autofilter => false,
:pivot_tables => false,
:select_unlocked_cells => true
}
The default boolean values are shown above. Individual elements
can be protected as follows:
worksheet.protect('drowssap', { :insert_rows => true } ) | [
"Set",
"the",
"worksheet",
"protection",
"flags",
"to",
"prevent",
"modification",
"of",
"worksheet",
"objects",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L602-L609 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.set_header | def set_header(string = '', margin = 0.3, options = {})
raise 'Header string must be less than 255 characters' if string.length >= 255
# Replace the Excel placeholder &[Picture] with the internal &G.
@page_setup.header = string.gsub(/&\[Picture\]/, '&G')
if string.size >= 255
raise 'Header string must be less than 255 characters'
end
if options[:align_with_margins]
@page_setup.header_footer_aligns = options[:align_with_margins]
end
if options[:scale_with_doc]
@page_setup.header_footer_scales = options[:scale_with_doc]
end
# Reset the array in case the function is called more than once.
@header_images = []
[
[:image_left, 'LH'], [:image_center, 'CH'], [:image_right, 'RH']
].each do |p|
if options[p.first]
@header_images << [options[p.first], p.last]
end
end
# placeholeder /&G/ の数
placeholder_count = @page_setup.header.scan(/&G/).count
image_count = @header_images.count
if image_count != placeholder_count
raise "Number of header image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.header}"
end
@has_header_vml = true if image_count > 0
@page_setup.margin_header = margin || 0.3
@page_setup.header_footer_changed = true
end | ruby | def set_header(string = '', margin = 0.3, options = {})
raise 'Header string must be less than 255 characters' if string.length >= 255
# Replace the Excel placeholder &[Picture] with the internal &G.
@page_setup.header = string.gsub(/&\[Picture\]/, '&G')
if string.size >= 255
raise 'Header string must be less than 255 characters'
end
if options[:align_with_margins]
@page_setup.header_footer_aligns = options[:align_with_margins]
end
if options[:scale_with_doc]
@page_setup.header_footer_scales = options[:scale_with_doc]
end
# Reset the array in case the function is called more than once.
@header_images = []
[
[:image_left, 'LH'], [:image_center, 'CH'], [:image_right, 'RH']
].each do |p|
if options[p.first]
@header_images << [options[p.first], p.last]
end
end
# placeholeder /&G/ の数
placeholder_count = @page_setup.header.scan(/&G/).count
image_count = @header_images.count
if image_count != placeholder_count
raise "Number of header image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.header}"
end
@has_header_vml = true if image_count > 0
@page_setup.margin_header = margin || 0.3
@page_setup.header_footer_changed = true
end | [
"def",
"set_header",
"(",
"string",
"=",
"''",
",",
"margin",
"=",
"0.3",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"'Header string must be less than 255 characters'",
"if",
"string",
".",
"length",
">=",
"255",
"# Replace the Excel placeholder &[Picture] with the internal &G.",
"@page_setup",
".",
"header",
"=",
"string",
".",
"gsub",
"(",
"/",
"\\[",
"\\]",
"/",
",",
"'&G'",
")",
"if",
"string",
".",
"size",
">=",
"255",
"raise",
"'Header string must be less than 255 characters'",
"end",
"if",
"options",
"[",
":align_with_margins",
"]",
"@page_setup",
".",
"header_footer_aligns",
"=",
"options",
"[",
":align_with_margins",
"]",
"end",
"if",
"options",
"[",
":scale_with_doc",
"]",
"@page_setup",
".",
"header_footer_scales",
"=",
"options",
"[",
":scale_with_doc",
"]",
"end",
"# Reset the array in case the function is called more than once.",
"@header_images",
"=",
"[",
"]",
"[",
"[",
":image_left",
",",
"'LH'",
"]",
",",
"[",
":image_center",
",",
"'CH'",
"]",
",",
"[",
":image_right",
",",
"'RH'",
"]",
"]",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"options",
"[",
"p",
".",
"first",
"]",
"@header_images",
"<<",
"[",
"options",
"[",
"p",
".",
"first",
"]",
",",
"p",
".",
"last",
"]",
"end",
"end",
"# placeholeder /&G/ の数",
"placeholder_count",
"=",
"@page_setup",
".",
"header",
".",
"scan",
"(",
"/",
"/",
")",
".",
"count",
"image_count",
"=",
"@header_images",
".",
"count",
"if",
"image_count",
"!=",
"placeholder_count",
"raise",
"\"Number of header image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.header}\"",
"end",
"@has_header_vml",
"=",
"true",
"if",
"image_count",
">",
"0",
"@page_setup",
".",
"margin_header",
"=",
"margin",
"||",
"0.3",
"@page_setup",
".",
"header_footer_changed",
"=",
"true",
"end"
] | Set the page header caption and optional margin.
Headers and footers are generated using a string which is a combination
of plain text and control characters. The margin parameter is optional.
The available control character are:
Control Category Description
======= ======== ===========
&L Justification Left
&C Center
&R Right
&P Information Page number
&N Total number of pages
&D Date
&T Time
&F File name
&A Worksheet name
&Z Workbook path
&fontsize Font Font size
&"font,style" Font name and style
&U Single underline
&E Double underline
&S Strikethrough
&X Superscript
&Y Subscript
&& Miscellaneous Literal ampersand &
Text in headers and footers can be justified (aligned) to the left,
center and right by prefixing the text with the control characters
&L, &C and &R.
For example (with ASCII art representation of the results):
worksheet.set_header('&LHello')
---------------------------------------------------------------
| |
| Hello |
| |
worksheet.set_header('&CHello')
---------------------------------------------------------------
| |
| Hello |
| |
worksheet.set_header('&RHello')
---------------------------------------------------------------
| |
| Hello |
| |
For simple text, if you do not specify any justification the text will
be centred. However, you must prefix the text with &C if you specify
a font name or any other formatting:
worksheet.set_header('Hello')
---------------------------------------------------------------
| |
| Hello |
| |
You can have text in each of the justification regions:
worksheet.set_header('&LCiao&CBello&RCielo')
---------------------------------------------------------------
| |
| Ciao Bello Cielo |
| |
The information control characters act as variables that Excel will update
as the workbook or worksheet changes. Times and dates are in the users
default format:
worksheet.set_header('&CPage &P of &N')
---------------------------------------------------------------
| |
| Page 1 of 6 |
| |
worksheet.set_header('&CUpdated at &T')
---------------------------------------------------------------
| |
| Updated at 12:30 PM |
| |
You can specify the font size of a section of the text by prefixing it
with the control character &n where n is the font size:
worksheet1.set_header('&C&30Hello Big' )
worksheet2.set_header('&C&10Hello Small' )
You can specify the font of a section of the text by prefixing it with
the control sequence &"font,style" where fontname is a font name such
as "Courier New" or "Times New Roman" and style is one of the standard
Windows font descriptions: "Regular", "Italic", "Bold" or "Bold Italic":
worksheet1.set_header('&C&"Courier New,Italic"Hello')
worksheet2.set_header('&C&"Courier New,Bold Italic"Hello')
worksheet3.set_header('&C&"Times New Roman,Regular"Hello')
It is possible to combine all of these features together to create
sophisticated headers and footers. As an aid to setting up complicated
headers and footers you can record a page set-up as a macro in Excel
and look at the format strings that VBA produces. Remember however
that VBA uses two double quotes "" to indicate a single double quote.
For the last example above the equivalent VBA code looks like this:
.LeftHeader = ""
.CenterHeader = "&""Times New Roman,Regular""Hello"
.RightHeader = ""
To include a single literal ampersand & in a header or footer you
should use a double ampersand &&:
worksheet1.set_header('&CCuriouser && Curiouser - Attorneys at Law')
As stated above the margin parameter is optional. As with the other
margins the value should be in inches. The default header and footer
margin is 0.3 inch. Note, the default margin is different from the
default used in the binary file format by Spreadsheet::WriteExcel.
The header and footer margin size can be set as follows:
worksheet.set_header('&CHello', 0.75)
The header and footer margins are independent of the top and bottom
margins.
Note, the header or footer string must be less than 255 characters.
Strings longer than this will not be written and a warning will be
generated.
See, also the headers.rb program in the examples directory of the
distribution. | [
"Set",
"the",
"page",
"header",
"caption",
"and",
"optional",
"margin",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L1198-L1239 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.set_footer | def set_footer(string = '', margin = 0.3, options = {})
raise 'Footer string must be less than 255 characters' if string.length >= 255
@page_setup.footer = string.dup
# Replace the Excel placeholder &[Picture] with the internal &G.
@page_setup.footer = string.gsub(/&\[Picture\]/, '&G')
if string.size >= 255
raise 'Header string must be less than 255 characters'
end
if options[:align_with_margins]
@page_setup.header_footer_aligns = options[:align_with_margins]
end
if options[:scale_with_doc]
@page_setup.header_footer_scales = options[:scale_with_doc]
end
# Reset the array in case the function is called more than once.
@footer_images = []
[
[:image_left, 'LF'], [:image_center, 'CF'], [:image_right, 'RF']
].each do |p|
if options[p.first]
@footer_images << [options[p.first], p.last]
end
end
# placeholeder /&G/ の数
placeholder_count = @page_setup.footer.scan(/&G/).count
image_count = @footer_images.count
if image_count != placeholder_count
raise "Number of footer image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.footer}"
end
@has_header_vml = true if image_count > 0
@page_setup.margin_footer = margin
@page_setup.header_footer_changed = true
end | ruby | def set_footer(string = '', margin = 0.3, options = {})
raise 'Footer string must be less than 255 characters' if string.length >= 255
@page_setup.footer = string.dup
# Replace the Excel placeholder &[Picture] with the internal &G.
@page_setup.footer = string.gsub(/&\[Picture\]/, '&G')
if string.size >= 255
raise 'Header string must be less than 255 characters'
end
if options[:align_with_margins]
@page_setup.header_footer_aligns = options[:align_with_margins]
end
if options[:scale_with_doc]
@page_setup.header_footer_scales = options[:scale_with_doc]
end
# Reset the array in case the function is called more than once.
@footer_images = []
[
[:image_left, 'LF'], [:image_center, 'CF'], [:image_right, 'RF']
].each do |p|
if options[p.first]
@footer_images << [options[p.first], p.last]
end
end
# placeholeder /&G/ の数
placeholder_count = @page_setup.footer.scan(/&G/).count
image_count = @footer_images.count
if image_count != placeholder_count
raise "Number of footer image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.footer}"
end
@has_header_vml = true if image_count > 0
@page_setup.margin_footer = margin
@page_setup.header_footer_changed = true
end | [
"def",
"set_footer",
"(",
"string",
"=",
"''",
",",
"margin",
"=",
"0.3",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"'Footer string must be less than 255 characters'",
"if",
"string",
".",
"length",
">=",
"255",
"@page_setup",
".",
"footer",
"=",
"string",
".",
"dup",
"# Replace the Excel placeholder &[Picture] with the internal &G.",
"@page_setup",
".",
"footer",
"=",
"string",
".",
"gsub",
"(",
"/",
"\\[",
"\\]",
"/",
",",
"'&G'",
")",
"if",
"string",
".",
"size",
">=",
"255",
"raise",
"'Header string must be less than 255 characters'",
"end",
"if",
"options",
"[",
":align_with_margins",
"]",
"@page_setup",
".",
"header_footer_aligns",
"=",
"options",
"[",
":align_with_margins",
"]",
"end",
"if",
"options",
"[",
":scale_with_doc",
"]",
"@page_setup",
".",
"header_footer_scales",
"=",
"options",
"[",
":scale_with_doc",
"]",
"end",
"# Reset the array in case the function is called more than once.",
"@footer_images",
"=",
"[",
"]",
"[",
"[",
":image_left",
",",
"'LF'",
"]",
",",
"[",
":image_center",
",",
"'CF'",
"]",
",",
"[",
":image_right",
",",
"'RF'",
"]",
"]",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"options",
"[",
"p",
".",
"first",
"]",
"@footer_images",
"<<",
"[",
"options",
"[",
"p",
".",
"first",
"]",
",",
"p",
".",
"last",
"]",
"end",
"end",
"# placeholeder /&G/ の数",
"placeholder_count",
"=",
"@page_setup",
".",
"footer",
".",
"scan",
"(",
"/",
"/",
")",
".",
"count",
"image_count",
"=",
"@footer_images",
".",
"count",
"if",
"image_count",
"!=",
"placeholder_count",
"raise",
"\"Number of footer image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.footer}\"",
"end",
"@has_header_vml",
"=",
"true",
"if",
"image_count",
">",
"0",
"@page_setup",
".",
"margin_footer",
"=",
"margin",
"@page_setup",
".",
"header_footer_changed",
"=",
"true",
"end"
] | Set the page footer caption and optional margin.
The syntax of the set_footer() method is the same as set_header() | [
"Set",
"the",
"page",
"footer",
"caption",
"and",
"optional",
"margin",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L1246-L1290 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.repeat_rows | def repeat_rows(row_min, row_max = nil)
row_max ||= row_min
# Convert to 1 based.
row_min += 1
row_max += 1
area = "$#{row_min}:$#{row_max}"
# Build up the print titles "Sheet1!$1:$2"
sheetname = quote_sheetname(@name)
@page_setup.repeat_rows = "#{sheetname}!#{area}"
end | ruby | def repeat_rows(row_min, row_max = nil)
row_max ||= row_min
# Convert to 1 based.
row_min += 1
row_max += 1
area = "$#{row_min}:$#{row_max}"
# Build up the print titles "Sheet1!$1:$2"
sheetname = quote_sheetname(@name)
@page_setup.repeat_rows = "#{sheetname}!#{area}"
end | [
"def",
"repeat_rows",
"(",
"row_min",
",",
"row_max",
"=",
"nil",
")",
"row_max",
"||=",
"row_min",
"# Convert to 1 based.",
"row_min",
"+=",
"1",
"row_max",
"+=",
"1",
"area",
"=",
"\"$#{row_min}:$#{row_max}\"",
"# Build up the print titles \"Sheet1!$1:$2\"",
"sheetname",
"=",
"quote_sheetname",
"(",
"@name",
")",
"@page_setup",
".",
"repeat_rows",
"=",
"\"#{sheetname}!#{area}\"",
"end"
] | Set the number of rows to repeat at the top of each printed page.
For large Excel documents it is often desirable to have the first row
or rows of the worksheet print out at the top of each page. This can
be achieved by using the repeat_rows() method. The parameters
first_row and last_row are zero based. The last_row parameter is
optional if you only wish to specify one row:
worksheet1.repeat_rows(0) # Repeat the first row
worksheet2.repeat_rows(0, 1) # Repeat the first two rows | [
"Set",
"the",
"number",
"of",
"rows",
"to",
"repeat",
"at",
"the",
"top",
"of",
"each",
"printed",
"page",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L1482-L1494 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.print_across | def print_across(across = true)
if across
@page_setup.across = true
@page_setup.page_setup_changed = true
else
@page_setup.across = false
end
end | ruby | def print_across(across = true)
if across
@page_setup.across = true
@page_setup.page_setup_changed = true
else
@page_setup.across = false
end
end | [
"def",
"print_across",
"(",
"across",
"=",
"true",
")",
"if",
"across",
"@page_setup",
".",
"across",
"=",
"true",
"@page_setup",
".",
"page_setup_changed",
"=",
"true",
"else",
"@page_setup",
".",
"across",
"=",
"false",
"end",
"end"
] | Set the order in which pages are printed.
The print_across method is used to change the default print direction.
This is referred to by Excel as the sheet "page order".
worksheet.print_across
The default page order is shown below for a worksheet that extends
over 4 pages. The order is called "down then across":
[1] [3]
[2] [4]
However, by using the print_across method the print order will be
changed to "across then down":
[1] [2]
[3] [4] | [
"Set",
"the",
"order",
"in",
"which",
"pages",
"are",
"printed",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L1685-L1692 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.filter_column | def filter_column(col, expression)
raise "Must call autofilter before filter_column" unless @autofilter_area
col = prepare_filter_column(col)
tokens = extract_filter_tokens(expression)
unless tokens.size == 3 || tokens.size == 7
raise "Incorrect number of tokens in expression '#{expression}'"
end
tokens = parse_filter_expression(expression, tokens)
# Excel handles single or double custom filters as default filters. We need
# to check for them and handle them accordingly.
if tokens.size == 2 && tokens[0] == 2
# Single equality.
filter_column_list(col, tokens[1])
elsif tokens.size == 5 && tokens[0] == 2 && tokens[2] == 1 && tokens[3] == 2
# Double equality with "or" operator.
filter_column_list(col, tokens[1], tokens[4])
else
# Non default custom filter.
@filter_cols[col] = Array.new(tokens)
@filter_type[col] = 0
end
@filter_on = 1
end | ruby | def filter_column(col, expression)
raise "Must call autofilter before filter_column" unless @autofilter_area
col = prepare_filter_column(col)
tokens = extract_filter_tokens(expression)
unless tokens.size == 3 || tokens.size == 7
raise "Incorrect number of tokens in expression '#{expression}'"
end
tokens = parse_filter_expression(expression, tokens)
# Excel handles single or double custom filters as default filters. We need
# to check for them and handle them accordingly.
if tokens.size == 2 && tokens[0] == 2
# Single equality.
filter_column_list(col, tokens[1])
elsif tokens.size == 5 && tokens[0] == 2 && tokens[2] == 1 && tokens[3] == 2
# Double equality with "or" operator.
filter_column_list(col, tokens[1], tokens[4])
else
# Non default custom filter.
@filter_cols[col] = Array.new(tokens)
@filter_type[col] = 0
end
@filter_on = 1
end | [
"def",
"filter_column",
"(",
"col",
",",
"expression",
")",
"raise",
"\"Must call autofilter before filter_column\"",
"unless",
"@autofilter_area",
"col",
"=",
"prepare_filter_column",
"(",
"col",
")",
"tokens",
"=",
"extract_filter_tokens",
"(",
"expression",
")",
"unless",
"tokens",
".",
"size",
"==",
"3",
"||",
"tokens",
".",
"size",
"==",
"7",
"raise",
"\"Incorrect number of tokens in expression '#{expression}'\"",
"end",
"tokens",
"=",
"parse_filter_expression",
"(",
"expression",
",",
"tokens",
")",
"# Excel handles single or double custom filters as default filters. We need",
"# to check for them and handle them accordingly.",
"if",
"tokens",
".",
"size",
"==",
"2",
"&&",
"tokens",
"[",
"0",
"]",
"==",
"2",
"# Single equality.",
"filter_column_list",
"(",
"col",
",",
"tokens",
"[",
"1",
"]",
")",
"elsif",
"tokens",
".",
"size",
"==",
"5",
"&&",
"tokens",
"[",
"0",
"]",
"==",
"2",
"&&",
"tokens",
"[",
"2",
"]",
"==",
"1",
"&&",
"tokens",
"[",
"3",
"]",
"==",
"2",
"# Double equality with \"or\" operator.",
"filter_column_list",
"(",
"col",
",",
"tokens",
"[",
"1",
"]",
",",
"tokens",
"[",
"4",
"]",
")",
"else",
"# Non default custom filter.",
"@filter_cols",
"[",
"col",
"]",
"=",
"Array",
".",
"new",
"(",
"tokens",
")",
"@filter_type",
"[",
"col",
"]",
"=",
"0",
"end",
"@filter_on",
"=",
"1",
"end"
] | Set the column filter criteria.
The filter_column method can be used to filter columns in a autofilter
range based on simple conditions.
NOTE: It isn't sufficient to just specify the filter condition.
You must also hide any rows that don't match the filter condition.
Rows are hidden using the set_row() +visible+ parameter. WriteXLSX cannot
do this automatically since it isn't part of the file format.
See the autofilter.rb program in the examples directory of the distro
for an example.
The conditions for the filter are specified using simple expressions:
worksheet.filter_column('A', 'x > 2000')
worksheet.filter_column('B', 'x > 2000 and x < 5000')
The +column+ parameter can either be a zero indexed column number or
a string column name.
The following operators are available:
Operator Synonyms
== = eq =~
!= <> ne !=
>
<
>=
<=
and &&
or ||
The operator synonyms are just syntactic sugar to make you more
comfortable using the expressions. It is important to remember that
the expressions will be interpreted by Excel and not by ruby.
An expression can comprise a single statement or two statements
separated by the +and+ and +or+ operators. For example:
'x < 2000'
'x > 2000'
'x == 2000'
'x > 2000 and x < 5000'
'x == 2000 or x == 5000'
Filtering of blank or non-blank data can be achieved by using a value
of +Blanks+ or +NonBlanks+ in the expression:
'x == Blanks'
'x == NonBlanks'
Excel also allows some simple string matching operations:
'x =~ b*' # begins with b
'x !~ b*' # doesn't begin with b
'x =~ *b' # ends with b
'x !~ *b' # doesn't end with b
'x =~ *b*' # contains b
'x !~ *b*' # doesn't contains b
You can also use * to match any character or number and ? to match any
single character or number. No other regular expression quantifier is
supported by Excel's filters. Excel's regular expression characters can
be escaped using +~+.
The placeholder variable +x+ in the above examples can be replaced by any
simple string. The actual placeholder name is ignored internally so the
following are all equivalent:
'x < 2000'
'col < 2000'
'Price < 2000'
Also, note that a filter condition can only be applied to a column
in a range specified by the autofilter() Worksheet method.
See the autofilter.rb program in the examples directory of the distro
for a more detailed example.
Note writeExcel gem supports Top 10 style filters. These aren't
currently supported by WriteXLSX but may be added later. | [
"Set",
"the",
"column",
"filter",
"criteria",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5389-L5417 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.filter_column_list | def filter_column_list(col, *tokens)
tokens.flatten!
raise "Incorrect number of arguments to filter_column_list" if tokens.empty?
raise "Must call autofilter before filter_column_list" unless @autofilter_area
col = prepare_filter_column(col)
@filter_cols[col] = tokens
@filter_type[col] = 1 # Default style.
@filter_on = 1
end | ruby | def filter_column_list(col, *tokens)
tokens.flatten!
raise "Incorrect number of arguments to filter_column_list" if tokens.empty?
raise "Must call autofilter before filter_column_list" unless @autofilter_area
col = prepare_filter_column(col)
@filter_cols[col] = tokens
@filter_type[col] = 1 # Default style.
@filter_on = 1
end | [
"def",
"filter_column_list",
"(",
"col",
",",
"*",
"tokens",
")",
"tokens",
".",
"flatten!",
"raise",
"\"Incorrect number of arguments to filter_column_list\"",
"if",
"tokens",
".",
"empty?",
"raise",
"\"Must call autofilter before filter_column_list\"",
"unless",
"@autofilter_area",
"col",
"=",
"prepare_filter_column",
"(",
"col",
")",
"@filter_cols",
"[",
"col",
"]",
"=",
"tokens",
"@filter_type",
"[",
"col",
"]",
"=",
"1",
"# Default style.",
"@filter_on",
"=",
"1",
"end"
] | Set the column filter criteria in Excel 2007 list style.
Prior to Excel 2007 it was only possible to have either 1 or 2 filter
conditions such as the ones shown above in the filter_column method.
Excel 2007 introduced a new list style filter where it is possible
to specify 1 or more 'or' style criteria. For example if your column
contained data for the first six months the initial data would be
displayed as all selected as shown on the left. Then if you selected
'March', 'April' and 'May' they would be displayed as shown on the right.
No criteria selected Some criteria selected.
[/] (Select all) [X] (Select all)
[/] January [ ] January
[/] February [ ] February
[/] March [/] March
[/] April [/] April
[/] May [/] May
[/] June [ ] June
The filter_column_list() method can be used to represent these types of
filters:
worksheet.filter_column_list('A', 'March', 'April', 'May')
The column parameter can either be a zero indexed column number or
a string column name.
One or more criteria can be selected:
worksheet.filter_column_list(0, 'March')
worksheet.filter_column_list(1, 100, 110, 120, 130)
NOTE: It isn't sufficient to just specify the filter condition. You must
also hide any rows that don't match the filter condition. Rows are hidden
using the set_row() visible parameter. WriteXLSX cannot do this
automatically since it isn't part of the file format.
See the autofilter.rb program in the examples directory of the distro
for an example. e conditions for the filter are specified
using simple expressions: | [
"Set",
"the",
"column",
"filter",
"criteria",
"in",
"Excel",
"2007",
"list",
"style",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5462-L5472 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.set_h_pagebreaks | def set_h_pagebreaks(*args)
breaks = args.collect do |brk|
Array(brk)
end.flatten
@page_setup.hbreaks += breaks
end | ruby | def set_h_pagebreaks(*args)
breaks = args.collect do |brk|
Array(brk)
end.flatten
@page_setup.hbreaks += breaks
end | [
"def",
"set_h_pagebreaks",
"(",
"*",
"args",
")",
"breaks",
"=",
"args",
".",
"collect",
"do",
"|",
"brk",
"|",
"Array",
"(",
"brk",
")",
"end",
".",
"flatten",
"@page_setup",
".",
"hbreaks",
"+=",
"breaks",
"end"
] | Store the horizontal page breaks on a worksheet.
Add horizontal page breaks to a worksheet. A page break causes all
the data that follows it to be printed on the next page. Horizontal
page breaks act between rows. To create a page break between rows
20 and 21 you must specify the break at row 21. However in zero index
notation this is actually row 20. So you can pretend for a small
while that you are using 1 index notation:
worksheet1.set_h_pagebreaks( 20 ) # Break between row 20 and 21
The set_h_pagebreaks() method will accept a list of page breaks
and you can call it more than once:
worksheet2.set_h_pagebreaks( 20, 40, 60, 80, 100 ) # Add breaks
worksheet2.set_h_pagebreaks( 120, 140, 160, 180, 200 ) # Add some more
Note: If you specify the "fit to page" option via the fit_to_pages()
method it will override all manual page breaks.
There is a silent limitation of about 1000 horizontal page breaks
per worksheet in line with an Excel internal limitation. | [
"Store",
"the",
"horizontal",
"page",
"breaks",
"on",
"a",
"worksheet",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5498-L5503 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.get_range_data | def get_range_data(row_start, col_start, row_end, col_end) # :nodoc:
# TODO. Check for worksheet limits.
# Iterate through the table data.
data = []
(row_start .. row_end).each do |row_num|
# Store nil if row doesn't exist.
if !@cell_data_table[row_num]
data << nil
next
end
(col_start .. col_end).each do |col_num|
if cell = @cell_data_table[row_num][col_num]
data << cell.data
else
# Store nil if col doesn't exist.
data << nil
end
end
end
return data
end | ruby | def get_range_data(row_start, col_start, row_end, col_end) # :nodoc:
# TODO. Check for worksheet limits.
# Iterate through the table data.
data = []
(row_start .. row_end).each do |row_num|
# Store nil if row doesn't exist.
if !@cell_data_table[row_num]
data << nil
next
end
(col_start .. col_end).each do |col_num|
if cell = @cell_data_table[row_num][col_num]
data << cell.data
else
# Store nil if col doesn't exist.
data << nil
end
end
end
return data
end | [
"def",
"get_range_data",
"(",
"row_start",
",",
"col_start",
",",
"row_end",
",",
"col_end",
")",
"# :nodoc:",
"# TODO. Check for worksheet limits.",
"# Iterate through the table data.",
"data",
"=",
"[",
"]",
"(",
"row_start",
"..",
"row_end",
")",
".",
"each",
"do",
"|",
"row_num",
"|",
"# Store nil if row doesn't exist.",
"if",
"!",
"@cell_data_table",
"[",
"row_num",
"]",
"data",
"<<",
"nil",
"next",
"end",
"(",
"col_start",
"..",
"col_end",
")",
".",
"each",
"do",
"|",
"col_num",
"|",
"if",
"cell",
"=",
"@cell_data_table",
"[",
"row_num",
"]",
"[",
"col_num",
"]",
"data",
"<<",
"cell",
".",
"data",
"else",
"# Store nil if col doesn't exist.",
"data",
"<<",
"nil",
"end",
"end",
"end",
"return",
"data",
"end"
] | Returns a range of data from the worksheet _table to be used in chart
cached data. Strings are returned as SST ids and decoded in the workbook.
Return nils for data that doesn't exist since Excel can chart series
with data missing. | [
"Returns",
"a",
"range",
"of",
"data",
"from",
"the",
"worksheet",
"_table",
"to",
"be",
"used",
"in",
"chart",
"cached",
"data",
".",
"Strings",
"are",
"returned",
"as",
"SST",
"ids",
"and",
"decoded",
"in",
"the",
"workbook",
".",
"Return",
"nils",
"for",
"data",
"that",
"doesn",
"t",
"exist",
"since",
"Excel",
"can",
"chart",
"series",
"with",
"data",
"missing",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5646-L5669 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.position_object_pixels | def position_object_pixels(col_start, row_start, x1, y1, width, height) #:nodoc:
# Calculate the absolute x offset of the top-left vertex.
if @col_size_changed
x_abs = (0 .. col_start-1).inject(0) {|sum, col| sum += size_col(col)}
else
# Optimisation for when the column widths haven't changed.
x_abs = @default_col_pixels * col_start
end
x_abs += x1
# Calculate the absolute y offset of the top-left vertex.
# Store the column change to allow optimisations.
if @row_size_changed
y_abs = (0 .. row_start-1).inject(0) {|sum, row| sum += size_row(row)}
else
# Optimisation for when the row heights haven't changed.
y_abs = @default_row_pixels * row_start
end
y_abs += y1
# Adjust start column for offsets that are greater than the col width.
x1, col_start = adjust_column_offset(x1, col_start)
# Adjust start row for offsets that are greater than the row height.
y1, row_start = adjust_row_offset(y1, row_start)
# Initialise end cell to the same as the start cell.
col_end = col_start
row_end = row_start
width += x1
height += y1
# Subtract the underlying cell widths to find the end cell of the object.
width, col_end = adjust_column_offset(width, col_end)
# Subtract the underlying cell heights to find the end cell of the object.
height, row_end = adjust_row_offset(height, row_end)
# The end vertices are whatever is left from the width and height.
x2 = width
y2 = height
[col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs]
end | ruby | def position_object_pixels(col_start, row_start, x1, y1, width, height) #:nodoc:
# Calculate the absolute x offset of the top-left vertex.
if @col_size_changed
x_abs = (0 .. col_start-1).inject(0) {|sum, col| sum += size_col(col)}
else
# Optimisation for when the column widths haven't changed.
x_abs = @default_col_pixels * col_start
end
x_abs += x1
# Calculate the absolute y offset of the top-left vertex.
# Store the column change to allow optimisations.
if @row_size_changed
y_abs = (0 .. row_start-1).inject(0) {|sum, row| sum += size_row(row)}
else
# Optimisation for when the row heights haven't changed.
y_abs = @default_row_pixels * row_start
end
y_abs += y1
# Adjust start column for offsets that are greater than the col width.
x1, col_start = adjust_column_offset(x1, col_start)
# Adjust start row for offsets that are greater than the row height.
y1, row_start = adjust_row_offset(y1, row_start)
# Initialise end cell to the same as the start cell.
col_end = col_start
row_end = row_start
width += x1
height += y1
# Subtract the underlying cell widths to find the end cell of the object.
width, col_end = adjust_column_offset(width, col_end)
# Subtract the underlying cell heights to find the end cell of the object.
height, row_end = adjust_row_offset(height, row_end)
# The end vertices are whatever is left from the width and height.
x2 = width
y2 = height
[col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs]
end | [
"def",
"position_object_pixels",
"(",
"col_start",
",",
"row_start",
",",
"x1",
",",
"y1",
",",
"width",
",",
"height",
")",
"#:nodoc:",
"# Calculate the absolute x offset of the top-left vertex.",
"if",
"@col_size_changed",
"x_abs",
"=",
"(",
"0",
"..",
"col_start",
"-",
"1",
")",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"col",
"|",
"sum",
"+=",
"size_col",
"(",
"col",
")",
"}",
"else",
"# Optimisation for when the column widths haven't changed.",
"x_abs",
"=",
"@default_col_pixels",
"*",
"col_start",
"end",
"x_abs",
"+=",
"x1",
"# Calculate the absolute y offset of the top-left vertex.",
"# Store the column change to allow optimisations.",
"if",
"@row_size_changed",
"y_abs",
"=",
"(",
"0",
"..",
"row_start",
"-",
"1",
")",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"row",
"|",
"sum",
"+=",
"size_row",
"(",
"row",
")",
"}",
"else",
"# Optimisation for when the row heights haven't changed.",
"y_abs",
"=",
"@default_row_pixels",
"*",
"row_start",
"end",
"y_abs",
"+=",
"y1",
"# Adjust start column for offsets that are greater than the col width.",
"x1",
",",
"col_start",
"=",
"adjust_column_offset",
"(",
"x1",
",",
"col_start",
")",
"# Adjust start row for offsets that are greater than the row height.",
"y1",
",",
"row_start",
"=",
"adjust_row_offset",
"(",
"y1",
",",
"row_start",
")",
"# Initialise end cell to the same as the start cell.",
"col_end",
"=",
"col_start",
"row_end",
"=",
"row_start",
"width",
"+=",
"x1",
"height",
"+=",
"y1",
"# Subtract the underlying cell widths to find the end cell of the object.",
"width",
",",
"col_end",
"=",
"adjust_column_offset",
"(",
"width",
",",
"col_end",
")",
"# Subtract the underlying cell heights to find the end cell of the object.",
"height",
",",
"row_end",
"=",
"adjust_row_offset",
"(",
"height",
",",
"row_end",
")",
"# The end vertices are whatever is left from the width and height.",
"x2",
"=",
"width",
"y2",
"=",
"height",
"[",
"col_start",
",",
"row_start",
",",
"x1",
",",
"y1",
",",
"col_end",
",",
"row_end",
",",
"x2",
",",
"y2",
",",
"x_abs",
",",
"y_abs",
"]",
"end"
] | Calculate the vertices that define the position of a graphical object within
the worksheet in pixels.
+------------+------------+
| A | B |
+-----+------------+------------+
| |(x1,y1) | |
| 1 |(A1)._______|______ |
| | | | |
| | | | |
+-----+----| Object |-----+
| | | | |
| 2 | |______________. |
| | | (B2)|
| | | (x2,y2)|
+---- +------------+------------+
Example of an object that covers some of the area from cell A1 to cell B2.
Based on the width and height of the object we need to calculate 8 vars:
col_start, row_start, col_end, row_end, x1, y1, x2, y2.
We also calculate the absolute x and y position of the top left vertex of
the object. This is required for images.
x_abs, y_abs
The width and height of the cells that the object occupies can be variable
and have to be taken into account.
The values of col_start and row_start are passed in from the calling
function. The values of col_end and row_end are calculated by subtracting
the width and height of the object from the width and height of the
underlying cells.
col_start # Col containing upper left corner of object.
x1 # Distance to left side of object.
row_start # Row containing top left corner of object.
y1 # Distance to top of object.
col_end # Col containing lower right corner of object.
x2 # Distance to right side of object.
row_end # Row containing bottom right corner of object.
y2 # Distance to bottom of object.
width # Width of object frame.
height # Height of object frame. | [
"Calculate",
"the",
"vertices",
"that",
"define",
"the",
"position",
"of",
"a",
"graphical",
"object",
"within",
"the",
"worksheet",
"in",
"pixels",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5718-L5762 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.prepare_vml_objects | def prepare_vml_objects(vml_data_id, vml_shape_id, vml_drawing_id, comment_id)
set_external_vml_links(vml_drawing_id)
set_external_comment_links(comment_id) if has_comments?
# The VML o:idmap data id contains a comma separated range when there is
# more than one 1024 block of comments, like this: data="1,2".
data = "#{vml_data_id}"
(1 .. num_comments_block).each do |i|
data += ",#{vml_data_id + i}"
end
@vml_data_id = data
@vml_shape_id = vml_shape_id
end | ruby | def prepare_vml_objects(vml_data_id, vml_shape_id, vml_drawing_id, comment_id)
set_external_vml_links(vml_drawing_id)
set_external_comment_links(comment_id) if has_comments?
# The VML o:idmap data id contains a comma separated range when there is
# more than one 1024 block of comments, like this: data="1,2".
data = "#{vml_data_id}"
(1 .. num_comments_block).each do |i|
data += ",#{vml_data_id + i}"
end
@vml_data_id = data
@vml_shape_id = vml_shape_id
end | [
"def",
"prepare_vml_objects",
"(",
"vml_data_id",
",",
"vml_shape_id",
",",
"vml_drawing_id",
",",
"comment_id",
")",
"set_external_vml_links",
"(",
"vml_drawing_id",
")",
"set_external_comment_links",
"(",
"comment_id",
")",
"if",
"has_comments?",
"# The VML o:idmap data id contains a comma separated range when there is",
"# more than one 1024 block of comments, like this: data=\"1,2\".",
"data",
"=",
"\"#{vml_data_id}\"",
"(",
"1",
"..",
"num_comments_block",
")",
".",
"each",
"do",
"|",
"i",
"|",
"data",
"+=",
"\",#{vml_data_id + i}\"",
"end",
"@vml_data_id",
"=",
"data",
"@vml_shape_id",
"=",
"vml_shape_id",
"end"
] | Turn the HoH that stores the comments into an array for easier handling
and set the external links for comments and buttons. | [
"Turn",
"the",
"HoH",
"that",
"stores",
"the",
"comments",
"into",
"an",
"array",
"for",
"easier",
"handling",
"and",
"set",
"the",
"external",
"links",
"for",
"comments",
"and",
"buttons",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5846-L5858 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.prepare_tables | def prepare_tables(table_id)
if tables_count > 0
id = table_id
tables.each do |table|
table.prepare(id)
# Store the link used for the rels file.
@external_table_links << ['/table', "../tables/table#{id}.xml"]
id += 1
end
end
tables_count || 0
end | ruby | def prepare_tables(table_id)
if tables_count > 0
id = table_id
tables.each do |table|
table.prepare(id)
# Store the link used for the rels file.
@external_table_links << ['/table', "../tables/table#{id}.xml"]
id += 1
end
end
tables_count || 0
end | [
"def",
"prepare_tables",
"(",
"table_id",
")",
"if",
"tables_count",
">",
"0",
"id",
"=",
"table_id",
"tables",
".",
"each",
"do",
"|",
"table",
"|",
"table",
".",
"prepare",
"(",
"id",
")",
"# Store the link used for the rels file.",
"@external_table_links",
"<<",
"[",
"'/table'",
",",
"\"../tables/table#{id}.xml\"",
"]",
"id",
"+=",
"1",
"end",
"end",
"tables_count",
"||",
"0",
"end"
] | Set the table ids for the worksheet tables. | [
"Set",
"the",
"table",
"ids",
"for",
"the",
"worksheet",
"tables",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5871-L5883 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.write_formatted_blank_to_area | def write_formatted_blank_to_area(row_first, row_last, col_first, col_last, format)
(row_first .. row_last).each do |row|
(col_first .. col_last).each do |col|
next if row == row_first && col == col_first
write_blank(row, col, format)
end
end
end | ruby | def write_formatted_blank_to_area(row_first, row_last, col_first, col_last, format)
(row_first .. row_last).each do |row|
(col_first .. col_last).each do |col|
next if row == row_first && col == col_first
write_blank(row, col, format)
end
end
end | [
"def",
"write_formatted_blank_to_area",
"(",
"row_first",
",",
"row_last",
",",
"col_first",
",",
"col_last",
",",
"format",
")",
"(",
"row_first",
"..",
"row_last",
")",
".",
"each",
"do",
"|",
"row",
"|",
"(",
"col_first",
"..",
"col_last",
")",
".",
"each",
"do",
"|",
"col",
"|",
"next",
"if",
"row",
"==",
"row_first",
"&&",
"col",
"==",
"col_first",
"write_blank",
"(",
"row",
",",
"col",
",",
"format",
")",
"end",
"end",
"end"
] | Pad out the rest of the area with formatted blank cells. | [
"Pad",
"out",
"the",
"rest",
"of",
"the",
"area",
"with",
"formatted",
"blank",
"cells",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L5998-L6005 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.parse_filter_tokens | def parse_filter_tokens(expression, tokens) #:nodoc:
operators = {
'==' => 2,
'=' => 2,
'=~' => 2,
'eq' => 2,
'!=' => 5,
'!~' => 5,
'ne' => 5,
'<>' => 5,
'<' => 1,
'<=' => 3,
'>' => 4,
'>=' => 6,
}
operator = operators[tokens[1]]
token = tokens[2]
# Special handling of "Top" filter expressions.
if tokens[0] =~ /^top|bottom$/i
value = tokens[1]
if (value =~ /\D/ or value.to_i < 1 or value.to_i > 500)
raise "The value '#{value}' in expression '#{expression}' " +
"must be in the range 1 to 500"
end
token.downcase!
if (token != 'items' and token != '%')
raise "The type '#{token}' in expression '#{expression}' " +
"must be either 'items' or '%'"
end
if (tokens[0] =~ /^top$/i)
operator = 30
else
operator = 32
end
if (tokens[2] == '%')
operator += 1
end
token = value
end
if (not operator and tokens[0])
raise "Token '#{tokens[1]}' is not a valid operator " +
"in filter expression '#{expression}'"
end
# Special handling for Blanks/NonBlanks.
if (token =~ /^blanks|nonblanks$/i)
# Only allow Equals or NotEqual in this context.
if (operator != 2 and operator != 5)
raise "The operator '#{tokens[1]}' in expression '#{expression}' " +
"is not valid in relation to Blanks/NonBlanks'"
end
token.downcase!
# The operator should always be 2 (=) to flag a "simple" equality in
# the binary record. Therefore we convert <> to =.
if token == 'blanks'
if operator == 5
token = ' '
end
else
if operator == 5
operator = 2
token = 'blanks'
else
operator = 5
token = ' '
end
end
end
# if the string token contains an Excel match character then change the
# operator type to indicate a non "simple" equality.
if (operator == 2 and token =~ /[*?]/)
operator = 22
end
[operator, token]
end | ruby | def parse_filter_tokens(expression, tokens) #:nodoc:
operators = {
'==' => 2,
'=' => 2,
'=~' => 2,
'eq' => 2,
'!=' => 5,
'!~' => 5,
'ne' => 5,
'<>' => 5,
'<' => 1,
'<=' => 3,
'>' => 4,
'>=' => 6,
}
operator = operators[tokens[1]]
token = tokens[2]
# Special handling of "Top" filter expressions.
if tokens[0] =~ /^top|bottom$/i
value = tokens[1]
if (value =~ /\D/ or value.to_i < 1 or value.to_i > 500)
raise "The value '#{value}' in expression '#{expression}' " +
"must be in the range 1 to 500"
end
token.downcase!
if (token != 'items' and token != '%')
raise "The type '#{token}' in expression '#{expression}' " +
"must be either 'items' or '%'"
end
if (tokens[0] =~ /^top$/i)
operator = 30
else
operator = 32
end
if (tokens[2] == '%')
operator += 1
end
token = value
end
if (not operator and tokens[0])
raise "Token '#{tokens[1]}' is not a valid operator " +
"in filter expression '#{expression}'"
end
# Special handling for Blanks/NonBlanks.
if (token =~ /^blanks|nonblanks$/i)
# Only allow Equals or NotEqual in this context.
if (operator != 2 and operator != 5)
raise "The operator '#{tokens[1]}' in expression '#{expression}' " +
"is not valid in relation to Blanks/NonBlanks'"
end
token.downcase!
# The operator should always be 2 (=) to flag a "simple" equality in
# the binary record. Therefore we convert <> to =.
if token == 'blanks'
if operator == 5
token = ' '
end
else
if operator == 5
operator = 2
token = 'blanks'
else
operator = 5
token = ' '
end
end
end
# if the string token contains an Excel match character then change the
# operator type to indicate a non "simple" equality.
if (operator == 2 and token =~ /[*?]/)
operator = 22
end
[operator, token]
end | [
"def",
"parse_filter_tokens",
"(",
"expression",
",",
"tokens",
")",
"#:nodoc:",
"operators",
"=",
"{",
"'=='",
"=>",
"2",
",",
"'='",
"=>",
"2",
",",
"'=~'",
"=>",
"2",
",",
"'eq'",
"=>",
"2",
",",
"'!='",
"=>",
"5",
",",
"'!~'",
"=>",
"5",
",",
"'ne'",
"=>",
"5",
",",
"'<>'",
"=>",
"5",
",",
"'<'",
"=>",
"1",
",",
"'<='",
"=>",
"3",
",",
"'>'",
"=>",
"4",
",",
"'>='",
"=>",
"6",
",",
"}",
"operator",
"=",
"operators",
"[",
"tokens",
"[",
"1",
"]",
"]",
"token",
"=",
"tokens",
"[",
"2",
"]",
"# Special handling of \"Top\" filter expressions.",
"if",
"tokens",
"[",
"0",
"]",
"=~",
"/",
"/i",
"value",
"=",
"tokens",
"[",
"1",
"]",
"if",
"(",
"value",
"=~",
"/",
"\\D",
"/",
"or",
"value",
".",
"to_i",
"<",
"1",
"or",
"value",
".",
"to_i",
">",
"500",
")",
"raise",
"\"The value '#{value}' in expression '#{expression}' \"",
"+",
"\"must be in the range 1 to 500\"",
"end",
"token",
".",
"downcase!",
"if",
"(",
"token",
"!=",
"'items'",
"and",
"token",
"!=",
"'%'",
")",
"raise",
"\"The type '#{token}' in expression '#{expression}' \"",
"+",
"\"must be either 'items' or '%'\"",
"end",
"if",
"(",
"tokens",
"[",
"0",
"]",
"=~",
"/",
"/i",
")",
"operator",
"=",
"30",
"else",
"operator",
"=",
"32",
"end",
"if",
"(",
"tokens",
"[",
"2",
"]",
"==",
"'%'",
")",
"operator",
"+=",
"1",
"end",
"token",
"=",
"value",
"end",
"if",
"(",
"not",
"operator",
"and",
"tokens",
"[",
"0",
"]",
")",
"raise",
"\"Token '#{tokens[1]}' is not a valid operator \"",
"+",
"\"in filter expression '#{expression}'\"",
"end",
"# Special handling for Blanks/NonBlanks.",
"if",
"(",
"token",
"=~",
"/",
"/i",
")",
"# Only allow Equals or NotEqual in this context.",
"if",
"(",
"operator",
"!=",
"2",
"and",
"operator",
"!=",
"5",
")",
"raise",
"\"The operator '#{tokens[1]}' in expression '#{expression}' \"",
"+",
"\"is not valid in relation to Blanks/NonBlanks'\"",
"end",
"token",
".",
"downcase!",
"# The operator should always be 2 (=) to flag a \"simple\" equality in",
"# the binary record. Therefore we convert <> to =.",
"if",
"token",
"==",
"'blanks'",
"if",
"operator",
"==",
"5",
"token",
"=",
"' '",
"end",
"else",
"if",
"operator",
"==",
"5",
"operator",
"=",
"2",
"token",
"=",
"'blanks'",
"else",
"operator",
"=",
"5",
"token",
"=",
"' '",
"end",
"end",
"end",
"# if the string token contains an Excel match character then change the",
"# operator type to indicate a non \"simple\" equality.",
"if",
"(",
"operator",
"==",
"2",
"and",
"token",
"=~",
"/",
"/",
")",
"operator",
"=",
"22",
"end",
"[",
"operator",
",",
"token",
"]",
"end"
] | Parse the 3 tokens of a filter expression and return the operator and token. | [
"Parse",
"the",
"3",
"tokens",
"of",
"a",
"filter",
"expression",
"and",
"return",
"the",
"operator",
"and",
"token",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6078-L6164 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.position_object_emus | def position_object_emus(col_start, row_start, x1, y1, width, height, x_dpi = 96, y_dpi = 96) #:nodoc:
col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs =
position_object_pixels(col_start, row_start, x1, y1, width, height)
# Convert the pixel values to EMUs. See above.
x1 = (0.5 + 9_525 * x1).to_i
y1 = (0.5 + 9_525 * y1).to_i
x2 = (0.5 + 9_525 * x2).to_i
y2 = (0.5 + 9_525 * y2).to_i
x_abs = (0.5 + 9_525 * x_abs).to_i
y_abs = (0.5 + 9_525 * y_abs).to_i
[col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs]
end | ruby | def position_object_emus(col_start, row_start, x1, y1, width, height, x_dpi = 96, y_dpi = 96) #:nodoc:
col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs =
position_object_pixels(col_start, row_start, x1, y1, width, height)
# Convert the pixel values to EMUs. See above.
x1 = (0.5 + 9_525 * x1).to_i
y1 = (0.5 + 9_525 * y1).to_i
x2 = (0.5 + 9_525 * x2).to_i
y2 = (0.5 + 9_525 * y2).to_i
x_abs = (0.5 + 9_525 * x_abs).to_i
y_abs = (0.5 + 9_525 * y_abs).to_i
[col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs]
end | [
"def",
"position_object_emus",
"(",
"col_start",
",",
"row_start",
",",
"x1",
",",
"y1",
",",
"width",
",",
"height",
",",
"x_dpi",
"=",
"96",
",",
"y_dpi",
"=",
"96",
")",
"#:nodoc:",
"col_start",
",",
"row_start",
",",
"x1",
",",
"y1",
",",
"col_end",
",",
"row_end",
",",
"x2",
",",
"y2",
",",
"x_abs",
",",
"y_abs",
"=",
"position_object_pixels",
"(",
"col_start",
",",
"row_start",
",",
"x1",
",",
"y1",
",",
"width",
",",
"height",
")",
"# Convert the pixel values to EMUs. See above.",
"x1",
"=",
"(",
"0.5",
"+",
"9_525",
"*",
"x1",
")",
".",
"to_i",
"y1",
"=",
"(",
"0.5",
"+",
"9_525",
"*",
"y1",
")",
".",
"to_i",
"x2",
"=",
"(",
"0.5",
"+",
"9_525",
"*",
"x2",
")",
".",
"to_i",
"y2",
"=",
"(",
"0.5",
"+",
"9_525",
"*",
"y2",
")",
".",
"to_i",
"x_abs",
"=",
"(",
"0.5",
"+",
"9_525",
"*",
"x_abs",
")",
".",
"to_i",
"y_abs",
"=",
"(",
"0.5",
"+",
"9_525",
"*",
"y_abs",
")",
".",
"to_i",
"[",
"col_start",
",",
"row_start",
",",
"x1",
",",
"y1",
",",
"col_end",
",",
"row_end",
",",
"x2",
",",
"y2",
",",
"x_abs",
",",
"y_abs",
"]",
"end"
] | Calculate the vertices that define the position of a graphical object within
the worksheet in EMUs.
The vertices are expressed as English Metric Units (EMUs). There are 12,700
EMUs per point. Therefore, 12,700 * 3 /4 = 9,525 EMUs per pixel. | [
"Calculate",
"the",
"vertices",
"that",
"define",
"the",
"position",
"of",
"a",
"graphical",
"object",
"within",
"the",
"worksheet",
"in",
"EMUs",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6212-L6225 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.size_col | def size_col(col) #:nodoc:
# Look up the cell value to see if it has been changed.
if @col_sizes[col]
width = @col_sizes[col]
# Convert to pixels.
if width == 0
pixels = 0
elsif width < 1
pixels = (width * (MAX_DIGIT_WIDTH + PADDING) + 0.5).to_i
else
pixels = (width * MAX_DIGIT_WIDTH + 0.5).to_i + PADDING
end
else
pixels = @default_col_pixels
end
pixels
end | ruby | def size_col(col) #:nodoc:
# Look up the cell value to see if it has been changed.
if @col_sizes[col]
width = @col_sizes[col]
# Convert to pixels.
if width == 0
pixels = 0
elsif width < 1
pixels = (width * (MAX_DIGIT_WIDTH + PADDING) + 0.5).to_i
else
pixels = (width * MAX_DIGIT_WIDTH + 0.5).to_i + PADDING
end
else
pixels = @default_col_pixels
end
pixels
end | [
"def",
"size_col",
"(",
"col",
")",
"#:nodoc:",
"# Look up the cell value to see if it has been changed.",
"if",
"@col_sizes",
"[",
"col",
"]",
"width",
"=",
"@col_sizes",
"[",
"col",
"]",
"# Convert to pixels.",
"if",
"width",
"==",
"0",
"pixels",
"=",
"0",
"elsif",
"width",
"<",
"1",
"pixels",
"=",
"(",
"width",
"*",
"(",
"MAX_DIGIT_WIDTH",
"+",
"PADDING",
")",
"+",
"0.5",
")",
".",
"to_i",
"else",
"pixels",
"=",
"(",
"width",
"*",
"MAX_DIGIT_WIDTH",
"+",
"0.5",
")",
".",
"to_i",
"+",
"PADDING",
"end",
"else",
"pixels",
"=",
"@default_col_pixels",
"end",
"pixels",
"end"
] | Convert the width of a cell from user's units to pixels. Excel rounds the
column width to the nearest pixel. If the width hasn't been set by the user
we use the default value. If the column is hidden it has a value of zero. | [
"Convert",
"the",
"width",
"of",
"a",
"cell",
"from",
"user",
"s",
"units",
"to",
"pixels",
".",
"Excel",
"rounds",
"the",
"column",
"width",
"to",
"the",
"nearest",
"pixel",
".",
"If",
"the",
"width",
"hasn",
"t",
"been",
"set",
"by",
"the",
"user",
"we",
"use",
"the",
"default",
"value",
".",
"If",
"the",
"column",
"is",
"hidden",
"it",
"has",
"a",
"value",
"of",
"zero",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6232-L6249 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.size_row | def size_row(row) #:nodoc:
# Look up the cell value to see if it has been changed
if @row_sizes[row]
height = @row_sizes[row]
if height == 0
pixels = 0
else
pixels = (4 / 3.0 * height).to_i
end
else
pixels = (4 / 3.0 * @default_row_height).to_i
end
pixels
end | ruby | def size_row(row) #:nodoc:
# Look up the cell value to see if it has been changed
if @row_sizes[row]
height = @row_sizes[row]
if height == 0
pixels = 0
else
pixels = (4 / 3.0 * height).to_i
end
else
pixels = (4 / 3.0 * @default_row_height).to_i
end
pixels
end | [
"def",
"size_row",
"(",
"row",
")",
"#:nodoc:",
"# Look up the cell value to see if it has been changed",
"if",
"@row_sizes",
"[",
"row",
"]",
"height",
"=",
"@row_sizes",
"[",
"row",
"]",
"if",
"height",
"==",
"0",
"pixels",
"=",
"0",
"else",
"pixels",
"=",
"(",
"4",
"/",
"3.0",
"*",
"height",
")",
".",
"to_i",
"end",
"else",
"pixels",
"=",
"(",
"4",
"/",
"3.0",
"*",
"@default_row_height",
")",
".",
"to_i",
"end",
"pixels",
"end"
] | Convert the height of a cell from user's units to pixels. If the height
hasn't been set by the user we use the default value. If the row is hidden
it has a value of zero. | [
"Convert",
"the",
"height",
"of",
"a",
"cell",
"from",
"user",
"s",
"units",
"to",
"pixels",
".",
"If",
"the",
"height",
"hasn",
"t",
"been",
"set",
"by",
"the",
"user",
"we",
"use",
"the",
"default",
"value",
".",
"If",
"the",
"row",
"is",
"hidden",
"it",
"has",
"a",
"value",
"of",
"zero",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6256-L6270 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.prepare_shape | def prepare_shape(index, drawing_id)
shape = @shapes[index]
# Create a Drawing object to use with worksheet unless one already exists.
unless drawing?
@drawing = Drawing.new
@drawing.embedded = 1
@external_drawing_links << ['/drawing', "../drawings/drawing#{drawing_id}.xml"]
@has_shapes = true
end
# Validate the he shape against various rules.
shape.validate(index)
shape.calc_position_emus(self)
drawing_type = 3
drawing.add_drawing_object(drawing_type, shape.dimensions, shape.name, shape)
end | ruby | def prepare_shape(index, drawing_id)
shape = @shapes[index]
# Create a Drawing object to use with worksheet unless one already exists.
unless drawing?
@drawing = Drawing.new
@drawing.embedded = 1
@external_drawing_links << ['/drawing', "../drawings/drawing#{drawing_id}.xml"]
@has_shapes = true
end
# Validate the he shape against various rules.
shape.validate(index)
shape.calc_position_emus(self)
drawing_type = 3
drawing.add_drawing_object(drawing_type, shape.dimensions, shape.name, shape)
end | [
"def",
"prepare_shape",
"(",
"index",
",",
"drawing_id",
")",
"shape",
"=",
"@shapes",
"[",
"index",
"]",
"# Create a Drawing object to use with worksheet unless one already exists.",
"unless",
"drawing?",
"@drawing",
"=",
"Drawing",
".",
"new",
"@drawing",
".",
"embedded",
"=",
"1",
"@external_drawing_links",
"<<",
"[",
"'/drawing'",
",",
"\"../drawings/drawing#{drawing_id}.xml\"",
"]",
"@has_shapes",
"=",
"true",
"end",
"# Validate the he shape against various rules.",
"shape",
".",
"validate",
"(",
"index",
")",
"shape",
".",
"calc_position_emus",
"(",
"self",
")",
"drawing_type",
"=",
"3",
"drawing",
".",
"add_drawing_object",
"(",
"drawing_type",
",",
"shape",
".",
"dimensions",
",",
"shape",
".",
"name",
",",
"shape",
")",
"end"
] | Set up drawing shapes | [
"Set",
"up",
"drawing",
"shapes"
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6410-L6427 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.button_params | def button_params(row, col, params)
button = Writexlsx::Package::Button.new
button_number = 1 + @buttons_array.size
# Set the button caption.
caption = params[:caption] || "Button #{button_number}"
button.font = { :_caption => caption }
# Set the macro name.
if params[:macro]
button.macro = "[0]!#{params[:macro]}"
else
button.macro = "[0]!Button#{button_number}_Click"
end
# Ensure that a width and height have been set.
default_width = @default_col_pixels
default_height = @default_row_pixels
params[:width] = default_width if !params[:width]
params[:height] = default_height if !params[:height]
# Set the x/y offsets.
params[:x_offset] = 0 if !params[:x_offset]
params[:y_offset] = 0 if !params[:y_offset]
# Scale the size of the comment box if required.
if params[:x_scale]
params[:width] = params[:width] * params[:x_scale]
end
if params[:y_scale]
params[:height] = params[:height] * params[:y_scale]
end
# Round the dimensions to the nearest pixel.
params[:width] = (0.5 + params[:width]).to_i
params[:height] = (0.5 + params[:height]).to_i
params[:start_row] = row
params[:start_col] = col
# Calculate the positions of comment object.
vertices = position_object_pixels(
params[:start_col],
params[:start_row],
params[:x_offset],
params[:y_offset],
params[:width],
params[:height]
)
# Add the width and height for VML.
vertices << [params[:width], params[:height]]
button.vertices = vertices
button
end | ruby | def button_params(row, col, params)
button = Writexlsx::Package::Button.new
button_number = 1 + @buttons_array.size
# Set the button caption.
caption = params[:caption] || "Button #{button_number}"
button.font = { :_caption => caption }
# Set the macro name.
if params[:macro]
button.macro = "[0]!#{params[:macro]}"
else
button.macro = "[0]!Button#{button_number}_Click"
end
# Ensure that a width and height have been set.
default_width = @default_col_pixels
default_height = @default_row_pixels
params[:width] = default_width if !params[:width]
params[:height] = default_height if !params[:height]
# Set the x/y offsets.
params[:x_offset] = 0 if !params[:x_offset]
params[:y_offset] = 0 if !params[:y_offset]
# Scale the size of the comment box if required.
if params[:x_scale]
params[:width] = params[:width] * params[:x_scale]
end
if params[:y_scale]
params[:height] = params[:height] * params[:y_scale]
end
# Round the dimensions to the nearest pixel.
params[:width] = (0.5 + params[:width]).to_i
params[:height] = (0.5 + params[:height]).to_i
params[:start_row] = row
params[:start_col] = col
# Calculate the positions of comment object.
vertices = position_object_pixels(
params[:start_col],
params[:start_row],
params[:x_offset],
params[:y_offset],
params[:width],
params[:height]
)
# Add the width and height for VML.
vertices << [params[:width], params[:height]]
button.vertices = vertices
button
end | [
"def",
"button_params",
"(",
"row",
",",
"col",
",",
"params",
")",
"button",
"=",
"Writexlsx",
"::",
"Package",
"::",
"Button",
".",
"new",
"button_number",
"=",
"1",
"+",
"@buttons_array",
".",
"size",
"# Set the button caption.",
"caption",
"=",
"params",
"[",
":caption",
"]",
"||",
"\"Button #{button_number}\"",
"button",
".",
"font",
"=",
"{",
":_caption",
"=>",
"caption",
"}",
"# Set the macro name.",
"if",
"params",
"[",
":macro",
"]",
"button",
".",
"macro",
"=",
"\"[0]!#{params[:macro]}\"",
"else",
"button",
".",
"macro",
"=",
"\"[0]!Button#{button_number}_Click\"",
"end",
"# Ensure that a width and height have been set.",
"default_width",
"=",
"@default_col_pixels",
"default_height",
"=",
"@default_row_pixels",
"params",
"[",
":width",
"]",
"=",
"default_width",
"if",
"!",
"params",
"[",
":width",
"]",
"params",
"[",
":height",
"]",
"=",
"default_height",
"if",
"!",
"params",
"[",
":height",
"]",
"# Set the x/y offsets.",
"params",
"[",
":x_offset",
"]",
"=",
"0",
"if",
"!",
"params",
"[",
":x_offset",
"]",
"params",
"[",
":y_offset",
"]",
"=",
"0",
"if",
"!",
"params",
"[",
":y_offset",
"]",
"# Scale the size of the comment box if required.",
"if",
"params",
"[",
":x_scale",
"]",
"params",
"[",
":width",
"]",
"=",
"params",
"[",
":width",
"]",
"*",
"params",
"[",
":x_scale",
"]",
"end",
"if",
"params",
"[",
":y_scale",
"]",
"params",
"[",
":height",
"]",
"=",
"params",
"[",
":height",
"]",
"*",
"params",
"[",
":y_scale",
"]",
"end",
"# Round the dimensions to the nearest pixel.",
"params",
"[",
":width",
"]",
"=",
"(",
"0.5",
"+",
"params",
"[",
":width",
"]",
")",
".",
"to_i",
"params",
"[",
":height",
"]",
"=",
"(",
"0.5",
"+",
"params",
"[",
":height",
"]",
")",
".",
"to_i",
"params",
"[",
":start_row",
"]",
"=",
"row",
"params",
"[",
":start_col",
"]",
"=",
"col",
"# Calculate the positions of comment object.",
"vertices",
"=",
"position_object_pixels",
"(",
"params",
"[",
":start_col",
"]",
",",
"params",
"[",
":start_row",
"]",
",",
"params",
"[",
":x_offset",
"]",
",",
"params",
"[",
":y_offset",
"]",
",",
"params",
"[",
":width",
"]",
",",
"params",
"[",
":height",
"]",
")",
"# Add the width and height for VML.",
"vertices",
"<<",
"[",
"params",
"[",
":width",
"]",
",",
"params",
"[",
":height",
"]",
"]",
"button",
".",
"vertices",
"=",
"vertices",
"button",
"end"
] | This method handles the parameters passed to insert_button as well as
calculating the comment object position and vertices. | [
"This",
"method",
"handles",
"the",
"parameters",
"passed",
"to",
"insert_button",
"as",
"well",
"as",
"calculating",
"the",
"comment",
"object",
"position",
"and",
"vertices",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6434-L6492 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.write_rows | def write_rows #:nodoc:
calculate_spans
(@dim_rowmin .. @dim_rowmax).each do |row_num|
# Skip row if it doesn't contain row formatting or cell data.
next if not_contain_formatting_or_data?(row_num)
span_index = row_num / 16
span = @row_spans[span_index]
# Write the cells if the row contains data.
if @cell_data_table[row_num]
args = @set_rows[row_num] || []
write_row_element(row_num, span, *args) do
write_cell_column_dimension(row_num)
end
elsif @comments[row_num]
write_empty_row(row_num, span, *(@set_rows[row_num]))
else
# Row attributes only.
write_empty_row(row_num, span, *(@set_rows[row_num]))
end
end
end | ruby | def write_rows #:nodoc:
calculate_spans
(@dim_rowmin .. @dim_rowmax).each do |row_num|
# Skip row if it doesn't contain row formatting or cell data.
next if not_contain_formatting_or_data?(row_num)
span_index = row_num / 16
span = @row_spans[span_index]
# Write the cells if the row contains data.
if @cell_data_table[row_num]
args = @set_rows[row_num] || []
write_row_element(row_num, span, *args) do
write_cell_column_dimension(row_num)
end
elsif @comments[row_num]
write_empty_row(row_num, span, *(@set_rows[row_num]))
else
# Row attributes only.
write_empty_row(row_num, span, *(@set_rows[row_num]))
end
end
end | [
"def",
"write_rows",
"#:nodoc:",
"calculate_spans",
"(",
"@dim_rowmin",
"..",
"@dim_rowmax",
")",
".",
"each",
"do",
"|",
"row_num",
"|",
"# Skip row if it doesn't contain row formatting or cell data.",
"next",
"if",
"not_contain_formatting_or_data?",
"(",
"row_num",
")",
"span_index",
"=",
"row_num",
"/",
"16",
"span",
"=",
"@row_spans",
"[",
"span_index",
"]",
"# Write the cells if the row contains data.",
"if",
"@cell_data_table",
"[",
"row_num",
"]",
"args",
"=",
"@set_rows",
"[",
"row_num",
"]",
"||",
"[",
"]",
"write_row_element",
"(",
"row_num",
",",
"span",
",",
"args",
")",
"do",
"write_cell_column_dimension",
"(",
"row_num",
")",
"end",
"elsif",
"@comments",
"[",
"row_num",
"]",
"write_empty_row",
"(",
"row_num",
",",
"span",
",",
"(",
"@set_rows",
"[",
"row_num",
"]",
")",
")",
"else",
"# Row attributes only.",
"write_empty_row",
"(",
"row_num",
",",
"span",
",",
"(",
"@set_rows",
"[",
"row_num",
"]",
")",
")",
"end",
"end",
"end"
] | Write out the worksheet data as a series of rows and cells. | [
"Write",
"out",
"the",
"worksheet",
"data",
"as",
"a",
"series",
"of",
"rows",
"and",
"cells",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6761-L6784 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.calculate_x_split_width | def calculate_x_split_width(width) #:nodoc:
# Convert to pixels.
if width < 1
pixels = int(width * 12 + 0.5)
else
pixels = (width * MAX_DIGIT_WIDTH + 0.5).to_i + PADDING
end
# Convert to points.
points = pixels * 3 / 4
# Convert to twips (twentieths of a point).
twips = points * 20
# Add offset/padding.
twips + 390
end | ruby | def calculate_x_split_width(width) #:nodoc:
# Convert to pixels.
if width < 1
pixels = int(width * 12 + 0.5)
else
pixels = (width * MAX_DIGIT_WIDTH + 0.5).to_i + PADDING
end
# Convert to points.
points = pixels * 3 / 4
# Convert to twips (twentieths of a point).
twips = points * 20
# Add offset/padding.
twips + 390
end | [
"def",
"calculate_x_split_width",
"(",
"width",
")",
"#:nodoc:",
"# Convert to pixels.",
"if",
"width",
"<",
"1",
"pixels",
"=",
"int",
"(",
"width",
"*",
"12",
"+",
"0.5",
")",
"else",
"pixels",
"=",
"(",
"width",
"*",
"MAX_DIGIT_WIDTH",
"+",
"0.5",
")",
".",
"to_i",
"+",
"PADDING",
"end",
"# Convert to points.",
"points",
"=",
"pixels",
"*",
"3",
"/",
"4",
"# Convert to twips (twentieths of a point).",
"twips",
"=",
"points",
"*",
"20",
"# Add offset/padding.",
"twips",
"+",
"390",
"end"
] | Convert column width from user units to pane split width. | [
"Convert",
"column",
"width",
"from",
"user",
"units",
"to",
"pane",
"split",
"width",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L6937-L6953 | train |
cxn03651/write_xlsx | lib/write_xlsx/worksheet.rb | Writexlsx.Worksheet.write_autofilters | def write_autofilters #:nodoc:
col1, col2 = @filter_range
(col1 .. col2).each do |col|
# Skip if column doesn't have an active filter.
next unless @filter_cols[col]
# Retrieve the filter tokens and write the autofilter records.
tokens = @filter_cols[col]
type = @filter_type[col]
# Filters are relative to first column in the autofilter.
write_filter_column(col - col1, type, *tokens)
end
end | ruby | def write_autofilters #:nodoc:
col1, col2 = @filter_range
(col1 .. col2).each do |col|
# Skip if column doesn't have an active filter.
next unless @filter_cols[col]
# Retrieve the filter tokens and write the autofilter records.
tokens = @filter_cols[col]
type = @filter_type[col]
# Filters are relative to first column in the autofilter.
write_filter_column(col - col1, type, *tokens)
end
end | [
"def",
"write_autofilters",
"#:nodoc:",
"col1",
",",
"col2",
"=",
"@filter_range",
"(",
"col1",
"..",
"col2",
")",
".",
"each",
"do",
"|",
"col",
"|",
"# Skip if column doesn't have an active filter.",
"next",
"unless",
"@filter_cols",
"[",
"col",
"]",
"# Retrieve the filter tokens and write the autofilter records.",
"tokens",
"=",
"@filter_cols",
"[",
"col",
"]",
"type",
"=",
"@filter_type",
"[",
"col",
"]",
"# Filters are relative to first column in the autofilter.",
"write_filter_column",
"(",
"col",
"-",
"col1",
",",
"type",
",",
"tokens",
")",
"end",
"end"
] | Function to iterate through the columns that form part of an autofilter
range and write the appropriate filters. | [
"Function",
"to",
"iterate",
"through",
"the",
"columns",
"that",
"form",
"part",
"of",
"an",
"autofilter",
"range",
"and",
"write",
"the",
"appropriate",
"filters",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/worksheet.rb#L7108-L7122 | train |
cxn03651/write_xlsx | lib/write_xlsx/shape.rb | Writexlsx.Shape.calc_position_emus | def calc_position_emus(worksheet)
c_start, r_start, xx1, yy1, c_end, r_end, xx2, yy2, x_abslt, y_abslt =
worksheet.position_object_pixels(
@column_start,
@row_start,
@x_offset,
@y_offset,
@width * @scale_x,
@height * @scale_y
)
# Now that x2/y2 have been calculated with a potentially negative
# width/height we use the absolute value and convert to EMUs.
@width_emu = (@width * 9_525).abs.to_i
@height_emu = (@height * 9_525).abs.to_i
@column_start = c_start.to_i
@row_start = r_start.to_i
@column_end = c_end.to_i
@row_end = r_end.to_i
# Convert the pixel values to EMUs. See above.
@x1 = (xx1 * 9_525).to_i
@y1 = (yy1 * 9_525).to_i
@x2 = (xx2 * 9_525).to_i
@y2 = (yy2 * 9_525).to_i
@x_abs = (x_abslt * 9_525).to_i
@y_abs = (y_abslt * 9_525).to_i
end | ruby | def calc_position_emus(worksheet)
c_start, r_start, xx1, yy1, c_end, r_end, xx2, yy2, x_abslt, y_abslt =
worksheet.position_object_pixels(
@column_start,
@row_start,
@x_offset,
@y_offset,
@width * @scale_x,
@height * @scale_y
)
# Now that x2/y2 have been calculated with a potentially negative
# width/height we use the absolute value and convert to EMUs.
@width_emu = (@width * 9_525).abs.to_i
@height_emu = (@height * 9_525).abs.to_i
@column_start = c_start.to_i
@row_start = r_start.to_i
@column_end = c_end.to_i
@row_end = r_end.to_i
# Convert the pixel values to EMUs. See above.
@x1 = (xx1 * 9_525).to_i
@y1 = (yy1 * 9_525).to_i
@x2 = (xx2 * 9_525).to_i
@y2 = (yy2 * 9_525).to_i
@x_abs = (x_abslt * 9_525).to_i
@y_abs = (y_abslt * 9_525).to_i
end | [
"def",
"calc_position_emus",
"(",
"worksheet",
")",
"c_start",
",",
"r_start",
",",
"xx1",
",",
"yy1",
",",
"c_end",
",",
"r_end",
",",
"xx2",
",",
"yy2",
",",
"x_abslt",
",",
"y_abslt",
"=",
"worksheet",
".",
"position_object_pixels",
"(",
"@column_start",
",",
"@row_start",
",",
"@x_offset",
",",
"@y_offset",
",",
"@width",
"*",
"@scale_x",
",",
"@height",
"*",
"@scale_y",
")",
"# Now that x2/y2 have been calculated with a potentially negative",
"# width/height we use the absolute value and convert to EMUs.",
"@width_emu",
"=",
"(",
"@width",
"*",
"9_525",
")",
".",
"abs",
".",
"to_i",
"@height_emu",
"=",
"(",
"@height",
"*",
"9_525",
")",
".",
"abs",
".",
"to_i",
"@column_start",
"=",
"c_start",
".",
"to_i",
"@row_start",
"=",
"r_start",
".",
"to_i",
"@column_end",
"=",
"c_end",
".",
"to_i",
"@row_end",
"=",
"r_end",
".",
"to_i",
"# Convert the pixel values to EMUs. See above.",
"@x1",
"=",
"(",
"xx1",
"*",
"9_525",
")",
".",
"to_i",
"@y1",
"=",
"(",
"yy1",
"*",
"9_525",
")",
".",
"to_i",
"@x2",
"=",
"(",
"xx2",
"*",
"9_525",
")",
".",
"to_i",
"@y2",
"=",
"(",
"yy2",
"*",
"9_525",
")",
".",
"to_i",
"@x_abs",
"=",
"(",
"x_abslt",
"*",
"9_525",
")",
".",
"to_i",
"@y_abs",
"=",
"(",
"y_abslt",
"*",
"9_525",
")",
".",
"to_i",
"end"
] | Calculate the vertices that define the position of a shape object within
the worksheet in EMUs. Save the vertices with the object.
The vertices are expressed as English Metric Units (EMUs). There are 12,700
EMUs per point. Therefore, 12,700 * 3 /4 = 9,525 EMUs per pixel. | [
"Calculate",
"the",
"vertices",
"that",
"define",
"the",
"position",
"of",
"a",
"shape",
"object",
"within",
"the",
"worksheet",
"in",
"EMUs",
".",
"Save",
"the",
"vertices",
"with",
"the",
"object",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/shape.rb#L156-L184 | train |
cxn03651/write_xlsx | lib/write_xlsx/shape.rb | Writexlsx.Shape.auto_locate_connectors | def auto_locate_connectors(shapes, shape_hash)
# Valid connector shapes.
connector_shapes = {
:straightConnector => 1,
:Connector => 1,
:bentConnector => 1,
:curvedConnector => 1,
:line => 1
}
shape_base = @type.chop.to_sym # Remove the number of segments from end of type.
@connect = connector_shapes[shape_base] ? 1 : 0
return if @connect == 0
# Both ends have to be connected to size it.
return if @start == 0 && @end == 0
# Both ends need to provide info about where to connect.
return if @start_side == 0 && @end_side == 0
sid = @start
eid = @end
slink_id = shape_hash[sid] || 0
sls = shapes.fetch(slink_id, Shape.new)
elink_id = shape_hash[eid] || 0
els = shapes.fetch(elink_id, Shape.new)
# Assume shape connections are to the middle of an object, and
# not a corner (for now).
connect_type = @start_side + @end_side
smidx = sls.x_offset + sls.width / 2
emidx = els.x_offset + els.width / 2
smidy = sls.y_offset + sls.height / 2
emidy = els.y_offset + els.height / 2
netx = (smidx - emidx).abs
nety = (smidy - emidy).abs
if connect_type == 'bt'
sy = sls.y_offset + sls.height
ey = els.y_offset
@width = (emidx - smidx).to_i.abs
@x_offset = [smidx, emidx].min.to_i
@height =
(els.y_offset - (sls.y_offset + sls.height)).to_i.abs
@y_offset =
[sls.y_offset + sls.height, els.y_offset].min.to_i
@flip_h = smidx < emidx ? 1 : 0
@rotation = 90
if sy > ey
@flip_v = 1
# Create 3 adjustments for an end shape vertically above a
# start @ Adjustments count from the upper left object.
if @adjustments.empty?
@adjustments = [-10, 50, 110]
end
@type = 'bentConnector5'
end
elsif connect_type == 'rl'
@width =
(els.x_offset - (sls.x_offset + sls.width)).to_i.abs
@height = (emidy - smidy).to_i.abs
@x_offset =
[sls.x_offset + sls.width, els.x_offset].min
@y_offset = [smidy, emidy].min
@flip_h = 1 if smidx < emidx && smidy > emidy
@flip_h = 1 if smidx > emidx && smidy < emidy
if smidx > emidx
# Create 3 adjustments for an end shape to the left of a
# start @
if @adjustments.empty?
@adjustments = [-10, 50, 110]
end
@type = 'bentConnector5'
end
end
end | ruby | def auto_locate_connectors(shapes, shape_hash)
# Valid connector shapes.
connector_shapes = {
:straightConnector => 1,
:Connector => 1,
:bentConnector => 1,
:curvedConnector => 1,
:line => 1
}
shape_base = @type.chop.to_sym # Remove the number of segments from end of type.
@connect = connector_shapes[shape_base] ? 1 : 0
return if @connect == 0
# Both ends have to be connected to size it.
return if @start == 0 && @end == 0
# Both ends need to provide info about where to connect.
return if @start_side == 0 && @end_side == 0
sid = @start
eid = @end
slink_id = shape_hash[sid] || 0
sls = shapes.fetch(slink_id, Shape.new)
elink_id = shape_hash[eid] || 0
els = shapes.fetch(elink_id, Shape.new)
# Assume shape connections are to the middle of an object, and
# not a corner (for now).
connect_type = @start_side + @end_side
smidx = sls.x_offset + sls.width / 2
emidx = els.x_offset + els.width / 2
smidy = sls.y_offset + sls.height / 2
emidy = els.y_offset + els.height / 2
netx = (smidx - emidx).abs
nety = (smidy - emidy).abs
if connect_type == 'bt'
sy = sls.y_offset + sls.height
ey = els.y_offset
@width = (emidx - smidx).to_i.abs
@x_offset = [smidx, emidx].min.to_i
@height =
(els.y_offset - (sls.y_offset + sls.height)).to_i.abs
@y_offset =
[sls.y_offset + sls.height, els.y_offset].min.to_i
@flip_h = smidx < emidx ? 1 : 0
@rotation = 90
if sy > ey
@flip_v = 1
# Create 3 adjustments for an end shape vertically above a
# start @ Adjustments count from the upper left object.
if @adjustments.empty?
@adjustments = [-10, 50, 110]
end
@type = 'bentConnector5'
end
elsif connect_type == 'rl'
@width =
(els.x_offset - (sls.x_offset + sls.width)).to_i.abs
@height = (emidy - smidy).to_i.abs
@x_offset =
[sls.x_offset + sls.width, els.x_offset].min
@y_offset = [smidy, emidy].min
@flip_h = 1 if smidx < emidx && smidy > emidy
@flip_h = 1 if smidx > emidx && smidy < emidy
if smidx > emidx
# Create 3 adjustments for an end shape to the left of a
# start @
if @adjustments.empty?
@adjustments = [-10, 50, 110]
end
@type = 'bentConnector5'
end
end
end | [
"def",
"auto_locate_connectors",
"(",
"shapes",
",",
"shape_hash",
")",
"# Valid connector shapes.",
"connector_shapes",
"=",
"{",
":straightConnector",
"=>",
"1",
",",
":Connector",
"=>",
"1",
",",
":bentConnector",
"=>",
"1",
",",
":curvedConnector",
"=>",
"1",
",",
":line",
"=>",
"1",
"}",
"shape_base",
"=",
"@type",
".",
"chop",
".",
"to_sym",
"# Remove the number of segments from end of type.",
"@connect",
"=",
"connector_shapes",
"[",
"shape_base",
"]",
"?",
"1",
":",
"0",
"return",
"if",
"@connect",
"==",
"0",
"# Both ends have to be connected to size it.",
"return",
"if",
"@start",
"==",
"0",
"&&",
"@end",
"==",
"0",
"# Both ends need to provide info about where to connect.",
"return",
"if",
"@start_side",
"==",
"0",
"&&",
"@end_side",
"==",
"0",
"sid",
"=",
"@start",
"eid",
"=",
"@end",
"slink_id",
"=",
"shape_hash",
"[",
"sid",
"]",
"||",
"0",
"sls",
"=",
"shapes",
".",
"fetch",
"(",
"slink_id",
",",
"Shape",
".",
"new",
")",
"elink_id",
"=",
"shape_hash",
"[",
"eid",
"]",
"||",
"0",
"els",
"=",
"shapes",
".",
"fetch",
"(",
"elink_id",
",",
"Shape",
".",
"new",
")",
"# Assume shape connections are to the middle of an object, and",
"# not a corner (for now).",
"connect_type",
"=",
"@start_side",
"+",
"@end_side",
"smidx",
"=",
"sls",
".",
"x_offset",
"+",
"sls",
".",
"width",
"/",
"2",
"emidx",
"=",
"els",
".",
"x_offset",
"+",
"els",
".",
"width",
"/",
"2",
"smidy",
"=",
"sls",
".",
"y_offset",
"+",
"sls",
".",
"height",
"/",
"2",
"emidy",
"=",
"els",
".",
"y_offset",
"+",
"els",
".",
"height",
"/",
"2",
"netx",
"=",
"(",
"smidx",
"-",
"emidx",
")",
".",
"abs",
"nety",
"=",
"(",
"smidy",
"-",
"emidy",
")",
".",
"abs",
"if",
"connect_type",
"==",
"'bt'",
"sy",
"=",
"sls",
".",
"y_offset",
"+",
"sls",
".",
"height",
"ey",
"=",
"els",
".",
"y_offset",
"@width",
"=",
"(",
"emidx",
"-",
"smidx",
")",
".",
"to_i",
".",
"abs",
"@x_offset",
"=",
"[",
"smidx",
",",
"emidx",
"]",
".",
"min",
".",
"to_i",
"@height",
"=",
"(",
"els",
".",
"y_offset",
"-",
"(",
"sls",
".",
"y_offset",
"+",
"sls",
".",
"height",
")",
")",
".",
"to_i",
".",
"abs",
"@y_offset",
"=",
"[",
"sls",
".",
"y_offset",
"+",
"sls",
".",
"height",
",",
"els",
".",
"y_offset",
"]",
".",
"min",
".",
"to_i",
"@flip_h",
"=",
"smidx",
"<",
"emidx",
"?",
"1",
":",
"0",
"@rotation",
"=",
"90",
"if",
"sy",
">",
"ey",
"@flip_v",
"=",
"1",
"# Create 3 adjustments for an end shape vertically above a",
"# start @ Adjustments count from the upper left object.",
"if",
"@adjustments",
".",
"empty?",
"@adjustments",
"=",
"[",
"-",
"10",
",",
"50",
",",
"110",
"]",
"end",
"@type",
"=",
"'bentConnector5'",
"end",
"elsif",
"connect_type",
"==",
"'rl'",
"@width",
"=",
"(",
"els",
".",
"x_offset",
"-",
"(",
"sls",
".",
"x_offset",
"+",
"sls",
".",
"width",
")",
")",
".",
"to_i",
".",
"abs",
"@height",
"=",
"(",
"emidy",
"-",
"smidy",
")",
".",
"to_i",
".",
"abs",
"@x_offset",
"=",
"[",
"sls",
".",
"x_offset",
"+",
"sls",
".",
"width",
",",
"els",
".",
"x_offset",
"]",
".",
"min",
"@y_offset",
"=",
"[",
"smidy",
",",
"emidy",
"]",
".",
"min",
"@flip_h",
"=",
"1",
"if",
"smidx",
"<",
"emidx",
"&&",
"smidy",
">",
"emidy",
"@flip_h",
"=",
"1",
"if",
"smidx",
">",
"emidx",
"&&",
"smidy",
"<",
"emidy",
"if",
"smidx",
">",
"emidx",
"# Create 3 adjustments for an end shape to the left of a",
"# start @",
"if",
"@adjustments",
".",
"empty?",
"@adjustments",
"=",
"[",
"-",
"10",
",",
"50",
",",
"110",
"]",
"end",
"@type",
"=",
"'bentConnector5'",
"end",
"end",
"end"
] | Re-size connector shapes if they are connected to other shapes. | [
"Re",
"-",
"size",
"connector",
"shapes",
"if",
"they",
"are",
"connected",
"to",
"other",
"shapes",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/shape.rb#L201-L282 | train |
cxn03651/write_xlsx | lib/write_xlsx/shape.rb | Writexlsx.Shape.validate | def validate(index)
unless %w[l ctr r just].include?(@align)
raise "Shape #{index} (#{@type}) alignment (#{@align}) not in ['l', 'ctr', 'r', 'just']\n"
end
unless %w[t ctr b].include?(@valign)
raise "Shape #{index} (#{@type}) vertical alignment (#{@valign}) not in ['t', 'ctr', 'v']\n"
end
end | ruby | def validate(index)
unless %w[l ctr r just].include?(@align)
raise "Shape #{index} (#{@type}) alignment (#{@align}) not in ['l', 'ctr', 'r', 'just']\n"
end
unless %w[t ctr b].include?(@valign)
raise "Shape #{index} (#{@type}) vertical alignment (#{@valign}) not in ['t', 'ctr', 'v']\n"
end
end | [
"def",
"validate",
"(",
"index",
")",
"unless",
"%w[",
"l",
"ctr",
"r",
"just",
"]",
".",
"include?",
"(",
"@align",
")",
"raise",
"\"Shape #{index} (#{@type}) alignment (#{@align}) not in ['l', 'ctr', 'r', 'just']\\n\"",
"end",
"unless",
"%w[",
"t",
"ctr",
"b",
"]",
".",
"include?",
"(",
"@valign",
")",
"raise",
"\"Shape #{index} (#{@type}) vertical alignment (#{@valign}) not in ['t', 'ctr', 'v']\\n\"",
"end",
"end"
] | Check shape attributes to ensure they are valid. | [
"Check",
"shape",
"attributes",
"to",
"ensure",
"they",
"are",
"valid",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/shape.rb#L287-L295 | train |
cxn03651/write_xlsx | lib/write_xlsx/format.rb | Writexlsx.Format.copy | def copy(other)
reserve = [
:xf_index,
:dxf_index,
:xdf_format_indices,
:palette
]
(instance_variables - reserve).each do |v|
instance_variable_set(v, other.instance_variable_get(v))
end
end | ruby | def copy(other)
reserve = [
:xf_index,
:dxf_index,
:xdf_format_indices,
:palette
]
(instance_variables - reserve).each do |v|
instance_variable_set(v, other.instance_variable_get(v))
end
end | [
"def",
"copy",
"(",
"other",
")",
"reserve",
"=",
"[",
":xf_index",
",",
":dxf_index",
",",
":xdf_format_indices",
",",
":palette",
"]",
"(",
"instance_variables",
"-",
"reserve",
")",
".",
"each",
"do",
"|",
"v",
"|",
"instance_variable_set",
"(",
"v",
",",
"other",
".",
"instance_variable_get",
"(",
"v",
")",
")",
"end",
"end"
] | Copy the attributes of another Format object. | [
"Copy",
"the",
"attributes",
"of",
"another",
"Format",
"object",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/format.rb#L248-L258 | train |
cxn03651/write_xlsx | lib/write_xlsx/utility.rb | Writexlsx.Utility.layout_properties | def layout_properties(args, is_text = false)
return unless ptrue?(args)
properties = is_text ? [:x, :y] : [:x, :y, :width, :height]
# Check for valid properties.
args.keys.each do |key|
unless properties.include?(key.to_sym)
raise "Property '#{key}' not allowed in layout options\n"
end
end
# Set the layout properties
layout = Hash.new
properties.each do |property|
value = args[property]
# Convert to the format used by Excel for easier testing.
layout[property] = sprintf("%.17g", value)
end
layout
end | ruby | def layout_properties(args, is_text = false)
return unless ptrue?(args)
properties = is_text ? [:x, :y] : [:x, :y, :width, :height]
# Check for valid properties.
args.keys.each do |key|
unless properties.include?(key.to_sym)
raise "Property '#{key}' not allowed in layout options\n"
end
end
# Set the layout properties
layout = Hash.new
properties.each do |property|
value = args[property]
# Convert to the format used by Excel for easier testing.
layout[property] = sprintf("%.17g", value)
end
layout
end | [
"def",
"layout_properties",
"(",
"args",
",",
"is_text",
"=",
"false",
")",
"return",
"unless",
"ptrue?",
"(",
"args",
")",
"properties",
"=",
"is_text",
"?",
"[",
":x",
",",
":y",
"]",
":",
"[",
":x",
",",
":y",
",",
":width",
",",
":height",
"]",
"# Check for valid properties.",
"args",
".",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"unless",
"properties",
".",
"include?",
"(",
"key",
".",
"to_sym",
")",
"raise",
"\"Property '#{key}' not allowed in layout options\\n\"",
"end",
"end",
"# Set the layout properties",
"layout",
"=",
"Hash",
".",
"new",
"properties",
".",
"each",
"do",
"|",
"property",
"|",
"value",
"=",
"args",
"[",
"property",
"]",
"# Convert to the format used by Excel for easier testing.",
"layout",
"[",
"property",
"]",
"=",
"sprintf",
"(",
"\"%.17g\"",
",",
"value",
")",
"end",
"layout",
"end"
] | Convert user defined layout properties to the format required internally. | [
"Convert",
"user",
"defined",
"layout",
"properties",
"to",
"the",
"format",
"required",
"internally",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/utility.rb#L365-L386 | train |
cxn03651/write_xlsx | lib/write_xlsx/utility.rb | Writexlsx.Utility.pixels_to_points | def pixels_to_points(vertices)
col_start, row_start, x1, y1,
col_end, row_end, x2, y2,
left, top, width, height = vertices.flatten
left *= 0.75
top *= 0.75
width *= 0.75
height *= 0.75
[left, top, width, height]
end | ruby | def pixels_to_points(vertices)
col_start, row_start, x1, y1,
col_end, row_end, x2, y2,
left, top, width, height = vertices.flatten
left *= 0.75
top *= 0.75
width *= 0.75
height *= 0.75
[left, top, width, height]
end | [
"def",
"pixels_to_points",
"(",
"vertices",
")",
"col_start",
",",
"row_start",
",",
"x1",
",",
"y1",
",",
"col_end",
",",
"row_end",
",",
"x2",
",",
"y2",
",",
"left",
",",
"top",
",",
"width",
",",
"height",
"=",
"vertices",
".",
"flatten",
"left",
"*=",
"0.75",
"top",
"*=",
"0.75",
"width",
"*=",
"0.75",
"height",
"*=",
"0.75",
"[",
"left",
",",
"top",
",",
"width",
",",
"height",
"]",
"end"
] | Convert vertices from pixels to points. | [
"Convert",
"vertices",
"from",
"pixels",
"to",
"points",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/utility.rb#L391-L402 | train |
cxn03651/write_xlsx | lib/write_xlsx/sparkline.rb | Writexlsx.Sparkline.write_spark_color | def write_spark_color(element, color) # :nodoc:
attr = []
attr << ['rgb', color[:_rgb]] if color[:_rgb]
attr << ['theme', color[:_theme]] if color[:_theme]
attr << ['tint', color[:_tint]] if color[:_tint]
@writer.empty_tag(element, attr)
end | ruby | def write_spark_color(element, color) # :nodoc:
attr = []
attr << ['rgb', color[:_rgb]] if color[:_rgb]
attr << ['theme', color[:_theme]] if color[:_theme]
attr << ['tint', color[:_tint]] if color[:_tint]
@writer.empty_tag(element, attr)
end | [
"def",
"write_spark_color",
"(",
"element",
",",
"color",
")",
"# :nodoc:",
"attr",
"=",
"[",
"]",
"attr",
"<<",
"[",
"'rgb'",
",",
"color",
"[",
":_rgb",
"]",
"]",
"if",
"color",
"[",
":_rgb",
"]",
"attr",
"<<",
"[",
"'theme'",
",",
"color",
"[",
":_theme",
"]",
"]",
"if",
"color",
"[",
":_theme",
"]",
"attr",
"<<",
"[",
"'tint'",
",",
"color",
"[",
":_tint",
"]",
"]",
"if",
"color",
"[",
":_tint",
"]",
"@writer",
".",
"empty_tag",
"(",
"element",
",",
"attr",
")",
"end"
] | Helper function for the sparkline color functions below. | [
"Helper",
"function",
"for",
"the",
"sparkline",
"color",
"functions",
"below",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/sparkline.rb#L272-L280 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.assemble_xml_file | def assemble_xml_file #:nodoc:
return unless @writer
# Prepare format object for passing to Style.rb.
prepare_format_properties
write_xml_declaration do
# Write the root workbook element.
write_workbook do
# Write the XLSX file version.
write_file_version
# Write the workbook properties.
write_workbook_pr
# Write the workbook view properties.
write_book_views
# Write the worksheet names and ids.
@worksheets.write_sheets(@writer)
# Write the workbook defined names.
write_defined_names
# Write the workbook calculation properties.
write_calc_pr
# Write the workbook extension storage.
#write_ext_lst
end
end
end | ruby | def assemble_xml_file #:nodoc:
return unless @writer
# Prepare format object for passing to Style.rb.
prepare_format_properties
write_xml_declaration do
# Write the root workbook element.
write_workbook do
# Write the XLSX file version.
write_file_version
# Write the workbook properties.
write_workbook_pr
# Write the workbook view properties.
write_book_views
# Write the worksheet names and ids.
@worksheets.write_sheets(@writer)
# Write the workbook defined names.
write_defined_names
# Write the workbook calculation properties.
write_calc_pr
# Write the workbook extension storage.
#write_ext_lst
end
end
end | [
"def",
"assemble_xml_file",
"#:nodoc:",
"return",
"unless",
"@writer",
"# Prepare format object for passing to Style.rb.",
"prepare_format_properties",
"write_xml_declaration",
"do",
"# Write the root workbook element.",
"write_workbook",
"do",
"# Write the XLSX file version.",
"write_file_version",
"# Write the workbook properties.",
"write_workbook_pr",
"# Write the workbook view properties.",
"write_book_views",
"# Write the worksheet names and ids.",
"@worksheets",
".",
"write_sheets",
"(",
"@writer",
")",
"# Write the workbook defined names.",
"write_defined_names",
"# Write the workbook calculation properties.",
"write_calc_pr",
"# Write the workbook extension storage.",
"#write_ext_lst",
"end",
"end",
"end"
] | user must not use. it is internal method. | [
"user",
"must",
"not",
"use",
".",
"it",
"is",
"internal",
"method",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L257-L290 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.add_format | def add_format(property_hash = {})
properties = {}
if @excel2003_style
properties.update(:font => 'Arial', :size => 10, :theme => -1)
end
properties.update(property_hash)
format = Format.new(@formats, properties)
@formats.formats.push(format) # Store format reference
format
end | ruby | def add_format(property_hash = {})
properties = {}
if @excel2003_style
properties.update(:font => 'Arial', :size => 10, :theme => -1)
end
properties.update(property_hash)
format = Format.new(@formats, properties)
@formats.formats.push(format) # Store format reference
format
end | [
"def",
"add_format",
"(",
"property_hash",
"=",
"{",
"}",
")",
"properties",
"=",
"{",
"}",
"if",
"@excel2003_style",
"properties",
".",
"update",
"(",
":font",
"=>",
"'Arial'",
",",
":size",
"=>",
"10",
",",
":theme",
"=>",
"-",
"1",
")",
"end",
"properties",
".",
"update",
"(",
"property_hash",
")",
"format",
"=",
"Format",
".",
"new",
"(",
"@formats",
",",
"properties",
")",
"@formats",
".",
"formats",
".",
"push",
"(",
"format",
")",
"# Store format reference",
"format",
"end"
] | The +add_format+ method can be used to create new Format objects
which are used to apply formatting to a cell. You can either define
the properties at creation time via a hash of property values
or later via method calls.
format1 = workbook.add_format(property_hash) # Set properties at creation
format2 = workbook.add_format # Set properties later
See the {Format Class's rdoc}[Format.html] for more details about
Format properties and how to set them. | [
"The",
"+",
"add_format",
"+",
"method",
"can",
"be",
"used",
"to",
"create",
"new",
"Format",
"objects",
"which",
"are",
"used",
"to",
"apply",
"formatting",
"to",
"a",
"cell",
".",
"You",
"can",
"either",
"define",
"the",
"properties",
"at",
"creation",
"time",
"via",
"a",
"hash",
"of",
"property",
"values",
"or",
"later",
"via",
"method",
"calls",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L427-L439 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.add_shape | def add_shape(properties = {})
shape = Shape.new(properties)
shape.palette = @palette
@shapes ||= []
@shapes << shape #Store shape reference.
shape
end | ruby | def add_shape(properties = {})
shape = Shape.new(properties)
shape.palette = @palette
@shapes ||= []
@shapes << shape #Store shape reference.
shape
end | [
"def",
"add_shape",
"(",
"properties",
"=",
"{",
"}",
")",
"shape",
"=",
"Shape",
".",
"new",
"(",
"properties",
")",
"shape",
".",
"palette",
"=",
"@palette",
"@shapes",
"||=",
"[",
"]",
"@shapes",
"<<",
"shape",
"#Store shape reference.",
"shape",
"end"
] | The +add_shape+ method can be used to create new shapes that may be
inserted into a worksheet.
You can either define the properties at creation time via a hash of
property values or later via method calls.
# Set properties at creation.
plus = workbook.add_shape(
:type => 'plus',
:id => 3,
:width => pw,
:height => ph
)
# Default rectangle shape. Set properties later.
rect = workbook.add_shape
See also the shape*.rb programs in the examples directory of the distro.
=== Shape Properties
Any shape property can be queried or modified by [ ] like hash.
ellipse = workbook.add_shape(properties)
ellipse[:type] = 'cross' # No longer an ellipse !
type = ellipse[:type] # Find out what it really is.
The properties of a shape object that can be defined via add_shape are
shown below.
===:name
Defines the name of the shape. This is an optional property and the shape
will be given a default name if not supplied. The name is generally only
used by Excel Macros to refer to the object.
===:type
Defines the type of the object such as +:rect+, +:ellipse+ OR +:triangle+.
ellipse = workbook.add_shape(:type => :ellipse)
The default type is +:rect+.
The full list of available shapes is shown below.
See also the shape_all.rb program in the examples directory of the distro.
It creates an example workbook with all supported shapes labelled with
their shape names.
=== Basic Shapes
blockArc can chevron cube decagon
diamond dodecagon donut ellipse funnel
gear6 gear9 heart heptagon hexagon
homePlate lightningBolt line lineInv moon
nonIsoscelesTrapezoid noSmoking octagon parallelogram pentagon
pie pieWedge plaque rect round1Rect
round2DiagRect round2SameRect roundRect rtTriangle smileyFace
snip1Rect snip2DiagRect snip2SameRect snipRoundRect star10
star12 star16 star24 star32 star4
star5 star6 star7 star8 sun
teardrop trapezoid triangle
=== Arrow Shapes
bentArrow bentUpArrow circularArrow curvedDownArrow
curvedLeftArrow curvedRightArrow curvedUpArrow downArrow
leftArrow leftCircularArrow leftRightArrow leftRightCircularArrow
leftRightUpArrow leftUpArrow notchedRightArrow quadArrow
rightArrow stripedRightArrow swooshArrow upArrow
upDownArrow uturnArrow
=== Connector Shapes
bentConnector2 bentConnector3 bentConnector4
bentConnector5 curvedConnector2 curvedConnector3
curvedConnector4 curvedConnector5 straightConnector1
=== Callout Shapes
accentBorderCallout1 accentBorderCallout2 accentBorderCallout3
accentCallout1 accentCallout2 accentCallout3
borderCallout1 borderCallout2 borderCallout3
callout1 callout2 callout3
cloudCallout downArrowCallout leftArrowCallout
leftRightArrowCallout quadArrowCallout rightArrowCallout
upArrowCallout upDownArrowCallout wedgeEllipseCallout
wedgeRectCallout wedgeRoundRectCallout
=== Flow Chart Shapes
flowChartAlternateProcess flowChartCollate flowChartConnector
flowChartDecision flowChartDelay flowChartDisplay
flowChartDocument flowChartExtract flowChartInputOutput
flowChartInternalStorage flowChartMagneticDisk flowChartMagneticDrum
flowChartMagneticTape flowChartManualInput flowChartManualOperation
flowChartMerge flowChartMultidocument flowChartOfflineStorage
flowChartOffpageConnector flowChartOnlineStorage flowChartOr
flowChartPredefinedProcess flowChartPreparation flowChartProcess
flowChartPunchedCard flowChartPunchedTape flowChartSort
flowChartSummingJunction flowChartTerminator
=== Action Shapes
actionButtonBackPrevious actionButtonBeginning actionButtonBlank
actionButtonDocument actionButtonEnd actionButtonForwardNext
actionButtonHelp actionButtonHome actionButtonInformation
actionButtonMovie actionButtonReturn actionButtonSound
=== Chart Shapes
Not to be confused with Excel Charts.
chartPlus chartStar chartX
=== Math Shapes
mathDivide mathEqual mathMinus mathMultiply mathNotEqual mathPlus
=== Starts and Banners
arc bevel bracePair bracketPair chord
cloud corner diagStripe doubleWave ellipseRibbon
ellipseRibbon2 foldedCorner frame halfFrame horizontalScroll
irregularSeal1 irregularSeal2 leftBrace leftBracket leftRightRibbon
plus ribbon ribbon2 rightBrace rightBracket
verticalScroll wave
=== Tab Shapes
cornerTabs plaqueTabs squareTabs
=== :text
This property is used to make the shape act like a text box.
rect = workbook.add_shape(:type => 'rect', :text => "Hello \nWorld")
The Text is super-imposed over the shape. The text can be wrapped using
the newline character \n.
=== :id
Identification number for internal identification. This number will be
auto-assigned, if not assigned, or if it is a duplicate.
=== :format
Workbook format for decorating the shape horizontally and/or vertically.
=== :rotation
Shape rotation, in degrees, from 0 to 360
=== :line, :fill
Shape color for the outline and fill.
Colors may be specified as a color index, or in RGB format, i.e. AA00FF.
See COULOURS IN EXCEL in the main documentation for more information.
=== :link_type
Line type for shape outline. The default is solid.
The list of possible values is:
dash, sysDot, dashDot, lgDash, lgDashDot, lgDashDotDot, solid
=== :valign, :align
Text alignment within the shape.
Vertical alignment can be:
Setting Meaning
======= =======
t Top
ctr Centre
b Bottom
Horizontal alignment can be:
Setting Meaning
======= =======
l Left
r Right
ctr Centre
just Justified
The default is to center both horizontally and vertically.
=== :scale_x, :scale_y
Scale factor in x and y dimension, for scaling the shape width and
height. The default value is 1.
Scaling may be set on the shape object or via insert_shape.
=== :adjustments
Adjustment of shape vertices. Most shapes do not use this. For some
shapes, there is a single adjustment to modify the geometry.
For instance, the plus shape has one adjustment to control the width
of the spokes.
Connectors can have a number of adjustments to control the shape
routing. Typically, a connector will have 3 to 5 handles for routing
the shape. The adjustment is in percent of the distance from the
starting shape to the ending shape, alternating between the x and y
dimension. Adjustments may be negative, to route the shape away
from the endpoint.
=== :stencil
Shapes work in stencil mode by default. That is, once a shape is
inserted, its connection is separated from its master.
The master shape may be modified after an instance is inserted,
and only subsequent insertions will show the modifications.
This is helpful for Org charts, where an employee shape may be
created once, and then the text of the shape is modified for each
employee.
The insert_shape method returns a reference to the inserted
shape (the child).
Stencil mode can be turned off, allowing for shape(s) to be
modified after insertion. In this case the insert_shape() method
returns a reference to the inserted shape (the master).
This is not very useful for inserting multiple shapes,
since the x/y coordinates also gets modified. | [
"The",
"+",
"add_shape",
"+",
"method",
"can",
"be",
"used",
"to",
"create",
"new",
"shapes",
"that",
"may",
"be",
"inserted",
"into",
"a",
"worksheet",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L675-L682 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.set_properties | def set_properties(params)
# Ignore if no args were passed.
return -1 if params.empty?
# List of valid input parameters.
valid = {
:title => 1,
:subject => 1,
:author => 1,
:keywords => 1,
:comments => 1,
:last_author => 1,
:created => 1,
:category => 1,
:manager => 1,
:company => 1,
:status => 1
}
# Check for valid input parameters.
params.each_key do |key|
return -1 unless valid.has_key?(key)
end
# Set the creation time unless specified by the user.
params[:created] = @local_time unless params.has_key?(:created)
@doc_properties = params.dup
end | ruby | def set_properties(params)
# Ignore if no args were passed.
return -1 if params.empty?
# List of valid input parameters.
valid = {
:title => 1,
:subject => 1,
:author => 1,
:keywords => 1,
:comments => 1,
:last_author => 1,
:created => 1,
:category => 1,
:manager => 1,
:company => 1,
:status => 1
}
# Check for valid input parameters.
params.each_key do |key|
return -1 unless valid.has_key?(key)
end
# Set the creation time unless specified by the user.
params[:created] = @local_time unless params.has_key?(:created)
@doc_properties = params.dup
end | [
"def",
"set_properties",
"(",
"params",
")",
"# Ignore if no args were passed.",
"return",
"-",
"1",
"if",
"params",
".",
"empty?",
"# List of valid input parameters.",
"valid",
"=",
"{",
":title",
"=>",
"1",
",",
":subject",
"=>",
"1",
",",
":author",
"=>",
"1",
",",
":keywords",
"=>",
"1",
",",
":comments",
"=>",
"1",
",",
":last_author",
"=>",
"1",
",",
":created",
"=>",
"1",
",",
":category",
"=>",
"1",
",",
":manager",
"=>",
"1",
",",
":company",
"=>",
"1",
",",
":status",
"=>",
"1",
"}",
"# Check for valid input parameters.",
"params",
".",
"each_key",
"do",
"|",
"key",
"|",
"return",
"-",
"1",
"unless",
"valid",
".",
"has_key?",
"(",
"key",
")",
"end",
"# Set the creation time unless specified by the user.",
"params",
"[",
":created",
"]",
"=",
"@local_time",
"unless",
"params",
".",
"has_key?",
"(",
":created",
")",
"@doc_properties",
"=",
"params",
".",
"dup",
"end"
] | The set_properties method can be used to set the document properties
of the Excel file created by WriteXLSX. These properties are visible
when you use the Office Button -> Prepare -> Properties option in Excel
and are also available to external applications that read or index windows
files.
The properties should be passed in hash format as follows:
workbook.set_properties(
:title => 'This is an example spreadsheet',
:author => 'Hideo NAKAMURA',
:comments => 'Created with Ruby and WriteXLSX'
)
The properties that can be set are:
:title
:subject
:author
:manager
:company
:category
:keywords
:comments
:status
See also the properties.rb program in the examples directory
of the distro. | [
"The",
"set_properties",
"method",
"can",
"be",
"used",
"to",
"set",
"the",
"document",
"properties",
"of",
"the",
"Excel",
"file",
"created",
"by",
"WriteXLSX",
".",
"These",
"properties",
"are",
"visible",
"when",
"you",
"use",
"the",
"Office",
"Button",
"-",
">",
"Prepare",
"-",
">",
"Properties",
"option",
"in",
"Excel",
"and",
"are",
"also",
"available",
"to",
"external",
"applications",
"that",
"read",
"or",
"index",
"windows",
"files",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L782-L810 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.set_custom_color | def set_custom_color(index, red = 0, green = 0, blue = 0)
# Match a HTML #xxyyzz style parameter
if red =~ /^#(\w\w)(\w\w)(\w\w)/
red = $1.hex
green = $2.hex
blue = $3.hex
end
# Check that the colour index is the right range
if index < 8 || index > 64
raise "Color index #{index} outside range: 8 <= index <= 64"
end
# Check that the colour components are in the right range
if (red < 0 || red > 255) ||
(green < 0 || green > 255) ||
(blue < 0 || blue > 255)
raise "Color component outside range: 0 <= color <= 255"
end
index -=8 # Adjust colour index (wingless dragonfly)
# Set the RGB value
@palette[index] = [red, green, blue]
# Store the custome colors for the style.xml file.
@custom_colors << sprintf("FF%02X%02X%02X", red, green, blue)
index + 8
end | ruby | def set_custom_color(index, red = 0, green = 0, blue = 0)
# Match a HTML #xxyyzz style parameter
if red =~ /^#(\w\w)(\w\w)(\w\w)/
red = $1.hex
green = $2.hex
blue = $3.hex
end
# Check that the colour index is the right range
if index < 8 || index > 64
raise "Color index #{index} outside range: 8 <= index <= 64"
end
# Check that the colour components are in the right range
if (red < 0 || red > 255) ||
(green < 0 || green > 255) ||
(blue < 0 || blue > 255)
raise "Color component outside range: 0 <= color <= 255"
end
index -=8 # Adjust colour index (wingless dragonfly)
# Set the RGB value
@palette[index] = [red, green, blue]
# Store the custome colors for the style.xml file.
@custom_colors << sprintf("FF%02X%02X%02X", red, green, blue)
index + 8
end | [
"def",
"set_custom_color",
"(",
"index",
",",
"red",
"=",
"0",
",",
"green",
"=",
"0",
",",
"blue",
"=",
"0",
")",
"# Match a HTML #xxyyzz style parameter",
"if",
"red",
"=~",
"/",
"\\w",
"\\w",
"\\w",
"\\w",
"\\w",
"\\w",
"/",
"red",
"=",
"$1",
".",
"hex",
"green",
"=",
"$2",
".",
"hex",
"blue",
"=",
"$3",
".",
"hex",
"end",
"# Check that the colour index is the right range",
"if",
"index",
"<",
"8",
"||",
"index",
">",
"64",
"raise",
"\"Color index #{index} outside range: 8 <= index <= 64\"",
"end",
"# Check that the colour components are in the right range",
"if",
"(",
"red",
"<",
"0",
"||",
"red",
">",
"255",
")",
"||",
"(",
"green",
"<",
"0",
"||",
"green",
">",
"255",
")",
"||",
"(",
"blue",
"<",
"0",
"||",
"blue",
">",
"255",
")",
"raise",
"\"Color component outside range: 0 <= color <= 255\"",
"end",
"index",
"-=",
"8",
"# Adjust colour index (wingless dragonfly)",
"# Set the RGB value",
"@palette",
"[",
"index",
"]",
"=",
"[",
"red",
",",
"green",
",",
"blue",
"]",
"# Store the custome colors for the style.xml file.",
"@custom_colors",
"<<",
"sprintf",
"(",
"\"FF%02X%02X%02X\"",
",",
"red",
",",
"green",
",",
"blue",
")",
"index",
"+",
"8",
"end"
] | Change the RGB components of the elements in the colour palette.
The set_custom_color method can be used to override one of the built-in
palette values with a more suitable colour.
The value for +index+ should be in the range 8..63,
see "COLOURS IN EXCEL".
The default named colours use the following indices:
8 => black
9 => white
10 => red
11 => lime
12 => blue
13 => yellow
14 => magenta
15 => cyan
16 => brown
17 => green
18 => navy
20 => purple
22 => silver
23 => gray
33 => pink
53 => orange
A new colour is set using its RGB (red green blue) components. The +red+,
+green+ and +blue+ values must be in the range 0..255. You can determine
the required values in Excel using the Tools->Options->Colors->Modify
dialog.
The set_custom_color workbook method can also be used with a HTML style
+#rrggbb+ hex value:
workbook.set_custom_color(40, 255, 102, 0 ) # Orange
workbook.set_custom_color(40, 0xFF, 0x66, 0x00) # Same thing
workbook.set_custom_color(40, '#FF6600' ) # Same thing
font = workbook.add_format(:color => 40) # Use the modified colour
The return value from set_custom_color() is the index of the colour that
was changed:
ferrari = workbook.set_custom_color(40, 216, 12, 12)
format = workbook.add_format(
:bg_color => ferrari,
:pattern => 1,
:border => 1
)
Note, In the XLSX format the color palette isn't actually confined to 53
unique colors. The WriteXLSX gem will be extended at a later stage to
support the newer, semi-infinite, palette. | [
"Change",
"the",
"RGB",
"components",
"of",
"the",
"elements",
"in",
"the",
"colour",
"palette",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L927-L956 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.store_workbook | def store_workbook #:nodoc:
# Add a default worksheet if non have been added.
add_worksheet if @worksheets.empty?
# Ensure that at least one worksheet has been selected.
@worksheets.visible_first.select if @activesheet == 0
# Set the active sheet.
@activesheet = @worksheets.visible_first.index if @activesheet == 0
@worksheets[@activesheet].activate
# Prepare the worksheet VML elements such as comments and buttons.
prepare_vml_objects
# Set the defined names for the worksheets such as Print Titles.
prepare_defined_names
# Prepare the drawings, charts and images.
prepare_drawings
# Add cached data to charts.
add_chart_data
# Prepare the worksheet tables.
prepare_tables
# Package the workbook.
packager = Package::Packager.new(self)
packager.set_package_dir(tempdir)
packager.create_package
# Free up the Packager object.
packager = nil
# Store the xlsx component files with the temp dir name removed.
ZipFileUtils.zip("#{tempdir}", filename)
IO.copy_stream(filename, fileobj) if fileobj
Writexlsx::Utility.delete_files(tempdir)
end | ruby | def store_workbook #:nodoc:
# Add a default worksheet if non have been added.
add_worksheet if @worksheets.empty?
# Ensure that at least one worksheet has been selected.
@worksheets.visible_first.select if @activesheet == 0
# Set the active sheet.
@activesheet = @worksheets.visible_first.index if @activesheet == 0
@worksheets[@activesheet].activate
# Prepare the worksheet VML elements such as comments and buttons.
prepare_vml_objects
# Set the defined names for the worksheets such as Print Titles.
prepare_defined_names
# Prepare the drawings, charts and images.
prepare_drawings
# Add cached data to charts.
add_chart_data
# Prepare the worksheet tables.
prepare_tables
# Package the workbook.
packager = Package::Packager.new(self)
packager.set_package_dir(tempdir)
packager.create_package
# Free up the Packager object.
packager = nil
# Store the xlsx component files with the temp dir name removed.
ZipFileUtils.zip("#{tempdir}", filename)
IO.copy_stream(filename, fileobj) if fileobj
Writexlsx::Utility.delete_files(tempdir)
end | [
"def",
"store_workbook",
"#:nodoc:",
"# Add a default worksheet if non have been added.",
"add_worksheet",
"if",
"@worksheets",
".",
"empty?",
"# Ensure that at least one worksheet has been selected.",
"@worksheets",
".",
"visible_first",
".",
"select",
"if",
"@activesheet",
"==",
"0",
"# Set the active sheet.",
"@activesheet",
"=",
"@worksheets",
".",
"visible_first",
".",
"index",
"if",
"@activesheet",
"==",
"0",
"@worksheets",
"[",
"@activesheet",
"]",
".",
"activate",
"# Prepare the worksheet VML elements such as comments and buttons.",
"prepare_vml_objects",
"# Set the defined names for the worksheets such as Print Titles.",
"prepare_defined_names",
"# Prepare the drawings, charts and images.",
"prepare_drawings",
"# Add cached data to charts.",
"add_chart_data",
"# Prepare the worksheet tables.",
"prepare_tables",
"# Package the workbook.",
"packager",
"=",
"Package",
"::",
"Packager",
".",
"new",
"(",
"self",
")",
"packager",
".",
"set_package_dir",
"(",
"tempdir",
")",
"packager",
".",
"create_package",
"# Free up the Packager object.",
"packager",
"=",
"nil",
"# Store the xlsx component files with the temp dir name removed.",
"ZipFileUtils",
".",
"zip",
"(",
"\"#{tempdir}\"",
",",
"filename",
")",
"IO",
".",
"copy_stream",
"(",
"filename",
",",
"fileobj",
")",
"if",
"fileobj",
"Writexlsx",
"::",
"Utility",
".",
"delete_files",
"(",
"tempdir",
")",
"end"
] | Assemble worksheets into a workbook. | [
"Assemble",
"worksheets",
"into",
"a",
"workbook",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1291-L1327 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_formats | def prepare_formats #:nodoc:
@formats.formats.each do |format|
xf_index = format.xf_index
dxf_index = format.dxf_index
@xf_formats[xf_index] = format if xf_index
@dxf_formats[dxf_index] = format if dxf_index
end
end | ruby | def prepare_formats #:nodoc:
@formats.formats.each do |format|
xf_index = format.xf_index
dxf_index = format.dxf_index
@xf_formats[xf_index] = format if xf_index
@dxf_formats[dxf_index] = format if dxf_index
end
end | [
"def",
"prepare_formats",
"#:nodoc:",
"@formats",
".",
"formats",
".",
"each",
"do",
"|",
"format",
"|",
"xf_index",
"=",
"format",
".",
"xf_index",
"dxf_index",
"=",
"format",
".",
"dxf_index",
"@xf_formats",
"[",
"xf_index",
"]",
"=",
"format",
"if",
"xf_index",
"@dxf_formats",
"[",
"dxf_index",
"]",
"=",
"format",
"if",
"dxf_index",
"end",
"end"
] | Iterate through the XF Format objects and separate them into XF and DXF
formats. | [
"Iterate",
"through",
"the",
"XF",
"Format",
"objects",
"and",
"separate",
"them",
"into",
"XF",
"and",
"DXF",
"formats",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1371-L1379 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_fonts | def prepare_fonts #:nodoc:
fonts = {}
@xf_formats.each { |format| format.set_font_info(fonts) }
@font_count = fonts.size
# For the DXF formats we only need to check if the properties have changed.
@dxf_formats.each do |format|
# The only font properties that can change for a DXF format are: color,
# bold, italic, underline and strikethrough.
if format.color? || format.bold? || format.italic? || format.underline? || format.strikeout?
format.has_dxf_font(true)
end
end
end | ruby | def prepare_fonts #:nodoc:
fonts = {}
@xf_formats.each { |format| format.set_font_info(fonts) }
@font_count = fonts.size
# For the DXF formats we only need to check if the properties have changed.
@dxf_formats.each do |format|
# The only font properties that can change for a DXF format are: color,
# bold, italic, underline and strikethrough.
if format.color? || format.bold? || format.italic? || format.underline? || format.strikeout?
format.has_dxf_font(true)
end
end
end | [
"def",
"prepare_fonts",
"#:nodoc:",
"fonts",
"=",
"{",
"}",
"@xf_formats",
".",
"each",
"{",
"|",
"format",
"|",
"format",
".",
"set_font_info",
"(",
"fonts",
")",
"}",
"@font_count",
"=",
"fonts",
".",
"size",
"# For the DXF formats we only need to check if the properties have changed.",
"@dxf_formats",
".",
"each",
"do",
"|",
"format",
"|",
"# The only font properties that can change for a DXF format are: color,",
"# bold, italic, underline and strikethrough.",
"if",
"format",
".",
"color?",
"||",
"format",
".",
"bold?",
"||",
"format",
".",
"italic?",
"||",
"format",
".",
"underline?",
"||",
"format",
".",
"strikeout?",
"format",
".",
"has_dxf_font",
"(",
"true",
")",
"end",
"end",
"end"
] | Iterate through the XF Format objects and give them an index to non-default
font elements. | [
"Iterate",
"through",
"the",
"XF",
"Format",
"objects",
"and",
"give",
"them",
"an",
"index",
"to",
"non",
"-",
"default",
"font",
"elements",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1385-L1400 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_num_formats | def prepare_num_formats #:nodoc:
num_formats = {}
index = 164
num_format_count = 0
(@xf_formats + @dxf_formats).each do |format|
num_format = format.num_format
# Check if num_format is an index to a built-in number format.
# Also check for a string of zeros, which is a valid number format
# string but would evaluate to zero.
#
if num_format.to_s =~ /^\d+$/ && num_format.to_s !~ /^0+\d/
# Index to a built-in number format.
format.num_format_index = num_format
next
end
if num_formats[num_format]
# Number format has already been used.
format.num_format_index = num_formats[num_format]
else
# Add a new number format.
num_formats[num_format] = index
format.num_format_index = index
index += 1
# Only increase font count for XF formats (not for DXF formats).
num_format_count += 1 if ptrue?(format.xf_index)
end
end
@num_format_count = num_format_count
end | ruby | def prepare_num_formats #:nodoc:
num_formats = {}
index = 164
num_format_count = 0
(@xf_formats + @dxf_formats).each do |format|
num_format = format.num_format
# Check if num_format is an index to a built-in number format.
# Also check for a string of zeros, which is a valid number format
# string but would evaluate to zero.
#
if num_format.to_s =~ /^\d+$/ && num_format.to_s !~ /^0+\d/
# Index to a built-in number format.
format.num_format_index = num_format
next
end
if num_formats[num_format]
# Number format has already been used.
format.num_format_index = num_formats[num_format]
else
# Add a new number format.
num_formats[num_format] = index
format.num_format_index = index
index += 1
# Only increase font count for XF formats (not for DXF formats).
num_format_count += 1 if ptrue?(format.xf_index)
end
end
@num_format_count = num_format_count
end | [
"def",
"prepare_num_formats",
"#:nodoc:",
"num_formats",
"=",
"{",
"}",
"index",
"=",
"164",
"num_format_count",
"=",
"0",
"(",
"@xf_formats",
"+",
"@dxf_formats",
")",
".",
"each",
"do",
"|",
"format",
"|",
"num_format",
"=",
"format",
".",
"num_format",
"# Check if num_format is an index to a built-in number format.",
"# Also check for a string of zeros, which is a valid number format",
"# string but would evaluate to zero.",
"#",
"if",
"num_format",
".",
"to_s",
"=~",
"/",
"\\d",
"/",
"&&",
"num_format",
".",
"to_s",
"!~",
"/",
"\\d",
"/",
"# Index to a built-in number format.",
"format",
".",
"num_format_index",
"=",
"num_format",
"next",
"end",
"if",
"num_formats",
"[",
"num_format",
"]",
"# Number format has already been used.",
"format",
".",
"num_format_index",
"=",
"num_formats",
"[",
"num_format",
"]",
"else",
"# Add a new number format.",
"num_formats",
"[",
"num_format",
"]",
"=",
"index",
"format",
".",
"num_format_index",
"=",
"index",
"index",
"+=",
"1",
"# Only increase font count for XF formats (not for DXF formats).",
"num_format_count",
"+=",
"1",
"if",
"ptrue?",
"(",
"format",
".",
"xf_index",
")",
"end",
"end",
"@num_format_count",
"=",
"num_format_count",
"end"
] | Iterate through the XF Format objects and give them an index to non-default
number format elements.
User defined records start from index 0xA4. | [
"Iterate",
"through",
"the",
"XF",
"Format",
"objects",
"and",
"give",
"them",
"an",
"index",
"to",
"non",
"-",
"default",
"number",
"format",
"elements",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1408-L1441 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_borders | def prepare_borders #:nodoc:
borders = {}
@xf_formats.each { |format| format.set_border_info(borders) }
@border_count = borders.size
# For the DXF formats we only need to check if the properties have changed.
@dxf_formats.each do |format|
key = format.get_border_key
format.has_dxf_border(true) if key =~ /[^0:]/
end
end | ruby | def prepare_borders #:nodoc:
borders = {}
@xf_formats.each { |format| format.set_border_info(borders) }
@border_count = borders.size
# For the DXF formats we only need to check if the properties have changed.
@dxf_formats.each do |format|
key = format.get_border_key
format.has_dxf_border(true) if key =~ /[^0:]/
end
end | [
"def",
"prepare_borders",
"#:nodoc:",
"borders",
"=",
"{",
"}",
"@xf_formats",
".",
"each",
"{",
"|",
"format",
"|",
"format",
".",
"set_border_info",
"(",
"borders",
")",
"}",
"@border_count",
"=",
"borders",
".",
"size",
"# For the DXF formats we only need to check if the properties have changed.",
"@dxf_formats",
".",
"each",
"do",
"|",
"format",
"|",
"key",
"=",
"format",
".",
"get_border_key",
"format",
".",
"has_dxf_border",
"(",
"true",
")",
"if",
"key",
"=~",
"/",
"/",
"end",
"end"
] | Iterate through the XF Format objects and give them an index to non-default
border elements. | [
"Iterate",
"through",
"the",
"XF",
"Format",
"objects",
"and",
"give",
"them",
"an",
"index",
"to",
"non",
"-",
"default",
"border",
"elements",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1447-L1459 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_fills | def prepare_fills #:nodoc:
fills = {}
index = 2 # Start from 2. See above.
# Add the default fills.
fills['0:0:0'] = 0
fills['17:0:0'] = 1
# Store the DXF colors separately since them may be reversed below.
@dxf_formats.each do |format|
if format.pattern != 0 || format.bg_color != 0 || format.fg_color != 0
format.has_dxf_fill(true)
format.dxf_bg_color = format.bg_color
format.dxf_fg_color = format.fg_color
end
end
@xf_formats.each do |format|
# The following logical statements jointly take care of special cases
# in relation to cell colours and patterns:
# 1. For a solid fill (_pattern == 1) Excel reverses the role of
# foreground and background colours, and
# 2. If the user specifies a foreground or background colour without
# a pattern they probably wanted a solid fill, so we fill in the
# defaults.
#
if format.pattern == 1 && ne_0?(format.bg_color) && ne_0?(format.fg_color)
format.fg_color, format.bg_color = format.bg_color, format.fg_color
elsif format.pattern <= 1 && ne_0?(format.bg_color) && eq_0?(format.fg_color)
format.fg_color = format.bg_color
format.bg_color = 0
format.pattern = 1
elsif format.pattern <= 1 && eq_0?(format.bg_color) && ne_0?(format.fg_color)
format.bg_color = 0
format.pattern = 1
end
key = format.get_fill_key
if fills[key]
# Fill has already been used.
format.fill_index = fills[key]
format.has_fill(false)
else
# This is a new fill.
fills[key] = index
format.fill_index = index
format.has_fill(true)
index += 1
end
end
@fill_count = index
end | ruby | def prepare_fills #:nodoc:
fills = {}
index = 2 # Start from 2. See above.
# Add the default fills.
fills['0:0:0'] = 0
fills['17:0:0'] = 1
# Store the DXF colors separately since them may be reversed below.
@dxf_formats.each do |format|
if format.pattern != 0 || format.bg_color != 0 || format.fg_color != 0
format.has_dxf_fill(true)
format.dxf_bg_color = format.bg_color
format.dxf_fg_color = format.fg_color
end
end
@xf_formats.each do |format|
# The following logical statements jointly take care of special cases
# in relation to cell colours and patterns:
# 1. For a solid fill (_pattern == 1) Excel reverses the role of
# foreground and background colours, and
# 2. If the user specifies a foreground or background colour without
# a pattern they probably wanted a solid fill, so we fill in the
# defaults.
#
if format.pattern == 1 && ne_0?(format.bg_color) && ne_0?(format.fg_color)
format.fg_color, format.bg_color = format.bg_color, format.fg_color
elsif format.pattern <= 1 && ne_0?(format.bg_color) && eq_0?(format.fg_color)
format.fg_color = format.bg_color
format.bg_color = 0
format.pattern = 1
elsif format.pattern <= 1 && eq_0?(format.bg_color) && ne_0?(format.fg_color)
format.bg_color = 0
format.pattern = 1
end
key = format.get_fill_key
if fills[key]
# Fill has already been used.
format.fill_index = fills[key]
format.has_fill(false)
else
# This is a new fill.
fills[key] = index
format.fill_index = index
format.has_fill(true)
index += 1
end
end
@fill_count = index
end | [
"def",
"prepare_fills",
"#:nodoc:",
"fills",
"=",
"{",
"}",
"index",
"=",
"2",
"# Start from 2. See above.",
"# Add the default fills.",
"fills",
"[",
"'0:0:0'",
"]",
"=",
"0",
"fills",
"[",
"'17:0:0'",
"]",
"=",
"1",
"# Store the DXF colors separately since them may be reversed below.",
"@dxf_formats",
".",
"each",
"do",
"|",
"format",
"|",
"if",
"format",
".",
"pattern",
"!=",
"0",
"||",
"format",
".",
"bg_color",
"!=",
"0",
"||",
"format",
".",
"fg_color",
"!=",
"0",
"format",
".",
"has_dxf_fill",
"(",
"true",
")",
"format",
".",
"dxf_bg_color",
"=",
"format",
".",
"bg_color",
"format",
".",
"dxf_fg_color",
"=",
"format",
".",
"fg_color",
"end",
"end",
"@xf_formats",
".",
"each",
"do",
"|",
"format",
"|",
"# The following logical statements jointly take care of special cases",
"# in relation to cell colours and patterns:",
"# 1. For a solid fill (_pattern == 1) Excel reverses the role of",
"# foreground and background colours, and",
"# 2. If the user specifies a foreground or background colour without",
"# a pattern they probably wanted a solid fill, so we fill in the",
"# defaults.",
"#",
"if",
"format",
".",
"pattern",
"==",
"1",
"&&",
"ne_0?",
"(",
"format",
".",
"bg_color",
")",
"&&",
"ne_0?",
"(",
"format",
".",
"fg_color",
")",
"format",
".",
"fg_color",
",",
"format",
".",
"bg_color",
"=",
"format",
".",
"bg_color",
",",
"format",
".",
"fg_color",
"elsif",
"format",
".",
"pattern",
"<=",
"1",
"&&",
"ne_0?",
"(",
"format",
".",
"bg_color",
")",
"&&",
"eq_0?",
"(",
"format",
".",
"fg_color",
")",
"format",
".",
"fg_color",
"=",
"format",
".",
"bg_color",
"format",
".",
"bg_color",
"=",
"0",
"format",
".",
"pattern",
"=",
"1",
"elsif",
"format",
".",
"pattern",
"<=",
"1",
"&&",
"eq_0?",
"(",
"format",
".",
"bg_color",
")",
"&&",
"ne_0?",
"(",
"format",
".",
"fg_color",
")",
"format",
".",
"bg_color",
"=",
"0",
"format",
".",
"pattern",
"=",
"1",
"end",
"key",
"=",
"format",
".",
"get_fill_key",
"if",
"fills",
"[",
"key",
"]",
"# Fill has already been used.",
"format",
".",
"fill_index",
"=",
"fills",
"[",
"key",
"]",
"format",
".",
"has_fill",
"(",
"false",
")",
"else",
"# This is a new fill.",
"fills",
"[",
"key",
"]",
"=",
"index",
"format",
".",
"fill_index",
"=",
"index",
"format",
".",
"has_fill",
"(",
"true",
")",
"index",
"+=",
"1",
"end",
"end",
"@fill_count",
"=",
"index",
"end"
] | Iterate through the XF Format objects and give them an index to non-default
fill elements.
The user defined fill properties start from 2 since there are 2 default
fills: patternType="none" and patternType="gray125". | [
"Iterate",
"through",
"the",
"XF",
"Format",
"objects",
"and",
"give",
"them",
"an",
"index",
"to",
"non",
"-",
"default",
"fill",
"elements",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1468-L1521 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_defined_names | def prepare_defined_names #:nodoc:
@worksheets.each do |sheet|
# Check for Print Area settings.
if sheet.autofilter_area
@defined_names << [
'_xlnm._FilterDatabase',
sheet.index,
sheet.autofilter_area,
1
]
end
# Check for Print Area settings.
if !sheet.print_area.empty?
@defined_names << [
'_xlnm.Print_Area',
sheet.index,
sheet.print_area
]
end
# Check for repeat rows/cols. aka, Print Titles.
if !sheet.print_repeat_cols.empty? || !sheet.print_repeat_rows.empty?
if !sheet.print_repeat_cols.empty? && !sheet.print_repeat_rows.empty?
range = sheet.print_repeat_cols + ',' + sheet.print_repeat_rows
else
range = sheet.print_repeat_cols + sheet.print_repeat_rows
end
# Store the defined names.
@defined_names << ['_xlnm.Print_Titles', sheet.index, range]
end
end
@defined_names = sort_defined_names(@defined_names)
@named_ranges = extract_named_ranges(@defined_names)
end | ruby | def prepare_defined_names #:nodoc:
@worksheets.each do |sheet|
# Check for Print Area settings.
if sheet.autofilter_area
@defined_names << [
'_xlnm._FilterDatabase',
sheet.index,
sheet.autofilter_area,
1
]
end
# Check for Print Area settings.
if !sheet.print_area.empty?
@defined_names << [
'_xlnm.Print_Area',
sheet.index,
sheet.print_area
]
end
# Check for repeat rows/cols. aka, Print Titles.
if !sheet.print_repeat_cols.empty? || !sheet.print_repeat_rows.empty?
if !sheet.print_repeat_cols.empty? && !sheet.print_repeat_rows.empty?
range = sheet.print_repeat_cols + ',' + sheet.print_repeat_rows
else
range = sheet.print_repeat_cols + sheet.print_repeat_rows
end
# Store the defined names.
@defined_names << ['_xlnm.Print_Titles', sheet.index, range]
end
end
@defined_names = sort_defined_names(@defined_names)
@named_ranges = extract_named_ranges(@defined_names)
end | [
"def",
"prepare_defined_names",
"#:nodoc:",
"@worksheets",
".",
"each",
"do",
"|",
"sheet",
"|",
"# Check for Print Area settings.",
"if",
"sheet",
".",
"autofilter_area",
"@defined_names",
"<<",
"[",
"'_xlnm._FilterDatabase'",
",",
"sheet",
".",
"index",
",",
"sheet",
".",
"autofilter_area",
",",
"1",
"]",
"end",
"# Check for Print Area settings.",
"if",
"!",
"sheet",
".",
"print_area",
".",
"empty?",
"@defined_names",
"<<",
"[",
"'_xlnm.Print_Area'",
",",
"sheet",
".",
"index",
",",
"sheet",
".",
"print_area",
"]",
"end",
"# Check for repeat rows/cols. aka, Print Titles.",
"if",
"!",
"sheet",
".",
"print_repeat_cols",
".",
"empty?",
"||",
"!",
"sheet",
".",
"print_repeat_rows",
".",
"empty?",
"if",
"!",
"sheet",
".",
"print_repeat_cols",
".",
"empty?",
"&&",
"!",
"sheet",
".",
"print_repeat_rows",
".",
"empty?",
"range",
"=",
"sheet",
".",
"print_repeat_cols",
"+",
"','",
"+",
"sheet",
".",
"print_repeat_rows",
"else",
"range",
"=",
"sheet",
".",
"print_repeat_cols",
"+",
"sheet",
".",
"print_repeat_rows",
"end",
"# Store the defined names.",
"@defined_names",
"<<",
"[",
"'_xlnm.Print_Titles'",
",",
"sheet",
".",
"index",
",",
"range",
"]",
"end",
"end",
"@defined_names",
"=",
"sort_defined_names",
"(",
"@defined_names",
")",
"@named_ranges",
"=",
"extract_named_ranges",
"(",
"@defined_names",
")",
"end"
] | Iterate through the worksheets and store any defined names in addition to
any user defined names. Stores the defined names for the Workbook.xml and
the named ranges for App.xml. | [
"Iterate",
"through",
"the",
"worksheets",
"and",
"store",
"any",
"defined",
"names",
"in",
"addition",
"to",
"any",
"user",
"defined",
"names",
".",
"Stores",
"the",
"defined",
"names",
"for",
"the",
"Workbook",
".",
"xml",
"and",
"the",
"named",
"ranges",
"for",
"App",
".",
"xml",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1536-L1572 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_vml_objects | def prepare_vml_objects #:nodoc:
comment_id = 0
vml_drawing_id = 0
vml_data_id = 1
vml_header_id = 0
vml_shape_id = 1024
comment_files = 0
has_button = false
@worksheets.each do |sheet|
next if !sheet.has_vml? && !sheet.has_header_vml?
if sheet.has_vml?
if sheet.has_comments?
comment_files += 1
comment_id += 1
end
vml_drawing_id += 1
sheet.prepare_vml_objects(vml_data_id, vml_shape_id,
vml_drawing_id, comment_id)
# Each VML file should start with a shape id incremented by 1024.
vml_data_id += 1 * ( 1 + sheet.num_comments_block )
vml_shape_id += 1024 * ( 1 + sheet.num_comments_block )
end
if sheet.has_header_vml?
vml_header_id += 1
vml_drawing_id += 1
sheet.prepare_header_vml_objects(vml_header_id, vml_drawing_id)
end
# Set the sheet vba_codename if it has a button and the workbook
# has a vbaProject binary.
unless sheet.buttons_data.empty?
has_button = true
if @vba_project && !sheet.vba_codename
sheet.set_vba_name
end
end
end
add_font_format_for_cell_comments if num_comment_files > 0
# Set the workbook vba_codename if one of the sheets has a button and
# the workbook has a vbaProject binary.
if has_button && @vba_project && !@vba_codename
set_vba_name
end
end | ruby | def prepare_vml_objects #:nodoc:
comment_id = 0
vml_drawing_id = 0
vml_data_id = 1
vml_header_id = 0
vml_shape_id = 1024
comment_files = 0
has_button = false
@worksheets.each do |sheet|
next if !sheet.has_vml? && !sheet.has_header_vml?
if sheet.has_vml?
if sheet.has_comments?
comment_files += 1
comment_id += 1
end
vml_drawing_id += 1
sheet.prepare_vml_objects(vml_data_id, vml_shape_id,
vml_drawing_id, comment_id)
# Each VML file should start with a shape id incremented by 1024.
vml_data_id += 1 * ( 1 + sheet.num_comments_block )
vml_shape_id += 1024 * ( 1 + sheet.num_comments_block )
end
if sheet.has_header_vml?
vml_header_id += 1
vml_drawing_id += 1
sheet.prepare_header_vml_objects(vml_header_id, vml_drawing_id)
end
# Set the sheet vba_codename if it has a button and the workbook
# has a vbaProject binary.
unless sheet.buttons_data.empty?
has_button = true
if @vba_project && !sheet.vba_codename
sheet.set_vba_name
end
end
end
add_font_format_for_cell_comments if num_comment_files > 0
# Set the workbook vba_codename if one of the sheets has a button and
# the workbook has a vbaProject binary.
if has_button && @vba_project && !@vba_codename
set_vba_name
end
end | [
"def",
"prepare_vml_objects",
"#:nodoc:",
"comment_id",
"=",
"0",
"vml_drawing_id",
"=",
"0",
"vml_data_id",
"=",
"1",
"vml_header_id",
"=",
"0",
"vml_shape_id",
"=",
"1024",
"comment_files",
"=",
"0",
"has_button",
"=",
"false",
"@worksheets",
".",
"each",
"do",
"|",
"sheet",
"|",
"next",
"if",
"!",
"sheet",
".",
"has_vml?",
"&&",
"!",
"sheet",
".",
"has_header_vml?",
"if",
"sheet",
".",
"has_vml?",
"if",
"sheet",
".",
"has_comments?",
"comment_files",
"+=",
"1",
"comment_id",
"+=",
"1",
"end",
"vml_drawing_id",
"+=",
"1",
"sheet",
".",
"prepare_vml_objects",
"(",
"vml_data_id",
",",
"vml_shape_id",
",",
"vml_drawing_id",
",",
"comment_id",
")",
"# Each VML file should start with a shape id incremented by 1024.",
"vml_data_id",
"+=",
"1",
"*",
"(",
"1",
"+",
"sheet",
".",
"num_comments_block",
")",
"vml_shape_id",
"+=",
"1024",
"*",
"(",
"1",
"+",
"sheet",
".",
"num_comments_block",
")",
"end",
"if",
"sheet",
".",
"has_header_vml?",
"vml_header_id",
"+=",
"1",
"vml_drawing_id",
"+=",
"1",
"sheet",
".",
"prepare_header_vml_objects",
"(",
"vml_header_id",
",",
"vml_drawing_id",
")",
"end",
"# Set the sheet vba_codename if it has a button and the workbook",
"# has a vbaProject binary.",
"unless",
"sheet",
".",
"buttons_data",
".",
"empty?",
"has_button",
"=",
"true",
"if",
"@vba_project",
"&&",
"!",
"sheet",
".",
"vba_codename",
"sheet",
".",
"set_vba_name",
"end",
"end",
"end",
"add_font_format_for_cell_comments",
"if",
"num_comment_files",
">",
"0",
"# Set the workbook vba_codename if one of the sheets has a button and",
"# the workbook has a vbaProject binary.",
"if",
"has_button",
"&&",
"@vba_project",
"&&",
"!",
"@vba_codename",
"set_vba_name",
"end",
"end"
] | Iterate through the worksheets and set up the VML objects. | [
"Iterate",
"through",
"the",
"worksheets",
"and",
"set",
"up",
"the",
"VML",
"objects",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1577-L1626 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.extract_named_ranges | def extract_named_ranges(defined_names) #:nodoc:
named_ranges = []
defined_names.each do |defined_name|
name, index, range = defined_name
# Skip autoFilter ranges.
next if name == '_xlnm._FilterDatabase'
# We are only interested in defined names with ranges.
if range =~ /^([^!]+)!/
sheet_name = $1
# Match Print_Area and Print_Titles xlnm types.
if name =~ /^_xlnm\.(.*)$/
xlnm_type = $1
name = "#{sheet_name}!#{xlnm_type}"
elsif index != -1
name = "#{sheet_name}!#{name}"
end
named_ranges << name
end
end
named_ranges
end | ruby | def extract_named_ranges(defined_names) #:nodoc:
named_ranges = []
defined_names.each do |defined_name|
name, index, range = defined_name
# Skip autoFilter ranges.
next if name == '_xlnm._FilterDatabase'
# We are only interested in defined names with ranges.
if range =~ /^([^!]+)!/
sheet_name = $1
# Match Print_Area and Print_Titles xlnm types.
if name =~ /^_xlnm\.(.*)$/
xlnm_type = $1
name = "#{sheet_name}!#{xlnm_type}"
elsif index != -1
name = "#{sheet_name}!#{name}"
end
named_ranges << name
end
end
named_ranges
end | [
"def",
"extract_named_ranges",
"(",
"defined_names",
")",
"#:nodoc:",
"named_ranges",
"=",
"[",
"]",
"defined_names",
".",
"each",
"do",
"|",
"defined_name",
"|",
"name",
",",
"index",
",",
"range",
"=",
"defined_name",
"# Skip autoFilter ranges.",
"next",
"if",
"name",
"==",
"'_xlnm._FilterDatabase'",
"# We are only interested in defined names with ranges.",
"if",
"range",
"=~",
"/",
"/",
"sheet_name",
"=",
"$1",
"# Match Print_Area and Print_Titles xlnm types.",
"if",
"name",
"=~",
"/",
"\\.",
"/",
"xlnm_type",
"=",
"$1",
"name",
"=",
"\"#{sheet_name}!#{xlnm_type}\"",
"elsif",
"index",
"!=",
"-",
"1",
"name",
"=",
"\"#{sheet_name}!#{name}\"",
"end",
"named_ranges",
"<<",
"name",
"end",
"end",
"named_ranges",
"end"
] | Extract the named ranges from the sorted list of defined names. These are
used in the App.xml file. | [
"Extract",
"the",
"named",
"ranges",
"from",
"the",
"sorted",
"list",
"of",
"defined",
"names",
".",
"These",
"are",
"used",
"in",
"the",
"App",
".",
"xml",
"file",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1770-L1796 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.prepare_drawings | def prepare_drawings #:nodoc:
chart_ref_id = 0
image_ref_id = 0
drawing_id = 0
@worksheets.each do |sheet|
chart_count = sheet.charts.size
image_count = sheet.images.size
shape_count = sheet.shapes.size
header_image_count = sheet.header_images.size
footer_image_count = sheet.footer_images.size
has_drawing = false
# Check that some image or drawing needs to be processed.
next if chart_count + image_count + shape_count + header_image_count + footer_image_count == 0
# Don't increase the drawing_id header/footer images.
if chart_count + image_count + shape_count > 0
drawing_id += 1
has_drawing = true
end
# Prepare the worksheet charts.
sheet.charts.each_with_index do |chart, index|
chart_ref_id += 1
sheet.prepare_chart(index, chart_ref_id, drawing_id)
end
# Prepare the worksheet images.
sheet.images.each_with_index do |image, index|
type, width, height, name, x_dpi, y_dpi = get_image_properties(image[2])
image_ref_id += 1
sheet.prepare_image(index, image_ref_id, drawing_id, width, height, name, type, x_dpi, y_dpi)
end
# Prepare the worksheet shapes.
sheet.shapes.each_with_index do |shape, index|
sheet.prepare_shape(index, drawing_id)
end
# Prepare the header images.
header_image_count.times do |index|
filename = sheet.header_images[index][0]
position = sheet.header_images[index][1]
type, width, height, name, x_dpi, y_dpi =
get_image_properties(filename)
image_ref_id += 1
sheet.prepare_header_image(image_ref_id, width, height,
name, type, position, x_dpi, y_dpi)
end
# Prepare the footer images.
footer_image_count.times do |index|
filename = sheet.footer_images[index][0]
position = sheet.footer_images[index][1]
type, width, height, name, x_dpi, y_dpi =
get_image_properties(filename)
image_ref_id += 1
sheet.prepare_header_image(image_ref_id, width, height,
name, type, position, x_dpi, y_dpi)
end
if has_drawing
drawing = sheet.drawing
@drawings << drawing
end
end
# Sort the workbook charts references into the order that the were
# written from the worksheets above.
@charts = @charts.select { |chart| chart.id != -1 }.
sort_by { |chart| chart.id }
@drawing_count = drawing_id
end | ruby | def prepare_drawings #:nodoc:
chart_ref_id = 0
image_ref_id = 0
drawing_id = 0
@worksheets.each do |sheet|
chart_count = sheet.charts.size
image_count = sheet.images.size
shape_count = sheet.shapes.size
header_image_count = sheet.header_images.size
footer_image_count = sheet.footer_images.size
has_drawing = false
# Check that some image or drawing needs to be processed.
next if chart_count + image_count + shape_count + header_image_count + footer_image_count == 0
# Don't increase the drawing_id header/footer images.
if chart_count + image_count + shape_count > 0
drawing_id += 1
has_drawing = true
end
# Prepare the worksheet charts.
sheet.charts.each_with_index do |chart, index|
chart_ref_id += 1
sheet.prepare_chart(index, chart_ref_id, drawing_id)
end
# Prepare the worksheet images.
sheet.images.each_with_index do |image, index|
type, width, height, name, x_dpi, y_dpi = get_image_properties(image[2])
image_ref_id += 1
sheet.prepare_image(index, image_ref_id, drawing_id, width, height, name, type, x_dpi, y_dpi)
end
# Prepare the worksheet shapes.
sheet.shapes.each_with_index do |shape, index|
sheet.prepare_shape(index, drawing_id)
end
# Prepare the header images.
header_image_count.times do |index|
filename = sheet.header_images[index][0]
position = sheet.header_images[index][1]
type, width, height, name, x_dpi, y_dpi =
get_image_properties(filename)
image_ref_id += 1
sheet.prepare_header_image(image_ref_id, width, height,
name, type, position, x_dpi, y_dpi)
end
# Prepare the footer images.
footer_image_count.times do |index|
filename = sheet.footer_images[index][0]
position = sheet.footer_images[index][1]
type, width, height, name, x_dpi, y_dpi =
get_image_properties(filename)
image_ref_id += 1
sheet.prepare_header_image(image_ref_id, width, height,
name, type, position, x_dpi, y_dpi)
end
if has_drawing
drawing = sheet.drawing
@drawings << drawing
end
end
# Sort the workbook charts references into the order that the were
# written from the worksheets above.
@charts = @charts.select { |chart| chart.id != -1 }.
sort_by { |chart| chart.id }
@drawing_count = drawing_id
end | [
"def",
"prepare_drawings",
"#:nodoc:",
"chart_ref_id",
"=",
"0",
"image_ref_id",
"=",
"0",
"drawing_id",
"=",
"0",
"@worksheets",
".",
"each",
"do",
"|",
"sheet",
"|",
"chart_count",
"=",
"sheet",
".",
"charts",
".",
"size",
"image_count",
"=",
"sheet",
".",
"images",
".",
"size",
"shape_count",
"=",
"sheet",
".",
"shapes",
".",
"size",
"header_image_count",
"=",
"sheet",
".",
"header_images",
".",
"size",
"footer_image_count",
"=",
"sheet",
".",
"footer_images",
".",
"size",
"has_drawing",
"=",
"false",
"# Check that some image or drawing needs to be processed.",
"next",
"if",
"chart_count",
"+",
"image_count",
"+",
"shape_count",
"+",
"header_image_count",
"+",
"footer_image_count",
"==",
"0",
"# Don't increase the drawing_id header/footer images.",
"if",
"chart_count",
"+",
"image_count",
"+",
"shape_count",
">",
"0",
"drawing_id",
"+=",
"1",
"has_drawing",
"=",
"true",
"end",
"# Prepare the worksheet charts.",
"sheet",
".",
"charts",
".",
"each_with_index",
"do",
"|",
"chart",
",",
"index",
"|",
"chart_ref_id",
"+=",
"1",
"sheet",
".",
"prepare_chart",
"(",
"index",
",",
"chart_ref_id",
",",
"drawing_id",
")",
"end",
"# Prepare the worksheet images.",
"sheet",
".",
"images",
".",
"each_with_index",
"do",
"|",
"image",
",",
"index",
"|",
"type",
",",
"width",
",",
"height",
",",
"name",
",",
"x_dpi",
",",
"y_dpi",
"=",
"get_image_properties",
"(",
"image",
"[",
"2",
"]",
")",
"image_ref_id",
"+=",
"1",
"sheet",
".",
"prepare_image",
"(",
"index",
",",
"image_ref_id",
",",
"drawing_id",
",",
"width",
",",
"height",
",",
"name",
",",
"type",
",",
"x_dpi",
",",
"y_dpi",
")",
"end",
"# Prepare the worksheet shapes.",
"sheet",
".",
"shapes",
".",
"each_with_index",
"do",
"|",
"shape",
",",
"index",
"|",
"sheet",
".",
"prepare_shape",
"(",
"index",
",",
"drawing_id",
")",
"end",
"# Prepare the header images.",
"header_image_count",
".",
"times",
"do",
"|",
"index",
"|",
"filename",
"=",
"sheet",
".",
"header_images",
"[",
"index",
"]",
"[",
"0",
"]",
"position",
"=",
"sheet",
".",
"header_images",
"[",
"index",
"]",
"[",
"1",
"]",
"type",
",",
"width",
",",
"height",
",",
"name",
",",
"x_dpi",
",",
"y_dpi",
"=",
"get_image_properties",
"(",
"filename",
")",
"image_ref_id",
"+=",
"1",
"sheet",
".",
"prepare_header_image",
"(",
"image_ref_id",
",",
"width",
",",
"height",
",",
"name",
",",
"type",
",",
"position",
",",
"x_dpi",
",",
"y_dpi",
")",
"end",
"# Prepare the footer images.",
"footer_image_count",
".",
"times",
"do",
"|",
"index",
"|",
"filename",
"=",
"sheet",
".",
"footer_images",
"[",
"index",
"]",
"[",
"0",
"]",
"position",
"=",
"sheet",
".",
"footer_images",
"[",
"index",
"]",
"[",
"1",
"]",
"type",
",",
"width",
",",
"height",
",",
"name",
",",
"x_dpi",
",",
"y_dpi",
"=",
"get_image_properties",
"(",
"filename",
")",
"image_ref_id",
"+=",
"1",
"sheet",
".",
"prepare_header_image",
"(",
"image_ref_id",
",",
"width",
",",
"height",
",",
"name",
",",
"type",
",",
"position",
",",
"x_dpi",
",",
"y_dpi",
")",
"end",
"if",
"has_drawing",
"drawing",
"=",
"sheet",
".",
"drawing",
"@drawings",
"<<",
"drawing",
"end",
"end",
"# Sort the workbook charts references into the order that the were",
"# written from the worksheets above.",
"@charts",
"=",
"@charts",
".",
"select",
"{",
"|",
"chart",
"|",
"chart",
".",
"id",
"!=",
"-",
"1",
"}",
".",
"sort_by",
"{",
"|",
"chart",
"|",
"chart",
".",
"id",
"}",
"@drawing_count",
"=",
"drawing_id",
"end"
] | Iterate through the worksheets and set up any chart or image drawings. | [
"Iterate",
"through",
"the",
"worksheets",
"and",
"set",
"up",
"any",
"chart",
"or",
"image",
"drawings",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1801-L1880 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.get_image_properties | def get_image_properties(filename)
# Note the image_id, and previous_images mechanism isn't currently used.
x_dpi = 96
y_dpi = 96
# Open the image file and import the data.
data = File.binread(filename)
if data.unpack('x A3')[0] == 'PNG'
# Test for PNGs.
type, width, height, x_dpi, y_dpi = process_png(data)
@image_types[:png] = 1
elsif data.unpack('n')[0] == 0xFFD8
# Test for JPEG files.
type, width, height, x_dpi, y_dpi = process_jpg(data, filename)
@image_types[:jpeg] = 1
elsif data.unpack('A2')[0] == 'BM'
# Test for BMPs.
type, width, height = process_bmp(data, filename)
@image_types[:bmp] = 1
else
# TODO. Add Image::Size to support other types.
raise "Unsupported image format for file: #{filename}\n"
end
@images << [filename, type]
[type, width, height, File.basename(filename), x_dpi, y_dpi]
end | ruby | def get_image_properties(filename)
# Note the image_id, and previous_images mechanism isn't currently used.
x_dpi = 96
y_dpi = 96
# Open the image file and import the data.
data = File.binread(filename)
if data.unpack('x A3')[0] == 'PNG'
# Test for PNGs.
type, width, height, x_dpi, y_dpi = process_png(data)
@image_types[:png] = 1
elsif data.unpack('n')[0] == 0xFFD8
# Test for JPEG files.
type, width, height, x_dpi, y_dpi = process_jpg(data, filename)
@image_types[:jpeg] = 1
elsif data.unpack('A2')[0] == 'BM'
# Test for BMPs.
type, width, height = process_bmp(data, filename)
@image_types[:bmp] = 1
else
# TODO. Add Image::Size to support other types.
raise "Unsupported image format for file: #{filename}\n"
end
@images << [filename, type]
[type, width, height, File.basename(filename), x_dpi, y_dpi]
end | [
"def",
"get_image_properties",
"(",
"filename",
")",
"# Note the image_id, and previous_images mechanism isn't currently used.",
"x_dpi",
"=",
"96",
"y_dpi",
"=",
"96",
"# Open the image file and import the data.",
"data",
"=",
"File",
".",
"binread",
"(",
"filename",
")",
"if",
"data",
".",
"unpack",
"(",
"'x A3'",
")",
"[",
"0",
"]",
"==",
"'PNG'",
"# Test for PNGs.",
"type",
",",
"width",
",",
"height",
",",
"x_dpi",
",",
"y_dpi",
"=",
"process_png",
"(",
"data",
")",
"@image_types",
"[",
":png",
"]",
"=",
"1",
"elsif",
"data",
".",
"unpack",
"(",
"'n'",
")",
"[",
"0",
"]",
"==",
"0xFFD8",
"# Test for JPEG files.",
"type",
",",
"width",
",",
"height",
",",
"x_dpi",
",",
"y_dpi",
"=",
"process_jpg",
"(",
"data",
",",
"filename",
")",
"@image_types",
"[",
":jpeg",
"]",
"=",
"1",
"elsif",
"data",
".",
"unpack",
"(",
"'A2'",
")",
"[",
"0",
"]",
"==",
"'BM'",
"# Test for BMPs.",
"type",
",",
"width",
",",
"height",
"=",
"process_bmp",
"(",
"data",
",",
"filename",
")",
"@image_types",
"[",
":bmp",
"]",
"=",
"1",
"else",
"# TODO. Add Image::Size to support other types.",
"raise",
"\"Unsupported image format for file: #{filename}\\n\"",
"end",
"@images",
"<<",
"[",
"filename",
",",
"type",
"]",
"[",
"type",
",",
"width",
",",
"height",
",",
"File",
".",
"basename",
"(",
"filename",
")",
",",
"x_dpi",
",",
"y_dpi",
"]",
"end"
] | Extract information from the image file such as dimension, type, filename,
and extension. Also keep track of previously seen images to optimise out
any duplicates. | [
"Extract",
"information",
"from",
"the",
"image",
"file",
"such",
"as",
"dimension",
"type",
"filename",
"and",
"extension",
".",
"Also",
"keep",
"track",
"of",
"previously",
"seen",
"images",
"to",
"optimise",
"out",
"any",
"duplicates",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1887-L1914 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.process_png | def process_png(data)
type = 'png'
width = 0
height = 0
x_dpi = 96
y_dpi = 96
offset = 8
data_length = data.size
# Search through the image data to read the height and width in th the
# IHDR element. Also read the DPI in the pHYs element.
while offset < data_length
length = data[offset + 0, 4].unpack("N")[0]
png_type = data[offset + 4, 4].unpack("A4")[0]
case png_type
when "IHDR"
width = data[offset + 8, 4].unpack("N")[0]
height = data[offset + 12, 4].unpack("N")[0]
when "pHYs"
x_ppu = data[offset + 8, 4].unpack("N")[0]
y_ppu = data[offset + 12, 4].unpack("N")[0]
units = data[offset + 16, 1].unpack("C")[0]
if units == 1
x_dpi = x_ppu * 0.0254
y_dpi = y_ppu * 0.0254
end
end
offset = offset + length + 12
break if png_type == "IEND"
end
raise "#{filename}: no size data found in png image.\n" unless height
[type, width, height, x_dpi, y_dpi]
end | ruby | def process_png(data)
type = 'png'
width = 0
height = 0
x_dpi = 96
y_dpi = 96
offset = 8
data_length = data.size
# Search through the image data to read the height and width in th the
# IHDR element. Also read the DPI in the pHYs element.
while offset < data_length
length = data[offset + 0, 4].unpack("N")[0]
png_type = data[offset + 4, 4].unpack("A4")[0]
case png_type
when "IHDR"
width = data[offset + 8, 4].unpack("N")[0]
height = data[offset + 12, 4].unpack("N")[0]
when "pHYs"
x_ppu = data[offset + 8, 4].unpack("N")[0]
y_ppu = data[offset + 12, 4].unpack("N")[0]
units = data[offset + 16, 1].unpack("C")[0]
if units == 1
x_dpi = x_ppu * 0.0254
y_dpi = y_ppu * 0.0254
end
end
offset = offset + length + 12
break if png_type == "IEND"
end
raise "#{filename}: no size data found in png image.\n" unless height
[type, width, height, x_dpi, y_dpi]
end | [
"def",
"process_png",
"(",
"data",
")",
"type",
"=",
"'png'",
"width",
"=",
"0",
"height",
"=",
"0",
"x_dpi",
"=",
"96",
"y_dpi",
"=",
"96",
"offset",
"=",
"8",
"data_length",
"=",
"data",
".",
"size",
"# Search through the image data to read the height and width in th the",
"# IHDR element. Also read the DPI in the pHYs element.",
"while",
"offset",
"<",
"data_length",
"length",
"=",
"data",
"[",
"offset",
"+",
"0",
",",
"4",
"]",
".",
"unpack",
"(",
"\"N\"",
")",
"[",
"0",
"]",
"png_type",
"=",
"data",
"[",
"offset",
"+",
"4",
",",
"4",
"]",
".",
"unpack",
"(",
"\"A4\"",
")",
"[",
"0",
"]",
"case",
"png_type",
"when",
"\"IHDR\"",
"width",
"=",
"data",
"[",
"offset",
"+",
"8",
",",
"4",
"]",
".",
"unpack",
"(",
"\"N\"",
")",
"[",
"0",
"]",
"height",
"=",
"data",
"[",
"offset",
"+",
"12",
",",
"4",
"]",
".",
"unpack",
"(",
"\"N\"",
")",
"[",
"0",
"]",
"when",
"\"pHYs\"",
"x_ppu",
"=",
"data",
"[",
"offset",
"+",
"8",
",",
"4",
"]",
".",
"unpack",
"(",
"\"N\"",
")",
"[",
"0",
"]",
"y_ppu",
"=",
"data",
"[",
"offset",
"+",
"12",
",",
"4",
"]",
".",
"unpack",
"(",
"\"N\"",
")",
"[",
"0",
"]",
"units",
"=",
"data",
"[",
"offset",
"+",
"16",
",",
"1",
"]",
".",
"unpack",
"(",
"\"C\"",
")",
"[",
"0",
"]",
"if",
"units",
"==",
"1",
"x_dpi",
"=",
"x_ppu",
"*",
"0.0254",
"y_dpi",
"=",
"y_ppu",
"*",
"0.0254",
"end",
"end",
"offset",
"=",
"offset",
"+",
"length",
"+",
"12",
"break",
"if",
"png_type",
"==",
"\"IEND\"",
"end",
"raise",
"\"#{filename}: no size data found in png image.\\n\"",
"unless",
"height",
"[",
"type",
",",
"width",
",",
"height",
",",
"x_dpi",
",",
"y_dpi",
"]",
"end"
] | Extract width and height information from a PNG file. | [
"Extract",
"width",
"and",
"height",
"information",
"from",
"a",
"PNG",
"file",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L1919-L1958 | train |
cxn03651/write_xlsx | lib/write_xlsx/workbook.rb | Writexlsx.Workbook.process_bmp | def process_bmp(data, filename) #:nodoc:
type = 'bmp'
# Check that the file is big enough to be a bitmap.
raise "#{filename} doesn't contain enough data." if data.bytesize <= 0x36
# Read the bitmap width and height. Verify the sizes.
width, height = data.unpack("x18 V2")
raise "#{filename}: largest image width #{width} supported is 65k." if width > 0xFFFF
raise "#{filename}: largest image height supported is 65k." if height > 0xFFFF
# Read the bitmap planes and bpp data. Verify them.
planes, bitcount = data.unpack("x26 v2")
raise "#{filename} isn't a 24bit true color bitmap." unless bitcount == 24
raise "#{filename}: only 1 plane supported in bitmap image." unless planes == 1
# Read the bitmap compression. Verify compression.
compression = data.unpack("x30 V")[0]
raise "#{filename}: compression not supported in bitmap image." unless compression == 0
[type, width, height]
end | ruby | def process_bmp(data, filename) #:nodoc:
type = 'bmp'
# Check that the file is big enough to be a bitmap.
raise "#{filename} doesn't contain enough data." if data.bytesize <= 0x36
# Read the bitmap width and height. Verify the sizes.
width, height = data.unpack("x18 V2")
raise "#{filename}: largest image width #{width} supported is 65k." if width > 0xFFFF
raise "#{filename}: largest image height supported is 65k." if height > 0xFFFF
# Read the bitmap planes and bpp data. Verify them.
planes, bitcount = data.unpack("x26 v2")
raise "#{filename} isn't a 24bit true color bitmap." unless bitcount == 24
raise "#{filename}: only 1 plane supported in bitmap image." unless planes == 1
# Read the bitmap compression. Verify compression.
compression = data.unpack("x30 V")[0]
raise "#{filename}: compression not supported in bitmap image." unless compression == 0
[type, width, height]
end | [
"def",
"process_bmp",
"(",
"data",
",",
"filename",
")",
"#:nodoc:",
"type",
"=",
"'bmp'",
"# Check that the file is big enough to be a bitmap.",
"raise",
"\"#{filename} doesn't contain enough data.\"",
"if",
"data",
".",
"bytesize",
"<=",
"0x36",
"# Read the bitmap width and height. Verify the sizes.",
"width",
",",
"height",
"=",
"data",
".",
"unpack",
"(",
"\"x18 V2\"",
")",
"raise",
"\"#{filename}: largest image width #{width} supported is 65k.\"",
"if",
"width",
">",
"0xFFFF",
"raise",
"\"#{filename}: largest image height supported is 65k.\"",
"if",
"height",
">",
"0xFFFF",
"# Read the bitmap planes and bpp data. Verify them.",
"planes",
",",
"bitcount",
"=",
"data",
".",
"unpack",
"(",
"\"x26 v2\"",
")",
"raise",
"\"#{filename} isn't a 24bit true color bitmap.\"",
"unless",
"bitcount",
"==",
"24",
"raise",
"\"#{filename}: only 1 plane supported in bitmap image.\"",
"unless",
"planes",
"==",
"1",
"# Read the bitmap compression. Verify compression.",
"compression",
"=",
"data",
".",
"unpack",
"(",
"\"x30 V\"",
")",
"[",
"0",
"]",
"raise",
"\"#{filename}: compression not supported in bitmap image.\"",
"unless",
"compression",
"==",
"0",
"[",
"type",
",",
"width",
",",
"height",
"]",
"end"
] | Extract width and height information from a BMP file. | [
"Extract",
"width",
"and",
"height",
"information",
"from",
"a",
"BMP",
"file",
"."
] | 6d658b29512e5ab63b947e2b03e67df70a83b55c | https://github.com/cxn03651/write_xlsx/blob/6d658b29512e5ab63b947e2b03e67df70a83b55c/lib/write_xlsx/workbook.rb#L2001-L2021 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/configuration.rb | XRay.Configuration.daemon_address= | def daemon_address=(v)
v = ENV[DaemonConfig::DAEMON_ADDRESS_KEY] || v
config = DaemonConfig.new(addr: v)
emitter.daemon_config = config
sampler.daemon_config = config if sampler.respond_to?(:daemon_config=)
end | ruby | def daemon_address=(v)
v = ENV[DaemonConfig::DAEMON_ADDRESS_KEY] || v
config = DaemonConfig.new(addr: v)
emitter.daemon_config = config
sampler.daemon_config = config if sampler.respond_to?(:daemon_config=)
end | [
"def",
"daemon_address",
"=",
"(",
"v",
")",
"v",
"=",
"ENV",
"[",
"DaemonConfig",
"::",
"DAEMON_ADDRESS_KEY",
"]",
"||",
"v",
"config",
"=",
"DaemonConfig",
".",
"new",
"(",
"addr",
":",
"v",
")",
"emitter",
".",
"daemon_config",
"=",
"config",
"sampler",
".",
"daemon_config",
"=",
"config",
"if",
"sampler",
".",
"respond_to?",
"(",
":daemon_config=",
")",
"end"
] | setting daemon address for components communicate with X-Ray daemon. | [
"setting",
"daemon",
"address",
"for",
"components",
"communicate",
"with",
"X",
"-",
"Ray",
"daemon",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/configuration.rb#L43-L48 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/model/subsegment.rb | XRay.Subsegment.all_children_count | def all_children_count
size = subsegments.count
subsegments.each { |v| size += v.all_children_count }
size
end | ruby | def all_children_count
size = subsegments.count
subsegments.each { |v| size += v.all_children_count }
size
end | [
"def",
"all_children_count",
"size",
"=",
"subsegments",
".",
"count",
"subsegments",
".",
"each",
"{",
"|",
"v",
"|",
"size",
"+=",
"v",
".",
"all_children_count",
"}",
"size",
"end"
] | Returns the number of its direct and indirect children.
This is useful when we remove the reference to a subsegment
and need to keep remaining subsegment size accurate. | [
"Returns",
"the",
"number",
"of",
"its",
"direct",
"and",
"indirect",
"children",
".",
"This",
"is",
"useful",
"when",
"we",
"remove",
"the",
"reference",
"to",
"a",
"subsegment",
"and",
"need",
"to",
"keep",
"remaining",
"subsegment",
"size",
"accurate",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/model/subsegment.rb#L52-L56 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/sampling/local/sampler.rb | XRay.LocalSampler.sample_request? | def sample_request?(sampling_req)
sample = sample?
return sample if sampling_req.nil? || sampling_req.empty?
@custom_rules ||= []
@custom_rules.each do |c|
return should_sample?(c) if c.applies?(sampling_req)
end
# use previously made decision based on default rule
# if no path-based rule has been matched
sample
end | ruby | def sample_request?(sampling_req)
sample = sample?
return sample if sampling_req.nil? || sampling_req.empty?
@custom_rules ||= []
@custom_rules.each do |c|
return should_sample?(c) if c.applies?(sampling_req)
end
# use previously made decision based on default rule
# if no path-based rule has been matched
sample
end | [
"def",
"sample_request?",
"(",
"sampling_req",
")",
"sample",
"=",
"sample?",
"return",
"sample",
"if",
"sampling_req",
".",
"nil?",
"||",
"sampling_req",
".",
"empty?",
"@custom_rules",
"||=",
"[",
"]",
"@custom_rules",
".",
"each",
"do",
"|",
"c",
"|",
"return",
"should_sample?",
"(",
"c",
")",
"if",
"c",
".",
"applies?",
"(",
"sampling_req",
")",
"end",
"# use previously made decision based on default rule",
"# if no path-based rule has been matched",
"sample",
"end"
] | Return True if the sampler decide to sample based on input
information and sampling rules. It will first check if any
custom rule should be applied, if not it falls back to the
default sampling rule.
All arugments are extracted from incoming requests by
X-Ray middleware to perform path based sampling. | [
"Return",
"True",
"if",
"the",
"sampler",
"decide",
"to",
"sample",
"based",
"on",
"input",
"information",
"and",
"sampling",
"rules",
".",
"It",
"will",
"first",
"check",
"if",
"any",
"custom",
"rule",
"should",
"be",
"applied",
"if",
"not",
"it",
"falls",
"back",
"to",
"the",
"default",
"sampling",
"rule",
".",
"All",
"arugments",
"are",
"extracted",
"from",
"incoming",
"requests",
"by",
"X",
"-",
"Ray",
"middleware",
"to",
"perform",
"path",
"based",
"sampling",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/sampling/local/sampler.rb#L56-L66 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/recorder.rb | XRay.Recorder.begin_segment | def begin_segment(name, trace_id: nil, parent_id: nil, sampled: nil)
seg_name = name || config.name
raise SegmentNameMissingError if seg_name.to_s.empty?
# sampling decision comes from outside has higher precedence.
sample = sampled.nil? ? config.sample? : sampled
if sample
segment = Segment.new name: seg_name, trace_id: trace_id, parent_id: parent_id
populate_runtime_context(segment, sample)
else
segment = DummySegment.new name: seg_name, trace_id: trace_id, parent_id: parent_id
end
context.store_entity entity: segment
segment
end | ruby | def begin_segment(name, trace_id: nil, parent_id: nil, sampled: nil)
seg_name = name || config.name
raise SegmentNameMissingError if seg_name.to_s.empty?
# sampling decision comes from outside has higher precedence.
sample = sampled.nil? ? config.sample? : sampled
if sample
segment = Segment.new name: seg_name, trace_id: trace_id, parent_id: parent_id
populate_runtime_context(segment, sample)
else
segment = DummySegment.new name: seg_name, trace_id: trace_id, parent_id: parent_id
end
context.store_entity entity: segment
segment
end | [
"def",
"begin_segment",
"(",
"name",
",",
"trace_id",
":",
"nil",
",",
"parent_id",
":",
"nil",
",",
"sampled",
":",
"nil",
")",
"seg_name",
"=",
"name",
"||",
"config",
".",
"name",
"raise",
"SegmentNameMissingError",
"if",
"seg_name",
".",
"to_s",
".",
"empty?",
"# sampling decision comes from outside has higher precedence.",
"sample",
"=",
"sampled",
".",
"nil?",
"?",
"config",
".",
"sample?",
":",
"sampled",
"if",
"sample",
"segment",
"=",
"Segment",
".",
"new",
"name",
":",
"seg_name",
",",
"trace_id",
":",
"trace_id",
",",
"parent_id",
":",
"parent_id",
"populate_runtime_context",
"(",
"segment",
",",
"sample",
")",
"else",
"segment",
"=",
"DummySegment",
".",
"new",
"name",
":",
"seg_name",
",",
"trace_id",
":",
"trace_id",
",",
"parent_id",
":",
"parent_id",
"end",
"context",
".",
"store_entity",
"entity",
":",
"segment",
"segment",
"end"
] | Begin a segment for the current context. The recorder
only keeps one segment at a time. Create a second one without
closing existing one will overwrite the existing one.
@return [Segment] thew newly created segment. | [
"Begin",
"a",
"segment",
"for",
"the",
"current",
"context",
".",
"The",
"recorder",
"only",
"keeps",
"one",
"segment",
"at",
"a",
"time",
".",
"Create",
"a",
"second",
"one",
"without",
"closing",
"existing",
"one",
"will",
"overwrite",
"the",
"existing",
"one",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/recorder.rb#L27-L41 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/recorder.rb | XRay.Recorder.end_segment | def end_segment(end_time: nil)
segment = current_segment
return unless segment
segment.close end_time: end_time
context.clear!
emitter.send_entity entity: segment if segment.ready_to_send?
end | ruby | def end_segment(end_time: nil)
segment = current_segment
return unless segment
segment.close end_time: end_time
context.clear!
emitter.send_entity entity: segment if segment.ready_to_send?
end | [
"def",
"end_segment",
"(",
"end_time",
":",
"nil",
")",
"segment",
"=",
"current_segment",
"return",
"unless",
"segment",
"segment",
".",
"close",
"end_time",
":",
"end_time",
"context",
".",
"clear!",
"emitter",
".",
"send_entity",
"entity",
":",
"segment",
"if",
"segment",
".",
"ready_to_send?",
"end"
] | End the current segment and send it to X-Ray daemon if it is ready. | [
"End",
"the",
"current",
"segment",
"and",
"send",
"it",
"to",
"X",
"-",
"Ray",
"daemon",
"if",
"it",
"is",
"ready",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/recorder.rb#L51-L57 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/recorder.rb | XRay.Recorder.begin_subsegment | def begin_subsegment(name, namespace: nil, segment: nil)
entity = segment || current_entity
return unless entity
if entity.sampled
subsegment = Subsegment.new name: name, segment: entity.segment, namespace: namespace
else
subsegment = DummySubsegment.new name: name, segment: entity.segment
end
# attach the new created subsegment under the current active entity
entity.add_subsegment subsegment: subsegment
# associate the new subsegment to the current context
context.store_entity entity: subsegment
subsegment
end | ruby | def begin_subsegment(name, namespace: nil, segment: nil)
entity = segment || current_entity
return unless entity
if entity.sampled
subsegment = Subsegment.new name: name, segment: entity.segment, namespace: namespace
else
subsegment = DummySubsegment.new name: name, segment: entity.segment
end
# attach the new created subsegment under the current active entity
entity.add_subsegment subsegment: subsegment
# associate the new subsegment to the current context
context.store_entity entity: subsegment
subsegment
end | [
"def",
"begin_subsegment",
"(",
"name",
",",
"namespace",
":",
"nil",
",",
"segment",
":",
"nil",
")",
"entity",
"=",
"segment",
"||",
"current_entity",
"return",
"unless",
"entity",
"if",
"entity",
".",
"sampled",
"subsegment",
"=",
"Subsegment",
".",
"new",
"name",
":",
"name",
",",
"segment",
":",
"entity",
".",
"segment",
",",
"namespace",
":",
"namespace",
"else",
"subsegment",
"=",
"DummySubsegment",
".",
"new",
"name",
":",
"name",
",",
"segment",
":",
"entity",
".",
"segment",
"end",
"# attach the new created subsegment under the current active entity",
"entity",
".",
"add_subsegment",
"subsegment",
":",
"subsegment",
"# associate the new subsegment to the current context",
"context",
".",
"store_entity",
"entity",
":",
"subsegment",
"subsegment",
"end"
] | Begin a new subsegment and add it to be the child of the current active
subsegment or segment. Also tie the new created subsegment to the current context.
Its sampling decision will follow its parent.
@return [Subsegment] the newly created subsegment. It could be `nil` if no active entity
can be found and `context_missing` is set to `LOG_ERROR`. | [
"Begin",
"a",
"new",
"subsegment",
"and",
"add",
"it",
"to",
"be",
"the",
"child",
"of",
"the",
"current",
"active",
"subsegment",
"or",
"segment",
".",
"Also",
"tie",
"the",
"new",
"created",
"subsegment",
"to",
"the",
"current",
"context",
".",
"Its",
"sampling",
"decision",
"will",
"follow",
"its",
"parent",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/recorder.rb#L64-L77 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/recorder.rb | XRay.Recorder.end_subsegment | def end_subsegment(end_time: nil)
entity = current_entity
return unless entity.is_a?(Subsegment)
entity.close end_time: end_time
# update current context
if entity.parent.closed?
context.clear!
else
context.store_entity entity: entity.parent
end
# check if the entire segment can be send.
# If not, stream subsegments when threshold is reached.
segment = entity.segment
if segment.ready_to_send?
emitter.send_entity entity: segment
elsif streamer.eligible? segment: segment
streamer.stream_subsegments root: segment, emitter: emitter
end
end | ruby | def end_subsegment(end_time: nil)
entity = current_entity
return unless entity.is_a?(Subsegment)
entity.close end_time: end_time
# update current context
if entity.parent.closed?
context.clear!
else
context.store_entity entity: entity.parent
end
# check if the entire segment can be send.
# If not, stream subsegments when threshold is reached.
segment = entity.segment
if segment.ready_to_send?
emitter.send_entity entity: segment
elsif streamer.eligible? segment: segment
streamer.stream_subsegments root: segment, emitter: emitter
end
end | [
"def",
"end_subsegment",
"(",
"end_time",
":",
"nil",
")",
"entity",
"=",
"current_entity",
"return",
"unless",
"entity",
".",
"is_a?",
"(",
"Subsegment",
")",
"entity",
".",
"close",
"end_time",
":",
"end_time",
"# update current context",
"if",
"entity",
".",
"parent",
".",
"closed?",
"context",
".",
"clear!",
"else",
"context",
".",
"store_entity",
"entity",
":",
"entity",
".",
"parent",
"end",
"# check if the entire segment can be send.",
"# If not, stream subsegments when threshold is reached.",
"segment",
"=",
"entity",
".",
"segment",
"if",
"segment",
".",
"ready_to_send?",
"emitter",
".",
"send_entity",
"entity",
":",
"segment",
"elsif",
"streamer",
".",
"eligible?",
"segment",
":",
"segment",
"streamer",
".",
"stream_subsegments",
"root",
":",
"segment",
",",
"emitter",
":",
"emitter",
"end",
"end"
] | End the current active subsegment. It also send the entire segment if
this subsegment is the last one open or stream out subsegments of its
parent segment if the stream threshold is breached. | [
"End",
"the",
"current",
"active",
"subsegment",
".",
"It",
"also",
"send",
"the",
"entire",
"segment",
"if",
"this",
"subsegment",
"is",
"the",
"last",
"one",
"open",
"or",
"stream",
"out",
"subsegments",
"of",
"its",
"parent",
"segment",
"if",
"the",
"stream",
"threshold",
"is",
"breached",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/recorder.rb#L89-L107 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.