_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q8600
|
Synacrb.Session.verify_callback
|
train
|
def verify_callback(_, cert)
pem = cert.current_cert.public_key.to_pem
sha256 = OpenSSL::Digest::SHA256.new
hash = sha256.digest(pem).unpack("H*")
hash[0].casecmp(@hash).zero?
end
|
ruby
|
{
"resource": ""
}
|
q8601
|
Synacrb.Session.login_with_token
|
train
|
def login_with_token(bot, name, token)
send Common::Login.new(bot, name, nil, token)
end
|
ruby
|
{
"resource": ""
}
|
q8602
|
Synacrb.Session.send
|
train
|
def send(packet)
id = Common.packet_to_id(packet)
data = [id, [packet.to_a]].to_msgpack
@stream.write Common.encode_u16(data.length)
@stream.write data
end
|
ruby
|
{
"resource": ""
}
|
q8603
|
Synacrb.Session.read
|
train
|
def read()
size_a = @stream.read 2
size = Common.decode_u16(size_a)
data = @stream.read size
data = MessagePack.unpack data
class_ = Common.packet_from_id data[0]
class_.new *data[1][0]
end
|
ruby
|
{
"resource": ""
}
|
q8604
|
Trustvox.Store.create
|
train
|
def create(store_data)
auth_by_platform_token!
response = self.class.post('/stores', { body: store_data.to_json })
data = JSON.parse(response.body) rescue nil
{
status: response.code,
data: data,
}
end
|
ruby
|
{
"resource": ""
}
|
q8605
|
Trustvox.Store.push_order
|
train
|
def push_order(order_data)
body = Utils.build_push_order_data(order_data)
auth_by_store_token!
response = self.class.post("/stores/#{Config.store_id}/orders", { body: body.to_json })
data = JSON.parse(response.body) rescue nil
{ status: response.code, data: data }
end
|
ruby
|
{
"resource": ""
}
|
q8606
|
Trustvox.Store.load_store
|
train
|
def load_store(url)
auth_by_platform_token!
response = self.class.get("/stores", { query: { url: url} })
data = JSON.parse(response.body) rescue nil
{
status: response.code,
data: data,
}
end
|
ruby
|
{
"resource": ""
}
|
q8607
|
GemFootprintAnalyzer.AverageRunner.calculate_averages
|
train
|
def calculate_averages(results)
Array.new(results.first.size) do |require_number|
samples = results.map { |r| r[require_number] }
first_sample = samples.first
average = initialize_average_with_copied_fields(first_sample)
AVERAGED_FIELDS.map do |field|
next unless first_sample.key?(field)
average[field] = calculate_average(samples.map { |s| s[field] })
end
average
end
end
|
ruby
|
{
"resource": ""
}
|
q8608
|
MaRuKu.Helpers.md_el
|
train
|
def md_el(node_type, children=[], meta={}, al=nil)
if (e=children.first).kind_of?(MDElement) and
e.node_type == :ial then
if al
al += e.ial
else
al = e.ial
end
children.shift
end
e = MDElement.new(node_type, children, meta, al)
e.doc = @doc
return e
end
|
ruby
|
{
"resource": ""
}
|
q8609
|
Actn.Paths.find_root_with_flag
|
train
|
def find_root_with_flag(flag, default=nil)
root_path = self.called_from[0]
while root_path && ::File.directory?(root_path) && !::File.exist?("#{root_path}/#{flag}")
parent = ::File.dirname(root_path)
root_path = parent != root_path && parent
end
root = ::File.exist?("#{root_path}/#{flag}") ? root_path : default
raise "Could not find root path for #{self}" unless root
RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ?
Pathname.new(root).expand_path : Pathname.new(root).realpath
end
|
ruby
|
{
"resource": ""
}
|
q8610
|
Gaigo.FormHelper.ilabel
|
train
|
def ilabel(object_name, method, content_or_options = nil, options = nil, &block)
options ||= {}
content_is_options = content_or_options.is_a?(Hash)
if content_is_options || block_given?
options.merge!(content_or_options) if content_is_options
text = nil
else
text = content_or_options
end
ActionView::Helpers::InstanceTag.new(object_name, method, self, options.delete(:object)).to_ilabel_tag(text, options, &block)
end
|
ruby
|
{
"resource": ""
}
|
q8611
|
Synacrb.State.get_private_channel
|
train
|
def get_private_channel(user)
@users.keys
.map { |channel| @channels[channel] }
.compact
.find { |channel| channel.private }
# the server doesn't send PMs you don't have access to
end
|
ruby
|
{
"resource": ""
}
|
q8612
|
Synacrb.State.get_recipient_unchecked
|
train
|
def get_recipient_unchecked(channel_id)
@users.values
.find { |user| user.modes.keys
.any { |channel| channel == channel_id }}
end
|
ruby
|
{
"resource": ""
}
|
q8613
|
Rester.Client._init_requester
|
train
|
def _init_requester
if circuit_breaker_enabled?
@_requester = Utils::CircuitBreaker.new(
threshold: error_threshold, retry_period: retry_period
) { |*args| _request(*args) }
@_requester.on_open do
logger.error("circuit opened for #{name}")
end
@_requester.on_close do
logger.info("circuit closed for #{name}")
end
else
@_requester = proc { |*args| _request(*args) }
end
end
|
ruby
|
{
"resource": ""
}
|
q8614
|
Rester.Client._request
|
train
|
def _request(verb, path, params)
Rester.wrap_request do
Rester.request_info[:producer_name] = name
Rester.request_info[:path] = path
Rester.request_info[:verb] = verb
logger.info('sending request')
_set_default_headers
start_time = Time.now.to_f
begin
response = adapter.request(verb, path, params)
_process_response(start_time, verb, path, *response)
rescue Errors::TimeoutError
logger.error('timed out')
raise
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8615
|
Danger.DangerJunitResults.parse
|
train
|
def parse(file_path)
require 'nokogiri'
@doc = Nokogiri::XML(File.open(file_path))
@total_count = @doc.xpath('//testsuite').map { |x| x.attr('tests').to_i }.inject(0){ |sum, x| sum + x }
@skipped_count = @doc.xpath('//testsuite').map { |x| x.attr('skipped').to_i }.inject(0){ |sum, x| sum + x }
@executed_count = @total_count - @skipped_count
@failed_count = @doc.xpath('//testsuite').map { |x| x.attr('failures').to_i }.inject(0){ |sum, x| sum + x }
@failures = @doc.xpath('//failure')
return @failed_count <= 0
end
|
ruby
|
{
"resource": ""
}
|
q8616
|
EasyExist.DB.put
|
train
|
def put(document_uri, document)
validate_uri(document_uri)
res = put_document(document_uri, document, "application/xml")
res.success? ? res : handle_error(res)
end
|
ruby
|
{
"resource": ""
}
|
q8617
|
EasyExist.DB.delete
|
train
|
def delete(document_uri)
validate_uri(document_uri)
res = HTTParty.delete(document_uri, @default_opts)
res.success? ? res : handle_error(res)
end
|
ruby
|
{
"resource": ""
}
|
q8618
|
EasyExist.DB.query
|
train
|
def query(query, opts = {})
body = EasyExist::QueryRequest.new(query, opts).body
res = HTTParty.post("", @default_opts.merge({
body: body,
headers: { 'Content-Type' => 'application/xml', 'Content-Length' => body.length.to_s }
}))
res.success? ? res.body : handle_error(res)
end
|
ruby
|
{
"resource": ""
}
|
q8619
|
EasyExist.DB.store_query
|
train
|
def store_query(query_uri, query)
validate_uri(query_uri)
res = put_document(query_uri, query, "application/xquery")
res.success? ? res : handle_error(res)
end
|
ruby
|
{
"resource": ""
}
|
q8620
|
EasyExist.DB.put_document
|
train
|
def put_document(uri, document, content_type)
HTTParty.put(uri, @default_opts.merge({
body: document,
headers: { "Content-Type" => content_type},
}))
end
|
ruby
|
{
"resource": ""
}
|
q8621
|
Institutions.Core.set_required_attributes
|
train
|
def set_required_attributes(code, name)
missing_arguments = []
missing_arguments << :code if code.nil?
missing_arguments << :name if name.nil?
raise ArgumentError.new("Cannot create the Institution based on the given arguments (:code => #{code.inspect}, :name => #{name.inspect}).\n"+
"The following arguments cannot be nil: #{missing_arguments.inspect}") unless missing_arguments.empty?
# Set the instance variables
@code, @name = code.to_sym, name
end
|
ruby
|
{
"resource": ""
}
|
q8622
|
Ruport.Formatter::JSON.build_table_body
|
train
|
def build_table_body
data.each_with_index do |row, i|
output << ",\n" if i > 0
build_row(row)
end
output << "\n"
end
|
ruby
|
{
"resource": ""
}
|
q8623
|
Ruport.Formatter::JSON.build_row
|
train
|
def build_row(data = self.data)
values = data.to_a
keys = self.data.column_names.to_a
hash = {}
values.each_with_index do |val, i|
key = (keys[i] || i).to_s
hash[key] = val
end
line = hash.to_json.to_s
output << " #{line}"
end
|
ruby
|
{
"resource": ""
}
|
q8624
|
Ruport.Formatter::JSON.build_grouping_body
|
train
|
def build_grouping_body
arr = []
data.each do |_,group|
arr << render_group(group, options)
end
output << arr.join(",\n")
end
|
ruby
|
{
"resource": ""
}
|
q8625
|
Checkdin.Users.users
|
train
|
def users(options={})
response = connection.get do |req|
req.url "users", options
end
return_error_or_body(response)
end
|
ruby
|
{
"resource": ""
}
|
q8626
|
Checkdin.Users.create_user
|
train
|
def create_user(options={})
response = connection.post do |req|
req.url "users", options
end
return_error_or_body(response)
end
|
ruby
|
{
"resource": ""
}
|
q8627
|
Checkdin.Users.create_user_authentication
|
train
|
def create_user_authentication(id, options={})
response = connection.post do |req|
req.url "users/#{id}/authentications", options
end
return_error_or_body(response)
end
|
ruby
|
{
"resource": ""
}
|
q8628
|
Checkdin.Users.blacklisted
|
train
|
def blacklisted(options={})
response = connection.get do |req|
req.url "users/blacklisted", options
end
return_error_or_body(response)
end
|
ruby
|
{
"resource": ""
}
|
q8629
|
Checkdin.Users.view_user_full_description
|
train
|
def view_user_full_description(id)
response = connection.get do |req|
req.url "users/#{id}/full"
end
return_error_or_body(response)
end
|
ruby
|
{
"resource": ""
}
|
q8630
|
Dragonfly::ActiveRecord.Store.write
|
train
|
def write(temp_object, opts={})
temp_object.file do |fd|
File.new.tap do |file|
file.metadata = temp_object.meta
file.data = fd
file.save!
return file.id.to_s
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8631
|
Aptly.Mirror.update
|
train
|
def update kwargs={}
ignore_cksum = kwargs.arg :ignore_cksum, false
ignore_sigs = kwargs.arg :ignore_sigs, false
cmd = 'aptly mirror update'
cmd += ' -ignore-checksums' if ignore_cksum
cmd += ' -ignore-signatures' if ignore_sigs
cmd += " #{@name.quote}"
Aptly::runcmd cmd
end
|
ruby
|
{
"resource": ""
}
|
q8632
|
StringTree.Tree.delete
|
train
|
def delete(key)
node = find_node(key)
return false if node.nil?
node.value = nil
node.prune
true
end
|
ruby
|
{
"resource": ""
}
|
q8633
|
StringTree.Tree.match_count
|
train
|
def match_count(data, list = {})
return nil if @root == nil
i=0
while (i<data.length)
node = @root.find_forward(data, i, data.length-i)
if (node!=nil && node.value!=nil)
if (!list.has_key?(node))
list[node] = 1
else
list[node] += 1
end
i += node.length
else
i += 1
end
end
list
end
|
ruby
|
{
"resource": ""
}
|
q8634
|
StringTree.Tree.find_node
|
train
|
def find_node(key)
return nil if @root == nil
node = @root.find_vertical(key)
(node.nil? || node.value.nil? ? nil : node)
end
|
ruby
|
{
"resource": ""
}
|
q8635
|
CaRuby.Migrator.migrate_to_database
|
train
|
def migrate_to_database(&block)
# migrate with save
tm = Jinx::Stopwatch.measure { execute_save(&block) }.elapsed
logger.debug { format_migration_time_log_message(tm) }
end
|
ruby
|
{
"resource": ""
}
|
q8636
|
EstoreConventions.ArchivedAttributes.archive_attributes_utc
|
train
|
def archive_attributes_utc(attribute,start_time = DEFAULT_DAYS_START.ago, end_time = DEFAULT_DAYS_END.ago)
archived_attribute_base(attribute, start_time, end_time) do |hsh, obj|
hsh[obj.send(archived_time_attribute).to_i] = obj.send(attribute)
hsh
end
end
|
ruby
|
{
"resource": ""
}
|
q8637
|
EstoreConventions.ArchivedAttributes.archive_attributes_by_time
|
train
|
def archive_attributes_by_time(attribute,start_time = DEFAULT_DAYS_START.ago, end_time = DEFAULT_DAYS_END.ago)
archived_attribute_base(attribute, start_time, end_time) do |hsh, obj|
hsh[obj.send(archived_time_attribute)] = obj.send(attribute)
hsh
end
end
|
ruby
|
{
"resource": ""
}
|
q8638
|
ContentDriven.Page.add_child
|
train
|
def add_child key, page = nil
if key.is_a? Page
page, key = key, (self.keys.length + 1).to_sym
end
page.parent = self
page.url = key
self[key] = page
end
|
ruby
|
{
"resource": ""
}
|
q8639
|
Credentials.Password.check_password
|
train
|
def check_password(password)
return false unless key
key == self.class.hash_password(password, key.split('|', 2).first)
end
|
ruby
|
{
"resource": ""
}
|
q8640
|
Credentials.Password.password=
|
train
|
def password=(new_password)
@password = new_password
salt = self.class.random_salt
self.key = new_password && self.class.hash_password(new_password, salt)
end
|
ruby
|
{
"resource": ""
}
|
q8641
|
HasMarkup.Shoulda.should_have_markup
|
train
|
def should_have_markup(column, options = {})
options = HasMarkup::default_has_markup_options.merge(options)
should_have_instance_methods "#{column}_html"
should_require_markup column if options[:required]
should_cache_markup column if options[:cache_html]
end
|
ruby
|
{
"resource": ""
}
|
q8642
|
Orchestrate.Client.send_request
|
train
|
def send_request(method, args)
request = API::Request.new(method, build_url(method, args), config.api_key) do |r|
r.data = args[:json] if args[:json]
r.ref = args[:ref] if args[:ref]
end
request.perform
end
|
ruby
|
{
"resource": ""
}
|
q8643
|
Orchestrate.Client.build_url
|
train
|
def build_url(method, args)
API::URL.new(method, config.base_url, args).path
end
|
ruby
|
{
"resource": ""
}
|
q8644
|
Simulator.VariableContext.add_variables
|
train
|
def add_variables(*vars)
# create bound variables for each variable
bound_vars = vars.collect do |v|
BoundVariable.new v, self
end
# add all the bound variables to the variables hash
keys = vars.collect(&:name)
append_hash = Hash[ keys.zip(bound_vars) ]
@variables_hash.merge!(append_hash) do |key, oldval, newval|
oldval # the first bound variable
end
end
|
ruby
|
{
"resource": ""
}
|
q8645
|
Simulator.VariableContext.set
|
train
|
def set(var_hash)
var_hash.each do |variable_name, value|
throw :MissingVariable unless @variables_hash.has_key? variable_name
bv = @variables_hash[variable_name]
bv.value = value
end
end
|
ruby
|
{
"resource": ""
}
|
q8646
|
SimpleMetarParser.MetarSpecials.calculate_rain_and_snow
|
train
|
def calculate_rain_and_snow
@snow_metar = 0
@rain_metar = 0
self.specials.each do |s|
new_rain = 0
new_snow = 0
coefficient = 1
case s[:precipitation]
when 'drizzle' then
new_rain = 5
when 'rain' then
new_rain = 10
when 'snow' then
new_snow = 10
when 'snow grains' then
new_snow = 5
when 'ice crystals' then
new_snow = 1
new_rain = 1
when 'ice pellets' then
new_snow = 2
new_rain = 2
when 'hail' then
new_snow = 3
new_rain = 3
when 'small hail/snow pellets' then
new_snow = 1
new_rain = 1
end
case s[:intensity]
when 'in the vicinity' then
coefficient = 1.5
when 'heavy' then
coefficient = 3
when 'light' then
coefficient = 0.5
when 'moderate' then
coefficient = 1
end
snow = new_snow * coefficient
rain = new_rain * coefficient
if @snow_metar < snow
@snow_metar = snow
end
if @rain_metar < rain
@rain_metar = rain
end
end
# http://www.ofcm.gov/fmh-1/pdf/H-CH8.pdf page 3
# 10 units means more than 0.3 (I assume 0.5) inch per hour, so:
# 10 units => 0.5 * 25.4mm
real_world_coefficient = 0.5 * 25.4 / 10.0
@snow_metar *= real_world_coefficient
@rain_metar *= real_world_coefficient
end
|
ruby
|
{
"resource": ""
}
|
q8647
|
Retentiongrid.Customer.save!
|
train
|
def save!
result = Api.post("#{BASE_PATH}/#{customer_id}", body: attributes.to_json)
Customer.new(result.parsed_response["rg_customer"])
end
|
ruby
|
{
"resource": ""
}
|
q8648
|
MzML.Doc.parse_index_list
|
train
|
def parse_index_list
self.seek(self.stat.size - 200)
# parse the index offset
tmp = self.read
tmp =~ MzML::RGX::INDEX_OFFSET
offset = $1
# if I didn't match anything, compute the index and return
unless (offset)
return compute_index_list
end
@index = {}
@spectrum_list = []
@chromatogram_list = []
self.seek(offset.to_i)
tmp = Nokogiri::XML.parse(self.read).root
tmp.css("index").each do |idx|
index_type = idx[:name].to_sym
@index[index_type] = {}
idx.css("offset").each do |o|
@index[index_type][o[:idRef]] = o.text().to_i
if index_type == :spectrum
@spectrum_list << o[:idRef]
else
@chromatogram_list << o[:idRef]
end
end
end
self.rewind
return @index
end
|
ruby
|
{
"resource": ""
}
|
q8649
|
Redstruct.Struct.expire
|
train
|
def expire(ttl)
ttl = (ttl.to_f * 1000).floor
return coerce_bool(self.connection.pexpire(@key, ttl))
end
|
ruby
|
{
"resource": ""
}
|
q8650
|
Redstruct.Struct.expire_at
|
train
|
def expire_at(time)
time = (time.to_f * 1000).floor
return coerce_bool(self.connection.pexpireat(@key, time))
end
|
ruby
|
{
"resource": ""
}
|
q8651
|
Redstruct.Struct.restore
|
train
|
def restore(serialized, ttl: 0)
ttl = (ttl.to_f * 1000).floor
return self.connection.restore(@key, ttl, serialized)
end
|
ruby
|
{
"resource": ""
}
|
q8652
|
Bitsa.CLI.parse
|
train
|
def parse(args)
@global_opts = create_global_args(args)
@cmd = args.shift || ''
@search_data = ''
if cmd == 'search'
@search_data << args.shift unless args.empty?
elsif !CLI::SUB_COMMANDS.include?(cmd)
Trollop.die "unknown subcommand '#{cmd}'"
end
end
|
ruby
|
{
"resource": ""
}
|
q8653
|
StorageRoom.Collection.field
|
train
|
def field(identifier)
ensure_loaded do
fields.each do |f|
return f if f.identifier == identifier
end
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q8654
|
StorageRoom.Collection.load_associated_collections
|
train
|
def load_associated_collections
array = association_fields
if array.map{|f| f.collection_loaded?}.include?(false)
StorageRoom.log("Fetching associated collections for '#{name}'")
array.each{|f| f.collection}
end
end
|
ruby
|
{
"resource": ""
}
|
q8655
|
Cornerstone.Discussion.created_by?
|
train
|
def created_by?(check_user)
return false unless check_user.present?
return true if check_user.cornerstone_admin?
self.user && self.user == check_user
end
|
ruby
|
{
"resource": ""
}
|
q8656
|
Cornerstone.Discussion.participants
|
train
|
def participants(exclude_email=nil)
ps = []
self.posts.each do |p|
if p.author_name && p.author_email
ps << [p.author_name, p.author_email]
end
end
ps.delete_if{|p| p[1] == exclude_email}.uniq
end
|
ruby
|
{
"resource": ""
}
|
q8657
|
ActiveRecord.Calculations.count
|
train
|
def count(column_name = nil, options = {})
column_name, options = nil, column_name if column_name.is_a?(Hash)
calculate(:count, column_name, options)
end
|
ruby
|
{
"resource": ""
}
|
q8658
|
ActiveRecord.Calculations.sum
|
train
|
def sum(*args)
if block_given?
self.to_a.sum(*args) {|*block_args| yield(*block_args)}
else
calculate(:sum, *args)
end
end
|
ruby
|
{
"resource": ""
}
|
q8659
|
ActiveRecord.QueryMethods.reorder
|
train
|
def reorder(*args)
return self if args.blank?
relation = clone
relation.reordering_value = true
relation.order_values = args.flatten
relation
end
|
ruby
|
{
"resource": ""
}
|
q8660
|
Permit.PermitRule.matches?
|
train
|
def matches?(person, context_binding)
matched = if BUILTIN_ROLES.include? @roles[0]
has_builtin_authorization? person, context_binding
else
has_named_authorizations? person, context_binding
end
passed_conditionals = matched ? passes_conditionals?(person, context_binding) : false
passed = matched && passed_conditionals
return passed
end
|
ruby
|
{
"resource": ""
}
|
q8661
|
LazyLoad.Mixin.best
|
train
|
def best(*names)
names.map do |name|
@groups[name] || name
end.flatten.each do |name|
begin
return const_get(name)
rescue NameError, LoadError; end
end
const_get(names.first)
end
|
ruby
|
{
"resource": ""
}
|
q8662
|
LinkShrink.CLI.set_options
|
train
|
def set_options(opts)
opts.version, opts.banner = options.version, options.banner
opts.set_program_name 'LinkShrink'
options.api.map do |k, v|
arg = k.to_s.downcase
opts.on_head("-#{arg[0]}", "--#{arg}", argument_text_for(k)) do
options.api[k] = true
end
end
opts.on_tail('-v', '--version',
'display the version of LinkShrink and exit') do
puts opts.ver
exit
end
opts.on_tail('-h', '--help', 'print this help') do
puts opts.help
exit
end
end
|
ruby
|
{
"resource": ""
}
|
q8663
|
LinkShrink.CLI.parse
|
train
|
def parse
opts = OptionParser.new(&method(:set_options))
opts.parse!(@args)
return process_url if url_present?
opts.help
end
|
ruby
|
{
"resource": ""
}
|
q8664
|
ZTK.Base.log_and_raise
|
train
|
def log_and_raise(exception, message, shift=2)
Base.log_and_raise(config.ui.logger, exception, message, shift)
end
|
ruby
|
{
"resource": ""
}
|
q8665
|
ZTK.Base.direct_log
|
train
|
def direct_log(log_level, &blocK)
@config.ui.logger.nil? and raise BaseError, "You must supply a logger for direct logging support!"
if !block_given?
log_and_raise(BaseError, "You must supply a block to the log method!")
elsif (@config.ui.logger.level <= ::Logger.const_get(log_level.to_s.upcase))
@config.ui.logger << ZTK::ANSI.uncolor(yield)
end
end
|
ruby
|
{
"resource": ""
}
|
q8666
|
Bitsa.Settings.load_config_file_settings
|
train
|
def load_config_file_settings(config_file_hash)
@login = config_file_hash.data[:login]
@password = config_file_hash.data[:password]
@cache_file_path = config_file_hash.data[:cache_file_path]
@auto_check = config_file_hash.data[:auto_check]
end
|
ruby
|
{
"resource": ""
}
|
q8667
|
Bitsa.Settings.load_cmd_line_settings
|
train
|
def load_cmd_line_settings(options)
@login = options[:login] if options[:login]
@password = options[:password] if options[:password]
@cache_file_path = options[:cache_file_path] if options[:cache_file_path]
@auto_check = options[:auto_check] if options[:auto_check]
end
|
ruby
|
{
"resource": ""
}
|
q8668
|
TastesBitter.JavascriptErrorsController.create
|
train
|
def create
browser = Browser.new(ua: params["user_agent"])
error_info = {
message: params["message"],
file_or_page: params["file_or_page"],
line_number: params["line_number"],
column_number: params["column_number"],
user_agent: params["user_agent"],
current_page: params["current_page"],
platform: browser.platform.to_s.humanize,
browser_name: browser.name,
browser_version: browser.full_version,
user_ip: request.remote_ip,
referrer: request.env["HTTP_REFERER"],
stack_trace: params["stack_trace"]
}
::TastesBitter::JavascriptErrorsMailer.javascript_error(error_info).deliver_later
respond_to do |format|
format.js { render nothing: true, status: :ok }
end
end
|
ruby
|
{
"resource": ""
}
|
q8669
|
Sem4r.ReportDefinitionAccountExtension.report_fields
|
train
|
def report_fields(report_type)
soap_message = service.report_definition.report_fields(credentials, report_type)
add_counters(soap_message.counters)
els = soap_message.response.xpath("//getReportFieldsResponse/rval")
els.map do |el|
ReportField.from_element(el)
end
end
|
ruby
|
{
"resource": ""
}
|
q8670
|
Sem4r.ReportDefinitionAccountExtension.report_definition_delete
|
train
|
def report_definition_delete(repdef_or_id)
if repdef_or_id.class == ReportDefinition
report_definition = repdef_or_id
else
report_definition = ReportDefinition.new(self)
report_definition.instance_eval { @id = repdef_or_id }
end
op = ReportDefinitionOperation.remove(report_definition)
soap_message = service.report_definition.mutate(credentials, op.to_xml)
add_counters(soap_message.counters)
unless @report_definitions
@report_definition.delete_if { |repdef| repdef == report_definition.id }
end
report_definition.instance_eval { @id = -1 } # repdef status invalid/deleted
self
end
|
ruby
|
{
"resource": ""
}
|
q8671
|
Sem4r.ReportDefinitionAccountExtension.p_report_definitions
|
train
|
def p_report_definitions(refresh = false)
report_definitions(refresh).each do |report_definition|
puts report_definition.to_s
end
self
end
|
ruby
|
{
"resource": ""
}
|
q8672
|
RsUserPolicy.UserCollection.add_users
|
train
|
def add_users(users)
users.each do |user|
unless @users_by_href.has_key?(user.href)
@users_by_href[user.href] = RsUserPolicy::User.new(user)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8673
|
EZMQ.Subscriber.receive
|
train
|
def receive(**options)
message = ''
@socket.recv_string message
message = message.match(/^(?<topic>[^\ ]*)\ (?<body>.*)/m)
decoded = (options[:decode] || @decode).call message['body']
if block_given?
yield decoded, message['topic']
else
[decoded, message['topic']]
end
end
|
ruby
|
{
"resource": ""
}
|
q8674
|
Kawaii.RenderMethods.render
|
train
|
def render(tmpl)
t = Tilt.new(File.join('views', tmpl)) # @todo Caching!
t.render(self)
end
|
ruby
|
{
"resource": ""
}
|
q8675
|
GrowthForecast.Client.get_json
|
train
|
def get_json(path)
@request_uri = "#{@base_uri}#{path}"
req = get_request(path)
@res = http_connection.start {|http| http.request(req) }
handle_error(@res, @request_uri)
JSON.parse(@res.body)
end
|
ruby
|
{
"resource": ""
}
|
q8676
|
GrowthForecast.Client.post_json
|
train
|
def post_json(path, data = {})
@request_uri = "#{@base_uri}#{path}"
body = JSON.generate(data)
extheader = { 'Content-Type' => 'application/json' }
req = post_request(path, body, extheader)
@res = http_connection.start {|http| http.request(req) }
handle_error(@res, @request_uri)
JSON.parse(@res.body)
end
|
ruby
|
{
"resource": ""
}
|
q8677
|
GrowthForecast.Client.post_query
|
train
|
def post_query(path, data = {})
@request_uri = "#{@base_uri}#{path}"
body = URI.encode_www_form(data)
extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' }
req = post_request(path, body, extheader)
@res = http_connection.start {|http| http.request(req) }
handle_error(@res, @request_uri)
JSON.parse(@res.body)
end
|
ruby
|
{
"resource": ""
}
|
q8678
|
FreelingClient.Analyzer.tokens
|
train
|
def tokens(cmd, text)
valide_command!(cmd)
Enumerator.new do |yielder|
call(cmd, text).each do |freeling_line|
yielder << parse_token_line(freeling_line) unless freeling_line.empty?
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8679
|
QLab.Machine.find_workspace
|
train
|
def find_workspace params={}
workspaces.find do |ws|
matches = true
# match each key to the given workspace
params.keys.each do |key|
matches = matches && (ws.send(key.to_sym) == params[key])
end
matches
end
end
|
ruby
|
{
"resource": ""
}
|
q8680
|
Analysand.Errors.ex
|
train
|
def ex(klass, response)
klass.new("Expected response to have code 2xx, got #{response.code} instead").tap do |ex|
ex.response = response
end
end
|
ruby
|
{
"resource": ""
}
|
q8681
|
Kelp.Checkbox.checkbox_should_be_checked
|
train
|
def checkbox_should_be_checked(checkbox, scope={})
in_scope(scope) do
field_checked = find_field(checkbox)['checked']
if !field_checked
raise Kelp::Unexpected,
"Expected '#{checkbox}' to be checked, but it is unchecked."
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8682
|
MaRuKu.Strings.parse_email_headers
|
train
|
def parse_email_headers(s)
keys={}
match = (s =~ /\A((\w[\w\s\_\-]+: .*\n)+)\s*\n/)
if match != 0
keys[:data] = s
else
keys[:data] = $'
headers = $1
headers.split("\n").each do |l|
# Fails if there are other ':' characters.
# k, v = l.split(':')
k, v = l.split(':', 2)
k, v = normalize_key_and_value(k, v)
k = k.to_sym
# puts "K = #{k}, V=#{v}"
keys[k] = v
end
end
keys
end
|
ruby
|
{
"resource": ""
}
|
q8683
|
MaRuKu.Strings.normalize_key_and_value
|
train
|
def normalize_key_and_value(k,v)
v = v ? v.strip : true # no value defaults to true
k = k.strip
# check synonyms
v = true if ['yes','true'].include?(v.to_s.downcase)
v = false if ['no','false'].include?(v.to_s.downcase)
k = k.downcase.gsub(' ','_')
return k, v
end
|
ruby
|
{
"resource": ""
}
|
q8684
|
MaRuKu.Strings.number_of_leading_spaces
|
train
|
def number_of_leading_spaces(s)
n=0; i=0;
while i < s.size
c = s[i,1]
if c == ' '
i+=1; n+=1;
elsif c == "\t"
i+=1; n+=TabSize;
else
break
end
end
n
end
|
ruby
|
{
"resource": ""
}
|
q8685
|
MaRuKu.Strings.spaces_before_first_char
|
train
|
def spaces_before_first_char(s)
case s.md_type
when :ulist
i=0;
# skip whitespace if present
while s[i,1] =~ /\s/; i+=1 end
# skip indicator (+, -, *)
i+=1
# skip optional whitespace
while s[i,1] =~ /\s/; i+=1 end
return i
when :olist
i=0;
# skip whitespace
while s[i,1] =~ /\s/; i+=1 end
# skip digits
while s[i,1] =~ /\d/; i+=1 end
# skip dot
i+=1
# skip whitespace
while s[i,1] =~ /\s/; i+=1 end
return i
else
tell_user "BUG (my bad): '#{s}' is not a list"
0
end
end
|
ruby
|
{
"resource": ""
}
|
q8686
|
MaRuKu.Strings.strip_hashes
|
train
|
def strip_hashes(s)
s = s[num_leading_hashes(s), s.size]
i = s.size-1
while i > 0 && (s[i,1] =~ /(#|\s)/); i-=1; end
s[0, i+1].strip
end
|
ruby
|
{
"resource": ""
}
|
q8687
|
MaRuKu.Strings.strip_indent
|
train
|
def strip_indent(s, n)
i = 0
while i < s.size && n>0
c = s[i,1]
if c == ' '
n-=1;
elsif c == "\t"
n-=TabSize;
else
break
end
i+=1
end
s[i, s.size]
end
|
ruby
|
{
"resource": ""
}
|
q8688
|
Activr.Timeline.dump
|
train
|
def dump(options = { })
options = options.dup
limit = options.delete(:nb) || 100
self.find(limit).map{ |tl_entry| tl_entry.humanize(options) }
end
|
ruby
|
{
"resource": ""
}
|
q8689
|
Activr.Timeline.trim!
|
train
|
def trim!
# check if trimming is needed
if (self.trim_max_length > 0) && (self.count > self.trim_max_length)
last_tle = self.find(1, :skip => self.trim_max_length - 1).first
if last_tle
self.delete(:before => last_tle.activity.at)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8690
|
GovukNavigationHelpers.RummagerTaxonomySidebarLinks.content_related_to
|
train
|
def content_related_to(taxon, used_related_links)
statsd.time(:taxonomy_sidebar_search_time) do
begin
results = Services.rummager.search(
similar_to: @content_item.base_path,
start: 0,
count: 3,
filter_taxons: [taxon.content_id],
filter_navigation_document_supertype: 'guidance',
reject_link: used_related_links.to_a,
fields: %w[title link],
)['results']
statsd.increment(:taxonomy_sidebar_searches)
results
.map { |result| { title: result['title'], link: result['link'], } }
.sort_by { |result| result[:title] }
rescue StandardError => e
GovukNavigationHelpers.configuration.error_handler.notify(e)
[]
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8691
|
ICU.Player.to_sp_text
|
train
|
def to_sp_text(rounds, format)
attrs = [num.to_s, name, id.to_s, ('%.1f' % points).sub(/\.0/, '')]
(1..rounds).each do |r|
result = find_result(r)
attrs << (result ? result.to_sp_text : " : ")
end
format % attrs
end
|
ruby
|
{
"resource": ""
}
|
q8692
|
ICU.Result.to_sp_text
|
train
|
def to_sp_text
sp = opponent ? opponent.to_s : '0'
sp << ':'
if rateable
sp << score
else
sp << case score
when 'W' then '+'
when 'L' then '-'
else '='
end
end
end
|
ruby
|
{
"resource": ""
}
|
q8693
|
Octo.Baseline.get_baseline_value
|
train
|
def get_baseline_value(baseline_type, obj, ts = Time.now.ceil)
unless Octo::Counter.constants.include?baseline_type
raise ArgumentError, 'No such baseline defined'
end
args = {
ts: ts,
type: Octo::Counter.const_get(baseline_type),
uid: obj.unique_id,
enterprise_id: obj.enterprise.id
}
bl = get_cached(args)
if bl
bl.val
else
0.01
end
end
|
ruby
|
{
"resource": ""
}
|
q8694
|
Octo.Baseline.aggregate
|
train
|
def aggregate(type, ts)
Octo::Enterprise.each do |enterprise|
aggregate_baseline enterprise.id, type, ts
end
end
|
ruby
|
{
"resource": ""
}
|
q8695
|
Octo.Baseline.aggregate_baseline
|
train
|
def aggregate_baseline(enterprise_id, type, ts = Time.now.floor)
clazz = @baseline_for.constantize
_ts = ts
start_calc_time = (_ts.to_datetime - MAX_DURATION.day).to_time
last_n_days_interval = start_calc_time.ceil.to(_ts, 24.hour)
last_n_days_interval.each do |hist|
args = {
ts: hist,
type: type,
enterprise_id: enterprise_id
}
counters = @baseline_for.constantize.send(:where, args)
baseline = baseline_from_counters(counters)
store_baseline enterprise_id, type, hist, baseline
end
end
|
ruby
|
{
"resource": ""
}
|
q8696
|
Octo.Baseline.store_baseline
|
train
|
def store_baseline(enterprise_id, type, ts, baseline)
return if baseline.nil? or baseline.empty?
baseline.each do |uid, val|
self.new({
enterprise_id: enterprise_id,
type: type,
ts: ts,
uid: uid,
val: val
}).save!
end
end
|
ruby
|
{
"resource": ""
}
|
q8697
|
Octo.Baseline.baseline_from_counters
|
train
|
def baseline_from_counters(counters)
baseline = {}
uid_groups = counters.group_by { |x| x.uid }
uid_groups.each do |uid, counts|
baseline[uid] = score_counts(counts)
end
baseline
end
|
ruby
|
{
"resource": ""
}
|
q8698
|
Octo.Baseline.score_counts
|
train
|
def score_counts(counts)
if counts.count > 0
_num = counts.map { |x| x.obp }
_num.percentile(90)
else
0.01
end
end
|
ruby
|
{
"resource": ""
}
|
q8699
|
LocaleDating.ClassMethods.locale_dating_naming_checks
|
train
|
def locale_dating_naming_checks(args, options)
options.reverse_merge!(:format => :default)
options[:ending] ||= "as_#{options[:format]}".to_sym unless options[:format] == :default
options[:ending] ||= :as_text
# error if multiple args used with :name option
raise MethodOverwriteError, "multiple attributes cannot be wrapped with an explicitly named method" if args.length > 1 && options.key?(:name)
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.