_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q19100 | Writeexcel.Worksheet.store_images | train | def store_images #:nodoc:
# Skip this if there aren't any images.
return if @images.array.empty?
spid = @object_ids.spid
@images.array.each_index do |i|
@images.array[i].store_image_record(i, @images.array.size, charts_size, @filter_area.count, comments_size, spid)
store_obj_image(i + 1)
end
@object_ids.spid = spid
end | ruby | {
"resource": ""
} |
q19101 | Writeexcel.Worksheet.store_charts | train | def store_charts #:nodoc:
# Skip this if there aren't any charts.
return if charts_size == 0
record = 0x00EC # Record identifier
charts = @charts.array
charts.each_index do |i|
data = ''
if i == 0 && images_size == 0
dg_length = 192 + 120 * (charts_size - 1) + 96 * filter_count + 128 * comments_size
spgr_length = dg_length - 24
# Write the parent MSODRAWIING record.
data += store_parent_mso_record(dg_length, spgr_length, @object_ids.spid)
@object_ids.spid += 1
end
data += store_mso_sp_container_sp(@object_ids.spid)
data += store_mso_opt_chart_client_anchor_client_data(*charts[i].vertices)
length = data.bytesize
header = [record, length].pack("vv")
append(header, data)
store_obj_chart(images_size + i + 1)
store_chart_binary(charts[i].chart)
@object_ids.spid += 1
end
# Simulate the EXTERNSHEET link between the chart and data using a formula
# such as '=Sheet1!A1'.
# TODO. Won't work for external data refs. Also should use a more direct
# method.
#
store_formula("='#{@name}'!A1")
end | ruby | {
"resource": ""
} |
q19102 | Writeexcel.Worksheet.store_comments | train | def store_comments #:nodoc:
return if @comments.array.empty?
spid = @object_ids.spid
num_comments = comments_size
# Number of objects written so far.
num_objects = images_size + @filter_area.count + charts_size
@comments.array.each_index { |i| spid = @comments.array[i].store_comment_record(i, num_objects, num_comments, spid) }
# Write the NOTE records after MSODRAWIING records.
@comments.array.each_index { |i| @comments.array[i].store_note_record(num_objects + i + 1) }
end | ruby | {
"resource": ""
} |
q19103 | Writeexcel.Worksheet.store_mso_dg_container | train | def store_mso_dg_container(length) #:nodoc:
type = 0xF002
version = 15
instance = 0
data = ''
add_mso_generic(type, version, instance, data, length)
end | ruby | {
"resource": ""
} |
q19104 | Writeexcel.Worksheet.store_mso_dg | train | def store_mso_dg #:nodoc:
type = 0xF008
version = 0
length = 8
data = [@object_ids.num_shapes, @object_ids.max_spid].pack("VV")
add_mso_generic(type, version, @object_ids.drawings_saved, data, length)
end | ruby | {
"resource": ""
} |
q19105 | Writeexcel.Worksheet.store_mso_spgr_container | train | def store_mso_spgr_container(length) #:nodoc:
type = 0xF003
version = 15
instance = 0
data = ''
add_mso_generic(type, version, instance, data, length)
end | ruby | {
"resource": ""
} |
q19106 | Writeexcel.Worksheet.store_mso_spgr | train | def store_mso_spgr #:nodoc:
type = 0xF009
version = 1
instance = 0
data = [0, 0, 0, 0].pack("VVVV")
length = 16
add_mso_generic(type, version, instance, data, length)
end | ruby | {
"resource": ""
} |
q19107 | Writeexcel.Format.get_font | train | def get_font # :nodoc:
# my $record; # Record identifier
# my $length; # Record length
# my $dyHeight; # Height of font (1/20 of a point)
# my $grbit; # Font attributes
# my $icv; # Index to color palette
# my $bls; # Bold style
# my $sss; # Superscript/subscript
# my $uls; # Underline
# my $bFamily; # Font family
# my $bCharSet; # Character set
# my $reserved; # Reserved
# my $cch; # Length of font name
# my $rgch; # Font name
# my $encoding; # Font name character encoding
dyHeight = @size * 20
icv = @color
bls = @bold
sss = @font_script
uls = @underline
bFamily = @font_family
bCharSet = @font_charset
rgch = @font
encoding = @font_encoding
ruby_19 { rgch = convert_to_ascii_if_ascii(rgch) }
# Handle utf8 strings
if is_utf8?(rgch)
rgch = utf8_to_16be(rgch)
encoding = 1
end
cch = rgch.bytesize
#
# Handle Unicode font names.
if (encoding == 1)
raise "Uneven number of bytes in Unicode font name" if cch % 2 != 0
cch /= 2 if encoding !=0
rgch = utf16be_to_16le(rgch)
end
record = 0x31
length = 0x10 + rgch.bytesize
reserved = 0x00
grbit = 0x00
grbit |= 0x02 if @italic != 0
grbit |= 0x08 if @font_strikeout != 0
grbit |= 0x10 if @font_outline != 0
grbit |= 0x20 if @font_shadow != 0
header = [record, length].pack("vv")
data = [dyHeight, grbit, icv, bls,
sss, uls, bFamily,
bCharSet, reserved, cch, encoding].pack('vvvvvCCCCCC')
header + data + rgch
end | ruby | {
"resource": ""
} |
q19108 | Writeexcel.Format.set_border | train | def set_border(style)
set_bottom(style)
set_top(style)
set_left(style)
set_right(style)
end | ruby | {
"resource": ""
} |
q19109 | Writeexcel.Format.set_border_color | train | def set_border_color(color)
set_bottom_color(color)
set_top_color(color)
set_left_color(color)
set_right_color(color)
end | ruby | {
"resource": ""
} |
q19110 | Writeexcel.Format.method_missing | train | def method_missing(name, *args) # :nodoc:
# -- original perl comment --
# There are two types of set methods: set_property() and
# set_property_color(). When a method is AUTOLOADED we store a new anonymous
# sub in the appropriate slot in the symbol table. The speeds up subsequent
# calls to the same method.
method = "#{name}"
# Check for a valid method names, i.e. "set_xxx_yyy".
method =~ /set_(\w+)/ or raise "Unknown method: #{method}\n"
# Match the attribute, i.e. "@xxx_yyy".
attribute = "@#{$1}"
# Check that the attribute exists
# ........
if method =~ /set\w+color$/ # for "set_property_color" methods
value = get_color(args[0])
else # for "set_xxx" methods
value = args[0].nil? ? 1 : args[0]
end
if value.respond_to?(:to_str) || !value.respond_to?(:+)
s = %Q!#{attribute} = "#{value.to_s}"!
else
s = %Q!#{attribute} = #{value.to_s}!
end
eval s
end | ruby | {
"resource": ""
} |
q19111 | Writeexcel.Image.process_jpg | train | def process_jpg(data)
@type = 5 # Excel Blip type (MSOBLIPTYPE).
offset = 2
data_length = data.bytesize
# Search through the image data to find the 0xFFC0 marker. The height and
# width are contained in the data for that sub element.
while offset < data_length
marker = data[offset, 2].unpack("n")
marker = marker[0]
length = data[offset+2, 2].unpack("n")
length = length[0]
if marker == 0xFFC0 || marker == 0xFFC2
height = data[offset+5, 2].unpack("n")
@height = height[0]
width = data[offset+7, 2].unpack("n")
@width = width[0]
break
end
offset += length + 2
break if marker == 0xFFDA
end
raise "#{@filename}: no size data found in jpeg image.\n" unless @height
end | ruby | {
"resource": ""
} |
q19112 | YARD::CodeObjects.StepTransformerObject.value | train | def value
unless @processed
@processed = true
until (nested = constants_from_value).empty?
nested.each {|n| @value.gsub!(value_regex(n),find_value_for_constant(n)) }
end
end
@value
end | ruby | {
"resource": ""
} |
q19113 | YARD::CodeObjects.StepTransformerObject.constants_from_value | train | def constants_from_value(data=@value)
data.scan(escape_pattern).flatten.collect { |value| value.strip }
end | ruby | {
"resource": ""
} |
q19114 | YARD::CodeObjects.StepTransformerObject.find_value_for_constant | train | def find_value_for_constant(name)
constant = YARD::Registry.all(:constant).find{|c| c.name == name.to_sym }
log.warn "StepTransformer#find_value_for_constant : Could not find the CONSTANT [#{name}] using the string value." unless constant
constant ? strip_regex_from(constant.value) : name
end | ruby | {
"resource": ""
} |
q19115 | YARD::Parser::Cucumber.FeatureParser.parse | train | def parse
begin
@parser.parse(@source)
@feature = @builder.ast
return nil if @feature.nil? # Nothing matched
# The parser used the following keywords when parsing the feature
# @feature.language = @parser.i18n_language.get_code_keywords.map {|word| word }
rescue Gherkin::ParserError => e
e.message.insert(0, "#{@file}: ")
warn e
end
self
end | ruby | {
"resource": ""
} |
q19116 | CucumberApi.Response.has | train | def has json_path, json=nil
if json.nil?
json = JSON.parse body
end
not JsonPath.new(json_path).on(json).empty?
end | ruby | {
"resource": ""
} |
q19117 | CucumberApi.Response.get | train | def get json_path, json=nil
if json.nil?
json = JSON.parse body
end
results = JsonPath.new(json_path).on(json)
if results.empty?
raise %/Expected json path '#{json_path}' not found\n#{to_json_s}/
end
results.first
end | ruby | {
"resource": ""
} |
q19118 | CucumberApi.Response.get_as_type | train | def get_as_type json_path, type, json=nil
value = get json_path, json
case type
when 'numeric'
valid = value.is_a? Numeric
when 'array'
valid = value.is_a? Array
when 'string'
valid = value.is_a? String
when 'boolean'
valid = !!value == value
when 'numeric_string'
valid = value.is_a?(Numeric) or value.is_a?(String)
when 'object'
valid = value.is_a? Hash
else
raise %/Invalid expected type '#{type}'/
end
unless valid
raise %/Expect '#{json_path}' as a '#{type}' but was '#{value.class}'\n#{to_json_s}/
end
value
end | ruby | {
"resource": ""
} |
q19119 | CucumberApi.Response.get_as_type_or_null | train | def get_as_type_or_null json_path, type, json=nil
value = get json_path, json
value.nil? ? value : get_as_type(json_path, type, json)
end | ruby | {
"resource": ""
} |
q19120 | CucumberApi.Response.get_as_type_and_check_value | train | def get_as_type_and_check_value json_path, type, value, json=nil
v = get_as_type json_path, type, json
if value != v.to_s
raise %/Expect '#{json_path}' to be '#{value}' but was '#{v}'\n#{to_json_s}/
end
end | ruby | {
"resource": ""
} |
q19121 | Rails.Auth.authorized! | train | def authorized!(rack_env, allowed_by)
Env.new(rack_env).tap do |env|
env.authorize(allowed_by)
end.to_rack
end | ruby | {
"resource": ""
} |
q19122 | Rails.Auth.set_allowed_by | train | def set_allowed_by(rack_env, allowed_by)
Env.new(rack_env).tap do |env|
env.allowed_by = allowed_by
end.to_rack
end | ruby | {
"resource": ""
} |
q19123 | Rails.Auth.add_credential | train | def add_credential(rack_env, type, credential)
Env.new(rack_env).tap do |env|
env.credentials[type] = credential
end.to_rack
end | ruby | {
"resource": ""
} |
q19124 | Braid.Config.write_db | train | def write_db
new_db = {}
@db.keys.sort.each do |key|
new_db[key] = {}
Braid::Mirror::ATTRIBUTES.each do |k|
new_db[key][k] = @db[key][k] if @db[key].has_key?(k)
end
end
new_data = {
'config_version' => CURRENT_CONFIG_VERSION,
'mirrors' => new_db
}
File.open(@config_file, 'wb') do |f|
f.write JSON.pretty_generate(new_data)
f.write "\n"
end
end | ruby | {
"resource": ""
} |
q19125 | Benchmark.Memory.memory | train | def memory(quiet: false)
raise ConfigurationError unless block_given?
job = Job.new(quiet: quiet)
yield job
job.run
job.run_comparison
job.full_report
end | ruby | {
"resource": ""
} |
q19126 | Populator.Factory.populate | train | def populate(amount, options = {}, &block)
self.class.remember_depth do
build_records(Populator.interpret_value(amount), options[:per_query] || DEFAULT_RECORDS_PER_QUERY, &block)
end
end | ruby | {
"resource": ""
} |
q19127 | Populator.Factory.save_records | train | def save_records
unless @records.empty?
@model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, "#{@model_class.name} Populate")
@last_id_in_database = @records.last.id
@records.clear
end
end | ruby | {
"resource": ""
} |
q19128 | Populator.ModelAdditions.populate | train | def populate(amount, options = {}, &block)
Factory.for_model(self).populate(amount, options, &block)
end | ruby | {
"resource": ""
} |
q19129 | Populator.Random.value_in_range | train | def value_in_range(range)
case range.first
when Integer then number_in_range(range)
when Time then time_in_range(range)
when Date then date_in_range(range)
else range.to_a[rand(range.to_a.size)]
end
end | ruby | {
"resource": ""
} |
q19130 | Nmap.Program.scan | train | def scan(options={},exec_options={},&block)
run_task(Task.new(options,&block),exec_options)
end | ruby | {
"resource": ""
} |
q19131 | Nmap.Program.sudo_scan | train | def sudo_scan(options={},exec_options={},&block)
sudo_task(Task.new(options,&block),exec_options)
end | ruby | {
"resource": ""
} |
q19132 | Nmap.XML.scanner | train | def scanner
@scanner ||= Scanner.new(
@doc.root['scanner'],
@doc.root['version'],
@doc.root['args'],
Time.at(@doc.root['start'].to_i)
)
end | ruby | {
"resource": ""
} |
q19133 | Nmap.XML.scan_info | train | def scan_info
@doc.xpath('/nmaprun/scaninfo').map do |scaninfo|
Scan.new(
scaninfo['type'].to_sym,
scaninfo['protocol'].to_sym,
scaninfo['services'].split(',').map { |ports|
if ports.include?('-')
Range.new(*(ports.split('-',2)))
else
ports.to_i
end
}
)
end
end | ruby | {
"resource": ""
} |
q19134 | Nmap.XML.each_run_stat | train | def each_run_stat
return enum_for(__method__) unless block_given?
@doc.xpath('/nmaprun/runstats/finished').each do |run_stat|
yield RunStat.new(
Time.at(run_stat['time'].to_i),
run_stat['elapsed'],
run_stat['summary'],
run_stat['exit']
)
end
return self
end | ruby | {
"resource": ""
} |
q19135 | Nmap.XML.each_task | train | def each_task
return enum_for(__method__) unless block_given?
@doc.xpath('/nmaprun/taskbegin').each do |task_begin|
task_end = task_begin.xpath('following-sibling::taskend').first
yield ScanTask.new(
task_begin['task'],
Time.at(task_begin['time'].to_i),
Time.at(task_end['time'].to_i),
task_end['extrainfo']
)
end
return self
end | ruby | {
"resource": ""
} |
q19136 | Nmap.XML.each_up_host | train | def each_up_host
return enum_for(__method__) unless block_given?
@doc.xpath("/nmaprun/host[status[@state='up']]").each do |host|
yield Host.new(host)
end
return self
end | ruby | {
"resource": ""
} |
q19137 | Nmap.Host.each_address | train | def each_address
return enum_for(__method__) unless block_given?
@node.xpath("address[@addr]").each do |addr|
address = Address.new(
addr['addrtype'].to_sym,
addr['addr'],
addr['vendor']
)
yield address
end
return self
end | ruby | {
"resource": ""
} |
q19138 | Nmap.Host.each_hostname | train | def each_hostname
return enum_for(__method__) unless block_given?
@node.xpath("hostnames/hostname[@name]").each do |host|
yield Hostname.new(host['type'],host['name'])
end
return self
end | ruby | {
"resource": ""
} |
q19139 | Nmap.Host.uptime | train | def uptime
@uptime ||= if (uptime = @node.at_xpath('uptime'))
Uptime.new(
uptime['seconds'].to_i,
Time.parse(uptime['lastboot'])
)
end
yield @uptime if (@uptime && block_given?)
return @uptime
end | ruby | {
"resource": ""
} |
q19140 | Nmap.Host.each_tcp_port | train | def each_tcp_port
return enum_for(__method__) unless block_given?
@node.xpath("ports/port[@protocol='tcp']").each do |port|
yield Port.new(port)
end
return self
end | ruby | {
"resource": ""
} |
q19141 | Nmap.Scripts.script_data | train | def script_data
unless @script_data
@script_data = {}
traverse = lambda do |node|
case node.name
when 'script', 'table'
unless node.xpath('*[@key]').empty?
hash = {}
node.elements.each do |element|
hash[element['key']] = traverse.call(element)
end
hash
else
array = []
node.elements.each do |element|
array << traverse.call(element)
end
array
end
when 'elem'
node.inner_text
else
raise(NotImplementedError,"unrecognized XML NSE element: #{node}")
end
end
@node.xpath('script').each do |script|
@script_data[script['id']] = traverse.call(script)
end
end
return @script_data
end | ruby | {
"resource": ""
} |
q19142 | Nmap.Traceroute.each | train | def each
return enum_for(__method__) unless block_given?
@node.xpath('hop').each do |hop|
yield Hop.new(hop['ipaddr'],hop['host'],hop['ttl'],hop['rtt'])
end
return self
end | ruby | {
"resource": ""
} |
q19143 | Nmap.OS.each_class | train | def each_class
return enum_for(__method__) unless block_given?
@node.xpath("osmatch/osclass").each do |osclass|
yield OSClass.new(osclass)
end
return self
end | ruby | {
"resource": ""
} |
q19144 | Nmap.OS.each_match | train | def each_match
return enum_for(__method__) unless block_given?
@node.xpath("osmatch").map do |osclass|
os_match = OSMatch.new(
osclass['name'],
osclass['accuracy'].to_i
)
yield os_match
end
return self
end | ruby | {
"resource": ""
} |
q19145 | RubyBBCode.BBTree.retrogress_bbtree | train | def retrogress_bbtree
if @tags_list[-1].definition[:self_closable]
# It is possible that the next (self_closable) tag is on the next line
# Remove newline of current tag and parent tag as they are (probably) not intented as an actual newline here but as tag separator
@tags_list[-1][:nodes][0][:text].chomp! unless @tags_list[-1][:nodes][0][:text].nil?
@tags_list[-2][:nodes][0][:text].chomp! unless @tags_list.length < 2 or @tags_list[-2][:nodes][0][:text].nil?
end
@tags_list.pop # remove latest tag in tags_list since it's closed now...
# The parsed data manifests in @bbtree.current_node.children << TagNode.new(element) which I think is more confusing than needed
if within_open_tag?
@current_node = @tags_list[-1]
else # If we're still at the root of the BBTree or have returned back to the root via encountring closing tags...
@current_node = TagNode.new({:nodes => self.nodes}) # Note: just passing in self works too...
end
end | ruby | {
"resource": ""
} |
q19146 | RubyBBCode.TagSifter.get_formatted_between | train | def get_formatted_between
between = @ti[:text]
# perform special formatting for cenrtain tags
between = match_url_id(between, @bbtree.current_node.definition[:url_matches]) if @bbtree.current_node.definition[:url_matches]
return between
end | ruby | {
"resource": ""
} |
q19147 | Docker::Compose.Session.up | train | def up(*services,
abort_on_container_exit: false,
detached: false, timeout: 10, build: false,
exit_code_from: nil,
no_build: false, no_deps: false, no_start: false)
o = opts(
abort_on_container_exit: [abort_on_container_exit, false],
d: [detached, false],
timeout: [timeout, 10],
build: [build, false],
exit_code_from: [exit_code_from, nil],
no_build: [no_build, false],
no_deps: [no_deps, false],
no_start: [no_start, false]
)
run!('up', o, services)
true
end | ruby | {
"resource": ""
} |
q19148 | Docker::Compose.Session.scale | train | def scale(container_count, timeout: 10)
args = container_count.map {|service, count| "#{service}=#{count}"}
o = opts(timeout: [timeout, 10])
run!('scale', o, *args)
end | ruby | {
"resource": ""
} |
q19149 | Docker::Compose.Session.run | train | def run(service, *cmd, detached: false, no_deps: false, volumes: [], env: [], rm: false, no_tty: false, user: nil, service_ports: false)
o = opts(d: [detached, false], no_deps: [no_deps, false], rm: [rm, false], T: [no_tty, false], u: [user, nil], service_ports: [service_ports, false])
env_params = env.map { |v| { e: v } }
volume_params = volumes.map { |v| { v: v } }
run!('run', o, *env_params, *volume_params, service, cmd)
end | ruby | {
"resource": ""
} |
q19150 | Docker::Compose.Session.stop | train | def stop(*services, timeout: 10)
o = opts(timeout: [timeout, 10])
run!('stop', o, services)
end | ruby | {
"resource": ""
} |
q19151 | Docker::Compose.Session.kill | train | def kill(*services, signal: 'KILL')
o = opts(signal: [signal, 'KILL'])
run!('kill', o, services)
end | ruby | {
"resource": ""
} |
q19152 | Docker::Compose.Session.version | train | def version(short: false)
o = opts(short: [short, false])
result = run!('version', o, file: false, dir: false)
if short
result.strip
else
lines = result.split(/[\r\n]+/)
lines.inject({}) do |h, line|
kv = line.split(/: +/, 2)
h[kv.first] = kv.last
h
end
end
end | ruby | {
"resource": ""
} |
q19153 | Docker::Compose.Session.run! | train | def run!(*args)
file_args = case @file
when 'docker-compose.yml'
[]
when Array
# backticks sugar can't handle array values; build a list of hashes
# IMPORTANT: preserve the order of the files so overrides work correctly
file_args = @file.map { |filepath| { :file => filepath } }
else
# a single String (or Pathname, etc); use normal sugar to add it
[{ file: @file.to_s }]
end
@shell.chdir = dir
@last_command = @shell.run('docker-compose', *file_args, *args).join
status = @last_command.status
out = @last_command.captured_output
err = @last_command.captured_error
status.success? || fail(Error.new(args.first, status, out+err))
out
end | ruby | {
"resource": ""
} |
q19154 | Docker::Compose.Session.parse | train | def parse(str)
fields = []
nest = 0
field = ''
str.each_char do |ch|
got = false
if nest == 0
if ch == '('
nest += 1
end
else
if ch == '('
nest += 1
field << ch
elsif ch == ')'
nest -= 1
if nest == 0
got = true
else
field << ch
end
else
field << ch
end
end
if got
fields << field
field = ''
end
end
fields
end | ruby | {
"resource": ""
} |
q19155 | Docker::Compose.RakeTasks.export_env | train | def export_env(print:)
Docker::Compose::Mapper.map(host_env,
session: @session,
net_info: @net_info) do |k, v|
ENV[k] = serialize_for_env(v)
print_env(k, ENV[k]) if print
end
extra_host_env.each do |k, v|
ENV[k] = serialize_for_env(v)
print_env(k, ENV[k]) if print
end
end | ruby | {
"resource": ""
} |
q19156 | Docker::Compose.RakeTasks.serialize_for_env | train | def serialize_for_env(v)
case v
when String
v
when NilClass
nil
when Array
JSON.dump(v)
else
fail ArgumentError, "Can't represent a #{v.class} in the environment"
end
end | ruby | {
"resource": ""
} |
q19157 | Docker::Compose.RakeTasks.print_env | train | def print_env(k, v)
if v
puts @shell_printer.export(k, v)
else
puts @shell_printer.unset(k)
end
end | ruby | {
"resource": ""
} |
q19158 | Docker::Compose.NetInfo.docker_routable_ip | train | def docker_routable_ip
case @docker_url.scheme
when 'tcp', 'http', 'https'
docker_dns = @docker_url.host
docker_port = @docker_url.port || 2376
else
# Cheap trick: for unix, file or other protocols, assume docker ports
# are proxied to localhost in addition to other interfaces
docker_dns = 'localhost'
docker_port = 2376
end
addr = Addrinfo.getaddrinfo(
docker_dns, docker_port,
Socket::AF_INET, Socket::SOCK_STREAM).first
addr && addr.ip_address
end | ruby | {
"resource": ""
} |
q19159 | Docker::Compose.Mapper.map | train | def map(value)
if value.respond_to?(:map)
value.map { |e| map_scalar(e) }
else
map_scalar(value)
end
end | ruby | {
"resource": ""
} |
q19160 | Docker::Compose.Mapper.map_scalar | train | def map_scalar(value)
uri = begin
URI.parse(value)
rescue
nil
end
pair = value.split(':')
if uri && uri.scheme && uri.host
# absolute URI with scheme, authority, etc
uri.host, uri.port = host_and_port(uri.host, uri.port)
return uri.to_s
elsif pair.size == 2
# "host:port" pair; three sub-cases...
if pair.first =~ ELIDED
# output only the port
service = pair.first.gsub(REMOVE_ELIDED, '')
_, port = host_and_port(service, pair.last)
return port.to_s
elsif pair.last =~ ELIDED
# output only the hostname; resolve the port anyway to ensure that
# the service is running.
service = pair.first
port = pair.last.gsub(REMOVE_ELIDED, '')
host, = host_and_port(service, port)
return host
else
# output port:hostname pair
host, port = host_and_port(pair.first, pair.last)
return "#{host}:#{port}"
end
else
fail BadSubstitution, "Can't understand '#{value}'"
end
end | ruby | {
"resource": ""
} |
q19161 | Rubicure.Girl.birthday? | train | def birthday?(date = Date.today)
return false unless have_birthday?
# NOTE: birthday is "mm/dd"
month, day = birthday.split("/")
birthday_date = Date.new(date.year, month.to_i, day.to_i)
birthday_date == date
end | ruby | {
"resource": ""
} |
q19162 | Rubicure.Core.all_stars | train | def all_stars(arg = Time.current)
extra_girls = []
# args is Time or Date
date = to_date(arg)
if date
last_all_stars_date = Rubicure::Movie.find(:stmm).started_date
if date > last_all_stars_date
date = last_all_stars_date
end
else
# args is movie name
movie = Rubicure::Movie.find(arg.to_sym)
date = movie.started_date
if movie.has_key?(:extra_girls)
extra_girls = movie.extra_girls.map {|girl_name| Rubicure::Girl.find(girl_name.to_sym) }
end
end
all_girls(date) - [Cure.echo] + extra_girls
end | ruby | {
"resource": ""
} |
q19163 | Rubicure.Core.all_girls | train | def all_girls(arg = Time.current)
date = to_date(arg)
unless @all_girls
@all_girls = []
Rubicure::Girl.names.each do |girl_name|
@all_girls << Rubicure::Girl.find(girl_name)
end
@all_girls.uniq!(&:human_name)
end
@all_girls.select {|girl| girl.created_date && girl.created_date <= date }
end | ruby | {
"resource": ""
} |
q19164 | Rubicure.Core.dream_stars | train | def dream_stars
return @dream_stars if @dream_stars
girls = Precure.go_princess.girls + Precure.maho_girls.girls + Precure.a_la_mode.girls
dream_stars_date = Rubicure::Movie.find(:dream_stars).started_date
@dream_stars = girls.select {|girl| girl.created_date && girl.created_date <= dream_stars_date }
@dream_stars
end | ruby | {
"resource": ""
} |
q19165 | Rubicure.Core.super_stars | train | def super_stars
return @super_stars if @super_stars
girls = Precure.maho_girls.girls + Precure.a_la_mode.girls + Precure.hugtto.girls
super_stars_date = Rubicure::Movie.find(:super_stars).started_date
@super_stars = girls.select {|girl| girl.created_date && girl.created_date <= super_stars_date }
@super_stars
end | ruby | {
"resource": ""
} |
q19166 | MigrationComments::ActiveRecord::ConnectionAdapters.PostgreSQLAdapter.set_column_comment | train | def set_column_comment(table_name, column_name, comment_text)
execute comment_sql(CommentDefinition.new(table_name, column_name, comment_text))
end | ruby | {
"resource": ""
} |
q19167 | Microformats.FormatParser.imply_dates | train | def imply_dates
return unless !@properties['end'].nil? && !@properties['start'].nil?
start_date = nil
@properties['start'].each do |start_val|
if start_val =~ /^(\d{4}-[01]\d-[0-3]\d)/
start_date = Regexp.last_match(1) if start_date.nil?
elsif start_val =~ /^(\d{4}-[0-3]\d\d)/
start_date = Regexp.last_match(1) if start_date.nil?
end
end
unless start_date.nil?
@properties['end'].map! do |end_val|
if end_val.match?(/^\d{4}-[01]\d-[0-3]\d/)
end_val
elsif end_val.match?(/^\d{4}-[0-3]\d\d/)
end_val
else
start_date + ' ' + end_val
end
end
end
end | ruby | {
"resource": ""
} |
q19168 | MarkovChains.Generator.get_sentences | train | def get_sentences(n)
sentences = []
n.times do
sentence = @dict.get_start_words
while nw = @dict.get(sentence[-@dict.order, @dict.order])
sentence << nw
end
sentences << (sentence[0...-1].join(" ").gsub(/\s([,;:])/, '\1') << sentence.last)
end
sentences
end | ruby | {
"resource": ""
} |
q19169 | DryCrud.Nestable.parents | train | def parents
@parents ||= Array(nesting).map do |p|
if p.is_a?(Class) && p < ActiveRecord::Base
parent_entry(p)
else
p
end
end
end | ruby | {
"resource": ""
} |
q19170 | BinProxy.ProxyMessage.headers | train | def headers
super.merge({
size: @raw.length,
# HACK - this will prevent errors, but will mangle anything that isn't
# actually utf8. We should try to handle this upstream where we might
# know what the actual encoding is.
summary: @message.summary.force_encoding('UTF-8').scrub,
message_class: @message_class.to_s,
})
end | ruby | {
"resource": ""
} |
q19171 | BinProxy.Parser.parse | train | def parse(raw_buffer, peer)
start_pos = nil
loop do
break if raw_buffer.eof?
start_pos = raw_buffer.pos
log.debug "at #{start_pos} of #{raw_buffer.length} in buffer"
read_fn = lambda { message_class.new(src: peer.to_s, protocol_state: @protocol_state).read(raw_buffer) }
message = if log.debug?
BinData::trace_reading &read_fn
else
read_fn.call
end
bytes_read = raw_buffer.pos - start_pos
log.debug "read #{bytes_read} bytes"
# Go back and grab raw bytes for validation of serialization
raw_buffer.pos = start_pos
raw_m = raw_buffer.read bytes_read
@protocol_state = message.update_state
log.debug "protocol state is now #{@protocol_state.inspect}"
pm = ProxyMessage.new(raw_m, message)
pm.src = peer
yield pm
end
rescue EOFError, IOError
log.info "Hit end of buffer while parsing. Consumed #{raw_buffer.pos - start_pos} bytes."
raw_buffer.pos = start_pos #rewind partial read
#todo, warn to client if validate flag set?
rescue Exception => e
log.err_trace(e, 'parsing message (probably an issue with user BinData class)', ::Logger::WARN)
self.class.proxy.on_bindata_error('parsing', e)
end | ruby | {
"resource": ""
} |
q19172 | BinProxy.Connection.connect | train | def connect(host=nil, port=nil, &cb)
host ||= opts[:upstream_host] || raise('no upstream host')
port ||= opts[:upstream_port] || raise('no upstream port')
cb ||= lambda { |conn| opts[:session_callback].call(self, conn) }
log.debug "Making upstream connection to #{host}:#{port}"
EM.connect(host, port, Connection, opts[:upstream_args], &cb)
end | ruby | {
"resource": ""
} |
q19173 | BinProxy.Connection.send_message | train | def send_message(pm)
log.error "OOPS! message going the wrong way (to #{peer})" if pm.dest != peer
data = pm.to_binary_s
@filters.each do |f|
data = f.write data
return if data.nil? or data == ''
end
send_data(data)
end | ruby | {
"resource": ""
} |
q19174 | ZMQ.Message.update_state | train | def update_state
current_state.dup.tap do |s|
src = eval_parameter :src
s[src] = next_state s[src]
end
end | ruby | {
"resource": ""
} |
q19175 | Couchbase.Cluster.create_bucket | train | def create_bucket(name, options = {})
defaults = {
:type => "couchbase",
:ram_quota => 100,
:replica_number => 1,
:auth_type => "sasl",
:sasl_password => "",
:proxy_port => nil,
:flush_enabled => false,
:replica_index => true,
:parallel_db_and_view_compaction => false
}
options = defaults.merge(options)
params = {"name" => name}
params["bucketType"] = options[:type]
params["ramQuotaMB"] = options[:ram_quota]
params["replicaNumber"] = options[:replica_number]
params["authType"] = options[:auth_type]
params["saslPassword"] = options[:sasl_password]
params["proxyPort"] = options[:proxy_port]
params["flushEnabled"] = options[:flush_enabled] ? 1 : 0
params["replicaIndex"] = options[:replica_index] ? 1 : 0
params["parallelDBAndViewCompaction"] = !!options[:parallel_db_and_view_compaction]
payload = Utils.encode_params(params.reject! { |_k, v| v.nil? })
response = @connection.send(:__http_query, :management, :post,
"/pools/default/buckets", payload,
"application/x-www-form-urlencoded", nil, nil, nil)
Result.new(response.merge(:operation => :create_bucket))
end | ruby | {
"resource": ""
} |
q19176 | Couchbase.DNS.locate | train | def locate(name, bootstrap_protocol = :http)
service = case bootstrap_protocol
when :http
"_cbhttp"
when :cccp
"_cbmcd"
else
raise ArgumentError, "unknown bootstrap protocol: #{bootstrap_transports}"
end
hosts = []
Resolv::DNS.open do |dns|
resources = dns.getresources("#{service}._tcp.#{name}", Resolv::DNS::Resource::IN::SRV)
hosts = resources.sort_by(&:priority).map { |res| "#{res.target}:#{res.port}" }
end
hosts
end | ruby | {
"resource": ""
} |
q19177 | Couchbase.View.fetch | train | def fetch(params = {})
params = @params.merge(params)
options = {}
options[:include_docs] = params.delete(:include_docs) if params.key?(:include_docs)
options[:format] = params.delete(:format) if params.key?(:format)
options[:transcoder] = params.delete(:transcoder) if params.key?(:transcoder)
options[:spatial] = params.delete(:spatial) if params.key?(:spatial)
body = params.delete(:body) || {}
body = MultiJson.dump(body) unless body.is_a?(String)
res = @bucket.send(:__view_query, @ddoc, @view, Utils.encode_params(params), body, options)
raise res[:error] if res[:error]
meta = MultiJson.load(res[:meta])
send_error(meta[S_ERRORS][S_FROM], meta[S_ERRORS][S_REASON]) if meta[S_ERRORS]
if block_given?
res[:rows].each do |row|
yield @wrapper_class.wrap(row)
end
else
rows = res[:rows].map { |row| @wrapper_class.wrap(row) }
ArrayWithTotalRows.new(rows, meta[S_TOTAL_ROWS])
end
end | ruby | {
"resource": ""
} |
q19178 | Couchbase.DesignDoc.method_missing | train | def method_missing(meth, *args)
name, options = @all_views[meth.to_s]
if name
View.new(@bucket, @id, name, (args[0] || {}).merge(options))
else
super
end
end | ruby | {
"resource": ""
} |
q19179 | Couchbase.Bucket.cas | train | def cas(key, options = {})
retries_remaining = options.delete(:retry) || 0
loop do
res = get(key, options)
val = yield(res.value) # get new value from caller
res = set(key, val, options.merge(:cas => res.cas))
if res.error && res.error.code == Couchbase::LibraryError::LCB_KEY_EEXISTS
if retries_remaining > 0
retries_remaining -= 1
next
end
end
return res
end
end | ruby | {
"resource": ""
} |
q19180 | Couchbase.Bucket.design_docs | train | def design_docs
req = __http_query(:management, :get, "/pools/default/buckets/#{bucket}/ddocs", nil, nil, nil, nil, nil)
docmap = {}
res = MultiJson.load(req[:chunks].join)
res["rows"].each do |obj|
obj['doc']['value'] = obj['doc'].delete('json') if obj['doc']
doc = DesignDoc.new(self, obj)
next if environment == :production && doc.id =~ /dev_/
docmap[doc.id] = doc
end
docmap
end | ruby | {
"resource": ""
} |
q19181 | Couchbase.Bucket.save_design_doc | train | def save_design_doc(data)
attrs = case data
when String
MultiJson.load(data)
when IO
MultiJson.load(data.read)
when Hash
data
else
raise ArgumentError, "Document should be Hash, String or IO instance"
end
id = attrs.delete('_id').to_s
attrs['language'] ||= 'javascript'
raise ArgumentError, "'_id' key must be set and start with '_design/'." if id !~ /\A_design\//
res = __http_query(:view, :put, "/#{id}", MultiJson.dump(attrs), 'application/json', nil, nil, nil)
return true if res[:status] == 201
val = MultiJson.load(res[:chunks].join)
raise Error::View.new("save_design_doc", val['error'])
end | ruby | {
"resource": ""
} |
q19182 | Couchbase.Bucket.delete_design_doc | train | def delete_design_doc(id, rev = nil)
ddoc = design_docs[id.sub(/^_design\//, '')]
return false unless ddoc
path = Utils.build_query(ddoc.id, :rev => rev || ddoc.meta['rev'])
res = __http_query(:view, :delete, path, nil, nil, nil, nil, nil)
return true if res[:status] == 200
val = MultiJson.load(res[:chunks].join)
raise Error::View.new("delete_design_doc", val['error'])
end | ruby | {
"resource": ""
} |
q19183 | Couchbase.Bucket.observe_and_wait | train | def observe_and_wait(*keys, &block)
options = {:timeout => default_observe_timeout}
options.update(keys.pop) if keys.size > 1 && keys.last.is_a?(Hash)
verify_observe_options(options)
raise ArgumentError, "at least one key is required" if keys.empty?
key_cas = if keys.size == 1 && keys[0].is_a?(Hash)
keys[0]
else
keys.flatten.each_with_object({}) do |kk, h|
h[kk] = nil # set CAS to nil
end
end
res = do_observe_and_wait(key_cas, options, &block) while res.nil?
return res.values.first if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol))
return res
end | ruby | {
"resource": ""
} |
q19184 | Effective.CrudController.resource_scope | train | def resource_scope # Thing
@_effective_resource_relation ||= (
relation = case @_effective_resource_scope # If this was initialized by the resource_scope before_filter
when ActiveRecord::Relation
@_effective_resource_scope
when Hash
effective_resource.klass.where(@_effective_resource_scope)
when Symbol
effective_resource.klass.send(@_effective_resource_scope)
when nil
effective_resource.klass.respond_to?(:all) ? effective_resource.klass.all : effective_resource.klass
else
raise "expected resource_scope method to return an ActiveRecord::Relation or Hash"
end
unless relation.kind_of?(ActiveRecord::Relation) || effective_resource.active_model?
raise("unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.")
end
relation
)
end | ruby | {
"resource": ""
} |
q19185 | TemplateMethodable.ClassMethods.must_impl | train | def must_impl(*methods)
return if methods.nil?
fail TypeError, "invalid args type #{methods.class}. you must use Array or Symbol" unless methods.class.any_of? Array, Symbol
methods = (methods.class.is_a? Symbol) ? [methods] : methods
methods.each do |method_name|
fail TypeError, "invalid args type #{method_name.class}. you must use Symbol" unless method_name.is_a? Symbol
define_method method_name do |*args|
fail NotImplementedError.new
end
end
end | ruby | {
"resource": ""
} |
q19186 | Effective.CodeReader.each_with_depth | train | def each_with_depth(from: nil, to: nil, &block)
Array(lines).each_with_index do |line, index|
next if index < (from || 0)
depth = line.length - line.lstrip.length
block.call(line.strip, depth, index)
break if to == index
end
nil
end | ruby | {
"resource": ""
} |
q19187 | Effective.CodeReader.index | train | def index(from: nil, to: nil, &block)
each_with_depth(from: from, to: to) do |line, depth, index|
return index if block.call(line, depth, index)
end
end | ruby | {
"resource": ""
} |
q19188 | Effective.CodeReader.last | train | def last(from: nil, to: nil, &block)
retval = nil
each_with_depth(from: from, to: nil) do |line, depth, index|
retval = line if block.call(line, depth, index)
end
retval
end | ruby | {
"resource": ""
} |
q19189 | Effective.CodeReader.select | train | def select(from: nil, to: nil, &block)
retval = []
each_with_depth(from: from, to: to) do |line, depth, index|
retval << line if (block_given? == false || block.call(line, depth, index))
end
retval
end | ruby | {
"resource": ""
} |
q19190 | ActsAsStatused.CanCan.acts_as_statused | train | def acts_as_statused(klass, only: nil, except: nil)
raise "klass does not implement acts_as_statused" unless klass.acts_as_statused?
statuses = klass.const_get(:STATUSES)
instance = klass.new
only = Array(only).compact
except = Array(except).compact
statuses.each_with_index do |status, index|
action = status_active_verb(status, instance)
next if action.blank?
next if only.present? && !only.include?(action)
next if except.present? && except.include?(action)
if index == 0
can(action, klass) and next
end
if status == :approved && statuses.include?(:declined)
if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0
can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") || obj.declined? }
next
end
end
if status == :declined && statuses.include?(:approved)
if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0
can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") }
next
end
end
can(action, klass) { |obj| obj.public_send("#{statuses[index-1]}?") }
end
end | ruby | {
"resource": ""
} |
q19191 | ActsAsStatused.CanCan.status_active_verb | train | def status_active_verb(status, instance)
status = status.to_s.strip
if status.end_with?('ied')
action = status[0...-3] + 'y'
return action.to_sym if instance.respond_to?(action + '!')
end
# ed, e, ing
[-1, -2, -3].each do |index|
action = status[0...index]
return action.to_sym if instance.respond_to?(action + '!')
end
nil
end | ruby | {
"resource": ""
} |
q19192 | Runt.Schedule.dates | train | def dates(event, date_range)
result=[]
date_range.each do |date|
result.push date if include?(event,date)
end
result
end | ruby | {
"resource": ""
} |
q19193 | Runt.Schedule.include? | train | def include?(event, date)
return false unless @elems.include?(event)
return 0<(self.select{|ev,xpr| ev.eql?(event)&&xpr.include?(date);}).size
end | ruby | {
"resource": ""
} |
q19194 | Fixy.Record.generate | train | def generate(debug = false)
decorator = debug ? Fixy::Decorator::Debug : Fixy::Decorator::Default
output = ''
current_position = 1
current_record = 1
while current_position <= self.class.record_length do
field = record_fields[current_position]
raise StandardError, "Undefined field for position #{current_position}" unless field
# We will first retrieve the value, then format it
method = field[:name]
value = send(method)
formatted_value = format_value(value, field[:size], field[:type])
formatted_value = decorator.field(formatted_value, current_record, current_position, method, field[:size], field[:type])
output << formatted_value
current_position = field[:to] + 1
current_record += 1
end
# Documentation mandates that every record ends with new line.
output << line_ending
# All ready. In the words of Mr. Peters: "Take it and go!"
decorator.record(output)
end | ruby | {
"resource": ""
} |
q19195 | Gas.Users.exists? | train | def exists?(nickname)
users.each do |user|
if user.nickname == nickname
return true;
end
end
false
end | ruby | {
"resource": ""
} |
q19196 | Gas.Users.get | train | def get(nickname)
users.each do |user|
if user.nickname == nickname.to_s
return user
end
end
nil
end | ruby | {
"resource": ""
} |
q19197 | Gas.Users.to_s | train | def to_s
current_user = GitConfig.current_user
users.map do |user|
if current_user == user
" ==> #{user.to_s[5,user.to_s.length]}"
else
user.to_s
end
end.join "\n"
end | ruby | {
"resource": ""
} |
q19198 | Ferret.FieldSymbolMethods.desc | train | def desc
fsym = FieldSymbol.new(self, respond_to?(:desc?) ? !desc? : true)
fsym.type = respond_to?(:type) ? type : nil
fsym
end | ruby | {
"resource": ""
} |
q19199 | Ferret.Document.to_s | train | def to_s
buf = ["Document {"]
self.keys.sort_by {|key| key.to_s}.each do |key|
val = self[key]
val_str = if val.instance_of? Array then %{["#{val.join('", "')}"]}
elsif val.is_a? Field then val.to_s
else %{"#{val.to_s}"}
end
buf << " :#{key} => #{val_str}"
end
buf << ["}#{@boost == 1.0 ? "" : "^" + @boost.to_s}"]
return buf.join("\n")
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.